@sprigr/apps-reporting-core 0.0.1 → 0.0.2

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 -1
  2. package/dist/index.js +126 -33
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -77,6 +77,7 @@ 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
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.
81
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
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.
@@ -90,7 +91,7 @@ Modes `total`, `period`, `variance`, `period_variance`, `transaction`, `stream`,
90
91
  - **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.
91
92
  - **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.
92
93
 
93
- Refused with a named reason until built: an others row in stream mode; 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.
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.
94
95
 
95
96
  ## To check against the source system at migration
96
97
 
package/dist/index.js CHANGED
@@ -1168,6 +1168,15 @@ function compileMode(model, view, ctx) {
1168
1168
  if (view.mode === "stream") return compileStreams(model, view, ctx);
1169
1169
  if (view.mode === "matrix") return compileMatrix(model, view, ctx);
1170
1170
  if (view.mode === "custom") return compileCustom(model, view, ctx);
1171
+ if (view.mode !== "period" && view.mode !== "variance") return compileGrouped(model, view, ctx);
1172
+ try {
1173
+ return compileOneStream(model, view, ctx);
1174
+ } catch (err) {
1175
+ if (!(err instanceof ReportingError) || err.reason !== "measure_not_on_stream" || ctx.periodShape === "long") throw err;
1176
+ return compileStreams(model, view, ctx);
1177
+ }
1178
+ }
1179
+ function compileOneStream(model, view, ctx) {
1171
1180
  if (view.mode !== "period" || ctx.periodShape === "wide") return compileGrouped(model, view, ctx);
1172
1181
  if (ctx.periodShape === "long") return compileMatrix(model, view, ctx, true);
1173
1182
  try {
@@ -1546,6 +1555,37 @@ function withLatestDayOfEach(table, date, columns, where, windows) {
1546
1555
  });
1547
1556
  return `(SELECT *${columns}, ${flags.join(", ")} FROM ${table} WHERE ${where}) AS ${FACT}`;
1548
1557
  }
1558
+ function comparedWith(model, view, ctx, window) {
1559
+ const compare = view.compare ?? "previous_year";
1560
+ let comparison;
1561
+ if (typeof compare === "object" && compare !== null) {
1562
+ if (typeof compare.period !== "object" || compare.period === null) fail("option_unsupported", "a comparison given as an object needs a period");
1563
+ comparison = resolvePeriod(compare.period, model.periods, ctx.today, { periodToDate: view.options?.period_to_date === true }).window;
1564
+ } else {
1565
+ if (compare !== "previous_year" && compare !== "previous_period") fail("option_unsupported", `"${String(compare)}" is not a comparison`);
1566
+ comparison = comparisonWindow(window, compare);
1567
+ }
1568
+ const whole = (key, label, w) => ({ key, label, from: w.from, to: w.to, days: daysBetween(w.from, w.to) });
1569
+ return {
1570
+ comparison,
1571
+ current: whole("current", "Current", window),
1572
+ previous: whole("previous", compare === "previous_year" ? "Previous year" : compare === "previous_period" ? "Previous period" : "Comparison", comparison)
1573
+ };
1574
+ }
1575
+ function factAcross(stream, range, buckets, comparison, latest) {
1576
+ if (buckets.length === 0 && !comparison) return factOver(stream, range, latest);
1577
+ const table = quoteIdent(stream.table);
1578
+ const date = quoteIdent(stream.date);
1579
+ const inWindow = (w) => `${date} >= ${sqlDate(w.from)} AND ${date} < ${sqlDate(w.to)}`;
1580
+ if (!comparison) {
1581
+ const numbered = perBucket(date, buckets, (_, i) => i + 1);
1582
+ const columns2 = `, ${numbered} AS "__b"`;
1583
+ return latest ? withLatestDays(table, date, numbered, columns2, inWindow(range)) : `(SELECT *${columns2} FROM ${table} WHERE ${inWindow(range)}) AS ${FACT}`;
1584
+ }
1585
+ const columns = `, (${inWindow(range)}) AS "__cur", (${inWindow(comparison)}) AS "__prev"`;
1586
+ const where = `(${inWindow(range)}) OR (${inWindow(comparison)})`;
1587
+ 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}`;
1588
+ }
1549
1589
  function perBucket(date, buckets, value) {
1550
1590
  return `CASE ${buckets.map((b, i) => `WHEN ${date} < ${sqlDate(b.to)} THEN ${value(b, i)}`).join(" ")} END`;
1551
1591
  }
@@ -1630,21 +1670,10 @@ function compileGrouped(model, view, ctx) {
1630
1670
  let earlierSlices = [];
1631
1671
  let earlierBuckets = [];
1632
1672
  if (view.mode === "variance" || periodVariance) {
1633
- const compare = view.compare ?? "previous_year";
1634
- if (typeof compare === "object" && compare !== null) {
1635
- if (typeof compare.period !== "object" || compare.period === null) fail("option_unsupported", "a comparison given as an object needs a period");
1636
- comparison = resolvePeriod(compare.period, model.periods, ctx.today, { periodToDate: options.period_to_date === true }).window;
1637
- } else {
1638
- if (compare !== "previous_year" && compare !== "previous_period") fail("option_unsupported", `"${String(compare)}" is not a comparison`);
1639
- comparison = comparisonWindow(period.window, compare);
1640
- }
1641
- const whole = (key, label, w) => ({ key, label, from: w.from, to: w.to, days: daysBetween(w.from, w.to) });
1642
- current = { bucket: whole("current", "Current", period.window), filter: `${FACT}."__cur"`, last: `${FACT}."__lastc"` };
1643
- previous = {
1644
- bucket: whole("previous", compare === "previous_year" ? "Previous year" : compare === "previous_period" ? "Previous period" : "Comparison", comparison),
1645
- filter: `${FACT}."__prev"`,
1646
- last: `${FACT}."__lastp"`
1647
- };
1673
+ const two = comparedWith(model, view, ctx, period.window);
1674
+ comparison = two.comparison;
1675
+ current = { bucket: two.current, filter: `${FACT}."__cur"`, last: `${FACT}."__lastc"` };
1676
+ previous = { bucket: two.previous, filter: `${FACT}."__prev"`, last: `${FACT}."__lastp"` };
1648
1677
  factColumns = `, (${inWindow(period.window)}) AS "__cur", (${inWindow(comparison)}) AS "__prev"`;
1649
1678
  factWhere = `(${inWindow(period.window)}) OR (${inWindow(comparison)})`;
1650
1679
  if (periodVariance) {
@@ -2081,9 +2110,11 @@ function compileTransactions(model, view, ctx) {
2081
2110
  }
2082
2111
  function compileStreams(model, view, ctx) {
2083
2112
  const options = view.options ?? {};
2084
- if (view.levels !== void 0) fail("option_unsupported", "nested rows are not compiled for stream mode yet");
2085
- if ((options.activity ?? "with") !== "with") fail("option_unsupported", "the activity option is not compiled for stream mode yet");
2086
- if (options.others_row) fail("option_unsupported", "an others row is not compiled for stream mode yet");
2113
+ const what = view.mode === "stream" ? "stream mode" : "a view of more than one stream";
2114
+ if (view.levels !== void 0) fail("option_unsupported", `nested rows are not compiled for ${what} yet`);
2115
+ if ((options.activity ?? "with") !== "with") fail("option_unsupported", `the activity option is not compiled for ${what} yet`);
2116
+ if (options.others_row) fail("option_unsupported", `an others row is not compiled for ${what} yet`);
2117
+ if (options.average_column && view.mode === "period") fail("option_unsupported", `an average column is not compiled for ${what} yet`);
2087
2118
  const totalRow = options.total_row === true;
2088
2119
  const averageRow = options.average_row === true;
2089
2120
  const sumRow = options.sum_row === true;
@@ -2093,9 +2124,18 @@ function compileStreams(model, view, ctx) {
2093
2124
  const unseen = lead.filterMeasures.filter((key) => !view.measures.includes(key)).map((key) => measureByKey.get(key) ?? fail("unknown_measure", `no measure "${key}"`));
2094
2125
  const period = resolvePeriod(view.period, model.periods, ctx.today, { periodToDate: options.period_to_date === true });
2095
2126
  const range = period.window;
2127
+ const buckets = view.mode === "period" ? period.buckets : [];
2128
+ const two = view.mode === "variance" ? comparedWith(model, view, ctx, range) : null;
2129
+ 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"` };
2130
+ const earlier = two ? { prefix: "ap", days: two.previous.days, filter: `${FACT}."__prev"`, last: `${FACT}."__lastp"` } : null;
2131
+ const perPeriod = buckets.map((bucket, i) => ({
2132
+ bucket,
2133
+ part: { prefix: `a${i + 1}`, days: bucket.days, filter: `${FACT}."__b" = ${i + 1}`, last: `${FACT}."__b" = ${i + 1} AND ${FACT}."__last"` },
2134
+ index: i + 1
2135
+ }));
2096
2136
  const needed = /* @__PURE__ */ new Map();
2097
2137
  const parsed = /* @__PURE__ */ new Map();
2098
- const exprOf = (key, depth) => {
2138
+ const exprOf = (key, part, depth) => {
2099
2139
  if (depth > 20) fail("formula_cycle", `"${key}" refers back to itself`);
2100
2140
  const measure = measureByKey.get(key) ?? fail("formula_unknown_measure", `"${key}" is not a measure`);
2101
2141
  if (isFormulaMeasure(measure)) {
@@ -2104,12 +2144,16 @@ function compileStreams(model, view, ctx) {
2104
2144
  node = parseFormula(measure.formula);
2105
2145
  parsed.set(key, node);
2106
2146
  }
2107
- return emitFormulaSql(node, { measure: (ref) => exprOf(ref, depth + 1), days: daysBetween(range.from, range.to) });
2147
+ return emitFormulaSql(node, {
2148
+ measure: (ref) => exprOf(ref, part, depth + 1),
2149
+ days: part.days,
2150
+ ...buckets.length > 0 ? { periodCount: buckets.length } : {}
2151
+ });
2108
2152
  }
2109
2153
  const list2 = needed.get(measure.stream) ?? [];
2110
- if (!list2.some((m) => m.key === measure.key)) list2.push(measure);
2154
+ if (!list2.some((n) => n.measure.key === measure.key && n.part === part)) list2.push({ measure, part });
2111
2155
  needed.set(measure.stream, list2);
2112
- return `any_value(${quoteIdent(`a__${measure.key}`)})`;
2156
+ return `any_value(${quoteIdent(`${part.prefix}__${measure.key}`)})`;
2113
2157
  };
2114
2158
  const properties = shownProperties(view);
2115
2159
  const columns = [{ name: "code", kind: "code", label: groupDim.label }];
@@ -2121,12 +2165,53 @@ function compileStreams(model, view, ctx) {
2121
2165
  columns.push({ name, kind: "property", label, property });
2122
2166
  });
2123
2167
  const left = ["__rn"];
2124
- const addMeasure = (measure, seen) => {
2125
- const name = `m__${measure.key}`;
2126
- select.push(`CAST(${exprOf(measure.key, 0)} AS DOUBLE) AS ${quoteIdent(name)}`);
2127
- if (seen) columns.push({ name, kind: "measure", label: measure.label, measure: measure.key, format: measure.format, period: null });
2168
+ const derived = [];
2169
+ const put = (into, name, expr, seen, column) => {
2170
+ into.push(`${expr} AS ${quoteIdent(name)}`);
2171
+ if (seen) columns.push({ name, kind: "measure", ...column });
2128
2172
  else left.push(name);
2129
2173
  };
2174
+ const figure = (key, part) => `CAST(${exprOf(key, part, 0)} AS DOUBLE)`;
2175
+ const display = options.reverse_periods ? [...perPeriod].reverse() : perPeriod;
2176
+ const addMeasure = (measure, seen) => {
2177
+ const about = { measure: measure.key, format: measure.format };
2178
+ if (seen) {
2179
+ display.forEach(({ bucket, part, index }) => {
2180
+ put(select, `b${index}__${measure.key}`, figure(measure.key, part), true, { ...about, label: `${measure.label} ${bucket.label}`, period: bucket });
2181
+ });
2182
+ }
2183
+ const wholeName = `m__${measure.key}`;
2184
+ put(select, wholeName, figure(measure.key, whole), seen, {
2185
+ ...about,
2186
+ label: buckets.length > 0 ? `${measure.label} Total` : measure.label,
2187
+ period: two ? two.current : null,
2188
+ ...two ? { part: "current" } : {}
2189
+ });
2190
+ if (!two || !earlier) return;
2191
+ const cur = quoteIdent(wholeName);
2192
+ const prev = quoteIdent(`prev__${measure.key}`);
2193
+ put(
2194
+ select,
2195
+ `prev__${measure.key}`,
2196
+ figure(measure.key, earlier),
2197
+ seen,
2198
+ { ...about, label: `${measure.label} ${two.previous.label}`, period: two.previous, part: "previous" }
2199
+ );
2200
+ put(
2201
+ derived,
2202
+ `var__${measure.key}`,
2203
+ `COALESCE(${cur}, 0) - COALESCE(${prev}, 0)`,
2204
+ seen,
2205
+ { ...about, label: `${measure.label} Variance`, period: null, part: "variance" }
2206
+ );
2207
+ put(
2208
+ derived,
2209
+ `varp__${measure.key}`,
2210
+ `(COALESCE(${cur}, 0) - ${prev}) / NULLIF(abs(${prev}), 0)`,
2211
+ seen,
2212
+ { measure: measure.key, format: "percent", label: `${measure.label} Variance %`, period: null, part: "variance_pct" }
2213
+ );
2214
+ };
2130
2215
  shown.forEach((measure) => addMeasure(measure, true));
2131
2216
  unseen.forEach((measure) => addMeasure(measure, false));
2132
2217
  select.push('"__total"');
@@ -2137,6 +2222,8 @@ function compileStreams(model, view, ctx) {
2137
2222
  if (!columns.some((c) => c.name === sortName && c.kind !== "meta")) fail("bad_sort", `"${String(sort.by)}" is not a column of this view`);
2138
2223
  const { limit, offset } = pageOf(view, ctx, (totalRow ? 1 : 0) + (averageRow ? 1 : 0) + (sumRow ? 1 : 0));
2139
2224
  const measured = columns.filter((c) => c.kind === "measure").map((c) => c.name);
2225
+ const figures = shown.flatMap((m) => two ? [`m__${m.key}`, `prev__${m.key}`] : [`m__${m.key}`]);
2226
+ const source = derived.length > 0 ? "v" : "g";
2140
2227
  const streamKeys = [lead.stream.key, ...model.streams.map((s) => s.key).filter((key) => key !== lead.stream.key && needed.has(key))];
2141
2228
  const stages = streamKeys.flatMap((key, i) => {
2142
2229
  const scope = i === 0 ? lead : scopeOf(model, { ...view, stream: key }, ctx);
@@ -2148,16 +2235,17 @@ function compileStreams(model, view, ctx) {
2148
2235
  const expr = `any_value(${scope.propertyOf(groupDim.key, property)})`;
2149
2236
  part.push(`${totalRow ? `CASE WHEN ${grouping} = 0 THEN ${expr} END` : expr} AS ${quoteIdent(`prop__${property}`)}`);
2150
2237
  });
2151
- mine.forEach((measure) => {
2238
+ mine.forEach(({ measure, part: over }) => {
2152
2239
  const call = aggregateOf(measure, "COUNT(*)");
2153
- part.push(`${measure.snapshot ? `${call} FILTER (WHERE ${FACT}."__lastw")` : call} AS ${quoteIdent(`a__${measure.key}`)}`);
2240
+ 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})`;
2241
+ part.push(`${sum} AS ${quoteIdent(`${over.prefix}__${measure.key}`)}`);
2154
2242
  });
2155
2243
  part.push(`${totalRow ? `CAST(${grouping} AS INTEGER)` : "0"} AS "__total"`);
2156
2244
  return [
2157
2245
  `${i === 0 ? "WITH" : "),"} s${i + 1} AS (`,
2158
2246
  `SELECT ${part.join(", ")}`,
2159
- // A snapshot measure reads its own stream's latest day in the period.
2160
- `FROM ${factOver(stream, range, mine.some((measure) => measure.snapshot))}`,
2247
+ // 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))}`,
2161
2249
  ...scope.joins.values(),
2162
2250
  ...scope.where.length > 0 ? [`WHERE ${scope.where.join(" AND ")}`] : [],
2163
2251
  totalRow ? `GROUP BY GROUPING SETS ((${codeExpr}), ())` : `GROUP BY ${codeExpr}`
@@ -2170,11 +2258,12 @@ function compileStreams(model, view, ctx) {
2170
2258
  // By name: each stage has its own sum columns, and a member one stream lacks gets blanks there.
2171
2259
  `FROM (${streamKeys.map((_, i) => `SELECT * FROM s${i + 1}`).join(" UNION ALL BY NAME ")}) AS u`,
2172
2260
  'GROUP BY "code", "__total"',
2261
+ ...source === "v" ? ["), v AS (", `SELECT g.*, ${derived.join(", ")}`, "FROM g"] : [],
2173
2262
  ...rankAndPage(
2174
- "g",
2263
+ source,
2175
2264
  sortName,
2176
2265
  sort,
2177
- keepRows(lead.having, options, shown.map((m) => `m__${m.key}`)),
2266
+ keepRows(lead.having, options, figures),
2178
2267
  left,
2179
2268
  offset,
2180
2269
  limit,
@@ -2182,7 +2271,11 @@ function compileStreams(model, view, ctx) {
2182
2271
  )
2183
2272
  ].join("\n");
2184
2273
  checkLength(sql, ctx);
2185
- return { ok: true, sql, columns, window: range, buckets: [], months: monthsRange(range), streams: streamKeys };
2274
+ const read = two ? {
2275
+ from: two.comparison.from < range.from ? two.comparison.from : range.from,
2276
+ to: two.comparison.to > range.to ? two.comparison.to : range.to
2277
+ } : range;
2278
+ return { ok: true, sql, columns, window: range, ...two ? { comparison: two.comparison } : {}, buckets, months: monthsRange(read), streams: streamKeys };
2186
2279
  }
2187
2280
  function compileMatrix(model, view, ctx, byPeriod = false) {
2188
2281
  const options = view.options ?? {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sprigr/apps-reporting-core",
3
- "version": "0.0.1",
3
+ "version": "0.0.2",
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",