Download web/src/customer-grid/aggregations.ts from fsanyoto/loopable: direct link, hf CLI and curl.
- Browser
- Download file 28.9 kB
-
https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/customer-grid/aggregations.ts
- Command line
-
hf download hf://spaces/fsanyoto/loopable/web/src/customer-grid/aggregations.ts
-
curl -L -o aggregations.ts https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/customer-grid/aggregations.ts
28.9 kB
| // --------------------------------------------------------------------------- | |
| // customer-grid / aggregations.ts | |
| // COLUMN SUMMARIES β the per-group subtotal AND the table's own totals row. | |
| // `computeAggs` folds every field carrying an `agg` over a bucket of rows and | |
| // returns fieldKey -> formatted display string. Non-agg fields are simply | |
| // absent from the map, so the footer renderer draws them blank. | |
| // | |
| // Called ONCE per group inside the useVisibleRows memo (never per cell/frame); | |
| // the resulting object is shared by that group's header and footer, and once | |
| // more for the ungrouped totals row. | |
| // --------------------------------------------------------------------------- | |
| import { isNumericFieldType } from "./types"; | |
| // β ONE numeric reading of a stored cell, shared with the CANVAS renderer β see its | |
| // note. Two copies is how a cell painted blank while the total under it counted 1,234.50. | |
| import { numberText, numericOrUndefined } from "./display"; | |
| import type { | |
| AggName, Field, Row, SummaryAggName, SummaryChoice, SummaryMap, SummaryPickAgg, | |
| } from "./types"; | |
| // ββ W29-T74 β IMPORTED, NOT RE-DECLARED, which is what `iconShapes.ts` always claimed. | |
| import { | |
| FIELD_AGGS, FIELD_AGG_LABELS, SUMMARY_AGGS as WIRE_SUMMARY_AGGS, SUMMARY_AGG_LABELS, | |
| } from "./iconShapes"; | |
| /** | |
| * ββ WAVE-29 CONTRACT C7 β **THE CLIENT MIRROR of `platform/aios_grid.FIELD_AGGS`**, published | |
| * by session C and held in step by a parity gate. The ORDER is the picker's order. | |
| * | |
| * β THE MIRROR IS NOW AN IMPORT, AND UNTIL W29-T74 IT WAS A LIE. Both `iconShapes.ts:620` and | |
| * `aios_grid.py:1069` said *"ONE CLIENT LIST, IMPORTED β never re-declared"* while this file | |
| * re-declared it three lines later. Every runtime consumer (`ColumnMenu`, `CustomerGrid`, | |
| * `useVisibleRows`) imports `./aggregations`, so `iconShapes`' copy had ZERO importers and the | |
| * parity gate was diffing a literal no production file read, while the live list drifted free | |
| * ([[gate-answers-the-wrong-question]]). Re-exported under this module's own name so no call | |
| * site had to change β the fix is the import, not a rename cascade. | |
| * | |
| * β THREE VOCABULARIES EXIST AND THEY ARE NOT ONE LIST β merging them is the trap on this | |
| * contract: | |
| * Β· `FIELD_AGGS` (iconShapes + aios_grid + user_tables) a FIELD's `agg`: the column summary. | |
| * Β· `CHART_AGGS` (aios_grid, `avg`) STORED chart values with live data. Untouchable: | |
| * an unknown agg falls back to `sum` and drops a | |
| * calendar metric card, with nothing red. | |
| * Β· `ROLLUP_FNS` (user_tables, 16 names) rollup FOLDS. Overlaps; is not the same list. | |
| * | |
| * β `average`, not `avg`: `ROLLUP_FNS` already spells it that way and 47 rollups run on it in | |
| * production, so a column summary and a rollup fold name the same operation the same way. | |
| * β `median` is in NEITHER of the other two β it is net-new on both sides of this contract. | |
| */ | |
| export { FIELD_AGGS }; | |
| /** How each one reads in the picker. Sentence case, because it is a menu row, not a header. | |
| * β The NAME differs from its source on purpose: `viewModes.tsx` has a module-local `AGG_LABELS` | |
| * over `CHART_AGGS` where the same names wear different words, so the icon module's copy is | |
| * prefixed. This alias keeps this module's callers reading `AGG_LABELS` and keeps ONE table. */ | |
| export const AGG_LABELS: Record<AggName, string> = FIELD_AGG_LABELS; | |
| /** | |
| * What THIS column may be summarised by (C7's semantics, not a preference): | |
| * `sum Β· average Β· median Β· min Β· max` are numeric-only; `count` counts ROWS and so applies to | |
| * every type. Offering Sum on a text column would render a number nobody can reconcile. | |
| */ | |
| export function aggOptions(field: Field): readonly AggName[] { | |
| return isNumericFieldType(field.type) | |
| ? FIELD_AGGS | |
| : FIELD_AGGS.filter((a) => a === "count"); | |
| } | |
| /** | |
| * The numeric value of a cell, or `undefined` β blank and unparseable are NOT zero. | |
| * | |
| * β IMPORTED, NOT RE-DERIVED (W29-T81 follow-up). This function and `display.numericIsBlank` | |
| * are the same question asked by two surfaces β "is there a number in this cell" β and while | |
| * they were two implementations they answered differently: this one stripped `$` and `,`, the | |
| * renderer's only trimmed, so `"1,234.50"` was COUNTED in the totals row under a cell that | |
| * painted BLANK. The fold's normalisation was the correct one and is now the only one. | |
| */ | |
| const numOf = numericOrUndefined; | |
| function median(sorted: number[]): number { | |
| const mid = sorted.length >> 1; | |
| return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; | |
| } | |
| /** | |
| * ββ W50-T03 / C1 β LINEAR INTERPOLATION BETWEEN ORDER STATISTICS, which is what | |
| * `percentile_cont` computes in Postgres and DuckDB. The server half of C1 answers the same | |
| * question over the whole predicate; two different definitions of "p75" on the two engines | |
| * would make the bar's number change when a table crossed into read-through, with nothing red. | |
| * β p50 is therefore the SAME number `median` returns, by construction rather than by luck. | |
| */ | |
| function percentile(sorted: number[], p: number): number { | |
| if (sorted.length === 1) return sorted[0]; | |
| const at = (p / 100) * (sorted.length - 1); | |
| const lo = Math.floor(at); | |
| const hi = Math.ceil(at); | |
| return lo === hi ? sorted[lo] : sorted[lo] + (sorted[hi] - sorted[lo]) * (at - lo); | |
| } | |
| /** C1's `p` is 0-100. An absent or unreadable one is the median, never a throw. */ | |
| export function cleanPercent(p: number | undefined): number { | |
| if (typeof p !== "number" || !Number.isFinite(p)) return 50; | |
| return Math.max(0, Math.min(100, p)); | |
| } | |
| /** | |
| * ββ WAVE 51 Β· W51-T02 (owner ruling R3) β **THE PICKER'S VOCABULARY IS THE WIRE'S PLUS | |
| * `share`, AND IT IS DECLARED HERE RATHER THAN WHERE THE WIRE ONE LIVES.** | |
| * | |
| * β WHY THE DECLARATION MOVED (W50-T03 re-exported the icon array bare). C1's summary | |
| * vocabulary is EIGHT names and it exists twice β `iconShapes.SUMMARY_AGGS` and | |
| * `platform/aios_grid.SUMMARY_AGGS` β with `verify_grid_ux.py::summary_bar_shape` holding the | |
| * two byte-for-byte so neither engine can widen the wire alone. R3's "% of total" is a PICKER | |
| * choice, never a wire agg: its numerator and denominator are ordinary wire aggregates (a | |
| * numeric column's `sum`, anything else's `count`) and the division is client-side. Adding it to | |
| * either array would break that parity leg and would tell lane F's route to compile an | |
| * aggregate that does not exist in SQL. | |
| * | |
| * β AND THE TWO FILES IT WOULD OTHERWISE HAVE TO TOUCH BELONG TO OTHER LANES (`iconShapes.ts` to | |
| * lane C, `aios_grid.py` to lane B), so the wire array is IMPORTED under an alias and the | |
| * picker's array is spread out of it. One list still, plus one name this module owns β the | |
| * wire cannot drift, because nothing here writes to it. | |
| */ | |
| export const SUMMARY_AGGS: readonly SummaryPickAgg[] = [...WIRE_SUMMARY_AGGS, "share"]; | |
| /** The picker's words. `share` reads "% of total" (sentence case, DESIGN.md Β§2) and the other | |
| * eight come from the icon module's table unchanged, for the reason above: one table, extended | |
| * where the extra name is declared rather than where the wire one is. */ | |
| export const SUMMARY_LABELS: Record<SummaryPickAgg, string> = { | |
| ...SUMMARY_AGG_LABELS, | |
| share: "% of total", | |
| }; | |
| /** | |
| * ββ W50-T03 / OWNER RULING R2 β **WHAT THIS COLUMN MAY BE SUMMARISED BY, AND IT IS THE TYPE | |
| * FAMILY THAT DECIDES, NEVER THE KIND.** | |
| * | |
| * β THE ERROR-20 BLANK IN ONE SENTENCE: a `formula` column IS numeric (`isNumericFieldType` | |
| * covers currency, int, pct, rating, formula, metric and rollup) and rendered blank anyway, | |
| * because nothing had ever chosen an `agg` for it. Any list written kind-by-kind reproduces | |
| * that the first time a kind is added, so the eligibility test is the shared predicate and | |
| * there is no second one here. | |
| * | |
| * `count` and `count_distinct` read ROWS and VALUES rather than numbers, so they are legal on | |
| * every type; the six numeric folds are offered only where a number can exist. | |
| * | |
| * ββ W51-T02 / R3 β **`share` IS LEGAL ON EVERY TYPE, AND THAT IS THE RULING'S SECOND HALF.** | |
| * R3: *"the primary column: Count / % of total"*. A share of a text column is that group's ROW | |
| * COUNT over the view's, which is a question every column can answer; on a numeric column it is | |
| * that column's own SUM over the view's. So it joins the two counting aggregates in the | |
| * non-numeric arm rather than being filtered out with the six folds. | |
| */ | |
| export function summaryOptions(field: Field): readonly SummaryPickAgg[] { | |
| return isNumericFieldType(field.type) | |
| ? SUMMARY_AGGS | |
| : SUMMARY_AGGS.filter((a) => a === "count" || a === "count_distinct" || a === "share"); | |
| } | |
| /** Today's behaviour, unchanged, for every caller that has no view map to offer (the per-group | |
| * subtotals in `useVisibleRows` are the live one): the FIELD's own `agg`, or nothing. */ | |
| function legacyChoice(field: Field): SummaryChoice | null { | |
| const agg = field.agg as AggName | undefined; | |
| return agg && FIELD_AGGS.includes(agg) ? { agg } : null; | |
| } | |
| /** | |
| * ββ W50-T03 / R2 β **THE RESOLUTION ORDER, AND ALL THREE STEPS ARE LOAD-BEARING.** | |
| * | |
| * R2, verbatim: *"the bottom bar's aggregate is a view setting; numeric kinds (number, | |
| * currency, formula, Metric, rollup) default to Sum; text kinds default to none."* | |
| * | |
| * 1. the VIEW's own choice (`ViewConfig.summary[colId]`) β including an explicit `"none"`, | |
| * which is why `none` is a stored value and not an absent key; | |
| * 2. the FIELD's legacy `agg`, so every view saved through `ColumnMenu`'s older "Summarize | |
| * this column" control keeps rendering exactly what it rendered before, with no migration | |
| * and no write; | |
| * 3. R2's default β Sum on a numeric family, nothing on the rest. | |
| * | |
| * β NOTHING HERE WRITES. The default is computed at read time on purpose: stamping `sum` into | |
| * the view the first time a grid paints would make every table dirty on open, and would turn | |
| * R2's default into a stored choice that a later change of default could never reach. | |
| */ | |
| export function resolveSummary(field: Field, summary: SummaryMap): SummaryChoice { | |
| const picked = summary[field.key]; | |
| if (picked && (picked.agg === "none" || SUMMARY_AGGS.includes(picked.agg))) | |
| return picked.agg === "none" || summaryOptions(field).includes(picked.agg) | |
| ? picked : { agg: "none" }; | |
| const legacy = legacyChoice(field); | |
| if (legacy && legacy.agg !== "none" && summaryOptions(field).includes(legacy.agg)) return legacy; | |
| return isNumericFieldType(field.type) ? { agg: "sum" } : { agg: "none" }; | |
| } | |
| /** The word the bar prints for a resolved choice. Percentile carries its point ("p75"), because | |
| * a cell reading "Percentile" over four different columns says nothing about any of them. */ | |
| export function summaryLabel(choice: SummaryChoice): string { | |
| if (choice.agg === "none") return "None"; | |
| if (choice.agg === "percentile") return "p" + String(cleanPercent(choice.p)); | |
| return SUMMARY_LABELS[choice.agg]; | |
| } | |
| /** | |
| * Fold every field carrying an `agg` over `rows`, formatted to match its column: | |
| * currency -> "$" + toLocaleString | everything else -> toLocaleString | |
| * Values drop float noise at 15 significant digits (1234.5600000001) and are never rounded. | |
| * | |
| * β **BLANK, NEVER ZERO** (C7, and the codebase's standing law): a numeric fold over a set | |
| * holding no numeric value at all returns nothing and the cell stays empty β `0` is a | |
| * measurement and this is an admission that there was nothing to measure. Only `count` returns | |
| * `0`, because "no rows" genuinely is a count. This is also what `_rollup_fold` already does. | |
| * | |
| * β `count` counts ROWS IN SCOPE, not non-blank cells. `ROLLUP_FNS` splits that hair three ways | |
| * (`count`/`counta`/`countall`); a column summary does not, and must not grow a second spelling. | |
| */ | |
| /** | |
| * ββ W50-T04 β **THE SIX NUMERIC FOLDS, IN ONE PLACE, BECAUSE THERE ARE NOW TWO READERS.** | |
| * | |
| * `computeAggs` wants the fold DRESSED (a string wearing its column's unit); a group header's | |
| * share of the view total and Summary mode's sort want it RAW. Two copies of this chain is how | |
| * a bar reads `$1,204` while the share above it divides a differently-rounded number by a | |
| * differently-rounded total β the same class of defect `numericOrUndefined` was extracted for. | |
| * | |
| * β `count` and `count_distinct` never reach here: they read ROWS and VALUES, not numbers, and | |
| * both callers answer them before folding. The final `else` is `percentile` on purpose β it is | |
| * the only remaining member, and a `switch` with an unreachable default would be a lie. | |
| */ | |
| /** Neumaier compensated sum: a naive float sum over thousands of prices drifts past 15 digits. */ | |
| function exactSum(nums: number[]): number { | |
| let sum = 0; | |
| let carry = 0; | |
| for (const n of nums) { | |
| const t = sum + n; | |
| carry += Math.abs(sum) >= Math.abs(n) ? (sum - t) + n : (n - t) + sum; | |
| sum = t; | |
| } | |
| return sum + carry; | |
| } | |
| function foldNumeric(nums: number[], agg: SummaryAggName, p: number | undefined): number { | |
| if (agg === "sum") return exactSum(nums); | |
| if (agg === "average") return exactSum(nums) / nums.length; | |
| if (agg === "median") return median([...nums].sort((a, b) => a - b)); | |
| if (agg === "min") return Math.min(...nums); | |
| if (agg === "max") return Math.max(...nums); | |
| return percentile([...nums].sort((a, b) => a - b), cleanPercent(p)); | |
| } | |
| /** Every readable number in one column of `rows`. β ONE numeric reading (`numOf`), shared with | |
| * the canvas renderer β see this module's head note; two readings is how a cell painted blank | |
| * while the total under it counted 1,234.50. */ | |
| function numbersOf(rows: Row[], key: string): number[] { | |
| const nums: number[] = []; | |
| for (const r of rows) { | |
| const n = numOf(r[key]); | |
| if (n !== undefined) nums.push(n); | |
| } | |
| return nums; | |
| } | |
| /** | |
| * ββ W51-T02 / R3 β **WHAT A `share` DIVIDES, AND IT IS ONE FUNCTION SO A NUMERATOR AND A | |
| * DENOMINATOR CANNOT BE MEASURED TWO DIFFERENT WAYS.** | |
| * | |
| * A numeric column's share is its own SUM over the view's sum. Every other column's β the | |
| * primary key column above all, which is instruction 4's whole subject β is that bucket's ROW | |
| * COUNT over the view's row count, because a column of text has no quantity to add up. | |
| * | |
| * β BLANK, NEVER ZERO, on the numeric arm: a set holding no readable number at all is `undefined` | |
| * rather than `0`, exactly as `computeAggs` returns nothing there. A row COUNT of zero is a real | |
| * measurement and stays `0` β `formatShare` then refuses the division only if the WHOLE is zero. | |
| * β NOTHING IS ROUNDED HERE. Rounding a numerator and a denominator separately is how a column | |
| * of shares stops adding to 100 (`computeAggNumbers`' own note). | |
| */ | |
| function shareBase(rows: Row[], field: Field): number | undefined { | |
| if (!isNumericFieldType(field.type)) return rows.length; | |
| const nums = numbersOf(rows, field.key); | |
| // β `foldNumeric`, not a second `reduce`: the sum a share divides and the sum the bar prints | |
| // must be ONE arithmetic, which is the same argument W50-T04 extracted that function for. | |
| return nums.length ? foldNumeric(nums, "sum", undefined) : undefined; | |
| } | |
| export function computeAggs( | |
| rows: Row[], | |
| fields: Field[], | |
| summary?: SummaryMap, | |
| /** | |
| * ββ W51-T02 / R3 β the VIEW's totals, keyed exactly as `computeAggNumbers` returns them, and | |
| * the ONLY thing a `share` may divide by. Absent means "this fold IS the view" β the bottom | |
| * bar, which therefore reads 100.0% under "% of total", which is what the done-when says. | |
| * β It is never the sum of the groups and never the painted list: R4 fixed the base at the | |
| * MATCHED, UNFOLDED set and a base that followed the fold would change every share on screen | |
| * as somebody tidied it. | |
| */ | |
| totals?: Record<string, number> | |
| ): Record<string, string> { | |
| const out: Record<string, string> = {}; | |
| for (const f of fields) { | |
| const choice = summary === undefined | |
| ? legacyChoice(f) | |
| : resolveSummary(f, summary); | |
| if (!choice || choice.agg === "none") continue; | |
| const agg = choice.agg; | |
| if (agg === "count") { | |
| out[f.key] = rows.length.toLocaleString(); | |
| continue; | |
| } | |
| // β ELIGIBILITY IS THE TYPE FAMILY, NEVER THE KIND β see `summaryOptions`. `count_distinct` | |
| // reads a cell as a VALUE rather than as a number, so it is legal on text too. | |
| if (agg === "count_distinct") { | |
| const seen = new Set<string>(); | |
| for (const r of rows) { | |
| const v = r[f.key]; | |
| if (v === null || v === undefined || v === "") continue; | |
| seen.add(typeof v === "object" ? JSON.stringify(v) : String(v)); | |
| } | |
| out[f.key] = seen.size.toLocaleString(); | |
| continue; | |
| } | |
| /* ββ W51-T02 / R3 β "% OF TOTAL" IS A PERCENT WHATEVER THE COLUMN'S UNIT, WHICH IS WHY IT | |
| RETURNS BEFORE `wearColumnUnit` EVER SEES IT. A share dressed in a money column's unit | |
| prints "$12.4" where it means "12.4%" β a number that is true of nothing, and one no type | |
| and no screenshot can catch. `formatShare` owns the arithmetic and the one decimal, and | |
| refuses a zero or absent denominator rather than painting `0%`. */ | |
| if (agg === "share") { | |
| const base = shareBase(rows, f); | |
| const whole = totals?.[f.key]; | |
| const text = formatShare(base, whole === undefined ? base : whole); | |
| if (text !== undefined) out[f.key] = text; | |
| continue; | |
| } | |
| if (!isNumericFieldType(f.type)) continue; | |
| const nums = numbersOf(rows, f.key); | |
| if (!nums.length) continue; // blank, never zero | |
| const clean = Number(foldNumeric(nums, agg, choice.p).toPrecision(15)); // drop float noise only, never round | |
| // β W41-T40 (instruction 16) β A SUMMARY WEARS ITS COLUMN'S UNIT. `display.cellText` paints | |
| // a `pct` cell as "12.5%", so a bare "37.5" in the footer under a column of percentages is a | |
| // number whose unit the reader has to infer. One decimal, the SAME as the cell, so the total | |
| // and the values it folds read as the same quantity. | |
| // β `count` never reaches here (it returns above), so "3 rows" is not dressed as "3.0%". | |
| out[f.key] = wearColumnUnit(f, clean); | |
| } | |
| return out; | |
| } | |
| /** | |
| * ββ W50-T04 β **THE SAME FOLD, UNDRESSED.** `computeAggs` above returns display strings, and a | |
| * share needs to DIVIDE. Parsing `"$1,204"` back into a number to do that is the trap this | |
| * function removes: it re-derives a quantity from its own presentation, so a currency symbol, | |
| * a thousands separator or a `%` suffix each break the arithmetic in a way nothing can see. | |
| * | |
| * β IDENTICAL RESOLUTION, IDENTICAL ELIGIBILITY, IDENTICAL BLANK RULE to `computeAggs` β the | |
| * same `resolveSummary`, the same `isNumericFieldType` gate, and a numeric fold over a set with | |
| * no numeric value in it is ABSENT rather than `0`. The one deliberate difference is that | |
| * nothing is rounded here: rounding is a presentation step, and `Math.round(x*100)/100` applied | |
| * to a numerator and a denominator separately is how a column of shares stops adding to 100. | |
| */ | |
| export function computeAggNumbers( | |
| rows: Row[], | |
| fields: Field[], | |
| summary?: SummaryMap | |
| ): Record<string, number> { | |
| const out: Record<string, number> = {}; | |
| for (const f of fields) { | |
| const choice = summary === undefined ? legacyChoice(f) : resolveSummary(f, summary); | |
| if (!choice || choice.agg === "none") continue; | |
| const agg = choice.agg; | |
| if (agg === "count") { | |
| out[f.key] = rows.length; | |
| continue; | |
| } | |
| if (agg === "count_distinct") { | |
| const seen = new Set<string>(); | |
| for (const r of rows) { | |
| const v = r[f.key]; | |
| if (v === null || v === undefined || v === "") continue; | |
| seen.add(typeof v === "object" ? JSON.stringify(v) : String(v)); | |
| } | |
| out[f.key] = seen.size; | |
| continue; | |
| } | |
| /* ββ W51-T02 / R3 β a `share` UNDRESSED is its BASE, not its percentage, and that is what | |
| makes this function the denominator source. `groupAnalytics` folds this over the whole | |
| matched set and hands the result back in as `computeAggs`' `totals`, so the group's base | |
| and the view's base are measured by one function over two scopes. Summary mode also sorts | |
| on it, and ordering by the base is the same order as by the share under one denominator. */ | |
| if (agg === "share") { | |
| const base = shareBase(rows, f); | |
| if (base !== undefined) out[f.key] = base; | |
| continue; | |
| } | |
| if (!isNumericFieldType(f.type)) continue; | |
| const nums = numbersOf(rows, f.key); | |
| if (!nums.length) continue; // blank, never zero | |
| out[f.key] = foldNumeric(nums, agg, choice.p); | |
| } | |
| return out; | |
| } | |
| /** | |
| * ββ W50-T04 / OWNER RULING R4 β **THE AGGREGATES THAT COMPOSE, AND ONLY THOSE.** | |
| * | |
| * R4: *"% of total base is ALWAYS the view's grand total (rows and headers add to 100% down the | |
| * grid, the bar reads 100%)."* That sentence is only TRUE for a fold whose parts add up to the | |
| * whole. `sum` does. `count` does. Nothing else on this list does: | |
| * | |
| * Β· `average`, `median`, `min`, `max`, `percentile` β a group's average over the view's | |
| * average is a ratio of two averages. It is a number, it renders, and a column of them adds | |
| * to whatever it happens to add to. That is the "plausible number that never sums to | |
| * anything" this ruling exists to forbid. | |
| * Β· `count_distinct` β β **THE ONE THAT LOOKS COMPOSABLE AND IS NOT, so it is named here | |
| * rather than left to the `includes` to imply.** Two groups sharing a customer each count | |
| * that customer once, so the per-group distincts sum to MORE than the view's distinct and | |
| * the column adds to over 100%. | |
| * | |
| * A column whose aggregate does not compose therefore shows its aggregate and NO share, which | |
| * is the honest half of what it can answer. | |
| */ | |
| export const SHARE_AGGS: readonly SummaryAggName[] = ["sum", "count"]; | |
| /** | |
| * ββ W51-T02 β **THIS IS THE ROW-LEVEL `Show as` GATE, AND R3 EXPLICITLY KEEPS IT.** R3, in its | |
| * own words: *"The row-level Show as (wave 50 R4) STAYS on the field."* Its one caller is | |
| * `CustomerGrid.tsx::getCellContent`, which composes a CELL's value with its share of the view | |
| * total through `ui/fmt.ts::withShare` under `field.showAs`. | |
| * | |
| * β IT IS NOT WHAT PAINTS A GROUP HEADER ANY MORE. W50-T04's `groupHeaderAggs` used this to | |
| * append an automatic SECOND number to every composable column's header, which is exactly what | |
| * instruction 1 called out; the header now paints one value, the bar's picker's choice, and | |
| * "% of total" is one of the choices rather than an extra. | |
| * β `share` can never be a member: it IS a share, and a share of a share is not a quantity. | |
| */ | |
| export function sharesTheTotal(choice: SummaryChoice): boolean { | |
| if (choice.agg === "none" || choice.agg === "share") return false; | |
| return SHARE_AGGS.includes(choice.agg); | |
| } | |
| /** | |
| * ββ W50-T04 / R4 β a part over the view's grand total, to ONE DECIMAL (the PRD's design | |
| * contract says so in those words), or nothing. | |
| * | |
| * β **NOT CLAMPED, AND THAT IS DELIBERATE.** A `sum` column can hold mixed signs β credits | |
| * against invoices, returns against orders β so a group's share can legitimately exceed 100% | |
| * or be negative, and the column still adds to 100. Clamping would make the printed shares stop | |
| * reconciling with each other, which is worse than a surprising number that is true. | |
| * β A ZERO DENOMINATOR IS NOT A ZERO SHARE. Nothing can be a share of nothing, so it is absent | |
| * β the codebase's standing "blank, never zero" law, applied to the division rather than to the | |
| * fold. | |
| */ | |
| export function formatShare( | |
| part: number | undefined, | |
| whole: number | undefined | |
| ): string | undefined { | |
| if (typeof part !== "number" || !Number.isFinite(part)) return undefined; | |
| if (typeof whole !== "number" || !Number.isFinite(whole) || whole === 0) return undefined; | |
| return ((part / whole) * 100).toFixed(1) + "%"; | |
| } | |
| /** | |
| * ββ W51-T02 / OWNER RULING R3 β **`groupHeaderAggs` IS GONE, AND ITS ABSENCE IS THE TICKET.** | |
| * | |
| * W50-T04 declared a function here that composed `"$12,340 12.4%"` β the column's aggregate, | |
| * then an AUTOMATIC share of the view total for every fold in `SHARE_AGGS`. Instruction 1, in | |
| * the owner's words: *"Under the Group function with numerics, do not show BOTH common size % | |
| * and the sum/average/median: the toggle for sum/average/median includes the common size."* | |
| * | |
| * R3 replaced it: *"The bottom-bar picker OWNS group headers and the bar: one value, the | |
| * picker's choice, with '% of total' as an option."* So a group header is now `computeAggs` over | |
| * that group's bucket under the view's summary map, with the view's own totals handed in as the | |
| * share denominator β the SAME function the bottom bar folds itself with, at a smaller scope. | |
| * There is nothing left to compose, so there is no composer. | |
| * | |
| * β WHAT THE HEADER STILL CARRIES BESIDE ITS COLUMNS is the group's ROW COUNT as a share of the | |
| * view's, appended to the group LABEL (`CustomerGrid.tsx::groupAnalytics`' `share` map). That is | |
| * a property of the grouping rather than of a column, it is not gated on `sharesTheTotal`, and | |
| * `export.ts::summaryExportSheet` files it as the "% of total" column of the Summary-mode | |
| * export. Deleting it would empty a shipped column to answer a ruling that speaks about columns. | |
| */ | |
| /** The formatting half of the fold, extracted so C1's SERVER numbers wear the same unit the | |
| * client's own fold does. Two formatters is how the same column reads "$1,204" on a small | |
| * table and "1204" on a windowed one, with nothing red. */ | |
| function wearColumnUnit(field: Field, clean: number): string { | |
| // ββ THIS WAS THE THIRD FORMATTER, AND IT IGNORED THE FIELD'S OWN FORMAT β which is the exact | |
| // thing the docstring above says the function exists to prevent. `clean.toFixed(1)` pinned every | |
| // percent footer to one decimal and `clean.toLocaleString()` dropped an authored decimals/ | |
| // thousands choice outright, so a column the owner had formatted to `0,000` read one way in its | |
| // cells and another in its own group summary. Found by the W58-T09 verifier as a counter-finding: | |
| // the ticket's clause named record detail and related records, this is the footer, and the | |
| // ticket's own word was "everywhere". | |
| // | |
| // `numberText` is the single implementation `display.ts::valueText` uses for the cells, so the | |
| // fold now wears the column's real unit by CALLING it rather than by resembling it. | |
| // S76-T29: the field's own symbol, once; `$` only when a currency field names none. | |
| return field.type === "currency" ? numberText(clean, field.format, "$") | |
| : field.type === "pct" ? numberText(clean, field.format) + "%" | |
| : numberText(clean, field.format); | |
| } | |
| /** | |
| * ββ W50-T03 / C1 β one server number, painted the way this column paints its own. | |
| * | |
| * β `null` IS AN ANSWER AND IT IS BLANK, NEVER `0`. C1 says an unanswerable column lands in | |
| * `limits` and its value is `null` β the codebase's standing law (`computeAggs`' own note) is | |
| * that a fold with nothing to measure returns nothing, because `0` is a measurement. | |
| * β The two counting aggregates are plain integers: a count of rows in a money column is not | |
| * money, and dressing it as "$412" is a number nobody can reconcile. | |
| * | |
| * ββ W51-T02 / R3 β **AND A `share` IS A PERCENT WHATEVER THE COLUMN'S UNIT, so it returns | |
| * before `wearColumnUnit` too.** On a server-windowed table there is no page to fold: `value` is | |
| * the server's aggregate for this group (a numeric column's `sum`, anything else's `count`, | |
| * which is what `CustomerGrid.tsx::summaryRequest` asks for in a share column's name) and | |
| * `whole` is C1's TOP-LEVEL overall answer for the same column. Both come from the aggregates | |
| * endpoint, so the share describes the whole predicate rather than the loaded window. | |
| * β NO SERVER ANSWER IS NO DENOMINATOR AND THEREFORE NO SHARE β `formatShare` refuses an absent | |
| * or zero `whole` and this returns `undefined`, which the callers paint as blank. Never `0%`. | |
| */ | |
| export function formatServerAgg( | |
| field: Field, | |
| choice: SummaryChoice, | |
| value: number | null | undefined, | |
| whole?: number | null | undefined | |
| ): string | undefined { | |
| if (typeof value !== "number" || !Number.isFinite(value)) return undefined; | |
| if (choice.agg === "share") | |
| return formatShare(value, typeof whole === "number" ? whole : undefined); | |
| if (choice.agg === "count" || choice.agg === "count_distinct") | |
| return Math.round(value).toLocaleString(); | |
| return wearColumnUnit(field, Number(value.toPrecision(15))); // drop float noise only, never round | |
| } | |