@sprigr/apps-reporting-core 0.0.2 → 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 +2 -2
  2. package/dist/index.js +87 -27
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -77,9 +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, period variance and custom views still refuse a measure of another stream with `measure_not_on_stream`.
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.
81
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.
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.
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.
83
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.
84
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.
85
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.
package/dist/index.js CHANGED
@@ -1903,13 +1903,30 @@ function compileCustom(model, view, ctx) {
1903
1903
  };
1904
1904
  const uses = /* @__PURE__ */ new Set();
1905
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
+ };
1906
1921
  const points = [];
1907
1922
  const pointOf = (point, what) => {
1908
1923
  if (typeof point !== "object" || point === null) fail("bad_custom_column", `${what} has no data point`);
1909
1924
  const measure = measureByKey.get(point.measure) ?? fail("unknown_measure", `no measure "${String(point.measure)}"`);
1910
1925
  const { window, number } = windowOf(point.period);
1911
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`);
1912
- 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)}`;
1913
1930
  const bucket = {
1914
1931
  key: `w${number}`,
1915
1932
  label: `${window.from} to ${addDays(window.to, -1)}`,
@@ -1918,9 +1935,10 @@ function compileCustom(model, view, ctx) {
1918
1935
  days: daysBetween(window.from, window.to)
1919
1936
  };
1920
1937
  const slice = { bucket, filter: `${FACT}.${quoteIdent(`__w${number}`)}${rule}`, last: `${FACT}.${quoteIdent(`__l${number}`)}${rule}` };
1921
- const sql2 = `CAST(${measureOver(reads, measure.key, slice)} AS DOUBLE)`;
1922
- const at = points.indexOf(sql2);
1923
- 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 };
1924
1942
  };
1925
1943
  const columns = [...nest?.columns ?? [], { name: "code", kind: "code", label: groupDim.label }];
1926
1944
  const select = [...nest?.select ?? [], `${codeExpr} AS "code"`];
@@ -1981,7 +1999,9 @@ function compileCustom(model, view, ctx) {
1981
1999
  const measured = columns.filter((c) => c.kind === "measure").map((c) => c.name);
1982
2000
  if (measured.length === 0) fail("bad_custom_column", "every column of the view is hidden");
1983
2001
  if (points.length === 0) fail("bad_custom_column", "no column of the view reads a data point");
1984
- 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) => {
1985
2005
  select.push(`${sql2} AS ${quoteIdent(`p${i + 1}`)}`);
1986
2006
  left.push(`p${i + 1}`);
1987
2007
  });
@@ -2003,13 +2023,42 @@ function compileCustom(model, view, ctx) {
2003
2023
  const flags = `, ${windows.map((w, i) => `(${inWindow(w)}) AS ${quoteIdent(`__w${i + 1}`)}`).join(", ")}`;
2004
2024
  const anyWindow = windows.map((w) => `(${inWindow(w)})`).join(" OR ");
2005
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
+ ];
2006
2053
  const sql = [
2007
- "WITH g AS (",
2008
- `SELECT ${select.join(", ")}`,
2009
- `FROM ${fact}`,
2010
- ...joins.values(),
2011
- ...where.length > 0 ? [`WHERE ${where.join(" AND ")}`] : [],
2012
- 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
+ ],
2013
2062
  "), v AS (",
2014
2063
  `SELECT g.*, ${derived.join(", ")}`,
2015
2064
  "FROM g",
@@ -2025,7 +2074,7 @@ function compileCustom(model, view, ctx) {
2025
2074
  from: windows.reduce((min, w) => w.from < min ? w.from : min, windows[0]?.from ?? own.from),
2026
2075
  to: windows.reduce((max, w) => w.to > max ? w.to : max, windows[0]?.to ?? own.to)
2027
2076
  };
2028
- 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 } : {} };
2029
2078
  }
2030
2079
  function compileTransactions(model, view, ctx) {
2031
2080
  const options = view.options ?? {};
@@ -2108,6 +2157,23 @@ function compileTransactions(model, view, ctx) {
2108
2157
  checkLength(sql, ctx);
2109
2158
  return { ok: true, sql, columns, window: period.window, buckets: [], months: monthsRange(period.window) };
2110
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
+ }
2111
2177
  function compileStreams(model, view, ctx) {
2112
2178
  const options = view.options ?? {};
2113
2179
  const what = view.mode === "stream" ? "stream mode" : "a view of more than one stream";
@@ -2225,7 +2291,7 @@ function compileStreams(model, view, ctx) {
2225
2291
  const figures = shown.flatMap((m) => two ? [`m__${m.key}`, `prev__${m.key}`] : [`m__${m.key}`]);
2226
2292
  const source = derived.length > 0 ? "v" : "g";
2227
2293
  const streamKeys = [lead.stream.key, ...model.streams.map((s) => s.key).filter((key) => key !== lead.stream.key && needed.has(key))];
2228
- const stages = streamKeys.flatMap((key, i) => {
2294
+ const stages = streamKeys.map((key, i) => {
2229
2295
  const scope = i === 0 ? lead : scopeOf(model, { ...view, stream: key }, ctx);
2230
2296
  const { stream, codeExpr } = scope;
2231
2297
  const mine = needed.get(key) ?? [];
@@ -2241,23 +2307,17 @@ function compileStreams(model, view, ctx) {
2241
2307
  part.push(`${sum} AS ${quoteIdent(`${over.prefix}__${measure.key}`)}`);
2242
2308
  });
2243
2309
  part.push(`${totalRow ? `CAST(${grouping} AS INTEGER)` : "0"} AS "__total"`);
2244
- return [
2245
- `${i === 0 ? "WITH" : "),"} s${i + 1} AS (`,
2246
- `SELECT ${part.join(", ")}`,
2310
+ return {
2311
+ select: part,
2247
2312
  // A snapshot measure reads its own stream's latest day in each set of dates.
2248
- `FROM ${factAcross(stream, range, buckets, two ? two.comparison : null, mine.some(({ measure }) => measure.snapshot))}`,
2249
- ...scope.joins.values(),
2250
- ...scope.where.length > 0 ? [`WHERE ${scope.where.join(" AND ")}`] : [],
2251
- totalRow ? `GROUP BY GROUPING SETS ((${codeExpr}), ())` : `GROUP BY ${codeExpr}`
2252
- ];
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
+ };
2253
2318
  });
2254
2319
  const sql = [
2255
- ...stages,
2256
- "), g AS (",
2257
- `SELECT ${select.join(", ")}`,
2258
- // By name: each stage has its own sum columns, and a member one stream lacks gets blanks there.
2259
- `FROM (${streamKeys.map((_, i) => `SELECT * FROM s${i + 1}`).join(" UNION ALL BY NAME ")}) AS u`,
2260
- 'GROUP BY "code", "__total"',
2320
+ ...foldStreams(stages, select),
2261
2321
  ...source === "v" ? ["), v AS (", `SELECT g.*, ${derived.join(", ")}`, "FROM g"] : [],
2262
2322
  ...rankAndPage(
2263
2323
  source,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sprigr/apps-reporting-core",
3
- "version": "0.0.2",
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",