@sprigr/apps-reporting-core 0.0.12 → 0.0.14

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
@@ -30,6 +30,19 @@ run(out.sql, { params: out.params, months: out.months });
30
30
  - A dimension's lookup table must hold one row per code, or sums multiply.
31
31
  - "Today" is passed in, in the tenant's time zone.
32
32
 
33
+ ## A stream's own filter
34
+
35
+ A stream can leave rows of its table out of every figure read from it:
36
+
37
+ ```json
38
+ { "key": "orders", "table": "order_lines", "date": "order_date", "dimension_keys": { "item": "item_code" },
39
+ "where": { "dimension": "item", "cmp": "not_in", "values": ["X1", "X2"] } }
40
+ ```
41
+
42
+ `where` takes the shape of a view's dimension filter: a rule (`dimension`, optional `property`, `cmp` of `in`, `not_in`, `contains` or `not_contains`, `values`) or a group (`op` of `and` or `or`, `rules`), nested at most three deep. It works as that filter does: a row with no value passes the two "not" rules, and a dimension can be reached through a parent. `validateModel` refuses a `where` whose dimension the stream does not reach, with `stream_filter_not_on_stream`, and a bad shape, comparison, property or value list with `stream_filter_invalid`, each with its path.
43
+
44
+ Every read of the stream goes through the filter: fact rows, the latest day a snapshot is read on, a member rule's own pass, a transaction list, and each window and stream of a view. A member list under `activity` drops the members the filter leaves out when the member's table can answer it. A rollup is read only when it keeps every dimension the filter names, and it is filtered the same way. `streams_filtered` in the result names each stream the statement read through its filter, so a reader can say the figures leave rows out.
45
+
33
46
  ## Rollups
34
47
 
35
48
  The fact table is too big to hand to a browser; a rollup of it by month is not. A stream lists its rollups in the model:
@@ -46,7 +59,8 @@ The fact table is too big to hand to a browser; a rollup of it by month is not.
46
59
 
47
60
  - a stream the view reads has no rollup holding every dimension and measure the view needs (a dimension reached through a parent needs the parent, and a formula needs every measure it reads);
48
61
  - a window or period of the view does not start and end on the first of a month, such as a period to date, a week or a custom range of days;
49
- - the view is a transaction list or reads a snapshot measure.
62
+ - the view is a transaction list or reads a snapshot measure;
63
+ - a stream's `where` names a dimension the rollup does not keep, directly or through a parent.
50
64
 
51
65
  Of the rollups that can answer, the one with the fewest dimensions is read, then the first listed. A view that does not compile at all refuses with its own reason. The statement still joins the dimension tables for names, properties and parent dimensions, so the caller loads those beside the rollup. `tables` in the result lists every table the statement reads, rollups and dimension tables alike, in the order it first reads them.
52
66
 
@@ -70,7 +84,7 @@ Modes `total`, `period`, `variance`, `period_variance`, `transaction`, `stream`,
70
84
 
71
85
  `__total` says what a result row is: 0 a member, 1 the total, 2 the others row, 3 the average row, 4 the sum row.
72
86
 
73
- - **Variance** reads the period and a comparison window (`compare`: `previous_year` for the same dates a year earlier, `previous_period` for the period just before, or `{ period }` for a window of its own, which may overlap the period or come after it) in one pass. Each measure gets four columns: current, previous, variance and variance percentage (a fraction).
87
+ - **Variance** reads the period and a comparison window (`compare`: `previous_year` for the same dates a year earlier, `previous_period` for the period just before, `{ period }` for a window of its own, which may overlap the period or come after it, or `{ shift: { days, length_days } }` for the period moved by `days` and lasting `length_days`, its own length when left out, so it moves with the period: `{ shift: { days: -364 } }` is the same weekdays 52 weeks earlier, and `{ shift: { days: -9, length_days: 9 } }` the 9 days just before) in one pass. Each measure gets four columns: current, previous, variance and variance percentage (a fraction).
74
88
  - **Period variance** is a period view where every period is a variance. Each period gets four columns: its own value, the value of the period at the same place in the comparison window, the variance and the variance percentage. The same four over the whole windows follow. `compare` is read as in a variance. The comparison window is cut with the period's grain, and the view is refused when the two windows do not cut into the same number of periods. Columns are named `b<n>__`, `pb<n>__`, `bv<n>__` and `bvp<n>__` before the measure key, `<n>` counted from the oldest period; each carries `bucket: n` and its `part`. `sort.by` and a filter on a measure take what a period view and a variance take. The statement is always one column per period, and a view too wide for the route is refused.
75
89
  - **A filter on a dimension** tests fact rows, on the code or on a property. `in` and `not_in` match whole values. `contains` and `not_contains` look for text anywhere in the value, whatever its case; a rule with several texts passes when any one is found, and a text can be up to 200 characters. A row with no value passes `not_in` and `not_contains`. Rules sit in groups joined by `and` or `or`, up to three deep, so a search over a code or a name is an `or` group of two `contains` rules. A data point of a custom view takes the same rules.
76
90
  - **A filter on a member's own figure** names a dimension and a measure together: `{ dimension, measure, cmp, value, period? }`. It keeps the fact rows of the members whose figure passes, worked out over the rule's own `period` (the view's when it gives none), so "products that sold more than 100 last year" can filter a view of this month. It sits with the dimension rules, in `and` and `or` groups and in every mode. The figure is over all of the rows of the measure's own stream in those dates, whatever else the view filters on, so "stock on hand over 0" can filter a view of sales. That stream must reach the rule's dimension, and a formula over two streams is refused. Each stream the view reads keeps the same members, and `compileRollupView` reads a rollup of the rule's stream too. A member with no rows on that stream has a sum or count of 0, as Phocas reads it, so "sales under 100" keeps products that sold nothing. Those members are listed from the dimension's table, or from the table of the dimension it hangs off, and a rule that 0 passes is refused on a dimension with neither. A snapshot figure, a formula and the other aggregates stay blank for such a member and pass no comparison. The result lists the dates each such rule reads in `ruleWindows`, and `months` covers them. A data point of a custom view does not take one.
package/dist/index.d.ts CHANGED
@@ -199,7 +199,28 @@ interface ModelStream {
199
199
  columns: ModelStreamColumn[];
200
200
  /** Tables that hold this stream already added up by month. A view one of them covers can be answered from it. */
201
201
  rollups: ModelRollup[];
202
+ /**
203
+ * Rows of the table the stream leaves out, in the shape a view's dimension filter takes. Every read of
204
+ * the stream keeps only the rows that pass, so the figures leave out those rows wherever they are read.
205
+ */
206
+ where?: StreamFilter;
207
+ }
208
+ /** Keeps the rows whose code, or `property`, of a dimension passes, as a view's dimension rule does. */
209
+ interface StreamFilterRule {
210
+ dimension: string;
211
+ property?: string;
212
+ cmp: StreamFilterCmp;
213
+ values: string[];
202
214
  }
215
+ interface StreamFilterGroup {
216
+ op: 'and' | 'or';
217
+ rules: StreamFilter[];
218
+ }
219
+ type StreamFilter = StreamFilterRule | StreamFilterGroup;
220
+ declare const STREAM_FILTER_CMPS: readonly ["in", "not_in", "contains", "not_contains"];
221
+ type StreamFilterCmp = (typeof STREAM_FILTER_CMPS)[number];
222
+ /** How deep a stream filter's groups may nest, as a view's filters may. */
223
+ declare const MAX_STREAM_FILTER_DEPTH = 3;
203
224
  /**
204
225
  * One rollup of a stream: its figures added up by month and by some of the stream's dimensions.
205
226
  * It is small enough to hand to a browser, where the fact table is not.
@@ -271,7 +292,7 @@ interface ReportingModel {
271
292
  measures: ModelMeasure[];
272
293
  periods: PeriodCalendar;
273
294
  }
274
- declare const MODEL_PROBLEMS: readonly ["not_an_object", "unsupported_model_version", "no_streams", "missing_field", "bad_key", "bad_identifier", "duplicate_key", "unknown_stream", "unknown_dimension", "dimension_table_incomplete", "via_parent_has_no_table", "dimension_cycle", "measure_shape", "unknown_agg", "unknown_format", "formula_invalid", "formula_unknown_measure", "formula_cycle", "bad_fiscal_month", "bad_week_start", "bad_date", "period_range_inverted", "rollup_dimension_not_on_stream", "rollup_measure_unknown", "rollup_measure_not_additive", "reserved_table_name", "reserved_name"];
295
+ declare const MODEL_PROBLEMS: readonly ["not_an_object", "unsupported_model_version", "no_streams", "missing_field", "bad_key", "bad_identifier", "duplicate_key", "unknown_stream", "unknown_dimension", "dimension_table_incomplete", "via_parent_has_no_table", "dimension_cycle", "measure_shape", "unknown_agg", "unknown_format", "formula_invalid", "formula_unknown_measure", "formula_cycle", "bad_fiscal_month", "bad_week_start", "bad_date", "period_range_inverted", "rollup_dimension_not_on_stream", "rollup_measure_unknown", "rollup_measure_not_additive", "reserved_table_name", "reserved_name", "stream_filter_invalid", "stream_filter_not_on_stream"];
275
296
  type ModelProblemReason = (typeof MODEL_PROBLEMS)[number];
276
297
  interface ModelProblem {
277
298
  reason: ModelProblemReason;
@@ -335,9 +356,17 @@ declare const MEASURE_CMPS: readonly ["=", "<>", "<", "<=", ">", ">="];
335
356
  /** The four columns a measure has in variance mode. */
336
357
  declare const VARIANCE_PARTS: readonly ["current", "previous", "variance", "variance_pct"];
337
358
  type VariancePart = (typeof VARIANCE_PARTS)[number];
338
- /** The same dates a year earlier, the period just before, or a period of its own. */
359
+ /**
360
+ * The same dates a year earlier, the period just before, a period of its own, or the period moved by `days`
361
+ * and lasting `length_days` (the period's own length when left out), so it moves with the period.
362
+ */
339
363
  type ViewCompare = 'previous_year' | 'previous_period' | {
340
364
  period: PeriodSpec;
365
+ } | {
366
+ shift: {
367
+ days: number;
368
+ length_days?: number;
369
+ };
341
370
  };
342
371
  interface ViewPathStep {
343
372
  dimension: string;
@@ -576,6 +605,8 @@ interface CompiledView {
576
605
  limit?: number;
577
606
  /** From `compileRollupView`: the rollup each stream is read from, in the order the statement reads them. */
578
607
  rollups?: CompiledRollup[];
608
+ /** The streams the statement reads through their own `where`, so the figures leave rows of those tables out. */
609
+ streams_filtered?: string[];
579
610
  }
580
611
  interface CompiledRollup {
581
612
  stream: string;
@@ -648,4 +679,4 @@ interface Grid {
648
679
  */
649
680
  declare function pivotLong(compiled: CompiledView, rows: ResultRow[]): Grid;
650
681
 
651
- 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 ViewCalculation, type ViewCompare, type ViewCustomColumn, type ViewDataPoint, type ViewDimensionRule, type ViewFilterGroup, type ViewMeasureRule, type ViewMemberRule, type ViewMode, type ViewNumberFormat, 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, shownColumns, splitWindow, sqlDate, sqlNumber, sqlString, sqlValue, startOfMonth, tablesIn, usesGridOnlyFunction, validateModel, withCalculations, writtenLength };
682
+ 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, MAX_STREAM_FILTER_DEPTH, 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, STREAM_FILTER_CMPS, type StreamFilter, type StreamFilterCmp, type StreamFilterGroup, type StreamFilterRule, VARIANCE_PARTS, VIEW_MODES, type VariancePart, type ViewAcross, type ViewCalculation, type ViewCompare, type ViewCustomColumn, type ViewDataPoint, type ViewDimensionRule, type ViewFilterGroup, type ViewMeasureRule, type ViewMemberRule, type ViewMode, type ViewNumberFormat, 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, shownColumns, splitWindow, sqlDate, sqlNumber, sqlString, sqlValue, startOfMonth, tablesIn, usesGridOnlyFunction, validateModel, withCalculations, writtenLength };
package/dist/index.js CHANGED
@@ -767,6 +767,8 @@ function monthsRange(window) {
767
767
  var MODEL_VERSION = 1;
768
768
  var MEASURE_AGGS = ["sum", "count", "count_distinct", "min", "max", "avg"];
769
769
  var MEASURE_FORMATS = ["number", "integer", "currency", "percent"];
770
+ var STREAM_FILTER_CMPS = ["in", "not_in", "contains", "not_contains"];
771
+ var MAX_STREAM_FILTER_DEPTH = 3;
770
772
  var MODEL_PROBLEMS = [
771
773
  "not_an_object",
772
774
  "unsupported_model_version",
@@ -794,7 +796,9 @@ var MODEL_PROBLEMS = [
794
796
  "rollup_measure_unknown",
795
797
  "rollup_measure_not_additive",
796
798
  "reserved_table_name",
797
- "reserved_name"
799
+ "reserved_name",
800
+ "stream_filter_invalid",
801
+ "stream_filter_not_on_stream"
798
802
  ];
799
803
  var KEY_RX = /^[a-z][a-z0-9_]{0,62}$/;
800
804
  function isRec(v) {
@@ -915,6 +919,53 @@ function validateModel(input) {
915
919
  cursor = cursor.via ? dimByKey.get(cursor.via.dimension) : void 0;
916
920
  }
917
921
  });
922
+ const onStream = (dimKey, keys, depth = 0) => {
923
+ if (has(keys, dimKey)) return true;
924
+ const via = dimByKey.get(dimKey)?.via;
925
+ return via !== void 0 && depth < 20 && onStream(via.dimension, keys, depth + 1);
926
+ };
927
+ const streamFilter = (raw, path, depth, keys) => {
928
+ const invalid = (detail) => {
929
+ bad("stream_filter_invalid", path, detail);
930
+ return null;
931
+ };
932
+ if (!isRec(raw)) return invalid("a stream filter is a rule or a group of rules");
933
+ if (raw.rules !== void 0 || raw.op !== void 0) {
934
+ if (depth > MAX_STREAM_FILTER_DEPTH) return invalid(`groups nest deeper than ${MAX_STREAM_FILTER_DEPTH} levels`);
935
+ const op = raw.op;
936
+ if (op !== "and" && op !== "or") return invalid('a group needs op "and" or "or"');
937
+ const rules = list(raw.rules);
938
+ if (rules.length === 0) return invalid("a group has no rules");
939
+ const kept = rules.map((rule, i) => streamFilter(rule, `${path}.rules[${i}]`, depth + 1, keys));
940
+ return kept.every((r) => r !== null) ? { op, rules: kept } : null;
941
+ }
942
+ if (raw.measure !== void 0) return invalid("a stream filter tests dimensions, not measures");
943
+ if (typeof raw.dimension !== "string") return invalid("a rule names a dimension");
944
+ const dim = dimByKey.get(raw.dimension);
945
+ if (!dim) {
946
+ bad("unknown_dimension", path, `no dimension "${raw.dimension}"`);
947
+ return null;
948
+ }
949
+ if (!onStream(dim.key, keys)) {
950
+ bad("stream_filter_not_on_stream", path, `the stream has no "${dim.key}", directly or through a parent`);
951
+ return null;
952
+ }
953
+ const property = raw.property === void 0 || raw.property === "code" ? void 0 : raw.property;
954
+ if (property !== void 0) {
955
+ const known = property === "name" && dim.name !== void 0 || dim.properties.some((p) => p.key === property);
956
+ if (!known) return invalid(`"${dim.key}" has no property "${String(property)}"`);
957
+ }
958
+ if (!STREAM_FILTER_CMPS.includes(raw.cmp)) return invalid(`cmp must be one of ${STREAM_FILTER_CMPS.join(", ")}`);
959
+ const cmp = raw.cmp;
960
+ const values = list(raw.values);
961
+ if (values.length === 0) return invalid("a rule needs at least one value");
962
+ if (!values.every((v) => typeof v === "string" || typeof v === "number")) return invalid("a value is text or a number");
963
+ const texts = values.map(String);
964
+ if ((cmp === "contains" || cmp === "not_contains") && texts.some((t) => t === "" || t.length > 200)) {
965
+ return invalid("a text to look for is 1 to 200 characters");
966
+ }
967
+ return { dimension: dim.key, ...typeof property === "string" ? { property } : {}, cmp, values: texts };
968
+ };
918
969
  const streams = [];
919
970
  const streamKeys = /* @__PURE__ */ new Set();
920
971
  list(input.streams).forEach((raw, i) => {
@@ -979,7 +1030,12 @@ function validateModel(input) {
979
1030
  });
980
1031
  rollups.push({ key: rk, table: rollupTable, date: rollupDate, dimension_keys: kept, measure_columns });
981
1032
  });
982
- streams.push({ key: k, label: label(raw.label, k), table, date, dimension_keys, columns, rollups });
1033
+ const stream = { key: k, label: label(raw.label, k), table, date, dimension_keys, columns, rollups };
1034
+ if (raw.where !== void 0 && raw.where !== null) {
1035
+ const where = streamFilter(raw.where, `${path}.where`, 0, dimension_keys);
1036
+ if (where !== null) stream.where = where;
1037
+ }
1038
+ streams.push(stream);
983
1039
  });
984
1040
  if (streams.length === 0 && problems.length === 0) bad("no_streams", "streams", "a model needs at least one stream");
985
1041
  const defaultStream = streams[0]?.key;
@@ -1219,6 +1275,7 @@ var MAX_LEVELS = 5;
1219
1275
  var VIEW_MODES = ["total", "period", "variance", "period_variance", "transaction", "stream", "matrix", "custom"];
1220
1276
  var MEASURE_CMPS = ["=", "<>", "<", "<=", ">", ">="];
1221
1277
  var VARIANCE_PARTS = ["current", "previous", "variance", "variance_pct"];
1278
+ var MAX_SHIFT_DAYS = 36600;
1222
1279
  var PART_PREFIX = { current: "m__", previous: "prev__", variance: "var__", variance_pct: "varp__" };
1223
1280
  var FACT = "f";
1224
1281
  function fail2(reason, detail) {
@@ -1236,7 +1293,7 @@ function stringList(values, what) {
1236
1293
  }
1237
1294
  function compileView(model, view, ctx) {
1238
1295
  try {
1239
- const full = withCalculations(model, view);
1296
+ const full = withStreamDimensions(withCalculations(model, view));
1240
1297
  const compiled = compileMode(full, view, ctx);
1241
1298
  const out = { ...compiled, columns: shownColumns(view, compiled.columns) };
1242
1299
  const { sql, params } = bindValues(out.sql);
@@ -1246,7 +1303,16 @@ function compileView(model, view, ctx) {
1246
1303
  (all, m) => ({ from: m.from < all.from ? m.from : all.from, to: m.to > all.to ? m.to : all.to }),
1247
1304
  out.months
1248
1305
  );
1249
- return { ...out, sql, params, months, ...ruleWindows.length > 0 ? { ruleWindows } : {}, tables: tablesIn(sql).filter((table) => known.has(table)) };
1306
+ const filtered = model.streams.filter((s) => s.where !== void 0 && sql.includes(`AS ${filteredAlias(s)}`)).sort((a, b) => sql.indexOf(`AS ${filteredAlias(a)}`) - sql.indexOf(`AS ${filteredAlias(b)}`)).map((s) => s.key);
1307
+ return {
1308
+ ...out,
1309
+ sql,
1310
+ params,
1311
+ months,
1312
+ ...ruleWindows.length > 0 ? { ruleWindows } : {},
1313
+ tables: tablesIn(sql).filter((table) => known.has(table)),
1314
+ ...filtered.length > 0 ? { streams_filtered: filtered } : {}
1315
+ };
1250
1316
  } catch (err) {
1251
1317
  return refusalOf(err);
1252
1318
  }
@@ -1395,6 +1461,70 @@ function memberRuleStreams(model, view) {
1395
1461
  if (view.filters) walk(view.filters);
1396
1462
  return found;
1397
1463
  }
1464
+ var inList = (values) => `(${values.map(sqlValue).join(", ")})`;
1465
+ function dimensionRuleSql(rule, resolve) {
1466
+ const whole = rule.cmp === "in" || rule.cmp === "not_in";
1467
+ if (!whole && rule.cmp !== "contains" && rule.cmp !== "not_contains") fail2("empty_filter", `"${String(rule.cmp)}" is not a filter comparison`);
1468
+ const expr = resolve(rule.dimension, rule.property ?? "code");
1469
+ const what = `the filter on "${String(rule.dimension)}"`;
1470
+ const values = stringList(rule.values, what);
1471
+ if (whole) {
1472
+ return rule.cmp === "in" ? `CAST(${expr} AS VARCHAR) IN ${inList(values)}` : `(${expr} IS NULL OR CAST(${expr} AS VARCHAR) NOT IN ${inList(values)})`;
1473
+ }
1474
+ const found = values.map((text) => {
1475
+ if (text === "") fail2("empty_selection", `${what} holds an empty text to look for`);
1476
+ if (text.length > MAX_KEYWORD_CHARS) fail2("keyword_too_long", `${what} holds a text longer than ${MAX_KEYWORD_CHARS} characters`);
1477
+ return `CAST(${expr} AS VARCHAR) ILIKE ${sqlValue(likePattern(text))} ESCAPE '\\'`;
1478
+ });
1479
+ const any = `(${found.join(" OR ")})`;
1480
+ return rule.cmp === "contains" ? any : `(${expr} IS NULL OR NOT ${any})`;
1481
+ }
1482
+ function streamFilterSql(filter, leaf, depth = 0) {
1483
+ if (depth > MAX_FILTER_DEPTH) fail2("filter_too_deep", `a stream filter nests deeper than ${MAX_FILTER_DEPTH} levels`);
1484
+ if (!("rules" in filter)) return leaf(filter);
1485
+ if (filter.rules.length === 0) fail2("empty_filter", "a stream filter group has no rules");
1486
+ return `(${filter.rules.map((rule) => streamFilterSql(rule, leaf, depth + 1)).join(filter.op === "and" ? " AND " : " OR ")})`;
1487
+ }
1488
+ var DIMENSIONS = /* @__PURE__ */ Symbol("model dimensions");
1489
+ function withStreamDimensions(model) {
1490
+ const dimByKey = new Map(model.dimensions.map((d) => [d.key, d]));
1491
+ return { ...model, streams: model.streams.map((s) => ({ ...s, [DIMENSIONS]: dimByKey })) };
1492
+ }
1493
+ function filteredAlias(stream) {
1494
+ return quoteIdent(`w__${stream.key}`);
1495
+ }
1496
+ function sourceOf(stream) {
1497
+ if (!stream.where) return quoteIdent(stream.table);
1498
+ const dims = stream[DIMENSIONS] ?? fail2("unknown_dimension", `stream "${stream.key}" was read without its model`);
1499
+ const row = quoteIdent("__w");
1500
+ const joins = /* @__PURE__ */ new Map();
1501
+ const dimension = (key) => dims.get(key) ?? fail2("unknown_dimension", `no dimension "${String(key)}"`);
1502
+ const codeOf = (key, depth = 0) => {
1503
+ if (depth > 20) fail2("unknown_dimension", `the via chain of "${key}" does not end`);
1504
+ const direct = stream.dimension_keys[key];
1505
+ if (direct !== void 0) return `${row}.${quoteIdent(direct)}`;
1506
+ const dim = dimension(key);
1507
+ if (!dim.via) fail2("dimension_not_on_stream", `stream "${stream.key}" has no "${key}" for its filter`);
1508
+ const parent = dimension(dim.via.dimension);
1509
+ return `${joined(parent, codeOf(parent.key, depth + 1))}.${quoteIdent(dim.via.column)}`;
1510
+ };
1511
+ const joined = (dim, code) => {
1512
+ if (!dim.table || !dim.code) fail2("dimension_has_no_table", `"${dim.key}" has no table to read from`);
1513
+ const a = quoteIdent(`__w_${dim.key}`);
1514
+ if (!joins.has(a)) joins.set(a, `LEFT JOIN ${quoteIdent(dim.table)} AS ${a} ON ${a}.${quoteIdent(dim.code)} = ${code}`);
1515
+ return a;
1516
+ };
1517
+ const resolve = (dimKey, property) => {
1518
+ const code = codeOf(dimKey);
1519
+ if (property === "code") return code;
1520
+ const dim = dimension(dimKey);
1521
+ const column = property === "name" ? dim.name : dim.properties.find((p) => p.key === property)?.column;
1522
+ if (column === void 0) fail2("unknown_property", `"${dim.key}" has no property "${String(property)}"`);
1523
+ return `${joined(dim, code)}.${quoteIdent(column)}`;
1524
+ };
1525
+ const cond = streamFilterSql(stream.where, (rule) => dimensionRuleSql(rule, resolve));
1526
+ return `(${[`SELECT ${row}.* FROM ${quoteIdent(stream.table)} AS ${row}`, ...joins.values(), `WHERE ${cond}`].join(" ")}) AS ${filteredAlias(stream)}`;
1527
+ }
1398
1528
  function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
1399
1529
  const stream = model.streams.find((s) => s.key === view.stream) ?? fail2("unknown_stream", `no stream "${String(view.stream)}"`);
1400
1530
  const dimByKey = new Map(model.dimensions.map((d) => [d.key, d]));
@@ -1468,7 +1598,6 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
1468
1598
  const mb = withMembers ? membersOf() : null;
1469
1599
  const where = [];
1470
1600
  const focus = [];
1471
- const inList = (values) => `(${values.map(sqlValue).join(", ")})`;
1472
1601
  (view.path ?? []).forEach((step) => {
1473
1602
  const values = stringList(step?.selected, `the drill step on "${String(step?.dimension)}"`);
1474
1603
  const kept = `CAST(${codeOf(step.dimension)} AS VARCHAR) IN ${inList(values)}`;
@@ -1505,21 +1634,7 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
1505
1634
  const dimensionLeafWith = (resolve) => (rule) => {
1506
1635
  if (isMemberRule(rule)) return memberLeaf(rule, resolve(rule.dimension, "code"));
1507
1636
  if ("measure" in rule) fail2("measure_filter_unsupported", "a measure rule cannot sit in a group of dimension rules");
1508
- const whole = rule.cmp === "in" || rule.cmp === "not_in";
1509
- if (!whole && rule.cmp !== "contains" && rule.cmp !== "not_contains") fail2("empty_filter", `"${String(rule.cmp)}" is not a filter comparison`);
1510
- const expr = resolve(rule.dimension, rule.property ?? "code");
1511
- const what = `the filter on "${String(rule.dimension)}"`;
1512
- const values = stringList(rule.values, what);
1513
- if (whole) {
1514
- return rule.cmp === "in" ? `CAST(${expr} AS VARCHAR) IN ${inList(values)}` : `(${expr} IS NULL OR CAST(${expr} AS VARCHAR) NOT IN ${inList(values)})`;
1515
- }
1516
- const found = values.map((text) => {
1517
- if (text === "") fail2("empty_selection", `${what} holds an empty text to look for`);
1518
- if (text.length > MAX_KEYWORD_CHARS) fail2("keyword_too_long", `${what} holds a text longer than ${MAX_KEYWORD_CHARS} characters`);
1519
- return `CAST(${expr} AS VARCHAR) ILIKE ${sqlValue(likePattern(text))} ESCAPE '\\'`;
1520
- });
1521
- const any = `(${found.join(" OR ")})`;
1522
- return rule.cmp === "contains" ? any : `(${expr} IS NULL OR NOT ${any})`;
1637
+ return dimensionRuleSql(rule, resolve);
1523
1638
  };
1524
1639
  const dimensionLeaf = dimensionLeafWith(propertyOf);
1525
1640
  const measureLeaf = (rule) => {
@@ -1567,6 +1682,12 @@ function scopeOf(model, view, ctx, withMembers = false, splitFocus = false) {
1567
1682
  }
1568
1683
  }
1569
1684
  }
1685
+ const streamWhere = stream.where;
1686
+ if (mb && streamWhere) {
1687
+ const answerable = (f) => "rules" in f ? f.rules.every(answerable) : mb.reaches(f.dimension);
1688
+ const parts2 = "rules" in streamWhere && streamWhere.op === "and" ? streamWhere.rules.filter(answerable) : answerable(streamWhere) ? [streamWhere] : [];
1689
+ parts2.forEach((part) => mb.conds.push(streamFilterSql(part, (rule) => dimensionRuleSql(rule, mb.propertyHere))));
1690
+ }
1570
1691
  const keyword = typeof view.keyword === "string" ? view.keyword.trim() : "";
1571
1692
  if (keyword.length > MAX_KEYWORD_CHARS) fail2("keyword_too_long", `the keyword is longer than ${MAX_KEYWORD_CHARS} characters`);
1572
1693
  if (keyword !== "") {
@@ -1704,7 +1825,7 @@ function measureOver(src, key, slice, depth = 0) {
1704
1825
  function factOver(stream, range, latest) {
1705
1826
  const date = quoteIdent(stream.date);
1706
1827
  const within = `${date} >= ${sqlDate(range.from)} AND ${date} < ${sqlDate(range.to)}`;
1707
- return latest ? withLatestDay(quoteIdent(stream.table), date, "", within) : `(SELECT * FROM ${quoteIdent(stream.table)} WHERE ${within}) AS ${FACT}`;
1828
+ return latest ? withLatestDay(sourceOf(stream), date, "", within) : `(SELECT * FROM ${sourceOf(stream)} WHERE ${within}) AS ${FACT}`;
1708
1829
  }
1709
1830
  function withLatestDay(table, date, columns, where) {
1710
1831
  return `(SELECT *${columns}, (${date} = (SELECT MAX(${date}) FROM ${table} WHERE ${where})) AS "__lastw" FROM ${table} WHERE ${where}) AS ${FACT}`;
@@ -1720,10 +1841,26 @@ function withLatestDayOfEach(table, date, columns, where, windows) {
1720
1841
  });
1721
1842
  return `(SELECT *${columns}, ${flags.join(", ")} FROM ${table} WHERE ${where}) AS ${FACT}`;
1722
1843
  }
1844
+ function shiftedWindow(window, shift) {
1845
+ const s = typeof shift === "object" && shift !== null ? shift : {};
1846
+ const days = s.days;
1847
+ if (typeof days !== "number" || !Number.isInteger(days) || Math.abs(days) > MAX_SHIFT_DAYS) {
1848
+ fail2("option_unsupported", `a shifted comparison needs "days", a whole number of days within ${MAX_SHIFT_DAYS} either way`);
1849
+ }
1850
+ const length = s.length_days ?? daysBetween(window.from, window.to);
1851
+ if (typeof length !== "number" || !Number.isInteger(length) || length < 1 || length > MAX_SHIFT_DAYS) {
1852
+ fail2("option_unsupported", `"length_days" is a whole number of days from 1 to ${MAX_SHIFT_DAYS}`);
1853
+ }
1854
+ const from = addDays(window.from, days);
1855
+ return { from, to: addDays(from, length) };
1856
+ }
1723
1857
  function comparedWith(model, view, ctx, window) {
1724
1858
  const compare = view.compare ?? "previous_year";
1725
1859
  let comparison;
1726
- if (typeof compare === "object" && compare !== null) {
1860
+ if (typeof compare === "object" && compare !== null && "shift" in compare) {
1861
+ if ("period" in compare) fail2("option_unsupported", "a comparison takes a period or a shift, not both");
1862
+ comparison = shiftedWindow(window, compare.shift);
1863
+ } else if (typeof compare === "object" && compare !== null) {
1727
1864
  if (typeof compare.period !== "object" || compare.period === null) fail2("option_unsupported", "a comparison given as an object needs a period");
1728
1865
  comparison = resolvePeriod(compare.period, model.periods, ctx.today, { periodToDate: view.options?.period_to_date === true }).window;
1729
1866
  } else {
@@ -1739,7 +1876,7 @@ function comparedWith(model, view, ctx, window) {
1739
1876
  }
1740
1877
  function factAcross(stream, range, buckets, comparison, latest, earlier = []) {
1741
1878
  if (buckets.length === 0 && !comparison) return factOver(stream, range, latest);
1742
- const table = quoteIdent(stream.table);
1879
+ const table = sourceOf(stream);
1743
1880
  const date = quoteIdent(stream.date);
1744
1881
  const inWindow = (w) => `${date} >= ${sqlDate(w.from)} AND ${date} < ${sqlDate(w.to)}`;
1745
1882
  if (!comparison) {
@@ -1999,7 +2136,7 @@ function compileGrouped(model, view, ctx) {
1999
2136
  const measured = columns.filter((c) => c.kind === "measure").map((c) => c.name);
2000
2137
  const figures = shown.flatMap((m) => previous ? [`m__${m.key}`, `prev__${m.key}`] : [`m__${m.key}`]);
2001
2138
  const periodOf = (parts2) => perBucket(date, parts2, (_, i) => i + 1);
2002
- const fact = !uses.has("snapshot") ? `(SELECT *${factColumns} FROM ${quoteIdent(stream.table)} WHERE ${factWhere}) AS ${FACT}` : buckets.length === 0 && !comparison ? withLatestDay(quoteIdent(stream.table), date, factColumns, factWhere) : !comparison ? withLatestDays(quoteIdent(stream.table), date, periodOf(buckets), factColumns, factWhere) : withLatestDayOfEach(quoteIdent(stream.table), date, factColumns, factWhere, [
2139
+ const fact = !uses.has("snapshot") ? `(SELECT *${factColumns} FROM ${sourceOf(stream)} WHERE ${factWhere}) AS ${FACT}` : buckets.length === 0 && !comparison ? withLatestDay(sourceOf(stream), date, factColumns, factWhere) : !comparison ? withLatestDays(sourceOf(stream), date, periodOf(buckets), factColumns, factWhere) : withLatestDayOfEach(sourceOf(stream), date, factColumns, factWhere, [
2003
2140
  { where: inWindow(period.window), flag: "__lastc", ...periodVariance ? { periods: { by: periodOf(buckets), flag: "__last" } } : {} },
2004
2141
  { where: inWindow(comparison), flag: "__lastp", ...periodVariance ? { periods: { by: periodOf(earlierBuckets), flag: "__plast" } } : {} }
2005
2142
  ]);
@@ -2204,7 +2341,7 @@ function compileCustom(model, view, ctx) {
2204
2341
  const { limit, offset } = pageOf(view, ctx, (totalRow ? 1 : 0) + (averageRow ? 1 : 0) + (sumRow ? 1 : 0));
2205
2342
  const flags = `, ${windows.map((w, i) => `(${inWindow(w)}) AS ${quoteIdent(`__w${i + 1}`)}`).join(", ")}`;
2206
2343
  const anyWindow = windows.map((w) => `(${inWindow(w)})`).join(" OR ");
2207
- 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}`;
2344
+ const fact = uses.has("snapshot") ? withLatestDayOfEach(sourceOf(stream), date, flags, anyWindow, windows.map((w, i) => ({ where: inWindow(w), flag: `__l${i + 1}` }))) : `(SELECT *${flags} FROM ${sourceOf(stream)} WHERE ${anyWindow}) AS ${FACT}`;
2208
2345
  const streamKeys = [stream.key, ...model.streams.map((s) => s.key).filter((key) => key !== stream.key && reading.has(key))];
2209
2346
  const stages = !multi ? [] : streamKeys.map((key) => {
2210
2347
  const { scope: s, reads: r, windows: used } = readsOf(key);
@@ -2225,7 +2362,7 @@ function compileCustom(model, view, ctx) {
2225
2362
  const sIn = (w) => `${sDate} >= ${sqlDate(w.from)} AND ${sDate} < ${sqlDate(w.to)}`;
2226
2363
  const sFlags = mine.map((n) => `(${sIn(windows[n - 1])}) AS ${quoteIdent(`__w${n}`)}`).join(", ");
2227
2364
  const sAny = mine.map((n) => `(${sIn(windows[n - 1])})`).join(" OR ");
2228
- 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}`;
2365
+ const from = mine.length === 0 ? factOver(s.stream, own, false) : r.uses.has("snapshot") ? withLatestDayOfEach(sourceOf(s.stream), sDate, `, ${sFlags}`, sAny, mine.map((n) => ({ where: sIn(windows[n - 1]), flag: `__l${n}` }))) : `(SELECT *, ${sFlags} FROM ${sourceOf(s.stream)} WHERE ${sAny}) AS ${FACT}`;
2229
2366
  const groupBy = levels ? levels.groupBy(totalRow) : totalRow ? `GROUP BY GROUPING SETS ((${s.codeExpr}), ())` : `GROUP BY ${s.codeExpr}`;
2230
2367
  return { select: parts2, from, joins: [...s.joins.values()], where: s.where, groupBy };
2231
2368
  });
@@ -2331,7 +2468,7 @@ function compileTransactions(model, view, ctx) {
2331
2468
  const sql = [
2332
2469
  "WITH g AS (",
2333
2470
  `SELECT ${select.join(", ")}`,
2334
- `FROM (SELECT * FROM ${quoteIdent(stream.table)} WHERE ${date} >= ${sqlDate(period.window.from)} AND ${date} < ${sqlDate(period.window.to)}) AS ${FACT}`,
2471
+ `FROM (SELECT * FROM ${sourceOf(stream)} WHERE ${date} >= ${sqlDate(period.window.from)} AND ${date} < ${sqlDate(period.window.to)}) AS ${FACT}`,
2335
2472
  ...scope.joins.values(),
2336
2473
  ...scope.where.length > 0 ? [`WHERE ${scope.where.join(" AND ")}`] : [],
2337
2474
  "), r AS (",
@@ -2712,7 +2849,7 @@ function compileMatrix(model, view, ctx, byPeriod = false, streams = false) {
2712
2849
  const numbered = perBucket(date, buckets, (_, i) => i + 1);
2713
2850
  const added = `, ${numbered} AS "__b"${perDay}`;
2714
2851
  const within = `${date} >= ${sqlDate(range.from)} AND ${date} < ${sqlDate(range.to)}`;
2715
- fact = uses.has("snapshot") ? withLatestDays(quoteIdent(stream.table), date, numbered, added, within) : `(SELECT *${added} FROM ${quoteIdent(stream.table)} WHERE ${within}) AS ${FACT}`;
2852
+ fact = uses.has("snapshot") ? withLatestDays(sourceOf(stream), date, numbered, added, within) : `(SELECT *${added} FROM ${sourceOf(stream)} WHERE ${within}) AS ${FACT}`;
2716
2853
  }
2717
2854
  const paged = `rw."__row" > ${offset} AND rw."__row" <= ${offset + limit}`;
2718
2855
  const beside = totalRow ? 'g."__total" = 1' : columnTotals ? '(g."__total" = 1 AND g."__across_total" = 0)' : null;
@@ -2854,6 +2991,7 @@ export {
2854
2991
  FORMULA_FUNCTIONS,
2855
2992
  FORMULA_MAX_CHARS,
2856
2993
  MAX_PERIOD_BUCKETS,
2994
+ MAX_STREAM_FILTER_DEPTH,
2857
2995
  MEASURE_AGGS,
2858
2996
  MEASURE_CMPS,
2859
2997
  MEASURE_FORMATS,
@@ -2866,6 +3004,7 @@ export {
2866
3004
  ROUTE_MAX_ROWS,
2867
3005
  ROUTE_MAX_SQL_CHARS,
2868
3006
  ReportingError,
3007
+ STREAM_FILTER_CMPS,
2869
3008
  VARIANCE_PARTS,
2870
3009
  VIEW_MODES,
2871
3010
  addDays,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sprigr/apps-reporting-core",
3
- "version": "0.0.12",
3
+ "version": "0.0.14",
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",