@sprigr/apps-reporting-core 0.0.3 → 0.0.5

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,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 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
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,12 +92,13 @@ 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
 
98
99
  - "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
100
  - Month presets run to the end of the current month; `period_to_date` stops them at today.
101
+ - 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
102
  - `-2^2` is -4.
101
103
  - `AVERAGE` and `SUM` skip blanks.
102
104
  - 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);
@@ -1168,11 +1191,12 @@ function compileMode(model, view, ctx) {
1168
1191
  if (view.mode === "stream") return compileStreams(model, view, ctx);
1169
1192
  if (view.mode === "matrix") return compileMatrix(model, view, ctx);
1170
1193
  if (view.mode === "custom") return compileCustom(model, view, ctx);
1171
- if (view.mode !== "period" && view.mode !== "variance") return compileGrouped(model, view, ctx);
1194
+ if (view.mode === "period_variance") return compileGrouped(model, view, ctx);
1195
+ const total = view.mode === "total";
1172
1196
  try {
1173
- return compileOneStream(model, view, ctx);
1197
+ return total ? compileGrouped(model, view, ctx) : compileOneStream(model, view, ctx);
1174
1198
  } catch (err) {
1175
- if (!(err instanceof ReportingError) || err.reason !== "measure_not_on_stream" || ctx.periodShape === "long") throw err;
1199
+ if (!(err instanceof ReportingError) || err.reason !== "measure_not_on_stream" || !total && ctx.periodShape === "long") throw err;
1176
1200
  return compileStreams(model, view, ctx);
1177
1201
  }
1178
1202
  }
@@ -2567,6 +2591,7 @@ export {
2567
2591
  MODEL_VERSION,
2568
2592
  PERIOD_GRAINS,
2569
2593
  PERIOD_PRESETS,
2594
+ RELATIVE_UNITS,
2570
2595
  REPORTING_REASONS,
2571
2596
  ROUTE_MAX_ROWS,
2572
2597
  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.3",
3
+ "version": "0.0.5",
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",