@tallyui/connector-woocommerce 3.11.0 → 3.13.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 CHANGED
@@ -1,4 +1,4 @@
1
- import { SyncContext, ServerCapabilities, StoreSettings, Customer, CustomerInput, OrderCreateEnvelope, CommandResult, ReconcileFeed, CatalogueReconcileAdapter, ProductTraits, CollectionSync, ReplicationAdapter, ConnectorUnauthorizedError, TallyConnector } from '@tallyui/core';
1
+ import { SyncContext, ServerCapabilities, StoreSettings, Customer, 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
 
@@ -19,6 +19,11 @@ type WooCustomerRow = {
19
19
  phone?: string | null;
20
20
  company?: string | null;
21
21
  } | null;
22
+ meta_data?: {
23
+ key?: string;
24
+ value?: unknown;
25
+ }[];
26
+ _rxdb_revision?: unknown;
22
27
  };
23
28
  declare function toWooCustomer(raw: WooCustomerRow): Customer;
24
29
  declare function createWooCustomers(options?: {
@@ -29,11 +34,17 @@ declare function createWooCustomers(options?: {
29
34
  }): Promise<Customer[]>;
30
35
  getCustomer(context: SyncContext, id: string): Promise<Customer | null>;
31
36
  createCustomer(context: SyncContext, input: CustomerInput): Promise<Customer>;
37
+ updateCustomer(context: SyncContext, id: string, patch: CustomerPatch): Promise<Customer>;
32
38
  emailReceipt(context: SyncContext, orderId: string, email: string, options?: {
33
39
  saveToBilling?: boolean;
34
40
  }): Promise<void>;
35
41
  };
36
42
 
43
+ /** Maps a WooCommerce order resource (as WCPOS `wcpos/v2/orders` serves it) to a `StoreOrder` (ADR-081). */
44
+ declare function toWooStoreOrder(raw: unknown): StoreOrder;
45
+ /** WCPOS `wcpos/v2/orders`: order history, read-only (ADR-081). */
46
+ declare function createWooOrders(): Required<Pick<TallyConnector, 'listOrders' | 'getOrders'>>;
47
+
37
48
  type WooTransportOutcome = {
38
49
  kind: 'results';
39
50
  results: CommandResult[];
@@ -224,7 +235,7 @@ declare const wooReconcileFingerprint: (p: {
224
235
  * fast-path request where the store offers it (#313), else page by page, with no date filter, and hands differences
225
236
  * to `feed`, which reaches the collection only through the pull. `confirmGone` is the deletion proof: a by-id re-read.
226
237
  */
227
- declare function wooCatalogueReconcile(feed: Pick<ReconcileFeed<any>, 'enqueue'>): CatalogueReconcileAdapter<any, number>;
238
+ declare function wooCatalogueReconcile(feed: Pick<ReconcileFeed<any>, 'enqueue'>): CatalogueReconcileAdapter<any, number | undefined>;
228
239
 
229
240
  /** One part of X-WCPOS-Client as WCPOS keeps it: lowercase [a-z0-9._-], at most 32 characters. */
230
241
  declare function wcposClientPart(part: string): string;
@@ -256,4 +267,4 @@ declare function createWooCommerceConnector(): TallyConnector;
256
267
  */
257
268
  declare const woocommerceConnector: TallyConnector;
258
269
 
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 };
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 };
package/dist/index.js CHANGED
@@ -673,30 +673,30 @@ 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 = (rows) => rows.filter((row) => Number.isInteger(row?.id)).map((row) => ({ key: String(row.id), fingerprint: wooReconcileFingerprint(row), remote: row.id }));
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
- async *fetchPages(context, from = 1) {
679
+ async *fetchPages(context, from) {
680
680
  const fast = await wooHasIdFastPath(context);
681
681
  yield { entries: [], cursor: from };
682
682
  if (fast) {
683
- let rows;
683
+ let rows2;
684
684
  let failed = false;
685
685
  try {
686
- rows = await get(wooBulkListingUrl(""), context);
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(rows)) {
693
- yield { entries: toEntries(rows), cursor: from };
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.");
697
697
  yield { entries: [], cursor: from };
698
698
  }
699
- for (let page = from; ; page++) {
699
+ for (let page = from ?? 1; ; page++) {
700
700
  const params = new URLSearchParams({
701
701
  per_page: String(PAGE_SIZE),
702
702
  page: String(page),
@@ -705,9 +705,9 @@ function wooCatalogueReconcile(feed) {
705
705
  status: "publish",
706
706
  _fields: LISTING_FIELDS
707
707
  });
708
- const rows = await get(`/products?${params}`, context);
709
- yield { entries: toEntries(rows), cursor: page + 1 };
710
- if (rows.length < PAGE_SIZE) return;
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 rows = await get(`/products?${params}`, context);
721
- const live = new Map(rows.filter((row) => row.status === "publish").map((row) => [row.id, wooProductUuid(row)]));
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 rows = await get2(`/coupons?${params}`, context);
783
- documents.push(...rows.map(toCouponDocument).filter((doc) => doc !== void 0));
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 = (rows) => rows.filter((row) => Number.isInteger(row?.id)).map((row) => ({ key: String(row.id), fingerprint: wooCouponFingerprint(row), remote: row.id }));
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 rows = await get2(`/coupons?${params}`, context);
804
- yield { entries: toEntries2(rows), cursor: page + 1 };
805
- if (rows.length < PAGE_SIZE2) return;
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 rows = await get2(`/coupons?${params}`, context);
819
- for (const row of rows) live.set(row.id, wooProductUuid(row));
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
  },
@@ -826,7 +826,45 @@ function wooCouponReconcile(feed) {
826
826
  }
827
827
 
828
828
  // src/customers.ts
829
- import { CustomerServiceError } from "@tallyui/core";
829
+ import {
830
+ CustomerServiceError
831
+ } from "@tallyui/core";
832
+ var WOO_ADDRESS = [
833
+ ["first_name", "firstName"],
834
+ ["last_name", "lastName"],
835
+ ["company", "company"],
836
+ ["address_1", "address1"],
837
+ ["address_2", "address2"],
838
+ ["city", "city"],
839
+ ["postcode", "postcode"],
840
+ ["country", "country"],
841
+ ["state", "state"],
842
+ ["email", "email"],
843
+ ["phone", "phone"]
844
+ ];
845
+ function toWooAddress(address, kind) {
846
+ return Object.fromEntries(WOO_ADDRESS.filter(([key]) => kind === "billing" || key !== "email").map(([key, field]) => [key, address[field] ?? ""]));
847
+ }
848
+ function toWooPatch(patch) {
849
+ const contact = {
850
+ ...patch.phone !== void 0 ? { phone: patch.phone } : {},
851
+ ...patch.company !== void 0 ? { company: patch.company } : {}
852
+ };
853
+ const billing = patch.billing ? { ...toWooAddress(patch.billing, "billing"), ...contact } : contact;
854
+ return {
855
+ ...patch.firstName !== void 0 ? { first_name: patch.firstName } : {},
856
+ ...patch.lastName !== void 0 ? { last_name: patch.lastName } : {},
857
+ ...patch.email !== void 0 ? { email: patch.email } : {},
858
+ ...Object.keys(billing).length > 0 ? { billing } : {},
859
+ ...patch.shipping ? { shipping: toWooAddress(patch.shipping, "shipping") } : {},
860
+ ...patch.taxIds ? { tax_ids: patch.taxIds.map(({ type, value, country, label }) => ({
861
+ type,
862
+ value,
863
+ ...country !== void 0 ? { country } : {},
864
+ ...label !== void 0 ? { label } : {}
865
+ })) } : {}
866
+ };
867
+ }
830
868
  function toWooCustomer(raw) {
831
869
  const customer = { id: String(raw.id), name: String(raw.id) };
832
870
  for (const [key, value] of [
@@ -864,9 +902,9 @@ async function customerRequest(context, route, init = {}) {
864
902
  const body = await response.json().catch(() => void 0);
865
903
  if (!response.ok) {
866
904
  const invalid = [400, 404, 422].includes(response.status);
867
- throw new CustomerServiceError(invalid ? "invalid" : "server", invalid ? body?.message ?? `HTTP ${response.status}` : `HTTP ${response.status}`);
905
+ throw new CustomerServiceError(invalid ? "invalid" : "server", invalid ? body?.message ?? `HTTP ${response.status}` : `HTTP ${response.status}`, { status: response.status });
868
906
  }
869
- return { status: response.status, body };
907
+ return { status: response.status, body, headers: response.headers };
870
908
  }
871
909
  function createWooCustomers(options) {
872
910
  const newId = options?.newId ?? newWooId;
@@ -914,6 +952,35 @@ function createWooCustomers(options) {
914
952
  if (status !== 200 && status !== 201 || !body?.document) throw new CustomerServiceError("server", "unexpected response");
915
953
  return toWooCustomer(body.document);
916
954
  },
955
+ // WCPOS's own write surface, as WCPOS v2's customer edit uses it: an `update` push of the changed Woo REST fields,
956
+ // keyed by the record's uuid and current revision, which only the customer read carries.
957
+ async updateCustomer(context, id, patch) {
958
+ if (!/^\d+$/.test(id)) throw new CustomerServiceError("invalid", "Unknown customer");
959
+ if (patch.shipping?.email) throw new CustomerServiceError("invalid", "WooCommerce shipping addresses have no email");
960
+ const params = new URLSearchParams({ include: id, per_page: "1", role: "all" });
961
+ const { body: rows2 } = await customerRequest(context, `customers?${params}`, { method: "GET" });
962
+ if (!Array.isArray(rows2)) throw new CustomerServiceError("server", "unexpected response");
963
+ const row = rows2.find((raw) => String(raw.id) === id);
964
+ if (!row) throw new CustomerServiceError("invalid", "Unknown customer");
965
+ const uuid = row.meta_data?.find((entry) => entry.key === "_woocommerce_pos_uuid")?.value;
966
+ if (typeof uuid !== "string" || !uuid) throw new CustomerServiceError("server", "unexpected response");
967
+ const payload = toWooPatch(patch);
968
+ if (Object.keys(payload).length === 0) return toWooCustomer(row);
969
+ const { status, body } = await customerRequest(context, "push/customers", {
970
+ method: "POST",
971
+ headers: { "Content-Type": "application/json" },
972
+ body: JSON.stringify({
973
+ mutationId: newId(),
974
+ operation: "update",
975
+ collection: "customers",
976
+ recordId: uuid,
977
+ baseRevision: typeof row._rxdb_revision === "string" ? row._rxdb_revision : null,
978
+ payload
979
+ })
980
+ });
981
+ if (status !== 200 || !body?.document) throw new CustomerServiceError("server", "unexpected response");
982
+ return toWooCustomer(body.document);
983
+ },
917
984
  async emailReceipt(context, orderId, email, options2) {
918
985
  if (!/^[1-9]\d*$/.test(orderId)) throw new CustomerServiceError("invalid", "Invalid order ID");
919
986
  const { status, body } = await customerRequest(context, `orders/${encodeURIComponent(orderId)}/email`, {
@@ -926,172 +993,15 @@ function createWooCustomers(options) {
926
993
  };
927
994
  }
928
995
 
929
- // src/store-settings.ts
930
- import { ConnectorUnauthorizedError as ConnectorUnauthorizedError2, StoreSettingsError, minorUnitDigits, woocommerceTax } from "@tallyui/core";
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.11.0";
996
+ // src/orders.ts
997
+ import { CustomerServiceError as CustomerServiceError2, minorUnitDigits as minorUnitDigits2 } from "@tallyui/core";
1088
998
 
1089
999
  // src/commands/transport.ts
1090
- import { minorUnitDigits as minorUnitDigits2, moneyFromDecimalString, moneyFromMajor as moneyFromMajor2 } from "@tallyui/core";
1000
+ import { minorUnitDigits, moneyFromDecimalString, moneyFromMajor as moneyFromMajor2 } from "@tallyui/core";
1091
1001
  function wooMinorFromDecimal(text, currency) {
1092
1002
  const trimmed = text.trim();
1093
1003
  if (!/^\d+(\.\d+)?$/.test(trimmed)) return void 0;
1094
- const digits = minorUnitDigits2(currency);
1004
+ const digits = minorUnitDigits(currency);
1095
1005
  const [whole, fraction = ""] = trimmed.split(".");
1096
1006
  let end = fraction.length;
1097
1007
  while (end > digits && fraction[end - 1] === "0") end--;
@@ -1106,6 +1016,9 @@ function stripTags(text) {
1106
1016
  } while (text !== previous);
1107
1017
  return text;
1108
1018
  }
1019
+ function wooAnyAttributeKey(name) {
1020
+ return /^[A-Za-z0-9]+(?:[ -][A-Za-z0-9]+)*$/.test(name) ? name.toLowerCase().replace(/ /g, "-") : void 0;
1021
+ }
1109
1022
  function decodeCouponMessage(message) {
1110
1023
  const entities = { quot: '"', amp: "&", lt: "<", gt: ">", apos: "'" };
1111
1024
  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 +1041,8 @@ function toWooOrderPayload(envelope, local, options) {
1128
1041
  return { error: { code: "invalid_payload", message: `Line ${line.clientLineId} has no WooCommerce product id.` } };
1129
1042
  }
1130
1043
  }
1131
- const digits = p.display?.exponent ?? minorUnitDigits2(p.currency);
1132
- const major = (minor) => (minor / 10 ** digits).toFixed(digits);
1044
+ const digits = p.display?.exponent ?? minorUnitDigits(p.currency);
1045
+ const major = (minor2) => (minor2 / 10 ** digits).toFixed(digits);
1133
1046
  const inclusiveNet = (netMicros, id) => {
1134
1047
  if (netMicros === void 0) {
1135
1048
  return { error: { code: "unsupported_tax_mode", message: "Tax-inclusive prices need the till's WooCommerce tax figures; update the till." } };
@@ -1158,11 +1071,17 @@ function toWooOrderPayload(envelope, local, options) {
1158
1071
  if (p.coupons?.length) {
1159
1072
  const discount = (line.taxInclusive ?? p.pricesIncludeTax) && (line.discountMinor ?? 0) > 0 ? local?.lines.find((stored) => stored.id === line.clientLineId)?.discountMinor : line.discountMinor ?? 0;
1160
1073
  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), minor = BigInt(line.unitPriceMinor) * quantity - BigInt(discount);
1162
- const divisor = quantity * 10n ** BigInt(digits), micros = (minor * 1000000n * 2n + divisor) / (divisor * 2n);
1163
- price = minor % quantity === 0n ? major(Number(minor / quantity)) : `${micros / 1000000n}.${(micros % 1000000n).toString().padStart(6, "0")}`;
1074
+ const quantity = BigInt(line.quantity), minor2 = BigInt(line.unitPriceMinor) * quantity - BigInt(discount);
1075
+ const divisor = quantity * 10n ** BigInt(digits), micros = (minor2 * 1000000n * 2n + divisor) / (divisor * 2n);
1076
+ price = minor2 % quantity === 0n ? major(Number(minor2 / quantity)) : `${micros / 1000000n}.${(micros % 1000000n).toString().padStart(6, "0")}`;
1164
1077
  }
1165
1078
  const regular_price = p.coupons?.length && line.regularUnitPriceMinor !== void 0 ? major(line.regularUnitPriceMinor) : price;
1079
+ const picked = (line.anyAttributes ?? []).flatMap((name) => {
1080
+ const key = wooAnyAttributeKey(name);
1081
+ const value = line.attributes?.[name];
1082
+ return key && value ? [{ key, value }] : [];
1083
+ });
1084
+ const lineMeta = [...p.coupons?.length ? [{ key: "_woocommerce_pos_data", value: JSON.stringify({ price, regular_price }) }] : [], ...picked];
1166
1085
  line_items.push(custom ? {
1167
1086
  product_id: 0,
1168
1087
  name: custom.name,
@@ -1180,7 +1099,7 @@ function toWooOrderPayload(envelope, local, options) {
1180
1099
  quantity: line.quantity,
1181
1100
  subtotal,
1182
1101
  total,
1183
- ...p.coupons?.length ? { meta_data: [{ key: "_woocommerce_pos_data", value: JSON.stringify({ price, regular_price }) }] } : {}
1102
+ ...lineMeta.length ? { meta_data: lineMeta } : {}
1184
1103
  });
1185
1104
  }
1186
1105
  const fee_lines = [], shipping_lines = [];
@@ -1326,6 +1245,315 @@ function createWooCommandTransport(options) {
1326
1245
  };
1327
1246
  }
1328
1247
 
1248
+ // src/orders.ts
1249
+ var MAX_PER_PAGE = 100;
1250
+ var unexpected = () => new CustomerServiceError2("server", "unexpected response");
1251
+ var isRow = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1252
+ var rows = (value) => Array.isArray(value) ? value.filter(isRow) : [];
1253
+ var nonEmpty = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
1254
+ var positiveId = (value) => typeof value === "number" && Number.isInteger(value) && value > 0 ? String(value) : void 0;
1255
+ function minor(text, currency) {
1256
+ if (typeof text !== "string") throw unexpected();
1257
+ const trimmed = text.trim();
1258
+ const negative = /^-\d/.test(trimmed);
1259
+ const value = wooMinorFromDecimal(negative ? trimmed.slice(1) : trimmed, currency);
1260
+ if (value === void 0) throw unexpected();
1261
+ return negative && value !== 0 ? -value : value;
1262
+ }
1263
+ function decimalSumMinor(a, b, currency) {
1264
+ const parts = [a, b].map((text) => /^(-?)(\d+)(?:\.(\d+))?$/.exec(typeof text === "string" ? text.trim() : ""));
1265
+ const scale = Math.max(minorUnitDigits2(currency), ...parts.map((part) => part?.[3]?.length ?? 0));
1266
+ let total = 0n;
1267
+ for (const part of parts) {
1268
+ if (!part) throw unexpected();
1269
+ total += BigInt(`${part[1]}${part[2]}${(part[3] ?? "").padEnd(scale, "0")}`);
1270
+ }
1271
+ const divisor = 10n ** BigInt(scale - minorUnitDigits2(currency));
1272
+ const rounded = ((total < 0n ? -total : total) + divisor / 2n) / divisor;
1273
+ return Number(total < 0n ? -rounded : rounded);
1274
+ }
1275
+ var grossTax = (net, tax, currency) => decimalSumMinor(net, tax, currency) - minor(net, currency);
1276
+ function posUuid(metaData) {
1277
+ const entry = rows(metaData).find((meta) => meta.key === "_woocommerce_pos_uuid" && nonEmpty(meta.value));
1278
+ return entry ? entry.value : void 0;
1279
+ }
1280
+ var PAYMENT_KINDS = { pos_cash: "cash", pos_card: "external" };
1281
+ function toWooStoreOrder(raw) {
1282
+ if (!isRow(raw) || raw.id === void 0 || raw.id === null || typeof raw.currency !== "string" || typeof raw.date_created_gmt !== "string") {
1283
+ throw unexpected();
1284
+ }
1285
+ const currency = raw.currency;
1286
+ const dateText = raw.date_created_gmt;
1287
+ const placed = new Date(/(Z|[+-]\d{2}:?\d{2})$/.test(dateText) ? dateText : `${dateText}Z`);
1288
+ if (Number.isNaN(placed.getTime())) throw unexpected();
1289
+ const billing = isRow(raw.billing) ? raw.billing : {};
1290
+ const customerId = positiveId(raw.customer_id);
1291
+ const name = [billing.first_name, billing.last_name].filter((part) => typeof part === "string").join(" ").trim();
1292
+ const email = nonEmpty(billing.email);
1293
+ const customer = customerId || name || email ? { ...customerId ? { id: customerId } : {}, ...name ? { name } : {}, ...email ? { email } : {} } : null;
1294
+ const clientOrderId = posUuid(raw.meta_data);
1295
+ const totalMinor = minor(raw.total, currency);
1296
+ const paymentMethod = nonEmpty(raw.payment_method);
1297
+ const paymentTitle = nonEmpty(raw.payment_method_title);
1298
+ const paymentKind = paymentMethod ? PAYMENT_KINDS[paymentMethod] : void 0;
1299
+ return {
1300
+ id: String(raw.id),
1301
+ reference: String(raw.number ?? raw.id),
1302
+ ...clientOrderId ? { clientOrderId } : {},
1303
+ status: String(raw.status),
1304
+ placedAt: placed.toISOString(),
1305
+ currency,
1306
+ pricesIncludeTax: raw.prices_include_tax === true,
1307
+ customer,
1308
+ lines: rows(raw.line_items).map((line) => {
1309
+ const clientLineId = posUuid(line.meta_data);
1310
+ const productId = positiveId(line.product_id);
1311
+ const variantId = positiveId(line.variation_id) ?? productId;
1312
+ const sku = nonEmpty(line.sku);
1313
+ return {
1314
+ id: String(line.id),
1315
+ ...clientLineId ? { clientLineId } : {},
1316
+ ...productId ? { productId } : {},
1317
+ ...variantId ? { variantId } : {},
1318
+ name: String(line.name),
1319
+ ...sku ? { sku } : {},
1320
+ quantity: Number(line.quantity),
1321
+ subtotalMinor: minor(line.subtotal, currency),
1322
+ subtotalTaxMinor: grossTax(line.subtotal, line.subtotal_tax, currency),
1323
+ totalMinor: minor(line.total, currency),
1324
+ taxMinor: grossTax(line.total, line.total_tax, currency)
1325
+ };
1326
+ }),
1327
+ fees: rows(raw.fee_lines).map((fee) => ({
1328
+ name: String(fee.name),
1329
+ totalMinor: minor(fee.total, currency),
1330
+ taxMinor: grossTax(fee.total, fee.total_tax, currency)
1331
+ })),
1332
+ shipping: rows(raw.shipping_lines).map((line) => ({
1333
+ name: String(line.method_title),
1334
+ totalMinor: minor(line.total, currency),
1335
+ taxMinor: grossTax(line.total, line.total_tax, currency)
1336
+ })),
1337
+ coupons: rows(raw.coupon_lines).map((coupon) => ({
1338
+ code: String(coupon.code),
1339
+ discountMinor: minor(coupon.discount, currency),
1340
+ discountTaxMinor: grossTax(coupon.discount, coupon.discount_tax, currency)
1341
+ })),
1342
+ taxLines: rows(raw.tax_lines).map((tax) => {
1343
+ const code = nonEmpty(tax.rate_code);
1344
+ return {
1345
+ label: String(tax.label),
1346
+ ...code ? { code } : {},
1347
+ ratePpm: typeof tax.rate_percent === "number" && Number.isFinite(tax.rate_percent) ? Math.round(tax.rate_percent * 1e4) : 0,
1348
+ amountMinor: minor(tax.tax_total, currency) + minor(tax.shipping_tax_total, currency)
1349
+ };
1350
+ }),
1351
+ discountMinor: minor(raw.discount_total, currency),
1352
+ discountTaxMinor: minor(raw.discount_tax, currency),
1353
+ taxMinor: minor(raw.total_tax, currency),
1354
+ totalMinor,
1355
+ payments: paymentMethod ? [{
1356
+ method: paymentMethod,
1357
+ ...paymentTitle ? { title: paymentTitle } : {},
1358
+ ...paymentKind ? { kind: paymentKind } : {},
1359
+ amountMinor: totalMinor
1360
+ }] : [],
1361
+ refunds: rows(raw.refunds).map((refund) => {
1362
+ const reason = nonEmpty(refund.reason);
1363
+ return { id: String(refund.id), amountMinor: Math.abs(minor(refund.total, currency)), ...reason ? { reason } : {} };
1364
+ })
1365
+ };
1366
+ }
1367
+ var wholeNumber = (value, fallback) => value === void 0 || !Number.isFinite(value) ? fallback : Math.trunc(value);
1368
+ function createWooOrders() {
1369
+ return {
1370
+ async listOrders(context, query = {}) {
1371
+ const page = Math.max(1, wholeNumber(query.page, 1));
1372
+ const perPage = Math.max(1, Math.min(MAX_PER_PAGE, wholeNumber(query.perPage, 25)));
1373
+ const params = new URLSearchParams({ page: String(page), per_page: String(perPage), orderby: "date", order: "desc" });
1374
+ const search = query.search?.trim();
1375
+ if (search) params.set("search", search);
1376
+ const { body, headers } = await customerRequest(context, `orders?${params}`, { method: "GET" });
1377
+ if (!Array.isArray(body)) throw unexpected();
1378
+ const orders = body.map(toWooStoreOrder);
1379
+ const totalPages = headers.get("X-WP-TotalPages");
1380
+ const hasMore = totalPages !== null && /^\d+$/.test(totalPages.trim()) ? page < Number.parseInt(totalPages, 10) : orders.length === perPage;
1381
+ return { orders, hasMore };
1382
+ },
1383
+ async getOrders(context, ids) {
1384
+ const wanted = [...new Set(ids.filter((id) => /^[1-9]\d*$/.test(id)))];
1385
+ const found = /* @__PURE__ */ new Map();
1386
+ for (let start = 0; start < wanted.length; start += MAX_PER_PAGE) {
1387
+ const chunk = wanted.slice(start, start + MAX_PER_PAGE);
1388
+ const { body } = await customerRequest(context, `orders?include=${chunk.join(",")}&per_page=${chunk.length}`, { method: "GET" });
1389
+ if (!Array.isArray(body)) throw unexpected();
1390
+ for (const order of body.map(toWooStoreOrder)) found.set(order.id, order);
1391
+ }
1392
+ return wanted.flatMap((id) => found.get(id) ?? []);
1393
+ }
1394
+ };
1395
+ }
1396
+
1397
+ // src/store-settings.ts
1398
+ import { ConnectorUnauthorizedError as ConnectorUnauthorizedError2, StoreSettingsError, minorUnitDigits as minorUnitDigits3, woocommerceTax } from "@tallyui/core";
1399
+ var WOO_ORDER_CREATE_VERSION = 5;
1400
+ var WOO_COUPON_ORDER_CREATE_VERSION = 6;
1401
+ var WOO_BASE_ORDER_CREATE_VERSION = 3;
1402
+ var WOO_COUPONS_MIN_PLUGIN = [1, 9, 0];
1403
+ function wooPluginSupportsCoupons(version2) {
1404
+ if (typeof version2 !== "string") return false;
1405
+ const match = /^(\d+)\.(\d+)(?:\.(\d+))?(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/.exec(version2.trim());
1406
+ if (!match) return false;
1407
+ const parts = [Number(match[1]), Number(match[2]), Number(match[3] ?? 0)];
1408
+ for (let index = 0; index < parts.length; index++) {
1409
+ if (parts[index] > WOO_COUPONS_MIN_PLUGIN[index]) return true;
1410
+ if (parts[index] < WOO_COUPONS_MIN_PLUGIN[index]) return false;
1411
+ }
1412
+ return !match[4];
1413
+ }
1414
+ async function wooStoreSettings(context) {
1415
+ try {
1416
+ const init = { method: "GET", headers: context.headers, signal: context.signal };
1417
+ const storesResponse = await fetch(`${context.baseUrl}/stores`, init);
1418
+ if (storesResponse.status === 401 || storesResponse.status === 403) {
1419
+ throw new ConnectorUnauthorizedError2(`WooCommerce stores: HTTP ${storesResponse.status}`, storesResponse.status);
1420
+ }
1421
+ if (!storesResponse.ok) throw new Error(`WooCommerce stores: HTTP ${storesResponse.status}`);
1422
+ const stores = await storesResponse.json();
1423
+ if (!Array.isArray(stores) || stores.length === 0) throw new Error("WooCommerce stores: expected a non-empty array");
1424
+ const store = stores[0];
1425
+ const currency = store.currency.toUpperCase();
1426
+ const digits = minorUnitDigits3(currency);
1427
+ if (typeof store.price_num_decimals === "number" && store.price_num_decimals !== digits) {
1428
+ console.warn(`WooCommerce price_num_decimals is ${store.price_num_decimals}; the till rounds ${currency} to ${digits} digits`);
1429
+ }
1430
+ const classesResponse = await fetch(`${context.baseUrl}/taxes/classes`, init);
1431
+ if (classesResponse.status === 401 || classesResponse.status === 403) {
1432
+ throw new ConnectorUnauthorizedError2(`WooCommerce tax classes: HTTP ${classesResponse.status}`, classesResponse.status);
1433
+ }
1434
+ if (!classesResponse.ok) throw new Error(`WooCommerce tax classes: HTTP ${classesResponse.status}`);
1435
+ const classes = await classesResponse.json();
1436
+ if (!Array.isArray(classes)) throw new Error("WooCommerce tax classes: expected an array");
1437
+ const taxRates = {};
1438
+ const taxRatesPpm = { default: 0 };
1439
+ const settings = {
1440
+ currency,
1441
+ pricesIncludeTax: store.prices_include_tax === "yes",
1442
+ taxRoundAtSubtotal: store.tax_round_at_subtotal === "yes",
1443
+ calcDiscountsSequentially: (store.woocommerce_calc_discounts_sequentially ?? store.calc_discounts_sequentially) === "yes",
1444
+ ...typeof store.shipping_tax_class === "string" ? { shippingTaxClass: store.shipping_tax_class } : {},
1445
+ taxClassSlugs: classes.map((row) => row.slug),
1446
+ taxRates,
1447
+ taxRatesPpm
1448
+ };
1449
+ if (store.calc_taxes !== "yes") return settings;
1450
+ const rates = [];
1451
+ 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);
1453
+ if (response.status === 401 || response.status === 403) {
1454
+ throw new ConnectorUnauthorizedError2(`WooCommerce taxes: HTTP ${response.status}`, response.status);
1455
+ }
1456
+ if (!response.ok) throw new Error(`WooCommerce taxes: HTTP ${response.status}`);
1457
+ const rows2 = await response.json();
1458
+ if (!Array.isArray(rows2)) throw new Error("WooCommerce taxes: expected an array");
1459
+ rates.push(...rows2.map((row) => ({
1460
+ ...row,
1461
+ postcodes: row.postcodes ?? [],
1462
+ cities: row.cities ?? []
1463
+ })));
1464
+ if (rows2.length < 100) break;
1465
+ }
1466
+ const taxAddress = store.tax_address;
1467
+ 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 };
1468
+ if (!address.country) {
1469
+ console.warn("WooCommerce has no tax or store country; matching tax rates with an empty address");
1470
+ address = {};
1471
+ }
1472
+ const matched = woocommerceTax.filterTaxRates(rates, address.country, address.state, address.postcode, address.city);
1473
+ for (const rate of matched) {
1474
+ const slug = woocommerceTax.normalizeTaxClass(rate.class);
1475
+ (taxRates[slug] ??= []).push({
1476
+ id: rate.id,
1477
+ code: [rate.country, rate.state, rate.name || "TAX", String(rate.priority)].filter(Boolean).join("-").toUpperCase(),
1478
+ label: rate.name,
1479
+ rate: rate.rate,
1480
+ priority: rate.priority,
1481
+ compound: rate.compound,
1482
+ shipping: rate.shipping
1483
+ });
1484
+ const key = slug === "standard" ? "default" : slug;
1485
+ taxRatesPpm[key] = (taxRatesPpm[key] ?? 0) + Math.round(Number(rate.rate) * 1e4);
1486
+ }
1487
+ return settings;
1488
+ } catch (error) {
1489
+ if (error instanceof ConnectorUnauthorizedError2) throw error;
1490
+ throw new StoreSettingsError("failed", error instanceof Error ? error.message : String(error));
1491
+ }
1492
+ }
1493
+ async function readWooCapabilities(context) {
1494
+ try {
1495
+ const response = await fetch(`${context.baseUrl}/stores`, {
1496
+ method: "GET",
1497
+ headers: context.headers,
1498
+ signal: context.signal
1499
+ });
1500
+ if (response.status === 401 || response.status === 403) {
1501
+ throw new ConnectorUnauthorizedError2(`WooCommerce stores: HTTP ${response.status}`, response.status);
1502
+ }
1503
+ if (!response.ok) return void 0;
1504
+ const stores = await response.json();
1505
+ if (!Array.isArray(stores) || !stores[0] || typeof stores[0] !== "object" || Array.isArray(stores[0])) return void 0;
1506
+ let multiplePayments = false;
1507
+ let capabilities = [];
1508
+ try {
1509
+ const status = await fetch(`${context.baseUrl}/status`, {
1510
+ method: "GET",
1511
+ headers: context.headers,
1512
+ signal: context.signal
1513
+ });
1514
+ if (status.status === 401 || status.status === 403) {
1515
+ throw new ConnectorUnauthorizedError2(`WooCommerce status: HTTP ${status.status}`, status.status);
1516
+ }
1517
+ if (status.ok) {
1518
+ const body = await status.json();
1519
+ capabilities = Array.isArray(body?.capabilities) ? body.capabilities : [];
1520
+ multiplePayments = capabilities.includes("order_payments_list");
1521
+ }
1522
+ } catch (error) {
1523
+ if (error instanceof ConnectorUnauthorizedError2) throw error;
1524
+ }
1525
+ let coupons = false;
1526
+ try {
1527
+ const site = await fetch(`${context.baseUrl}/site`, {
1528
+ method: "GET",
1529
+ headers: context.headers,
1530
+ signal: context.signal
1531
+ });
1532
+ if (site.ok) {
1533
+ const body = await site.json();
1534
+ coupons = wooPluginSupportsCoupons(body?.wcpos_version);
1535
+ }
1536
+ } catch {
1537
+ coupons = false;
1538
+ }
1539
+ const orderCreate = capabilities.includes("order_create_v5") ? coupons ? WOO_COUPON_ORDER_CREATE_VERSION : WOO_ORDER_CREATE_VERSION : WOO_BASE_ORDER_CREATE_VERSION;
1540
+ return {
1541
+ orderCreate,
1542
+ taxRounding: { granularity: "woocommerce", roundAtSubtotal: stores[0].tax_round_at_subtotal === "yes" },
1543
+ multiplePayments,
1544
+ coupons,
1545
+ // 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.
1546
+ lineTax: { none: true, classes: true }
1547
+ };
1548
+ } catch (error) {
1549
+ if (error instanceof ConnectorUnauthorizedError2) throw error;
1550
+ return void 0;
1551
+ }
1552
+ }
1553
+
1554
+ // package.json
1555
+ var version = "3.13.0";
1556
+
1329
1557
  // src/index.ts
1330
1558
  import { ConnectorUnauthorizedError as ConnectorUnauthorizedError4 } from "@tallyui/core";
1331
1559
  function wcposClientPart(part) {
@@ -1345,6 +1573,8 @@ function createWooCommerceConnector() {
1345
1573
  ...wooConnectorParts,
1346
1574
  // WCPOS wcpos/v2/customers, push/customers and orders/<id>/email.
1347
1575
  ...customers,
1576
+ // WCPOS wcpos/v2/orders: order history (ADR-081).
1577
+ ...createWooOrders(),
1348
1578
  replication: {
1349
1579
  // One replication per collection; the reconcile feed is last, so its fetch wins duplicates;
1350
1580
  // duplicates are matched by uuid, the primary key, not the store id (#331). legacyKey
@@ -1422,10 +1652,12 @@ export {
1422
1652
  createWooCommerceConnector,
1423
1653
  createWooCouponFeed,
1424
1654
  createWooCustomers,
1655
+ createWooOrders,
1425
1656
  readWooCapabilities,
1426
1657
  toCouponDocument,
1427
1658
  toWooCustomer,
1428
1659
  toWooOrderPayload,
1660
+ toWooStoreOrder,
1429
1661
  wcposClientPart,
1430
1662
  wooCatalogueReconcile,
1431
1663
  wooCouponFingerprint,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/connector-woocommerce",
3
- "version": "3.11.0",
3
+ "version": "3.13.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.11.0"
30
+ "@tallyui/core": "^3.13.0"
31
31
  },
32
32
  "devDependencies": {
33
- "@tallyui/database": "3.11.0",
33
+ "@tallyui/database": "3.13.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
- ...(p.coupons?.length ? { meta_data: [{ key: '_woocommerce_pos_data', value: JSON.stringify({ price, regular_price }) }] } : {}) });
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
@@ -1,4 +1,6 @@
1
- import { CustomerServiceError, type Customer, type CustomerInput, type SyncContext } from '@tallyui/core';
1
+ import {
2
+ CustomerServiceError, type Customer, type CustomerAddress, type CustomerInput, type CustomerPatch, type SyncContext,
3
+ } from '@tallyui/core';
2
4
  import { checkResponse } from './replication/products';
3
5
 
4
6
  type WooCustomerRow = {
@@ -10,8 +12,40 @@ type WooCustomerRow = {
10
12
  first_name?: string | null; last_name?: string | null; email?: string | null;
11
13
  phone?: string | null; company?: string | null;
12
14
  } | null;
15
+ meta_data?: { key?: string; value?: unknown }[];
16
+ _rxdb_revision?: unknown;
13
17
  };
14
18
 
19
+ // Woo's address keys and the CustomerAddress field each comes from; shipping has no email.
20
+ const WOO_ADDRESS = [
21
+ ['first_name', 'firstName'], ['last_name', 'lastName'], ['company', 'company'], ['address_1', 'address1'],
22
+ ['address_2', 'address2'], ['city', 'city'], ['postcode', 'postcode'], ['country', 'country'], ['state', 'state'],
23
+ ['email', 'email'], ['phone', 'phone'],
24
+ ] as const;
25
+
26
+ /** The whole Woo address, '' for an absent field, so a patch replaces the stored address rather than merging into it. */
27
+ function toWooAddress(address: CustomerAddress, kind: 'billing' | 'shipping'): Record<string, string> {
28
+ return Object.fromEntries(WOO_ADDRESS.filter(([key]) => kind === 'billing' || key !== 'email')
29
+ .map(([key, field]) => [key, address[field] ?? '']));
30
+ }
31
+
32
+ function toWooPatch(patch: CustomerPatch): Record<string, unknown> {
33
+ const contact = {
34
+ ...(patch.phone !== undefined ? { phone: patch.phone } : {}), ...(patch.company !== undefined ? { company: patch.company } : {}),
35
+ };
36
+ const billing = patch.billing ? { ...toWooAddress(patch.billing, 'billing'), ...contact } : contact;
37
+ return {
38
+ ...(patch.firstName !== undefined ? { first_name: patch.firstName } : {}),
39
+ ...(patch.lastName !== undefined ? { last_name: patch.lastName } : {}),
40
+ ...(patch.email !== undefined ? { email: patch.email } : {}),
41
+ ...(Object.keys(billing).length > 0 ? { billing } : {}),
42
+ ...(patch.shipping ? { shipping: toWooAddress(patch.shipping, 'shipping') } : {}),
43
+ ...(patch.taxIds ? { tax_ids: patch.taxIds.map(({ type, value, country, label }) => ({
44
+ type, value, ...(country !== undefined ? { country } : {}), ...(label !== undefined ? { label } : {}),
45
+ })) } : {}),
46
+ };
47
+ }
48
+
15
49
  export function toWooCustomer(raw: WooCustomerRow): Customer {
16
50
  const customer: Customer = { id: String(raw.id), name: String(raw.id) };
17
51
  for (const [key, value] of [
@@ -35,7 +69,7 @@ function newWooId(): string {
35
69
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
36
70
  }
37
71
 
38
- async function customerRequest(context: SyncContext, route: string, init: RequestInit = {}) {
72
+ export async function customerRequest(context: SyncContext, route: string, init: RequestInit = {}) {
39
73
  let response: Response;
40
74
  try {
41
75
  response = await fetch(`${context.baseUrl}/${route}`, {
@@ -48,9 +82,9 @@ async function customerRequest(context: SyncContext, route: string, init: Reques
48
82
  const body = await response.json().catch(() => undefined);
49
83
  if (!response.ok) {
50
84
  const invalid = [400, 404, 422].includes(response.status);
51
- throw new CustomerServiceError(invalid ? 'invalid' : 'server', invalid ? body?.message ?? `HTTP ${response.status}` : `HTTP ${response.status}`);
85
+ throw new CustomerServiceError(invalid ? 'invalid' : 'server', invalid ? body?.message ?? `HTTP ${response.status}` : `HTTP ${response.status}`, { status: response.status });
52
86
  }
53
- return { status: response.status, body };
87
+ return { status: response.status, body, headers: response.headers };
54
88
  }
55
89
 
56
90
  export function createWooCustomers(options?: { newId?: () => string }) {
@@ -95,6 +129,31 @@ export function createWooCustomers(options?: { newId?: () => string }) {
95
129
  return toWooCustomer(body.document);
96
130
  },
97
131
 
132
+ // WCPOS's own write surface, as WCPOS v2's customer edit uses it: an `update` push of the changed Woo REST fields,
133
+ // keyed by the record's uuid and current revision, which only the customer read carries.
134
+ async updateCustomer(context: SyncContext, id: string, patch: CustomerPatch): Promise<Customer> {
135
+ if (!/^\d+$/.test(id)) throw new CustomerServiceError('invalid', 'Unknown customer');
136
+ if (patch.shipping?.email) throw new CustomerServiceError('invalid', 'WooCommerce shipping addresses have no email');
137
+ const params = new URLSearchParams({ include: id, per_page: '1', role: 'all' });
138
+ const { body: rows } = await customerRequest(context, `customers?${params}`, { method: 'GET' });
139
+ if (!Array.isArray(rows)) throw new CustomerServiceError('server', 'unexpected response');
140
+ const row: WooCustomerRow | undefined = rows.find((raw: WooCustomerRow) => String(raw.id) === id);
141
+ if (!row) throw new CustomerServiceError('invalid', 'Unknown customer');
142
+ const uuid = row.meta_data?.find((entry) => entry.key === '_woocommerce_pos_uuid')?.value;
143
+ if (typeof uuid !== 'string' || !uuid) throw new CustomerServiceError('server', 'unexpected response');
144
+ const payload = toWooPatch(patch);
145
+ if (Object.keys(payload).length === 0) return toWooCustomer(row);
146
+ const { status, body } = await customerRequest(context, 'push/customers', {
147
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
148
+ body: JSON.stringify({
149
+ mutationId: newId(), operation: 'update', collection: 'customers', recordId: uuid,
150
+ baseRevision: typeof row._rxdb_revision === 'string' ? row._rxdb_revision : null, payload,
151
+ }),
152
+ });
153
+ if (status !== 200 || !body?.document) throw new CustomerServiceError('server', 'unexpected response');
154
+ return toWooCustomer(body.document);
155
+ },
156
+
98
157
  async emailReceipt(context: SyncContext, orderId: string, email: string, options?: { saveToBilling?: boolean }): Promise<void> {
99
158
  if (!/^[1-9]\d*$/.test(orderId)) throw new CustomerServiceError('invalid', 'Invalid order ID');
100
159
  const { status, body } = await customerRequest(context, `orders/${encodeURIComponent(orderId)}/email`, {
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
+ }
@@ -62,11 +62,12 @@ const toEntries = (rows: any[]) => rows.filter((row) => Number.isInteger(row?.id
62
62
  * fast-path request where the store offers it (#313), else page by page, with no date filter, and hands differences
63
63
  * to `feed`, which reaches the collection only through the pull. `confirmGone` is the deletion proof: a by-id re-read.
64
64
  */
65
- export function wooCatalogueReconcile(feed: Pick<ReconcileFeed<any>, 'enqueue'>): CatalogueReconcileAdapter<any, number> {
65
+ export function wooCatalogueReconcile(feed: Pick<ReconcileFeed<any>, 'enqueue'>): CatalogueReconcileAdapter<any, number | undefined> {
66
66
  return {
67
- async *fetchPages(context, from = 1) {
67
+ async *fetchPages(context, from) {
68
68
  // One status read per pass, yielded as an empty page so that it takes its own budget slot.
69
69
  const fast = await wooHasIdFastPath(context);
70
+ // A fresh pass carries no cursor, so a failure before the first listing page restarts it uninterrupted (#376).
70
71
  yield { entries: [], cursor: from };
71
72
  if (fast) {
72
73
  // The whole catalogue in one request, so `from` is moot. A store that refuses it (a store scope answers 400)
@@ -91,7 +92,7 @@ export function wooCatalogueReconcile(feed: Pick<ReconcileFeed<any>, 'enqueue'>)
91
92
  }
92
93
  // status=publish: a product that is not published is absent, so it becomes a deletion candidate and
93
94
  // confirmGone decides; drafts cost no daily refetch.
94
- for (let page = from; ; page++) {
95
+ for (let page = from ?? 1; ; page++) {
95
96
  const params = new URLSearchParams({
96
97
  per_page: String(PAGE_SIZE), page: String(page), orderby: 'id', order: 'asc', status: 'publish', _fields: LISTING_FIELDS,
97
98
  });