@sincpro/web-framework 3.0.0 → 3.2.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 (62) hide show
  1. package/README.md +29 -0
  2. package/dist/core/copy.d.ts +13 -1
  3. package/dist/core/copy.js +30 -0
  4. package/dist/core/explain.d.ts +12 -4
  5. package/dist/core/explain.js +18 -6
  6. package/dist/core/form.d.ts +7 -3
  7. package/dist/core/form.js +11 -5
  8. package/dist/core/groups.d.ts +17 -0
  9. package/dist/core/groups.js +31 -0
  10. package/dist/core/history.d.ts +41 -4
  11. package/dist/core/history.js +79 -12
  12. package/dist/core/index.d.ts +4 -3
  13. package/dist/core/index.js +4 -3
  14. package/dist/core/list.d.ts +3 -0
  15. package/dist/core/measure.d.ts +14 -5
  16. package/dist/core/measure.js +32 -7
  17. package/dist/core/present.d.ts +51 -3
  18. package/dist/core/present.js +162 -15
  19. package/dist/core/summary.d.ts +6 -2
  20. package/dist/react/context.d.ts +26 -2
  21. package/dist/react/context.js +56 -2
  22. package/dist/react/useGroups.js +15 -4
  23. package/dist/react/useHistory.d.ts +4 -2
  24. package/dist/react/useHistory.js +20 -5
  25. package/dist/react/usePivot.js +18 -3
  26. package/dist/react/useRecord.d.ts +3 -0
  27. package/dist/react/useRecord.js +14 -2
  28. package/dist/web/Refused.d.ts +3 -3
  29. package/dist/web/Refused.js +3 -3
  30. package/dist/web/index.d.ts +3 -2
  31. package/dist/web/index.js +2 -1
  32. package/dist/web/list/EntityList.d.ts +4 -1
  33. package/dist/web/list/EntityList.js +69 -21
  34. package/dist/web/list/EntitySearchBar.d.ts +6 -2
  35. package/dist/web/list/EntitySearchBar.js +11 -3
  36. package/dist/web/list/columns.d.ts +6 -1
  37. package/dist/web/list/columns.js +81 -9
  38. package/dist/web/list/presentation.d.ts +20 -1
  39. package/dist/web/list/search.d.ts +14 -5
  40. package/dist/web/list/search.js +29 -14
  41. package/dist/web/record/ActionButton.d.ts +14 -4
  42. package/dist/web/record/ActionButton.js +45 -2
  43. package/dist/web/record/CommandButton.d.ts +10 -1
  44. package/dist/web/record/CommandButton.js +23 -4
  45. package/dist/web/record/RelatedList.d.ts +0 -15
  46. package/dist/web/record/RelatedList.js +35 -6
  47. package/dist/web/record/ServiceButton.d.ts +20 -4
  48. package/dist/web/record/ServiceButton.js +30 -5
  49. package/dist/web/record/ask.d.ts +59 -0
  50. package/dist/web/record/ask.js +59 -0
  51. package/dist/web/record/control.d.ts +2 -2
  52. package/dist/web/record/control.js +7 -3
  53. package/dist/web/record/edit.d.ts +6 -1
  54. package/dist/web/record/edit.js +56 -8
  55. package/dist/web/record/record.js +5 -2
  56. package/dist/web/workspace/SincproApp.d.ts +10 -1
  57. package/dist/web/workspace/SincproApp.js +18 -4
  58. package/dist/web/workspace/composer.d.ts +7 -2
  59. package/dist/web/workspace/composer.js +24 -4
  60. package/dist/web/workspace/record.d.ts +7 -2
  61. package/dist/web/workspace/record.js +31 -6
  62. package/package.json +7 -7
package/README.md CHANGED
@@ -213,6 +213,20 @@ workspace (`domain:kind`). `summary` only when its fields are not the convention
213
213
  on sincpro_framework does not write them: `sincpro-client generate` does, from its contract
214
214
  («From the contract», below).
215
215
 
216
+ `summary` is how an application says which of its fields plays each part of a record — its
217
+ state, its type, its description, its picture, who made it. The convention only knows English
218
+ names (`state`/`status`, `type`/`kind`/`category`, `description`/`summary`, `image`…): a model
219
+ whose state is `estado` names it, or its header shows no state and its rows no tag. Guessing is
220
+ not safe — an entity may hold two choices — so a field not named this way plays no part.
221
+
222
+ ```ts
223
+ // quipu's payment: Spanish field names, said once.
224
+ export const payments = {
225
+ ...generated.pagos,
226
+ summary: { state: "estado", description: "descripcion" },
227
+ };
228
+ ```
229
+
216
230
  ```ts
217
231
  import { entity } from "@sincpro/client-framework";
218
232
 
@@ -229,6 +243,21 @@ export const invoices = entity<Invoice>("sales:invoice", {
229
243
  });
230
244
  ```
231
245
 
246
+ An entity with neither `edit` nor `save` — a payment, an order that only its Commands move — has
247
+ its records drawn read only, whole: nothing on screen invites typing what nobody can store.
248
+
249
+ **How a record looks** is the client's, declared once with the entity (`presented`): its row,
250
+ card and option, the columns of a table of it, the colour of each value of a choice and of each
251
+ kind of fact in its history. Cells, rows, cards, the record's tag and its activity use them:
252
+
253
+ ```ts
254
+ export const payments = presented(entity<Payment>("billing:payment", { list: "/payments" }), {
255
+ tones: { estado: { EN_REVISION: "warn", VALIDADO: "good", RECHAZADO: "bad" } },
256
+ facts: { pago_aprobado: "good", pago_rechazado: "bad" }, // by a fact's `name`, or its last part
257
+ columns: ["periodo", "monto", "estado"],
258
+ });
259
+ ```
260
+
232
261
  **4. The views** — each entity becomes a composer view: its list without an id, its record with
233
262
  one, its search in ⌘K. Declared and nothing more, it already has both screens, drawn from its
234
263
  model: `EntityList` (literal search on Enter, pages, «New») and `EntityRecord` (its name, type and
@@ -38,6 +38,10 @@ export type FrameworkCopy = {
38
38
  groupsCapped: (shown: number) => string;
39
39
  /** «12 groups · 187 records»: what the grouping split. */
40
40
  groups: (groups: number, records: number) => string;
41
+ /** The foot adds up the rows in hand, and they are not the whole set. */
42
+ pageTotals: string;
43
+ /** A grouped question answered with something that is not groups. */
44
+ notGrouped: string;
41
45
  };
42
46
  record: {
43
47
  /** A draft this caller kept is back on screen. */
@@ -90,15 +94,23 @@ export type FrameworkCopy = {
90
94
  cancel: string;
91
95
  /** While the dry run is asked. */
92
96
  rehearsing: string;
97
+ /** Sends what an action asked for (`ask`). */
98
+ send: string;
93
99
  };
94
100
  failure: {
95
101
  /** The server could not be reached at all — nothing it said is known. */
96
102
  unreachable: string;
103
+ /** It answered, but not what was asked (a grouped question answered with records). */
104
+ unexpected: string;
97
105
  /** It answered with a status and no problem to read. */
98
106
  status: (status: number) => string;
99
107
  retry: string;
100
- /** What each kind of refusal is called when the server sent no title of its own. */
108
+ /** What each kind of refusal is called — the heading, before the server's own `title`. */
101
109
  kind: Record<FailureKind, string>;
110
+ /** What to do next, by kind, when it is the same whatever was refused. A kind left out
111
+ * (`invalid`, `domain`) keeps the server's `guidance`: only the use case knows what fixes
112
+ * its own refusal. */
113
+ next: Partial<Record<FailureKind, string>>;
102
114
  };
103
115
  };
104
116
  export declare const ENGLISH_FRAMEWORK_COPY: FrameworkCopy;
package/dist/core/copy.js CHANGED
@@ -19,6 +19,8 @@ export const ENGLISH_FRAMEWORK_COPY = {
19
19
  noValue: "No value",
20
20
  groupsCapped: (shown) => `The first ${shown} groups. Narrow the search to see the rest.`,
21
21
  groups: (groups, records) => `${groups} ${groups === 1 ? "group" : "groups"} · ${records} ${records === 1 ? "record" : "records"}`,
22
+ pageTotals: "Totals of this page",
23
+ notGrouped: "The server did not answer with groups: this list cannot be grouped there.",
22
24
  },
23
25
  record: {
24
26
  restored: "A draft you kept is back. Save it or discard it.",
@@ -51,9 +53,11 @@ export const ENGLISH_FRAMEWORK_COPY = {
51
53
  confirm: "Do it",
52
54
  cancel: "Cancel",
53
55
  rehearsing: "Checking what it would do…",
56
+ send: "Confirm",
54
57
  },
55
58
  failure: {
56
59
  unreachable: "The server could not be reached",
60
+ unexpected: "The server answered something else",
57
61
  status: (status) => `The server answered ${status}`,
58
62
  retry: "Retry",
59
63
  kind: {
@@ -70,6 +74,17 @@ export const ENGLISH_FRAMEWORK_COPY = {
70
74
  unknown_outcome: "It is not known whether it was done",
71
75
  internal: "Something failed on the server",
72
76
  },
77
+ next: {
78
+ permission_denied: "Ask whoever administers it for access.",
79
+ not_found: "It may have been deleted, or the link is old.",
80
+ conflict: "Read it again before changing it.",
81
+ in_progress: "Wait a moment and look again.",
82
+ key_reused: "Read it again to see whether it was done.",
83
+ exhausted: "Wait a moment and try again.",
84
+ unavailable: "Try again in a few minutes.",
85
+ unknown_outcome: "Read it again before repeating it.",
86
+ internal: "If it happens again, report it.",
87
+ },
73
88
  },
74
89
  };
75
90
  export const SPANISH_FRAMEWORK_COPY = {
@@ -93,6 +108,8 @@ export const SPANISH_FRAMEWORK_COPY = {
93
108
  noValue: "Sin valor",
94
109
  groupsCapped: (shown) => `Los primeros ${shown} grupos. Acotá la búsqueda para ver el resto.`,
95
110
  groups: (groups, records) => `${groups} ${groups === 1 ? "grupo" : "grupos"} · ${records} ${records === 1 ? "registro" : "registros"}`,
111
+ pageTotals: "Totales de esta página",
112
+ notGrouped: "El servidor no contestó con grupos: esta lista no se puede agrupar ahí.",
96
113
  },
97
114
  record: {
98
115
  restored: "Volvió un borrador que guardaste. Guardalo o descartalo.",
@@ -125,9 +142,11 @@ export const SPANISH_FRAMEWORK_COPY = {
125
142
  confirm: "Hacerlo",
126
143
  cancel: "Cancelar",
127
144
  rehearsing: "Revisando qué haría…",
145
+ send: "Confirmar",
128
146
  },
129
147
  failure: {
130
148
  unreachable: "No se pudo hablar con el servidor",
149
+ unexpected: "El servidor contestó otra cosa",
131
150
  status: (status) => `El servidor respondió ${status}`,
132
151
  retry: "Reintentar",
133
152
  kind: {
@@ -144,6 +163,17 @@ export const SPANISH_FRAMEWORK_COPY = {
144
163
  unknown_outcome: "No se sabe si se hizo",
145
164
  internal: "Algo falló en el servidor",
146
165
  },
166
+ next: {
167
+ permission_denied: "Pedí acceso a quien lo administra.",
168
+ not_found: "Puede que lo hayan eliminado, o el enlace es viejo.",
169
+ conflict: "Volvé a leerlo antes de cambiarlo.",
170
+ in_progress: "Esperá un momento y volvé a mirar.",
171
+ key_reused: "Volvé a leerlo para ver si se hizo.",
172
+ exhausted: "Esperá un momento y reintentá.",
173
+ unavailable: "Reintentá en unos minutos.",
174
+ unknown_outcome: "Volvé a leerlo antes de repetirlo.",
175
+ internal: "Si vuelve a pasar, avisá a soporte.",
176
+ },
147
177
  },
148
178
  };
149
179
  let installed = ENGLISH_FRAMEWORK_COPY;
@@ -1,12 +1,20 @@
1
1
  /**
2
2
  * What a person reads about a failure: a heading, and a sentence with what happened and what
3
- * to do. The server's own words first; the copy table's when it sent none.
3
+ * to do. The heading is the client's word for the kind of failure; the sentence is what the
4
+ * server said happened (`detail`) and what to do next — the copy table's for a kind whose next
5
+ * step is always the same, the server's `guidance` for one only the use case knows (`invalid`,
6
+ * `domain`).
4
7
  *
5
- * explain(new TransportError("/x", 403, { kind: "permission_denied", guidance: "Pedí acceso.", … }))
6
- * -> { heading: "No tenés acceso", sentence: "Pedí acceso.", retryable: false }
8
+ * explain(new TransportError("/x", 403, { kind: "permission_denied", detail: "No es tu pago.", … }))
9
+ * -> { heading: "No tenés acceso", sentence: "No es tu pago. Pedí acceso a quien lo administra.",
10
+ * retryable: false }
7
11
  *
8
12
  * Context: the transport is @sincpro/client-framework's and speaks no language; how a refusal
9
- * reads on a screen is the web's, with the words of its copy table.
13
+ * reads on a screen is the web's, with the words of its copy table. The server's `title` is one
14
+ * per kind and English until the language travels at the edge (sincpro_framework #190), and its
15
+ * default `guidance` too — so the heading and the generic next step are the copy's, and the
16
+ * server's words are kept where only it knows them: what happened, and how to fix a refusal of
17
+ * its own. quipu drew its own box because the server's English headed every refusal.
10
18
  */
11
19
  export declare function explain(error: unknown): {
12
20
  heading: string;
@@ -1,25 +1,37 @@
1
1
  import { TransportError } from "@sincpro/client-framework";
2
2
  import { frameworkCopy } from "./copy.js";
3
+ import { NotGrouped } from "./groups.js";
3
4
  /**
4
5
  * What a person reads about a failure: a heading, and a sentence with what happened and what
5
- * to do. The server's own words first; the copy table's when it sent none.
6
+ * to do. The heading is the client's word for the kind of failure; the sentence is what the
7
+ * server said happened (`detail`) and what to do next — the copy table's for a kind whose next
8
+ * step is always the same, the server's `guidance` for one only the use case knows (`invalid`,
9
+ * `domain`).
6
10
  *
7
- * explain(new TransportError("/x", 403, { kind: "permission_denied", guidance: "Pedí acceso.", … }))
8
- * -> { heading: "No tenés acceso", sentence: "Pedí acceso.", retryable: false }
11
+ * explain(new TransportError("/x", 403, { kind: "permission_denied", detail: "No es tu pago.", … }))
12
+ * -> { heading: "No tenés acceso", sentence: "No es tu pago. Pedí acceso a quien lo administra.",
13
+ * retryable: false }
9
14
  *
10
15
  * Context: the transport is @sincpro/client-framework's and speaks no language; how a refusal
11
- * reads on a screen is the web's, with the words of its copy table.
16
+ * reads on a screen is the web's, with the words of its copy table. The server's `title` is one
17
+ * per kind and English until the language travels at the edge (sincpro_framework #190), and its
18
+ * default `guidance` too — so the heading and the generic next step are the copy's, and the
19
+ * server's words are kept where only it knows them: what happened, and how to fix a refusal of
20
+ * its own. quipu drew its own box because the server's English headed every refusal.
12
21
  */
13
22
  export function explain(error) {
14
23
  const copy = frameworkCopy().failure;
15
24
  if (error instanceof TransportError && error.problem !== null) {
16
25
  const { kind, title, detail, guidance, retryable } = error.problem;
17
26
  return {
18
- heading: title ?? copy.kind[kind] ?? copy.status(error.status ?? 0),
19
- sentence: [detail, guidance].filter(Boolean).join(" "),
27
+ heading: copy.kind[kind] ?? title ?? copy.status(error.status ?? 0),
28
+ sentence: [detail, copy.next[kind] ?? guidance].filter(Boolean).join(" "),
20
29
  retryable,
21
30
  };
22
31
  }
32
+ // It answered, and not what was asked: retrying asks the same thing again.
33
+ if (error instanceof NotGrouped)
34
+ return { heading: copy.unexpected, sentence: error.message, retryable: false };
23
35
  if (error instanceof TransportError && error.status !== null)
24
36
  return { heading: copy.status(error.status), sentence: error.message, retryable: true };
25
37
  return {
@@ -6,16 +6,20 @@ import type { Meta } from "@sincpro/criteria";
6
6
  *
7
7
  * Context: the default form must be useful on any entity, not a dump of every key. So:
8
8
  *
9
- * - the bookkeeping (`version`, `updated_at`) and who made and changed it are not fields: the
10
- * paper says them on its last line (`Record.Audit`); the picture is not a text box;
9
+ * - the framework's stamps (`version`, who made and changed it and when, `archived_at`) are not
10
+ * fields: the paper says them on its last line (`Record.Audit`) and the activity says the
11
+ * rest; the picture is not a text box;
11
12
  * - a read-only identity is the record's name, not a field to look at;
12
13
  * - a many2one is written by its KEY (`customer_id`, a picker of customers): the expanded
13
14
  * relation beside it (`customer`) would be the same thing twice;
14
15
  * - a one2many is a page of its own — a list, not a field;
15
- * - a value object, and a many2many the backend cannot write yet, are left to the screen.
16
+ * - a value object the record embeds (a payment's receipt) is a section of its own fields, read
17
+ * from its definition (`sections`, each field named `recibo.numero`); a money stays a field;
18
+ * - a list of values and a many2many the backend cannot write yet are left to the screen.
16
19
  */
17
20
  export type FormLayout = {
18
21
  fields: string[];
19
22
  pages: string[];
23
+ sections: string[];
20
24
  };
21
25
  export declare function formOf(meta: Meta | null | undefined, summary?: SummaryFields): FormLayout;
package/dist/core/form.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import {} from "@sincpro/client-framework";
2
- import { BOOKKEEPING } from "./present.js";
2
+ import { BOOKKEEPING, isMoneyDefinition, STAMPS } from "./present.js";
3
3
  import { summaryFieldsOf } from "./summary.js";
4
4
  export function formOf(meta, summary = {}) {
5
5
  if (!meta)
6
- return { fields: [], pages: [] };
6
+ return { fields: [], pages: [], sections: [] };
7
7
  const parts = summaryFieldsOf(meta, {}, summary);
8
8
  const told = new Set([parts.createdAt, parts.createdBy, parts.updatedAt, parts.updatedBy, parts.image].filter((name) => name !== undefined));
9
9
  const keys = new Set(Object.values(meta.fields)
@@ -11,13 +11,19 @@ export function formOf(meta, summary = {}) {
11
11
  .filter((name) => typeof name === "string" && name in meta.fields));
12
12
  const fields = [];
13
13
  const pages = [];
14
+ const sections = [];
14
15
  for (const [name, field] of Object.entries(meta.fields)) {
15
- if (BOOKKEEPING.has(name) || told.has(name))
16
+ if (BOOKKEEPING.has(name) || STAMPS.has(name) || told.has(name))
16
17
  continue;
17
18
  if (name === meta.identity && field.readonly)
18
19
  continue;
19
- if (field.kind === "embedded")
20
+ if (field.kind === "embedded") {
21
+ // A money is one value; any other value object with a definition is its fields.
22
+ const money = field.widget === "money" || isMoneyDefinition(field.definition);
23
+ if (field.many !== true && field.definition && !money)
24
+ sections.push(name);
20
25
  continue;
26
+ }
21
27
  if (field.kind === "relation") {
22
28
  if (field.type === "one2many")
23
29
  pages.push(name);
@@ -27,5 +33,5 @@ export function formOf(meta, summary = {}) {
27
33
  }
28
34
  fields.push(name);
29
35
  }
30
- return { fields, pages };
36
+ return { fields, pages, sections };
31
37
  }
@@ -0,0 +1,17 @@
1
+ import type { Bucket } from "@sincpro/criteria";
2
+ /**
3
+ * Whether an answer to a grouped question holds groups — each with how many records it holds
4
+ * (`count`) and the criteria that opens it, its levels below too.
5
+ *
6
+ * Context: a backend that does not group answers records to the same question (sincpro_framework
7
+ * before 3.37.1, a fake that never learned), and a record read as a group has no `count`: web-ui's
8
+ * table fell over drawing it, and drawing «—» instead would show N empty groups that look valid
9
+ * (web-ui decided so in Sincpro-SRL/sincpro_web_ui#33). So the answer is checked here, once, and
10
+ * a list that got no groups says so in its failed state.
11
+ */
12
+ export declare function areGroups(rows: readonly unknown[]): rows is readonly Bucket[];
13
+ /** What a grouped question was answered with when it was not groups: the list's failure. */
14
+ export declare class NotGrouped extends Error {
15
+ readonly route: string;
16
+ constructor(route: string);
17
+ }
@@ -0,0 +1,31 @@
1
+ import { frameworkCopy } from "./copy.js";
2
+ /**
3
+ * Whether an answer to a grouped question holds groups — each with how many records it holds
4
+ * (`count`) and the criteria that opens it, its levels below too.
5
+ *
6
+ * Context: a backend that does not group answers records to the same question (sincpro_framework
7
+ * before 3.37.1, a fake that never learned), and a record read as a group has no `count`: web-ui's
8
+ * table fell over drawing it, and drawing «—» instead would show N empty groups that look valid
9
+ * (web-ui decided so in Sincpro-SRL/sincpro_web_ui#33). So the answer is checked here, once, and
10
+ * a list that got no groups says so in its failed state.
11
+ */
12
+ export function areGroups(rows) {
13
+ return rows.every((row) => {
14
+ if (typeof row !== "object" || row === null)
15
+ return false;
16
+ const bucket = row;
17
+ return (typeof bucket.count === "number" &&
18
+ typeof bucket.criteria === "object" &&
19
+ bucket.criteria !== null &&
20
+ (bucket.groups === undefined || areGroups(bucket.groups)));
21
+ });
22
+ }
23
+ /** What a grouped question was answered with when it was not groups: the list's failure. */
24
+ export class NotGrouped extends Error {
25
+ route;
26
+ constructor(route) {
27
+ super(frameworkCopy().list.notGrouped);
28
+ this.route = route;
29
+ this.name = "NotGrouped";
30
+ }
31
+ }
@@ -13,9 +13,18 @@ import { type AnyRecord, type Meta } from "@sincpro/criteria";
13
13
  * observability stack, not to a record's screen.
14
14
  *
15
15
  * Since sincpro_framework 3.37 every fact also says which one it is (`name`, `billing.v1.deleted`),
16
- * who did it (`actor`, the context's user) and who the record was then (`entity_display`), and
17
- * the contract labels a subclass's own fields (`reason` → «Motivo»). Who did it is the entry's
18
- * `by` — web-ui's activity draws it —; the rest of the envelope never repeats in its detail.
16
+ * who did it (`actor`, the context's user — from the caller's identity since 3.37.1) and who the
17
+ * record was then (`entity_display`). Who did it is the entry's `by` — web-ui's activity draws
18
+ * it —; the rest of the envelope never repeats in its detail. What a fact's own fields are
19
+ * called is its event's definition in the contract (3.37.1): `eventMetasOf(contract)`
20
+ * (client-framework), by the fact's `name` — «reason» reads «Motivo» —, given to the provider as
21
+ * `events`; without it, the history route's own definition.
22
+ *
23
+ * An edit (`EntityUpdated`) carries each field it moved as `changes: {field: [before, after]}`
24
+ * and the word it was called then (`field_labels`, kept because an audit says what a person saw
25
+ * at the time): it reads «Título: Bienvenidos → Bienvenidos al CAUOR», each side as the record's
26
+ * own model writes it (a state by its word, an amount as money, a date in the installed style).
27
+ * quipu wrote this formatter itself, because the detail read `changes: {…} · field_labels: {…}`.
19
28
  */
20
29
  export type HistoryEntry = {
21
30
  id: string;
@@ -24,5 +33,33 @@ export type HistoryEntry = {
24
33
  /** Who did it, as the fact says (`actor`); absent: the system, or a backend before 3.37. */
25
34
  by?: string;
26
35
  detail?: string;
36
+ /** The colour of this kind of fact (`FACT_TONES`, or the application's by `name`). */
37
+ tone?: FactTone;
27
38
  };
28
- export declare function historyOf(rows: readonly AnyRecord[], meta: Meta | null | undefined, locale?: string): HistoryEntry[];
39
+ /** The tones a fact may take — web-ui's `Tone`, named here because `core/` imports no UI. */
40
+ export type FactTone = "neutral" | "info" | "good" | "warn" | "bad" | "accent";
41
+ /**
42
+ * The colour of a kind of fact, by its `name` — whole (`quipu.pagos.v1.pago_aprobado`) or its
43
+ * last part (`pago_aprobado`), so a version bump keeps it. These are the framework's own facts
44
+ * of a record's life; an application names its own (`presented(entity, { facts })`), over these.
45
+ * An edit and a creation carry no tone: they are the ordinary life of a record.
46
+ */
47
+ export declare const FACT_TONES: Readonly<Record<string, FactTone>>;
48
+ /** The tone of a fact by its name, among `tones`; none when nothing names it. */
49
+ export declare function toneOfFact(name: unknown, tones?: Readonly<Record<string, FactTone>>): FactTone | undefined;
50
+ /**
51
+ * The facts of a record as entries of web-ui's activity.
52
+ *
53
+ * historyOf(rows, eventsMeta, "es", { record: pagoMeta, tones: { pago_aprobado: "good" } })
54
+ * -> [{ label: "Se actualizó", detail: "Estado: En revisión → Validado", by: "ana", … }]
55
+ *
56
+ * `meta` is the history route's definition; `events` each event's own, by its wire name
57
+ * (`eventMetasOf(contract)`), which names a fact's own fields first; `record` is the record's,
58
+ * which writes each side of an edit. `tones` colour each kind of fact by its `name`, over the
59
+ * framework's own (`FACT_TONES`).
60
+ */
61
+ export declare function historyOf(rows: readonly AnyRecord[], meta: Meta | null | undefined, locale?: string, options?: {
62
+ record?: Meta | null | undefined;
63
+ events?: Readonly<Record<string, Meta>> | undefined;
64
+ tones?: Readonly<Record<string, FactTone>> | undefined;
65
+ }): HistoryEntry[];
@@ -1,5 +1,23 @@
1
1
  import { labelOf } from "@sincpro/criteria";
2
2
  import { frameworkCopy } from "./copy.js";
3
+ import { textOf } from "./present.js";
4
+ /**
5
+ * The colour of a kind of fact, by its `name` — whole (`quipu.pagos.v1.pago_aprobado`) or its
6
+ * last part (`pago_aprobado`), so a version bump keeps it. These are the framework's own facts
7
+ * of a record's life; an application names its own (`presented(entity, { facts })`), over these.
8
+ * An edit and a creation carry no tone: they are the ordinary life of a record.
9
+ */
10
+ export const FACT_TONES = {
11
+ deleted: "bad",
12
+ archived: "warn",
13
+ restored: "info",
14
+ };
15
+ /** The tone of a fact by its name, among `tones`; none when nothing names it. */
16
+ export function toneOfFact(name, tones = FACT_TONES) {
17
+ if (typeof name !== "string" || name === "")
18
+ return undefined;
19
+ return tones[name] ?? tones[name.slice(name.lastIndexOf(".") + 1)];
20
+ }
3
21
  /** What every fact carries: what remains is what this fact says. */
4
22
  const ENVELOPE = new Set([
5
23
  "id",
@@ -15,6 +33,9 @@ const ENVELOPE = new Set([
15
33
  "actor",
16
34
  "correlation_id",
17
35
  "causation_id",
36
+ // An edit's own: drawn as «Field: before → after», never as JSON.
37
+ "changes",
38
+ "field_labels",
18
39
  ]);
19
40
  function said(value) {
20
41
  if (value === null || value === undefined || value === "")
@@ -23,27 +44,73 @@ function said(value) {
23
44
  return value.length === 0 ? null : value.map(String).join(", ");
24
45
  return typeof value === "object" ? JSON.stringify(value) : String(value);
25
46
  }
26
- export function historyOf(rows, meta, locale) {
47
+ /** A word in every language (`{default, es}`), or a plain one, in `locale`. */
48
+ function wordOf(word, locale) {
49
+ if (typeof word === "string")
50
+ return word === "" ? undefined : word;
51
+ return (locale ? word?.[locale] : undefined) ?? word?.["default"];
52
+ }
53
+ /** One side of a change, as the record's model writes the field; nothing is «—». */
54
+ function sideOf(record, field, value, locale) {
55
+ // A record's own model writes it (a choice by its word, money as money); without one, a
56
+ // boolean is still the copy table's word and never «true».
57
+ const text = typeof value === "boolean" && !record?.fields[field]
58
+ ? value
59
+ ? frameworkCopy().value.yes
60
+ : frameworkCopy().value.no
61
+ : (textOf(record, field, value, locale) ?? said(value));
62
+ return text ?? "—";
63
+ }
64
+ /** What an edit moved: «Título: Bienvenidos → Bienvenidos al CAUOR», one per field. */
65
+ function changesOf(row, record, locale) {
66
+ const changes = row["changes"];
67
+ if (typeof changes !== "object" || changes === null || Array.isArray(changes))
68
+ return [];
69
+ const labels = (row["field_labels"] ?? {});
70
+ return Object.entries(changes).map(([field, pair]) => {
71
+ // `(before, after)` travels as a list; anything else is only what it is now.
72
+ const [before, after] = Array.isArray(pair) ? pair : [undefined, pair];
73
+ // The word it had THEN, else the record's model's, else its name.
74
+ const word = wordOf(labels[field], locale) ?? labelOf(record, field, locale);
75
+ return `${word}: ${sideOf(record, field, before, locale)} → ${sideOf(record, field, after, locale)}`;
76
+ });
77
+ }
78
+ /**
79
+ * The facts of a record as entries of web-ui's activity.
80
+ *
81
+ * historyOf(rows, eventsMeta, "es", { record: pagoMeta, tones: { pago_aprobado: "good" } })
82
+ * -> [{ label: "Se actualizó", detail: "Estado: En revisión → Validado", by: "ana", … }]
83
+ *
84
+ * `meta` is the history route's definition; `events` each event's own, by its wire name
85
+ * (`eventMetasOf(contract)`), which names a fact's own fields first; `record` is the record's,
86
+ * which writes each side of an edit. `tones` colour each kind of fact by its `name`, over the
87
+ * framework's own (`FACT_TONES`).
88
+ */
89
+ export function historyOf(rows, meta, locale, options = {}) {
90
+ const tones = { ...FACT_TONES, ...options.tones };
27
91
  return rows.map((row) => {
28
92
  const label = row["label"];
29
- const word = typeof label === "string"
30
- ? label
31
- : // A fact without a label is still a change; its id is not a word anyone reads.
32
- ((locale ? label?.[locale] : undefined) ??
33
- label?.["default"] ??
34
- frameworkCopy().summary.recorded);
35
- const parts = Object.entries(row)
36
- .filter(([key]) => !ENVELOPE.has(key))
37
- .map(([key, value]) => [key, said(value)])
38
- .filter(([, value]) => value !== null && value !== row["entity_id"])
39
- .map(([key, value]) => `${labelOf(meta, key, locale)}: ${value}`);
93
+ // A fact without a label is still a change; its id is not a word anyone reads.
94
+ const word = wordOf(label, locale) ?? frameworkCopy().summary.recorded;
95
+ // This kind of fact's own definition names its fields; the route's, when it is not known.
96
+ const own = (typeof row["name"] === "string" && options.events?.[row["name"]]) || meta;
97
+ const parts = [
98
+ ...changesOf(row, options.record, locale),
99
+ ...Object.entries(row)
100
+ .filter(([key]) => !ENVELOPE.has(key))
101
+ .map(([key, value]) => [key, said(value)])
102
+ .filter(([, value]) => value !== null && value !== row["entity_id"])
103
+ .map(([key, value]) => `${labelOf(own, key, locale)}: ${value}`),
104
+ ];
40
105
  const actor = said(row["actor"]);
106
+ const tone = toneOfFact(row["name"], tones);
41
107
  return {
42
108
  id: String(row["id"]),
43
109
  label: word,
44
110
  at: String(row["created_at"] ?? ""),
45
111
  ...(actor === null ? {} : { by: actor }),
46
112
  ...(parts.length === 0 ? {} : { detail: parts.join(" · ") }),
113
+ ...(tone === undefined ? {} : { tone }),
47
114
  };
48
115
  });
49
116
  }
@@ -12,12 +12,13 @@ export { ENGLISH_FRAMEWORK_COPY, type FrameworkCopy, frameworkCopy, installFrame
12
12
  export { type Advice, adviceAt, changesOf, computedLocally, creationOf, defaultsOf, editedOf, errorAt, errorsByField, type FieldState, fieldStateOf, type FieldStates, linePlacesOf, lineStatesOf, missingOf, needsPreview, pathOf, type ServerFieldState, } from "./edit.js";
13
13
  export { explain } from "./explain.js";
14
14
  export { type FormLayout, formOf } from "./form.js";
15
- export { type HistoryEntry, historyOf } from "./history.js";
15
+ export { areGroups, NotGrouped } from "./groups.js";
16
+ export { FACT_TONES, type FactTone, type HistoryEntry, historyOf, toneOfFact, } from "./history.js";
16
17
  export { addingOf, type AddingRule, blankLine, type Declared, editableLines, isReference, type LineAdding, lineFields, lineKey, linesAnswered, moved, sameLine, writtenInCell, } from "./lines.js";
17
18
  export { defineList, type GroupLevel, isList, type ListDefinition, type ListSpec, type NamedFilter, scopeOf, trashOf, } from "./list.js";
18
19
  export { lookupOf, type LookupOption } from "./lookup.js";
19
- export { detailOf, measuresOf, sumsOf } from "./measure.js";
20
- export { BOOKKEEPING, dayTextOf, defaultFields, type FieldView, instantTextOf, moneyTextOf, numberTextOf, sortKeyOf, textOf, viewOf, } from "./present.js";
20
+ export { detailOf, measuresOf, sumsOf, type Total, totalOf, } from "./measure.js";
21
+ export { BOOKKEEPING, currencyNow, type DateStyle, dateStyleNow, dayTextOf, defaultFields, fieldAt, fieldMetaOf, type FieldView, installCurrency, installDateStyle, instantTextOf, moneyTextOf, numberTextOf, sortKeyOf, STAMPS, textOf, valueAt, viewOf, } from "./present.js";
21
22
  export { type Related, relatedOf } from "./related.js";
22
23
  export { backReference, entityFor, relatedScope, type RelationField, relationFieldOf, } from "./relation.js";
23
24
  export { type RecordSummary, summaryFieldsOf, summaryOf, } from "./summary.js";
@@ -12,12 +12,13 @@ export { ENGLISH_FRAMEWORK_COPY, frameworkCopy, installFrameworkCopy, SPANISH_FR
12
12
  export { adviceAt, changesOf, computedLocally, creationOf, defaultsOf, editedOf, errorAt, errorsByField, fieldStateOf, linePlacesOf, lineStatesOf, missingOf, needsPreview, pathOf, } from "./edit.js";
13
13
  export { explain } from "./explain.js";
14
14
  export { formOf } from "./form.js";
15
- export { historyOf } from "./history.js";
15
+ export { areGroups, NotGrouped } from "./groups.js";
16
+ export { FACT_TONES, historyOf, toneOfFact, } from "./history.js";
16
17
  export { addingOf, blankLine, editableLines, isReference, lineFields, lineKey, linesAnswered, moved, sameLine, writtenInCell, } from "./lines.js";
17
18
  export { defineList, isList, scopeOf, trashOf, } from "./list.js";
18
19
  export { lookupOf } from "./lookup.js";
19
- export { detailOf, measuresOf, sumsOf } from "./measure.js";
20
- export { BOOKKEEPING, dayTextOf, defaultFields, instantTextOf, moneyTextOf, numberTextOf, sortKeyOf, textOf, viewOf, } from "./present.js";
20
+ export { detailOf, measuresOf, sumsOf, totalOf, } from "./measure.js";
21
+ export { BOOKKEEPING, currencyNow, dateStyleNow, dayTextOf, defaultFields, fieldAt, fieldMetaOf, installCurrency, installDateStyle, instantTextOf, moneyTextOf, numberTextOf, sortKeyOf, STAMPS, textOf, valueAt, viewOf, } from "./present.js";
21
22
  export { relatedOf } from "./related.js";
22
23
  export { backReference, entityFor, relatedScope, relationFieldOf, } from "./relation.js";
23
24
  export { summaryFieldsOf, summaryOf, } from "./summary.js";
@@ -40,6 +40,9 @@ export type ListDefinition<T extends AnyRecord = AnyRecord> = {
40
40
  columns?: readonly string[];
41
41
  /** The cuts it offers by name in the search bar. */
42
42
  filters?: readonly NamedFilter<T>[];
43
+ /** The fields the search bar offers to look a typed text up in, in order — «Buscar Nombres:
44
+ * Excel». Without it, the ones the entity's search template names, else its display. */
45
+ facets?: readonly string[];
43
46
  /** The faces it offers, the first one shown. */
44
47
  views?: readonly ("table" | "rows" | "board" | "sheet" | "pivot")[];
45
48
  /** Grouped from the start — the server counts the groups. */
@@ -1,16 +1,25 @@
1
1
  import { type Measure, type Meta } from "@sincpro/criteria";
2
+ /**
3
+ * How the model adds a field up (`Presentation.totals` on the server, `"total": "sum"` in the
4
+ * Meta), as one of the functions a screen draws; none when it says nothing, or names one this
5
+ * package does not draw.
6
+ */
7
+ export type Total = "sum" | "avg" | "min" | "max";
8
+ export declare function totalOf(meta: Meta | null | undefined, name: string): Total | undefined;
2
9
  /**
3
10
  * What a group ADDS UP TO — «Total 1.204.933,00» beside «Pagadas · 187» — summed by the server
4
11
  * over every row of the group, never the page.
5
12
  *
6
13
  * Context: a count says how many; whoever groups invoices by state wants to know how much. Which
7
- * fields add up is the domain's, and the model does not say it yet, so the default is the
8
- * figure a record computes: an exact number that is read-only (a total, a subtotal, a balance).
9
- * What a person types — a discount, a percentage, a limit — is not added up: a sum of
14
+ * fields add up is the domain's: the model says it with `total` (sincpro_framework's
15
+ * `Presentation.totals`), and those are the default. A model that says nothing falls back to
16
+ * the figure a record computes: an exact number that is read-only (a total, a subtotal, a
17
+ * balance). What a person types — a discount, a percentage, a limit — is not added up: a sum of
10
18
  * percentages means nothing. A screen names its own (`EntityList sums`).
11
19
  */
12
20
  export declare function sumsOf(meta: Meta | null | undefined): string[];
13
- /** The grouping's measures for these fields, each under its own name. */
14
- export declare function measuresOf(fields: readonly string[]): Record<string, Measure>;
21
+ /** The grouping's measures for these fields, each under its own name — by the function the
22
+ * model adds it up with (`total`), a sum when it names none. */
23
+ export declare function measuresOf(fields: readonly string[], meta?: Meta | null): Record<string, Measure>;
15
24
  /** What a group's measures read as: «Total 1.204.933,00 · Saldo 12,50». */
16
25
  export declare function detailOf(meta: Meta | null | undefined, measures: Readonly<Record<string, unknown>> | undefined, locale?: string): string | undefined;