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

100% Statements 143/143
100% Branches 65/65
100% Functions 7/7
100% Lines 143/143

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 14451x 51x 51x 783x 783x 783x 783x 783x 783x 783x 783x 783x 783x 783x 174x 1x 1x 1x 1x 1x 174x 1x 1x 1x 1x 1x 783x 783x 216x 216x 216x 216x 11x 11x 11x 216x 58x 58x 58x 216x 137x 137x 137x 137x 216x 216x 216x 216x 216x 783x 149x 149x 149x 149x 149x 149x 149x 149x 149x 149x 149x 149x 149x 149x 149x 149x 149x 149x 149x 149x 149x 149x 149x 149x 783x 55x 43x 43x 43x 49x 54x 55x 55x 55x 55x 55x 55x 55x 46x 46x 46x 46x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 783x 4x 4x 2x 2x 5x 5x 2x 4x 783x 143x 143x 21x 21x 21x 4x 21x 10x 143x 143x 143x 783x 192x 192x 192x 18x 18x 149x 149x 191x 192x 94x 192x 192x 192x 783x 51x  
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
module.exports = ({ apiOptions: { accounts, booleanOption, dateBasis, dateRange, valuation, validateDateRange, parseOptions }, core: { appendTotal, }, numeric: { decimal: { formatDecimal, multiplyDecimals, negateDecimal, parseDecimal, }, }, accountFilter: { accountFilter }, costValuation: { validateCostValuation, costValueSql }, valuationRates: { queryValuationRates }, databaseValuationCommodity: { valuationCommodityFromDatabase }, external: { zod: { z } }, }) => {
    const optionsSchema = z.strictObject({
        accounts,
        dateBasis,
        valuation,
        ...dateRange,
        groupBy: z.enum(['account', 'commodity'], { error: 'Invalid groupBy' }).default('account'),
        includeTotal: booleanOption,
        denominate: booleanOption,
        invert: booleanOption,
        withValuationValue: booleanOption,
    }).superRefine(validateDateRange).superRefine((input, context) => {
        if (input.denominate && input.withValuationValue) {
            context.addIssue({
                code: 'custom',
                message: 'denominate and withValuationValue cannot be used together',
            });
        }
        if (input.includeTotal && input.groupBy === 'commodity') {
            context.addIssue({
                code: 'custom',
                message: 'includeTotal cannot be used when grouping by commodity',
            });
        }
    });
    function reportFilter(options) {
        const dateExpression = options.dateBasis === 'transaction' ? 't.date' : 'p.posting_date';
        const clauses = [];
        const parameters = [];
        if (options.from) {
            clauses.push(`${dateExpression} >= ?`);
            parameters.push(options.from);
        }
        if (options.to) {
            clauses.push(`${dateExpression} <= ?`);
            parameters.push(options.to);
        }
        if (options.accounts.length > 0) {
            const filter = accountFilter('p.account', options.accounts);
            clauses.push(filter.sql);
            parameters.push(...filter.parameters);
        }
        return {
            sql: clauses.length === 0 ? '' : `WHERE ${clauses.join('\n      AND ')}`,
            parameters,
        };
    }
    function queryCommodityTotals(database, options) {
        const filter = reportFilter(options);
        const costColumn = options.withValuationValue && options.valuation === 'cost'
            ? `, decimal_sum(${costValueSql}) AS valuationValue`
            : '';
        const accountColumn = options.groupBy === 'account' ? 'p.account,\n      ' : '';
        const groupBy = options.groupBy === 'account'
            ? 'p.account, r.amount_commodity'
            : 'r.amount_commodity';
        const nonZero = options.groupBy === 'account'
            ? "\n    HAVING decimal_cmp(decimal_sum(r.amount_quantity), '0') != 0"
            : '';
        const orderBy = options.groupBy === 'account' ? 'p.account, r.amount_commodity' : 'r.amount_commodity';
        return database.prepare(`
    SELECT
      ${accountColumn}r.amount_commodity AS commodity,
      decimal_sum(r.amount_quantity) AS quantity${costColumn}
    FROM resolved_posting_amounts AS r
    JOIN postings AS p ON p.id = r.posting_id
    JOIN transactions AS t ON t.entry_id = p.transaction_id
    ${filter.sql}
    GROUP BY ${groupBy}${nonZero}
    ORDER BY ${orderBy}
  `).all(...filter.parameters);
    }
    function queryValuationTotals(database, options, commodityTotals, valuationPriceCache) {
        if (options.valuation === 'market') {
            const rates = queryValuationRates(database, options.to, new Set(commodityTotals.map((row) => row.commodity)), valuationPriceCache);
            database.function('valuation_rate', { deterministic: true }, (commodity) => rates.get(commodity));
        }
        const valueSql = options.valuation === 'cost'
            ? costValueSql
            : 'decimal_mul(r.amount_quantity, valuation_rate(r.amount_commodity))';
        const valuationCommodity = valuationCommodityFromDatabase(database);
        const filter = reportFilter(options);
        const accountColumn = options.groupBy === 'account' ? 'p.account,\n      ' : '';
        const groupBy = options.groupBy === 'account' ? 'p.account' : '1';
        const nonZero = options.groupBy === 'account'
            ? `
    HAVING decimal_cmp(
      decimal_sum(${valueSql}),
      '0'
    ) != 0`
            : '';
        const orderBy = options.groupBy === 'account' ? 'p.account' : '1';
        return database.prepare(`
    SELECT
      ${accountColumn}? AS commodity,
      decimal_sum(${valueSql}) AS quantity
    FROM resolved_posting_amounts AS r
    JOIN postings AS p ON p.id = r.posting_id
    JOIN transactions AS t ON t.entry_id = p.transaction_id
    ${filter.sql}
    GROUP BY ${groupBy}${nonZero}
    ORDER BY ${orderBy}
  `).all(valuationCommodity, ...filter.parameters);
    }
    function withValuationValues(database, options, commodityTotals, valuationPriceCache) {
        if (options.valuation === 'cost')
            return commodityTotals;
        const rates = queryValuationRates(database, options.to, new Set(commodityTotals.map((row) => row.commodity)), valuationPriceCache);
        return commodityTotals.map((row) => ({
            ...row,
            valuationValue: formatDecimal(multiplyDecimals(parseDecimal(row.quantity), parseDecimal(rates.get(row.commodity)))),
        }));
    }
    function transformRows(rows, options) {
        const transformed = options.invert
            ? rows.map((row) => ({
                ...row,
                quantity: formatDecimal(negateDecimal(parseDecimal(row.quantity))),
                ...(row.valuationValue === undefined ? {} : {
                    valuationValue: formatDecimal(negateDecimal(parseDecimal(row.valuationValue))),
                }),
            }))
            : rows;
        return options.includeTotal ? appendTotal(transformed) : transformed;
    }
    function queryAggregate(database, options, { valuationPriceCache }) {
        const reportOptions = parseOptions(optionsSchema, options, 'aggregate');
        if (reportOptions.valuation === 'cost' &&
            (reportOptions.denominate || reportOptions.withValuationValue)) {
            validateCostValuation(database, reportFilter(reportOptions));
        }
        const commodityTotals = queryCommodityTotals(database, reportOptions);
        const rows = reportOptions.denominate
            ? queryValuationTotals(database, reportOptions, commodityTotals, valuationPriceCache)
            : reportOptions.withValuationValue
                ? withValuationValues(database, reportOptions, commodityTotals, valuationPriceCache)
                : commodityTotals;
        return transformRows(rows, reportOptions);
    }
    return { inputSchema: optionsSchema, execute: queryAggregate };
};