@tallyui/core 2.0.0 → 3.0.0-next.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.
- package/dist/chunk-C4PWPOKO.js +18 -0
- package/dist/commands-BW4YYgRG.d.ts +306 -0
- package/dist/index.d.ts +226 -130
- package/dist/index.js +193 -19
- package/dist/rxdb/index.d.ts +5 -9
- package/dist/server/index.d.ts +213 -0
- package/dist/server/index.js +591 -0
- package/package.json +8 -2
- package/src/commands.ts +1 -1
- package/src/context/connector-context.tsx +30 -1
- package/src/index.ts +17 -5
- package/src/known-warnings.ts +77 -0
- package/src/replication/combine.ts +7 -3
- package/src/replication/reconcile-feed.ts +57 -20
- package/src/rxdb/read-fresh.ts +3 -7
- package/src/rxdb/watch-fresh.ts +2 -2
- package/src/rxdb-remote-version-mismatch.ts +30 -0
- package/src/server/__fixtures__/fingerprint-vectors.json +139 -0
- package/src/server/__fixtures__/order-create-v3.json +97 -0
- package/src/server/batch-outcome.ts +19 -0
- package/src/server/batch.ts +112 -0
- package/src/server/command-result.ts +138 -0
- package/src/server/fingerprint.ts +18 -0
- package/src/server/fiscal-figures.ts +84 -0
- package/src/server/index.ts +20 -0
- package/src/server/money.ts +34 -0
- package/src/server/order-payload-shape.ts +112 -0
- package/src/server/register-figures.ts +32 -0
- package/src/server/register-outcome.ts +12 -0
- package/src/server/register-payload-shape.ts +86 -0
- package/src/server/rejection-codes.ts +49 -0
- package/src/server/total-warnings.ts +10 -0
- package/src/server/versions.ts +9 -0
- package/src/sync-notice.ts +26 -0
- package/src/types/commands.ts +138 -9
- package/src/types/connector.ts +58 -1
- package/src/types/customers.ts +26 -0
- package/src/types/index.ts +9 -2
- package/src/types/reconcile.ts +30 -0
- package/src/types/replication.ts +6 -0
- package/src/types/store-settings.ts +4 -0
- package/src/types/traits/product.ts +7 -0
- package/src/unauthorized.ts +13 -0
|
@@ -0,0 +1,591 @@
|
|
|
1
|
+
import {
|
|
2
|
+
MAX_COMMANDS_PER_BATCH
|
|
3
|
+
} from "../chunk-C4PWPOKO.js";
|
|
4
|
+
|
|
5
|
+
// src/server/money.ts
|
|
6
|
+
function currencyDecimals(currency) {
|
|
7
|
+
return new Intl.NumberFormat("en", { style: "currency", currency }).resolvedOptions().maximumFractionDigits;
|
|
8
|
+
}
|
|
9
|
+
function minorToMajor(minor, decimals) {
|
|
10
|
+
if (!Number.isSafeInteger(minor)) throw new RangeError("minor must be a safe integer");
|
|
11
|
+
const sign = minor < 0 ? "-" : "";
|
|
12
|
+
const digits = Math.abs(minor).toString().padStart(decimals + 1, "0");
|
|
13
|
+
return sign + (decimals === 0 ? digits : `${digits.slice(0, -decimals)}.${digits.slice(-decimals)}`);
|
|
14
|
+
}
|
|
15
|
+
function majorToMinor(value, decimals) {
|
|
16
|
+
const match = /^([+-]?)(\d+(?:\.\d*)?|\.\d+)(?:e([+-]?\d+))?$/i.exec(String(value));
|
|
17
|
+
if (!match) throw new RangeError("value must be a finite decimal");
|
|
18
|
+
const [, sign, mantissa, exponent = "0"] = match;
|
|
19
|
+
const [whole, fraction = ""] = mantissa.split(".");
|
|
20
|
+
const coefficient = BigInt(whole + fraction);
|
|
21
|
+
const shift = BigInt(decimals) + BigInt(exponent) - BigInt(fraction.length);
|
|
22
|
+
let rounded;
|
|
23
|
+
if (shift >= 0n) {
|
|
24
|
+
rounded = coefficient * 10n ** shift;
|
|
25
|
+
} else {
|
|
26
|
+
const divisor = 10n ** -shift;
|
|
27
|
+
rounded = coefficient / divisor + (coefficient % divisor * 2n >= divisor ? 1n : 0n);
|
|
28
|
+
}
|
|
29
|
+
const minor = Number(sign === "-" ? -rounded : rounded);
|
|
30
|
+
if (!Number.isSafeInteger(minor)) throw new RangeError("minor amount exceeds safe integer range");
|
|
31
|
+
return minor;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// src/server/fingerprint.ts
|
|
35
|
+
import { createHash } from "node:crypto";
|
|
36
|
+
function canonicalJson(value) {
|
|
37
|
+
if (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item) ?? "null").join(",")}]`;
|
|
38
|
+
if (value !== null && typeof value === "object") {
|
|
39
|
+
const object = value;
|
|
40
|
+
return `{${Object.keys(object).sort().filter((key) => object[key] !== void 0).map((key) => `${JSON.stringify(key)}:${canonicalJson(object[key])}`).join(",")}}`;
|
|
41
|
+
}
|
|
42
|
+
return JSON.stringify(value);
|
|
43
|
+
}
|
|
44
|
+
function commandFingerprint(envelope) {
|
|
45
|
+
const { type, version, payload } = envelope;
|
|
46
|
+
return createHash("sha256").update(canonicalJson({ type, version, payload })).digest("hex");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// src/server/order-payload-shape.ts
|
|
50
|
+
function payloadShapeErrors(payload) {
|
|
51
|
+
const errors = [];
|
|
52
|
+
const object = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
53
|
+
const check = (valid, path, expected) => {
|
|
54
|
+
if (!valid && errors.length < 10) errors.push(`${path}: expected ${expected}`);
|
|
55
|
+
};
|
|
56
|
+
const number = (value, path) => check(typeof value === "number" && Number.isFinite(value), path, "a finite number");
|
|
57
|
+
const discount = (value, path) => {
|
|
58
|
+
const valid = value === void 0 || Number.isSafeInteger(value) && value > 0;
|
|
59
|
+
check(valid, path, "a positive safe integer");
|
|
60
|
+
return valid && value !== void 0 ? BigInt(value) : 0n;
|
|
61
|
+
};
|
|
62
|
+
if (!object(payload)) return ["payload: expected an object"];
|
|
63
|
+
check(typeof payload.clientOrderId === "string" && payload.clientOrderId.length > 0, "clientOrderId", "a non-empty string");
|
|
64
|
+
for (const field of ["createdAt", "currency"]) check(typeof payload[field] === "string", field, "a string");
|
|
65
|
+
check(typeof payload.pricesIncludeTax === "boolean", "pricesIncludeTax", "a boolean");
|
|
66
|
+
for (const field of ["lines", "payments"]) {
|
|
67
|
+
const items = payload[field];
|
|
68
|
+
const isLines = field === "lines";
|
|
69
|
+
check(Array.isArray(items) && (!isLines || items.length > 0), field, isLines ? "a non-empty array" : "an array");
|
|
70
|
+
if (!Array.isArray(items)) continue;
|
|
71
|
+
for (const [index, item] of items.entries()) {
|
|
72
|
+
if (errors.length === 10) break;
|
|
73
|
+
const path = `${field}[${index}]`;
|
|
74
|
+
check(object(item), path, "an object");
|
|
75
|
+
if (!object(item)) continue;
|
|
76
|
+
for (const key of isLines ? ["clientLineId", "variantId"] : ["clientPaymentId", "method"]) {
|
|
77
|
+
check(typeof item[key] === "string", `${path}.${key}`, "a string");
|
|
78
|
+
}
|
|
79
|
+
const optionalString = isLines ? "title" : "reference";
|
|
80
|
+
if (item[optionalString] !== void 0) {
|
|
81
|
+
check(typeof item[optionalString] === "string", `${path}.${optionalString}`, "a string");
|
|
82
|
+
}
|
|
83
|
+
if (isLines && item.taxInclusive !== void 0) {
|
|
84
|
+
check(typeof item.taxInclusive === "boolean", `${path}.taxInclusive`, "a boolean");
|
|
85
|
+
}
|
|
86
|
+
for (const key of isLines ? ["quantity", "unitPriceMinor"] : ["amountMinor"]) number(item[key], `${path}.${key}`);
|
|
87
|
+
if (!isLines) {
|
|
88
|
+
for (const key of ["tenderedMinor", "changeMinor"]) {
|
|
89
|
+
if (item[key] !== void 0) number(item[key], `${path}.${key}`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
for (const field of ["subtotalMinor", "taxMinor", "totalMinor"]) number(payload[field], field);
|
|
95
|
+
const lineDiscounts = (Array.isArray(payload.lines) ? payload.lines : []).reduce((sum, line, index) => sum + (object(line) ? discount(line.discountMinor, `lines[${index}].discountMinor`) : 0n), 0n);
|
|
96
|
+
const orderDiscount = discount(payload.discountMinor, "discountMinor");
|
|
97
|
+
if (errors.length === 0) check(orderDiscount === lineDiscounts, "discountMinor", "the sum of lines[].discountMinor");
|
|
98
|
+
if (payload.customer !== void 0 && payload.customer !== null) {
|
|
99
|
+
check(object(payload.customer), "customer", "an object");
|
|
100
|
+
if (object(payload.customer) && payload.customer.email !== void 0) {
|
|
101
|
+
check(typeof payload.customer.email === "string", "customer.email", "a string");
|
|
102
|
+
}
|
|
103
|
+
if (object(payload.customer) && payload.customer.customerId !== void 0) {
|
|
104
|
+
const id = payload.customer.customerId;
|
|
105
|
+
check(typeof id === "string" && id.length > 0 && id.length <= 64, "customer.customerId", "a string of at most 64 characters");
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (payload.sessionId !== void 0) {
|
|
109
|
+
check(
|
|
110
|
+
typeof payload.sessionId === "string" && payload.sessionId.length > 0 && payload.sessionId.length <= 36,
|
|
111
|
+
"sessionId",
|
|
112
|
+
"a string of at most 36 characters"
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
for (const field of ["registerId", "cashierRef", "locationId"]) {
|
|
116
|
+
if (payload[field] !== void 0) check(typeof payload[field] === "string", field, "a string");
|
|
117
|
+
}
|
|
118
|
+
for (const [value, path] of payloadStrings(payload)) check(!value.includes("\0"), path, "no NUL character");
|
|
119
|
+
return errors;
|
|
120
|
+
}
|
|
121
|
+
function payloadBoundErrors(payload) {
|
|
122
|
+
if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return [];
|
|
123
|
+
return payloadStrings(payload).filter(([value, , max]) => max !== void 0 && value.length > max).map(([, path, max]) => `${path}: expected at most ${max} characters`).slice(0, 10);
|
|
124
|
+
}
|
|
125
|
+
function payloadStrings(payload) {
|
|
126
|
+
const found = [];
|
|
127
|
+
const object = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
128
|
+
for (const field of ["clientOrderId", "createdAt", "currency", "registerId", "cashierRef", "locationId"]) found.push([payload[field], field, 255]);
|
|
129
|
+
for (const field of ["lines", "payments"]) {
|
|
130
|
+
const items = payload[field];
|
|
131
|
+
if (Array.isArray(items)) items.forEach((item, index) => {
|
|
132
|
+
if (object(item)) for (const key of field === "lines" ? ["clientLineId", "variantId", "title"] : ["clientPaymentId", "method", "reference"]) {
|
|
133
|
+
found.push([item[key], `${field}[${index}].${key}`, 255]);
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
if (object(payload.customer)) found.push([payload.customer.email, "customer.email", 254], [payload.customer.customerId, "customer.customerId", void 0]);
|
|
138
|
+
found.push([payload.sessionId, "sessionId", void 0]);
|
|
139
|
+
return found.filter((entry) => typeof entry[0] === "string");
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// src/server/fiscal-figures.ts
|
|
143
|
+
function fiscalFiguresErrors(payload) {
|
|
144
|
+
const errors = [];
|
|
145
|
+
const check = (valid, path, expected) => {
|
|
146
|
+
if (!valid && errors.length < 10) errors.push(`${path}: expected ${expected}`);
|
|
147
|
+
};
|
|
148
|
+
const object = (value, path, keys) => {
|
|
149
|
+
const valid = typeof value === "object" && value !== null && !Array.isArray(value);
|
|
150
|
+
check(valid, path, "an object");
|
|
151
|
+
if (valid) for (const key of Object.keys(value)) check(keys.includes(key), `${path}.${key}`, "no unknown key");
|
|
152
|
+
return valid;
|
|
153
|
+
};
|
|
154
|
+
const money = (value, path, keys) => {
|
|
155
|
+
for (const key of keys) check(Number.isSafeInteger(value[key]), `${path}.${key}`, "a safe integer");
|
|
156
|
+
};
|
|
157
|
+
const { display, taxByRate } = payload;
|
|
158
|
+
if (object(display, "display", ["currency", "exponent", "taxInclusive", "subtotalMinor", "discountMinor", "taxMinor", "totalMinor", "orderDiscountMinor", "lines"])) {
|
|
159
|
+
check(typeof display.currency === "string", "display.currency", "a string");
|
|
160
|
+
check(Number.isInteger(display.exponent) && display.exponent >= 0, "display.exponent", "an integer >= 0");
|
|
161
|
+
check(typeof display.taxInclusive === "boolean", "display.taxInclusive", "a boolean");
|
|
162
|
+
money(display, "display", ["subtotalMinor", "discountMinor", "taxMinor", "totalMinor", "orderDiscountMinor"]);
|
|
163
|
+
check(Array.isArray(display.lines), "display.lines", "an array");
|
|
164
|
+
if (Array.isArray(display.lines)) display.lines.forEach((line, index) => {
|
|
165
|
+
const path = `display.lines[${index}]`;
|
|
166
|
+
if (!object(line, path, ["clientLineId", "amountMinor", "discounts"])) return;
|
|
167
|
+
check(typeof line.clientLineId === "string", `${path}.clientLineId`, "a string");
|
|
168
|
+
money(line, path, ["amountMinor"]);
|
|
169
|
+
check(Array.isArray(line.discounts), `${path}.discounts`, "an array");
|
|
170
|
+
if (Array.isArray(line.discounts)) line.discounts.forEach((discount, index2) => {
|
|
171
|
+
const discountPath = `${path}.discounts[${index2}]`;
|
|
172
|
+
if (!object(discount, discountPath, ["discountId", "label", "amountMinor"])) return;
|
|
173
|
+
check(typeof discount.discountId === "string", `${discountPath}.discountId`, "a string");
|
|
174
|
+
if (discount.label !== void 0) check(typeof discount.label === "string", `${discountPath}.label`, "a string");
|
|
175
|
+
money(discount, discountPath, ["amountMinor"]);
|
|
176
|
+
});
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
check(Array.isArray(taxByRate), "taxByRate", "an array");
|
|
180
|
+
if (Array.isArray(taxByRate)) taxByRate.forEach((rate, index) => {
|
|
181
|
+
const path = `taxByRate[${index}]`;
|
|
182
|
+
if (!object(rate, path, ["ratePpm", "code", "netMinor", "taxMinor", "grossMinor"])) return;
|
|
183
|
+
check(Number.isInteger(rate.ratePpm), `${path}.ratePpm`, "an integer");
|
|
184
|
+
if (rate.code !== void 0) check(typeof rate.code === "string", `${path}.code`, "a string");
|
|
185
|
+
money(rate, path, ["netMinor", "taxMinor", "grossMinor"]);
|
|
186
|
+
});
|
|
187
|
+
if (errors.length || !display || !Array.isArray(taxByRate)) return errors;
|
|
188
|
+
check(display.currency === payload.currency, "display.currency", "payload.currency");
|
|
189
|
+
check(display.totalMinor === payload.totalMinor, "display.totalMinor", "payload.totalMinor");
|
|
190
|
+
check(display.taxMinor === payload.taxMinor, "display.taxMinor", "payload.taxMinor");
|
|
191
|
+
check(taxByRate.length > 0 || payload.taxMinor === 0, "taxByRate", "a non-empty array when payload.taxMinor is nonzero");
|
|
192
|
+
check(Number.isSafeInteger(payload.taxMinor) && taxByRate.reduce((sum, rate) => sum + BigInt(rate.taxMinor), 0n) === BigInt(payload.taxMinor), "taxByRate", "the sum of taxMinor to equal payload.taxMinor");
|
|
193
|
+
taxByRate.forEach((rate, index) => check(BigInt(rate.grossMinor) === BigInt(rate.netMinor) + BigInt(rate.taxMinor), `taxByRate[${index}].grossMinor`, "netMinor + taxMinor"));
|
|
194
|
+
const ids = new Set(Array.isArray(payload.lines) ? payload.lines.map((line) => line?.clientLineId) : []);
|
|
195
|
+
const seen = /* @__PURE__ */ new Set();
|
|
196
|
+
display.lines.forEach((line, index) => {
|
|
197
|
+
check(ids.has(line.clientLineId), `display.lines[${index}].clientLineId`, "a payload.lines[].clientLineId");
|
|
198
|
+
check(!seen.has(line.clientLineId), `display.lines[${index}].clientLineId`, "no duplicate clientLineId");
|
|
199
|
+
seen.add(line.clientLineId);
|
|
200
|
+
});
|
|
201
|
+
try {
|
|
202
|
+
check(display.exponent === currencyDecimals(payload.currency), "display.exponent", "the currency decimals");
|
|
203
|
+
} catch {
|
|
204
|
+
}
|
|
205
|
+
const text = (value, path) => {
|
|
206
|
+
if (typeof value !== "string") return;
|
|
207
|
+
check(value.length <= 255, path, "at most 255 characters");
|
|
208
|
+
check(!value.includes("\0"), path, "no NUL character");
|
|
209
|
+
};
|
|
210
|
+
display.lines.forEach((line, index) => line.discounts.forEach((discount, i) => {
|
|
211
|
+
for (const key of ["discountId", "label"]) text(discount[key], `display.lines[${index}].discounts[${i}].${key}`);
|
|
212
|
+
}));
|
|
213
|
+
taxByRate.forEach((rate, index) => text(rate.code, `taxByRate[${index}].code`));
|
|
214
|
+
return errors;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// src/server/versions.ts
|
|
218
|
+
var SUPPORTED_ORDER_CREATE_VERSIONS = [1, 2, 3, 4];
|
|
219
|
+
var SUPPORTED_REGISTER_VERSIONS = [1];
|
|
220
|
+
|
|
221
|
+
// src/server/batch.ts
|
|
222
|
+
function validateBatch(body) {
|
|
223
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
224
|
+
return { ok: false, status: 400, message: "Expected body object with commands array" };
|
|
225
|
+
}
|
|
226
|
+
const { commands } = body;
|
|
227
|
+
if (!Array.isArray(commands)) return { ok: false, status: 400, message: "Expected commands array" };
|
|
228
|
+
if (commands.length > MAX_COMMANDS_PER_BATCH) {
|
|
229
|
+
const message = `At most ${MAX_COMMANDS_PER_BATCH} commands are allowed`;
|
|
230
|
+
return { ok: false, status: 413, message, body: { code: "batch_too_large", maxCommands: MAX_COMMANDS_PER_BATCH, message } };
|
|
231
|
+
}
|
|
232
|
+
if (commands.length === 0) return { ok: false, status: 400, message: "commands must not be empty" };
|
|
233
|
+
for (const [index, command] of commands.entries()) {
|
|
234
|
+
if (typeof command !== "object" || command === null || Array.isArray(command)) {
|
|
235
|
+
return { ok: false, status: 400, message: `Invalid commands[${index}]: expected object` };
|
|
236
|
+
}
|
|
237
|
+
let field;
|
|
238
|
+
if (typeof command.id !== "string" || command.id.length === 0 || command.id.length > 64) field = "id";
|
|
239
|
+
else if (![
|
|
240
|
+
"order.create",
|
|
241
|
+
"register.session.open",
|
|
242
|
+
"register.session.transition",
|
|
243
|
+
"register.movement.record",
|
|
244
|
+
"register.movement.void",
|
|
245
|
+
"register.closure.submit"
|
|
246
|
+
].includes(command.type)) field = "type";
|
|
247
|
+
else if (!Number.isSafeInteger(command.version) || command.version < 1) field = "version";
|
|
248
|
+
else if (typeof command.payload !== "object" || command.payload === null || Array.isArray(command.payload)) field = "payload";
|
|
249
|
+
else if (typeof command.createdAt !== "string") field = "createdAt";
|
|
250
|
+
else if (typeof command.deviceId !== "string") field = "deviceId";
|
|
251
|
+
else if (!Number.isSafeInteger(command.attempt) || command.attempt < 1) field = "attempt";
|
|
252
|
+
if (field) return { ok: false, status: 400, message: `Invalid commands[${index}].${field}` };
|
|
253
|
+
}
|
|
254
|
+
return { ok: true, commands };
|
|
255
|
+
}
|
|
256
|
+
function precheckCommand(envelope, supported) {
|
|
257
|
+
for (const key of ["orderCreate", "register"]) {
|
|
258
|
+
if (!supported[key]?.length) throw new TypeError(`precheckCommand: supported.${key} must list at least one version`);
|
|
259
|
+
}
|
|
260
|
+
if (envelope.type !== "order.create") {
|
|
261
|
+
if (!supported.register.includes(envelope.version)) {
|
|
262
|
+
return { id: envelope.id, status: "rejected", error: {
|
|
263
|
+
code: "unsupported_version",
|
|
264
|
+
message: `register version ${envelope.version} is not supported; this server supports ${supported.register.join(", ")}`,
|
|
265
|
+
data: { register: Math.max(...supported.register) }
|
|
266
|
+
} };
|
|
267
|
+
}
|
|
268
|
+
return void 0;
|
|
269
|
+
}
|
|
270
|
+
const command = envelope;
|
|
271
|
+
if (!supported.orderCreate.includes(command.version)) {
|
|
272
|
+
return { id: command.id, status: "rejected", error: {
|
|
273
|
+
code: "unsupported_version",
|
|
274
|
+
message: `order.create version ${command.version} is not supported; this server supports ${supported.orderCreate.join(", ")}`,
|
|
275
|
+
data: { orderCreate: Math.max(...supported.orderCreate) }
|
|
276
|
+
} };
|
|
277
|
+
}
|
|
278
|
+
const { lines, discountMinor } = command.payload;
|
|
279
|
+
const discounted = discountMinor !== void 0 || Array.isArray(lines) && lines.some((line) => line?.discountMinor !== void 0);
|
|
280
|
+
const payload = command.payload;
|
|
281
|
+
const { display, taxByRate, sessionId } = payload;
|
|
282
|
+
const v3 = command.version >= 3;
|
|
283
|
+
const versionError = command.version === 2 && discountMinor === void 0 ? "version 2 requires discountMinor" : command.version === 1 && discounted ? "discountMinor requires version 2" : !v3 && (display !== void 0 || taxByRate !== void 0) ? "display and taxByRate require version 3" : !v3 && sessionId !== void 0 ? "sessionId requires version 3" : !v3 && payload.customer?.customerId !== void 0 ? "customerId requires version 3" : v3 && display !== void 0 !== (taxByRate !== void 0) ? "display and taxByRate must both be present or both absent" : void 0;
|
|
284
|
+
if (versionError) {
|
|
285
|
+
return { id: command.id, status: "rejected", error: { code: "invalid_payload", message: versionError } };
|
|
286
|
+
}
|
|
287
|
+
const bounds = payloadBoundErrors(payload);
|
|
288
|
+
if (bounds.length) {
|
|
289
|
+
return { id: command.id, status: "rejected", error: { code: "invalid_payload", message: bounds.slice(0, 10).join("; ") } };
|
|
290
|
+
}
|
|
291
|
+
const errors = v3 && display !== void 0 && taxByRate !== void 0 && payloadShapeErrors(payload).length === 0 ? fiscalFiguresErrors(payload) : [];
|
|
292
|
+
if (errors.length) {
|
|
293
|
+
return { id: command.id, status: "rejected", error: { code: "invalid_payload", message: errors.slice(0, 10).join("; ") } };
|
|
294
|
+
}
|
|
295
|
+
return void 0;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// src/server/batch-outcome.ts
|
|
299
|
+
function inProgressOutcome(id) {
|
|
300
|
+
return { status: 409, body: { code: "in_progress", id } };
|
|
301
|
+
}
|
|
302
|
+
function transientOutcome(id) {
|
|
303
|
+
return { status: 503, body: { code: "transient", id, message: "Temporary failure, retry later." } };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// src/server/total-warnings.ts
|
|
307
|
+
function totalWarnings(expectedMinor, serverMinor) {
|
|
308
|
+
return serverMinor === expectedMinor ? [] : [{ code: "total_mismatch", expectedMinor, serverMinor }];
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// src/server/command-result.ts
|
|
312
|
+
var CommandResultError = class extends Error {
|
|
313
|
+
constructor(message) {
|
|
314
|
+
super(message);
|
|
315
|
+
this.name = "CommandResultError";
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
function parseCommandResult(value) {
|
|
319
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
320
|
+
throw new CommandResultError("Invalid result: expected object");
|
|
321
|
+
}
|
|
322
|
+
const input = value;
|
|
323
|
+
if (typeof input.id !== "string" || input.id.length === 0) {
|
|
324
|
+
throw new CommandResultError("Invalid id");
|
|
325
|
+
}
|
|
326
|
+
if (input.status !== "applied" && input.status !== "duplicate" && input.status !== "rejected") {
|
|
327
|
+
throw new CommandResultError("Invalid status");
|
|
328
|
+
}
|
|
329
|
+
const result = { id: input.id, status: input.status };
|
|
330
|
+
const object = (value2) => typeof value2 === "object" && value2 !== null && (Object.getPrototypeOf(value2) === Object.prototype || Object.getPrototypeOf(value2) === null);
|
|
331
|
+
if (input.serverRefs !== void 0) {
|
|
332
|
+
if (typeof input.serverRefs !== "object" || input.serverRefs === null || Array.isArray(input.serverRefs)) {
|
|
333
|
+
throw new CommandResultError("Invalid serverRefs");
|
|
334
|
+
}
|
|
335
|
+
const refs = input.serverRefs;
|
|
336
|
+
if (typeof refs.orderId !== "string" || refs.orderId.length === 0) {
|
|
337
|
+
throw new CommandResultError("Invalid serverRefs.orderId");
|
|
338
|
+
}
|
|
339
|
+
if (refs.displayId !== void 0 && typeof refs.displayId !== "string") {
|
|
340
|
+
throw new CommandResultError("Invalid serverRefs.displayId");
|
|
341
|
+
}
|
|
342
|
+
if (!Number.isSafeInteger(refs.totalMinor)) {
|
|
343
|
+
throw new CommandResultError("Invalid serverRefs.totalMinor");
|
|
344
|
+
}
|
|
345
|
+
result.serverRefs = { orderId: refs.orderId, totalMinor: refs.totalMinor };
|
|
346
|
+
if (refs.displayId !== void 0) result.serverRefs.displayId = refs.displayId;
|
|
347
|
+
}
|
|
348
|
+
if (input.register !== void 0) {
|
|
349
|
+
if (!object(input.register)) throw new CommandResultError("Invalid register");
|
|
350
|
+
result.register = input.register;
|
|
351
|
+
}
|
|
352
|
+
if (result.status === "applied" && result.serverRefs === void 0 && result.register === void 0) {
|
|
353
|
+
throw new CommandResultError("Invalid serverRefs: required for applied");
|
|
354
|
+
}
|
|
355
|
+
if (input.warnings !== void 0) {
|
|
356
|
+
if (!Array.isArray(input.warnings)) {
|
|
357
|
+
throw new CommandResultError("Invalid warnings");
|
|
358
|
+
}
|
|
359
|
+
result.warnings = input.warnings.map((warning, index) => {
|
|
360
|
+
const field = `warnings[${index}]`;
|
|
361
|
+
if (typeof warning !== "object" || warning === null || Array.isArray(warning)) {
|
|
362
|
+
throw new CommandResultError(`Invalid ${field}`);
|
|
363
|
+
}
|
|
364
|
+
const item = warning;
|
|
365
|
+
if (item.code === "total_mismatch") {
|
|
366
|
+
for (const key of ["expectedMinor", "serverMinor"]) {
|
|
367
|
+
if (!Number.isInteger(item[key])) {
|
|
368
|
+
throw new CommandResultError(`Invalid ${field}.${key}`);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
if (item.bridgeMinor != null && !Number.isSafeInteger(item.bridgeMinor)) {
|
|
372
|
+
throw new CommandResultError(`Invalid ${field}.bridgeMinor`);
|
|
373
|
+
}
|
|
374
|
+
return item.bridgeMinor != null ? { code: item.code, expectedMinor: item.expectedMinor, serverMinor: item.serverMinor, bridgeMinor: item.bridgeMinor } : { code: item.code, expectedMinor: item.expectedMinor, serverMinor: item.serverMinor };
|
|
375
|
+
}
|
|
376
|
+
if (item.code === "insufficient_stock") {
|
|
377
|
+
if (typeof item.variantId !== "string" || item.variantId.length === 0) {
|
|
378
|
+
throw new CommandResultError(`Invalid ${field}.variantId`);
|
|
379
|
+
}
|
|
380
|
+
if (!Number.isInteger(item.quantity) || item.quantity < 1) {
|
|
381
|
+
throw new CommandResultError(`Invalid ${field}.quantity`);
|
|
382
|
+
}
|
|
383
|
+
return { code: item.code, variantId: item.variantId, quantity: item.quantity };
|
|
384
|
+
}
|
|
385
|
+
if (item.code === "tax_rate_mismatch") {
|
|
386
|
+
if (!Number.isSafeInteger(item.ratePpm) || item.ratePpm < 0) {
|
|
387
|
+
throw new CommandResultError(`Invalid ${field}.ratePpm`);
|
|
388
|
+
}
|
|
389
|
+
for (const key of ["expectedMinor", "serverMinor"]) {
|
|
390
|
+
if (!Number.isSafeInteger(item[key])) {
|
|
391
|
+
throw new CommandResultError(`Invalid ${field}.${key}`);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
return { code: item.code, ratePpm: item.ratePpm, expectedMinor: item.expectedMinor, serverMinor: item.serverMinor };
|
|
395
|
+
}
|
|
396
|
+
if (item.code === "customer_ignored") {
|
|
397
|
+
if (typeof item.customerId !== "string" || item.customerId.length === 0 || item.customerId.length > 64) {
|
|
398
|
+
throw new CommandResultError(`Invalid ${field}.customerId`);
|
|
399
|
+
}
|
|
400
|
+
return { code: item.code, customerId: item.customerId };
|
|
401
|
+
}
|
|
402
|
+
if (item.code === "figures_mismatch") {
|
|
403
|
+
if (!Array.isArray(item.fields) || item.fields.length === 0) throw new CommandResultError(`Invalid ${field}.fields`);
|
|
404
|
+
const seen = [];
|
|
405
|
+
return { code: item.code, fields: item.fields.map((value2, i) => {
|
|
406
|
+
const path = `${field}.fields[${i}]`;
|
|
407
|
+
if (typeof value2 !== "object" || value2 === null || Array.isArray(value2)) throw new CommandResultError(`Invalid ${path}`);
|
|
408
|
+
const entry = value2;
|
|
409
|
+
if (!["subtotalMinor", "taxMinor", "discountMinor"].includes(entry.field) || seen.includes(entry.field)) {
|
|
410
|
+
throw new CommandResultError(`Invalid ${path}.field`);
|
|
411
|
+
}
|
|
412
|
+
seen.push(entry.field);
|
|
413
|
+
if (!Number.isSafeInteger(entry.tillMinor)) throw new CommandResultError(`Invalid ${path}.tillMinor`);
|
|
414
|
+
if (!Number.isSafeInteger(entry.serverMinor) || entry.serverMinor === entry.tillMinor) throw new CommandResultError(`Invalid ${path}.serverMinor`);
|
|
415
|
+
return { field: entry.field, tillMinor: entry.tillMinor, serverMinor: entry.serverMinor };
|
|
416
|
+
}) };
|
|
417
|
+
}
|
|
418
|
+
throw new CommandResultError(`Invalid ${field}.code`);
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
if (input.error !== void 0) {
|
|
422
|
+
if (typeof input.error !== "object" || input.error === null || Array.isArray(input.error)) {
|
|
423
|
+
throw new CommandResultError("Invalid error");
|
|
424
|
+
}
|
|
425
|
+
const error = input.error;
|
|
426
|
+
if (typeof error.code !== "string" || error.code.length === 0) {
|
|
427
|
+
throw new CommandResultError("Invalid error.code");
|
|
428
|
+
}
|
|
429
|
+
if (typeof error.message !== "string") {
|
|
430
|
+
throw new CommandResultError("Invalid error.message");
|
|
431
|
+
}
|
|
432
|
+
result.error = { code: error.code, message: error.message };
|
|
433
|
+
if (error.data !== void 0) {
|
|
434
|
+
if (!object(error.data)) throw new CommandResultError("Invalid error.data");
|
|
435
|
+
result.error.data = error.data;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
if (result.status === "rejected" && result.error === void 0) {
|
|
439
|
+
throw new CommandResultError("Invalid error: required for rejected");
|
|
440
|
+
}
|
|
441
|
+
return result;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// src/server/register-payload-shape.ts
|
|
445
|
+
function registerPayloadErrors(type, payload) {
|
|
446
|
+
const errors = [];
|
|
447
|
+
const object = (value) => typeof value === "object" && value !== null && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
|
|
448
|
+
const check = (valid, field, expected) => {
|
|
449
|
+
if (!valid && errors.length < 10) errors.push(`${field}: expected ${expected}`);
|
|
450
|
+
};
|
|
451
|
+
if (!object(payload)) return ["payload: expected an object"];
|
|
452
|
+
const noNul = (value, field) => {
|
|
453
|
+
if (typeof value === "string") check(!value.includes("\0"), field, "no NUL character");
|
|
454
|
+
};
|
|
455
|
+
const string = (field, optional = false) => {
|
|
456
|
+
const value = payload[field];
|
|
457
|
+
if (optional && value === void 0) return;
|
|
458
|
+
check(typeof value === "string" && (optional || value.length > 0), field, optional ? "a string" : "a non-empty string");
|
|
459
|
+
if (typeof value === "string" && (field.endsWith("Id") || field === "voids")) check(value.length <= 64, field, "at most 64 characters");
|
|
460
|
+
if (typeof value === "string" && ["openedAt", "at", "createdAt", "closedAt"].includes(field)) {
|
|
461
|
+
check(!Number.isNaN(Date.parse(value)), field, "a valid date");
|
|
462
|
+
}
|
|
463
|
+
noNul(value, field);
|
|
464
|
+
};
|
|
465
|
+
const integer = (field, min = -Infinity) => check(Number.isSafeInteger(payload[field]) && payload[field] >= min, field, `a safe integer >= ${min}`);
|
|
466
|
+
const record = (field) => {
|
|
467
|
+
const value = payload[field];
|
|
468
|
+
check(object(value), field, "a record of integers");
|
|
469
|
+
if (object(value)) for (const [key, amount] of Object.entries(value)) {
|
|
470
|
+
check(key.length > 0 && Number.isSafeInteger(amount), `${field}.${key}`, "a non-empty key with a safe integer");
|
|
471
|
+
noNul(key, `${field}.${JSON.stringify(key)}`);
|
|
472
|
+
}
|
|
473
|
+
};
|
|
474
|
+
string("sessionId");
|
|
475
|
+
switch (type) {
|
|
476
|
+
case "register.session.open":
|
|
477
|
+
for (const field of ["registerId", "openedAt"]) string(field);
|
|
478
|
+
for (const field of ["storeKey", "businessDay", "openedBy"]) string(field, true);
|
|
479
|
+
integer("countedFloatMinor", 0);
|
|
480
|
+
for (const field of ["expectedFloatMinor", "openingVarianceMinor"]) if (payload[field] !== void 0) integer(field);
|
|
481
|
+
break;
|
|
482
|
+
case "register.session.transition":
|
|
483
|
+
string("at");
|
|
484
|
+
check(["open", "counting", "closed"].includes(payload.status), "status", "open, counting or closed");
|
|
485
|
+
for (const field of ["counted", "closedBy", "approvedBy"]) if (payload[field] !== void 0) {
|
|
486
|
+
check(payload.status === "closed", field, "a closing transition");
|
|
487
|
+
if (field === "counted") record(field);
|
|
488
|
+
else string(field, true);
|
|
489
|
+
}
|
|
490
|
+
break;
|
|
491
|
+
case "register.movement.record":
|
|
492
|
+
case "register.movement.void":
|
|
493
|
+
for (const field of ["movementId", "createdAt"]) string(field);
|
|
494
|
+
string("createdBy", true);
|
|
495
|
+
if (type === "register.movement.void") string("voids");
|
|
496
|
+
else {
|
|
497
|
+
check(
|
|
498
|
+
typeof payload.reason === "string" && payload.reason.trim().length > 0 && payload.reason.length <= 500,
|
|
499
|
+
"reason",
|
|
500
|
+
"a non-empty string after trim of at most 500 characters"
|
|
501
|
+
);
|
|
502
|
+
noNul(payload.reason, "reason");
|
|
503
|
+
check(["paid_in", "paid_out", "no_sale"].includes(payload.type), "type", "paid_in, paid_out or no_sale");
|
|
504
|
+
integer("amountMinor", payload.type === "no_sale" ? 0 : 1);
|
|
505
|
+
if (payload.type === "no_sale") check(payload.amountMinor === 0, "amountMinor", "0 for no_sale");
|
|
506
|
+
}
|
|
507
|
+
break;
|
|
508
|
+
case "register.closure.submit":
|
|
509
|
+
for (const field of ["closureId", "registerId", "openedAt", "closedAt", "softwareVersion"]) string(field);
|
|
510
|
+
for (const field of ["businessDay", "closedBy", "approvedBy"]) string(field, true);
|
|
511
|
+
integer("number", 1);
|
|
512
|
+
for (const field of [
|
|
513
|
+
"periodSalesTotalMinor",
|
|
514
|
+
"periodRefundsTotalMinor",
|
|
515
|
+
"perpetualSalesTotalMinor",
|
|
516
|
+
"perpetualRefundsTotalMinor",
|
|
517
|
+
"unsyncedCount",
|
|
518
|
+
"unsyncedTotalMinor"
|
|
519
|
+
]) integer(field, 0);
|
|
520
|
+
for (const field of ["number", "unsyncedCount"])
|
|
521
|
+
check(payload[field] <= 2147483647, field, "at most 2147483647");
|
|
522
|
+
for (const field of ["tillExpected", "counted"]) record(field);
|
|
523
|
+
for (const field of ["orderIds", "movementIds"]) {
|
|
524
|
+
const value = payload[field];
|
|
525
|
+
check(Array.isArray(value), field, "an array of ids");
|
|
526
|
+
if (Array.isArray(value)) value.forEach((id, index) => {
|
|
527
|
+
check(typeof id === "string" && id.length > 0 && id.length <= 64, `${field}[${index}]`, "a non-empty string of at most 64 characters");
|
|
528
|
+
noNul(id, `${field}[${index}]`);
|
|
529
|
+
});
|
|
530
|
+
}
|
|
531
|
+
break;
|
|
532
|
+
default:
|
|
533
|
+
check(false, "type", "a register command type");
|
|
534
|
+
}
|
|
535
|
+
return errors;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// src/server/register-figures.ts
|
|
539
|
+
function deriveSessionFigures(input) {
|
|
540
|
+
const expected = Object.assign(/* @__PURE__ */ Object.create(null), { cash: input.countedFloatMinor });
|
|
541
|
+
for (const order of input.orders) {
|
|
542
|
+
if (!Array.isArray(order.payments)) continue;
|
|
543
|
+
for (const payment of order.payments) {
|
|
544
|
+
if (typeof payment?.method !== "string" || !payment.method.length || !Number.isSafeInteger(payment.amountMinor)) continue;
|
|
545
|
+
expected[payment.method] = (expected[payment.method] ?? 0) + payment.amountMinor;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
const voided = new Set(input.movements.filter((row) => row.type === "void").map((row) => row.voids));
|
|
549
|
+
for (const row of input.movements) {
|
|
550
|
+
if (row.type === "void" || voided.has(row.id)) continue;
|
|
551
|
+
if (row.type === "paid_in") expected.cash += row.amountMinor;
|
|
552
|
+
if (row.type === "paid_out") expected.cash -= row.amountMinor;
|
|
553
|
+
}
|
|
554
|
+
return { expected: { ...expected }, salesCount: input.orders.length };
|
|
555
|
+
}
|
|
556
|
+
function deriveVariance(counted, expected) {
|
|
557
|
+
return Object.fromEntries(Object.entries(counted).map(([key, value]) => [key, value - (expected[key] ?? 0)]));
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
// src/server/rejection-codes.ts
|
|
561
|
+
function platformErrorResult(id, platformCode, platformMessage) {
|
|
562
|
+
return { id, status: "rejected", error: { code: "platform_error", message: `${platformCode}: ${platformMessage}`, data: { platformCode, platformMessage } } };
|
|
563
|
+
}
|
|
564
|
+
function internalErrorResult(id, correlationId) {
|
|
565
|
+
return { id, status: "rejected", error: { code: "internal_error", message: `Internal error (ref ${correlationId})`, data: { correlationId } } };
|
|
566
|
+
}
|
|
567
|
+
export {
|
|
568
|
+
CommandResultError,
|
|
569
|
+
MAX_COMMANDS_PER_BATCH,
|
|
570
|
+
SUPPORTED_ORDER_CREATE_VERSIONS,
|
|
571
|
+
SUPPORTED_REGISTER_VERSIONS,
|
|
572
|
+
canonicalJson,
|
|
573
|
+
commandFingerprint,
|
|
574
|
+
currencyDecimals,
|
|
575
|
+
deriveSessionFigures,
|
|
576
|
+
deriveVariance,
|
|
577
|
+
fiscalFiguresErrors,
|
|
578
|
+
inProgressOutcome,
|
|
579
|
+
internalErrorResult,
|
|
580
|
+
majorToMinor,
|
|
581
|
+
minorToMajor,
|
|
582
|
+
parseCommandResult,
|
|
583
|
+
payloadBoundErrors,
|
|
584
|
+
payloadShapeErrors,
|
|
585
|
+
platformErrorResult,
|
|
586
|
+
precheckCommand,
|
|
587
|
+
registerPayloadErrors,
|
|
588
|
+
totalWarnings,
|
|
589
|
+
transientOutcome,
|
|
590
|
+
validateBatch
|
|
591
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tallyui/core",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "3.0.0-next.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Core interfaces, traits, and context providers for Tally UI",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -16,6 +16,12 @@
|
|
|
16
16
|
"types": "./dist/rxdb/index.d.ts",
|
|
17
17
|
"import": "./dist/rxdb/index.js",
|
|
18
18
|
"source": "./src/rxdb/index.ts"
|
|
19
|
+
},
|
|
20
|
+
"./server": {
|
|
21
|
+
"types": "./dist/server/index.d.ts",
|
|
22
|
+
"import": "./dist/server/index.js",
|
|
23
|
+
"source": "./src/server/index.ts",
|
|
24
|
+
"default": "./dist/server/index.js"
|
|
19
25
|
}
|
|
20
26
|
},
|
|
21
27
|
"files": [
|
|
@@ -46,7 +52,7 @@
|
|
|
46
52
|
},
|
|
47
53
|
"devDependencies": {
|
|
48
54
|
"@types/react": ">=18",
|
|
49
|
-
"rxdb": "
|
|
55
|
+
"rxdb": "17.5.0",
|
|
50
56
|
"rxjs": ">=7",
|
|
51
57
|
"react": "^19.2.4"
|
|
52
58
|
},
|
package/src/commands.ts
CHANGED
|
@@ -6,7 +6,7 @@ export const COMMANDS_PATH = '/tally/v1/commands';
|
|
|
6
6
|
export const PROTOCOL_HEADER = 'X-Tally-Protocol';
|
|
7
7
|
/** Current protocol version. */
|
|
8
8
|
export const PROTOCOL_VERSION = 1;
|
|
9
|
-
/**
|
|
9
|
+
/** The ADR-038 batch limit; a server answers more with 413 and a BatchTooLargeBody. */
|
|
10
10
|
export const MAX_COMMANDS_PER_BATCH = 50;
|
|
11
11
|
|
|
12
12
|
/**
|