All files / src/modules/implementations/accounting posting-resolver.js

100% Statements 124/124
95.77% Branches 68/71
100% Functions 11/11
100% Lines 124/124

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 12563x 63x 798x 798x 34429x 34429x 798x 68701x 68701x 798x 18x 18x 18x 798x 34408x 34408x 31380x 31983x 141x 141x 141x 141x 141x 34408x 34408x 34408x 34408x 798x 34294x 34294x 3154x 3154x 34290x 445x 445x 445x 2709x 2709x 2709x 3154x 34294x 798x 392x 392x 392x 392x 392x 392x 392x 22x 22x 392x 34407x 34407x 392x 14947x 14947x 14947x 14947x 14947x 14947x 14947x 34408x 34408x 34408x 34408x 34408x 34408x 34408x 10x 10x 10x 10x 10x 10x 10x 10x 34398x 114x 2x 2x 2x 2x 112x 112x 112x 34294x 34294x 34294x 34294x 34408x 12x 12x 12x 7x 7x 7x 7x 12x 14947x 14947x 2x 2x 2x 14945x 14945x 110x 110x 113x 113x 113x 113x 110x 14835x 26x 26x 26x 26x 26x 14945x 14947x 392x 798x 63x  
'use strict';
module.exports = ({ numeric: { decimal: { addDecimals, compareDecimals, formatDecimal, multiplyDecimals, negateDecimal, parseDecimal, subtractDecimals, }, }, journal: { ingestionWarning: { createWarning, warningCodes }, }, }) => {
    const ZERO = parseDecimal('0');
    function balanceKey(account, commodity) {
        return `${account}\u0000${commodity}`;
    }
    function addToMap(map, key, value) {
        map.set(key, addDecimals(map.get(key) || ZERO, value));
    }
    function isCommodityExchange(residuals) {
        return residuals.length === 2 &&
            (residuals[0][1].coefficient < 0n) !== (residuals[1][1].coefficient < 0n);
    }
    function balancingCost(posting, postings) {
        if (posting.cost)
            return posting.lotCost || posting.cost;
        if (!posting.lotCost)
            return null;
        const costCommodity = posting.lotCost.amount.commodity;
        const hasImplicitPosting = postings.some((candidate) => !candidate.amount && !candidate.balanceAssignment);
        const hasMatchingPosting = postings.some((candidate) => candidate !== posting &&
            (candidate.amount?.commodity || candidate.balanceAssignment?.commodity) === costCommodity);
        const samePostingCommodity = postings.length > 1 && postings.every((candidate) => (candidate.amount?.commodity || candidate.balanceAssignment?.commodity) ===
            posting.amount?.commodity);
        return hasImplicitPosting || hasMatchingPosting || samePostingCommodity
            ? posting.lotCost : null;
    }
    function balancingAmount(annotation, amount) {
        if (!annotation)
            return amount;
        const cost = parseDecimal(annotation.amount.quantity);
        let quantity;
        if (annotation.total) {
            const amountSign = compareDecimals(parseDecimal(amount.quantity), ZERO);
            quantity = amountSign < 0 && compareDecimals(cost, ZERO) > 0 ? negateDecimal(cost) : cost;
        }
        else {
            quantity = multiplyDecimals(parseDecimal(amount.quantity), cost);
        }
        return { quantity: formatDecimal(quantity), commodity: annotation.amount.commodity };
    }
    class PostingResolver {
        balances;
        warnings;
        constructor(warnings) {
            this.balances = new Map();
            this.warnings = warnings || [];
        }
        accountBalance(account, commodity) {
            return this.balances.get(balanceKey(account, commodity)) || ZERO;
        }
        apply(account, amount) {
            addToMap(this.balances, balanceKey(account, amount.commodity), parseDecimal(amount.quantity));
        }
        resolve(transaction) {
            const balancesBeforeTransaction = new Map(this.balances);
            const resolved = transaction.postings.map(() => []);
            const transactionBalance = new Map();
            let implicitPosition = null;
            let hasCost = false;
            let invalidTransaction = false;
            transaction.postings.forEach((posting, position) => {
                if (invalidTransaction)
                    return;
                const annotation = balancingCost(posting, transaction.postings);
                if (annotation)
                    hasCost = true;
                let amount = posting.amount;
                if (posting.balanceAssignment) {
                    const { commodity } = posting.balanceAssignment;
                    const target = parseDecimal(posting.balanceAssignment.quantity);
                    const current = this.accountBalance(posting.account, commodity);
                    amount = {
                        quantity: formatDecimal(subtractDecimals(target, current)),
                        commodity,
                    };
                }
                else if (!amount) {
                    if (implicitPosition !== null) {
                        this.warnings.push(createWarning(warningCodes.MULTIPLE_IMPLICIT_POSTINGS, 'Transaction has multiple implicit postings', transaction.location));
                        invalidTransaction = true;
                        return;
                    }
                    implicitPosition = position;
                    return;
                }
                resolved[position].push(amount);
                this.apply(posting.account, amount);
                const balancing = balancingAmount(annotation, amount);
                addToMap(transactionBalance, balancing.commodity, parseDecimal(balancing.quantity));
                if (posting.balanceAssertion) {
                    const actual = this.accountBalance(posting.account, posting.balanceAssertion.commodity);
                    const expected = parseDecimal(posting.balanceAssertion.quantity);
                    if (compareDecimals(actual, expected) !== 0) {
                        this.warnings.push(createWarning(warningCodes.BALANCE_ASSERTION_FAILED, `Balance assertion failed: expected ${formatDecimal(expected)} ` +
                            `${posting.balanceAssertion.commodity}, got ${formatDecimal(actual)} ` +
                            posting.balanceAssertion.commodity, posting.location));
                    }
                }
            });
            if (invalidTransaction) {
                this.balances = balancesBeforeTransaction;
                return null;
            }
            const residuals = [...transactionBalance].filter(([, residual]) => compareDecimals(residual, ZERO) !== 0);
            if (implicitPosition !== null) {
                const posting = transaction.postings[implicitPosition];
                for (const [commodity, residual] of residuals) {
                    const amount = { quantity: formatDecimal(negateDecimal(residual)), commodity };
                    resolved[implicitPosition].push(amount);
                    this.apply(posting.account, amount);
                }
            }
            else if (residuals.length > 0 && (hasCost || !isCommodityExchange(residuals))) {
                const imbalance = residuals
                    .map(([commodity, residual]) => `${formatDecimal(residual)} ${commodity}`)
                    .join(', ');
                this.warnings.push(createWarning(warningCodes.UNBALANCED_TRANSACTION, `Transaction does not balance: ${imbalance}`, transaction.location));
            }
            return resolved;
        }
    }
    return { PostingResolver };
};