All files / src/modules/implementations/database posting-balance-materializer.js

100% Statements 34/34
100% Branches 6/6
100% Functions 2/2
100% Lines 34/34

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 3554x 54x 784x 391x 391x 391x 391x 391x 391x 391x 391x 391x 391x 391x 391x 391x 391x 391x 391x 391x 391x 34403x 34403x 1585x 1585x 1585x 34403x 34403x 34403x 34403x 391x 391x 784x 54x  
'use strict';
module.exports = ({ numeric: { decimal: { addDecimals, formatDecimal, parseDecimal }, }, }) => {
    function materializePostingBalances(database) {
        const rows = database.prepare(`
      SELECT
        amounts.id,
        postings.account,
        amounts.amount_quantity AS quantity,
        amounts.amount_commodity AS commodity
      FROM resolved_posting_amounts AS amounts
      JOIN postings ON postings.id = amounts.posting_id
      ORDER BY postings.posting_date, postings.transaction_id,
        postings.position, amounts.position
    `).all();
        const updateBalance = database.prepare(`
      UPDATE resolved_posting_amounts
      SET balance_quantity = ?
      WHERE id = ?
    `);
        const balancesByAccount = new Map();
        for (const row of rows) {
            let balances = balancesByAccount.get(row.account);
            if (!balances) {
                balances = new Map();
                balancesByAccount.set(row.account, balances);
            }
            const balance = addDecimals(balances.get(row.commodity) ?? parseDecimal('0'), parseDecimal(row.quantity));
            balances.set(row.commodity, balance);
            updateBalance.run(formatDecimal(balance), row.id);
        }
        return rows.length;
    }
    return { materializePostingBalances };
};