Debian Codegraph @

frontend/src/charts/query-charts.ts

raw
1 import { stratify } from "../lib/tree";
2 import type { Inventory, QueryResultTable } from "../reports/query/query_table";
3 import type { ChartContext } from "./context";
4 import type { HierarchyChart } from "./hierarchy";
5 import { hierarchy_from_parsed_data } from "./hierarchy";
6 import type { LineChart } from "./line";
7 import { balances_from_parsed_data } from "./line";
8
9 /** Get the query chart, if possible, from a query result */
10 export function getQueryChart(
11 table: QueryResultTable,
12 $chartContext: ChartContext,
13 ): HierarchyChart | LineChart | null {
14 const { columns } = table;
15 const [first, second] = columns;
16 if (!first || !second || columns.length > 2) {
17 return null;
18 }
19 if (first.dtype === "str" && second.dtype === "Inventory") {
20 const grouped = (table.rows as [string, Inventory][]).map(
21 ([group, inv]) => ({ group, balance: inv.value }),
22 );
23 const root = stratify(
24 grouped,
25 (d) => d.group,
26 (account, d) => ({ account, balance: d?.balance ?? {} }),
27 );
28 root.account = "(root)";
29 return hierarchy_from_parsed_data(null, root, $chartContext);
30 }
31 if (first.dtype === "date" && second.dtype === "Inventory") {
32 const bals = (table.rows as [Date, Inventory][]).map(([date, inv]) => ({
33 date,
34 balance: inv.value,
35 }));
36 return balances_from_parsed_data(null, bals);
37 }
38 return null;
39 }