@sprigr/apps-reporting-core 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +3 -2
  2. package/dist/index.js +212 -59
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -77,8 +77,9 @@ Modes `total`, `period`, `variance`, `period_variance`, `transaction`, `stream`,
77
77
  - **A filter on a measure** drops rows after grouping. It never drops the total row, which stays the total of every member. A measure the view does not show can be filtered on. Dimension rules and measure rules combine with "and" only.
78
78
  - **Transaction** lists the fact rows: the date as text, every dimension code of the stream, the stream's extra `columns`, and each measure as that row holds it (a count is 1).
79
79
  - **Stream** puts measures from more than one stream side by side over the whole period, such as invoiced beside ordered. It reads the view's own stream and every other stream its measures belong to. Each stream is grouped on its own under the same drill path, filters and keyword, then the results are folded to one row per member, so a formula can read sums from two streams. A member is listed when any of those streams has rows for it. Every stream read must carry each dimension the view uses. `streams` in the result lists them.
80
+ - **A period or variance view with a measure of another stream** is compiled the same way: each stream is grouped on its own, over its own date column, then the results are folded to one row per member. A period view gets one column per period for every measure, and a variance its current, earlier, variance and variance percentage columns, all named as in a view of one stream. A formula is worked out for each period from the folded sums, with that period's own days. A snapshot measure reads the latest day of each period, or of each window, in its own stream. Every stream read must carry each dimension the view uses, `streams` in the result lists them, and `compileRollupView` reads a rollup of each. The statement is always one column per period: the long shape is refused, and so is a view too wide for the route. Total and period variance views still refuse a measure of another stream with `measure_not_on_stream`; a custom view reads one through its points, below.
80
81
  - **Matrix** groups by two dimensions: `group_by` gives the rows and `across` the columns. The result is long, one row per cell, and the grid pivots it. `__row` and `__col` say where a cell goes (0 is a total), `__total = 1` marks a column total and `__across_total = 1` a row total. Cells, row totals, column totals and the grand total come from one pass, each worked out from its own sums. Rows are sorted, paged and filtered on a measure by their row totals. `across.limit` keeps the first columns (12 unless given), picked by the first measure's column total or by code. Row totals and column totals are always returned, the column totals because they name the columns; the grand total comes with `options.total_row`. A page holds fewer rows than in other modes, since each row costs one result row per column kept and the column totals take one each; a `limit` above that is cut down, and `limit` in the result says what a page holds.
81
- - **Custom** builds each column on its own. `custom_columns` lists them and `measures` is not read. A column is one of three things. A data point: `point` names a measure, and may give its own `period` (the view's period when left out) and a `where` rule on one dimension, such as sales of one department last June. A comparison: `point` and `against`, shown as the difference or, with `show: 'percent'`, as a fraction of the second point; a blank counts as 0 and the percentage is blank when there is nothing to compare against, as in a variance. An expression: a formula over the column's own `points`, named by the letters the formula uses, with a `format` (`number` unless given). `hidden` keeps a column out of the result; it can still be sorted on. `sort.by` takes `code`, `property.<key>` or `column.<key>`, and the first shown column, descending, when left out. Every distinct data point is read once, in one pass over the rows of every window the columns use. Result columns are named `c__<key>`. `windows` in the result lists those windows and `window` runs from the earliest to the latest. The drill path, dimension filters, keyword, properties, the total, sum and average rows and hiding zero rows work as in total mode, the last three over the shown columns. A snapshot measure reads the latest day of its own point's window.
82
+ - **Custom** builds each column on its own. `custom_columns` lists them and `measures` is not read. A column is one of three things. A data point: `point` names a measure, and may give its own `period` (the view's period when left out) and a `where` rule on one dimension, such as sales of one department last June. A comparison: `point` and `against`, shown as the difference or, with `show: 'percent'`, as a fraction of the second point; a blank counts as 0 and the percentage is blank when there is nothing to compare against, as in a variance. An expression: a formula over the column's own `points`, named by the letters the formula uses, with a `format` (`number` unless given). `hidden` keeps a column out of the result; it can still be sorted on. `sort.by` takes `code`, `property.<key>` or `column.<key>`, and the first shown column, descending, when left out. Every distinct data point is read once, in one pass over the rows of every window the columns use. Result columns are named `c__<key>`. `windows` in the result lists those windows and `window` runs from the earliest to the latest. The drill path, dimension filters, keyword, properties, the total, sum and average rows and hiding zero rows work as in total mode, the last three over the shown columns. A snapshot measure reads the latest day of its own point's window. A point may read a measure of another stream, such as stock on hand beside sales: each stream is then grouped in its own stage, over only the windows its points use, under the same drill path, filters and keyword, and the stages are folded to one row per member as in stream mode. The view's own stream is always read, every stream read must carry each dimension the view uses, and `streams` in the result lists them. A formula measure is read on the stream of the first measure it names, so one that mixes streams still refuses with `measure_not_on_stream`; put each stream's figure in its own point and combine them in an expression column. Nested rows are refused across streams.
82
83
  - **A period view that is too wide** for one column per period (the route takes 24,000 characters of SQL) is returned long instead: the matrix result with the periods as its columns, `shape: 'long'`, and `across` holding the period's number from the oldest. A period no row falls in has no cell. A total is worked out over the whole window, so `DAYS()` and a snapshot measure read the window there and the period on a cell. `sort.by` can still name one period of a shown measure. `periodShape` in the context forces `wide` or `long`; left out, the compiler goes long only when it must. A page holds fewer rows (153 with 12 periods), and `limit` in the result says how many.
83
84
  - **Activity** (`options.activity`): `with` lists members that have fact rows. `all` adds the members that have none, read from the dimension's own table. `without` lists only those, with no total row. The keyword, and the path steps and "and" filters on the group-by dimension or a dimension above it, narrow the member list; every filter decides what counts as activity.
84
85
  - **The others row** (`options.others_row`, modes `total`, `period` and `variance`): a view is focused when its drill path has a step on the group-by dimension itself. The others row is every member that step leaves out, as one row, with formulas worked out from its own sums. The total row is then the focused members' total. Without a focus there is no others row.
@@ -90,7 +91,7 @@ Modes `total`, `period`, `variance`, `period_variance`, `transaction`, `stream`,
90
91
  - **A snapshot measure** (a level, such as stock on hand) reads the rows of the latest day in each window. That day is the same for every member and is found before any filter, so the stream must hold every member's row on each snapshot day.
91
92
  - **A measure of two columns** (`times` on a base measure that is not a count): reads `column` times the `times` column on each row, then aggregates, such as units on order times a unit cost. A rollup's column for such a measure already holds the product, so the rollup is read as it is. `measureAvailability` hides the measure from a role that lacks either column.
92
93
 
93
- Refused with a named reason until built: an others row in stream mode; others, average and sum rows in matrix mode and in the long shape of a period view; an others row or hidden zero rows with the activity option; the average column in the long shape of a period view; the activity option, period columns and a variance in stream and matrix modes; the activity option in the long shape of a period view; a snapshot measure or a total row on a transaction list; a filter on a measure, an others row and the activity option in custom mode; the grid functions RANK, PERCENTILE and FORECAST.LINEAR.
94
+ Refused with a named reason until built: an others row in stream mode; nested rows, the activity option and an others row in a period or variance view of more than one stream, and the average column in such a period view; others, average and sum rows in matrix mode and in the long shape of a period view; an others row or hidden zero rows with the activity option; the average column in the long shape of a period view; the activity option, period columns and a variance in stream and matrix modes; the activity option in the long shape of a period view; a snapshot measure or a total row on a transaction list; a filter on a measure, an others row and the activity option in custom mode; the grid functions RANK, PERCENTILE and FORECAST.LINEAR.
94
95
 
95
96
  ## To check against the source system at migration
96
97
 
package/dist/index.js CHANGED
@@ -1168,6 +1168,15 @@ function compileMode(model, view, ctx) {
1168
1168
  if (view.mode === "stream") return compileStreams(model, view, ctx);
1169
1169
  if (view.mode === "matrix") return compileMatrix(model, view, ctx);
1170
1170
  if (view.mode === "custom") return compileCustom(model, view, ctx);
1171
+ if (view.mode !== "period" && view.mode !== "variance") return compileGrouped(model, view, ctx);
1172
+ try {
1173
+ return compileOneStream(model, view, ctx);
1174
+ } catch (err) {
1175
+ if (!(err instanceof ReportingError) || err.reason !== "measure_not_on_stream" || ctx.periodShape === "long") throw err;
1176
+ return compileStreams(model, view, ctx);
1177
+ }
1178
+ }
1179
+ function compileOneStream(model, view, ctx) {
1171
1180
  if (view.mode !== "period" || ctx.periodShape === "wide") return compileGrouped(model, view, ctx);
1172
1181
  if (ctx.periodShape === "long") return compileMatrix(model, view, ctx, true);
1173
1182
  try {
@@ -1546,6 +1555,37 @@ function withLatestDayOfEach(table, date, columns, where, windows) {
1546
1555
  });
1547
1556
  return `(SELECT *${columns}, ${flags.join(", ")} FROM ${table} WHERE ${where}) AS ${FACT}`;
1548
1557
  }
1558
+ function comparedWith(model, view, ctx, window) {
1559
+ const compare = view.compare ?? "previous_year";
1560
+ let comparison;
1561
+ if (typeof compare === "object" && compare !== null) {
1562
+ if (typeof compare.period !== "object" || compare.period === null) fail("option_unsupported", "a comparison given as an object needs a period");
1563
+ comparison = resolvePeriod(compare.period, model.periods, ctx.today, { periodToDate: view.options?.period_to_date === true }).window;
1564
+ } else {
1565
+ if (compare !== "previous_year" && compare !== "previous_period") fail("option_unsupported", `"${String(compare)}" is not a comparison`);
1566
+ comparison = comparisonWindow(window, compare);
1567
+ }
1568
+ const whole = (key, label, w) => ({ key, label, from: w.from, to: w.to, days: daysBetween(w.from, w.to) });
1569
+ return {
1570
+ comparison,
1571
+ current: whole("current", "Current", window),
1572
+ previous: whole("previous", compare === "previous_year" ? "Previous year" : compare === "previous_period" ? "Previous period" : "Comparison", comparison)
1573
+ };
1574
+ }
1575
+ function factAcross(stream, range, buckets, comparison, latest) {
1576
+ if (buckets.length === 0 && !comparison) return factOver(stream, range, latest);
1577
+ const table = quoteIdent(stream.table);
1578
+ const date = quoteIdent(stream.date);
1579
+ const inWindow = (w) => `${date} >= ${sqlDate(w.from)} AND ${date} < ${sqlDate(w.to)}`;
1580
+ if (!comparison) {
1581
+ const numbered = perBucket(date, buckets, (_, i) => i + 1);
1582
+ const columns2 = `, ${numbered} AS "__b"`;
1583
+ return latest ? withLatestDays(table, date, numbered, columns2, inWindow(range)) : `(SELECT *${columns2} FROM ${table} WHERE ${inWindow(range)}) AS ${FACT}`;
1584
+ }
1585
+ const columns = `, (${inWindow(range)}) AS "__cur", (${inWindow(comparison)}) AS "__prev"`;
1586
+ const where = `(${inWindow(range)}) OR (${inWindow(comparison)})`;
1587
+ return latest ? withLatestDayOfEach(table, date, columns, where, [{ where: inWindow(range), flag: "__lastc" }, { where: inWindow(comparison), flag: "__lastp" }]) : `(SELECT *${columns} FROM ${table} WHERE ${where}) AS ${FACT}`;
1588
+ }
1549
1589
  function perBucket(date, buckets, value) {
1550
1590
  return `CASE ${buckets.map((b, i) => `WHEN ${date} < ${sqlDate(b.to)} THEN ${value(b, i)}`).join(" ")} END`;
1551
1591
  }
@@ -1630,21 +1670,10 @@ function compileGrouped(model, view, ctx) {
1630
1670
  let earlierSlices = [];
1631
1671
  let earlierBuckets = [];
1632
1672
  if (view.mode === "variance" || periodVariance) {
1633
- const compare = view.compare ?? "previous_year";
1634
- if (typeof compare === "object" && compare !== null) {
1635
- if (typeof compare.period !== "object" || compare.period === null) fail("option_unsupported", "a comparison given as an object needs a period");
1636
- comparison = resolvePeriod(compare.period, model.periods, ctx.today, { periodToDate: options.period_to_date === true }).window;
1637
- } else {
1638
- if (compare !== "previous_year" && compare !== "previous_period") fail("option_unsupported", `"${String(compare)}" is not a comparison`);
1639
- comparison = comparisonWindow(period.window, compare);
1640
- }
1641
- const whole = (key, label, w) => ({ key, label, from: w.from, to: w.to, days: daysBetween(w.from, w.to) });
1642
- current = { bucket: whole("current", "Current", period.window), filter: `${FACT}."__cur"`, last: `${FACT}."__lastc"` };
1643
- previous = {
1644
- bucket: whole("previous", compare === "previous_year" ? "Previous year" : compare === "previous_period" ? "Previous period" : "Comparison", comparison),
1645
- filter: `${FACT}."__prev"`,
1646
- last: `${FACT}."__lastp"`
1647
- };
1673
+ const two = comparedWith(model, view, ctx, period.window);
1674
+ comparison = two.comparison;
1675
+ current = { bucket: two.current, filter: `${FACT}."__cur"`, last: `${FACT}."__lastc"` };
1676
+ previous = { bucket: two.previous, filter: `${FACT}."__prev"`, last: `${FACT}."__lastp"` };
1648
1677
  factColumns = `, (${inWindow(period.window)}) AS "__cur", (${inWindow(comparison)}) AS "__prev"`;
1649
1678
  factWhere = `(${inWindow(period.window)}) OR (${inWindow(comparison)})`;
1650
1679
  if (periodVariance) {
@@ -1874,13 +1903,30 @@ function compileCustom(model, view, ctx) {
1874
1903
  };
1875
1904
  const uses = /* @__PURE__ */ new Set();
1876
1905
  const reads = { stream, measureByKey, parsed: /* @__PURE__ */ new Map(), countAll: "COUNT(*)", days: daysBetween(own.from, own.to), uses };
1906
+ const reading = /* @__PURE__ */ new Map([[stream.key, { scope, reads, windows: /* @__PURE__ */ new Set() }]]);
1907
+ const readsOf = (key) => {
1908
+ let found = reading.get(key);
1909
+ if (!found) {
1910
+ const other = scopeOf(model, { ...view, stream: key }, ctx);
1911
+ found = { scope: other, reads: { ...reads, stream: other.stream, parsed: /* @__PURE__ */ new Map(), uses: /* @__PURE__ */ new Set() }, windows: /* @__PURE__ */ new Set() };
1912
+ reading.set(key, found);
1913
+ }
1914
+ return found;
1915
+ };
1916
+ const streamOf = (measure, depth = 0) => {
1917
+ if (!isFormulaMeasure(measure)) return measure.stream;
1918
+ const first = depth > 20 ? void 0 : formulaRefs(parseFormula(measure.formula)).map((ref) => measureByKey.get(ref)).find((m) => m !== void 0);
1919
+ return first === void 0 ? stream.key : streamOf(first, depth + 1);
1920
+ };
1877
1921
  const points = [];
1878
1922
  const pointOf = (point, what) => {
1879
1923
  if (typeof point !== "object" || point === null) fail("bad_custom_column", `${what} has no data point`);
1880
1924
  const measure = measureByKey.get(point.measure) ?? fail("unknown_measure", `no measure "${String(point.measure)}"`);
1881
1925
  const { window, number } = windowOf(point.period);
1882
1926
  if (point.where !== void 0 && (typeof point.where !== "object" || point.where === null || "measure" in point.where)) fail("bad_custom_column", `the rule of ${what} is not a dimension rule`);
1883
- const rule = point.where === void 0 ? "" : ` AND ${scope.dimensionRule(point.where)}`;
1927
+ const src = readsOf(streamOf(measure));
1928
+ src.windows.add(number);
1929
+ const rule = point.where === void 0 ? "" : ` AND ${src.scope.dimensionRule(point.where)}`;
1884
1930
  const bucket = {
1885
1931
  key: `w${number}`,
1886
1932
  label: `${window.from} to ${addDays(window.to, -1)}`,
@@ -1889,9 +1935,10 @@ function compileCustom(model, view, ctx) {
1889
1935
  days: daysBetween(window.from, window.to)
1890
1936
  };
1891
1937
  const slice = { bucket, filter: `${FACT}.${quoteIdent(`__w${number}`)}${rule}`, last: `${FACT}.${quoteIdent(`__l${number}`)}${rule}` };
1892
- const sql2 = `CAST(${measureOver(reads, measure.key, slice)} AS DOUBLE)`;
1893
- const at = points.indexOf(sql2);
1894
- return { name: `p${at >= 0 ? at + 1 : points.push(sql2)}`, measure, bucket };
1938
+ const sql2 = `CAST(${measureOver(src.reads, measure.key, slice)} AS DOUBLE)`;
1939
+ const key = src.scope.stream.key;
1940
+ const at = points.findIndex((p) => p.stream === key && p.sql === sql2);
1941
+ return { name: `p${at >= 0 ? at + 1 : points.push({ stream: key, sql: sql2 })}`, measure, bucket };
1895
1942
  };
1896
1943
  const columns = [...nest?.columns ?? [], { name: "code", kind: "code", label: groupDim.label }];
1897
1944
  const select = [...nest?.select ?? [], `${codeExpr} AS "code"`];
@@ -1952,7 +1999,9 @@ function compileCustom(model, view, ctx) {
1952
1999
  const measured = columns.filter((c) => c.kind === "measure").map((c) => c.name);
1953
2000
  if (measured.length === 0) fail("bad_custom_column", "every column of the view is hidden");
1954
2001
  if (points.length === 0) fail("bad_custom_column", "no column of the view reads a data point");
1955
- points.forEach((sql2, i) => {
2002
+ const multi = reading.size > 1;
2003
+ if (multi && nest) fail("option_unsupported", "nested rows are not compiled for a custom view of more than one stream yet");
2004
+ points.forEach(({ sql: sql2 }, i) => {
1956
2005
  select.push(`${sql2} AS ${quoteIdent(`p${i + 1}`)}`);
1957
2006
  left.push(`p${i + 1}`);
1958
2007
  });
@@ -1974,13 +2023,42 @@ function compileCustom(model, view, ctx) {
1974
2023
  const flags = `, ${windows.map((w, i) => `(${inWindow(w)}) AS ${quoteIdent(`__w${i + 1}`)}`).join(", ")}`;
1975
2024
  const anyWindow = windows.map((w) => `(${inWindow(w)})`).join(" OR ");
1976
2025
  const fact = uses.has("snapshot") ? withLatestDayOfEach(quoteIdent(stream.table), date, flags, anyWindow, windows.map((w, i) => ({ where: inWindow(w), flag: `__l${i + 1}` }))) : `(SELECT *${flags} FROM ${quoteIdent(stream.table)} WHERE ${anyWindow}) AS ${FACT}`;
2026
+ const streamKeys = [stream.key, ...model.streams.map((s) => s.key).filter((key) => key !== stream.key && reading.has(key))];
2027
+ const stages = !multi ? [] : streamKeys.map((key) => {
2028
+ const { scope: s, reads: r, windows: used } = readsOf(key);
2029
+ const grouped = `GROUPING(${s.codeExpr})`;
2030
+ const parts2 = [`${s.codeExpr} AS "code"`];
2031
+ shownProperties(view).forEach((property) => {
2032
+ const expr = `any_value(${s.propertyOf(groupDim.key, property)})`;
2033
+ parts2.push(`${totalRow ? `CASE WHEN ${grouped} = 0 THEN ${expr} END` : expr} AS ${quoteIdent(`prop__${property}`)}`);
2034
+ });
2035
+ points.forEach((p, i) => {
2036
+ if (p.stream === key) parts2.push(`${p.sql} AS ${quoteIdent(`p${i + 1}`)}`);
2037
+ });
2038
+ parts2.push(`${totalRow ? `CAST(${grouped} AS INTEGER)` : "0"} AS "__total"`);
2039
+ const mine = [...used].sort((a, b) => a - b);
2040
+ const sDate = quoteIdent(s.stream.date);
2041
+ const sIn = (w) => `${sDate} >= ${sqlDate(w.from)} AND ${sDate} < ${sqlDate(w.to)}`;
2042
+ const sFlags = mine.map((n) => `(${sIn(windows[n - 1])}) AS ${quoteIdent(`__w${n}`)}`).join(", ");
2043
+ const sAny = mine.map((n) => `(${sIn(windows[n - 1])})`).join(" OR ");
2044
+ const from = mine.length === 0 ? factOver(s.stream, own, false) : r.uses.has("snapshot") ? withLatestDayOfEach(quoteIdent(s.stream.table), sDate, `, ${sFlags}`, sAny, mine.map((n) => ({ where: sIn(windows[n - 1]), flag: `__l${n}` }))) : `(SELECT *, ${sFlags} FROM ${quoteIdent(s.stream.table)} WHERE ${sAny}) AS ${FACT}`;
2045
+ return { select: parts2, from, joins: [...s.joins.values()], where: s.where, groupBy: totalRow ? `GROUP BY GROUPING SETS ((${s.codeExpr}), ())` : `GROUP BY ${s.codeExpr}` };
2046
+ });
2047
+ const fold = [
2048
+ '"code"',
2049
+ ...shownProperties(view).map((property) => `any_value(${quoteIdent(`prop__${property}`)}) AS ${quoteIdent(`prop__${property}`)}`),
2050
+ ...points.map((_, i) => `any_value(${quoteIdent(`p${i + 1}`)}) AS ${quoteIdent(`p${i + 1}`)}`),
2051
+ '"__total"'
2052
+ ];
1977
2053
  const sql = [
1978
- "WITH g AS (",
1979
- `SELECT ${select.join(", ")}`,
1980
- `FROM ${fact}`,
1981
- ...joins.values(),
1982
- ...where.length > 0 ? [`WHERE ${where.join(" AND ")}`] : [],
1983
- nest ? nest.groupBy(totalRow) : totalRow ? `GROUP BY GROUPING SETS ((${codeExpr}), ())` : `GROUP BY ${codeExpr}`,
2054
+ ...multi ? foldStreams(stages, fold) : [
2055
+ "WITH g AS (",
2056
+ `SELECT ${select.join(", ")}`,
2057
+ `FROM ${fact}`,
2058
+ ...joins.values(),
2059
+ ...where.length > 0 ? [`WHERE ${where.join(" AND ")}`] : [],
2060
+ nest ? nest.groupBy(totalRow) : totalRow ? `GROUP BY GROUPING SETS ((${codeExpr}), ())` : `GROUP BY ${codeExpr}`
2061
+ ],
1984
2062
  "), v AS (",
1985
2063
  `SELECT g.*, ${derived.join(", ")}`,
1986
2064
  "FROM g",
@@ -1996,7 +2074,7 @@ function compileCustom(model, view, ctx) {
1996
2074
  from: windows.reduce((min, w) => w.from < min ? w.from : min, windows[0]?.from ?? own.from),
1997
2075
  to: windows.reduce((max, w) => w.to > max ? w.to : max, windows[0]?.to ?? own.to)
1998
2076
  };
1999
- return { ok: true, sql, columns, window: hull, windows, buckets: [], months: monthsRange(hull) };
2077
+ return { ok: true, sql, columns, window: hull, windows, buckets: [], months: monthsRange(hull), ...multi ? { streams: streamKeys } : {} };
2000
2078
  }
2001
2079
  function compileTransactions(model, view, ctx) {
2002
2080
  const options = view.options ?? {};
@@ -2079,11 +2157,30 @@ function compileTransactions(model, view, ctx) {
2079
2157
  checkLength(sql, ctx);
2080
2158
  return { ok: true, sql, columns, window: period.window, buckets: [], months: monthsRange(period.window) };
2081
2159
  }
2160
+ function foldStreams(stages, fold) {
2161
+ return [
2162
+ ...stages.flatMap((stage, i) => [
2163
+ `${i === 0 ? "WITH" : "),"} s${i + 1} AS (`,
2164
+ `SELECT ${stage.select.join(", ")}`,
2165
+ `FROM ${stage.from}`,
2166
+ ...stage.joins,
2167
+ ...stage.where.length > 0 ? [`WHERE ${stage.where.join(" AND ")}`] : [],
2168
+ stage.groupBy
2169
+ ]),
2170
+ "), g AS (",
2171
+ `SELECT ${fold.join(", ")}`,
2172
+ // By name: each stage has its own sum columns, and a member one stream lacks gets blanks there.
2173
+ `FROM (${stages.map((_, i) => `SELECT * FROM s${i + 1}`).join(" UNION ALL BY NAME ")}) AS u`,
2174
+ 'GROUP BY "code", "__total"'
2175
+ ];
2176
+ }
2082
2177
  function compileStreams(model, view, ctx) {
2083
2178
  const options = view.options ?? {};
2084
- if (view.levels !== void 0) fail("option_unsupported", "nested rows are not compiled for stream mode yet");
2085
- if ((options.activity ?? "with") !== "with") fail("option_unsupported", "the activity option is not compiled for stream mode yet");
2086
- if (options.others_row) fail("option_unsupported", "an others row is not compiled for stream mode yet");
2179
+ const what = view.mode === "stream" ? "stream mode" : "a view of more than one stream";
2180
+ if (view.levels !== void 0) fail("option_unsupported", `nested rows are not compiled for ${what} yet`);
2181
+ if ((options.activity ?? "with") !== "with") fail("option_unsupported", `the activity option is not compiled for ${what} yet`);
2182
+ if (options.others_row) fail("option_unsupported", `an others row is not compiled for ${what} yet`);
2183
+ if (options.average_column && view.mode === "period") fail("option_unsupported", `an average column is not compiled for ${what} yet`);
2087
2184
  const totalRow = options.total_row === true;
2088
2185
  const averageRow = options.average_row === true;
2089
2186
  const sumRow = options.sum_row === true;
@@ -2093,9 +2190,18 @@ function compileStreams(model, view, ctx) {
2093
2190
  const unseen = lead.filterMeasures.filter((key) => !view.measures.includes(key)).map((key) => measureByKey.get(key) ?? fail("unknown_measure", `no measure "${key}"`));
2094
2191
  const period = resolvePeriod(view.period, model.periods, ctx.today, { periodToDate: options.period_to_date === true });
2095
2192
  const range = period.window;
2193
+ const buckets = view.mode === "period" ? period.buckets : [];
2194
+ const two = view.mode === "variance" ? comparedWith(model, view, ctx, range) : null;
2195
+ const whole = two ? { prefix: "a", days: two.current.days, filter: `${FACT}."__cur"`, last: `${FACT}."__lastc"` } : { prefix: "a", days: daysBetween(range.from, range.to), filter: null, last: `${FACT}."__lastw"` };
2196
+ const earlier = two ? { prefix: "ap", days: two.previous.days, filter: `${FACT}."__prev"`, last: `${FACT}."__lastp"` } : null;
2197
+ const perPeriod = buckets.map((bucket, i) => ({
2198
+ bucket,
2199
+ part: { prefix: `a${i + 1}`, days: bucket.days, filter: `${FACT}."__b" = ${i + 1}`, last: `${FACT}."__b" = ${i + 1} AND ${FACT}."__last"` },
2200
+ index: i + 1
2201
+ }));
2096
2202
  const needed = /* @__PURE__ */ new Map();
2097
2203
  const parsed = /* @__PURE__ */ new Map();
2098
- const exprOf = (key, depth) => {
2204
+ const exprOf = (key, part, depth) => {
2099
2205
  if (depth > 20) fail("formula_cycle", `"${key}" refers back to itself`);
2100
2206
  const measure = measureByKey.get(key) ?? fail("formula_unknown_measure", `"${key}" is not a measure`);
2101
2207
  if (isFormulaMeasure(measure)) {
@@ -2104,12 +2210,16 @@ function compileStreams(model, view, ctx) {
2104
2210
  node = parseFormula(measure.formula);
2105
2211
  parsed.set(key, node);
2106
2212
  }
2107
- return emitFormulaSql(node, { measure: (ref) => exprOf(ref, depth + 1), days: daysBetween(range.from, range.to) });
2213
+ return emitFormulaSql(node, {
2214
+ measure: (ref) => exprOf(ref, part, depth + 1),
2215
+ days: part.days,
2216
+ ...buckets.length > 0 ? { periodCount: buckets.length } : {}
2217
+ });
2108
2218
  }
2109
2219
  const list2 = needed.get(measure.stream) ?? [];
2110
- if (!list2.some((m) => m.key === measure.key)) list2.push(measure);
2220
+ if (!list2.some((n) => n.measure.key === measure.key && n.part === part)) list2.push({ measure, part });
2111
2221
  needed.set(measure.stream, list2);
2112
- return `any_value(${quoteIdent(`a__${measure.key}`)})`;
2222
+ return `any_value(${quoteIdent(`${part.prefix}__${measure.key}`)})`;
2113
2223
  };
2114
2224
  const properties = shownProperties(view);
2115
2225
  const columns = [{ name: "code", kind: "code", label: groupDim.label }];
@@ -2121,12 +2231,53 @@ function compileStreams(model, view, ctx) {
2121
2231
  columns.push({ name, kind: "property", label, property });
2122
2232
  });
2123
2233
  const left = ["__rn"];
2124
- const addMeasure = (measure, seen) => {
2125
- const name = `m__${measure.key}`;
2126
- select.push(`CAST(${exprOf(measure.key, 0)} AS DOUBLE) AS ${quoteIdent(name)}`);
2127
- if (seen) columns.push({ name, kind: "measure", label: measure.label, measure: measure.key, format: measure.format, period: null });
2234
+ const derived = [];
2235
+ const put = (into, name, expr, seen, column) => {
2236
+ into.push(`${expr} AS ${quoteIdent(name)}`);
2237
+ if (seen) columns.push({ name, kind: "measure", ...column });
2128
2238
  else left.push(name);
2129
2239
  };
2240
+ const figure = (key, part) => `CAST(${exprOf(key, part, 0)} AS DOUBLE)`;
2241
+ const display = options.reverse_periods ? [...perPeriod].reverse() : perPeriod;
2242
+ const addMeasure = (measure, seen) => {
2243
+ const about = { measure: measure.key, format: measure.format };
2244
+ if (seen) {
2245
+ display.forEach(({ bucket, part, index }) => {
2246
+ put(select, `b${index}__${measure.key}`, figure(measure.key, part), true, { ...about, label: `${measure.label} ${bucket.label}`, period: bucket });
2247
+ });
2248
+ }
2249
+ const wholeName = `m__${measure.key}`;
2250
+ put(select, wholeName, figure(measure.key, whole), seen, {
2251
+ ...about,
2252
+ label: buckets.length > 0 ? `${measure.label} Total` : measure.label,
2253
+ period: two ? two.current : null,
2254
+ ...two ? { part: "current" } : {}
2255
+ });
2256
+ if (!two || !earlier) return;
2257
+ const cur = quoteIdent(wholeName);
2258
+ const prev = quoteIdent(`prev__${measure.key}`);
2259
+ put(
2260
+ select,
2261
+ `prev__${measure.key}`,
2262
+ figure(measure.key, earlier),
2263
+ seen,
2264
+ { ...about, label: `${measure.label} ${two.previous.label}`, period: two.previous, part: "previous" }
2265
+ );
2266
+ put(
2267
+ derived,
2268
+ `var__${measure.key}`,
2269
+ `COALESCE(${cur}, 0) - COALESCE(${prev}, 0)`,
2270
+ seen,
2271
+ { ...about, label: `${measure.label} Variance`, period: null, part: "variance" }
2272
+ );
2273
+ put(
2274
+ derived,
2275
+ `varp__${measure.key}`,
2276
+ `(COALESCE(${cur}, 0) - ${prev}) / NULLIF(abs(${prev}), 0)`,
2277
+ seen,
2278
+ { measure: measure.key, format: "percent", label: `${measure.label} Variance %`, period: null, part: "variance_pct" }
2279
+ );
2280
+ };
2130
2281
  shown.forEach((measure) => addMeasure(measure, true));
2131
2282
  unseen.forEach((measure) => addMeasure(measure, false));
2132
2283
  select.push('"__total"');
@@ -2137,8 +2288,10 @@ function compileStreams(model, view, ctx) {
2137
2288
  if (!columns.some((c) => c.name === sortName && c.kind !== "meta")) fail("bad_sort", `"${String(sort.by)}" is not a column of this view`);
2138
2289
  const { limit, offset } = pageOf(view, ctx, (totalRow ? 1 : 0) + (averageRow ? 1 : 0) + (sumRow ? 1 : 0));
2139
2290
  const measured = columns.filter((c) => c.kind === "measure").map((c) => c.name);
2291
+ const figures = shown.flatMap((m) => two ? [`m__${m.key}`, `prev__${m.key}`] : [`m__${m.key}`]);
2292
+ const source = derived.length > 0 ? "v" : "g";
2140
2293
  const streamKeys = [lead.stream.key, ...model.streams.map((s) => s.key).filter((key) => key !== lead.stream.key && needed.has(key))];
2141
- const stages = streamKeys.flatMap((key, i) => {
2294
+ const stages = streamKeys.map((key, i) => {
2142
2295
  const scope = i === 0 ? lead : scopeOf(model, { ...view, stream: key }, ctx);
2143
2296
  const { stream, codeExpr } = scope;
2144
2297
  const mine = needed.get(key) ?? [];
@@ -2148,33 +2301,29 @@ function compileStreams(model, view, ctx) {
2148
2301
  const expr = `any_value(${scope.propertyOf(groupDim.key, property)})`;
2149
2302
  part.push(`${totalRow ? `CASE WHEN ${grouping} = 0 THEN ${expr} END` : expr} AS ${quoteIdent(`prop__${property}`)}`);
2150
2303
  });
2151
- mine.forEach((measure) => {
2304
+ mine.forEach(({ measure, part: over }) => {
2152
2305
  const call = aggregateOf(measure, "COUNT(*)");
2153
- part.push(`${measure.snapshot ? `${call} FILTER (WHERE ${FACT}."__lastw")` : call} AS ${quoteIdent(`a__${measure.key}`)}`);
2306
+ const sum = measure.snapshot ? `${call} FILTER (WHERE ${over.last})` : over.filter === null ? call : measure.agg === "count" && measure.rolled ? `COALESCE(${call} FILTER (WHERE ${over.filter}), 0)` : `${call} FILTER (WHERE ${over.filter})`;
2307
+ part.push(`${sum} AS ${quoteIdent(`${over.prefix}__${measure.key}`)}`);
2154
2308
  });
2155
2309
  part.push(`${totalRow ? `CAST(${grouping} AS INTEGER)` : "0"} AS "__total"`);
2156
- return [
2157
- `${i === 0 ? "WITH" : "),"} s${i + 1} AS (`,
2158
- `SELECT ${part.join(", ")}`,
2159
- // A snapshot measure reads its own stream's latest day in the period.
2160
- `FROM ${factOver(stream, range, mine.some((measure) => measure.snapshot))}`,
2161
- ...scope.joins.values(),
2162
- ...scope.where.length > 0 ? [`WHERE ${scope.where.join(" AND ")}`] : [],
2163
- totalRow ? `GROUP BY GROUPING SETS ((${codeExpr}), ())` : `GROUP BY ${codeExpr}`
2164
- ];
2310
+ return {
2311
+ select: part,
2312
+ // A snapshot measure reads its own stream's latest day in each set of dates.
2313
+ from: factAcross(stream, range, buckets, two ? two.comparison : null, mine.some(({ measure }) => measure.snapshot)),
2314
+ joins: [...scope.joins.values()],
2315
+ where: scope.where,
2316
+ groupBy: totalRow ? `GROUP BY GROUPING SETS ((${codeExpr}), ())` : `GROUP BY ${codeExpr}`
2317
+ };
2165
2318
  });
2166
2319
  const sql = [
2167
- ...stages,
2168
- "), g AS (",
2169
- `SELECT ${select.join(", ")}`,
2170
- // By name: each stage has its own sum columns, and a member one stream lacks gets blanks there.
2171
- `FROM (${streamKeys.map((_, i) => `SELECT * FROM s${i + 1}`).join(" UNION ALL BY NAME ")}) AS u`,
2172
- 'GROUP BY "code", "__total"',
2320
+ ...foldStreams(stages, select),
2321
+ ...source === "v" ? ["), v AS (", `SELECT g.*, ${derived.join(", ")}`, "FROM g"] : [],
2173
2322
  ...rankAndPage(
2174
- "g",
2323
+ source,
2175
2324
  sortName,
2176
2325
  sort,
2177
- keepRows(lead.having, options, shown.map((m) => `m__${m.key}`)),
2326
+ keepRows(lead.having, options, figures),
2178
2327
  left,
2179
2328
  offset,
2180
2329
  limit,
@@ -2182,7 +2331,11 @@ function compileStreams(model, view, ctx) {
2182
2331
  )
2183
2332
  ].join("\n");
2184
2333
  checkLength(sql, ctx);
2185
- return { ok: true, sql, columns, window: range, buckets: [], months: monthsRange(range), streams: streamKeys };
2334
+ const read = two ? {
2335
+ from: two.comparison.from < range.from ? two.comparison.from : range.from,
2336
+ to: two.comparison.to > range.to ? two.comparison.to : range.to
2337
+ } : range;
2338
+ return { ok: true, sql, columns, window: range, ...two ? { comparison: two.comparison } : {}, buckets, months: monthsRange(read), streams: streamKeys };
2186
2339
  }
2187
2340
  function compileMatrix(model, view, ctx, byPeriod = false) {
2188
2341
  const options = view.options ?? {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sprigr/apps-reporting-core",
3
- "version": "0.0.1",
3
+ "version": "0.0.3",
4
4
  "description": "Pure reporting core: a model of dimensions and measures, a formula parser, a period engine, and a compiler from a saved view to one DuckDB statement.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",