@tallyui/core 5.0.0 → 5.2.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.
@@ -2,6 +2,9 @@ import { MAX_COMMANDS_PER_BATCH } from '../commands'
2
2
  import type { AnyCommandEnvelope, BatchTooLargeBody, CommandEnvelope, CommandResult, OrderCreatePayload, RegisterCommandEnvelope } from '../types'
3
3
  import { fiscalFiguresErrors } from './fiscal-figures'
4
4
  import { payloadBoundErrors, payloadShapeErrors } from './order-payload-shape'
5
+ import { refundPayloadErrors } from './refund-payload-shape'
6
+ import { registerPayloadErrors } from './register-payload-shape'
7
+ import { reopenPayloadErrors } from './reopen-payload-shape'
5
8
  import { orderCreatePart, updatePayloadErrors } from './update-payload-shape'
6
9
 
7
10
  /** An envelope validateBatch accepted: every field's shape is checked, and its version is any positive
@@ -51,6 +54,8 @@ const rejected = (id: string, code: 'unsupported_version' | 'invalid_payload', m
51
54
  ({ id, status: 'rejected', error: data === undefined ? { code, message } : { code, message, data } })
52
55
  // A server lists at most ten payload errors in one message.
53
56
  const firstTen = (errors: readonly string[]) => errors.slice(0, 10).join('; ')
57
+ // The `invalid_payload` result for a shape function's errors, or undefined when there are none.
58
+ const shapeRefusal = (id: string, errors: readonly string[]) => errors.length ? rejected(id, 'invalid_payload', firstTen(errors)) : undefined
54
59
 
55
60
  /** The `unsupported_version` result for a command whose version list the server may leave out (absent or empty: it takes none). */
56
61
  function unsupportedOptional(envelope: { id: string; type: string; version: number },
@@ -71,8 +76,10 @@ function unsupportedOptional(envelope: { id: string; type: string; version: numb
71
76
  * claim, in the executor (order.create; register commands follow ADR-068). It pushes any result
72
77
  * one of those steps returns and moves on.
73
78
  *
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.
79
+ * For order.update the shape check is updatePayloadErrors (ADR-090): it adds the update's store ids; for order.refund
80
+ * refundPayloadErrors, for order.reopen reopenPayloadErrors, for a register command registerPayloadErrors.
81
+ * precheckCommand repeats the shape check for every command type at every version, after the version answer, as a
82
+ * backstop (#1344, #1346): for order.update's create part too.
76
83
  *
77
84
  * The replay lookup goes before precheckCommand so an already-applied command always replays
78
85
  * as `duplicate`, even once a later @tallyui/core tightens what precheckCommand accepts.
@@ -82,15 +89,22 @@ function unsupportedOptional(envelope: { id: string; type: string; version: numb
82
89
  * `precheckCommand(envelope, { orderCreate: [1, 2, 3], register: [1], orderRefund: [1], orderReopen: [1], orderUpdate: [1] })` (`orderRefund`, `orderReopen` and `orderUpdate` are optional).
83
90
  * `cashRounding` is the server's own word too (ADR-094): without `true`, an order.create (or an order.update's create part)
84
91
  * carrying `cashRoundings` is refused as `invalid_payload`, never sent on with the field dropped, which would be a wrong total.
92
+ * Likewise, a fee or shipping charge carrying `amountIncludesTax` is refused unless the server declares `chargeTaxMode: true`.
85
93
  */
86
94
  export function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCommandEnvelope, 'id' | 'type' | 'version' | 'payload'>,
87
- supported: { orderCreate: readonly number[]; register: readonly number[]; orderRefund?: readonly number[]; orderReopen?: readonly number[]; orderUpdate?: readonly number[]; cashRounding?: boolean }): CommandResult | undefined {
95
+ supported: { orderCreate: readonly number[]; register: readonly number[]; orderRefund?: readonly number[]; orderReopen?: readonly number[]; orderUpdate?: readonly number[]; cashRounding?: boolean; chargeTaxMode?: boolean }): CommandResult | undefined {
88
96
  // An empty list would send Math.max() of nothing (-Infinity, null in JSON) as the server's version.
89
97
  for (const key of ['orderCreate', 'register'] as const) {
90
98
  if (!supported[key]?.length) throw new TypeError(`precheckCommand: supported.${key} must list at least one version`)
91
99
  }
92
- if (envelope.type === 'order.refund') return unsupportedOptional(envelope, 'orderRefund', supported.orderRefund ?? [], 'refunds')
93
- if (envelope.type === 'order.reopen') return unsupportedOptional(envelope, 'orderReopen', supported.orderReopen ?? [], 'reopens')
100
+ if (envelope.type === 'order.refund') {
101
+ return unsupportedOptional(envelope, 'orderRefund', supported.orderRefund ?? [], 'refunds')
102
+ ?? shapeRefusal(envelope.id, refundPayloadErrors(envelope.payload))
103
+ }
104
+ if (envelope.type === 'order.reopen') {
105
+ return unsupportedOptional(envelope, 'orderReopen', supported.orderReopen ?? [], 'reopens')
106
+ ?? shapeRefusal(envelope.id, reopenPayloadErrors(envelope.payload))
107
+ }
94
108
  if (envelope.type === 'order.update') {
95
109
  const refusal = unsupportedOptional(envelope, 'orderUpdate', supported.orderUpdate ?? [], 'updates')
96
110
  if (refusal) return refusal
@@ -107,7 +121,7 @@ export function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCom
107
121
  `register version ${envelope.version} is not supported; this server supports ${supported.register.join(', ')}`,
108
122
  { register: Math.max(...supported.register) })
109
123
  }
110
- return undefined
124
+ return shapeRefusal(envelope.id, registerPayloadErrors(envelope.type, envelope.payload))
111
125
  }
112
126
  const command = envelope as CommandEnvelope<OrderCreatePayload>
113
127
  if (!supported.orderCreate.includes(command.version)) {
@@ -118,6 +132,10 @@ export function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCom
118
132
  if ((command.payload as { cashRoundings?: unknown }).cashRoundings !== undefined && supported.cashRounding !== true) {
119
133
  return rejected(command.id, 'invalid_payload', 'cashRoundings requires the cashRounding capability, which this server does not declare')
120
134
  }
135
+ if (supported.chargeTaxMode !== true && [command.payload.fees, command.payload.shipping].some(items =>
136
+ Array.isArray(items) && items.some(entry => entry?.amountIncludesTax !== undefined))) {
137
+ return rejected(command.id, 'invalid_payload', 'amountIncludesTax requires the chargeTaxMode capability, which this server does not declare')
138
+ }
121
139
  // ADR-062 sends version 2 exactly when there is a discount, so version 1 can never create adjustments.
122
140
  const { lines, discountMinor } = command.payload as { lines?: unknown; discountMinor?: unknown }
123
141
  const discounted = discountMinor !== undefined
@@ -183,8 +201,8 @@ export function precheckCommand(envelope: Pick<AnyCommandEnvelope | ValidatedCom
183
201
  return rejected(command.id, 'invalid_payload', firstTen(bounds))
184
202
  }
185
203
  const shape = payloadShapeErrors(payload)
186
- const errors = command.version >= 5 && shape.length ? shape
187
- : v3 && display !== undefined && taxByRate !== undefined && shape.length === 0 ? fiscalFiguresErrors(payload) : []
204
+ const errors = shape.length ? shape
205
+ : v3 && display !== undefined && taxByRate !== undefined ? fiscalFiguresErrors(payload) : []
188
206
  if (errors.length) {
189
207
  return rejected(command.id, 'invalid_payload', firstTen(errors))
190
208
  }
@@ -45,8 +45,8 @@ export function fiscalFiguresErrors(payload: OrderCreatePayload): string[] {
45
45
  if (payload.fees?.length || payload.shipping?.length) check(display.taxInclusive === payload.pricesIncludeTax, 'display.taxInclusive', 'payload.pricesIncludeTax')
46
46
  for (const field of ['fees', 'shipping'] as const) {
47
47
  const id = field === 'fees' ? 'clientFeeId' : 'clientShippingId'
48
- const amounts = new Map((payload[field] ?? []).map(entry => [
49
- 'clientFeeId' in entry ? entry.clientFeeId : entry.clientShippingId, entry.amountMinor,
48
+ const charges = new Map((payload[field] ?? []).map(entry => [
49
+ 'clientFeeId' in entry ? entry.clientFeeId : entry.clientShippingId, entry,
50
50
  ]))
51
51
  const rows = display[field]
52
52
  if (rows !== undefined) check(Array.isArray(rows), `display.${field}`, 'an array')
@@ -56,12 +56,19 @@ export function fiscalFiguresErrors(payload: OrderCreatePayload): string[] {
56
56
  if (!object(row, path, [id, 'amountMinor'])) return
57
57
  check(typeof row[id] === 'string' && row[id].length > 0, `${path}.${id}`, 'a non-empty string')
58
58
  money(row, path, ['amountMinor'])
59
- check(amounts.has(row[id] as string), `${path}.${id}`, `a payload.${field}[].${id}`)
59
+ const entry = charges.get(row[id] as string)
60
+ check(entry !== undefined, `${path}.${id}`, `a payload.${field}[].${id}`)
60
61
  check(!seen.has(row[id]), `${path}.${id}`, `no duplicate ${id}`)
61
62
  seen.add(row[id])
62
- if (amounts.has(row[id] as string)) check(row.amountMinor === amounts.get(row[id] as string), `${path}.amountMinor`, `the payload.${field} amountMinor`)
63
+ if (entry) {
64
+ // #1383: the display row stays in display mode, the wire charge is in its own mode, and a converted row may carry the till's one-cent display residue (order-builder.ts).
65
+ const converted = entry.amountIncludesTax !== undefined && entry.amountIncludesTax !== payload.pricesIncludeTax
66
+ const expected = !converted ? entry.amountMinor : entry.amountMinor + (entry.amountIncludesTax ? -entry.taxMinor : entry.taxMinor)
67
+ const matches = converted ? typeof row.amountMinor === 'number' && Math.abs(row.amountMinor - expected) <= 1 : row.amountMinor === expected
68
+ check(matches, `${path}.amountMinor`, `the payload.${field} amountMinor${converted ? ' converted to the display tax mode' : ''}`)
69
+ }
63
70
  })
64
- for (const key of amounts.keys()) check(seen.has(key), `display.${field}`, `a row for ${id} ${key}`)
71
+ for (const key of charges.keys()) check(seen.has(key), `display.${field}`, `a row for ${id} ${key}`)
65
72
  }
66
73
  const codes = new Set((payload.coupons ?? []).map(coupon => coupon.code))
67
74
  const seen = new Set<string>()
@@ -124,7 +124,7 @@ export function payloadShapeErrors(payload: unknown): string[] {
124
124
  check(object(item), path, 'an object')
125
125
  if (!object(item)) return
126
126
  const keys = custom ? ['name', 'sku', 'taxClass', 'taxStatus']
127
- : [id, 'name', 'amountMinor', 'taxMinor', 'taxStatus', 'taxClass', ...(field === 'shipping' ? ['methodId'] : [])]
127
+ : [id, 'name', 'amountMinor', 'amountIncludesTax', 'taxMinor', 'taxStatus', 'taxClass', ...(field === 'shipping' ? ['methodId'] : [])]
128
128
  for (const key of Object.keys(item)) check(keys.includes(key), `${path}.${key}`, 'no unknown key')
129
129
  check(typeof item.name === 'string' && item.name.length > 0, `${path}.name`, 'a non-empty string')
130
130
  check(item.taxStatus === 'taxable' || item.taxStatus === 'none', `${path}.taxStatus`, 'taxable or none')
@@ -132,6 +132,7 @@ export function payloadShapeErrors(payload: unknown): string[] {
132
132
  if (item[key] !== undefined) check(typeof item[key] === 'string', `${path}.${key}`, 'a string')
133
133
  }
134
134
  if (!custom) {
135
+ if (item.amountIncludesTax !== undefined) check(typeof item.amountIncludesTax === 'boolean', `${path}.amountIncludesTax`, 'a boolean')
135
136
  check(typeof item[id] === 'string' && item[id].length > 0, `${path}.${id}`, 'a non-empty string')
136
137
  check(!seen.has(item[id]), `${path}.${id}`, `no duplicate ${id}`)
137
138
  seen.add(item[id])
@@ -7,7 +7,7 @@ import type { StoreOrderLine } from '../types/orders'
7
7
  import { roundRatio } from './round-ratio'
8
8
 
9
9
  /** The fields of an order line this needs; a StoreOrderLine fits. */
10
- export type RefundableOrderLine = Pick<StoreOrderLine, 'id' | 'quantity' | 'totalMinor' | 'taxMinor'>;
10
+ export type RefundableOrderLine = Pick<StoreOrderLine, 'id' | 'quantity' | 'totalMinor' | 'taxMinor' | 'soldTotalMinor' | 'soldTaxMinor'>;
11
11
  /** Earlier refund lines; negative quantities count by magnitude. */
12
12
  export interface EarlierRefund { lines: ReadonlyArray<Pick<OrderRefundLine, 'orderLineId' | 'quantity'>> }
13
13
 
@@ -37,6 +37,15 @@ export interface PricedRefund {
37
37
  netMinor: number; taxMinor: number; totalMinor: number;
38
38
  }
39
39
 
40
+ // Sold figures win when present: a store whose live line totals shrink on return still prices from the sale (medusapos#636).
41
+ function pricingBase({ totalMinor, taxMinor, soldTotalMinor, soldTaxMinor }: RefundableOrderLine): [number, number] {
42
+ if (soldTotalMinor === undefined && soldTaxMinor === undefined) return [totalMinor, taxMinor];
43
+ if (soldTotalMinor === undefined || soldTaxMinor === undefined || !Number.isSafeInteger(soldTotalMinor) || !Number.isSafeInteger(soldTaxMinor)) {
44
+ throw new RangeError('A line carries both sold figures or neither, as safe integers');
45
+ }
46
+ return [soldTotalMinor, soldTaxMinor];
47
+ }
48
+
40
49
  /** Returns the quantities and amounts still refundable, in order-line order. */
41
50
  export function refundableLines(
42
51
  lines: readonly RefundableOrderLine[], refunds: readonly EarlierRefund[],
@@ -52,7 +61,7 @@ export function refundableLines(
52
61
  }
53
62
  const refundedQuantity = earlier.reduce((sum, refund) => refund.orderLineId === line.id
54
63
  ? Math.min(line.quantity, sum + Math.abs(refund.quantity)) : sum, 0);
55
- const [netMinor, taxMinor] = [line.totalMinor, line.taxMinor].map((total) => line.quantity === 0 ? 0
64
+ const [netMinor, taxMinor] = pricingBase(line).map((total) => line.quantity === 0 ? 0
56
65
  : total - Number(roundRatio(BigInt(refundedQuantity) * BigInt(total), BigInt(line.quantity), 'half_up')));
57
66
  return {
58
67
  orderLineId: line.id, refundedQuantity, refundableQuantity: line.quantity - refundedQuantity, netMinor, taxMinor,
@@ -78,7 +87,7 @@ export function priceRefund(
78
87
  if (quantity < 1) continue;
79
88
  const line = lines[index];
80
89
  const refundedQuantity = available[index].refundedQuantity;
81
- const [netMinor, taxMinor] = [line.totalMinor, line.taxMinor].map((total) =>
90
+ const [netMinor, taxMinor] = pricingBase(line).map((total) =>
82
91
  Number(roundRatio(BigInt(refundedQuantity + quantity) * BigInt(total), BigInt(line.quantity), 'half_up'))
83
92
  - Number(roundRatio(BigInt(refundedQuantity) * BigInt(total), BigInt(line.quantity), 'half_up')));
84
93
  const totalMinor = netMinor + taxMinor;
@@ -356,8 +356,10 @@ export interface OrderCreateFee {
356
356
  clientFeeId: string;
357
357
  /** Recorded fee title, 1–255 characters. */
358
358
  name: string;
359
- /** Instruction: integer >= 0, gross when pricesIncludeTax, net otherwise; never discounted. */
359
+ /** Instruction: integer >= 0, gross when its own mode (`amountIncludesTax`, else `pricesIncludeTax`) includes tax, net otherwise; never discounted. */
360
360
  amountMinor: number;
361
+ /** Instruction (vendurepos 2.10b): `amountMinor`'s own mode, gross when true and net when false. Absent means `pricesIncludeTax`'s. Sent only to a store whose connector declares `chargeTaxMode`, and only when it differs from `pricesIncludeTax`. */
362
+ amountIncludesTax?: boolean;
361
363
  /** Instruction: `none` means no tax on this fee. */
362
364
  taxStatus: 'taxable' | 'none';
363
365
  /** Instruction, at most 64 characters; absent means the standard class. */
@@ -12,6 +12,7 @@ import type { ReceiptTemplate, ReceiptTemplateKind } from './receipt-templates';
12
12
  import type { RegisterInfo } from './registers';
13
13
  import type { ClosureReads } from './closures';
14
14
  import type { Cashier } from './cashier';
15
+ import type { PaymentMethodKind } from './commands';
15
16
  import type { FailureClass } from '../connectivity';
16
17
  import type { DisplayAdvertisement, DisplaySignalling } from './display-signalling';
17
18
  import { parseDisplayAdvertisement } from '../customer-display/advertisement';
@@ -91,6 +92,8 @@ export interface ServerCapabilities {
91
92
  pluginContract?: number;
92
93
  /** True only when the store's connector carries order.create's `cashRoundings` (ADR-094). Absent: the till never rounds a cash leg, and finalize refuses an order with entries. */
93
94
  cashRounding?: boolean;
95
+ /** True only when the store takes a fee's or shipping charge's own tax mode as order.create's `amountIncludesTax` (vendurepos 2.10b). Absent: finalize converts every charge to the order's mode and sends no `amountIncludesTax`. */
96
+ chargeTaxMode?: boolean;
94
97
  }
95
98
 
96
99
  /** #287, ADR-071. `custom`: the till computes as when absent; that server never emits `figures_mismatch` for subtotal or tax. */
@@ -293,11 +296,66 @@ export interface ConnectorTraits {
293
296
  customer?: CustomerTraits;
294
297
  }
295
298
 
299
+ /** The answer to one `settleRefusedOrder` call. */
300
+ export type SettleOutcome =
301
+ /** The order is cancelled. */
302
+ | { kind: 'done'; status: string }
303
+ /** It is not a waiting unpaid order any more; nothing was cancelled. `capturedMinor` is what the store holds as captured. */
304
+ | { kind: 'changed'; status: string; capturedMinor: number }
305
+ /** The store or this check said no. */
306
+ | { kind: 'refused'; code: string; message: string }
307
+ /** The store no longer has it. */
308
+ | { kind: 'gone' }
309
+ /** No definite answer: try again later with the same `attemptId`. */
310
+ | { kind: 'retry'; reason: string };
311
+
312
+ /** Which order to settle: the store's id, the till's own order uuid, and the id of this attempt. */
313
+ export interface SettleCancelRequest { storeOrderId: string; clientOrderId: string; attemptId: string }
314
+
315
+ /** One till leg to record on the store order (#1101 slice 3): a new payment id, the till leg's method, amount and cash tendered. */
316
+ export interface SettlePayment { id: string; method: PaymentMethodKind; amountMinor: number; tenderedMinor?: number }
317
+ /** Record the till's unrecorded legs on the store order a refused sale left part paid. */
318
+ export interface SettlePayRequest extends SettleCancelRequest { currency: string; payments: readonly SettlePayment[] }
319
+ /** `recorded`: the ids in `payments` the store holds as captured when the call ends, in request order. */
320
+ export interface SettlePayResult { outcome: SettleOutcome; recorded: readonly string[] }
321
+
322
+ /** One till leg to take off the store order (#1101 slice 4): its store payment id and the void's command id, kept across repeats of an attempt.
323
+ * `amountMinor` is the till leg's amount in minor units, which the connector checks against the store row. */
324
+ export interface SettleReverseLeg { paymentId: string; commandId: string; amountMinor: number }
325
+ /** Void the till's recorded legs on the store order a refused sale left part paid, then cancel it. */
326
+ export interface SettleReverseRequest extends SettleCancelRequest { legs: readonly SettleReverseLeg[] }
327
+ /** `voided`: the request's payment ids the store holds as voided when the call ends, in request order. */
328
+ export interface SettleReverseResult { outcome: SettleOutcome; voided: readonly string[] }
329
+
330
+ /** Settlement of an order the store created before it refused the sale. */
331
+ export interface RefusedOrderSettlement {
332
+ cancel?: (context: SyncContext, request: SettleCancelRequest) => Promise<SettleOutcome>;
333
+ /**
334
+ * Records the till's unrecorded legs, money the customer already paid at the till, on a part-paid store order: no new
335
+ * money is taken. `done` means every payment is recorded and the order reads `completed`; `changed` means nothing was
336
+ * sent because the store's figures or status do not match; `gone` comes only from the uuid resolver's 404; `retry`
337
+ * means no definite answer: send again with the same `attemptId` and payment ids.
338
+ */
339
+ pay?: (context: SyncContext, request: SettlePayRequest) => Promise<SettlePayResult>;
340
+ /**
341
+ * No money moves: the cashier hands it back. `voided` lists the legs the store holds as voided when the call ends.
342
+ * `done`: every leg is voided and the order reads `cancelled`.
343
+ * `changed`: the store shows money or a status the till does not hold, so nothing more was sent.
344
+ * `refused`: the store refused this step, or answered in a way that is not a usable ledger answer (as for `cancel` and `pay`).
345
+ * The order is not cancelled. A refused void always stops the run before any cancel is sent.
346
+ * `gone`: only from the uuid resolver's 404.
347
+ * `retry`: no definite answer. Send again with the same `attemptId` and command ids.
348
+ */
349
+ reverse?: (context: SyncContext, request: SettleReverseRequest) => Promise<SettleReverseResult>;
350
+ }
351
+
296
352
  /**
297
353
  * The main connector interface.
298
354
  * Each backend (WooCommerce, Medusa, Vendure, etc.) implements this.
299
355
  */
300
356
  export interface TallyConnector {
357
+ /** True when the store's live order-line totals shrink as units are returned while `quantity` stays the sold quantity (Medusa). The refund form then refuses a partial refund of a line without `soldTotalMinor`/`soldTaxMinor`. Absent: line totals are as sold. */
358
+ lineTotalsShrinkOnReturn?: boolean;
301
359
  /** Unique identifier for this connector */
302
360
  id: string;
303
361
  /** Human-readable name */
@@ -424,6 +482,14 @@ export interface TallyConnector {
424
482
  * read-only; rejects as `listOrders`. `undefined` when the connector has no order history.
425
483
  */
426
484
  getOrders?: (context: SyncContext, ids: readonly string[]) => Promise<StoreOrder[]>;
485
+ /**
486
+ * Settles an order the store created before it refused the sale: online only, never through the outbox. `cancel`
487
+ * cancels it only when the store's own current record shows nothing paid; `pay` records the till's unrecorded legs
488
+ * only when the store's due is exactly their sum. `attemptId` identifies one attempt and is
489
+ * sent again unchanged until a definite answer; `retry` means no definite answer. Rejects with
490
+ * `ConnectorUnauthorizedError` for credentials. `undefined` when the connector can't settle refused orders.
491
+ */
492
+ settleRefusedOrder?: RefusedOrderSettlement;
427
493
  /**
428
494
  * The store's refunds, newest first, one page per call, dated by when each was made (ADR-081 decision 7): online only,
429
495
  * read-only. Rejects as `listOrders` does; a `dateRange` end that is not a UTC instant ending in Z is a TypeError
@@ -20,6 +20,12 @@ export interface StoreOrderLine {
20
20
  /** After discounts, excluding tax. */
21
21
  totalMinor: number;
22
22
  taxMinor: number;
23
+ /** The line's total after discounts, excluding tax, as sold, before any return; set by a connector whose live totals shrink on return (connector-medusa at plugin contract 7), absent otherwise. */
24
+ soldTotalMinor?: number;
25
+ /** The tax beside `soldTotalMinor`, as sold. Present exactly when it is. */
26
+ soldTaxMinor?: number;
27
+ /** The store's returned quantity for the line (requested, received or dismissed returns); absent when the store does not say. Refund pricing does not read it. */
28
+ returnedQuantity?: number;
23
29
  }
24
30
 
25
31
  /** A fee or shipping line: excluding tax, the tax beside it. A fee may be negative.