@tallyui/connector-woocommerce 3.18.0 → 3.19.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.
- package/dist/index.d.ts +9 -2
- package/dist/index.js +256 -33
- package/package.json +3 -3
- package/src/commands/transport.ts +17 -2
- package/src/customers.ts +18 -5
- package/src/index.ts +7 -2
- package/src/orders.ts +32 -1
- package/src/payment-methods.ts +133 -0
- package/src/receipt-templates.ts +54 -0
- package/src/reconcile/catalogue.ts +1 -1
- package/src/reconcile/coupons.ts +1 -1
- package/src/reconcile/feed.ts +1 -1
- package/src/replication/products.ts +5 -3
- package/src/store-settings.ts +19 -9
- package/src/sync/products.ts +3 -3
package/dist/index.d.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
import { SyncContext, ServerCapabilities, StoreSettings, Customer, CustomerInput, CustomerPatch, TallyConnector, StoreOrder, OrderCreateEnvelope, CommandResult, ReconcileFeed, CatalogueReconcileAdapter, ProductTraits, CollectionSync, ReplicationAdapter, ConnectorUnauthorizedError } from '@tallyui/core';
|
|
1
|
+
import { SyncContext, ServerCapabilities, StoreSettings, Customer, CustomerPage, CustomerInput, CustomerPatch, TallyConnector, StoreOrder, OrderCreateEnvelope, CommandResult, ReconcileFeed, CatalogueReconcileAdapter, ProductTraits, CollectionSync, ReplicationAdapter, ConnectorUnauthorizedError } from '@tallyui/core';
|
|
2
2
|
export { ConnectorUnauthorizedError } from '@tallyui/core';
|
|
3
3
|
import { RxJsonSchema } from 'rxdb';
|
|
4
4
|
|
|
5
5
|
/** 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). Coupons make 6 (ADR-077 d4a-woo). */
|
|
6
6
|
declare const WOO_ORDER_CREATE_VERSION = 5;
|
|
7
|
+
/** 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. */
|
|
8
|
+
declare const WOO_NOTE_ORDER_CREATE_VERSION = 7;
|
|
7
9
|
declare function wooStoreSettings(context: SyncContext): Promise<StoreSettings>;
|
|
8
10
|
declare function readWooCapabilities(context: SyncContext): Promise<ServerCapabilities | undefined>;
|
|
9
11
|
|
|
@@ -12,6 +14,7 @@ type WooCustomerRow = {
|
|
|
12
14
|
first_name?: string | null;
|
|
13
15
|
last_name?: string | null;
|
|
14
16
|
email?: string | null;
|
|
17
|
+
date_created_gmt?: string | null;
|
|
15
18
|
billing?: {
|
|
16
19
|
first_name?: string | null;
|
|
17
20
|
last_name?: string | null;
|
|
@@ -32,6 +35,10 @@ declare function createWooCustomers(options?: {
|
|
|
32
35
|
searchCustomers(context: SyncContext, query: string, options?: {
|
|
33
36
|
limit?: number;
|
|
34
37
|
}): Promise<Customer[]>;
|
|
38
|
+
searchCustomersPage(context: SyncContext, query: string, options?: {
|
|
39
|
+
limit?: number;
|
|
40
|
+
page?: number;
|
|
41
|
+
}): Promise<CustomerPage>;
|
|
35
42
|
getCustomer(context: SyncContext, id: string): Promise<Customer | null>;
|
|
36
43
|
createCustomer(context: SyncContext, input: CustomerInput): Promise<Customer>;
|
|
37
44
|
updateCustomer(context: SyncContext, id: string, patch: CustomerPatch): Promise<Customer>;
|
|
@@ -267,4 +274,4 @@ declare function createWooCommerceConnector(): TallyConnector;
|
|
|
267
274
|
*/
|
|
268
275
|
declare const woocommerceConnector: TallyConnector;
|
|
269
276
|
|
|
270
|
-
export { WOO_ORDER_CREATE_VERSION, type WooCommandTransportOptions, WooDateFilterError, WooMissingTokenError, WooMissingUuidError, WooTillUpdateRequiredError, WooTokenRefusedError, createWooCommandTransport, createWooCommerceConnector, createWooCouponFeed, createWooCustomers, createWooOrders, readWooCapabilities, toCouponDocument, toWooCustomer, toWooOrderPayload, toWooStoreOrder, wcposClientPart, wooCatalogueReconcile, wooCouponFingerprint, wooCouponReconcile, wooCouponSchema, wooProductReplication, wooProductSchema, wooProductSync, wooProductTraits, wooReconcileFingerprint, wooStoreSettings, woocommerceConnector };
|
|
277
|
+
export { WOO_NOTE_ORDER_CREATE_VERSION, WOO_ORDER_CREATE_VERSION, type WooCommandTransportOptions, WooDateFilterError, WooMissingTokenError, WooMissingUuidError, WooTillUpdateRequiredError, WooTokenRefusedError, createWooCommandTransport, createWooCommerceConnector, createWooCouponFeed, createWooCustomers, createWooOrders, readWooCapabilities, toCouponDocument, toWooCustomer, toWooOrderPayload, toWooStoreOrder, wcposClientPart, wooCatalogueReconcile, wooCouponFingerprint, wooCouponReconcile, wooCouponSchema, wooProductReplication, wooProductSchema, wooProductSync, wooProductTraits, wooReconcileFingerprint, wooStoreSettings, woocommerceConnector };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/index.ts
|
|
2
|
-
import { combinePullAdapters, ConnectorUnauthorizedError as
|
|
2
|
+
import { combinePullAdapters, ConnectorUnauthorizedError as ConnectorUnauthorizedError4 } from "@tallyui/core";
|
|
3
3
|
|
|
4
4
|
// src/schemas/products.ts
|
|
5
5
|
var wooProductSchema = {
|
|
@@ -387,6 +387,7 @@ function toProductDocument(product) {
|
|
|
387
387
|
if (uuid === void 0) throw new WooMissingUuidError(product.id);
|
|
388
388
|
const barcode = wooProductBarcode(product);
|
|
389
389
|
const projected = Object.fromEntries(Object.keys(wooProductSchema.properties).filter((key) => Object.prototype.hasOwnProperty.call(product, key)).map((key) => [key, product[key]]));
|
|
390
|
+
if (Array.isArray(projected.meta_data)) projected.meta_data = projected.meta_data.filter((entry) => typeof entry?.value === "string");
|
|
390
391
|
return { ...projected, uuid, ...barcode !== void 0 ? { barcode } : {}, _deleted: product.status !== "publish" };
|
|
391
392
|
}
|
|
392
393
|
var WooDateFilterError = class extends Error {
|
|
@@ -428,7 +429,7 @@ var wooProductReplication = {
|
|
|
428
429
|
if (requests++ >= MAX_REQUESTS_PER_CALL) return spent;
|
|
429
430
|
const newer = modified ? { modified_after: modified, dates_are_gmt: "true" } : {};
|
|
430
431
|
const mark = new URLSearchParams({ per_page: "1", orderby: "modified", order: "desc", ...newer });
|
|
431
|
-
const markResponse = await fetch(
|
|
432
|
+
const markResponse = await (context.fetch ?? globalThis.fetch)(
|
|
432
433
|
`${context.baseUrl}/products?${mark}`,
|
|
433
434
|
{ headers: { ...context.headers, "Content-Type": "application/json" }, signal: context.signal }
|
|
434
435
|
);
|
|
@@ -449,7 +450,7 @@ var wooProductReplication = {
|
|
|
449
450
|
params.set("dates_are_gmt", "true");
|
|
450
451
|
}
|
|
451
452
|
if (requests++ >= MAX_REQUESTS_PER_CALL) return spent;
|
|
452
|
-
const response = await fetch(`${context.baseUrl}/products?${params}`, {
|
|
453
|
+
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/products?${params}`, {
|
|
453
454
|
headers: {
|
|
454
455
|
...context.headers,
|
|
455
456
|
"Content-Type": "application/json"
|
|
@@ -476,7 +477,7 @@ var wooProductReplication = {
|
|
|
476
477
|
for (let i = 0; i < variationIds.length; i += 100) {
|
|
477
478
|
const chunk = variationIds.slice(i, i + 100);
|
|
478
479
|
const variationParams = new URLSearchParams({ include: chunk.join(","), per_page: String(chunk.length), orderby: "id", order: "asc" });
|
|
479
|
-
const response2 = await fetch(`${context.baseUrl}/variations?${variationParams}`, {
|
|
480
|
+
const response2 = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/variations?${variationParams}`, {
|
|
480
481
|
headers: { ...context.headers, "Content-Type": "application/json" },
|
|
481
482
|
signal: context.signal
|
|
482
483
|
});
|
|
@@ -590,7 +591,7 @@ var wooProductTraits = {
|
|
|
590
591
|
// src/sync/products.ts
|
|
591
592
|
var wooProductSync = {
|
|
592
593
|
async fetchAllIds(context) {
|
|
593
|
-
const response = await fetch(`${context.baseUrl}/products`, {
|
|
594
|
+
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/products`, {
|
|
594
595
|
headers: {
|
|
595
596
|
...context.headers,
|
|
596
597
|
"Content-Type": "application/json"
|
|
@@ -608,7 +609,7 @@ var wooProductSync = {
|
|
|
608
609
|
},
|
|
609
610
|
async fetchByIds(ids, context) {
|
|
610
611
|
const include = ids.join(",");
|
|
611
|
-
const response = await fetch(
|
|
612
|
+
const response = await (context.fetch ?? globalThis.fetch)(
|
|
612
613
|
`${context.baseUrl}/products?include=${include}&per_page=${ids.length}`,
|
|
613
614
|
{
|
|
614
615
|
headers: {
|
|
@@ -629,7 +630,7 @@ var wooProductSync = {
|
|
|
629
630
|
dates_are_gmt: "true",
|
|
630
631
|
per_page: "100"
|
|
631
632
|
});
|
|
632
|
-
const response = await fetch(
|
|
633
|
+
const response = await (context.fetch ?? globalThis.fetch)(
|
|
633
634
|
`${context.baseUrl}/products?${params}`,
|
|
634
635
|
{
|
|
635
636
|
headers: {
|
|
@@ -653,7 +654,7 @@ var LISTING_FIELDS = "id,date_modified_gmt,stock_quantity,stock_status";
|
|
|
653
654
|
var ID_FAST_PATH = "products_id_fast_path";
|
|
654
655
|
var wooReconcileFingerprint = (p) => [p.date_modified_gmt ?? "", p.stock_quantity ?? "", p.stock_status ?? ""].join("|");
|
|
655
656
|
async function get(path, context) {
|
|
656
|
-
const response = await fetch(`${context.baseUrl}${path}`, {
|
|
657
|
+
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}${path}`, {
|
|
657
658
|
headers: { ...context.headers, "Content-Type": "application/json" },
|
|
658
659
|
signal: context.signal
|
|
659
660
|
});
|
|
@@ -736,7 +737,7 @@ async function wooFetchByIds(entries, context) {
|
|
|
736
737
|
for (let i = 0; i < ids.length; i += MAX_IDS_PER_REQUEST) {
|
|
737
738
|
const chunk = ids.slice(i, i + MAX_IDS_PER_REQUEST);
|
|
738
739
|
const params = new URLSearchParams({ include: chunk.join(","), per_page: String(MAX_IDS_PER_REQUEST), status: "any" });
|
|
739
|
-
const response = await fetch(`${context.baseUrl}/products?${params}`, {
|
|
740
|
+
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/products?${params}`, {
|
|
740
741
|
headers: { ...context.headers, "Content-Type": "application/json" },
|
|
741
742
|
signal: context.signal
|
|
742
743
|
});
|
|
@@ -766,7 +767,7 @@ var PAGE_SIZE2 = 100;
|
|
|
766
767
|
var LISTING_FIELDS2 = "id,date_modified_gmt,usage_count,used_by";
|
|
767
768
|
var wooCouponFingerprint = (c) => [c.date_modified_gmt ?? "", c.usage_count ?? "", JSON.stringify((c.used_by ?? []).map(String))].join("|");
|
|
768
769
|
async function get2(path, context) {
|
|
769
|
-
const response = await fetch(`${context.baseUrl}${path}`, {
|
|
770
|
+
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}${path}`, {
|
|
770
771
|
headers: { ...context.headers, "Content-Type": "application/json" },
|
|
771
772
|
signal: context.signal
|
|
772
773
|
});
|
|
@@ -876,6 +877,8 @@ function toWooCustomer(raw) {
|
|
|
876
877
|
]) {
|
|
877
878
|
if (typeof value === "string" && value.length > 0) customer[key] = value;
|
|
878
879
|
}
|
|
880
|
+
const created = raw.date_created_gmt;
|
|
881
|
+
if (typeof created === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/.test(created)) customer.createdAt = `${created}Z`;
|
|
879
882
|
customer.name = [customer.firstName, customer.lastName].filter(Boolean).join(" ") || customer.company || customer.email || customer.id;
|
|
880
883
|
return customer;
|
|
881
884
|
}
|
|
@@ -890,7 +893,7 @@ function newWooId() {
|
|
|
890
893
|
async function customerRequest(context, route, init = {}) {
|
|
891
894
|
let response;
|
|
892
895
|
try {
|
|
893
|
-
response = await fetch(`${context.baseUrl}/${route}`, {
|
|
896
|
+
response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/${route}`, {
|
|
894
897
|
...init,
|
|
895
898
|
headers: { ...init.headers, ...context.headers },
|
|
896
899
|
signal: context.signal
|
|
@@ -908,14 +911,21 @@ async function customerRequest(context, route, init = {}) {
|
|
|
908
911
|
}
|
|
909
912
|
function createWooCustomers(options) {
|
|
910
913
|
const newId = options?.newId ?? newWooId;
|
|
911
|
-
|
|
914
|
+
const api = {
|
|
912
915
|
async searchCustomers(context, query, options2) {
|
|
916
|
+
return (await api.searchCustomersPage(context, query, { limit: options2?.limit })).customers;
|
|
917
|
+
},
|
|
918
|
+
async searchCustomersPage(context, query, options2) {
|
|
913
919
|
const q = query.trim();
|
|
914
920
|
const perPage = String(Math.max(1, Math.min(50, options2?.limit ?? 20)));
|
|
915
921
|
const params = q ? new URLSearchParams({ search: q, role: "customer", per_page: perPage }) : new URLSearchParams({ role: "customer", per_page: perPage, orderby: "last_name", order: "asc" });
|
|
916
|
-
const
|
|
922
|
+
const requested = options2?.page ?? 1;
|
|
923
|
+
const page = Number.isFinite(requested) ? Math.max(1, Math.floor(requested)) : 1;
|
|
924
|
+
if (page > 1) params.append("page", String(page));
|
|
925
|
+
const { body, headers } = await customerRequest(context, `customers?${params}`, { method: "GET" });
|
|
917
926
|
if (!Array.isArray(body)) throw new CustomerServiceError("server", "unexpected response");
|
|
918
|
-
|
|
927
|
+
const total = headers.get("X-WP-Total");
|
|
928
|
+
return { customers: body.map(toWooCustomer), ...total && /^\d+$/.test(total) ? { total: Number(total) } : {} };
|
|
919
929
|
},
|
|
920
930
|
async getCustomer(context, id) {
|
|
921
931
|
if (!/^\d+$/.test(id)) return null;
|
|
@@ -991,10 +1001,15 @@ function createWooCustomers(options) {
|
|
|
991
1001
|
if (status !== 200 || body?.success !== true) throw new CustomerServiceError("server", "unexpected response");
|
|
992
1002
|
}
|
|
993
1003
|
};
|
|
1004
|
+
return api;
|
|
994
1005
|
}
|
|
995
1006
|
|
|
996
1007
|
// src/orders.ts
|
|
997
|
-
import {
|
|
1008
|
+
import {
|
|
1009
|
+
assertOrderFiltersSupported,
|
|
1010
|
+
CustomerServiceError as CustomerServiceError2,
|
|
1011
|
+
minorUnitDigits as minorUnitDigits2
|
|
1012
|
+
} from "@tallyui/core";
|
|
998
1013
|
|
|
999
1014
|
// src/commands/transport.ts
|
|
1000
1015
|
import { minorUnitDigits, moneyFromDecimalString, moneyFromMajor as moneyFromMajor2 } from "@tallyui/core";
|
|
@@ -1025,6 +1040,21 @@ function decodeCouponMessage(message) {
|
|
|
1025
1040
|
parseInt(entity.slice(entity[1].toLowerCase() === "x" ? 2 : 1), entity[1].toLowerCase() === "x" ? 16 : 10)
|
|
1026
1041
|
)).replace(/[<>]/g, "").replace(/\s+/g, " ").trim() || "status_400";
|
|
1027
1042
|
}
|
|
1043
|
+
var WOO_ADDRESS_KEYS = [
|
|
1044
|
+
["firstName", "first_name"],
|
|
1045
|
+
["lastName", "last_name"],
|
|
1046
|
+
["company", "company"],
|
|
1047
|
+
["address1", "address_1"],
|
|
1048
|
+
["address2", "address_2"],
|
|
1049
|
+
["city", "city"],
|
|
1050
|
+
["state", "state"],
|
|
1051
|
+
["postcode", "postcode"],
|
|
1052
|
+
["country", "country"],
|
|
1053
|
+
["phone", "phone"]
|
|
1054
|
+
];
|
|
1055
|
+
function wooAddress(address) {
|
|
1056
|
+
return Object.fromEntries(WOO_ADDRESS_KEYS.flatMap(([ours, theirs]) => typeof address?.[ours] === "string" ? [[theirs, address[ours]]] : []));
|
|
1057
|
+
}
|
|
1028
1058
|
function toWooOrderPayload(envelope, local, options) {
|
|
1029
1059
|
const p = envelope.payload;
|
|
1030
1060
|
if (p.payments.length === 0 || p.payments.length > 1 && !options?.paymentsList) {
|
|
@@ -1108,10 +1138,10 @@ function toWooOrderPayload(envelope, local, options) {
|
|
|
1108
1138
|
if (typeof total !== "string") return total;
|
|
1109
1139
|
fee_lines.push({ name: fee.name, total, tax_status: fee.taxStatus, tax_class: fee.taxClass ?? "" });
|
|
1110
1140
|
}
|
|
1111
|
-
for (const
|
|
1112
|
-
const total = p.pricesIncludeTax ? inclusiveNet(local?.shipping?.find((stored) => stored.id ===
|
|
1141
|
+
for (const shipping2 of p.shipping ?? []) {
|
|
1142
|
+
const total = p.pricesIncludeTax ? inclusiveNet(local?.shipping?.find((stored) => stored.id === shipping2.clientShippingId)?.netMicros, shipping2.clientShippingId) : major(shipping2.amountMinor);
|
|
1113
1143
|
if (typeof total !== "string") return total;
|
|
1114
|
-
shipping_lines.push({ method_id:
|
|
1144
|
+
shipping_lines.push({ method_id: shipping2.methodId ?? "pos", method_title: shipping2.name, total });
|
|
1115
1145
|
}
|
|
1116
1146
|
const primary = p.payments.reduce((largest, payment) => payment.amountMinor > largest.amountMinor ? payment : largest);
|
|
1117
1147
|
const cash = primary.method === "cash";
|
|
@@ -1126,6 +1156,9 @@ function toWooOrderPayload(envelope, local, options) {
|
|
|
1126
1156
|
...payment.method === "cash" && payment.changeMinor !== void 0 ? { change: major(payment.changeMinor) } : {}
|
|
1127
1157
|
}))) });
|
|
1128
1158
|
}
|
|
1159
|
+
if (p.taxAddress) meta_data.push({ key: "_woocommerce_pos_tax_based_on", value: p.taxAddress });
|
|
1160
|
+
const billing = { ...p.customer?.email ? { email: p.customer.email } : {}, ...p.taxAddress ? wooAddress(p.customer?.billing) : {} };
|
|
1161
|
+
const shipping = p.taxAddress && p.customer?.shipping ? wooAddress(p.customer.shipping) : void 0;
|
|
1129
1162
|
return { payload: {
|
|
1130
1163
|
status: "completed",
|
|
1131
1164
|
set_paid: true,
|
|
@@ -1138,11 +1171,14 @@ function toWooOrderPayload(envelope, local, options) {
|
|
|
1138
1171
|
...p.coupons?.length ? { coupon_lines: p.coupons.map(({ code }) => ({ code })) } : {},
|
|
1139
1172
|
meta_data,
|
|
1140
1173
|
...p.customer?.customerId && /^\d+$/.test(p.customer.customerId) ? { customer_id: Number(p.customer.customerId) } : {},
|
|
1141
|
-
...
|
|
1174
|
+
...Object.keys(billing).length ? { billing } : {},
|
|
1175
|
+
...shipping ? { shipping } : {},
|
|
1176
|
+
// Version 7 (ADR-083): the till froze and cut the note already, and wc/v3 sanitises it; no note, no key.
|
|
1177
|
+
...typeof p.note === "string" && p.note.length > 0 ? { customer_note: p.note } : {}
|
|
1142
1178
|
} };
|
|
1143
1179
|
}
|
|
1144
1180
|
function createWooCommandTransport(options) {
|
|
1145
|
-
const
|
|
1181
|
+
const fetch = options.fetch ?? globalThis.fetch;
|
|
1146
1182
|
let baseUrl = options.baseUrl;
|
|
1147
1183
|
while (baseUrl.endsWith("/")) baseUrl = baseUrl.slice(0, -1);
|
|
1148
1184
|
return {
|
|
@@ -1168,7 +1204,7 @@ function createWooCommandTransport(options) {
|
|
|
1168
1204
|
const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? 3e4);
|
|
1169
1205
|
let outcome;
|
|
1170
1206
|
try {
|
|
1171
|
-
const response = await
|
|
1207
|
+
const response = await fetch(`${baseUrl}/push/orders`, {
|
|
1172
1208
|
method: "POST",
|
|
1173
1209
|
headers: { "Content-Type": "application/json", ...await options.getHeaders() },
|
|
1174
1210
|
body: JSON.stringify({
|
|
@@ -1365,14 +1401,37 @@ function toWooStoreOrder(raw) {
|
|
|
1365
1401
|
};
|
|
1366
1402
|
}
|
|
1367
1403
|
var wholeNumber = (value, fallback) => value === void 0 || !Number.isFinite(value) ? fallback : Math.trunc(value);
|
|
1404
|
+
var WOO_ORDER_FILTERS = ["status", "customerId", "cashierId", "storeId", "createdVia", "dateRange"];
|
|
1405
|
+
var wooGmtSecond = (instant, shiftSeconds) => new Date((Math.ceil(Date.parse(instant) / 1e3) + shiftSeconds) * 1e3).toISOString().slice(0, 19);
|
|
1368
1406
|
function createWooOrders() {
|
|
1369
1407
|
return {
|
|
1408
|
+
/**
|
|
1409
|
+
* Filters on the server: status, customerId (customer), cashierId (pos_cashier), storeId (pos_store), createdVia
|
|
1410
|
+
* (created_via) and dateRange; any other filter field is refused. An id that is not all digits, or an empty status
|
|
1411
|
+
* or createdVia, matches no order, so it resolves an empty page without a request. dateRange is sent in GMT (dates_are_gmt): WooCommerce compares
|
|
1412
|
+
* whole seconds strictly, so the inclusive `after` goes as its instant rounded up to the second minus one second,
|
|
1413
|
+
* and the exclusive `before` as its instant rounded up to the second.
|
|
1414
|
+
*/
|
|
1370
1415
|
async listOrders(context, query = {}) {
|
|
1416
|
+
assertOrderFiltersSupported(query, WOO_ORDER_FILTERS);
|
|
1417
|
+
if (query.status === "" || query.createdVia === "") return { orders: [], hasMore: false };
|
|
1371
1418
|
const page = Math.max(1, wholeNumber(query.page, 1));
|
|
1372
1419
|
const perPage = Math.max(1, Math.min(MAX_PER_PAGE, wholeNumber(query.perPage, 25)));
|
|
1373
1420
|
const params = new URLSearchParams({ page: String(page), per_page: String(perPage), orderby: "date", order: "desc" });
|
|
1374
1421
|
const search = query.search?.trim();
|
|
1375
1422
|
if (search) params.set("search", search);
|
|
1423
|
+
if (query.status !== void 0) params.set("status", query.status);
|
|
1424
|
+
const ids = [["customer", query.customerId], ["pos_cashier", query.cashierId], ["pos_store", query.storeId]];
|
|
1425
|
+
for (const [param, id] of ids) {
|
|
1426
|
+
if (id === void 0) continue;
|
|
1427
|
+
if (!/^\d+$/.test(id)) return { orders: [], hasMore: false };
|
|
1428
|
+
params.set(param, id);
|
|
1429
|
+
}
|
|
1430
|
+
if (query.createdVia !== void 0) params.set("created_via", query.createdVia);
|
|
1431
|
+
const { after, before } = query.dateRange ?? {};
|
|
1432
|
+
if (after !== void 0 || before !== void 0) params.set("dates_are_gmt", "true");
|
|
1433
|
+
if (after !== void 0) params.set("after", wooGmtSecond(after, -1));
|
|
1434
|
+
if (before !== void 0) params.set("before", wooGmtSecond(before, 0));
|
|
1376
1435
|
const { body, headers } = await customerRequest(context, `orders?${params}`, { method: "GET" });
|
|
1377
1436
|
if (!Array.isArray(body)) throw unexpected();
|
|
1378
1437
|
const orders = body.map(toWooStoreOrder);
|
|
@@ -1397,7 +1456,8 @@ function createWooOrders() {
|
|
|
1397
1456
|
// src/store-settings.ts
|
|
1398
1457
|
import { ConnectorUnauthorizedError as ConnectorUnauthorizedError2, StoreSettingsError, minorUnitDigits as minorUnitDigits3, woocommerceTax } from "@tallyui/core";
|
|
1399
1458
|
var WOO_ORDER_CREATE_VERSION = 5;
|
|
1400
|
-
var
|
|
1459
|
+
var WOO_NOTE_ORDER_CREATE_VERSION = 7;
|
|
1460
|
+
var WOO_TAX_ADDRESS_ORDER_CREATE_VERSION = 8;
|
|
1401
1461
|
var WOO_BASE_ORDER_CREATE_VERSION = 3;
|
|
1402
1462
|
var WOO_COUPONS_MIN_PLUGIN = [1, 9, 0];
|
|
1403
1463
|
function wooPluginSupportsCoupons(version2) {
|
|
@@ -1414,7 +1474,7 @@ function wooPluginSupportsCoupons(version2) {
|
|
|
1414
1474
|
async function wooStoreSettings(context) {
|
|
1415
1475
|
try {
|
|
1416
1476
|
const init = { method: "GET", headers: context.headers, signal: context.signal };
|
|
1417
|
-
const storesResponse = await fetch(`${context.baseUrl}/stores`, init);
|
|
1477
|
+
const storesResponse = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/stores`, init);
|
|
1418
1478
|
if (storesResponse.status === 401 || storesResponse.status === 403) {
|
|
1419
1479
|
throw new ConnectorUnauthorizedError2(`WooCommerce stores: HTTP ${storesResponse.status}`, storesResponse.status);
|
|
1420
1480
|
}
|
|
@@ -1427,7 +1487,7 @@ async function wooStoreSettings(context) {
|
|
|
1427
1487
|
if (typeof store.price_num_decimals === "number" && store.price_num_decimals !== digits) {
|
|
1428
1488
|
console.warn(`WooCommerce price_num_decimals is ${store.price_num_decimals}; the till rounds ${currency} to ${digits} digits`);
|
|
1429
1489
|
}
|
|
1430
|
-
const classesResponse = await fetch(`${context.baseUrl}/taxes/classes`, init);
|
|
1490
|
+
const classesResponse = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/taxes/classes`, init);
|
|
1431
1491
|
if (classesResponse.status === 401 || classesResponse.status === 403) {
|
|
1432
1492
|
throw new ConnectorUnauthorizedError2(`WooCommerce tax classes: HTTP ${classesResponse.status}`, classesResponse.status);
|
|
1433
1493
|
}
|
|
@@ -1447,9 +1507,10 @@ async function wooStoreSettings(context) {
|
|
|
1447
1507
|
taxRatesPpm
|
|
1448
1508
|
};
|
|
1449
1509
|
if (store.calc_taxes !== "yes") return settings;
|
|
1510
|
+
settings.taxBasedOn = woocommerceTax.normalizeTaxBasedOn(store.tax_based_on);
|
|
1450
1511
|
const rates = [];
|
|
1451
1512
|
for (let page = 1; page <= 100; page++) {
|
|
1452
|
-
const response = await fetch(`${context.baseUrl}/taxes?per_page=100&page=${page}&orderby=order&order=asc`, init);
|
|
1513
|
+
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/taxes?per_page=100&page=${page}&orderby=order&order=asc`, init);
|
|
1453
1514
|
if (response.status === 401 || response.status === 403) {
|
|
1454
1515
|
throw new ConnectorUnauthorizedError2(`WooCommerce taxes: HTTP ${response.status}`, response.status);
|
|
1455
1516
|
}
|
|
@@ -1484,6 +1545,10 @@ async function wooStoreSettings(context) {
|
|
|
1484
1545
|
console.warn("WooCommerce has no tax or store country; matching tax rates with an empty address");
|
|
1485
1546
|
address = {};
|
|
1486
1547
|
}
|
|
1548
|
+
const text = (value) => typeof value === "string" ? value : "";
|
|
1549
|
+
const baseTaxAddress = { country: text(address.country), state: text(address.state), city: text(address.city), postcode: text(address.postcode) };
|
|
1550
|
+
if (baseTaxAddress.country) settings.baseTaxAddress = baseTaxAddress;
|
|
1551
|
+
if (baseTaxAddress.country) settings.taxRateTable = rates;
|
|
1487
1552
|
const matched = woocommerceTax.filterTaxRates(rates, address.country, address.state, address.postcode, address.city);
|
|
1488
1553
|
for (const rate of matched) {
|
|
1489
1554
|
const slug = woocommerceTax.normalizeTaxClass(rate.class);
|
|
@@ -1507,7 +1572,7 @@ async function wooStoreSettings(context) {
|
|
|
1507
1572
|
}
|
|
1508
1573
|
async function readWooCapabilities(context) {
|
|
1509
1574
|
try {
|
|
1510
|
-
const response = await fetch(`${context.baseUrl}/stores`, {
|
|
1575
|
+
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/stores`, {
|
|
1511
1576
|
method: "GET",
|
|
1512
1577
|
headers: context.headers,
|
|
1513
1578
|
signal: context.signal
|
|
@@ -1521,7 +1586,7 @@ async function readWooCapabilities(context) {
|
|
|
1521
1586
|
let multiplePayments = false;
|
|
1522
1587
|
let capabilities = [];
|
|
1523
1588
|
try {
|
|
1524
|
-
const status = await fetch(`${context.baseUrl}/status`, {
|
|
1589
|
+
const status = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/status`, {
|
|
1525
1590
|
method: "GET",
|
|
1526
1591
|
headers: context.headers,
|
|
1527
1592
|
signal: context.signal
|
|
@@ -1539,7 +1604,7 @@ async function readWooCapabilities(context) {
|
|
|
1539
1604
|
}
|
|
1540
1605
|
let coupons = false;
|
|
1541
1606
|
try {
|
|
1542
|
-
const site = await fetch(`${context.baseUrl}/site`, {
|
|
1607
|
+
const site = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/site`, {
|
|
1543
1608
|
method: "GET",
|
|
1544
1609
|
headers: context.headers,
|
|
1545
1610
|
signal: context.signal
|
|
@@ -1551,7 +1616,7 @@ async function readWooCapabilities(context) {
|
|
|
1551
1616
|
} catch {
|
|
1552
1617
|
coupons = false;
|
|
1553
1618
|
}
|
|
1554
|
-
const orderCreate = capabilities.includes("order_create_v5") ? coupons ?
|
|
1619
|
+
const orderCreate = capabilities.includes("order_create_v5") ? coupons ? WOO_TAX_ADDRESS_ORDER_CREATE_VERSION : WOO_ORDER_CREATE_VERSION : WOO_BASE_ORDER_CREATE_VERSION;
|
|
1555
1620
|
return {
|
|
1556
1621
|
orderCreate,
|
|
1557
1622
|
taxRounding: { granularity: "woocommerce", roundAtSubtotal: stores[0].tax_round_at_subtotal === "yes" },
|
|
@@ -1566,15 +1631,169 @@ async function readWooCapabilities(context) {
|
|
|
1566
1631
|
}
|
|
1567
1632
|
}
|
|
1568
1633
|
|
|
1634
|
+
// src/payment-methods.ts
|
|
1635
|
+
import { ConnectorUnauthorizedError as ConnectorUnauthorizedError3, defaultPaymentMethods } from "@tallyui/core";
|
|
1636
|
+
var WOO_DEFAULT_ORDER = 999;
|
|
1637
|
+
var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1638
|
+
var objectOr = (value) => isObject(value) ? value : {};
|
|
1639
|
+
var stringOr = (value, fallback) => typeof value === "string" ? value : fallback;
|
|
1640
|
+
var isModeEntry = (value) => isObject(value) && typeof value.mode === "string";
|
|
1641
|
+
function toHardware(value) {
|
|
1642
|
+
if (!isObject(value)) return null;
|
|
1643
|
+
const discovery = value.discovery;
|
|
1644
|
+
if (Array.isArray(value.readers)) {
|
|
1645
|
+
return {
|
|
1646
|
+
discovery,
|
|
1647
|
+
defaultReader: value.default_reader ?? null,
|
|
1648
|
+
lockToDefault: value.lock_to_default === true,
|
|
1649
|
+
readers: value.readers.filter((reader) => isObject(reader) && typeof reader.id === "string").map((reader) => ({ id: reader.id, label: reader.label, status: reader.status, default: reader.default === true }))
|
|
1650
|
+
};
|
|
1651
|
+
}
|
|
1652
|
+
if (!Array.isArray(value.transports)) return null;
|
|
1653
|
+
return { discovery, transports: value.transports.map(objectOr).map((entry) => ({ transport: entry.transport, offline: entry.offline, tips: entry.tips })) };
|
|
1654
|
+
}
|
|
1655
|
+
function toCaptureEntry(value) {
|
|
1656
|
+
return { mode: value.mode, provider: stringOr(value.provider, null), hardware: toHardware(value.hardware) };
|
|
1657
|
+
}
|
|
1658
|
+
function hasMoneyString(row) {
|
|
1659
|
+
const amount = objectOr(row.capabilities.amount), rounding = objectOr(objectOr(row.defaults).rounding);
|
|
1660
|
+
return typeof amount.min === "string" || typeof amount.max === "string" || typeof rounding.increment === "string";
|
|
1661
|
+
}
|
|
1662
|
+
async function storeCurrency(context) {
|
|
1663
|
+
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/stores`, { method: "GET", headers: context.headers, signal: context.signal }).catch(() => void 0);
|
|
1664
|
+
if (response?.status === 401 || response?.status === 403) throw new ConnectorUnauthorizedError3(`WooCommerce stores: HTTP ${response.status}`, response.status);
|
|
1665
|
+
const stores = response?.ok ? await response.json().catch(() => void 0) : void 0;
|
|
1666
|
+
const currency = Array.isArray(stores) ? objectOr(stores[0]).currency : void 0;
|
|
1667
|
+
if (typeof currency !== "string") throw new Error("WooCommerce payment methods: no store currency");
|
|
1668
|
+
return currency.toUpperCase();
|
|
1669
|
+
}
|
|
1670
|
+
function toRounding(value, currency, id) {
|
|
1671
|
+
if (value === null || value === void 0) return null;
|
|
1672
|
+
const { increment, mode } = objectOr(value);
|
|
1673
|
+
const incrementMinor = typeof increment === "string" ? wooMinorFromDecimal(increment, currency) : void 0;
|
|
1674
|
+
if (incrementMinor === void 0 || incrementMinor <= 0 || mode !== "nearest" && mode !== "up" && mode !== "down") {
|
|
1675
|
+
console.warn(`WooCommerce payment method ${id}: unreadable cash rounding; the till does not round it`);
|
|
1676
|
+
return null;
|
|
1677
|
+
}
|
|
1678
|
+
return { incrementMinor, mode };
|
|
1679
|
+
}
|
|
1680
|
+
function toAmount(amount, currency) {
|
|
1681
|
+
const result = { partial: amount.partial === true };
|
|
1682
|
+
for (const [wire, key] of [["min", "minMinor"], ["max", "maxMinor"]]) {
|
|
1683
|
+
const text = amount[wire];
|
|
1684
|
+
if (text === void 0) continue;
|
|
1685
|
+
const minor2 = typeof text === "string" ? wooMinorFromDecimal(text, currency) : void 0;
|
|
1686
|
+
if (minor2 === void 0) return void 0;
|
|
1687
|
+
result[key] = minor2;
|
|
1688
|
+
}
|
|
1689
|
+
return result;
|
|
1690
|
+
}
|
|
1691
|
+
function toDescriptor(row, currency) {
|
|
1692
|
+
const caps = row.capabilities, defaults = objectOr(row.defaults);
|
|
1693
|
+
const amount = toAmount(objectOr(caps.amount), currency);
|
|
1694
|
+
if (!amount) {
|
|
1695
|
+
console.warn(`WooCommerce payment method ${row.id}: unreadable amount limit; dropped`);
|
|
1696
|
+
return void 0;
|
|
1697
|
+
}
|
|
1698
|
+
const refunds = objectOr(caps.refunds);
|
|
1699
|
+
return {
|
|
1700
|
+
id: row.id,
|
|
1701
|
+
title: typeof row.title === "string" && row.title.length > 0 ? row.title : row.id,
|
|
1702
|
+
kind: row.kind,
|
|
1703
|
+
capture: {
|
|
1704
|
+
...toCaptureEntry(row.capture),
|
|
1705
|
+
...Array.isArray(row.capture.modes) ? { modes: row.capture.modes.filter(isModeEntry).map(toCaptureEntry) } : {}
|
|
1706
|
+
},
|
|
1707
|
+
capabilities: {
|
|
1708
|
+
amount,
|
|
1709
|
+
change: caps.change === true,
|
|
1710
|
+
void: caps.void === true,
|
|
1711
|
+
refunds: { via: stringOr(refunds.via, "none"), partial: refunds.partial === true },
|
|
1712
|
+
tips: stringOr(caps.tips, "none"),
|
|
1713
|
+
offline: stringOr(caps.offline, "none")
|
|
1714
|
+
},
|
|
1715
|
+
defaults: { rounding: toRounding(defaults.rounding, currency, row.id), openDrawer: defaults.open_drawer === true }
|
|
1716
|
+
};
|
|
1717
|
+
}
|
|
1718
|
+
async function wooPaymentMethods(context) {
|
|
1719
|
+
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/payment-methods`, { method: "GET", headers: context.headers, signal: context.signal });
|
|
1720
|
+
if (response.status === 404) return defaultPaymentMethods();
|
|
1721
|
+
if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError3(`WooCommerce payment methods: HTTP ${response.status}`, response.status);
|
|
1722
|
+
if (!response.ok) throw new Error(`WooCommerce payment methods: HTTP ${response.status}`);
|
|
1723
|
+
const body = await response.json();
|
|
1724
|
+
if (!isObject(body) || !Number.isInteger(body.schema) || typeof body.contract !== "string" || !Array.isArray(body.methods)) {
|
|
1725
|
+
throw new Error("WooCommerce payment methods: unexpected response");
|
|
1726
|
+
}
|
|
1727
|
+
if (body.schema !== 1) throw new Error(`WooCommerce payment methods: unsupported schema ${body.schema}`);
|
|
1728
|
+
const valid = body.methods.filter((row, index) => {
|
|
1729
|
+
const ok = isObject(row) && row.schema === 1 && typeof row.id === "string" && row.id.length > 0 && typeof row.kind === "string" && isModeEntry(row.capture) && isObject(row.capabilities);
|
|
1730
|
+
if (!ok) {
|
|
1731
|
+
const id = isObject(row) && typeof row.id === "string" && row.id.length > 0 ? row.id : `at index ${index}`;
|
|
1732
|
+
console.warn(`WooCommerce payment method ${id}: malformed descriptor; dropped`);
|
|
1733
|
+
}
|
|
1734
|
+
return ok;
|
|
1735
|
+
});
|
|
1736
|
+
if (body.methods.length > 0 && valid.length === 0) {
|
|
1737
|
+
console.warn("WooCommerce payment methods: every descriptor is malformed; offering the default methods");
|
|
1738
|
+
return defaultPaymentMethods();
|
|
1739
|
+
}
|
|
1740
|
+
const order = (row) => typeof row.order === "number" ? row.order : WOO_DEFAULT_ORDER;
|
|
1741
|
+
const enabled = valid.filter((row) => row.pos_enabled === true).sort((a, b) => order(a) - order(b));
|
|
1742
|
+
const currency = enabled.some(hasMoneyString) ? await storeCurrency(context) : "";
|
|
1743
|
+
return enabled.map((row) => toDescriptor(row, currency)).filter((row) => row !== void 0);
|
|
1744
|
+
}
|
|
1745
|
+
|
|
1746
|
+
// src/receipt-templates.ts
|
|
1747
|
+
var WOO_ENGINES = { logicless: "html", thermal: "thermal" };
|
|
1748
|
+
async function wooReceiptTemplates(context, kind = "receipt") {
|
|
1749
|
+
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/templates${kind === "receipt" ? "" : `?type=${kind}`}`, {
|
|
1750
|
+
method: "GET",
|
|
1751
|
+
headers: context.headers,
|
|
1752
|
+
signal: context.signal
|
|
1753
|
+
});
|
|
1754
|
+
if (response.status === 404) return [];
|
|
1755
|
+
if (!response.ok) {
|
|
1756
|
+
await checkResponse(response);
|
|
1757
|
+
throw new Error(`WooCommerce API error: ${response.status}`);
|
|
1758
|
+
}
|
|
1759
|
+
const rows2 = await response.json().catch(() => void 0);
|
|
1760
|
+
if (!Array.isArray(rows2)) throw new Error("connector-woocommerce: unexpected templates response");
|
|
1761
|
+
const templates = [];
|
|
1762
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1763
|
+
for (const row of rows2) {
|
|
1764
|
+
if (typeof row !== "object" || row === null || row.type !== kind) continue;
|
|
1765
|
+
if (row.engine !== "logicless" && row.engine !== "thermal") continue;
|
|
1766
|
+
if (typeof row.content !== "string" || row.content.length === 0) continue;
|
|
1767
|
+
if (row.is_disabled === true || row.is_virtual !== true && row.status !== "publish") continue;
|
|
1768
|
+
if (!(typeof row.id === "number" || typeof row.id === "string" && row.id.length > 0)) continue;
|
|
1769
|
+
if (typeof row.title !== "string") continue;
|
|
1770
|
+
const id = String(row.id);
|
|
1771
|
+
if (seen.has(id)) continue;
|
|
1772
|
+
seen.add(id);
|
|
1773
|
+
const engine = WOO_ENGINES[row.engine];
|
|
1774
|
+
const paper = engine === "thermal" && (row.paper_width === "58mm" || row.paper_width === "80mm") ? row.paper_width : void 0;
|
|
1775
|
+
templates.push({
|
|
1776
|
+
id,
|
|
1777
|
+
kind,
|
|
1778
|
+
title: row.title,
|
|
1779
|
+
engine,
|
|
1780
|
+
body: row.content,
|
|
1781
|
+
...paper ? { paper } : {},
|
|
1782
|
+
dataModel: "wcpos"
|
|
1783
|
+
});
|
|
1784
|
+
}
|
|
1785
|
+
return templates;
|
|
1786
|
+
}
|
|
1787
|
+
|
|
1569
1788
|
// package.json
|
|
1570
|
-
var version = "3.
|
|
1789
|
+
var version = "3.19.0";
|
|
1571
1790
|
|
|
1572
1791
|
// src/index.ts
|
|
1573
|
-
import { ConnectorUnauthorizedError as
|
|
1792
|
+
import { ConnectorUnauthorizedError as ConnectorUnauthorizedError5 } from "@tallyui/core";
|
|
1574
1793
|
function wcposClientPart(part) {
|
|
1575
1794
|
return part.toLowerCase().replace(/[^a-z0-9._-]/g, "").slice(0, 32);
|
|
1576
1795
|
}
|
|
1577
|
-
var WooMissingTokenError = class extends
|
|
1796
|
+
var WooMissingTokenError = class extends ConnectorUnauthorizedError4 {
|
|
1578
1797
|
constructor() {
|
|
1579
1798
|
super("WooCommerce credentials have no WCPOS access token: sign in again", 401);
|
|
1580
1799
|
this.name = "WooMissingTokenError";
|
|
@@ -1590,6 +1809,7 @@ function createWooCommerceConnector() {
|
|
|
1590
1809
|
...customers,
|
|
1591
1810
|
// WCPOS wcpos/v2/orders: order history (ADR-081).
|
|
1592
1811
|
...createWooOrders(),
|
|
1812
|
+
orderFilters: WOO_ORDER_FILTERS,
|
|
1593
1813
|
replication: {
|
|
1594
1814
|
// One replication per collection; the reconcile feed is last, so its fetch wins duplicates;
|
|
1595
1815
|
// duplicates are matched by uuid, the primary key, not the store id (#331). legacyKey
|
|
@@ -1611,7 +1831,9 @@ var wooConnectorParts = {
|
|
|
1611
1831
|
icon: void 0,
|
|
1612
1832
|
// TODO: WooCommerce logo
|
|
1613
1833
|
storeSettings: wooStoreSettings,
|
|
1834
|
+
paymentMethods: wooPaymentMethods,
|
|
1614
1835
|
capabilities: readWooCapabilities,
|
|
1836
|
+
receiptTemplates: wooReceiptTemplates,
|
|
1615
1837
|
auth: {
|
|
1616
1838
|
type: "WCPOS token",
|
|
1617
1839
|
fields: [
|
|
@@ -1656,7 +1878,8 @@ var wooConnectorParts = {
|
|
|
1656
1878
|
};
|
|
1657
1879
|
var woocommerceConnector = createWooCommerceConnector();
|
|
1658
1880
|
export {
|
|
1659
|
-
|
|
1881
|
+
ConnectorUnauthorizedError5 as ConnectorUnauthorizedError,
|
|
1882
|
+
WOO_NOTE_ORDER_CREATE_VERSION,
|
|
1660
1883
|
WOO_ORDER_CREATE_VERSION,
|
|
1661
1884
|
WooDateFilterError,
|
|
1662
1885
|
WooMissingTokenError,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tallyui/connector-woocommerce",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.19.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "WooCommerce connector for Tally UI",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -27,10 +27,10 @@
|
|
|
27
27
|
"directory": "connectors/woocommerce"
|
|
28
28
|
},
|
|
29
29
|
"peerDependencies": {
|
|
30
|
-
"@tallyui/core": "^3.
|
|
30
|
+
"@tallyui/core": "^3.19.0"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
|
-
"@tallyui/database": "3.
|
|
33
|
+
"@tallyui/database": "3.19.0",
|
|
34
34
|
"rxdb": "17.5.0"
|
|
35
35
|
},
|
|
36
36
|
"scripts": {
|
|
@@ -1,5 +1,5 @@
|
|
|
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 OrderCreateEnvelope } from '@tallyui/core';
|
|
2
|
+
import { minorUnitDigits, moneyFromDecimalString, moneyFromMajor, type CommandResult, type OrderAddress, type OrderCreateEnvelope } from '@tallyui/core';
|
|
3
3
|
|
|
4
4
|
export type WooTransportOutcome =
|
|
5
5
|
| { kind: 'results'; results: CommandResult[] }
|
|
@@ -63,6 +63,14 @@ function decodeCouponMessage(message: unknown): string {
|
|
|
63
63
|
.replace(/\s+/g, ' ').trim() || 'status_400';
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
+
// order.create 8's address keys and wc/v3's names for them (#722).
|
|
67
|
+
const WOO_ADDRESS_KEYS = [['firstName', 'first_name'], ['lastName', 'last_name'], ['company', 'company'], ['address1', 'address_1'],
|
|
68
|
+
['address2', 'address_2'], ['city', 'city'], ['state', 'state'], ['postcode', 'postcode'], ['country', 'country'], ['phone', 'phone']] as const;
|
|
69
|
+
|
|
70
|
+
function wooAddress(address: OrderAddress | undefined): Record<string, string> {
|
|
71
|
+
return Object.fromEntries(WOO_ADDRESS_KEYS.flatMap(([ours, theirs]) => typeof address?.[ours] === 'string' ? [[theirs, address[ours]]] : []));
|
|
72
|
+
}
|
|
73
|
+
|
|
66
74
|
export function toWooOrderPayload(envelope: OrderCreateEnvelope, local?: WooLocalOrder, options?: { paymentsList?: boolean }): { payload: Record<string, unknown> } | { error: { code: string; message: string } } {
|
|
67
75
|
const p = envelope.payload;
|
|
68
76
|
if (p.payments.length === 0 || (p.payments.length > 1 && !options?.paymentsList)) {
|
|
@@ -154,6 +162,10 @@ export function toWooOrderPayload(envelope: OrderCreateEnvelope, local?: WooLoca
|
|
|
154
162
|
...(payment.method === 'cash' && payment.changeMinor !== undefined ? { change: major(payment.changeMinor) } : {}),
|
|
155
163
|
}))) });
|
|
156
164
|
}
|
|
165
|
+
// Version 8 (#722): WCPOS taxes the order on the address its meta names (billing, or shipping with no fallback), else the base.
|
|
166
|
+
if (p.taxAddress) meta_data.push({ key: '_woocommerce_pos_tax_based_on', value: p.taxAddress });
|
|
167
|
+
const billing = { ...(p.customer?.email ? { email: p.customer.email } : {}), ...(p.taxAddress ? wooAddress(p.customer?.billing) : {}) };
|
|
168
|
+
const shipping = p.taxAddress && p.customer?.shipping ? wooAddress(p.customer.shipping) : undefined;
|
|
157
169
|
return { payload: {
|
|
158
170
|
status: 'completed', set_paid: true, currency: p.currency,
|
|
159
171
|
payment_method: cash ? 'pos_cash' : 'pos_card', payment_method_title: cash ? 'Cash' : 'Card',
|
|
@@ -163,7 +175,10 @@ export function toWooOrderPayload(envelope: OrderCreateEnvelope, local?: WooLoca
|
|
|
163
175
|
...(p.coupons?.length ? { coupon_lines: p.coupons.map(({ code }) => ({ code })) } : {}),
|
|
164
176
|
meta_data,
|
|
165
177
|
...(p.customer?.customerId && /^\d+$/.test(p.customer.customerId) ? { customer_id: Number(p.customer.customerId) } : {}),
|
|
166
|
-
...(
|
|
178
|
+
...(Object.keys(billing).length ? { billing } : {}),
|
|
179
|
+
...(shipping ? { shipping } : {}),
|
|
180
|
+
// Version 7 (ADR-083): the till froze and cut the note already, and wc/v3 sanitises it; no note, no key.
|
|
181
|
+
...(typeof p.note === 'string' && p.note.length > 0 ? { customer_note: p.note } : {}),
|
|
167
182
|
} };
|
|
168
183
|
}
|
|
169
184
|
|
package/src/customers.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import {
|
|
2
|
-
CustomerServiceError, type Customer, type CustomerAddress, type CustomerInput, type CustomerPatch, type SyncContext,
|
|
2
|
+
CustomerServiceError, type Customer, type CustomerAddress, type CustomerInput, type CustomerPage, type CustomerPatch, type SyncContext,
|
|
3
3
|
} from '@tallyui/core';
|
|
4
4
|
import { checkResponse } from './replication/products';
|
|
5
5
|
|
|
@@ -8,6 +8,7 @@ type WooCustomerRow = {
|
|
|
8
8
|
first_name?: string | null;
|
|
9
9
|
last_name?: string | null;
|
|
10
10
|
email?: string | null;
|
|
11
|
+
date_created_gmt?: string | null;
|
|
11
12
|
billing?: {
|
|
12
13
|
first_name?: string | null; last_name?: string | null; email?: string | null;
|
|
13
14
|
phone?: string | null; company?: string | null;
|
|
@@ -56,6 +57,8 @@ export function toWooCustomer(raw: WooCustomerRow): Customer {
|
|
|
56
57
|
] as const) {
|
|
57
58
|
if (typeof value === 'string' && value.length > 0) customer[key] = value;
|
|
58
59
|
}
|
|
60
|
+
const created = raw.date_created_gmt; // UTC without a zone suffix; `date_created` is site-local
|
|
61
|
+
if (typeof created === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/.test(created)) customer.createdAt = `${created}Z`;
|
|
59
62
|
customer.name = [customer.firstName, customer.lastName].filter(Boolean).join(' ') || customer.company || customer.email || customer.id;
|
|
60
63
|
return customer;
|
|
61
64
|
}
|
|
@@ -72,7 +75,7 @@ function newWooId(): string {
|
|
|
72
75
|
export async function customerRequest(context: SyncContext, route: string, init: RequestInit = {}) {
|
|
73
76
|
let response: Response;
|
|
74
77
|
try {
|
|
75
|
-
response = await fetch(`${context.baseUrl}/${route}`, {
|
|
78
|
+
response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/${route}`, {
|
|
76
79
|
...init, headers: { ...init.headers, ...context.headers }, signal: context.signal,
|
|
77
80
|
});
|
|
78
81
|
} catch (error) {
|
|
@@ -89,8 +92,12 @@ export async function customerRequest(context: SyncContext, route: string, init:
|
|
|
89
92
|
|
|
90
93
|
export function createWooCustomers(options?: { newId?: () => string }) {
|
|
91
94
|
const newId = options?.newId ?? newWooId;
|
|
92
|
-
|
|
95
|
+
const api = {
|
|
93
96
|
async searchCustomers(context: SyncContext, query: string, options?: { limit?: number }): Promise<Customer[]> {
|
|
97
|
+
return (await api.searchCustomersPage(context, query, { limit: options?.limit })).customers;
|
|
98
|
+
},
|
|
99
|
+
|
|
100
|
+
async searchCustomersPage(context: SyncContext, query: string, options?: { limit?: number; page?: number }): Promise<CustomerPage> {
|
|
94
101
|
const q = query.trim();
|
|
95
102
|
const perPage = String(Math.max(1, Math.min(50, options?.limit ?? 20)));
|
|
96
103
|
// An empty query lists the first page in WCPOS v2's customer-picker order, last name ascending; the wcpos/v2
|
|
@@ -98,9 +105,14 @@ export function createWooCustomers(options?: { newId?: () => string }) {
|
|
|
98
105
|
const params = q
|
|
99
106
|
? new URLSearchParams({ search: q, role: 'customer', per_page: perPage })
|
|
100
107
|
: new URLSearchParams({ role: 'customer', per_page: perPage, orderby: 'last_name', order: 'asc' });
|
|
101
|
-
const
|
|
108
|
+
const requested = options?.page ?? 1;
|
|
109
|
+
const page = Number.isFinite(requested) ? Math.max(1, Math.floor(requested)) : 1;
|
|
110
|
+
if (page > 1) params.append('page', String(page));
|
|
111
|
+
const { body, headers } = await customerRequest(context, `customers?${params}`, { method: 'GET' });
|
|
102
112
|
if (!Array.isArray(body)) throw new CustomerServiceError('server', 'unexpected response');
|
|
103
|
-
|
|
113
|
+
// The wcpos/v2 proxy returns wc/v3's response with its headers, so `X-WP-Total` counts every match.
|
|
114
|
+
const total = headers.get('X-WP-Total');
|
|
115
|
+
return { customers: body.map(toWooCustomer), ...(total && /^\d+$/.test(total) ? { total: Number(total) } : {}) };
|
|
104
116
|
},
|
|
105
117
|
|
|
106
118
|
async getCustomer(context: SyncContext, id: string): Promise<Customer | null> {
|
|
@@ -167,4 +179,5 @@ export function createWooCustomers(options?: { newId?: () => string }) {
|
|
|
167
179
|
if (status !== 200 || body?.success !== true) throw new CustomerServiceError('server', 'unexpected response');
|
|
168
180
|
},
|
|
169
181
|
};
|
|
182
|
+
return api;
|
|
170
183
|
}
|
package/src/index.ts
CHANGED
|
@@ -9,8 +9,10 @@ import { wooCatalogueReconcile } from './reconcile/catalogue';
|
|
|
9
9
|
import { createWooReconcileFeed, MAX_IDS_PER_REQUEST } from './reconcile/feed';
|
|
10
10
|
import { createWooCouponFeed, wooCouponReconcile } from './reconcile/coupons';
|
|
11
11
|
import { createWooCustomers } from './customers';
|
|
12
|
-
import { createWooOrders } from './orders';
|
|
12
|
+
import { createWooOrders, WOO_ORDER_FILTERS } from './orders';
|
|
13
13
|
import { wooStoreSettings, readWooCapabilities } from './store-settings';
|
|
14
|
+
import { wooPaymentMethods } from './payment-methods';
|
|
15
|
+
import { wooReceiptTemplates } from './receipt-templates';
|
|
14
16
|
import { version } from '../package.json';
|
|
15
17
|
|
|
16
18
|
/** One part of X-WCPOS-Client as WCPOS keeps it: lowercase [a-z0-9._-], at most 32 characters. */
|
|
@@ -54,6 +56,7 @@ export function createWooCommerceConnector(): TallyConnector {
|
|
|
54
56
|
...customers,
|
|
55
57
|
// WCPOS wcpos/v2/orders: order history (ADR-081).
|
|
56
58
|
...createWooOrders(),
|
|
59
|
+
orderFilters: WOO_ORDER_FILTERS,
|
|
57
60
|
replication: {
|
|
58
61
|
// One replication per collection; the reconcile feed is last, so its fetch wins duplicates;
|
|
59
62
|
// duplicates are matched by uuid, the primary key, not the store id (#331). legacyKey
|
|
@@ -76,7 +79,9 @@ const wooConnectorParts = {
|
|
|
76
79
|
description: 'Connect to WooCommerce stores via the REST API',
|
|
77
80
|
icon: undefined, // TODO: WooCommerce logo
|
|
78
81
|
storeSettings: wooStoreSettings,
|
|
82
|
+
paymentMethods: wooPaymentMethods,
|
|
79
83
|
capabilities: readWooCapabilities,
|
|
84
|
+
receiptTemplates: wooReceiptTemplates,
|
|
80
85
|
|
|
81
86
|
auth: {
|
|
82
87
|
type: 'WCPOS token',
|
|
@@ -131,7 +136,7 @@ const wooConnectorParts = {
|
|
|
131
136
|
export const woocommerceConnector: TallyConnector = createWooCommerceConnector();
|
|
132
137
|
|
|
133
138
|
// Re-export pieces for advanced usage
|
|
134
|
-
export { wooStoreSettings, readWooCapabilities, WOO_ORDER_CREATE_VERSION } from './store-settings';
|
|
139
|
+
export { wooStoreSettings, readWooCapabilities, WOO_ORDER_CREATE_VERSION, WOO_NOTE_ORDER_CREATE_VERSION } from './store-settings';
|
|
135
140
|
export { createWooCustomers, toWooCustomer } from './customers';
|
|
136
141
|
export { createWooOrders, toWooStoreOrder } from './orders';
|
|
137
142
|
export { createWooCommandTransport, toWooOrderPayload, type WooCommandTransportOptions } from './commands/transport';
|
package/src/orders.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
assertOrderFiltersSupported, CustomerServiceError, minorUnitDigits,
|
|
3
|
+
type OrderFilterField, type PaymentMethodKind, type StoreOrder, type StoreOrderLine, type SyncContext, type TallyConnector,
|
|
4
|
+
} from '@tallyui/core';
|
|
2
5
|
import { customerRequest } from './customers';
|
|
3
6
|
import { wooMinorFromDecimal } from './commands/transport';
|
|
4
7
|
|
|
@@ -133,15 +136,43 @@ export function toWooStoreOrder(raw: unknown): StoreOrder {
|
|
|
133
136
|
|
|
134
137
|
const wholeNumber = (value: number | undefined, fallback: number) => (value === undefined || !Number.isFinite(value) ? fallback : Math.trunc(value));
|
|
135
138
|
|
|
139
|
+
/** The ListOrdersQuery filters `wcpos/v2/orders` honours; it has no payment-method or register filter (it ignores both). */
|
|
140
|
+
export const WOO_ORDER_FILTERS: readonly OrderFilterField[] = ['status', 'customerId', 'cashierId', 'storeId', 'createdVia', 'dateRange'];
|
|
141
|
+
|
|
142
|
+
/** A validated UTC instant, rounded up to the whole second and shifted by `shiftSeconds`, as `YYYY-MM-DDTHH:MM:SS` in UTC. */
|
|
143
|
+
const wooGmtSecond = (instant: string, shiftSeconds: number) =>
|
|
144
|
+
new Date((Math.ceil(Date.parse(instant) / 1000) + shiftSeconds) * 1000).toISOString().slice(0, 19);
|
|
145
|
+
|
|
136
146
|
/** WCPOS `wcpos/v2/orders`: order history, read-only (ADR-081). */
|
|
137
147
|
export function createWooOrders(): Required<Pick<TallyConnector, 'listOrders' | 'getOrders'>> {
|
|
138
148
|
return {
|
|
149
|
+
/**
|
|
150
|
+
* Filters on the server: status, customerId (customer), cashierId (pos_cashier), storeId (pos_store), createdVia
|
|
151
|
+
* (created_via) and dateRange; any other filter field is refused. An id that is not all digits, or an empty status
|
|
152
|
+
* or createdVia, matches no order, so it resolves an empty page without a request. dateRange is sent in GMT (dates_are_gmt): WooCommerce compares
|
|
153
|
+
* whole seconds strictly, so the inclusive `after` goes as its instant rounded up to the second minus one second,
|
|
154
|
+
* and the exclusive `before` as its instant rounded up to the second.
|
|
155
|
+
*/
|
|
139
156
|
async listOrders(context: SyncContext, query = {}) {
|
|
157
|
+
assertOrderFiltersSupported(query, WOO_ORDER_FILTERS);
|
|
158
|
+
if (query.status === '' || query.createdVia === '') return { orders: [], hasMore: false };
|
|
140
159
|
const page = Math.max(1, wholeNumber(query.page, 1));
|
|
141
160
|
const perPage = Math.max(1, Math.min(MAX_PER_PAGE, wholeNumber(query.perPage, 25)));
|
|
142
161
|
const params = new URLSearchParams({ page: String(page), per_page: String(perPage), orderby: 'date', order: 'desc' });
|
|
143
162
|
const search = query.search?.trim();
|
|
144
163
|
if (search) params.set('search', search);
|
|
164
|
+
if (query.status !== undefined) params.set('status', query.status);
|
|
165
|
+
const ids = [['customer', query.customerId], ['pos_cashier', query.cashierId], ['pos_store', query.storeId]] as const;
|
|
166
|
+
for (const [param, id] of ids) {
|
|
167
|
+
if (id === undefined) continue;
|
|
168
|
+
if (!/^\d+$/.test(id)) return { orders: [], hasMore: false };
|
|
169
|
+
params.set(param, id);
|
|
170
|
+
}
|
|
171
|
+
if (query.createdVia !== undefined) params.set('created_via', query.createdVia);
|
|
172
|
+
const { after, before } = query.dateRange ?? {};
|
|
173
|
+
if (after !== undefined || before !== undefined) params.set('dates_are_gmt', 'true');
|
|
174
|
+
if (after !== undefined) params.set('after', wooGmtSecond(after, -1));
|
|
175
|
+
if (before !== undefined) params.set('before', wooGmtSecond(before, 0));
|
|
145
176
|
const { body, headers } = await customerRequest(context, `orders?${params}`, { method: 'GET' });
|
|
146
177
|
if (!Array.isArray(body)) throw unexpected();
|
|
147
178
|
const orders = body.map(toWooStoreOrder);
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { ConnectorUnauthorizedError, defaultPaymentMethods } from '@tallyui/core';
|
|
2
|
+
import type { CaptureModeEntry, PaymentHardware, PaymentMethodDescriptor, PaymentRounding, SyncContext } from '@tallyui/core';
|
|
3
|
+
|
|
4
|
+
import { wooMinorFromDecimal } from './commands/transport';
|
|
5
|
+
|
|
6
|
+
// The plugin's own default `order` for a gateway without one (woocommerce-pos Descriptor_Builder.php).
|
|
7
|
+
const WOO_DEFAULT_ORDER = 999;
|
|
8
|
+
|
|
9
|
+
type Row = Record<string, unknown>;
|
|
10
|
+
/** A row that passed the shape check; open-vocabulary values pass through as the wire has them. */
|
|
11
|
+
type WireRow = Row & { id: string; kind: string; capture: Row & { mode: string }; capabilities: Row };
|
|
12
|
+
|
|
13
|
+
const isObject = (value: unknown): value is Row => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
14
|
+
const objectOr = (value: unknown): Row => (isObject(value) ? value : {});
|
|
15
|
+
const stringOr = <T>(value: unknown, fallback: T): string | T => (typeof value === 'string' ? value : fallback);
|
|
16
|
+
const isModeEntry = (value: unknown): value is Row & { mode: string } => isObject(value) && typeof value.mode === 'string';
|
|
17
|
+
|
|
18
|
+
function toHardware(value: unknown): PaymentHardware | null {
|
|
19
|
+
if (!isObject(value)) return null;
|
|
20
|
+
const discovery = value.discovery as string;
|
|
21
|
+
if (Array.isArray(value.readers)) {
|
|
22
|
+
return { discovery, defaultReader: (value.default_reader as string | null | undefined) ?? null, lockToDefault: value.lock_to_default === true,
|
|
23
|
+
readers: value.readers.filter((reader): reader is Row => isObject(reader) && typeof reader.id === 'string')
|
|
24
|
+
.map((reader) => ({ id: reader.id as string, label: reader.label as string, status: reader.status as string, default: reader.default === true })) };
|
|
25
|
+
}
|
|
26
|
+
if (!Array.isArray(value.transports)) return null;
|
|
27
|
+
return { discovery, transports: value.transports.map(objectOr)
|
|
28
|
+
.map((entry) => ({ transport: entry.transport as string, offline: entry.offline as string, tips: entry.tips as string })) };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function toCaptureEntry(value: Row & { mode: string }): CaptureModeEntry {
|
|
32
|
+
return { mode: value.mode, provider: stringOr(value.provider, null), hardware: toHardware(value.hardware) };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Whether the row carries a money string, which needs the store currency to convert. */
|
|
36
|
+
function hasMoneyString(row: WireRow): boolean {
|
|
37
|
+
const amount = objectOr(row.capabilities.amount), rounding = objectOr(objectOr(row.defaults).rounding);
|
|
38
|
+
return typeof amount.min === 'string' || typeof amount.max === 'string' || typeof rounding.increment === 'string';
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Only /stores, not wooStoreSettings: that also pages through every tax rate.
|
|
42
|
+
async function storeCurrency(context: SyncContext): Promise<string> {
|
|
43
|
+
// Any failure but a refusal is "no store currency".
|
|
44
|
+
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/stores`, { method: 'GET', headers: context.headers, signal: context.signal }).catch(() => undefined);
|
|
45
|
+
if (response?.status === 401 || response?.status === 403) throw new ConnectorUnauthorizedError(`WooCommerce stores: HTTP ${response.status}`, response.status);
|
|
46
|
+
const stores: unknown = response?.ok ? await response.json().catch(() => undefined) : undefined;
|
|
47
|
+
const currency = Array.isArray(stores) ? objectOr(stores[0]).currency : undefined;
|
|
48
|
+
if (typeof currency !== 'string') throw new Error('WooCommerce payment methods: no store currency');
|
|
49
|
+
return currency.toUpperCase();
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function toRounding(value: unknown, currency: string, id: string): PaymentRounding {
|
|
53
|
+
if (value === null || value === undefined) return null;
|
|
54
|
+
const { increment, mode } = objectOr(value);
|
|
55
|
+
const incrementMinor = typeof increment === 'string' ? wooMinorFromDecimal(increment, currency) : undefined;
|
|
56
|
+
if (incrementMinor === undefined || incrementMinor <= 0 || (mode !== 'nearest' && mode !== 'up' && mode !== 'down')) {
|
|
57
|
+
console.warn(`WooCommerce payment method ${id}: unreadable cash rounding; the till does not round it`);
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
return { incrementMinor, mode };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** `undefined` when a present bound does not convert: the till cannot enforce a limit it cannot read. */
|
|
64
|
+
function toAmount(amount: Row, currency: string): PaymentMethodDescriptor['capabilities']['amount'] | undefined {
|
|
65
|
+
const result: PaymentMethodDescriptor['capabilities']['amount'] = { partial: amount.partial === true };
|
|
66
|
+
for (const [wire, key] of [['min', 'minMinor'], ['max', 'maxMinor']] as const) {
|
|
67
|
+
const text = amount[wire];
|
|
68
|
+
if (text === undefined) continue;
|
|
69
|
+
const minor = typeof text === 'string' ? wooMinorFromDecimal(text, currency) : undefined;
|
|
70
|
+
if (minor === undefined) return undefined;
|
|
71
|
+
result[key] = minor;
|
|
72
|
+
}
|
|
73
|
+
return result;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function toDescriptor(row: WireRow, currency: string): PaymentMethodDescriptor | undefined {
|
|
77
|
+
const caps = row.capabilities, defaults = objectOr(row.defaults);
|
|
78
|
+
const amount = toAmount(objectOr(caps.amount), currency);
|
|
79
|
+
if (!amount) {
|
|
80
|
+
console.warn(`WooCommerce payment method ${row.id}: unreadable amount limit; dropped`);
|
|
81
|
+
return undefined;
|
|
82
|
+
}
|
|
83
|
+
const refunds = objectOr(caps.refunds);
|
|
84
|
+
return {
|
|
85
|
+
id: row.id,
|
|
86
|
+
title: typeof row.title === 'string' && row.title.length > 0 ? row.title : row.id,
|
|
87
|
+
kind: row.kind,
|
|
88
|
+
capture: { ...toCaptureEntry(row.capture),
|
|
89
|
+
...(Array.isArray(row.capture.modes) ? { modes: row.capture.modes.filter(isModeEntry).map(toCaptureEntry) } : {}) },
|
|
90
|
+
capabilities: {
|
|
91
|
+
amount, change: caps.change === true, void: caps.void === true,
|
|
92
|
+
refunds: { via: stringOr(refunds.via, 'none'), partial: refunds.partial === true },
|
|
93
|
+
tips: stringOr(caps.tips, 'none'), offline: stringOr(caps.offline, 'none'),
|
|
94
|
+
},
|
|
95
|
+
defaults: { rounding: toRounding(defaults.rounding, currency, row.id), openDrawer: defaults.open_drawer === true },
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** WCPOS wcpos/v2/payment-methods (woocommerce-pos >= 2.0.0, contract 1.3) mapped to the till's payment methods; read-only. */
|
|
100
|
+
export async function wooPaymentMethods(context: SyncContext): Promise<PaymentMethodDescriptor[]> {
|
|
101
|
+
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/payment-methods`, { method: 'GET', headers: context.headers, signal: context.signal });
|
|
102
|
+
// The route shipped in woocommerce-pos 2.0.0; an older plugin keeps today's two methods.
|
|
103
|
+
if (response.status === 404) return defaultPaymentMethods();
|
|
104
|
+
if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError(`WooCommerce payment methods: HTTP ${response.status}`, response.status);
|
|
105
|
+
if (!response.ok) throw new Error(`WooCommerce payment methods: HTTP ${response.status}`);
|
|
106
|
+
const body: unknown = await response.json();
|
|
107
|
+
if (!isObject(body) || !Number.isInteger(body.schema) || typeof body.contract !== 'string' || !Array.isArray(body.methods)) {
|
|
108
|
+
throw new Error('WooCommerce payment methods: unexpected response');
|
|
109
|
+
}
|
|
110
|
+
// v2 refuses to take payments on an unknown schema until the app is updated (contract §13).
|
|
111
|
+
if (body.schema !== 1) throw new Error(`WooCommerce payment methods: unsupported schema ${body.schema}`);
|
|
112
|
+
|
|
113
|
+
const valid = body.methods.filter((row: unknown, index): row is WireRow => {
|
|
114
|
+
const ok = isObject(row) && row.schema === 1 && typeof row.id === 'string' && row.id.length > 0 && typeof row.kind === 'string'
|
|
115
|
+
&& isModeEntry(row.capture) && isObject(row.capabilities);
|
|
116
|
+
if (!ok) {
|
|
117
|
+
const id = isObject(row) && typeof row.id === 'string' && row.id.length > 0 ? row.id : `at index ${index}`;
|
|
118
|
+
console.warn(`WooCommerce payment method ${id}: malformed descriptor; dropped`);
|
|
119
|
+
}
|
|
120
|
+
return ok;
|
|
121
|
+
});
|
|
122
|
+
if (body.methods.length > 0 && valid.length === 0) {
|
|
123
|
+
// As v2 does: a broken payload is not an empty till.
|
|
124
|
+
console.warn('WooCommerce payment methods: every descriptor is malformed; offering the default methods');
|
|
125
|
+
return defaultPaymentMethods();
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const order = (row: WireRow) => (typeof row.order === 'number' ? row.order : WOO_DEFAULT_ORDER);
|
|
129
|
+
const enabled = valid.filter((row) => row.pos_enabled === true).sort((a, b) => order(a) - order(b));
|
|
130
|
+
// Without a money string nothing converts, so the empty currency is never read.
|
|
131
|
+
const currency = enabled.some(hasMoneyString) ? await storeCurrency(context) : '';
|
|
132
|
+
return enabled.map((row) => toDescriptor(row, currency)).filter((row): row is PaymentMethodDescriptor => row !== undefined);
|
|
133
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { ReceiptTemplate, ReceiptTemplateKind, SyncContext } from '@tallyui/core';
|
|
2
|
+
import { checkResponse } from './replication/products';
|
|
3
|
+
|
|
4
|
+
type WooTemplateRow = {
|
|
5
|
+
id?: unknown;
|
|
6
|
+
title?: unknown;
|
|
7
|
+
type?: unknown;
|
|
8
|
+
engine?: unknown;
|
|
9
|
+
content?: unknown;
|
|
10
|
+
paper_width?: unknown;
|
|
11
|
+
status?: unknown;
|
|
12
|
+
is_virtual?: unknown;
|
|
13
|
+
is_disabled?: unknown;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
// WCPOS's offline-capable engines and the TallyUI renderer each maps to; legacy-php bodies run only on the server.
|
|
17
|
+
const WOO_ENGINES = { logicless: 'html', thermal: 'thermal' } as const;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* WCPOS wcpos/v2/templates: the store's templates of one kind, in the plugin's order (as v2's templates sync keeps it).
|
|
21
|
+
* Only published or virtual, enabled rows with a body the till can render; all carry WCPOS's data model.
|
|
22
|
+
*/
|
|
23
|
+
export async function wooReceiptTemplates(context: SyncContext, kind: ReceiptTemplateKind = 'receipt'): Promise<ReceiptTemplate[]> {
|
|
24
|
+
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/templates${kind === 'receipt' ? '' : `?type=${kind}`}`, {
|
|
25
|
+
method: 'GET', headers: context.headers, signal: context.signal,
|
|
26
|
+
});
|
|
27
|
+
if (response.status === 404) return [];
|
|
28
|
+
if (!response.ok) {
|
|
29
|
+
await checkResponse(response);
|
|
30
|
+
throw new Error(`WooCommerce API error: ${response.status}`);
|
|
31
|
+
}
|
|
32
|
+
const rows: unknown = await response.json().catch(() => undefined);
|
|
33
|
+
if (!Array.isArray(rows)) throw new Error('connector-woocommerce: unexpected templates response');
|
|
34
|
+
|
|
35
|
+
const templates: ReceiptTemplate[] = [];
|
|
36
|
+
const seen = new Set<string>();
|
|
37
|
+
for (const row of rows as (WooTemplateRow | null)[]) {
|
|
38
|
+
if (typeof row !== 'object' || row === null || row.type !== kind) continue;
|
|
39
|
+
if (row.engine !== 'logicless' && row.engine !== 'thermal') continue;
|
|
40
|
+
if (typeof row.content !== 'string' || row.content.length === 0) continue;
|
|
41
|
+
if (row.is_disabled === true || (row.is_virtual !== true && row.status !== 'publish')) continue;
|
|
42
|
+
if (!(typeof row.id === 'number' || (typeof row.id === 'string' && row.id.length > 0))) continue;
|
|
43
|
+
if (typeof row.title !== 'string') continue;
|
|
44
|
+
const id = String(row.id);
|
|
45
|
+
if (seen.has(id)) continue;
|
|
46
|
+
seen.add(id);
|
|
47
|
+
const engine = WOO_ENGINES[row.engine];
|
|
48
|
+
const paper = engine === 'thermal' && (row.paper_width === '58mm' || row.paper_width === '80mm') ? row.paper_width : undefined;
|
|
49
|
+
templates.push({
|
|
50
|
+
id, kind, title: row.title, engine, body: row.content, ...(paper ? { paper } : {}), dataModel: 'wcpos',
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
return templates;
|
|
54
|
+
}
|
|
@@ -19,7 +19,7 @@ export const wooReconcileFingerprint = (p: { date_modified_gmt?: string | null;
|
|
|
19
19
|
[p.date_modified_gmt ?? '', p.stock_quantity ?? '', p.stock_status ?? ''].join('|');
|
|
20
20
|
|
|
21
21
|
async function get(path: string, context: SyncContext): Promise<any> {
|
|
22
|
-
const response = await fetch(`${context.baseUrl}${path}`, {
|
|
22
|
+
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}${path}`, {
|
|
23
23
|
headers: { ...context.headers, 'Content-Type': 'application/json' },
|
|
24
24
|
signal: context.signal,
|
|
25
25
|
});
|
package/src/reconcile/coupons.ts
CHANGED
|
@@ -13,7 +13,7 @@ export const wooCouponFingerprint = (c: { date_modified_gmt?: string | null; usa
|
|
|
13
13
|
[c.date_modified_gmt ?? '', c.usage_count ?? '', JSON.stringify((c.used_by ?? []).map(String))].join('|');
|
|
14
14
|
|
|
15
15
|
async function get(path: string, context: SyncContext): Promise<any> {
|
|
16
|
-
const response = await fetch(`${context.baseUrl}${path}`, {
|
|
16
|
+
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}${path}`, {
|
|
17
17
|
headers: { ...context.headers, 'Content-Type': 'application/json' },
|
|
18
18
|
signal: context.signal,
|
|
19
19
|
});
|
package/src/reconcile/feed.ts
CHANGED
|
@@ -15,7 +15,7 @@ export async function wooFetchByIds(entries: Array<ReconcileFetchEntry<any>>, co
|
|
|
15
15
|
for (let i = 0; i < ids.length; i += MAX_IDS_PER_REQUEST) {
|
|
16
16
|
const chunk = ids.slice(i, i + MAX_IDS_PER_REQUEST);
|
|
17
17
|
const params = new URLSearchParams({ include: chunk.join(','), per_page: String(MAX_IDS_PER_REQUEST), status: 'any' });
|
|
18
|
-
const response = await fetch(`${context.baseUrl}/products?${params}`, {
|
|
18
|
+
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/products?${params}`, {
|
|
19
19
|
headers: { ...context.headers, 'Content-Type': 'application/json' },
|
|
20
20
|
signal: context.signal,
|
|
21
21
|
});
|
|
@@ -107,6 +107,8 @@ export function toProductDocument(product: any): any {
|
|
|
107
107
|
const projected = Object.fromEntries(Object.keys(wooProductSchema.properties)
|
|
108
108
|
.filter((key) => Object.prototype.hasOwnProperty.call(product, key))
|
|
109
109
|
.map((key) => [key, product[key]]));
|
|
110
|
+
// The schema types meta value as a string; WCPOS 1.10.20 sends object meta such as _woocommerce_pos_variable_prices.
|
|
111
|
+
if (Array.isArray(projected.meta_data)) projected.meta_data = projected.meta_data.filter((entry: { value?: unknown } | null) => typeof entry?.value === 'string');
|
|
110
112
|
return { ...projected, uuid, ...(barcode !== undefined ? { barcode } : {}), _deleted: product.status !== 'publish' };
|
|
111
113
|
}
|
|
112
114
|
|
|
@@ -166,7 +168,7 @@ export const wooProductReplication: ReplicationAdapter<any, WooProductCheckpoint
|
|
|
166
168
|
// formats it back in that zone, so an offset would move the bound to local time before the post_modified_gmt comparison.
|
|
167
169
|
const newer: Record<string, string> = modified ? { modified_after: modified, dates_are_gmt: 'true' } : {};
|
|
168
170
|
const mark = new URLSearchParams({ per_page: '1', orderby: 'modified', order: 'desc', ...newer });
|
|
169
|
-
const markResponse = await fetch(
|
|
171
|
+
const markResponse = await (context.fetch ?? globalThis.fetch)(
|
|
170
172
|
`${context.baseUrl}/products?${mark}`,
|
|
171
173
|
{ headers: { ...context.headers, 'Content-Type': 'application/json' }, signal: context.signal },
|
|
172
174
|
);
|
|
@@ -192,7 +194,7 @@ export const wooProductReplication: ReplicationAdapter<any, WooProductCheckpoint
|
|
|
192
194
|
}
|
|
193
195
|
|
|
194
196
|
if (requests++ >= MAX_REQUESTS_PER_CALL) return spent;
|
|
195
|
-
const response = await fetch(`${context.baseUrl}/products?${params}`, {
|
|
197
|
+
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/products?${params}`, {
|
|
196
198
|
headers: {
|
|
197
199
|
...context.headers,
|
|
198
200
|
'Content-Type': 'application/json',
|
|
@@ -225,7 +227,7 @@ export const wooProductReplication: ReplicationAdapter<any, WooProductCheckpoint
|
|
|
225
227
|
for (let i = 0; i < variationIds.length; i += 100) {
|
|
226
228
|
const chunk = variationIds.slice(i, i + 100);
|
|
227
229
|
const variationParams = new URLSearchParams({ include: chunk.join(','), per_page: String(chunk.length), orderby: 'id', order: 'asc' });
|
|
228
|
-
const response = await fetch(`${context.baseUrl}/variations?${variationParams}`, {
|
|
230
|
+
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/variations?${variationParams}`, {
|
|
229
231
|
headers: { ...context.headers, 'Content-Type': 'application/json' }, signal: context.signal,
|
|
230
232
|
});
|
|
231
233
|
await checkResponse(response);
|
package/src/store-settings.ts
CHANGED
|
@@ -3,8 +3,11 @@ import type { ServerCapabilities, StoreSettings, SyncContext } from '@tallyui/co
|
|
|
3
3
|
|
|
4
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). Coupons make 6 (ADR-077 d4a-woo). */
|
|
5
5
|
export const WOO_ORDER_CREATE_VERSION = 5;
|
|
6
|
-
|
|
7
|
-
const
|
|
6
|
+
/** 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
|
+
export const WOO_NOTE_ORDER_CREATE_VERSION = 7;
|
|
8
|
+
/** 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
|
+
* meta with the order's billing and shipping, which push/orders already passes through; a store takes it wherever it takes 7. */
|
|
10
|
+
export const WOO_TAX_ADDRESS_ORDER_CREATE_VERSION = 8;
|
|
8
11
|
// The order.create version a store gets unless /status lists order_create_v5, which only the TallyUI fork of the plugin advertises.
|
|
9
12
|
const WOO_BASE_ORDER_CREATE_VERSION = 3;
|
|
10
13
|
// The first woocommerce-pos release whose coupon recalculation keeps the POS price (ADR-077 amendment 4, R2: 1.9.0, 2026-05-15).
|
|
@@ -25,7 +28,7 @@ export function wooPluginSupportsCoupons(version: unknown): boolean {
|
|
|
25
28
|
export async function wooStoreSettings(context: SyncContext): Promise<StoreSettings> {
|
|
26
29
|
try {
|
|
27
30
|
const init = { method: 'GET', headers: context.headers, signal: context.signal };
|
|
28
|
-
const storesResponse = await fetch(`${context.baseUrl}/stores`, init);
|
|
31
|
+
const storesResponse = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/stores`, init);
|
|
29
32
|
if (storesResponse.status === 401 || storesResponse.status === 403) {
|
|
30
33
|
throw new ConnectorUnauthorizedError(`WooCommerce stores: HTTP ${storesResponse.status}`, storesResponse.status);
|
|
31
34
|
}
|
|
@@ -39,7 +42,7 @@ export async function wooStoreSettings(context: SyncContext): Promise<StoreSetti
|
|
|
39
42
|
console.warn(`WooCommerce price_num_decimals is ${store.price_num_decimals}; the till rounds ${currency} to ${digits} digits`);
|
|
40
43
|
}
|
|
41
44
|
|
|
42
|
-
const classesResponse = await fetch(`${context.baseUrl}/taxes/classes`, init);
|
|
45
|
+
const classesResponse = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/taxes/classes`, init);
|
|
43
46
|
if (classesResponse.status === 401 || classesResponse.status === 403) {
|
|
44
47
|
throw new ConnectorUnauthorizedError(`WooCommerce tax classes: HTTP ${classesResponse.status}`, classesResponse.status);
|
|
45
48
|
}
|
|
@@ -61,10 +64,12 @@ export async function wooStoreSettings(context: SyncContext): Promise<StoreSetti
|
|
|
61
64
|
taxRatesPpm,
|
|
62
65
|
};
|
|
63
66
|
if (store.calc_taxes !== 'yes') return settings;
|
|
67
|
+
// The per-store basis WCPOS v2's till reads, not WooCommerce's woocommerce_tax_based_on option.
|
|
68
|
+
settings.taxBasedOn = woocommerceTax.normalizeTaxBasedOn(store.tax_based_on);
|
|
64
69
|
|
|
65
70
|
const rates: woocommerceTax.WooTaxRate[] = [];
|
|
66
71
|
for (let page = 1; page <= 100; page++) {
|
|
67
|
-
const response = await fetch(`${context.baseUrl}/taxes?per_page=100&page=${page}&orderby=order&order=asc`, init);
|
|
72
|
+
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/taxes?per_page=100&page=${page}&orderby=order&order=asc`, init);
|
|
68
73
|
if (response.status === 401 || response.status === 403) {
|
|
69
74
|
throw new ConnectorUnauthorizedError(`WooCommerce taxes: HTTP ${response.status}`, response.status);
|
|
70
75
|
}
|
|
@@ -101,6 +106,11 @@ export async function wooStoreSettings(context: SyncContext): Promise<StoreSetti
|
|
|
101
106
|
console.warn('WooCommerce has no tax or store country; matching tax rates with an empty address');
|
|
102
107
|
address = {};
|
|
103
108
|
}
|
|
109
|
+
const text = (value: unknown): string => (typeof value === 'string' ? value : '');
|
|
110
|
+
const baseTaxAddress = { country: text(address.country), state: text(address.state), city: text(address.city), postcode: text(address.postcode) };
|
|
111
|
+
if (baseTaxAddress.country) settings.baseTaxAddress = baseTaxAddress;
|
|
112
|
+
// The whole table, for re-taxing a sale on the customer's address: order.create 8 tells the server which address it was (#722).
|
|
113
|
+
if (baseTaxAddress.country) settings.taxRateTable = rates;
|
|
104
114
|
const matched = woocommerceTax.filterTaxRates(rates, address.country, address.state, address.postcode, address.city);
|
|
105
115
|
for (const rate of matched) {
|
|
106
116
|
const slug = woocommerceTax.normalizeTaxClass(rate.class);
|
|
@@ -125,7 +135,7 @@ export async function wooStoreSettings(context: SyncContext): Promise<StoreSetti
|
|
|
125
135
|
|
|
126
136
|
export async function readWooCapabilities(context: SyncContext): Promise<ServerCapabilities | undefined> {
|
|
127
137
|
try {
|
|
128
|
-
const response = await fetch(`${context.baseUrl}/stores`, {
|
|
138
|
+
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/stores`, {
|
|
129
139
|
method: 'GET', headers: context.headers, signal: context.signal,
|
|
130
140
|
});
|
|
131
141
|
if (response.status === 401 || response.status === 403) {
|
|
@@ -137,7 +147,7 @@ export async function readWooCapabilities(context: SyncContext): Promise<ServerC
|
|
|
137
147
|
let multiplePayments = false;
|
|
138
148
|
let capabilities: unknown[] = [];
|
|
139
149
|
try {
|
|
140
|
-
const status = await fetch(`${context.baseUrl}/status`, {
|
|
150
|
+
const status = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/status`, {
|
|
141
151
|
method: 'GET', headers: context.headers, signal: context.signal,
|
|
142
152
|
});
|
|
143
153
|
if (status.status === 401 || status.status === 403) {
|
|
@@ -153,7 +163,7 @@ export async function readWooCapabilities(context: SyncContext): Promise<ServerC
|
|
|
153
163
|
}
|
|
154
164
|
let coupons = false;
|
|
155
165
|
try {
|
|
156
|
-
const site = await fetch(`${context.baseUrl}/site`, {
|
|
166
|
+
const site = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/site`, {
|
|
157
167
|
method: 'GET', headers: context.headers, signal: context.signal,
|
|
158
168
|
});
|
|
159
169
|
if (site.ok) {
|
|
@@ -164,7 +174,7 @@ export async function readWooCapabilities(context: SyncContext): Promise<ServerC
|
|
|
164
174
|
coupons = false;
|
|
165
175
|
}
|
|
166
176
|
const orderCreate = capabilities.includes('order_create_v5')
|
|
167
|
-
? (coupons ?
|
|
177
|
+
? (coupons ? WOO_TAX_ADDRESS_ORDER_CREATE_VERSION : WOO_ORDER_CREATE_VERSION) : WOO_BASE_ORDER_CREATE_VERSION;
|
|
168
178
|
return {
|
|
169
179
|
orderCreate,
|
|
170
180
|
taxRounding: { granularity: 'woocommerce', roundAtSubtotal: stores[0].tax_round_at_subtotal === 'yes' },
|
package/src/sync/products.ts
CHANGED
|
@@ -9,7 +9,7 @@ import type { CollectionSync, SyncContext, RemoteIdEntry } from '@tallyui/core';
|
|
|
9
9
|
*/
|
|
10
10
|
export const wooProductSync: CollectionSync = {
|
|
11
11
|
async fetchAllIds(context: SyncContext): Promise<RemoteIdEntry[]> {
|
|
12
|
-
const response = await fetch(`${context.baseUrl}/products`, {
|
|
12
|
+
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/products`, {
|
|
13
13
|
headers: {
|
|
14
14
|
...context.headers,
|
|
15
15
|
'Content-Type': 'application/json',
|
|
@@ -31,7 +31,7 @@ export const wooProductSync: CollectionSync = {
|
|
|
31
31
|
async fetchByIds(ids: string[], context: SyncContext): Promise<any[]> {
|
|
32
32
|
// WooCommerce supports ?include=1,2,3 for bulk fetching
|
|
33
33
|
const include = ids.join(',');
|
|
34
|
-
const response = await fetch(
|
|
34
|
+
const response = await (context.fetch ?? globalThis.fetch)(
|
|
35
35
|
`${context.baseUrl}/products?include=${include}&per_page=${ids.length}`,
|
|
36
36
|
{
|
|
37
37
|
headers: {
|
|
@@ -55,7 +55,7 @@ export const wooProductSync: CollectionSync = {
|
|
|
55
55
|
dates_are_gmt: 'true',
|
|
56
56
|
per_page: '100',
|
|
57
57
|
});
|
|
58
|
-
const response = await fetch(
|
|
58
|
+
const response = await (context.fetch ?? globalThis.fetch)(
|
|
59
59
|
`${context.baseUrl}/products?${params}`,
|
|
60
60
|
{
|
|
61
61
|
headers: {
|