@tallyui/connector-woocommerce 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.
@@ -1,5 +1,7 @@
1
1
  // ADR-073; M3-spike-paid-push.md proves paid order pushes against WCPOS 1.10.20.
2
- import { minorUnitDigits, moneyFromDecimalString, moneyFromMajor, type CommandResult, type OrderAddress, type OrderCreateEnvelope } from '@tallyui/core';
2
+ import { minorUnitDigits, moneyFromDecimalString, moneyFromMajor, woocommerceTax, type CommandResult, type OrderAddress, type OrderCreateEnvelope } from '@tallyui/core';
3
+ import { WCPOS_UUID_META_KEY } from '../replication/products';
4
+ import { createWooCall, type Answer } from './http';
3
5
 
4
6
  export type WooTransportOutcome =
5
7
  | { kind: 'results'; results: CommandResult[] }
@@ -18,8 +20,21 @@ export interface WooCommandTransportOptions {
18
20
  /** True when the store passes the coupons gate (`ServerCapabilities.coupons`, ADR-077 R2/R3). Read at push time;
19
21
  * absent means closed, so a sale still carrying coupons is refused with `coupon_invalid` and no request is made. */
20
22
  acceptsCoupons?: boolean | (() => boolean | Promise<boolean>);
23
+ /** True for a WCPOS 2.0.x store, whose push carries no money: the sale is pushed `pending`, then paid through the
24
+ * payment ledger. Read at push time; absent, the transport reads `/site` once and decides from `wcpos_version`. */
25
+ ledgerPayments?: boolean | (() => boolean | Promise<boolean>);
21
26
  }
22
27
 
28
+ // Any-version 8-4-4-4-12 uuid, as WCPOS checks a payment id (v2.0.4 includes/Sync/Pos_Uuid.php:46-48, Ledger.php:1645).
29
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
30
+
31
+ // A sale's minor amount as Woo's decimal string, at the display exponent else the currency's: one rule for bodies and messages.
32
+ const wooDigits = (p: OrderCreateEnvelope['payload']) => p.display?.exponent ?? minorUnitDigits(p.currency);
33
+ const wooMajor = (minor: number, digits: number) => (minor / 10 ** digits).toFixed(digits);
34
+
35
+ /** A money command for the ledger, sent with the order revision it was built against. */
36
+ export interface WooMoneyCommand { path: 'payments' | 'close'; body: Record<string, unknown> }
37
+
23
38
  export function wooMinorFromDecimal(text: string, currency: string): number | undefined {
24
39
  const trimmed = text.trim();
25
40
  if (!/^\d+(\.\d+)?$/.test(trimmed)) return undefined;
@@ -32,11 +47,24 @@ export function wooMinorFromDecimal(text: string, currency: string): number | un
32
47
  }
33
48
 
34
49
  export interface WooLocalOrder {
35
- lines: ReadonlyArray<{ id: string; netMicros?: string; /** The line's discount in its own tax mode (gross when inclusive), as stored. */ discountMinor?: number }>;
50
+ lines: ReadonlyArray<{ id: string; netMicros?: string; /** The line's discount in its own tax mode (gross when inclusive), as stored. */ discountMinor?: number;
51
+ taxLines?: ReadonlyArray<{ rateId?: number; compound?: boolean; ratePpm: number }> }>;
36
52
  fees?: ReadonlyArray<{ id: string; netMicros?: string }>;
37
53
  shipping?: ReadonlyArray<{ id: string; netMicros?: string }>;
38
54
  }
39
55
 
56
+ // Match woocommerceLine's pre-coupon net calculation exactly (ADR-076).
57
+ function preCouponNetMicros(minor: bigint, digits: number, stored: WooLocalOrder['lines'][number] | undefined): string | undefined {
58
+ if (!stored || stored.taxLines?.some((tax) => typeof tax.rateId !== 'number' || typeof tax.compound !== 'boolean')) return undefined;
59
+ const factor = 10 ** digits, precision = woocommerceTax.getRoundingPrecision(digits);
60
+ const input = { amount: Number(minor) / factor, rates: (stored.taxLines ?? []).map((tax, index) => ({
61
+ id: tax.rateId!, rate: String(tax.ratePpm / 10000), compound: tax.compound!, priority: index, order: index,
62
+ })), amountIncludesTax: true, dp: digits, perRatePrecision: precision };
63
+ const result = woocommerceTax.calculateTaxes(input);
64
+ const net = woocommerceTax.roundHalfUp(input.amount - result.total, precision);
65
+ return String(Math.round(net * factor * 1e6));
66
+ }
67
+
40
68
  // Repeated until stable so no removal can join a new tag (CodeQL js/incomplete-multi-character-sanitization).
41
69
  function stripTags(text: string): string {
42
70
  let previous;
@@ -71,11 +99,21 @@ function wooAddress(address: OrderAddress | undefined): Record<string, string> {
71
99
  return Object.fromEntries(WOO_ADDRESS_KEYS.flatMap(([ours, theirs]) => typeof address?.[ours] === 'string' ? [[theirs, address[ours]]] : []));
72
100
  }
73
101
 
74
- export function toWooOrderPayload(envelope: OrderCreateEnvelope, local?: WooLocalOrder, options?: { paymentsList?: boolean }): { payload: Record<string, unknown> } | { error: { code: string; message: string } } {
102
+ export function toWooOrderPayload(envelope: OrderCreateEnvelope, local?: WooLocalOrder, options?: { paymentsList?: boolean; ledger?: boolean }): { payload: Record<string, unknown>; money?: WooMoneyCommand[] } | { error: { code: string; message: string } } {
75
103
  const p = envelope.payload;
76
104
  if (p.payments.length === 0 || (p.payments.length > 1 && !options?.paymentsList)) {
77
105
  return { error: { code: 'invalid_payload', message: 'WooCommerce orders take one payment.' } };
78
106
  }
107
+ const ledger = options?.ledger === true;
108
+ const closes = p.totalMinor === 0 && !p.payments.some((payment) => payment.amountMinor > 0);
109
+ if (ledger && p.payments.some((payment) => !UUID.test(payment.clientPaymentId))) {
110
+ return { error: { code: 'invalid_payload', message: 'WooCommerce POS 2.0 records each payment by a UUID; this sale has a payment without one.' } };
111
+ }
112
+ if (ledger && closes && !UUID.test(envelope.id)) return { error: { code: 'invalid_payload', message: "WooCommerce POS 2.0 closes a free sale by a UUID command id; this sale's id is not one." } };
113
+ // Ledger::validate_input refuses an amount that is not positive (v2.0.4 Ledger.php:1648-1654).
114
+ if (ledger && !closes && p.payments.some((payment) => payment.amountMinor <= 0)) {
115
+ return { error: { code: 'invalid_payload', message: 'Every payment on a WooCommerce POS 2.0 sale must be more than zero.' } };
116
+ }
79
117
  if (p.payments.length > 20) {
80
118
  return { error: { code: 'invalid_payload', message: 'WooCommerce records at most 20 payments.' } };
81
119
  }
@@ -87,8 +125,8 @@ export function toWooOrderPayload(envelope: OrderCreateEnvelope, local?: WooLoca
87
125
  return { error: { code: 'invalid_payload', message: `Line ${line.clientLineId} has no WooCommerce product id.` } };
88
126
  }
89
127
  }
90
- const digits = p.display?.exponent ?? minorUnitDigits(p.currency);
91
- const major = (minor: number) => (minor / 10 ** digits).toFixed(digits);
128
+ const digits = wooDigits(p);
129
+ const major = (minor: number) => wooMajor(minor, digits);
92
130
  const inclusiveNet = (netMicros: string | undefined, id: string) => {
93
131
  if (netMicros === undefined) {
94
132
  return { error: { code: 'unsupported_tax_mode', message: "Tax-inclusive prices need the till's WooCommerce tax figures; update the till." } };
@@ -103,22 +141,33 @@ export function toWooOrderPayload(envelope: OrderCreateEnvelope, local?: WooLoca
103
141
  const micros = net / divisor;
104
142
  return `${micros / 1000000n}.${(micros % 1000000n).toString().padStart(6, '0')}`;
105
143
  };
144
+ // 2.10 PR4: an exclusive store gets a charge's 6-dp net when it is not a whole cent.
145
+ const chargeTotal = (amountMinor: number, netMicros: string | undefined, id: string) =>
146
+ p.pricesIncludeTax || (netMicros !== undefined && BigInt(netMicros) !== BigInt(amountMinor) * 1000000n)
147
+ ? inclusiveNet(netMicros, id) : major(amountMinor);
106
148
  const line_items = [];
107
149
  for (const line of p.lines) {
150
+ const inclusive = line.taxInclusive ?? p.pricesIncludeTax;
151
+ const stored = local?.lines.find((entry) => entry.id === line.clientLineId);
108
152
  let total = major(line.unitPriceMinor * line.quantity - (line.discountMinor ?? 0));
109
153
  let subtotal = total;
110
- if (line.taxInclusive ?? p.pricesIncludeTax) {
111
- const net = inclusiveNet(local?.lines.find((stored) => stored.id === line.clientLineId)?.netMicros, line.clientLineId);
154
+ if (inclusive) {
155
+ const net = inclusiveNet(stored?.netMicros, line.clientLineId);
112
156
  if (typeof net !== 'string') return net;
113
157
  subtotal = total = net;
114
158
  }
115
159
  const custom = line.custom;
116
160
  let price = major(line.unitPriceMinor);
117
161
  if (p.coupons?.length) {
118
- const discount = (line.taxInclusive ?? p.pricesIncludeTax) && (line.discountMinor ?? 0) > 0
119
- ? local?.lines.find((stored) => stored.id === line.clientLineId)?.discountMinor : line.discountMinor ?? 0;
162
+ const discount = inclusive && (line.discountMinor ?? 0) > 0
163
+ ? stored?.discountMinor : line.discountMinor ?? 0;
120
164
  if (discount === undefined) return { error: { code: 'unsupported_tax_mode', message: "Tax-inclusive prices need the till's WooCommerce tax figures; update the till." } };
121
165
  const quantity = BigInt(line.quantity), minor = BigInt(line.unitPriceMinor) * quantity - BigInt(discount);
166
+ if (inclusive) {
167
+ const net = inclusiveNet(preCouponNetMicros(minor, digits, stored), line.clientLineId);
168
+ if (typeof net !== 'string') return net;
169
+ subtotal = total = net;
170
+ }
122
171
  const divisor = quantity * 10n ** BigInt(digits), micros = (minor * 1000000n * 2n + divisor) / (divisor * 2n);
123
172
  price = minor % quantity === 0n ? major(Number(minor / quantity))
124
173
  : `${micros / 1000000n}.${(micros % 1000000n).toString().padStart(6, '0')}`;
@@ -139,21 +188,22 @@ export function toWooOrderPayload(envelope: OrderCreateEnvelope, local?: WooLoca
139
188
  }
140
189
  const fee_lines = [], shipping_lines = [];
141
190
  for (const fee of p.fees ?? []) {
142
- const total = p.pricesIncludeTax
143
- ? inclusiveNet(local?.fees?.find((stored) => stored.id === fee.clientFeeId)?.netMicros, fee.clientFeeId) : major(fee.amountMinor);
191
+ const total = chargeTotal(fee.amountMinor, local?.fees?.find((stored) => stored.id === fee.clientFeeId)?.netMicros, fee.clientFeeId);
144
192
  if (typeof total !== 'string') return total;
145
193
  fee_lines.push({ name: fee.name, total, tax_status: fee.taxStatus, tax_class: fee.taxClass ?? '' });
146
194
  }
147
195
  for (const shipping of p.shipping ?? []) {
148
- const total = p.pricesIncludeTax
149
- ? inclusiveNet(local?.shipping?.find((stored) => stored.id === shipping.clientShippingId)?.netMicros, shipping.clientShippingId) : major(shipping.amountMinor);
196
+ const total = chargeTotal(shipping.amountMinor,
197
+ local?.shipping?.find((stored) => stored.id === shipping.clientShippingId)?.netMicros, shipping.clientShippingId);
150
198
  if (typeof total !== 'string') return total;
151
- shipping_lines.push({ method_id: shipping.methodId ?? 'pos', method_title: shipping.name, total });
199
+ // WCPOS (1.10.20 and 2.0.4 Orders.php) clears a shipping line's taxes when this meta says `none`.
200
+ shipping_lines.push({ method_id: shipping.methodId ?? 'pos', method_title: shipping.name, total,
201
+ ...(shipping.taxStatus === 'none' ? { meta_data: [{ key: '_woocommerce_pos_data', value: JSON.stringify({ tax_status: 'none' }) }] } : {}) });
152
202
  }
153
203
  const primary = p.payments.reduce((largest, payment) => payment.amountMinor > largest.amountMinor ? payment : largest);
154
204
  const cash = primary.method === 'cash';
155
- const meta_data = [{ key: '_woocommerce_pos_uuid', value: p.clientOrderId }];
156
- if (p.payments.length > 1) {
205
+ const meta_data = [{ key: WCPOS_UUID_META_KEY, value: p.clientOrderId }];
206
+ if (p.payments.length > 1 && !ledger) {
157
207
  meta_data.push({ key: '_woocommerce_pos_payments', value: JSON.stringify(p.payments.map((payment) => ({
158
208
  method: payment.method === 'cash' ? 'pos_cash' : 'pos_card',
159
209
  title: payment.method === 'cash' ? 'Cash' : 'Card', amount: major(payment.amountMinor),
@@ -166,9 +216,23 @@ export function toWooOrderPayload(envelope: OrderCreateEnvelope, local?: WooLoca
166
216
  if (p.taxAddress) meta_data.push({ key: '_woocommerce_pos_tax_based_on', value: p.taxAddress });
167
217
  const billing = { ...(p.customer?.email ? { email: p.customer.email } : {}), ...(p.taxAddress ? wooAddress(p.customer?.billing) : {}) };
168
218
  const shipping = p.taxAddress && p.customer?.shipping ? wooAddress(p.customer.shipping) : undefined;
169
- return { payload: {
170
- status: 'completed', set_paid: true, currency: p.currency,
171
- payment_method: cash ? 'pos_cash' : 'pos_card', payment_method_title: cash ? 'Cash' : 'Card',
219
+ // WCPOS 2.0 pushes only open statuses and strips money keys (v2.0.4 Writers/Pushable_Document.php:36,68-70; Services/
220
+ // Pos_Order_Audit.php:72): a ledger sale is pushed pending, then one `record` per payment (API/V2/Payments_Controller.php:
221
+ // 62-75,138-163; id, method_id, positive amount, matching currency, cash-only tendered: Ledger.php:603-636,1644-1661), or a
222
+ // free sale closed (Payments_Controller.php:69,172-179) with the envelope id at version nibble 8 as its uuid command_id
223
+ // (Money_Command.php:70-72): the same on every retry, never equal to a till's v7 id.
224
+ const money: WooMoneyCommand[] | undefined = !ledger ? undefined : closes
225
+ ? [{ path: 'close', body: { command_id: `${envelope.id.slice(0, 14)}8${envelope.id.slice(15)}` } }]
226
+ : p.payments.map((payment) => ({ path: 'payments', body: { payment: {
227
+ id: payment.clientPaymentId, method_id: payment.method === 'cash' ? 'pos_cash' : 'pos_card',
228
+ amount: major(payment.amountMinor), currency: p.currency,
229
+ ...(payment.method === 'cash' && payment.tenderedMinor !== undefined ? { tendered: major(payment.tenderedMinor) } : {}),
230
+ } } }));
231
+ return { ...(money ? { money } : {}), payload: {
232
+ ...(ledger ? { status: 'pending', currency: p.currency } : {
233
+ status: 'completed', set_paid: true, currency: p.currency,
234
+ payment_method: cash ? 'pos_cash' : 'pos_card', payment_method_title: cash ? 'Cash' : 'Card',
235
+ }),
172
236
  line_items,
173
237
  ...(fee_lines.length ? { fee_lines } : {}),
174
238
  ...(shipping_lines.length ? { shipping_lines } : {}),
@@ -182,18 +246,33 @@ export function toWooOrderPayload(envelope: OrderCreateEnvelope, local?: WooLoca
182
246
  } };
183
247
  }
184
248
 
249
+ /** A capability option given as a value or read at push time; absent means closed. */
250
+ function capability(flag: boolean | (() => boolean | Promise<boolean>) | undefined): boolean | Promise<boolean> {
251
+ return typeof flag === 'function' ? flag() : flag ?? false;
252
+ }
253
+
185
254
  export function createWooCommandTransport(options: WooCommandTransportOptions): {
186
255
  send(batch: OrderCreateEnvelope[], context?: { local?: { orders?: ReadonlyMap<string, WooLocalOrder> } }): Promise<WooTransportOutcome>;
187
256
  } {
188
- const fetch = options.fetch ?? globalThis.fetch;
189
- let baseUrl = options.baseUrl;
190
- while (baseUrl.endsWith('/')) baseUrl = baseUrl.slice(0, -1);
257
+ const { call, retry } = createWooCall(options);
258
+ // WCPOS 2.0.0 and later (its pre-releases too) take money only through the ledger; 1.10.x and the fork have none.
259
+ let siteLedger: boolean | undefined;
260
+ const ledgerStore = async (): Promise<boolean | undefined> => {
261
+ if (options.ledgerPayments !== undefined) return capability(options.ledgerPayments);
262
+ if (siteLedger === undefined) {
263
+ const version = (await call('site', { method: 'GET' })).body?.wcpos_version;
264
+ const major = typeof version === 'string' ? /^(\d+)\.\d+(?:\.\d+)?(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.exec(version.trim())?.[1] : undefined;
265
+ if (major !== undefined) siteLedger = Number(major) >= 2;
266
+ }
267
+ return siteLedger;
268
+ };
191
269
  return {
192
270
  async send(batch, context) {
193
- const paymentsList = typeof options.acceptsPaymentsList === 'function'
194
- ? await options.acceptsPaymentsList() : options.acceptsPaymentsList ?? false;
195
- const coupons = batch.some((envelope) => envelope.payload.coupons?.length) && (typeof options.acceptsCoupons === 'function'
196
- ? await options.acceptsCoupons() : options.acceptsCoupons ?? false);
271
+ if (batch.length === 0) return { kind: 'results', results: [] };
272
+ const ledger = await ledgerStore();
273
+ if (ledger === undefined) return { kind: 'retry', reason: 'store_version_unknown' };
274
+ const paymentsList = await capability(options.acceptsPaymentsList);
275
+ const coupons = batch.some((envelope) => envelope.payload.coupons?.length) && await capability(options.acceptsCoupons);
197
276
  const results: CommandResult[] = [];
198
277
  for (const envelope of batch) {
199
278
  if (envelope.payload.coupons?.length && !coupons) {
@@ -202,66 +281,98 @@ export function createWooCommandTransport(options: WooCommandTransportOptions):
202
281
  data: { storeCode: 'coupons_unsupported' } } });
203
282
  continue;
204
283
  }
205
- const mapped = toWooOrderPayload(envelope, context?.local?.orders?.get(envelope.id), { paymentsList });
284
+ const mapped = toWooOrderPayload(envelope, context?.local?.orders?.get(envelope.id), { paymentsList, ledger });
206
285
  if ('error' in mapped) {
207
286
  results.push({ id: envelope.id, status: 'rejected', error: mapped.error });
208
287
  continue;
209
288
  }
210
- const controller = new AbortController();
211
- const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? 30000);
212
289
  let outcome: WooTransportOutcome;
213
- try {
214
- const response = await fetch(`${baseUrl}/push/orders`, {
215
- method: 'POST',
216
- headers: { 'Content-Type': 'application/json', ...await options.getHeaders() },
217
- body: JSON.stringify({ mutationId: envelope.id, operation: 'create', collection: 'orders',
218
- recordId: envelope.payload.clientOrderId, baseRevision: null, payload: mapped.payload }),
219
- signal: controller.signal,
220
- });
221
- const status = response.status;
222
- const retryAfter = response.headers.get('Retry-After');
223
- const seconds = retryAfter === null ? NaN : Number(retryAfter);
224
- const retry = (reason: string): WooTransportOutcome => ({ kind: 'retry', reason,
225
- ...(Number.isFinite(seconds) && seconds >= 0 ? { retryAfterMs: seconds * 1000 } : {}),
226
- });
227
- if (status === 401) outcome = { kind: 'unauthorized' };
228
- else if (![200, 201, 400, 422, 403, 413, 415].includes(status)) outcome = retry(`status_${status}`);
229
- else {
230
- let body;
231
- try { body = await response.json(); } catch {}
232
- if (status === 200 || status === 201) {
233
- const doc = body?.document;
234
- const totalMinor = wooMinorFromDecimal(String(doc?.total), envelope.payload.currency);
235
- if (doc?.id == null || totalMinor === undefined) {
236
- outcome = retry(controller.signal.aborted ? 'timeout' : 'bad_body');
237
- } else {
238
- results.push({ id: envelope.id, status: 'applied', serverRefs: {
239
- orderId: String(doc.id), displayId: String(doc.number ?? doc.id), totalMinor,
240
- }, ...(totalMinor !== envelope.payload.totalMinor ? { warnings: [{
241
- code: 'total_mismatch' as const, expectedMinor: envelope.payload.totalMinor, serverMinor: totalMinor,
242
- }] } : {}) });
290
+ const pushed = await call('push/orders', { method: 'POST', body: { mutationId: envelope.id, operation: 'create', collection: 'orders',
291
+ recordId: envelope.payload.clientOrderId, baseRevision: null, payload: mapped.payload } });
292
+ const { status, body } = pushed;
293
+ if (status === 0) outcome = retry(pushed, 'network');
294
+ else if (status === 401) outcome = { kind: 'unauthorized' };
295
+ // WCPOS 2.0.4 refuses a till below its protocol: 426 wcpos_update_required (Services/Protocol_Gate.php:15-17).
296
+ else if (status === 426 && body?.code === 'wcpos_update_required') outcome = { kind: 'refused', status, reason: body?.message ?? body.code };
297
+ // A 2.0 store refuses a legacy `completed` push (API/V2/Writers/Pushable_Document.php:100-105): it was upgraded under this transport.
298
+ else if (!ledger && status === 422 && body?.code === 'wcpos_status_not_pushable' && options.ledgerPayments === undefined) { siteLedger = undefined; outcome = retry(pushed, 'ledger_store_detected'); }
299
+ else if (![200, 201, 400, 422, 403, 413, 415].includes(status)) outcome = retry(pushed, `status_${status}`);
300
+ else if (status === 200 || status === 201) {
301
+ const doc = body?.document;
302
+ const totalMinor = wooMinorFromDecimal(String(doc?.total), envelope.payload.currency);
303
+ // The push answers { document, currentRevision } (v2.0.4 API/V2/Write_Controller.php:767-783).
304
+ let revision = body?.currentRevision;
305
+ if (doc?.id == null || totalMinor === undefined || (mapped.money && (typeof revision !== 'string' || !revision))) {
306
+ outcome = retry(pushed, pushed.aborted ? 'timeout' : 'bad_body');
307
+ } else {
308
+ const orderId = String(doc.id), displayId = String(doc.number ?? doc.id);
309
+ // v2.0.4 leaves an under-covered order pos-partial (Projection.php:72-78) and refuses an over-covering record (Ledger.php:662-699).
310
+ if (ledger && totalMinor !== envelope.payload.totalMinor) {
311
+ const tillMinor = envelope.payload.totalMinor, digits = wooDigits(envelope.payload);
312
+ results.push({ id: envelope.id, status: 'rejected', error: { code: 'invalid_payload', message: `WooCommerce order #${displayId} totals ${wooMajor(totalMinor, digits)} but the till charged ${wooMajor(tillMinor, digits)}; no payment was recorded on it.`,
313
+ data: { orderId, storeCode: 'total_mismatch', tillMinor, serverMinor: totalMinor } } });
314
+ continue;
315
+ }
316
+ let failed: Answer | undefined;
317
+ let recorded = 0;
318
+ for (const command of mapped.money ?? []) {
319
+ const path = `orders/${orderId}/${command.path}`;
320
+ let answer = await call(path, { method: 'POST', body: { ...command.body, revision } });
321
+ // A stale revision is resent once, same body, with the server's (Command_Log.php:256-275); the
322
+ // fingerprint leaves out command_id and revision (Command_Log.php:47-48), so the resend is the same command.
323
+ const stale = answer.status === 409 && answer.body?.code === 'wcpos_revision_stale' ? answer.body?.data?.currentRevision : undefined;
324
+ if (typeof stale === 'string' && stale) answer = await call(path, { method: 'POST', body: { ...command.body, revision: stale } });
325
+ // Every 2xx money answer carries the revision after it (Payments_Controller.php:376-405); a refused row is
326
+ // never a 2xx (Payments_Controller.php:154-161, Ledger.php:698).
327
+ if (answer.status >= 200 && answer.status < 300 && typeof answer.body?.revision === 'string' && answer.body.revision) {
328
+ revision = answer.body.revision;
329
+ recorded += 1;
243
330
  continue;
244
331
  }
245
- } else if (status === 400 && body?.code === 'woocommerce_rest_invalid_coupon') {
246
- const message = decodeCouponMessage(body?.message), quoted = /"([^"]*)"/.exec(message)?.[1];
247
- const couponCode = envelope.payload.coupons?.find(({ code }) => code.toLowerCase() === quoted?.toLowerCase())?.code;
248
- results.push({ id: envelope.id, status: 'rejected', error: { code: 'coupon_invalid', message,
249
- data: { storeCode: body.code, ...(couponCode ? { couponCode } : {}) } } });
332
+ failed = answer;
333
+ break;
334
+ }
335
+ const code = failed?.body?.code;
336
+ const terminal = typeof code === 'string' && (code.startsWith('wcpos_') || code === 'rest_invalid_param' || code === 'rest_forbidden');
337
+ if (!failed) {
338
+ results.push({ id: envelope.id, status: 'applied', serverRefs: { orderId, displayId, totalMinor },
339
+ ...(totalMinor !== envelope.payload.totalMinor ? { warnings: [{
340
+ code: 'total_mismatch' as const, expectedMinor: envelope.payload.totalMinor, serverMinor: totalMinor,
341
+ }] } : {}) });
250
342
  continue;
251
- } else if (status === 400 || status === 422) {
343
+ } else if (failed.status === 401) outcome = { kind: 'unauthorized' };
344
+ // The store was rolled back below 2.0 under this transport: /site is read again.
345
+ else if (failed.status === 404 && code === 'rest_no_route') { siteLedger = undefined; outcome = retry(failed, 'ledger_route_missing'); }
346
+ // A retry resends the whole envelope: the push replays by mutationId (Write_Controller.php:153-157,219-240)
347
+ // and a recorded payment by its id, whatever revision it carries (Ledger.php:585-595, Command_Log.php:93-112).
348
+ // Lock busy: Order_Lock.php:136-147, Payments_Controller.php:103-105.
349
+ // Only known refusals are terminal: `Payments_Controller.php:394-398` answers a failed re-read after the effect stood as a plain 4xx; a replay answers the stored outcome.
350
+ else if (failed.status < 400 || failed.status >= 500 || (failed.status === 409
351
+ && ['wcpos_revision_stale', 'wcpos_payment_locked', 'woo_rxdb_sync_record_locked'].includes(code)) || !terminal) {
352
+ outcome = retry(failed, failed.status >= 200 && failed.status < 300 ? (failed.aborted ? 'timeout' : 'bad_body') : code ?? `status_${failed.status}`);
353
+ } else {
354
+ // Stock is held on record and close (Ledger.php:701-705,1848-1852; Services/Stock_Validator.php:382-392).
252
355
  results.push({ id: envelope.id, status: 'rejected', error: {
253
- code: status === 400 && body?.code === 'wcpos_insufficient_stock' ? 'insufficient_stock' : 'invalid_payload',
254
- message: body?.message ?? `status_${status}`,
255
- } });
356
+ code: failed.status === 400 && code === 'wcpos_insufficient_stock' ? 'insufficient_stock' : 'invalid_payload',
357
+ message: `WooCommerce order #${displayId} was ${recorded === 0 ? 'created but not paid' : `created and part paid (${recorded} of ${mapped.money!.length} payments recorded)`}: ${failed.body?.message ?? code ?? `status_${failed.status}`}`,
358
+ data: { orderId, storeCode: code ?? `status_${failed.status}`, ...(recorded ? { recorded } : {}) } } });
256
359
  continue;
257
- } else {
258
- outcome = { kind: 'refused', status, reason: body?.message ?? body?.code ?? `status_${status}` };
259
360
  }
260
361
  }
261
- } catch {
262
- outcome = { kind: 'retry', reason: controller.signal.aborted ? 'timeout' : 'network' };
263
- } finally {
264
- clearTimeout(timeout);
362
+ } else if (status === 400 && body?.code === 'woocommerce_rest_invalid_coupon') {
363
+ const message = decodeCouponMessage(body?.message), quoted = /"([^"]*)"/.exec(message)?.[1];
364
+ const couponCode = envelope.payload.coupons?.find(({ code }) => code.toLowerCase() === quoted?.toLowerCase())?.code;
365
+ results.push({ id: envelope.id, status: 'rejected', error: { code: 'coupon_invalid', message,
366
+ data: { storeCode: body.code, ...(couponCode ? { couponCode } : {}) } } });
367
+ continue;
368
+ } else if (status === 400 || status === 422) {
369
+ results.push({ id: envelope.id, status: 'rejected', error: {
370
+ code: status === 400 && body?.code === 'wcpos_insufficient_stock' ? 'insufficient_stock' : 'invalid_payload',
371
+ message: body?.message ?? `status_${status}`,
372
+ } });
373
+ continue;
374
+ } else {
375
+ outcome = { kind: 'refused', status, reason: body?.message ?? body?.code ?? `status_${status}` };
265
376
  }
266
377
  return results.length ? { kind: 'results', results } : outcome;
267
378
  }
@@ -0,0 +1,166 @@
1
+ /** WooCommerce's currency symbols (wc/v3/data/currencies), HTML entities decoded, as WCPOS v2 bundles them (monorepo 84e698ed packages/core/src/contexts/currencies/currencies.json). */
2
+ export const WOO_CURRENCY_SYMBOLS: Readonly<Record<string, string>> = {
3
+ AED: "د.إ",
4
+ AFN: "؋",
5
+ ALL: "L",
6
+ AMD: "AMD",
7
+ ANG: "ƒ",
8
+ AOA: "Kz",
9
+ ARS: "$",
10
+ AUD: "$",
11
+ AWG: "Afl.",
12
+ AZN: "₼",
13
+ BAM: "KM",
14
+ BBD: "$",
15
+ BDT: "৳ ",
16
+ BGN: "лв.",
17
+ BHD: ".د.ب",
18
+ BIF: "Fr",
19
+ BMD: "$",
20
+ BND: "$",
21
+ BOB: "Bs.",
22
+ BRL: "R$",
23
+ BSD: "$",
24
+ BTC: "฿",
25
+ BTN: "Nu.",
26
+ BWP: "P",
27
+ BYN: "Br",
28
+ BYR: "Br",
29
+ BZD: "$",
30
+ CAD: "$",
31
+ CDF: "Fr",
32
+ CHF: "CHF",
33
+ CLP: "$",
34
+ CNY: "¥",
35
+ COP: "$",
36
+ CRC: "₡",
37
+ CUC: "$",
38
+ CUP: "$",
39
+ CVE: "$",
40
+ CZK: "Kč",
41
+ DJF: "Fr",
42
+ DKK: "kr.",
43
+ DOP: "RD$",
44
+ DZD: "د.ج",
45
+ EGP: "EGP",
46
+ ERN: "Nfk",
47
+ ETB: "Br",
48
+ EUR: "€",
49
+ FJD: "$",
50
+ FKP: "£",
51
+ GBP: "£",
52
+ GEL: "₾",
53
+ GGP: "£",
54
+ GHS: "₵",
55
+ GIP: "£",
56
+ GMD: "D",
57
+ GNF: "Fr",
58
+ GTQ: "Q",
59
+ GYD: "$",
60
+ HKD: "$",
61
+ HNL: "L",
62
+ HRK: "kn",
63
+ HTG: "G",
64
+ HUF: "Ft",
65
+ IDR: "Rp",
66
+ ILS: "₪",
67
+ IMP: "£",
68
+ INR: "₹",
69
+ IQD: "د.ع",
70
+ IRR: "﷼",
71
+ IRT: "تومان",
72
+ ISK: "kr.",
73
+ JEP: "£",
74
+ JMD: "$",
75
+ JOD: "د.ا",
76
+ JPY: "¥",
77
+ KES: "KSh",
78
+ KGS: "сом",
79
+ KHR: "៛",
80
+ KMF: "Fr",
81
+ KPW: "₩",
82
+ KRW: "₩",
83
+ KWD: "د.ك",
84
+ KYD: "$",
85
+ KZT: "₸",
86
+ LAK: "₭",
87
+ LBP: "ل.ل",
88
+ LKR: "රු",
89
+ LRD: "$",
90
+ LSL: "L",
91
+ LYD: "د.ل",
92
+ MAD: "د.م.",
93
+ MDL: "MDL",
94
+ MGA: "Ar",
95
+ MKD: "ден",
96
+ MMK: "Ks",
97
+ MNT: "₮",
98
+ MOP: "P",
99
+ MRU: "UM",
100
+ MUR: "₨",
101
+ MVR: ".ރ",
102
+ MWK: "MK",
103
+ MXN: "$",
104
+ MYR: "RM",
105
+ MZN: "MT",
106
+ NAD: "N$",
107
+ NGN: "₦",
108
+ NIO: "C$",
109
+ NOK: "kr",
110
+ NPR: "₨",
111
+ NZD: "$",
112
+ OMR: "ر.ع.",
113
+ PAB: "B/.",
114
+ PEN: "S/",
115
+ PGK: "K",
116
+ PHP: "₱",
117
+ PKR: "₨",
118
+ PLN: "zł",
119
+ PRB: "р.",
120
+ PYG: "₲",
121
+ QAR: "ر.ق",
122
+ RON: "lei",
123
+ RSD: "рсд",
124
+ RUB: "₽",
125
+ RWF: "Fr",
126
+ SAR: "ر.س",
127
+ SBD: "$",
128
+ SCR: "₨",
129
+ SDG: "ج.س.",
130
+ SEK: "kr",
131
+ SGD: "$",
132
+ SHP: "£",
133
+ SLL: "Le",
134
+ SOS: "Sh",
135
+ SRD: "$",
136
+ SSP: "£",
137
+ STN: "Db",
138
+ SYP: "ل.س",
139
+ SZL: "E",
140
+ THB: "฿",
141
+ TJS: "ЅМ",
142
+ TMT: "m",
143
+ TND: "د.ت",
144
+ TOP: "T$",
145
+ TRY: "₺",
146
+ TTD: "$",
147
+ TWD: "NT$",
148
+ TZS: "Sh",
149
+ UAH: "₴",
150
+ UGX: "UGX",
151
+ USD: "$",
152
+ UYU: "$",
153
+ UZS: "UZS",
154
+ VEF: "Bs F",
155
+ VES: "Bs.S",
156
+ VND: "₫",
157
+ VUV: "Vt",
158
+ WST: "T",
159
+ XAF: "CFA",
160
+ XCD: "$",
161
+ XOF: "CFA",
162
+ XPF: "Fr",
163
+ YER: "﷼",
164
+ ZAR: "R",
165
+ ZMW: "ZK",
166
+ };
package/src/customers.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  CustomerServiceError, type Customer, type CustomerAddress, type CustomerInput, type CustomerPage, type CustomerPatch, type SyncContext,
3
3
  } from '@tallyui/core';
4
- import { checkResponse } from './replication/products';
4
+ import { checkResponse, WCPOS_UUID_META_KEY } from './replication/products';
5
5
 
6
6
  type WooCustomerRow = {
7
7
  id: number | string;
@@ -9,10 +9,8 @@ type WooCustomerRow = {
9
9
  last_name?: string | null;
10
10
  email?: string | null;
11
11
  date_created_gmt?: string | null;
12
- billing?: {
13
- first_name?: string | null; last_name?: string | null; email?: string | null;
14
- phone?: string | null; company?: string | null;
15
- } | null;
12
+ billing?: WooAddressRow | null;
13
+ shipping?: Omit<WooAddressRow, 'email'> | null;
16
14
  meta_data?: { key?: string; value?: unknown }[];
17
15
  _rxdb_revision?: unknown;
18
16
  };
@@ -24,6 +22,18 @@ const WOO_ADDRESS = [
24
22
  ['email', 'email'], ['phone', 'phone'],
25
23
  ] as const;
26
24
 
25
+ type WooAddressRow = { [key in (typeof WOO_ADDRESS)[number][0]]?: string | null };
26
+
27
+ /** The inverse of toWooAddress: the non-empty fields of a read Woo address, or undefined when none is left. */
28
+ function fromWooAddress(raw: WooAddressRow | null | undefined, kind: 'billing' | 'shipping'): CustomerAddress | undefined {
29
+ const address: CustomerAddress = {};
30
+ for (const [key, field] of WOO_ADDRESS) {
31
+ const value: unknown = raw?.[key];
32
+ if ((kind === 'billing' || key !== 'email') && typeof value === 'string' && value.length > 0) address[field] = value;
33
+ }
34
+ return Object.keys(address).length > 0 ? address : undefined;
35
+ }
36
+
27
37
  /** The whole Woo address, '' for an absent field, so a patch replaces the stored address rather than merging into it. */
28
38
  function toWooAddress(address: CustomerAddress, kind: 'billing' | 'shipping'): Record<string, string> {
29
39
  return Object.fromEntries(WOO_ADDRESS.filter(([key]) => kind === 'billing' || key !== 'email')
@@ -57,6 +67,10 @@ export function toWooCustomer(raw: WooCustomerRow): Customer {
57
67
  ] as const) {
58
68
  if (typeof value === 'string' && value.length > 0) customer[key] = value;
59
69
  }
70
+ const billing = fromWooAddress(raw.billing, 'billing');
71
+ if (billing) customer.billing = billing;
72
+ const shipping = fromWooAddress(raw.shipping, 'shipping');
73
+ if (shipping) customer.shipping = shipping;
60
74
  const created = raw.date_created_gmt; // UTC without a zone suffix; `date_created` is site-local
61
75
  if (typeof created === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/.test(created)) customer.createdAt = `${created}Z`;
62
76
  customer.name = [customer.firstName, customer.lastName].filter(Boolean).join(' ') || customer.company || customer.email || customer.id;
@@ -92,6 +106,13 @@ export async function customerRequest(context: SyncContext, route: string, init:
92
106
 
93
107
  export function createWooCustomers(options?: { newId?: () => string }) {
94
108
  const newId = options?.newId ?? newWooId;
109
+ /** The one customer row with this numeric id (any role), or undefined when the store has none. */
110
+ const readCustomerRow = async (context: SyncContext, id: string): Promise<WooCustomerRow | undefined> => {
111
+ const params = new URLSearchParams({ include: id, per_page: '1', role: 'all' });
112
+ const { body } = await customerRequest(context, `customers?${params}`, { method: 'GET' });
113
+ if (!Array.isArray(body)) throw new CustomerServiceError('server', 'unexpected response');
114
+ return body.find((row: WooCustomerRow) => String(row.id) === id);
115
+ };
95
116
  const api = {
96
117
  async searchCustomers(context: SyncContext, query: string, options?: { limit?: number }): Promise<Customer[]> {
97
118
  return (await api.searchCustomersPage(context, query, { limit: options?.limit })).customers;
@@ -117,10 +138,7 @@ export function createWooCustomers(options?: { newId?: () => string }) {
117
138
 
118
139
  async getCustomer(context: SyncContext, id: string): Promise<Customer | null> {
119
140
  if (!/^\d+$/.test(id)) return null;
120
- const params = new URLSearchParams({ include: id, per_page: '1', role: 'all' });
121
- const { body } = await customerRequest(context, `customers?${params}`, { method: 'GET' });
122
- if (!Array.isArray(body)) throw new CustomerServiceError('server', 'unexpected response');
123
- const raw = body.find((row: WooCustomerRow) => String(row.id) === id);
141
+ const raw = await readCustomerRow(context, id);
124
142
  return raw ? toWooCustomer(raw) : null;
125
143
  },
126
144
 
@@ -150,12 +168,9 @@ export function createWooCustomers(options?: { newId?: () => string }) {
150
168
  async updateCustomer(context: SyncContext, id: string, patch: CustomerPatch): Promise<Customer> {
151
169
  if (!/^\d+$/.test(id)) throw new CustomerServiceError('invalid', 'Unknown customer');
152
170
  if (patch.shipping?.email) throw new CustomerServiceError('invalid', 'WooCommerce shipping addresses have no email');
153
- const params = new URLSearchParams({ include: id, per_page: '1', role: 'all' });
154
- const { body: rows } = await customerRequest(context, `customers?${params}`, { method: 'GET' });
155
- if (!Array.isArray(rows)) throw new CustomerServiceError('server', 'unexpected response');
156
- const row: WooCustomerRow | undefined = rows.find((raw: WooCustomerRow) => String(raw.id) === id);
171
+ const row = await readCustomerRow(context, id);
157
172
  if (!row) throw new CustomerServiceError('invalid', 'Unknown customer');
158
- const uuid = row.meta_data?.find((entry) => entry.key === '_woocommerce_pos_uuid')?.value;
173
+ const uuid = row.meta_data?.find((entry) => entry.key === WCPOS_UUID_META_KEY)?.value;
159
174
  if (typeof uuid !== 'string' || !uuid) throw new CustomerServiceError('server', 'unexpected response');
160
175
  const payload = toWooPatch(patch);
161
176
  if (Object.keys(payload).length === 0) return toWooCustomer(row);