@tallyui/connector-woocommerce 3.20.1 → 4.0.1
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/README.md +7 -3
- package/dist/index.d.ts +40 -11
- package/dist/index.js +943 -156
- package/package.json +4 -5
- package/src/closures.ts +184 -0
- package/src/commands/http.ts +37 -0
- package/src/commands/register-transport.ts +212 -0
- package/src/commands/transport.ts +167 -74
- package/src/currency-symbols.ts +166 -0
- package/src/customers.ts +29 -14
- package/src/index.ts +8 -2
- package/src/orders.ts +59 -10
- package/src/payment-methods.ts +4 -3
- package/src/registers.ts +55 -0
- package/src/replication/products.ts +7 -3
- package/src/schemas/products.ts +7 -2
- package/src/store-settings.ts +71 -25
- package/src/traits/product.ts +2 -0
- package/src/unauthorized.ts +8 -0
package/dist/index.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
// src/index.ts
|
|
2
|
-
import { combinePullAdapters, ConnectorUnauthorizedError as
|
|
2
|
+
import { combinePullAdapters, ConnectorUnauthorizedError as ConnectorUnauthorizedError5 } from "@tallyui/core";
|
|
3
3
|
|
|
4
4
|
// src/schemas/products.ts
|
|
5
5
|
var wooProductSchema = {
|
|
6
6
|
title: "WooCommerce Product",
|
|
7
|
-
version:
|
|
7
|
+
version: 4,
|
|
8
|
+
// 3: backorders (A16); 4: low_stock_amount; a till resyncs its products once
|
|
8
9
|
type: "object",
|
|
9
10
|
primaryKey: "uuid",
|
|
10
11
|
properties: {
|
|
@@ -68,6 +69,9 @@ var wooProductSchema = {
|
|
|
68
69
|
stock_quantity: {
|
|
69
70
|
type: ["number", "null"]
|
|
70
71
|
},
|
|
72
|
+
low_stock_amount: {
|
|
73
|
+
type: ["number", "null"]
|
|
74
|
+
},
|
|
71
75
|
stock_status: {
|
|
72
76
|
type: "string",
|
|
73
77
|
default: "instock",
|
|
@@ -78,6 +82,7 @@ var wooProductSchema = {
|
|
|
78
82
|
type: "boolean",
|
|
79
83
|
default: false
|
|
80
84
|
},
|
|
85
|
+
backorders: { type: "string" },
|
|
81
86
|
categories: {
|
|
82
87
|
type: "array",
|
|
83
88
|
items: {
|
|
@@ -146,7 +151,9 @@ var wooProductSchema = {
|
|
|
146
151
|
on_sale: { type: "boolean" },
|
|
147
152
|
stock_status: { type: "string" },
|
|
148
153
|
stock_quantity: { type: ["number", "null"] },
|
|
154
|
+
low_stock_amount: { type: ["number", "null"] },
|
|
149
155
|
manage_stock: { type: "boolean" },
|
|
156
|
+
backorders: { type: "string" },
|
|
150
157
|
status: { type: "string" },
|
|
151
158
|
purchasable: { type: "boolean" },
|
|
152
159
|
attributes: { type: "array", items: { type: "object", properties: { name: { type: "string" }, option: { type: "string" } } } }
|
|
@@ -354,7 +361,9 @@ function toVariationDocument(payload) {
|
|
|
354
361
|
on_sale,
|
|
355
362
|
stock_status,
|
|
356
363
|
stock_quantity,
|
|
364
|
+
low_stock_amount,
|
|
357
365
|
manage_stock,
|
|
366
|
+
backorders,
|
|
358
367
|
status,
|
|
359
368
|
purchasable,
|
|
360
369
|
tax_class,
|
|
@@ -370,7 +379,9 @@ function toVariationDocument(payload) {
|
|
|
370
379
|
on_sale,
|
|
371
380
|
stock_status,
|
|
372
381
|
stock_quantity,
|
|
382
|
+
low_stock_amount,
|
|
373
383
|
manage_stock,
|
|
384
|
+
backorders,
|
|
374
385
|
status,
|
|
375
386
|
purchasable,
|
|
376
387
|
tax_class,
|
|
@@ -407,9 +418,9 @@ var WooDateFilterError = class extends Error {
|
|
|
407
418
|
minVersion = "5.8";
|
|
408
419
|
};
|
|
409
420
|
var WooTokenRefusedError = class extends Error {
|
|
410
|
-
constructor(
|
|
421
|
+
constructor(storeCode2) {
|
|
411
422
|
super("The store refused the sign-in token (403). Ask the store owner to check the JWT Authentication plugin's settings, or pair the till again.");
|
|
412
|
-
this.storeCode =
|
|
423
|
+
this.storeCode = storeCode2;
|
|
413
424
|
}
|
|
414
425
|
name = "WooTokenRefusedError";
|
|
415
426
|
code = "store_misconfigured";
|
|
@@ -483,7 +494,9 @@ var wooProductReplication = {
|
|
|
483
494
|
});
|
|
484
495
|
await checkResponse(response2);
|
|
485
496
|
const body = await response2.json();
|
|
486
|
-
|
|
497
|
+
const docs = Array.isArray(body) ? body.map((payload) => ({ parent_id: payload.parent_id, payload })) : Array.isArray(body?.documents) ? body.documents : void 0;
|
|
498
|
+
if (!docs) throw new Error(`Unexpected /variations response: ${JSON.stringify(body)?.slice(0, 100)}`);
|
|
499
|
+
for (const doc of docs) {
|
|
487
500
|
const parentId = doc.parent_id ?? doc.payload.parent_id;
|
|
488
501
|
const group = variations.get(parentId) ?? [];
|
|
489
502
|
group.push(toVariationDocument(doc.payload));
|
|
@@ -510,6 +523,7 @@ var WOO_STOCK_STATUS = {
|
|
|
510
523
|
outofstock: "out_of_stock",
|
|
511
524
|
onbackorder: "backorder"
|
|
512
525
|
};
|
|
526
|
+
var WOO_BACKORDERS = /* @__PURE__ */ new Set(["no", "notify", "yes"]);
|
|
513
527
|
var wooProductTraits = {
|
|
514
528
|
getId: (doc) => String(doc.id),
|
|
515
529
|
getName: (doc) => doc.name ?? "",
|
|
@@ -536,7 +550,8 @@ var wooProductTraits = {
|
|
|
536
550
|
},
|
|
537
551
|
getStock: (doc) => ({
|
|
538
552
|
status: WOO_STOCK_STATUS[doc.stock_status] ?? "unknown",
|
|
539
|
-
quantity: doc.manage_stock === false ? void 0 : doc.stock_quantity ?? void 0
|
|
553
|
+
quantity: doc.manage_stock === false ? void 0 : doc.stock_quantity ?? void 0,
|
|
554
|
+
...WOO_BACKORDERS.has(doc.backorders) ? { backorders: doc.backorders } : {}
|
|
540
555
|
}),
|
|
541
556
|
getPrice: (doc) => doc.price || void 0,
|
|
542
557
|
getRegularPrice: (doc) => doc.regular_price || void 0,
|
|
@@ -843,6 +858,14 @@ var WOO_ADDRESS = [
|
|
|
843
858
|
["email", "email"],
|
|
844
859
|
["phone", "phone"]
|
|
845
860
|
];
|
|
861
|
+
function fromWooAddress(raw, kind) {
|
|
862
|
+
const address = {};
|
|
863
|
+
for (const [key, field] of WOO_ADDRESS) {
|
|
864
|
+
const value = raw?.[key];
|
|
865
|
+
if ((kind === "billing" || key !== "email") && typeof value === "string" && value.length > 0) address[field] = value;
|
|
866
|
+
}
|
|
867
|
+
return Object.keys(address).length > 0 ? address : void 0;
|
|
868
|
+
}
|
|
846
869
|
function toWooAddress(address, kind) {
|
|
847
870
|
return Object.fromEntries(WOO_ADDRESS.filter(([key]) => kind === "billing" || key !== "email").map(([key, field]) => [key, address[field] ?? ""]));
|
|
848
871
|
}
|
|
@@ -877,6 +900,10 @@ function toWooCustomer(raw) {
|
|
|
877
900
|
]) {
|
|
878
901
|
if (typeof value === "string" && value.length > 0) customer[key] = value;
|
|
879
902
|
}
|
|
903
|
+
const billing = fromWooAddress(raw.billing, "billing");
|
|
904
|
+
if (billing) customer.billing = billing;
|
|
905
|
+
const shipping = fromWooAddress(raw.shipping, "shipping");
|
|
906
|
+
if (shipping) customer.shipping = shipping;
|
|
880
907
|
const created = raw.date_created_gmt;
|
|
881
908
|
if (typeof created === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/.test(created)) customer.createdAt = `${created}Z`;
|
|
882
909
|
customer.name = [customer.firstName, customer.lastName].filter(Boolean).join(" ") || customer.company || customer.email || customer.id;
|
|
@@ -911,6 +938,12 @@ async function customerRequest(context, route, init = {}) {
|
|
|
911
938
|
}
|
|
912
939
|
function createWooCustomers(options) {
|
|
913
940
|
const newId = options?.newId ?? newWooId;
|
|
941
|
+
const readCustomerRow = async (context, id) => {
|
|
942
|
+
const params = new URLSearchParams({ include: id, per_page: "1", role: "all" });
|
|
943
|
+
const { body } = await customerRequest(context, `customers?${params}`, { method: "GET" });
|
|
944
|
+
if (!Array.isArray(body)) throw new CustomerServiceError("server", "unexpected response");
|
|
945
|
+
return body.find((row) => String(row.id) === id);
|
|
946
|
+
};
|
|
914
947
|
const api = {
|
|
915
948
|
async searchCustomers(context, query, options2) {
|
|
916
949
|
return (await api.searchCustomersPage(context, query, { limit: options2?.limit })).customers;
|
|
@@ -929,10 +962,7 @@ function createWooCustomers(options) {
|
|
|
929
962
|
},
|
|
930
963
|
async getCustomer(context, id) {
|
|
931
964
|
if (!/^\d+$/.test(id)) return null;
|
|
932
|
-
const
|
|
933
|
-
const { body } = await customerRequest(context, `customers?${params}`, { method: "GET" });
|
|
934
|
-
if (!Array.isArray(body)) throw new CustomerServiceError("server", "unexpected response");
|
|
935
|
-
const raw = body.find((row) => String(row.id) === id);
|
|
965
|
+
const raw = await readCustomerRow(context, id);
|
|
936
966
|
return raw ? toWooCustomer(raw) : null;
|
|
937
967
|
},
|
|
938
968
|
async createCustomer(context, input) {
|
|
@@ -967,12 +997,9 @@ function createWooCustomers(options) {
|
|
|
967
997
|
async updateCustomer(context, id, patch) {
|
|
968
998
|
if (!/^\d+$/.test(id)) throw new CustomerServiceError("invalid", "Unknown customer");
|
|
969
999
|
if (patch.shipping?.email) throw new CustomerServiceError("invalid", "WooCommerce shipping addresses have no email");
|
|
970
|
-
const
|
|
971
|
-
const { body: rows2 } = await customerRequest(context, `customers?${params}`, { method: "GET" });
|
|
972
|
-
if (!Array.isArray(rows2)) throw new CustomerServiceError("server", "unexpected response");
|
|
973
|
-
const row = rows2.find((raw) => String(raw.id) === id);
|
|
1000
|
+
const row = await readCustomerRow(context, id);
|
|
974
1001
|
if (!row) throw new CustomerServiceError("invalid", "Unknown customer");
|
|
975
|
-
const uuid = row.meta_data?.find((entry) => entry.key ===
|
|
1002
|
+
const uuid = row.meta_data?.find((entry) => entry.key === WCPOS_UUID_META_KEY)?.value;
|
|
976
1003
|
if (typeof uuid !== "string" || !uuid) throw new CustomerServiceError("server", "unexpected response");
|
|
977
1004
|
const payload = toWooPatch(patch);
|
|
978
1005
|
if (Object.keys(payload).length === 0) return toWooCustomer(row);
|
|
@@ -1013,6 +1040,46 @@ import {
|
|
|
1013
1040
|
|
|
1014
1041
|
// src/commands/transport.ts
|
|
1015
1042
|
import { minorUnitDigits, moneyFromDecimalString, moneyFromMajor as moneyFromMajor2, woocommerceTax } from "@tallyui/core";
|
|
1043
|
+
|
|
1044
|
+
// src/commands/http.ts
|
|
1045
|
+
function createWooCall(options) {
|
|
1046
|
+
const fetch = options.fetch ?? globalThis.fetch;
|
|
1047
|
+
let baseUrl = options.baseUrl;
|
|
1048
|
+
while (baseUrl.endsWith("/")) baseUrl = baseUrl.slice(0, -1);
|
|
1049
|
+
const call = async (path, init) => {
|
|
1050
|
+
const controller = new AbortController();
|
|
1051
|
+
const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? 3e4);
|
|
1052
|
+
try {
|
|
1053
|
+
const response = await fetch(`${baseUrl}/${path}`, {
|
|
1054
|
+
method: init.method,
|
|
1055
|
+
headers: { ...init.body === void 0 ? {} : { "Content-Type": "application/json" }, ...await options.getHeaders() },
|
|
1056
|
+
...init.body === void 0 ? {} : { body: JSON.stringify(init.body) },
|
|
1057
|
+
signal: controller.signal
|
|
1058
|
+
});
|
|
1059
|
+
let body;
|
|
1060
|
+
try {
|
|
1061
|
+
body = await response.json();
|
|
1062
|
+
} catch {
|
|
1063
|
+
}
|
|
1064
|
+
return { status: response.status, body, retryAfter: response.headers.get("Retry-After"), aborted: controller.signal.aborted };
|
|
1065
|
+
} catch {
|
|
1066
|
+
return { status: 0, aborted: controller.signal.aborted };
|
|
1067
|
+
} finally {
|
|
1068
|
+
clearTimeout(timeout);
|
|
1069
|
+
}
|
|
1070
|
+
};
|
|
1071
|
+
const retry = (answer, reason) => {
|
|
1072
|
+
if (answer.status === 0) return { kind: "retry", reason: answer.aborted ? "timeout" : "network" };
|
|
1073
|
+
const seconds = answer.retryAfter == null ? NaN : Number(answer.retryAfter);
|
|
1074
|
+
return { kind: "retry", reason, ...Number.isFinite(seconds) && seconds >= 0 ? { retryAfterMs: seconds * 1e3 } : {} };
|
|
1075
|
+
};
|
|
1076
|
+
return { call, retry };
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
// src/commands/transport.ts
|
|
1080
|
+
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
1081
|
+
var wooDigits = (p) => p.display?.exponent ?? minorUnitDigits(p.currency);
|
|
1082
|
+
var wooMajor = (minor2, digits) => (minor2 / 10 ** digits).toFixed(digits);
|
|
1016
1083
|
function wooMinorFromDecimal(text, currency) {
|
|
1017
1084
|
const trimmed = text.trim();
|
|
1018
1085
|
if (!/^\d+(\.\d+)?$/.test(trimmed)) return void 0;
|
|
@@ -1074,6 +1141,15 @@ function toWooOrderPayload(envelope, local, options) {
|
|
|
1074
1141
|
if (p.payments.length === 0 || p.payments.length > 1 && !options?.paymentsList) {
|
|
1075
1142
|
return { error: { code: "invalid_payload", message: "WooCommerce orders take one payment." } };
|
|
1076
1143
|
}
|
|
1144
|
+
const ledger = options?.ledger === true;
|
|
1145
|
+
const closes = p.totalMinor === 0 && !p.payments.some((payment) => payment.amountMinor > 0);
|
|
1146
|
+
if (ledger && p.payments.some((payment) => !UUID.test(payment.clientPaymentId))) {
|
|
1147
|
+
return { error: { code: "invalid_payload", message: "WooCommerce POS 2.0 records each payment by a UUID; this sale has a payment without one." } };
|
|
1148
|
+
}
|
|
1149
|
+
if (ledger && closes && !UUID.test(envelope.id)) return { error: { code: "invalid_payload", message: "WooCommerce POS 2.0 closes a free sale by a UUID command id; this sale's id is not one." } };
|
|
1150
|
+
if (ledger && !closes && p.payments.some((payment) => payment.amountMinor <= 0)) {
|
|
1151
|
+
return { error: { code: "invalid_payload", message: "Every payment on a WooCommerce POS 2.0 sale must be more than zero." } };
|
|
1152
|
+
}
|
|
1077
1153
|
if (p.payments.length > 20) {
|
|
1078
1154
|
return { error: { code: "invalid_payload", message: "WooCommerce records at most 20 payments." } };
|
|
1079
1155
|
}
|
|
@@ -1085,8 +1161,8 @@ function toWooOrderPayload(envelope, local, options) {
|
|
|
1085
1161
|
return { error: { code: "invalid_payload", message: `Line ${line.clientLineId} has no WooCommerce product id.` } };
|
|
1086
1162
|
}
|
|
1087
1163
|
}
|
|
1088
|
-
const digits =
|
|
1089
|
-
const major = (minor2) => (minor2
|
|
1164
|
+
const digits = wooDigits(p);
|
|
1165
|
+
const major = (minor2) => wooMajor(minor2, digits);
|
|
1090
1166
|
const inclusiveNet = (netMicros, id) => {
|
|
1091
1167
|
if (netMicros === void 0) {
|
|
1092
1168
|
return { error: { code: "unsupported_tax_mode", message: "Tax-inclusive prices need the till's WooCommerce tax figures; update the till." } };
|
|
@@ -1101,23 +1177,26 @@ function toWooOrderPayload(envelope, local, options) {
|
|
|
1101
1177
|
const micros = net / divisor;
|
|
1102
1178
|
return `${micros / 1000000n}.${(micros % 1000000n).toString().padStart(6, "0")}`;
|
|
1103
1179
|
};
|
|
1180
|
+
const chargeTotal = (amountMinor, netMicros, id) => p.pricesIncludeTax || netMicros !== void 0 && BigInt(netMicros) !== BigInt(amountMinor) * 1000000n ? inclusiveNet(netMicros, id) : major(amountMinor);
|
|
1104
1181
|
const line_items = [];
|
|
1105
1182
|
for (const line of p.lines) {
|
|
1183
|
+
const inclusive = line.taxInclusive ?? p.pricesIncludeTax;
|
|
1184
|
+
const stored = local?.lines.find((entry) => entry.id === line.clientLineId);
|
|
1106
1185
|
let total = major(line.unitPriceMinor * line.quantity - (line.discountMinor ?? 0));
|
|
1107
1186
|
let subtotal = total;
|
|
1108
|
-
if (
|
|
1109
|
-
const net = inclusiveNet(
|
|
1187
|
+
if (inclusive) {
|
|
1188
|
+
const net = inclusiveNet(stored?.netMicros, line.clientLineId);
|
|
1110
1189
|
if (typeof net !== "string") return net;
|
|
1111
1190
|
subtotal = total = net;
|
|
1112
1191
|
}
|
|
1113
1192
|
const custom = line.custom;
|
|
1114
1193
|
let price = major(line.unitPriceMinor);
|
|
1115
1194
|
if (p.coupons?.length) {
|
|
1116
|
-
const discount =
|
|
1195
|
+
const discount = inclusive && (line.discountMinor ?? 0) > 0 ? stored?.discountMinor : line.discountMinor ?? 0;
|
|
1117
1196
|
if (discount === void 0) return { error: { code: "unsupported_tax_mode", message: "Tax-inclusive prices need the till's WooCommerce tax figures; update the till." } };
|
|
1118
1197
|
const quantity = BigInt(line.quantity), minor2 = BigInt(line.unitPriceMinor) * quantity - BigInt(discount);
|
|
1119
|
-
if (
|
|
1120
|
-
const net = inclusiveNet(preCouponNetMicros(minor2, digits,
|
|
1198
|
+
if (inclusive) {
|
|
1199
|
+
const net = inclusiveNet(preCouponNetMicros(minor2, digits, stored), line.clientLineId);
|
|
1121
1200
|
if (typeof net !== "string") return net;
|
|
1122
1201
|
subtotal = total = net;
|
|
1123
1202
|
}
|
|
@@ -1153,19 +1232,28 @@ function toWooOrderPayload(envelope, local, options) {
|
|
|
1153
1232
|
}
|
|
1154
1233
|
const fee_lines = [], shipping_lines = [];
|
|
1155
1234
|
for (const fee of p.fees ?? []) {
|
|
1156
|
-
const total =
|
|
1235
|
+
const total = chargeTotal(fee.amountMinor, local?.fees?.find((stored) => stored.id === fee.clientFeeId)?.netMicros, fee.clientFeeId);
|
|
1157
1236
|
if (typeof total !== "string") return total;
|
|
1158
1237
|
fee_lines.push({ name: fee.name, total, tax_status: fee.taxStatus, tax_class: fee.taxClass ?? "" });
|
|
1159
1238
|
}
|
|
1160
1239
|
for (const shipping2 of p.shipping ?? []) {
|
|
1161
|
-
const total =
|
|
1240
|
+
const total = chargeTotal(
|
|
1241
|
+
shipping2.amountMinor,
|
|
1242
|
+
local?.shipping?.find((stored) => stored.id === shipping2.clientShippingId)?.netMicros,
|
|
1243
|
+
shipping2.clientShippingId
|
|
1244
|
+
);
|
|
1162
1245
|
if (typeof total !== "string") return total;
|
|
1163
|
-
shipping_lines.push({
|
|
1246
|
+
shipping_lines.push({
|
|
1247
|
+
method_id: shipping2.methodId ?? "pos",
|
|
1248
|
+
method_title: shipping2.name,
|
|
1249
|
+
total,
|
|
1250
|
+
...shipping2.taxStatus === "none" ? { meta_data: [{ key: "_woocommerce_pos_data", value: JSON.stringify({ tax_status: "none" }) }] } : {}
|
|
1251
|
+
});
|
|
1164
1252
|
}
|
|
1165
1253
|
const primary = p.payments.reduce((largest, payment) => payment.amountMinor > largest.amountMinor ? payment : largest);
|
|
1166
1254
|
const cash = primary.method === "cash";
|
|
1167
|
-
const meta_data = [{ key:
|
|
1168
|
-
if (p.payments.length > 1) {
|
|
1255
|
+
const meta_data = [{ key: WCPOS_UUID_META_KEY, value: p.clientOrderId }];
|
|
1256
|
+
if (p.payments.length > 1 && !ledger) {
|
|
1169
1257
|
meta_data.push({ key: "_woocommerce_pos_payments", value: JSON.stringify(p.payments.map((payment) => ({
|
|
1170
1258
|
method: payment.method === "cash" ? "pos_cash" : "pos_card",
|
|
1171
1259
|
title: payment.method === "cash" ? "Cash" : "Card",
|
|
@@ -1178,12 +1266,21 @@ function toWooOrderPayload(envelope, local, options) {
|
|
|
1178
1266
|
if (p.taxAddress) meta_data.push({ key: "_woocommerce_pos_tax_based_on", value: p.taxAddress });
|
|
1179
1267
|
const billing = { ...p.customer?.email ? { email: p.customer.email } : {}, ...p.taxAddress ? wooAddress(p.customer?.billing) : {} };
|
|
1180
1268
|
const shipping = p.taxAddress && p.customer?.shipping ? wooAddress(p.customer.shipping) : void 0;
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1269
|
+
const money = !ledger ? void 0 : closes ? [{ path: "close", body: { command_id: `${envelope.id.slice(0, 14)}8${envelope.id.slice(15)}` } }] : p.payments.map((payment) => ({ path: "payments", body: { payment: {
|
|
1270
|
+
id: payment.clientPaymentId,
|
|
1271
|
+
method_id: payment.method === "cash" ? "pos_cash" : "pos_card",
|
|
1272
|
+
amount: major(payment.amountMinor),
|
|
1184
1273
|
currency: p.currency,
|
|
1185
|
-
|
|
1186
|
-
|
|
1274
|
+
...payment.method === "cash" && payment.tenderedMinor !== void 0 ? { tendered: major(payment.tenderedMinor) } : {}
|
|
1275
|
+
} } }));
|
|
1276
|
+
return { ...money ? { money } : {}, payload: {
|
|
1277
|
+
...ledger ? { status: "pending", currency: p.currency } : {
|
|
1278
|
+
status: "completed",
|
|
1279
|
+
set_paid: true,
|
|
1280
|
+
currency: p.currency,
|
|
1281
|
+
payment_method: cash ? "pos_cash" : "pos_card",
|
|
1282
|
+
payment_method_title: cash ? "Cash" : "Card"
|
|
1283
|
+
},
|
|
1187
1284
|
line_items,
|
|
1188
1285
|
...fee_lines.length ? { fee_lines } : {},
|
|
1189
1286
|
...shipping_lines.length ? { shipping_lines } : {},
|
|
@@ -1196,14 +1293,28 @@ function toWooOrderPayload(envelope, local, options) {
|
|
|
1196
1293
|
...typeof p.note === "string" && p.note.length > 0 ? { customer_note: p.note } : {}
|
|
1197
1294
|
} };
|
|
1198
1295
|
}
|
|
1296
|
+
function capability(flag) {
|
|
1297
|
+
return typeof flag === "function" ? flag() : flag ?? false;
|
|
1298
|
+
}
|
|
1199
1299
|
function createWooCommandTransport(options) {
|
|
1200
|
-
const
|
|
1201
|
-
let
|
|
1202
|
-
|
|
1300
|
+
const { call, retry } = createWooCall(options);
|
|
1301
|
+
let siteLedger;
|
|
1302
|
+
const ledgerStore = async () => {
|
|
1303
|
+
if (options.ledgerPayments !== void 0) return capability(options.ledgerPayments);
|
|
1304
|
+
if (siteLedger === void 0) {
|
|
1305
|
+
const version2 = (await call("site", { method: "GET" })).body?.wcpos_version;
|
|
1306
|
+
const major = typeof version2 === "string" ? /^(\d+)\.\d+(?:\.\d+)?(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.exec(version2.trim())?.[1] : void 0;
|
|
1307
|
+
if (major !== void 0) siteLedger = Number(major) >= 2;
|
|
1308
|
+
}
|
|
1309
|
+
return siteLedger;
|
|
1310
|
+
};
|
|
1203
1311
|
return {
|
|
1204
1312
|
async send(batch, context) {
|
|
1205
|
-
|
|
1206
|
-
const
|
|
1313
|
+
if (batch.length === 0) return { kind: "results", results: [] };
|
|
1314
|
+
const ledger = await ledgerStore();
|
|
1315
|
+
if (ledger === void 0) return { kind: "retry", reason: "store_version_unknown" };
|
|
1316
|
+
const paymentsList = await capability(options.acceptsPaymentsList);
|
|
1317
|
+
const coupons = batch.some((envelope) => envelope.payload.coupons?.length) && await capability(options.acceptsCoupons);
|
|
1207
1318
|
const results = [];
|
|
1208
1319
|
for (const envelope of batch) {
|
|
1209
1320
|
if (envelope.payload.coupons?.length && !coupons) {
|
|
@@ -1214,84 +1325,106 @@ function createWooCommandTransport(options) {
|
|
|
1214
1325
|
} });
|
|
1215
1326
|
continue;
|
|
1216
1327
|
}
|
|
1217
|
-
const mapped = toWooOrderPayload(envelope, context?.local?.orders?.get(envelope.id), { paymentsList });
|
|
1328
|
+
const mapped = toWooOrderPayload(envelope, context?.local?.orders?.get(envelope.id), { paymentsList, ledger });
|
|
1218
1329
|
if ("error" in mapped) {
|
|
1219
1330
|
results.push({ id: envelope.id, status: "rejected", error: mapped.error });
|
|
1220
1331
|
continue;
|
|
1221
1332
|
}
|
|
1222
|
-
const controller = new AbortController();
|
|
1223
|
-
const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? 3e4);
|
|
1224
1333
|
let outcome;
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
const
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1334
|
+
const pushed = await call("push/orders", { method: "POST", body: {
|
|
1335
|
+
mutationId: envelope.id,
|
|
1336
|
+
operation: "create",
|
|
1337
|
+
collection: "orders",
|
|
1338
|
+
recordId: envelope.payload.clientOrderId,
|
|
1339
|
+
baseRevision: null,
|
|
1340
|
+
payload: mapped.payload
|
|
1341
|
+
} });
|
|
1342
|
+
const { status, body } = pushed;
|
|
1343
|
+
if (status === 0) outcome = retry(pushed, "network");
|
|
1344
|
+
else if (status === 401) outcome = { kind: "unauthorized" };
|
|
1345
|
+
else if (status === 426 && body?.code === "wcpos_update_required") outcome = { kind: "refused", status, reason: body?.message ?? body.code };
|
|
1346
|
+
else if (!ledger && status === 422 && body?.code === "wcpos_status_not_pushable" && options.ledgerPayments === void 0) {
|
|
1347
|
+
siteLedger = void 0;
|
|
1348
|
+
outcome = retry(pushed, "ledger_store_detected");
|
|
1349
|
+
} else if (![200, 201, 400, 422, 403, 413, 415].includes(status)) outcome = retry(pushed, `status_${status}`);
|
|
1350
|
+
else if (status === 200 || status === 201) {
|
|
1351
|
+
const doc = body?.document;
|
|
1352
|
+
const totalMinor = wooMinorFromDecimal(String(doc?.total), envelope.payload.currency);
|
|
1353
|
+
let revision = body?.currentRevision;
|
|
1354
|
+
if (doc?.id == null || totalMinor === void 0 || mapped.money && (typeof revision !== "string" || !revision)) {
|
|
1355
|
+
outcome = retry(pushed, pushed.aborted ? "timeout" : "bad_body");
|
|
1356
|
+
} else {
|
|
1357
|
+
const orderId = String(doc.id), displayId = String(doc.number ?? doc.id);
|
|
1358
|
+
if (ledger && totalMinor !== envelope.payload.totalMinor) {
|
|
1359
|
+
const tillMinor = envelope.payload.totalMinor, digits = wooDigits(envelope.payload);
|
|
1360
|
+
results.push({ id: envelope.id, status: "rejected", error: {
|
|
1361
|
+
code: "invalid_payload",
|
|
1362
|
+
message: `WooCommerce order #${displayId} totals ${wooMajor(totalMinor, digits)} but the till charged ${wooMajor(tillMinor, digits)}; no payment was recorded on it.`,
|
|
1363
|
+
data: { orderId, storeCode: "total_mismatch", tillMinor, serverMinor: totalMinor }
|
|
1364
|
+
} });
|
|
1365
|
+
continue;
|
|
1366
|
+
}
|
|
1367
|
+
let failed;
|
|
1368
|
+
let recorded = 0;
|
|
1369
|
+
for (const command of mapped.money ?? []) {
|
|
1370
|
+
const path = `orders/${orderId}/${command.path}`;
|
|
1371
|
+
let answer = await call(path, { method: "POST", body: { ...command.body, revision } });
|
|
1372
|
+
const stale = answer.status === 409 && answer.body?.code === "wcpos_revision_stale" ? answer.body?.data?.currentRevision : void 0;
|
|
1373
|
+
if (typeof stale === "string" && stale) answer = await call(path, { method: "POST", body: { ...command.body, revision: stale } });
|
|
1374
|
+
if (answer.status >= 200 && answer.status < 300 && typeof answer.body?.revision === "string" && answer.body.revision) {
|
|
1375
|
+
revision = answer.body.revision;
|
|
1376
|
+
recorded += 1;
|
|
1377
|
+
continue;
|
|
1378
|
+
}
|
|
1379
|
+
failed = answer;
|
|
1380
|
+
break;
|
|
1254
1381
|
}
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
displayId: String(doc.number ?? doc.id),
|
|
1264
|
-
totalMinor
|
|
1265
|
-
}, ...totalMinor !== envelope.payload.totalMinor ? { warnings: [{
|
|
1382
|
+
const code = failed?.body?.code;
|
|
1383
|
+
const terminal = typeof code === "string" && (code.startsWith("wcpos_") || code === "rest_invalid_param" || code === "rest_forbidden");
|
|
1384
|
+
if (!failed) {
|
|
1385
|
+
results.push({
|
|
1386
|
+
id: envelope.id,
|
|
1387
|
+
status: "applied",
|
|
1388
|
+
serverRefs: { orderId, displayId, totalMinor },
|
|
1389
|
+
...totalMinor !== envelope.payload.totalMinor ? { warnings: [{
|
|
1266
1390
|
code: "total_mismatch",
|
|
1267
1391
|
expectedMinor: envelope.payload.totalMinor,
|
|
1268
1392
|
serverMinor: totalMinor
|
|
1269
|
-
}] } : {}
|
|
1270
|
-
|
|
1271
|
-
}
|
|
1272
|
-
} else if (status === 400 && body?.code === "woocommerce_rest_invalid_coupon") {
|
|
1273
|
-
const message = decodeCouponMessage(body?.message), quoted = /"([^"]*)"/.exec(message)?.[1];
|
|
1274
|
-
const couponCode = envelope.payload.coupons?.find(({ code }) => code.toLowerCase() === quoted?.toLowerCase())?.code;
|
|
1275
|
-
results.push({ id: envelope.id, status: "rejected", error: {
|
|
1276
|
-
code: "coupon_invalid",
|
|
1277
|
-
message,
|
|
1278
|
-
data: { storeCode: body.code, ...couponCode ? { couponCode } : {} }
|
|
1279
|
-
} });
|
|
1393
|
+
}] } : {}
|
|
1394
|
+
});
|
|
1280
1395
|
continue;
|
|
1281
|
-
} else if (status ===
|
|
1396
|
+
} else if (failed.status === 401) outcome = { kind: "unauthorized" };
|
|
1397
|
+
else if (failed.status === 404 && code === "rest_no_route") {
|
|
1398
|
+
siteLedger = void 0;
|
|
1399
|
+
outcome = retry(failed, "ledger_route_missing");
|
|
1400
|
+
} else if (failed.status < 400 || failed.status >= 500 || failed.status === 409 && ["wcpos_revision_stale", "wcpos_payment_locked", "woo_rxdb_sync_record_locked"].includes(code) || !terminal) {
|
|
1401
|
+
outcome = retry(failed, failed.status >= 200 && failed.status < 300 ? failed.aborted ? "timeout" : "bad_body" : code ?? `status_${failed.status}`);
|
|
1402
|
+
} else {
|
|
1282
1403
|
results.push({ id: envelope.id, status: "rejected", error: {
|
|
1283
|
-
code: status === 400 &&
|
|
1284
|
-
message: body?.message ?? `status_${status}`
|
|
1404
|
+
code: failed.status === 400 && code === "wcpos_insufficient_stock" ? "insufficient_stock" : "invalid_payload",
|
|
1405
|
+
message: `WooCommerce order #${displayId} was ${recorded === 0 ? "created but not paid" : `created and part paid (${recorded} of ${mapped.money.length} payments recorded)`}: ${failed.body?.message ?? code ?? `status_${failed.status}`}`,
|
|
1406
|
+
data: { orderId, storeCode: code ?? `status_${failed.status}`, ...recorded ? { recorded } : {} }
|
|
1285
1407
|
} });
|
|
1286
1408
|
continue;
|
|
1287
|
-
} else {
|
|
1288
|
-
outcome = { kind: "refused", status, reason: body?.message ?? body?.code ?? `status_${status}` };
|
|
1289
1409
|
}
|
|
1290
1410
|
}
|
|
1291
|
-
}
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1411
|
+
} else if (status === 400 && body?.code === "woocommerce_rest_invalid_coupon") {
|
|
1412
|
+
const message = decodeCouponMessage(body?.message), quoted = /"([^"]*)"/.exec(message)?.[1];
|
|
1413
|
+
const couponCode = envelope.payload.coupons?.find(({ code }) => code.toLowerCase() === quoted?.toLowerCase())?.code;
|
|
1414
|
+
results.push({ id: envelope.id, status: "rejected", error: {
|
|
1415
|
+
code: "coupon_invalid",
|
|
1416
|
+
message,
|
|
1417
|
+
data: { storeCode: body.code, ...couponCode ? { couponCode } : {} }
|
|
1418
|
+
} });
|
|
1419
|
+
continue;
|
|
1420
|
+
} else if (status === 400 || status === 422) {
|
|
1421
|
+
results.push({ id: envelope.id, status: "rejected", error: {
|
|
1422
|
+
code: status === 400 && body?.code === "wcpos_insufficient_stock" ? "insufficient_stock" : "invalid_payload",
|
|
1423
|
+
message: body?.message ?? `status_${status}`
|
|
1424
|
+
} });
|
|
1425
|
+
continue;
|
|
1426
|
+
} else {
|
|
1427
|
+
outcome = { kind: "refused", status, reason: body?.message ?? body?.code ?? `status_${status}` };
|
|
1295
1428
|
}
|
|
1296
1429
|
return results.length ? { kind: "results", results } : outcome;
|
|
1297
1430
|
}
|
|
@@ -1329,10 +1462,45 @@ function decimalSumMinor(a, b, currency) {
|
|
|
1329
1462
|
}
|
|
1330
1463
|
var grossTax = (net, tax, currency) => decimalSumMinor(net, tax, currency) - minor(net, currency);
|
|
1331
1464
|
function posUuid(metaData) {
|
|
1332
|
-
const entry = rows(metaData).find((meta) => meta.key ===
|
|
1465
|
+
const entry = rows(metaData).find((meta) => meta.key === WCPOS_UUID_META_KEY && nonEmpty(meta.value));
|
|
1333
1466
|
return entry ? entry.value : void 0;
|
|
1334
1467
|
}
|
|
1335
1468
|
var PAYMENT_KINDS = { pos_cash: "cash", pos_card: "external" };
|
|
1469
|
+
function paymentLedger(metaData) {
|
|
1470
|
+
const entry = rows(metaData).find((meta) => meta.key === "_wcpos_payments");
|
|
1471
|
+
if (!entry) return { present: false, payments: null };
|
|
1472
|
+
const value = entry.value;
|
|
1473
|
+
return { present: true, payments: isRow(value) && value.schema === 1 && Array.isArray(value.payments) ? value.payments : null };
|
|
1474
|
+
}
|
|
1475
|
+
function storePayments(raw, currency, totalMinor) {
|
|
1476
|
+
const { payments } = paymentLedger(raw.meta_data);
|
|
1477
|
+
const captured = payments ? rows(payments).filter((row) => row.status === "captured") : [];
|
|
1478
|
+
if (captured.length) {
|
|
1479
|
+
const title2 = captured.every((row) => row.method_id === raw.payment_method) ? nonEmpty(raw.payment_method_title) : void 0;
|
|
1480
|
+
return captured.map((row) => {
|
|
1481
|
+
const method2 = nonEmpty(row.method_id);
|
|
1482
|
+
if (!method2 || typeof row.currency === "string" && row.currency !== currency) throw unexpected();
|
|
1483
|
+
const kind2 = PAYMENT_KINDS[method2];
|
|
1484
|
+
const id = nonEmpty(row.id);
|
|
1485
|
+
return {
|
|
1486
|
+
...id ? { id } : {},
|
|
1487
|
+
method: method2,
|
|
1488
|
+
...title2 ? { title: title2 } : {},
|
|
1489
|
+
...kind2 ? { kind: kind2 } : {},
|
|
1490
|
+
amountMinor: minor(row.amount, currency)
|
|
1491
|
+
};
|
|
1492
|
+
});
|
|
1493
|
+
}
|
|
1494
|
+
const method = nonEmpty(raw.payment_method);
|
|
1495
|
+
const title = nonEmpty(raw.payment_method_title);
|
|
1496
|
+
const kind = method ? PAYMENT_KINDS[method] : void 0;
|
|
1497
|
+
return method && (nonEmpty(raw.date_paid_gmt) || nonEmpty(raw.date_paid)) ? [{
|
|
1498
|
+
method,
|
|
1499
|
+
...title ? { title } : {},
|
|
1500
|
+
...kind ? { kind } : {},
|
|
1501
|
+
amountMinor: totalMinor
|
|
1502
|
+
}] : [];
|
|
1503
|
+
}
|
|
1336
1504
|
function toWooStoreOrder(raw) {
|
|
1337
1505
|
if (!isRow(raw) || raw.id === void 0 || raw.id === null || typeof raw.currency !== "string" || typeof raw.date_created_gmt !== "string") {
|
|
1338
1506
|
throw unexpected();
|
|
@@ -1347,14 +1515,15 @@ function toWooStoreOrder(raw) {
|
|
|
1347
1515
|
const email = nonEmpty(billing.email);
|
|
1348
1516
|
const customer = customerId || name || email ? { ...customerId ? { id: customerId } : {}, ...name ? { name } : {}, ...email ? { email } : {} } : null;
|
|
1349
1517
|
const clientOrderId = posUuid(raw.meta_data);
|
|
1518
|
+
const revision = nonEmpty(raw._rxdb_revision);
|
|
1350
1519
|
const totalMinor = minor(raw.total, currency);
|
|
1351
|
-
const
|
|
1352
|
-
const
|
|
1353
|
-
const paymentKind = paymentMethod ? PAYMENT_KINDS[paymentMethod] : void 0;
|
|
1520
|
+
const ledger = paymentLedger(raw.meta_data);
|
|
1521
|
+
const paymentRecordUnreadable = ledger.present && ledger.payments === null;
|
|
1354
1522
|
return {
|
|
1355
1523
|
id: String(raw.id),
|
|
1356
1524
|
reference: String(raw.number ?? raw.id),
|
|
1357
1525
|
...clientOrderId ? { clientOrderId } : {},
|
|
1526
|
+
...revision ? { revision } : {},
|
|
1358
1527
|
status: String(raw.status),
|
|
1359
1528
|
placedAt: placed.toISOString(),
|
|
1360
1529
|
currency,
|
|
@@ -1380,11 +1549,17 @@ function toWooStoreOrder(raw) {
|
|
|
1380
1549
|
};
|
|
1381
1550
|
}),
|
|
1382
1551
|
fees: rows(raw.fee_lines).map((fee) => ({
|
|
1552
|
+
...positiveId(fee.id) ? { id: positiveId(fee.id) } : {},
|
|
1553
|
+
...fee.tax_status === "taxable" || fee.tax_status === "none" ? { taxStatus: fee.tax_status } : {},
|
|
1554
|
+
...nonEmpty(fee.tax_class) ? { taxClass: nonEmpty(fee.tax_class) } : {},
|
|
1383
1555
|
name: String(fee.name),
|
|
1384
1556
|
totalMinor: minor(fee.total, currency),
|
|
1385
1557
|
taxMinor: grossTax(fee.total, fee.total_tax, currency)
|
|
1386
1558
|
})),
|
|
1387
1559
|
shipping: rows(raw.shipping_lines).map((line) => ({
|
|
1560
|
+
...positiveId(line.id) ? { id: positiveId(line.id) } : {},
|
|
1561
|
+
...line.tax_status === "taxable" || line.tax_status === "none" ? { taxStatus: line.tax_status } : {},
|
|
1562
|
+
...nonEmpty(line.method_id) ? { methodId: nonEmpty(line.method_id) } : {},
|
|
1388
1563
|
name: String(line.method_title),
|
|
1389
1564
|
totalMinor: minor(line.total, currency),
|
|
1390
1565
|
taxMinor: grossTax(line.total, line.total_tax, currency)
|
|
@@ -1407,12 +1582,8 @@ function toWooStoreOrder(raw) {
|
|
|
1407
1582
|
discountTaxMinor: minor(raw.discount_tax, currency),
|
|
1408
1583
|
taxMinor: minor(raw.total_tax, currency),
|
|
1409
1584
|
totalMinor,
|
|
1410
|
-
payments:
|
|
1411
|
-
|
|
1412
|
-
...paymentTitle ? { title: paymentTitle } : {},
|
|
1413
|
-
...paymentKind ? { kind: paymentKind } : {},
|
|
1414
|
-
amountMinor: totalMinor
|
|
1415
|
-
}] : [],
|
|
1585
|
+
payments: storePayments(raw, currency, totalMinor),
|
|
1586
|
+
...paymentRecordUnreadable ? { paymentRecordUnreadable: true } : {},
|
|
1416
1587
|
refunds: rows(raw.refunds).map((refund) => {
|
|
1417
1588
|
const reason = nonEmpty(refund.reason);
|
|
1418
1589
|
return { id: String(refund.id), amountMinor: Math.abs(minor(refund.total, currency)), ...reason ? { reason } : {} };
|
|
@@ -1453,11 +1624,20 @@ function createWooOrders() {
|
|
|
1453
1624
|
if (before !== void 0) params.set("before", wooGmtSecond(before, 0));
|
|
1454
1625
|
const { body, headers } = await customerRequest(context, `orders?${params}`, { method: "GET" });
|
|
1455
1626
|
if (!Array.isArray(body)) throw unexpected();
|
|
1456
|
-
|
|
1627
|
+
let unreadable = 0;
|
|
1628
|
+
const orders = body.flatMap((row) => {
|
|
1629
|
+
try {
|
|
1630
|
+
return [toWooStoreOrder(row)];
|
|
1631
|
+
} catch (error) {
|
|
1632
|
+
if (!(error instanceof CustomerServiceError2)) throw error;
|
|
1633
|
+
unreadable += 1;
|
|
1634
|
+
return [];
|
|
1635
|
+
}
|
|
1636
|
+
});
|
|
1457
1637
|
const totalPages = headers.get("X-WP-TotalPages");
|
|
1458
|
-
const hasMore = totalPages !== null && /^\d+$/.test(totalPages.trim()) ? page < Number.parseInt(totalPages, 10) :
|
|
1638
|
+
const hasMore = totalPages !== null && /^\d+$/.test(totalPages.trim()) ? page < Number.parseInt(totalPages, 10) : body.length === perPage;
|
|
1459
1639
|
const total = headers.get("X-WP-Total");
|
|
1460
|
-
return { orders, hasMore, ...total && /^\d+$/.test(total) ? { total: Number(total) } : {} };
|
|
1640
|
+
return { orders, hasMore, ...unreadable ? { unreadable } : {}, ...total && /^\d+$/.test(total) ? { total: Number(total) } : {} };
|
|
1461
1641
|
},
|
|
1462
1642
|
async getOrders(context, ids) {
|
|
1463
1643
|
const wanted = [...new Set(ids.filter((id) => /^[1-9]\d*$/.test(id)))];
|
|
@@ -1474,43 +1654,236 @@ function createWooOrders() {
|
|
|
1474
1654
|
}
|
|
1475
1655
|
|
|
1476
1656
|
// src/store-settings.ts
|
|
1477
|
-
import { ConnectorUnauthorizedError as
|
|
1657
|
+
import { ConnectorUnauthorizedError as ConnectorUnauthorizedError3, StoreSettingsError, minorUnitDigits as minorUnitDigits3, woocommerceTax as woocommerceTax2 } from "@tallyui/core";
|
|
1658
|
+
|
|
1659
|
+
// src/currency-symbols.ts
|
|
1660
|
+
var WOO_CURRENCY_SYMBOLS = {
|
|
1661
|
+
AED: "\u062F.\u0625",
|
|
1662
|
+
AFN: "\u060B",
|
|
1663
|
+
ALL: "L",
|
|
1664
|
+
AMD: "AMD",
|
|
1665
|
+
ANG: "\u0192",
|
|
1666
|
+
AOA: "Kz",
|
|
1667
|
+
ARS: "$",
|
|
1668
|
+
AUD: "$",
|
|
1669
|
+
AWG: "Afl.",
|
|
1670
|
+
AZN: "\u20BC",
|
|
1671
|
+
BAM: "KM",
|
|
1672
|
+
BBD: "$",
|
|
1673
|
+
BDT: "\u09F3\xA0",
|
|
1674
|
+
BGN: "\u043B\u0432.",
|
|
1675
|
+
BHD: ".\u062F.\u0628",
|
|
1676
|
+
BIF: "Fr",
|
|
1677
|
+
BMD: "$",
|
|
1678
|
+
BND: "$",
|
|
1679
|
+
BOB: "Bs.",
|
|
1680
|
+
BRL: "R$",
|
|
1681
|
+
BSD: "$",
|
|
1682
|
+
BTC: "\u0E3F",
|
|
1683
|
+
BTN: "Nu.",
|
|
1684
|
+
BWP: "P",
|
|
1685
|
+
BYN: "Br",
|
|
1686
|
+
BYR: "Br",
|
|
1687
|
+
BZD: "$",
|
|
1688
|
+
CAD: "$",
|
|
1689
|
+
CDF: "Fr",
|
|
1690
|
+
CHF: "CHF",
|
|
1691
|
+
CLP: "$",
|
|
1692
|
+
CNY: "\xA5",
|
|
1693
|
+
COP: "$",
|
|
1694
|
+
CRC: "\u20A1",
|
|
1695
|
+
CUC: "$",
|
|
1696
|
+
CUP: "$",
|
|
1697
|
+
CVE: "$",
|
|
1698
|
+
CZK: "K\u010D",
|
|
1699
|
+
DJF: "Fr",
|
|
1700
|
+
DKK: "kr.",
|
|
1701
|
+
DOP: "RD$",
|
|
1702
|
+
DZD: "\u062F.\u062C",
|
|
1703
|
+
EGP: "EGP",
|
|
1704
|
+
ERN: "Nfk",
|
|
1705
|
+
ETB: "Br",
|
|
1706
|
+
EUR: "\u20AC",
|
|
1707
|
+
FJD: "$",
|
|
1708
|
+
FKP: "\xA3",
|
|
1709
|
+
GBP: "\xA3",
|
|
1710
|
+
GEL: "\u20BE",
|
|
1711
|
+
GGP: "\xA3",
|
|
1712
|
+
GHS: "\u20B5",
|
|
1713
|
+
GIP: "\xA3",
|
|
1714
|
+
GMD: "D",
|
|
1715
|
+
GNF: "Fr",
|
|
1716
|
+
GTQ: "Q",
|
|
1717
|
+
GYD: "$",
|
|
1718
|
+
HKD: "$",
|
|
1719
|
+
HNL: "L",
|
|
1720
|
+
HRK: "kn",
|
|
1721
|
+
HTG: "G",
|
|
1722
|
+
HUF: "Ft",
|
|
1723
|
+
IDR: "Rp",
|
|
1724
|
+
ILS: "\u20AA",
|
|
1725
|
+
IMP: "\xA3",
|
|
1726
|
+
INR: "\u20B9",
|
|
1727
|
+
IQD: "\u062F.\u0639",
|
|
1728
|
+
IRR: "\uFDFC",
|
|
1729
|
+
IRT: "\u062A\u0648\u0645\u0627\u0646",
|
|
1730
|
+
ISK: "kr.",
|
|
1731
|
+
JEP: "\xA3",
|
|
1732
|
+
JMD: "$",
|
|
1733
|
+
JOD: "\u062F.\u0627",
|
|
1734
|
+
JPY: "\xA5",
|
|
1735
|
+
KES: "KSh",
|
|
1736
|
+
KGS: "\u0441\u043E\u043C",
|
|
1737
|
+
KHR: "\u17DB",
|
|
1738
|
+
KMF: "Fr",
|
|
1739
|
+
KPW: "\u20A9",
|
|
1740
|
+
KRW: "\u20A9",
|
|
1741
|
+
KWD: "\u062F.\u0643",
|
|
1742
|
+
KYD: "$",
|
|
1743
|
+
KZT: "\u20B8",
|
|
1744
|
+
LAK: "\u20AD",
|
|
1745
|
+
LBP: "\u0644.\u0644",
|
|
1746
|
+
LKR: "\u0DBB\u0DD4",
|
|
1747
|
+
LRD: "$",
|
|
1748
|
+
LSL: "L",
|
|
1749
|
+
LYD: "\u062F.\u0644",
|
|
1750
|
+
MAD: "\u062F.\u0645.",
|
|
1751
|
+
MDL: "MDL",
|
|
1752
|
+
MGA: "Ar",
|
|
1753
|
+
MKD: "\u0434\u0435\u043D",
|
|
1754
|
+
MMK: "Ks",
|
|
1755
|
+
MNT: "\u20AE",
|
|
1756
|
+
MOP: "P",
|
|
1757
|
+
MRU: "UM",
|
|
1758
|
+
MUR: "\u20A8",
|
|
1759
|
+
MVR: ".\u0783",
|
|
1760
|
+
MWK: "MK",
|
|
1761
|
+
MXN: "$",
|
|
1762
|
+
MYR: "RM",
|
|
1763
|
+
MZN: "MT",
|
|
1764
|
+
NAD: "N$",
|
|
1765
|
+
NGN: "\u20A6",
|
|
1766
|
+
NIO: "C$",
|
|
1767
|
+
NOK: "kr",
|
|
1768
|
+
NPR: "\u20A8",
|
|
1769
|
+
NZD: "$",
|
|
1770
|
+
OMR: "\u0631.\u0639.",
|
|
1771
|
+
PAB: "B/.",
|
|
1772
|
+
PEN: "S/",
|
|
1773
|
+
PGK: "K",
|
|
1774
|
+
PHP: "\u20B1",
|
|
1775
|
+
PKR: "\u20A8",
|
|
1776
|
+
PLN: "z\u0142",
|
|
1777
|
+
PRB: "\u0440.",
|
|
1778
|
+
PYG: "\u20B2",
|
|
1779
|
+
QAR: "\u0631.\u0642",
|
|
1780
|
+
RON: "lei",
|
|
1781
|
+
RSD: "\u0440\u0441\u0434",
|
|
1782
|
+
RUB: "\u20BD",
|
|
1783
|
+
RWF: "Fr",
|
|
1784
|
+
SAR: "\u0631.\u0633",
|
|
1785
|
+
SBD: "$",
|
|
1786
|
+
SCR: "\u20A8",
|
|
1787
|
+
SDG: "\u062C.\u0633.",
|
|
1788
|
+
SEK: "kr",
|
|
1789
|
+
SGD: "$",
|
|
1790
|
+
SHP: "\xA3",
|
|
1791
|
+
SLL: "Le",
|
|
1792
|
+
SOS: "Sh",
|
|
1793
|
+
SRD: "$",
|
|
1794
|
+
SSP: "\xA3",
|
|
1795
|
+
STN: "Db",
|
|
1796
|
+
SYP: "\u0644.\u0633",
|
|
1797
|
+
SZL: "E",
|
|
1798
|
+
THB: "\u0E3F",
|
|
1799
|
+
TJS: "\u0405\u041C",
|
|
1800
|
+
TMT: "m",
|
|
1801
|
+
TND: "\u062F.\u062A",
|
|
1802
|
+
TOP: "T$",
|
|
1803
|
+
TRY: "\u20BA",
|
|
1804
|
+
TTD: "$",
|
|
1805
|
+
TWD: "NT$",
|
|
1806
|
+
TZS: "Sh",
|
|
1807
|
+
UAH: "\u20B4",
|
|
1808
|
+
UGX: "UGX",
|
|
1809
|
+
USD: "$",
|
|
1810
|
+
UYU: "$",
|
|
1811
|
+
UZS: "UZS",
|
|
1812
|
+
VEF: "Bs F",
|
|
1813
|
+
VES: "Bs.S",
|
|
1814
|
+
VND: "\u20AB",
|
|
1815
|
+
VUV: "Vt",
|
|
1816
|
+
WST: "T",
|
|
1817
|
+
XAF: "CFA",
|
|
1818
|
+
XCD: "$",
|
|
1819
|
+
XOF: "CFA",
|
|
1820
|
+
XPF: "Fr",
|
|
1821
|
+
YER: "\uFDFC",
|
|
1822
|
+
ZAR: "R",
|
|
1823
|
+
ZMW: "ZK"
|
|
1824
|
+
};
|
|
1825
|
+
|
|
1826
|
+
// src/unauthorized.ts
|
|
1827
|
+
import { ConnectorUnauthorizedError as ConnectorUnauthorizedError2 } from "@tallyui/core";
|
|
1828
|
+
function throwIfUnauthorized(response, what) {
|
|
1829
|
+
if (response?.status === 401 || response?.status === 403) {
|
|
1830
|
+
throw new ConnectorUnauthorizedError2(`WooCommerce ${what}: HTTP ${response.status}`, response.status);
|
|
1831
|
+
}
|
|
1832
|
+
}
|
|
1833
|
+
|
|
1834
|
+
// src/store-settings.ts
|
|
1478
1835
|
var WOO_ORDER_CREATE_VERSION = 5;
|
|
1479
1836
|
var WOO_NOTE_ORDER_CREATE_VERSION = 7;
|
|
1480
1837
|
var WOO_TAX_ADDRESS_ORDER_CREATE_VERSION = 8;
|
|
1481
1838
|
var WOO_BASE_ORDER_CREATE_VERSION = 3;
|
|
1482
1839
|
var WOO_COUPONS_MIN_PLUGIN = [1, 9, 0];
|
|
1483
|
-
|
|
1840
|
+
var WOO_ORDER_LINES_FLOOR = [1, 10, 20];
|
|
1841
|
+
var WOO_ORDER_LINES_VERSION_CAP = 7;
|
|
1842
|
+
var WOO_ORDER_LINES_20_FLOOR = [2, 0, 4];
|
|
1843
|
+
var WOO_ORDER_LINES_20_CAP = 6;
|
|
1844
|
+
function atLeast(version2, floor) {
|
|
1484
1845
|
if (typeof version2 !== "string") return false;
|
|
1485
1846
|
const match = /^(\d+)\.(\d+)(?:\.(\d+))?(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/.exec(version2.trim());
|
|
1486
1847
|
if (!match) return false;
|
|
1487
1848
|
const parts = [Number(match[1]), Number(match[2]), Number(match[3] ?? 0)];
|
|
1488
1849
|
for (let index = 0; index < parts.length; index++) {
|
|
1489
|
-
if (parts[index] >
|
|
1490
|
-
if (parts[index] <
|
|
1850
|
+
if (parts[index] > floor[index]) return true;
|
|
1851
|
+
if (parts[index] < floor[index]) return false;
|
|
1491
1852
|
}
|
|
1492
1853
|
return !match[4];
|
|
1493
1854
|
}
|
|
1855
|
+
function wooPluginSupportsCoupons(version2) {
|
|
1856
|
+
return atLeast(version2, WOO_COUPONS_MIN_PLUGIN);
|
|
1857
|
+
}
|
|
1858
|
+
function wooOnOrderLinesLine(version2) {
|
|
1859
|
+
return typeof version2 === "string" && /^1\.10\.\d+$/.test(version2.trim()) && atLeast(version2, WOO_ORDER_LINES_FLOOR);
|
|
1860
|
+
}
|
|
1861
|
+
function wooOnOrderLines20Line(version2) {
|
|
1862
|
+
return typeof version2 === "string" && /^2\.0\.\d+$/.test(version2.trim()) && atLeast(version2, WOO_ORDER_LINES_20_FLOOR);
|
|
1863
|
+
}
|
|
1494
1864
|
async function wooStoreSettings(context) {
|
|
1495
1865
|
try {
|
|
1496
1866
|
const init = { method: "GET", headers: context.headers, signal: context.signal };
|
|
1497
1867
|
const storesResponse = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/stores`, init);
|
|
1498
|
-
|
|
1499
|
-
throw new ConnectorUnauthorizedError2(`WooCommerce stores: HTTP ${storesResponse.status}`, storesResponse.status);
|
|
1500
|
-
}
|
|
1868
|
+
throwIfUnauthorized(storesResponse, "stores");
|
|
1501
1869
|
if (!storesResponse.ok) throw new Error(`WooCommerce stores: HTTP ${storesResponse.status}`);
|
|
1502
1870
|
const stores = await storesResponse.json();
|
|
1503
1871
|
if (!Array.isArray(stores) || stores.length === 0) throw new Error("WooCommerce stores: expected a non-empty array");
|
|
1504
1872
|
const store = stores[0];
|
|
1505
1873
|
const currency = store.currency.toUpperCase();
|
|
1874
|
+
const moneyFormat = {
|
|
1875
|
+
...["left", "right", "left_space", "right_space"].includes(store.currency_pos) ? { position: store.currency_pos } : {},
|
|
1876
|
+
...typeof store.price_thousand_sep === "string" ? { thousandSeparator: store.price_thousand_sep } : {},
|
|
1877
|
+
...typeof store.price_decimal_sep === "string" ? { decimalSeparator: store.price_decimal_sep } : {},
|
|
1878
|
+
...Number.isInteger(store.price_num_decimals) && store.price_num_decimals >= 0 ? { decimals: store.price_num_decimals } : {},
|
|
1879
|
+
...WOO_CURRENCY_SYMBOLS[currency] !== void 0 ? { symbol: WOO_CURRENCY_SYMBOLS[currency] } : {}
|
|
1880
|
+
};
|
|
1506
1881
|
const digits = minorUnitDigits3(currency);
|
|
1507
1882
|
if (typeof store.price_num_decimals === "number" && store.price_num_decimals !== digits) {
|
|
1508
1883
|
console.warn(`WooCommerce price_num_decimals is ${store.price_num_decimals}; the till rounds ${currency} to ${digits} digits`);
|
|
1509
1884
|
}
|
|
1510
1885
|
const classesResponse = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/taxes/classes`, init);
|
|
1511
|
-
|
|
1512
|
-
throw new ConnectorUnauthorizedError2(`WooCommerce tax classes: HTTP ${classesResponse.status}`, classesResponse.status);
|
|
1513
|
-
}
|
|
1886
|
+
throwIfUnauthorized(classesResponse, "tax classes");
|
|
1514
1887
|
if (!classesResponse.ok) throw new Error(`WooCommerce tax classes: HTTP ${classesResponse.status}`);
|
|
1515
1888
|
const classes = await classesResponse.json();
|
|
1516
1889
|
if (!Array.isArray(classes)) throw new Error("WooCommerce tax classes: expected an array");
|
|
@@ -1521,6 +1894,8 @@ async function wooStoreSettings(context) {
|
|
|
1521
1894
|
pricesIncludeTax: store.prices_include_tax === "yes",
|
|
1522
1895
|
taxRoundAtSubtotal: store.tax_round_at_subtotal === "yes",
|
|
1523
1896
|
calcDiscountsSequentially: (store.woocommerce_calc_discounts_sequentially ?? store.calc_discounts_sequentially) === "yes",
|
|
1897
|
+
preventOverselling: store.prevent_overselling === true,
|
|
1898
|
+
...Object.keys(moneyFormat).length > 0 ? { moneyFormat } : {},
|
|
1524
1899
|
...typeof store.shipping_tax_class === "string" ? { shippingTaxClass: store.shipping_tax_class } : {},
|
|
1525
1900
|
taxClassSlugs: classes.map((row) => row.slug),
|
|
1526
1901
|
taxClasses: classes.map((row) => ({ slug: row.slug, name: typeof row.name === "string" && row.name !== "" ? row.name : row.slug })),
|
|
@@ -1532,9 +1907,7 @@ async function wooStoreSettings(context) {
|
|
|
1532
1907
|
const rates = [];
|
|
1533
1908
|
for (let page = 1; page <= 100; page++) {
|
|
1534
1909
|
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/taxes?per_page=100&page=${page}&orderby=order&order=asc`, init);
|
|
1535
|
-
|
|
1536
|
-
throw new ConnectorUnauthorizedError2(`WooCommerce taxes: HTTP ${response.status}`, response.status);
|
|
1537
|
-
}
|
|
1910
|
+
throwIfUnauthorized(response, "taxes");
|
|
1538
1911
|
if (!response.ok) throw new Error(`WooCommerce taxes: HTTP ${response.status}`);
|
|
1539
1912
|
const rows2 = await response.json();
|
|
1540
1913
|
if (!Array.isArray(rows2)) throw new Error("WooCommerce taxes: expected an array");
|
|
@@ -1587,10 +1960,17 @@ async function wooStoreSettings(context) {
|
|
|
1587
1960
|
}
|
|
1588
1961
|
return settings;
|
|
1589
1962
|
} catch (error) {
|
|
1590
|
-
if (error instanceof
|
|
1963
|
+
if (error instanceof ConnectorUnauthorizedError3) throw error;
|
|
1591
1964
|
throw new StoreSettingsError("failed", error instanceof Error ? error.message : String(error));
|
|
1592
1965
|
}
|
|
1593
1966
|
}
|
|
1967
|
+
function wooThresholdMinor(value, currency) {
|
|
1968
|
+
if (typeof value !== "string" || typeof currency !== "string" || !/^\d+(\.\d+)?$/.test(value)) return void 0;
|
|
1969
|
+
const digits = minorUnitDigits3(currency);
|
|
1970
|
+
const [whole, fraction = ""] = value.split(".");
|
|
1971
|
+
const minor2 = Number(whole + fraction.slice(0, digits).padEnd(digits, "0"));
|
|
1972
|
+
return Number.isSafeInteger(minor2) ? minor2 : void 0;
|
|
1973
|
+
}
|
|
1594
1974
|
async function readWooCapabilities(context) {
|
|
1595
1975
|
try {
|
|
1596
1976
|
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/stores`, {
|
|
@@ -1598,32 +1978,31 @@ async function readWooCapabilities(context) {
|
|
|
1598
1978
|
headers: context.headers,
|
|
1599
1979
|
signal: context.signal
|
|
1600
1980
|
});
|
|
1601
|
-
|
|
1602
|
-
throw new ConnectorUnauthorizedError2(`WooCommerce stores: HTTP ${response.status}`, response.status);
|
|
1603
|
-
}
|
|
1981
|
+
throwIfUnauthorized(response, "stores");
|
|
1604
1982
|
if (!response.ok) return void 0;
|
|
1605
1983
|
const stores = await response.json();
|
|
1606
1984
|
if (!Array.isArray(stores) || !stores[0] || typeof stores[0] !== "object" || Array.isArray(stores[0])) return void 0;
|
|
1607
1985
|
let multiplePayments = false;
|
|
1608
1986
|
let capabilities = [];
|
|
1987
|
+
let flagged;
|
|
1609
1988
|
try {
|
|
1610
1989
|
const status = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/status`, {
|
|
1611
1990
|
method: "GET",
|
|
1612
1991
|
headers: context.headers,
|
|
1613
1992
|
signal: context.signal
|
|
1614
1993
|
});
|
|
1615
|
-
|
|
1616
|
-
throw new ConnectorUnauthorizedError2(`WooCommerce status: HTTP ${status.status}`, status.status);
|
|
1617
|
-
}
|
|
1994
|
+
throwIfUnauthorized(status, "status");
|
|
1618
1995
|
if (status.ok) {
|
|
1619
1996
|
const body = await status.json();
|
|
1620
|
-
|
|
1997
|
+
flagged = Array.isArray(body?.capabilities);
|
|
1998
|
+
capabilities = flagged ? body.capabilities : [];
|
|
1621
1999
|
multiplePayments = capabilities.includes("order_payments_list");
|
|
1622
2000
|
}
|
|
1623
2001
|
} catch (error) {
|
|
1624
|
-
if (error instanceof
|
|
2002
|
+
if (error instanceof ConnectorUnauthorizedError3) throw error;
|
|
1625
2003
|
}
|
|
1626
2004
|
let coupons = false;
|
|
2005
|
+
let wcposVersion;
|
|
1627
2006
|
try {
|
|
1628
2007
|
const site = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/site`, {
|
|
1629
2008
|
method: "GET",
|
|
@@ -1632,28 +2011,432 @@ async function readWooCapabilities(context) {
|
|
|
1632
2011
|
});
|
|
1633
2012
|
if (site.ok) {
|
|
1634
2013
|
const body = await site.json();
|
|
1635
|
-
|
|
2014
|
+
wcposVersion = body?.wcpos_version;
|
|
2015
|
+
coupons = wooPluginSupportsCoupons(wcposVersion);
|
|
1636
2016
|
}
|
|
1637
2017
|
} catch {
|
|
1638
2018
|
coupons = false;
|
|
1639
2019
|
}
|
|
1640
|
-
const
|
|
2020
|
+
const linesVersion = coupons ? WOO_TAX_ADDRESS_ORDER_CREATE_VERSION : WOO_ORDER_CREATE_VERSION;
|
|
2021
|
+
const orderCreate = flagged === void 0 ? WOO_BASE_ORDER_CREATE_VERSION : capabilities.includes("order_create_v5") ? linesVersion : wooOnOrderLines20Line(wcposVersion) ? Math.min(WOO_ORDER_LINES_20_CAP, linesVersion) : !flagged && wooOnOrderLinesLine(wcposVersion) ? Math.min(WOO_ORDER_LINES_VERSION_CAP, linesVersion) : WOO_BASE_ORDER_CREATE_VERSION;
|
|
2022
|
+
const thresholdMinor = wooThresholdMinor(stores[0].variance_threshold, stores[0].currency);
|
|
1641
2023
|
return {
|
|
1642
2024
|
orderCreate,
|
|
1643
2025
|
taxRounding: { granularity: "woocommerce", roundAtSubtotal: stores[0].tax_round_at_subtotal === "yes" },
|
|
1644
2026
|
multiplePayments,
|
|
1645
2027
|
coupons,
|
|
1646
2028
|
// WCPOS v5 takes a fee's, shipping line's and custom line's tax_status and tax_class (orders #146, #161); it has no /tally/v1/info.
|
|
1647
|
-
lineTax: { none: true, classes: true }
|
|
2029
|
+
lineTax: { none: true, classes: true },
|
|
2030
|
+
...thresholdMinor !== void 0 ? { registerApproval: { thresholdMinor } } : {},
|
|
2031
|
+
// WCPOS 2.0's per-store register_sessions setting: the register transport sends to sessions, movements and closures.
|
|
2032
|
+
...stores[0].register_sessions === true ? { register: 3 } : {}
|
|
1648
2033
|
};
|
|
1649
2034
|
} catch (error) {
|
|
1650
|
-
if (error instanceof
|
|
2035
|
+
if (error instanceof ConnectorUnauthorizedError3) throw error;
|
|
1651
2036
|
return void 0;
|
|
1652
2037
|
}
|
|
1653
2038
|
}
|
|
1654
2039
|
|
|
2040
|
+
// src/registers.ts
|
|
2041
|
+
async function wooFirstStore(context) {
|
|
2042
|
+
const init = { method: "GET", headers: context.headers, signal: context.signal };
|
|
2043
|
+
const storesResponse = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/stores`, init);
|
|
2044
|
+
throwIfUnauthorized(storesResponse, "stores");
|
|
2045
|
+
if (!storesResponse.ok) throw new Error(`WooCommerce stores: HTTP ${storesResponse.status}`);
|
|
2046
|
+
const stores = await storesResponse.json();
|
|
2047
|
+
if (!Array.isArray(stores) || stores.length === 0) throw new Error("WooCommerce stores: expected a non-empty array");
|
|
2048
|
+
const store = stores[0];
|
|
2049
|
+
if (typeof store?.currency !== "string") throw new Error("WooCommerce stores: expected a currency");
|
|
2050
|
+
return { currency: store.currency.toUpperCase(), store };
|
|
2051
|
+
}
|
|
2052
|
+
async function wooStoreCurrency(context) {
|
|
2053
|
+
return (await wooFirstStore(context)).currency;
|
|
2054
|
+
}
|
|
2055
|
+
async function wooListRegisters(context) {
|
|
2056
|
+
const init = { method: "GET", headers: context.headers, signal: context.signal };
|
|
2057
|
+
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/registers`, init);
|
|
2058
|
+
throwIfUnauthorized(response, "registers");
|
|
2059
|
+
if (response.status === 404) return [];
|
|
2060
|
+
if (!response.ok) throw new Error(`WooCommerce registers: HTTP ${response.status}`);
|
|
2061
|
+
const { currency, store } = await wooFirstStore(context);
|
|
2062
|
+
const closeTime = typeof store.expected_close_time === "string" && /^\d{2}:\d{2}$/.test(store.expected_close_time) ? store.expected_close_time : void 0;
|
|
2063
|
+
const rows2 = await response.json();
|
|
2064
|
+
if (!Array.isArray(rows2)) throw new Error("WooCommerce registers: expected an array");
|
|
2065
|
+
const registers = [];
|
|
2066
|
+
for (const row of rows2) {
|
|
2067
|
+
if (typeof row?.id !== "string" || row.id === "" || typeof row.name !== "string" || row.name === "") {
|
|
2068
|
+
console.warn("WooCommerce registers: skipping a register without an id or name");
|
|
2069
|
+
continue;
|
|
2070
|
+
}
|
|
2071
|
+
const float = typeof row.default_float === "string" ? wooMinorFromDecimal(row.default_float, currency) : void 0;
|
|
2072
|
+
registers.push({
|
|
2073
|
+
id: row.id,
|
|
2074
|
+
name: row.name,
|
|
2075
|
+
...float !== void 0 ? { defaultFloatMinor: float } : {},
|
|
2076
|
+
...closeTime !== void 0 ? { expectedCloseTime: closeTime } : {}
|
|
2077
|
+
});
|
|
2078
|
+
}
|
|
2079
|
+
return registers;
|
|
2080
|
+
}
|
|
2081
|
+
|
|
2082
|
+
// src/closures.ts
|
|
2083
|
+
import { ConnectorUnauthorizedError as ConnectorUnauthorizedError4, minorUnitDigits as minorUnitDigits5 } from "@tallyui/core";
|
|
2084
|
+
|
|
2085
|
+
// src/commands/register-transport.ts
|
|
2086
|
+
import {
|
|
2087
|
+
minorUnitDigits as minorUnitDigits4
|
|
2088
|
+
} from "@tallyui/core";
|
|
2089
|
+
var TENDER_KEY = /^[a-zA-Z0-9_-]{1,191}$/;
|
|
2090
|
+
function wooDecimal(minor2, digits) {
|
|
2091
|
+
const text = String(Math.abs(minor2)).padStart(digits + 1, "0");
|
|
2092
|
+
return `${minor2 < 0 ? "-" : ""}${digits ? `${text.slice(0, -digits)}.${text.slice(-digits)}` : text}`;
|
|
2093
|
+
}
|
|
2094
|
+
function wooSignedMinor(value, currency) {
|
|
2095
|
+
if (typeof value !== "string") return void 0;
|
|
2096
|
+
const text = value.trim();
|
|
2097
|
+
if (!text.startsWith("-")) return wooMinorFromDecimal(text, currency);
|
|
2098
|
+
const minor2 = wooMinorFromDecimal(text.slice(1), currency);
|
|
2099
|
+
return minor2 === void 0 ? void 0 : 0 - minor2;
|
|
2100
|
+
}
|
|
2101
|
+
function wooTenders(map, digits) {
|
|
2102
|
+
return Object.fromEntries(Object.entries({ cash: 0, ...map }).map(([key, minor2]) => [key, wooDecimal(minor2, digits)]));
|
|
2103
|
+
}
|
|
2104
|
+
function rejected(id, code, message, data) {
|
|
2105
|
+
return { id, status: "rejected", error: { code, message: typeof message === "string" && message ? message : code, ...data ? { data } : {} } };
|
|
2106
|
+
}
|
|
2107
|
+
function storeCode(answer) {
|
|
2108
|
+
return typeof answer.body?.code === "string" ? { storeCode: answer.body.code } : void 0;
|
|
2109
|
+
}
|
|
2110
|
+
function sessionResult(id, status) {
|
|
2111
|
+
const known = status === "open" || status === "counting" || status === "closed";
|
|
2112
|
+
return { session: { id: String(id), ...known ? { status } : {} } };
|
|
2113
|
+
}
|
|
2114
|
+
function createWooRegisterTransport(options) {
|
|
2115
|
+
const { call, retry } = createWooCall(options);
|
|
2116
|
+
const post = (path, body) => call(path, { method: "POST", body });
|
|
2117
|
+
const shared = (answer, id) => {
|
|
2118
|
+
const { status, body } = answer;
|
|
2119
|
+
if (status === 0) return retry(answer, "network");
|
|
2120
|
+
if (status === 401 || status === 403 && body?.code === "rest_forbidden") return { kind: "unauthorized" };
|
|
2121
|
+
if (status === 426) return { kind: "refused", status, reason: typeof body?.code === "string" ? body.code : "update_required" };
|
|
2122
|
+
if (status === 400) return rejected(id, "invalid_payload", body?.message, storeCode(answer));
|
|
2123
|
+
return void 0;
|
|
2124
|
+
};
|
|
2125
|
+
const sendOne = async (envelope, currency) => {
|
|
2126
|
+
const id = envelope.id, digits = minorUnitDigits4(currency);
|
|
2127
|
+
const decimal = (minor2) => wooDecimal(minor2, digits);
|
|
2128
|
+
const answered = (answer, own) => shared(answer, id) ?? own(answer) ?? retry(answer, `status_${answer.status}`);
|
|
2129
|
+
switch (envelope.type) {
|
|
2130
|
+
case "register.session.open": {
|
|
2131
|
+
const p = envelope.payload;
|
|
2132
|
+
return answered(await post("sessions", {
|
|
2133
|
+
id: p.sessionId,
|
|
2134
|
+
register_id: p.registerId,
|
|
2135
|
+
opened_at: p.openedAt,
|
|
2136
|
+
counted_float: decimal(p.countedFloatMinor),
|
|
2137
|
+
...typeof p.expectedFloatMinor === "number" ? { expected_float: decimal(p.expectedFloatMinor) } : {},
|
|
2138
|
+
...typeof p.businessDay === "string" && p.businessDay ? { business_day: p.businessDay } : {}
|
|
2139
|
+
}), (answer) => {
|
|
2140
|
+
const { status, body } = answer;
|
|
2141
|
+
if (status === 201 || status === 200) return { id, status: "applied", register: sessionResult(body?.id, body?.status) };
|
|
2142
|
+
if (status === 409 && body?.code === "wcpos_session_already_open") {
|
|
2143
|
+
return rejected(
|
|
2144
|
+
id,
|
|
2145
|
+
"register_session_already_open",
|
|
2146
|
+
body?.message,
|
|
2147
|
+
{ sessionId: typeof body?.data?.session_id === "string" ? body.data.session_id : p.sessionId }
|
|
2148
|
+
);
|
|
2149
|
+
}
|
|
2150
|
+
if (status === 409) return rejected(id, "register_session_open_refused", body?.message, storeCode(answer));
|
|
2151
|
+
return void 0;
|
|
2152
|
+
});
|
|
2153
|
+
}
|
|
2154
|
+
case "register.session.transition": {
|
|
2155
|
+
const p = envelope.payload;
|
|
2156
|
+
if (p.status === "closed") return { id, status: "applied" };
|
|
2157
|
+
return answered(await post(`sessions/${p.sessionId}/status`, { status: p.status, at: p.at }), (answer) => {
|
|
2158
|
+
if (answer.status === 200) return { id, status: "applied", register: sessionResult(answer.body?.id, answer.body?.status) };
|
|
2159
|
+
if (answer.status === 409) return rejected(id, "register_session_transition_refused", answer.body?.message, storeCode(answer));
|
|
2160
|
+
if (answer.status === 404) return rejected(id, "register_session_unknown", answer.body?.message);
|
|
2161
|
+
return void 0;
|
|
2162
|
+
});
|
|
2163
|
+
}
|
|
2164
|
+
case "register.movement.record":
|
|
2165
|
+
case "register.movement.void": {
|
|
2166
|
+
let body;
|
|
2167
|
+
if (envelope.type === "register.movement.record") {
|
|
2168
|
+
const p = envelope.payload;
|
|
2169
|
+
if (!Number.isSafeInteger(p.amountMinor) || p.amountMinor < 0) {
|
|
2170
|
+
return rejected(id, "invalid_payload", "A cash movement amount must be a whole number of minor units, 0 or more.");
|
|
2171
|
+
}
|
|
2172
|
+
body = { id: p.movementId, session_id: p.sessionId, type: p.type, amount: decimal(p.amountMinor), reason: p.reason, created_at: p.createdAt };
|
|
2173
|
+
} else {
|
|
2174
|
+
const p = envelope.payload;
|
|
2175
|
+
body = { id: p.movementId, session_id: p.sessionId, type: "void", amount: "0", reason: "", voids: p.voids, created_at: p.createdAt };
|
|
2176
|
+
}
|
|
2177
|
+
return answered(await post("movements", body), (answer) => {
|
|
2178
|
+
if (answer.status === 201 || answer.status === 200) return { id, status: "applied" };
|
|
2179
|
+
if (answer.status === 409) return rejected(id, "register_movement_refused", answer.body?.message, storeCode(answer));
|
|
2180
|
+
return void 0;
|
|
2181
|
+
});
|
|
2182
|
+
}
|
|
2183
|
+
case "register.closure.submit": {
|
|
2184
|
+
const p = envelope.payload;
|
|
2185
|
+
const keys = [...Object.keys(p.tillExpected), ...Object.keys(p.counted)];
|
|
2186
|
+
if (keys.some((key) => !TENDER_KEY.test(key)) || Object.values(p.counted).some((minor2) => minor2 < 0)) {
|
|
2187
|
+
return rejected(id, "invalid_payload", "A closure tender must be named with letters, digits, _ or -, and counted at 0 or more.");
|
|
2188
|
+
}
|
|
2189
|
+
const counting = await post(`sessions/${p.sessionId}/status`, { status: "counting", at: p.closedAt });
|
|
2190
|
+
if (counting.status !== 200 && counting.status !== 409) {
|
|
2191
|
+
return answered(counting, (answer) => answer.status === 404 ? rejected(id, "register_session_unknown", answer.body?.message) : void 0);
|
|
2192
|
+
}
|
|
2193
|
+
return answered(await post("closures", {
|
|
2194
|
+
id: p.closureId,
|
|
2195
|
+
session_id: p.sessionId,
|
|
2196
|
+
number: p.number,
|
|
2197
|
+
opened_at: p.openedAt,
|
|
2198
|
+
closed_at: p.closedAt,
|
|
2199
|
+
...typeof p.businessDay === "string" && p.businessDay ? { business_day: p.businessDay } : {},
|
|
2200
|
+
software_version: p.softwareVersion,
|
|
2201
|
+
breakdowns: {},
|
|
2202
|
+
till_expected: wooTenders(p.tillExpected, digits),
|
|
2203
|
+
counted: wooTenders(p.counted, digits),
|
|
2204
|
+
period_sales_total: decimal(p.periodSalesTotalMinor),
|
|
2205
|
+
period_refunds_total: decimal(p.periodRefundsTotalMinor),
|
|
2206
|
+
perpetual_sales_total: decimal(p.perpetualSalesTotalMinor),
|
|
2207
|
+
perpetual_refunds_total: decimal(p.perpetualRefundsTotalMinor),
|
|
2208
|
+
unsynced_total: decimal(p.unsyncedTotalMinor),
|
|
2209
|
+
unsynced_count: p.unsyncedCount
|
|
2210
|
+
}), (answer) => {
|
|
2211
|
+
const { status, body } = answer;
|
|
2212
|
+
if (status === 201 || status === 200) {
|
|
2213
|
+
return { id, status: "applied", register: {
|
|
2214
|
+
session: { id: p.sessionId, status: "closed" },
|
|
2215
|
+
closure: { serverClosureId: String(body?.id), number: body?.number }
|
|
2216
|
+
} };
|
|
2217
|
+
}
|
|
2218
|
+
if (status === 404) return rejected(id, "register_session_unknown", body?.message, storeCode(answer));
|
|
2219
|
+
if (status === 403 && body?.code === "wcpos_override_refused") {
|
|
2220
|
+
const variance = wooSignedMinor(body?.data?.variance, currency);
|
|
2221
|
+
const thresholdMinor = wooThresholdMinor(body?.data?.threshold, currency);
|
|
2222
|
+
return variance === void 0 || typeof body?.data?.variance !== "string" ? rejected(id, "register_approval_invalid", body?.message, { reason: "unknown" }) : rejected(id, "register_approval_required", body?.message, { sessionId: p.sessionId, thresholdMinor, variance: { cash: variance } });
|
|
2223
|
+
}
|
|
2224
|
+
if (status === 409 && body?.code === "wcpos_closure_exists") return rejected(id, "register_closure_exists", body?.message);
|
|
2225
|
+
if (status === 409 && body?.code === "wcpos_closure_number_invalid") return rejected(id, "register_closure_number_invalid", body?.message);
|
|
2226
|
+
if (status === 409) return rejected(id, "register_closure_refused", body?.message, storeCode(answer));
|
|
2227
|
+
return void 0;
|
|
2228
|
+
});
|
|
2229
|
+
}
|
|
2230
|
+
default:
|
|
2231
|
+
return rejected(id, "invalid_payload", `unsupported register command ${String(envelope.type)}`);
|
|
2232
|
+
}
|
|
2233
|
+
};
|
|
2234
|
+
return {
|
|
2235
|
+
async send(batch) {
|
|
2236
|
+
if (batch.length === 0) return { kind: "results", results: [] };
|
|
2237
|
+
const currency = typeof options.currency === "function" ? await options.currency() : options.currency;
|
|
2238
|
+
const results = [];
|
|
2239
|
+
for (const envelope of batch) {
|
|
2240
|
+
const outcome = await sendOne(envelope, currency);
|
|
2241
|
+
if ("kind" in outcome) return results.length ? { kind: "results", results } : outcome;
|
|
2242
|
+
results.push(outcome);
|
|
2243
|
+
}
|
|
2244
|
+
return { kind: "results", results };
|
|
2245
|
+
}
|
|
2246
|
+
};
|
|
2247
|
+
}
|
|
2248
|
+
async function wooApproveSession(context, input) {
|
|
2249
|
+
const post = async (path, body2) => {
|
|
2250
|
+
const response2 = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/${path}`, {
|
|
2251
|
+
method: "POST",
|
|
2252
|
+
headers: { "Content-Type": "application/json", ...context.headers },
|
|
2253
|
+
body: JSON.stringify(body2),
|
|
2254
|
+
signal: context.signal
|
|
2255
|
+
});
|
|
2256
|
+
let json;
|
|
2257
|
+
try {
|
|
2258
|
+
json = await response2.json();
|
|
2259
|
+
} catch {
|
|
2260
|
+
}
|
|
2261
|
+
return { response: response2, body: json };
|
|
2262
|
+
};
|
|
2263
|
+
const fail = (response2) => {
|
|
2264
|
+
throwIfUnauthorized(response2, "approve");
|
|
2265
|
+
throw new Error(`WooCommerce approve: HTTP ${response2.status}`);
|
|
2266
|
+
};
|
|
2267
|
+
const counting = await post(`sessions/${input.sessionId}/status`, { status: "counting", at: (/* @__PURE__ */ new Date()).toISOString() });
|
|
2268
|
+
if (counting.response.status === 404) return { refused: "not_counting" };
|
|
2269
|
+
if (counting.response.status !== 200 && counting.response.status !== 409) fail(counting.response);
|
|
2270
|
+
const counted = wooTenders(input.counted, minorUnitDigits4(input.currency));
|
|
2271
|
+
const { response, body } = await post(
|
|
2272
|
+
`sessions/${input.sessionId}/approve`,
|
|
2273
|
+
{ username: input.credentials.username, password: input.credentials.password, counted }
|
|
2274
|
+
);
|
|
2275
|
+
if (response.status === 403) return { refused: "override_refused" };
|
|
2276
|
+
if (response.status === 404 || response.status === 409) return { refused: "not_counting" };
|
|
2277
|
+
if (response.status !== 200) fail(response);
|
|
2278
|
+
const approved = body?.approved_counted, approvedBy = body?.approved_by;
|
|
2279
|
+
const expected = { cash: 0, ...input.counted };
|
|
2280
|
+
const matches = approved !== null && typeof approved === "object" && !Array.isArray(approved) && Object.keys(approved).length === Object.keys(expected).length && Object.entries(expected).every(([key, minor2]) => wooSignedMinor(approved[key], input.currency) === minor2);
|
|
2281
|
+
if (typeof approvedBy !== "number" || !Number.isInteger(approvedBy) || !matches) return { refused: "override_refused" };
|
|
2282
|
+
return { approval: `wcpos-approve:${input.sessionId}:${approvedBy}`, approvedBy: String(approvedBy) };
|
|
2283
|
+
}
|
|
2284
|
+
|
|
2285
|
+
// src/closures.ts
|
|
2286
|
+
var TENDER_KEY2 = /^[a-zA-Z0-9_-]{1,191}$/;
|
|
2287
|
+
var STORE_TIME = /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})$/;
|
|
2288
|
+
var isRow2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2289
|
+
var unexpected2 = () => new Error("WooCommerce closures: unexpected body");
|
|
2290
|
+
function request(context, path, body) {
|
|
2291
|
+
const init = body ? { method: "POST", headers: { "Content-Type": "application/json", ...context.headers }, body: JSON.stringify(body), signal: context.signal } : { method: "GET", headers: context.headers, signal: context.signal };
|
|
2292
|
+
return (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/${path}`, init);
|
|
2293
|
+
}
|
|
2294
|
+
var errorCode = (response) => response.json().then((body) => typeof body?.code === "string" ? body.code : void 0, () => void 0);
|
|
2295
|
+
function amount(value, currency, field) {
|
|
2296
|
+
const minor2 = wooSignedMinor(value, currency);
|
|
2297
|
+
if (minor2 === void 0) throw new Error(`WooCommerce closures: bad amount ${field}`);
|
|
2298
|
+
return minor2;
|
|
2299
|
+
}
|
|
2300
|
+
function tenders(value, currency, field) {
|
|
2301
|
+
if (Array.isArray(value) && value.length === 0) return {};
|
|
2302
|
+
if (!isRow2(value)) throw new Error(`WooCommerce closures: bad amount ${field}`);
|
|
2303
|
+
return Object.fromEntries(Object.entries(value).map(([tender, text]) => [tender, amount(text, currency, `${field}.${tender}`)]));
|
|
2304
|
+
}
|
|
2305
|
+
var storeTime = (value) => value.replace(STORE_TIME, "$1T$2Z");
|
|
2306
|
+
function toCorrection(row, currency) {
|
|
2307
|
+
if (!isRow2(row) || typeof row.id !== "number" || !isRow2(row.actor) || !isRow2(row.figures)) throw unexpected2();
|
|
2308
|
+
const figures = {};
|
|
2309
|
+
for (const key of ["expected_delta", "counted", "variance"])
|
|
2310
|
+
if (row.figures[key] != null) figures[key] = tenders(row.figures[key], currency, key);
|
|
2311
|
+
for (const key of ["cash_delta", "sales_delta", "refunds_delta"])
|
|
2312
|
+
if (row.figures[key] != null) figures[key] = amount(row.figures[key], currency, key);
|
|
2313
|
+
const approver = isRow2(row.approver) ? { id: String(row.approver.id), name: String(row.approver.name) } : null;
|
|
2314
|
+
return {
|
|
2315
|
+
id: row.id,
|
|
2316
|
+
type: row.type,
|
|
2317
|
+
created_at: row.created_at,
|
|
2318
|
+
actor: { id: String(row.actor.id), name: String(row.actor.name) },
|
|
2319
|
+
approver,
|
|
2320
|
+
reason: row.reason,
|
|
2321
|
+
figures
|
|
2322
|
+
};
|
|
2323
|
+
}
|
|
2324
|
+
function toClosure(row, currency) {
|
|
2325
|
+
if (!isRow2(row) || typeof row.id !== "string" || typeof row.register_id !== "string" || typeof row.session_id !== "string" || typeof row.number !== "number" || typeof row.opened_at_gmt !== "string" || typeof row.closed_at_gmt !== "string") throw unexpected2();
|
|
2326
|
+
const closure = {
|
|
2327
|
+
id: row.id,
|
|
2328
|
+
number: row.number,
|
|
2329
|
+
registerId: row.register_id,
|
|
2330
|
+
sessionId: row.session_id,
|
|
2331
|
+
reason: typeof row.reason === "string" ? row.reason : "end_of_day",
|
|
2332
|
+
openedAt: storeTime(row.opened_at_gmt),
|
|
2333
|
+
closedAt: storeTime(row.closed_at_gmt),
|
|
2334
|
+
printCount: typeof row.print_count === "number" ? row.print_count : 0,
|
|
2335
|
+
unsyncedCount: typeof row.unsynced_count === "number" ? row.unsynced_count : 0
|
|
2336
|
+
};
|
|
2337
|
+
const map = (key) => row[key] == null ? void 0 : tenders(row[key], currency, key);
|
|
2338
|
+
const total = (key) => row[key] == null ? void 0 : amount(row[key], currency, key);
|
|
2339
|
+
const optional = {
|
|
2340
|
+
storeId: typeof row.store_id === "number" ? String(row.store_id) : void 0,
|
|
2341
|
+
businessDay: typeof row.business_day === "string" ? row.business_day : void 0,
|
|
2342
|
+
printedAt: typeof row.printed_at_gmt === "string" ? storeTime(row.printed_at_gmt) : void 0,
|
|
2343
|
+
lastPrintedAt: typeof row.last_printed_at_gmt === "string" ? storeTime(row.last_printed_at_gmt) : void 0,
|
|
2344
|
+
expected: map("expected"),
|
|
2345
|
+
tillExpected: map("till_expected"),
|
|
2346
|
+
counted: map("counted"),
|
|
2347
|
+
variance: map("variance"),
|
|
2348
|
+
periodSalesTotalMinor: total("period_sales_total"),
|
|
2349
|
+
periodRefundsTotalMinor: total("period_refunds_total"),
|
|
2350
|
+
perpetualSalesTotalMinor: total("perpetual_sales_total"),
|
|
2351
|
+
perpetualRefundsTotalMinor: total("perpetual_refunds_total"),
|
|
2352
|
+
unsyncedTotalMinor: total("unsynced_total"),
|
|
2353
|
+
correctionsCount: typeof row.corrections_count === "number" ? row.corrections_count : void 0,
|
|
2354
|
+
corrections: Array.isArray(row.corrections) ? row.corrections.map((correction) => toCorrection(correction, currency)) : void 0
|
|
2355
|
+
};
|
|
2356
|
+
for (const [key, value] of Object.entries(optional)) if (value !== void 0) Object.assign(closure, { [key]: value });
|
|
2357
|
+
return closure;
|
|
2358
|
+
}
|
|
2359
|
+
async function read(context, path) {
|
|
2360
|
+
const response = await request(context, path);
|
|
2361
|
+
throwIfUnauthorized(response, "closures");
|
|
2362
|
+
if (response.status === 404) return null;
|
|
2363
|
+
if (!response.ok) throw new Error(`WooCommerce closures: HTTP ${response.status}`);
|
|
2364
|
+
return response.json().catch(() => {
|
|
2365
|
+
throw unexpected2();
|
|
2366
|
+
});
|
|
2367
|
+
}
|
|
2368
|
+
async function getClosure(context, id, currency) {
|
|
2369
|
+
const body = await read(context, `closures/${encodeURIComponent(id)}`);
|
|
2370
|
+
return body === null ? null : toClosure(body, currency ?? await wooStoreCurrency(context));
|
|
2371
|
+
}
|
|
2372
|
+
var wooClosures = {
|
|
2373
|
+
async list(context, query = {}) {
|
|
2374
|
+
const perPage = Math.min(query.perPage ?? 50, 100);
|
|
2375
|
+
const params = new URLSearchParams();
|
|
2376
|
+
if (query.registerId !== void 0) params.set("register_id", query.registerId);
|
|
2377
|
+
if (query.after !== void 0) params.set("after", query.after);
|
|
2378
|
+
if (query.before !== void 0) params.set("before", query.before);
|
|
2379
|
+
if (query.page !== void 0) params.set("page", String(query.page));
|
|
2380
|
+
params.set("per_page", String(perPage));
|
|
2381
|
+
const body = await read(context, `closures?${params}`);
|
|
2382
|
+
if (body === null) return { items: [], hasMore: false };
|
|
2383
|
+
if (!Array.isArray(body)) throw unexpected2();
|
|
2384
|
+
const currency = await wooStoreCurrency(context);
|
|
2385
|
+
return { items: body.map((row) => toClosure(row, currency)), hasMore: body.length === perPage };
|
|
2386
|
+
},
|
|
2387
|
+
async get(context, id) {
|
|
2388
|
+
return getClosure(context, id);
|
|
2389
|
+
},
|
|
2390
|
+
async last(context, registerId) {
|
|
2391
|
+
const body = await read(context, `closures/last?${new URLSearchParams({ register_id: registerId })}`);
|
|
2392
|
+
return body === null ? null : toClosure(body, await wooStoreCurrency(context));
|
|
2393
|
+
},
|
|
2394
|
+
async recount(context, id, input) {
|
|
2395
|
+
const { correctionId, counted, reason, approval } = input;
|
|
2396
|
+
if (!Object.hasOwn(counted, "cash") || !Object.entries(counted).every(([tender, minor2]) => TENDER_KEY2.test(tender) && Number.isInteger(minor2) && minor2 >= 0)) {
|
|
2397
|
+
throw new Error("WooCommerce closure recount: invalid counted");
|
|
2398
|
+
}
|
|
2399
|
+
const currency = await wooStoreCurrency(context);
|
|
2400
|
+
const digits = minorUnitDigits5(currency);
|
|
2401
|
+
const response = await request(context, `closures/${encodeURIComponent(id)}/recount`, {
|
|
2402
|
+
id: correctionId,
|
|
2403
|
+
counted: Object.fromEntries(Object.entries(counted).map(([tender, minor2]) => [tender, wooDecimal(minor2, digits)])),
|
|
2404
|
+
reason,
|
|
2405
|
+
...approval ? { approval: { username: approval.username, password: approval.password } } : {}
|
|
2406
|
+
});
|
|
2407
|
+
if (response.status === 200 || response.status === 201) {
|
|
2408
|
+
try {
|
|
2409
|
+
const closure = await getClosure(context, id, currency);
|
|
2410
|
+
return closure ? { closure } : { refused: "not_found" };
|
|
2411
|
+
} catch (error) {
|
|
2412
|
+
if (error instanceof ConnectorUnauthorizedError4 && error.status === 403) return {};
|
|
2413
|
+
throw error;
|
|
2414
|
+
}
|
|
2415
|
+
}
|
|
2416
|
+
const code = await errorCode(response);
|
|
2417
|
+
if (response.status === 403 && code === "rest_forbidden" && !approval) return { refused: "approval_required" };
|
|
2418
|
+
if (response.status === 403 && code === "wcpos_recount_approval_invalid") return { refused: "approval_invalid" };
|
|
2419
|
+
if (response.status === 403 && code === "wcpos_recount_approval_forbidden") return { refused: "approval_forbidden" };
|
|
2420
|
+
if (response.status === 404) return { refused: "not_found" };
|
|
2421
|
+
throwIfUnauthorized(response, "closure recount");
|
|
2422
|
+
throw new Error(`WooCommerce closure recount: HTTP ${response.status}${code ? ` ${code}` : ""}`);
|
|
2423
|
+
},
|
|
2424
|
+
async markPrinted(context, id) {
|
|
2425
|
+
const currency = await wooStoreCurrency(context);
|
|
2426
|
+
const response = await request(context, `closures/${encodeURIComponent(id)}/print`, {});
|
|
2427
|
+
if (response.status === 200) return toClosure(await response.json().catch(() => {
|
|
2428
|
+
throw unexpected2();
|
|
2429
|
+
}), currency);
|
|
2430
|
+
const code = await errorCode(response);
|
|
2431
|
+
if (response.status === 403 && code === "rest_forbidden") return { refused: "forbidden" };
|
|
2432
|
+
if (response.status === 404) return { refused: "not_found" };
|
|
2433
|
+
if (response.status === 401) throwIfUnauthorized(response, "closure print");
|
|
2434
|
+
throw new Error(`WooCommerce closure print: HTTP ${response.status}`);
|
|
2435
|
+
}
|
|
2436
|
+
};
|
|
2437
|
+
|
|
1655
2438
|
// src/payment-methods.ts
|
|
1656
|
-
import {
|
|
2439
|
+
import { defaultPaymentMethods } from "@tallyui/core";
|
|
1657
2440
|
var WOO_DEFAULT_ORDER = 999;
|
|
1658
2441
|
var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1659
2442
|
var objectOr = (value) => isObject(value) ? value : {};
|
|
@@ -1677,12 +2460,12 @@ function toCaptureEntry(value) {
|
|
|
1677
2460
|
return { mode: value.mode, provider: stringOr(value.provider, null), hardware: toHardware(value.hardware) };
|
|
1678
2461
|
}
|
|
1679
2462
|
function hasMoneyString(row) {
|
|
1680
|
-
const
|
|
1681
|
-
return typeof
|
|
2463
|
+
const amount2 = objectOr(row.capabilities.amount), rounding = objectOr(objectOr(row.defaults).rounding);
|
|
2464
|
+
return typeof amount2.min === "string" || typeof amount2.max === "string" || typeof rounding.increment === "string";
|
|
1682
2465
|
}
|
|
1683
2466
|
async function storeCurrency(context) {
|
|
1684
2467
|
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/stores`, { method: "GET", headers: context.headers, signal: context.signal }).catch(() => void 0);
|
|
1685
|
-
|
|
2468
|
+
throwIfUnauthorized(response, "stores");
|
|
1686
2469
|
const stores = response?.ok ? await response.json().catch(() => void 0) : void 0;
|
|
1687
2470
|
const currency = Array.isArray(stores) ? objectOr(stores[0]).currency : void 0;
|
|
1688
2471
|
if (typeof currency !== "string") throw new Error("WooCommerce payment methods: no store currency");
|
|
@@ -1698,10 +2481,10 @@ function toRounding(value, currency, id) {
|
|
|
1698
2481
|
}
|
|
1699
2482
|
return { incrementMinor, mode };
|
|
1700
2483
|
}
|
|
1701
|
-
function toAmount(
|
|
1702
|
-
const result = { partial:
|
|
2484
|
+
function toAmount(amount2, currency) {
|
|
2485
|
+
const result = { partial: amount2.partial === true };
|
|
1703
2486
|
for (const [wire, key] of [["min", "minMinor"], ["max", "maxMinor"]]) {
|
|
1704
|
-
const text =
|
|
2487
|
+
const text = amount2[wire];
|
|
1705
2488
|
if (text === void 0) continue;
|
|
1706
2489
|
const minor2 = typeof text === "string" ? wooMinorFromDecimal(text, currency) : void 0;
|
|
1707
2490
|
if (minor2 === void 0) return void 0;
|
|
@@ -1711,8 +2494,8 @@ function toAmount(amount, currency) {
|
|
|
1711
2494
|
}
|
|
1712
2495
|
function toDescriptor(row, currency) {
|
|
1713
2496
|
const caps = row.capabilities, defaults = objectOr(row.defaults);
|
|
1714
|
-
const
|
|
1715
|
-
if (!
|
|
2497
|
+
const amount2 = toAmount(objectOr(caps.amount), currency);
|
|
2498
|
+
if (!amount2) {
|
|
1716
2499
|
console.warn(`WooCommerce payment method ${row.id}: unreadable amount limit; dropped`);
|
|
1717
2500
|
return void 0;
|
|
1718
2501
|
}
|
|
@@ -1726,7 +2509,7 @@ function toDescriptor(row, currency) {
|
|
|
1726
2509
|
...Array.isArray(row.capture.modes) ? { modes: row.capture.modes.filter(isModeEntry).map(toCaptureEntry) } : {}
|
|
1727
2510
|
},
|
|
1728
2511
|
capabilities: {
|
|
1729
|
-
amount,
|
|
2512
|
+
amount: amount2,
|
|
1730
2513
|
change: caps.change === true,
|
|
1731
2514
|
void: caps.void === true,
|
|
1732
2515
|
refunds: { via: stringOr(refunds.via, "none"), partial: refunds.partial === true },
|
|
@@ -1739,7 +2522,7 @@ function toDescriptor(row, currency) {
|
|
|
1739
2522
|
async function wooPaymentMethods(context) {
|
|
1740
2523
|
const response = await (context.fetch ?? globalThis.fetch)(`${context.baseUrl}/payment-methods`, { method: "GET", headers: context.headers, signal: context.signal });
|
|
1741
2524
|
if (response.status === 404) return defaultPaymentMethods();
|
|
1742
|
-
|
|
2525
|
+
throwIfUnauthorized(response, "payment methods");
|
|
1743
2526
|
if (!response.ok) throw new Error(`WooCommerce payment methods: HTTP ${response.status}`);
|
|
1744
2527
|
const body = await response.json();
|
|
1745
2528
|
if (!isObject(body) || !Number.isInteger(body.schema) || typeof body.contract !== "string" || !Array.isArray(body.methods)) {
|
|
@@ -1807,14 +2590,14 @@ async function wooReceiptTemplates(context, kind = "receipt") {
|
|
|
1807
2590
|
}
|
|
1808
2591
|
|
|
1809
2592
|
// package.json
|
|
1810
|
-
var version = "
|
|
2593
|
+
var version = "4.0.1";
|
|
1811
2594
|
|
|
1812
2595
|
// src/index.ts
|
|
1813
|
-
import { ConnectorUnauthorizedError as
|
|
2596
|
+
import { ConnectorUnauthorizedError as ConnectorUnauthorizedError6 } from "@tallyui/core";
|
|
1814
2597
|
function wcposClientPart(part) {
|
|
1815
2598
|
return part.toLowerCase().replace(/[^a-z0-9._-]/g, "").slice(0, 32);
|
|
1816
2599
|
}
|
|
1817
|
-
var WooMissingTokenError = class extends
|
|
2600
|
+
var WooMissingTokenError = class extends ConnectorUnauthorizedError5 {
|
|
1818
2601
|
constructor() {
|
|
1819
2602
|
super("WooCommerce credentials have no WCPOS access token: sign in again", 401);
|
|
1820
2603
|
this.name = "WooMissingTokenError";
|
|
@@ -1854,6 +2637,8 @@ var wooConnectorParts = {
|
|
|
1854
2637
|
storeSettings: wooStoreSettings,
|
|
1855
2638
|
paymentMethods: wooPaymentMethods,
|
|
1856
2639
|
capabilities: readWooCapabilities,
|
|
2640
|
+
listRegisters: wooListRegisters,
|
|
2641
|
+
closures: wooClosures,
|
|
1857
2642
|
receiptTemplates: wooReceiptTemplates,
|
|
1858
2643
|
auth: {
|
|
1859
2644
|
type: "WCPOS token",
|
|
@@ -1879,8 +2664,8 @@ var wooConnectorParts = {
|
|
|
1879
2664
|
return {
|
|
1880
2665
|
Authorization: `Bearer ${credentials.token}`,
|
|
1881
2666
|
"X-WCPOS": "1",
|
|
1882
|
-
// WCPOS 2.0 refuses a POS request below protocol
|
|
1883
|
-
"X-WCPOS-Protocol": "
|
|
2667
|
+
// WCPOS 2.0.4 refuses a POS request below protocol 3 with HTTP 426 (Services/Protocol_Gate.php:15-17).
|
|
2668
|
+
"X-WCPOS-Protocol": "3",
|
|
1884
2669
|
// For WCPOS's consent-gated telemetry only.
|
|
1885
2670
|
"X-WCPOS-Client": `tallyui/${wcposClientPart(version)}`
|
|
1886
2671
|
};
|
|
@@ -1899,7 +2684,7 @@ var wooConnectorParts = {
|
|
|
1899
2684
|
};
|
|
1900
2685
|
var woocommerceConnector = createWooCommerceConnector();
|
|
1901
2686
|
export {
|
|
1902
|
-
|
|
2687
|
+
ConnectorUnauthorizedError6 as ConnectorUnauthorizedError,
|
|
1903
2688
|
WOO_NOTE_ORDER_CREATE_VERSION,
|
|
1904
2689
|
WOO_ORDER_CREATE_VERSION,
|
|
1905
2690
|
WooDateFilterError,
|
|
@@ -1912,12 +2697,14 @@ export {
|
|
|
1912
2697
|
createWooCouponFeed,
|
|
1913
2698
|
createWooCustomers,
|
|
1914
2699
|
createWooOrders,
|
|
2700
|
+
createWooRegisterTransport,
|
|
1915
2701
|
readWooCapabilities,
|
|
1916
2702
|
toCouponDocument,
|
|
1917
2703
|
toWooCustomer,
|
|
1918
2704
|
toWooOrderPayload,
|
|
1919
2705
|
toWooStoreOrder,
|
|
1920
2706
|
wcposClientPart,
|
|
2707
|
+
wooApproveSession,
|
|
1921
2708
|
wooCatalogueReconcile,
|
|
1922
2709
|
wooCouponFingerprint,
|
|
1923
2710
|
wooCouponReconcile,
|