@tallyui/connector-woocommerce 3.20.1 → 4.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -3
- package/dist/index.d.ts +40 -11
- package/dist/index.js +943 -156
- package/package.json +4 -5
- package/src/closures.ts +184 -0
- package/src/commands/http.ts +37 -0
- package/src/commands/register-transport.ts +212 -0
- package/src/commands/transport.ts +167 -74
- package/src/currency-symbols.ts +166 -0
- package/src/customers.ts +29 -14
- package/src/index.ts +8 -2
- package/src/orders.ts +59 -10
- package/src/payment-methods.ts +4 -3
- package/src/registers.ts +55 -0
- package/src/replication/products.ts +7 -3
- package/src/schemas/products.ts +7 -2
- package/src/store-settings.ts +71 -25
- package/src/traits/product.ts +2 -0
- package/src/unauthorized.ts +8 -0
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
// ADR-073; M3-spike-paid-push.md proves paid order pushes against WCPOS 1.10.20.
|
|
2
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;
|
|
@@ -84,11 +99,21 @@ function wooAddress(address: OrderAddress | undefined): Record<string, string> {
|
|
|
84
99
|
return Object.fromEntries(WOO_ADDRESS_KEYS.flatMap(([ours, theirs]) => typeof address?.[ours] === 'string' ? [[theirs, address[ours]]] : []));
|
|
85
100
|
}
|
|
86
101
|
|
|
87
|
-
export function toWooOrderPayload(envelope: OrderCreateEnvelope, local?: WooLocalOrder, options?: { paymentsList?: boolean }): { payload: Record<string, unknown
|
|
102
|
+
export function toWooOrderPayload(envelope: OrderCreateEnvelope, local?: WooLocalOrder, options?: { paymentsList?: boolean; ledger?: boolean }): { payload: Record<string, unknown>; money?: WooMoneyCommand[] } | { error: { code: string; message: string } } {
|
|
88
103
|
const p = envelope.payload;
|
|
89
104
|
if (p.payments.length === 0 || (p.payments.length > 1 && !options?.paymentsList)) {
|
|
90
105
|
return { error: { code: 'invalid_payload', message: 'WooCommerce orders take one payment.' } };
|
|
91
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
|
+
}
|
|
92
117
|
if (p.payments.length > 20) {
|
|
93
118
|
return { error: { code: 'invalid_payload', message: 'WooCommerce records at most 20 payments.' } };
|
|
94
119
|
}
|
|
@@ -100,8 +125,8 @@ export function toWooOrderPayload(envelope: OrderCreateEnvelope, local?: WooLoca
|
|
|
100
125
|
return { error: { code: 'invalid_payload', message: `Line ${line.clientLineId} has no WooCommerce product id.` } };
|
|
101
126
|
}
|
|
102
127
|
}
|
|
103
|
-
const digits =
|
|
104
|
-
const major = (minor: number) => (minor
|
|
128
|
+
const digits = wooDigits(p);
|
|
129
|
+
const major = (minor: number) => wooMajor(minor, digits);
|
|
105
130
|
const inclusiveNet = (netMicros: string | undefined, id: string) => {
|
|
106
131
|
if (netMicros === undefined) {
|
|
107
132
|
return { error: { code: 'unsupported_tax_mode', message: "Tax-inclusive prices need the till's WooCommerce tax figures; update the till." } };
|
|
@@ -116,24 +141,30 @@ export function toWooOrderPayload(envelope: OrderCreateEnvelope, local?: WooLoca
|
|
|
116
141
|
const micros = net / divisor;
|
|
117
142
|
return `${micros / 1000000n}.${(micros % 1000000n).toString().padStart(6, '0')}`;
|
|
118
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);
|
|
119
148
|
const line_items = [];
|
|
120
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);
|
|
121
152
|
let total = major(line.unitPriceMinor * line.quantity - (line.discountMinor ?? 0));
|
|
122
153
|
let subtotal = total;
|
|
123
|
-
if (
|
|
124
|
-
const net = inclusiveNet(
|
|
154
|
+
if (inclusive) {
|
|
155
|
+
const net = inclusiveNet(stored?.netMicros, line.clientLineId);
|
|
125
156
|
if (typeof net !== 'string') return net;
|
|
126
157
|
subtotal = total = net;
|
|
127
158
|
}
|
|
128
159
|
const custom = line.custom;
|
|
129
160
|
let price = major(line.unitPriceMinor);
|
|
130
161
|
if (p.coupons?.length) {
|
|
131
|
-
const discount =
|
|
132
|
-
?
|
|
162
|
+
const discount = inclusive && (line.discountMinor ?? 0) > 0
|
|
163
|
+
? stored?.discountMinor : line.discountMinor ?? 0;
|
|
133
164
|
if (discount === undefined) return { error: { code: 'unsupported_tax_mode', message: "Tax-inclusive prices need the till's WooCommerce tax figures; update the till." } };
|
|
134
165
|
const quantity = BigInt(line.quantity), minor = BigInt(line.unitPriceMinor) * quantity - BigInt(discount);
|
|
135
|
-
if (
|
|
136
|
-
const net = inclusiveNet(preCouponNetMicros(minor, digits,
|
|
166
|
+
if (inclusive) {
|
|
167
|
+
const net = inclusiveNet(preCouponNetMicros(minor, digits, stored), line.clientLineId);
|
|
137
168
|
if (typeof net !== 'string') return net;
|
|
138
169
|
subtotal = total = net;
|
|
139
170
|
}
|
|
@@ -157,21 +188,22 @@ export function toWooOrderPayload(envelope: OrderCreateEnvelope, local?: WooLoca
|
|
|
157
188
|
}
|
|
158
189
|
const fee_lines = [], shipping_lines = [];
|
|
159
190
|
for (const fee of p.fees ?? []) {
|
|
160
|
-
const total =
|
|
161
|
-
? 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);
|
|
162
192
|
if (typeof total !== 'string') return total;
|
|
163
193
|
fee_lines.push({ name: fee.name, total, tax_status: fee.taxStatus, tax_class: fee.taxClass ?? '' });
|
|
164
194
|
}
|
|
165
195
|
for (const shipping of p.shipping ?? []) {
|
|
166
|
-
const total =
|
|
167
|
-
|
|
196
|
+
const total = chargeTotal(shipping.amountMinor,
|
|
197
|
+
local?.shipping?.find((stored) => stored.id === shipping.clientShippingId)?.netMicros, shipping.clientShippingId);
|
|
168
198
|
if (typeof total !== 'string') return total;
|
|
169
|
-
|
|
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' }) }] } : {}) });
|
|
170
202
|
}
|
|
171
203
|
const primary = p.payments.reduce((largest, payment) => payment.amountMinor > largest.amountMinor ? payment : largest);
|
|
172
204
|
const cash = primary.method === 'cash';
|
|
173
|
-
const meta_data = [{ key:
|
|
174
|
-
if (p.payments.length > 1) {
|
|
205
|
+
const meta_data = [{ key: WCPOS_UUID_META_KEY, value: p.clientOrderId }];
|
|
206
|
+
if (p.payments.length > 1 && !ledger) {
|
|
175
207
|
meta_data.push({ key: '_woocommerce_pos_payments', value: JSON.stringify(p.payments.map((payment) => ({
|
|
176
208
|
method: payment.method === 'cash' ? 'pos_cash' : 'pos_card',
|
|
177
209
|
title: payment.method === 'cash' ? 'Cash' : 'Card', amount: major(payment.amountMinor),
|
|
@@ -184,9 +216,23 @@ export function toWooOrderPayload(envelope: OrderCreateEnvelope, local?: WooLoca
|
|
|
184
216
|
if (p.taxAddress) meta_data.push({ key: '_woocommerce_pos_tax_based_on', value: p.taxAddress });
|
|
185
217
|
const billing = { ...(p.customer?.email ? { email: p.customer.email } : {}), ...(p.taxAddress ? wooAddress(p.customer?.billing) : {}) };
|
|
186
218
|
const shipping = p.taxAddress && p.customer?.shipping ? wooAddress(p.customer.shipping) : undefined;
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
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
|
+
}),
|
|
190
236
|
line_items,
|
|
191
237
|
...(fee_lines.length ? { fee_lines } : {}),
|
|
192
238
|
...(shipping_lines.length ? { shipping_lines } : {}),
|
|
@@ -200,18 +246,33 @@ export function toWooOrderPayload(envelope: OrderCreateEnvelope, local?: WooLoca
|
|
|
200
246
|
} };
|
|
201
247
|
}
|
|
202
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
|
+
|
|
203
254
|
export function createWooCommandTransport(options: WooCommandTransportOptions): {
|
|
204
255
|
send(batch: OrderCreateEnvelope[], context?: { local?: { orders?: ReadonlyMap<string, WooLocalOrder> } }): Promise<WooTransportOutcome>;
|
|
205
256
|
} {
|
|
206
|
-
const
|
|
207
|
-
|
|
208
|
-
|
|
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
|
+
};
|
|
209
269
|
return {
|
|
210
270
|
async send(batch, context) {
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
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);
|
|
215
276
|
const results: CommandResult[] = [];
|
|
216
277
|
for (const envelope of batch) {
|
|
217
278
|
if (envelope.payload.coupons?.length && !coupons) {
|
|
@@ -220,66 +281,98 @@ export function createWooCommandTransport(options: WooCommandTransportOptions):
|
|
|
220
281
|
data: { storeCode: 'coupons_unsupported' } } });
|
|
221
282
|
continue;
|
|
222
283
|
}
|
|
223
|
-
const mapped = toWooOrderPayload(envelope, context?.local?.orders?.get(envelope.id), { paymentsList });
|
|
284
|
+
const mapped = toWooOrderPayload(envelope, context?.local?.orders?.get(envelope.id), { paymentsList, ledger });
|
|
224
285
|
if ('error' in mapped) {
|
|
225
286
|
results.push({ id: envelope.id, status: 'rejected', error: mapped.error });
|
|
226
287
|
continue;
|
|
227
288
|
}
|
|
228
|
-
const controller = new AbortController();
|
|
229
|
-
const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? 30000);
|
|
230
289
|
let outcome: WooTransportOutcome;
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
const
|
|
243
|
-
|
|
244
|
-
})
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
const totalMinor =
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
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;
|
|
261
330
|
continue;
|
|
262
331
|
}
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
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
|
+
}] } : {}) });
|
|
268
342
|
continue;
|
|
269
|
-
} else if (status ===
|
|
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).
|
|
270
355
|
results.push({ id: envelope.id, status: 'rejected', error: {
|
|
271
|
-
code: status === 400 &&
|
|
272
|
-
message: body?.message ?? `status_${status}`,
|
|
273
|
-
|
|
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 } : {}) } } });
|
|
274
359
|
continue;
|
|
275
|
-
} else {
|
|
276
|
-
outcome = { kind: 'refused', status, reason: body?.message ?? body?.code ?? `status_${status}` };
|
|
277
360
|
}
|
|
278
361
|
}
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
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}` };
|
|
283
376
|
}
|
|
284
377
|
return results.length ? { kind: 'results', results } : outcome;
|
|
285
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
|
-
|
|
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
|
|
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
|
|
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 ===
|
|
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);
|