@sprigr/apps-reporting-core 0.0.3 → 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
 
@@ -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);
@@ -2567,6 +2590,7 @@ export {
2567
2590
  MODEL_VERSION,
2568
2591
  PERIOD_GRAINS,
2569
2592
  PERIOD_PRESETS,
2593
+ RELATIVE_UNITS,
2570
2594
  REPORTING_REASONS,
2571
2595
  ROUTE_MAX_ROWS,
2572
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.3",
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",