@tallyui/pos 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.js CHANGED
@@ -1,3 +1,9 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
1
7
  // src/logging/logger.ts
2
8
  function createLogger(scope = "root") {
3
9
  const sinks = /* @__PURE__ */ new Map();
@@ -205,6 +211,7 @@ function woocommerceCouponReplay(lines, codes, context, getTaxRates, currency, r
205
211
  }),
206
212
  coupons: result.couponLines.map((coupon, index2) => ({
207
213
  code: codes[index2],
214
+ couponId: context.couponIds.get(codes[index2]),
208
215
  discountMinor: Math.round(woocommerceTax.roundHalfUp(Number(coupon.discount), dp) * factor),
209
216
  discountTaxMinor: Math.round(woocommerceTax.roundHalfUp(Number(coupon.discount_tax), dp) * factor)
210
217
  }))
@@ -677,8 +684,12 @@ function assertDisplayResidue(residue, convertedLines, conversions) {
677
684
  const bound = convertedLines === 0 ? 0 : Math.floor(conversions / 2) + 1;
678
685
  if (Math.abs(residue) > bound) throw new Error(`Display residue ${residue} exceeds its bound of ${bound} (ADR-063)`);
679
686
  }
687
+ function regularUnitPriceMinor(resolved) {
688
+ return resolved.was === void 0 ? resolved.current.amount : resolved.was.taxInclusive === resolved.current.taxInclusive ? resolved.was.amount : void 0;
689
+ }
680
690
  function createOrderBuilder(options) {
681
- const { taxContext, couponContext } = options;
691
+ const { taxContext } = options;
692
+ let { couponContext } = options;
682
693
  const currency = options.currency.toUpperCase();
683
694
  const orderId = options.id ?? uid();
684
695
  const woo = taxContext.rounding?.granularity === "woocommerce" && taxContext.getTaxRates ? taxContext.rounding : void 0;
@@ -941,11 +952,13 @@ function createOrderBuilder(options) {
941
952
  if (unitPrice.currency !== currency) throw new RangeError("Line currency must match " + currency);
942
953
  if (!Number.isInteger(unitPrice.amount)) throw new RangeError("Price must be integer minor units");
943
954
  if (!Number.isInteger(quantity) || quantity < 1) throw new RangeError("Quantity must be an integer >= 1");
955
+ if (input.regularUnitPriceMinor !== void 0 && (!Number.isInteger(input.regularUnitPriceMinor) || input.regularUnitPriceMinor < 0))
956
+ throw new RangeError("Regular price must be integer minor units >= 0");
944
957
  const code = woo || input.taxRates ? void 0 : taxContext.getTaxRateCode?.(input.taxClass);
945
958
  const taxRates = woo ? wooLine(unitPrice.amount * quantity, input.taxClass, unitPrice.taxInclusive ?? taxContext.pricesIncludeTax, input.taxStatus === "none").taxLines : input.taxStatus === "none" ? [{ ...code !== void 0 ? { code } : {}, ratePpm: 0 }] : input.taxRates ?? [{ ...code !== void 0 ? { code } : {}, ratePpm: taxContext.getTaxRatePpm(input.taxClass) }];
946
959
  const taxInclusive = unitPrice.taxInclusive ?? taxContext.pricesIncludeTax;
947
960
  const existing = lineItems.find(
948
- (li) => !input.custom && !li.custom && li.productId === productId && li.variantId === variantId && li.taxInclusive === taxInclusive && (!woo || li.taxClass === input.taxClass && li.taxStatus === "none" === (input.taxStatus === "none")) && li.unitPriceMinor === unitPrice.amount && li.taxLines.length === taxRates.length && li.taxLines.every((tax, index) => tax.code === taxRates[index].code && tax.ratePpm === taxRates[index].ratePpm)
961
+ (li) => !input.custom && !li.custom && li.productId === productId && li.variantId === variantId && li.taxInclusive === taxInclusive && (!woo || li.taxClass === input.taxClass && li.taxStatus === "none" === (input.taxStatus === "none")) && li.regularUnitPriceMinor === input.regularUnitPriceMinor && li.unitPriceMinor === unitPrice.amount && li.taxLines.length === taxRates.length && li.taxLines.every((tax, index) => tax.code === taxRates[index].code && tax.ratePpm === taxRates[index].ratePpm)
949
962
  );
950
963
  if (existing) {
951
964
  lineItems = lineItems.map(
@@ -963,9 +976,11 @@ function createOrderBuilder(options) {
963
976
  ...input.taxStatus === "none" ? { taxStatus: "none" } : {},
964
977
  variantId,
965
978
  name: input.name,
979
+ ...input.attributes && Object.keys(input.attributes).length ? { attributes: { ...input.attributes } } : {},
966
980
  sku: input.sku ?? "",
967
981
  imageUrl: input.imageUrl,
968
982
  unitPriceMinor: unitPrice.amount,
983
+ ...input.regularUnitPriceMinor !== void 0 && !input.custom ? { regularUnitPriceMinor: input.regularUnitPriceMinor } : {},
969
984
  quantity,
970
985
  taxLines: taxRates.map((tax) => ({ ...tax, taxMicros: "0" })),
971
986
  discounts: [],
@@ -1031,8 +1046,9 @@ function createOrderBuilder(options) {
1031
1046
  const variant = opts?.variantId !== void 0 && traits.getVariants ? traits.getVariants(doc, { currency }).find((variant2) => variant2.id === opts.variantId) : void 0;
1032
1047
  if (opts?.variantId !== void 0 && traits.getVariants && !variant)
1033
1048
  throw new Error(`Unknown variant ${opts.variantId} for product ${productId}`);
1034
- const unitPrice = resolvePrice(variant ? variant.prices : traits.getPrices(doc, { currency }), currency)?.current;
1035
- if (!unitPrice) throw new Error("No price in " + currency + " for product " + productId);
1049
+ const resolved = resolvePrice(variant ? variant.prices : traits.getPrices(doc, { currency }), currency);
1050
+ if (!resolved) throw new Error("No price in " + currency + " for product " + productId);
1051
+ const unitPrice = resolved.current, regularPrice = regularUnitPriceMinor(resolved);
1036
1052
  return addLine({
1037
1053
  productId,
1038
1054
  variantId: opts?.variantId,
@@ -1040,6 +1056,7 @@ function createOrderBuilder(options) {
1040
1056
  sku: variant?.sku ?? traits.getSku(doc),
1041
1057
  imageUrl: traits.getImageUrl(doc),
1042
1058
  unitPrice,
1059
+ ...regularPrice !== void 0 ? { regularUnitPriceMinor: regularPrice } : {},
1043
1060
  quantity: opts?.quantity,
1044
1061
  taxClass: traits.getTaxClass?.(doc, opts?.variantId),
1045
1062
  ...traits.getTaxStatus?.(doc, opts?.variantId) === "none" ? { taxStatus: "none" } : {}
@@ -1119,14 +1136,18 @@ function createOrderBuilder(options) {
1119
1136
  note = n;
1120
1137
  emit();
1121
1138
  },
1122
- setCoupons(codes) {
1139
+ setCoupons(codes, context) {
1140
+ const nextContext = context ?? couponContext;
1123
1141
  const normalized = [...new Set(codes.map((code) => code.trim().toLowerCase()))];
1124
- if (normalized.length && !couponContext) throw new Error("Coupon context is required");
1142
+ if (normalized.length && !nextContext) throw new Error("Coupon context is required");
1125
1143
  for (const code of normalized) {
1126
- const config = couponContext.configs.get(code);
1144
+ const config = nextContext.configs.get(code);
1127
1145
  if (!config) throw new RangeError(`Unknown coupon ${code}`);
1128
1146
  if (config.exclude_sale_items) throw new RangeError(`Coupon ${code} excludes sale items`);
1147
+ const couponId = nextContext.couponIds.get(code);
1148
+ if (couponId === void 0 || couponId === "") throw new RangeError(`Coupon ${code} has no id`);
1129
1149
  }
1150
+ if (context) couponContext = context;
1130
1151
  couponCodes = normalized;
1131
1152
  emit();
1132
1153
  },
@@ -1201,6 +1222,7 @@ function netDiscountMinor(line, pricesIncludeTax) {
1201
1222
  return roundMicrosToMinor(BigInt(line.discountMinor) * MICROS_PER_MINOR - taxBefore + taxAfter);
1202
1223
  }
1203
1224
  function contentVersion(order) {
1225
+ if (order.coupons?.length) return 6;
1204
1226
  if (order.fees?.length || order.shipping?.length || order.lines.some((line) => line.custom)) return 5;
1205
1227
  return order.display && order.taxByRate ? 3 : order.lines.reduce((sum, line) => sum + line.discountMinor, 0) > 0 ? 2 : 1;
1206
1228
  }
@@ -1209,6 +1231,7 @@ function toOrderCreateEnvelope(order, deviceId, attempt2 = 1, options) {
1209
1231
  const content = contentVersion(order);
1210
1232
  const cap = options?.maxVersion === void 0 ? order.sentVersion : Math.min(options.maxVersion, order.sentVersion ?? options.maxVersion);
1211
1233
  if (content === 5 && cap !== void 0 && cap < 5) throw new UnsupportedOrderVersionError(5, cap);
1234
+ if (content === 6 && cap !== void 0 && cap < 6) throw new UnsupportedOrderVersionError(6, cap);
1212
1235
  if (grossMinor > 0 && cap !== void 0 && cap < 2) throw new UnsupportedOrderVersionError(2, cap);
1213
1236
  const version = content === 3 && cap !== void 0 && cap >= 4 ? 4 : Math.min(content, cap ?? content);
1214
1237
  const lineDiscounts = order.lines.map((line) => version >= 4 ? netDiscountMinor(line, order.pricesIncludeTax) : line.discountMinor);
@@ -1217,7 +1240,7 @@ function toOrderCreateEnvelope(order, deviceId, attempt2 = 1, options) {
1217
1240
  const id2 = order.customer?.id;
1218
1241
  const customerId = typeof id2 === "string" && id2.length > 0 && id2.length <= 64 ? id2 : void 0;
1219
1242
  const sessionId = order.sessionId ?? order.lateSessionId;
1220
- const { fees: _fees, shipping: _shipping, ...storedDisplay } = { ...order.display };
1243
+ const { fees: _fees, shipping: _shipping, coupons: _coupons, ...storedDisplay } = { ...order.display };
1221
1244
  return {
1222
1245
  id: order.commandId,
1223
1246
  type: "order.create",
@@ -1237,9 +1260,11 @@ function toOrderCreateEnvelope(order, deviceId, attempt2 = 1, options) {
1237
1260
  quantity: line.quantity,
1238
1261
  unitPriceMinor: line.unitPriceMinor,
1239
1262
  ...line.taxInclusive !== void 0 ? { taxInclusive: line.taxInclusive } : {},
1240
- ...lineDiscounts[i] > 0 ? { discountMinor: lineDiscounts[i] } : {}
1263
+ ...lineDiscounts[i] > 0 ? { discountMinor: lineDiscounts[i] } : {},
1264
+ ...version === 6 && line.regularUnitPriceMinor !== void 0 ? { regularUnitPriceMinor: line.regularUnitPriceMinor } : {},
1265
+ ...version === 6 && line.attributes && Object.keys(line.attributes).length ? { attributes: { ...line.attributes } } : {}
1241
1266
  })),
1242
- ...version === 5 && order.fees?.length ? { fees: order.fees.map((fee) => ({
1267
+ ...version >= 5 && order.fees?.length ? { fees: order.fees.map((fee) => ({
1243
1268
  clientFeeId: fee.id,
1244
1269
  name: fee.name,
1245
1270
  amountMinor: fee.amountMinor,
@@ -1247,7 +1272,7 @@ function toOrderCreateEnvelope(order, deviceId, attempt2 = 1, options) {
1247
1272
  ...fee.taxClass !== void 0 ? { taxClass: fee.taxClass } : {},
1248
1273
  taxMinor: roundMicrosToMinor(BigInt(fee.taxMicros))
1249
1274
  })) } : {},
1250
- ...version === 5 && order.shipping?.length ? { shipping: order.shipping.map((charge) => ({
1275
+ ...version >= 5 && order.shipping?.length ? { shipping: order.shipping.map((charge) => ({
1251
1276
  clientShippingId: charge.id,
1252
1277
  name: charge.name,
1253
1278
  ...charge.methodId !== void 0 ? { methodId: charge.methodId } : {},
@@ -1256,6 +1281,12 @@ function toOrderCreateEnvelope(order, deviceId, attempt2 = 1, options) {
1256
1281
  ...charge.taxClass !== void 0 ? { taxClass: charge.taxClass } : {},
1257
1282
  taxMinor: roundMicrosToMinor(BigInt(charge.taxMicros))
1258
1283
  })) } : {},
1284
+ ...version === 6 ? { coupons: order.coupons.map(({ code, couponId, discountMinor: discountMinor2, discountTaxMinor }) => ({
1285
+ code,
1286
+ couponId,
1287
+ discountMinor: discountMinor2,
1288
+ discountTaxMinor
1289
+ })) } : {},
1259
1290
  payments: order.payments.map((payment) => ({
1260
1291
  clientPaymentId: payment.id,
1261
1292
  method: payment.method,
@@ -1276,8 +1307,9 @@ function toOrderCreateEnvelope(order, deviceId, attempt2 = 1, options) {
1276
1307
  amountMinor,
1277
1308
  discounts
1278
1309
  })),
1279
- ...version === 5 && order.display.fees ? { fees: order.display.fees.map(({ id: id3, amountMinor }) => ({ clientFeeId: id3, amountMinor })) } : {},
1280
- ...version === 5 && order.display.shipping ? { shipping: order.display.shipping.map(({ id: id3, amountMinor }) => ({ clientShippingId: id3, amountMinor })) } : {}
1310
+ ...version >= 5 && order.display.fees ? { fees: order.display.fees.map(({ id: id3, amountMinor }) => ({ clientFeeId: id3, amountMinor })) } : {},
1311
+ ...version >= 5 && order.display.shipping ? { shipping: order.display.shipping.map(({ id: id3, amountMinor }) => ({ clientShippingId: id3, amountMinor })) } : {},
1312
+ ...version === 6 && order.display.coupons ? { coupons: order.display.coupons.map(({ code, amountMinor }) => ({ code, amountMinor })) } : {}
1281
1313
  },
1282
1314
  taxByRate: order.taxByRate.map(({ ratePpm, code, netMinor, amountMinor, grossMinor: grossMinor2 }) => ({
1283
1315
  ratePpm,
@@ -1311,10 +1343,9 @@ var orderDraftSchema = {
1311
1343
  required: ["id", "data"]
1312
1344
  };
1313
1345
  async function writeOrderDraft(drafts, snapshot) {
1314
- const { coupons: _coupons, ...draft } = snapshot;
1315
1346
  await drafts.upsert({
1316
1347
  id: snapshot.id,
1317
- data: JSON.stringify(draft),
1348
+ data: JSON.stringify(snapshot),
1318
1349
  customerName: snapshot.customer?.name ?? "",
1319
1350
  itemCount: snapshot.lineItems.length,
1320
1351
  total: snapshot.totalMinor,
@@ -1343,9 +1374,11 @@ function restoreOrderDraft(saved, options) {
1343
1374
  ...taxContext.rounding?.granularity === "woocommerce" ? { taxClass: line.taxClass } : {},
1344
1375
  variantId: line.variantId,
1345
1376
  name: line.name,
1377
+ ...line.attributes !== void 0 ? { attributes: line.attributes } : {},
1346
1378
  sku: line.sku,
1347
1379
  imageUrl: line.imageUrl,
1348
1380
  unitPrice: { amount: line.unitPriceMinor, currency, taxInclusive: line.taxInclusive },
1381
+ ...line.regularUnitPriceMinor !== void 0 ? { regularUnitPriceMinor: line.regularUnitPriceMinor } : {},
1349
1382
  quantity: line.quantity,
1350
1383
  taxRates: line.taxLines.map(({ code, ratePpm }) => ({ code, ratePpm }))
1351
1384
  });
@@ -1512,6 +1545,7 @@ function buildReceiptData(order, config) {
1512
1545
  },
1513
1546
  lineItems: order.lineItems.map((li, index) => ({
1514
1547
  name: li.name,
1548
+ ...li.attributes && Object.keys(li.attributes).length ? { attributes: { ...li.attributes } } : {},
1515
1549
  sku: li.sku,
1516
1550
  quantity: li.quantity,
1517
1551
  unitPriceMinor: li.unitPriceMinor,
@@ -1836,6 +1870,9 @@ function finalizeOrder(order, options = {}) {
1836
1870
  if ((order.fees?.length || order.shipping?.length || order.lineItems.some((line) => line.custom)) && (options.capabilities?.orderCreate ?? 1) < 5) {
1837
1871
  throw new Error("finalize: fees, shipping and custom lines need the store to accept order.create version 5; update the store's TallyUI plugin");
1838
1872
  }
1873
+ if (order.coupons?.length && (options.capabilities?.orderCreate ?? 1) < 6) {
1874
+ throw new Error("finalize: coupons need the store to accept order.create version 6; update the store's TallyUI plugin");
1875
+ }
1839
1876
  if (!order.lineItems.length) throw new Error("finalize: no lines");
1840
1877
  if (order.discountMinor < 0 || order.lineItems.some((line) => line.discountMinor < 0) || order.discounts.some((d) => d.amountMinor < 0)) {
1841
1878
  throw new Error("finalize: negative discount");
@@ -1888,6 +1925,8 @@ function finalizeOrder(order, options = {}) {
1888
1925
  sku: line.sku,
1889
1926
  quantity: line.quantity,
1890
1927
  unitPriceMinor: line.unitPriceMinor,
1928
+ ...line.attributes && Object.keys(line.attributes).length ? { attributes: { ...line.attributes } } : {},
1929
+ ...line.regularUnitPriceMinor !== void 0 ? { regularUnitPriceMinor: line.regularUnitPriceMinor } : {},
1891
1930
  discountMinor: line.discountMinor,
1892
1931
  netMinor: line.netMinor,
1893
1932
  ...order.taxRounding?.granularity === "woocommerce" ? { netMicros: line.netMicros } : {},
@@ -1983,6 +2022,7 @@ function finalizeOrder(order, options = {}) {
1983
2022
  taxMinor: order.taxMinor,
1984
2023
  totalMinor: order.totalMinor,
1985
2024
  taxRounding,
2025
+ ...order.coupons?.length ? { coupons: order.coupons.map(({ code, couponId, discountMinor, discountTaxMinor }) => ({ code, couponId, discountMinor, discountTaxMinor })) } : {},
1986
2026
  ...display && taxByRate ? { display, taxByRate } : {},
1987
2027
  customer: order.customer ? {
1988
2028
  id: order.customer.id,
@@ -2000,7 +2040,7 @@ function finalizeOrder(order, options = {}) {
2000
2040
  import { addRxPlugin } from "rxdb";
2001
2041
  import { RxDBMigrationSchemaPlugin } from "rxdb/plugins/migration-schema";
2002
2042
  var posOrderSchema = {
2003
- version: 8,
2043
+ version: 9,
2004
2044
  primaryKey: "id",
2005
2045
  type: "object",
2006
2046
  additionalProperties: false,
@@ -2010,6 +2050,7 @@ var posOrderSchema = {
2010
2050
  commandId: { type: "string", maxLength: 36 },
2011
2051
  createdAt: { type: "string", maxLength: 40 },
2012
2052
  updatedAt: { type: "string" },
2053
+ reopenedAt: { type: "string", maxLength: 40 },
2013
2054
  currency: { type: "string" },
2014
2055
  pricesIncludeTax: { type: "boolean" },
2015
2056
  subtotalMinor: { type: "integer" },
@@ -2021,6 +2062,12 @@ var posOrderSchema = {
2021
2062
  registerId: { type: "string" },
2022
2063
  sessionId: { type: "string", maxLength: 36 },
2023
2064
  cashierRef: { type: "string" },
2065
+ coupons: { type: "array", items: { type: "object", additionalProperties: false, properties: {
2066
+ code: { type: "string", minLength: 1, maxLength: 255 },
2067
+ couponId: { type: "string", minLength: 1, maxLength: 64 },
2068
+ discountMinor: { type: "integer", minimum: 0 },
2069
+ discountTaxMinor: { type: "integer", minimum: 0 }
2070
+ }, required: ["code", "couponId", "discountMinor", "discountTaxMinor"] } },
2024
2071
  lines: { type: "array", items: {
2025
2072
  type: "object",
2026
2073
  properties: {
@@ -2040,6 +2087,8 @@ var posOrderSchema = {
2040
2087
  unitPriceMinor: { type: "integer" },
2041
2088
  discountMinor: { type: "integer" },
2042
2089
  netMinor: { type: "integer" },
2090
+ attributes: { type: "object", additionalProperties: { type: "string" } },
2091
+ regularUnitPriceMinor: { type: "integer" },
2043
2092
  netMicros: { type: "string", pattern: "^-?[0-9]{1,24}$", maxLength: 25 },
2044
2093
  taxLines: { type: "array", items: {
2045
2094
  type: "object",
@@ -2127,8 +2176,8 @@ var posOrderSchema = {
2127
2176
  roundAtSubtotal: { type: "boolean" },
2128
2177
  mode: { type: "string", enum: ["half_away_from_zero", "half_up"] }
2129
2178
  }, required: ["granularity"] },
2130
- sentVersion: { type: "integer", minimum: 1, maximum: 5 },
2131
- downgradedFrom: { type: "integer", minimum: 1, maximum: 5 },
2179
+ sentVersion: { type: "integer", minimum: 1, maximum: 6 },
2180
+ downgradedFrom: { type: "integer", minimum: 1, maximum: 6 },
2132
2181
  // The nested objects are closed too: loosening a schema later is free, tightening one costs a migration.
2133
2182
  display: { type: "object", additionalProperties: false, properties: {
2134
2183
  currency: { type: "string" },
@@ -2139,6 +2188,10 @@ var posOrderSchema = {
2139
2188
  taxMinor: { type: "integer" },
2140
2189
  totalMinor: { type: "integer" },
2141
2190
  orderDiscountMinor: { type: "integer" },
2191
+ coupons: { type: "array", items: { type: "object", additionalProperties: false, properties: {
2192
+ code: { type: "string", minLength: 1, maxLength: 255 },
2193
+ amountMinor: { type: "integer" }
2194
+ }, required: ["code", "amountMinor"] } },
2142
2195
  fees: { type: "array", items: { type: "object", additionalProperties: false, properties: {
2143
2196
  id: { type: "string", maxLength: 36 },
2144
2197
  name: { type: "string", minLength: 1, maxLength: 255 },
@@ -2211,7 +2264,7 @@ function posOrderCollection() {
2211
2264
  };
2212
2265
  return {
2213
2266
  schema: posOrderSchema,
2214
- migrationStrategies: { 1: identity2, 2: identity2, 3: identity2, 4: identity2, 5: recordSent, 6: recordRounding, 7: identity2, 8: identity2 }
2267
+ migrationStrategies: { 1: identity2, 2: identity2, 3: identity2, 4: identity2, 5: recordSent, 6: recordRounding, 7: identity2, 8: identity2, 9: identity2 }
2215
2268
  };
2216
2269
  }
2217
2270
 
@@ -2411,47 +2464,20 @@ function getDeviceId(storage, key) {
2411
2464
 
2412
2465
  // src/pos-order/needs-attention.ts
2413
2466
  import { knownWarnings } from "@tallyui/core";
2414
- function needsAttention(orders, options = {}) {
2415
- return orders.filter((order) => order.syncStatus === "rejected" || (order.localWarnings?.length ?? 0) > 0 || order.syncStatus === "applied" && knownWarnings(order.warnings).some((warning) => warning.code !== "register_session_unknown") || order.lateSessionId !== void 0 || order.syncStatus === "pending" && options.stuckCommandIds?.includes(order.commandId) === true).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
2416
- }
2417
-
2418
- // src/pos-order/same-sale.ts
2419
- function sameSale(stored, retried) {
2420
- return stored.totalMinor === retried.totalMinor && stored.currency === retried.currency && stored.lines.length === retried.lines.length && stored.lines.every((line, i) => {
2421
- const other = retried.lines[i];
2422
- return line.id === other.id && line.quantity === other.quantity && line.netMinor === other.netMinor;
2423
- }) && stored.payments.length === retried.payments.length && stored.payments.every((payment, i) => payment.method === retried.payments[i].method && payment.amountMinor === retried.payments[i].amountMinor);
2424
- }
2425
- var OrderContentMismatchError = class extends Error {
2426
- constructor(orderId) {
2427
- super(`Order ${orderId} is already stored with different content`);
2428
- this.orderId = orderId;
2429
- this.name = "OrderContentMismatchError";
2430
- }
2431
- };
2432
2467
 
2433
- // src/register/movement-input.ts
2434
- var SERVER_DECIMAL = /^\d+(?:\.\d+)?$/;
2435
- var MAX_INTEGER_DIGITS = 15;
2436
- var MAX_REASON_LENGTH = 500;
2437
- var KEYPAD_DECIMAL_COMMA = /^(\d+),(\d{1,2})$/;
2438
- function normalizeAmount(raw) {
2439
- const trimmed = raw.trim();
2440
- const dotted = trimmed.replace(KEYPAD_DECIMAL_COMMA, "$1.$2");
2441
- return dotted.replace(/^\./, "0.").replace(/\.$/, "");
2468
+ // src/pos-order/reopened.ts
2469
+ function isReopened(order) {
2470
+ return order.syncStatus === "rejected" && order.reopenedAt !== void 0;
2442
2471
  }
2443
- function isServerDecimal(value) {
2444
- if (!SERVER_DECIMAL.test(value)) return false;
2445
- return value.split(".")[0].replace(/^0+/, "").length <= MAX_INTEGER_DIGITS;
2472
+ function replacedOrderIds(orders) {
2473
+ const predecessors = new Set(orders.filter((order) => order.saleId !== order.id).map((order) => order.saleId));
2474
+ return new Set(orders.filter((order) => order.syncStatus === "rejected" && predecessors.has(order.id)).map((order) => order.id));
2446
2475
  }
2447
- function movementFieldError(input) {
2448
- if (input.type !== "no_sale") {
2449
- const amount = normalizeAmount(input.amount);
2450
- if (!isServerDecimal(amount) || Number(amount) <= 0) return "amount";
2451
- }
2452
- const reason = input.reason.trim();
2453
- if (!reason || reason.length > MAX_REASON_LENGTH) return "reason";
2454
- return null;
2476
+
2477
+ // src/pos-order/needs-attention.ts
2478
+ function needsAttention(orders, options = {}) {
2479
+ const replaced = replacedOrderIds(orders);
2480
+ return orders.filter((order) => order.syncStatus === "rejected" || (order.localWarnings?.length ?? 0) > 0 || order.syncStatus === "applied" && knownWarnings(order.warnings).some((warning) => warning.code !== "register_session_unknown") || order.lateSessionId !== void 0 || order.syncStatus === "pending" && options.stuckCommandIds?.includes(order.commandId) === true).filter((order) => !replaced.has(order.id)).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
2455
2481
  }
2456
2482
 
2457
2483
  // src/register/expected.ts
@@ -2489,190 +2515,6 @@ function deriveExpected({
2489
2515
  return totals;
2490
2516
  }
2491
2517
 
2492
- // src/register/register-count.helpers.ts
2493
- function parseMinor(text2, exponent) {
2494
- const [whole, fraction = ""] = text2.trim().split(".");
2495
- if (fraction.length > exponent) return NaN;
2496
- return Number(whole || "0") * 10 ** exponent + Number(fraction.padEnd(exponent, "0") || "0");
2497
- }
2498
- var validAmount = (value, exponent) => /^(?:\d+\.?\d*|\.\d+)$/.test(value) && Number.isFinite(Number(value)) && Number.isSafeInteger(parseMinor(value, exponent));
2499
- var countVariance = (countedMinor, expectedMinor) => countedMinor - expectedMinor;
2500
- var overThreshold = (variance, thresholdMinor) => thresholdMinor != null && Math.abs(variance) > thresholdMinor;
2501
- var closeNeedsApproval = (countedCashMinor, expectedCashMinor, thresholdMinor) => overThreshold(countVariance(countedCashMinor, expectedCashMinor), thresholdMinor);
2502
- var denominationTotal = (pieces) => Object.entries(pieces).reduce((sum, [value, count]) => sum + Number(value) * count, 0);
2503
- function varianceText(variance, exponent, format2, t) {
2504
- if (!variance) return t("register.exact");
2505
- return `${format2(Math.abs(variance) / 10 ** exponent)} ${t(variance < 0 ? "register.short" : "register.over")}`;
2506
- }
2507
-
2508
- // src/register/register-count.denominations.ts
2509
- var coinsMinor = [200, 100, 50, 20, 10, 5, 2, 1];
2510
- var denominations = {
2511
- GBP: [5e3, 2e3, 1e3, 500, ...coinsMinor],
2512
- EUR: [5e4, 2e4, 1e4, 5e3, 2e3, 1e3, 500, ...coinsMinor],
2513
- USD: [1e4, 5e3, 2e3, 1e3, 500, 100, 25, 10, 5, 1],
2514
- default: [1e4, 5e3, 2e3, 1e3, 500, 200, 100, 50, 25, 10, 5, 1]
2515
- };
2516
-
2517
- // src/register/schemas.ts
2518
- import { addRxPlugin as addRxPlugin2 } from "rxdb";
2519
- import { RxDBLocalDocumentsPlugin } from "rxdb/plugins/local-documents";
2520
- import { RxDBMigrationSchemaPlugin as RxDBMigrationSchemaPlugin2 } from "rxdb/plugins/migration-schema";
2521
- var id = { type: "string", maxLength: 36 };
2522
- var text = { type: "string" };
2523
- var nullableText = { type: ["string", "null"] };
2524
- var minor = { type: "integer" };
2525
- var nullableMinor = { type: ["integer", "null"] };
2526
- var tenders = { type: "object", additionalProperties: minor };
2527
- var registerSessionSchema = {
2528
- title: "Register sessions",
2529
- version: 1,
2530
- primaryKey: "id",
2531
- type: "object",
2532
- additionalProperties: false,
2533
- properties: {
2534
- id,
2535
- register_id: id,
2536
- store_key: nullableText,
2537
- status: { type: "string", maxLength: 20 },
2538
- server_session_id: { ...nullableText, default: null },
2539
- business_day: { type: "string", maxLength: 10 },
2540
- opened_at_gmt: text,
2541
- opened_by: nullableText,
2542
- expected_float_minor: nullableMinor,
2543
- counted_float_minor: minor,
2544
- opening_variance_minor: nullableMinor,
2545
- counting_started_at_gmt: nullableText,
2546
- closed_at_gmt: nullableText,
2547
- closed_by: nullableText,
2548
- approval_required: { type: "boolean", default: false },
2549
- approved_by: nullableText,
2550
- counted: { type: ["object", "null"], additionalProperties: minor },
2551
- closure_id: nullableText,
2552
- pending_status: { ...nullableText, default: null },
2553
- server_status: { ...nullableText, default: null },
2554
- status_at: { ...nullableText, default: null },
2555
- approver_token: { ...nullableText, default: null },
2556
- server_expected: { type: ["object", "null"], additionalProperties: minor, default: null },
2557
- server_sales_count: { type: ["integer", "null"], default: null }
2558
- },
2559
- required: ["id", "register_id", "status", "opened_at_gmt", "counted_float_minor"],
2560
- indexes: [["register_id", "status"]]
2561
- };
2562
- function registerSessionCreator() {
2563
- addRxPlugin2(RxDBLocalDocumentsPlugin);
2564
- addRxPlugin2(RxDBMigrationSchemaPlugin2);
2565
- return { schema: registerSessionSchema, localDocuments: true, migrationStrategies: { 1: (doc) => {
2566
- doc.server_session_id ??= null;
2567
- return doc;
2568
- } } };
2569
- }
2570
- function registerSessionCollection() {
2571
- throw new Error("registerSessionCollection() is gone: open register_sessions with await addRegisterSessionCollection(db). Adding it with addCollections would run RxDB's own migration of schema version 1, which can lose sessions (ADR-078, #371).");
2572
- }
2573
- var cashMovementSchema = {
2574
- title: "Cash movements",
2575
- version: 0,
2576
- primaryKey: "id",
2577
- type: "object",
2578
- additionalProperties: false,
2579
- properties: {
2580
- id,
2581
- session_id: id,
2582
- type: { type: "string", enum: ["paid_in", "paid_out", "no_sale", "void"] },
2583
- amountMinor: minor,
2584
- reason: text,
2585
- created_at_gmt: text,
2586
- created_by: nullableText,
2587
- voids: nullableText,
2588
- voided_by: nullableText
2589
- },
2590
- required: ["id", "session_id", "type", "amountMinor", "reason", "created_at_gmt"],
2591
- indexes: [["session_id"]]
2592
- };
2593
- var closureSchema = {
2594
- title: "Register closures",
2595
- version: 0,
2596
- primaryKey: "id",
2597
- type: "object",
2598
- additionalProperties: false,
2599
- properties: {
2600
- id,
2601
- session_id: id,
2602
- register_id: id,
2603
- store_key: nullableText,
2604
- business_day: { type: "string", maxLength: 10 },
2605
- closed_by: nullableText,
2606
- corrections_count: { type: "integer" },
2607
- number: { type: "integer" },
2608
- opened_at: text,
2609
- closed_at: text,
2610
- till_expected: tenders,
2611
- expected: tenders,
2612
- counted: tenders,
2613
- variance: tenders,
2614
- period_sales_total_minor: minor,
2615
- period_refunds_total_minor: minor,
2616
- perpetual_sales_total_minor: minor,
2617
- perpetual_refunds_total_minor: minor,
2618
- unsynced_count: { type: "integer" },
2619
- unsynced_total_minor: minor,
2620
- software_version: text,
2621
- breakdowns: { type: "object", additionalProperties: true },
2622
- order_ids: { type: "array", items: text },
2623
- movement_ids: { type: "array", items: text },
2624
- server_closure_id: { ...nullableText, default: null },
2625
- printed_at: { ...nullableText, default: null },
2626
- print_count: { type: "integer", default: 0 },
2627
- number_retried: { type: "boolean", default: false }
2628
- },
2629
- required: [
2630
- "id",
2631
- "session_id",
2632
- "register_id",
2633
- "number",
2634
- "opened_at",
2635
- "closed_at",
2636
- "till_expected",
2637
- "expected",
2638
- "counted",
2639
- "variance",
2640
- "period_sales_total_minor",
2641
- "period_refunds_total_minor",
2642
- "perpetual_sales_total_minor",
2643
- "perpetual_refunds_total_minor",
2644
- "unsynced_count",
2645
- "unsynced_total_minor",
2646
- "software_version",
2647
- "breakdowns",
2648
- "order_ids",
2649
- "movement_ids",
2650
- "print_count"
2651
- ],
2652
- indexes: [["register_id"], ["session_id"]]
2653
- };
2654
-
2655
- // src/register/open.ts
2656
- var registerSessionsLogger = createLogger("register-sessions");
2657
- var REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS = 1e4;
2658
- var RegisterSessionOpenClosedError = class extends Error {
2659
- constructor(databaseName) {
2660
- super(`addRegisterSessionCollection: database ${databaseName} closed during the open; reopen it and open register_sessions again`);
2661
- this.databaseName = databaseName;
2662
- this.name = "RegisterSessionOpenClosedError";
2663
- }
2664
- code = "REGISTER_SESSION_OPEN_CLOSED";
2665
- };
2666
- function addRegisterSessionCollection(db, closeWaitMs = REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS) {
2667
- return openMigratedCollection(db, {
2668
- name: "register_sessions",
2669
- creator: registerSessionCreator,
2670
- label: "addRegisterSessionCollection",
2671
- logger: registerSessionsLogger,
2672
- closedError: (name) => new RegisterSessionOpenClosedError(name)
2673
- }, closeWaitMs);
2674
- }
2675
-
2676
2518
  // src/register/register-document.ts
2677
2519
  import { map as map4 } from "rxjs";
2678
2520
  var REGISTER = "register";
@@ -2899,15 +2741,55 @@ function recordRegisterFact(fact) {
2899
2741
  }
2900
2742
  }
2901
2743
 
2902
- // src/register/session-store.ts
2903
- var RegisterSessionRequiredError = class extends Error {
2904
- constructor() {
2905
- super("register_session_not_open");
2906
- this.name = "RegisterSessionRequiredError";
2744
+ // src/register/movement-input.ts
2745
+ var SERVER_DECIMAL = /^\d+(?:\.\d+)?$/;
2746
+ var MAX_INTEGER_DIGITS = 15;
2747
+ var MAX_REASON_LENGTH = 500;
2748
+ var KEYPAD_DECIMAL_COMMA = /^(\d+),(\d{1,2})$/;
2749
+ function normalizeAmount(raw) {
2750
+ const trimmed = raw.trim();
2751
+ const dotted = trimmed.replace(KEYPAD_DECIMAL_COMMA, "$1.$2");
2752
+ return dotted.replace(/^\./, "0.").replace(/\.$/, "");
2753
+ }
2754
+ function isServerDecimal(value) {
2755
+ if (!SERVER_DECIMAL.test(value)) return false;
2756
+ return value.split(".")[0].replace(/^0+/, "").length <= MAX_INTEGER_DIGITS;
2757
+ }
2758
+ function movementFieldError(input) {
2759
+ if (input.type !== "no_sale") {
2760
+ const amount = normalizeAmount(input.amount);
2761
+ if (!isServerDecimal(amount) || Number(amount) <= 0) return "amount";
2907
2762
  }
2908
- };
2909
- var RegisterSessionClosedError = class extends Error {
2910
- constructor() {
2763
+ const reason = input.reason.trim();
2764
+ if (!reason || reason.length > MAX_REASON_LENGTH) return "reason";
2765
+ return null;
2766
+ }
2767
+
2768
+ // src/register/register-count.helpers.ts
2769
+ function parseMinor(text2, exponent) {
2770
+ const [whole, fraction = ""] = text2.trim().split(".");
2771
+ if (fraction.length > exponent) return NaN;
2772
+ return Number(whole || "0") * 10 ** exponent + Number(fraction.padEnd(exponent, "0") || "0");
2773
+ }
2774
+ var validAmount = (value, exponent) => /^(?:\d+\.?\d*|\.\d+)$/.test(value) && Number.isFinite(Number(value)) && Number.isSafeInteger(parseMinor(value, exponent));
2775
+ var countVariance = (countedMinor, expectedMinor) => countedMinor - expectedMinor;
2776
+ var overThreshold = (variance, thresholdMinor) => thresholdMinor != null && Math.abs(variance) > thresholdMinor;
2777
+ var closeNeedsApproval = (countedCashMinor, expectedCashMinor, thresholdMinor) => overThreshold(countVariance(countedCashMinor, expectedCashMinor), thresholdMinor);
2778
+ var denominationTotal = (pieces) => Object.entries(pieces).reduce((sum, [value, count]) => sum + Number(value) * count, 0);
2779
+ function varianceText(variance, exponent, format2, t) {
2780
+ if (!variance) return t("register.exact");
2781
+ return `${format2(Math.abs(variance) / 10 ** exponent)} ${t(variance < 0 ? "register.short" : "register.over")}`;
2782
+ }
2783
+
2784
+ // src/register/session-store.ts
2785
+ var RegisterSessionRequiredError = class extends Error {
2786
+ constructor() {
2787
+ super("register_session_not_open");
2788
+ this.name = "RegisterSessionRequiredError";
2789
+ }
2790
+ };
2791
+ var RegisterSessionClosedError = class extends Error {
2792
+ constructor() {
2911
2793
  super("register_session_closed");
2912
2794
  this.name = "RegisterSessionClosedError";
2913
2795
  }
@@ -3173,7 +3055,8 @@ async function writeClosure({
3173
3055
  });
3174
3056
  return existing;
3175
3057
  }
3176
- const bound = orders.filter((order) => order.sessionId === session.id);
3058
+ const replaced = replacedOrderIds(orders);
3059
+ const bound = orders.filter((order) => order.sessionId === session.id && !replaced.has(order.id));
3177
3060
  const countedRefunds = (refunds ?? []).filter((refund) => refund.status === "applied" && refund.sessionId === session.id);
3178
3061
  const rows = bound.flatMap(
3179
3062
  (order) => order.payments.map((payment) => ({
@@ -3306,6 +3189,279 @@ async function writeClosure({
3306
3189
  return row;
3307
3190
  }
3308
3191
 
3192
+ // src/pos-order/reopen.ts
3193
+ var REOPENABLE_CODES = ["coupon_invalid", "total_mismatch"];
3194
+ var ReopenRefusedOrderError = class extends Error {
3195
+ constructor(orderId, reason) {
3196
+ super(`Cannot reopen order ${orderId}: ${reason}`);
3197
+ this.orderId = orderId;
3198
+ this.reason = reason;
3199
+ this.name = "ReopenRefusedOrderError";
3200
+ }
3201
+ };
3202
+ async function reopenRefusedOrder(orderId, deps) {
3203
+ const [order] = await readFresh(deps.orders, { selector: { id: orderId } });
3204
+ if (!order) throw new ReopenRefusedOrderError(orderId, "not_found");
3205
+ if (order.syncStatus !== "rejected") throw new ReopenRefusedOrderError(orderId, "not_rejected");
3206
+ if (!REOPENABLE_CODES.includes(order.error?.code ?? "")) throw new ReopenRefusedOrderError(orderId, "code_not_reopenable");
3207
+ const successors = await readFresh(deps.orders, { selector: { saleId: orderId } });
3208
+ if (successors.some((successor) => successor.id !== orderId)) throw new ReopenRefusedOrderError(orderId, "already_replaced");
3209
+ if (order.sessionId) {
3210
+ const session = await readSession(deps.sessions, order.sessionId);
3211
+ if (!session || session.status !== "open") throw new ReopenRefusedOrderError(orderId, "session_closed");
3212
+ }
3213
+ if (!await deps.drafts.findOne(orderId).exec()) {
3214
+ const builder = createOrderBuilder({ currency: order.currency, taxContext: deps.taxContext, id: order.id });
3215
+ const converted = order.lines.some((line) => line.taxInclusive !== void 0 && line.taxInclusive !== order.pricesIncludeTax);
3216
+ const display = order.display && !converted ? order.display : void 0;
3217
+ for (const [i, line] of order.lines.entries()) {
3218
+ const lineId = builder.addLine({
3219
+ productId: line.productId,
3220
+ variantId: line.variantId,
3221
+ name: line.name,
3222
+ sku: line.sku,
3223
+ unitPrice: { amount: line.unitPriceMinor, currency: order.currency, taxInclusive: line.taxInclusive },
3224
+ ...line.regularUnitPriceMinor !== void 0 ? { regularUnitPriceMinor: line.regularUnitPriceMinor } : {},
3225
+ ...line.attributes !== void 0 ? { attributes: line.attributes } : {},
3226
+ quantity: line.quantity,
3227
+ taxRates: line.taxLines.map(({ code, ratePpm }) => ({ code, ratePpm })),
3228
+ ...line.custom ? { custom: true, taxClass: line.custom.taxClass, taxStatus: line.custom.taxStatus } : { taxClass: deps.taxClassOf?.(line.productId, line.variantId) ?? "standard", taxStatus: line.taxStatus }
3229
+ });
3230
+ if (display) {
3231
+ for (const row of display.lines[i].discounts) builder.applyLineDiscount(lineId, {
3232
+ type: "fixed",
3233
+ value: row.amountMinor,
3234
+ ...row.label !== void 0 ? { label: row.label } : {}
3235
+ });
3236
+ } else if (line.discountMinor > 0) {
3237
+ builder.applyLineDiscount(lineId, { type: "fixed", value: line.discountMinor, label: "Discount" });
3238
+ }
3239
+ }
3240
+ if (display && display.orderDiscountMinor > 0) {
3241
+ builder.applyOrderDiscount({ type: "fixed", value: display.orderDiscountMinor, label: "Discount" });
3242
+ }
3243
+ for (const fee of order.fees ?? []) builder.addFee({
3244
+ name: fee.name,
3245
+ amountMinor: fee.amountMinor,
3246
+ ...fee.taxClass !== void 0 ? { taxClass: fee.taxClass } : {},
3247
+ ...fee.taxStatus !== void 0 ? { taxStatus: fee.taxStatus } : {}
3248
+ });
3249
+ for (const shipping of order.shipping ?? []) builder.addShipping({
3250
+ name: shipping.name,
3251
+ amountMinor: shipping.amountMinor,
3252
+ ...shipping.taxClass !== void 0 ? { taxClass: shipping.taxClass } : {},
3253
+ ...shipping.taxStatus !== void 0 ? { taxStatus: shipping.taxStatus } : {},
3254
+ ...shipping.methodId !== void 0 ? { methodId: shipping.methodId } : {}
3255
+ });
3256
+ for (const payment of order.payments) builder.addPayment({
3257
+ method: payment.method,
3258
+ amountMinor: payment.amountMinor,
3259
+ ...payment.reference !== void 0 ? { reference: payment.reference } : {}
3260
+ });
3261
+ if (order.customer?.id && order.customer.name && customerRefusal(order.customer) === null) {
3262
+ builder.setCustomer({
3263
+ id: order.customer.id,
3264
+ name: order.customer.name,
3265
+ ...order.customer.email !== void 0 ? { email: order.customer.email } : {}
3266
+ });
3267
+ }
3268
+ const prefix = `Refused by the store: ${order.error.message}`;
3269
+ builder.setNote(prefix + (order.note ? "\n" + order.note : ""));
3270
+ await writeOrderDraft(deps.drafts, builder.getSnapshot());
3271
+ }
3272
+ const document = await deps.orders.findOne(orderId).exec();
3273
+ await document.incrementalModify((data) => {
3274
+ if (data.syncStatus === "rejected" && !data.reopenedAt) {
3275
+ data.reopenedAt = data.updatedAt = (deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
3276
+ }
3277
+ return data;
3278
+ });
3279
+ return orderId;
3280
+ }
3281
+
3282
+ // src/pos-order/same-sale.ts
3283
+ function sameSale(stored, retried) {
3284
+ return stored.totalMinor === retried.totalMinor && stored.currency === retried.currency && stored.lines.length === retried.lines.length && stored.lines.every((line, i) => {
3285
+ const other = retried.lines[i];
3286
+ return line.id === other.id && line.quantity === other.quantity && line.netMinor === other.netMinor;
3287
+ }) && stored.payments.length === retried.payments.length && stored.payments.every((payment, i) => payment.method === retried.payments[i].method && payment.amountMinor === retried.payments[i].amountMinor);
3288
+ }
3289
+ var OrderContentMismatchError = class extends Error {
3290
+ constructor(orderId) {
3291
+ super(`Order ${orderId} is already stored with different content`);
3292
+ this.orderId = orderId;
3293
+ this.name = "OrderContentMismatchError";
3294
+ }
3295
+ };
3296
+
3297
+ // src/register/register-count.denominations.ts
3298
+ var coinsMinor = [200, 100, 50, 20, 10, 5, 2, 1];
3299
+ var denominations = {
3300
+ GBP: [5e3, 2e3, 1e3, 500, ...coinsMinor],
3301
+ EUR: [5e4, 2e4, 1e4, 5e3, 2e3, 1e3, 500, ...coinsMinor],
3302
+ USD: [1e4, 5e3, 2e3, 1e3, 500, 100, 25, 10, 5, 1],
3303
+ default: [1e4, 5e3, 2e3, 1e3, 500, 200, 100, 50, 25, 10, 5, 1]
3304
+ };
3305
+
3306
+ // src/register/schemas.ts
3307
+ import { addRxPlugin as addRxPlugin2 } from "rxdb";
3308
+ import { RxDBLocalDocumentsPlugin } from "rxdb/plugins/local-documents";
3309
+ import { RxDBMigrationSchemaPlugin as RxDBMigrationSchemaPlugin2 } from "rxdb/plugins/migration-schema";
3310
+ var id = { type: "string", maxLength: 36 };
3311
+ var text = { type: "string" };
3312
+ var nullableText = { type: ["string", "null"] };
3313
+ var minor = { type: "integer" };
3314
+ var nullableMinor = { type: ["integer", "null"] };
3315
+ var tenders = { type: "object", additionalProperties: minor };
3316
+ var registerSessionSchema = {
3317
+ title: "Register sessions",
3318
+ version: 1,
3319
+ primaryKey: "id",
3320
+ type: "object",
3321
+ additionalProperties: false,
3322
+ properties: {
3323
+ id,
3324
+ register_id: id,
3325
+ store_key: nullableText,
3326
+ status: { type: "string", maxLength: 20 },
3327
+ server_session_id: { ...nullableText, default: null },
3328
+ business_day: { type: "string", maxLength: 10 },
3329
+ opened_at_gmt: text,
3330
+ opened_by: nullableText,
3331
+ expected_float_minor: nullableMinor,
3332
+ counted_float_minor: minor,
3333
+ opening_variance_minor: nullableMinor,
3334
+ counting_started_at_gmt: nullableText,
3335
+ closed_at_gmt: nullableText,
3336
+ closed_by: nullableText,
3337
+ approval_required: { type: "boolean", default: false },
3338
+ approved_by: nullableText,
3339
+ counted: { type: ["object", "null"], additionalProperties: minor },
3340
+ closure_id: nullableText,
3341
+ pending_status: { ...nullableText, default: null },
3342
+ server_status: { ...nullableText, default: null },
3343
+ status_at: { ...nullableText, default: null },
3344
+ approver_token: { ...nullableText, default: null },
3345
+ server_expected: { type: ["object", "null"], additionalProperties: minor, default: null },
3346
+ server_sales_count: { type: ["integer", "null"], default: null }
3347
+ },
3348
+ required: ["id", "register_id", "status", "opened_at_gmt", "counted_float_minor"],
3349
+ indexes: [["register_id", "status"]]
3350
+ };
3351
+ function registerSessionCreator() {
3352
+ addRxPlugin2(RxDBLocalDocumentsPlugin);
3353
+ addRxPlugin2(RxDBMigrationSchemaPlugin2);
3354
+ return { schema: registerSessionSchema, localDocuments: true, migrationStrategies: { 1: (doc) => {
3355
+ doc.server_session_id ??= null;
3356
+ return doc;
3357
+ } } };
3358
+ }
3359
+ function registerSessionCollection() {
3360
+ throw new Error("registerSessionCollection() is gone: open register_sessions with await addRegisterSessionCollection(db). Adding it with addCollections would run RxDB's own migration of schema version 1, which can lose sessions (ADR-078, #371).");
3361
+ }
3362
+ var cashMovementSchema = {
3363
+ title: "Cash movements",
3364
+ version: 0,
3365
+ primaryKey: "id",
3366
+ type: "object",
3367
+ additionalProperties: false,
3368
+ properties: {
3369
+ id,
3370
+ session_id: id,
3371
+ type: { type: "string", enum: ["paid_in", "paid_out", "no_sale", "void"] },
3372
+ amountMinor: minor,
3373
+ reason: text,
3374
+ created_at_gmt: text,
3375
+ created_by: nullableText,
3376
+ voids: nullableText,
3377
+ voided_by: nullableText
3378
+ },
3379
+ required: ["id", "session_id", "type", "amountMinor", "reason", "created_at_gmt"],
3380
+ indexes: [["session_id"]]
3381
+ };
3382
+ var closureSchema = {
3383
+ title: "Register closures",
3384
+ version: 0,
3385
+ primaryKey: "id",
3386
+ type: "object",
3387
+ additionalProperties: false,
3388
+ properties: {
3389
+ id,
3390
+ session_id: id,
3391
+ register_id: id,
3392
+ store_key: nullableText,
3393
+ business_day: { type: "string", maxLength: 10 },
3394
+ closed_by: nullableText,
3395
+ corrections_count: { type: "integer" },
3396
+ number: { type: "integer" },
3397
+ opened_at: text,
3398
+ closed_at: text,
3399
+ till_expected: tenders,
3400
+ expected: tenders,
3401
+ counted: tenders,
3402
+ variance: tenders,
3403
+ period_sales_total_minor: minor,
3404
+ period_refunds_total_minor: minor,
3405
+ perpetual_sales_total_minor: minor,
3406
+ perpetual_refunds_total_minor: minor,
3407
+ unsynced_count: { type: "integer" },
3408
+ unsynced_total_minor: minor,
3409
+ software_version: text,
3410
+ breakdowns: { type: "object", additionalProperties: true },
3411
+ order_ids: { type: "array", items: text },
3412
+ movement_ids: { type: "array", items: text },
3413
+ server_closure_id: { ...nullableText, default: null },
3414
+ printed_at: { ...nullableText, default: null },
3415
+ print_count: { type: "integer", default: 0 },
3416
+ number_retried: { type: "boolean", default: false }
3417
+ },
3418
+ required: [
3419
+ "id",
3420
+ "session_id",
3421
+ "register_id",
3422
+ "number",
3423
+ "opened_at",
3424
+ "closed_at",
3425
+ "till_expected",
3426
+ "expected",
3427
+ "counted",
3428
+ "variance",
3429
+ "period_sales_total_minor",
3430
+ "period_refunds_total_minor",
3431
+ "perpetual_sales_total_minor",
3432
+ "perpetual_refunds_total_minor",
3433
+ "unsynced_count",
3434
+ "unsynced_total_minor",
3435
+ "software_version",
3436
+ "breakdowns",
3437
+ "order_ids",
3438
+ "movement_ids",
3439
+ "print_count"
3440
+ ],
3441
+ indexes: [["register_id"], ["session_id"]]
3442
+ };
3443
+
3444
+ // src/register/open.ts
3445
+ var registerSessionsLogger = createLogger("register-sessions");
3446
+ var REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS = 1e4;
3447
+ var RegisterSessionOpenClosedError = class extends Error {
3448
+ constructor(databaseName) {
3449
+ super(`addRegisterSessionCollection: database ${databaseName} closed during the open; reopen it and open register_sessions again`);
3450
+ this.databaseName = databaseName;
3451
+ this.name = "RegisterSessionOpenClosedError";
3452
+ }
3453
+ code = "REGISTER_SESSION_OPEN_CLOSED";
3454
+ };
3455
+ function addRegisterSessionCollection(db, closeWaitMs = REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS) {
3456
+ return openMigratedCollection(db, {
3457
+ name: "register_sessions",
3458
+ creator: registerSessionCreator,
3459
+ label: "addRegisterSessionCollection",
3460
+ logger: registerSessionsLogger,
3461
+ closedError: (name) => new RegisterSessionOpenClosedError(name)
3462
+ }, closeWaitMs);
3463
+ }
3464
+
3309
3465
  // src/register/settled-figures.ts
3310
3466
  function deriveSettled(recorded, corrections) {
3311
3467
  const settled = {
@@ -3996,8 +4152,8 @@ function currentSession(rows, closureRows, reservation) {
3996
4152
  if (rows.some((row) => !isKnownSessionStatus(row.status))) return null;
3997
4153
  return (reservation && !reservation.applied ? rows.find((row) => row.id === reservation.row.session_id) : void 0) ?? rows.find((row) => row.status === "open" || row.status === "counting") ?? rows.find((row) => row.status === "conflict") ?? rows.find((row) => unwritten(row, closureRows)) ?? null;
3998
4154
  }
3999
- function ledgerRows(orders) {
4000
- return orders.flatMap((order) => order.payments.map((payment) => ({
4155
+ function ledgerRows(orders, replaced = replacedOrderIds(orders)) {
4156
+ return orders.filter((order) => !replaced.has(order.id)).flatMap((order) => order.payments.map((payment) => ({
4001
4157
  session_id: order.sessionId,
4002
4158
  kind: payment.method === "cash" ? "cash" : "other",
4003
4159
  method_id: payment.method,
@@ -4108,7 +4264,8 @@ function useRegisterSession(options) {
4108
4264
  const conflict = session?.status !== "conflict" || !commandTarget ? void 0 : data?.open?.syncStatus === "pending" && typeof data.open.payload.supersedes === "string" ? { sessionId: data.open.payload.supersedes, takingOver: true } : data?.open?.syncStatus === "rejected" && refusal ? { sessionId: refusal.sessionId, openedAt: refusal.openedAt, openedBy: refusal.openedBy, deviceName: refusal.deviceName, takingOver: false } : void 0;
4109
4265
  const entries = data?.entries ?? [];
4110
4266
  const sales = data?.sales ?? [];
4111
- const expected = session ? deriveExpected({ session: { id: session.id, countedFloatMinor: session.counted_float_minor }, movements: entries, ledgerRowsBySession: ledgerRows(sales), refunds: data?.refundRows ?? [] }) : {};
4267
+ const replaced = replacedOrderIds(sales);
4268
+ const expected = session ? deriveExpected({ session: { id: session.id, countedFloatMinor: session.counted_float_minor }, movements: entries, ledgerRowsBySession: ledgerRows(sales, replaced), refunds: data?.refundRows ?? [] }) : {};
4112
4269
  const now = /* @__PURE__ */ new Date();
4113
4270
  const [hour, minute] = String(expectedCloseTime ?? "").split(":").map(Number);
4114
4271
  const overdue = session?.status === "open" && !!expectedCloseTime && now.getTime() > new Date(now.getFullYear(), now.getMonth(), now.getDate(), hour, minute).getTime();
@@ -4137,7 +4294,7 @@ function useRegisterSession(options) {
4137
4294
  needsUpgrade: data?.rows.some((row) => !isKnownSessionStatus(row.status)) ?? false,
4138
4295
  movements: entries,
4139
4296
  expected,
4140
- salesCount: sales.length,
4297
+ salesCount: sales.filter((order) => !replaced.has(order.id)).length,
4141
4298
  overdue,
4142
4299
  /** A `closeSession` for this register is in flight, in any hook instance: the session can already be stored `closed` while its closure isn't written yet. */
4143
4300
  closing,
@@ -4376,20 +4533,26 @@ function addEntryToCart(builder, entry, traits, currency) {
4376
4533
  return existing.id;
4377
4534
  }
4378
4535
  const name = traits.getName(product) + (traits.getVariantCount(product) > 1 ? ` \xB7 ${variant.title}` : "");
4379
- const unitPrice = resolvePrice3(variant.prices, currency)?.current;
4380
- if (!unitPrice) throw new CartError(`No ${currency} price for ${name}`);
4536
+ const resolved = resolvePrice3(variant.prices, currency);
4537
+ if (!resolved) throw new CartError(`No ${currency} price for ${name}`);
4538
+ const unitPrice = resolved.current, regularPrice = regularUnitPriceMinor(resolved);
4381
4539
  return builder.addLine({
4382
4540
  productId: traits.getId(product),
4383
4541
  variantId: variant.id,
4384
4542
  name,
4543
+ ...variant.options && Object.keys(variant.options).length ? { attributes: variant.options } : {},
4385
4544
  sku: variant.sku ?? "",
4386
4545
  imageUrl: traits.getImageUrl?.(product),
4387
4546
  unitPrice,
4547
+ ...regularPrice !== void 0 ? { regularUnitPriceMinor: regularPrice } : {},
4388
4548
  taxClass: traits.getTaxClass?.(product, variant.id),
4389
4549
  ...traits.getTaxStatus?.(product, variant.id) === "none" ? { taxStatus: "none" } : {}
4390
4550
  });
4391
4551
  }
4392
4552
 
4553
+ // src/sale/discount-codes.ts
4554
+ var COUPONS_UNSUPPORTED = "This store's plugin does not support coupons yet";
4555
+
4393
4556
  // src/sale/use-sale.ts
4394
4557
  var saleLogger = createLogger("sale");
4395
4558
  var DISCOUNTS_UNSUPPORTED = "finalize: discounts are not supported by the server yet (order.create v2)";
@@ -4400,6 +4563,15 @@ function useSale(settings, opts) {
4400
4563
  const madeWith = useRef3({ taxContext, currency: settings.currency });
4401
4564
  const [rendered, setBuilder] = useState4(() => createOrderBuilder({ currency: settings.currency, taxContext }));
4402
4565
  const builderNow = useRef3(rendered);
4566
+ const applied = useRef3(/* @__PURE__ */ new Map());
4567
+ const appliedWith = useRef3(null);
4568
+ const categories = useRef3(/* @__PURE__ */ new Map());
4569
+ function discountState(order2, accepted) {
4570
+ return { order: order2, accepted: new Map(accepted), categories: categories.current, settings: { calcDiscountsSequentially: settings.calcDiscountsSequentially } };
4571
+ }
4572
+ function codesFor() {
4573
+ return opts.capabilities?.coupons === true && (opts.capabilities?.orderCreate ?? 1) >= 6 && opts.discountCodes && opts.discountCodes.supports({ capabilities: opts.capabilities, rounding: taxContext.rounding }) ? opts.discountCodes : null;
4574
+ }
4403
4575
  const [order, setOrder] = useState4(() => rendered.getSnapshot());
4404
4576
  const [stage, setStage] = useState4({ kind: "cart" });
4405
4577
  const [saleError, setError] = useState4(null);
@@ -4449,6 +4621,8 @@ function useSale(settings, opts) {
4449
4621
  const next = restored ?? createOrderBuilder({ currency: settings.currency, taxContext });
4450
4622
  if (customer !== null) next.setCustomer(customer);
4451
4623
  builderNow.current = next;
4624
+ applied.current.clear();
4625
+ appliedWith.current = null;
4452
4626
  setBuilder(next);
4453
4627
  setOrder(next.getSnapshot());
4454
4628
  setStage({ kind: "cart" });
@@ -4566,6 +4740,11 @@ function useSale(settings, opts) {
4566
4740
  const builder = builderNow.current;
4567
4741
  try {
4568
4742
  const known = new Set(builder.getSnapshot().lineItems.map((line2) => line2.id));
4743
+ const productId = Number(traits.getId(entry.product));
4744
+ if (Number.isSafeInteger(productId) && productId >= 0) {
4745
+ const ids = productCategories(entry.product, traits).map(({ id: id2 }) => ({ id: Number(id2) })).filter(({ id: id2 }) => Number.isSafeInteger(id2));
4746
+ if (ids.length) categories.current.set(productId, ids);
4747
+ }
4569
4748
  const lineId = addEntryToCart(builder, entry, traits, madeWith.current.currency);
4570
4749
  const line = builder.getSnapshot().lineItems.find((item) => item.id === lineId && !known.has(item.id));
4571
4750
  const name = line && `"${cutText(line.name, MESSAGE_NAME_MAX)}"`;
@@ -4685,11 +4864,11 @@ function useSale(settings, opts) {
4685
4864
  if (locked()) return SALE_SAVING;
4686
4865
  if ((opts.capabilities?.orderCreate ?? 1) < 2) return DISCOUNTS_UNSUPPORTED;
4687
4866
  const builder = builderNow.current;
4688
- const applied = (snapshot) => lineId === null ? snapshot.discounts : snapshot.lineItems.find((line) => line.id === lineId)?.discounts ?? [];
4689
- const before = new Set(applied(builder.getSnapshot()).map((entry) => entry.id));
4867
+ const applied2 = (snapshot) => lineId === null ? snapshot.discounts : snapshot.lineItems.find((line) => line.id === lineId)?.discounts ?? [];
4868
+ const before = new Set(applied2(builder.getSnapshot()).map((entry) => entry.id));
4690
4869
  if (lineId === null) builder.applyOrderDiscount(discount);
4691
4870
  else builder.applyLineDiscount(lineId, discount);
4692
- const added = applied(builder.getSnapshot()).find((entry) => !before.has(entry.id));
4871
+ const added = applied2(builder.getSnapshot()).find((entry) => !before.has(entry.id));
4693
4872
  if (added?.type === "fixed" && added.amountMinor < added.value) {
4694
4873
  builder.removeDiscount(added.id);
4695
4874
  return `The discount is more than the ${lineId === null ? "order" : "line"}`;
@@ -4699,6 +4878,42 @@ function useSale(settings, opts) {
4699
4878
  removeDiscount(id2) {
4700
4879
  if (!locked()) builderNow.current.removeDiscount(id2);
4701
4880
  },
4881
+ /** ADR-077: looks up, checks and applies a discount code through the platform's discount codes; resolves to the refusal to show, or null once applied. */
4882
+ async applyCoupon(code) {
4883
+ if (locked()) return SALE_SAVING;
4884
+ const codes = codesFor();
4885
+ if (!codes) return COUPONS_UNSUPPORTED;
4886
+ const builder = builderNow.current, normalized = code.trim().toLowerCase();
4887
+ if (!normalized) return "Enter a coupon code";
4888
+ const result2 = await codes.find(normalized, discountState(builder.getSnapshot(), applied.current));
4889
+ if ("refusal" in result2) return result2.refusal;
4890
+ if (locked()) return SALE_SAVING;
4891
+ if (builderNow.current !== builder || stageNow.current.kind === "receipt") return "The sale changed while the coupon was being checked; apply it again";
4892
+ const refusal = codes.check(normalized, result2.found, discountState(builder.getSnapshot(), applied.current));
4893
+ if (refusal !== null) return refusal;
4894
+ const next = new Map([...applied.current, [normalized, result2.found]]);
4895
+ try {
4896
+ codes.apply(builder, discountState(builder.getSnapshot(), next));
4897
+ } catch (error2) {
4898
+ if (error2 instanceof Error) return error2.message;
4899
+ throw error2;
4900
+ }
4901
+ applied.current.set(normalized, result2.found);
4902
+ appliedWith.current = codes;
4903
+ setError(null);
4904
+ return null;
4905
+ },
4906
+ /** Removes an applied coupon; returns the refusal to show, or null once removed. */
4907
+ removeCoupon(code) {
4908
+ if (locked()) return SALE_SAVING;
4909
+ const normalized = code.trim().toLowerCase();
4910
+ if (!applied.current.has(normalized)) return null;
4911
+ const remaining = new Map(applied.current);
4912
+ remaining.delete(normalized);
4913
+ appliedWith.current.apply(builderNow.current, discountState(builderNow.current.getSnapshot(), remaining));
4914
+ applied.current.delete(normalized);
4915
+ return null;
4916
+ },
4702
4917
  /** the picked customer reaches the server as order.create v3's customer.customerId */
4703
4918
  setCustomer(customer) {
4704
4919
  if (locked()) return;
@@ -4862,13 +5077,42 @@ function useSale(settings, opts) {
4862
5077
  }
4863
5078
  }
4864
5079
  }
5080
+ const kept = /* @__PURE__ */ new Map(), messages = [];
5081
+ const codes = saved.coupons?.length ? codesFor() : null;
5082
+ if (n > 0) messages.push(`Prices changed since this sale was parked: ${n} ${n === 1 ? "line" : "lines"} updated to today's price.`);
5083
+ if (saved.coupons?.length) {
5084
+ const supported = codes !== null;
5085
+ if (supported) await codes.beforeResume?.(discountState(builder.getSnapshot(), /* @__PURE__ */ new Map()));
5086
+ for (const { code } of saved.coupons) {
5087
+ let reason = supported ? null : COUPONS_UNSUPPORTED;
5088
+ if (supported) {
5089
+ const result2 = await codes.find(code, discountState(builder.getSnapshot(), kept));
5090
+ if ("refusal" in result2) reason = result2.refusal;
5091
+ else {
5092
+ reason = codes.check(code, result2.found, discountState(builder.getSnapshot(), kept));
5093
+ if (reason === null) try {
5094
+ codes.apply(builder, discountState(builder.getSnapshot(), new Map([...kept, [code, result2.found]])));
5095
+ kept.set(code, result2.found);
5096
+ } catch (error2) {
5097
+ if (error2 instanceof Error) reason = error2.message;
5098
+ else throw error2;
5099
+ }
5100
+ }
5101
+ }
5102
+ if (reason !== null) messages.push(`Coupon ${code} was removed: ${reason}.`);
5103
+ }
5104
+ }
4865
5105
  await doc.remove();
4866
5106
  if (builderNow.current !== live || live.getSnapshot() !== liveSnapshot) {
4867
5107
  await writeOrderDraft(opts.drafts, saved);
4868
5108
  return "The sale changed while it was being resumed; resume it again";
4869
5109
  }
4870
5110
  resetSale(null, builder);
4871
- if (n > 0) setError(`Prices changed since this sale was parked: ${n} ${n === 1 ? "line" : "lines"} updated to today's price.`);
5111
+ if (builderNow.current === builder) {
5112
+ applied.current = kept;
5113
+ appliedWith.current = kept.size ? codes : null;
5114
+ }
5115
+ if (messages.length) setError(messages.join(" "));
4872
5116
  return null;
4873
5117
  },
4874
5118
  /**
@@ -4883,6 +5127,197 @@ function useSale(settings, opts) {
4883
5127
  return result;
4884
5128
  }
4885
5129
 
5130
+ // src/sale/woocommerce/index.ts
5131
+ var woocommerce_exports = {};
5132
+ __export(woocommerce_exports, {
5133
+ couponRefusal: () => couponRefusal,
5134
+ createDiscountCodes: () => createDiscountCodes,
5135
+ createSaleCouponSource: () => createSaleCouponSource,
5136
+ startCouponUsageRefetch: () => startCouponUsageRefetch
5137
+ });
5138
+
5139
+ // src/sale/woocommerce/discount-codes.ts
5140
+ import { minorUnitDigits as minorUnitDigits4, woocommerceCoupons as woocommerceCoupons3 } from "@tallyui/core";
5141
+
5142
+ // src/sale/woocommerce/coupons.ts
5143
+ import { minorUnitDigits as minorUnitDigits3 } from "@tallyui/core";
5144
+ function couponRefusal(code, rejection) {
5145
+ switch (rejection.code) {
5146
+ case "already_applied":
5147
+ return `Coupon ${code} is already applied`;
5148
+ case "expired":
5149
+ return `Coupon ${code} has expired`;
5150
+ case "usage_limit_reached":
5151
+ return `Coupon ${code} has reached its usage limit`;
5152
+ case "usage_limit_reached_for_customer":
5153
+ return `This customer has used coupon ${code} as often as it allows`;
5154
+ case "minimum_spend_not_met":
5155
+ return `Coupon ${code} needs a spend of at least ${rejection.params?.amount}`;
5156
+ case "maximum_spend_exceeded":
5157
+ return `Coupon ${code} allows a spend of at most ${rejection.params?.amount}`;
5158
+ case "individual_use":
5159
+ return `Coupon ${code} cannot be used with other coupons`;
5160
+ case "individual_use_conflict":
5161
+ return `Coupon ${rejection.params?.code} cannot be used with other coupons`;
5162
+ case "email_required":
5163
+ return `Coupon ${code} needs a customer with an email address`;
5164
+ case "email_not_allowed":
5165
+ return `This customer's email address cannot use coupon ${code}`;
5166
+ case "not_applicable_to_cart":
5167
+ return `Coupon ${code} does not apply to anything in this sale`;
5168
+ }
5169
+ }
5170
+ function couponLineItems(lines, currency, categories) {
5171
+ const digits = minorUnitDigits3(currency), factor = 10 ** digits;
5172
+ return lines.flatMap((line, lineIndex) => {
5173
+ if (line.unitPriceMinor < 0) return [];
5174
+ const id2 = Number(line.productId), product_id = !line.custom && Number.isSafeInteger(id2) && id2 >= 0 ? id2 : 0;
5175
+ return [{
5176
+ product_id,
5177
+ quantity: line.quantity,
5178
+ price: line.unitPriceMinor / factor,
5179
+ subtotal: (line.netMinor / factor).toFixed(digits),
5180
+ total: (line.netMinor / factor).toFixed(digits),
5181
+ categories: [...categories.get(product_id) ?? []],
5182
+ lineIndex,
5183
+ on_sale: line.regularUnitPriceMinor !== void 0 && line.unitPriceMinor < line.regularUnitPriceMinor
5184
+ }];
5185
+ });
5186
+ }
5187
+
5188
+ // src/sale/woocommerce/discount-codes.ts
5189
+ function wooCustomerId(customer) {
5190
+ const id2 = Number(customer?.id);
5191
+ return Number.isSafeInteger(id2) && id2 > 0 ? id2 : null;
5192
+ }
5193
+ function createDiscountCodes(source) {
5194
+ return {
5195
+ supports: ({ rounding }) => rounding?.granularity === "woocommerce",
5196
+ async find(code, sale) {
5197
+ if (sale.accepted.has(code)) return { refusal: couponRefusal(code, { code: "already_applied" }) };
5198
+ const coupon = await source.find(code);
5199
+ return coupon === null ? { refusal: `Coupon ${code} does not exist` } : { found: coupon };
5200
+ },
5201
+ check(code, coupon, sale) {
5202
+ const snapshot = sale.order;
5203
+ const validation = woocommerceCoupons3.validateCoupon(coupon, {
5204
+ lineItems: couponLineItems(snapshot.lineItems, snapshot.currency, sale.categories),
5205
+ appliedCoupons: [...sale.accepted.keys()],
5206
+ appliedCouponsWithIndividualUse: [...sale.accepted].filter(([, value]) => value.individual_use).map(([key]) => key),
5207
+ cartSubtotal: snapshot.display.subtotalMinor / 10 ** minorUnitDigits4(snapshot.currency),
5208
+ customerEmail: snapshot.customer?.email ?? "",
5209
+ customerId: wooCustomerId(snapshot.customer),
5210
+ now: Date.now()
5211
+ });
5212
+ return validation.valid ? null : couponRefusal(code, validation.rejection);
5213
+ },
5214
+ apply(builder, sale) {
5215
+ const context = {
5216
+ configs: woocommerceCoupons3.toCouponConfigs([...sale.accepted.keys()], sale.accepted),
5217
+ couponIds: new Map([...sale.accepted].map(([code, coupon]) => [code, String(coupon.id)])),
5218
+ productCategories: sale.categories,
5219
+ calcDiscountsSequentially: sale.settings.calcDiscountsSequentially ?? false
5220
+ };
5221
+ builder.setCoupons([...sale.accepted.keys()], context);
5222
+ },
5223
+ async beforeResume(sale) {
5224
+ const ids = sale.order.lineItems.filter((line) => !line.custom).map((line) => Number(line.productId)).filter((id2) => Number.isSafeInteger(id2) && id2 >= 0);
5225
+ for (const [id2, values] of await source.productCategories(ids)) if (values.length) sale.categories.set(id2, [...values]);
5226
+ }
5227
+ };
5228
+ }
5229
+
5230
+ // src/sale/woocommerce/coupon-source.ts
5231
+ var APPLIED_USE_GRACE_MS = 6e5;
5232
+ function createSaleCouponSource(deps) {
5233
+ const now = deps.now ?? Date.now;
5234
+ return {
5235
+ async find(code) {
5236
+ let doc = await deps.coupons.findOne({ selector: { code } }).exec();
5237
+ if (!doc) {
5238
+ doc = (await deps.coupons.find().exec()).find((coupon) => typeof coupon.code === "string" && coupon.code.toLowerCase() === code) ?? null;
5239
+ }
5240
+ if (!doc) return null;
5241
+ const data = doc.toJSON(true);
5242
+ if (!["percent", "fixed_cart", "fixed_product"].includes(data.discount_type) || !Number.isInteger(data.id) || typeof data.amount !== "string") return null;
5243
+ const orders = await deps.orders.find({ selector: { syncStatus: { $in: ["pending", "applied"] } } }).exec();
5244
+ const counted = orders.filter((order) => order.coupons?.some((coupon) => coupon.code === code) && (order.syncStatus === "pending" || Date.parse(order.updatedAt) > data._meta.lwt && now() - Date.parse(order.updatedAt) < APPLIED_USE_GRACE_MS));
5245
+ const usedBy = [...data.used_by ?? []];
5246
+ for (const order of counted) {
5247
+ const id2 = Number(order.customer?.id);
5248
+ const email = order.customer?.email;
5249
+ if (Number.isSafeInteger(id2) && id2 > 0) usedBy.push(String(id2));
5250
+ else if (typeof email === "string" && email.length > 0) usedBy.push(email.toLowerCase());
5251
+ }
5252
+ const fields = [
5253
+ "limit_usage_to_x_items",
5254
+ "product_ids",
5255
+ "excluded_product_ids",
5256
+ "product_categories",
5257
+ "excluded_product_categories",
5258
+ "exclude_sale_items",
5259
+ "individual_use",
5260
+ "date_expires_gmt",
5261
+ "usage_limit",
5262
+ "usage_limit_per_user",
5263
+ "minimum_amount",
5264
+ "maximum_amount",
5265
+ "email_restrictions"
5266
+ ];
5267
+ return {
5268
+ ...Object.fromEntries(fields.filter((field) => field in data).map((field) => [field, data[field]])),
5269
+ discount_type: data.discount_type,
5270
+ amount: data.amount,
5271
+ id: data.id,
5272
+ code,
5273
+ usage_count: (data.usage_count ?? 0) + counted.length,
5274
+ used_by: usedBy
5275
+ };
5276
+ },
5277
+ async productCategories(productIds) {
5278
+ const products = await deps.products.find({ selector: { id: { $in: [...productIds] } } }).exec();
5279
+ return new Map(products.map((product) => [
5280
+ product.id,
5281
+ (product.categories ?? []).map(({ id: id2 }) => ({ id: id2 }))
5282
+ ]));
5283
+ }
5284
+ };
5285
+ }
5286
+
5287
+ // src/sale/woocommerce/coupon-refetch.ts
5288
+ function startCouponUsageRefetch(deps) {
5289
+ const now = deps.now ?? Date.now;
5290
+ const handled = /* @__PURE__ */ new Set();
5291
+ let stopped = false;
5292
+ const subscription = deps.orders.find({ selector: { syncStatus: "applied" } }).$.subscribe(async (orders) => {
5293
+ const ids = /* @__PURE__ */ new Set();
5294
+ for (const order of orders) {
5295
+ if (!order.coupons?.length || handled.has(order.id) || !(now() - Date.parse(order.updatedAt) < APPLIED_USE_GRACE_MS)) continue;
5296
+ handled.add(order.id);
5297
+ for (const coupon of order.coupons) {
5298
+ const id2 = Number(coupon.couponId);
5299
+ if (Number.isInteger(id2)) ids.add(id2);
5300
+ }
5301
+ }
5302
+ if (!ids.size) return;
5303
+ try {
5304
+ const docs = await deps.coupons.find({ selector: { id: { $in: [...ids] } } }).exec();
5305
+ if (stopped || !docs.length) return;
5306
+ deps.enqueue(docs.map((doc) => ({ key: doc.uuid, local: doc.toJSON(), refreshOnly: true })));
5307
+ deps.reSync();
5308
+ } catch (error) {
5309
+ saleLogger.warn(
5310
+ "coupon refetch failed",
5311
+ { couponIds: [...ids], error: String(error) }
5312
+ );
5313
+ }
5314
+ });
5315
+ return { stop() {
5316
+ stopped = true;
5317
+ subscription.unsubscribe();
5318
+ } };
5319
+ }
5320
+
4886
5321
  // src/sale/catalogue.ts
4887
5322
  import { findVariantByCode, formatMoney as formatMoney2, resolvePrice as resolvePrice4 } from "@tallyui/core";
4888
5323
  function catalogueEntries(products, traits, context) {
@@ -4992,7 +5427,10 @@ function createBackendNotFound() {
4992
5427
 
4993
5428
  // src/outbox/order-outbox.ts
4994
5429
  var AUTH_FAILURES_BEFORE_PROMPT = 3;
4995
- var NOT_REQUEUEABLE = /* @__PURE__ */ new Set(["idempotency_mismatch"]);
5430
+ var NOT_REQUEUEABLE = /* @__PURE__ */ new Set(["idempotency_mismatch", "coupon_invalid", "total_mismatch"]);
5431
+ function isRequeueable(code) {
5432
+ return !NOT_REQUEUEABLE.has(code ?? "");
5433
+ }
4996
5434
  var REFUSAL_LOG_MESSAGE_MAX = 200;
4997
5435
  var ISOLATE_AFTER_ATTEMPTS = 5;
4998
5436
  var STUCK_AFTER_MS = 15 * 6e4;
@@ -5087,7 +5525,10 @@ function createOrderOutbox(options) {
5087
5525
  const recordsSentForm = (before, after) => deepEqual2(bare({ ...freezeSentForm(before), sentVersion: before.sentVersion ?? after.sentVersion }), bare(after));
5088
5526
  async function updateState(patch = {}) {
5089
5527
  const pending = await countFresh(collection, { syncStatus: "pending" });
5090
- const rejected = await countFresh(collection, { syncStatus: "rejected" });
5528
+ const refused = await readFresh(collection, { selector: { syncStatus: "rejected" } });
5529
+ const successors = refused.length ? await readFresh(collection, { selector: { saleId: { $in: refused.map((order) => order.id) } } }) : [];
5530
+ const replaced = replacedOrderIds([...refused, ...successors]);
5531
+ const rejected = refused.filter((order) => !replaced.has(order.id)).length;
5091
5532
  state$.next({ ...state$.value, ...patch, pending, rejected, stuck: stuckState() });
5092
5533
  }
5093
5534
  function isolate(id2, reason, retryAfterMs = 0) {
@@ -5189,7 +5630,7 @@ function createOrderOutbox(options) {
5189
5630
  envelope2 = toOrderCreateEnvelope(frozen, deviceId, attempt2, { maxVersion: order.sentVersion ?? serverMax });
5190
5631
  } catch (cause) {
5191
5632
  if (!(cause instanceof UnsupportedOrderVersionError)) throw cause;
5192
- envelope2 = toOrderCreateEnvelope(frozen, deviceId, attempt2, { maxVersion: cause.needed === 5 ? 5 : 3 });
5633
+ envelope2 = toOrderCreateEnvelope(frozen, deviceId, attempt2, { maxVersion: cause.needed >= 5 ? cause.needed : 3 });
5193
5634
  }
5194
5635
  if (frozen !== order || order.sentVersion === void 0) {
5195
5636
  await (await collection.findOne(order.id).exec())?.incrementalModify((data) => ({ ...freezeSentForm(data), sentVersion: data.sentVersion ?? envelope2.version }));
@@ -5387,13 +5828,13 @@ function createOrderOutbox(options) {
5387
5828
  const orders = (await readFresh(collection, { selector: {
5388
5829
  syncStatus: "rejected",
5389
5830
  ...orderIds ? { id: { $in: orderIds } } : {}
5390
- } })).filter((order) => !NOT_REQUEUEABLE.has(order.error?.code ?? ""));
5831
+ } })).filter((order) => isRequeueable(order.error?.code));
5391
5832
  let count = 0;
5392
5833
  for (const order of orders) {
5393
5834
  const oldCommandId = order.commandId;
5394
5835
  let changed = false;
5395
5836
  await (await collection.findOne(order.id).exec())?.incrementalModify((data) => {
5396
- changed = data.syncStatus === "rejected" && !NOT_REQUEUEABLE.has(data.error?.code ?? "");
5837
+ changed = data.syncStatus === "rejected" && isRequeueable(data.error?.code);
5397
5838
  if (!changed) return data;
5398
5839
  data.syncStatus = "pending";
5399
5840
  delete data.error;
@@ -6268,6 +6709,7 @@ function tenderVoidCollection() {
6268
6709
  return { schema: tenderVoidSchema };
6269
6710
  }
6270
6711
  export {
6712
+ COUPONS_UNSUPPORTED,
6271
6713
  CartError,
6272
6714
  CurrencyProvider,
6273
6715
  DEFAULT_CATALOGUE_VIEW_STATE,
@@ -6279,6 +6721,7 @@ export {
6279
6721
  PosOrderOpenClosedError,
6280
6722
  RECEIPT_SCHEMA_VERSION,
6281
6723
  REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS,
6724
+ REOPENABLE_CODES,
6282
6725
  RefundAnswerPendingError,
6283
6726
  RegisterApprovalRequiredError,
6284
6727
  RegisterCloseIncompleteError,
@@ -6294,6 +6737,7 @@ export {
6294
6737
  RegisterSessionRequiredError,
6295
6738
  RegisterTakeOverError,
6296
6739
  RegisterTenderInProgressError,
6740
+ ReopenRefusedOrderError,
6297
6741
  SALE_SAVING,
6298
6742
  TAX_ROUNDING_MIXED_NOTE,
6299
6743
  TaxProvider,
@@ -6351,6 +6795,8 @@ export {
6351
6795
  initTenderState,
6352
6796
  initialTenderState,
6353
6797
  isKnownSessionStatus,
6798
+ isReopened,
6799
+ isRequeueable,
6354
6800
  isServerDecimal,
6355
6801
  labelKeys,
6356
6802
  listCategories,
@@ -6394,6 +6840,8 @@ export {
6394
6840
  registerSessionCollection,
6395
6841
  registerSessionSchema,
6396
6842
  registerSessionsLogger,
6843
+ reopenRefusedOrder,
6844
+ replacedOrderIds,
6397
6845
  requireOpenSession,
6398
6846
  resolveGridColumns,
6399
6847
  resolveStoreSettings,
@@ -6440,6 +6888,7 @@ export {
6440
6888
  watchFresh,
6441
6889
  withPricingContext,
6442
6890
  withStockOverlay,
6891
+ woocommerce_exports as woocommerceDiscountCodes,
6443
6892
  writeClosure,
6444
6893
  writeOrderDraft
6445
6894
  };