@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
package/src/index.ts
CHANGED
|
@@ -11,6 +11,8 @@ import { createWooCouponFeed, wooCouponReconcile } from './reconcile/coupons';
|
|
|
11
11
|
import { createWooCustomers } from './customers';
|
|
12
12
|
import { createWooOrders, WOO_ORDER_FILTERS } from './orders';
|
|
13
13
|
import { wooStoreSettings, readWooCapabilities } from './store-settings';
|
|
14
|
+
import { wooListRegisters } from './registers';
|
|
15
|
+
import { wooClosures } from './closures';
|
|
14
16
|
import { wooPaymentMethods } from './payment-methods';
|
|
15
17
|
import { wooReceiptTemplates } from './receipt-templates';
|
|
16
18
|
import { version } from '../package.json';
|
|
@@ -81,6 +83,8 @@ const wooConnectorParts = {
|
|
|
81
83
|
storeSettings: wooStoreSettings,
|
|
82
84
|
paymentMethods: wooPaymentMethods,
|
|
83
85
|
capabilities: readWooCapabilities,
|
|
86
|
+
listRegisters: wooListRegisters,
|
|
87
|
+
closures: wooClosures,
|
|
84
88
|
receiptTemplates: wooReceiptTemplates,
|
|
85
89
|
|
|
86
90
|
auth: {
|
|
@@ -107,8 +111,8 @@ const wooConnectorParts = {
|
|
|
107
111
|
return {
|
|
108
112
|
Authorization: `Bearer ${credentials.token}`,
|
|
109
113
|
'X-WCPOS': '1',
|
|
110
|
-
// WCPOS 2.0 refuses a POS request below protocol
|
|
111
|
-
'X-WCPOS-Protocol': '
|
|
114
|
+
// WCPOS 2.0.4 refuses a POS request below protocol 3 with HTTP 426 (Services/Protocol_Gate.php:15-17).
|
|
115
|
+
'X-WCPOS-Protocol': '3',
|
|
112
116
|
// For WCPOS's consent-gated telemetry only.
|
|
113
117
|
'X-WCPOS-Client': `tallyui/${wcposClientPart(version)}`,
|
|
114
118
|
};
|
|
@@ -140,6 +144,8 @@ export { wooStoreSettings, readWooCapabilities, WOO_ORDER_CREATE_VERSION, WOO_NO
|
|
|
140
144
|
export { createWooCustomers, toWooCustomer } from './customers';
|
|
141
145
|
export { createWooOrders, toWooStoreOrder } from './orders';
|
|
142
146
|
export { createWooCommandTransport, toWooOrderPayload, type WooCommandTransportOptions } from './commands/transport';
|
|
147
|
+
export { createWooRegisterTransport, wooApproveSession, type WooRegisterTransportOptions } from './commands/register-transport';
|
|
148
|
+
export type { ApproverCredentials } from '@tallyui/core';
|
|
143
149
|
export { ConnectorUnauthorizedError } from '@tallyui/core';
|
|
144
150
|
export { wooProductSchema } from './schemas/products';
|
|
145
151
|
export { wooCouponSchema } from './schemas/coupons';
|
package/src/orders.ts
CHANGED
|
@@ -4,6 +4,7 @@ import {
|
|
|
4
4
|
} from '@tallyui/core';
|
|
5
5
|
import { customerRequest } from './customers';
|
|
6
6
|
import { wooMinorFromDecimal } from './commands/transport';
|
|
7
|
+
import { WCPOS_UUID_META_KEY } from './replication/products';
|
|
7
8
|
|
|
8
9
|
type Row = Record<string, unknown>;
|
|
9
10
|
|
|
@@ -42,12 +43,45 @@ function decimalSumMinor(a: unknown, b: unknown, currency: string): number {
|
|
|
42
43
|
const grossTax = (net: unknown, tax: unknown, currency: string) => decimalSumMinor(net, tax, currency) - minor(net, currency);
|
|
43
44
|
|
|
44
45
|
function posUuid(metaData: unknown): string | undefined {
|
|
45
|
-
const entry = rows(metaData).find((meta) => meta.key ===
|
|
46
|
+
const entry = rows(metaData).find((meta) => meta.key === WCPOS_UUID_META_KEY && nonEmpty(meta.value));
|
|
46
47
|
return entry ? (entry.value as string) : undefined;
|
|
47
48
|
}
|
|
48
49
|
|
|
49
50
|
const PAYMENT_KINDS: Record<string, PaymentMethodKind> = { pos_cash: 'cash', pos_card: 'external' };
|
|
50
51
|
|
|
52
|
+
/** The `_wcpos_payments` ledger: absent, readable (schema 1 with a payments array), or present but unreadable. */
|
|
53
|
+
function paymentLedger(metaData: unknown): { present: boolean; payments: unknown[] | null } {
|
|
54
|
+
const entry = rows(metaData).find((meta) => meta.key === '_wcpos_payments');
|
|
55
|
+
if (!entry) return { present: false, payments: null };
|
|
56
|
+
const value = entry.value;
|
|
57
|
+
return { present: true, payments: isRow(value) && value.schema === 1 && Array.isArray(value.payments) ? value.payments : null };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Captured rows are the store's counting rule; with none, its paid state decides, as its balance and reopen adoption do. */
|
|
61
|
+
function storePayments(raw: Row, currency: string, totalMinor: number): StoreOrder['payments'] {
|
|
62
|
+
const { payments } = paymentLedger(raw.meta_data);
|
|
63
|
+
const captured = payments ? rows(payments).filter((row) => row.status === 'captured') : [];
|
|
64
|
+
if (captured.length) {
|
|
65
|
+
const title = captured.every((row) => row.method_id === raw.payment_method) ? nonEmpty(raw.payment_method_title) : undefined;
|
|
66
|
+
return captured.map((row) => {
|
|
67
|
+
const method = nonEmpty(row.method_id);
|
|
68
|
+
if (!method || (typeof row.currency === 'string' && row.currency !== currency)) throw unexpected();
|
|
69
|
+
const kind = PAYMENT_KINDS[method];
|
|
70
|
+
const id = nonEmpty(row.id);
|
|
71
|
+
return {
|
|
72
|
+
...(id ? { id } : {}),
|
|
73
|
+
method, ...(title ? { title } : {}), ...(kind ? { kind } : {}), amountMinor: minor(row.amount, currency),
|
|
74
|
+
};
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
const method = nonEmpty(raw.payment_method);
|
|
78
|
+
const title = nonEmpty(raw.payment_method_title);
|
|
79
|
+
const kind = method ? PAYMENT_KINDS[method] : undefined;
|
|
80
|
+
return method && (nonEmpty(raw.date_paid_gmt) || nonEmpty(raw.date_paid)) ? [{
|
|
81
|
+
method, ...(title ? { title } : {}), ...(kind ? { kind } : {}), amountMinor: totalMinor,
|
|
82
|
+
}] : [];
|
|
83
|
+
}
|
|
84
|
+
|
|
51
85
|
/** Maps a WooCommerce order resource (as WCPOS `wcpos/v2/orders` serves it) to a `StoreOrder` (ADR-081). */
|
|
52
86
|
export function toWooStoreOrder(raw: unknown): StoreOrder {
|
|
53
87
|
if (!isRow(raw) || raw.id === undefined || raw.id === null || typeof raw.currency !== 'string' || typeof raw.date_created_gmt !== 'string') {
|
|
@@ -67,15 +101,16 @@ export function toWooStoreOrder(raw: unknown): StoreOrder {
|
|
|
67
101
|
: null;
|
|
68
102
|
|
|
69
103
|
const clientOrderId = posUuid(raw.meta_data);
|
|
104
|
+
const revision = nonEmpty(raw._rxdb_revision);
|
|
70
105
|
const totalMinor = minor(raw.total, currency);
|
|
71
|
-
const
|
|
72
|
-
const
|
|
73
|
-
const paymentKind = paymentMethod ? PAYMENT_KINDS[paymentMethod] : undefined;
|
|
106
|
+
const ledger = paymentLedger(raw.meta_data);
|
|
107
|
+
const paymentRecordUnreadable = ledger.present && ledger.payments === null;
|
|
74
108
|
|
|
75
109
|
return {
|
|
76
110
|
id: String(raw.id),
|
|
77
111
|
reference: String(raw.number ?? raw.id),
|
|
78
112
|
...(clientOrderId ? { clientOrderId } : {}),
|
|
113
|
+
...(revision ? { revision } : {}),
|
|
79
114
|
status: String(raw.status),
|
|
80
115
|
placedAt: placed.toISOString(),
|
|
81
116
|
currency,
|
|
@@ -101,9 +136,15 @@ export function toWooStoreOrder(raw: unknown): StoreOrder {
|
|
|
101
136
|
};
|
|
102
137
|
}),
|
|
103
138
|
fees: rows(raw.fee_lines).map((fee) => ({
|
|
139
|
+
...(positiveId(fee.id) ? { id: positiveId(fee.id) } : {}),
|
|
140
|
+
...(fee.tax_status === 'taxable' || fee.tax_status === 'none' ? { taxStatus: fee.tax_status } : {}),
|
|
141
|
+
...(nonEmpty(fee.tax_class) ? { taxClass: nonEmpty(fee.tax_class) } : {}),
|
|
104
142
|
name: String(fee.name), totalMinor: minor(fee.total, currency), taxMinor: grossTax(fee.total, fee.total_tax, currency),
|
|
105
143
|
})),
|
|
106
144
|
shipping: rows(raw.shipping_lines).map((line) => ({
|
|
145
|
+
...(positiveId(line.id) ? { id: positiveId(line.id) } : {}),
|
|
146
|
+
...(line.tax_status === 'taxable' || line.tax_status === 'none' ? { taxStatus: line.tax_status } : {}),
|
|
147
|
+
...(nonEmpty(line.method_id) ? { methodId: nonEmpty(line.method_id) } : {}),
|
|
107
148
|
name: String(line.method_title), totalMinor: minor(line.total, currency), taxMinor: grossTax(line.total, line.total_tax, currency),
|
|
108
149
|
})),
|
|
109
150
|
coupons: rows(raw.coupon_lines).map((coupon) => ({
|
|
@@ -124,9 +165,8 @@ export function toWooStoreOrder(raw: unknown): StoreOrder {
|
|
|
124
165
|
discountTaxMinor: minor(raw.discount_tax, currency),
|
|
125
166
|
taxMinor: minor(raw.total_tax, currency),
|
|
126
167
|
totalMinor,
|
|
127
|
-
payments:
|
|
128
|
-
|
|
129
|
-
}] : [],
|
|
168
|
+
payments: storePayments(raw, currency, totalMinor),
|
|
169
|
+
...(paymentRecordUnreadable ? { paymentRecordUnreadable: true } : {}),
|
|
130
170
|
refunds: rows(raw.refunds).map((refund) => {
|
|
131
171
|
const reason = nonEmpty(refund.reason);
|
|
132
172
|
return { id: String(refund.id), amountMinor: Math.abs(minor(refund.total, currency)), ...(reason ? { reason } : {}) };
|
|
@@ -175,14 +215,23 @@ export function createWooOrders(): Required<Pick<TallyConnector, 'listOrders' |
|
|
|
175
215
|
if (before !== undefined) params.set('before', wooGmtSecond(before, 0));
|
|
176
216
|
const { body, headers } = await customerRequest(context, `orders?${params}`, { method: 'GET' });
|
|
177
217
|
if (!Array.isArray(body)) throw unexpected();
|
|
178
|
-
|
|
218
|
+
let unreadable = 0;
|
|
219
|
+
const orders = body.flatMap((row) => {
|
|
220
|
+
try {
|
|
221
|
+
return [toWooStoreOrder(row)];
|
|
222
|
+
} catch (error) {
|
|
223
|
+
if (!(error instanceof CustomerServiceError)) throw error;
|
|
224
|
+
unreadable += 1;
|
|
225
|
+
return [];
|
|
226
|
+
}
|
|
227
|
+
});
|
|
179
228
|
const totalPages = headers.get('X-WP-TotalPages');
|
|
180
229
|
const hasMore = totalPages !== null && /^\d+$/.test(totalPages.trim())
|
|
181
230
|
? page < Number.parseInt(totalPages, 10)
|
|
182
|
-
:
|
|
231
|
+
: body.length === perPage;
|
|
183
232
|
// X-WP-Total counts every order the query matches.
|
|
184
233
|
const total = headers.get('X-WP-Total');
|
|
185
|
-
return { orders, hasMore, ...(total && /^\d+$/.test(total) ? { total: Number(total) } : {}) };
|
|
234
|
+
return { orders, hasMore, ...(unreadable ? { unreadable } : {}), ...(total && /^\d+$/.test(total) ? { total: Number(total) } : {}) };
|
|
186
235
|
},
|
|
187
236
|
|
|
188
237
|
async getOrders(context: SyncContext, ids: readonly string[]) {
|
package/src/payment-methods.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { defaultPaymentMethods } from '@tallyui/core';
|
|
2
2
|
import type { CaptureModeEntry, PaymentHardware, PaymentMethodDescriptor, PaymentRounding, SyncContext } from '@tallyui/core';
|
|
3
3
|
|
|
4
4
|
import { wooMinorFromDecimal } from './commands/transport';
|
|
5
|
+
import { throwIfUnauthorized } from './unauthorized';
|
|
5
6
|
|
|
6
7
|
// The plugin's own default `order` for a gateway without one (woocommerce-pos Descriptor_Builder.php).
|
|
7
8
|
const WOO_DEFAULT_ORDER = 999;
|
|
@@ -42,7 +43,7 @@ function hasMoneyString(row: WireRow): boolean {
|
|
|
42
43
|
async function storeCurrency(context: SyncContext): Promise<string> {
|
|
43
44
|
// Any failure but a refusal is "no store currency".
|
|
44
45
|
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/stores`, { method: 'GET', headers: context.headers, signal: context.signal }).catch(() => undefined);
|
|
45
|
-
|
|
46
|
+
throwIfUnauthorized(response, 'stores');
|
|
46
47
|
const stores: unknown = response?.ok ? await response.json().catch(() => undefined) : undefined;
|
|
47
48
|
const currency = Array.isArray(stores) ? objectOr(stores[0]).currency : undefined;
|
|
48
49
|
if (typeof currency !== 'string') throw new Error('WooCommerce payment methods: no store currency');
|
|
@@ -101,7 +102,7 @@ export async function wooPaymentMethods(context: SyncContext): Promise<PaymentMe
|
|
|
101
102
|
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/payment-methods`, { method: 'GET', headers: context.headers, signal: context.signal });
|
|
102
103
|
// The route shipped in woocommerce-pos 2.0.0; an older plugin keeps today's two methods.
|
|
103
104
|
if (response.status === 404) return defaultPaymentMethods();
|
|
104
|
-
|
|
105
|
+
throwIfUnauthorized(response, 'payment methods');
|
|
105
106
|
if (!response.ok) throw new Error(`WooCommerce payment methods: HTTP ${response.status}`);
|
|
106
107
|
const body: unknown = await response.json();
|
|
107
108
|
if (!isObject(body) || !Number.isInteger(body.schema) || typeof body.contract !== 'string' || !Array.isArray(body.methods)) {
|
package/src/registers.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { RegisterInfo, SyncContext } from '@tallyui/core';
|
|
2
|
+
import { wooMinorFromDecimal } from './commands/transport';
|
|
3
|
+
import { throwIfUnauthorized } from './unauthorized';
|
|
4
|
+
|
|
5
|
+
/** The first store from `GET stores` and its currency, upper-cased. */
|
|
6
|
+
async function wooFirstStore(context: SyncContext): Promise<{ currency: string; store: Record<string, unknown> }> {
|
|
7
|
+
const init = { method: 'GET', headers: context.headers, signal: context.signal };
|
|
8
|
+
const storesResponse = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/stores`, init);
|
|
9
|
+
throwIfUnauthorized(storesResponse, 'stores');
|
|
10
|
+
if (!storesResponse.ok) throw new Error(`WooCommerce stores: HTTP ${storesResponse.status}`);
|
|
11
|
+
const stores = await storesResponse.json();
|
|
12
|
+
if (!Array.isArray(stores) || stores.length === 0) throw new Error('WooCommerce stores: expected a non-empty array');
|
|
13
|
+
// The first store only: a Pro multi-store site whose stores differ in currency is parsed with stores[0]'s digits (#1129 item 5; multi-store selection is AUDIT 213).
|
|
14
|
+
const store = stores[0];
|
|
15
|
+
if (typeof store?.currency !== 'string') throw new Error('WooCommerce stores: expected a currency');
|
|
16
|
+
return { currency: store.currency.toUpperCase(), store };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The store currency (`stores[0].currency`), upper-cased. */
|
|
20
|
+
export async function wooStoreCurrency(context: SyncContext): Promise<string> {
|
|
21
|
+
return (await wooFirstStore(context)).currency;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** WCPOS 2.0's registers (`GET registers`), with the float in the store currency's minor units; `[]` below 2.0 (no route). */
|
|
25
|
+
export async function wooListRegisters(context: SyncContext): Promise<RegisterInfo[]> {
|
|
26
|
+
const init = { method: 'GET', headers: context.headers, signal: context.signal };
|
|
27
|
+
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/registers`, init);
|
|
28
|
+
throwIfUnauthorized(response, 'registers');
|
|
29
|
+
if (response.status === 404) return [];
|
|
30
|
+
if (!response.ok) throw new Error(`WooCommerce registers: HTTP ${response.status}`);
|
|
31
|
+
|
|
32
|
+
// Only once the route answered, so a store without it never needs `stores`.
|
|
33
|
+
const { currency, store } = await wooFirstStore(context);
|
|
34
|
+
// WCPOS sets the close time per store; core reads it per register.
|
|
35
|
+
const closeTime = typeof store.expected_close_time === 'string' && /^\d{2}:\d{2}$/.test(store.expected_close_time)
|
|
36
|
+
? store.expected_close_time : undefined;
|
|
37
|
+
const rows = await response.json();
|
|
38
|
+
if (!Array.isArray(rows)) throw new Error('WooCommerce registers: expected an array');
|
|
39
|
+
// Every register, whatever its store_id: multi-store selection (AUDIT 213) is out of scope.
|
|
40
|
+
const registers: RegisterInfo[] = [];
|
|
41
|
+
for (const row of rows) {
|
|
42
|
+
if (typeof row?.id !== 'string' || row.id === '' || typeof row.name !== 'string' || row.name === '') {
|
|
43
|
+
console.warn('WooCommerce registers: skipping a register without an id or name');
|
|
44
|
+
continue;
|
|
45
|
+
}
|
|
46
|
+
const float = typeof row.default_float === 'string' ? wooMinorFromDecimal(row.default_float, currency) : undefined;
|
|
47
|
+
registers.push({
|
|
48
|
+
id: row.id,
|
|
49
|
+
name: row.name,
|
|
50
|
+
...(float !== undefined ? { defaultFloatMinor: float } : {}),
|
|
51
|
+
...(closeTime !== undefined ? { expectedCloseTime: closeTime } : {}),
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
return registers;
|
|
55
|
+
}
|
|
@@ -85,10 +85,10 @@ export function wooProductBarcode(product: any): string | undefined {
|
|
|
85
85
|
|
|
86
86
|
export function toVariationDocument(payload: any) {
|
|
87
87
|
const { id, sku, price, regular_price, sale_price, on_sale, stock_status,
|
|
88
|
-
stock_quantity, manage_stock, status, purchasable, tax_class, tax_status } = payload;
|
|
88
|
+
stock_quantity, low_stock_amount, manage_stock, backorders, status, purchasable, tax_class, tax_status } = payload;
|
|
89
89
|
return Object.fromEntries(Object.entries({
|
|
90
90
|
id, sku, barcode: wooProductBarcode(payload), price, regular_price, sale_price, on_sale,
|
|
91
|
-
stock_status, stock_quantity, manage_stock, status, purchasable,
|
|
91
|
+
stock_status, stock_quantity, low_stock_amount, manage_stock, backorders, status, purchasable,
|
|
92
92
|
tax_class, tax_status,
|
|
93
93
|
attributes: (payload.attributes ?? []).map(({ id, name, option }: any) => ({
|
|
94
94
|
...(typeof id === 'number' ? { id } : {}), name, option,
|
|
@@ -232,7 +232,11 @@ export const wooProductReplication: ReplicationAdapter<any, WooProductCheckpoint
|
|
|
232
232
|
});
|
|
233
233
|
await checkResponse(response);
|
|
234
234
|
const body = await response.json();
|
|
235
|
-
|
|
235
|
+
// WCPOS 2.0.x answers a bare array of variations; 1.10.x wraps each in a sync envelope under `documents`.
|
|
236
|
+
const docs = Array.isArray(body) ? body.map((payload: { parent_id?: number }) => ({ parent_id: payload.parent_id, payload }))
|
|
237
|
+
: Array.isArray(body?.documents) ? body.documents : undefined;
|
|
238
|
+
if (!docs) throw new Error(`Unexpected /variations response: ${JSON.stringify(body)?.slice(0, 100)}`);
|
|
239
|
+
for (const doc of docs) {
|
|
236
240
|
const parentId = doc.parent_id ?? doc.payload.parent_id;
|
|
237
241
|
const group = variations.get(parentId) ?? [];
|
|
238
242
|
group.push(toVariationDocument(doc.payload));
|
package/src/schemas/products.ts
CHANGED
|
@@ -7,7 +7,7 @@ import type { RxJsonSchema } from 'rxdb';
|
|
|
7
7
|
*/
|
|
8
8
|
export const wooProductSchema: RxJsonSchema<any> = {
|
|
9
9
|
title: 'WooCommerce Product',
|
|
10
|
-
version:
|
|
10
|
+
version: 4, // 3: backorders (A16); 4: low_stock_amount; a till resyncs its products once
|
|
11
11
|
type: 'object',
|
|
12
12
|
primaryKey: 'uuid',
|
|
13
13
|
properties: {
|
|
@@ -71,6 +71,9 @@ export const wooProductSchema: RxJsonSchema<any> = {
|
|
|
71
71
|
stock_quantity: {
|
|
72
72
|
type: ['number', 'null'],
|
|
73
73
|
},
|
|
74
|
+
low_stock_amount: {
|
|
75
|
+
type: ['number', 'null'],
|
|
76
|
+
},
|
|
74
77
|
stock_status: {
|
|
75
78
|
type: 'string',
|
|
76
79
|
default: 'instock',
|
|
@@ -81,6 +84,7 @@ export const wooProductSchema: RxJsonSchema<any> = {
|
|
|
81
84
|
type: 'boolean',
|
|
82
85
|
default: false,
|
|
83
86
|
},
|
|
87
|
+
backorders: { type: 'string' },
|
|
84
88
|
categories: {
|
|
85
89
|
type: 'array',
|
|
86
90
|
items: {
|
|
@@ -142,7 +146,8 @@ export const wooProductSchema: RxJsonSchema<any> = {
|
|
|
142
146
|
price: { type: 'string' }, regular_price: { type: 'string' }, sale_price: { type: 'string' },
|
|
143
147
|
tax_class: { type: 'string' }, tax_status: { type: 'string' },
|
|
144
148
|
on_sale: { type: 'boolean' }, stock_status: { type: 'string' }, stock_quantity: { type: ['number', 'null'] },
|
|
145
|
-
|
|
149
|
+
low_stock_amount: { type: ['number', 'null'] },
|
|
150
|
+
manage_stock: { type: 'boolean' }, backorders: { type: 'string' }, status: { type: 'string' }, purchasable: { type: 'boolean' },
|
|
146
151
|
attributes: { type: 'array', items: { type: 'object', properties: { name: { type: 'string' }, option: { type: 'string' } } } },
|
|
147
152
|
} } },
|
|
148
153
|
meta_data: {
|
package/src/store-settings.ts
CHANGED
|
@@ -1,51 +1,79 @@
|
|
|
1
1
|
import { ConnectorUnauthorizedError, StoreSettingsError, minorUnitDigits, woocommerceTax } from '@tallyui/core';
|
|
2
|
-
import type { ServerCapabilities, StoreSettings, SyncContext } from '@tallyui/core';
|
|
2
|
+
import type { MoneyFormat, ServerCapabilities, StoreSettings, SyncContext } from '@tallyui/core';
|
|
3
|
+
import { WOO_CURRENCY_SYMBOLS } from './currency-symbols';
|
|
4
|
+
import { throwIfUnauthorized } from './unauthorized';
|
|
3
5
|
|
|
4
|
-
/** The highest order.create version the WooCommerce transport maps without coupons: v4's net discounts, and v5's fees, shipping and custom lines (WCPOS push/orders; orders #146, #161).
|
|
6
|
+
/** The highest order.create version the WooCommerce transport maps without coupons: v4's net discounts, and v5's fees, shipping and custom lines (WCPOS push/orders; orders #146, #161). A store with coupons gets 8 (`WOO_TAX_ADDRESS_ORDER_CREATE_VERSION`): 6 adds coupons (ADR-077 d4a-woo), 7 the note, 8 the tax address. */
|
|
5
7
|
export const WOO_ORDER_CREATE_VERSION = 5;
|
|
6
8
|
/** Version 7 is version 6 plus the sale note (ADR-083), mapped to WooCommerce's customer_note; a store takes it wherever it takes 6. Version 6 is version 5 plus coupons: it needs both order_create_v5 and the coupons gate. */
|
|
7
9
|
export const WOO_NOTE_ORDER_CREATE_VERSION = 7;
|
|
8
10
|
/** Version 8 is version 7 plus the tax address and the customer's addresses (#722), sent as WCPOS's `_woocommerce_pos_tax_based_on`
|
|
9
11
|
* meta with the order's billing and shipping, which push/orders already passes through; a store takes it wherever it takes 7. */
|
|
10
12
|
export const WOO_TAX_ADDRESS_ORDER_CREATE_VERSION = 8;
|
|
11
|
-
// The order.create version a store gets unless /status lists order_create_v5,
|
|
13
|
+
// The order.create version a store gets unless /status lists order_create_v5 (TallyUI fork), /site reports stock 2.0.4+ on the 2.0 line (then 6) or, with no capabilities list, stock 1.10.20+ (then 7).
|
|
12
14
|
const WOO_BASE_ORDER_CREATE_VERSION = 3;
|
|
13
15
|
// The first woocommerce-pos release whose coupon recalculation keeps the POS price (ADR-077 amendment 4, R2: 1.9.0, 2026-05-15).
|
|
14
16
|
const WOO_COUPONS_MIN_PLUGIN: readonly [number, number, number] = [1, 9, 0];
|
|
17
|
+
// Stock 1.10.20 took order.create v3-v7 to the cent without capability flags (20 Nov stock proof; Front desk ruling, 2026-11-20).
|
|
18
|
+
const WOO_ORDER_LINES_FLOOR: readonly [number, number, number] = [1, 10, 20];
|
|
19
|
+
// The version route stops at 7: v8's tax address is unproven, stock /stores answers `base` (20 Nov stock proof; desk ruling).
|
|
20
|
+
const WOO_ORDER_LINES_VERSION_CAP = 7;
|
|
21
|
+
// Stock 2.0.4 took order.create v3-v6 without the order_create_v5 flag (20 Nov stock 2.0.4 proof; Front desk ruling, 2026-11-20).
|
|
22
|
+
const WOO_ORDER_LINES_20_FLOOR: readonly [number, number, number] = [2, 0, 4];
|
|
23
|
+
// The 2.0 route stops at 6: v7's note and v8's tax address were never sent (20 Nov stock 2.0.4 proof; desk ruling).
|
|
24
|
+
const WOO_ORDER_LINES_20_CAP = 6;
|
|
15
25
|
|
|
16
|
-
|
|
26
|
+
/** True when the version is at or above the floor; a prerelease of the floor itself is below it. */
|
|
27
|
+
function atLeast(version: unknown, floor: readonly [number, number, number]): boolean {
|
|
17
28
|
if (typeof version !== 'string') return false;
|
|
18
29
|
const match = /^(\d+)\.(\d+)(?:\.(\d+))?(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/.exec(version.trim());
|
|
19
30
|
if (!match) return false;
|
|
20
31
|
const parts: readonly [number, number, number] = [Number(match[1]), Number(match[2]), Number(match[3] ?? 0)];
|
|
21
32
|
for (let index = 0; index < parts.length; index++) {
|
|
22
|
-
if (parts[index] >
|
|
23
|
-
if (parts[index] <
|
|
33
|
+
if (parts[index] > floor[index]) return true;
|
|
34
|
+
if (parts[index] < floor[index]) return false;
|
|
24
35
|
}
|
|
25
36
|
return !match[4];
|
|
26
37
|
}
|
|
27
38
|
|
|
39
|
+
export function wooPluginSupportsCoupons(version: unknown): boolean {
|
|
40
|
+
return atLeast(version, WOO_COUPONS_MIN_PLUGIN);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** A plain `1.10.N` with N >= 20 and no prerelease or build suffix: the stock 1.10 line the version route serves. */
|
|
44
|
+
export function wooOnOrderLinesLine(version: unknown): boolean {
|
|
45
|
+
return typeof version === 'string' && /^1\.10\.\d+$/.test(version.trim()) && atLeast(version, WOO_ORDER_LINES_FLOOR);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** A plain `2.0.N` with N >= 4 and no prerelease or build suffix: the stock 2.0 line the version route serves, capped at 6. */
|
|
49
|
+
export function wooOnOrderLines20Line(version: unknown): boolean {
|
|
50
|
+
return typeof version === 'string' && /^2\.0\.\d+$/.test(version.trim()) && atLeast(version, WOO_ORDER_LINES_20_FLOOR);
|
|
51
|
+
}
|
|
52
|
+
|
|
28
53
|
export async function wooStoreSettings(context: SyncContext): Promise<StoreSettings> {
|
|
29
54
|
try {
|
|
30
55
|
const init = { method: 'GET', headers: context.headers, signal: context.signal };
|
|
31
56
|
const storesResponse = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/stores`, init);
|
|
32
|
-
|
|
33
|
-
throw new ConnectorUnauthorizedError(`WooCommerce stores: HTTP ${storesResponse.status}`, storesResponse.status);
|
|
34
|
-
}
|
|
57
|
+
throwIfUnauthorized(storesResponse, 'stores');
|
|
35
58
|
if (!storesResponse.ok) throw new Error(`WooCommerce stores: HTTP ${storesResponse.status}`);
|
|
36
59
|
const stores = await storesResponse.json();
|
|
37
60
|
if (!Array.isArray(stores) || stores.length === 0) throw new Error('WooCommerce stores: expected a non-empty array');
|
|
38
61
|
const store = stores[0];
|
|
39
62
|
const currency = store.currency.toUpperCase();
|
|
63
|
+
const moneyFormat: MoneyFormat = {
|
|
64
|
+
...(['left', 'right', 'left_space', 'right_space'].includes(store.currency_pos) ? { position: store.currency_pos } : {}),
|
|
65
|
+
...(typeof store.price_thousand_sep === 'string' ? { thousandSeparator: store.price_thousand_sep } : {}),
|
|
66
|
+
...(typeof store.price_decimal_sep === 'string' ? { decimalSeparator: store.price_decimal_sep } : {}),
|
|
67
|
+
...(Number.isInteger(store.price_num_decimals) && store.price_num_decimals >= 0 ? { decimals: store.price_num_decimals } : {}),
|
|
68
|
+
...(WOO_CURRENCY_SYMBOLS[currency] !== undefined ? { symbol: WOO_CURRENCY_SYMBOLS[currency] } : {}),
|
|
69
|
+
};
|
|
40
70
|
const digits = minorUnitDigits(currency);
|
|
41
71
|
if (typeof store.price_num_decimals === 'number' && store.price_num_decimals !== digits) {
|
|
42
72
|
console.warn(`WooCommerce price_num_decimals is ${store.price_num_decimals}; the till rounds ${currency} to ${digits} digits`);
|
|
43
73
|
}
|
|
44
74
|
|
|
45
75
|
const classesResponse = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/taxes/classes`, init);
|
|
46
|
-
|
|
47
|
-
throw new ConnectorUnauthorizedError(`WooCommerce tax classes: HTTP ${classesResponse.status}`, classesResponse.status);
|
|
48
|
-
}
|
|
76
|
+
throwIfUnauthorized(classesResponse, 'tax classes');
|
|
49
77
|
if (!classesResponse.ok) throw new Error(`WooCommerce tax classes: HTTP ${classesResponse.status}`);
|
|
50
78
|
const classes = await classesResponse.json();
|
|
51
79
|
if (!Array.isArray(classes)) throw new Error('WooCommerce tax classes: expected an array');
|
|
@@ -58,6 +86,8 @@ export async function wooStoreSettings(context: SyncContext): Promise<StoreSetti
|
|
|
58
86
|
pricesIncludeTax: store.prices_include_tax === 'yes',
|
|
59
87
|
taxRoundAtSubtotal: store.tax_round_at_subtotal === 'yes',
|
|
60
88
|
calcDiscountsSequentially: (store.woocommerce_calc_discounts_sequentially ?? store.calc_discounts_sequentially) === 'yes',
|
|
89
|
+
preventOverselling: store.prevent_overselling === true,
|
|
90
|
+
...(Object.keys(moneyFormat).length > 0 ? { moneyFormat } : {}),
|
|
61
91
|
...(typeof store.shipping_tax_class === 'string' ? { shippingTaxClass: store.shipping_tax_class } : {}),
|
|
62
92
|
taxClassSlugs: classes.map((row) => row.slug),
|
|
63
93
|
taxClasses: classes.map((row) => ({ slug: row.slug, name: typeof row.name === 'string' && row.name !== '' ? row.name : row.slug })),
|
|
@@ -71,9 +101,7 @@ export async function wooStoreSettings(context: SyncContext): Promise<StoreSetti
|
|
|
71
101
|
const rates: woocommerceTax.WooTaxRate[] = [];
|
|
72
102
|
for (let page = 1; page <= 100; page++) {
|
|
73
103
|
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/taxes?per_page=100&page=${page}&orderby=order&order=asc`, init);
|
|
74
|
-
|
|
75
|
-
throw new ConnectorUnauthorizedError(`WooCommerce taxes: HTTP ${response.status}`, response.status);
|
|
76
|
-
}
|
|
104
|
+
throwIfUnauthorized(response, 'taxes');
|
|
77
105
|
if (!response.ok) throw new Error(`WooCommerce taxes: HTTP ${response.status}`);
|
|
78
106
|
const rows = await response.json();
|
|
79
107
|
if (!Array.isArray(rows)) throw new Error('WooCommerce taxes: expected an array');
|
|
@@ -134,48 +162,63 @@ export async function wooStoreSettings(context: SyncContext): Promise<StoreSetti
|
|
|
134
162
|
}
|
|
135
163
|
}
|
|
136
164
|
|
|
165
|
+
// WCPOS 2.0.4 asks for approval when ABS(variance) > threshold for any `^\d+(\.\d+)?$` string, "0" included
|
|
166
|
+
// (Register_Session_Store.php:400-405). A till counts whole minor units, so the threshold is truncated, never rounded.
|
|
167
|
+
export function wooThresholdMinor(value: unknown, currency: unknown): number | undefined {
|
|
168
|
+
if (typeof value !== 'string' || typeof currency !== 'string' || !/^\d+(\.\d+)?$/.test(value)) return undefined;
|
|
169
|
+
const digits = minorUnitDigits(currency);
|
|
170
|
+
const [whole, fraction = ''] = value.split('.');
|
|
171
|
+
const minor = Number(whole + fraction.slice(0, digits).padEnd(digits, '0'));
|
|
172
|
+
return Number.isSafeInteger(minor) ? minor : undefined;
|
|
173
|
+
}
|
|
174
|
+
|
|
137
175
|
export async function readWooCapabilities(context: SyncContext): Promise<ServerCapabilities | undefined> {
|
|
138
176
|
try {
|
|
139
177
|
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/stores`, {
|
|
140
178
|
method: 'GET', headers: context.headers, signal: context.signal,
|
|
141
179
|
});
|
|
142
|
-
|
|
143
|
-
throw new ConnectorUnauthorizedError(`WooCommerce stores: HTTP ${response.status}`, response.status);
|
|
144
|
-
}
|
|
180
|
+
throwIfUnauthorized(response, 'stores');
|
|
145
181
|
if (!response.ok) return undefined;
|
|
146
182
|
const stores = await response.json();
|
|
147
183
|
if (!Array.isArray(stores) || !stores[0] || typeof stores[0] !== 'object' || Array.isArray(stores[0])) return undefined;
|
|
148
184
|
let multiplePayments = false;
|
|
149
185
|
let capabilities: unknown[] = [];
|
|
186
|
+
// undefined when /status failed; false when it answered without a capabilities array (stock 1.10.x).
|
|
187
|
+
let flagged: boolean | undefined;
|
|
150
188
|
try {
|
|
151
189
|
const status = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/status`, {
|
|
152
190
|
method: 'GET', headers: context.headers, signal: context.signal,
|
|
153
191
|
});
|
|
154
|
-
|
|
155
|
-
throw new ConnectorUnauthorizedError(`WooCommerce status: HTTP ${status.status}`, status.status);
|
|
156
|
-
}
|
|
192
|
+
throwIfUnauthorized(status, 'status');
|
|
157
193
|
if (status.ok) {
|
|
158
194
|
const body = await status.json();
|
|
159
|
-
|
|
195
|
+
flagged = Array.isArray(body?.capabilities);
|
|
196
|
+
capabilities = flagged ? body.capabilities : [];
|
|
160
197
|
multiplePayments = capabilities.includes('order_payments_list');
|
|
161
198
|
}
|
|
162
199
|
} catch (error) {
|
|
163
200
|
if (error instanceof ConnectorUnauthorizedError) throw error;
|
|
164
201
|
}
|
|
165
202
|
let coupons = false;
|
|
203
|
+
let wcposVersion: unknown;
|
|
166
204
|
try {
|
|
167
205
|
const site = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/site`, {
|
|
168
206
|
method: 'GET', headers: context.headers, signal: context.signal,
|
|
169
207
|
});
|
|
170
208
|
if (site.ok) {
|
|
171
209
|
const body = await site.json();
|
|
172
|
-
|
|
210
|
+
wcposVersion = body?.wcpos_version;
|
|
211
|
+
coupons = wooPluginSupportsCoupons(wcposVersion);
|
|
173
212
|
}
|
|
174
213
|
} catch {
|
|
175
214
|
coupons = false;
|
|
176
215
|
}
|
|
177
|
-
const
|
|
178
|
-
|
|
216
|
+
const linesVersion = coupons ? WOO_TAX_ADDRESS_ORDER_CREATE_VERSION : WOO_ORDER_CREATE_VERSION;
|
|
217
|
+
// The flag decides when present; else stock 2.0.4+ gets 6 (array or not), stock 1.10.20+ with no array gets 7; a failed /status gets 3.
|
|
218
|
+
const orderCreate = flagged === undefined ? WOO_BASE_ORDER_CREATE_VERSION : capabilities.includes('order_create_v5') ? linesVersion
|
|
219
|
+
: wooOnOrderLines20Line(wcposVersion) ? Math.min(WOO_ORDER_LINES_20_CAP, linesVersion)
|
|
220
|
+
: !flagged && wooOnOrderLinesLine(wcposVersion) ? Math.min(WOO_ORDER_LINES_VERSION_CAP, linesVersion) : WOO_BASE_ORDER_CREATE_VERSION;
|
|
221
|
+
const thresholdMinor = wooThresholdMinor(stores[0].variance_threshold, stores[0].currency);
|
|
179
222
|
return {
|
|
180
223
|
orderCreate,
|
|
181
224
|
taxRounding: { granularity: 'woocommerce', roundAtSubtotal: stores[0].tax_round_at_subtotal === 'yes' },
|
|
@@ -183,6 +226,9 @@ export async function readWooCapabilities(context: SyncContext): Promise<ServerC
|
|
|
183
226
|
coupons,
|
|
184
227
|
// WCPOS v5 takes a fee's, shipping line's and custom line's tax_status and tax_class (orders #146, #161); it has no /tally/v1/info.
|
|
185
228
|
lineTax: { none: true, classes: true },
|
|
229
|
+
...(thresholdMinor !== undefined ? { registerApproval: { thresholdMinor } } : {}),
|
|
230
|
+
// WCPOS 2.0's per-store register_sessions setting: the register transport sends to sessions, movements and closures.
|
|
231
|
+
...(stores[0].register_sessions === true ? { register: 3 } : {}),
|
|
186
232
|
};
|
|
187
233
|
} catch (error) {
|
|
188
234
|
if (error instanceof ConnectorUnauthorizedError) throw error;
|
package/src/traits/product.ts
CHANGED
|
@@ -8,6 +8,7 @@ const WOO_STOCK_STATUS: Record<string, StockStatus> = {
|
|
|
8
8
|
outofstock: 'out_of_stock',
|
|
9
9
|
onbackorder: 'backorder',
|
|
10
10
|
};
|
|
11
|
+
const WOO_BACKORDERS: ReadonlySet<unknown> = new Set(['no', 'notify', 'yes']);
|
|
11
12
|
|
|
12
13
|
/**
|
|
13
14
|
* WooCommerce product trait implementations.
|
|
@@ -52,6 +53,7 @@ export const wooProductTraits: ProductTraits = {
|
|
|
52
53
|
getStock: (doc) => ({
|
|
53
54
|
status: WOO_STOCK_STATUS[doc.stock_status] ?? 'unknown',
|
|
54
55
|
quantity: doc.manage_stock === false ? undefined : doc.stock_quantity ?? undefined,
|
|
56
|
+
...(WOO_BACKORDERS.has(doc.backorders) ? { backorders: doc.backorders } : {}),
|
|
55
57
|
}),
|
|
56
58
|
|
|
57
59
|
getPrice: (doc) => doc.price || undefined,
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { ConnectorUnauthorizedError } from '@tallyui/core';
|
|
2
|
+
|
|
3
|
+
/** Throws `ConnectorUnauthorizedError` when the store refused the credentials (401/403); `what` names the resource in the message. */
|
|
4
|
+
export function throwIfUnauthorized(response: Response | undefined, what: string): void {
|
|
5
|
+
if (response?.status === 401 || response?.status === 403) {
|
|
6
|
+
throw new ConnectorUnauthorizedError(`WooCommerce ${what}: HTTP ${response.status}`, response.status);
|
|
7
|
+
}
|
|
8
|
+
}
|