@sprigr/apps-reporting-core 0.0.2 → 0.0.4

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
@@ -6,7 +6,7 @@ Pure reporting core. No IO, no clock, no tenant names. It turns a saved view int
6
6
  |---|---|
7
7
  | `model` | `validateModel(json)`: a tenant's dimensions, measures, streams and calendar, checked. `measureAvailability(model, schema)`: which measures a role can use, given the columns its build holds. |
8
8
  | `formula` | `parseFormula`, `emitFormulaSql`: formula measures over other measures. Closed function list, typed, every division guarded. |
9
- | `periods` | `resolvePeriod`, `splitWindow`, `comparisonWindow`, `monthsRange`: presets, custom and named periods, period columns. |
9
+ | `periods` | `resolvePeriod`, `splitWindow`, `comparisonWindow`, `monthsRange`: presets, custom, named and relative periods, period columns. |
10
10
  | `compile` | `compileView(model, view, { today })`: the statement, the typed values it reads (`params`), the column map, the `months` range and the `tables` it reads. `compileRollupView`: the same view over a monthly rollup, for the browser. |
11
11
  | `grid` | `pivotLong(compiled, rows)`: the rows of a long result folded to one grid row per member with one cell per column. |
12
12
 
@@ -77,9 +77,9 @@ 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
+ - **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.
81
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.
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
+ - **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
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.
84
84
  - **Activity** (`options.activity`): `with` lists members that have fact rows. `all` adds the members that have none, read from the dimension's own table. `without` lists only those, with no total row. The keyword, and the path steps and "and" filters on the group-by dimension or a dimension above it, narrow the member list; every filter decides what counts as activity.
85
85
  - **The others row** (`options.others_row`, modes `total`, `period` and `variance`): a view is focused when its drill path has a step on the group-by dimension itself. The others row is every member that step leaves out, as one row, with formulas worked out from its own sums. The total row is then the focused members' total. Without a focus there is no others row.
@@ -97,6 +97,7 @@ Refused with a named reason until built: an others row in stream mode; nested ro
97
97
 
98
98
  - "Last 3 months" is taken as the three whole months before this one, and "rolling 3" and "rolling 12" as ending with the current month.
99
99
  - Month presets run to the end of the current month; `period_to_date` stops them at today.
100
+ - A relative period (`{ relative: { unit, from, to } }`) counts whole days, weeks or months from the current one, which is 0, both ends inclusive: `{ unit: 'week', from: -1, to: -1 }` is last week, starting on the calendar's `week_start`, and `{ unit: 'month', from: -3, to: 0 }` is three whole months and the current one.
100
101
  - `-2^2` is -4.
101
102
  - `AVERAGE` and `SUM` skip blanks.
102
103
  - In a variance, a blank counts as 0, and the percentage is blank when there is no previous value.
package/dist/index.d.ts CHANGED
@@ -115,7 +115,13 @@ interface PeriodCalendar {
115
115
  /** A tenant's own named periods. `to` is the last day, inclusive. */
116
116
  custom: NamedPeriod[];
117
117
  }
118
- /** What a view stores. In `custom`, `to` is the last day, inclusive. */
118
+ declare const RELATIVE_UNITS: readonly ["day", "week", "month"];
119
+ type RelativeUnit = (typeof RELATIVE_UNITS)[number];
120
+ /**
121
+ * What a view stores. In `custom`, `to` is the last day, inclusive. `relative` counts whole days,
122
+ * weeks or months from the current one (0), both ends inclusive: `{ unit: 'week', from: -1, to: -1 }`
123
+ * is last week.
124
+ */
119
125
  type PeriodSpec = {
120
126
  preset: PeriodPreset;
121
127
  grain?: PeriodGrain;
@@ -128,6 +134,13 @@ type PeriodSpec = {
128
134
  } | {
129
135
  named: string;
130
136
  grain?: PeriodGrain;
137
+ } | {
138
+ relative: {
139
+ unit: RelativeUnit;
140
+ from: number;
141
+ to: number;
142
+ };
143
+ grain?: PeriodGrain;
131
144
  };
132
145
  interface PeriodWindow {
133
146
  from: string;
@@ -596,4 +609,4 @@ interface Grid {
596
609
  */
597
610
  declare function pivotLong(compiled: CompiledView, rows: ResultRow[]): Grid;
598
611
 
599
- export { type CompileContext, type CompiledColumn, type CompiledRollup, type CompiledView, DEFAULT_ACROSS_MEMBERS, DEFAULT_PAGE_ROWS, FORMULA_FUNCTIONS, FORMULA_MAX_CHARS, type FormulaBinaryOp, type FormulaEmitContext, type FormulaFunction, type FormulaNode, type Grid, type GridColumn, type GridFigures, type GridRow, MAX_PERIOD_BUCKETS, MEASURE_AGGS, MEASURE_CMPS, MEASURE_FORMATS, MODEL_PROBLEMS, MODEL_VERSION, type MeasureAgg, type MeasureFormat, type ModelBaseMeasure, type ModelDimension, type ModelFormulaMeasure, type ModelMeasure, type ModelProblem, type ModelProblemReason, type ModelProperty, type ModelRollup, type ModelStream, type ModelStreamColumn, type ModelValidation, type NamedPeriod, PERIOD_GRAINS, PERIOD_PRESETS, type PeriodBucket, type PeriodCalendar, type PeriodGrain, type PeriodPreset, type PeriodSpec, type PeriodWindow, REPORTING_REASONS, ROUTE_MAX_ROWS, ROUTE_MAX_SQL_CHARS, type Refusal, ReportingError, type ReportingModel, type ReportingReason, type ResolvePeriodOptions, type ResolvedPeriod, type ResultRow, VARIANCE_PARTS, VIEW_MODES, type VariancePart, type ViewAcross, type ViewCompare, type ViewCustomColumn, type ViewDataPoint, type ViewDimensionRule, type ViewFilterGroup, type ViewMeasureRule, type ViewMemberRule, type ViewMode, type ViewOptions, type ViewPathStep, type ViewSort, type ViewState, type WeekStart, addDays, addMonths, bindValues, comparisonWindow, compileRollupView, compileView, daysBetween, emitFormulaSql, fiscalYearStart, formulaRefs, inlineParams, isFormulaMeasure, isIdentifier, isIsoDate, isRouteWord, isStageName, likePattern, measureAvailability, monthsRange, parseFormula, pivotLong, quoteIdent, refusalOf, resolvePeriod, splitWindow, sqlDate, sqlNumber, sqlString, sqlValue, startOfMonth, tablesIn, usesGridOnlyFunction, validateModel, writtenLength };
612
+ export { type CompileContext, type CompiledColumn, type CompiledRollup, type CompiledView, DEFAULT_ACROSS_MEMBERS, DEFAULT_PAGE_ROWS, FORMULA_FUNCTIONS, FORMULA_MAX_CHARS, type FormulaBinaryOp, type FormulaEmitContext, type FormulaFunction, type FormulaNode, type Grid, type GridColumn, type GridFigures, type GridRow, MAX_PERIOD_BUCKETS, MEASURE_AGGS, MEASURE_CMPS, MEASURE_FORMATS, MODEL_PROBLEMS, MODEL_VERSION, type MeasureAgg, type MeasureFormat, type ModelBaseMeasure, type ModelDimension, type ModelFormulaMeasure, type ModelMeasure, type ModelProblem, type ModelProblemReason, type ModelProperty, type ModelRollup, type ModelStream, type ModelStreamColumn, type ModelValidation, type NamedPeriod, PERIOD_GRAINS, PERIOD_PRESETS, type PeriodBucket, type PeriodCalendar, type PeriodGrain, type PeriodPreset, type PeriodSpec, type PeriodWindow, RELATIVE_UNITS, REPORTING_REASONS, ROUTE_MAX_ROWS, ROUTE_MAX_SQL_CHARS, type Refusal, type RelativeUnit, ReportingError, type ReportingModel, type ReportingReason, type ResolvePeriodOptions, type ResolvedPeriod, type ResultRow, VARIANCE_PARTS, VIEW_MODES, type VariancePart, type ViewAcross, type ViewCompare, type ViewCustomColumn, type ViewDataPoint, type ViewDimensionRule, type ViewFilterGroup, type ViewMeasureRule, type ViewMemberRule, type ViewMode, type ViewOptions, type ViewPathStep, type ViewSort, type ViewState, type WeekStart, addDays, addMonths, bindValues, comparisonWindow, compileRollupView, compileView, daysBetween, emitFormulaSql, fiscalYearStart, formulaRefs, inlineParams, isFormulaMeasure, isIdentifier, isIsoDate, isRouteWord, isStageName, likePattern, measureAvailability, monthsRange, parseFormula, pivotLong, quoteIdent, refusalOf, resolvePeriod, splitWindow, sqlDate, sqlNumber, sqlString, sqlValue, startOfMonth, tablesIn, usesGridOnlyFunction, validateModel, writtenLength };
package/dist/index.js CHANGED
@@ -555,6 +555,8 @@ var PERIOD_PRESETS = [
555
555
  "rolling_3",
556
556
  "rolling_12"
557
557
  ];
558
+ var RELATIVE_UNITS = ["day", "week", "month"];
559
+ var RELATIVE_REACH = { day: 36600, week: 5220, month: 1200 };
558
560
  var MAX_PERIOD_BUCKETS = 120;
559
561
  var ISO_RX = /^(\d{4})-(\d{2})-(\d{2})$/;
560
562
  var MONTH_NAMES = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
@@ -643,6 +645,25 @@ function presetWindow(preset, cal, today) {
643
645
  return { from: addMonths(month, -11), to: nextMonth };
644
646
  }
645
647
  }
648
+ function relativeWindow(r, cal, today) {
649
+ const unit = r?.unit;
650
+ if (typeof unit !== "string" || !RELATIVE_UNITS.includes(unit)) {
651
+ throw new ReportingError("unknown_period", `a relative period counts "day", "week" or "month", not "${String(unit).slice(0, 20)}"`);
652
+ }
653
+ const reach = RELATIVE_REACH[unit];
654
+ const offset = (n, end) => {
655
+ if (typeof n !== "number" || !Number.isInteger(n) || Math.abs(n) > reach) {
656
+ throw new ReportingError("unknown_period", `a relative period's ${end} must be a whole number of ${unit}s within ${reach} of now`);
657
+ }
658
+ return n;
659
+ };
660
+ const from = offset(r?.from, "from");
661
+ const to = offset(r?.to, "to");
662
+ if (to < from) throw new ReportingError("period_range_inverted", `the period ends (${to}) before it starts (${from})`);
663
+ const step = (start, n) => unit === "month" ? addMonths(start, n) : addDays(start, unit === "week" ? n * 7 : n);
664
+ const current = unit === "month" ? startOfMonth(today) : unit === "week" ? addDays(today, -daysIntoWeek(today, cal.week_start)) : today;
665
+ return { from: step(current, from), to: step(current, to + 1) };
666
+ }
646
667
  function inclusiveWindow(from, to) {
647
668
  need(from);
648
669
  need(to);
@@ -712,8 +733,10 @@ function resolvePeriod(spec, cal, today, options = {}) {
712
733
  const named = cal.custom.find((p) => p.key === spec.named);
713
734
  if (!named) throw new ReportingError("unknown_period", `no named period "${String(spec.named).slice(0, 60)}"`);
714
735
  window = inclusiveWindow(named.from, named.to);
736
+ } else if ("relative" in spec) {
737
+ window = relativeWindow(spec.relative, cal, today);
715
738
  } else {
716
- throw new ReportingError("unknown_period", "a period needs a preset, a custom range or a named period");
739
+ throw new ReportingError("unknown_period", "a period needs a preset, a custom range, a named period or a relative range");
717
740
  }
718
741
  if (options.periodToDate) {
719
742
  const stop = addDays(today, 1);
@@ -1903,13 +1926,30 @@ function compileCustom(model, view, ctx) {
1903
1926
  };
1904
1927
  const uses = /* @__PURE__ */ new Set();
1905
1928
  const reads = { stream, measureByKey, parsed: /* @__PURE__ */ new Map(), countAll: "COUNT(*)", days: daysBetween(own.from, own.to), uses };
1929
+ const reading = /* @__PURE__ */ new Map([[stream.key, { scope, reads, windows: /* @__PURE__ */ new Set() }]]);
1930
+ const readsOf = (key) => {
1931
+ let found = reading.get(key);
1932
+ if (!found) {
1933
+ const other = scopeOf(model, { ...view, stream: key }, ctx);
1934
+ found = { scope: other, reads: { ...reads, stream: other.stream, parsed: /* @__PURE__ */ new Map(), uses: /* @__PURE__ */ new Set() }, windows: /* @__PURE__ */ new Set() };
1935
+ reading.set(key, found);
1936
+ }
1937
+ return found;
1938
+ };
1939
+ const streamOf = (measure, depth = 0) => {
1940
+ if (!isFormulaMeasure(measure)) return measure.stream;
1941
+ const first = depth > 20 ? void 0 : formulaRefs(parseFormula(measure.formula)).map((ref) => measureByKey.get(ref)).find((m) => m !== void 0);
1942
+ return first === void 0 ? stream.key : streamOf(first, depth + 1);
1943
+ };
1906
1944
  const points = [];
1907
1945
  const pointOf = (point, what) => {
1908
1946
  if (typeof point !== "object" || point === null) fail("bad_custom_column", `${what} has no data point`);
1909
1947
  const measure = measureByKey.get(point.measure) ?? fail("unknown_measure", `no measure "${String(point.measure)}"`);
1910
1948
  const { window, number } = windowOf(point.period);
1911
1949
  if (point.where !== void 0 && (typeof point.where !== "object" || point.where === null || "measure" in point.where)) fail("bad_custom_column", `the rule of ${what} is not a dimension rule`);
1912
- const rule = point.where === void 0 ? "" : ` AND ${scope.dimensionRule(point.where)}`;
1950
+ const src = readsOf(streamOf(measure));
1951
+ src.windows.add(number);
1952
+ const rule = point.where === void 0 ? "" : ` AND ${src.scope.dimensionRule(point.where)}`;
1913
1953
  const bucket = {
1914
1954
  key: `w${number}`,
1915
1955
  label: `${window.from} to ${addDays(window.to, -1)}`,
@@ -1918,9 +1958,10 @@ function compileCustom(model, view, ctx) {
1918
1958
  days: daysBetween(window.from, window.to)
1919
1959
  };
1920
1960
  const slice = { bucket, filter: `${FACT}.${quoteIdent(`__w${number}`)}${rule}`, last: `${FACT}.${quoteIdent(`__l${number}`)}${rule}` };
1921
- const sql2 = `CAST(${measureOver(reads, measure.key, slice)} AS DOUBLE)`;
1922
- const at = points.indexOf(sql2);
1923
- return { name: `p${at >= 0 ? at + 1 : points.push(sql2)}`, measure, bucket };
1961
+ const sql2 = `CAST(${measureOver(src.reads, measure.key, slice)} AS DOUBLE)`;
1962
+ const key = src.scope.stream.key;
1963
+ const at = points.findIndex((p) => p.stream === key && p.sql === sql2);
1964
+ return { name: `p${at >= 0 ? at + 1 : points.push({ stream: key, sql: sql2 })}`, measure, bucket };
1924
1965
  };
1925
1966
  const columns = [...nest?.columns ?? [], { name: "code", kind: "code", label: groupDim.label }];
1926
1967
  const select = [...nest?.select ?? [], `${codeExpr} AS "code"`];
@@ -1981,7 +2022,9 @@ function compileCustom(model, view, ctx) {
1981
2022
  const measured = columns.filter((c) => c.kind === "measure").map((c) => c.name);
1982
2023
  if (measured.length === 0) fail("bad_custom_column", "every column of the view is hidden");
1983
2024
  if (points.length === 0) fail("bad_custom_column", "no column of the view reads a data point");
1984
- points.forEach((sql2, i) => {
2025
+ const multi = reading.size > 1;
2026
+ if (multi && nest) fail("option_unsupported", "nested rows are not compiled for a custom view of more than one stream yet");
2027
+ points.forEach(({ sql: sql2 }, i) => {
1985
2028
  select.push(`${sql2} AS ${quoteIdent(`p${i + 1}`)}`);
1986
2029
  left.push(`p${i + 1}`);
1987
2030
  });
@@ -2003,13 +2046,42 @@ function compileCustom(model, view, ctx) {
2003
2046
  const flags = `, ${windows.map((w, i) => `(${inWindow(w)}) AS ${quoteIdent(`__w${i + 1}`)}`).join(", ")}`;
2004
2047
  const anyWindow = windows.map((w) => `(${inWindow(w)})`).join(" OR ");
2005
2048
  const fact = uses.has("snapshot") ? withLatestDayOfEach(quoteIdent(stream.table), date, flags, anyWindow, windows.map((w, i) => ({ where: inWindow(w), flag: `__l${i + 1}` }))) : `(SELECT *${flags} FROM ${quoteIdent(stream.table)} WHERE ${anyWindow}) AS ${FACT}`;
2049
+ const streamKeys = [stream.key, ...model.streams.map((s) => s.key).filter((key) => key !== stream.key && reading.has(key))];
2050
+ const stages = !multi ? [] : streamKeys.map((key) => {
2051
+ const { scope: s, reads: r, windows: used } = readsOf(key);
2052
+ const grouped = `GROUPING(${s.codeExpr})`;
2053
+ const parts2 = [`${s.codeExpr} AS "code"`];
2054
+ shownProperties(view).forEach((property) => {
2055
+ const expr = `any_value(${s.propertyOf(groupDim.key, property)})`;
2056
+ parts2.push(`${totalRow ? `CASE WHEN ${grouped} = 0 THEN ${expr} END` : expr} AS ${quoteIdent(`prop__${property}`)}`);
2057
+ });
2058
+ points.forEach((p, i) => {
2059
+ if (p.stream === key) parts2.push(`${p.sql} AS ${quoteIdent(`p${i + 1}`)}`);
2060
+ });
2061
+ parts2.push(`${totalRow ? `CAST(${grouped} AS INTEGER)` : "0"} AS "__total"`);
2062
+ const mine = [...used].sort((a, b) => a - b);
2063
+ const sDate = quoteIdent(s.stream.date);
2064
+ const sIn = (w) => `${sDate} >= ${sqlDate(w.from)} AND ${sDate} < ${sqlDate(w.to)}`;
2065
+ const sFlags = mine.map((n) => `(${sIn(windows[n - 1])}) AS ${quoteIdent(`__w${n}`)}`).join(", ");
2066
+ const sAny = mine.map((n) => `(${sIn(windows[n - 1])})`).join(" OR ");
2067
+ const from = mine.length === 0 ? factOver(s.stream, own, false) : r.uses.has("snapshot") ? withLatestDayOfEach(quoteIdent(s.stream.table), sDate, `, ${sFlags}`, sAny, mine.map((n) => ({ where: sIn(windows[n - 1]), flag: `__l${n}` }))) : `(SELECT *, ${sFlags} FROM ${quoteIdent(s.stream.table)} WHERE ${sAny}) AS ${FACT}`;
2068
+ return { select: parts2, from, joins: [...s.joins.values()], where: s.where, groupBy: totalRow ? `GROUP BY GROUPING SETS ((${s.codeExpr}), ())` : `GROUP BY ${s.codeExpr}` };
2069
+ });
2070
+ const fold = [
2071
+ '"code"',
2072
+ ...shownProperties(view).map((property) => `any_value(${quoteIdent(`prop__${property}`)}) AS ${quoteIdent(`prop__${property}`)}`),
2073
+ ...points.map((_, i) => `any_value(${quoteIdent(`p${i + 1}`)}) AS ${quoteIdent(`p${i + 1}`)}`),
2074
+ '"__total"'
2075
+ ];
2006
2076
  const sql = [
2007
- "WITH g AS (",
2008
- `SELECT ${select.join(", ")}`,
2009
- `FROM ${fact}`,
2010
- ...joins.values(),
2011
- ...where.length > 0 ? [`WHERE ${where.join(" AND ")}`] : [],
2012
- nest ? nest.groupBy(totalRow) : totalRow ? `GROUP BY GROUPING SETS ((${codeExpr}), ())` : `GROUP BY ${codeExpr}`,
2077
+ ...multi ? foldStreams(stages, fold) : [
2078
+ "WITH g AS (",
2079
+ `SELECT ${select.join(", ")}`,
2080
+ `FROM ${fact}`,
2081
+ ...joins.values(),
2082
+ ...where.length > 0 ? [`WHERE ${where.join(" AND ")}`] : [],
2083
+ nest ? nest.groupBy(totalRow) : totalRow ? `GROUP BY GROUPING SETS ((${codeExpr}), ())` : `GROUP BY ${codeExpr}`
2084
+ ],
2013
2085
  "), v AS (",
2014
2086
  `SELECT g.*, ${derived.join(", ")}`,
2015
2087
  "FROM g",
@@ -2025,7 +2097,7 @@ function compileCustom(model, view, ctx) {
2025
2097
  from: windows.reduce((min, w) => w.from < min ? w.from : min, windows[0]?.from ?? own.from),
2026
2098
  to: windows.reduce((max, w) => w.to > max ? w.to : max, windows[0]?.to ?? own.to)
2027
2099
  };
2028
- return { ok: true, sql, columns, window: hull, windows, buckets: [], months: monthsRange(hull) };
2100
+ return { ok: true, sql, columns, window: hull, windows, buckets: [], months: monthsRange(hull), ...multi ? { streams: streamKeys } : {} };
2029
2101
  }
2030
2102
  function compileTransactions(model, view, ctx) {
2031
2103
  const options = view.options ?? {};
@@ -2108,6 +2180,23 @@ function compileTransactions(model, view, ctx) {
2108
2180
  checkLength(sql, ctx);
2109
2181
  return { ok: true, sql, columns, window: period.window, buckets: [], months: monthsRange(period.window) };
2110
2182
  }
2183
+ function foldStreams(stages, fold) {
2184
+ return [
2185
+ ...stages.flatMap((stage, i) => [
2186
+ `${i === 0 ? "WITH" : "),"} s${i + 1} AS (`,
2187
+ `SELECT ${stage.select.join(", ")}`,
2188
+ `FROM ${stage.from}`,
2189
+ ...stage.joins,
2190
+ ...stage.where.length > 0 ? [`WHERE ${stage.where.join(" AND ")}`] : [],
2191
+ stage.groupBy
2192
+ ]),
2193
+ "), g AS (",
2194
+ `SELECT ${fold.join(", ")}`,
2195
+ // By name: each stage has its own sum columns, and a member one stream lacks gets blanks there.
2196
+ `FROM (${stages.map((_, i) => `SELECT * FROM s${i + 1}`).join(" UNION ALL BY NAME ")}) AS u`,
2197
+ 'GROUP BY "code", "__total"'
2198
+ ];
2199
+ }
2111
2200
  function compileStreams(model, view, ctx) {
2112
2201
  const options = view.options ?? {};
2113
2202
  const what = view.mode === "stream" ? "stream mode" : "a view of more than one stream";
@@ -2225,7 +2314,7 @@ function compileStreams(model, view, ctx) {
2225
2314
  const figures = shown.flatMap((m) => two ? [`m__${m.key}`, `prev__${m.key}`] : [`m__${m.key}`]);
2226
2315
  const source = derived.length > 0 ? "v" : "g";
2227
2316
  const streamKeys = [lead.stream.key, ...model.streams.map((s) => s.key).filter((key) => key !== lead.stream.key && needed.has(key))];
2228
- const stages = streamKeys.flatMap((key, i) => {
2317
+ const stages = streamKeys.map((key, i) => {
2229
2318
  const scope = i === 0 ? lead : scopeOf(model, { ...view, stream: key }, ctx);
2230
2319
  const { stream, codeExpr } = scope;
2231
2320
  const mine = needed.get(key) ?? [];
@@ -2241,23 +2330,17 @@ function compileStreams(model, view, ctx) {
2241
2330
  part.push(`${sum} AS ${quoteIdent(`${over.prefix}__${measure.key}`)}`);
2242
2331
  });
2243
2332
  part.push(`${totalRow ? `CAST(${grouping} AS INTEGER)` : "0"} AS "__total"`);
2244
- return [
2245
- `${i === 0 ? "WITH" : "),"} s${i + 1} AS (`,
2246
- `SELECT ${part.join(", ")}`,
2333
+ return {
2334
+ select: part,
2247
2335
  // 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))}`,
2249
- ...scope.joins.values(),
2250
- ...scope.where.length > 0 ? [`WHERE ${scope.where.join(" AND ")}`] : [],
2251
- totalRow ? `GROUP BY GROUPING SETS ((${codeExpr}), ())` : `GROUP BY ${codeExpr}`
2252
- ];
2336
+ from: factAcross(stream, range, buckets, two ? two.comparison : null, mine.some(({ measure }) => measure.snapshot)),
2337
+ joins: [...scope.joins.values()],
2338
+ where: scope.where,
2339
+ groupBy: totalRow ? `GROUP BY GROUPING SETS ((${codeExpr}), ())` : `GROUP BY ${codeExpr}`
2340
+ };
2253
2341
  });
2254
2342
  const sql = [
2255
- ...stages,
2256
- "), g AS (",
2257
- `SELECT ${select.join(", ")}`,
2258
- // By name: each stage has its own sum columns, and a member one stream lacks gets blanks there.
2259
- `FROM (${streamKeys.map((_, i) => `SELECT * FROM s${i + 1}`).join(" UNION ALL BY NAME ")}) AS u`,
2260
- 'GROUP BY "code", "__total"',
2343
+ ...foldStreams(stages, select),
2261
2344
  ...source === "v" ? ["), v AS (", `SELECT g.*, ${derived.join(", ")}`, "FROM g"] : [],
2262
2345
  ...rankAndPage(
2263
2346
  source,
@@ -2507,6 +2590,7 @@ export {
2507
2590
  MODEL_VERSION,
2508
2591
  PERIOD_GRAINS,
2509
2592
  PERIOD_PRESETS,
2593
+ RELATIVE_UNITS,
2510
2594
  REPORTING_REASONS,
2511
2595
  ROUTE_MAX_ROWS,
2512
2596
  ROUTE_MAX_SQL_CHARS,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sprigr/apps-reporting-core",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
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",