@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,19 @@
|
|
|
1
|
+
import type { CommandBatchResponse } from '../types'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A plugin's batch handler stops at the first in-progress or transient command and returns that
|
|
5
|
+
* outcome for the whole batch; otherwise it returns 200 with every result in order.
|
|
6
|
+
*/
|
|
7
|
+
export type BatchOutcome =
|
|
8
|
+
| { status: 200; body: CommandBatchResponse }
|
|
9
|
+
| { status: 409; body: { code: 'in_progress'; id: string } }
|
|
10
|
+
| { status: 503; body: { code: 'transient'; id: string; message: 'Temporary failure, retry later.' } }
|
|
11
|
+
|
|
12
|
+
export function inProgressOutcome(id: string): BatchOutcome {
|
|
13
|
+
return { status: 409, body: { code: 'in_progress', id } }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** The message is fixed so a server never leaks its internal error (log that separately). */
|
|
17
|
+
export function transientOutcome(id: string): BatchOutcome {
|
|
18
|
+
return { status: 503, body: { code: 'transient', id, message: 'Temporary failure, retry later.' } }
|
|
19
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { MAX_COMMANDS_PER_BATCH } from '../commands'
|
|
2
|
+
import type { AnyCommandEnvelope, BatchTooLargeBody, CommandEnvelope, CommandResult, OrderCreatePayload, RegisterCommandEnvelope } from '../types'
|
|
3
|
+
import { fiscalFiguresErrors, type OrderCreatePayloadV3 } from './fiscal-figures'
|
|
4
|
+
import { payloadBoundErrors, payloadShapeErrors } from './order-payload-shape'
|
|
5
|
+
|
|
6
|
+
/** An envelope validateBatch accepted: every field's shape is checked, and its version is any positive
|
|
7
|
+
* safe integer (precheckCommand decides which versions this server supports). */
|
|
8
|
+
export type ValidatedCommandEnvelope =
|
|
9
|
+
| (Omit<CommandEnvelope<Record<string, unknown>>, 'version'> & { type: 'order.create'; version: number })
|
|
10
|
+
| RegisterCommandEnvelope<Record<string, unknown>>
|
|
11
|
+
|
|
12
|
+
/** Validates every envelope before any command is claimed. */
|
|
13
|
+
export function validateBatch(body: unknown):
|
|
14
|
+
| { ok: true; commands: ValidatedCommandEnvelope[] }
|
|
15
|
+
| { ok: false; status: 400; message: string }
|
|
16
|
+
| { ok: false; status: 413; message: string; body: BatchTooLargeBody } {
|
|
17
|
+
if (typeof body !== 'object' || body === null || Array.isArray(body)) {
|
|
18
|
+
return { ok: false, status: 400, message: 'Expected body object with commands array' }
|
|
19
|
+
}
|
|
20
|
+
const { commands } = body as Record<string, unknown>
|
|
21
|
+
if (!Array.isArray(commands)) return { ok: false, status: 400, message: 'Expected commands array' }
|
|
22
|
+
if (commands.length > MAX_COMMANDS_PER_BATCH) {
|
|
23
|
+
const message = `At most ${MAX_COMMANDS_PER_BATCH} commands are allowed`
|
|
24
|
+
return { ok: false, status: 413, message, body: { code: 'batch_too_large', maxCommands: MAX_COMMANDS_PER_BATCH, message } }
|
|
25
|
+
}
|
|
26
|
+
if (commands.length === 0) return { ok: false, status: 400, message: 'commands must not be empty' }
|
|
27
|
+
for (const [index, command] of commands.entries()) {
|
|
28
|
+
if (typeof command !== 'object' || command === null || Array.isArray(command)) {
|
|
29
|
+
return { ok: false, status: 400, message: `Invalid commands[${index}]: expected object` }
|
|
30
|
+
}
|
|
31
|
+
let field: string | undefined
|
|
32
|
+
if (typeof command.id !== 'string' || command.id.length === 0 || command.id.length > 64) field = 'id'
|
|
33
|
+
else if (!['order.create', 'register.session.open', 'register.session.transition', 'register.movement.record',
|
|
34
|
+
'register.movement.void', 'register.closure.submit'].includes(command.type)) field = 'type'
|
|
35
|
+
else if (!Number.isSafeInteger(command.version) || command.version < 1) field = 'version'
|
|
36
|
+
else if (typeof command.payload !== 'object' || command.payload === null || Array.isArray(command.payload)) field = 'payload'
|
|
37
|
+
else if (typeof command.createdAt !== 'string') field = 'createdAt'
|
|
38
|
+
else if (typeof command.deviceId !== 'string') field = 'deviceId'
|
|
39
|
+
else if (!Number.isSafeInteger(command.attempt) || command.attempt < 1) field = 'attempt'
|
|
40
|
+
if (field) return { ok: false, status: 400, message: `Invalid commands[${index}].${field}` }
|
|
41
|
+
}
|
|
42
|
+
return { ok: true, commands }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The rejection a batch returns for this command before any executor runs, or undefined
|
|
47
|
+
* when the command goes on to the plugin's executor. A plugin's batch handler calls
|
|
48
|
+
* validateBatch once, then, for each command in order: the shape check (payloadShapeErrors:
|
|
49
|
+
* types and NUL) first, before any database access, because a NUL in clientOrderId would make
|
|
50
|
+
* the lookup itself fail; then the plugin's own replay and collision lookups; then
|
|
51
|
+
* precheckCommand (versions, string lengths via payloadBoundErrors, fiscal figures); then the
|
|
52
|
+
* claim, in the executor (order.create; register commands follow ADR-068). It pushes any result
|
|
53
|
+
* one of those steps returns and moves on.
|
|
54
|
+
*
|
|
55
|
+
* The replay lookup goes before precheckCommand so an already-applied command always replays
|
|
56
|
+
* as `duplicate`, even once a later @tallyui/core tightens what precheckCommand accepts.
|
|
57
|
+
*
|
|
58
|
+
* `supported` is the SERVER's own list (what its /info advertises), never core's constants, which are the
|
|
59
|
+
* till's capability (#297). The version check, the `unsupported_version` message and its `data` all use it:
|
|
60
|
+
* `precheckCommand(envelope, { orderCreate: [1, 2, 3], register: [1] })`.
|
|
61
|
+
*/
|
|
62
|
+
export function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCommandEnvelope, 'id' | 'type' | 'version' | 'payload'>,
|
|
63
|
+
supported: { orderCreate: readonly number[]; register: readonly number[] }): CommandResult | undefined {
|
|
64
|
+
// An empty list would send Math.max() of nothing (-Infinity, null in JSON) as the server's version.
|
|
65
|
+
for (const key of ['orderCreate', 'register'] as const) {
|
|
66
|
+
if (!supported[key]?.length) throw new TypeError(`precheckCommand: supported.${key} must list at least one version`)
|
|
67
|
+
}
|
|
68
|
+
if (envelope.type !== 'order.create') {
|
|
69
|
+
if (!supported.register.includes(envelope.version)) {
|
|
70
|
+
return { id: envelope.id, status: 'rejected', error: { code: 'unsupported_version',
|
|
71
|
+
message: `register version ${envelope.version} is not supported; this server supports ${supported.register.join(', ')}`,
|
|
72
|
+
data: { register: Math.max(...supported.register) },
|
|
73
|
+
} }
|
|
74
|
+
}
|
|
75
|
+
return undefined
|
|
76
|
+
}
|
|
77
|
+
const command = envelope as CommandEnvelope<OrderCreatePayload>
|
|
78
|
+
if (!supported.orderCreate.includes(command.version)) {
|
|
79
|
+
return { id: command.id, status: 'rejected', error: { code: 'unsupported_version',
|
|
80
|
+
message: `order.create version ${command.version} is not supported; this server supports ${supported.orderCreate.join(', ')}`,
|
|
81
|
+
data: { orderCreate: Math.max(...supported.orderCreate) },
|
|
82
|
+
} }
|
|
83
|
+
}
|
|
84
|
+
// ADR-062 sends version 2 exactly when there is a discount, so version 1 can never create adjustments.
|
|
85
|
+
const { lines, discountMinor } = command.payload as { lines?: unknown; discountMinor?: unknown }
|
|
86
|
+
const discounted = discountMinor !== undefined
|
|
87
|
+
|| (Array.isArray(lines) && lines.some(line => (line as { discountMinor?: unknown } | null)?.discountMinor !== undefined))
|
|
88
|
+
const payload = command.payload as OrderCreatePayloadV3
|
|
89
|
+
const { display, taxByRate, sessionId } = payload
|
|
90
|
+
// Version 4 carries version 3's fields (#286); only what discountMinor means changes.
|
|
91
|
+
const v3 = command.version >= 3
|
|
92
|
+
const versionError = command.version === 2 && discountMinor === undefined ? 'version 2 requires discountMinor'
|
|
93
|
+
: command.version === 1 && discounted ? 'discountMinor requires version 2'
|
|
94
|
+
: !v3 && (display !== undefined || taxByRate !== undefined) ? 'display and taxByRate require version 3'
|
|
95
|
+
: !v3 && sessionId !== undefined ? 'sessionId requires version 3'
|
|
96
|
+
: !v3 && payload.customer?.customerId !== undefined ? 'customerId requires version 3'
|
|
97
|
+
: v3 && (display !== undefined) !== (taxByRate !== undefined) ? 'display and taxByRate must both be present or both absent'
|
|
98
|
+
: undefined
|
|
99
|
+
if (versionError) {
|
|
100
|
+
return { id: command.id, status: 'rejected', error: { code: 'invalid_payload', message: versionError } }
|
|
101
|
+
}
|
|
102
|
+
const bounds = payloadBoundErrors(payload)
|
|
103
|
+
if (bounds.length) {
|
|
104
|
+
return { id: command.id, status: 'rejected', error: { code: 'invalid_payload', message: bounds.slice(0, 10).join('; ') } }
|
|
105
|
+
}
|
|
106
|
+
const errors = v3 && display !== undefined && taxByRate !== undefined && payloadShapeErrors(payload).length === 0
|
|
107
|
+
? fiscalFiguresErrors(payload) : []
|
|
108
|
+
if (errors.length) {
|
|
109
|
+
return { id: command.id, status: 'rejected', error: { code: 'invalid_payload', message: errors.slice(0, 10).join('; ') } }
|
|
110
|
+
}
|
|
111
|
+
return undefined
|
|
112
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import type { CommandResult, RegisterCommandResult } from '../types'
|
|
2
|
+
|
|
3
|
+
/** parseCommandResult's refusal; its message names the first bad field. A plugin maps it
|
|
4
|
+
* to its own invalid-data error (e.g. Medusa's MedusaError INVALID_DATA). */
|
|
5
|
+
export class CommandResultError extends Error {
|
|
6
|
+
constructor(message: string) { super(message); this.name = 'CommandResultError' }
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** Validates a CommandResult (e.g. one read back from the ledger). Throws
|
|
10
|
+
* CommandResultError naming the first bad field. */
|
|
11
|
+
export function parseCommandResult(value: unknown): CommandResult {
|
|
12
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
13
|
+
throw new CommandResultError('Invalid result: expected object')
|
|
14
|
+
}
|
|
15
|
+
const input = value as Record<string, unknown>
|
|
16
|
+
if (typeof input.id !== 'string' || input.id.length === 0) {
|
|
17
|
+
throw new CommandResultError('Invalid id')
|
|
18
|
+
}
|
|
19
|
+
if (input.status !== 'applied' && input.status !== 'duplicate' && input.status !== 'rejected') {
|
|
20
|
+
throw new CommandResultError('Invalid status')
|
|
21
|
+
}
|
|
22
|
+
const result: CommandResult = { id: input.id, status: input.status }
|
|
23
|
+
const object = (value: unknown): boolean => typeof value === 'object' && value !== null
|
|
24
|
+
&& (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)
|
|
25
|
+
if (input.serverRefs !== undefined) {
|
|
26
|
+
if (typeof input.serverRefs !== 'object' || input.serverRefs === null || Array.isArray(input.serverRefs)) {
|
|
27
|
+
throw new CommandResultError('Invalid serverRefs')
|
|
28
|
+
}
|
|
29
|
+
const refs = input.serverRefs as Record<string, unknown>
|
|
30
|
+
if (typeof refs.orderId !== 'string' || refs.orderId.length === 0) {
|
|
31
|
+
throw new CommandResultError('Invalid serverRefs.orderId')
|
|
32
|
+
}
|
|
33
|
+
if (refs.displayId !== undefined && typeof refs.displayId !== 'string') {
|
|
34
|
+
throw new CommandResultError('Invalid serverRefs.displayId')
|
|
35
|
+
}
|
|
36
|
+
if (!Number.isSafeInteger(refs.totalMinor)) {
|
|
37
|
+
throw new CommandResultError('Invalid serverRefs.totalMinor')
|
|
38
|
+
}
|
|
39
|
+
result.serverRefs = { orderId: refs.orderId, totalMinor: refs.totalMinor as number }
|
|
40
|
+
if (refs.displayId !== undefined) result.serverRefs.displayId = refs.displayId as string
|
|
41
|
+
}
|
|
42
|
+
if (input.register !== undefined) {
|
|
43
|
+
if (!object(input.register)) throw new CommandResultError('Invalid register')
|
|
44
|
+
result.register = input.register as RegisterCommandResult
|
|
45
|
+
}
|
|
46
|
+
if (result.status === 'applied' && result.serverRefs === undefined && result.register === undefined) {
|
|
47
|
+
throw new CommandResultError('Invalid serverRefs: required for applied')
|
|
48
|
+
}
|
|
49
|
+
if (input.warnings !== undefined) {
|
|
50
|
+
if (!Array.isArray(input.warnings)) {
|
|
51
|
+
throw new CommandResultError('Invalid warnings')
|
|
52
|
+
}
|
|
53
|
+
result.warnings = input.warnings.map((warning: unknown, index) => {
|
|
54
|
+
const field = `warnings[${index}]`
|
|
55
|
+
if (typeof warning !== 'object' || warning === null || Array.isArray(warning)) {
|
|
56
|
+
throw new CommandResultError(`Invalid ${field}`)
|
|
57
|
+
}
|
|
58
|
+
const item = warning as Record<string, unknown>
|
|
59
|
+
if (item.code === 'total_mismatch') {
|
|
60
|
+
for (const key of ['expectedMinor', 'serverMinor']) {
|
|
61
|
+
if (!Number.isInteger(item[key])) {
|
|
62
|
+
throw new CommandResultError(`Invalid ${field}.${key}`)
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if (item.bridgeMinor != null && !Number.isSafeInteger(item.bridgeMinor)) {
|
|
66
|
+
throw new CommandResultError(`Invalid ${field}.bridgeMinor`)
|
|
67
|
+
}
|
|
68
|
+
return item.bridgeMinor != null
|
|
69
|
+
? { code: item.code, expectedMinor: item.expectedMinor as number, serverMinor: item.serverMinor as number, bridgeMinor: item.bridgeMinor as number }
|
|
70
|
+
: { code: item.code, expectedMinor: item.expectedMinor as number, serverMinor: item.serverMinor as number }
|
|
71
|
+
}
|
|
72
|
+
if (item.code === 'insufficient_stock') {
|
|
73
|
+
if (typeof item.variantId !== 'string' || item.variantId.length === 0) {
|
|
74
|
+
throw new CommandResultError(`Invalid ${field}.variantId`)
|
|
75
|
+
}
|
|
76
|
+
if (!Number.isInteger(item.quantity) || (item.quantity as number) < 1) {
|
|
77
|
+
throw new CommandResultError(`Invalid ${field}.quantity`)
|
|
78
|
+
}
|
|
79
|
+
return { code: item.code, variantId: item.variantId, quantity: item.quantity as number }
|
|
80
|
+
}
|
|
81
|
+
if (item.code === 'tax_rate_mismatch') {
|
|
82
|
+
if (!Number.isSafeInteger(item.ratePpm) || (item.ratePpm as number) < 0) {
|
|
83
|
+
throw new CommandResultError(`Invalid ${field}.ratePpm`)
|
|
84
|
+
}
|
|
85
|
+
for (const key of ['expectedMinor', 'serverMinor']) {
|
|
86
|
+
if (!Number.isSafeInteger(item[key])) {
|
|
87
|
+
throw new CommandResultError(`Invalid ${field}.${key}`)
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return { code: item.code, ratePpm: item.ratePpm as number, expectedMinor: item.expectedMinor as number, serverMinor: item.serverMinor as number }
|
|
91
|
+
}
|
|
92
|
+
if (item.code === 'customer_ignored') {
|
|
93
|
+
if (typeof item.customerId !== 'string' || item.customerId.length === 0 || item.customerId.length > 64) {
|
|
94
|
+
throw new CommandResultError(`Invalid ${field}.customerId`)
|
|
95
|
+
}
|
|
96
|
+
return { code: item.code, customerId: item.customerId }
|
|
97
|
+
}
|
|
98
|
+
if (item.code === 'figures_mismatch') {
|
|
99
|
+
if (!Array.isArray(item.fields) || item.fields.length === 0) throw new CommandResultError(`Invalid ${field}.fields`)
|
|
100
|
+
const seen: string[] = []
|
|
101
|
+
return { code: item.code, fields: item.fields.map((value: unknown, i) => {
|
|
102
|
+
const path = `${field}.fields[${i}]`
|
|
103
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new CommandResultError(`Invalid ${path}`)
|
|
104
|
+
const entry = value as Record<string, unknown>
|
|
105
|
+
if (!['subtotalMinor', 'taxMinor', 'discountMinor'].includes(entry.field as string) || seen.includes(entry.field as string)) {
|
|
106
|
+
throw new CommandResultError(`Invalid ${path}.field`)
|
|
107
|
+
}
|
|
108
|
+
seen.push(entry.field as string)
|
|
109
|
+
if (!Number.isSafeInteger(entry.tillMinor)) throw new CommandResultError(`Invalid ${path}.tillMinor`)
|
|
110
|
+
if (!Number.isSafeInteger(entry.serverMinor) || entry.serverMinor === entry.tillMinor) throw new CommandResultError(`Invalid ${path}.serverMinor`)
|
|
111
|
+
return { field: entry.field as 'subtotalMinor' | 'taxMinor' | 'discountMinor', tillMinor: entry.tillMinor as number, serverMinor: entry.serverMinor as number }
|
|
112
|
+
}) }
|
|
113
|
+
}
|
|
114
|
+
throw new CommandResultError(`Invalid ${field}.code`)
|
|
115
|
+
})
|
|
116
|
+
}
|
|
117
|
+
if (input.error !== undefined) {
|
|
118
|
+
if (typeof input.error !== 'object' || input.error === null || Array.isArray(input.error)) {
|
|
119
|
+
throw new CommandResultError('Invalid error')
|
|
120
|
+
}
|
|
121
|
+
const error = input.error as Record<string, unknown>
|
|
122
|
+
if (typeof error.code !== 'string' || error.code.length === 0) {
|
|
123
|
+
throw new CommandResultError('Invalid error.code')
|
|
124
|
+
}
|
|
125
|
+
if (typeof error.message !== 'string') {
|
|
126
|
+
throw new CommandResultError('Invalid error.message')
|
|
127
|
+
}
|
|
128
|
+
result.error = { code: error.code, message: error.message }
|
|
129
|
+
if (error.data !== undefined) {
|
|
130
|
+
if (!object(error.data)) throw new CommandResultError('Invalid error.data')
|
|
131
|
+
result.error.data = error.data as Record<string, unknown>
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (result.status === 'rejected' && result.error === undefined) {
|
|
135
|
+
throw new CommandResultError('Invalid error: required for rejected')
|
|
136
|
+
}
|
|
137
|
+
return result
|
|
138
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
|
|
3
|
+
/** JSON with recursively sorted object keys; arrays keep their order. */
|
|
4
|
+
export function canonicalJson(value: unknown): string {
|
|
5
|
+
if (Array.isArray(value)) return `[${value.map(item => canonicalJson(item) ?? 'null').join(',')}]`
|
|
6
|
+
if (value !== null && typeof value === 'object') {
|
|
7
|
+
const object = value as Record<string, unknown>
|
|
8
|
+
return `{${Object.keys(object).sort().filter(key => object[key] !== undefined)
|
|
9
|
+
.map(key => `${JSON.stringify(key)}:${canonicalJson(object[key])}`).join(',')}}`
|
|
10
|
+
}
|
|
11
|
+
return JSON.stringify(value)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Lower-case hex SHA-256 of the canonical command content. */
|
|
15
|
+
export function commandFingerprint(envelope: { type: string; version: number; payload: unknown }): string {
|
|
16
|
+
const { type, version, payload } = envelope
|
|
17
|
+
return createHash('sha256').update(canonicalJson({ type, version, payload })).digest('hex')
|
|
18
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import type { CommandError, OrderCreatePayload } from '../types'
|
|
2
|
+
import { currencyDecimals } from './money'
|
|
3
|
+
|
|
4
|
+
export type { OrderCreateDisplay, OrderCreateTaxRate } from '../types'
|
|
5
|
+
/** @deprecated Use `CommandError` from `@tallyui/core`; kept for plugins migrating from local copies. */
|
|
6
|
+
export type CommandErrorWithData = CommandError
|
|
7
|
+
/** @deprecated Use `OrderCreatePayload` from `@tallyui/core`; kept for plugins migrating from local copies. */
|
|
8
|
+
export type OrderCreatePayloadV3 = OrderCreatePayload
|
|
9
|
+
|
|
10
|
+
export function fiscalFiguresErrors(payload: OrderCreatePayloadV3): string[] {
|
|
11
|
+
const errors: string[] = []
|
|
12
|
+
const check = (valid: boolean, path: string, expected: string) => {
|
|
13
|
+
if (!valid && errors.length < 10) errors.push(`${path}: expected ${expected}`)
|
|
14
|
+
}
|
|
15
|
+
const object = (value: unknown, path: string, keys: string[]): value is Record<string, unknown> => {
|
|
16
|
+
const valid = typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
17
|
+
check(valid, path, 'an object')
|
|
18
|
+
if (valid) for (const key of Object.keys(value)) check(keys.includes(key), `${path}.${key}`, 'no unknown key')
|
|
19
|
+
return valid
|
|
20
|
+
}
|
|
21
|
+
const money = (value: Record<string, unknown>, path: string, keys: string[]) => {
|
|
22
|
+
for (const key of keys) check(Number.isSafeInteger(value[key]), `${path}.${key}`, 'a safe integer')
|
|
23
|
+
}
|
|
24
|
+
const { display, taxByRate } = payload
|
|
25
|
+
if (object(display, 'display', ['currency', 'exponent', 'taxInclusive', 'subtotalMinor', 'discountMinor', 'taxMinor', 'totalMinor', 'orderDiscountMinor', 'lines'])) {
|
|
26
|
+
check(typeof display.currency === 'string', 'display.currency', 'a string')
|
|
27
|
+
check(Number.isInteger(display.exponent) && display.exponent >= 0, 'display.exponent', 'an integer >= 0')
|
|
28
|
+
check(typeof display.taxInclusive === 'boolean', 'display.taxInclusive', 'a boolean')
|
|
29
|
+
money(display, 'display', ['subtotalMinor', 'discountMinor', 'taxMinor', 'totalMinor', 'orderDiscountMinor'])
|
|
30
|
+
check(Array.isArray(display.lines), 'display.lines', 'an array')
|
|
31
|
+
if (Array.isArray(display.lines)) display.lines.forEach((line, index) => {
|
|
32
|
+
const path = `display.lines[${index}]`
|
|
33
|
+
if (!object(line, path, ['clientLineId', 'amountMinor', 'discounts'])) return
|
|
34
|
+
check(typeof line.clientLineId === 'string', `${path}.clientLineId`, 'a string')
|
|
35
|
+
money(line, path, ['amountMinor'])
|
|
36
|
+
check(Array.isArray(line.discounts), `${path}.discounts`, 'an array')
|
|
37
|
+
if (Array.isArray(line.discounts)) line.discounts.forEach((discount, index) => {
|
|
38
|
+
const discountPath = `${path}.discounts[${index}]`
|
|
39
|
+
if (!object(discount, discountPath, ['discountId', 'label', 'amountMinor'])) return
|
|
40
|
+
check(typeof discount.discountId === 'string', `${discountPath}.discountId`, 'a string')
|
|
41
|
+
if (discount.label !== undefined) check(typeof discount.label === 'string', `${discountPath}.label`, 'a string')
|
|
42
|
+
money(discount, discountPath, ['amountMinor'])
|
|
43
|
+
})
|
|
44
|
+
})
|
|
45
|
+
}
|
|
46
|
+
check(Array.isArray(taxByRate), 'taxByRate', 'an array')
|
|
47
|
+
if (Array.isArray(taxByRate)) taxByRate.forEach((rate, index) => {
|
|
48
|
+
const path = `taxByRate[${index}]`
|
|
49
|
+
if (!object(rate, path, ['ratePpm', 'code', 'netMinor', 'taxMinor', 'grossMinor'])) return
|
|
50
|
+
check(Number.isInteger(rate.ratePpm), `${path}.ratePpm`, 'an integer')
|
|
51
|
+
if (rate.code !== undefined) check(typeof rate.code === 'string', `${path}.code`, 'a string')
|
|
52
|
+
money(rate, path, ['netMinor', 'taxMinor', 'grossMinor'])
|
|
53
|
+
})
|
|
54
|
+
if (errors.length || !display || !Array.isArray(taxByRate)) return errors
|
|
55
|
+
check(display.currency === payload.currency, 'display.currency', 'payload.currency')
|
|
56
|
+
check(display.totalMinor === payload.totalMinor, 'display.totalMinor', 'payload.totalMinor')
|
|
57
|
+
check(display.taxMinor === payload.taxMinor, 'display.taxMinor', 'payload.taxMinor')
|
|
58
|
+
check(taxByRate.length > 0 || payload.taxMinor === 0, 'taxByRate', 'a non-empty array when payload.taxMinor is nonzero')
|
|
59
|
+
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')
|
|
60
|
+
taxByRate.forEach((rate, index) => check(BigInt(rate.grossMinor) === BigInt(rate.netMinor) + BigInt(rate.taxMinor), `taxByRate[${index}].grossMinor`, 'netMinor + taxMinor'))
|
|
61
|
+
const ids = new Set(Array.isArray(payload.lines) ? payload.lines.map(line => line?.clientLineId) : [])
|
|
62
|
+
const seen = new Set<string>()
|
|
63
|
+
display.lines.forEach((line, index) => {
|
|
64
|
+
check(ids.has(line.clientLineId), `display.lines[${index}].clientLineId`, 'a payload.lines[].clientLineId')
|
|
65
|
+
check(!seen.has(line.clientLineId), `display.lines[${index}].clientLineId`, 'no duplicate clientLineId')
|
|
66
|
+
seen.add(line.clientLineId)
|
|
67
|
+
})
|
|
68
|
+
try {
|
|
69
|
+
check(display.exponent === currencyDecimals(payload.currency), 'display.exponent', 'the currency decimals')
|
|
70
|
+
} catch {
|
|
71
|
+
// Leave unsupported currencies to the planner's unsupported_currency rejection.
|
|
72
|
+
}
|
|
73
|
+
// The shared string bound and NUL check (payloadBoundErrors' length rule and payloadShapeErrors' NUL rule) on the v3 strings, after every check above.
|
|
74
|
+
const text = (value: unknown, path: string) => {
|
|
75
|
+
if (typeof value !== 'string') return
|
|
76
|
+
check(value.length <= 255, path, 'at most 255 characters')
|
|
77
|
+
check(!value.includes('\u0000'), path, 'no NUL character')
|
|
78
|
+
}
|
|
79
|
+
display.lines.forEach((line, index) => line.discounts.forEach((discount, i) => {
|
|
80
|
+
for (const key of ['discountId', 'label'] as const) text(discount[key], `display.lines[${index}].discounts[${i}].${key}`)
|
|
81
|
+
}))
|
|
82
|
+
taxByRate.forEach((rate, index) => text(rate.code, `taxByRate[${index}].code`))
|
|
83
|
+
return errors
|
|
84
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export { currencyDecimals, minorToMajor, majorToMinor } from './money'
|
|
2
|
+
export { canonicalJson, commandFingerprint } from './fingerprint'
|
|
3
|
+
export { payloadBoundErrors, payloadShapeErrors } from './order-payload-shape'
|
|
4
|
+
export { fiscalFiguresErrors } from './fiscal-figures'
|
|
5
|
+
export type { CommandErrorWithData, OrderCreateDisplay, OrderCreateTaxRate, OrderCreatePayloadV3 } from './fiscal-figures'
|
|
6
|
+
export { SUPPORTED_ORDER_CREATE_VERSIONS, SUPPORTED_REGISTER_VERSIONS } from './versions'
|
|
7
|
+
export { MAX_COMMANDS_PER_BATCH } from '../commands'
|
|
8
|
+
export { validateBatch, precheckCommand } from './batch'
|
|
9
|
+
export type { ValidatedCommandEnvelope } from './batch'
|
|
10
|
+
export type { BatchTooLargeBody } from '../types'
|
|
11
|
+
export { inProgressOutcome, transientOutcome } from './batch-outcome'
|
|
12
|
+
export type { BatchOutcome } from './batch-outcome'
|
|
13
|
+
export { totalWarnings } from './total-warnings'
|
|
14
|
+
export type { OrderRejectionCode, Rejection } from './total-warnings'
|
|
15
|
+
export { parseCommandResult, CommandResultError } from './command-result'
|
|
16
|
+
export { registerPayloadErrors } from './register-payload-shape'
|
|
17
|
+
export { deriveSessionFigures, deriveVariance } from './register-figures'
|
|
18
|
+
export type { RegisterConflictCode, RegisterOutcome } from './register-outcome'
|
|
19
|
+
export { platformErrorResult, internalErrorResult } from './rejection-codes'
|
|
20
|
+
export type { CommandRejectionCode } from './rejection-codes'
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** ISO 4217 minor-unit exponent as resolved by Intl (which rejects malformed codes); depends on the runtime's ICU data. */
|
|
2
|
+
export function currencyDecimals(currency: string): number {
|
|
3
|
+
return new Intl.NumberFormat('en', { style: 'currency', currency }).resolvedOptions().maximumFractionDigits!
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
/** Converts a safe integer minor amount to an exact major-unit decimal string. */
|
|
7
|
+
export function minorToMajor(minor: number, decimals: number): string {
|
|
8
|
+
if (!Number.isSafeInteger(minor)) throw new RangeError('minor must be a safe integer')
|
|
9
|
+
const sign = minor < 0 ? '-' : ''
|
|
10
|
+
const digits = Math.abs(minor).toString().padStart(decimals + 1, '0')
|
|
11
|
+
return sign + (decimals === 0 ? digits : `${digits.slice(0, -decimals)}.${digits.slice(-decimals)}`)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Rounds a major-unit decimal to minor units, half away from zero, without float scaling. */
|
|
15
|
+
export function majorToMinor(value: string | number, decimals: number): number {
|
|
16
|
+
// The dot group is optional as a whole, not per-side: `\d+\.?\d*` lets `\d+` and `\d*` split a
|
|
17
|
+
// digit run many ways, so a long non-matching digit string backtracks quadratically (CodeQL ReDoS).
|
|
18
|
+
const match = /^([+-]?)(\d+(?:\.\d*)?|\.\d+)(?:e([+-]?\d+))?$/i.exec(String(value))
|
|
19
|
+
if (!match) throw new RangeError('value must be a finite decimal')
|
|
20
|
+
const [, sign, mantissa, exponent = '0'] = match
|
|
21
|
+
const [whole, fraction = ''] = mantissa.split('.')
|
|
22
|
+
const coefficient = BigInt(whole + fraction)
|
|
23
|
+
const shift = BigInt(decimals) + BigInt(exponent) - BigInt(fraction.length)
|
|
24
|
+
let rounded: bigint
|
|
25
|
+
if (shift >= 0n) {
|
|
26
|
+
rounded = coefficient * 10n ** shift
|
|
27
|
+
} else {
|
|
28
|
+
const divisor = 10n ** -shift
|
|
29
|
+
rounded = coefficient / divisor + (coefficient % divisor * 2n >= divisor ? 1n : 0n)
|
|
30
|
+
}
|
|
31
|
+
const minor = Number(sign === '-' ? -rounded : rounded)
|
|
32
|
+
if (!Number.isSafeInteger(minor)) throw new RangeError('minor amount exceeds safe integer range')
|
|
33
|
+
return minor
|
|
34
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/** Shape errors of an order.create payload, e.g. ['lines: expected a non-empty array',
|
|
2
|
+
* 'payments[0].method: expected a string']; [] when the shape is valid, at most ten. Checks
|
|
3
|
+
* presence, types, the `customerId` (64) and `sessionId` (36) bounds, and U+0000 in any string;
|
|
4
|
+
* numbers are finite numbers, and value ranges are the planner's job. A plugin runs it before its
|
|
5
|
+
* replay lookup; every other length bound is payloadBoundErrors', after that lookup. The NUL check
|
|
6
|
+
* runs last, so the earlier checks' errors keep their order. */
|
|
7
|
+
export function payloadShapeErrors(payload: unknown): string[] {
|
|
8
|
+
const errors: string[] = []
|
|
9
|
+
const object = (value: unknown): value is Record<string, unknown> =>
|
|
10
|
+
typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
11
|
+
const check = (valid: boolean, path: string, expected: string) => {
|
|
12
|
+
if (!valid && errors.length < 10) errors.push(`${path}: expected ${expected}`)
|
|
13
|
+
}
|
|
14
|
+
const number = (value: unknown, path: string) =>
|
|
15
|
+
check(typeof value === 'number' && Number.isFinite(value), path, 'a finite number')
|
|
16
|
+
// Discounts (ADR-062) are checked here, values included, when present.
|
|
17
|
+
const discount = (value: unknown, path: string): bigint => {
|
|
18
|
+
const valid = value === undefined || (Number.isSafeInteger(value) && (value as number) > 0)
|
|
19
|
+
check(valid, path, 'a positive safe integer')
|
|
20
|
+
return valid && value !== undefined ? BigInt(value as number) : 0n
|
|
21
|
+
}
|
|
22
|
+
if (!object(payload)) return ['payload: expected an object']
|
|
23
|
+
check(typeof payload.clientOrderId === 'string' && payload.clientOrderId.length > 0, 'clientOrderId', 'a non-empty string')
|
|
24
|
+
for (const field of ['createdAt', 'currency']) check(typeof payload[field] === 'string', field, 'a string')
|
|
25
|
+
check(typeof payload.pricesIncludeTax === 'boolean', 'pricesIncludeTax', 'a boolean')
|
|
26
|
+
for (const field of ['lines', 'payments']) {
|
|
27
|
+
const items = payload[field]
|
|
28
|
+
const isLines = field === 'lines'
|
|
29
|
+
check(Array.isArray(items) && (!isLines || items.length > 0), field, isLines ? 'a non-empty array' : 'an array')
|
|
30
|
+
if (!Array.isArray(items)) continue
|
|
31
|
+
for (const [index, item] of items.entries()) {
|
|
32
|
+
if (errors.length === 10) break
|
|
33
|
+
const path = `${field}[${index}]`
|
|
34
|
+
check(object(item), path, 'an object')
|
|
35
|
+
if (!object(item)) continue
|
|
36
|
+
for (const key of isLines ? ['clientLineId', 'variantId'] : ['clientPaymentId', 'method']) {
|
|
37
|
+
check(typeof item[key] === 'string', `${path}.${key}`, 'a string')
|
|
38
|
+
}
|
|
39
|
+
const optionalString = isLines ? 'title' : 'reference'
|
|
40
|
+
if (item[optionalString] !== undefined) {
|
|
41
|
+
check(typeof item[optionalString] === 'string', `${path}.${optionalString}`, 'a string')
|
|
42
|
+
}
|
|
43
|
+
if (isLines && item.taxInclusive !== undefined) {
|
|
44
|
+
check(typeof item.taxInclusive === 'boolean', `${path}.taxInclusive`, 'a boolean')
|
|
45
|
+
}
|
|
46
|
+
for (const key of isLines ? ['quantity', 'unitPriceMinor'] : ['amountMinor']) number(item[key], `${path}.${key}`)
|
|
47
|
+
if (!isLines) {
|
|
48
|
+
for (const key of ['tenderedMinor', 'changeMinor']) {
|
|
49
|
+
if (item[key] !== undefined) number(item[key], `${path}.${key}`)
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
for (const field of ['subtotalMinor', 'taxMinor', 'totalMinor']) number(payload[field], field)
|
|
55
|
+
const lineDiscounts = (Array.isArray(payload.lines) ? payload.lines : [])
|
|
56
|
+
.reduce((sum: bigint, line, index) => sum + (object(line) ? discount(line.discountMinor, `lines[${index}].discountMinor`) : 0n), 0n)
|
|
57
|
+
const orderDiscount = discount(payload.discountMinor, 'discountMinor')
|
|
58
|
+
if (errors.length === 0) check(orderDiscount === lineDiscounts, 'discountMinor', 'the sum of lines[].discountMinor')
|
|
59
|
+
if (payload.customer !== undefined && payload.customer !== null) {
|
|
60
|
+
check(object(payload.customer), 'customer', 'an object')
|
|
61
|
+
if (object(payload.customer) && payload.customer.email !== undefined) {
|
|
62
|
+
check(typeof payload.customer.email === 'string', 'customer.email', 'a string')
|
|
63
|
+
}
|
|
64
|
+
if (object(payload.customer) && payload.customer.customerId !== undefined) {
|
|
65
|
+
const id = payload.customer.customerId
|
|
66
|
+
check(typeof id === 'string' && id.length > 0 && id.length <= 64, 'customer.customerId', 'a string of at most 64 characters')
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
if (payload.sessionId !== undefined) {
|
|
70
|
+
check(typeof payload.sessionId === 'string' && payload.sessionId.length > 0 && payload.sessionId.length <= 36,
|
|
71
|
+
'sessionId', 'a string of at most 36 characters')
|
|
72
|
+
}
|
|
73
|
+
for (const field of ['registerId', 'cashierRef', 'locationId']) {
|
|
74
|
+
if (payload[field] !== undefined) check(typeof payload[field] === 'string', field, 'a string')
|
|
75
|
+
}
|
|
76
|
+
// NUL, only on strings (the checks above name any other type): Postgres text can't hold it, and the lookup keys must be clean.
|
|
77
|
+
for (const [value, path] of payloadStrings(payload)) check(!value.includes('\u0000'), path, 'no NUL character')
|
|
78
|
+
return errors
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Length-bound errors of an order.create payload, e.g. ['lines[0].title: expected at most 255
|
|
82
|
+
* characters']; [] when every string is within its bound, at most ten. Bounds in UTF-16 code units:
|
|
83
|
+
* `customer.email` 254, every other string 255 (`customerId` and `sessionId` keep theirs in
|
|
84
|
+
* payloadShapeErrors); only strings are checked. A plugin calls it through precheckCommand, after
|
|
85
|
+
* its replay lookup, so a bound tightened later never turns an applied command's resend into
|
|
86
|
+
* `invalid_payload`. */
|
|
87
|
+
export function payloadBoundErrors(payload: unknown): string[] {
|
|
88
|
+
if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) return []
|
|
89
|
+
return payloadStrings(payload as Record<string, unknown>)
|
|
90
|
+
.filter(([value, , max]) => max !== undefined && value.length > max)
|
|
91
|
+
.map(([, path, max]) => `${path}: expected at most ${max} characters`).slice(0, 10)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Every string field order.create's checks cover, as [value, path, bound]; no bound for `customerId`
|
|
95
|
+
* and `sessionId`, whose bounds payloadShapeErrors checks with their own messages. */
|
|
96
|
+
function payloadStrings(payload: Record<string, unknown>): Array<[string, string, number | undefined]> {
|
|
97
|
+
const found: Array<[unknown, string, number | undefined]> = []
|
|
98
|
+
const object = (value: unknown): value is Record<string, unknown> =>
|
|
99
|
+
typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
100
|
+
for (const field of ['clientOrderId', 'createdAt', 'currency', 'registerId', 'cashierRef', 'locationId']) found.push([payload[field], field, 255])
|
|
101
|
+
for (const field of ['lines', 'payments']) {
|
|
102
|
+
const items = payload[field]
|
|
103
|
+
if (Array.isArray(items)) items.forEach((item, index) => {
|
|
104
|
+
if (object(item)) for (const key of field === 'lines' ? ['clientLineId', 'variantId', 'title'] : ['clientPaymentId', 'method', 'reference']) {
|
|
105
|
+
found.push([item[key], `${field}[${index}].${key}`, 255])
|
|
106
|
+
}
|
|
107
|
+
})
|
|
108
|
+
}
|
|
109
|
+
if (object(payload.customer)) found.push([payload.customer.email, 'customer.email', 254], [payload.customer.customerId, 'customer.customerId', undefined])
|
|
110
|
+
found.push([payload.sessionId, 'sessionId', undefined])
|
|
111
|
+
return found.filter((entry): entry is [string, string, number | undefined] => typeof entry[0] === 'string')
|
|
112
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A session's expected figures per method: the counted float in cash, plus each order's payments, plus paid_in
|
|
3
|
+
* and minus paid_out movements that are not voided. The plugin chooses which orders count (for Medusa: completed,
|
|
4
|
+
* archived and cancelled POS orders, so a received sale stays counted after an admin archives or cancels it) and
|
|
5
|
+
* passes each order's recorded POS payments; this function only sums.
|
|
6
|
+
*/
|
|
7
|
+
export function deriveSessionFigures(input: {
|
|
8
|
+
countedFloatMinor: number
|
|
9
|
+
orders: { payments: { method: string; amountMinor: number }[] }[]
|
|
10
|
+
movements: { id: string; type: 'paid_in' | 'paid_out' | 'no_sale' | 'void'; amountMinor: number; voids: string | null }[]
|
|
11
|
+
}): { expected: Record<string, number>; salesCount: number } {
|
|
12
|
+
const expected: Record<string, number> = Object.assign(Object.create(null), { cash: input.countedFloatMinor })
|
|
13
|
+
// tally_payments is order metadata an admin could edit, and a malformed row must never make register commands transient.
|
|
14
|
+
for (const order of input.orders) {
|
|
15
|
+
if (!Array.isArray(order.payments)) continue
|
|
16
|
+
for (const payment of order.payments) {
|
|
17
|
+
if (typeof payment?.method !== 'string' || !payment.method.length || !Number.isSafeInteger(payment.amountMinor)) continue
|
|
18
|
+
expected[payment.method] = (expected[payment.method] ?? 0) + payment.amountMinor
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
const voided = new Set(input.movements.filter(row => row.type === 'void').map(row => row.voids))
|
|
22
|
+
for (const row of input.movements) {
|
|
23
|
+
if (row.type === 'void' || voided.has(row.id)) continue
|
|
24
|
+
if (row.type === 'paid_in') expected.cash += row.amountMinor
|
|
25
|
+
if (row.type === 'paid_out') expected.cash -= row.amountMinor
|
|
26
|
+
}
|
|
27
|
+
return { expected: { ...expected }, salesCount: input.orders.length }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function deriveVariance(counted: Record<string, number>, expected: Record<string, number>): Record<string, number> {
|
|
31
|
+
return Object.fromEntries(Object.entries(counted).map(([key, value]) => [key, value - (expected[key] ?? 0)]))
|
|
32
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { RegisterCommandResult } from '../types'
|
|
2
|
+
|
|
3
|
+
export type RegisterConflictCode =
|
|
4
|
+
| 'register_session_already_open'
|
|
5
|
+
| 'register_session_closed'
|
|
6
|
+
| 'register_closure_exists'
|
|
7
|
+
| 'register_closure_number_invalid'
|
|
8
|
+
|
|
9
|
+
export type RegisterOutcome =
|
|
10
|
+
| { kind: 'ok'; register: RegisterCommandResult }
|
|
11
|
+
| { kind: 'conflict'; code: RegisterConflictCode; data?: Record<string, unknown> }
|
|
12
|
+
| { kind: 'invalid'; message: string }
|