@tallyui/connector-woocommerce 3.9.2 → 3.11.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
@@ -2,7 +2,7 @@ import { SyncContext, ServerCapabilities, StoreSettings, Customer, CustomerInput
2
2
  export { ConnectorUnauthorizedError } from '@tallyui/core';
3
3
  import { RxJsonSchema } from 'rxdb';
4
4
 
5
- /** The highest order.create version the WooCommerce transport maps: v4's net discounts, and v5's fees, shipping and custom lines (WCPOS push/orders; orders #146, #161). */
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
7
  declare function wooStoreSettings(context: SyncContext): Promise<StoreSettings>;
8
8
  declare function readWooCapabilities(context: SyncContext): Promise<ServerCapabilities | undefined>;
@@ -56,11 +56,15 @@ interface WooCommandTransportOptions {
56
56
  /** True when the store's `/status` lists `order_payments_list` (`ServerCapabilities.multiplePayments`): an order may
57
57
  * then carry several payments, recorded in `_woocommerce_pos_payments`. */
58
58
  acceptsPaymentsList?: boolean | (() => boolean | Promise<boolean>);
59
+ /** True when the store passes the coupons gate (`ServerCapabilities.coupons`, ADR-077 R2/R3). Read at push time;
60
+ * absent means closed, so a sale still carrying coupons is refused with `coupon_invalid` and no request is made. */
61
+ acceptsCoupons?: boolean | (() => boolean | Promise<boolean>);
59
62
  }
60
63
  interface WooLocalOrder {
61
64
  lines: ReadonlyArray<{
62
65
  id: string;
63
- netMicros?: string;
66
+ netMicros?: string; /** The line's discount in its own tax mode (gross when inclusive), as stored. */
67
+ discountMinor?: number;
64
68
  }>;
65
69
  fees?: ReadonlyArray<{
66
70
  id: string;
package/dist/index.js CHANGED
@@ -929,6 +929,7 @@ function createWooCustomers(options) {
929
929
  // src/store-settings.ts
930
930
  import { ConnectorUnauthorizedError as ConnectorUnauthorizedError2, StoreSettingsError, minorUnitDigits, woocommerceTax } from "@tallyui/core";
931
931
  var WOO_ORDER_CREATE_VERSION = 5;
932
+ var WOO_COUPON_ORDER_CREATE_VERSION = 6;
932
933
  var WOO_BASE_ORDER_CREATE_VERSION = 3;
933
934
  var WOO_COUPONS_MIN_PLUGIN = [1, 9, 0];
934
935
  function wooPluginSupportsCoupons(version2) {
@@ -1067,7 +1068,7 @@ async function readWooCapabilities(context) {
1067
1068
  } catch {
1068
1069
  coupons = false;
1069
1070
  }
1070
- const orderCreate = capabilities.includes("order_create_v5") ? WOO_ORDER_CREATE_VERSION : WOO_BASE_ORDER_CREATE_VERSION;
1071
+ const orderCreate = capabilities.includes("order_create_v5") ? coupons ? WOO_COUPON_ORDER_CREATE_VERSION : WOO_ORDER_CREATE_VERSION : WOO_BASE_ORDER_CREATE_VERSION;
1071
1072
  return {
1072
1073
  orderCreate,
1073
1074
  taxRounding: { granularity: "woocommerce", roundAtSubtotal: stores[0].tax_round_at_subtotal === "yes" },
@@ -1083,7 +1084,7 @@ async function readWooCapabilities(context) {
1083
1084
  }
1084
1085
 
1085
1086
  // package.json
1086
- var version = "3.9.2";
1087
+ var version = "3.11.0";
1087
1088
 
1088
1089
  // src/commands/transport.ts
1089
1090
  import { minorUnitDigits as minorUnitDigits2, moneyFromDecimalString, moneyFromMajor as moneyFromMajor2 } from "@tallyui/core";
@@ -1097,6 +1098,20 @@ function wooMinorFromDecimal(text, currency) {
1097
1098
  if (end > digits) return moneyFromMajor2(trimmed, currency)?.amount;
1098
1099
  return moneyFromDecimalString(end ? `${whole}.${fraction.slice(0, end)}` : whole, currency)?.amount;
1099
1100
  }
1101
+ function stripTags(text) {
1102
+ let previous;
1103
+ do {
1104
+ previous = text;
1105
+ text = text.replace(/<[^>]*>/g, "");
1106
+ } while (text !== previous);
1107
+ return text;
1108
+ }
1109
+ function decodeCouponMessage(message) {
1110
+ const entities = { quot: '"', amp: "&", lt: "<", gt: ">", apos: "'" };
1111
+ 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))(
1112
+ parseInt(entity.slice(entity[1].toLowerCase() === "x" ? 2 : 1), entity[1].toLowerCase() === "x" ? 16 : 10)
1113
+ )).replace(/[<>]/g, "").replace(/\s+/g, " ").trim() || "status_400";
1114
+ }
1100
1115
  function toWooOrderPayload(envelope, local, options) {
1101
1116
  const p = envelope.payload;
1102
1117
  if (p.payments.length === 0 || p.payments.length > 1 && !options?.paymentsList) {
@@ -1139,7 +1154,15 @@ function toWooOrderPayload(envelope, local, options) {
1139
1154
  subtotal = total = net;
1140
1155
  }
1141
1156
  const custom = line.custom;
1142
- const price = major(line.unitPriceMinor);
1157
+ let price = major(line.unitPriceMinor);
1158
+ if (p.coupons?.length) {
1159
+ const discount = (line.taxInclusive ?? p.pricesIncludeTax) && (line.discountMinor ?? 0) > 0 ? local?.lines.find((stored) => stored.id === line.clientLineId)?.discountMinor : line.discountMinor ?? 0;
1160
+ 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")}`;
1164
+ }
1165
+ const regular_price = p.coupons?.length && line.regularUnitPriceMinor !== void 0 ? major(line.regularUnitPriceMinor) : price;
1143
1166
  line_items.push(custom ? {
1144
1167
  product_id: 0,
1145
1168
  name: custom.name,
@@ -1150,9 +1173,15 @@ function toWooOrderPayload(envelope, local, options) {
1150
1173
  tax_class: custom.taxClass ?? "",
1151
1174
  meta_data: [{
1152
1175
  key: "_woocommerce_pos_data",
1153
- value: JSON.stringify({ price, regular_price: price, tax_status: custom.taxStatus })
1176
+ value: JSON.stringify({ price, regular_price, tax_status: custom.taxStatus })
1154
1177
  }]
1155
- } : { product_id: Number(line.variantId), quantity: line.quantity, subtotal, total });
1178
+ } : {
1179
+ product_id: Number(line.variantId),
1180
+ quantity: line.quantity,
1181
+ subtotal,
1182
+ total,
1183
+ ...p.coupons?.length ? { meta_data: [{ key: "_woocommerce_pos_data", value: JSON.stringify({ price, regular_price }) }] } : {}
1184
+ });
1156
1185
  }
1157
1186
  const fee_lines = [], shipping_lines = [];
1158
1187
  for (const fee of p.fees ?? []) {
@@ -1187,6 +1216,7 @@ function toWooOrderPayload(envelope, local, options) {
1187
1216
  line_items,
1188
1217
  ...fee_lines.length ? { fee_lines } : {},
1189
1218
  ...shipping_lines.length ? { shipping_lines } : {},
1219
+ ...p.coupons?.length ? { coupon_lines: p.coupons.map(({ code }) => ({ code })) } : {},
1190
1220
  meta_data,
1191
1221
  ...p.customer?.customerId && /^\d+$/.test(p.customer.customerId) ? { customer_id: Number(p.customer.customerId) } : {},
1192
1222
  ...p.customer?.email ? { billing: { email: p.customer.email } } : {}
@@ -1199,8 +1229,17 @@ function createWooCommandTransport(options) {
1199
1229
  return {
1200
1230
  async send(batch, context) {
1201
1231
  const paymentsList = typeof options.acceptsPaymentsList === "function" ? await options.acceptsPaymentsList() : options.acceptsPaymentsList ?? false;
1232
+ const coupons = batch.some((envelope) => envelope.payload.coupons?.length) && (typeof options.acceptsCoupons === "function" ? await options.acceptsCoupons() : options.acceptsCoupons ?? false);
1202
1233
  const results = [];
1203
1234
  for (const envelope of batch) {
1235
+ if (envelope.payload.coupons?.length && !coupons) {
1236
+ results.push({ id: envelope.id, status: "rejected", error: {
1237
+ code: "coupon_invalid",
1238
+ message: "This store's WooCommerce POS plugin does not accept coupons (1.9.0 or later is needed). Remove the coupon and complete the sale again.",
1239
+ data: { storeCode: "coupons_unsupported" }
1240
+ } });
1241
+ continue;
1242
+ }
1204
1243
  const mapped = toWooOrderPayload(envelope, context?.local?.orders?.get(envelope.id), { paymentsList });
1205
1244
  if ("error" in mapped) {
1206
1245
  results.push({ id: envelope.id, status: "rejected", error: mapped.error });
@@ -1256,6 +1295,15 @@ function createWooCommandTransport(options) {
1256
1295
  }] } : {} });
1257
1296
  continue;
1258
1297
  }
1298
+ } else if (status === 400 && body?.code === "woocommerce_rest_invalid_coupon") {
1299
+ const message = decodeCouponMessage(body?.message), quoted = /"([^"]*)"/.exec(message)?.[1];
1300
+ const couponCode = envelope.payload.coupons?.find(({ code }) => code.toLowerCase() === quoted?.toLowerCase())?.code;
1301
+ results.push({ id: envelope.id, status: "rejected", error: {
1302
+ code: "coupon_invalid",
1303
+ message,
1304
+ data: { storeCode: body.code, ...couponCode ? { couponCode } : {} }
1305
+ } });
1306
+ continue;
1259
1307
  } else if (status === 400 || status === 422) {
1260
1308
  results.push({ id: envelope.id, status: "rejected", error: {
1261
1309
  code: status === 400 && body?.code === "wcpos_insufficient_stock" ? "insufficient_stock" : "invalid_payload",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/connector-woocommerce",
3
- "version": "3.9.2",
3
+ "version": "3.11.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.9.2"
30
+ "@tallyui/core": "^3.11.0"
31
31
  },
32
32
  "devDependencies": {
33
- "@tallyui/database": "3.9.2",
33
+ "@tallyui/database": "3.11.0",
34
34
  "rxdb": "17.5.0"
35
35
  },
36
36
  "scripts": {
@@ -15,6 +15,9 @@ export interface WooCommandTransportOptions {
15
15
  /** True when the store's `/status` lists `order_payments_list` (`ServerCapabilities.multiplePayments`): an order may
16
16
  * then carry several payments, recorded in `_woocommerce_pos_payments`. */
17
17
  acceptsPaymentsList?: boolean | (() => boolean | Promise<boolean>);
18
+ /** True when the store passes the coupons gate (`ServerCapabilities.coupons`, ADR-077 R2/R3). Read at push time;
19
+ * absent means closed, so a sale still carrying coupons is refused with `coupon_invalid` and no request is made. */
20
+ acceptsCoupons?: boolean | (() => boolean | Promise<boolean>);
18
21
  }
19
22
 
20
23
  export function wooMinorFromDecimal(text: string, currency: string): number | undefined {
@@ -29,11 +32,31 @@ export function wooMinorFromDecimal(text: string, currency: string): number | un
29
32
  }
30
33
 
31
34
  export interface WooLocalOrder {
32
- lines: ReadonlyArray<{ id: string; netMicros?: string }>;
35
+ lines: ReadonlyArray<{ id: string; netMicros?: string; /** The line's discount in its own tax mode (gross when inclusive), as stored. */ discountMinor?: number }>;
33
36
  fees?: ReadonlyArray<{ id: string; netMicros?: string }>;
34
37
  shipping?: ReadonlyArray<{ id: string; netMicros?: string }>;
35
38
  }
36
39
 
40
+ // Repeated until stable so no removal can join a new tag (CodeQL js/incomplete-multi-character-sanitization).
41
+ function stripTags(text: string): string {
42
+ let previous;
43
+ do {
44
+ previous = text;
45
+ text = text.replace(/<[^>]*>/g, '');
46
+ } while (text !== previous);
47
+ return text;
48
+ }
49
+
50
+ function decodeCouponMessage(message: unknown): string {
51
+ const entities: Record<string, string> = { quot: '"', amp: '&', lt: '<', gt: '>', apos: "'" };
52
+ return stripTags(typeof message === 'string' ? message : '')
53
+ .replace(/&(quot|amp|lt|gt|apos|#\d+|#x[\da-f]+);/gi, (_, entity: string) => entities[entity.toLowerCase()]
54
+ ?? ((value: number) => value > 0x10FFFF ? _ : String.fromCodePoint(value))(
55
+ parseInt(entity.slice(entity[1].toLowerCase() === 'x' ? 2 : 1), entity[1].toLowerCase() === 'x' ? 16 : 10)))
56
+ .replace(/[<>]/g, '')
57
+ .replace(/\s+/g, ' ').trim() || 'status_400';
58
+ }
59
+
37
60
  export function toWooOrderPayload(envelope: OrderCreateEnvelope, local?: WooLocalOrder, options?: { paymentsList?: boolean }): { payload: Record<string, unknown> } | { error: { code: string; message: string } } {
38
61
  const p = envelope.payload;
39
62
  if (p.payments.length === 0 || (p.payments.length > 1 && !options?.paymentsList)) {
@@ -76,12 +99,23 @@ export function toWooOrderPayload(envelope: OrderCreateEnvelope, local?: WooLoca
76
99
  subtotal = total = net;
77
100
  }
78
101
  const custom = line.custom;
79
- const price = major(line.unitPriceMinor);
102
+ let price = major(line.unitPriceMinor);
103
+ if (p.coupons?.length) {
104
+ const discount = (line.taxInclusive ?? p.pricesIncludeTax) && (line.discountMinor ?? 0) > 0
105
+ ? local?.lines.find((stored) => stored.id === line.clientLineId)?.discountMinor : line.discountMinor ?? 0;
106
+ if (discount === undefined) return { error: { code: 'unsupported_tax_mode', message: "Tax-inclusive prices need the till's WooCommerce tax figures; update the till." } };
107
+ const quantity = BigInt(line.quantity), minor = BigInt(line.unitPriceMinor) * quantity - BigInt(discount);
108
+ const divisor = quantity * 10n ** BigInt(digits), micros = (minor * 1000000n * 2n + divisor) / (divisor * 2n);
109
+ price = minor % quantity === 0n ? major(Number(minor / quantity))
110
+ : `${micros / 1000000n}.${(micros % 1000000n).toString().padStart(6, '0')}`;
111
+ }
112
+ const regular_price = p.coupons?.length && line.regularUnitPriceMinor !== undefined ? major(line.regularUnitPriceMinor) : price;
80
113
  line_items.push(custom ? {
81
114
  product_id: 0, name: custom.name, ...(custom.sku ? { sku: custom.sku } : {}), quantity: line.quantity, subtotal, total,
82
115
  tax_class: custom.taxClass ?? '', meta_data: [{ key: '_woocommerce_pos_data',
83
- value: JSON.stringify({ price, regular_price: price, tax_status: custom.taxStatus }) }],
84
- } : { product_id: Number(line.variantId), quantity: line.quantity, subtotal, total });
116
+ value: JSON.stringify({ price, regular_price, tax_status: custom.taxStatus }) }],
117
+ } : { 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 }) }] } : {}) });
85
119
  }
86
120
  const fee_lines = [], shipping_lines = [];
87
121
  for (const fee of p.fees ?? []) {
@@ -114,6 +148,7 @@ export function toWooOrderPayload(envelope: OrderCreateEnvelope, local?: WooLoca
114
148
  line_items,
115
149
  ...(fee_lines.length ? { fee_lines } : {}),
116
150
  ...(shipping_lines.length ? { shipping_lines } : {}),
151
+ ...(p.coupons?.length ? { coupon_lines: p.coupons.map(({ code }) => ({ code })) } : {}),
117
152
  meta_data,
118
153
  ...(p.customer?.customerId && /^\d+$/.test(p.customer.customerId) ? { customer_id: Number(p.customer.customerId) } : {}),
119
154
  ...(p.customer?.email ? { billing: { email: p.customer.email } } : {}),
@@ -130,8 +165,16 @@ export function createWooCommandTransport(options: WooCommandTransportOptions):
130
165
  async send(batch, context) {
131
166
  const paymentsList = typeof options.acceptsPaymentsList === 'function'
132
167
  ? await options.acceptsPaymentsList() : options.acceptsPaymentsList ?? false;
168
+ const coupons = batch.some((envelope) => envelope.payload.coupons?.length) && (typeof options.acceptsCoupons === 'function'
169
+ ? await options.acceptsCoupons() : options.acceptsCoupons ?? false);
133
170
  const results: CommandResult[] = [];
134
171
  for (const envelope of batch) {
172
+ if (envelope.payload.coupons?.length && !coupons) {
173
+ results.push({ id: envelope.id, status: 'rejected', error: { code: 'coupon_invalid',
174
+ message: "This store's WooCommerce POS plugin does not accept coupons (1.9.0 or later is needed). Remove the coupon and complete the sale again.",
175
+ data: { storeCode: 'coupons_unsupported' } } });
176
+ continue;
177
+ }
135
178
  const mapped = toWooOrderPayload(envelope, context?.local?.orders?.get(envelope.id), { paymentsList });
136
179
  if ('error' in mapped) {
137
180
  results.push({ id: envelope.id, status: 'rejected', error: mapped.error });
@@ -172,6 +215,12 @@ export function createWooCommandTransport(options: WooCommandTransportOptions):
172
215
  }] } : {}) });
173
216
  continue;
174
217
  }
218
+ } else if (status === 400 && body?.code === 'woocommerce_rest_invalid_coupon') {
219
+ const message = decodeCouponMessage(body?.message), quoted = /"([^"]*)"/.exec(message)?.[1];
220
+ const couponCode = envelope.payload.coupons?.find(({ code }) => code.toLowerCase() === quoted?.toLowerCase())?.code;
221
+ results.push({ id: envelope.id, status: 'rejected', error: { code: 'coupon_invalid', message,
222
+ data: { storeCode: body.code, ...(couponCode ? { couponCode } : {}) } } });
223
+ continue;
175
224
  } else if (status === 400 || status === 422) {
176
225
  results.push({ id: envelope.id, status: 'rejected', error: {
177
226
  code: status === 400 && body?.code === 'wcpos_insufficient_stock' ? 'insufficient_stock' : 'invalid_payload',
@@ -1,8 +1,10 @@
1
1
  import { ConnectorUnauthorizedError, StoreSettingsError, minorUnitDigits, woocommerceTax } from '@tallyui/core';
2
2
  import type { ServerCapabilities, StoreSettings, SyncContext } from '@tallyui/core';
3
3
 
4
- /** The highest order.create version the WooCommerce transport maps: v4's net discounts, and v5's fees, shipping and custom lines (WCPOS push/orders; orders #146, #161). */
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
8
  // The order.create version a store gets unless /status lists order_create_v5, which only the TallyUI fork of the plugin advertises.
7
9
  const WOO_BASE_ORDER_CREATE_VERSION = 3;
8
10
  // The first woocommerce-pos release whose coupon recalculation keeps the POS price (ADR-077 amendment 4, R2: 1.9.0, 2026-05-15).
@@ -145,7 +147,8 @@ export async function readWooCapabilities(context: SyncContext): Promise<ServerC
145
147
  } catch {
146
148
  coupons = false;
147
149
  }
148
- const orderCreate = capabilities.includes('order_create_v5') ? WOO_ORDER_CREATE_VERSION : WOO_BASE_ORDER_CREATE_VERSION;
150
+ const orderCreate = capabilities.includes('order_create_v5')
151
+ ? (coupons ? WOO_COUPON_ORDER_CREATE_VERSION : WOO_ORDER_CREATE_VERSION) : WOO_BASE_ORDER_CREATE_VERSION;
149
152
  return {
150
153
  orderCreate,
151
154
  taxRounding: { granularity: 'woocommerce', roundAtSubtotal: stores[0].tax_round_at_subtotal === 'yes' },