@tallyui/pos 3.9.1 → 3.10.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(
@@ -966,6 +979,7 @@ function createOrderBuilder(options) {
966
979
  sku: input.sku ?? "",
967
980
  imageUrl: input.imageUrl,
968
981
  unitPriceMinor: unitPrice.amount,
982
+ ...input.regularUnitPriceMinor !== void 0 && !input.custom ? { regularUnitPriceMinor: input.regularUnitPriceMinor } : {},
969
983
  quantity,
970
984
  taxLines: taxRates.map((tax) => ({ ...tax, taxMicros: "0" })),
971
985
  discounts: [],
@@ -1031,8 +1045,9 @@ function createOrderBuilder(options) {
1031
1045
  const variant = opts?.variantId !== void 0 && traits.getVariants ? traits.getVariants(doc, { currency }).find((variant2) => variant2.id === opts.variantId) : void 0;
1032
1046
  if (opts?.variantId !== void 0 && traits.getVariants && !variant)
1033
1047
  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);
1048
+ const resolved = resolvePrice(variant ? variant.prices : traits.getPrices(doc, { currency }), currency);
1049
+ if (!resolved) throw new Error("No price in " + currency + " for product " + productId);
1050
+ const unitPrice = resolved.current, regularPrice = regularUnitPriceMinor(resolved);
1036
1051
  return addLine({
1037
1052
  productId,
1038
1053
  variantId: opts?.variantId,
@@ -1040,6 +1055,7 @@ function createOrderBuilder(options) {
1040
1055
  sku: variant?.sku ?? traits.getSku(doc),
1041
1056
  imageUrl: traits.getImageUrl(doc),
1042
1057
  unitPrice,
1058
+ ...regularPrice !== void 0 ? { regularUnitPriceMinor: regularPrice } : {},
1043
1059
  quantity: opts?.quantity,
1044
1060
  taxClass: traits.getTaxClass?.(doc, opts?.variantId),
1045
1061
  ...traits.getTaxStatus?.(doc, opts?.variantId) === "none" ? { taxStatus: "none" } : {}
@@ -1119,14 +1135,18 @@ function createOrderBuilder(options) {
1119
1135
  note = n;
1120
1136
  emit();
1121
1137
  },
1122
- setCoupons(codes) {
1138
+ setCoupons(codes, context) {
1139
+ const nextContext = context ?? couponContext;
1123
1140
  const normalized = [...new Set(codes.map((code) => code.trim().toLowerCase()))];
1124
- if (normalized.length && !couponContext) throw new Error("Coupon context is required");
1141
+ if (normalized.length && !nextContext) throw new Error("Coupon context is required");
1125
1142
  for (const code of normalized) {
1126
- const config = couponContext.configs.get(code);
1143
+ const config = nextContext.configs.get(code);
1127
1144
  if (!config) throw new RangeError(`Unknown coupon ${code}`);
1128
1145
  if (config.exclude_sale_items) throw new RangeError(`Coupon ${code} excludes sale items`);
1146
+ const couponId = nextContext.couponIds.get(code);
1147
+ if (couponId === void 0 || couponId === "") throw new RangeError(`Coupon ${code} has no id`);
1129
1148
  }
1149
+ if (context) couponContext = context;
1130
1150
  couponCodes = normalized;
1131
1151
  emit();
1132
1152
  },
@@ -1201,6 +1221,7 @@ function netDiscountMinor(line, pricesIncludeTax) {
1201
1221
  return roundMicrosToMinor(BigInt(line.discountMinor) * MICROS_PER_MINOR - taxBefore + taxAfter);
1202
1222
  }
1203
1223
  function contentVersion(order) {
1224
+ if (order.coupons?.length) return 6;
1204
1225
  if (order.fees?.length || order.shipping?.length || order.lines.some((line) => line.custom)) return 5;
1205
1226
  return order.display && order.taxByRate ? 3 : order.lines.reduce((sum, line) => sum + line.discountMinor, 0) > 0 ? 2 : 1;
1206
1227
  }
@@ -1209,6 +1230,7 @@ function toOrderCreateEnvelope(order, deviceId, attempt2 = 1, options) {
1209
1230
  const content = contentVersion(order);
1210
1231
  const cap = options?.maxVersion === void 0 ? order.sentVersion : Math.min(options.maxVersion, order.sentVersion ?? options.maxVersion);
1211
1232
  if (content === 5 && cap !== void 0 && cap < 5) throw new UnsupportedOrderVersionError(5, cap);
1233
+ if (content === 6 && cap !== void 0 && cap < 6) throw new UnsupportedOrderVersionError(6, cap);
1212
1234
  if (grossMinor > 0 && cap !== void 0 && cap < 2) throw new UnsupportedOrderVersionError(2, cap);
1213
1235
  const version = content === 3 && cap !== void 0 && cap >= 4 ? 4 : Math.min(content, cap ?? content);
1214
1236
  const lineDiscounts = order.lines.map((line) => version >= 4 ? netDiscountMinor(line, order.pricesIncludeTax) : line.discountMinor);
@@ -1217,7 +1239,7 @@ function toOrderCreateEnvelope(order, deviceId, attempt2 = 1, options) {
1217
1239
  const id2 = order.customer?.id;
1218
1240
  const customerId = typeof id2 === "string" && id2.length > 0 && id2.length <= 64 ? id2 : void 0;
1219
1241
  const sessionId = order.sessionId ?? order.lateSessionId;
1220
- const { fees: _fees, shipping: _shipping, ...storedDisplay } = { ...order.display };
1242
+ const { fees: _fees, shipping: _shipping, coupons: _coupons, ...storedDisplay } = { ...order.display };
1221
1243
  return {
1222
1244
  id: order.commandId,
1223
1245
  type: "order.create",
@@ -1237,9 +1259,11 @@ function toOrderCreateEnvelope(order, deviceId, attempt2 = 1, options) {
1237
1259
  quantity: line.quantity,
1238
1260
  unitPriceMinor: line.unitPriceMinor,
1239
1261
  ...line.taxInclusive !== void 0 ? { taxInclusive: line.taxInclusive } : {},
1240
- ...lineDiscounts[i] > 0 ? { discountMinor: lineDiscounts[i] } : {}
1262
+ ...lineDiscounts[i] > 0 ? { discountMinor: lineDiscounts[i] } : {},
1263
+ ...version === 6 && line.regularUnitPriceMinor !== void 0 ? { regularUnitPriceMinor: line.regularUnitPriceMinor } : {},
1264
+ ...version === 6 && line.attributes && Object.keys(line.attributes).length ? { attributes: { ...line.attributes } } : {}
1241
1265
  })),
1242
- ...version === 5 && order.fees?.length ? { fees: order.fees.map((fee) => ({
1266
+ ...version >= 5 && order.fees?.length ? { fees: order.fees.map((fee) => ({
1243
1267
  clientFeeId: fee.id,
1244
1268
  name: fee.name,
1245
1269
  amountMinor: fee.amountMinor,
@@ -1247,7 +1271,7 @@ function toOrderCreateEnvelope(order, deviceId, attempt2 = 1, options) {
1247
1271
  ...fee.taxClass !== void 0 ? { taxClass: fee.taxClass } : {},
1248
1272
  taxMinor: roundMicrosToMinor(BigInt(fee.taxMicros))
1249
1273
  })) } : {},
1250
- ...version === 5 && order.shipping?.length ? { shipping: order.shipping.map((charge) => ({
1274
+ ...version >= 5 && order.shipping?.length ? { shipping: order.shipping.map((charge) => ({
1251
1275
  clientShippingId: charge.id,
1252
1276
  name: charge.name,
1253
1277
  ...charge.methodId !== void 0 ? { methodId: charge.methodId } : {},
@@ -1256,6 +1280,12 @@ function toOrderCreateEnvelope(order, deviceId, attempt2 = 1, options) {
1256
1280
  ...charge.taxClass !== void 0 ? { taxClass: charge.taxClass } : {},
1257
1281
  taxMinor: roundMicrosToMinor(BigInt(charge.taxMicros))
1258
1282
  })) } : {},
1283
+ ...version === 6 ? { coupons: order.coupons.map(({ code, couponId, discountMinor: discountMinor2, discountTaxMinor }) => ({
1284
+ code,
1285
+ couponId,
1286
+ discountMinor: discountMinor2,
1287
+ discountTaxMinor
1288
+ })) } : {},
1259
1289
  payments: order.payments.map((payment) => ({
1260
1290
  clientPaymentId: payment.id,
1261
1291
  method: payment.method,
@@ -1276,8 +1306,9 @@ function toOrderCreateEnvelope(order, deviceId, attempt2 = 1, options) {
1276
1306
  amountMinor,
1277
1307
  discounts
1278
1308
  })),
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 })) } : {}
1309
+ ...version >= 5 && order.display.fees ? { fees: order.display.fees.map(({ id: id3, amountMinor }) => ({ clientFeeId: id3, amountMinor })) } : {},
1310
+ ...version >= 5 && order.display.shipping ? { shipping: order.display.shipping.map(({ id: id3, amountMinor }) => ({ clientShippingId: id3, amountMinor })) } : {},
1311
+ ...version === 6 && order.display.coupons ? { coupons: order.display.coupons.map(({ code, amountMinor }) => ({ code, amountMinor })) } : {}
1281
1312
  },
1282
1313
  taxByRate: order.taxByRate.map(({ ratePpm, code, netMinor, amountMinor, grossMinor: grossMinor2 }) => ({
1283
1314
  ratePpm,
@@ -1311,10 +1342,9 @@ var orderDraftSchema = {
1311
1342
  required: ["id", "data"]
1312
1343
  };
1313
1344
  async function writeOrderDraft(drafts, snapshot) {
1314
- const { coupons: _coupons, ...draft } = snapshot;
1315
1345
  await drafts.upsert({
1316
1346
  id: snapshot.id,
1317
- data: JSON.stringify(draft),
1347
+ data: JSON.stringify(snapshot),
1318
1348
  customerName: snapshot.customer?.name ?? "",
1319
1349
  itemCount: snapshot.lineItems.length,
1320
1350
  total: snapshot.totalMinor,
@@ -1346,6 +1376,7 @@ function restoreOrderDraft(saved, options) {
1346
1376
  sku: line.sku,
1347
1377
  imageUrl: line.imageUrl,
1348
1378
  unitPrice: { amount: line.unitPriceMinor, currency, taxInclusive: line.taxInclusive },
1379
+ ...line.regularUnitPriceMinor !== void 0 ? { regularUnitPriceMinor: line.regularUnitPriceMinor } : {},
1349
1380
  quantity: line.quantity,
1350
1381
  taxRates: line.taxLines.map(({ code, ratePpm }) => ({ code, ratePpm }))
1351
1382
  });
@@ -1836,6 +1867,9 @@ function finalizeOrder(order, options = {}) {
1836
1867
  if ((order.fees?.length || order.shipping?.length || order.lineItems.some((line) => line.custom)) && (options.capabilities?.orderCreate ?? 1) < 5) {
1837
1868
  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
1869
  }
1870
+ if (order.coupons?.length && (options.capabilities?.orderCreate ?? 1) < 6) {
1871
+ throw new Error("finalize: coupons need the store to accept order.create version 6; update the store's TallyUI plugin");
1872
+ }
1839
1873
  if (!order.lineItems.length) throw new Error("finalize: no lines");
1840
1874
  if (order.discountMinor < 0 || order.lineItems.some((line) => line.discountMinor < 0) || order.discounts.some((d) => d.amountMinor < 0)) {
1841
1875
  throw new Error("finalize: negative discount");
@@ -1888,6 +1922,7 @@ function finalizeOrder(order, options = {}) {
1888
1922
  sku: line.sku,
1889
1923
  quantity: line.quantity,
1890
1924
  unitPriceMinor: line.unitPriceMinor,
1925
+ ...line.regularUnitPriceMinor !== void 0 ? { regularUnitPriceMinor: line.regularUnitPriceMinor } : {},
1891
1926
  discountMinor: line.discountMinor,
1892
1927
  netMinor: line.netMinor,
1893
1928
  ...order.taxRounding?.granularity === "woocommerce" ? { netMicros: line.netMicros } : {},
@@ -1983,6 +2018,7 @@ function finalizeOrder(order, options = {}) {
1983
2018
  taxMinor: order.taxMinor,
1984
2019
  totalMinor: order.totalMinor,
1985
2020
  taxRounding,
2021
+ ...order.coupons?.length ? { coupons: order.coupons.map(({ code, couponId, discountMinor, discountTaxMinor }) => ({ code, couponId, discountMinor, discountTaxMinor })) } : {},
1986
2022
  ...display && taxByRate ? { display, taxByRate } : {},
1987
2023
  customer: order.customer ? {
1988
2024
  id: order.customer.id,
@@ -2000,7 +2036,7 @@ function finalizeOrder(order, options = {}) {
2000
2036
  import { addRxPlugin } from "rxdb";
2001
2037
  import { RxDBMigrationSchemaPlugin } from "rxdb/plugins/migration-schema";
2002
2038
  var posOrderSchema = {
2003
- version: 8,
2039
+ version: 9,
2004
2040
  primaryKey: "id",
2005
2041
  type: "object",
2006
2042
  additionalProperties: false,
@@ -2010,6 +2046,7 @@ var posOrderSchema = {
2010
2046
  commandId: { type: "string", maxLength: 36 },
2011
2047
  createdAt: { type: "string", maxLength: 40 },
2012
2048
  updatedAt: { type: "string" },
2049
+ reopenedAt: { type: "string", maxLength: 40 },
2013
2050
  currency: { type: "string" },
2014
2051
  pricesIncludeTax: { type: "boolean" },
2015
2052
  subtotalMinor: { type: "integer" },
@@ -2021,6 +2058,12 @@ var posOrderSchema = {
2021
2058
  registerId: { type: "string" },
2022
2059
  sessionId: { type: "string", maxLength: 36 },
2023
2060
  cashierRef: { type: "string" },
2061
+ coupons: { type: "array", items: { type: "object", additionalProperties: false, properties: {
2062
+ code: { type: "string", minLength: 1, maxLength: 255 },
2063
+ couponId: { type: "string", minLength: 1, maxLength: 64 },
2064
+ discountMinor: { type: "integer", minimum: 0 },
2065
+ discountTaxMinor: { type: "integer", minimum: 0 }
2066
+ }, required: ["code", "couponId", "discountMinor", "discountTaxMinor"] } },
2024
2067
  lines: { type: "array", items: {
2025
2068
  type: "object",
2026
2069
  properties: {
@@ -2040,6 +2083,8 @@ var posOrderSchema = {
2040
2083
  unitPriceMinor: { type: "integer" },
2041
2084
  discountMinor: { type: "integer" },
2042
2085
  netMinor: { type: "integer" },
2086
+ attributes: { type: "object", additionalProperties: { type: "string" } },
2087
+ regularUnitPriceMinor: { type: "integer" },
2043
2088
  netMicros: { type: "string", pattern: "^-?[0-9]{1,24}$", maxLength: 25 },
2044
2089
  taxLines: { type: "array", items: {
2045
2090
  type: "object",
@@ -2127,8 +2172,8 @@ var posOrderSchema = {
2127
2172
  roundAtSubtotal: { type: "boolean" },
2128
2173
  mode: { type: "string", enum: ["half_away_from_zero", "half_up"] }
2129
2174
  }, required: ["granularity"] },
2130
- sentVersion: { type: "integer", minimum: 1, maximum: 5 },
2131
- downgradedFrom: { type: "integer", minimum: 1, maximum: 5 },
2175
+ sentVersion: { type: "integer", minimum: 1, maximum: 6 },
2176
+ downgradedFrom: { type: "integer", minimum: 1, maximum: 6 },
2132
2177
  // The nested objects are closed too: loosening a schema later is free, tightening one costs a migration.
2133
2178
  display: { type: "object", additionalProperties: false, properties: {
2134
2179
  currency: { type: "string" },
@@ -2139,6 +2184,10 @@ var posOrderSchema = {
2139
2184
  taxMinor: { type: "integer" },
2140
2185
  totalMinor: { type: "integer" },
2141
2186
  orderDiscountMinor: { type: "integer" },
2187
+ coupons: { type: "array", items: { type: "object", additionalProperties: false, properties: {
2188
+ code: { type: "string", minLength: 1, maxLength: 255 },
2189
+ amountMinor: { type: "integer" }
2190
+ }, required: ["code", "amountMinor"] } },
2142
2191
  fees: { type: "array", items: { type: "object", additionalProperties: false, properties: {
2143
2192
  id: { type: "string", maxLength: 36 },
2144
2193
  name: { type: "string", minLength: 1, maxLength: 255 },
@@ -2211,7 +2260,7 @@ function posOrderCollection() {
2211
2260
  };
2212
2261
  return {
2213
2262
  schema: posOrderSchema,
2214
- migrationStrategies: { 1: identity2, 2: identity2, 3: identity2, 4: identity2, 5: recordSent, 6: recordRounding, 7: identity2, 8: identity2 }
2263
+ migrationStrategies: { 1: identity2, 2: identity2, 3: identity2, 4: identity2, 5: recordSent, 6: recordRounding, 7: identity2, 8: identity2, 9: identity2 }
2215
2264
  };
2216
2265
  }
2217
2266
 
@@ -2411,47 +2460,20 @@ function getDeviceId(storage, key) {
2411
2460
 
2412
2461
  // src/pos-order/needs-attention.ts
2413
2462
  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
2463
 
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(/\.$/, "");
2464
+ // src/pos-order/reopened.ts
2465
+ function isReopened(order) {
2466
+ return order.syncStatus === "rejected" && order.reopenedAt !== void 0;
2442
2467
  }
2443
- function isServerDecimal(value) {
2444
- if (!SERVER_DECIMAL.test(value)) return false;
2445
- return value.split(".")[0].replace(/^0+/, "").length <= MAX_INTEGER_DIGITS;
2468
+ function replacedOrderIds(orders) {
2469
+ const predecessors = new Set(orders.filter((order) => order.saleId !== order.id).map((order) => order.saleId));
2470
+ return new Set(orders.filter((order) => order.syncStatus === "rejected" && predecessors.has(order.id)).map((order) => order.id));
2446
2471
  }
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;
2472
+
2473
+ // src/pos-order/needs-attention.ts
2474
+ function needsAttention(orders, options = {}) {
2475
+ const replaced = replacedOrderIds(orders);
2476
+ 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
2477
  }
2456
2478
 
2457
2479
  // src/register/expected.ts
@@ -2489,190 +2511,6 @@ function deriveExpected({
2489
2511
  return totals;
2490
2512
  }
2491
2513
 
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
2514
  // src/register/register-document.ts
2677
2515
  import { map as map4 } from "rxjs";
2678
2516
  var REGISTER = "register";
@@ -2899,15 +2737,55 @@ function recordRegisterFact(fact) {
2899
2737
  }
2900
2738
  }
2901
2739
 
2902
- // src/register/session-store.ts
2903
- var RegisterSessionRequiredError = class extends Error {
2904
- constructor() {
2905
- super("register_session_not_open");
2906
- this.name = "RegisterSessionRequiredError";
2740
+ // src/register/movement-input.ts
2741
+ var SERVER_DECIMAL = /^\d+(?:\.\d+)?$/;
2742
+ var MAX_INTEGER_DIGITS = 15;
2743
+ var MAX_REASON_LENGTH = 500;
2744
+ var KEYPAD_DECIMAL_COMMA = /^(\d+),(\d{1,2})$/;
2745
+ function normalizeAmount(raw) {
2746
+ const trimmed = raw.trim();
2747
+ const dotted = trimmed.replace(KEYPAD_DECIMAL_COMMA, "$1.$2");
2748
+ return dotted.replace(/^\./, "0.").replace(/\.$/, "");
2749
+ }
2750
+ function isServerDecimal(value) {
2751
+ if (!SERVER_DECIMAL.test(value)) return false;
2752
+ return value.split(".")[0].replace(/^0+/, "").length <= MAX_INTEGER_DIGITS;
2753
+ }
2754
+ function movementFieldError(input) {
2755
+ if (input.type !== "no_sale") {
2756
+ const amount = normalizeAmount(input.amount);
2757
+ if (!isServerDecimal(amount) || Number(amount) <= 0) return "amount";
2907
2758
  }
2908
- };
2909
- var RegisterSessionClosedError = class extends Error {
2910
- constructor() {
2759
+ const reason = input.reason.trim();
2760
+ if (!reason || reason.length > MAX_REASON_LENGTH) return "reason";
2761
+ return null;
2762
+ }
2763
+
2764
+ // src/register/register-count.helpers.ts
2765
+ function parseMinor(text2, exponent) {
2766
+ const [whole, fraction = ""] = text2.trim().split(".");
2767
+ if (fraction.length > exponent) return NaN;
2768
+ return Number(whole || "0") * 10 ** exponent + Number(fraction.padEnd(exponent, "0") || "0");
2769
+ }
2770
+ var validAmount = (value, exponent) => /^(?:\d+\.?\d*|\.\d+)$/.test(value) && Number.isFinite(Number(value)) && Number.isSafeInteger(parseMinor(value, exponent));
2771
+ var countVariance = (countedMinor, expectedMinor) => countedMinor - expectedMinor;
2772
+ var overThreshold = (variance, thresholdMinor) => thresholdMinor != null && Math.abs(variance) > thresholdMinor;
2773
+ var closeNeedsApproval = (countedCashMinor, expectedCashMinor, thresholdMinor) => overThreshold(countVariance(countedCashMinor, expectedCashMinor), thresholdMinor);
2774
+ var denominationTotal = (pieces) => Object.entries(pieces).reduce((sum, [value, count]) => sum + Number(value) * count, 0);
2775
+ function varianceText(variance, exponent, format2, t) {
2776
+ if (!variance) return t("register.exact");
2777
+ return `${format2(Math.abs(variance) / 10 ** exponent)} ${t(variance < 0 ? "register.short" : "register.over")}`;
2778
+ }
2779
+
2780
+ // src/register/session-store.ts
2781
+ var RegisterSessionRequiredError = class extends Error {
2782
+ constructor() {
2783
+ super("register_session_not_open");
2784
+ this.name = "RegisterSessionRequiredError";
2785
+ }
2786
+ };
2787
+ var RegisterSessionClosedError = class extends Error {
2788
+ constructor() {
2911
2789
  super("register_session_closed");
2912
2790
  this.name = "RegisterSessionClosedError";
2913
2791
  }
@@ -3173,7 +3051,8 @@ async function writeClosure({
3173
3051
  });
3174
3052
  return existing;
3175
3053
  }
3176
- const bound = orders.filter((order) => order.sessionId === session.id);
3054
+ const replaced = replacedOrderIds(orders);
3055
+ const bound = orders.filter((order) => order.sessionId === session.id && !replaced.has(order.id));
3177
3056
  const countedRefunds = (refunds ?? []).filter((refund) => refund.status === "applied" && refund.sessionId === session.id);
3178
3057
  const rows = bound.flatMap(
3179
3058
  (order) => order.payments.map((payment) => ({
@@ -3306,6 +3185,278 @@ async function writeClosure({
3306
3185
  return row;
3307
3186
  }
3308
3187
 
3188
+ // src/pos-order/reopen.ts
3189
+ var REOPENABLE_CODES = ["coupon_invalid", "total_mismatch"];
3190
+ var ReopenRefusedOrderError = class extends Error {
3191
+ constructor(orderId, reason) {
3192
+ super(`Cannot reopen order ${orderId}: ${reason}`);
3193
+ this.orderId = orderId;
3194
+ this.reason = reason;
3195
+ this.name = "ReopenRefusedOrderError";
3196
+ }
3197
+ };
3198
+ async function reopenRefusedOrder(orderId, deps) {
3199
+ const [order] = await readFresh(deps.orders, { selector: { id: orderId } });
3200
+ if (!order) throw new ReopenRefusedOrderError(orderId, "not_found");
3201
+ if (order.syncStatus !== "rejected") throw new ReopenRefusedOrderError(orderId, "not_rejected");
3202
+ if (!REOPENABLE_CODES.includes(order.error?.code ?? "")) throw new ReopenRefusedOrderError(orderId, "code_not_reopenable");
3203
+ const successors = await readFresh(deps.orders, { selector: { saleId: orderId } });
3204
+ if (successors.some((successor) => successor.id !== orderId)) throw new ReopenRefusedOrderError(orderId, "already_replaced");
3205
+ if (order.sessionId) {
3206
+ const session = await readSession(deps.sessions, order.sessionId);
3207
+ if (!session || session.status !== "open") throw new ReopenRefusedOrderError(orderId, "session_closed");
3208
+ }
3209
+ if (!await deps.drafts.findOne(orderId).exec()) {
3210
+ const builder = createOrderBuilder({ currency: order.currency, taxContext: deps.taxContext, id: order.id });
3211
+ const converted = order.lines.some((line) => line.taxInclusive !== void 0 && line.taxInclusive !== order.pricesIncludeTax);
3212
+ const display = order.display && !converted ? order.display : void 0;
3213
+ for (const [i, line] of order.lines.entries()) {
3214
+ const lineId = builder.addLine({
3215
+ productId: line.productId,
3216
+ variantId: line.variantId,
3217
+ name: line.name,
3218
+ sku: line.sku,
3219
+ unitPrice: { amount: line.unitPriceMinor, currency: order.currency, taxInclusive: line.taxInclusive },
3220
+ ...line.regularUnitPriceMinor !== void 0 ? { regularUnitPriceMinor: line.regularUnitPriceMinor } : {},
3221
+ quantity: line.quantity,
3222
+ taxRates: line.taxLines.map(({ code, ratePpm }) => ({ code, ratePpm })),
3223
+ ...line.custom ? { custom: true, taxClass: line.custom.taxClass, taxStatus: line.custom.taxStatus } : { taxClass: deps.taxClassOf?.(line.productId, line.variantId) ?? "standard", taxStatus: line.taxStatus }
3224
+ });
3225
+ if (display) {
3226
+ for (const row of display.lines[i].discounts) builder.applyLineDiscount(lineId, {
3227
+ type: "fixed",
3228
+ value: row.amountMinor,
3229
+ ...row.label !== void 0 ? { label: row.label } : {}
3230
+ });
3231
+ } else if (line.discountMinor > 0) {
3232
+ builder.applyLineDiscount(lineId, { type: "fixed", value: line.discountMinor, label: "Discount" });
3233
+ }
3234
+ }
3235
+ if (display && display.orderDiscountMinor > 0) {
3236
+ builder.applyOrderDiscount({ type: "fixed", value: display.orderDiscountMinor, label: "Discount" });
3237
+ }
3238
+ for (const fee of order.fees ?? []) builder.addFee({
3239
+ name: fee.name,
3240
+ amountMinor: fee.amountMinor,
3241
+ ...fee.taxClass !== void 0 ? { taxClass: fee.taxClass } : {},
3242
+ ...fee.taxStatus !== void 0 ? { taxStatus: fee.taxStatus } : {}
3243
+ });
3244
+ for (const shipping of order.shipping ?? []) builder.addShipping({
3245
+ name: shipping.name,
3246
+ amountMinor: shipping.amountMinor,
3247
+ ...shipping.taxClass !== void 0 ? { taxClass: shipping.taxClass } : {},
3248
+ ...shipping.taxStatus !== void 0 ? { taxStatus: shipping.taxStatus } : {},
3249
+ ...shipping.methodId !== void 0 ? { methodId: shipping.methodId } : {}
3250
+ });
3251
+ for (const payment of order.payments) builder.addPayment({
3252
+ method: payment.method,
3253
+ amountMinor: payment.amountMinor,
3254
+ ...payment.reference !== void 0 ? { reference: payment.reference } : {}
3255
+ });
3256
+ if (order.customer?.id && order.customer.name && customerRefusal(order.customer) === null) {
3257
+ builder.setCustomer({
3258
+ id: order.customer.id,
3259
+ name: order.customer.name,
3260
+ ...order.customer.email !== void 0 ? { email: order.customer.email } : {}
3261
+ });
3262
+ }
3263
+ const prefix = `Refused by the store: ${order.error.message}`;
3264
+ builder.setNote(prefix + (order.note ? "\n" + order.note : ""));
3265
+ await writeOrderDraft(deps.drafts, builder.getSnapshot());
3266
+ }
3267
+ const document = await deps.orders.findOne(orderId).exec();
3268
+ await document.incrementalModify((data) => {
3269
+ if (data.syncStatus === "rejected" && !data.reopenedAt) {
3270
+ data.reopenedAt = data.updatedAt = (deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
3271
+ }
3272
+ return data;
3273
+ });
3274
+ return orderId;
3275
+ }
3276
+
3277
+ // src/pos-order/same-sale.ts
3278
+ function sameSale(stored, retried) {
3279
+ return stored.totalMinor === retried.totalMinor && stored.currency === retried.currency && stored.lines.length === retried.lines.length && stored.lines.every((line, i) => {
3280
+ const other = retried.lines[i];
3281
+ return line.id === other.id && line.quantity === other.quantity && line.netMinor === other.netMinor;
3282
+ }) && stored.payments.length === retried.payments.length && stored.payments.every((payment, i) => payment.method === retried.payments[i].method && payment.amountMinor === retried.payments[i].amountMinor);
3283
+ }
3284
+ var OrderContentMismatchError = class extends Error {
3285
+ constructor(orderId) {
3286
+ super(`Order ${orderId} is already stored with different content`);
3287
+ this.orderId = orderId;
3288
+ this.name = "OrderContentMismatchError";
3289
+ }
3290
+ };
3291
+
3292
+ // src/register/register-count.denominations.ts
3293
+ var coinsMinor = [200, 100, 50, 20, 10, 5, 2, 1];
3294
+ var denominations = {
3295
+ GBP: [5e3, 2e3, 1e3, 500, ...coinsMinor],
3296
+ EUR: [5e4, 2e4, 1e4, 5e3, 2e3, 1e3, 500, ...coinsMinor],
3297
+ USD: [1e4, 5e3, 2e3, 1e3, 500, 100, 25, 10, 5, 1],
3298
+ default: [1e4, 5e3, 2e3, 1e3, 500, 200, 100, 50, 25, 10, 5, 1]
3299
+ };
3300
+
3301
+ // src/register/schemas.ts
3302
+ import { addRxPlugin as addRxPlugin2 } from "rxdb";
3303
+ import { RxDBLocalDocumentsPlugin } from "rxdb/plugins/local-documents";
3304
+ import { RxDBMigrationSchemaPlugin as RxDBMigrationSchemaPlugin2 } from "rxdb/plugins/migration-schema";
3305
+ var id = { type: "string", maxLength: 36 };
3306
+ var text = { type: "string" };
3307
+ var nullableText = { type: ["string", "null"] };
3308
+ var minor = { type: "integer" };
3309
+ var nullableMinor = { type: ["integer", "null"] };
3310
+ var tenders = { type: "object", additionalProperties: minor };
3311
+ var registerSessionSchema = {
3312
+ title: "Register sessions",
3313
+ version: 1,
3314
+ primaryKey: "id",
3315
+ type: "object",
3316
+ additionalProperties: false,
3317
+ properties: {
3318
+ id,
3319
+ register_id: id,
3320
+ store_key: nullableText,
3321
+ status: { type: "string", maxLength: 20 },
3322
+ server_session_id: { ...nullableText, default: null },
3323
+ business_day: { type: "string", maxLength: 10 },
3324
+ opened_at_gmt: text,
3325
+ opened_by: nullableText,
3326
+ expected_float_minor: nullableMinor,
3327
+ counted_float_minor: minor,
3328
+ opening_variance_minor: nullableMinor,
3329
+ counting_started_at_gmt: nullableText,
3330
+ closed_at_gmt: nullableText,
3331
+ closed_by: nullableText,
3332
+ approval_required: { type: "boolean", default: false },
3333
+ approved_by: nullableText,
3334
+ counted: { type: ["object", "null"], additionalProperties: minor },
3335
+ closure_id: nullableText,
3336
+ pending_status: { ...nullableText, default: null },
3337
+ server_status: { ...nullableText, default: null },
3338
+ status_at: { ...nullableText, default: null },
3339
+ approver_token: { ...nullableText, default: null },
3340
+ server_expected: { type: ["object", "null"], additionalProperties: minor, default: null },
3341
+ server_sales_count: { type: ["integer", "null"], default: null }
3342
+ },
3343
+ required: ["id", "register_id", "status", "opened_at_gmt", "counted_float_minor"],
3344
+ indexes: [["register_id", "status"]]
3345
+ };
3346
+ function registerSessionCreator() {
3347
+ addRxPlugin2(RxDBLocalDocumentsPlugin);
3348
+ addRxPlugin2(RxDBMigrationSchemaPlugin2);
3349
+ return { schema: registerSessionSchema, localDocuments: true, migrationStrategies: { 1: (doc) => {
3350
+ doc.server_session_id ??= null;
3351
+ return doc;
3352
+ } } };
3353
+ }
3354
+ function registerSessionCollection() {
3355
+ 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).");
3356
+ }
3357
+ var cashMovementSchema = {
3358
+ title: "Cash movements",
3359
+ version: 0,
3360
+ primaryKey: "id",
3361
+ type: "object",
3362
+ additionalProperties: false,
3363
+ properties: {
3364
+ id,
3365
+ session_id: id,
3366
+ type: { type: "string", enum: ["paid_in", "paid_out", "no_sale", "void"] },
3367
+ amountMinor: minor,
3368
+ reason: text,
3369
+ created_at_gmt: text,
3370
+ created_by: nullableText,
3371
+ voids: nullableText,
3372
+ voided_by: nullableText
3373
+ },
3374
+ required: ["id", "session_id", "type", "amountMinor", "reason", "created_at_gmt"],
3375
+ indexes: [["session_id"]]
3376
+ };
3377
+ var closureSchema = {
3378
+ title: "Register closures",
3379
+ version: 0,
3380
+ primaryKey: "id",
3381
+ type: "object",
3382
+ additionalProperties: false,
3383
+ properties: {
3384
+ id,
3385
+ session_id: id,
3386
+ register_id: id,
3387
+ store_key: nullableText,
3388
+ business_day: { type: "string", maxLength: 10 },
3389
+ closed_by: nullableText,
3390
+ corrections_count: { type: "integer" },
3391
+ number: { type: "integer" },
3392
+ opened_at: text,
3393
+ closed_at: text,
3394
+ till_expected: tenders,
3395
+ expected: tenders,
3396
+ counted: tenders,
3397
+ variance: tenders,
3398
+ period_sales_total_minor: minor,
3399
+ period_refunds_total_minor: minor,
3400
+ perpetual_sales_total_minor: minor,
3401
+ perpetual_refunds_total_minor: minor,
3402
+ unsynced_count: { type: "integer" },
3403
+ unsynced_total_minor: minor,
3404
+ software_version: text,
3405
+ breakdowns: { type: "object", additionalProperties: true },
3406
+ order_ids: { type: "array", items: text },
3407
+ movement_ids: { type: "array", items: text },
3408
+ server_closure_id: { ...nullableText, default: null },
3409
+ printed_at: { ...nullableText, default: null },
3410
+ print_count: { type: "integer", default: 0 },
3411
+ number_retried: { type: "boolean", default: false }
3412
+ },
3413
+ required: [
3414
+ "id",
3415
+ "session_id",
3416
+ "register_id",
3417
+ "number",
3418
+ "opened_at",
3419
+ "closed_at",
3420
+ "till_expected",
3421
+ "expected",
3422
+ "counted",
3423
+ "variance",
3424
+ "period_sales_total_minor",
3425
+ "period_refunds_total_minor",
3426
+ "perpetual_sales_total_minor",
3427
+ "perpetual_refunds_total_minor",
3428
+ "unsynced_count",
3429
+ "unsynced_total_minor",
3430
+ "software_version",
3431
+ "breakdowns",
3432
+ "order_ids",
3433
+ "movement_ids",
3434
+ "print_count"
3435
+ ],
3436
+ indexes: [["register_id"], ["session_id"]]
3437
+ };
3438
+
3439
+ // src/register/open.ts
3440
+ var registerSessionsLogger = createLogger("register-sessions");
3441
+ var REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS = 1e4;
3442
+ var RegisterSessionOpenClosedError = class extends Error {
3443
+ constructor(databaseName) {
3444
+ super(`addRegisterSessionCollection: database ${databaseName} closed during the open; reopen it and open register_sessions again`);
3445
+ this.databaseName = databaseName;
3446
+ this.name = "RegisterSessionOpenClosedError";
3447
+ }
3448
+ code = "REGISTER_SESSION_OPEN_CLOSED";
3449
+ };
3450
+ function addRegisterSessionCollection(db, closeWaitMs = REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS) {
3451
+ return openMigratedCollection(db, {
3452
+ name: "register_sessions",
3453
+ creator: registerSessionCreator,
3454
+ label: "addRegisterSessionCollection",
3455
+ logger: registerSessionsLogger,
3456
+ closedError: (name) => new RegisterSessionOpenClosedError(name)
3457
+ }, closeWaitMs);
3458
+ }
3459
+
3309
3460
  // src/register/settled-figures.ts
3310
3461
  function deriveSettled(recorded, corrections) {
3311
3462
  const settled = {
@@ -3996,8 +4147,8 @@ function currentSession(rows, closureRows, reservation) {
3996
4147
  if (rows.some((row) => !isKnownSessionStatus(row.status))) return null;
3997
4148
  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
4149
  }
3999
- function ledgerRows(orders) {
4000
- return orders.flatMap((order) => order.payments.map((payment) => ({
4150
+ function ledgerRows(orders, replaced = replacedOrderIds(orders)) {
4151
+ return orders.filter((order) => !replaced.has(order.id)).flatMap((order) => order.payments.map((payment) => ({
4001
4152
  session_id: order.sessionId,
4002
4153
  kind: payment.method === "cash" ? "cash" : "other",
4003
4154
  method_id: payment.method,
@@ -4108,7 +4259,8 @@ function useRegisterSession(options) {
4108
4259
  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
4260
  const entries = data?.entries ?? [];
4110
4261
  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 ?? [] }) : {};
4262
+ const replaced = replacedOrderIds(sales);
4263
+ const expected = session ? deriveExpected({ session: { id: session.id, countedFloatMinor: session.counted_float_minor }, movements: entries, ledgerRowsBySession: ledgerRows(sales, replaced), refunds: data?.refundRows ?? [] }) : {};
4112
4264
  const now = /* @__PURE__ */ new Date();
4113
4265
  const [hour, minute] = String(expectedCloseTime ?? "").split(":").map(Number);
4114
4266
  const overdue = session?.status === "open" && !!expectedCloseTime && now.getTime() > new Date(now.getFullYear(), now.getMonth(), now.getDate(), hour, minute).getTime();
@@ -4137,7 +4289,7 @@ function useRegisterSession(options) {
4137
4289
  needsUpgrade: data?.rows.some((row) => !isKnownSessionStatus(row.status)) ?? false,
4138
4290
  movements: entries,
4139
4291
  expected,
4140
- salesCount: sales.length,
4292
+ salesCount: sales.filter((order) => !replaced.has(order.id)).length,
4141
4293
  overdue,
4142
4294
  /** 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
4295
  closing,
@@ -4376,8 +4528,9 @@ function addEntryToCart(builder, entry, traits, currency) {
4376
4528
  return existing.id;
4377
4529
  }
4378
4530
  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}`);
4531
+ const resolved = resolvePrice3(variant.prices, currency);
4532
+ if (!resolved) throw new CartError(`No ${currency} price for ${name}`);
4533
+ const unitPrice = resolved.current, regularPrice = regularUnitPriceMinor(resolved);
4381
4534
  return builder.addLine({
4382
4535
  productId: traits.getId(product),
4383
4536
  variantId: variant.id,
@@ -4385,11 +4538,15 @@ function addEntryToCart(builder, entry, traits, currency) {
4385
4538
  sku: variant.sku ?? "",
4386
4539
  imageUrl: traits.getImageUrl?.(product),
4387
4540
  unitPrice,
4541
+ ...regularPrice !== void 0 ? { regularUnitPriceMinor: regularPrice } : {},
4388
4542
  taxClass: traits.getTaxClass?.(product, variant.id),
4389
4543
  ...traits.getTaxStatus?.(product, variant.id) === "none" ? { taxStatus: "none" } : {}
4390
4544
  });
4391
4545
  }
4392
4546
 
4547
+ // src/sale/discount-codes.ts
4548
+ var COUPONS_UNSUPPORTED = "This store's plugin does not support coupons yet";
4549
+
4393
4550
  // src/sale/use-sale.ts
4394
4551
  var saleLogger = createLogger("sale");
4395
4552
  var DISCOUNTS_UNSUPPORTED = "finalize: discounts are not supported by the server yet (order.create v2)";
@@ -4400,6 +4557,15 @@ function useSale(settings, opts) {
4400
4557
  const madeWith = useRef3({ taxContext, currency: settings.currency });
4401
4558
  const [rendered, setBuilder] = useState4(() => createOrderBuilder({ currency: settings.currency, taxContext }));
4402
4559
  const builderNow = useRef3(rendered);
4560
+ const applied = useRef3(/* @__PURE__ */ new Map());
4561
+ const appliedWith = useRef3(null);
4562
+ const categories = useRef3(/* @__PURE__ */ new Map());
4563
+ function discountState(order2, accepted) {
4564
+ return { order: order2, accepted: new Map(accepted), categories: categories.current, settings: { calcDiscountsSequentially: settings.calcDiscountsSequentially } };
4565
+ }
4566
+ function codesFor() {
4567
+ return opts.capabilities?.coupons === true && (opts.capabilities?.orderCreate ?? 1) >= 6 && opts.discountCodes && opts.discountCodes.supports({ capabilities: opts.capabilities, rounding: taxContext.rounding }) ? opts.discountCodes : null;
4568
+ }
4403
4569
  const [order, setOrder] = useState4(() => rendered.getSnapshot());
4404
4570
  const [stage, setStage] = useState4({ kind: "cart" });
4405
4571
  const [saleError, setError] = useState4(null);
@@ -4449,6 +4615,8 @@ function useSale(settings, opts) {
4449
4615
  const next = restored ?? createOrderBuilder({ currency: settings.currency, taxContext });
4450
4616
  if (customer !== null) next.setCustomer(customer);
4451
4617
  builderNow.current = next;
4618
+ applied.current.clear();
4619
+ appliedWith.current = null;
4452
4620
  setBuilder(next);
4453
4621
  setOrder(next.getSnapshot());
4454
4622
  setStage({ kind: "cart" });
@@ -4566,6 +4734,11 @@ function useSale(settings, opts) {
4566
4734
  const builder = builderNow.current;
4567
4735
  try {
4568
4736
  const known = new Set(builder.getSnapshot().lineItems.map((line2) => line2.id));
4737
+ const productId = Number(traits.getId(entry.product));
4738
+ if (Number.isSafeInteger(productId) && productId >= 0) {
4739
+ const ids = productCategories(entry.product, traits).map(({ id: id2 }) => ({ id: Number(id2) })).filter(({ id: id2 }) => Number.isSafeInteger(id2));
4740
+ if (ids.length) categories.current.set(productId, ids);
4741
+ }
4569
4742
  const lineId = addEntryToCart(builder, entry, traits, madeWith.current.currency);
4570
4743
  const line = builder.getSnapshot().lineItems.find((item) => item.id === lineId && !known.has(item.id));
4571
4744
  const name = line && `"${cutText(line.name, MESSAGE_NAME_MAX)}"`;
@@ -4685,11 +4858,11 @@ function useSale(settings, opts) {
4685
4858
  if (locked()) return SALE_SAVING;
4686
4859
  if ((opts.capabilities?.orderCreate ?? 1) < 2) return DISCOUNTS_UNSUPPORTED;
4687
4860
  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));
4861
+ const applied2 = (snapshot) => lineId === null ? snapshot.discounts : snapshot.lineItems.find((line) => line.id === lineId)?.discounts ?? [];
4862
+ const before = new Set(applied2(builder.getSnapshot()).map((entry) => entry.id));
4690
4863
  if (lineId === null) builder.applyOrderDiscount(discount);
4691
4864
  else builder.applyLineDiscount(lineId, discount);
4692
- const added = applied(builder.getSnapshot()).find((entry) => !before.has(entry.id));
4865
+ const added = applied2(builder.getSnapshot()).find((entry) => !before.has(entry.id));
4693
4866
  if (added?.type === "fixed" && added.amountMinor < added.value) {
4694
4867
  builder.removeDiscount(added.id);
4695
4868
  return `The discount is more than the ${lineId === null ? "order" : "line"}`;
@@ -4699,6 +4872,42 @@ function useSale(settings, opts) {
4699
4872
  removeDiscount(id2) {
4700
4873
  if (!locked()) builderNow.current.removeDiscount(id2);
4701
4874
  },
4875
+ /** 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. */
4876
+ async applyCoupon(code) {
4877
+ if (locked()) return SALE_SAVING;
4878
+ const codes = codesFor();
4879
+ if (!codes) return COUPONS_UNSUPPORTED;
4880
+ const builder = builderNow.current, normalized = code.trim().toLowerCase();
4881
+ if (!normalized) return "Enter a coupon code";
4882
+ const result2 = await codes.find(normalized, discountState(builder.getSnapshot(), applied.current));
4883
+ if ("refusal" in result2) return result2.refusal;
4884
+ if (locked()) return SALE_SAVING;
4885
+ if (builderNow.current !== builder || stageNow.current.kind === "receipt") return "The sale changed while the coupon was being checked; apply it again";
4886
+ const refusal = codes.check(normalized, result2.found, discountState(builder.getSnapshot(), applied.current));
4887
+ if (refusal !== null) return refusal;
4888
+ const next = new Map([...applied.current, [normalized, result2.found]]);
4889
+ try {
4890
+ codes.apply(builder, discountState(builder.getSnapshot(), next));
4891
+ } catch (error2) {
4892
+ if (error2 instanceof Error) return error2.message;
4893
+ throw error2;
4894
+ }
4895
+ applied.current.set(normalized, result2.found);
4896
+ appliedWith.current = codes;
4897
+ setError(null);
4898
+ return null;
4899
+ },
4900
+ /** Removes an applied coupon; returns the refusal to show, or null once removed. */
4901
+ removeCoupon(code) {
4902
+ if (locked()) return SALE_SAVING;
4903
+ const normalized = code.trim().toLowerCase();
4904
+ if (!applied.current.has(normalized)) return null;
4905
+ const remaining = new Map(applied.current);
4906
+ remaining.delete(normalized);
4907
+ appliedWith.current.apply(builderNow.current, discountState(builderNow.current.getSnapshot(), remaining));
4908
+ applied.current.delete(normalized);
4909
+ return null;
4910
+ },
4702
4911
  /** the picked customer reaches the server as order.create v3's customer.customerId */
4703
4912
  setCustomer(customer) {
4704
4913
  if (locked()) return;
@@ -4862,13 +5071,42 @@ function useSale(settings, opts) {
4862
5071
  }
4863
5072
  }
4864
5073
  }
5074
+ const kept = /* @__PURE__ */ new Map(), messages = [];
5075
+ const codes = saved.coupons?.length ? codesFor() : null;
5076
+ if (n > 0) messages.push(`Prices changed since this sale was parked: ${n} ${n === 1 ? "line" : "lines"} updated to today's price.`);
5077
+ if (saved.coupons?.length) {
5078
+ const supported = codes !== null;
5079
+ if (supported) await codes.beforeResume?.(discountState(builder.getSnapshot(), /* @__PURE__ */ new Map()));
5080
+ for (const { code } of saved.coupons) {
5081
+ let reason = supported ? null : COUPONS_UNSUPPORTED;
5082
+ if (supported) {
5083
+ const result2 = await codes.find(code, discountState(builder.getSnapshot(), kept));
5084
+ if ("refusal" in result2) reason = result2.refusal;
5085
+ else {
5086
+ reason = codes.check(code, result2.found, discountState(builder.getSnapshot(), kept));
5087
+ if (reason === null) try {
5088
+ codes.apply(builder, discountState(builder.getSnapshot(), new Map([...kept, [code, result2.found]])));
5089
+ kept.set(code, result2.found);
5090
+ } catch (error2) {
5091
+ if (error2 instanceof Error) reason = error2.message;
5092
+ else throw error2;
5093
+ }
5094
+ }
5095
+ }
5096
+ if (reason !== null) messages.push(`Coupon ${code} was removed: ${reason}.`);
5097
+ }
5098
+ }
4865
5099
  await doc.remove();
4866
5100
  if (builderNow.current !== live || live.getSnapshot() !== liveSnapshot) {
4867
5101
  await writeOrderDraft(opts.drafts, saved);
4868
5102
  return "The sale changed while it was being resumed; resume it again";
4869
5103
  }
4870
5104
  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.`);
5105
+ if (builderNow.current === builder) {
5106
+ applied.current = kept;
5107
+ appliedWith.current = kept.size ? codes : null;
5108
+ }
5109
+ if (messages.length) setError(messages.join(" "));
4872
5110
  return null;
4873
5111
  },
4874
5112
  /**
@@ -4883,6 +5121,197 @@ function useSale(settings, opts) {
4883
5121
  return result;
4884
5122
  }
4885
5123
 
5124
+ // src/sale/woocommerce/index.ts
5125
+ var woocommerce_exports = {};
5126
+ __export(woocommerce_exports, {
5127
+ couponRefusal: () => couponRefusal,
5128
+ createDiscountCodes: () => createDiscountCodes,
5129
+ createSaleCouponSource: () => createSaleCouponSource,
5130
+ startCouponUsageRefetch: () => startCouponUsageRefetch
5131
+ });
5132
+
5133
+ // src/sale/woocommerce/discount-codes.ts
5134
+ import { minorUnitDigits as minorUnitDigits4, woocommerceCoupons as woocommerceCoupons3 } from "@tallyui/core";
5135
+
5136
+ // src/sale/woocommerce/coupons.ts
5137
+ import { minorUnitDigits as minorUnitDigits3 } from "@tallyui/core";
5138
+ function couponRefusal(code, rejection) {
5139
+ switch (rejection.code) {
5140
+ case "already_applied":
5141
+ return `Coupon ${code} is already applied`;
5142
+ case "expired":
5143
+ return `Coupon ${code} has expired`;
5144
+ case "usage_limit_reached":
5145
+ return `Coupon ${code} has reached its usage limit`;
5146
+ case "usage_limit_reached_for_customer":
5147
+ return `This customer has used coupon ${code} as often as it allows`;
5148
+ case "minimum_spend_not_met":
5149
+ return `Coupon ${code} needs a spend of at least ${rejection.params?.amount}`;
5150
+ case "maximum_spend_exceeded":
5151
+ return `Coupon ${code} allows a spend of at most ${rejection.params?.amount}`;
5152
+ case "individual_use":
5153
+ return `Coupon ${code} cannot be used with other coupons`;
5154
+ case "individual_use_conflict":
5155
+ return `Coupon ${rejection.params?.code} cannot be used with other coupons`;
5156
+ case "email_required":
5157
+ return `Coupon ${code} needs a customer with an email address`;
5158
+ case "email_not_allowed":
5159
+ return `This customer's email address cannot use coupon ${code}`;
5160
+ case "not_applicable_to_cart":
5161
+ return `Coupon ${code} does not apply to anything in this sale`;
5162
+ }
5163
+ }
5164
+ function couponLineItems(lines, currency, categories) {
5165
+ const digits = minorUnitDigits3(currency), factor = 10 ** digits;
5166
+ return lines.flatMap((line, lineIndex) => {
5167
+ if (line.unitPriceMinor < 0) return [];
5168
+ const id2 = Number(line.productId), product_id = !line.custom && Number.isSafeInteger(id2) && id2 >= 0 ? id2 : 0;
5169
+ return [{
5170
+ product_id,
5171
+ quantity: line.quantity,
5172
+ price: line.unitPriceMinor / factor,
5173
+ subtotal: (line.netMinor / factor).toFixed(digits),
5174
+ total: (line.netMinor / factor).toFixed(digits),
5175
+ categories: [...categories.get(product_id) ?? []],
5176
+ lineIndex,
5177
+ on_sale: line.regularUnitPriceMinor !== void 0 && line.unitPriceMinor < line.regularUnitPriceMinor
5178
+ }];
5179
+ });
5180
+ }
5181
+
5182
+ // src/sale/woocommerce/discount-codes.ts
5183
+ function wooCustomerId(customer) {
5184
+ const id2 = Number(customer?.id);
5185
+ return Number.isSafeInteger(id2) && id2 > 0 ? id2 : null;
5186
+ }
5187
+ function createDiscountCodes(source) {
5188
+ return {
5189
+ supports: ({ rounding }) => rounding?.granularity === "woocommerce",
5190
+ async find(code, sale) {
5191
+ if (sale.accepted.has(code)) return { refusal: couponRefusal(code, { code: "already_applied" }) };
5192
+ const coupon = await source.find(code);
5193
+ return coupon === null ? { refusal: `Coupon ${code} does not exist` } : { found: coupon };
5194
+ },
5195
+ check(code, coupon, sale) {
5196
+ const snapshot = sale.order;
5197
+ const validation = woocommerceCoupons3.validateCoupon(coupon, {
5198
+ lineItems: couponLineItems(snapshot.lineItems, snapshot.currency, sale.categories),
5199
+ appliedCoupons: [...sale.accepted.keys()],
5200
+ appliedCouponsWithIndividualUse: [...sale.accepted].filter(([, value]) => value.individual_use).map(([key]) => key),
5201
+ cartSubtotal: snapshot.display.subtotalMinor / 10 ** minorUnitDigits4(snapshot.currency),
5202
+ customerEmail: snapshot.customer?.email ?? "",
5203
+ customerId: wooCustomerId(snapshot.customer),
5204
+ now: Date.now()
5205
+ });
5206
+ return validation.valid ? null : couponRefusal(code, validation.rejection);
5207
+ },
5208
+ apply(builder, sale) {
5209
+ const context = {
5210
+ configs: woocommerceCoupons3.toCouponConfigs([...sale.accepted.keys()], sale.accepted),
5211
+ couponIds: new Map([...sale.accepted].map(([code, coupon]) => [code, String(coupon.id)])),
5212
+ productCategories: sale.categories,
5213
+ calcDiscountsSequentially: sale.settings.calcDiscountsSequentially ?? false
5214
+ };
5215
+ builder.setCoupons([...sale.accepted.keys()], context);
5216
+ },
5217
+ async beforeResume(sale) {
5218
+ const ids = sale.order.lineItems.filter((line) => !line.custom).map((line) => Number(line.productId)).filter((id2) => Number.isSafeInteger(id2) && id2 >= 0);
5219
+ for (const [id2, values] of await source.productCategories(ids)) if (values.length) sale.categories.set(id2, [...values]);
5220
+ }
5221
+ };
5222
+ }
5223
+
5224
+ // src/sale/woocommerce/coupon-source.ts
5225
+ var APPLIED_USE_GRACE_MS = 6e5;
5226
+ function createSaleCouponSource(deps) {
5227
+ const now = deps.now ?? Date.now;
5228
+ return {
5229
+ async find(code) {
5230
+ let doc = await deps.coupons.findOne({ selector: { code } }).exec();
5231
+ if (!doc) {
5232
+ doc = (await deps.coupons.find().exec()).find((coupon) => typeof coupon.code === "string" && coupon.code.toLowerCase() === code) ?? null;
5233
+ }
5234
+ if (!doc) return null;
5235
+ const data = doc.toJSON(true);
5236
+ if (!["percent", "fixed_cart", "fixed_product"].includes(data.discount_type) || !Number.isInteger(data.id) || typeof data.amount !== "string") return null;
5237
+ const orders = await deps.orders.find({ selector: { syncStatus: { $in: ["pending", "applied"] } } }).exec();
5238
+ 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));
5239
+ const usedBy = [...data.used_by ?? []];
5240
+ for (const order of counted) {
5241
+ const id2 = Number(order.customer?.id);
5242
+ const email = order.customer?.email;
5243
+ if (Number.isSafeInteger(id2) && id2 > 0) usedBy.push(String(id2));
5244
+ else if (typeof email === "string" && email.length > 0) usedBy.push(email.toLowerCase());
5245
+ }
5246
+ const fields = [
5247
+ "limit_usage_to_x_items",
5248
+ "product_ids",
5249
+ "excluded_product_ids",
5250
+ "product_categories",
5251
+ "excluded_product_categories",
5252
+ "exclude_sale_items",
5253
+ "individual_use",
5254
+ "date_expires_gmt",
5255
+ "usage_limit",
5256
+ "usage_limit_per_user",
5257
+ "minimum_amount",
5258
+ "maximum_amount",
5259
+ "email_restrictions"
5260
+ ];
5261
+ return {
5262
+ ...Object.fromEntries(fields.filter((field) => field in data).map((field) => [field, data[field]])),
5263
+ discount_type: data.discount_type,
5264
+ amount: data.amount,
5265
+ id: data.id,
5266
+ code,
5267
+ usage_count: (data.usage_count ?? 0) + counted.length,
5268
+ used_by: usedBy
5269
+ };
5270
+ },
5271
+ async productCategories(productIds) {
5272
+ const products = await deps.products.find({ selector: { id: { $in: [...productIds] } } }).exec();
5273
+ return new Map(products.map((product) => [
5274
+ product.id,
5275
+ (product.categories ?? []).map(({ id: id2 }) => ({ id: id2 }))
5276
+ ]));
5277
+ }
5278
+ };
5279
+ }
5280
+
5281
+ // src/sale/woocommerce/coupon-refetch.ts
5282
+ function startCouponUsageRefetch(deps) {
5283
+ const now = deps.now ?? Date.now;
5284
+ const handled = /* @__PURE__ */ new Set();
5285
+ let stopped = false;
5286
+ const subscription = deps.orders.find({ selector: { syncStatus: "applied" } }).$.subscribe(async (orders) => {
5287
+ const ids = /* @__PURE__ */ new Set();
5288
+ for (const order of orders) {
5289
+ if (!order.coupons?.length || handled.has(order.id) || !(now() - Date.parse(order.updatedAt) < APPLIED_USE_GRACE_MS)) continue;
5290
+ handled.add(order.id);
5291
+ for (const coupon of order.coupons) {
5292
+ const id2 = Number(coupon.couponId);
5293
+ if (Number.isInteger(id2)) ids.add(id2);
5294
+ }
5295
+ }
5296
+ if (!ids.size) return;
5297
+ try {
5298
+ const docs = await deps.coupons.find({ selector: { id: { $in: [...ids] } } }).exec();
5299
+ if (stopped || !docs.length) return;
5300
+ deps.enqueue(docs.map((doc) => ({ key: doc.uuid, local: doc.toJSON(), refreshOnly: true })));
5301
+ deps.reSync();
5302
+ } catch (error) {
5303
+ saleLogger.warn(
5304
+ "coupon refetch failed",
5305
+ { couponIds: [...ids], error: String(error) }
5306
+ );
5307
+ }
5308
+ });
5309
+ return { stop() {
5310
+ stopped = true;
5311
+ subscription.unsubscribe();
5312
+ } };
5313
+ }
5314
+
4886
5315
  // src/sale/catalogue.ts
4887
5316
  import { findVariantByCode, formatMoney as formatMoney2, resolvePrice as resolvePrice4 } from "@tallyui/core";
4888
5317
  function catalogueEntries(products, traits, context) {
@@ -4992,7 +5421,10 @@ function createBackendNotFound() {
4992
5421
 
4993
5422
  // src/outbox/order-outbox.ts
4994
5423
  var AUTH_FAILURES_BEFORE_PROMPT = 3;
4995
- var NOT_REQUEUEABLE = /* @__PURE__ */ new Set(["idempotency_mismatch"]);
5424
+ var NOT_REQUEUEABLE = /* @__PURE__ */ new Set(["idempotency_mismatch", "coupon_invalid", "total_mismatch"]);
5425
+ function isRequeueable(code) {
5426
+ return !NOT_REQUEUEABLE.has(code ?? "");
5427
+ }
4996
5428
  var REFUSAL_LOG_MESSAGE_MAX = 200;
4997
5429
  var ISOLATE_AFTER_ATTEMPTS = 5;
4998
5430
  var STUCK_AFTER_MS = 15 * 6e4;
@@ -5087,7 +5519,10 @@ function createOrderOutbox(options) {
5087
5519
  const recordsSentForm = (before, after) => deepEqual2(bare({ ...freezeSentForm(before), sentVersion: before.sentVersion ?? after.sentVersion }), bare(after));
5088
5520
  async function updateState(patch = {}) {
5089
5521
  const pending = await countFresh(collection, { syncStatus: "pending" });
5090
- const rejected = await countFresh(collection, { syncStatus: "rejected" });
5522
+ const refused = await readFresh(collection, { selector: { syncStatus: "rejected" } });
5523
+ const successors = refused.length ? await readFresh(collection, { selector: { saleId: { $in: refused.map((order) => order.id) } } }) : [];
5524
+ const replaced = replacedOrderIds([...refused, ...successors]);
5525
+ const rejected = refused.filter((order) => !replaced.has(order.id)).length;
5091
5526
  state$.next({ ...state$.value, ...patch, pending, rejected, stuck: stuckState() });
5092
5527
  }
5093
5528
  function isolate(id2, reason, retryAfterMs = 0) {
@@ -5189,7 +5624,7 @@ function createOrderOutbox(options) {
5189
5624
  envelope2 = toOrderCreateEnvelope(frozen, deviceId, attempt2, { maxVersion: order.sentVersion ?? serverMax });
5190
5625
  } catch (cause) {
5191
5626
  if (!(cause instanceof UnsupportedOrderVersionError)) throw cause;
5192
- envelope2 = toOrderCreateEnvelope(frozen, deviceId, attempt2, { maxVersion: cause.needed === 5 ? 5 : 3 });
5627
+ envelope2 = toOrderCreateEnvelope(frozen, deviceId, attempt2, { maxVersion: cause.needed >= 5 ? cause.needed : 3 });
5193
5628
  }
5194
5629
  if (frozen !== order || order.sentVersion === void 0) {
5195
5630
  await (await collection.findOne(order.id).exec())?.incrementalModify((data) => ({ ...freezeSentForm(data), sentVersion: data.sentVersion ?? envelope2.version }));
@@ -5387,13 +5822,13 @@ function createOrderOutbox(options) {
5387
5822
  const orders = (await readFresh(collection, { selector: {
5388
5823
  syncStatus: "rejected",
5389
5824
  ...orderIds ? { id: { $in: orderIds } } : {}
5390
- } })).filter((order) => !NOT_REQUEUEABLE.has(order.error?.code ?? ""));
5825
+ } })).filter((order) => isRequeueable(order.error?.code));
5391
5826
  let count = 0;
5392
5827
  for (const order of orders) {
5393
5828
  const oldCommandId = order.commandId;
5394
5829
  let changed = false;
5395
5830
  await (await collection.findOne(order.id).exec())?.incrementalModify((data) => {
5396
- changed = data.syncStatus === "rejected" && !NOT_REQUEUEABLE.has(data.error?.code ?? "");
5831
+ changed = data.syncStatus === "rejected" && isRequeueable(data.error?.code);
5397
5832
  if (!changed) return data;
5398
5833
  data.syncStatus = "pending";
5399
5834
  delete data.error;
@@ -5893,7 +6328,7 @@ function useOrderOutbox(options) {
5893
6328
  }
5894
6329
 
5895
6330
  // src/refund/send-order-refund.ts
5896
- import { parseCommandResult } from "@tallyui/core/server";
6331
+ import { parseCommandResult } from "@tallyui/core";
5897
6332
  async function sendOrderRefund(transport, envelope2) {
5898
6333
  let outcome;
5899
6334
  try {
@@ -6268,6 +6703,7 @@ function tenderVoidCollection() {
6268
6703
  return { schema: tenderVoidSchema };
6269
6704
  }
6270
6705
  export {
6706
+ COUPONS_UNSUPPORTED,
6271
6707
  CartError,
6272
6708
  CurrencyProvider,
6273
6709
  DEFAULT_CATALOGUE_VIEW_STATE,
@@ -6279,6 +6715,7 @@ export {
6279
6715
  PosOrderOpenClosedError,
6280
6716
  RECEIPT_SCHEMA_VERSION,
6281
6717
  REGISTER_SESSION_MIGRATION_CLOSE_WAIT_MS,
6718
+ REOPENABLE_CODES,
6282
6719
  RefundAnswerPendingError,
6283
6720
  RegisterApprovalRequiredError,
6284
6721
  RegisterCloseIncompleteError,
@@ -6294,6 +6731,7 @@ export {
6294
6731
  RegisterSessionRequiredError,
6295
6732
  RegisterTakeOverError,
6296
6733
  RegisterTenderInProgressError,
6734
+ ReopenRefusedOrderError,
6297
6735
  SALE_SAVING,
6298
6736
  TAX_ROUNDING_MIXED_NOTE,
6299
6737
  TaxProvider,
@@ -6351,6 +6789,8 @@ export {
6351
6789
  initTenderState,
6352
6790
  initialTenderState,
6353
6791
  isKnownSessionStatus,
6792
+ isReopened,
6793
+ isRequeueable,
6354
6794
  isServerDecimal,
6355
6795
  labelKeys,
6356
6796
  listCategories,
@@ -6394,6 +6834,8 @@ export {
6394
6834
  registerSessionCollection,
6395
6835
  registerSessionSchema,
6396
6836
  registerSessionsLogger,
6837
+ reopenRefusedOrder,
6838
+ replacedOrderIds,
6397
6839
  requireOpenSession,
6398
6840
  resolveGridColumns,
6399
6841
  resolveStoreSettings,
@@ -6440,6 +6882,7 @@ export {
6440
6882
  watchFresh,
6441
6883
  withPricingContext,
6442
6884
  withStockOverlay,
6885
+ woocommerce_exports as woocommerceDiscountCodes,
6443
6886
  writeClosure,
6444
6887
  writeOrderDraft
6445
6888
  };