@sprigr/apps-reporting-core 0.0.4 → 0.0.6

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 +66 -19
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -77,7 +77,8 @@ 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
+ - **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
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.
82
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.
83
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.
@@ -91,7 +92,7 @@ Modes `total`, `period`, `variance`, `period_variance`, `transaction`, `stream`,
91
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.
92
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.
93
94
 
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.
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
96
 
96
97
  ## To check against the source system at migration
97
98
 
package/dist/index.js CHANGED
@@ -1191,11 +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" && view.mode !== "variance") return compileGrouped(model, view, ctx);
1194
+ const direct = view.mode === "total" || view.mode === "period_variance";
1195
1195
  try {
1196
- return compileOneStream(model, view, ctx);
1196
+ return direct ? compileGrouped(model, view, ctx) : compileOneStream(model, view, ctx);
1197
1197
  } catch (err) {
1198
- if (!(err instanceof ReportingError) || err.reason !== "measure_not_on_stream" || ctx.periodShape === "long") throw err;
1198
+ if (!(err instanceof ReportingError) || err.reason !== "measure_not_on_stream" || !direct && ctx.periodShape === "long") throw err;
1199
1199
  return compileStreams(model, view, ctx);
1200
1200
  }
1201
1201
  }
@@ -1595,19 +1595,26 @@ function comparedWith(model, view, ctx, window) {
1595
1595
  previous: whole("previous", compare === "previous_year" ? "Previous year" : compare === "previous_period" ? "Previous period" : "Comparison", comparison)
1596
1596
  };
1597
1597
  }
1598
- function factAcross(stream, range, buckets, comparison, latest) {
1598
+ function factAcross(stream, range, buckets, comparison, latest, earlier = []) {
1599
1599
  if (buckets.length === 0 && !comparison) return factOver(stream, range, latest);
1600
1600
  const table = quoteIdent(stream.table);
1601
1601
  const date = quoteIdent(stream.date);
1602
1602
  const inWindow = (w) => `${date} >= ${sqlDate(w.from)} AND ${date} < ${sqlDate(w.to)}`;
1603
1603
  if (!comparison) {
1604
- const numbered = perBucket(date, buckets, (_, i) => i + 1);
1605
- const columns2 = `, ${numbered} AS "__b"`;
1606
- 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}`;
1607
1607
  }
1608
- 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"`;
1609
1612
  const where = `(${inWindow(range)}) OR (${inWindow(comparison)})`;
1610
- 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}`;
1611
1618
  }
1612
1619
  function perBucket(date, buckets, value) {
1613
1620
  return `CASE ${buckets.map((b, i) => `WHEN ${date} < ${sqlDate(b.to)} THEN ${value(b, i)}`).join(" ")} END`;
@@ -2213,15 +2220,24 @@ function compileStreams(model, view, ctx) {
2213
2220
  const unseen = lead.filterMeasures.filter((key) => !view.measures.includes(key)).map((key) => measureByKey.get(key) ?? fail("unknown_measure", `no measure "${key}"`));
2214
2221
  const period = resolvePeriod(view.period, model.periods, ctx.today, { periodToDate: options.period_to_date === true });
2215
2222
  const range = period.window;
2216
- const buckets = view.mode === "period" ? period.buckets : [];
2217
- const two = view.mode === "variance" ? comparedWith(model, view, ctx, range) : null;
2223
+ const periodVariance = view.mode === "period_variance";
2224
+ const buckets = view.mode === "period" || periodVariance ? period.buckets : [];
2225
+ const two = view.mode === "variance" || periodVariance ? comparedWith(model, view, ctx, range) : null;
2226
+ const earlierBuckets = periodVariance && two ? splitWindow(two.comparison, period.grain, model.periods) : [];
2227
+ if (periodVariance && earlierBuckets.length !== buckets.length) {
2228
+ fail("option_unsupported", `the period splits into ${buckets.length} columns and the comparison into ${earlierBuckets.length}, so they cannot be set side by side`);
2229
+ }
2218
2230
  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"` };
2219
2231
  const earlier = two ? { prefix: "ap", days: two.previous.days, filter: `${FACT}."__prev"`, last: `${FACT}."__lastp"` } : null;
2220
- const perPeriod = buckets.map((bucket, i) => ({
2221
- bucket,
2222
- part: { prefix: `a${i + 1}`, days: bucket.days, filter: `${FACT}."__b" = ${i + 1}`, last: `${FACT}."__b" = ${i + 1} AND ${FACT}."__last"` },
2223
- index: i + 1
2224
- }));
2232
+ const perPeriod = buckets.map((bucket, i) => {
2233
+ const back = earlierBuckets[i];
2234
+ return {
2235
+ bucket,
2236
+ part: { prefix: `a${i + 1}`, days: bucket.days, filter: `${FACT}."__b" = ${i + 1}`, last: `${FACT}."__b" = ${i + 1} AND ${FACT}."__last"` },
2237
+ index: i + 1,
2238
+ 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
2239
+ };
2240
+ });
2225
2241
  const needed = /* @__PURE__ */ new Map();
2226
2242
  const parsed = /* @__PURE__ */ new Map();
2227
2243
  const exprOf = (key, part, depth) => {
@@ -2265,8 +2281,39 @@ function compileStreams(model, view, ctx) {
2265
2281
  const addMeasure = (measure, seen) => {
2266
2282
  const about = { measure: measure.key, format: measure.format };
2267
2283
  if (seen) {
2268
- display.forEach(({ bucket, part, index }) => {
2269
- put(select, `b${index}__${measure.key}`, figure(measure.key, part), true, { ...about, label: `${measure.label} ${bucket.label}`, period: bucket });
2284
+ display.forEach(({ bucket, part, index, before }) => {
2285
+ const name = `b${index}__${measure.key}`;
2286
+ put(
2287
+ select,
2288
+ name,
2289
+ figure(measure.key, part),
2290
+ true,
2291
+ { ...about, label: `${measure.label} ${bucket.label}`, period: bucket, ...before ? { part: "current", bucket: index } : {} }
2292
+ );
2293
+ if (!before) return;
2294
+ const earlierName = `pb${index}__${measure.key}`;
2295
+ const group = { ...about, bucket: index };
2296
+ put(
2297
+ select,
2298
+ earlierName,
2299
+ figure(measure.key, before.part),
2300
+ true,
2301
+ { ...group, label: `${measure.label} ${before.bucket.label}`, period: before.bucket, part: "previous" }
2302
+ );
2303
+ put(
2304
+ derived,
2305
+ `bv${index}__${measure.key}`,
2306
+ `COALESCE(${quoteIdent(name)}, 0) - COALESCE(${quoteIdent(earlierName)}, 0)`,
2307
+ true,
2308
+ { ...group, label: `${measure.label} ${bucket.label} Variance`, period: bucket, part: "variance" }
2309
+ );
2310
+ put(
2311
+ derived,
2312
+ `bvp${index}__${measure.key}`,
2313
+ `(COALESCE(${quoteIdent(name)}, 0) - ${quoteIdent(earlierName)}) / NULLIF(abs(${quoteIdent(earlierName)}), 0)`,
2314
+ true,
2315
+ { ...group, format: "percent", label: `${measure.label} ${bucket.label} Variance %`, period: bucket, part: "variance_pct" }
2316
+ );
2270
2317
  });
2271
2318
  }
2272
2319
  const wholeName = `m__${measure.key}`;
@@ -2333,7 +2380,7 @@ function compileStreams(model, view, ctx) {
2333
2380
  return {
2334
2381
  select: part,
2335
2382
  // A snapshot measure reads its own stream's latest day in each set of dates.
2336
- from: factAcross(stream, range, buckets, two ? two.comparison : null, mine.some(({ measure }) => measure.snapshot)),
2383
+ from: factAcross(stream, range, buckets, two ? two.comparison : null, mine.some(({ measure }) => measure.snapshot), earlierBuckets),
2337
2384
  joins: [...scope.joins.values()],
2338
2385
  where: scope.where,
2339
2386
  groupBy: totalRow ? `GROUP BY GROUPING SETS ((${codeExpr}), ())` : `GROUP BY ${codeExpr}`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sprigr/apps-reporting-core",
3
- "version": "0.0.4",
3
+ "version": "0.0.6",
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",