All files / src/modules/implementations/queries/support journal-printer.js

99.43% Statements 175/176
95.6% Branches 87/91
100% Functions 11/11
99.43% Lines 175/176

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 167 168 169 170 171 172 173 174 175 176 17751x 51x 51x 783x 783x 783x 783x 783x 783x 61x 61x 20x 20x 61x 16x 16x 16x 16x 61x 61x 26x 26x 26x 26x 26x 26x 26x 61x 61x 783x 41x 41x 39x 39x 41x 4x 4x 4x 41x 4x 4x 41x 1x 1x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 783x 20x 20x 20x 20x 20x 20x 20x 41x 41x 20x 20x 783x 108x 108x 10x 108x 108x 44x 108x 22x 22x 22x 22x 22x 108x 12x 12x 108x 20x 108x   108x 108x 783x 16x 16x 16x 16x 16x 16x 96x 108x 108x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 41x 41x 41x 41x 16x 16x 16x 16x 20x 20x 20x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 108x 108x 108x 84x 84x 108x 8x 8x 8x 4x 4x 4x 8x 16x 5x 16x 16x 16x 16x 783x 51x  
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
module.exports = ({ numeric: { decimal: { formatDecimal, parseDecimal }, }, }) => {
    const quantityText = (quantity) => formatDecimal(parseDecimal(quantity));
    const amountText = (quantity, commodity) => `${quantityText(quantity)} ${commodity}`;
    const withComment = (text, comment) => comment === null ? text : `${text}  ; ${comment}`;
    const tagText = ({ name, value }) => value === null ? `:${name}:` : `${name}: ${value}`;
    const entryRank = { comment: 0, account: 1, tag: 2, commodity: 3, price: 4, transaction: 5 };
    function metadataLines(owner) {
        const byPosition = new Map();
        for (const { position, text } of owner.comments) {
            byPosition.set(position, { comment: text, tags: [] });
        }
        for (const tag of owner.tags) {
            if (!byPosition.has(tag.position))
                byPosition.set(tag.position, { tags: [] });
            byPosition.get(tag.position).tags.push(tag);
        }
        return [...byPosition].sort(([left], [right]) => left - right)
            .map(([position, { comment, tags }]) => {
            const tagsText = tags.length > 0 && tags.every(({ value }) => value === null)
                ? `:${tags.map(({ name }) => name).join(':')}:`
                : tags.map(tagText).join(' ');
            return {
                position,
                text: [tagsText, comment].filter((part) => part !== undefined && part !== '').join(' '),
            };
        });
    }
    function postingText(posting, accountWidth, transactionDate) {
        const expression = [];
        if (posting.amountQuantity !== null) {
            expression.push(amountText(posting.amountQuantity, posting.amountCommodity));
        }
        if (posting.lotCostQuantity !== null) {
            const braces = posting.lotCostIsTotal ? ['{{', '}}'] : ['{', '}'];
            expression.push(`${braces[0]}${amountText(posting.lotCostQuantity, posting.lotCostCommodity)}${braces[1]}`);
        }
        if (posting.costQuantity !== null) {
            expression.push(`${posting.costIsTotal ? '@@' : '@'} ${amountText(posting.costQuantity, posting.costCommodity)}`);
        }
        if (posting.balanceQuantity !== null) {
            expression.push(`= ${amountText(posting.balanceQuantity, posting.balanceCommodity)}`);
        }
        const account = expression.length === 0
            ? posting.account
            : posting.account.padEnd(accountWidth);
        const line = `    ${account}${expression.length ? `  ${expression.join(' ')}` : ''}`;
        const metadata = metadataLines(posting);
        const inline = metadata.find(({ position }) => position === 0)?.text;
        const dateMarker = posting.postingDate === transactionDate
            ? null : `[${posting.postingDate}]`;
        const inlineText = [dateMarker, inline]
            .filter((part) => part !== null && part !== undefined && part !== '').join(' ');
        return [
            withComment(line, dateMarker === null && inline === undefined ? null : inlineText),
            ...metadata.filter(({ position }) => position !== 0)
                .map(({ text }) => `    ; ${text}`),
        ];
    }
    function transactionText(entry) {
        const metadata = metadataLines(entry);
        const inline = metadata.find(({ position }) => position === 0)?.text ?? null;
        const lines = [withComment(`${entry.date} ${entry.description}`, inline)];
        lines.push(...metadata.filter(({ position }) => position !== 0)
            .map(({ text }) => `    ; ${text}`));
        const accountWidth = Math.max(0, ...entry.postings.map(({ account }) => account.length));
        for (const posting of entry.postings) {
            lines.push(...postingText(posting, accountWidth, entry.date));
        }
        return lines.join('\n');
    }
    function entryText(entry) {
        switch (entry.type) {
            case 'comment':
                return `; ${entry.text}`;
            case 'account':
            case 'tag':
                return withComment(`${entry.type} ${entry.name}`, entry.comment);
            case 'commodity':
                return [
                    withComment(`commodity ${entry.symbol}`, entry.comment),
                    ...(entry.isDefault ? ['  default'] : []),
                    ...(entry.format === null ? [] : [`  format ${entry.format}`]),
                ].join('\n');
            case 'price':
                return withComment(`P ${entry.date} ${entry.baseCommodity} ` +
                    amountText(entry.quoteQuantity, entry.quoteCommodity), entry.comment);
            case 'transaction':
                return transactionText(entry);
            default:
                throw new Error(`Cannot print unsupported journal entry type: ${entry.type}`);
        }
    }
    function printJournal(database, { density, sortDeclarations }) {
        const ids = database.prepare('SELECT id FROM journal_entries ORDER BY id').pluck().all();
        if (ids.length === 0)
            return '';
        const entries = new Map();
        const postings = new Map();
        const load = (type, sql, decorate) => {
            for (const row of database.prepare(sql).all()) {
                entries.set(row.entryId, { type, ...(decorate ? decorate(row) : row) });
            }
        };
        load('comment', 'SELECT entry_id AS entryId, text FROM file_comments');
        load('transaction', `
      SELECT entry_id AS entryId, date, description FROM transactions
    `, (row) => ({ ...row, postings: [], comments: [], tags: [] }));
        load('account', `
      SELECT entry_id AS entryId, name, comment FROM account_declarations
    `);
        load('tag', `
      SELECT entry_id AS entryId, name, comment FROM tag_declarations
    `);
        load('commodity', `
      SELECT entry_id AS entryId, symbol, comment, format, is_default AS isDefault
      FROM commodity_declarations
    `);
        load('price', `
      SELECT entry_id AS entryId, date, base_commodity AS baseCommodity,
        quote_quantity AS quoteQuantity, quote_commodity AS quoteCommodity, comment
      FROM prices
    `);
        for (const row of database.prepare(`
      SELECT id AS postingId, transaction_id AS transactionId, posting_date AS postingDate,
        account, amount_quantity AS amountQuantity, amount_commodity AS amountCommodity,
        lot_cost_quantity AS lotCostQuantity, lot_cost_commodity AS lotCostCommodity,
        lot_cost_is_total AS lotCostIsTotal,
        cost_quantity AS costQuantity, cost_commodity AS costCommodity,
        cost_is_total AS costIsTotal,
        balance_quantity AS balanceQuantity, balance_commodity AS balanceCommodity
      FROM postings ORDER BY transaction_id, position
    `).all()) {
            const posting = { ...row, comments: [], tags: [] };
            entries.get(row.transactionId).postings.push(posting);
            postings.set(row.postingId, posting);
        }
        for (const row of database.prepare(`
      SELECT transaction_id AS transactionId, posting_id AS postingId, position, text
      FROM comments ORDER BY id
    `).all()) {
            const owner = row.postingId === null ? entries.get(row.transactionId) : postings.get(row.postingId);
            owner.comments.push({ position: row.position, text: row.text });
        }
        for (const row of database.prepare(`
      SELECT transaction_id AS transactionId, posting_id AS postingId,
        position, name, value
      FROM tags ORDER BY transaction_id, posting_id, position, ordinal
    `).all()) {
            const owner = row.postingId === null ? entries.get(row.transactionId) : postings.get(row.postingId);
            owner.tags.push({ position: row.position, name: row.name, value: row.value });
        }
        const orderedIds = sortDeclarations
            ? ids.toSorted((leftId, rightId) => {
                const left = entries.get(leftId);
                const right = entries.get(rightId);
                if (entryRank[left.type] !== entryRank[right.type]) {
                    return entryRank[left.type] - entryRank[right.type];
                }
                if (left.type === 'price') {
                    const commodityOrder = left.baseCommodity.localeCompare(right.baseCommodity, 'en');
                    if (commodityOrder !== 0)
                        return commodityOrder;
                    const dateOrder = left.date.localeCompare(right.date, 'en');
                    if (dateOrder !== 0)
                        return dateOrder;
                }
                return leftId - rightId;
            })
            : ids;
        return `${orderedIds.map((id) => entryText(entries.get(id)))
            .join(density === 'compact' ? '\n' : '\n\n')}\n`;
    }
    return { printJournal };
};