@tallyui/core 0.2.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/LICENSE +21 -0
- package/dist/chunk-C4PWPOKO.js +18 -0
- package/dist/commands-BW4YYgRG.d.ts +306 -0
- package/dist/index.d.ts +636 -8
- package/dist/index.js +468 -4
- package/dist/rxdb/index.d.ts +37 -0
- package/dist/rxdb/index.js +26 -0
- package/dist/server/index.d.ts +213 -0
- package/dist/server/index.js +591 -0
- package/package.json +33 -3
- package/src/commands.ts +32 -0
- package/src/context/connector-context.tsx +78 -4
- package/src/index.ts +53 -0
- package/src/known-warnings.ts +77 -0
- package/src/money.ts +142 -0
- package/src/replication/combine.ts +77 -0
- package/src/replication/reconcile-feed.ts +116 -0
- package/src/rxdb/index.ts +4 -0
- package/src/rxdb/read-fresh.ts +32 -0
- package/src/rxdb/watch-fresh.ts +19 -0
- 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/sign-in.ts +21 -0
- package/src/stock-overlay.ts +35 -0
- package/src/store-settings.ts +29 -0
- package/src/sync-notice.ts +26 -0
- package/src/types/commands.ts +236 -0
- package/src/types/connector.ts +127 -0
- package/src/types/customers.ts +26 -0
- package/src/types/index.ts +23 -1
- package/src/types/money.ts +33 -0
- package/src/types/reconcile.ts +73 -0
- package/src/types/replication.ts +12 -0
- package/src/types/stock.ts +18 -0
- package/src/types/store-settings.ts +27 -0
- package/src/types/traits/product.ts +62 -6
- package/src/unauthorized.ts +13 -0
- package/src/utils/compare-ids.ts +16 -0
- package/src/variants.ts +14 -0
- package/src/__tests__/connector-context.test.tsx +0 -100
- package/src/types/replication.test-d.ts +0 -20
|
@@ -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 }
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/** Shape errors before a register command claims a ledger row. Unknown top-level keys are allowed. */
|
|
2
|
+
export function registerPayloadErrors(type: string, payload: unknown): string[] {
|
|
3
|
+
const errors: string[] = []
|
|
4
|
+
const object = (value: unknown): value is Record<string, unknown> =>
|
|
5
|
+
typeof value === 'object' && value !== null && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)
|
|
6
|
+
const check = (valid: boolean, field: string, expected: string) => {
|
|
7
|
+
if (!valid && errors.length < 10) errors.push(`${field}: expected ${expected}`)
|
|
8
|
+
}
|
|
9
|
+
if (!object(payload)) return ['payload: expected an object']
|
|
10
|
+
const noNul = (value: unknown, field: string) => {
|
|
11
|
+
if (typeof value === 'string') check(!value.includes('\u0000'), field, 'no NUL character')
|
|
12
|
+
}
|
|
13
|
+
const string = (field: string, optional = false) => {
|
|
14
|
+
const value = payload[field]
|
|
15
|
+
if (optional && value === undefined) return
|
|
16
|
+
check(typeof value === 'string' && (optional || value.length > 0), field, optional ? 'a string' : 'a non-empty string')
|
|
17
|
+
if (typeof value === 'string' && (field.endsWith('Id') || field === 'voids')) check(value.length <= 64, field, 'at most 64 characters')
|
|
18
|
+
if (typeof value === 'string' && ['openedAt', 'at', 'createdAt', 'closedAt'].includes(field)) {
|
|
19
|
+
check(!Number.isNaN(Date.parse(value)), field, 'a valid date')
|
|
20
|
+
}
|
|
21
|
+
noNul(value, field)
|
|
22
|
+
}
|
|
23
|
+
const integer = (field: string, min = -Infinity) =>
|
|
24
|
+
check(Number.isSafeInteger(payload[field]) && (payload[field] as number) >= min, field, `a safe integer >= ${min}`)
|
|
25
|
+
const record = (field: string) => {
|
|
26
|
+
const value = payload[field]
|
|
27
|
+
check(object(value), field, 'a record of integers')
|
|
28
|
+
if (object(value)) for (const [key, amount] of Object.entries(value)) {
|
|
29
|
+
check(key.length > 0 && Number.isSafeInteger(amount), `${field}.${key}`, 'a non-empty key with a safe integer')
|
|
30
|
+
noNul(key, `${field}.${JSON.stringify(key)}`) // quoted, so the NUL is never echoed raw
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
string('sessionId')
|
|
34
|
+
switch (type) {
|
|
35
|
+
case 'register.session.open':
|
|
36
|
+
for (const field of ['registerId', 'openedAt']) string(field)
|
|
37
|
+
for (const field of ['storeKey', 'businessDay', 'openedBy']) string(field, true)
|
|
38
|
+
integer('countedFloatMinor', 0)
|
|
39
|
+
for (const field of ['expectedFloatMinor', 'openingVarianceMinor']) if (payload[field] !== undefined) integer(field)
|
|
40
|
+
break
|
|
41
|
+
case 'register.session.transition':
|
|
42
|
+
string('at')
|
|
43
|
+
check(['open', 'counting', 'closed'].includes(payload.status as string), 'status', 'open, counting or closed')
|
|
44
|
+
for (const field of ['counted', 'closedBy', 'approvedBy']) if (payload[field] !== undefined) {
|
|
45
|
+
check(payload.status === 'closed', field, 'a closing transition')
|
|
46
|
+
if (field === 'counted') record(field)
|
|
47
|
+
else string(field, true)
|
|
48
|
+
}
|
|
49
|
+
break
|
|
50
|
+
case 'register.movement.record':
|
|
51
|
+
case 'register.movement.void':
|
|
52
|
+
for (const field of ['movementId', 'createdAt']) string(field)
|
|
53
|
+
string('createdBy', true)
|
|
54
|
+
if (type === 'register.movement.void') string('voids')
|
|
55
|
+
else {
|
|
56
|
+
check(typeof payload.reason === 'string' && payload.reason.trim().length > 0 && payload.reason.length <= 500,
|
|
57
|
+
'reason', 'a non-empty string after trim of at most 500 characters')
|
|
58
|
+
noNul(payload.reason, 'reason')
|
|
59
|
+
check(['paid_in', 'paid_out', 'no_sale'].includes(payload.type as string), 'type', 'paid_in, paid_out or no_sale')
|
|
60
|
+
integer('amountMinor', payload.type === 'no_sale' ? 0 : 1)
|
|
61
|
+
if (payload.type === 'no_sale') check(payload.amountMinor === 0, 'amountMinor', '0 for no_sale')
|
|
62
|
+
}
|
|
63
|
+
break
|
|
64
|
+
case 'register.closure.submit':
|
|
65
|
+
for (const field of ['closureId', 'registerId', 'openedAt', 'closedAt', 'softwareVersion']) string(field)
|
|
66
|
+
for (const field of ['businessDay', 'closedBy', 'approvedBy']) string(field, true)
|
|
67
|
+
integer('number', 1)
|
|
68
|
+
for (const field of ['periodSalesTotalMinor', 'periodRefundsTotalMinor', 'perpetualSalesTotalMinor',
|
|
69
|
+
'perpetualRefundsTotalMinor', 'unsyncedCount', 'unsyncedTotalMinor']) integer(field, 0)
|
|
70
|
+
for (const field of ['number', 'unsyncedCount'])
|
|
71
|
+
check((payload[field] as number) <= 2147483647, field, 'at most 2147483647')
|
|
72
|
+
for (const field of ['tillExpected', 'counted']) record(field)
|
|
73
|
+
for (const field of ['orderIds', 'movementIds']) {
|
|
74
|
+
const value = payload[field]
|
|
75
|
+
check(Array.isArray(value), field, 'an array of ids')
|
|
76
|
+
if (Array.isArray(value)) value.forEach((id, index) => {
|
|
77
|
+
check(typeof id === 'string' && id.length > 0 && id.length <= 64, `${field}[${index}]`, 'a non-empty string of at most 64 characters')
|
|
78
|
+
noNul(id, `${field}[${index}]`)
|
|
79
|
+
})
|
|
80
|
+
}
|
|
81
|
+
break
|
|
82
|
+
default:
|
|
83
|
+
check(false, 'type', 'a register command type')
|
|
84
|
+
}
|
|
85
|
+
return errors
|
|
86
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { CommandResult } from '../types'
|
|
2
|
+
import type { OrderRejectionCode } from './total-warnings'
|
|
3
|
+
import type { RegisterConflictCode } from './register-outcome'
|
|
4
|
+
|
|
5
|
+
/** Every error.code a plugin may put on a rejected result (ADR-038 and its amendments, ADR-068),
|
|
6
|
+
* except `register_approval_required`, which arrives with registers c2c. */
|
|
7
|
+
export type CommandRejectionCode =
|
|
8
|
+
| 'invalid_payload' | 'unsupported_version' | 'idempotency_mismatch' | 'store_configuration' | 'platform_error'
|
|
9
|
+
| 'insufficient_stock' | 'unsupported_tax_mode' | 'internal_error'
|
|
10
|
+
| OrderRejectionCode | RegisterConflictCode
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The rejected result for a platform-native error the plugin has judged permanent (a replay would fail
|
|
14
|
+
* the same way, e.g. a Vendure ErrorResult code) and the contract has no code for. `platform_error` is
|
|
15
|
+
* for `order.create` only, for now: a rejected register command halts that register's queue until c2c,
|
|
16
|
+
* so register refusals use the ADR-068 codes.
|
|
17
|
+
*
|
|
18
|
+
* Return it only when the platform made no durable change for this command: the plugin threw so its
|
|
19
|
+
* transaction rolled back, or it compensated. Otherwise the plugin applies the command (with a warning
|
|
20
|
+
* where one fits), or compensates the partial write and then stays transient (ADR-039). The till offers
|
|
21
|
+
* Retry for `platform_error` and requeue resends under a new command id, and a transient result resends
|
|
22
|
+
* the same id after the ledger claim is released, so either would duplicate a partly written sale.
|
|
23
|
+
*
|
|
24
|
+
* It is stored in the ledger and replayed as recorded; the order shows under "Needs attention" with
|
|
25
|
+
* Retry. An error the plugin can't classify stays transient (503, retried), never platform_error.
|
|
26
|
+
*/
|
|
27
|
+
export function platformErrorResult(id: string, platformCode: string, platformMessage: string): CommandResult {
|
|
28
|
+
return { id, status: 'rejected', error: { code: 'platform_error', message: `${platformCode}: ${platformMessage}`, data: { platformCode, platformMessage } } }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The rejected result for an exception from the plugin's own code (a programming error, not the
|
|
33
|
+
* database, the network, or an unknown SQLSTATE), raised after a complete rollback or a complete
|
|
34
|
+
* compensation, so that nothing of the sale remains, in the database or outside it. "The plugin's own
|
|
35
|
+
* code" excludes an error thrown from inside the platform SDK, the database client or the HTTP client.
|
|
36
|
+
*
|
|
37
|
+
* It is stored in the ledger and replayed as recorded, because it fails the same way on every retry
|
|
38
|
+
* and a retry loop would hide the bug. The message is generic so no internal detail reaches the till;
|
|
39
|
+
* the correlation id links it to the plugin's log.
|
|
40
|
+
*
|
|
41
|
+
* Database, network, unknown-SQLSTATE and any other unclassifiable errors stay transient (503), never
|
|
42
|
+
* `internal_error`. `order.create` only, as for `platform_error`.
|
|
43
|
+
*
|
|
44
|
+
* See ADR-038's `internal_error` amendment (needs-admin on a failed compensation; on Vendure only
|
|
45
|
+
* before the first write).
|
|
46
|
+
*/
|
|
47
|
+
export function internalErrorResult(id: string, correlationId: string): CommandResult {
|
|
48
|
+
return { id, status: 'rejected', error: { code: 'internal_error', message: `Internal error (ref ${correlationId})`, data: { correlationId } } }
|
|
49
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { CommandWarning } from '../types'
|
|
2
|
+
|
|
3
|
+
export type OrderRejectionCode =
|
|
4
|
+
'unknown_variant' | 'invalid_quantity' | 'underpaid' | 'unsupported_currency'
|
|
5
|
+
|
|
6
|
+
export type Rejection = { code: OrderRejectionCode; message: string }
|
|
7
|
+
|
|
8
|
+
export function totalWarnings(expectedMinor: number, serverMinor: number): CommandWarning[] {
|
|
9
|
+
return serverMinor === expectedMinor ? [] : [{ code: 'total_mismatch', expectedMinor, serverMinor }]
|
|
10
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The till's capability: the order.create versions `toOrderCreateEnvelope` can produce. It is not what a server
|
|
3
|
+
* supports (#297). A server passes its own lists to `precheckCommand`, and its /info advertises them, gated by its
|
|
4
|
+
* own check (Front desk, 2026-09-30): 4 (#286) is 3 with every discountMinor tax-exclusive, and a plugin
|
|
5
|
+
* advertises it only once it handles it.
|
|
6
|
+
*/
|
|
7
|
+
export const SUPPORTED_ORDER_CREATE_VERSIONS: readonly number[] = [1, 2, 3, 4]
|
|
8
|
+
/** The till's capability for the contract versions shared by all five register commands; a server passes its own. */
|
|
9
|
+
export const SUPPORTED_REGISTER_VERSIONS: readonly number[] = [1]
|
package/src/sign-in.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Why `ConnectorAuth.signIn` failed:
|
|
3
|
+
* - `failed`: no response arrived (network error, DNS, TLS, refused);
|
|
4
|
+
* - `server_error`: a response arrived but was unusable;
|
|
5
|
+
* - `unsupported`: the backend needs a sign-in flow this connector can't do;
|
|
6
|
+
* - `invalid_credentials`: wrong email or password.
|
|
7
|
+
*/
|
|
8
|
+
export type SignInErrorCode = 'invalid_credentials' | 'unsupported' | 'failed' | 'server_error';
|
|
9
|
+
|
|
10
|
+
/** The rejection from `ConnectorAuth.signIn`; the app picks its message from `code`. */
|
|
11
|
+
export class SignInError extends Error {
|
|
12
|
+
readonly code: SignInErrorCode;
|
|
13
|
+
readonly status?: number;
|
|
14
|
+
|
|
15
|
+
constructor(code: SignInErrorCode, message: string, status?: number) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = 'SignInError';
|
|
18
|
+
this.code = code;
|
|
19
|
+
this.status = status;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { ProductTraits, StockLevel, StockReconcileAdapter } from './types';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Local document id, in the `stock_levels` collection, that holds the time of
|
|
5
|
+
* the last successful reconcile pass (`{ completedAt }`). Lives here so the
|
|
6
|
+
* runner in `@tallyui/database` and the readers in `@tallyui/pos` share it.
|
|
7
|
+
*/
|
|
8
|
+
export const STOCK_LEVELS_LAST_PASS = 'last-pass';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* A read-only view of `doc` with reconciled stock merged in (ADR-060).
|
|
12
|
+
* Returns `doc` itself when there is nothing to merge; never mutates it.
|
|
13
|
+
*/
|
|
14
|
+
export function withStockOverlay<Doc>(
|
|
15
|
+
doc: Doc,
|
|
16
|
+
adapter: StockReconcileAdapter<Doc> | undefined,
|
|
17
|
+
overlay: Map<string, unknown> | undefined,
|
|
18
|
+
): Doc {
|
|
19
|
+
if (!adapter || !overlay) return doc;
|
|
20
|
+
const fields = adapter.overlay(doc, overlay);
|
|
21
|
+
return fields ? { ...doc, ...fields } : doc;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The product's stock, from the overlay where it has an entry for a variant
|
|
26
|
+
* or item, otherwise from the replicated document.
|
|
27
|
+
*/
|
|
28
|
+
export function getProductStock<Doc>(
|
|
29
|
+
doc: Doc,
|
|
30
|
+
traits: ProductTraits<Doc>,
|
|
31
|
+
adapter: StockReconcileAdapter<Doc> | undefined,
|
|
32
|
+
overlay: Map<string, unknown> | undefined,
|
|
33
|
+
): StockLevel {
|
|
34
|
+
return traits.getStock(withStockOverlay(doc, adapter, overlay));
|
|
35
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Why `TallyConnector.storeSettings` failed:
|
|
3
|
+
* - `choice_required`: the store has more than one region, country or
|
|
4
|
+
* channel and none is chosen yet (or the stored choice no longer
|
|
5
|
+
* resolves); `choices` says what the app can offer;
|
|
6
|
+
* - `failed`: the read could not complete (network error, non-OK response,
|
|
7
|
+
* a GraphQL/API error).
|
|
8
|
+
*/
|
|
9
|
+
export type StoreSettingsErrorCode = 'choice_required' | 'failed';
|
|
10
|
+
|
|
11
|
+
/** What the app can offer the user when `StoreSettingsError.code` is `choice_required`. */
|
|
12
|
+
export interface StoreSettingsChoices {
|
|
13
|
+
regions?: Array<{ id: string; name: string }>;
|
|
14
|
+
countries?: string[];
|
|
15
|
+
channels?: Array<{ id: string; name: string }>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** The rejection from `TallyConnector.storeSettings`; the app picks its message from `code`. */
|
|
19
|
+
export class StoreSettingsError extends Error {
|
|
20
|
+
readonly code: StoreSettingsErrorCode;
|
|
21
|
+
readonly choices?: StoreSettingsChoices;
|
|
22
|
+
|
|
23
|
+
constructor(code: StoreSettingsErrorCode, message: string, choices?: StoreSettingsChoices) {
|
|
24
|
+
super(message);
|
|
25
|
+
this.name = 'StoreSettingsError';
|
|
26
|
+
this.code = code;
|
|
27
|
+
this.choices = choices;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A pull that stopped until someone acts; `SyncStatus` owns the words for each `code`.
|
|
3
|
+
* `fixedBy` says who can fix it: the till (sign in again) or the store owner.
|
|
4
|
+
* `software` / `minVersion` / `fix` are copied from the error when it names them.
|
|
5
|
+
*/
|
|
6
|
+
export type SyncNotice = {
|
|
7
|
+
code: string;
|
|
8
|
+
since: number;
|
|
9
|
+
fixedBy: 'till' | 'store';
|
|
10
|
+
software?: string;
|
|
11
|
+
minVersion?: string;
|
|
12
|
+
fix?: string;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/** Who can fix a pull error: the till, the store owner, or nobody (it passes, so it is retried). */
|
|
16
|
+
export type ErrorKind = 'till' | 'store' | 'transient';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* 'till' or 'store' for an error whose class sets `fixedBy` to that value and a
|
|
20
|
+
* string `code`; 'transient' for anything else.
|
|
21
|
+
*/
|
|
22
|
+
export function errorKind(error: unknown): ErrorKind {
|
|
23
|
+
if (typeof error !== 'object' || error === null) return 'transient';
|
|
24
|
+
const { fixedBy, code } = error as { fixedBy?: unknown; code?: unknown };
|
|
25
|
+
return (fixedBy === 'till' || fixedBy === 'store') && typeof code === 'string' ? fixedBy : 'transient';
|
|
26
|
+
}
|