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

100% Statements 129/129
100% Branches 35/35
100% Functions 3/3
100% Lines 129/129

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 13051x 51x 51x 783x 783x 783x 783x 783x 783x 783x 783x 42x 42x 42x 42x 42x 42x 28x 42x 42x 28x 28x 28x 42x 42x 42x 42x 42x 42x 42x 14x 14x 14x 14x 14x 14x 40x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 71x 1x 1x 71x 39x 70x 70x 70x 70x 70x 70x 70x 70x 39x 42x 783x 73x 73x 73x 783x 51x  
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
module.exports = ({ apiOptions: { accounts, booleanOption, dateBasis, dateRange, valuation, validateDateRange, parseOptions }, core: { publicErrors: { createError, errorCodes }, }, numeric: { decimal: { formatDecimal, negateDecimal, parseDecimal, }, }, accountFilter: { accountFilter }, costValuation: { validateCostValuation, costValueSql }, databaseValuationCommodity: { valuationCommodityFromDatabase }, external: { zod: { z } }, }) => {
    const optionsSchema = z.strictObject({
        accounts,
        dateBasis,
        valuation,
        ...dateRange,
        invert: booleanOption,
    }).superRefine(validateDateRange);
    function selectTotalHistory(database, options, valuationCommodity) {
        const atCost = options.valuation === 'cost';
        const quantitySql = atCost ? costValueSql : 'r.amount_quantity';
        const totalSql = atCost
            ? 'positions.quantity'
            : 'decimal_mul(positions.quantity, valuation_prices.rate)';
        const priceJoin = atCost ? '' : `LEFT JOIN valuation_prices
          ON valuation_prices.commodity = positions.commodity
          AND valuation_prices.date = positions.date`;
        const missingCommoditySql = atCost ? 'NULL' : `MIN(CASE
            WHEN valuation_prices.rate IS NULL
              AND decimal_cmp(positions.quantity, '0') != 0
            THEN positions.commodity
          END)`;
        const dateExpression = options.dateBasis === 'transaction' ? 't.date' : 'p.posting_date';
        const selectionFilter = options.accounts.length > 0
            ? accountFilter('p.account', options.accounts)
            : undefined;
        const parameters = [options.to ?? null, ...(selectionFilter?.parameters ?? [])];
        if (atCost) {
            validateCostValuation(database, {
                sql: `WHERE ${dateExpression} <= COALESCE(?, '9999-12-31')` +
                    (selectionFilter ? ` AND ${selectionFilter.sql}` : ''),
                parameters,
            });
        }
        const postingWhere = `WHERE ${dateExpression} <= (SELECT value FROM report_end)` +
            (selectionFilter ? ` AND ${selectionFilter.sql}` : '');
        const latestSelectedDate = options.dateBasis === 'transaction'
            ? 'SELECT MAX(date) AS date FROM transactions'
            : 'SELECT MAX(posting_date) AS date FROM postings';
        const reportEnd = `SELECT MIN(value, COALESCE(?, value)) AS value
      FROM (
        SELECT MAX(date) AS value FROM (
          ${latestSelectedDate}
          UNION ALL
          SELECT MAX(date) AS date FROM prices
        )
      )`;
        parameters.push(options.from ?? null, options.to ?? null);
        const rows = database.prepare(`
    WITH RECURSIVE
      report_end(value) AS MATERIALIZED (
        ${reportEnd}
      ),
      selected_changes AS (
        SELECT
          ${dateExpression} AS date,
          r.amount_commodity AS commodity,
          decimal_sum(${quantitySql}) 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
        ${postingWhere}
        GROUP BY ${dateExpression}, r.amount_commodity
      ),
      commodity_bounds AS (
        SELECT commodity, MIN(date) AS start_date
        FROM selected_changes
        GROUP BY commodity
      ),
      positions(commodity, date, quantity) AS (
        SELECT
          bounds.commodity,
          bounds.start_date,
          COALESCE(changes.quantity, '0')
        FROM commodity_bounds AS bounds
        JOIN report_end ON bounds.start_date <= report_end.value
        LEFT JOIN selected_changes AS changes
          ON changes.commodity = bounds.commodity
          AND changes.date = bounds.start_date
        UNION ALL
        SELECT
          positions.commodity,
          date(positions.date, '+1 day'),
          decimal_add(positions.quantity, COALESCE(changes.quantity, '0'))
        FROM positions
        JOIN report_end ON positions.date < report_end.value
        LEFT JOIN selected_changes AS changes
          ON changes.commodity = positions.commodity
          AND changes.date = date(positions.date, '+1 day')
      ),
      daily_totals AS (
        SELECT
          positions.date,
          decimal_sum(${totalSql}) AS total,
          ${missingCommoditySql} AS missing_commodity
        FROM positions
        ${priceJoin}
        GROUP BY positions.date
      )
    SELECT date, total AS amount, missing_commodity
    FROM daily_totals
    WHERE date >= COALESCE(?, '0000-00-00')
      AND date <= COALESCE(?, '9999-12-31')
    ORDER BY date
  `).all(...parameters);
        for (const row of rows) {
            if (row.missing_commodity) {
                throw createError(errorCodes.MISSING_VALUATION_DATA, `No price for ${row.missing_commodity} on or before ${row.date} can convert it to ${valuationCommodity}`);
            }
        }
        return rows.map(({ date, amount }) => {
            const value = options.invert
                ? formatDecimal(negateDecimal(parseDecimal(amount)))
                : amount;
            return {
                date,
                amount: value,
                commodity: valuationCommodity,
            };
        });
    }
    function queryTotalHistory(database, options, _caches) {
        const reportOptions = parseOptions(optionsSchema, options, 'totalHistory');
        return selectTotalHistory(database, reportOptions, valuationCommodityFromDatabase(database));
    }
    return { inputSchema: optionsSchema, execute: queryTotalHistory };
};