@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.
Files changed (43) hide show
  1. package/dist/chunk-C4PWPOKO.js +18 -0
  2. package/dist/commands-BW4YYgRG.d.ts +306 -0
  3. package/dist/index.d.ts +226 -130
  4. package/dist/index.js +193 -19
  5. package/dist/rxdb/index.d.ts +5 -9
  6. package/dist/server/index.d.ts +213 -0
  7. package/dist/server/index.js +591 -0
  8. package/package.json +8 -2
  9. package/src/commands.ts +1 -1
  10. package/src/context/connector-context.tsx +30 -1
  11. package/src/index.ts +17 -5
  12. package/src/known-warnings.ts +77 -0
  13. package/src/replication/combine.ts +7 -3
  14. package/src/replication/reconcile-feed.ts +57 -20
  15. package/src/rxdb/read-fresh.ts +3 -7
  16. package/src/rxdb/watch-fresh.ts +2 -2
  17. package/src/rxdb-remote-version-mismatch.ts +30 -0
  18. package/src/server/__fixtures__/fingerprint-vectors.json +139 -0
  19. package/src/server/__fixtures__/order-create-v3.json +97 -0
  20. package/src/server/batch-outcome.ts +19 -0
  21. package/src/server/batch.ts +112 -0
  22. package/src/server/command-result.ts +138 -0
  23. package/src/server/fingerprint.ts +18 -0
  24. package/src/server/fiscal-figures.ts +84 -0
  25. package/src/server/index.ts +20 -0
  26. package/src/server/money.ts +34 -0
  27. package/src/server/order-payload-shape.ts +112 -0
  28. package/src/server/register-figures.ts +32 -0
  29. package/src/server/register-outcome.ts +12 -0
  30. package/src/server/register-payload-shape.ts +86 -0
  31. package/src/server/rejection-codes.ts +49 -0
  32. package/src/server/total-warnings.ts +10 -0
  33. package/src/server/versions.ts +9 -0
  34. package/src/sync-notice.ts +26 -0
  35. package/src/types/commands.ts +138 -9
  36. package/src/types/connector.ts +58 -1
  37. package/src/types/customers.ts +26 -0
  38. package/src/types/index.ts +9 -2
  39. package/src/types/reconcile.ts +30 -0
  40. package/src/types/replication.ts +6 -0
  41. package/src/types/store-settings.ts +4 -0
  42. package/src/types/traits/product.ts +7 -0
  43. package/src/unauthorized.ts +13 -0
@@ -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]
@@ -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
+ }
@@ -5,14 +5,27 @@ export type CommandType = 'order.create';
5
5
  export interface CommandEnvelope<P = unknown> {
6
6
  id: string; // UUIDv7, the idempotency key; never reused
7
7
  type: CommandType;
8
- /** 2 only when an `order.create` carries a discount (ADR-062); a discount-free payload stays 1, byte-identical. */
9
- version: 1 | 2;
8
+ /** 3 when the order carries ADR-065's `display` and `taxByRate` (the store accepts 3), else 2 when discounted, else 1;
9
+ * 4 is 3 with every `discountMinor` tax-exclusive, built only when capped at 4 or more (#286). */
10
+ version: 1 | 2 | 3 | 4;
10
11
  payload: P;
11
12
  createdAt: string; // ISO 8601, client clock
12
13
  deviceId: string;
13
14
  attempt: number; // 1-based, informational
14
15
  }
15
16
 
17
+ /** The register commands (ADR-068); each versions on its own, from 1. */
18
+ export type RegisterCommandType = 'register.session.open' | 'register.session.transition'
19
+ | 'register.movement.record' | 'register.movement.void' | 'register.closure.submit';
20
+ /** A register command's envelope: the same fields as CommandEnvelope, with its own type and a numeric version. */
21
+ export type RegisterCommandEnvelope<P = Record<string, unknown>> =
22
+ Omit<CommandEnvelope<P>, 'type' | 'version'> & { type: RegisterCommandType; version: number };
23
+ /** Any command a transport can carry. */
24
+ export type AnyCommandEnvelope = CommandEnvelope<unknown> | RegisterCommandEnvelope<unknown>;
25
+
26
+ /** An order.create envelope: its version is 1 | 2 | 3 | 4 (ADR-062, ADR-065, #286). */
27
+ export type OrderCreateEnvelope = CommandEnvelope<OrderCreatePayload> & { type: 'order.create'; version: 1 | 2 | 3 | 4 };
28
+
16
29
  /** Outcome of processing a command. */
17
30
  export type CommandStatus = 'applied' | 'duplicate' | 'rejected';
18
31
 
@@ -23,15 +36,52 @@ export interface CommandServerRefs {
23
36
  totalMinor: number;
24
37
  }
25
38
 
26
- /** Non-fatal discrepancies reported while processing a command. */
39
+ /**
40
+ * Non-fatal discrepancies reported while processing a command. A server may send codes not
41
+ * listed here (a newer contract); readers go through `knownWarnings`, which drops them, and a
42
+ * warning never rejects a sale.
43
+ */
27
44
  export type CommandWarning =
28
- | { code: 'total_mismatch'; expectedMinor: number; serverMinor: number }
29
- | { code: 'insufficient_stock'; variantId: string; quantity: number };
45
+ | {
46
+ code: 'total_mismatch'; expectedMinor: number; serverMinor: number;
47
+ /**
48
+ * Present if and only if the server added an untaxed rounding surcharge so its total
49
+ * matches the till's; signed, in minor units, `expectedMinor - serverMinor`, where
50
+ * `serverMinor` is the platform's total before the bridge.
51
+ */
52
+ bridgeMinor?: number;
53
+ }
54
+ | { code: 'insufficient_stock'; variantId: string; quantity: number }
55
+ | {
56
+ /**
57
+ * One warning per tax rate whose tax differs by more than the server's rounding tolerance
58
+ * (order.create v3 only); `expectedMinor` is the till's `taxByRate[].taxMinor` for that
59
+ * rate and `serverMinor` the platform's tax for it.
60
+ */
61
+ code: 'tax_rate_mismatch'; ratePpm: number; expectedMinor: number; serverMinor: number;
62
+ }
63
+ /**
64
+ * The sale's `customerId` (1 to 64 characters) was unknown, deleted or in another channel, so
65
+ * the sale was kept as a guest sale rather than held (ADR-070).
66
+ */
67
+ | { code: 'customer_ignored'; customerId: string }
68
+ /**
69
+ * One warning per sale, never a refusal: each of the till's figures that differs from the
70
+ * server's own computation, once, with both values (#257). `total_mismatch` stays separate.
71
+ * `parseCommandResult` refuses a `field` it doesn't know; `knownWarnings` keeps it (a newer
72
+ * store's figure), so the type admits any non-empty string besides the three names.
73
+ */
74
+ | {
75
+ code: 'figures_mismatch';
76
+ fields: Array<{ field: 'subtotalMinor' | 'taxMinor' | 'discountMinor' | (string & {}); tillMinor: number; serverMinor: number }>;
77
+ };
30
78
 
31
79
  /** Error reported when a command is rejected. */
32
80
  export interface CommandError {
33
81
  code: string;
34
82
  message: string;
83
+ /** A refusal's details, e.g. the server's supported version. */
84
+ data?: Record<string, unknown>;
35
85
  }
36
86
 
37
87
  /** Server result for a single command. */
@@ -41,6 +91,42 @@ export interface CommandResult {
41
91
  serverRefs?: CommandServerRefs;
42
92
  warnings?: CommandWarning[];
43
93
  error?: CommandError;
94
+ register?: RegisterCommandResult;
95
+ }
96
+
97
+ /** A register command's server figures (registers c2b applies them). */
98
+ export interface RegisterCommandResult {
99
+ /** The session's server state after this command. `expected` is absent when the server redacts it (blind). */
100
+ session?: { id: string; status: 'open' | 'counting' | 'closed'; expected?: Record<string, number>; salesCount?: number };
101
+ /** The register's counters: a floor for the till's own, never lowered. */
102
+ counters?: { lastClosureNumber: number; perpetualSalesTotalMinor: number; perpetualRefundsTotalMinor: number };
103
+ /** `register.closure.submit` only. */
104
+ closure?: { serverClosureId: string; number: number; expected?: Record<string, number>; variance?: Record<string, number> };
105
+ }
106
+
107
+ export interface RegisterSessionOpenPayload {
108
+ sessionId: string; registerId: string; storeKey?: string; businessDay?: string; openedAt: string; openedBy?: string;
109
+ expectedFloatMinor?: number; countedFloatMinor: number; openingVarianceMinor?: number;
110
+ }
111
+ export interface RegisterSessionTransitionPayload {
112
+ sessionId: string; status: 'open' | 'counting' | 'closed'; at: string;
113
+ /** Closing only. */ counted?: Record<string, number>; closedBy?: string; approvedBy?: string;
114
+ }
115
+ export interface RegisterMovementRecordPayload {
116
+ movementId: string; sessionId: string; type: 'paid_in' | 'paid_out' | 'no_sale'; amountMinor: number; reason: string;
117
+ createdAt: string; createdBy?: string;
118
+ }
119
+ export interface RegisterMovementVoidPayload {
120
+ movementId: string; sessionId: string; voids: string; createdAt: string; createdBy?: string;
121
+ }
122
+ export interface RegisterClosureSubmitPayload {
123
+ closureId: string; sessionId: string; registerId: string; number: number; businessDay?: string;
124
+ openedAt: string; closedAt: string; closedBy?: string; approvedBy?: string;
125
+ tillExpected: Record<string, number>; counted: Record<string, number>;
126
+ periodSalesTotalMinor: number; periodRefundsTotalMinor: number;
127
+ perpetualSalesTotalMinor: number; perpetualRefundsTotalMinor: number;
128
+ unsyncedCount: number; unsyncedTotalMinor: number; softwareVersion: string;
129
+ orderIds: string[]; movementIds: string[];
44
130
  }
45
131
 
46
132
  /** Order line with client identity and price in minor units. */
@@ -60,6 +146,7 @@ export interface OrderCreateLine {
60
146
  * Version 2 (ADR-062): this line's total discount, its own line discounts plus its allocated share of
61
147
  * the order discount, in the line's own tax mode and integer minor units. The line is taxed on
62
148
  * `unitPriceMinor × quantity − discountMinor`. Present only when above 0.
149
+ * Version 4 (#286): tax-exclusive (net) in every mode; an inclusive line's is `net(A) − net(A − D)`.
63
150
  */
64
151
  discountMinor?: number;
65
152
  }
@@ -77,6 +164,32 @@ export interface OrderCreatePayment {
77
164
  reference?: string;
78
165
  }
79
166
 
167
+ /** Version 3 (ADR-065): the receipt's display figures, integer minor units of `currency` at `exponent`. */
168
+ export interface OrderCreateDisplay {
169
+ currency: string;
170
+ exponent: number;
171
+ taxInclusive: boolean;
172
+ subtotalMinor: number;
173
+ discountMinor: number;
174
+ taxMinor: number;
175
+ totalMinor: number;
176
+ orderDiscountMinor: number;
177
+ lines: Array<{
178
+ clientLineId: string;
179
+ amountMinor: number;
180
+ discounts: Array<{ discountId: string; label?: string; amountMinor: number }>;
181
+ }>;
182
+ }
183
+
184
+ /** Version 3 (ADR-065): one tax rate's net, tax and gross, as the receipt's tax summary splits them. */
185
+ export interface OrderCreateTaxRate {
186
+ ratePpm: number;
187
+ code?: string;
188
+ netMinor: number;
189
+ taxMinor: number;
190
+ grossMinor: number;
191
+ }
192
+
80
193
  /** Client order data submitted by an order.create command. */
81
194
  export interface OrderCreatePayload {
82
195
  clientOrderId: string;
@@ -85,23 +198,39 @@ export interface OrderCreatePayload {
85
198
  pricesIncludeTax: boolean;
86
199
  lines: OrderCreateLine[];
87
200
  subtotalMinor: number;
88
- /** Version 2 (ADR-062): the order's total discount, equal to Σ `lines[].discountMinor`. Present only when above 0. */
201
+ /**
202
+ * Version 2 (ADR-062): the order's total discount, equal to Σ `lines[].discountMinor`. Present only when above 0.
203
+ * Version 4 (#286) means every `discountMinor`, this and each line's, is tax-exclusive, so the sum still holds.
204
+ */
89
205
  discountMinor?: number;
90
206
  taxMinor: number;
91
207
  totalMinor: number;
92
208
  payments: OrderCreatePayment[];
93
- customer?: { email?: string } | null;
209
+ /** version 3 only; both or neither. */
210
+ display?: OrderCreateDisplay;
211
+ /** version 3 only; both or neither. */
212
+ taxByRate?: OrderCreateTaxRate[];
213
+ customer?: {
214
+ email?: string;
215
+ /** Version 3 only: the platform's id for the customer picked at the till, a soft reference of at most 64 characters. Absent for a guest sale, or when no customer was picked. */
216
+ customerId?: string;
217
+ } | null;
94
218
  registerId?: string;
95
219
  cashierRef?: string;
96
220
  locationId?: string;
221
+ /** Version 3 only: the register session the sale was taken for, stamped or late (ADR-032). A late sale names the session that refused its stamp; the server tells the two apart by the session's closure `orderIds`. Absent when the sale had no session. */
222
+ sessionId?: string;
97
223
  }
98
224
 
99
225
  /** Batch of commands submitted to the server. */
100
- export interface CommandBatchRequest {
101
- commands: CommandEnvelope[];
226
+ export interface CommandBatchRequest<E extends AnyCommandEnvelope = CommandEnvelope> {
227
+ commands: E[];
102
228
  }
103
229
 
104
230
  /** Results returned by the server for a command batch. */
105
231
  export interface CommandBatchResponse {
106
232
  results: CommandResult[];
107
233
  }
234
+
235
+ /** The `413` body for a batch over the limit (ADR-038; Front desk ruling 18). */
236
+ export type BatchTooLargeBody = { code: 'batch_too_large'; maxCommands: number; message: string };
@@ -3,8 +3,9 @@ import type { RxJsonSchema } from 'rxdb';
3
3
  import type { ProductTraits } from './traits/product';
4
4
  import type { CustomerTraits } from './traits/customer';
5
5
  import type { ReplicationAdapter } from './replication';
6
- import type { FingerprintReconcileAdapter, IdReconcileAdapter, StockReconcileAdapter } from './reconcile';
6
+ import type { CatalogueReconcileAdapter, FingerprintReconcileAdapter, IdReconcileAdapter, StockReconcileAdapter } from './reconcile';
7
7
  import type { StoreSettings, StoreSettingsChoice } from './store-settings';
8
+ import type { Customer, CustomerInput } from './customers';
8
9
 
9
10
  /**
10
11
  * Authentication configuration for a connector.
@@ -38,8 +39,17 @@ export interface SignInResult {
38
39
  /** The highest `order.create` contract version a store's server currently accepts (ADR-062). */
39
40
  export interface ServerCapabilities {
40
41
  orderCreate: number;
42
+ /** The highest `register` contract version; absent or 0 means no register sync. */
43
+ register?: number;
44
+ /** How the store rounds tax (#287). Absent: an older server, per_order + half_away_from_zero. */
45
+ taxRounding?: TaxRounding;
41
46
  }
42
47
 
48
+ /** #287, ADR-071. `custom`: the till computes as when absent; that server never emits `figures_mismatch` for subtotal or tax. */
49
+ export type TaxRounding =
50
+ | { granularity: 'per_order' | 'per_line_items' | 'per_rate_group_items'; mode: 'half_away_from_zero' | 'half_up' }
51
+ | { granularity: 'custom' };
52
+
43
53
  /**
44
54
  * Resolves the capabilities to act on: a definitive fresh read always wins,
45
55
  * even a downgrade to 1; an inconclusive fresh read (`undefined`) keeps the
@@ -55,6 +65,45 @@ export function resolveCapabilities(
55
65
  return fresh ?? stored;
56
66
  }
57
67
 
68
+ const GRANULARITIES = ['per_order', 'per_line_items', 'per_rate_group_items'];
69
+ const MODES = ['half_away_from_zero', 'half_up'];
70
+
71
+ /**
72
+ * Reads the `taxRounding` of `GET /tally/v1/info` (#287): a valid value comes back without
73
+ * extra keys, and `custom` drops any `mode`. Absent gives `undefined`, the default. Core has
74
+ * no logger, so a malformed value gives `undefined` and one reason to `warn` for the caller to log.
75
+ */
76
+ export function parseTaxRounding(value: unknown, warn?: (reason: string) => void): TaxRounding | undefined {
77
+ if (value === undefined) return undefined;
78
+ const { granularity, mode } = (value ?? {}) as { granularity?: unknown; mode?: unknown };
79
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
80
+ if (granularity === 'custom') return { granularity };
81
+ if (GRANULARITIES.includes(granularity as string) && MODES.includes(mode as string)) {
82
+ return { granularity, mode } as TaxRounding;
83
+ }
84
+ }
85
+ warn?.(`ignoring a malformed taxRounding, so the default applies: ${JSON.stringify(value)}`);
86
+ return undefined;
87
+ }
88
+
89
+ const maxVersion = (list: unknown): number | undefined => {
90
+ const valid = Array.isArray(list) ? list.filter((v): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v > 0) : [];
91
+ return valid.length > 0 ? Math.max(...valid) : undefined;
92
+ };
93
+
94
+ /**
95
+ * Reads a 2xx body of `GET /tally/v1/info` (ADR-062): `orderCreate` is the max of
96
+ * `contracts["order.create"]`, or 1 when it's missing or malformed; `register` is the max of
97
+ * `contracts.register` when valid; `taxRounding` is the top-level sibling of `contracts` (#287).
98
+ */
99
+ export function parseInfoCapabilities(body: unknown, warn?: (reason: string) => void): ServerCapabilities {
100
+ const { contracts, taxRounding } = (body ?? {}) as { contracts?: Record<string, unknown> | null; taxRounding?: unknown };
101
+ const register = maxVersion(contracts?.register);
102
+ const rounding = parseTaxRounding(taxRounding, warn);
103
+ return { orderCreate: maxVersion(contracts?.['order.create']) ?? 1,
104
+ ...(register !== undefined ? { register } : {}), ...(rounding ? { taxRounding: rounding } : {}) };
105
+ }
106
+
58
107
  export interface AuthField {
59
108
  key: string;
60
109
  label: string;
@@ -174,6 +223,8 @@ export interface TallyConnector {
174
223
  prices?: FingerprintReconcileAdapter;
175
224
  /** Prices the backend calculates for the sales context (price lists, sale dates), which change without a timestamp bump. */
176
225
  calculatedPrices?: FingerprintReconcileAdapter;
226
+ /** The daily catalogue check (#248): refetches what differs, deletes only with proof. */
227
+ catalogue?: CatalogueReconcileAdapter;
177
228
  };
178
229
 
179
230
  /**
@@ -192,4 +243,10 @@ export interface TallyConnector {
192
243
  * see `resolveCapabilities`.
193
244
  */
194
245
  capabilities?: (context: SyncContext) => Promise<ServerCapabilities | undefined>;
246
+ /** Customer search: online only; `undefined` when the connector has no customer support. */
247
+ searchCustomers?: (context: SyncContext, query: string, options?: { limit?: number }) => Promise<Customer[]>;
248
+ /** Customer creation: online only; `undefined` when the connector has no customer support. */
249
+ createCustomer?: (context: SyncContext, input: CustomerInput) => Promise<Customer>;
250
+ /** Customer lookup: online only; `undefined` when the connector has no customer support. */
251
+ getCustomer?: (context: SyncContext, id: string) => Promise<Customer | null>;
195
252
  }
@@ -0,0 +1,26 @@
1
+ import type { CustomerTraits } from './traits/customer';
2
+
3
+ /** A store customer, as the till shows and picks it (programme item 14). Platform-neutral. */
4
+ export interface Customer {
5
+ /** The platform's id: order.create v3 sends it as `customer.customerId`. */
6
+ id: string;
7
+ /** Display name: first + last, else company, else email, else id. Never empty. */
8
+ name: string;
9
+ firstName?: string; lastName?: string; email?: string; phone?: string; company?: string;
10
+ }
11
+
12
+ /** What the till collects to create a customer. v1 requires an email. */
13
+ export interface CustomerInput { email: string; firstName?: string; lastName?: string; phone?: string; company?: string }
14
+
15
+ export const customerTraits: CustomerTraits<Customer> = {
16
+ getId: (customer) => customer.id,
17
+ getName: (customer) => customer.name,
18
+ getEmail: (customer) => customer.email,
19
+ getPhone: (customer) => customer.phone,
20
+ getAddressSummary: () => undefined,
21
+ };
22
+
23
+ /** A customer call that failed for a reason other than credentials (credentials throw ConnectorUnauthorizedError). */
24
+ export class CustomerServiceError extends Error {
25
+ constructor(readonly code: 'network' | 'server' | 'invalid', message: string) { super(message); this.name = 'CustomerServiceError'; }
26
+ }
@@ -7,6 +7,8 @@ export type {
7
7
  CollectionSync,
8
8
  RemoteIdEntry,
9
9
  SyncContext,
10
+ ServerCapabilities,
11
+ TaxRounding,
10
12
  } from './connector';
11
13
 
12
14
  export type { ReplicationAdapter } from './replication';
@@ -14,6 +16,7 @@ export type { ReplicationAdapter } from './replication';
14
16
  export type { FingerprintReconcileAdapter, IdReconcileAdapter, StockReconcileAdapter } from './reconcile';
15
17
 
16
18
  export type { StoreSettings, StoreSettingsChoice } from './store-settings';
19
+ export { customerTraits, CustomerServiceError, type Customer, type CustomerInput } from './customers';
17
20
 
18
21
  export type { ProductTraits, TraitContext, VariantSummary } from './traits/product';
19
22
 
@@ -25,7 +28,11 @@ export type { CustomerTraits } from './traits/customer';
25
28
 
26
29
  export type {
27
30
  CommandType, CommandEnvelope, CommandStatus, CommandServerRefs,
31
+ RegisterCommandType, RegisterCommandEnvelope, AnyCommandEnvelope,
28
32
  CommandWarning, CommandError, CommandResult, OrderCreateLine,
29
- PaymentMethodKind, OrderCreatePayment, OrderCreatePayload,
30
- CommandBatchRequest, CommandBatchResponse,
33
+ PaymentMethodKind, OrderCreatePayment, OrderCreatePayload, OrderCreateEnvelope,
34
+ OrderCreateDisplay, OrderCreateTaxRate,
35
+ CommandBatchRequest, CommandBatchResponse, BatchTooLargeBody,
36
+ RegisterCommandResult, RegisterSessionOpenPayload, RegisterSessionTransitionPayload,
37
+ RegisterMovementRecordPayload, RegisterMovementVoidPayload, RegisterClosureSubmitPayload,
31
38
  } from './commands';
@@ -26,6 +26,8 @@ export interface IdReconcileAdapter<Doc = any> {
26
26
  variantIds(doc: Doc): string[];
27
27
  /** Hand local documents that disagree with the backend to the collection's pull (see createReconcileFeed). */
28
28
  enqueue(entries: Array<{ id: string; local: Doc }>): void;
29
+ /** Ids per `fetchByIds` request; see `CatalogueReconcileAdapter.refetchBatchSize`. */
30
+ refetchBatchSize?: number;
29
31
  }
30
32
 
31
33
  /** Re-delivers products whose remote fingerprint differs from the local one (ADR-060). */
@@ -40,4 +42,32 @@ export interface FingerprintReconcileAdapter<Doc = any> {
40
42
  * id reconcile, with its mass-delete brake, may delete.
41
43
  */
42
44
  enqueue(entries: Array<{ id: string; local: Doc; refreshOnly?: boolean }>): void;
45
+ /** Ids per `fetchByIds` request; see `CatalogueReconcileAdapter.refetchBatchSize`. */
46
+ refetchBatchSize?: number;
47
+ }
48
+
49
+ /** One product in the catalogue listing. `key` is the local primary key value; `remote` is whatever the connector needs to refetch it (a numeric backend id, say). */
50
+ export interface CatalogueReconcileEntry { key: string; fingerprint: string; remote?: unknown }
51
+
52
+ /**
53
+ * The daily catalogue check (#248): one walk that refetches what differs and
54
+ * deletes only with proof. Nothing is written locally: `enqueue` hands
55
+ * documents to the collection's pull (the reconcile feed). `Cursor` must be
56
+ * JSON-serialisable, since the runner persists it to resume a stopped pass.
57
+ */
58
+ export interface CatalogueReconcileAdapter<Doc = any, Cursor = unknown> {
59
+ /** Remote listing, one backend request per page, from `from` (a cursor this adapter yielded earlier) or the start. */
60
+ fetchPages(context: SyncContext, from?: Cursor): AsyncIterable<{ entries: CatalogueReconcileEntry[]; cursor: Cursor }>;
61
+ /** Pure: the same fingerprint from a local document. */
62
+ fingerprint(doc: Doc): string;
63
+ /**
64
+ * Deletion proof, required: of these local documents (the ones the listing did not name), the keys
65
+ * the backend confirms gone (absent, or no longer sellable). One or more requests. Only confirmed
66
+ * keys are tombstoned; an adapter that never deletes returns none.
67
+ */
68
+ confirmGone(locals: Doc[], context: SyncContext): Promise<string[]>;
69
+ /** Hand documents to the collection's pull (the reconcile feed). */
70
+ enqueue(entries: Array<{ key: string; local?: Doc; remote?: unknown; tombstone?: boolean }>): void;
71
+ /** Ids per `fetchByIds` request of the feed this adapter enqueues into: a page's `n` refetches take `ceil(n / refetchBatchSize)` budget slots (1 when unset). */
72
+ refetchBatchSize?: number;
43
73
  }
@@ -26,6 +26,12 @@ export interface ReplicationAdapter<RxDocType, CheckpointType = any> {
26
26
  checkpoint: CheckpointType;
27
27
  }>;
28
28
 
29
+ /**
30
+ * Documents per pull page, passed to handler as batchSize. RxDB treats a
31
+ * shorter page as the end of the cycle. Defaults to RxDB's 100.
32
+ */
33
+ batchSize?: number;
34
+
29
35
  /**
30
36
  * Fresh install only: the checkpoint this feed starts from instead of a full first pass,
31
37
  * read before any feed runs (combinePullAdapters). Absent: a full first pass, as today.
@@ -1,3 +1,5 @@
1
+ import type { TaxRounding } from './connector';
2
+
1
3
  /** What the POS needs from the store's own settings (TV4). Read once after sign-in; the app feeds all three consumers from it. */
2
4
  export interface StoreSettings {
3
5
  /** ISO 4217, upper case (the currency prices are sold in). */
@@ -8,6 +10,8 @@ export interface StoreSettings {
8
10
  taxRatesPpm: { default: number; [taxClass: string]: number };
9
11
  /** Connector-specific and opaque to the app: what the connector needs to price documents. The app passes it back to the connector unchanged, and never logs it. */
10
12
  pricingContext?: Record<string, string>;
13
+ /** Derived, never read by `storeSettings`: the store's `ServerCapabilities.taxRounding`, which `useStoreSettings` fills in (#324). */
14
+ taxRounding?: TaxRounding;
11
15
  }
12
16
 
13
17
  /**
@@ -58,6 +58,13 @@ export interface ProductTraits<Doc = any> {
58
58
  /** All purchasable variants, in id order (connectors store variants sorted by id). Optional: connectors without variant support omit it. */
59
59
  getVariants?: (doc: Doc, context?: TraitContext) => VariantSummary[];
60
60
 
61
+ /**
62
+ * The backend's tax class id for the variant `variantId`, or for the product (its default variant) when omitted.
63
+ * The id is a key of `StoreSettings.taxRatesPpm`; undefined means the default class. Optional: without it, every
64
+ * line is taxed at the default rate.
65
+ */
66
+ getTaxClass?: (doc: Doc, variantId?: string) => string | undefined;
67
+
61
68
  /** @deprecated Use `getPrices` with `resolvePrice`. */
62
69
  getPrice: (doc: Doc) => string | undefined;
63
70
 
@@ -0,0 +1,13 @@
1
+ /** A backend refused the stored credentials (expired, revoked or insufficient); the app should sign in again. */
2
+ export class ConnectorUnauthorizedError extends Error {
3
+ readonly code = 'unauthorized' as const;
4
+ /** Only signing in on this till fixes it, so the pull stops until `resume()` (`errorKind`). */
5
+ readonly fixedBy = 'till' as const;
6
+ readonly status?: number;
7
+
8
+ constructor(message: string, status?: number) {
9
+ super(message);
10
+ this.name = 'ConnectorUnauthorizedError';
11
+ this.status = status;
12
+ }
13
+ }