@tallyui/connector-woocommerce 3.10.0 → 3.12.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 +7 -2
- package/dist/index.js +351 -186
- package/package.json +3 -3
- package/src/commands/transport.ts +13 -1
- package/src/customers.ts +2 -2
- package/src/index.ts +4 -0
- package/src/orders.ts +168 -0
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { SyncContext, ServerCapabilities, StoreSettings, Customer, CustomerInput, OrderCreateEnvelope, CommandResult, ReconcileFeed, CatalogueReconcileAdapter, ProductTraits, CollectionSync, ReplicationAdapter, ConnectorUnauthorizedError
|
|
1
|
+
import { SyncContext, ServerCapabilities, StoreSettings, Customer, CustomerInput, 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
|
|
|
@@ -34,6 +34,11 @@ declare function createWooCustomers(options?: {
|
|
|
34
34
|
}): Promise<void>;
|
|
35
35
|
};
|
|
36
36
|
|
|
37
|
+
/** Maps a WooCommerce order resource (as WCPOS `wcpos/v2/orders` serves it) to a `StoreOrder` (ADR-081). */
|
|
38
|
+
declare function toWooStoreOrder(raw: unknown): StoreOrder;
|
|
39
|
+
/** WCPOS `wcpos/v2/orders`: order history, read-only (ADR-081). */
|
|
40
|
+
declare function createWooOrders(): Required<Pick<TallyConnector, 'listOrders' | 'getOrders'>>;
|
|
41
|
+
|
|
37
42
|
type WooTransportOutcome = {
|
|
38
43
|
kind: 'results';
|
|
39
44
|
results: CommandResult[];
|
|
@@ -256,4 +261,4 @@ declare function createWooCommerceConnector(): TallyConnector;
|
|
|
256
261
|
*/
|
|
257
262
|
declare const woocommerceConnector: TallyConnector;
|
|
258
263
|
|
|
259
|
-
export { WOO_ORDER_CREATE_VERSION, type WooCommandTransportOptions, WooDateFilterError, WooMissingTokenError, WooMissingUuidError, WooTillUpdateRequiredError, WooTokenRefusedError, createWooCommandTransport, createWooCommerceConnector, createWooCouponFeed, createWooCustomers, readWooCapabilities, toCouponDocument, toWooCustomer, toWooOrderPayload, wcposClientPart, wooCatalogueReconcile, wooCouponFingerprint, wooCouponReconcile, wooCouponSchema, wooProductReplication, wooProductSchema, wooProductSync, wooProductTraits, wooReconcileFingerprint, wooStoreSettings, woocommerceConnector };
|
|
264
|
+
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 };
|
package/dist/index.js
CHANGED
|
@@ -673,24 +673,24 @@ async function wooHasIdFastPath(context) {
|
|
|
673
673
|
function wooBulkListingUrl(baseUrl) {
|
|
674
674
|
return `${baseUrl}/products?${new URLSearchParams({ per_page: "-1", _fields: LISTING_FIELDS })}`;
|
|
675
675
|
}
|
|
676
|
-
var toEntries = (
|
|
676
|
+
var toEntries = (rows2) => rows2.filter((row) => Number.isInteger(row?.id)).map((row) => ({ key: String(row.id), fingerprint: wooReconcileFingerprint(row), remote: row.id }));
|
|
677
677
|
function wooCatalogueReconcile(feed) {
|
|
678
678
|
return {
|
|
679
679
|
async *fetchPages(context, from = 1) {
|
|
680
680
|
const fast = await wooHasIdFastPath(context);
|
|
681
681
|
yield { entries: [], cursor: from };
|
|
682
682
|
if (fast) {
|
|
683
|
-
let
|
|
683
|
+
let rows2;
|
|
684
684
|
let failed = false;
|
|
685
685
|
try {
|
|
686
|
-
|
|
686
|
+
rows2 = await get(wooBulkListingUrl(""), context);
|
|
687
687
|
} catch (error) {
|
|
688
688
|
if (errorKind(error) === "till" || context.signal?.aborted) throw error;
|
|
689
689
|
failed = true;
|
|
690
690
|
console.warn(`WooCommerce catalogue reconcile: the fast path failed (${error?.message ?? error}); listing page by page.`);
|
|
691
691
|
}
|
|
692
|
-
if (Array.isArray(
|
|
693
|
-
yield { entries: toEntries(
|
|
692
|
+
if (Array.isArray(rows2)) {
|
|
693
|
+
yield { entries: toEntries(rows2), cursor: from };
|
|
694
694
|
return;
|
|
695
695
|
}
|
|
696
696
|
if (!failed) console.warn("WooCommerce catalogue reconcile: the fast path answered with something that is not a list; listing page by page.");
|
|
@@ -705,9 +705,9 @@ function wooCatalogueReconcile(feed) {
|
|
|
705
705
|
status: "publish",
|
|
706
706
|
_fields: LISTING_FIELDS
|
|
707
707
|
});
|
|
708
|
-
const
|
|
709
|
-
yield { entries: toEntries(
|
|
710
|
-
if (
|
|
708
|
+
const rows2 = await get(`/products?${params}`, context);
|
|
709
|
+
yield { entries: toEntries(rows2), cursor: page + 1 };
|
|
710
|
+
if (rows2.length < PAGE_SIZE) return;
|
|
711
711
|
}
|
|
712
712
|
},
|
|
713
713
|
fingerprint: wooReconcileFingerprint,
|
|
@@ -717,8 +717,8 @@ function wooCatalogueReconcile(feed) {
|
|
|
717
717
|
const ids = locals.map((doc) => doc.id).filter((id) => Number.isInteger(id));
|
|
718
718
|
if (!ids.length) return [];
|
|
719
719
|
const params = new URLSearchParams({ include: ids.join(","), per_page: String(PAGE_SIZE), status: "any", _fields: "id,uuid,status,meta_data" });
|
|
720
|
-
const
|
|
721
|
-
const live = new Map(
|
|
720
|
+
const rows2 = await get(`/products?${params}`, context);
|
|
721
|
+
const live = new Map(rows2.filter((row) => row.status === "publish").map((row) => [row.id, wooProductUuid(row)]));
|
|
722
722
|
return locals.filter((doc) => Number.isInteger(doc.id) && (!live.has(doc.id) || typeof live.get(doc.id) === "string" && live.get(doc.id) !== doc.uuid)).map((doc) => doc.uuid);
|
|
723
723
|
},
|
|
724
724
|
// An entry with no numeric id, locally or in the listing, is dropped: the store cannot be asked about it, so
|
|
@@ -779,15 +779,15 @@ async function wooFetchCouponsByIds(entries, context) {
|
|
|
779
779
|
for (let i = 0; i < ids.length; i += MAX_IDS_PER_REQUEST) {
|
|
780
780
|
const chunk = ids.slice(i, i + MAX_IDS_PER_REQUEST);
|
|
781
781
|
const params = new URLSearchParams({ include: chunk.join(","), per_page: String(MAX_IDS_PER_REQUEST), status: "any" });
|
|
782
|
-
const
|
|
783
|
-
documents.push(...
|
|
782
|
+
const rows2 = await get2(`/coupons?${params}`, context);
|
|
783
|
+
documents.push(...rows2.map(toCouponDocument).filter((doc) => doc !== void 0));
|
|
784
784
|
}
|
|
785
785
|
return documents;
|
|
786
786
|
}
|
|
787
787
|
function createWooCouponFeed() {
|
|
788
788
|
return createReconcileFeed2({ key: (doc) => doc.uuid, remote: (doc) => doc.id, fetchByIds: wooFetchCouponsByIds });
|
|
789
789
|
}
|
|
790
|
-
var toEntries2 = (
|
|
790
|
+
var toEntries2 = (rows2) => rows2.filter((row) => Number.isInteger(row?.id)).map((row) => ({ key: String(row.id), fingerprint: wooCouponFingerprint(row), remote: row.id }));
|
|
791
791
|
function wooCouponReconcile(feed) {
|
|
792
792
|
return {
|
|
793
793
|
async *fetchPages(context, from = 1) {
|
|
@@ -800,9 +800,9 @@ function wooCouponReconcile(feed) {
|
|
|
800
800
|
status: "publish",
|
|
801
801
|
_fields: LISTING_FIELDS2
|
|
802
802
|
});
|
|
803
|
-
const
|
|
804
|
-
yield { entries: toEntries2(
|
|
805
|
-
if (
|
|
803
|
+
const rows2 = await get2(`/coupons?${params}`, context);
|
|
804
|
+
yield { entries: toEntries2(rows2), cursor: page + 1 };
|
|
805
|
+
if (rows2.length < PAGE_SIZE2) return;
|
|
806
806
|
}
|
|
807
807
|
},
|
|
808
808
|
fingerprint: wooCouponFingerprint,
|
|
@@ -815,8 +815,8 @@ function wooCouponReconcile(feed) {
|
|
|
815
815
|
for (let i = 0; i < ids.length; i += MAX_IDS_PER_REQUEST) {
|
|
816
816
|
const chunk = ids.slice(i, i + MAX_IDS_PER_REQUEST);
|
|
817
817
|
const params = new URLSearchParams({ include: chunk.join(","), per_page: String(MAX_IDS_PER_REQUEST), _fields: "id,meta_data" });
|
|
818
|
-
const
|
|
819
|
-
for (const row of
|
|
818
|
+
const rows2 = await get2(`/coupons?${params}`, context);
|
|
819
|
+
for (const row of rows2) live.set(row.id, wooProductUuid(row));
|
|
820
820
|
}
|
|
821
821
|
return locals.filter((doc) => Number.isInteger(doc.id) && (!live.has(doc.id) || typeof live.get(doc.id) === "string" && live.get(doc.id) !== doc.uuid)).map((doc) => doc.uuid);
|
|
822
822
|
},
|
|
@@ -866,7 +866,7 @@ async function customerRequest(context, route, init = {}) {
|
|
|
866
866
|
const invalid = [400, 404, 422].includes(response.status);
|
|
867
867
|
throw new CustomerServiceError(invalid ? "invalid" : "server", invalid ? body?.message ?? `HTTP ${response.status}` : `HTTP ${response.status}`);
|
|
868
868
|
}
|
|
869
|
-
return { status: response.status, body };
|
|
869
|
+
return { status: response.status, body, headers: response.headers };
|
|
870
870
|
}
|
|
871
871
|
function createWooCustomers(options) {
|
|
872
872
|
const newId = options?.newId ?? newWooId;
|
|
@@ -926,172 +926,15 @@ function createWooCustomers(options) {
|
|
|
926
926
|
};
|
|
927
927
|
}
|
|
928
928
|
|
|
929
|
-
// src/
|
|
930
|
-
import {
|
|
931
|
-
var WOO_ORDER_CREATE_VERSION = 5;
|
|
932
|
-
var WOO_COUPON_ORDER_CREATE_VERSION = 6;
|
|
933
|
-
var WOO_BASE_ORDER_CREATE_VERSION = 3;
|
|
934
|
-
var WOO_COUPONS_MIN_PLUGIN = [1, 9, 0];
|
|
935
|
-
function wooPluginSupportsCoupons(version2) {
|
|
936
|
-
if (typeof version2 !== "string") return false;
|
|
937
|
-
const match = /^(\d+)\.(\d+)(?:\.(\d+))?(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/.exec(version2.trim());
|
|
938
|
-
if (!match) return false;
|
|
939
|
-
const parts = [Number(match[1]), Number(match[2]), Number(match[3] ?? 0)];
|
|
940
|
-
for (let index = 0; index < parts.length; index++) {
|
|
941
|
-
if (parts[index] > WOO_COUPONS_MIN_PLUGIN[index]) return true;
|
|
942
|
-
if (parts[index] < WOO_COUPONS_MIN_PLUGIN[index]) return false;
|
|
943
|
-
}
|
|
944
|
-
return !match[4];
|
|
945
|
-
}
|
|
946
|
-
async function wooStoreSettings(context) {
|
|
947
|
-
try {
|
|
948
|
-
const init = { method: "GET", headers: context.headers, signal: context.signal };
|
|
949
|
-
const storesResponse = await fetch(`${context.baseUrl}/stores`, init);
|
|
950
|
-
if (storesResponse.status === 401 || storesResponse.status === 403) {
|
|
951
|
-
throw new ConnectorUnauthorizedError2(`WooCommerce stores: HTTP ${storesResponse.status}`, storesResponse.status);
|
|
952
|
-
}
|
|
953
|
-
if (!storesResponse.ok) throw new Error(`WooCommerce stores: HTTP ${storesResponse.status}`);
|
|
954
|
-
const stores = await storesResponse.json();
|
|
955
|
-
if (!Array.isArray(stores) || stores.length === 0) throw new Error("WooCommerce stores: expected a non-empty array");
|
|
956
|
-
const store = stores[0];
|
|
957
|
-
const currency = store.currency.toUpperCase();
|
|
958
|
-
const digits = minorUnitDigits(currency);
|
|
959
|
-
if (typeof store.price_num_decimals === "number" && store.price_num_decimals !== digits) {
|
|
960
|
-
console.warn(`WooCommerce price_num_decimals is ${store.price_num_decimals}; the till rounds ${currency} to ${digits} digits`);
|
|
961
|
-
}
|
|
962
|
-
const classesResponse = await fetch(`${context.baseUrl}/taxes/classes`, init);
|
|
963
|
-
if (classesResponse.status === 401 || classesResponse.status === 403) {
|
|
964
|
-
throw new ConnectorUnauthorizedError2(`WooCommerce tax classes: HTTP ${classesResponse.status}`, classesResponse.status);
|
|
965
|
-
}
|
|
966
|
-
if (!classesResponse.ok) throw new Error(`WooCommerce tax classes: HTTP ${classesResponse.status}`);
|
|
967
|
-
const classes = await classesResponse.json();
|
|
968
|
-
if (!Array.isArray(classes)) throw new Error("WooCommerce tax classes: expected an array");
|
|
969
|
-
const taxRates = {};
|
|
970
|
-
const taxRatesPpm = { default: 0 };
|
|
971
|
-
const settings = {
|
|
972
|
-
currency,
|
|
973
|
-
pricesIncludeTax: store.prices_include_tax === "yes",
|
|
974
|
-
taxRoundAtSubtotal: store.tax_round_at_subtotal === "yes",
|
|
975
|
-
calcDiscountsSequentially: (store.woocommerce_calc_discounts_sequentially ?? store.calc_discounts_sequentially) === "yes",
|
|
976
|
-
...typeof store.shipping_tax_class === "string" ? { shippingTaxClass: store.shipping_tax_class } : {},
|
|
977
|
-
taxClassSlugs: classes.map((row) => row.slug),
|
|
978
|
-
taxRates,
|
|
979
|
-
taxRatesPpm
|
|
980
|
-
};
|
|
981
|
-
if (store.calc_taxes !== "yes") return settings;
|
|
982
|
-
const rates = [];
|
|
983
|
-
for (let page = 1; page <= 100; page++) {
|
|
984
|
-
const response = await fetch(`${context.baseUrl}/taxes?per_page=100&page=${page}&orderby=order&order=asc`, init);
|
|
985
|
-
if (response.status === 401 || response.status === 403) {
|
|
986
|
-
throw new ConnectorUnauthorizedError2(`WooCommerce taxes: HTTP ${response.status}`, response.status);
|
|
987
|
-
}
|
|
988
|
-
if (!response.ok) throw new Error(`WooCommerce taxes: HTTP ${response.status}`);
|
|
989
|
-
const rows = await response.json();
|
|
990
|
-
if (!Array.isArray(rows)) throw new Error("WooCommerce taxes: expected an array");
|
|
991
|
-
rates.push(...rows.map((row) => ({
|
|
992
|
-
...row,
|
|
993
|
-
postcodes: row.postcodes ?? [],
|
|
994
|
-
cities: row.cities ?? []
|
|
995
|
-
})));
|
|
996
|
-
if (rows.length < 100) break;
|
|
997
|
-
}
|
|
998
|
-
const taxAddress = store.tax_address;
|
|
999
|
-
let address = taxAddress && typeof taxAddress === "object" && typeof taxAddress.country === "string" && taxAddress.country.length > 0 ? taxAddress : { country: store.store_country, state: store.store_state, postcode: store.store_postcode, city: store.store_city };
|
|
1000
|
-
if (!address.country) {
|
|
1001
|
-
console.warn("WooCommerce has no tax or store country; matching tax rates with an empty address");
|
|
1002
|
-
address = {};
|
|
1003
|
-
}
|
|
1004
|
-
const matched = woocommerceTax.filterTaxRates(rates, address.country, address.state, address.postcode, address.city);
|
|
1005
|
-
for (const rate of matched) {
|
|
1006
|
-
const slug = woocommerceTax.normalizeTaxClass(rate.class);
|
|
1007
|
-
(taxRates[slug] ??= []).push({
|
|
1008
|
-
id: rate.id,
|
|
1009
|
-
code: [rate.country, rate.state, rate.name || "TAX", String(rate.priority)].filter(Boolean).join("-").toUpperCase(),
|
|
1010
|
-
label: rate.name,
|
|
1011
|
-
rate: rate.rate,
|
|
1012
|
-
priority: rate.priority,
|
|
1013
|
-
compound: rate.compound,
|
|
1014
|
-
shipping: rate.shipping
|
|
1015
|
-
});
|
|
1016
|
-
const key = slug === "standard" ? "default" : slug;
|
|
1017
|
-
taxRatesPpm[key] = (taxRatesPpm[key] ?? 0) + Math.round(Number(rate.rate) * 1e4);
|
|
1018
|
-
}
|
|
1019
|
-
return settings;
|
|
1020
|
-
} catch (error) {
|
|
1021
|
-
if (error instanceof ConnectorUnauthorizedError2) throw error;
|
|
1022
|
-
throw new StoreSettingsError("failed", error instanceof Error ? error.message : String(error));
|
|
1023
|
-
}
|
|
1024
|
-
}
|
|
1025
|
-
async function readWooCapabilities(context) {
|
|
1026
|
-
try {
|
|
1027
|
-
const response = await fetch(`${context.baseUrl}/stores`, {
|
|
1028
|
-
method: "GET",
|
|
1029
|
-
headers: context.headers,
|
|
1030
|
-
signal: context.signal
|
|
1031
|
-
});
|
|
1032
|
-
if (response.status === 401 || response.status === 403) {
|
|
1033
|
-
throw new ConnectorUnauthorizedError2(`WooCommerce stores: HTTP ${response.status}`, response.status);
|
|
1034
|
-
}
|
|
1035
|
-
if (!response.ok) return void 0;
|
|
1036
|
-
const stores = await response.json();
|
|
1037
|
-
if (!Array.isArray(stores) || !stores[0] || typeof stores[0] !== "object" || Array.isArray(stores[0])) return void 0;
|
|
1038
|
-
let multiplePayments = false;
|
|
1039
|
-
let capabilities = [];
|
|
1040
|
-
try {
|
|
1041
|
-
const status = await fetch(`${context.baseUrl}/status`, {
|
|
1042
|
-
method: "GET",
|
|
1043
|
-
headers: context.headers,
|
|
1044
|
-
signal: context.signal
|
|
1045
|
-
});
|
|
1046
|
-
if (status.status === 401 || status.status === 403) {
|
|
1047
|
-
throw new ConnectorUnauthorizedError2(`WooCommerce status: HTTP ${status.status}`, status.status);
|
|
1048
|
-
}
|
|
1049
|
-
if (status.ok) {
|
|
1050
|
-
const body = await status.json();
|
|
1051
|
-
capabilities = Array.isArray(body?.capabilities) ? body.capabilities : [];
|
|
1052
|
-
multiplePayments = capabilities.includes("order_payments_list");
|
|
1053
|
-
}
|
|
1054
|
-
} catch (error) {
|
|
1055
|
-
if (error instanceof ConnectorUnauthorizedError2) throw error;
|
|
1056
|
-
}
|
|
1057
|
-
let coupons = false;
|
|
1058
|
-
try {
|
|
1059
|
-
const site = await fetch(`${context.baseUrl}/site`, {
|
|
1060
|
-
method: "GET",
|
|
1061
|
-
headers: context.headers,
|
|
1062
|
-
signal: context.signal
|
|
1063
|
-
});
|
|
1064
|
-
if (site.ok) {
|
|
1065
|
-
const body = await site.json();
|
|
1066
|
-
coupons = wooPluginSupportsCoupons(body?.wcpos_version);
|
|
1067
|
-
}
|
|
1068
|
-
} catch {
|
|
1069
|
-
coupons = false;
|
|
1070
|
-
}
|
|
1071
|
-
const orderCreate = capabilities.includes("order_create_v5") ? coupons ? WOO_COUPON_ORDER_CREATE_VERSION : WOO_ORDER_CREATE_VERSION : WOO_BASE_ORDER_CREATE_VERSION;
|
|
1072
|
-
return {
|
|
1073
|
-
orderCreate,
|
|
1074
|
-
taxRounding: { granularity: "woocommerce", roundAtSubtotal: stores[0].tax_round_at_subtotal === "yes" },
|
|
1075
|
-
multiplePayments,
|
|
1076
|
-
coupons,
|
|
1077
|
-
// 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.
|
|
1078
|
-
lineTax: { none: true, classes: true }
|
|
1079
|
-
};
|
|
1080
|
-
} catch (error) {
|
|
1081
|
-
if (error instanceof ConnectorUnauthorizedError2) throw error;
|
|
1082
|
-
return void 0;
|
|
1083
|
-
}
|
|
1084
|
-
}
|
|
1085
|
-
|
|
1086
|
-
// package.json
|
|
1087
|
-
var version = "3.10.0";
|
|
929
|
+
// src/orders.ts
|
|
930
|
+
import { CustomerServiceError as CustomerServiceError2, minorUnitDigits as minorUnitDigits2 } from "@tallyui/core";
|
|
1088
931
|
|
|
1089
932
|
// src/commands/transport.ts
|
|
1090
|
-
import { minorUnitDigits
|
|
933
|
+
import { minorUnitDigits, moneyFromDecimalString, moneyFromMajor as moneyFromMajor2 } from "@tallyui/core";
|
|
1091
934
|
function wooMinorFromDecimal(text, currency) {
|
|
1092
935
|
const trimmed = text.trim();
|
|
1093
936
|
if (!/^\d+(\.\d+)?$/.test(trimmed)) return void 0;
|
|
1094
|
-
const digits =
|
|
937
|
+
const digits = minorUnitDigits(currency);
|
|
1095
938
|
const [whole, fraction = ""] = trimmed.split(".");
|
|
1096
939
|
let end = fraction.length;
|
|
1097
940
|
while (end > digits && fraction[end - 1] === "0") end--;
|
|
@@ -1106,6 +949,9 @@ function stripTags(text) {
|
|
|
1106
949
|
} while (text !== previous);
|
|
1107
950
|
return text;
|
|
1108
951
|
}
|
|
952
|
+
function wooAnyAttributeKey(name) {
|
|
953
|
+
return /^[A-Za-z0-9]+(?:[ -][A-Za-z0-9]+)*$/.test(name) ? name.toLowerCase().replace(/ /g, "-") : void 0;
|
|
954
|
+
}
|
|
1109
955
|
function decodeCouponMessage(message) {
|
|
1110
956
|
const entities = { quot: '"', amp: "&", lt: "<", gt: ">", apos: "'" };
|
|
1111
957
|
return stripTags(typeof message === "string" ? message : "").replace(/&(quot|amp|lt|gt|apos|#\d+|#x[\da-f]+);/gi, (_, entity) => entities[entity.toLowerCase()] ?? ((value) => value > 1114111 ? _ : String.fromCodePoint(value))(
|
|
@@ -1128,8 +974,8 @@ function toWooOrderPayload(envelope, local, options) {
|
|
|
1128
974
|
return { error: { code: "invalid_payload", message: `Line ${line.clientLineId} has no WooCommerce product id.` } };
|
|
1129
975
|
}
|
|
1130
976
|
}
|
|
1131
|
-
const digits = p.display?.exponent ??
|
|
1132
|
-
const major = (
|
|
977
|
+
const digits = p.display?.exponent ?? minorUnitDigits(p.currency);
|
|
978
|
+
const major = (minor2) => (minor2 / 10 ** digits).toFixed(digits);
|
|
1133
979
|
const inclusiveNet = (netMicros, id) => {
|
|
1134
980
|
if (netMicros === void 0) {
|
|
1135
981
|
return { error: { code: "unsupported_tax_mode", message: "Tax-inclusive prices need the till's WooCommerce tax figures; update the till." } };
|
|
@@ -1158,11 +1004,17 @@ function toWooOrderPayload(envelope, local, options) {
|
|
|
1158
1004
|
if (p.coupons?.length) {
|
|
1159
1005
|
const discount = (line.taxInclusive ?? p.pricesIncludeTax) && (line.discountMinor ?? 0) > 0 ? local?.lines.find((stored) => stored.id === line.clientLineId)?.discountMinor : line.discountMinor ?? 0;
|
|
1160
1006
|
if (discount === void 0) return { error: { code: "unsupported_tax_mode", message: "Tax-inclusive prices need the till's WooCommerce tax figures; update the till." } };
|
|
1161
|
-
const quantity = BigInt(line.quantity),
|
|
1162
|
-
const divisor = quantity * 10n ** BigInt(digits), micros = (
|
|
1163
|
-
price =
|
|
1007
|
+
const quantity = BigInt(line.quantity), minor2 = BigInt(line.unitPriceMinor) * quantity - BigInt(discount);
|
|
1008
|
+
const divisor = quantity * 10n ** BigInt(digits), micros = (minor2 * 1000000n * 2n + divisor) / (divisor * 2n);
|
|
1009
|
+
price = minor2 % quantity === 0n ? major(Number(minor2 / quantity)) : `${micros / 1000000n}.${(micros % 1000000n).toString().padStart(6, "0")}`;
|
|
1164
1010
|
}
|
|
1165
1011
|
const regular_price = p.coupons?.length && line.regularUnitPriceMinor !== void 0 ? major(line.regularUnitPriceMinor) : price;
|
|
1012
|
+
const picked = (line.anyAttributes ?? []).flatMap((name) => {
|
|
1013
|
+
const key = wooAnyAttributeKey(name);
|
|
1014
|
+
const value = line.attributes?.[name];
|
|
1015
|
+
return key && value ? [{ key, value }] : [];
|
|
1016
|
+
});
|
|
1017
|
+
const lineMeta = [...p.coupons?.length ? [{ key: "_woocommerce_pos_data", value: JSON.stringify({ price, regular_price }) }] : [], ...picked];
|
|
1166
1018
|
line_items.push(custom ? {
|
|
1167
1019
|
product_id: 0,
|
|
1168
1020
|
name: custom.name,
|
|
@@ -1180,7 +1032,7 @@ function toWooOrderPayload(envelope, local, options) {
|
|
|
1180
1032
|
quantity: line.quantity,
|
|
1181
1033
|
subtotal,
|
|
1182
1034
|
total,
|
|
1183
|
-
...
|
|
1035
|
+
...lineMeta.length ? { meta_data: lineMeta } : {}
|
|
1184
1036
|
});
|
|
1185
1037
|
}
|
|
1186
1038
|
const fee_lines = [], shipping_lines = [];
|
|
@@ -1326,6 +1178,315 @@ function createWooCommandTransport(options) {
|
|
|
1326
1178
|
};
|
|
1327
1179
|
}
|
|
1328
1180
|
|
|
1181
|
+
// src/orders.ts
|
|
1182
|
+
var MAX_PER_PAGE = 100;
|
|
1183
|
+
var unexpected = () => new CustomerServiceError2("server", "unexpected response");
|
|
1184
|
+
var isRow = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1185
|
+
var rows = (value) => Array.isArray(value) ? value.filter(isRow) : [];
|
|
1186
|
+
var nonEmpty = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
|
|
1187
|
+
var positiveId = (value) => typeof value === "number" && Number.isInteger(value) && value > 0 ? String(value) : void 0;
|
|
1188
|
+
function minor(text, currency) {
|
|
1189
|
+
if (typeof text !== "string") throw unexpected();
|
|
1190
|
+
const trimmed = text.trim();
|
|
1191
|
+
const negative = /^-\d/.test(trimmed);
|
|
1192
|
+
const value = wooMinorFromDecimal(negative ? trimmed.slice(1) : trimmed, currency);
|
|
1193
|
+
if (value === void 0) throw unexpected();
|
|
1194
|
+
return negative && value !== 0 ? -value : value;
|
|
1195
|
+
}
|
|
1196
|
+
function decimalSumMinor(a, b, currency) {
|
|
1197
|
+
const parts = [a, b].map((text) => /^(-?)(\d+)(?:\.(\d+))?$/.exec(typeof text === "string" ? text.trim() : ""));
|
|
1198
|
+
const scale = Math.max(minorUnitDigits2(currency), ...parts.map((part) => part?.[3]?.length ?? 0));
|
|
1199
|
+
let total = 0n;
|
|
1200
|
+
for (const part of parts) {
|
|
1201
|
+
if (!part) throw unexpected();
|
|
1202
|
+
total += BigInt(`${part[1]}${part[2]}${(part[3] ?? "").padEnd(scale, "0")}`);
|
|
1203
|
+
}
|
|
1204
|
+
const divisor = 10n ** BigInt(scale - minorUnitDigits2(currency));
|
|
1205
|
+
const rounded = ((total < 0n ? -total : total) + divisor / 2n) / divisor;
|
|
1206
|
+
return Number(total < 0n ? -rounded : rounded);
|
|
1207
|
+
}
|
|
1208
|
+
var grossTax = (net, tax, currency) => decimalSumMinor(net, tax, currency) - minor(net, currency);
|
|
1209
|
+
function posUuid(metaData) {
|
|
1210
|
+
const entry = rows(metaData).find((meta) => meta.key === "_woocommerce_pos_uuid" && nonEmpty(meta.value));
|
|
1211
|
+
return entry ? entry.value : void 0;
|
|
1212
|
+
}
|
|
1213
|
+
var PAYMENT_KINDS = { pos_cash: "cash", pos_card: "external" };
|
|
1214
|
+
function toWooStoreOrder(raw) {
|
|
1215
|
+
if (!isRow(raw) || raw.id === void 0 || raw.id === null || typeof raw.currency !== "string" || typeof raw.date_created_gmt !== "string") {
|
|
1216
|
+
throw unexpected();
|
|
1217
|
+
}
|
|
1218
|
+
const currency = raw.currency;
|
|
1219
|
+
const dateText = raw.date_created_gmt;
|
|
1220
|
+
const placed = new Date(/(Z|[+-]\d{2}:?\d{2})$/.test(dateText) ? dateText : `${dateText}Z`);
|
|
1221
|
+
if (Number.isNaN(placed.getTime())) throw unexpected();
|
|
1222
|
+
const billing = isRow(raw.billing) ? raw.billing : {};
|
|
1223
|
+
const customerId = positiveId(raw.customer_id);
|
|
1224
|
+
const name = [billing.first_name, billing.last_name].filter((part) => typeof part === "string").join(" ").trim();
|
|
1225
|
+
const email = nonEmpty(billing.email);
|
|
1226
|
+
const customer = customerId || name || email ? { ...customerId ? { id: customerId } : {}, ...name ? { name } : {}, ...email ? { email } : {} } : null;
|
|
1227
|
+
const clientOrderId = posUuid(raw.meta_data);
|
|
1228
|
+
const totalMinor = minor(raw.total, currency);
|
|
1229
|
+
const paymentMethod = nonEmpty(raw.payment_method);
|
|
1230
|
+
const paymentTitle = nonEmpty(raw.payment_method_title);
|
|
1231
|
+
const paymentKind = paymentMethod ? PAYMENT_KINDS[paymentMethod] : void 0;
|
|
1232
|
+
return {
|
|
1233
|
+
id: String(raw.id),
|
|
1234
|
+
reference: String(raw.number ?? raw.id),
|
|
1235
|
+
...clientOrderId ? { clientOrderId } : {},
|
|
1236
|
+
status: String(raw.status),
|
|
1237
|
+
placedAt: placed.toISOString(),
|
|
1238
|
+
currency,
|
|
1239
|
+
pricesIncludeTax: raw.prices_include_tax === true,
|
|
1240
|
+
customer,
|
|
1241
|
+
lines: rows(raw.line_items).map((line) => {
|
|
1242
|
+
const clientLineId = posUuid(line.meta_data);
|
|
1243
|
+
const productId = positiveId(line.product_id);
|
|
1244
|
+
const variantId = positiveId(line.variation_id) ?? productId;
|
|
1245
|
+
const sku = nonEmpty(line.sku);
|
|
1246
|
+
return {
|
|
1247
|
+
id: String(line.id),
|
|
1248
|
+
...clientLineId ? { clientLineId } : {},
|
|
1249
|
+
...productId ? { productId } : {},
|
|
1250
|
+
...variantId ? { variantId } : {},
|
|
1251
|
+
name: String(line.name),
|
|
1252
|
+
...sku ? { sku } : {},
|
|
1253
|
+
quantity: Number(line.quantity),
|
|
1254
|
+
subtotalMinor: minor(line.subtotal, currency),
|
|
1255
|
+
subtotalTaxMinor: grossTax(line.subtotal, line.subtotal_tax, currency),
|
|
1256
|
+
totalMinor: minor(line.total, currency),
|
|
1257
|
+
taxMinor: grossTax(line.total, line.total_tax, currency)
|
|
1258
|
+
};
|
|
1259
|
+
}),
|
|
1260
|
+
fees: rows(raw.fee_lines).map((fee) => ({
|
|
1261
|
+
name: String(fee.name),
|
|
1262
|
+
totalMinor: minor(fee.total, currency),
|
|
1263
|
+
taxMinor: grossTax(fee.total, fee.total_tax, currency)
|
|
1264
|
+
})),
|
|
1265
|
+
shipping: rows(raw.shipping_lines).map((line) => ({
|
|
1266
|
+
name: String(line.method_title),
|
|
1267
|
+
totalMinor: minor(line.total, currency),
|
|
1268
|
+
taxMinor: grossTax(line.total, line.total_tax, currency)
|
|
1269
|
+
})),
|
|
1270
|
+
coupons: rows(raw.coupon_lines).map((coupon) => ({
|
|
1271
|
+
code: String(coupon.code),
|
|
1272
|
+
discountMinor: minor(coupon.discount, currency),
|
|
1273
|
+
discountTaxMinor: grossTax(coupon.discount, coupon.discount_tax, currency)
|
|
1274
|
+
})),
|
|
1275
|
+
taxLines: rows(raw.tax_lines).map((tax) => {
|
|
1276
|
+
const code = nonEmpty(tax.rate_code);
|
|
1277
|
+
return {
|
|
1278
|
+
label: String(tax.label),
|
|
1279
|
+
...code ? { code } : {},
|
|
1280
|
+
ratePpm: typeof tax.rate_percent === "number" && Number.isFinite(tax.rate_percent) ? Math.round(tax.rate_percent * 1e4) : 0,
|
|
1281
|
+
amountMinor: minor(tax.tax_total, currency) + minor(tax.shipping_tax_total, currency)
|
|
1282
|
+
};
|
|
1283
|
+
}),
|
|
1284
|
+
discountMinor: minor(raw.discount_total, currency),
|
|
1285
|
+
discountTaxMinor: minor(raw.discount_tax, currency),
|
|
1286
|
+
taxMinor: minor(raw.total_tax, currency),
|
|
1287
|
+
totalMinor,
|
|
1288
|
+
payments: paymentMethod ? [{
|
|
1289
|
+
method: paymentMethod,
|
|
1290
|
+
...paymentTitle ? { title: paymentTitle } : {},
|
|
1291
|
+
...paymentKind ? { kind: paymentKind } : {},
|
|
1292
|
+
amountMinor: totalMinor
|
|
1293
|
+
}] : [],
|
|
1294
|
+
refunds: rows(raw.refunds).map((refund) => {
|
|
1295
|
+
const reason = nonEmpty(refund.reason);
|
|
1296
|
+
return { id: String(refund.id), amountMinor: Math.abs(minor(refund.total, currency)), ...reason ? { reason } : {} };
|
|
1297
|
+
})
|
|
1298
|
+
};
|
|
1299
|
+
}
|
|
1300
|
+
var wholeNumber = (value, fallback) => value === void 0 || !Number.isFinite(value) ? fallback : Math.trunc(value);
|
|
1301
|
+
function createWooOrders() {
|
|
1302
|
+
return {
|
|
1303
|
+
async listOrders(context, query = {}) {
|
|
1304
|
+
const page = Math.max(1, wholeNumber(query.page, 1));
|
|
1305
|
+
const perPage = Math.max(1, Math.min(MAX_PER_PAGE, wholeNumber(query.perPage, 25)));
|
|
1306
|
+
const params = new URLSearchParams({ page: String(page), per_page: String(perPage), orderby: "date", order: "desc" });
|
|
1307
|
+
const search = query.search?.trim();
|
|
1308
|
+
if (search) params.set("search", search);
|
|
1309
|
+
const { body, headers } = await customerRequest(context, `orders?${params}`, { method: "GET" });
|
|
1310
|
+
if (!Array.isArray(body)) throw unexpected();
|
|
1311
|
+
const orders = body.map(toWooStoreOrder);
|
|
1312
|
+
const totalPages = headers.get("X-WP-TotalPages");
|
|
1313
|
+
const hasMore = totalPages !== null && /^\d+$/.test(totalPages.trim()) ? page < Number.parseInt(totalPages, 10) : orders.length === perPage;
|
|
1314
|
+
return { orders, hasMore };
|
|
1315
|
+
},
|
|
1316
|
+
async getOrders(context, ids) {
|
|
1317
|
+
const wanted = [...new Set(ids.filter((id) => /^[1-9]\d*$/.test(id)))];
|
|
1318
|
+
const found = /* @__PURE__ */ new Map();
|
|
1319
|
+
for (let start = 0; start < wanted.length; start += MAX_PER_PAGE) {
|
|
1320
|
+
const chunk = wanted.slice(start, start + MAX_PER_PAGE);
|
|
1321
|
+
const { body } = await customerRequest(context, `orders?include=${chunk.join(",")}&per_page=${chunk.length}`, { method: "GET" });
|
|
1322
|
+
if (!Array.isArray(body)) throw unexpected();
|
|
1323
|
+
for (const order of body.map(toWooStoreOrder)) found.set(order.id, order);
|
|
1324
|
+
}
|
|
1325
|
+
return wanted.flatMap((id) => found.get(id) ?? []);
|
|
1326
|
+
}
|
|
1327
|
+
};
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
// src/store-settings.ts
|
|
1331
|
+
import { ConnectorUnauthorizedError as ConnectorUnauthorizedError2, StoreSettingsError, minorUnitDigits as minorUnitDigits3, woocommerceTax } from "@tallyui/core";
|
|
1332
|
+
var WOO_ORDER_CREATE_VERSION = 5;
|
|
1333
|
+
var WOO_COUPON_ORDER_CREATE_VERSION = 6;
|
|
1334
|
+
var WOO_BASE_ORDER_CREATE_VERSION = 3;
|
|
1335
|
+
var WOO_COUPONS_MIN_PLUGIN = [1, 9, 0];
|
|
1336
|
+
function wooPluginSupportsCoupons(version2) {
|
|
1337
|
+
if (typeof version2 !== "string") return false;
|
|
1338
|
+
const match = /^(\d+)\.(\d+)(?:\.(\d+))?(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/.exec(version2.trim());
|
|
1339
|
+
if (!match) return false;
|
|
1340
|
+
const parts = [Number(match[1]), Number(match[2]), Number(match[3] ?? 0)];
|
|
1341
|
+
for (let index = 0; index < parts.length; index++) {
|
|
1342
|
+
if (parts[index] > WOO_COUPONS_MIN_PLUGIN[index]) return true;
|
|
1343
|
+
if (parts[index] < WOO_COUPONS_MIN_PLUGIN[index]) return false;
|
|
1344
|
+
}
|
|
1345
|
+
return !match[4];
|
|
1346
|
+
}
|
|
1347
|
+
async function wooStoreSettings(context) {
|
|
1348
|
+
try {
|
|
1349
|
+
const init = { method: "GET", headers: context.headers, signal: context.signal };
|
|
1350
|
+
const storesResponse = await fetch(`${context.baseUrl}/stores`, init);
|
|
1351
|
+
if (storesResponse.status === 401 || storesResponse.status === 403) {
|
|
1352
|
+
throw new ConnectorUnauthorizedError2(`WooCommerce stores: HTTP ${storesResponse.status}`, storesResponse.status);
|
|
1353
|
+
}
|
|
1354
|
+
if (!storesResponse.ok) throw new Error(`WooCommerce stores: HTTP ${storesResponse.status}`);
|
|
1355
|
+
const stores = await storesResponse.json();
|
|
1356
|
+
if (!Array.isArray(stores) || stores.length === 0) throw new Error("WooCommerce stores: expected a non-empty array");
|
|
1357
|
+
const store = stores[0];
|
|
1358
|
+
const currency = store.currency.toUpperCase();
|
|
1359
|
+
const digits = minorUnitDigits3(currency);
|
|
1360
|
+
if (typeof store.price_num_decimals === "number" && store.price_num_decimals !== digits) {
|
|
1361
|
+
console.warn(`WooCommerce price_num_decimals is ${store.price_num_decimals}; the till rounds ${currency} to ${digits} digits`);
|
|
1362
|
+
}
|
|
1363
|
+
const classesResponse = await fetch(`${context.baseUrl}/taxes/classes`, init);
|
|
1364
|
+
if (classesResponse.status === 401 || classesResponse.status === 403) {
|
|
1365
|
+
throw new ConnectorUnauthorizedError2(`WooCommerce tax classes: HTTP ${classesResponse.status}`, classesResponse.status);
|
|
1366
|
+
}
|
|
1367
|
+
if (!classesResponse.ok) throw new Error(`WooCommerce tax classes: HTTP ${classesResponse.status}`);
|
|
1368
|
+
const classes = await classesResponse.json();
|
|
1369
|
+
if (!Array.isArray(classes)) throw new Error("WooCommerce tax classes: expected an array");
|
|
1370
|
+
const taxRates = {};
|
|
1371
|
+
const taxRatesPpm = { default: 0 };
|
|
1372
|
+
const settings = {
|
|
1373
|
+
currency,
|
|
1374
|
+
pricesIncludeTax: store.prices_include_tax === "yes",
|
|
1375
|
+
taxRoundAtSubtotal: store.tax_round_at_subtotal === "yes",
|
|
1376
|
+
calcDiscountsSequentially: (store.woocommerce_calc_discounts_sequentially ?? store.calc_discounts_sequentially) === "yes",
|
|
1377
|
+
...typeof store.shipping_tax_class === "string" ? { shippingTaxClass: store.shipping_tax_class } : {},
|
|
1378
|
+
taxClassSlugs: classes.map((row) => row.slug),
|
|
1379
|
+
taxRates,
|
|
1380
|
+
taxRatesPpm
|
|
1381
|
+
};
|
|
1382
|
+
if (store.calc_taxes !== "yes") return settings;
|
|
1383
|
+
const rates = [];
|
|
1384
|
+
for (let page = 1; page <= 100; page++) {
|
|
1385
|
+
const response = await fetch(`${context.baseUrl}/taxes?per_page=100&page=${page}&orderby=order&order=asc`, init);
|
|
1386
|
+
if (response.status === 401 || response.status === 403) {
|
|
1387
|
+
throw new ConnectorUnauthorizedError2(`WooCommerce taxes: HTTP ${response.status}`, response.status);
|
|
1388
|
+
}
|
|
1389
|
+
if (!response.ok) throw new Error(`WooCommerce taxes: HTTP ${response.status}`);
|
|
1390
|
+
const rows2 = await response.json();
|
|
1391
|
+
if (!Array.isArray(rows2)) throw new Error("WooCommerce taxes: expected an array");
|
|
1392
|
+
rates.push(...rows2.map((row) => ({
|
|
1393
|
+
...row,
|
|
1394
|
+
postcodes: row.postcodes ?? [],
|
|
1395
|
+
cities: row.cities ?? []
|
|
1396
|
+
})));
|
|
1397
|
+
if (rows2.length < 100) break;
|
|
1398
|
+
}
|
|
1399
|
+
const taxAddress = store.tax_address;
|
|
1400
|
+
let address = taxAddress && typeof taxAddress === "object" && typeof taxAddress.country === "string" && taxAddress.country.length > 0 ? taxAddress : { country: store.store_country, state: store.store_state, postcode: store.store_postcode, city: store.store_city };
|
|
1401
|
+
if (!address.country) {
|
|
1402
|
+
console.warn("WooCommerce has no tax or store country; matching tax rates with an empty address");
|
|
1403
|
+
address = {};
|
|
1404
|
+
}
|
|
1405
|
+
const matched = woocommerceTax.filterTaxRates(rates, address.country, address.state, address.postcode, address.city);
|
|
1406
|
+
for (const rate of matched) {
|
|
1407
|
+
const slug = woocommerceTax.normalizeTaxClass(rate.class);
|
|
1408
|
+
(taxRates[slug] ??= []).push({
|
|
1409
|
+
id: rate.id,
|
|
1410
|
+
code: [rate.country, rate.state, rate.name || "TAX", String(rate.priority)].filter(Boolean).join("-").toUpperCase(),
|
|
1411
|
+
label: rate.name,
|
|
1412
|
+
rate: rate.rate,
|
|
1413
|
+
priority: rate.priority,
|
|
1414
|
+
compound: rate.compound,
|
|
1415
|
+
shipping: rate.shipping
|
|
1416
|
+
});
|
|
1417
|
+
const key = slug === "standard" ? "default" : slug;
|
|
1418
|
+
taxRatesPpm[key] = (taxRatesPpm[key] ?? 0) + Math.round(Number(rate.rate) * 1e4);
|
|
1419
|
+
}
|
|
1420
|
+
return settings;
|
|
1421
|
+
} catch (error) {
|
|
1422
|
+
if (error instanceof ConnectorUnauthorizedError2) throw error;
|
|
1423
|
+
throw new StoreSettingsError("failed", error instanceof Error ? error.message : String(error));
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
async function readWooCapabilities(context) {
|
|
1427
|
+
try {
|
|
1428
|
+
const response = await fetch(`${context.baseUrl}/stores`, {
|
|
1429
|
+
method: "GET",
|
|
1430
|
+
headers: context.headers,
|
|
1431
|
+
signal: context.signal
|
|
1432
|
+
});
|
|
1433
|
+
if (response.status === 401 || response.status === 403) {
|
|
1434
|
+
throw new ConnectorUnauthorizedError2(`WooCommerce stores: HTTP ${response.status}`, response.status);
|
|
1435
|
+
}
|
|
1436
|
+
if (!response.ok) return void 0;
|
|
1437
|
+
const stores = await response.json();
|
|
1438
|
+
if (!Array.isArray(stores) || !stores[0] || typeof stores[0] !== "object" || Array.isArray(stores[0])) return void 0;
|
|
1439
|
+
let multiplePayments = false;
|
|
1440
|
+
let capabilities = [];
|
|
1441
|
+
try {
|
|
1442
|
+
const status = await fetch(`${context.baseUrl}/status`, {
|
|
1443
|
+
method: "GET",
|
|
1444
|
+
headers: context.headers,
|
|
1445
|
+
signal: context.signal
|
|
1446
|
+
});
|
|
1447
|
+
if (status.status === 401 || status.status === 403) {
|
|
1448
|
+
throw new ConnectorUnauthorizedError2(`WooCommerce status: HTTP ${status.status}`, status.status);
|
|
1449
|
+
}
|
|
1450
|
+
if (status.ok) {
|
|
1451
|
+
const body = await status.json();
|
|
1452
|
+
capabilities = Array.isArray(body?.capabilities) ? body.capabilities : [];
|
|
1453
|
+
multiplePayments = capabilities.includes("order_payments_list");
|
|
1454
|
+
}
|
|
1455
|
+
} catch (error) {
|
|
1456
|
+
if (error instanceof ConnectorUnauthorizedError2) throw error;
|
|
1457
|
+
}
|
|
1458
|
+
let coupons = false;
|
|
1459
|
+
try {
|
|
1460
|
+
const site = await fetch(`${context.baseUrl}/site`, {
|
|
1461
|
+
method: "GET",
|
|
1462
|
+
headers: context.headers,
|
|
1463
|
+
signal: context.signal
|
|
1464
|
+
});
|
|
1465
|
+
if (site.ok) {
|
|
1466
|
+
const body = await site.json();
|
|
1467
|
+
coupons = wooPluginSupportsCoupons(body?.wcpos_version);
|
|
1468
|
+
}
|
|
1469
|
+
} catch {
|
|
1470
|
+
coupons = false;
|
|
1471
|
+
}
|
|
1472
|
+
const orderCreate = capabilities.includes("order_create_v5") ? coupons ? WOO_COUPON_ORDER_CREATE_VERSION : WOO_ORDER_CREATE_VERSION : WOO_BASE_ORDER_CREATE_VERSION;
|
|
1473
|
+
return {
|
|
1474
|
+
orderCreate,
|
|
1475
|
+
taxRounding: { granularity: "woocommerce", roundAtSubtotal: stores[0].tax_round_at_subtotal === "yes" },
|
|
1476
|
+
multiplePayments,
|
|
1477
|
+
coupons,
|
|
1478
|
+
// 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.
|
|
1479
|
+
lineTax: { none: true, classes: true }
|
|
1480
|
+
};
|
|
1481
|
+
} catch (error) {
|
|
1482
|
+
if (error instanceof ConnectorUnauthorizedError2) throw error;
|
|
1483
|
+
return void 0;
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
1486
|
+
|
|
1487
|
+
// package.json
|
|
1488
|
+
var version = "3.12.0";
|
|
1489
|
+
|
|
1329
1490
|
// src/index.ts
|
|
1330
1491
|
import { ConnectorUnauthorizedError as ConnectorUnauthorizedError4 } from "@tallyui/core";
|
|
1331
1492
|
function wcposClientPart(part) {
|
|
@@ -1345,6 +1506,8 @@ function createWooCommerceConnector() {
|
|
|
1345
1506
|
...wooConnectorParts,
|
|
1346
1507
|
// WCPOS wcpos/v2/customers, push/customers and orders/<id>/email.
|
|
1347
1508
|
...customers,
|
|
1509
|
+
// WCPOS wcpos/v2/orders: order history (ADR-081).
|
|
1510
|
+
...createWooOrders(),
|
|
1348
1511
|
replication: {
|
|
1349
1512
|
// One replication per collection; the reconcile feed is last, so its fetch wins duplicates;
|
|
1350
1513
|
// duplicates are matched by uuid, the primary key, not the store id (#331). legacyKey
|
|
@@ -1422,10 +1585,12 @@ export {
|
|
|
1422
1585
|
createWooCommerceConnector,
|
|
1423
1586
|
createWooCouponFeed,
|
|
1424
1587
|
createWooCustomers,
|
|
1588
|
+
createWooOrders,
|
|
1425
1589
|
readWooCapabilities,
|
|
1426
1590
|
toCouponDocument,
|
|
1427
1591
|
toWooCustomer,
|
|
1428
1592
|
toWooOrderPayload,
|
|
1593
|
+
toWooStoreOrder,
|
|
1429
1594
|
wcposClientPart,
|
|
1430
1595
|
wooCatalogueReconcile,
|
|
1431
1596
|
wooCouponFingerprint,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tallyui/connector-woocommerce",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.12.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.12.0"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
|
-
"@tallyui/database": "3.
|
|
33
|
+
"@tallyui/database": "3.12.0",
|
|
34
34
|
"rxdb": "17.5.0"
|
|
35
35
|
},
|
|
36
36
|
"scripts": {
|
|
@@ -47,6 +47,12 @@ function stripTags(text: string): string {
|
|
|
47
47
|
return text;
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
+
// The dev store keyed "Size" as `size` and "Shoe Size" as `shoe-size` (#495 c/d proof, 2026-10-14): lower case, a space
|
|
51
|
+
// as a hyphen. A name with any other character is not sent, so Woo keeps its own empty row for it, as before.
|
|
52
|
+
function wooAnyAttributeKey(name: string): string | undefined {
|
|
53
|
+
return /^[A-Za-z0-9]+(?:[ -][A-Za-z0-9]+)*$/.test(name) ? name.toLowerCase().replace(/ /g, '-') : undefined;
|
|
54
|
+
}
|
|
55
|
+
|
|
50
56
|
function decodeCouponMessage(message: unknown): string {
|
|
51
57
|
const entities: Record<string, string> = { quot: '"', amp: '&', lt: '<', gt: '>', apos: "'" };
|
|
52
58
|
return stripTags(typeof message === 'string' ? message : '')
|
|
@@ -110,12 +116,18 @@ export function toWooOrderPayload(envelope: OrderCreateEnvelope, local?: WooLoca
|
|
|
110
116
|
: `${micros / 1000000n}.${(micros % 1000000n).toString().padStart(6, '0')}`;
|
|
111
117
|
}
|
|
112
118
|
const regular_price = p.coupons?.length && line.regularUnitPriceMinor !== undefined ? major(line.regularUnitPriceMinor) : price;
|
|
119
|
+
const picked = (line.anyAttributes ?? []).flatMap((name) => {
|
|
120
|
+
const key = wooAnyAttributeKey(name);
|
|
121
|
+
const value = line.attributes?.[name];
|
|
122
|
+
return key && value ? [{ key, value }] : [];
|
|
123
|
+
});
|
|
124
|
+
const lineMeta = [...(p.coupons?.length ? [{ key: '_woocommerce_pos_data', value: JSON.stringify({ price, regular_price }) }] : []), ...picked];
|
|
113
125
|
line_items.push(custom ? {
|
|
114
126
|
product_id: 0, name: custom.name, ...(custom.sku ? { sku: custom.sku } : {}), quantity: line.quantity, subtotal, total,
|
|
115
127
|
tax_class: custom.taxClass ?? '', meta_data: [{ key: '_woocommerce_pos_data',
|
|
116
128
|
value: JSON.stringify({ price, regular_price, tax_status: custom.taxStatus }) }],
|
|
117
129
|
} : { product_id: Number(line.variantId), quantity: line.quantity, subtotal, total,
|
|
118
|
-
...(
|
|
130
|
+
...(lineMeta.length ? { meta_data: lineMeta } : {}) });
|
|
119
131
|
}
|
|
120
132
|
const fee_lines = [], shipping_lines = [];
|
|
121
133
|
for (const fee of p.fees ?? []) {
|
package/src/customers.ts
CHANGED
|
@@ -35,7 +35,7 @@ function newWooId(): string {
|
|
|
35
35
|
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
-
async function customerRequest(context: SyncContext, route: string, init: RequestInit = {}) {
|
|
38
|
+
export async function customerRequest(context: SyncContext, route: string, init: RequestInit = {}) {
|
|
39
39
|
let response: Response;
|
|
40
40
|
try {
|
|
41
41
|
response = await fetch(`${context.baseUrl}/${route}`, {
|
|
@@ -50,7 +50,7 @@ async function customerRequest(context: SyncContext, route: string, init: Reques
|
|
|
50
50
|
const invalid = [400, 404, 422].includes(response.status);
|
|
51
51
|
throw new CustomerServiceError(invalid ? 'invalid' : 'server', invalid ? body?.message ?? `HTTP ${response.status}` : `HTTP ${response.status}`);
|
|
52
52
|
}
|
|
53
|
-
return { status: response.status, body };
|
|
53
|
+
return { status: response.status, body, headers: response.headers };
|
|
54
54
|
}
|
|
55
55
|
|
|
56
56
|
export function createWooCustomers(options?: { newId?: () => string }) {
|
package/src/index.ts
CHANGED
|
@@ -9,6 +9,7 @@ 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
13
|
import { wooStoreSettings, readWooCapabilities } from './store-settings';
|
|
13
14
|
import { version } from '../package.json';
|
|
14
15
|
|
|
@@ -51,6 +52,8 @@ export function createWooCommerceConnector(): TallyConnector {
|
|
|
51
52
|
...wooConnectorParts,
|
|
52
53
|
// WCPOS wcpos/v2/customers, push/customers and orders/<id>/email.
|
|
53
54
|
...customers,
|
|
55
|
+
// WCPOS wcpos/v2/orders: order history (ADR-081).
|
|
56
|
+
...createWooOrders(),
|
|
54
57
|
replication: {
|
|
55
58
|
// One replication per collection; the reconcile feed is last, so its fetch wins duplicates;
|
|
56
59
|
// duplicates are matched by uuid, the primary key, not the store id (#331). legacyKey
|
|
@@ -130,6 +133,7 @@ export const woocommerceConnector: TallyConnector = createWooCommerceConnector()
|
|
|
130
133
|
// Re-export pieces for advanced usage
|
|
131
134
|
export { wooStoreSettings, readWooCapabilities, WOO_ORDER_CREATE_VERSION } from './store-settings';
|
|
132
135
|
export { createWooCustomers, toWooCustomer } from './customers';
|
|
136
|
+
export { createWooOrders, toWooStoreOrder } from './orders';
|
|
133
137
|
export { createWooCommandTransport, toWooOrderPayload, type WooCommandTransportOptions } from './commands/transport';
|
|
134
138
|
export { ConnectorUnauthorizedError } from '@tallyui/core';
|
|
135
139
|
export { wooProductSchema } from './schemas/products';
|
package/src/orders.ts
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { CustomerServiceError, minorUnitDigits, type PaymentMethodKind, type StoreOrder, type StoreOrderLine, type SyncContext, type TallyConnector } from '@tallyui/core';
|
|
2
|
+
import { customerRequest } from './customers';
|
|
3
|
+
import { wooMinorFromDecimal } from './commands/transport';
|
|
4
|
+
|
|
5
|
+
type Row = Record<string, unknown>;
|
|
6
|
+
|
|
7
|
+
const MAX_PER_PAGE = 100;
|
|
8
|
+
|
|
9
|
+
const unexpected = () => new CustomerServiceError('server', 'unexpected response');
|
|
10
|
+
const isRow = (value: unknown): value is Row => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
11
|
+
const rows = (value: unknown): Row[] => (Array.isArray(value) ? value.filter(isRow) : []);
|
|
12
|
+
const nonEmpty = (value: unknown) => (typeof value === 'string' && value.length > 0 ? value : undefined);
|
|
13
|
+
const positiveId = (value: unknown) => (typeof value === 'number' && Number.isInteger(value) && value > 0 ? String(value) : undefined);
|
|
14
|
+
|
|
15
|
+
function minor(text: unknown, currency: string): number {
|
|
16
|
+
if (typeof text !== 'string') throw unexpected();
|
|
17
|
+
const trimmed = text.trim();
|
|
18
|
+
const negative = /^-\d/.test(trimmed);
|
|
19
|
+
const value = wooMinorFromDecimal(negative ? trimmed.slice(1) : trimmed, currency);
|
|
20
|
+
if (value === undefined) throw unexpected();
|
|
21
|
+
return negative && value !== 0 ? -value : value;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Sum two WooCommerce decimal strings (WCPOS stores 6dp) exactly, then round half away from zero to minor units.
|
|
25
|
+
function decimalSumMinor(a: unknown, b: unknown, currency: string): number {
|
|
26
|
+
const parts = [a, b].map((text) => /^(-?)(\d+)(?:\.(\d+))?$/.exec(typeof text === 'string' ? text.trim() : ''));
|
|
27
|
+
const scale = Math.max(minorUnitDigits(currency), ...parts.map((part) => part?.[3]?.length ?? 0));
|
|
28
|
+
let total = 0n;
|
|
29
|
+
for (const part of parts) {
|
|
30
|
+
if (!part) throw unexpected();
|
|
31
|
+
total += BigInt(`${part[1]}${part[2]}${(part[3] ?? '').padEnd(scale, '0')}`);
|
|
32
|
+
}
|
|
33
|
+
const divisor = 10n ** BigInt(scale - minorUnitDigits(currency));
|
|
34
|
+
const rounded = ((total < 0n ? -total : total) + divisor / 2n) / divisor;
|
|
35
|
+
return Number(total < 0n ? -rounded : rounded);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The tax such that net + tax is the gross rounded once, exactly. */
|
|
39
|
+
const grossTax = (net: unknown, tax: unknown, currency: string) => decimalSumMinor(net, tax, currency) - minor(net, currency);
|
|
40
|
+
|
|
41
|
+
function posUuid(metaData: unknown): string | undefined {
|
|
42
|
+
const entry = rows(metaData).find((meta) => meta.key === '_woocommerce_pos_uuid' && nonEmpty(meta.value));
|
|
43
|
+
return entry ? (entry.value as string) : undefined;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const PAYMENT_KINDS: Record<string, PaymentMethodKind> = { pos_cash: 'cash', pos_card: 'external' };
|
|
47
|
+
|
|
48
|
+
/** Maps a WooCommerce order resource (as WCPOS `wcpos/v2/orders` serves it) to a `StoreOrder` (ADR-081). */
|
|
49
|
+
export function toWooStoreOrder(raw: unknown): StoreOrder {
|
|
50
|
+
if (!isRow(raw) || raw.id === undefined || raw.id === null || typeof raw.currency !== 'string' || typeof raw.date_created_gmt !== 'string') {
|
|
51
|
+
throw unexpected();
|
|
52
|
+
}
|
|
53
|
+
const currency = raw.currency;
|
|
54
|
+
const dateText = raw.date_created_gmt;
|
|
55
|
+
const placed = new Date(/(Z|[+-]\d{2}:?\d{2})$/.test(dateText) ? dateText : `${dateText}Z`);
|
|
56
|
+
if (Number.isNaN(placed.getTime())) throw unexpected();
|
|
57
|
+
|
|
58
|
+
const billing = isRow(raw.billing) ? raw.billing : {};
|
|
59
|
+
const customerId = positiveId(raw.customer_id);
|
|
60
|
+
const name = [billing.first_name, billing.last_name].filter((part) => typeof part === 'string').join(' ').trim();
|
|
61
|
+
const email = nonEmpty(billing.email);
|
|
62
|
+
const customer = customerId || name || email
|
|
63
|
+
? { ...(customerId ? { id: customerId } : {}), ...(name ? { name } : {}), ...(email ? { email } : {}) }
|
|
64
|
+
: null;
|
|
65
|
+
|
|
66
|
+
const clientOrderId = posUuid(raw.meta_data);
|
|
67
|
+
const totalMinor = minor(raw.total, currency);
|
|
68
|
+
const paymentMethod = nonEmpty(raw.payment_method);
|
|
69
|
+
const paymentTitle = nonEmpty(raw.payment_method_title);
|
|
70
|
+
const paymentKind = paymentMethod ? PAYMENT_KINDS[paymentMethod] : undefined;
|
|
71
|
+
|
|
72
|
+
return {
|
|
73
|
+
id: String(raw.id),
|
|
74
|
+
reference: String(raw.number ?? raw.id),
|
|
75
|
+
...(clientOrderId ? { clientOrderId } : {}),
|
|
76
|
+
status: String(raw.status),
|
|
77
|
+
placedAt: placed.toISOString(),
|
|
78
|
+
currency,
|
|
79
|
+
pricesIncludeTax: raw.prices_include_tax === true,
|
|
80
|
+
customer,
|
|
81
|
+
lines: rows(raw.line_items).map((line): StoreOrderLine => {
|
|
82
|
+
const clientLineId = posUuid(line.meta_data);
|
|
83
|
+
const productId = positiveId(line.product_id);
|
|
84
|
+
const variantId = positiveId(line.variation_id) ?? productId;
|
|
85
|
+
const sku = nonEmpty(line.sku);
|
|
86
|
+
return {
|
|
87
|
+
id: String(line.id),
|
|
88
|
+
...(clientLineId ? { clientLineId } : {}),
|
|
89
|
+
...(productId ? { productId } : {}),
|
|
90
|
+
...(variantId ? { variantId } : {}),
|
|
91
|
+
name: String(line.name),
|
|
92
|
+
...(sku ? { sku } : {}),
|
|
93
|
+
quantity: Number(line.quantity),
|
|
94
|
+
subtotalMinor: minor(line.subtotal, currency),
|
|
95
|
+
subtotalTaxMinor: grossTax(line.subtotal, line.subtotal_tax, currency),
|
|
96
|
+
totalMinor: minor(line.total, currency),
|
|
97
|
+
taxMinor: grossTax(line.total, line.total_tax, currency),
|
|
98
|
+
};
|
|
99
|
+
}),
|
|
100
|
+
fees: rows(raw.fee_lines).map((fee) => ({
|
|
101
|
+
name: String(fee.name), totalMinor: minor(fee.total, currency), taxMinor: grossTax(fee.total, fee.total_tax, currency),
|
|
102
|
+
})),
|
|
103
|
+
shipping: rows(raw.shipping_lines).map((line) => ({
|
|
104
|
+
name: String(line.method_title), totalMinor: minor(line.total, currency), taxMinor: grossTax(line.total, line.total_tax, currency),
|
|
105
|
+
})),
|
|
106
|
+
coupons: rows(raw.coupon_lines).map((coupon) => ({
|
|
107
|
+
code: String(coupon.code),
|
|
108
|
+
discountMinor: minor(coupon.discount, currency),
|
|
109
|
+
discountTaxMinor: grossTax(coupon.discount, coupon.discount_tax, currency),
|
|
110
|
+
})),
|
|
111
|
+
taxLines: rows(raw.tax_lines).map((tax) => {
|
|
112
|
+
const code = nonEmpty(tax.rate_code);
|
|
113
|
+
return {
|
|
114
|
+
label: String(tax.label),
|
|
115
|
+
...(code ? { code } : {}),
|
|
116
|
+
ratePpm: typeof tax.rate_percent === 'number' && Number.isFinite(tax.rate_percent) ? Math.round(tax.rate_percent * 10000) : 0,
|
|
117
|
+
amountMinor: minor(tax.tax_total, currency) + minor(tax.shipping_tax_total, currency),
|
|
118
|
+
};
|
|
119
|
+
}),
|
|
120
|
+
discountMinor: minor(raw.discount_total, currency),
|
|
121
|
+
discountTaxMinor: minor(raw.discount_tax, currency),
|
|
122
|
+
taxMinor: minor(raw.total_tax, currency),
|
|
123
|
+
totalMinor,
|
|
124
|
+
payments: paymentMethod ? [{
|
|
125
|
+
method: paymentMethod, ...(paymentTitle ? { title: paymentTitle } : {}), ...(paymentKind ? { kind: paymentKind } : {}), amountMinor: totalMinor,
|
|
126
|
+
}] : [],
|
|
127
|
+
refunds: rows(raw.refunds).map((refund) => {
|
|
128
|
+
const reason = nonEmpty(refund.reason);
|
|
129
|
+
return { id: String(refund.id), amountMinor: Math.abs(minor(refund.total, currency)), ...(reason ? { reason } : {}) };
|
|
130
|
+
}),
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const wholeNumber = (value: number | undefined, fallback: number) => (value === undefined || !Number.isFinite(value) ? fallback : Math.trunc(value));
|
|
135
|
+
|
|
136
|
+
/** WCPOS `wcpos/v2/orders`: order history, read-only (ADR-081). */
|
|
137
|
+
export function createWooOrders(): Required<Pick<TallyConnector, 'listOrders' | 'getOrders'>> {
|
|
138
|
+
return {
|
|
139
|
+
async listOrders(context: SyncContext, query = {}) {
|
|
140
|
+
const page = Math.max(1, wholeNumber(query.page, 1));
|
|
141
|
+
const perPage = Math.max(1, Math.min(MAX_PER_PAGE, wholeNumber(query.perPage, 25)));
|
|
142
|
+
const params = new URLSearchParams({ page: String(page), per_page: String(perPage), orderby: 'date', order: 'desc' });
|
|
143
|
+
const search = query.search?.trim();
|
|
144
|
+
if (search) params.set('search', search);
|
|
145
|
+
const { body, headers } = await customerRequest(context, `orders?${params}`, { method: 'GET' });
|
|
146
|
+
if (!Array.isArray(body)) throw unexpected();
|
|
147
|
+
const orders = body.map(toWooStoreOrder);
|
|
148
|
+
const totalPages = headers.get('X-WP-TotalPages');
|
|
149
|
+
const hasMore = totalPages !== null && /^\d+$/.test(totalPages.trim())
|
|
150
|
+
? page < Number.parseInt(totalPages, 10)
|
|
151
|
+
: orders.length === perPage;
|
|
152
|
+
return { orders, hasMore };
|
|
153
|
+
},
|
|
154
|
+
|
|
155
|
+
async getOrders(context: SyncContext, ids: readonly string[]) {
|
|
156
|
+
const wanted = [...new Set(ids.filter((id) => /^[1-9]\d*$/.test(id)))];
|
|
157
|
+
const found = new Map<string, StoreOrder>();
|
|
158
|
+
for (let start = 0; start < wanted.length; start += MAX_PER_PAGE) {
|
|
159
|
+
const chunk = wanted.slice(start, start + MAX_PER_PAGE);
|
|
160
|
+
// The ids are digits only, so the comma-joined list needs no encoding.
|
|
161
|
+
const { body } = await customerRequest(context, `orders?include=${chunk.join(',')}&per_page=${chunk.length}`, { method: 'GET' });
|
|
162
|
+
if (!Array.isArray(body)) throw unexpected();
|
|
163
|
+
for (const order of body.map(toWooStoreOrder)) found.set(order.id, order);
|
|
164
|
+
}
|
|
165
|
+
return wanted.flatMap((id) => found.get(id) ?? []);
|
|
166
|
+
},
|
|
167
|
+
};
|
|
168
|
+
}
|