@tallyui/core 3.20.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/chunk-XF3RD6GX.js +515 -0
  2. package/dist/index.d.ts +41 -47
  3. package/dist/index.js +119 -101
  4. package/dist/server/index.cjs +1923 -0
  5. package/dist/server/index.d.cts +1039 -0
  6. package/dist/server/index.d.ts +46 -48
  7. package/dist/server/index.js +516 -206
  8. package/dist/{command-result-E_nH57WD.d.ts → tax-rate-DCJhfJbZ.d.ts} +442 -26
  9. package/package.json +10 -5
  10. package/src/commands.ts +12 -0
  11. package/src/context/money-format-context.tsx +50 -0
  12. package/src/coupons/woocommerce/to-coupon-configs.ts +5 -8
  13. package/src/fnv1a32.ts +14 -0
  14. package/src/index.ts +18 -5
  15. package/src/known-warnings.ts +23 -0
  16. package/src/money.ts +85 -2
  17. package/src/server/batch.ts +63 -27
  18. package/src/server/command-result.ts +28 -1
  19. package/src/server/display-signalling/contract.ts +203 -78
  20. package/src/server/display-signalling/memory-server.ts +71 -23
  21. package/src/server/fiscal-figures.ts +1 -1
  22. package/src/server/index.ts +5 -1
  23. package/src/server/money.ts +4 -1
  24. package/src/server/order-payload-shape.ts +96 -5
  25. package/src/server/refund-payload-shape.ts +5 -11
  26. package/src/server/register-payload-shape.ts +6 -12
  27. package/src/server/rejection-codes.ts +4 -4
  28. package/src/server/reopen-payload-shape.ts +25 -0
  29. package/src/server/shape-errors.ts +17 -0
  30. package/src/server/tax-rate.ts +13 -0
  31. package/src/server/update-payload-shape.ts +51 -0
  32. package/src/server/versions.ts +9 -2
  33. package/src/types/closures.ts +34 -0
  34. package/src/types/commands.ts +93 -8
  35. package/src/types/connector.ts +37 -4
  36. package/src/types/display-signalling.ts +30 -14
  37. package/src/types/index.ts +6 -3
  38. package/src/types/orders.ts +25 -3
  39. package/src/types/payment-methods.ts +17 -0
  40. package/src/types/stock.ts +2 -0
  41. package/src/types/store-settings.ts +7 -0
  42. package/src/types/traits/product.ts +19 -0
  43. package/dist/chunk-27L7XLTT.js +0 -235
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/core",
3
- "version": "3.20.0",
3
+ "version": "4.0.0",
4
4
  "type": "module",
5
5
  "description": "Core interfaces, traits, and context providers for Tally UI",
6
6
  "main": "./dist/index.js",
@@ -20,9 +20,15 @@
20
20
  "default": "./dist/rxdb/index.js"
21
21
  },
22
22
  "./server": {
23
- "types": "./dist/server/index.d.ts",
24
- "import": "./dist/server/index.js",
25
23
  "source": "./src/server/index.ts",
24
+ "import": {
25
+ "types": "./dist/server/index.d.ts",
26
+ "default": "./dist/server/index.js"
27
+ },
28
+ "require": {
29
+ "types": "./dist/server/index.d.cts",
30
+ "default": "./dist/server/index.cjs"
31
+ },
26
32
  "default": "./dist/server/index.js"
27
33
  }
28
34
  },
@@ -60,7 +66,6 @@
60
66
  },
61
67
  "scripts": {
62
68
  "build": "tsup",
63
- "typecheck": "tsc --noEmit",
64
- "test": "echo \"no tests yet\""
69
+ "typecheck": "tsc --noEmit"
65
70
  }
66
71
  }
package/src/commands.ts CHANGED
@@ -10,6 +10,18 @@ export const PROTOCOL_VERSION = 1;
10
10
  export const MAX_COMMANDS_PER_BATCH = 50;
11
11
  /** The longest order.create `note` (version 7, ADR-083), in UTF-16 code units. WCPOS v2's order note has no cap; this bounds the wire. */
12
12
  export const ORDER_NOTE_MAX = 1000;
13
+ /** The most tax ids order.create 12 carries in `customer.taxIds` (ADR-092). */
14
+ export const ORDER_TAX_IDS_MAX = 10;
15
+ /** The longest order.create 12 tax id `type` (the connector's scheme id), in UTF-16 code units (ADR-092). */
16
+ export const ORDER_TAX_ID_TYPE_MAX = 32;
17
+ /** The longest order.create 12 tax id `value`, in UTF-16 code units (ADR-092). */
18
+ export const ORDER_TAX_ID_VALUE_MAX = 64;
19
+ /** The most entries order.create 12 carries in `meta`; a meta value's bound is ORDER_NOTE_MAX (ADR-092). */
20
+ export const ORDER_META_MAX = 50;
21
+ /** The longest order.create 12 meta `key`, in UTF-16 code units (ADR-092). */
22
+ export const ORDER_META_KEY_MAX = 255;
23
+ /** The longest order.create 12 catalogue line `sku`, in UTF-16 code units; WooCommerce's product lookup table holds 100 (ADR-092). */
24
+ export const ORDER_LINE_SKU_MAX = 100;
13
25
 
14
26
  /**
15
27
  * True if `value` has the shape of a CommandBatchResponse: an object with a
@@ -0,0 +1,50 @@
1
+ import { createContext, useCallback, useContext, useMemo, type ReactNode } from 'react';
2
+ import { currencySymbol, formatMoney, type MoneyFormat } from '../money';
3
+ import type { Money } from '../types/money';
4
+
5
+ interface MoneyFormatContextValue { locale?: string; format?: MoneyFormat }
6
+
7
+ const MoneyFormatContext = createContext<MoneyFormatContextValue>({});
8
+
9
+ export interface MoneyFormatProviderProps {
10
+ /** The store's locale for Intl; a component's own `locale` prop wins over it. */
11
+ locale?: string;
12
+ /** The store's money format (position, separators, decimals, symbol). */
13
+ format?: MoneyFormat;
14
+ children: ReactNode;
15
+ }
16
+
17
+ /** Hands a store's locale and money format to every `useFormatMoney` / `useCurrencySymbol` below it. */
18
+ export function MoneyFormatProvider({ locale, format, children }: MoneyFormatProviderProps) {
19
+ const value = useMemo(() => ({ locale, format }), [locale, format]);
20
+ return <MoneyFormatContext.Provider value={value}>{children}</MoneyFormatContext.Provider>;
21
+ }
22
+
23
+ /** The nearest provider's store money format; `undefined` outside a provider or when it has none. */
24
+ export function useMoneyFormat(): MoneyFormat | undefined {
25
+ return useContext(MoneyFormatContext).format;
26
+ }
27
+
28
+ /**
29
+ * `formatMoney` with the nearest provider's locale and store format. An explicit `locale` wins over the provider's.
30
+ * Outside a provider it is exactly `formatMoney(money, locale)`.
31
+ */
32
+ export function useFormatMoney(): (money: Money, locale?: string) => string | undefined {
33
+ const { locale: storeLocale, format } = useContext(MoneyFormatContext);
34
+ return useCallback(
35
+ (money: Money, locale?: string) => formatMoney(money, locale ?? storeLocale, format),
36
+ [storeLocale, format],
37
+ );
38
+ }
39
+
40
+ /**
41
+ * The symbol to show beside a money input: the store format's `symbol` when set, else `currencySymbol(currency, locale)`.
42
+ * Outside a provider it is exactly `currencySymbol(currency, locale)`.
43
+ */
44
+ export function useCurrencySymbol(): (currency: string, locale?: string) => string {
45
+ const { locale: storeLocale, format } = useContext(MoneyFormatContext);
46
+ return useCallback(
47
+ (currency: string, locale?: string) => format?.symbol ?? currencySymbol(currency, locale ?? storeLocale),
48
+ [storeLocale, format],
49
+ );
50
+ }
@@ -7,15 +7,12 @@ import type { CouponInput } from './types';
7
7
  * Map `CouponInput`s (the adapter-prefetched coupon documents) to the replay's
8
8
  * `CouponDiscountConfig` shape, keyed by the given (lowercase) codes.
9
9
  *
10
- * Extracted from `settleCart` so a differential harness can replay the composition
11
- * with the EXACT mapping settle uses — the defaults here (`amount || '0'`, `?? null`,
12
- * `?? false`, array copies) must never be duplicated. The original caller,
13
- * `settle.oracle.test.ts`, is retired; `settle-cart-differential.test.ts` in
14
- * packages/core is the harness that relies on this now (via its own
15
- * `toLegacyCouponConfigs`, which must stay in step with this function).
10
+ * The defaults (`amount || '0'`, `?? null`, `?? false`, array copies) live only
11
+ * here and must not be duplicated by callers. The sale's discount-code step
12
+ * (`@tallyui/pos` `sale/woocommerce/discount-codes.ts`) passes the accepted
13
+ * coupons' own codes.
16
14
  *
17
- * Codes absent from the map are skipped; `settleCart`'s missing_coupon gate
18
- * guarantees presence before this runs, and `recalculateCoupons` zeroes the
15
+ * Codes absent from the map are skipped; `recalculateCoupons` zeroes the
19
16
  * discount for any coupon line without a config.
20
17
  */
21
18
  export function toCouponConfigs(
package/src/fnv1a32.ts ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * 32-bit FNV-1a over the string's UTF-16 code units (charCodeAt), as lowercase hex.
3
+ * Platform apps derive persisted database names from it, so the output format is part of the contract:
4
+ * `pad: true` left-pads to 8 hex digits, `pad: false` keeps the shortest form. An app keeps the form it already stores.
5
+ */
6
+ export function fnv1a32(text: string, options: { pad: boolean }): string {
7
+ let hash = 0x811c9dc5;
8
+ for (let i = 0; i < text.length; i++) {
9
+ hash ^= text.charCodeAt(i);
10
+ hash = Math.imul(hash, 16777619);
11
+ }
12
+ const hex = (hash >>> 0).toString(16);
13
+ return options.pad ? hex.padStart(8, '0') : hex;
14
+ }
package/src/index.ts CHANGED
@@ -17,6 +17,7 @@ export type {
17
17
  VariantSummary,
18
18
  VariantOptionGroup,
19
19
  ProductCategory,
20
+ ProductTerm,
20
21
  CustomerTraits,
21
22
  Money,
22
23
  ProductPrice,
@@ -32,7 +33,7 @@ export type {
32
33
  export type { SignInResult, ServerCapabilities, TaxRounding } from './types/connector';
33
34
  export type {
34
35
  DisplaySignalling, DisplaySignallingContext, DisplaySignallingErrorCode, DisplayAdvertisement, IceServer,
35
- PendingPairing, DisplayRecord, SignalMessage,
36
+ PendingPairing, DisplayRecord, SignalMessage, TillDevice,
36
37
  } from './types';
37
38
  export { DisplaySignallingError, DISPLAY_PAIR_CAPABILITY } from './types/display-signalling';
38
39
  export { DEFAULT_ICE_SERVERS, parseDisplayAdvertisement, rateLimitSource } from './customer-display';
@@ -46,7 +47,7 @@ export { classifyFailure, neutralFailureClass, noResponse, type ConnectivityStat
46
47
  export type { SignInErrorCode } from './sign-in';
47
48
  export { StoreSettingsError } from './store-settings';
48
49
  export { customerTraits, CustomerServiceError, type Customer, type CustomerInput, type CustomerAddress, type CustomerTaxId, type CustomerPatch, type CustomerPage } from './types/customers';
49
- export { paymentMethodOf, defaultPaymentMethods } from './types/payment-methods';
50
+ export { paymentMethodOf, defaultPaymentMethods, wireMethodOf, legMethodId } from './types/payment-methods';
50
51
  export type {
51
52
  PaymentMethodDescriptor, PaymentKind, CaptureMode, CaptureModeEntry, PaymentHardware, PaymentTransport,
52
53
  PaymentOfflineMode, PaymentTipsMode, PaymentRounding,
@@ -57,6 +58,7 @@ export type {
57
58
  } from './types/orders';
58
59
  export { ORDER_FILTER_FIELDS, UnsupportedOrderFilterError, orderFilterFields, assertOrderFiltersSupported, assertOrderDateRange } from './order-filters';
59
60
  export type { RegisterInfo } from './types/registers';
61
+ export type { ApproverCredentials, Correction, StoreClosure, ClosureReads } from './types/closures';
60
62
  export { CASHIER_PERMISSIONS, cashierPermissions, isCashierPermission, type Cashier, type CashierPermission } from './types/cashier';
61
63
  export type { StoreSettingsErrorCode, StoreSettingsChoices } from './store-settings';
62
64
 
@@ -65,7 +67,10 @@ export type {
65
67
  RegisterCommandType, RegisterCommandEnvelope, AnyCommandEnvelope,
66
68
  OrderRefundLine, OrderRefundPayload, OrderRefundEnvelope, OrderRefundResult, OrderRefundRejectionCode,
67
69
  OrderRefundQuantityExceedsData, OrderRefundAmountMismatchData, OrderRefundOrderStateData, OrderRefundNoOpenSessionData,
68
- CommandWarning, CommandError, CommandResult, OrderCreateLine,
70
+ OrderReopenPayload, OrderReopenEnvelope, OrderReopenResult, OrderReopenRejectionCode,
71
+ OrderReopenPaymentInMotionData, OrderReopenOrderStateData,
72
+ OrderUpdateLine, OrderUpdateFee, OrderUpdateShipping, OrderUpdatePayment, OrderUpdatePayload, OrderUpdateEnvelope, OrderUpdateRejectionCode, OrderUpdateReopenRequiredData,
73
+ CommandWarning, CommandError, CommandResult, OrderCreateLine, OrderCreateTaxId, OrderCreateMeta,
69
74
  PaymentMethodKind, OrderCreatePayment, OrderCreatePayload, OrderCreateEnvelope,
70
75
  OrderCreateDisplay, OrderCreateTaxRate,
71
76
  OrderCreateCoupon, OrderCreateCouponInvalidData, OrderCreateTotalMismatchData,
@@ -75,18 +80,21 @@ export type {
75
80
  RegisterSessionTransitionPayload,
76
81
  RegisterMovementRecordPayload, RegisterMovementVoidPayload, RegisterClosureSubmitPayload,
77
82
  } from './types';
78
- export type { OrderAddress } from './types/commands';
83
+ export type { OrderAddress, OrderCreateCouponLine } from './types/commands';
79
84
 
80
85
  export {
81
86
  COMMANDS_PATH, PROTOCOL_HEADER, PROTOCOL_VERSION, MAX_COMMANDS_PER_BATCH, ORDER_NOTE_MAX,
87
+ ORDER_TAX_IDS_MAX, ORDER_TAX_ID_TYPE_MAX, ORDER_TAX_ID_VALUE_MAX, ORDER_META_MAX, ORDER_META_KEY_MAX, ORDER_LINE_SKU_MAX,
82
88
  isCommandBatchResponse,
83
89
  } from './commands';
84
90
 
85
91
  // Money helpers
86
- export { currencySymbol, formatMoney, minorUnitDigits, moneyFromDecimalString, moneyFromMajor, moneyToMajor, resolvePrice, resolvePriceRange } from './money';
92
+ export { currencySymbol, formatMoney, type MoneyFormat, minorUnitDigits, moneyFromDecimalString, moneyFromMajor, moneyToMajor, normalizeMoneyText, resolvePrice, resolvePriceRange } from './money';
93
+ export { minorToMajor } from './server/money';
87
94
  export { findVariantByCode } from './variants';
88
95
  export { knownWarnings } from './known-warnings';
89
96
  export { compareIds } from './utils/compare-ids';
97
+ export { fnv1a32 } from './fnv1a32';
90
98
  export { STOCK_LEVELS_LAST_PASS, withStockOverlay, getProductStock } from './stock-overlay';
91
99
  export { combinePullAdapters } from './replication/combine';
92
100
  export { createReconcileFeed } from './replication/reconcile-feed';
@@ -104,9 +112,14 @@ export {
104
112
  useStockOverlayAsOf,
105
113
  } from './context/connector-context';
106
114
  export type { ConnectorProviderProps } from './context/connector-context';
115
+ export { MoneyFormatProvider, useCurrencySymbol, useFormatMoney, useMoneyFormat, type MoneyFormatProviderProps } from './context/money-format-context';
107
116
  export * as woocommerceTax from './tax/woocommerce';
108
117
  export * as woocommerceCoupons from './coupons/woocommerce';
109
118
 
110
119
  // Browser-safe: command-result.ts imports only types. @tallyui/core/server re-exports these too, but
111
120
  // its barrel reaches node:crypto (fingerprint.ts), so browser packages import them from here.
112
121
  export { parseCommandResult, CommandResultError } from './server/command-result';
122
+ // Browser-safe: register-figures.ts has no imports. The till and demo backends derive the same session figures.
123
+ export { deriveSessionFigures, deriveVariance } from './server/register-figures';
124
+ // Browser-safe: tax-rate.ts has no imports. The till and servers convert percentages to the same integer ppm.
125
+ export { ratePpmFromPercent } from './server/tax-rate';
@@ -19,6 +19,22 @@ function figuresMismatchFields(fields: unknown): FiguresMismatchField[] | null {
19
19
  return rebuilt;
20
20
  }
21
21
 
22
+ type LineFiguresMismatchLine = Extract<CommandWarning, { code: 'line_figures_mismatch' }>['lines'][number];
23
+
24
+ function lineFiguresMismatchLines(lines: unknown): LineFiguresMismatchLine[] | null {
25
+ if (!Array.isArray(lines) || lines.length === 0) return null;
26
+ const rebuilt: LineFiguresMismatchLine[] = [];
27
+ for (const entry of lines) {
28
+ if (typeof entry !== 'object' || entry === null) return null;
29
+ const { lineId, field, tillMinor, serverMinor } = entry as Record<string, unknown>;
30
+ if (typeof lineId !== 'string' || lineId === '' || lineId.length > 64) return null;
31
+ if (typeof field !== 'string' || field === '' || rebuilt.some((kept) => kept.lineId === lineId && kept.field === field)) return null;
32
+ if (!isSafeInt(tillMinor) || !isSafeInt(serverMinor) || tillMinor === serverMinor) return null;
33
+ rebuilt.push({ lineId, field, tillMinor, serverMinor });
34
+ }
35
+ return rebuilt;
36
+ }
37
+
22
38
  /**
23
39
  * The till's single reader of stored warnings. `[]` for anything that isn't a warnings array.
24
40
  * A `total_mismatch`'s `bridgeMinor` is dropped (the rest of the warning is kept) when it's
@@ -29,6 +45,8 @@ function figuresMismatchFields(fields: unknown): FiguresMismatchField[] | null {
29
45
  * A `figures_mismatch` is dropped entirely unless `fields` is non-empty and each entry names a
30
46
  * different figure with two differing safe integers; each entry is rebuilt from its known keys.
31
47
  * A figure name it doesn't know (any non-empty string) is kept, since a newer store may send one.
48
+ * A `line_figures_mismatch` is dropped entirely unless `lines` is non-empty and each entry has a `lineId` of 1 to 64
49
+ * characters, a non-empty `field` (kept when unknown), two differing safe integers, and a `lineId` and `field` pair of its own.
32
50
  */
33
51
  export function knownWarnings(warnings: unknown): CommandWarning[] {
34
52
  if (!Array.isArray(warnings)) return [];
@@ -76,6 +94,11 @@ export function knownWarnings(warnings: unknown): CommandWarning[] {
76
94
  if (fields !== null) kept.push({ code: 'figures_mismatch', fields });
77
95
  break;
78
96
  }
97
+ case 'line_figures_mismatch': {
98
+ const lines = lineFiguresMismatchLines(warning.lines);
99
+ if (lines !== null) kept.push({ code: 'line_figures_mismatch', lines });
100
+ break;
101
+ }
79
102
  default:
80
103
  continue;
81
104
  }
package/src/money.ts CHANGED
@@ -67,18 +67,32 @@ export function moneyFromDecimalString(text: string, currency: string): Money |
67
67
  return Number.isSafeInteger(amount) ? { amount, currency: code } : undefined;
68
68
  }
69
69
 
70
- /** Converts Money back to a major-unit number, e.g. for Intl formatting. */
70
+ /**
71
+ * Converts Money back to a major-unit number, e.g. for Intl formatting.
72
+ * @deprecated Use `minorToMajor(money.amount, minorUnitDigits(money.currency))`, which returns an exact decimal string instead of a float.
73
+ */
71
74
  export function moneyToMajor(money: Money): number {
72
75
  return money.amount / 10 ** minorUnitDigits(money.currency);
73
76
  }
74
77
 
75
78
  const formatters = new Map<string, Intl.NumberFormat>();
76
79
 
80
+ /** A store's own money format (WCPOS v2 General settings); a field left out keeps the locale's. */
81
+ export interface MoneyFormat {
82
+ position?: 'left' | 'right' | 'left_space' | 'right_space';
83
+ thousandSeparator?: string;
84
+ decimalSeparator?: string;
85
+ decimals?: number;
86
+ /** The store's currency symbol as plain text (e.g. WooCommerce's `currency_symbol` with HTML entities decoded); Intl's symbol for the currency and locale when unset. */
87
+ symbol?: string;
88
+ }
89
+
77
90
  /**
78
91
  * Formats Money for display with Intl, e.g. '€12.50' or '¥1,200'.
79
92
  * Returns undefined for 'XXX' (currency unknown), so callers can fall back.
80
93
  */
81
- export function formatMoney(money: Money, locale?: string): string | undefined {
94
+ export function formatMoney(money: Money, locale?: string, format?: MoneyFormat): string | undefined {
95
+ if (format !== undefined) return formatMoneyWith(money, format, locale);
82
96
  if (money.currency === 'XXX') return undefined;
83
97
  const key = `${money.currency}:${locale ?? ''}`;
84
98
  let formatter = formatters.get(key);
@@ -93,6 +107,75 @@ export function formatMoney(money: Money, locale?: string): string | undefined {
93
107
  return formatter.format(moneyToMajor(money));
94
108
  }
95
109
 
110
+ const POSITIONS: ReadonlyArray<string> = ['left', 'right', 'left_space', 'right_space'];
111
+
112
+ /**
113
+ * Money in a store's format, ported from WCPOS v2 (MIT): the position map of
114
+ * `packages/core/src/screens/main/hooks/use-currency-format.tsx` and the separators and places of
115
+ * `use-number-format.ts`. As there, the places are always shown, digits are Latin, and a minus leads the symbol.
116
+ * With a thousand separator the integer is grouped every three digits; without one, Intl groups it for the locale.
117
+ * Departures from v2: the symbol falls back to Intl's when the format has none; a position outside the four values
118
+ * means Intl's side and gap (v2 shows no symbol); fewer places round halves away from zero (v2 rounds them toward
119
+ * +infinity, so -12.50 at 0 places reads -13 here, -12 there); v2's lakh/wan grouping styles are not supported.
120
+ * Returns undefined for 'XXX' or a code Intl refuses, so callers can fall back.
121
+ */
122
+ function formatMoneyWith(money: Money, format: MoneyFormat, locale?: string): string | undefined {
123
+ if (money.currency === 'XXX') return undefined;
124
+ const minor = minorUnitDigits(money.currency);
125
+ const decimals = format.decimals ?? minor;
126
+ const abs = Math.abs(money.amount);
127
+ // Fewer places round whole minor units half away from zero, so -12.50 and 12.50 read alike.
128
+ const major = decimals >= minor ? abs / 10 ** minor : Math.round(abs / 10 ** (minor - decimals)) / 10 ** decimals;
129
+ let parts: Intl.NumberFormatPart[];
130
+ try {
131
+ parts = new Intl.NumberFormat(locale, {
132
+ style: 'currency', currency: money.currency, minimumFractionDigits: decimals, maximumFractionDigits: decimals,
133
+ numberingSystem: 'latn',
134
+ }).formatToParts(major);
135
+ } catch {
136
+ return undefined;
137
+ }
138
+ const text = (...types: string[]) => parts.filter((p) => types.includes(p.type)).map((p) => p.value).join('');
139
+ const { thousandSeparator, decimalSeparator } = format;
140
+ const position = format.position !== undefined && POSITIONS.includes(format.position) ? format.position : undefined;
141
+ const integer = thousandSeparator === undefined
142
+ ? text('integer', 'group')
143
+ : text('integer').replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator);
144
+ const number = integer + (decimals > 0 ? (decimalSeparator ?? text('decimal')) + text('fraction') : '');
145
+ const symbol = format.symbol ?? text('currency');
146
+ const left = position
147
+ ? position.startsWith('left')
148
+ : parts.findIndex((p) => p.type === 'currency') < parts.findIndex((p) => p.type === 'integer');
149
+ const gap = position ? (position.endsWith('_space') ? ' ' : '') : text('literal');
150
+ return (money.amount < 0 && major > 0 ? '-' : '') + (left ? symbol + gap + number : number + gap + symbol);
151
+ }
152
+
153
+ /**
154
+ * A typed amount in the store's separators as plain decimal text ('1.234,50' → '1234.50'); ported from WCPOS v2 typed-field.tsx parseNumber.
155
+ * Without a format the text is untouched; it never rounds, so too many places stay the caller's refusal (#672).
156
+ */
157
+ export function normalizeMoneyText(text: string, format?: MoneyFormat): string {
158
+ if (format === undefined || (!format.decimalSeparator && !format.thousandSeparator)) return text;
159
+ const decimal = format.decimalSeparator || '.';
160
+ const thousands = format.thousandSeparator === decimal ? '' : format.thousandSeparator || '';
161
+ const trimmed = text.trim();
162
+ // An ambiguous amount is refused, never guessed up: the text comes back unchanged for the caller to refuse.
163
+ if (['.', ','].some((sep) => sep !== decimal && sep !== thousands && trimmed.includes(sep))) return text;
164
+ const [whole = '', fraction, ...more] = trimmed.split(decimal);
165
+ if (more.length > 0 || (fraction !== undefined && /\D/.test(fraction))) return text;
166
+ let integer = whole;
167
+ if (thousands && whole.includes(thousands)) {
168
+ const groups = whole.split(thousands);
169
+ if (/^-?[1-9]\d{0,2}$/.test(groups[0] ?? '') && groups.slice(1).every((g) => /^\d{3}$/.test(g))) integer = groups.join('');
170
+ // A lone '.' or ',' separator not followed by exactly 3 digits cannot be grouping, so it is the decimal point ('1,5').
171
+ else if (fraction === undefined && groups.length === 2 && (thousands === '.' || thousands === ',') && !/^\d{3}$/.test(groups[1] ?? '')) integer = groups.join('.');
172
+ else return text;
173
+ }
174
+ const t = fraction === undefined ? integer : `${integer}.${fraction}`;
175
+ if (!/^-?(\d+(?:\.\d*)?|\.\d+)$/.test(t)) return text;
176
+ return t.replace(/^(-?)\./, (_, sign: string) => `${sign}0.`).replace(/\.$/, '');
177
+ }
178
+
96
179
  /**
97
180
  * Picks the price to charge from a price list, in `currency` if given, else in
98
181
  * the first currency listed. A sale entry wins over the base entry.
@@ -1,7 +1,8 @@
1
1
  import { MAX_COMMANDS_PER_BATCH } from '../commands'
2
2
  import type { AnyCommandEnvelope, BatchTooLargeBody, CommandEnvelope, CommandResult, OrderCreatePayload, RegisterCommandEnvelope } from '../types'
3
- import { fiscalFiguresErrors, type OrderCreatePayloadV3 } from './fiscal-figures'
3
+ import { fiscalFiguresErrors } from './fiscal-figures'
4
4
  import { payloadBoundErrors, payloadShapeErrors } from './order-payload-shape'
5
+ import { orderCreatePart, updatePayloadErrors } from './update-payload-shape'
5
6
 
6
7
  /** An envelope validateBatch accepted: every field's shape is checked, and its version is any positive
7
8
  * safe integer (precheckCommand decides which versions this server supports). */
@@ -9,6 +10,8 @@ export type ValidatedCommandEnvelope =
9
10
  | (Omit<CommandEnvelope<Record<string, unknown>>, 'version'> & { type: 'order.create'; version: number })
10
11
  | RegisterCommandEnvelope<Record<string, unknown>>
11
12
  | (Omit<CommandEnvelope<Record<string, unknown>>, 'type' | 'version'> & { type: 'order.refund'; version: number })
13
+ | (Omit<CommandEnvelope<Record<string, unknown>>, 'type' | 'version'> & { type: 'order.reopen'; version: number })
14
+ | (Omit<CommandEnvelope<Record<string, unknown>>, 'type' | 'version'> & { type: 'order.update'; version: number })
12
15
 
13
16
  /** Validates every envelope before any command is claimed. */
14
17
  export function validateBatch(body: unknown):
@@ -31,7 +34,7 @@ export function validateBatch(body: unknown):
31
34
  }
32
35
  let field: string | undefined
33
36
  if (typeof command.id !== 'string' || command.id.length === 0 || command.id.length > 64) field = 'id'
34
- else if (!['order.create', 'order.refund', 'register.session.open', 'register.session.transition', 'register.movement.record',
37
+ else if (!['order.create', 'order.refund', 'order.reopen', 'order.update', 'register.session.open', 'register.session.transition', 'register.movement.record',
35
38
  'register.movement.void', 'register.closure.submit'].includes(command.type)) field = 'type'
36
39
  else if (!Number.isSafeInteger(command.version) || command.version < 1) field = 'version'
37
40
  else if (typeof command.payload !== 'object' || command.payload === null || Array.isArray(command.payload)) field = 'payload'
@@ -43,6 +46,21 @@ export function validateBatch(body: unknown):
43
46
  return { ok: true, commands }
44
47
  }
45
48
 
49
+ // A rejected result; `data` is set only when given, so an invalid_payload error has no data key.
50
+ const rejected = (id: string, code: 'unsupported_version' | 'invalid_payload', message: string, data?: Record<string, number>): CommandResult =>
51
+ ({ id, status: 'rejected', error: data === undefined ? { code, message } : { code, message, data } })
52
+ // A server lists at most ten payload errors in one message.
53
+ const firstTen = (errors: readonly string[]) => errors.slice(0, 10).join('; ')
54
+
55
+ /** The `unsupported_version` result for a command whose version list the server may leave out (absent or empty: it takes none). */
56
+ function unsupportedOptional(envelope: { id: string; type: string; version: number },
57
+ key: 'orderRefund' | 'orderReopen' | 'orderUpdate', versions: readonly number[], noun: string): CommandResult | undefined {
58
+ if (versions.includes(envelope.version)) return undefined
59
+ return rejected(envelope.id, 'unsupported_version',
60
+ `${envelope.type} version ${envelope.version} is not supported; this server ${versions.length ? `supports ${versions.join(', ')}` : `takes no ${noun}`}`,
61
+ { [key]: versions.length ? Math.max(...versions) : 0 })
62
+ }
63
+
46
64
  /**
47
65
  * The rejection a batch returns for this command before any executor runs, or undefined
48
66
  * when the command goes on to the plugin's executor. A plugin's batch handler calls
@@ -53,52 +71,55 @@ export function validateBatch(body: unknown):
53
71
  * claim, in the executor (order.create; register commands follow ADR-068). It pushes any result
54
72
  * one of those steps returns and moves on.
55
73
  *
74
+ * For order.update the shape check is updatePayloadErrors (ADR-090): it adds the update's store ids, and below
75
+ * createVersion 5 precheckCommand does not repeat it.
76
+ *
56
77
  * The replay lookup goes before precheckCommand so an already-applied command always replays
57
78
  * as `duplicate`, even once a later @tallyui/core tightens what precheckCommand accepts.
58
79
  *
59
80
  * `supported` is the SERVER's own list (what its /info advertises), never core's constants, which are the
60
81
  * till's capability (#297). The version check, the `unsupported_version` message and its `data` all use it:
61
- * `precheckCommand(envelope, { orderCreate: [1, 2, 3], register: [1], orderRefund: [1] })` (`orderRefund` is optional).
82
+ * `precheckCommand(envelope, { orderCreate: [1, 2, 3], register: [1], orderRefund: [1], orderReopen: [1], orderUpdate: [1] })` (`orderRefund`, `orderReopen` and `orderUpdate` are optional).
62
83
  */
63
84
  export function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCommandEnvelope, 'id' | 'type' | 'version' | 'payload'>,
64
- supported: { orderCreate: readonly number[]; register: readonly number[]; orderRefund?: readonly number[] }): CommandResult | undefined {
85
+ supported: { orderCreate: readonly number[]; register: readonly number[]; orderRefund?: readonly number[]; orderReopen?: readonly number[]; orderUpdate?: readonly number[] }): CommandResult | undefined {
65
86
  // An empty list would send Math.max() of nothing (-Infinity, null in JSON) as the server's version.
66
87
  for (const key of ['orderCreate', 'register'] as const) {
67
88
  if (!supported[key]?.length) throw new TypeError(`precheckCommand: supported.${key} must list at least one version`)
68
89
  }
69
- if (envelope.type === 'order.refund') {
70
- const versions = supported.orderRefund ?? []
71
- if (!versions.includes(envelope.version)) {
72
- return { id: envelope.id, status: 'rejected', error: { code: 'unsupported_version',
73
- message: `order.refund version ${envelope.version} is not supported; this server ${versions.length ? `supports ${versions.join(', ')}` : 'takes no refunds'}`,
74
- data: { orderRefund: versions.length ? Math.max(...versions) : 0 },
75
- } }
76
- }
77
- return undefined
90
+ if (envelope.type === 'order.refund') return unsupportedOptional(envelope, 'orderRefund', supported.orderRefund ?? [], 'refunds')
91
+ if (envelope.type === 'order.reopen') return unsupportedOptional(envelope, 'orderReopen', supported.orderReopen ?? [], 'reopens')
92
+ if (envelope.type === 'order.update') {
93
+ const refusal = unsupportedOptional(envelope, 'orderUpdate', supported.orderUpdate ?? [], 'updates')
94
+ if (refusal) return refusal
95
+ const payload = envelope.payload as Record<string, unknown>
96
+ const createPayload = orderCreatePart(payload)
97
+ const shape = payloadShapeErrors(createPayload)
98
+ const errors = updatePayloadErrors(payload).filter(error => !shape.includes(error))
99
+ if (errors.length) return rejected(envelope.id, 'invalid_payload', firstTen(errors))
100
+ return precheckCommand({ id: envelope.id, type: 'order.create', version: payload.createVersion as number, payload: createPayload }, supported)
78
101
  }
79
102
  if (envelope.type !== 'order.create') {
80
103
  if (!supported.register.includes(envelope.version)) {
81
- return { id: envelope.id, status: 'rejected', error: { code: 'unsupported_version',
82
- message: `register version ${envelope.version} is not supported; this server supports ${supported.register.join(', ')}`,
83
- data: { register: Math.max(...supported.register) },
84
- } }
104
+ return rejected(envelope.id, 'unsupported_version',
105
+ `register version ${envelope.version} is not supported; this server supports ${supported.register.join(', ')}`,
106
+ { register: Math.max(...supported.register) })
85
107
  }
86
108
  return undefined
87
109
  }
88
110
  const command = envelope as CommandEnvelope<OrderCreatePayload>
89
111
  if (!supported.orderCreate.includes(command.version)) {
90
- return { id: command.id, status: 'rejected', error: { code: 'unsupported_version',
91
- message: `order.create version ${command.version} is not supported; this server supports ${supported.orderCreate.join(', ')}`,
92
- data: { orderCreate: Math.max(...supported.orderCreate) },
93
- } }
112
+ return rejected(command.id, 'unsupported_version',
113
+ `order.create version ${command.version} is not supported; this server supports ${supported.orderCreate.join(', ')}`,
114
+ { orderCreate: Math.max(...supported.orderCreate) })
94
115
  }
95
116
  // ADR-062 sends version 2 exactly when there is a discount, so version 1 can never create adjustments.
96
117
  const { lines, discountMinor } = command.payload as { lines?: unknown; discountMinor?: unknown }
97
118
  const discounted = discountMinor !== undefined
98
119
  || (Array.isArray(lines) && lines.some(line => (line as { discountMinor?: unknown } | null)?.discountMinor !== undefined))
99
- const payload = command.payload as OrderCreatePayloadV3
120
+ const payload = command.payload as OrderCreatePayload
100
121
  const { display, taxByRate, sessionId } = payload
101
- // Versions 4 and 5 carry version 3's fields, with tax-exclusive discountMinor (#286).
122
+ // Version 4 and later carry version 3's fields, with tax-exclusive discountMinor (#286).
102
123
  const v3 = command.version >= 3
103
124
  const v5Fields = ['fees', 'shipping'].filter(field => payload[field as 'fees' | 'shipping'] !== undefined)
104
125
  if (Array.isArray(lines)) lines.forEach((line, index) => {
@@ -112,13 +133,28 @@ export function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCom
112
133
  if (line?.[field] !== undefined) v6Fields.push(`lines[${index}].${field}`)
113
134
  }
114
135
  })
136
+ const coupons = Array.isArray(payload.coupons) ? payload.coupons.filter(coupon => typeof coupon === 'object' && coupon !== null && !Array.isArray(coupon)) : []
137
+ const couponLines = coupons.filter(coupon => coupon.lines !== undefined)
138
+ const couponsWithoutLines = coupons.filter(coupon => coupon.lines === undefined)
139
+ const paymentsWithMethodId = Array.isArray(payload.payments) && payload.payments.some(payment =>
140
+ typeof payment === 'object' && payment !== null && (payment as { methodId?: unknown }).methodId !== undefined)
141
+ // Version 12 (ADR-092): informational fields, named in this order.
142
+ const v12Fields = payload.customer?.taxIds !== undefined ? ['customer.taxIds'] : []
143
+ if (Array.isArray(lines)) lines.forEach((line, index) => { if (line?.sku !== undefined) v12Fields.push(`lines[${index}].sku`) })
144
+ if (payload.meta !== undefined) v12Fields.push('meta')
115
145
  let versionError = command.version < 5 && v5Fields.length ? v5Fields.map(field => `${field} requires version 5`).join('; ')
116
146
  : command.version < 6 && v6Fields.length ? v6Fields.map(field => `${field} requires version 6`).join('; ')
117
147
  : command.version < 7 && payload.note !== undefined ? 'note requires version 7'
118
148
  : command.version < 8 && payload.taxAddress !== undefined ? 'taxAddress requires version 8'
119
149
  : command.version < 8 && (payload.customer?.billing !== undefined || payload.customer?.shipping !== undefined)
120
150
  ? 'customer address requires version 8'
121
- : command.version >= 8 && payload.taxAddress === undefined ? 'version 8 requires taxAddress'
151
+ : command.version < 9 && couponLines.length ? 'coupons[].lines requires version 9'
152
+ : command.version < 10 && paymentsWithMethodId ? 'payments[].methodId requires version 10'
153
+ : command.version < 12 && v12Fields.length ? v12Fields.map(field => `${field} requires version 12`).join('; ')
154
+ : command.version >= 9 && couponsWithoutLines.length ? 'version 9 requires coupons[].lines'
155
+ : command.version === 8 && payload.taxAddress === undefined ? 'version 8 requires taxAddress'
156
+ : command.version >= 9 && command.version < 11 && payload.taxAddress === undefined && (payload.customer?.billing !== undefined || payload.customer?.shipping !== undefined)
157
+ ? 'version 9 customer address requires taxAddress'
122
158
  : command.version === 2 && discountMinor === undefined ? 'version 2 requires discountMinor'
123
159
  : command.version === 1 && discounted ? 'discountMinor requires version 2'
124
160
  : !v3 && (display !== undefined || taxByRate !== undefined) ? 'display and taxByRate require version 3'
@@ -135,17 +171,17 @@ export function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCom
135
171
  if (versionError) break
136
172
  }
137
173
  if (versionError) {
138
- return { id: command.id, status: 'rejected', error: { code: 'invalid_payload', message: versionError } }
174
+ return rejected(command.id, 'invalid_payload', versionError)
139
175
  }
140
176
  const bounds = payloadBoundErrors(payload)
141
177
  if (bounds.length) {
142
- return { id: command.id, status: 'rejected', error: { code: 'invalid_payload', message: bounds.slice(0, 10).join('; ') } }
178
+ return rejected(command.id, 'invalid_payload', firstTen(bounds))
143
179
  }
144
180
  const shape = payloadShapeErrors(payload)
145
181
  const errors = command.version >= 5 && shape.length ? shape
146
182
  : v3 && display !== undefined && taxByRate !== undefined && shape.length === 0 ? fiscalFiguresErrors(payload) : []
147
183
  if (errors.length) {
148
- return { id: command.id, status: 'rejected', error: { code: 'invalid_payload', message: errors.slice(0, 10).join('; ') } }
184
+ return rejected(command.id, 'invalid_payload', firstTen(errors))
149
185
  }
150
186
  return undefined
151
187
  }
@@ -69,7 +69,16 @@ export function parseCommandResult(value: unknown): CommandResult {
69
69
  if (refunds.reduce((sum, entry) => sum + entry.totalMinor, 0) !== refund.totalMinor) throw new CommandResultError('Invalid refund.refunds')
70
70
  result.refund = { totalMinor: refund.totalMinor as number, byMethod, refunds }
71
71
  }
72
- if (result.status === 'applied' && result.serverRefs === undefined && result.register === undefined && result.refund === undefined) {
72
+ if (input.reopen !== undefined) {
73
+ if (!object(input.reopen)) throw new CommandResultError('Invalid reopen')
74
+ const reopen = input.reopen as Record<string, unknown>
75
+ if (typeof reopen.orderId !== 'string' || reopen.orderId.length === 0) throw new CommandResultError('Invalid reopen.orderId')
76
+ if (typeof reopen.status !== 'string' || reopen.status.length === 0) throw new CommandResultError('Invalid reopen.status')
77
+ if (reopen.revision !== undefined && (typeof reopen.revision !== 'string' || reopen.revision.length === 0)) throw new CommandResultError('Invalid reopen.revision')
78
+ result.reopen = { orderId: reopen.orderId, status: reopen.status }
79
+ if (reopen.revision !== undefined) result.reopen.revision = reopen.revision as string
80
+ }
81
+ if (result.status === 'applied' && result.serverRefs === undefined && result.register === undefined && result.refund === undefined && result.reopen === undefined) {
73
82
  throw new CommandResultError('Invalid serverRefs: required for applied')
74
83
  }
75
84
  if (input.warnings !== undefined) {
@@ -143,6 +152,24 @@ export function parseCommandResult(value: unknown): CommandResult {
143
152
  return { field: entry.field as 'subtotalMinor' | 'taxMinor' | 'discountMinor', tillMinor: entry.tillMinor as number, serverMinor: entry.serverMinor as number }
144
153
  }) }
145
154
  }
155
+ if (item.code === 'line_figures_mismatch') {
156
+ if (!Array.isArray(item.lines) || item.lines.length === 0) throw new CommandResultError(`Invalid ${field}.lines`)
157
+ const seen: string[] = []
158
+ return { code: item.code, lines: item.lines.map((value: unknown, i) => {
159
+ const path = `${field}.lines[${i}]`
160
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new CommandResultError(`Invalid ${path}`)
161
+ const entry = value as Record<string, unknown>
162
+ if (typeof entry.lineId !== 'string' || entry.lineId.length === 0 || entry.lineId.length > 64) throw new CommandResultError(`Invalid ${path}.lineId`)
163
+ const key = JSON.stringify([entry.lineId, entry.field])
164
+ if (!['subtotalMinor', 'taxMinor', 'discountMinor', 'totalMinor'].includes(entry.field as string) || seen.includes(key)) {
165
+ throw new CommandResultError(`Invalid ${path}.field`)
166
+ }
167
+ seen.push(key)
168
+ if (!Number.isSafeInteger(entry.tillMinor)) throw new CommandResultError(`Invalid ${path}.tillMinor`)
169
+ if (!Number.isSafeInteger(entry.serverMinor) || entry.serverMinor === entry.tillMinor) throw new CommandResultError(`Invalid ${path}.serverMinor`)
170
+ return { lineId: entry.lineId, field: entry.field as 'subtotalMinor' | 'taxMinor' | 'discountMinor' | 'totalMinor', tillMinor: entry.tillMinor as number, serverMinor: entry.serverMinor as number }
171
+ }) }
172
+ }
146
173
  throw new CommandResultError(`Invalid ${field}.code`)
147
174
  })
148
175
  }