suppa-mcp-2 1.46.1 → 1.47.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.
@@ -0,0 +1,817 @@
1
+ /**
2
+ * Registers — the platform's 1C-style accumulation and information registers
3
+ * (entity-builder `src/common/registers`, REST `/core/registers`).
4
+ *
5
+ * Every shape, limit and code here is the platform documentation's, cited by
6
+ * page: `documents` repo, develop —
7
+ * api = src/api/entity-builder/registers.md
8
+ * arch = src/architecture/entity-builder/registers.md
9
+ * app = src/application-developing/data/registers.md
10
+ * and, where the documentation is silent, the entity-builder source it
11
+ * describes (named in place). The same knowledge, for the model, is the bundled
12
+ * skill skills/suppa-registers — suppa_registers_kb serves it.
13
+ *
14
+ * What this module adds over raw calls:
15
+ * - a register is created with its roles checked BEFORE the request (a wrong
16
+ * one is a 400 after nothing, but a frozen option set wrong is a new register);
17
+ * - a rule is written by NAMES and previewed on a document before the write;
18
+ * - a repost shows the platform's dry run in its confirmation request;
19
+ * - every `register.*` refusal comes back as data with the step that fixes it.
20
+ */
21
+ import { existsSync, readFileSync } from "node:fs";
22
+ import { dirname, join } from "node:path";
23
+ import { fileURLToPath } from "node:url";
24
+ import { ApiError, dataUrl, makeRequest, searchEntity } from "../httpClient.js";
25
+ import { confirmRequired, jsonResponse, parseJsonParam } from "../utils.js";
26
+ import { _entityNameProblem, _expandTitle, buildFieldDef } from "./entity.js";
27
+ const BASE = "/api/core/registers";
28
+ const RULES_ENTITY = "RegisterPostingRules";
29
+ const seg = (s) => encodeURIComponent(String(s));
30
+ // ---------------------------------------------------------------------------
31
+ // The skill
32
+ // ---------------------------------------------------------------------------
33
+ export const KB_TOPICS = ["concepts", "rules", "reads", "operations", "errors"];
34
+ /** A file of the bundled skill, from the source tree or the published package. */
35
+ export function registersSkillFile(...parts) {
36
+ const here = dirname(fileURLToPath(import.meta.url));
37
+ for (const root of [join(here, "..", ".."), join(here, "..", "..", "..")]) {
38
+ const p = join(root, "skills", "suppa-registers", ...parts);
39
+ if (existsSync(p))
40
+ return p;
41
+ }
42
+ return null;
43
+ }
44
+ export async function registersKb(topic) {
45
+ if (!topic) {
46
+ const file = registersSkillFile("SKILL.md");
47
+ if (!file)
48
+ return jsonResponse({ error: "The suppa-registers skill is missing from this install — reinstall suppa-mcp-2." });
49
+ const text = readFileSync(file, "utf-8").replace(/^---[\s\S]*?---\s*/, "");
50
+ return jsonResponse({ topic: "overview", topics: [...KB_TOPICS], text });
51
+ }
52
+ if (!KB_TOPICS.includes(topic)) {
53
+ return jsonResponse({ error: `Unknown topic '${topic}'.`, topics: [...KB_TOPICS] });
54
+ }
55
+ const file = registersSkillFile("references", `${topic}.md`);
56
+ if (!file)
57
+ return jsonResponse({ error: `The topic file '${topic}.md' is missing from this install — reinstall suppa-mcp-2.` });
58
+ return jsonResponse({ topic, text: readFileSync(file, "utf-8") });
59
+ }
60
+ // ---------------------------------------------------------------------------
61
+ // Refusals: data with the next step (api "Errors")
62
+ // ---------------------------------------------------------------------------
63
+ /** What to do on each code — api "Errors" and the skill's errors topic. */
64
+ const NEXT_STEP = {
65
+ "register.balance_negative": "Not enough of a controlled resource: reduce the quantity, post a receipt first, or have an operator take the resource out of RegisterSettings.controlResources.",
66
+ "register.period_closed": "The movement falls before the register's closed date: change the document date, or an operator moves it — suppa_operate_register(action='close_period').",
67
+ "register.duplicate_record": "Another live record holds this key and period: update that record, or use another period.",
68
+ "register.rule_broken": "Save the register's rule again (suppa_save_posting_rule) — saving adds the recorder field.",
69
+ "register.maintenance": "Retryable: totals are suspended or rebuilding, or a job of the kind already runs (see reason). Wait retryAfterSec and retry; a running job is jobId — follow it with suppa_register_status(job_id).",
70
+ "register.concurrent_posting": "Retryable: a lock wait timed out. Retry once.",
71
+ "register.totals_suspended": "Totals are suspended: suppa_operate_register(action='resume_totals') starts a rebuild; movements stay readable meanwhile.",
72
+ "register.backlog": "The queue still holds documents of this register: wait until suppa_register_status shows pending 0, then retry.",
73
+ "register.mapping_failed": "A movement leaves a dimension empty: fill the document fields named in `fields`, or make the rule's expression total (COALESCE).",
74
+ "register.write_forbidden": "Movements, companions and RegisterStates are the engine's: write the DOCUMENT and let its rule post it; the closed date is suppa_operate_register(action='close_period').",
75
+ "register.forbidden": "A capability is missing (`permission`): the tenant owner grants it through the REGISTERS system permission.",
76
+ "register.invalid_definition": "The definition is refused (see reason). Frozen options never change — a new register under another name; `not_empty`: a dimension or resource with rows cannot change.",
77
+ "register.invalid_posting_rule": "Fix the rule definition (suppa_registers_kb topic='rules', the reason names what) and preview it again.",
78
+ "register.query_invalid": "Fix the argument the reason names (suppa_registers_kb topic='reads'); virtualTable names the alias of a suppa_query table.",
79
+ "register.permission_filter_not_dimension": "A permission group of a register may filter by a dimension only: change the group's filter.",
80
+ "register.posting_failed": "The engine could not finish the posting (500). Retry once; if it repeats, tell the user — it is a platform fault, not the document's.",
81
+ "validation.failed": "An unknown key or a wrong type — `violations` names it.",
82
+ "register.disabled": "Registers are off on this platform (REGISTERS_ENABLED=false). There is no workaround — tell the user.",
83
+ "register.not_found": "Unknown register, or a document the caller cannot read. suppa_register_status() lists the registers.",
84
+ "metadata.change_requires_resolution": "A posting rule reads this field (`dependents`): change the rule first.",
85
+ };
86
+ /**
87
+ * The body fields of a register error worth passing on (api "Errors";
88
+ * register-error-body.ts RegisterErrorContext / RegisterErrorBody). `jobId` is
89
+ * the job a `maintenance` refusal is about, `virtualTable` the alias a
90
+ * `/registers/query` refusal names, `retryAfterSec` the wait of a retryable one
91
+ * — without them the next step has nothing to act on.
92
+ */
93
+ const ERROR_FIELDS = [
94
+ "reason",
95
+ "register",
96
+ "recorder",
97
+ "jobId",
98
+ "virtualTable",
99
+ "retryAfterSec",
100
+ "shortages",
101
+ "basis",
102
+ "truncated",
103
+ "dimensions",
104
+ "row",
105
+ "fields",
106
+ "permission",
107
+ "violations",
108
+ "dependents",
109
+ ];
110
+ /** A register refusal as data, or null when `e` is not one (then it is rethrown). */
111
+ export function registerRefusal(e) {
112
+ if (!(e instanceof ApiError))
113
+ return null;
114
+ const body = e.parsedBody && typeof e.parsedBody === "object" ? e.parsedBody : null;
115
+ const code = typeof body?.code === "string" ? body.code : null;
116
+ if (!body || !code)
117
+ return null;
118
+ const out = { error: String(body.message ?? e.message), code, status: e.status };
119
+ for (const key of ERROR_FIELDS)
120
+ if (body[key] !== undefined)
121
+ out[key] = body[key];
122
+ const next = NEXT_STEP[code];
123
+ if (next)
124
+ out.next = next;
125
+ return out;
126
+ }
127
+ /** Run a request; a register refusal comes back as a JSON answer, anything else is thrown. */
128
+ async function call(work, onOk) {
129
+ try {
130
+ return jsonResponse(onOk(await work()));
131
+ }
132
+ catch (e) {
133
+ const refusal = registerRefusal(e);
134
+ if (refusal)
135
+ return jsonResponse(refusal);
136
+ throw e;
137
+ }
138
+ }
139
+ /** The JSON argument, or an error answer naming it. */
140
+ function parseArg(raw, param, expect) {
141
+ if (raw === null || raw === undefined || (typeof raw === "string" && raw.trim() === ""))
142
+ return {};
143
+ try {
144
+ return { value: parseJsonParam(raw, param, expect) };
145
+ }
146
+ catch (e) {
147
+ return { error: jsonResponse({ error: e instanceof Error ? e.message : String(e) }) };
148
+ }
149
+ }
150
+ // ---------------------------------------------------------------------------
151
+ // Create a register (arch "Kinds", "Fields and roles")
152
+ // ---------------------------------------------------------------------------
153
+ export const REGISTER_NAME_MAX = 24; // arch "Kinds"; register-option.types.ts REGISTER_NAME_MAX_LENGTH
154
+ export const MAX_DIMENSIONS = 8; // arch "Fields and roles"
155
+ export const MAX_RESOURCE_DECIMALS = 6;
156
+ export const REGISTER_KINDS = ["accumulation", "information"];
157
+ export const ACCUMULATION_TYPES = ["balance", "turnover"];
158
+ export const PERIODICITIES = ["none", "second", "day", "month", "quarter", "year"];
159
+ export const WRITE_MODES = ["independent", "recorder"];
160
+ export const ROLES = ["dimension", "resource", "attribute"];
161
+ /** Types each role takes (arch "Fields and roles"; register-field-role.util.ts). */
162
+ const ROLE_TYPES = {
163
+ dimension: ["many-to-one", "text", "integer", "boolean", "timestamp"],
164
+ resource: ["numeric", "integer"],
165
+ attribute: ["many-to-one", "text", "integer", "numeric", "boolean", "timestamp", "uuid"],
166
+ };
167
+ /**
168
+ * Names no declared field may take: the platform fields, the companions'
169
+ * columns (arch "Fields and roles"), and — for a dimension or resource — the
170
+ * keys a shortage row or the error sanitizer owns (register-error-body.ts
171
+ * SHORTAGE_RESERVED_KEYS).
172
+ */
173
+ const RESERVED_NAMES = new Set([
174
+ "period", "recorder", "lineNo", "recordKind", "active", "sourceLine", "template", "slot", "month", "moves",
175
+ ]);
176
+ const RESERVED_KEY_NAMES = new Set([
177
+ "resource", "balance", "shortage", "at", "code", "stack", "details", "query", "sql", "severity", "routine",
178
+ "where", "constraint", "internalQuery", "file", "line", "hint",
179
+ ]);
180
+ function validTimezone(tz) {
181
+ try {
182
+ new Intl.DateTimeFormat("en-US", { timeZone: tz });
183
+ return true;
184
+ }
185
+ catch {
186
+ return false;
187
+ }
188
+ }
189
+ /** Every problem of a register spec, before any request; empty = fine. */
190
+ export function registerSpecProblems(spec) {
191
+ const problems = [];
192
+ const nameProblem = _entityNameProblem(spec.name);
193
+ if (nameProblem)
194
+ problems.push(nameProblem);
195
+ if (spec.name.length > REGISTER_NAME_MAX) {
196
+ problems.push(`name '${spec.name}' has ${spec.name.length} characters; a register name has at most ${REGISTER_NAME_MAX}.`);
197
+ }
198
+ if (!REGISTER_KINDS.includes(spec.kind)) {
199
+ problems.push(`kind must be ${REGISTER_KINDS.join(" or ")}.`);
200
+ }
201
+ const accumulation = spec.kind === "accumulation";
202
+ if (accumulation) {
203
+ if (spec.periodicity)
204
+ problems.push("periodicity is for an information register; an accumulation register's movements carry the full moment (by day / month is a read's grain).");
205
+ if (spec.writeMode)
206
+ problems.push("write_mode is for an information register; an accumulation register is always written by its rules.");
207
+ if (spec.accumulationType && !ACCUMULATION_TYPES.includes(spec.accumulationType)) {
208
+ problems.push(`accumulation_type must be ${ACCUMULATION_TYPES.join(" or ")}.`);
209
+ }
210
+ }
211
+ else if (spec.kind === "information") {
212
+ if (spec.accumulationType)
213
+ problems.push("accumulation_type is for an accumulation register.");
214
+ if (!spec.periodicity || !PERIODICITIES.includes(spec.periodicity)) {
215
+ problems.push(`an information register needs periodicity: ${PERIODICITIES.join(", ")}.`);
216
+ }
217
+ if (spec.writeMode && !WRITE_MODES.includes(spec.writeMode)) {
218
+ problems.push(`write_mode must be ${WRITE_MODES.join(" or ")}.`);
219
+ }
220
+ }
221
+ if (!validTimezone(spec.timezone))
222
+ problems.push(`timezone '${spec.timezone}' is not an IANA zone (e.g. Europe/Kyiv).`);
223
+ const seen = new Set();
224
+ let dimensions = 0;
225
+ let resources = 0;
226
+ for (const [i, f] of spec.fields.entries()) {
227
+ const at = `fields[${i}]${f?.name ? ` '${f.name}'` : ""}`;
228
+ if (!f || typeof f !== "object" || typeof f.name !== "string" || !f.name) {
229
+ problems.push(`${at}: needs name, type and role.`);
230
+ continue;
231
+ }
232
+ if (seen.has(f.name))
233
+ problems.push(`${at}: the name appears twice.`);
234
+ seen.add(f.name);
235
+ if (RESERVED_NAMES.has(f.name))
236
+ problems.push(`${at}: '${f.name}' is the platform's — never declare period, recorder, lineNo, recordKind, active, sourceLine, template, slot, month, moves.`);
237
+ const role = f.role;
238
+ if (!ROLES.includes(role)) {
239
+ problems.push(`${at}: role must be ${ROLES.join(", ")}.`);
240
+ continue;
241
+ }
242
+ if (role !== "attribute" && RESERVED_KEY_NAMES.has(f.name))
243
+ problems.push(`${at}: a ${role} may not be named '${f.name}' (a key of the shortage row / error body).`);
244
+ if (!ROLE_TYPES[role].includes(f.type)) {
245
+ problems.push(`${at}: a ${role} takes ${ROLE_TYPES[role].join(", ")}, not '${f.type}'.`);
246
+ }
247
+ if (role === "dimension") {
248
+ dimensions += 1;
249
+ if (f.type === "timestamp" && f.sub_type !== "date")
250
+ problems.push(`${at}: a timestamp dimension must be a date (sub_type 'date') — every second would be its own key.`);
251
+ }
252
+ if (role === "resource") {
253
+ resources += 1;
254
+ if ((f.decimal_places ?? 0) > MAX_RESOURCE_DECIMALS)
255
+ problems.push(`${at}: a resource takes at most ${MAX_RESOURCE_DECIMALS} decimal places.`);
256
+ }
257
+ if (f.type === "many-to-one" && !f.relation_entity)
258
+ problems.push(`${at}: a many-to-one needs relation_entity.`);
259
+ }
260
+ if (dimensions > MAX_DIMENSIONS)
261
+ problems.push(`${dimensions} dimensions; a register takes at most ${MAX_DIMENSIONS}.`);
262
+ if (accumulation && resources === 0)
263
+ problems.push("an accumulation register needs at least one resource — the thing it sums.");
264
+ return problems;
265
+ }
266
+ export async function createRegister(name, title, kind, accumulationType, periodicity, writeMode, timezone, fieldsJson, confirm) {
267
+ const parsed = parseArg(fieldsJson, "fields_json", "array");
268
+ if (parsed.error)
269
+ return parsed.error;
270
+ const fields = (parsed.value ?? []);
271
+ // The zone freezes with the register, so it is never assumed: a default would give every tenant
272
+ // the same one without a word (review 2026-11-19).
273
+ if (typeof timezone !== "string" || !timezone.trim()) {
274
+ return jsonResponse({
275
+ error: "timezone is required: the IANA zone the register's days and months are counted in (e.g. Europe/Kyiv). It is frozen once the register exists — ask the user, do not assume it.",
276
+ });
277
+ }
278
+ const spec = { name, kind, accumulationType, periodicity, writeMode, timezone, fields };
279
+ const problems = registerSpecProblems(spec);
280
+ if (problems.length) {
281
+ return jsonResponse({
282
+ error: "Refused before any request — the register's kind, type, periodicity, write mode and timezone are frozen once created, so they are checked first.",
283
+ problems,
284
+ hint: "suppa_registers_kb(topic='concepts') has the roles and the types each takes.",
285
+ });
286
+ }
287
+ const defs = [];
288
+ for (const f of fields) {
289
+ const built = await buildFieldDef(name, f.name, f.type, f.title ?? null, {
290
+ relationEntity: f.relation_entity ?? null,
291
+ decimalPlaces: f.decimal_places ?? null,
292
+ subType: f.sub_type ?? null,
293
+ entityIsNew: true,
294
+ });
295
+ if (built.error)
296
+ return built.error;
297
+ // The role is the register's own field option (arch "Fields and roles");
298
+ // the platform makes a dimension NOT NULL and a resource of an accumulation
299
+ // register NOT NULL DEFAULT 0 itself (register-field-role.util.ts).
300
+ defs.push({ ...built.fieldDef, options: { ...(built.fieldDef?.options ?? {}), registerRole: f.role } });
301
+ }
302
+ const option = { kind, timezone };
303
+ if (kind === "accumulation")
304
+ option.accumulationType = accumulationType ?? "balance";
305
+ else {
306
+ option.periodicity = periodicity;
307
+ option.writeMode = writeMode ?? "independent";
308
+ }
309
+ const body = {
310
+ name,
311
+ title: await _expandTitle(title, name),
312
+ type: "register",
313
+ options: { register: option },
314
+ fields: defs,
315
+ };
316
+ // Gated, unlike suppa_create_entity: nothing this server has removes a register (the platform
317
+ // refuses a hard delete of its metadata — register-option.types.ts `hard_delete`), and its option
318
+ // never changes. The request shows the option as it will be stored, defaults written out.
319
+ if (!confirm) {
320
+ return confirmRequired("create register", { name, register: option }, { fields: fields.map((f) => ({ name: f.name, type: f.type, role: f.role, ...(f.relation_entity ? { relation_entity: f.relation_entity } : {}) })) }, [
321
+ `Frozen once created: ${Object.entries(option).map(([k, v]) => `${k}=${v}`).join(", ")}. A wrong one is a new register under another name.`,
322
+ "A register cannot be removed from here; a dimension or resource cannot change once the register has rows.",
323
+ ]);
324
+ }
325
+ return call(() => makeRequest("POST", "/api/core/builder/create-entity", body), (created) => ({
326
+ created: name,
327
+ id: created?.id ?? null,
328
+ register: option,
329
+ fields: fields.map((f) => ({ name: f.name, type: f.type, role: f.role })),
330
+ next: kind === "accumulation" || writeMode === "recorder"
331
+ ? "Rows come from posting rules: make the document entity a recorder (suppa_update_entity_options with {\"document\": true}), then suppa_save_posting_rule. Balance control is off until an operator sets RegisterSettings.controlResources."
332
+ : "Records are ordinary data: suppa_create_record. Read with suppa_read_register(kind='slice_last').",
333
+ }));
334
+ }
335
+ // ---------------------------------------------------------------------------
336
+ // Posting rules (arch "Posting rules", api "Rule Editor Preview")
337
+ // ---------------------------------------------------------------------------
338
+ /**
339
+ * A rule key as a TENANT may write it: register-rule.types.ts RULE_KEY_PATTERN and
340
+ * MAX_RULE_KEY_LENGTH, without ':' — the platform keeps that for an application's rule
341
+ * (`<app>:<key>`, register-rule-guard.extension.ts: `invalid_key` for a tenant writer), and a
342
+ * tenant cannot edit such a rule either (`application_rule`): it switches it off.
343
+ */
344
+ export const RULE_KEY_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
345
+ const RULE_DEFINITION_KEYS = ["link", "condition", "period", "movements"]; // register-rule.types.ts
346
+ const SQL_RULE_KEYS = ["sql", "link"]; // register-sql-rule.util.ts
347
+ const MAX_MOVEMENTS = 16;
348
+ async function schemaOf(entity) {
349
+ let schema;
350
+ try {
351
+ schema = await makeRequest("GET", `/api/core/schema/${seg(entity)}`);
352
+ }
353
+ catch (e) {
354
+ if (e instanceof ApiError && (e.status === 404 || e.status === 400))
355
+ return null;
356
+ throw e;
357
+ }
358
+ const s = (schema ?? {});
359
+ const raw = s.fields;
360
+ const fields = Array.isArray(raw)
361
+ ? raw
362
+ : raw && typeof raw === "object"
363
+ ? Object.entries(raw).map(([name, f]) => ({ ...f, name: f?.name ?? name }))
364
+ : [];
365
+ return {
366
+ id: typeof s.id === "number" ? s.id : null,
367
+ type: typeof s.type === "string" ? s.type : null,
368
+ fields,
369
+ options: s.options ?? {},
370
+ };
371
+ }
372
+ const roleOf = (f) => {
373
+ const r = f.options?.registerRole;
374
+ return typeof r === "string" ? r : null;
375
+ };
376
+ /** Problems of a rule definition the platform would refuse, checked against the register. */
377
+ export function ruleDefinitionProblems(definition, register, hasSource) {
378
+ const problems = [];
379
+ if (!definition || typeof definition !== "object" || Array.isArray(definition)) {
380
+ return ["definition must be an object: { link?, condition?, period?, movements } or { sql, link? }."];
381
+ }
382
+ const d = definition;
383
+ const isSql = "sql" in d;
384
+ const allowed = isSql ? SQL_RULE_KEYS : RULE_DEFINITION_KEYS;
385
+ const unknown = Object.keys(d).filter((k) => !allowed.includes(k));
386
+ if (unknown.length)
387
+ problems.push(`definition takes only ${allowed.join(", ")}; not ${unknown.join(", ")}.`);
388
+ if (hasSource && typeof d.link !== "string")
389
+ problems.push("a rule with a source needs definition.link — the tabular part's many-to-one to the document (usually 'owner').");
390
+ if (!hasSource && d.link !== undefined)
391
+ problems.push("definition.link is only for a rule with a source (a tabular part).");
392
+ if (isSql) {
393
+ if (typeof d.sql !== "string" || !/^\s*(select|with)\b/i.test(d.sql))
394
+ problems.push("definition.sql must be one SuppaSQL SELECT for $recorder.");
395
+ else if (!d.sql.includes("$recorder"))
396
+ problems.push("definition.sql must be pinned to the document: WHERE \"id\" = $recorder, or \"<link>.id\" = $recorder over a source.");
397
+ return problems;
398
+ }
399
+ const movements = d.movements;
400
+ if (!Array.isArray(movements) || movements.length < 1 || movements.length > MAX_MOVEMENTS) {
401
+ problems.push(`definition.movements must be 1 to ${MAX_MOVEMENTS} movements.`);
402
+ return problems;
403
+ }
404
+ const accumulation = register.option.kind === "accumulation";
405
+ const turnover = register.option.accumulationType === "turnover";
406
+ const needsKind = accumulation && !turnover;
407
+ const dimensions = register.fields.filter((f) => roleOf(f) === "dimension").map((f) => f.name);
408
+ const targets = new Set(register.fields.filter((f) => roleOf(f) !== null).map((f) => f.name));
409
+ for (const [i, m] of movements.entries()) {
410
+ const at = `movements[${i}]`;
411
+ if (!m || typeof m !== "object" || Array.isArray(m)) {
412
+ problems.push(`${at} must be { recordKind?, set }.`);
413
+ continue;
414
+ }
415
+ const mv = m;
416
+ const extra = Object.keys(mv).filter((k) => k !== "recordKind" && k !== "set");
417
+ if (extra.length)
418
+ problems.push(`${at} takes only recordKind and set; not ${extra.join(", ")} (period and condition belong to the definition).`);
419
+ if (needsKind && mv.recordKind !== "receipt" && mv.recordKind !== "expense")
420
+ problems.push(`${at}.recordKind must be 'receipt' or 'expense' in a balance register.`);
421
+ if (!needsKind && mv.recordKind !== undefined)
422
+ problems.push(`${at}.recordKind is not taken here (${turnover ? "a turnover register sums signed values" : "an information register's records have no kind"}).`);
423
+ const set = mv.set;
424
+ if (!set || typeof set !== "object" || Array.isArray(set)) {
425
+ problems.push(`${at}.set must map the register's fields to SuppaSQL expressions.`);
426
+ continue;
427
+ }
428
+ for (const [field, expr] of Object.entries(set)) {
429
+ if (!targets.has(field))
430
+ problems.push(`${at}.set.${field}: not a dimension, resource or attribute of the register.`);
431
+ if (typeof expr !== "string" || !expr.trim())
432
+ problems.push(`${at}.set.${field}: an expression is a string — "qty", "owner.warehouse", 'sale'.`);
433
+ }
434
+ const missing = dimensions.filter((dim) => !(dim in set));
435
+ if (missing.length)
436
+ problems.push(`${at}.set: every dimension must be set in every movement — missing ${missing.join(", ")}.`);
437
+ }
438
+ return problems;
439
+ }
440
+ async function existingRule(registerId, recorderId, key) {
441
+ const rows = await searchEntity(RULES_ENTITY, [
442
+ { field: "register.id", comparator: "=", value: registerId },
443
+ { field: "recorder.id", comparator: "=", value: recorderId },
444
+ { field: "key", comparator: "=", value: key },
445
+ ], { id: true, key: true, status: true, source: { id: true, name: true } }, 1);
446
+ return rows[0] ?? null;
447
+ }
448
+ /**
449
+ * Why an existing rule cannot take this call's source, or null. A rule's register, recorder and
450
+ * source never change (register-rule-guard.extension.ts `immutable_target`) and an update writes
451
+ * the definition only — so without this check the preview ran on the NEW source while the save
452
+ * kept the OLD one: the user approved movements the saved rule does not give.
453
+ */
454
+ function sourceMismatch(existing, key, sourceName, sourceId) {
455
+ // No `source` key at all = the read did not return the column (a projection the caller's rights
456
+ // dropped): unknown is not a mismatch, and the platform's own immutable_target still guards it.
457
+ if (!existing || !("source" in existing))
458
+ return null;
459
+ const stored = existing.source && typeof existing.source === "object" ? existing.source : null;
460
+ const storedId = typeof stored?.id === "number" ? stored.id : null;
461
+ if (storedId === sourceId)
462
+ return null;
463
+ const was = storedId === null ? "the document itself (no source)" : `the tabular part '${stored?.name ?? `#${storedId}`}'`;
464
+ const asked = sourceId === null ? "the document itself (no source)" : `the tabular part '${sourceName}'`;
465
+ return {
466
+ error: `Rule '${key}' already exists and reads ${was}; this call names ${asked}. A rule's source never changes. Nothing was written.`,
467
+ existing_rule_id: existing.id ?? null,
468
+ next: `To change what the rule reads: save it under another key, then switch this one off — suppa_update_record(entity_name="RegisterPostingRules", record_id=${existing.id}, fields_json='{"tenantDisabled": true}') — or remove it (suppa_delete_record). To change only its definition: call again with source=${storedId === null ? "null" : `"${stored?.name ?? ""}"`}.`,
469
+ };
470
+ }
471
+ export async function savePostingRule(register, recorder, source, key, definitionJson, previewDocumentId, confirm) {
472
+ const parsed = parseArg(definitionJson, "definition_json", "object");
473
+ if (parsed.error)
474
+ return parsed.error;
475
+ if (!RULE_KEY_PATTERN.test(key)) {
476
+ return jsonResponse({
477
+ error: key.includes(":")
478
+ ? "key: ':' marks an application's rule (<app>:<key>). A tenant can neither create nor edit one — it switches it off: suppa_update_record(entity_name=\"RegisterPostingRules\", record_id, fields_json='{\"tenantDisabled\": true}'). For a rule of your own, a key without ':'."
479
+ : "key: 1-64 characters of A-Z a-z 0-9 _ . -, unique within (register, recorder).",
480
+ });
481
+ }
482
+ let resolved;
483
+ try {
484
+ resolved = await Promise.all([schemaOf(register), schemaOf(recorder), source ? schemaOf(source) : Promise.resolve(null)]);
485
+ }
486
+ catch (e) {
487
+ // The schema reads build the preview; without them the gate still holds and says why.
488
+ if (confirm)
489
+ throw e;
490
+ return confirmRequired("save posting rule", { register, recorder, source, key }, { definition: parsed.value, preview: { error: `Could not read the schemas: ${e instanceof Error ? e.message : String(e)}` } });
491
+ }
492
+ const [reg, rec, src] = resolved;
493
+ if (!reg || (reg.type !== "register" && !reg.options.register))
494
+ return jsonResponse({ error: `'${register}' is not a register on this tenant.`, next: "suppa_register_status() lists the registers." });
495
+ if (!rec || rec.id === null)
496
+ return jsonResponse({ error: `Document entity '${recorder}' does not exist on this tenant.` });
497
+ if (source && (!src || src.id === null))
498
+ return jsonResponse({ error: `Tabular part '${source}' does not exist on this tenant.`, next: `suppa_list_tabular_parts(entity_name="${recorder}")` });
499
+ const option = reg.options.register ?? {};
500
+ const problems = ruleDefinitionProblems(parsed.value, { option, fields: reg.fields }, Boolean(source));
501
+ if (problems.length) {
502
+ return jsonResponse({ error: "Refused before any request.", problems, hint: "suppa_registers_kb(topic='rules')." });
503
+ }
504
+ const definition = parsed.value;
505
+ const ids = { register: reg.id, recorder: rec.id, source: src?.id ?? null };
506
+ const existing = await existingRule(ids.register, ids.recorder, key);
507
+ const mismatch = sourceMismatch(existing, key, source, ids.source);
508
+ if (mismatch)
509
+ return jsonResponse(mismatch);
510
+ if (!confirm) {
511
+ let preview = null;
512
+ if (previewDocumentId !== null && previewDocumentId !== undefined) {
513
+ try {
514
+ preview = await makeRequest("POST", `${BASE}/rules/preview`, {
515
+ register: ids.register,
516
+ recorder: ids.recorder,
517
+ ...(ids.source !== null ? { source: ids.source } : {}),
518
+ definition,
519
+ document: previewDocumentId,
520
+ });
521
+ }
522
+ catch (e) {
523
+ preview = registerRefusal(e) ?? { error: e instanceof Error ? e.message : String(e) };
524
+ }
525
+ }
526
+ const warnings = [
527
+ "A rule change does not repost documents that already exist — afterwards preview and run suppa_repost_documents.",
528
+ ];
529
+ if (previewDocumentId === null || previewDocumentId === undefined) {
530
+ warnings.unshift("No preview: pass preview_document_id (a document of this recorder) to see the movements this rule gives it before saving.");
531
+ }
532
+ return confirmRequired(existing ? "update posting rule" : "create posting rule", { register, recorder, source, key, existing_rule_id: existing?.id ?? null }, { definition, preview }, warnings);
533
+ }
534
+ const row = {
535
+ key,
536
+ register: { id: ids.register },
537
+ recorder: { id: ids.recorder },
538
+ ...(ids.source !== null ? { source: { id: ids.source } } : {}),
539
+ definition,
540
+ };
541
+ return call(() => existing
542
+ ? makeRequest("POST", dataUrl(RULES_ENTITY, "update") + `/${seg(existing.id)}`, { fields: { definition } })
543
+ : makeRequest("POST", dataUrl(RULES_ENTITY, "insert"), { fields: [row], returning: { id: true, status: true }, getAccessByFields: false }), (result) => ({
544
+ saved: existing ? "updated" : "created",
545
+ rule_id: existing?.id ?? (Array.isArray(result) ? result[0]?.id : result?.id) ?? null,
546
+ result,
547
+ next: "Existing documents are NOT reposted: suppa_repost_documents(entity=\"" + recorder + "\", from_date=\"all\") — its confirmation request is the platform's dry run.",
548
+ }));
549
+ }
550
+ // ---------------------------------------------------------------------------
551
+ // Reads (api "Reads")
552
+ // ---------------------------------------------------------------------------
553
+ export const READ_KINDS = ["balance", "turnovers", "balance_and_turnovers", "movements", "slice_last", "slice_first"];
554
+ const READ_PATH = {
555
+ balance: "balance",
556
+ turnovers: "turnovers",
557
+ balance_and_turnovers: "balance-and-turnovers",
558
+ movements: "movements",
559
+ slice_last: "slice-last",
560
+ slice_first: "slice-first",
561
+ };
562
+ export const GRAINS = ["none", "day", "month", "recorder"];
563
+ export const READ_MAX_LIMIT = 10_000; // api "Reads": limit 1–10 000
564
+ /** The read's body, or the reason it is refused before sending. */
565
+ export function readBody(a) {
566
+ const body = {};
567
+ const takesAt = a.kind === "balance" || a.kind === "slice_last" || a.kind === "slice_first";
568
+ const takesRange = !takesAt;
569
+ if (a.at && !takesAt)
570
+ return { error: `at is for balance and slices; ${a.kind} takes from / to.` };
571
+ if ((a.from || a.to) && !takesRange)
572
+ return { error: `from / to are for turnovers, balance and turnovers, and movements; ${a.kind} takes at.` };
573
+ if ((a.kind === "turnovers" || a.kind === "balance_and_turnovers") && !(a.from && a.to)) {
574
+ return { error: `${a.kind} needs both from and to (from inclusive, to exclusive; a day as to means its end).` };
575
+ }
576
+ if (a.grain && a.kind !== "turnovers" && a.kind !== "balance_and_turnovers")
577
+ return { error: "grain is for turnovers and balance and turnovers." };
578
+ if (a.groupBy && (a.kind === "movements" || a.kind.startsWith("slice")))
579
+ return { error: `group_by is for balance and turnovers reads, not ${a.kind}.` };
580
+ if (a.at)
581
+ body.at = a.at;
582
+ if (a.from)
583
+ body.from = a.from;
584
+ if (a.to)
585
+ body.to = a.to;
586
+ if (a.groupBy)
587
+ body.groupBy = a.groupBy;
588
+ if (a.grain)
589
+ body.grain = a.grain;
590
+ const filter = parseArg(a.filterJson, "filter_json", "object");
591
+ if (filter.error)
592
+ return { error: JSON.parse(filter.error).error };
593
+ const conditions = parseArg(a.conditionsJson, "conditions_json", "object");
594
+ if (conditions.error)
595
+ return { error: JSON.parse(conditions.error).error };
596
+ if (filter.value !== undefined && conditions.value !== undefined)
597
+ return { error: "Pass filter_json or conditions_json, not both (the platform refuses both: filter_and_conditions)." };
598
+ if (filter.value !== undefined)
599
+ body.filter = filter.value;
600
+ if (conditions.value !== undefined)
601
+ body.conditions = conditions.value;
602
+ if (a.limit)
603
+ body.limit = a.limit;
604
+ if (a.cursor)
605
+ body.cursor = a.cursor;
606
+ return { body };
607
+ }
608
+ export async function readRegister(a) {
609
+ const built = readBody(a);
610
+ if (built.error)
611
+ return jsonResponse({ error: built.error, hint: "suppa_registers_kb(topic='reads')." });
612
+ return call(() => makeRequest("POST", `${BASE}/${seg(a.register)}/${READ_PATH[a.kind]}`, built.body), (answer) => {
613
+ const r = (answer ?? {});
614
+ const meta = (r.meta ?? {});
615
+ const out = { ...r };
616
+ const notes = [];
617
+ if (typeof meta.pending === "number" && meta.pending > 0)
618
+ notes.push(`${meta.pending} document(s) of this register are still queued — the numbers will still move.`);
619
+ if (Array.isArray(meta.omittedResources) && meta.omittedResources.length)
620
+ notes.push(`Not shown (no right to read them): ${meta.omittedResources.join(", ")}.`);
621
+ if (r.nextCursor)
622
+ notes.push("More rows follow: call again with cursor=nextCursor. Stop on nextCursor null, not on a short page.");
623
+ if (notes.length)
624
+ out.notes = notes;
625
+ return out;
626
+ });
627
+ }
628
+ /** suppa_query with virtual_tables_json: POST /core/registers/query (api "Virtual Tables"). */
629
+ export async function queryRegisters(query, virtualTables, bindParams) {
630
+ return makeRequest("POST", `${BASE}/query`, { query, virtualTables, ...(bindParams ? { bindParams } : {}) });
631
+ }
632
+ // ---------------------------------------------------------------------------
633
+ // A document (api "Documents")
634
+ // ---------------------------------------------------------------------------
635
+ export async function registerDocument(entity, recordId, recordIds, preview) {
636
+ if (recordIds && recordIds.length) {
637
+ if (recordIds.length > 1000)
638
+ return jsonResponse({ error: "record_ids: at most 1000 per call." });
639
+ return call(() => makeRequest("POST", `${BASE}/recorders/status`, { entity, ids: recordIds }), (a) => a);
640
+ }
641
+ if (recordId === null || recordId === undefined)
642
+ return jsonResponse({ error: "Pass record_id (one document's card) or record_ids (the state of a page of documents)." });
643
+ return call(() => makeRequest("GET", `${BASE}/recorders/${seg(entity)}/${seg(recordId)}`, null, preview ? { query: { preview: true } } : {}), (a) => a);
644
+ }
645
+ // ---------------------------------------------------------------------------
646
+ // Repost (api "Repost One Document", "Repost History")
647
+ // ---------------------------------------------------------------------------
648
+ export async function repostDocuments(entity, recordId, fromDate, rate, confirm) {
649
+ if ((recordId === null || recordId === undefined) === !fromDate) {
650
+ return jsonResponse({ error: "Pass record_id (repost one document now) OR from_date (repost history as a job: 'all', a day, or an instant with an offset) — exactly one." });
651
+ }
652
+ if (recordId !== null && recordId !== undefined) {
653
+ if (!confirm) {
654
+ let preview;
655
+ try {
656
+ preview = await makeRequest("GET", `${BASE}/recorders/${seg(entity)}/${seg(recordId)}`, null, { query: { preview: true } });
657
+ }
658
+ catch (e) {
659
+ preview = registerRefusal(e) ?? { error: e instanceof Error ? e.message : String(e) };
660
+ }
661
+ return confirmRequired("repost document", { entity, record_id: recordId }, { what_the_rules_give_now: preview }, ["Interactive: balance control and the closed period apply to you (409). One transaction; equal movements stay as they are."]);
662
+ }
663
+ return call(() => makeRequest("POST", `${BASE}/recorders/${seg(entity)}/${seg(recordId)}/repost`, {}), (a) => a);
664
+ }
665
+ if (!confirm) {
666
+ let preview;
667
+ try {
668
+ preview = await makeRequest("POST", `${BASE}/repost/preview`, { recorder: entity, from: fromDate });
669
+ }
670
+ catch (e) {
671
+ preview = registerRefusal(e) ?? { error: e instanceof Error ? e.message : String(e) };
672
+ }
673
+ return confirmRequired("start repost job", { recorder: entity, from: fromDate, rate }, { dry_run: preview }, [
674
+ "The dry run reposted a sample in a transaction it rolled back; its registers and documents were locked while it ran.",
675
+ "The job posts through the queue with control 'report': shortages become violations, refusals become held documents. Follow it with suppa_register_status(job_id).",
676
+ ]);
677
+ }
678
+ return call(() => makeRequest("POST", `${BASE}/repost`, { recorder: entity, from: fromDate, rate }), (job) => ({ job, next: "Follow it: suppa_register_status(job_id=<id>) until status is done, failed or cancelled." }));
679
+ }
680
+ // ---------------------------------------------------------------------------
681
+ // Status (api "Maintenance", "Jobs")
682
+ // ---------------------------------------------------------------------------
683
+ export async function registerStatus(register, jobId, part) {
684
+ try {
685
+ if (jobId !== null && jobId !== undefined) {
686
+ const job = await makeRequest("GET", `${BASE}/jobs/${seg(jobId)}`);
687
+ if (part === null || part === undefined)
688
+ return jsonResponse({ job });
689
+ const results = await makeRequest("GET", `${BASE}/jobs/${seg(jobId)}/results`, null, { query: { part } });
690
+ return jsonResponse({ job, results });
691
+ }
692
+ if (!register) {
693
+ const panel = await makeRequest("GET", BASE);
694
+ return jsonResponse({ registers: panel });
695
+ }
696
+ const [state, held, violations] = await Promise.all([
697
+ makeRequest("GET", `${BASE}/${seg(register)}/state`),
698
+ makeRequest("GET", `${BASE}/held`, null, { query: { register, limit: 20 } }),
699
+ makeRequest("GET", `${BASE}/${seg(register)}/violations`, null, { query: { status: "open", limit: 20 } }),
700
+ ]);
701
+ return jsonResponse({
702
+ state,
703
+ held,
704
+ open_violations: violations,
705
+ note: "held and open_violations are first pages of 20 (nextAfter says more follow).",
706
+ });
707
+ }
708
+ catch (e) {
709
+ const refusal = registerRefusal(e);
710
+ if (refusal)
711
+ return jsonResponse(refusal);
712
+ throw e;
713
+ }
714
+ }
715
+ // ---------------------------------------------------------------------------
716
+ // Operate (api "Maintenance", "Jobs")
717
+ // ---------------------------------------------------------------------------
718
+ export const OPERATE_ACTIONS = [
719
+ "suspend_totals",
720
+ "resume_totals",
721
+ "close_period",
722
+ "rebuild_totals",
723
+ "check_totals",
724
+ "release_held",
725
+ "resolve_violation",
726
+ "pause_job",
727
+ "resume_job",
728
+ "cancel_job",
729
+ ];
730
+ /** closed_until's word for "no closed period" — the platform's `closedUntil: null`, said on purpose. */
731
+ export const CLOSED_UNTIL_NONE = "none";
732
+ /** The request an action sends, or why it cannot be sent. */
733
+ export function operateRequest(a) {
734
+ const needRegister = !["resolve_violation", "pause_job", "resume_job", "cancel_job"].includes(a.action);
735
+ if (needRegister && !a.register)
736
+ return { error: `${a.action} needs register.` };
737
+ const r = a.register ? `${BASE}/${seg(a.register)}` : "";
738
+ switch (a.action) {
739
+ case "suspend_totals":
740
+ return { method: "PATCH", path: `${r}/state`, body: { totals: "suspended" } };
741
+ case "resume_totals":
742
+ return { method: "PATCH", path: `${r}/state`, body: { totals: "live" } };
743
+ case "close_period": {
744
+ // Never from an omitted argument: the platform reads `closedUntil: null` as "open everything",
745
+ // so a forgotten closed_until used to lift the whole closed period (review 2026-11-19).
746
+ const until = typeof a.closedUntil === "string" ? a.closedUntil.trim() : "";
747
+ if (until === CLOSED_UNTIL_NONE)
748
+ return { method: "PATCH", path: `${r}/state`, body: { closedUntil: null } };
749
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(until)) {
750
+ return {
751
+ error: `close_period needs closed_until: the last closed day YYYY-MM-DD in the register's zone, or '${CLOSED_UNTIL_NONE}' ` +
752
+ "to open every period. It is never assumed — leaving it out is not a way to open the period.",
753
+ };
754
+ }
755
+ return { method: "PATCH", path: `${r}/state`, body: { closedUntil: until } };
756
+ }
757
+ case "rebuild_totals":
758
+ if (a.fromMonth && a.fromMonth !== "all" && !/^\d{4}-\d{2}$/.test(a.fromMonth))
759
+ return { error: "from_month is YYYY-MM or 'all'." };
760
+ return { method: "POST", path: `${r}/totals/rebuild`, body: { from: a.fromMonth || "all" } };
761
+ case "check_totals": {
762
+ const body = {};
763
+ if (a.repair)
764
+ body.repair = true;
765
+ if (a.derivation)
766
+ body.derivation = true;
767
+ if (a.fromDate) {
768
+ if (!a.derivation)
769
+ return { error: "from_date limits a derivation check — pass derivation=true with it." };
770
+ body.from = a.fromDate;
771
+ }
772
+ return { method: "POST", path: `${r}/check`, body };
773
+ }
774
+ case "release_held":
775
+ return { method: "POST", path: `${r}/held/release`, body: {} };
776
+ case "resolve_violation":
777
+ if (!a.violationId)
778
+ return { error: "resolve_violation needs violation_id (suppa_register_status(register) lists open violations)." };
779
+ return { method: "POST", path: `${BASE}/violations/${seg(a.violationId)}/resolve`, body: {} };
780
+ case "pause_job":
781
+ case "resume_job":
782
+ case "cancel_job":
783
+ if (!a.jobId)
784
+ return { error: `${a.action} needs job_id.` };
785
+ return { method: "POST", path: `${BASE}/jobs/${seg(a.jobId)}/${a.action.slice(0, -4)}`, body: {} };
786
+ }
787
+ return { error: `Unknown action '${a.action}'.` };
788
+ }
789
+ const ACTION_WARNINGS = {
790
+ suspend_totals: "While suspended, balance / turnover reads answer 409 totals_suspended and a person's write that lowers a balance answers 409 maintenance. resume_totals starts a rebuild.",
791
+ resume_totals: "Starts a rebuild from the earliest month touched; the register reads 'rebuilding' until it ends.",
792
+ close_period: "With a day: nobody without REGISTERS.CLOSED_PERIOD_EDIT can add or remove movements up to it; the queue holds such documents. With 'none' (body closedUntil: null): EVERY period opens — anyone who may write the documents can change the past.",
793
+ rebuild_totals: "Postings of the register wait while each month is rebuilt (exclusive gate, a month at a time).",
794
+ check_totals: "derivation=true reposts every document in a rolled-back transaction — hours on a big register.",
795
+ release_held: "Every held document of the register goes back to the queue; one the engine refuses again is held again.",
796
+ cancel_job: "A cancelled rebuild leaves the register 'rebuilding' until a new rebuild.",
797
+ };
798
+ export async function operateRegister(a, confirm) {
799
+ const req = operateRequest(a);
800
+ if (req.error)
801
+ return jsonResponse({ error: req.error, hint: "suppa_registers_kb(topic='operations')." });
802
+ if (!confirm) {
803
+ let current = null;
804
+ try {
805
+ if (a.jobId)
806
+ current = await makeRequest("GET", `${BASE}/jobs/${seg(a.jobId)}`);
807
+ else if (a.register)
808
+ current = await makeRequest("GET", `${BASE}/${seg(a.register)}/state`);
809
+ }
810
+ catch (e) {
811
+ current = registerRefusal(e) ?? { error: e instanceof Error ? e.message : String(e) };
812
+ }
813
+ const warning = ACTION_WARNINGS[a.action];
814
+ return confirmRequired(a.action.replace(/_/g, " "), { register: a.register ?? null, job_id: a.jobId ?? null, violation_id: a.violationId ?? null, current }, { request: `${req.method} ${req.path}`, body: req.body }, warning ? [warning] : undefined);
815
+ }
816
+ return call(() => makeRequest(req.method, req.path, req.body), (result) => ({ action: a.action, result }));
817
+ }