@sprigr/apps-reporting-core 0.0.6 → 0.0.7

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 +33 -21
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -88,11 +88,11 @@ Modes `total`, `period`, `variance`, `period_variance`, `transaction`, `stream`,
88
88
  - **The average row** (`options.average_row`, same modes as the sum row): the plain mean of each measure column over the member rows of the list, on every page, after any filter on a measure. Blanks are skipped.
89
89
  - **The average column** (`options.average_column`, period mode with one column per period): one more column a measure, the mean of that measure's period columns on the same row, so the total row holds the mean of the period totals. A period with no value is skipped, not counted as zero. `sort.by` takes `average.<measure>`. Other modes ignore the option.
90
90
  - **Hiding zero rows** (`options.hide_zero_rows`, every grouped mode): leaves out a member whose every shown measure is zero or blank over the whole period, and in a variance over the earlier period too. Sales that net to zero are hidden even when single periods are not zero. The total row still counts those members; the row count and the average row do not.
91
- - **Nested rows** (`levels`, modes `total`, `period` with one column per period, `variance`, `period_variance` and `custom`): up to five dimensions above `group_by`, the outermost first, such as branch, then department, then product as the rows. Each member of a level gets a row of its own, the subtotal of the rows beneath it, with formulas worked out from its own sums. Every level is grouped in the same pass as the rows, so it is still one statement. A row comes right after the row it sits under. Each level is ordered by its own figure in the column the view is sorted on, or by its code when the sort is on the code or a property. The result has `lv<n>` for each level's code and `lvn<n>` for its name where the dimension has one (`kind: 'level'`, with `level` and `dimension`), and `__level`: 1 on the outermost level's rows, one more on each level below, and 0 on the total row. `code` and the properties are blank on a level's row. `limit`, `offset` and `__rows` count every row, level rows included, so a page can start part way down a level. The total row works as in total mode. Not compiled with nested rows yet: the activity option, the others, average and sum rows, hiding zero rows, a filter on a measure, stream and matrix modes, and the long shape of a period view. Opening one row of a nested grid needs no nested statement: it is a plain view grouped by the next dimension with a path step on the row opened. The nested statement is for showing every level at once, as an export or an emailed report does.
91
+ - **Nested rows** (`levels`, modes `total`, `period` with one column per period, `variance`, `period_variance`, `stream` and `custom`): up to five dimensions above `group_by`, the outermost first, such as branch, then department, then product as the rows. Each member of a level gets a row of its own, the subtotal of the rows beneath it, with formulas worked out from its own sums. Every level is grouped in the same pass as the rows, so it is still one statement. A row comes right after the row it sits under. Each level is ordered by its own figure in the column the view is sorted on, or by its code when the sort is on the code or a property. The result has `lv<n>` for each level's code and `lvn<n>` for its name where the dimension has one (`kind: 'level'`, with `level` and `dimension`), and `__level`: 1 on the outermost level's rows, one more on each level below, and 0 on the total row. `code` and the properties are blank on a level's row. `limit`, `offset` and `__rows` count every row, level rows included, so a page can start part way down a level. The total row works as in total mode. Not compiled with nested rows yet: the activity option, the others, average and sum rows, hiding zero rows, a filter on a measure, matrix mode, a custom view of more than one stream, and the long shape of a period view. A view of more than one stream groups every level in each stream's own stage, so each stream must carry every level. Opening one row of a nested grid needs no nested statement: it is a plain view grouped by the next dimension with a path step on the row opened. The nested statement is for showing every level at once, as an export or an emailed report does.
92
92
  - **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.
93
93
  - **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.
94
94
 
95
- Refused with a named reason until built: an others row in stream mode; nested rows, the activity option and an others row in a total, 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.
95
+ Refused with a named reason until built: an others row in stream mode; the activity option and an others row in a total, 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.
96
96
 
97
97
  ## To check against the source system at migration
98
98
 
package/dist/index.js CHANGED
@@ -2187,7 +2187,7 @@ function compileTransactions(model, view, ctx) {
2187
2187
  checkLength(sql, ctx);
2188
2188
  return { ok: true, sql, columns, window: period.window, buckets: [], months: monthsRange(period.window) };
2189
2189
  }
2190
- function foldStreams(stages, fold) {
2190
+ function foldStreams(stages, fold, levels = []) {
2191
2191
  return [
2192
2192
  ...stages.flatMap((stage, i) => [
2193
2193
  `${i === 0 ? "WITH" : "),"} s${i + 1} AS (`,
@@ -2201,13 +2201,12 @@ function foldStreams(stages, fold) {
2201
2201
  `SELECT ${fold.join(", ")}`,
2202
2202
  // By name: each stage has its own sum columns, and a member one stream lacks gets blanks there.
2203
2203
  `FROM (${stages.map((_, i) => `SELECT * FROM s${i + 1}`).join(" UNION ALL BY NAME ")}) AS u`,
2204
- 'GROUP BY "code", "__total"'
2204
+ `GROUP BY ${[...levels.map(quoteIdent), '"code"', '"__total"', ...levels.length > 0 ? ['"__level"'] : []].join(", ")}`
2205
2205
  ];
2206
2206
  }
2207
2207
  function compileStreams(model, view, ctx) {
2208
2208
  const options = view.options ?? {};
2209
2209
  const what = view.mode === "stream" ? "stream mode" : "a view of more than one stream";
2210
- if (view.levels !== void 0) fail("option_unsupported", `nested rows are not compiled for ${what} yet`);
2211
2210
  if ((options.activity ?? "with") !== "with") fail("option_unsupported", `the activity option is not compiled for ${what} yet`);
2212
2211
  if (options.others_row) fail("option_unsupported", `an others row is not compiled for ${what} yet`);
2213
2212
  if (options.average_column && view.mode === "period") fail("option_unsupported", `an average column is not compiled for ${what} yet`);
@@ -2216,6 +2215,13 @@ function compileStreams(model, view, ctx) {
2216
2215
  const sumRow = options.sum_row === true;
2217
2216
  const lead = scopeOf(model, view, ctx);
2218
2217
  const { measureByKey, groupDim } = lead;
2218
+ const nest = nestOf(view, lead);
2219
+ if (nest) {
2220
+ if (averageRow || sumRow || options.hide_zero_rows) {
2221
+ fail("option_unsupported", "an average or sum row and hiding zero rows are not compiled with nested rows yet");
2222
+ }
2223
+ if (lead.having !== null) fail("measure_filter_unsupported", "a filter on a measure with nested rows is not compiled yet");
2224
+ }
2219
2225
  const shown = shownMeasures(view, measureByKey);
2220
2226
  const unseen = lead.filterMeasures.filter((key) => !view.measures.includes(key)).map((key) => measureByKey.get(key) ?? fail("unknown_measure", `no measure "${key}"`));
2221
2227
  const period = resolvePeriod(view.period, model.periods, ctx.today, { periodToDate: options.period_to_date === true });
@@ -2261,8 +2267,11 @@ function compileStreams(model, view, ctx) {
2261
2267
  return `any_value(${quoteIdent(`${part.prefix}__${measure.key}`)})`;
2262
2268
  };
2263
2269
  const properties = shownProperties(view);
2264
- const columns = [{ name: "code", kind: "code", label: groupDim.label }];
2265
- const select = ['"code"'];
2270
+ const columns = [...nest?.columns ?? [], { name: "code", kind: "code", label: groupDim.label }];
2271
+ const select = [
2272
+ ...(nest?.columns ?? []).map((c) => c.property === "name" ? `any_value(${quoteIdent(c.name)}) AS ${quoteIdent(c.name)}` : quoteIdent(c.name)),
2273
+ '"code"'
2274
+ ];
2266
2275
  properties.forEach((property) => {
2267
2276
  const name = `prop__${property}`;
2268
2277
  select.push(`any_value(${quoteIdent(name)}) AS ${quoteIdent(name)}`);
@@ -2351,7 +2360,12 @@ function compileStreams(model, view, ctx) {
2351
2360
  shown.forEach((measure) => addMeasure(measure, true));
2352
2361
  unseen.forEach((measure) => addMeasure(measure, false));
2353
2362
  select.push('"__total"');
2354
- columns.push({ name: "__total", kind: "meta", label: "Total row" }, { name: "__rows", kind: "meta", label: "Row count" });
2363
+ columns.push({ name: "__total", kind: "meta", label: "Total row" });
2364
+ if (nest) {
2365
+ select.push('"__level"');
2366
+ columns.push({ name: "__level", kind: "meta", label: "Level" });
2367
+ }
2368
+ columns.push({ name: "__rows", kind: "meta", label: "Row count" });
2355
2369
  const sort = view.sort ?? { by: `total.${shown[0]?.key ?? ""}`, dir: "desc" };
2356
2370
  if (sort.dir !== "asc" && sort.dir !== "desc") fail("bad_sort", "sort.dir must be asc or desc");
2357
2371
  const sortName = sortNameOf(sort.by);
@@ -2366,39 +2380,37 @@ function compileStreams(model, view, ctx) {
2366
2380
  const { stream, codeExpr } = scope;
2367
2381
  const mine = needed.get(key) ?? [];
2368
2382
  const grouping = `GROUPING(${codeExpr})`;
2369
- const part = [`${codeExpr} AS "code"`];
2383
+ const levels = nest ? nestOf(view, scope) : null;
2384
+ const part = [...levels?.select ?? [], `${codeExpr} AS "code"`];
2370
2385
  properties.forEach((property) => {
2371
2386
  const expr = `any_value(${scope.propertyOf(groupDim.key, property)})`;
2372
- part.push(`${totalRow ? `CASE WHEN ${grouping} = 0 THEN ${expr} END` : expr} AS ${quoteIdent(`prop__${property}`)}`);
2387
+ part.push(`${totalRow || levels ? `CASE WHEN ${grouping} = 0 THEN ${expr} END` : expr} AS ${quoteIdent(`prop__${property}`)}`);
2373
2388
  });
2374
2389
  mine.forEach(({ measure, part: over }) => {
2375
2390
  const call = aggregateOf(measure, "COUNT(*)");
2376
2391
  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})`;
2377
2392
  part.push(`${sum} AS ${quoteIdent(`${over.prefix}__${measure.key}`)}`);
2378
2393
  });
2379
- part.push(`${totalRow ? `CAST(${grouping} AS INTEGER)` : "0"} AS "__total"`);
2394
+ part.push(`${totalRow ? `CAST(${levels ? levels.total : grouping} AS INTEGER)` : "0"} AS "__total"`);
2395
+ if (levels) part.push(levels.level);
2380
2396
  return {
2381
2397
  select: part,
2382
2398
  // A snapshot measure reads its own stream's latest day in each set of dates.
2383
2399
  from: factAcross(stream, range, buckets, two ? two.comparison : null, mine.some(({ measure }) => measure.snapshot), earlierBuckets),
2384
2400
  joins: [...scope.joins.values()],
2385
2401
  where: scope.where,
2386
- groupBy: totalRow ? `GROUP BY GROUPING SETS ((${codeExpr}), ())` : `GROUP BY ${codeExpr}`
2402
+ groupBy: levels ? levels.groupBy(totalRow) : totalRow ? `GROUP BY GROUPING SETS ((${codeExpr}), ())` : `GROUP BY ${codeExpr}`
2387
2403
  };
2388
2404
  });
2389
2405
  const sql = [
2390
- ...foldStreams(stages, select),
2406
+ ...foldStreams(stages, select, nest ? Array.from({ length: nest.count }, (_, i) => `lv${i + 1}`) : []),
2391
2407
  ...source === "v" ? ["), v AS (", `SELECT g.*, ${derived.join(", ")}`, "FROM g"] : [],
2392
- ...rankAndPage(
2393
- source,
2394
- sortName,
2395
- sort,
2396
- keepRows(lead.having, options, figures),
2397
- left,
2398
- offset,
2399
- limit,
2400
- { others: false, average: averageRow ? measured : [], sum: sumRow ? measured : [] }
2401
- )
2408
+ ...rankAndPage(source, sortName, sort, keepRows(lead.having, options, figures), left, offset, limit, {
2409
+ others: false,
2410
+ average: averageRow ? measured : [],
2411
+ sum: sumRow ? measured : [],
2412
+ ...nest ? { nest: { levels: nest.count, byMeasure: columns.find((c) => c.name === sortName)?.kind === "measure" } } : {}
2413
+ })
2402
2414
  ].join("\n");
2403
2415
  checkLength(sql, ctx);
2404
2416
  const read = two ? {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sprigr/apps-reporting-core",
3
- "version": "0.0.6",
3
+ "version": "0.0.7",
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",