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