@sincpro/web-ui 1.9.0 → 1.11.0

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 (95) hide show
  1. package/dist/components/board/Board.d.ts +51 -0
  2. package/dist/components/board/Board.js +15 -0
  3. package/dist/components/board/index.d.ts +1 -0
  4. package/dist/components/board/index.js +2 -0
  5. package/dist/components/canvas/Canvas.d.ts +14 -0
  6. package/dist/components/canvas/Canvas.js +9 -0
  7. package/dist/components/canvas/canvas.css +19 -0
  8. package/dist/components/canvas/index.d.ts +1 -0
  9. package/dist/components/canvas/index.js +2 -0
  10. package/dist/components/chat/ChatComposer.d.ts +10 -0
  11. package/dist/components/chat/ChatComposer.js +29 -0
  12. package/dist/components/chat/ChatThread.d.ts +13 -0
  13. package/dist/components/chat/ChatThread.js +76 -0
  14. package/dist/components/chat/ConversationList.d.ts +22 -0
  15. package/dist/components/chat/ConversationList.js +22 -0
  16. package/dist/components/chat/index.d.ts +4 -0
  17. package/dist/components/chat/index.js +5 -0
  18. package/dist/components/chat/model.d.ts +30 -0
  19. package/dist/components/chat/model.js +53 -0
  20. package/dist/components/frame/Chart.d.ts +12 -7
  21. package/dist/components/frame/Chart.js +17 -17
  22. package/dist/components/frame/FrameView.d.ts +3 -3
  23. package/dist/components/frame/FrameView.js +79 -26
  24. package/dist/components/frame/model.d.ts +12 -3
  25. package/dist/components/frame/model.js +53 -19
  26. package/dist/components/index.d.ts +4 -0
  27. package/dist/components/index.js +4 -0
  28. package/dist/components/listing/AxisLevels.d.ts +24 -0
  29. package/dist/components/listing/AxisLevels.js +58 -0
  30. package/dist/components/listing/ChartExplorer.d.ts +79 -0
  31. package/dist/components/listing/ChartExplorer.js +114 -0
  32. package/dist/components/listing/ColumnsMenu.d.ts +7 -1
  33. package/dist/components/listing/ColumnsMenu.js +16 -5
  34. package/dist/components/listing/GroupingLevels.d.ts +5 -1
  35. package/dist/components/listing/GroupingLevels.js +7 -4
  36. package/dist/components/listing/ListingBar.js +2 -2
  37. package/dist/components/listing/PivotExplorer.js +5 -36
  38. package/dist/components/listing/index.d.ts +2 -0
  39. package/dist/components/listing/index.js +2 -0
  40. package/dist/components/listing/set.d.ts +3 -1
  41. package/dist/components/preview/FilePreview.d.ts +19 -0
  42. package/dist/components/preview/FilePreview.js +112 -0
  43. package/dist/components/preview/PdfPreview.d.ts +7 -0
  44. package/dist/components/preview/PdfPreview.js +47 -0
  45. package/dist/components/preview/index.d.ts +1 -0
  46. package/dist/components/preview/index.js +2 -0
  47. package/dist/components/record/SmartButtons.js +1 -1
  48. package/dist/components/search/FieldPath.d.ts +54 -0
  49. package/dist/components/search/FieldPath.js +159 -0
  50. package/dist/components/search/FilterBuilder.d.ts +38 -5
  51. package/dist/components/search/FilterBuilder.js +129 -25
  52. package/dist/components/search/SearchBar.js +7 -2
  53. package/dist/components/search/criteria.d.ts +23 -1
  54. package/dist/components/search/index.d.ts +4 -2
  55. package/dist/components/search/index.js +4 -0
  56. package/dist/components/search/paths.d.ts +49 -0
  57. package/dist/components/search/paths.js +75 -0
  58. package/dist/components/shell/TopBar.js +1 -1
  59. package/dist/foundations/calendar.d.ts +15 -0
  60. package/dist/foundations/calendar.js +59 -1
  61. package/dist/foundations/chart.d.ts +126 -0
  62. package/dist/foundations/chart.js +297 -0
  63. package/dist/foundations/copy.d.ts +125 -0
  64. package/dist/foundations/copy.es.js +90 -0
  65. package/dist/foundations/copy.js +84 -0
  66. package/dist/foundations/index.d.ts +2 -1
  67. package/dist/foundations/index.js +4 -1
  68. package/dist/foundations/pivot.d.ts +9 -0
  69. package/dist/foundations/pivot.js +1 -0
  70. package/dist/primitives/chart/Chart.d.ts +39 -0
  71. package/dist/primitives/chart/Chart.js +235 -0
  72. package/dist/primitives/chart/index.d.ts +1 -0
  73. package/dist/primitives/chart/index.js +1 -0
  74. package/dist/primitives/field/Field.js +2 -1
  75. package/dist/primitives/index.d.ts +1 -0
  76. package/dist/primitives/index.js +1 -0
  77. package/dist/primitives/notice/Callout.d.ts +4 -1
  78. package/dist/primitives/notice/Callout.js +12 -2
  79. package/dist/primitives/notice/Notice.d.ts +26 -2
  80. package/dist/primitives/notice/Notice.js +64 -4
  81. package/dist/primitives/notice/Toast.js +10 -1
  82. package/dist/primitives/value/Markdown.d.ts +9 -0
  83. package/dist/primitives/value/Markdown.js +18 -0
  84. package/dist/primitives/value/Metric.d.ts +13 -2
  85. package/dist/primitives/value/Metric.js +25 -3
  86. package/dist/primitives/value/index.d.ts +1 -0
  87. package/dist/primitives/value/index.js +1 -0
  88. package/dist/tokens.css +73 -0
  89. package/dist/views/list/List.d.ts +2 -1
  90. package/dist/views/list/List.js +8 -1
  91. package/dist/views/list/ListView.d.ts +1 -1
  92. package/dist/views/list/ListView.js +37 -5
  93. package/dist/views/list/index.d.ts +1 -1
  94. package/dist/views/list/types.d.ts +34 -0
  95. package/package.json +5 -1
@@ -0,0 +1,75 @@
1
+ import { fieldLabel, } from "./model.js";
2
+ /** Whether a field points to another model: the picker can walk into it. */
3
+ export function isRelation(field) {
4
+ return (field.kind === "relation" || (field.relation !== undefined && field.relation !== null));
5
+ }
6
+ /** Whether a relation reaches MANY records. A filter through it has to say how many of them
7
+ * must match: some, none or all. */
8
+ export function isToMany(field) {
9
+ return isRelation(field) && field.many === true;
10
+ }
11
+ /** «Líneas > Impuestos > Monto»: how a path reads on a button or a chip. */
12
+ export function pathLabel(labels) {
13
+ return labels.join(" > ");
14
+ }
15
+ const key = (path) => path.join("\u0000");
16
+ export function createModelCache(root, loadModel) {
17
+ const pending = new Map();
18
+ const arrived = new Map([[key([]), root]]);
19
+ return {
20
+ root,
21
+ canLoad: loadModel !== undefined,
22
+ peek: (path) => arrived.get(key(path)),
23
+ get(path) {
24
+ const at = key(path);
25
+ const known = arrived.get(at);
26
+ if (known !== undefined)
27
+ return Promise.resolve(known);
28
+ const asked = pending.get(at);
29
+ if (asked !== undefined)
30
+ return asked;
31
+ if (loadModel === undefined) {
32
+ return Promise.reject(new Error(`No loadModel to follow «${path.join(".")}»`));
33
+ }
34
+ const request = loadModel(path).then((model) => {
35
+ arrived.set(at, model);
36
+ pending.delete(at);
37
+ return model;
38
+ }, (error) => {
39
+ pending.delete(at);
40
+ throw error;
41
+ });
42
+ pending.set(at, request);
43
+ return request;
44
+ },
45
+ };
46
+ }
47
+ /**
48
+ * A path resolved into its steps: each field with its definition and its label.
49
+ *
50
+ * in ["lines", "taxes", "amount"], the invoice model
51
+ * out [Líneas (to-many), Impuestos (to-many), Monto (number)]
52
+ *
53
+ * A name the model does not have stops the walk: it answers `null`, because half a path is
54
+ * a different question, not a shorter one.
55
+ */
56
+ export async function resolvePath(models, path, locale) {
57
+ const steps = [];
58
+ for (let at = 0; at < path.length; at++) {
59
+ const model = await models.get(path.slice(0, at));
60
+ const name = path[at];
61
+ const field = model.fields[name];
62
+ if (field === undefined)
63
+ return null;
64
+ steps.push({ name, field, label: fieldLabel(model, name, locale) });
65
+ }
66
+ return steps;
67
+ }
68
+ /** The labels of a path with what has already arrived; a model still on its way leaves the
69
+ * raw name, which is what there is to say until it arrives. */
70
+ export function peekLabels(models, path, locale) {
71
+ return path.map((name, at) => {
72
+ const model = models.peek(path.slice(0, at));
73
+ return model === undefined ? name : fieldLabel(model, name, locale);
74
+ });
75
+ }
@@ -10,7 +10,7 @@ export function TopBar({ app, apps, currentApp, onAppSelect, menus, onMenuSelect
10
10
  const copy = useUiCopy();
11
11
  const actual = apps?.find((a) => a.id === currentApp);
12
12
  const brand = app ?? actual;
13
- return (_jsx(SurfaceProvider, { value: "chrome", children: _jsxs("header", { className: "flex h-(--size-appbar) min-w-0 items-center gap-1 border-b border-chrome-edge bg-chrome px-2", children: [apps === undefined || apps.length === 0 ? null : (_jsx(AppSwitcher, { apps: apps, current: currentApp, ...(onAppSelect === undefined ? {} : { onSelect: onAppSelect }) })), brand === undefined ? null : (_jsxs("span", { className: "flex shrink-0 items-center gap-2 pr-2 pl-1", children: [brand.icon === undefined ? null : (_jsx(brand.icon, { className: "size-(--size-icon-md) text-chrome-link", strokeWidth: 2, "aria-hidden": true })), _jsx("span", { className: "text-lead font-medium text-chrome-ink", children: brand.label })] })), menus === undefined ? null : (_jsx("nav", { className: "flex min-w-0 items-center gap-0.5 overflow-hidden", "aria-label": copy.shell.menus, children: menus.map((m) => (_jsx(Menu, { label: m.label, groups: m.groups, surface: "chrome", variant: "text", chevron: false, onSelect: (id) => onMenuSelect?.(m.id, id) }, m.id))) })), _jsxs("div", { className: "ml-auto flex shrink-0 items-center gap-1 pl-2", children: [systray, user === undefined ? null : (_jsx(UserMenu, { name: user.name, ...(user.detail === undefined ? {} : { detail: user.detail }), groups: userGroups ?? [], ...(onUserSelect === undefined ? {} : { onSelect: onUserSelect }) }))] })] }) }));
13
+ return (_jsx(SurfaceProvider, { value: "chrome", children: _jsxs("header", { className: "flex h-(--size-appbar) min-w-0 items-center gap-1 border-b border-chrome-edge bg-chrome px-2", children: [apps === undefined || apps.length === 0 ? null : (_jsx(AppSwitcher, { apps: apps, current: currentApp, ...(onAppSelect === undefined ? {} : { onSelect: onAppSelect }) })), brand === undefined ? null : (_jsxs("span", { className: "flex shrink-0 items-center gap-2 pr-2 pl-1", children: [brand.icon === undefined ? null : (_jsx(brand.icon, { className: "size-(--size-icon-md) text-chrome-link", strokeWidth: 2, "aria-hidden": true })), _jsx("span", { className: "text-lead font-medium text-chrome-ink", children: brand.label })] })), menus === undefined ? null : (_jsx("nav", { className: "scroll-quiet flex min-w-0 items-center gap-0.5", "aria-label": copy.shell.menus, children: menus.map((m) => (_jsx(Menu, { label: m.label, groups: m.groups, surface: "chrome", variant: "text", chevron: false, onSelect: (id) => onMenuSelect?.(m.id, id) }, m.id))) })), _jsxs("div", { className: "ml-auto flex shrink-0 items-center gap-1 pl-2", children: [systray, user === undefined ? null : (_jsx(UserMenu, { name: user.name, ...(user.detail === undefined ? {} : { detail: user.detail }), groups: userGroups ?? [], ...(onUserSelect === undefined ? {} : { onSelect: onUserSelect }) }))] })] }) }));
14
14
  }
15
15
  /** The app switcher: a grid, not a list.
16
16
  *
@@ -21,6 +21,21 @@ export declare function dateKey(when: Date | string | number | null | undefined,
21
21
  * en vez de desaparecer detrás de una fecha inventada.
22
22
  */
23
23
  export declare function dateLabel(key: string, grain: GroupGrain, within?: readonly GroupGrain[]): string;
24
+ /**
25
+ * La clave SIGUIENTE en el mismo grano: «2026-09» → «2026-10», «2026-Q4» → «2027-Q1»,
26
+ * «2026-W52» → la semana ISO que sigue. `null` si la clave no tiene la forma de su grano —
27
+ * una contada afuera, que esta capa no escribió y entonces no puede continuar.
28
+ */
29
+ export declare function nextDateKey(key: string, grain: GroupGrain): string | null;
30
+ /**
31
+ * Todas las claves de un grano entre dos, las dos incluidas: el EJE de tiempo entero.
32
+ *
33
+ * Un eje que salta el mes en que no pasó nada miente sobre el tiempo —agosto pegado a
34
+ * octubre se lee como un mes— y ese hueco suele ser justo lo que alguien busca. `null` si
35
+ * alguna clave no se puede continuar o si serían más de `max`: un eje por día de diez años
36
+ * no es un gráfico.
37
+ */
38
+ export declare function dateKeysBetween(first: string, last: string, grain: GroupGrain, max?: number): string[] | null;
24
39
  /** El nombre de un mes —1 a 12— en el idioma activo. Lo usa el que ofrece meses
25
40
  * sin tener ninguna fecha en la mano, como el recorte por período. */
26
41
  export declare function monthName(month: number): string;
@@ -64,7 +64,15 @@ const KEY_SHAPES = {
64
64
  export function dateKey(when, grain) {
65
65
  if (when === null || when === undefined || when === "")
66
66
  return "";
67
- const date = when instanceof Date ? when : new Date(when);
67
+ /* A date WITHOUT a time («2025-01-01») is a day of the calendar, not an instant: `new Date`
68
+ reads it as midnight UTC, which in La Paz (UTC−4) is the 31st of December — and January's
69
+ sales landed in last year's December. It is read as a local day instead. */
70
+ const day = typeof when === "string" ? /^(\d{4})-(\d{2})-(\d{2})$/.exec(when) : null;
71
+ const date = day !== null
72
+ ? new Date(Number(day[1]), Number(day[2]) - 1, Number(day[3]))
73
+ : when instanceof Date
74
+ ? when
75
+ : new Date(when);
68
76
  if (Number.isNaN(date.getTime()))
69
77
  return "";
70
78
  const year = date.getFullYear();
@@ -140,6 +148,56 @@ export function dateLabel(key, grain, within = []) {
140
148
  ...(said("year") ? {} : { year: "numeric" }),
141
149
  }).format(when));
142
150
  }
151
+ /**
152
+ * La clave SIGUIENTE en el mismo grano: «2026-09» → «2026-10», «2026-Q4» → «2027-Q1»,
153
+ * «2026-W52» → la semana ISO que sigue. `null` si la clave no tiene la forma de su grano —
154
+ * una contada afuera, que esta capa no escribió y entonces no puede continuar.
155
+ */
156
+ export function nextDateKey(key, grain) {
157
+ const parts = KEY_SHAPES[grain].exec(key);
158
+ if (parts === null)
159
+ return null;
160
+ const year = Number(key.slice(0, 4));
161
+ if (grain === "year")
162
+ return String(year + 1);
163
+ if (grain === "quarter") {
164
+ const quarter = Number(key.slice(6));
165
+ return quarter === 4 ? `${year + 1}-Q1` : `${year}-Q${quarter + 1}`;
166
+ }
167
+ if (grain === "month") {
168
+ const month = Number(key.slice(5, 7));
169
+ return month === 12 ? `${year + 1}-01` : `${year}-${pad(month + 1)}`;
170
+ }
171
+ if (grain === "week") {
172
+ /* The Monday of ISO week 1 is the Monday of the week holding 4 January. */
173
+ const week = Number(key.slice(6));
174
+ const fourth = new Date(year, 0, 4);
175
+ const monday = new Date(year, 0, 4 - ((fourth.getDay() + 6) % 7) + (week - 1) * 7);
176
+ return dateKey(new Date(monday.getFullYear(), monday.getMonth(), monday.getDate() + 7), "week");
177
+ }
178
+ const date = new Date(year, Number(key.slice(5, 7)) - 1, Number(key.slice(8, 10)) + 1);
179
+ return dateKey(date, "day");
180
+ }
181
+ /**
182
+ * Todas las claves de un grano entre dos, las dos incluidas: el EJE de tiempo entero.
183
+ *
184
+ * Un eje que salta el mes en que no pasó nada miente sobre el tiempo —agosto pegado a
185
+ * octubre se lee como un mes— y ese hueco suele ser justo lo que alguien busca. `null` si
186
+ * alguna clave no se puede continuar o si serían más de `max`: un eje por día de diez años
187
+ * no es un gráfico.
188
+ */
189
+ export function dateKeysBetween(first, last, grain, max = 1000) {
190
+ const out = [first];
191
+ let key = first;
192
+ while (key < last) {
193
+ const next = nextDateKey(key, grain);
194
+ if (next === null || out.length >= max)
195
+ return null;
196
+ out.push(next);
197
+ key = next;
198
+ }
199
+ return key === last ? out : null;
200
+ }
143
201
  /** El nombre de un mes —1 a 12— en el idioma activo. Lo usa el que ofrece meses
144
202
  * sin tener ninguna fecha en la mano, como el recorte por período. */
145
203
  export function monthName(month) {
@@ -0,0 +1,126 @@
1
+ import { type Pivot, type PivotKey } from "./pivot.js";
2
+ /**
3
+ * EL GRÁFICO: un pivote leído como marcas.
4
+ *
5
+ * Context: un gráfico de un ERP —el de Odoo, el de cualquiera— contesta la misma pregunta
6
+ * que un pivote: el conjunto partido por un campo (el eje), a veces por otro más (las
7
+ * series), y en cada cruce un número plegado. Por eso esto NO trae otra manera de plegar:
8
+ * lee un `Pivot`. Y como un `Pivot` lo arma igual quien tiene los registros en la mano
9
+ * (`pivotFrom`), quien lo plegó en el servidor (`pivotOf`) o quien lo armó desde las celdas
10
+ * de un archivo, el mismo gráfico sirve para registros, para un dataset y para lo agrupado
11
+ * a mil kilómetros. Un diccionario o un `SeriesBar[]` entran por sus dos helpers de abajo.
12
+ *
13
+ * ── Las filas del pivote son el EJE; sus columnas, las SERIES ───────
14
+ *
15
+ * Igual que en Odoo: el primer agrupado va abajo y el segundo se apila o se pone al lado.
16
+ *
17
+ * ── Tres reglas que vienen del pivote, y siguen valiendo ────────────
18
+ *
19
+ * 1. **Un agujero no es un cero.** `null` es «ahí no hay filas»: la barra no se dibuja y
20
+ * la línea se corta. Un cero es una barra a ras del eje.
21
+ * 2. **No se inventan sumas.** Juntar la cola en «otros» o acumular una línea es sumar, y
22
+ * sólo se hace si la medida se suma (`additive`; el conteo siempre). Si no, la cola se
23
+ * deja afuera y se DICE (`hiddenSeries`): un promedio de promedios no es un promedio.
24
+ * 3. **El color sigue a la serie, no a su puesto.** Las series que quedan conservan el
25
+ * orden del pivote; ordenar por tamaño ordena el EJE, nunca repinta.
26
+ */
27
+ export type ChartKind = "bar" | "line" | "pie";
28
+ export type ChartOrder = "asc" | "desc";
29
+ /** El conteo de filas de cada cruce, ofrecido como una medida más: es la única que
30
+ * siempre se puede contestar. */
31
+ export declare const COUNT_MEASURE = "__count";
32
+ /** Cuántas series se distinguen por color. Es el largo de la paleta (`--color-series-*`):
33
+ * una novena serie sería un color generado, y bajo daltonismo ése se confunde con otro. */
34
+ export declare const SERIES_COLORS = 8;
35
+ /** Una clave de un eje del gráfico: su ruta en el pivote y cómo se lee. */
36
+ export type ChartPoint = {
37
+ key: PivotKey;
38
+ /** `pathKey(key)`: la identidad estable para React y para el color. */
39
+ id: string;
40
+ label: string;
41
+ /** La cola juntada en una: «otros (12)». Se dibuja más callada y no se abre. */
42
+ rest?: boolean;
43
+ /** El período anterior de una comparación: se dibuja callado, detrás del actual. */
44
+ previous?: boolean;
45
+ };
46
+ export type ChartMeasure = {
47
+ id: string;
48
+ header: string;
49
+ format?: (value: number) => string;
50
+ additive: boolean;
51
+ };
52
+ export type ChartData = {
53
+ categories: readonly ChartPoint[];
54
+ series: readonly ChartPoint[];
55
+ /** `values[categoría][serie]`; `null` es un agujero. */
56
+ values: readonly (readonly (number | null)[])[];
57
+ /** Lo que da cada categoría entera, plegado de la base cuando el pivote lo trae. Es lo
58
+ * que mide una torta y lo que ordena el eje. */
59
+ totals: readonly (number | null)[];
60
+ measure: ChartMeasure;
61
+ /** Cómo se llaman los cortes: «sucursal», «año · forma de pago». */
62
+ categoryTitle: string;
63
+ seriesTitle: string;
64
+ /** Series que no entraron y no se pudieron juntar en «otros» (la medida no se suma). */
65
+ hiddenSeries: number;
66
+ /** Lo mismo, para las categorías que una torta no puede mostrar. */
67
+ hiddenCategories: number;
68
+ /** Las dos series son el período actual y el anterior (`chartCompare`). */
69
+ compare?: boolean;
70
+ };
71
+ export type ChartReading = {
72
+ /** El id de la medida, o `COUNT_MEASURE`. Por defecto la primera del pivote. */
73
+ measure?: string;
74
+ /** Ordena el EJE por lo que da cada categoría. Sin esto, el orden de sus claves. */
75
+ order?: ChartOrder;
76
+ /** Cada punto suma los anteriores: «cuánto llevamos». Sólo con una medida que se suma. */
77
+ cumulative?: boolean;
78
+ /** Más series que esto se juntan en «otros». Por defecto, los colores de la paleta. */
79
+ maxSeries?: number;
80
+ /** Más categorías que esto se juntan en «otros». Una torta pide seis. */
81
+ maxCategories?: number;
82
+ /**
83
+ * Con un solo nivel de FECHA en el eje, completa los períodos en que no pasó nada:
84
+ * agosto no queda pegado a octubre. El conteo de un período vacío es 0; cualquier otra
85
+ * medida es un agujero (`null`), como cualquier cruce sin filas. Encendido por defecto.
86
+ */
87
+ fillDates?: boolean;
88
+ };
89
+ /** Las medidas que se pueden graficar de un pivote: el conteo y las suyas. */
90
+ export declare function chartMeasures(pivot: Pivot): ChartMeasure[];
91
+ /**
92
+ * El pivote como gráfico: las filas son el eje, las columnas las series, y en cada cruce
93
+ * el número de la medida elegida.
94
+ */
95
+ export declare function chartFromPivot(pivot: Pivot, reading?: ChartReading): ChartData;
96
+ /**
97
+ * Ordena el EJE de un gráfico ya armado por lo que da cada categoría. La cola juntada
98
+ * («otros») queda al final. Es lo mismo que `order` en `chartFromPivot`, para un gráfico
99
+ * que se armó de otra manera —una comparación, un diccionario—.
100
+ */
101
+ export declare function orderChart(data: ChartData, order: ChartOrder | undefined): ChartData;
102
+ /**
103
+ * EL PERÍODO ANTERIOR al lado del actual — el «comparar con» de Odoo.
104
+ *
105
+ * Cada gráfico se arma por su lado (`chartFromPivot` sobre los registros de cada período)
106
+ * y esto los junta en dos series: el actual y el anterior, que se dibuja callado. Lo que se
107
+ * compara es lo que da cada categoría entera.
108
+ *
109
+ * `by` dice cómo se encuentran: por CLAVE cuando el eje es una cosa —La Paz con La Paz— y
110
+ * por POSICIÓN cuando es tiempo —el primer mes con el primer mes—, porque «2026-09» y
111
+ * «2025-09» son claves distintas y lo que se compara es «el mismo momento del período».
112
+ * Una categoría del anterior que no está en el actual no se dibuja: el eje es el de ahora.
113
+ */
114
+ export declare function chartCompare(current: ChartData, previous: ChartData, labels: {
115
+ current: string;
116
+ previous: string;
117
+ }, by?: "key" | "position"): ChartData;
118
+ /**
119
+ * Un DICCIONARIO como gráfico: `{ "La Paz": 120, "Oruro": 40 }`, o sus pares. Es lo que
120
+ * devuelve un endpoint de resumen, y no hace falta armarle un pivote.
121
+ */
122
+ export declare function chartFromRecord(entries: Readonly<Record<string, number | null>> | readonly (readonly [string, number | null])[], measure: {
123
+ header: string;
124
+ format?: (value: number) => string;
125
+ additive?: boolean;
126
+ }): ChartData;
@@ -0,0 +1,297 @@
1
+ import { dateKeysBetween } from "./calendar.js";
2
+ import { currentCopy, fillCopy } from "./copy.js";
3
+ import { pathKey } from "./grouping.js";
4
+ import { axisLabels, } from "./pivot.js";
5
+ /** El conteo de filas de cada cruce, ofrecido como una medida más: es la única que
6
+ * siempre se puede contestar. */
7
+ export const COUNT_MEASURE = "__count";
8
+ /** Cuántas series se distinguen por color. Es el largo de la paleta (`--color-series-*`):
9
+ * una novena serie sería un color generado, y bajo daltonismo ése se confunde con otro. */
10
+ export const SERIES_COLORS = 8;
11
+ /** Las medidas que se pueden graficar de un pivote: el conteo y las suyas. */
12
+ export function chartMeasures(pivot) {
13
+ return [
14
+ { id: COUNT_MEASURE, header: currentCopy().chart.count, additive: true },
15
+ ...pivot.measures.map((one) => ({
16
+ id: one.id,
17
+ header: one.header,
18
+ ...(one.format === undefined ? {} : { format: one.format }),
19
+ additive: one.additive === true,
20
+ })),
21
+ ];
22
+ }
23
+ function title(axis) {
24
+ return axis.levels.map((level) => level.label).join(" · ");
25
+ }
26
+ function pointOf(axis, key, fallback) {
27
+ return {
28
+ key,
29
+ id: pathKey(key),
30
+ label: axis.levels.length === 0 ? fallback : axisLabels(axis, key).join(" · "),
31
+ };
32
+ }
33
+ function sum(values) {
34
+ let out = null;
35
+ for (const value of values)
36
+ if (value !== null)
37
+ out = (out ?? 0) + value;
38
+ return out;
39
+ }
40
+ /** Biggest first; a hole goes last, because «nothing there» is not «less than zero». */
41
+ function byTotal(totals, order) {
42
+ return (a, b) => {
43
+ const x = totals[a] ?? null;
44
+ const y = totals[b] ?? null;
45
+ if (x === null || y === null)
46
+ return x === y ? a - b : x === null ? 1 : -1;
47
+ return order === "asc" ? x - y || a - b : y - x || a - b;
48
+ };
49
+ }
50
+ /**
51
+ * Which indices stay, in their own order, when there are more than `max`: the biggest by
52
+ * total. With an additive measure one place is left for «otros».
53
+ */
54
+ function keep(totals, max, additive) {
55
+ const all = totals.map((_, at) => at);
56
+ if (all.length <= max)
57
+ return { kept: all, rest: [] };
58
+ const room = additive ? Math.max(1, max - 1) : max;
59
+ const top = new Set([...all].sort(byTotal(totals, "desc")).slice(0, room));
60
+ return {
61
+ kept: all.filter((at) => top.has(at)),
62
+ rest: all.filter((at) => !top.has(at)),
63
+ };
64
+ }
65
+ /**
66
+ * El pivote como gráfico: las filas son el eje, las columnas las series, y en cada cruce
67
+ * el número de la medida elegida.
68
+ */
69
+ export function chartFromPivot(pivot, reading = {}) {
70
+ const words = currentCopy();
71
+ const measures = chartMeasures(pivot);
72
+ const wanted = reading.measure ?? pivot.measures[0]?.id ?? COUNT_MEASURE;
73
+ const measure = measures.find((one) => one.id === wanted) ?? measures[0];
74
+ const read = (cell) => cell === undefined
75
+ ? null
76
+ : measure.id === COUNT_MEASURE
77
+ ? cell.count
78
+ : (cell.values[measure.id] ?? null);
79
+ let categories = pivot.rows.keys.map((key) => pointOf(pivot.rows, key, words.pivot.total));
80
+ let series = pivot.columns.keys.map((key) => pointOf(pivot.columns, key, measure.header));
81
+ let values = categories.map((row) => series.map((column) => read(pivot.cell(row.key, column.key))));
82
+ /* Los márgenes salen de la BASE cuando el pivote los trae; sumar celdas es la salida
83
+ honesta sólo cuando la medida se suma. */
84
+ const margin = (cell, inside) => cell !== undefined ? read(cell) : measure.additive ? sum(inside) : null;
85
+ let totals = categories.map((row, at) => margin(pivot.rowTotal?.(row.key), values[at] ?? []));
86
+ /* 0 · El tiempo entero: los períodos vacíos entre el primero y el último. */
87
+ const grain = pivot.rows.levels.length === 1 ? pivot.rows.levels[0]?.grain : undefined;
88
+ if (grain !== undefined && reading.fillDates !== false) {
89
+ const dated = categories
90
+ .map((point, at) => ({ point, at, key: point.key[0] ?? "" }))
91
+ .filter((one) => one.key !== "")
92
+ .sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
93
+ const first = dated[0]?.key;
94
+ const last = dated[dated.length - 1]?.key;
95
+ const full = first === undefined || last === undefined ? null : dateKeysBetween(first, last, grain);
96
+ if (full !== null) {
97
+ const byKey = new Map(dated.map((one) => [one.key, one.at]));
98
+ const empty = measure.id === COUNT_MEASURE ? 0 : null;
99
+ const undated = categories
100
+ .map((_, at) => at)
101
+ .filter((at) => (categories[at]?.key[0] ?? "") === "");
102
+ const filled = full.map((key) => {
103
+ const at = byKey.get(key);
104
+ return at === undefined
105
+ ? {
106
+ point: pointOf(pivot.rows, [key], key),
107
+ values: series.map(() => empty),
108
+ total: empty,
109
+ }
110
+ : { point: categories[at], values: values[at], total: totals[at] ?? null };
111
+ });
112
+ /* The records without a date stay, at the end: they are not a moment in time. */
113
+ for (const at of undated) {
114
+ filled.push({
115
+ point: categories[at],
116
+ values: values[at],
117
+ total: totals[at] ?? null,
118
+ });
119
+ }
120
+ categories = filled.map((one) => one.point);
121
+ values = filled.map((one) => one.values);
122
+ totals = filled.map((one) => one.total);
123
+ }
124
+ }
125
+ /* 1 · Las series que no entran en la paleta. */
126
+ let hiddenSeries = 0;
127
+ const seriesTotals = series.map((column, at) => margin(pivot.columnTotal?.(column.key), values.map((row) => row[at] ?? null)));
128
+ const seriesCut = keep(seriesTotals, reading.maxSeries ?? SERIES_COLORS, measure.additive);
129
+ if (seriesCut.rest.length > 0) {
130
+ const kept = seriesCut.kept;
131
+ if (measure.additive) {
132
+ series = [
133
+ ...kept.map((at) => series[at]),
134
+ {
135
+ key: [],
136
+ id: "\u0000rest",
137
+ label: fillCopy(words.chart.rest, { count: seriesCut.rest.length }),
138
+ rest: true,
139
+ },
140
+ ];
141
+ values = values.map((row) => [
142
+ ...kept.map((at) => row[at] ?? null),
143
+ sum(seriesCut.rest.map((at) => row[at] ?? null)),
144
+ ]);
145
+ }
146
+ else {
147
+ hiddenSeries = seriesCut.rest.length;
148
+ series = kept.map((at) => series[at]);
149
+ values = values.map((row) => kept.map((at) => row[at] ?? null));
150
+ }
151
+ }
152
+ /* 2 · Las categorías que no entran (una torta). */
153
+ let hiddenCategories = 0;
154
+ let restCategory = null;
155
+ if (reading.maxCategories !== undefined) {
156
+ const cut = keep(totals, reading.maxCategories, measure.additive);
157
+ if (cut.rest.length > 0) {
158
+ if (measure.additive) {
159
+ restCategory = {
160
+ point: {
161
+ key: [],
162
+ id: "\u0000rest",
163
+ label: fillCopy(words.chart.rest, { count: cut.rest.length }),
164
+ rest: true,
165
+ },
166
+ values: series.map((_, s) => sum(cut.rest.map((at) => values[at]?.[s] ?? null))),
167
+ total: sum(cut.rest.map((at) => totals[at] ?? null)),
168
+ };
169
+ }
170
+ else {
171
+ hiddenCategories = cut.rest.length;
172
+ }
173
+ categories = cut.kept.map((at) => categories[at]);
174
+ values = cut.kept.map((at) => values[at]);
175
+ totals = cut.kept.map((at) => totals[at] ?? null);
176
+ }
177
+ }
178
+ /* 3 · El orden del eje. La cola juntada va siempre al final: no es una categoría más. */
179
+ if (reading.order !== undefined) {
180
+ const at = categories.map((_, index) => index).sort(byTotal(totals, reading.order));
181
+ categories = at.map((index) => categories[index]);
182
+ values = at.map((index) => values[index]);
183
+ totals = at.map((index) => totals[index] ?? null);
184
+ }
185
+ if (restCategory !== null) {
186
+ categories = [...categories, restCategory.point];
187
+ values = [...values, restCategory.values];
188
+ totals = [...totals, restCategory.total];
189
+ }
190
+ /* 4 · Acumulado: un agujero arrastra lo que se llevaba, no lo corta. */
191
+ if (reading.cumulative === true && measure.additive) {
192
+ const running = series.map(() => null);
193
+ values = values.map((row) => row.map((value, s) => {
194
+ if (value !== null)
195
+ running[s] = (running[s] ?? 0) + value;
196
+ return running[s] ?? null;
197
+ }));
198
+ let total = null;
199
+ totals = totals.map((value) => {
200
+ if (value !== null)
201
+ total = (total ?? 0) + value;
202
+ return total;
203
+ });
204
+ }
205
+ return {
206
+ categories,
207
+ series,
208
+ values,
209
+ totals,
210
+ measure,
211
+ categoryTitle: title(pivot.rows),
212
+ seriesTitle: title(pivot.columns),
213
+ hiddenSeries,
214
+ hiddenCategories,
215
+ };
216
+ }
217
+ /**
218
+ * Ordena el EJE de un gráfico ya armado por lo que da cada categoría. La cola juntada
219
+ * («otros») queda al final. Es lo mismo que `order` en `chartFromPivot`, para un gráfico
220
+ * que se armó de otra manera —una comparación, un diccionario—.
221
+ */
222
+ export function orderChart(data, order) {
223
+ if (order === undefined)
224
+ return data;
225
+ const at = data.categories
226
+ .map((_, index) => index)
227
+ .filter((index) => data.categories[index]?.rest !== true)
228
+ .sort(byTotal(data.totals, order));
229
+ const tail = data.categories
230
+ .map((_, index) => index)
231
+ .filter((index) => data.categories[index]?.rest === true);
232
+ const all = [...at, ...tail];
233
+ return {
234
+ ...data,
235
+ categories: all.map((index) => data.categories[index]),
236
+ values: all.map((index) => data.values[index]),
237
+ totals: all.map((index) => data.totals[index] ?? null),
238
+ };
239
+ }
240
+ /**
241
+ * EL PERÍODO ANTERIOR al lado del actual — el «comparar con» de Odoo.
242
+ *
243
+ * Cada gráfico se arma por su lado (`chartFromPivot` sobre los registros de cada período)
244
+ * y esto los junta en dos series: el actual y el anterior, que se dibuja callado. Lo que se
245
+ * compara es lo que da cada categoría entera.
246
+ *
247
+ * `by` dice cómo se encuentran: por CLAVE cuando el eje es una cosa —La Paz con La Paz— y
248
+ * por POSICIÓN cuando es tiempo —el primer mes con el primer mes—, porque «2026-09» y
249
+ * «2025-09» son claves distintas y lo que se compara es «el mismo momento del período».
250
+ * Una categoría del anterior que no está en el actual no se dibuja: el eje es el de ahora.
251
+ */
252
+ export function chartCompare(current, previous, labels, by = "key") {
253
+ const whole = (data, at) => data.series.length === 1 ? (data.values[at]?.[0] ?? null) : (data.totals[at] ?? null);
254
+ const index = new Map(previous.categories.map((point, at) => [point.id, at]));
255
+ const before = (point, at) => {
256
+ const found = by === "position" ? at : index.get(point.id);
257
+ return found === undefined || found >= previous.categories.length
258
+ ? null
259
+ : whole(previous, found);
260
+ };
261
+ return {
262
+ ...current,
263
+ series: [
264
+ { key: [], id: "\u0000current", label: labels.current },
265
+ { key: [], id: "\u0000previous", label: labels.previous, previous: true },
266
+ ],
267
+ values: current.categories.map((point, at) => [whole(current, at), before(point, at)]),
268
+ totals: current.categories.map((_, at) => whole(current, at)),
269
+ hiddenSeries: 0,
270
+ compare: true,
271
+ };
272
+ }
273
+ /**
274
+ * Un DICCIONARIO como gráfico: `{ "La Paz": 120, "Oruro": 40 }`, o sus pares. Es lo que
275
+ * devuelve un endpoint de resumen, y no hace falta armarle un pivote.
276
+ */
277
+ export function chartFromRecord(entries, measure) {
278
+ const pairs = Array.isArray(entries)
279
+ ? entries
280
+ : Object.entries(entries);
281
+ return {
282
+ categories: pairs.map(([label]) => ({ key: [label], id: label, label })),
283
+ series: [{ key: [], id: "", label: measure.header }],
284
+ values: pairs.map(([, value]) => [value]),
285
+ totals: pairs.map(([, value]) => value),
286
+ measure: {
287
+ id: "value",
288
+ header: measure.header,
289
+ ...(measure.format === undefined ? {} : { format: measure.format }),
290
+ additive: measure.additive ?? true,
291
+ },
292
+ categoryTitle: "",
293
+ seriesTitle: "",
294
+ hiddenSeries: 0,
295
+ hiddenCategories: 0,
296
+ };
297
+ }