@sprigr/apps-reporting-core 0.0.9 → 0.0.10

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.
package/README.md CHANGED
@@ -78,7 +78,7 @@ Modes `total`, `period`, `variance`, `period_variance`, `transaction`, `stream`,
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
80
  - **A total view with a measure of another stream** compiles exactly as stream mode does, so a view saved as a total of stock beside sales needs no change of mode.
81
- - **A period, variance or period 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, a variance its current, earlier, variance and variance percentage columns, and a period variance those four for every period beside the same period of the comparison window, 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. A custom view reads one through its points, below.
81
+ - **A period, variance or period 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, a variance its current, earlier, variance and variance percentage columns, and a period variance those four for every period beside the same period of the comparison window, 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. A period view takes the long shape as a view of one stream does: each stream groups by member and period in its own stage, the stages are folded by cell, and a formula, `DAYS()`, a snapshot measure and a sort on one period read the folded sums. A variance or period variance view is always one column per period, and is refused when too wide for the route. A custom view reads one through its points, below.
82
82
  - **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. A matrix may read a measure of another stream, such as ordered beside sales: each stream groups the same four ways in its own stage, under the same drill path, filters and keyword, and the stages are folded by cell, so a formula that mixes streams is worked out at every level from the folded sums. Every stream read must carry both dimensions, and `streams` in the result lists them.
83
83
  - **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 that mixes streams, such as a fill rate of sales over ordered, is read as one point per measure it names, each on its own stream under the point's dates and rule, and the formula is worked out from those points. With nested rows, every level is grouped in each stream's stage, so each stream must carry every level.
84
84
  - **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.
package/dist/index.js CHANGED
@@ -1202,8 +1202,23 @@ function compileMode(model, view, ctx) {
1202
1202
  try {
1203
1203
  return direct ? compileGrouped(model, view, ctx) : compileOneStream(model, view, ctx);
1204
1204
  } catch (err) {
1205
- if (!(err instanceof ReportingError) || err.reason !== "measure_not_on_stream" || !direct && ctx.periodShape === "long") throw err;
1206
- return compileStreams(model, view, ctx);
1205
+ if (!(err instanceof ReportingError) || err.reason !== "measure_not_on_stream") throw err;
1206
+ if (direct || view.mode !== "period" || ctx.periodShape === "wide") {
1207
+ if (!direct && ctx.periodShape === "long") throw err;
1208
+ return compileStreams(model, view, ctx);
1209
+ }
1210
+ if (ctx.periodShape === "long") return compileMatrix(model, view, ctx, true, true);
1211
+ try {
1212
+ return compileStreams(model, view, ctx);
1213
+ } catch (tooLong) {
1214
+ if (!(tooLong instanceof ReportingError) || tooLong.reason !== "sql_too_long") throw tooLong;
1215
+ try {
1216
+ return compileMatrix(model, view, ctx, true, true);
1217
+ } catch (longErr) {
1218
+ if (longErr instanceof ReportingError) throw tooLong;
1219
+ throw longErr;
1220
+ }
1221
+ }
1207
1222
  }
1208
1223
  }
1209
1224
  function compileOneStream(model, view, ctx) {
@@ -2249,7 +2264,7 @@ function foldedMeasures(measureByKey, periodCount) {
2249
2264
  }
2250
2265
  return emitFormulaSql(node, {
2251
2266
  measure: (ref) => exprOf(ref, part, depth + 1),
2252
- days: part.days,
2267
+ ...part.daysSql !== void 0 ? { daysSql: part.daysSql } : { days: part.days },
2253
2268
  ...periodCount > 0 ? { periodCount } : {}
2254
2269
  });
2255
2270
  }
@@ -2262,7 +2277,7 @@ function foldedMeasures(measureByKey, periodCount) {
2262
2277
  }
2263
2278
  function streamSum(measure, over) {
2264
2279
  const call = aggregateOf(measure, "COUNT(*)");
2265
- 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})`;
2280
+ const sum = measure.snapshot && over.cellWhen !== void 0 ? `CASE WHEN ${over.cellWhen} THEN ${call} FILTER (WHERE ${FACT}."__last") ELSE ${call} FILTER (WHERE ${over.last}) END` : 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})`;
2266
2281
  return `${sum} AS ${quoteIdent(`${over.prefix}__${measure.key}`)}`;
2267
2282
  }
2268
2283
  function compileStreams(model, view, ctx) {
@@ -2480,8 +2495,16 @@ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
2480
2495
  const days = daysBetween(range.from, range.to);
2481
2496
  const uses = /* @__PURE__ */ new Set();
2482
2497
  const reads = { stream, measureByKey, parsed: /* @__PURE__ */ new Map(), countAll: "COUNT(*)", days, uses };
2483
- const folded = streams ? foldedMeasures(measureByKey, 0) : null;
2484
- const whole = { prefix: "a", days, filter: null, last: `${FACT}."__lastw"` };
2498
+ const folded = streams ? foldedMeasures(measureByKey, buckets.length) : null;
2499
+ const whole = byPeriod ? {
2500
+ prefix: "a",
2501
+ days,
2502
+ filter: null,
2503
+ last: `${FACT}."__lastw"`,
2504
+ cellWhen: `GROUPING(${FACT}."__b") = 0`,
2505
+ // A folded row is a cell when it has a period number, and a total over the whole window when it has none.
2506
+ daysSql: `CASE ${buckets.map((b, i) => `WHEN "across" = ${i + 1} THEN ${sqlNumber(b.days)}`).join(" ")} ELSE ${sqlNumber(days)} END`
2507
+ } : { prefix: "a", days, filter: null, last: `${FACT}."__lastw"` };
2485
2508
  const rowCode = scope.codeExpr;
2486
2509
  let colCode = `${FACT}."__b"`;
2487
2510
  let keep = buckets.length;
@@ -2552,7 +2575,8 @@ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
2552
2575
  if (bucket && shown.some((measure) => measure.key === byOne[2])) {
2553
2576
  const n = buckets.indexOf(bucket) + 1;
2554
2577
  const slice = { bucket, filter: `${FACT}."__b" = ${n}`, last: `${FACT}."__b" = ${n} AND ${FACT}."__last"` };
2555
- select.push(`CAST(${measureOver(reads, String(byOne[2]), slice)} AS DOUBLE) AS "__sort"`);
2578
+ const part = { prefix: `a${n}`, days: bucket.days, filter: slice.filter, last: slice.last };
2579
+ select.push(`CAST(${folded ? folded.exprOf(String(byOne[2]), part, 0) : measureOver(reads, String(byOne[2]), slice)} AS DOUBLE) AS "__sort"`);
2556
2580
  hidden.push("__sort");
2557
2581
  sortName = "__sort";
2558
2582
  } else if (!columns.some((c) => c.name === sortName && c.kind !== "across")) {
@@ -2585,7 +2609,7 @@ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
2585
2609
  const stages = streamKeys.map((key, i) => {
2586
2610
  const own = i === 0 ? scope : scopeOf(model, { ...view, stream: key }, ctx);
2587
2611
  const row = own.codeExpr;
2588
- const col = own.propertyOf(own.dimension(acrossColumn.dimension ?? "").key, "code");
2612
+ const col = byPeriod ? `${FACT}."__b"` : own.propertyOf(own.dimension(acrossColumn.dimension ?? "").key, "code");
2589
2613
  const mine = folded?.needed.get(key) ?? [];
2590
2614
  const part = [`${row} AS "code"`];
2591
2615
  properties.forEach((property) => {
@@ -2599,7 +2623,7 @@ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
2599
2623
  part.push(...flags(row, col));
2600
2624
  return {
2601
2625
  select: part,
2602
- from: factAcross(own.stream, range, [], null, mine.some(({ measure }) => measure.snapshot)),
2626
+ from: factAcross(own.stream, range, buckets, null, mine.some(({ measure }) => measure.snapshot)),
2603
2627
  joins: [...own.joins.values()],
2604
2628
  where: own.where,
2605
2629
  groupBy: sets(row, col)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sprigr/apps-reporting-core",
3
- "version": "0.0.9",
3
+ "version": "0.0.10",
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",