@sprigr/apps-reporting-core 0.0.8 → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +2 -2
  2. package/dist/index.js +49 -25
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -80,7 +80,7 @@ Modes `total`, `period`, `variance`, `period_variance`, `transaction`, `stream`,
80
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
81
  - **A period, variance or period 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, a variance its current, earlier, variance and variance percentage columns, and a period variance those four for every period beside the same period of the comparison window, 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. A custom view reads one through its points, below.
82
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. A matrix may read a measure of another stream, such as ordered beside sales: each stream groups the same four ways in its own stage, under the same drill path, filters and keyword, and the stages are folded by cell, so a formula that mixes streams is worked out at every level from the folded sums. Every stream read must carry both dimensions, and `streams` in the result lists them.
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
+ - **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 that mixes streams, such as a fill rate of sales over ordered, is read as one point per measure it names, each on its own stream under the point's dates and rule, and the formula is worked out from those points. With nested rows, every level is grouped in each stream's stage, so each stream must carry every level.
84
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.
85
85
  - **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.
86
86
  - **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.
@@ -88,7 +88,7 @@ Modes `total`, `period`, `variance`, `period_variance`, `transaction`, `stream`,
88
88
  - **The average row** (`options.average_row`, same modes as the sum row): the plain mean of each measure column over the member rows of the list, on every page, after any filter on a measure. Blanks are skipped.
89
89
  - **The average column** (`options.average_column`, period mode with one column per period): one more column a measure, the mean of that measure's period columns on the same row, so the total row holds the mean of the period totals. A period with no value is skipped, not counted as zero. `sort.by` takes `average.<measure>`. Other modes ignore the option.
90
90
  - **Hiding zero rows** (`options.hide_zero_rows`, every grouped mode): leaves out a member whose every shown measure is zero or blank over the whole period, and in a variance over the earlier period too. Sales that net to zero are hidden even when single periods are not zero. The total row still counts those members; the row count and the average row do not.
91
- - **Nested rows** (`levels`, modes `total`, `period` with one column per period, `variance`, `period_variance`, `stream` and `custom`): up to five dimensions above `group_by`, the outermost first, such as branch, then department, then product as the rows. Each member of a level gets a row of its own, the subtotal of the rows beneath it, with formulas worked out from its own sums. Every level is grouped in the same pass as the rows, so it is still one statement. A row comes right after the row it sits under. Each level is ordered by its own figure in the column the view is sorted on, or by its code when the sort is on the code or a property. The result has `lv<n>` for each level's code and `lvn<n>` for its name where the dimension has one (`kind: 'level'`, with `level` and `dimension`), and `__level`: 1 on the outermost level's rows, one more on each level below, and 0 on the total row. `code` and the properties are blank on a level's row. `limit`, `offset` and `__rows` count every row, level rows included, so a page can start part way down a level. The total row works as in total mode. Not compiled with nested rows yet: the activity option, the others, average and sum rows, hiding zero rows, a filter on a measure, matrix mode, a custom view of more than one stream, and the long shape of a period view. A view of more than one stream groups every level in each stream's own stage, so each stream must carry every level. Opening one row of a nested grid needs no nested statement: it is a plain view grouped by the next dimension with a path step on the row opened. The nested statement is for showing every level at once, as an export or an emailed report does.
91
+ - **Nested rows** (`levels`, modes `total`, `period` with one column per period, `variance`, `period_variance`, `stream` and `custom`): up to five dimensions above `group_by`, the outermost first, such as branch, then department, then product as the rows. Each member of a level gets a row of its own, the subtotal of the rows beneath it, with formulas worked out from its own sums. Every level is grouped in the same pass as the rows, so it is still one statement. A row comes right after the row it sits under. Each level is ordered by its own figure in the column the view is sorted on, or by its code when the sort is on the code or a property. The result has `lv<n>` for each level's code and `lvn<n>` for its name where the dimension has one (`kind: 'level'`, with `level` and `dimension`), and `__level`: 1 on the outermost level's rows, one more on each level below, and 0 on the total row. `code` and the properties are blank on a level's row. `limit`, `offset` and `__rows` count every row, level rows included, so a page can start part way down a level. The total row works as in total mode. Not compiled with nested rows yet: the activity option, the others, average and sum rows, hiding zero rows, a filter on a measure, matrix mode, and the long shape of a period view. A view of more than one stream groups every level in each stream's own stage, so each stream must carry every level. Opening one row of a nested grid needs no nested statement: it is a plain view grouped by the next dimension with a path step on the row opened. The nested statement is for showing every level at once, as an export or an emailed report does.
92
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.
93
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.
94
94
 
package/dist/index.js CHANGED
@@ -1950,20 +1950,24 @@ function compileCustom(model, view, ctx) {
1950
1950
  }
1951
1951
  return found;
1952
1952
  };
1953
- const streamOf = (measure, depth = 0) => {
1954
- if (!isFormulaMeasure(measure)) return measure.stream;
1955
- const first = depth > 20 ? void 0 : formulaRefs(parseFormula(measure.formula)).map((ref) => measureByKey.get(ref)).find((m) => m !== void 0);
1956
- return first === void 0 ? stream.key : streamOf(first, depth + 1);
1953
+ const streamsOf = (measure, depth = 0) => {
1954
+ if (!isFormulaMeasure(measure)) return /* @__PURE__ */ new Set([measure.stream]);
1955
+ const found = /* @__PURE__ */ new Set();
1956
+ if (depth <= 20) {
1957
+ formulaRefs(parseFormula(measure.formula)).forEach((ref) => {
1958
+ const named = measureByKey.get(ref);
1959
+ if (named) streamsOf(named, depth + 1).forEach((key) => found.add(key));
1960
+ });
1961
+ }
1962
+ return found.size > 0 ? found : /* @__PURE__ */ new Set([stream.key]);
1957
1963
  };
1958
1964
  const points = [];
1959
1965
  const pointOf = (point, what) => {
1960
1966
  if (typeof point !== "object" || point === null) fail("bad_custom_column", `${what} has no data point`);
1961
1967
  const measure = measureByKey.get(point.measure) ?? fail("unknown_measure", `no measure "${String(point.measure)}"`);
1962
1968
  const { window, number } = windowOf(point.period);
1963
- 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`);
1964
- const src = readsOf(streamOf(measure));
1965
- src.windows.add(number);
1966
- const rule = point.where === void 0 ? "" : ` AND ${src.scope.dimensionRule(point.where)}`;
1969
+ const where2 = point.where;
1970
+ if (where2 !== void 0 && (typeof where2 !== "object" || where2 === null || "measure" in where2)) fail("bad_custom_column", `the rule of ${what} is not a dimension rule`);
1967
1971
  const bucket = {
1968
1972
  key: `w${number}`,
1969
1973
  label: `${window.from} to ${addDays(window.to, -1)}`,
@@ -1971,11 +1975,25 @@ function compileCustom(model, view, ctx) {
1971
1975
  to: window.to,
1972
1976
  days: daysBetween(window.from, window.to)
1973
1977
  };
1974
- const slice = { bucket, filter: `${FACT}.${quoteIdent(`__w${number}`)}${rule}`, last: `${FACT}.${quoteIdent(`__l${number}`)}${rule}` };
1975
- const sql2 = `CAST(${measureOver(src.reads, measure.key, slice)} AS DOUBLE)`;
1976
- const key = src.scope.stream.key;
1977
- const at = points.findIndex((p) => p.stream === key && p.sql === sql2);
1978
- return { name: `p${at >= 0 ? at + 1 : points.push({ stream: key, sql: sql2 })}`, measure, bucket };
1978
+ const read = (m, depth) => {
1979
+ const streams = streamsOf(m);
1980
+ if (streams.size > 1 && isFormulaMeasure(m)) {
1981
+ if (depth > 20) fail("formula_cycle", `"${m.key}" refers back to itself`);
1982
+ return emitFormulaSql(parseFormula(m.formula), {
1983
+ measure: (ref) => read(measureByKey.get(ref) ?? fail("formula_unknown_measure", `"${ref}" is not a measure`), depth + 1),
1984
+ days: bucket.days
1985
+ });
1986
+ }
1987
+ const src = readsOf([...streams][0] ?? stream.key);
1988
+ src.windows.add(number);
1989
+ const rule = where2 === void 0 ? "" : ` AND ${src.scope.dimensionRule(where2)}`;
1990
+ const slice = { bucket, filter: `${FACT}.${quoteIdent(`__w${number}`)}${rule}`, last: `${FACT}.${quoteIdent(`__l${number}`)}${rule}` };
1991
+ const sql2 = `CAST(${measureOver(src.reads, m.key, slice)} AS DOUBLE)`;
1992
+ const key = src.scope.stream.key;
1993
+ const at = points.findIndex((p) => p.stream === key && p.sql === sql2);
1994
+ return quoteIdent(`p${at >= 0 ? at + 1 : points.push({ stream: key, sql: sql2 })}`);
1995
+ };
1996
+ return { ref: read(measure, 0), measure, bucket };
1979
1997
  };
1980
1998
  const columns = [...nest?.columns ?? [], { name: "code", kind: "code", label: groupDim.label }];
1981
1999
  const select = [...nest?.select ?? [], `${codeExpr} AS "code"`];
@@ -2001,13 +2019,13 @@ function compileCustom(model, view, ctx) {
2001
2019
  const cur = pointOf(column.point, `"${key}"`);
2002
2020
  if (column.against === void 0) {
2003
2021
  if (column.show !== void 0) fail("bad_custom_column", `"${key}" has "show" and no second point to compare against`);
2004
- expr = quoteIdent(cur.name);
2022
+ expr = cur.ref;
2005
2023
  about = { label: column.label ?? cur.measure.label, measure: cur.measure.key, format: cur.measure.format, period: cur.bucket };
2006
2024
  } else {
2007
2025
  const prev = pointOf(column.against, `"${key}"`);
2008
2026
  const show = column.show ?? "difference";
2009
2027
  if (show !== "difference" && show !== "percent") fail("bad_custom_column", `"${String(show)}" is not a way to show a comparison`);
2010
- expr = show === "difference" ? `COALESCE(${quoteIdent(cur.name)}, 0) - COALESCE(${quoteIdent(prev.name)}, 0)` : `(COALESCE(${quoteIdent(cur.name)}, 0) - ${quoteIdent(prev.name)}) / NULLIF(abs(${quoteIdent(prev.name)}), 0)`;
2028
+ expr = show === "difference" ? `COALESCE(${cur.ref}, 0) - COALESCE(${prev.ref}, 0)` : `(COALESCE(${cur.ref}, 0) - ${prev.ref}) / NULLIF(abs(${prev.ref}), 0)`;
2011
2029
  about = {
2012
2030
  label: column.label ?? `${cur.measure.label} ${show === "difference" ? "Variance" : "Variance %"}`,
2013
2031
  measure: cur.measure.key,
@@ -2022,7 +2040,7 @@ function compileCustom(model, view, ctx) {
2022
2040
  expr = emitFormulaSql(parseFormula(String(column.expression)), {
2023
2041
  measure: (ref) => {
2024
2042
  if (!Object.prototype.hasOwnProperty.call(named, ref)) fail("bad_custom_column", `"${key}" reads "${ref}", which is not one of its points`);
2025
- return quoteIdent(pointOf(named[ref], `point "${ref}" of "${key}"`).name);
2043
+ return pointOf(named[ref], `point "${ref}" of "${key}"`).ref;
2026
2044
  },
2027
2045
  days: reads.days
2028
2046
  });
@@ -2037,7 +2055,6 @@ function compileCustom(model, view, ctx) {
2037
2055
  if (measured.length === 0) fail("bad_custom_column", "every column of the view is hidden");
2038
2056
  if (points.length === 0) fail("bad_custom_column", "no column of the view reads a data point");
2039
2057
  const multi = reading.size > 1;
2040
- if (multi && nest) fail("option_unsupported", "nested rows are not compiled for a custom view of more than one stream yet");
2041
2058
  points.forEach(({ sql: sql2 }, i) => {
2042
2059
  select.push(`${sql2} AS ${quoteIdent(`p${i + 1}`)}`);
2043
2060
  left.push(`p${i + 1}`);
@@ -2064,31 +2081,38 @@ function compileCustom(model, view, ctx) {
2064
2081
  const stages = !multi ? [] : streamKeys.map((key) => {
2065
2082
  const { scope: s, reads: r, windows: used } = readsOf(key);
2066
2083
  const grouped = `GROUPING(${s.codeExpr})`;
2067
- const parts2 = [`${s.codeExpr} AS "code"`];
2084
+ const levels = nest ? nestOf(view, s) : null;
2085
+ const parts2 = [...levels?.select ?? [], `${s.codeExpr} AS "code"`];
2068
2086
  shownProperties(view).forEach((property) => {
2069
2087
  const expr = `any_value(${s.propertyOf(groupDim.key, property)})`;
2070
- parts2.push(`${totalRow ? `CASE WHEN ${grouped} = 0 THEN ${expr} END` : expr} AS ${quoteIdent(`prop__${property}`)}`);
2088
+ parts2.push(`${totalRow || levels ? `CASE WHEN ${grouped} = 0 THEN ${expr} END` : expr} AS ${quoteIdent(`prop__${property}`)}`);
2071
2089
  });
2072
2090
  points.forEach((p, i) => {
2073
2091
  if (p.stream === key) parts2.push(`${p.sql} AS ${quoteIdent(`p${i + 1}`)}`);
2074
2092
  });
2075
- parts2.push(`${totalRow ? `CAST(${grouped} AS INTEGER)` : "0"} AS "__total"`);
2093
+ parts2.push(`${totalRow ? `CAST(${levels ? levels.total : grouped} AS INTEGER)` : "0"} AS "__total"`);
2094
+ if (levels) parts2.push(levels.level);
2076
2095
  const mine = [...used].sort((a, b) => a - b);
2077
2096
  const sDate = quoteIdent(s.stream.date);
2078
2097
  const sIn = (w) => `${sDate} >= ${sqlDate(w.from)} AND ${sDate} < ${sqlDate(w.to)}`;
2079
2098
  const sFlags = mine.map((n) => `(${sIn(windows[n - 1])}) AS ${quoteIdent(`__w${n}`)}`).join(", ");
2080
2099
  const sAny = mine.map((n) => `(${sIn(windows[n - 1])})`).join(" OR ");
2081
2100
  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}`;
2082
- return { select: parts2, from, joins: [...s.joins.values()], where: s.where, groupBy: totalRow ? `GROUP BY GROUPING SETS ((${s.codeExpr}), ())` : `GROUP BY ${s.codeExpr}` };
2101
+ const groupBy = levels ? levels.groupBy(totalRow) : totalRow ? `GROUP BY GROUPING SETS ((${s.codeExpr}), ())` : `GROUP BY ${s.codeExpr}`;
2102
+ return { select: parts2, from, joins: [...s.joins.values()], where: s.where, groupBy };
2083
2103
  });
2104
+ const anyOf = (name) => `any_value(${quoteIdent(name)}) AS ${quoteIdent(name)}`;
2084
2105
  const fold = [
2106
+ ...(nest?.columns ?? []).map((c) => c.property === "name" ? anyOf(c.name) : quoteIdent(c.name)),
2085
2107
  '"code"',
2086
- ...shownProperties(view).map((property) => `any_value(${quoteIdent(`prop__${property}`)}) AS ${quoteIdent(`prop__${property}`)}`),
2087
- ...points.map((_, i) => `any_value(${quoteIdent(`p${i + 1}`)}) AS ${quoteIdent(`p${i + 1}`)}`),
2088
- '"__total"'
2108
+ ...shownProperties(view).map((property) => anyOf(`prop__${property}`)),
2109
+ ...points.map((_, i) => anyOf(`p${i + 1}`)),
2110
+ '"__total"',
2111
+ ...nest ? ['"__level"'] : []
2089
2112
  ];
2113
+ const foldKeys = [...nest ? Array.from({ length: nest.count }, (_, i) => quoteIdent(`lv${i + 1}`)) : [], '"code"', '"__total"', ...nest ? ['"__level"'] : []];
2090
2114
  const sql = [
2091
- ...multi ? foldStreams(stages, fold, ['"code"', '"__total"']) : [
2115
+ ...multi ? foldStreams(stages, fold, foldKeys) : [
2092
2116
  "WITH g AS (",
2093
2117
  `SELECT ${select.join(", ")}`,
2094
2118
  `FROM ${fact}`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sprigr/apps-reporting-core",
3
- "version": "0.0.8",
3
+ "version": "0.0.9",
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",