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

96.7% Statements 88/91
89.47% Branches 17/19
100% Functions 6/6
96.7% Lines 88/91

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 9251x 51x 51x 783x 783x 783x 783x 783x 783x 783x 118x 118x 118x 118x 118x 118x 118x 16x 16x 16x 16x 118x 118x 783x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 118x 783x 118x 96x       96x 118x 783x 117x 117x 95x 95x 95x 95x 117x 117x 117x 117x 81x 81x 81x 117x 117x 783x 139x 139x 139x 139x 139x 139x 139x 139x 783x 783x 783x 783x 51x  
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
module.exports = ({ apiOptions: { accounts, dateBasis, dateOption, parseOptions }, numeric: { decimal: { addDecimals, compareDecimals, formatDecimal, multiplyDecimals, parseDecimal, subtractDecimals, }, }, accountFilter: { accountFilter }, valuationRates: { queryValuationRates }, databaseValuationCommodity: { valuationCommodityFromDatabase }, external: { zod: { z } }, }) => {
    const ZERO = parseDecimal('0');
    const optionsSchema = z.strictObject({
        accounts,
        dateBasis,
        to: dateOption,
    });
    function reportFilter(options, valuationCommodity) {
        const dateExpression = options.dateBasis === 'transaction' ? 't.date' : 'p.posting_date';
        const clauses = [
            'r.amount_commodity != ?',
            `${dateExpression} <= COALESCE(?, '9999-12-31')`,
        ];
        const parameters = [valuationCommodity, options.to ?? null];
        if (options.accounts.length > 0) {
            const filter = accountFilter('p.account', options.accounts);
            clauses.push(filter.sql);
            parameters.push(...filter.parameters);
        }
        return { sql: `WHERE ${clauses.join('\n      AND ')}`, parameters };
    }
    function queryPositions(database, options, valuationCommodity) {
        const filter = reportFilter(options, valuationCommodity);
        return database.prepare(`
      SELECT
        p.account,
        r.amount_commodity AS commodity,
        decimal_sum(r.amount_quantity) AS quantity,
        decimal_sum(CASE
          WHEN p.lot_cost_quantity IS NULL THEN NULL
          WHEN p.lot_cost_is_total = 1 THEN CASE
            WHEN decimal_cmp(r.amount_quantity, '0') < 0 AND
                 decimal_cmp(p.lot_cost_quantity, '0') > 0
              THEN decimal_mul(p.lot_cost_quantity, '-1')
            ELSE p.lot_cost_quantity
          END
          ELSE decimal_mul(r.amount_quantity, p.lot_cost_quantity)
        END) AS cost_basis,
        MIN(CASE WHEN p.lot_cost_quantity IS NULL THEN r.amount_commodity END) AS missing_lot_cost,
        MIN(CASE
          WHEN p.lot_cost_commodity != ? THEN p.lot_cost_commodity
        END) AS foreign_lot_cost_commodity
      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 p.account, r.amount_commodity
      HAVING decimal_cmp(decimal_sum(r.amount_quantity), '0') != 0
      ORDER BY p.account, r.amount_commodity
    `).all(valuationCommodity, ...filter.parameters);
    }
    function validateCostBases(positions) {
        for (const position of positions) {
            if (position.missing_lot_cost) {
                throw new Error(`Cannot calculate unrealized gain for ${position.account}: ` +
                    `${position.missing_lot_cost} has no lot cost`);
            }
        }
    }
    function calculateRows(positions, rates, valuationCommodity) {
        const gains = new Map();
        for (const position of positions) {
            const marketValue = multiplyDecimals(parseDecimal(position.quantity), parseDecimal(rates.get(position.commodity)));
            const gain = subtractDecimals(marketValue, parseDecimal(position.cost_basis));
            gains.set(position.account, addDecimals(gains.get(position.account) || ZERO, gain));
        }
        return [...gains]
            .filter(([, gain]) => compareDecimals(gain, ZERO) !== 0)
            .sort(([left], [right]) => left.localeCompare(right, 'en'))
            .map(([account, gain]) => ({
            account,
            quantity: formatDecimal(gain),
            commodity: valuationCommodity,
        }));
    }
    function queryUnrealizedGains(database, options, { valuationPriceCache }) {
        const reportOptions = parseOptions(optionsSchema, options, 'unrealizedGains');
        const valuationCommodity = valuationCommodityFromDatabase(database);
        const positions = queryPositions(database, reportOptions, valuationCommodity)
            .filter((position) => !position.foreign_lot_cost_commodity);
        validateCostBases(positions);
        const rates = queryValuationRates(database, reportOptions.to, new Set(positions.map((position) => position.commodity)), valuationPriceCache);
        return calculateRows(positions, rates, valuationCommodity);
    }
    return {
        inputSchema: optionsSchema,
        execute: queryUnrealizedGains,
    };
};