All files / src/modules/implementations/queries/list-definitions postings.js

100% Statements 166/166
92.5% Branches 37/40
100% Functions 2/2
100% Lines 166/166

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 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 16751x 51x 51x 783x 783x 783x 783x 783x 53x 53x 53x 53x 8x 8x 8x 53x 5x 5x 5x 53x 9x 9x 9x 9x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 53x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 9x 9x 9x 46x 46x 46x 46x 9x 9x 9x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 46x 53x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 10x 10x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 8x 8x 22x 22x 22x 22x 22x 22x 22x 22x 3x 3x 3x 3x 3x 3x 3x 22x 22x 46x 46x 46x 46x 46x 22x 25x 53x 783x 51x  
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
module.exports = ({ apiOptions: { accounts, dateRange, validateDateRange, parseOptions }, accountFilter: { accountFilter }, external: { zod: { z } }, }) => {
    const optionsSchema = z.strictObject({
        accounts,
        ...dateRange,
    }).superRefine(validateDateRange);
    function queryPostings(database, options, _caches) {
        const { accounts, from, to } = parseOptions(optionsSchema, options, 'postings');
        const clauses = [];
        const parameters = [];
        if (from) {
            clauses.push('postings.posting_date >= ?');
            parameters.push(from);
        }
        if (to) {
            clauses.push('postings.posting_date <= ?');
            parameters.push(to);
        }
        if (accounts.length > 0) {
            const match = accountFilter('postings.account', accounts);
            clauses.push(match.sql);
            parameters.push(...match.parameters);
        }
        const where = clauses.length === 0 ? '' : `WHERE ${clauses.join('\n        AND ')}`;
        const rows = database.prepare(`
      SELECT
        postings.id AS postingId,
        postings.transaction_id AS transactionId,
        transactions.date AS transactionDate,
        source_files.path AS filename,
        entries.line AS transactionSourceLine,
        transactions.description,
        postings.posting_date AS postingDate,
        postings.account,
        postings.amount_quantity AS amountQuantity,
        postings.amount_commodity AS amountCommodity,
        postings.lot_cost_quantity AS lotCostQuantity,
        postings.lot_cost_commodity AS lotCostCommodity,
        postings.lot_cost_is_total AS lotCostIsTotal,
        postings.cost_quantity AS costQuantity,
        postings.cost_commodity AS costCommodity,
        postings.cost_is_total AS costIsTotal,
        postings.balance_quantity AS balanceQuantity,
        postings.balance_commodity AS balanceCommodity,
        amounts.amount_quantity AS quantity,
        amounts.amount_commodity AS commodity,
        amounts.balance_quantity AS balance
      FROM postings
      JOIN transactions ON transactions.entry_id = postings.transaction_id
      JOIN journal_entries AS entries ON entries.id = transactions.entry_id
      JOIN source_files ON source_files.id = entries.source_file_id
      JOIN resolved_posting_amounts AS amounts ON amounts.posting_id = postings.id
      ${where}
      ORDER BY transactions.entry_id, postings.position, amounts.position
    `).all(...parameters);
        const postings = [];
        const byId = new Map();
        for (const row of rows) {
            let posting = byId.get(row.postingId);
            if (!posting) {
                const balance = row.balanceQuantity === null
                    ? null
                    : { quantity: row.balanceQuantity, commodity: row.balanceCommodity };
                posting = {
                    postingId: row.postingId,
                    transactionId: row.transactionId,
                    transactionDate: row.transactionDate,
                    filename: row.filename,
                    transactionSourceLine: row.transactionSourceLine,
                    description: row.description,
                    transactionComments: [],
                    postingDate: row.postingDate,
                    account: row.account,
                    postingComments: [],
                    amount: row.amountQuantity === null
                        ? null
                        : { quantity: row.amountQuantity, commodity: row.amountCommodity },
                    lotCost: row.lotCostQuantity === null
                        ? null
                        : {
                            quantity: row.lotCostQuantity,
                            commodity: row.lotCostCommodity,
                            isTotal: Boolean(row.lotCostIsTotal),
                        },
                    cost: row.costQuantity === null
                        ? null
                        : {
                            quantity: row.costQuantity,
                            commodity: row.costCommodity,
                            isTotal: Boolean(row.costIsTotal),
                        },
                    balanceAssignment: row.amountQuantity === null ? balance : null,
                    balanceAssertion: row.amountQuantity === null ? null : balance,
                    amounts: [],
                };
                byId.set(row.postingId, posting);
                postings.push(posting);
            }
            posting.amounts.push({
                quantity: row.quantity,
                commodity: row.commodity,
                balance: row.balance,
            });
        }
        if (postings.length > 0) {
            const transactionIds = [...new Set(postings.map(({ transactionId }) => transactionId))];
            const commentsByTransaction = new Map(transactionIds.map((id) => [id, []]));
            const tagsByTransaction = new Map(transactionIds.map((id) => [id, []]));
            for (let offset = 0; offset < transactionIds.length; offset += 500) {
                const ids = transactionIds.slice(offset, offset + 500);
                const placeholders = ids.map(() => '?').join(', ');
                const transactionComments = database.prepare(`
          SELECT transaction_id AS transactionId, text
          FROM comments
          WHERE transaction_id IN (${placeholders})
          ORDER BY transaction_id, position
        `).all(...ids);
                for (const comment of transactionComments) {
                    commentsByTransaction.get(comment.transactionId).push(comment.text);
                }
                const postingComments = database.prepare(`
          SELECT comments.posting_id AS postingId, comments.text
          FROM postings
          JOIN comments ON comments.posting_id = postings.id
          WHERE postings.transaction_id IN (${placeholders})
          ORDER BY postings.transaction_id, postings.position, comments.position
        `).all(...ids);
                for (const comment of postingComments)
                    byId.get(comment.postingId)?.postingComments.push(comment.text);
                const transactionTags = database.prepare(`
          SELECT transaction_id AS transactionId, name, value
          FROM tags
          WHERE transaction_id IN (${placeholders})
          ORDER BY transaction_id, position, ordinal
        `).all(...ids);
                for (const tag of transactionTags) {
                    tagsByTransaction.get(tag.transactionId).push({ name: tag.name, value: tag.value });
                }
                const postingTags = database.prepare(`
          SELECT tags.posting_id AS postingId, tags.name, tags.value
          FROM postings
          JOIN tags ON tags.posting_id = postings.id
          WHERE postings.transaction_id IN (${placeholders})
          ORDER BY postings.transaction_id, postings.position, tags.position, tags.ordinal
        `).all(...ids);
                for (const tag of postingTags) {
                    const posting = byId.get(tag.postingId);
                    if (!posting)
                        continue;
                    if (!posting.postingTags)
                        posting.postingTags = [];
                    posting.postingTags.push({ name: tag.name, value: tag.value });
                }
            }
            for (const posting of postings) {
                posting.transactionComments = [...(commentsByTransaction.get(posting.transactionId) ?? [])];
                const transactionTags = tagsByTransaction.get(posting.transactionId) ?? [];
                if (transactionTags.length > 0)
                    posting.transactionTags = [...transactionTags];
            }
        }
        return postings;
    }
    return { inputSchema: optionsSchema, execute: queryPostings };
};