@sprigr/apps-reporting-core 0.0.5 → 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 +3 -3
  2. package/dist/index.js +99 -41
  3. package/package.json +1 -1
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 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. 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
+ - **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.
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.
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 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.
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.
@@ -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
@@ -1191,12 +1191,11 @@ function compileMode(model, view, ctx) {
1191
1191
  if (view.mode === "stream") return compileStreams(model, view, ctx);
1192
1192
  if (view.mode === "matrix") return compileMatrix(model, view, ctx);
1193
1193
  if (view.mode === "custom") return compileCustom(model, view, ctx);
1194
- if (view.mode === "period_variance") return compileGrouped(model, view, ctx);
1195
- const total = view.mode === "total";
1194
+ const direct = view.mode === "total" || view.mode === "period_variance";
1196
1195
  try {
1197
- return total ? compileGrouped(model, view, ctx) : compileOneStream(model, view, ctx);
1196
+ return direct ? compileGrouped(model, view, ctx) : compileOneStream(model, view, ctx);
1198
1197
  } catch (err) {
1199
- if (!(err instanceof ReportingError) || err.reason !== "measure_not_on_stream" || !total && ctx.periodShape === "long") throw err;
1198
+ if (!(err instanceof ReportingError) || err.reason !== "measure_not_on_stream" || !direct && ctx.periodShape === "long") throw err;
1200
1199
  return compileStreams(model, view, ctx);
1201
1200
  }
1202
1201
  }
@@ -1596,19 +1595,26 @@ function comparedWith(model, view, ctx, window) {
1596
1595
  previous: whole("previous", compare === "previous_year" ? "Previous year" : compare === "previous_period" ? "Previous period" : "Comparison", comparison)
1597
1596
  };
1598
1597
  }
1599
- function factAcross(stream, range, buckets, comparison, latest) {
1598
+ function factAcross(stream, range, buckets, comparison, latest, earlier = []) {
1600
1599
  if (buckets.length === 0 && !comparison) return factOver(stream, range, latest);
1601
1600
  const table = quoteIdent(stream.table);
1602
1601
  const date = quoteIdent(stream.date);
1603
1602
  const inWindow = (w) => `${date} >= ${sqlDate(w.from)} AND ${date} < ${sqlDate(w.to)}`;
1604
1603
  if (!comparison) {
1605
- const numbered = perBucket(date, buckets, (_, i) => i + 1);
1606
- const columns2 = `, ${numbered} AS "__b"`;
1607
- return latest ? withLatestDays(table, date, numbered, columns2, inWindow(range)) : `(SELECT *${columns2} FROM ${table} WHERE ${inWindow(range)}) AS ${FACT}`;
1604
+ const numbered2 = perBucket(date, buckets, (_, i) => i + 1);
1605
+ const columns2 = `, ${numbered2} AS "__b"`;
1606
+ return latest ? withLatestDays(table, date, numbered2, columns2, inWindow(range)) : `(SELECT *${columns2} FROM ${table} WHERE ${inWindow(range)}) AS ${FACT}`;
1608
1607
  }
1609
- const columns = `, (${inWindow(range)}) AS "__cur", (${inWindow(comparison)}) AS "__prev"`;
1608
+ const byPeriod = earlier.length > 0;
1609
+ const numbered = (w, parts2) => `CASE WHEN ${inWindow(w)} THEN ${perBucket(date, parts2, (_, i) => i + 1)} END`;
1610
+ const periods = byPeriod ? `, ${numbered(range, buckets)} AS "__b", ${numbered(comparison, earlier)} AS "__pb"` : "";
1611
+ const columns = `${periods}, (${inWindow(range)}) AS "__cur", (${inWindow(comparison)}) AS "__prev"`;
1610
1612
  const where = `(${inWindow(range)}) OR (${inWindow(comparison)})`;
1611
- 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}`;
1613
+ const periodOf = (parts2) => perBucket(date, parts2, (_, i) => i + 1);
1614
+ return latest ? withLatestDayOfEach(table, date, columns, where, [
1615
+ { where: inWindow(range), flag: "__lastc", ...byPeriod ? { periods: { by: periodOf(buckets), flag: "__last" } } : {} },
1616
+ { where: inWindow(comparison), flag: "__lastp", ...byPeriod ? { periods: { by: periodOf(earlier), flag: "__plast" } } : {} }
1617
+ ]) : `(SELECT *${columns} FROM ${table} WHERE ${where}) AS ${FACT}`;
1612
1618
  }
1613
1619
  function perBucket(date, buckets, value) {
1614
1620
  return `CASE ${buckets.map((b, i) => `WHEN ${date} < ${sqlDate(b.to)} THEN ${value(b, i)}`).join(" ")} END`;
@@ -2181,7 +2187,7 @@ function compileTransactions(model, view, ctx) {
2181
2187
  checkLength(sql, ctx);
2182
2188
  return { ok: true, sql, columns, window: period.window, buckets: [], months: monthsRange(period.window) };
2183
2189
  }
2184
- function foldStreams(stages, fold) {
2190
+ function foldStreams(stages, fold, levels = []) {
2185
2191
  return [
2186
2192
  ...stages.flatMap((stage, i) => [
2187
2193
  `${i === 0 ? "WITH" : "),"} s${i + 1} AS (`,
@@ -2195,13 +2201,12 @@ function foldStreams(stages, fold) {
2195
2201
  `SELECT ${fold.join(", ")}`,
2196
2202
  // By name: each stage has its own sum columns, and a member one stream lacks gets blanks there.
2197
2203
  `FROM (${stages.map((_, i) => `SELECT * FROM s${i + 1}`).join(" UNION ALL BY NAME ")}) AS u`,
2198
- 'GROUP BY "code", "__total"'
2204
+ `GROUP BY ${[...levels.map(quoteIdent), '"code"', '"__total"', ...levels.length > 0 ? ['"__level"'] : []].join(", ")}`
2199
2205
  ];
2200
2206
  }
2201
2207
  function compileStreams(model, view, ctx) {
2202
2208
  const options = view.options ?? {};
2203
2209
  const what = view.mode === "stream" ? "stream mode" : "a view of more than one stream";
2204
- if (view.levels !== void 0) fail("option_unsupported", `nested rows are not compiled for ${what} yet`);
2205
2210
  if ((options.activity ?? "with") !== "with") fail("option_unsupported", `the activity option is not compiled for ${what} yet`);
2206
2211
  if (options.others_row) fail("option_unsupported", `an others row is not compiled for ${what} yet`);
2207
2212
  if (options.average_column && view.mode === "period") fail("option_unsupported", `an average column is not compiled for ${what} yet`);
@@ -2210,19 +2215,35 @@ function compileStreams(model, view, ctx) {
2210
2215
  const sumRow = options.sum_row === true;
2211
2216
  const lead = scopeOf(model, view, ctx);
2212
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
+ }
2213
2225
  const shown = shownMeasures(view, measureByKey);
2214
2226
  const unseen = lead.filterMeasures.filter((key) => !view.measures.includes(key)).map((key) => measureByKey.get(key) ?? fail("unknown_measure", `no measure "${key}"`));
2215
2227
  const period = resolvePeriod(view.period, model.periods, ctx.today, { periodToDate: options.period_to_date === true });
2216
2228
  const range = period.window;
2217
- const buckets = view.mode === "period" ? period.buckets : [];
2218
- const two = view.mode === "variance" ? comparedWith(model, view, ctx, range) : null;
2229
+ const periodVariance = view.mode === "period_variance";
2230
+ const buckets = view.mode === "period" || periodVariance ? period.buckets : [];
2231
+ const two = view.mode === "variance" || periodVariance ? comparedWith(model, view, ctx, range) : null;
2232
+ const earlierBuckets = periodVariance && two ? splitWindow(two.comparison, period.grain, model.periods) : [];
2233
+ if (periodVariance && earlierBuckets.length !== buckets.length) {
2234
+ fail("option_unsupported", `the period splits into ${buckets.length} columns and the comparison into ${earlierBuckets.length}, so they cannot be set side by side`);
2235
+ }
2219
2236
  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"` };
2220
2237
  const earlier = two ? { prefix: "ap", days: two.previous.days, filter: `${FACT}."__prev"`, last: `${FACT}."__lastp"` } : null;
2221
- const perPeriod = buckets.map((bucket, i) => ({
2222
- bucket,
2223
- part: { prefix: `a${i + 1}`, days: bucket.days, filter: `${FACT}."__b" = ${i + 1}`, last: `${FACT}."__b" = ${i + 1} AND ${FACT}."__last"` },
2224
- index: i + 1
2225
- }));
2238
+ const perPeriod = buckets.map((bucket, i) => {
2239
+ const back = earlierBuckets[i];
2240
+ return {
2241
+ bucket,
2242
+ part: { prefix: `a${i + 1}`, days: bucket.days, filter: `${FACT}."__b" = ${i + 1}`, last: `${FACT}."__b" = ${i + 1} AND ${FACT}."__last"` },
2243
+ index: i + 1,
2244
+ before: back ? { bucket: back, part: { prefix: `p${i + 1}`, days: back.days, filter: `${FACT}."__pb" = ${i + 1}`, last: `${FACT}."__pb" = ${i + 1} AND ${FACT}."__plast"` } } : null
2245
+ };
2246
+ });
2226
2247
  const needed = /* @__PURE__ */ new Map();
2227
2248
  const parsed = /* @__PURE__ */ new Map();
2228
2249
  const exprOf = (key, part, depth) => {
@@ -2246,8 +2267,11 @@ function compileStreams(model, view, ctx) {
2246
2267
  return `any_value(${quoteIdent(`${part.prefix}__${measure.key}`)})`;
2247
2268
  };
2248
2269
  const properties = shownProperties(view);
2249
- const columns = [{ name: "code", kind: "code", label: groupDim.label }];
2250
- 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
+ ];
2251
2275
  properties.forEach((property) => {
2252
2276
  const name = `prop__${property}`;
2253
2277
  select.push(`any_value(${quoteIdent(name)}) AS ${quoteIdent(name)}`);
@@ -2266,8 +2290,39 @@ function compileStreams(model, view, ctx) {
2266
2290
  const addMeasure = (measure, seen) => {
2267
2291
  const about = { measure: measure.key, format: measure.format };
2268
2292
  if (seen) {
2269
- display.forEach(({ bucket, part, index }) => {
2270
- put(select, `b${index}__${measure.key}`, figure(measure.key, part), true, { ...about, label: `${measure.label} ${bucket.label}`, period: bucket });
2293
+ display.forEach(({ bucket, part, index, before }) => {
2294
+ const name = `b${index}__${measure.key}`;
2295
+ put(
2296
+ select,
2297
+ name,
2298
+ figure(measure.key, part),
2299
+ true,
2300
+ { ...about, label: `${measure.label} ${bucket.label}`, period: bucket, ...before ? { part: "current", bucket: index } : {} }
2301
+ );
2302
+ if (!before) return;
2303
+ const earlierName = `pb${index}__${measure.key}`;
2304
+ const group = { ...about, bucket: index };
2305
+ put(
2306
+ select,
2307
+ earlierName,
2308
+ figure(measure.key, before.part),
2309
+ true,
2310
+ { ...group, label: `${measure.label} ${before.bucket.label}`, period: before.bucket, part: "previous" }
2311
+ );
2312
+ put(
2313
+ derived,
2314
+ `bv${index}__${measure.key}`,
2315
+ `COALESCE(${quoteIdent(name)}, 0) - COALESCE(${quoteIdent(earlierName)}, 0)`,
2316
+ true,
2317
+ { ...group, label: `${measure.label} ${bucket.label} Variance`, period: bucket, part: "variance" }
2318
+ );
2319
+ put(
2320
+ derived,
2321
+ `bvp${index}__${measure.key}`,
2322
+ `(COALESCE(${quoteIdent(name)}, 0) - ${quoteIdent(earlierName)}) / NULLIF(abs(${quoteIdent(earlierName)}), 0)`,
2323
+ true,
2324
+ { ...group, format: "percent", label: `${measure.label} ${bucket.label} Variance %`, period: bucket, part: "variance_pct" }
2325
+ );
2271
2326
  });
2272
2327
  }
2273
2328
  const wholeName = `m__${measure.key}`;
@@ -2305,7 +2360,12 @@ function compileStreams(model, view, ctx) {
2305
2360
  shown.forEach((measure) => addMeasure(measure, true));
2306
2361
  unseen.forEach((measure) => addMeasure(measure, false));
2307
2362
  select.push('"__total"');
2308
- 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" });
2309
2369
  const sort = view.sort ?? { by: `total.${shown[0]?.key ?? ""}`, dir: "desc" };
2310
2370
  if (sort.dir !== "asc" && sort.dir !== "desc") fail("bad_sort", "sort.dir must be asc or desc");
2311
2371
  const sortName = sortNameOf(sort.by);
@@ -2320,39 +2380,37 @@ function compileStreams(model, view, ctx) {
2320
2380
  const { stream, codeExpr } = scope;
2321
2381
  const mine = needed.get(key) ?? [];
2322
2382
  const grouping = `GROUPING(${codeExpr})`;
2323
- const part = [`${codeExpr} AS "code"`];
2383
+ const levels = nest ? nestOf(view, scope) : null;
2384
+ const part = [...levels?.select ?? [], `${codeExpr} AS "code"`];
2324
2385
  properties.forEach((property) => {
2325
2386
  const expr = `any_value(${scope.propertyOf(groupDim.key, property)})`;
2326
- 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}`)}`);
2327
2388
  });
2328
2389
  mine.forEach(({ measure, part: over }) => {
2329
2390
  const call = aggregateOf(measure, "COUNT(*)");
2330
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})`;
2331
2392
  part.push(`${sum} AS ${quoteIdent(`${over.prefix}__${measure.key}`)}`);
2332
2393
  });
2333
- 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);
2334
2396
  return {
2335
2397
  select: part,
2336
2398
  // A snapshot measure reads its own stream's latest day in each set of dates.
2337
- from: factAcross(stream, range, buckets, two ? two.comparison : null, mine.some(({ measure }) => measure.snapshot)),
2399
+ from: factAcross(stream, range, buckets, two ? two.comparison : null, mine.some(({ measure }) => measure.snapshot), earlierBuckets),
2338
2400
  joins: [...scope.joins.values()],
2339
2401
  where: scope.where,
2340
- 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}`
2341
2403
  };
2342
2404
  });
2343
2405
  const sql = [
2344
- ...foldStreams(stages, select),
2406
+ ...foldStreams(stages, select, nest ? Array.from({ length: nest.count }, (_, i) => `lv${i + 1}`) : []),
2345
2407
  ...source === "v" ? ["), v AS (", `SELECT g.*, ${derived.join(", ")}`, "FROM g"] : [],
2346
- ...rankAndPage(
2347
- source,
2348
- sortName,
2349
- sort,
2350
- keepRows(lead.having, options, figures),
2351
- left,
2352
- offset,
2353
- limit,
2354
- { others: false, average: averageRow ? measured : [], sum: sumRow ? measured : [] }
2355
- )
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
+ })
2356
2414
  ].join("\n");
2357
2415
  checkLength(sql, ctx);
2358
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.5",
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",