@tallyui/pos 5.0.0 → 5.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +161 -10
- package/dist/index.js +251 -20
- package/package.json +6 -6
- package/src/index.ts +4 -4
- package/src/outbox/index.ts +1 -0
- package/src/outbox/order-outbox.ts +13 -6
- package/src/outbox/store-settlement.ts +136 -0
- package/src/outbox/use-order-outbox.ts +47 -1
- package/src/pos-order/attention-handled.ts +2 -0
- package/src/pos-order/command.ts +28 -9
- package/src/pos-order/index.ts +3 -1
- package/src/pos-order/needs-attention.ts +8 -3
- package/src/pos-order/schema.ts +17 -2
- package/src/pos-order/store-order-left.ts +21 -0
- package/src/pos-order/store-settlement.ts +51 -0
- package/src/pos-order/types.ts +22 -0
- package/src/sale/use-sale.ts +13 -6
- package/src/tender/cash-rounding.ts +17 -9
- package/src/tender/index.ts +1 -1
package/dist/index.js
CHANGED
|
@@ -562,10 +562,24 @@ function sendableMeta(meta) {
|
|
|
562
562
|
}).slice(0, ORDER_META_MAX);
|
|
563
563
|
}
|
|
564
564
|
var editedSku = (line) => !line.custom && line.catalogueSku !== void 0 && line.sku !== "" && line.sku !== line.catalogueSku;
|
|
565
|
-
function netDiscountMinor(line,
|
|
566
|
-
if (!(line.taxInclusive ?? pricesIncludeTax) || line.discountMinor === 0) return line.discountMinor;
|
|
567
|
-
const
|
|
565
|
+
function netDiscountMinor(line, order) {
|
|
566
|
+
if (!(line.taxInclusive ?? order.pricesIncludeTax) || line.discountMinor === 0) return line.discountMinor;
|
|
567
|
+
const woocommerce = order.taxRounding?.granularity === "woocommerce", stored = line.taxLines;
|
|
568
568
|
const afterDiscount = line.unitPriceMinor * line.quantity - line.discountMinor;
|
|
569
|
+
if (woocommerce && (order.coupons?.length || stored.some((tax) => tax.compound))) {
|
|
570
|
+
const rates = stored.map((tax, i) => ({
|
|
571
|
+
id: i,
|
|
572
|
+
code: tax.code ?? "",
|
|
573
|
+
label: "",
|
|
574
|
+
rate: (tax.ratePpm / 1e4).toFixed(4),
|
|
575
|
+
priority: i,
|
|
576
|
+
compound: tax.compound ?? false,
|
|
577
|
+
shipping: true
|
|
578
|
+
}));
|
|
579
|
+
const net = (minor2) => BigInt(woocommerceLine(minor2, rates, true, order.currency, false).netMicros);
|
|
580
|
+
return roundMicrosToMinor(net(line.unitPriceMinor * line.quantity) - net(afterDiscount));
|
|
581
|
+
}
|
|
582
|
+
const ratePpm = line.taxLines.reduce((sum4, tax) => sum4 + tax.ratePpm, 0);
|
|
569
583
|
const taxAfter = !woocommerce && line.netMinor < afterDiscount ? taxMicros(afterDiscount, ratePpm, true) : line.taxLines.reduce((sum4, tax) => sum4 + BigInt(tax.taxMicros), 0n);
|
|
570
584
|
const taxBefore = taxMicros(line.unitPriceMinor * line.quantity, ratePpm, true);
|
|
571
585
|
return roundMicrosToMinor(BigInt(line.discountMinor) * MICROS_PER_MINOR - taxBefore + taxAfter);
|
|
@@ -582,6 +596,10 @@ function wireNote(note) {
|
|
|
582
596
|
const newline = note.indexOf("\n");
|
|
583
597
|
return newline === -1 ? void 0 : note.slice(newline + 1) || void 0;
|
|
584
598
|
}
|
|
599
|
+
function wireChargeMinor(order, charge, rows) {
|
|
600
|
+
if (order.taxRounding?.granularity !== "woocommerce") return charge.amountMinor;
|
|
601
|
+
return rows?.find(({ id: id2 }) => id2 === charge.id)?.amountMinor ?? charge.amountMinor;
|
|
602
|
+
}
|
|
585
603
|
function toOrderCreateEnvelope(order, deviceId, attempt2 = 1, options) {
|
|
586
604
|
if (order.storeOrderId !== void 0) throw new Error(`Order ${order.id} reopened store order ${order.storeOrderId}: it is sent as order.update, never order.create (ADR-090)`);
|
|
587
605
|
return createEnvelope(order, deviceId, attempt2, options);
|
|
@@ -612,7 +630,7 @@ function createEnvelope(order, deviceId, attempt2, options, floor) {
|
|
|
612
630
|
const withTaxAddress = version === 8 || version >= 9 && taxAddress !== void 0;
|
|
613
631
|
const withAddresses = withTaxAddress || version >= UNTAXED_ADDRESS_ORDER_CREATE_VERSION;
|
|
614
632
|
const taxIds = version >= INFORMATIONAL_EXTRAS_ORDER_CREATE_VERSION && sentTaxIds.length ? { taxIds: sentTaxIds } : void 0;
|
|
615
|
-
const lineDiscounts = order.lines.map((line) => base >= 4 ? netDiscountMinor(line, order
|
|
633
|
+
const lineDiscounts = order.lines.map((line) => base >= 4 ? netDiscountMinor(line, order) : line.discountMinor);
|
|
616
634
|
for (const coupon of carried) {
|
|
617
635
|
if (!coupon.lines) throw new Error(`Order ${order.id}: a carried coupon has no line shares`);
|
|
618
636
|
for (const [i, line] of order.lines.entries()) lineDiscounts[i] += coupon.lines.find(({ lineId }) => lineId === line.id)?.discountMinor ?? 0;
|
|
@@ -654,7 +672,7 @@ function createEnvelope(order, deviceId, attempt2, options, floor) {
|
|
|
654
672
|
...base >= 5 && order.fees?.length ? { fees: order.fees.map((fee) => ({
|
|
655
673
|
clientFeeId: fee.id,
|
|
656
674
|
name: fee.name,
|
|
657
|
-
amountMinor: fee.
|
|
675
|
+
amountMinor: wireChargeMinor(order, fee, order.display?.fees),
|
|
658
676
|
taxStatus: fee.taxStatus,
|
|
659
677
|
...fee.taxClass !== void 0 ? { taxClass: fee.taxClass } : {},
|
|
660
678
|
// #1131: WooCommerce totals a fee line's tax per rate, as its own order totals do.
|
|
@@ -664,7 +682,7 @@ function createEnvelope(order, deviceId, attempt2, options, floor) {
|
|
|
664
682
|
clientShippingId: charge.id,
|
|
665
683
|
name: charge.name,
|
|
666
684
|
...charge.methodId !== void 0 ? { methodId: charge.methodId } : {},
|
|
667
|
-
amountMinor: charge.
|
|
685
|
+
amountMinor: wireChargeMinor(order, charge, order.display?.shipping),
|
|
668
686
|
taxStatus: charge.taxStatus,
|
|
669
687
|
...charge.taxClass !== void 0 ? { taxClass: charge.taxClass } : {},
|
|
670
688
|
// #1120: WooCommerce totals a shipping line's tax per rate, as its own order totals do.
|
|
@@ -8353,7 +8371,7 @@ var orderAddressSchema = { type: "object", additionalProperties: false, properti
|
|
|
8353
8371
|
phone: { type: "string" }
|
|
8354
8372
|
} };
|
|
8355
8373
|
var posOrderSchema = {
|
|
8356
|
-
version:
|
|
8374
|
+
version: 22,
|
|
8357
8375
|
primaryKey: "id",
|
|
8358
8376
|
type: "object",
|
|
8359
8377
|
additionalProperties: false,
|
|
@@ -8367,6 +8385,34 @@ var posOrderSchema = {
|
|
|
8367
8385
|
updatedAt: { type: "string" },
|
|
8368
8386
|
reopenedAt: { type: "string", maxLength: 40 },
|
|
8369
8387
|
attentionHandledFor: { type: "string", maxLength: 36 },
|
|
8388
|
+
storeSettlement: { type: "object", additionalProperties: false, properties: {
|
|
8389
|
+
kind: { type: "string", enum: ["cancel", "pay", "reverse"] },
|
|
8390
|
+
state: { type: "string", enum: ["sending", "done", "changed", "refused", "gone"] },
|
|
8391
|
+
attemptId: { type: "string", maxLength: 36 },
|
|
8392
|
+
at: { type: "string", maxLength: 40 },
|
|
8393
|
+
storeStatus: { type: "string" },
|
|
8394
|
+
capturedMinor: { type: "integer" },
|
|
8395
|
+
code: { type: "string" },
|
|
8396
|
+
message: { type: "string" },
|
|
8397
|
+
payments: { type: "array", items: { type: "object", additionalProperties: false, properties: {
|
|
8398
|
+
id: { type: "string", maxLength: 36 },
|
|
8399
|
+
method: { type: "string" },
|
|
8400
|
+
amountMinor: { type: "integer" },
|
|
8401
|
+
tenderedMinor: { type: "integer" },
|
|
8402
|
+
done: { type: "boolean" }
|
|
8403
|
+
}, required: ["id", "method", "amountMinor"] } },
|
|
8404
|
+
closeId: { type: "string", maxLength: 36 },
|
|
8405
|
+
legs: { type: "array", items: {
|
|
8406
|
+
type: "object",
|
|
8407
|
+
additionalProperties: false,
|
|
8408
|
+
properties: {
|
|
8409
|
+
paymentId: { type: "string", maxLength: 36 },
|
|
8410
|
+
commandId: { type: "string", maxLength: 36 },
|
|
8411
|
+
done: { type: "boolean" }
|
|
8412
|
+
},
|
|
8413
|
+
required: ["paymentId", "commandId"]
|
|
8414
|
+
} }
|
|
8415
|
+
}, required: ["kind", "state", "attemptId", "at"] },
|
|
8370
8416
|
currency: { type: "string" },
|
|
8371
8417
|
pricesIncludeTax: { type: "boolean" },
|
|
8372
8418
|
subtotalMinor: { type: "integer" },
|
|
@@ -8618,7 +8664,7 @@ function posOrderCollection() {
|
|
|
8618
8664
|
};
|
|
8619
8665
|
return {
|
|
8620
8666
|
schema: posOrderSchema,
|
|
8621
|
-
migrationStrategies: { 1: identity2, 2: identity2, 3: identity2, 4: identity2, 5: recordSent, 6: recordRounding, 7: identity2, 8: identity2, 9: identity2, 10: identity2, 11: identity2, 12: identity2, 13: identity2, 14: identity2, 15: identity2, 16: identity2, 17: identity2, 18: identity2, 19: identity2, 20: identity2, 21: identity2 }
|
|
8667
|
+
migrationStrategies: { 1: identity2, 2: identity2, 3: identity2, 4: identity2, 5: recordSent, 6: recordRounding, 7: identity2, 8: identity2, 9: identity2, 10: identity2, 11: identity2, 12: identity2, 13: identity2, 14: identity2, 15: identity2, 16: identity2, 17: identity2, 18: identity2, 19: identity2, 20: identity2, 21: identity2, 22: identity2 }
|
|
8622
8668
|
};
|
|
8623
8669
|
}
|
|
8624
8670
|
|
|
@@ -8828,12 +8874,53 @@ function replacedOrderIds(orders) {
|
|
|
8828
8874
|
return new Set(orders.filter((order) => order.syncStatus === "rejected" && predecessors.has(order.id)).map((order) => order.id));
|
|
8829
8875
|
}
|
|
8830
8876
|
|
|
8877
|
+
// src/pos-order/store-order-left.ts
|
|
8878
|
+
function storeOrderLeft(order) {
|
|
8879
|
+
const data = order.error?.data;
|
|
8880
|
+
if (order.syncStatus !== "rejected" || order.storeOrderId !== void 0 || typeof data?.orderId !== "string" || !data.orderId) return void 0;
|
|
8881
|
+
const { orderId, displayId, recorded } = data;
|
|
8882
|
+
const count = Number.isSafeInteger(recorded) && recorded > 0 ? recorded : 0;
|
|
8883
|
+
return {
|
|
8884
|
+
orderId,
|
|
8885
|
+
reference: typeof displayId === "string" && displayId ? displayId : orderId,
|
|
8886
|
+
recordedMinor: order.payments.slice(0, count).reduce((sum4, payment) => sum4 + payment.amountMinor, 0)
|
|
8887
|
+
};
|
|
8888
|
+
}
|
|
8889
|
+
|
|
8890
|
+
// src/pos-order/store-settlement.ts
|
|
8891
|
+
function settledOnStore(order) {
|
|
8892
|
+
const state = order.storeSettlement?.state;
|
|
8893
|
+
if (state === "done") return true;
|
|
8894
|
+
if (state !== "gone") return false;
|
|
8895
|
+
const left = "syncStatus" in order ? storeOrderLeft(order) : void 0;
|
|
8896
|
+
return !left || left.recordedMinor === 0;
|
|
8897
|
+
}
|
|
8898
|
+
function canCancelOnStore(order) {
|
|
8899
|
+
const left = storeOrderLeft(order);
|
|
8900
|
+
if (!left || left.recordedMinor !== 0 || settledOnStore(order)) return false;
|
|
8901
|
+
const settlement = order.storeSettlement;
|
|
8902
|
+
return settlement === void 0 || settlement.kind === "cancel" || settlement.state === "changed" || settlement.state === "refused";
|
|
8903
|
+
}
|
|
8904
|
+
function unrecordedLegs(order) {
|
|
8905
|
+
const recorded = order.error?.data?.recorded;
|
|
8906
|
+
return order.payments.slice(Number.isSafeInteger(recorded) && recorded > 0 ? recorded : 0);
|
|
8907
|
+
}
|
|
8908
|
+
function canPayRestOnStore(order) {
|
|
8909
|
+
const left = storeOrderLeft(order);
|
|
8910
|
+
if (!left || left.recordedMinor <= 0 || settledOnStore(order)) return false;
|
|
8911
|
+
const legs = unrecordedLegs(order);
|
|
8912
|
+
if (legs.length === 0 || !legs.every((leg) => leg.amountMinor > 0)) return false;
|
|
8913
|
+
const settlement = order.storeSettlement;
|
|
8914
|
+
if (settlement?.state === "gone") return false;
|
|
8915
|
+
return settlement === void 0 || settlement.kind === "pay" || settlement.state === "changed" || settlement.state === "refused";
|
|
8916
|
+
}
|
|
8917
|
+
|
|
8831
8918
|
// src/pos-order/needs-attention.ts
|
|
8832
8919
|
var UPDATE_UNSENDABLE = "update_unsendable";
|
|
8833
8920
|
var UPDATE_UNSENDABLE_MESSAGE = "The store can't accept this change yet. Ask the owner to update the POS plugin, then press Retry.";
|
|
8834
8921
|
function needsAttention(orders, options = {}) {
|
|
8835
8922
|
const replaced = replacedOrderIds(orders);
|
|
8836
|
-
return orders.filter((order) => order.syncStatus === "rejected" || order.syncStatus === "pending" && order.error?.code === UPDATE_UNSENDABLE || (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) && !(order.attentionHandledFor !== void 0 && order.attentionHandledFor === order.commandId)).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
8923
|
+
return orders.filter((order) => order.syncStatus === "rejected" && !settledOnStore(order) || order.syncStatus === "pending" && order.error?.code === UPDATE_UNSENDABLE || (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) && !(order.attentionHandledFor !== void 0 && order.attentionHandledFor === order.commandId && storeOrderLeft(order) === void 0)).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
8837
8924
|
}
|
|
8838
8925
|
|
|
8839
8926
|
// src/pos-order/attention-handled.ts
|
|
@@ -10168,14 +10255,17 @@ function roundedRemainder(balanceMinor, entriesMinor, rounding) {
|
|
|
10168
10255
|
const unrounded = balanceMinor - entriesMinor;
|
|
10169
10256
|
return unrounded <= 0 ? 0 : roundToIncrement(unrounded, rounding.incrementMinor, rounding.mode);
|
|
10170
10257
|
}
|
|
10171
|
-
function roundedPickTarget(targetMinor, rounding) {
|
|
10172
|
-
|
|
10258
|
+
function roundedPickTarget(targetMinor, rounding, entriesMinor = 0) {
|
|
10259
|
+
if (!rounding) return targetMinor;
|
|
10260
|
+
const unrounded = targetMinor - entriesMinor;
|
|
10261
|
+
return unrounded <= 0 ? 0 : roundToIncrement(unrounded, rounding.incrementMinor, rounding.mode);
|
|
10173
10262
|
}
|
|
10174
10263
|
function remainderEntriesMinor(order) {
|
|
10175
|
-
return (order.cashRoundings ?? []).reduce((sum4, entry) =>
|
|
10176
|
-
|
|
10177
|
-
|
|
10178
|
-
|
|
10264
|
+
return (order.cashRoundings ?? []).reduce((sum4, entry) => sum4 + entry.minor, 0);
|
|
10265
|
+
}
|
|
10266
|
+
function writeOffLeg(order) {
|
|
10267
|
+
const counted2 = order.payments.filter(countsTowardPaid);
|
|
10268
|
+
return counted2.filter((leg) => leg.method === "cash").at(-1) ?? counted2.at(-1);
|
|
10179
10269
|
}
|
|
10180
10270
|
function cashVoidRefusal(order, paymentId) {
|
|
10181
10271
|
const carries = (id2) => (order.cashRoundings ?? []).some((entry) => entry.paymentId === id2 && entry.minor !== 0);
|
|
@@ -11134,6 +11224,7 @@ function isRequeueable(code) {
|
|
|
11134
11224
|
return !NOT_REQUEUEABLE.has(code ?? "");
|
|
11135
11225
|
}
|
|
11136
11226
|
function isRequeueableOrder(order) {
|
|
11227
|
+
if (order.storeSettlement !== void 0) return false;
|
|
11137
11228
|
return order.syncStatus === "pending" ? order.error?.code === UPDATE_UNSENDABLE : order.syncStatus === "rejected" && isRequeueable(order.error?.code) && !(order.storeOrderId !== void 0 && ["reopen_required", "revision_conflict"].includes(order.error?.code ?? ""));
|
|
11138
11229
|
}
|
|
11139
11230
|
var REFUSAL_LOG_MESSAGE_MAX = 200;
|
|
@@ -11237,7 +11328,7 @@ function createOrderOutbox(options) {
|
|
|
11237
11328
|
const refused = await readFresh(collection, { selector: { syncStatus: "rejected" } });
|
|
11238
11329
|
const successors = refused.length ? await readFresh(collection, { selector: { saleId: { $in: refused.map((order) => order.id) } } }) : [];
|
|
11239
11330
|
const replaced = replacedOrderIds([...refused, ...successors]);
|
|
11240
|
-
const rejected = refused.filter((order) => !replaced.has(order.id)).length;
|
|
11331
|
+
const rejected = refused.filter((order) => !replaced.has(order.id) && !settledOnStore(order)).length;
|
|
11241
11332
|
state$.next({ ...state$.value, ...patch, pending, rejected, stuck: stuckState() });
|
|
11242
11333
|
}
|
|
11243
11334
|
function isolate(id2, reason, retryAfterMs = 0) {
|
|
@@ -11636,7 +11727,7 @@ function createOrderOutbox(options) {
|
|
|
11636
11727
|
});
|
|
11637
11728
|
let commandId;
|
|
11638
11729
|
await (await collection.findOne(orderId).exec())?.incrementalModify((data) => {
|
|
11639
|
-
commandId = data.syncStatus === "rejected" ? data.commandId : void 0;
|
|
11730
|
+
commandId = data.syncStatus === "rejected" && storeOrderLeft(data) === void 0 ? data.commandId : void 0;
|
|
11640
11731
|
if (commandId === void 0) return data;
|
|
11641
11732
|
data._deleted = true;
|
|
11642
11733
|
return data;
|
|
@@ -13625,7 +13716,7 @@ function useSale(settings, opts) {
|
|
|
13625
13716
|
});
|
|
13626
13717
|
},
|
|
13627
13718
|
setTender,
|
|
13628
|
-
/** ADR-072: external is capped at the balance due; change comes only from cash. A cash leg records the amount applied, the amount handed over (`tenderedMinor`) and the change (`changeMinor`). A leg is captured unless a status says otherwise; a leg in motion is held against the external cap. Units are checked against the units legs hold (`heldUnitsByLine`), but a leg's amount is not tied to its units' money here; the pane enforces that (#1133). A cash part pick rounds its
|
|
13719
|
+
/** ADR-072: external is capped at the balance due; change comes only from cash. A cash leg records the amount applied, the amount handed over (`tenderedMinor`) and the change (`changeMinor`). A leg is captured unless a status says otherwise; a leg in motion is held against the external cap. Units are checked against the units legs hold (`heldUnitsByLine`), but a leg's amount is not tied to its units' money here; the pane enforces that (#1133). A cash part pick rounds its target less the live entries on a cashRounding store, and one that reaches the whole-settle due is taken as that settle (ADR-094 item 7). */
|
|
13629
13720
|
addTender(input) {
|
|
13630
13721
|
const { rounding, ...tender } = input;
|
|
13631
13722
|
if (stageNow.current.kind === "receipt") {
|
|
@@ -13651,12 +13742,21 @@ function useSale(settings, opts) {
|
|
|
13651
13742
|
const unpaid = unpaidUnitsByLine(lineItems.map(({ id: id2, quantity }) => ({ id: id2, quantity, totalMinor: 0 })), heldUnitsByLine(payments));
|
|
13652
13743
|
if (Object.entries(tender.units).some(([id2, units]) => !id2 || !Number.isInteger(units) || units <= 0 || !Object.hasOwn(unpaid, id2) || units > unpaid[id2])) return null;
|
|
13653
13744
|
}
|
|
13654
|
-
const pickMinor = pickRule && tender.tenderedMinor !== void 0 ? roundedPickTarget(tender.amountMinor, pickRule) : tender.amountMinor;
|
|
13745
|
+
const pickMinor = pickRule && tender.tenderedMinor !== void 0 ? roundedPickTarget(tender.amountMinor, pickRule, remainderEntriesMinor(builderNow.current.getSnapshot())) : tender.amountMinor;
|
|
13655
13746
|
if (tender.tenderedMinor !== void 0 && pickMinor === 0) return null;
|
|
13656
13747
|
if (tender.tenderedMinor !== void 0 && (tender.method !== "cash" || !tender.units || !Object.keys(tender.units).length || !Number.isInteger(tender.tenderedMinor) || tender.tenderedMinor < pickMinor)) return null;
|
|
13657
13748
|
if (tender.tenderedMinor !== void 0) {
|
|
13658
13749
|
const snapshot = builderNow.current.getSnapshot();
|
|
13659
13750
|
if (tender.amountMinor > snapshot.balanceDueMinor - inMotionMinor(snapshot.payments)) return null;
|
|
13751
|
+
const due = snapshot.balanceDueMinor;
|
|
13752
|
+
if (pickRule && pickMinor === roundedRemainder(due, remainderEntriesMinor(snapshot), pickRule)) {
|
|
13753
|
+
if ((snapshot.cashRoundings ?? []).length >= CASH_PICK_ENTRIES_MAX + 1 && pickMinor !== due) {
|
|
13754
|
+
setError(CASH_SETTLE_LIMIT);
|
|
13755
|
+
return null;
|
|
13756
|
+
}
|
|
13757
|
+
clearStaleError();
|
|
13758
|
+
return addOne({ ...tender, amountMinor: pickMinor, changeMinor: tender.tenderedMinor - pickMinor }, true, pickMinor !== due ? { minor: pickMinor - due } : void 0);
|
|
13759
|
+
}
|
|
13660
13760
|
if (pickMinor !== tender.amountMinor && (snapshot.cashRoundings ?? []).length >= CASH_PICK_ENTRIES_MAX) {
|
|
13661
13761
|
setError(CASH_PICK_LIMIT);
|
|
13662
13762
|
return null;
|
|
@@ -13683,7 +13783,7 @@ function useSale(settings, opts) {
|
|
|
13683
13783
|
const entries2 = remainderEntriesMinor(snapshot);
|
|
13684
13784
|
const dueMinor = rule ? roundedRemainder(due, entries2, rule) : due;
|
|
13685
13785
|
if (rule && settlesAtRoundedDue({ amountMinor: Math.min(tender.amountMinor, due), tenderedMinor: tender.amountMinor, balanceMinor: due, dueMinor })) {
|
|
13686
|
-
const against = snapshot
|
|
13786
|
+
const against = writeOffLeg(snapshot);
|
|
13687
13787
|
const roundings = snapshot.cashRoundings ?? [];
|
|
13688
13788
|
if (roundings.length >= CASH_PICK_ENTRIES_MAX + 1 && (dueMinor > 0 ? dueMinor !== due : against !== void 0 && !roundings.some((entry) => entry.paymentId === against.id))) {
|
|
13689
13789
|
setError(CASH_SETTLE_LIMIT);
|
|
@@ -14502,6 +14602,97 @@ function createHttpCommandTransport(options) {
|
|
|
14502
14602
|
};
|
|
14503
14603
|
}
|
|
14504
14604
|
|
|
14605
|
+
// src/outbox/store-settlement.ts
|
|
14606
|
+
async function cancelOnStore(deps, orderId) {
|
|
14607
|
+
const stamp2 = () => (deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
|
|
14608
|
+
let request;
|
|
14609
|
+
await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
|
|
14610
|
+
request = void 0;
|
|
14611
|
+
if (data._deleted || !canCancelOnStore(data)) return data;
|
|
14612
|
+
const stored = data.storeSettlement;
|
|
14613
|
+
const attemptId = stored?.kind === "cancel" && stored.state === "sending" ? stored.attemptId : uuidv7();
|
|
14614
|
+
const at2 = stamp2();
|
|
14615
|
+
data.storeSettlement = { kind: "cancel", state: "sending", attemptId, at: at2 };
|
|
14616
|
+
data.updatedAt = at2;
|
|
14617
|
+
request = { storeOrderId: storeOrderLeft(data).orderId, clientOrderId: data.id, attemptId };
|
|
14618
|
+
return data;
|
|
14619
|
+
});
|
|
14620
|
+
if (!request) return { kind: "not_offered" };
|
|
14621
|
+
const sent = request;
|
|
14622
|
+
const outcome = await deps.cancel(sent);
|
|
14623
|
+
if (outcome.kind === "retry") {
|
|
14624
|
+
outboxLogger.info("Cancelling the store order got no definite answer; it stays sending", { orderId, reason: outcome.reason });
|
|
14625
|
+
return outcome;
|
|
14626
|
+
}
|
|
14627
|
+
if (outcome.kind === "refused") outboxLogger.warn("The store refused to cancel the order", { orderId, code: outcome.code, message: outcome.message });
|
|
14628
|
+
if (outcome.kind === "changed") {
|
|
14629
|
+
outboxLogger.warn("The store order changed; nothing was cancelled", { orderId, status: outcome.status, capturedMinor: outcome.capturedMinor });
|
|
14630
|
+
}
|
|
14631
|
+
await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
|
|
14632
|
+
const stored = data.storeSettlement;
|
|
14633
|
+
if (stored?.attemptId !== sent.attemptId || stored.state !== "sending") return data;
|
|
14634
|
+
const at2 = stamp2();
|
|
14635
|
+
const base = { kind: "cancel", attemptId: sent.attemptId, at: at2 };
|
|
14636
|
+
const settled = outcome.kind === "done" ? { ...base, state: "done", storeStatus: outcome.status } : outcome.kind === "changed" ? { ...base, state: "changed", storeStatus: outcome.status, capturedMinor: outcome.capturedMinor } : outcome.kind === "refused" ? { ...base, state: "refused", code: outcome.code, message: outcome.message } : { ...base, state: "gone" };
|
|
14637
|
+
data.storeSettlement = settled;
|
|
14638
|
+
data.updatedAt = at2;
|
|
14639
|
+
return data;
|
|
14640
|
+
});
|
|
14641
|
+
return outcome;
|
|
14642
|
+
}
|
|
14643
|
+
async function payRestOnStore(deps, orderId) {
|
|
14644
|
+
const stamp2 = () => (deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
|
|
14645
|
+
let request;
|
|
14646
|
+
await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
|
|
14647
|
+
request = void 0;
|
|
14648
|
+
if (data._deleted || !canPayRestOnStore(data)) return data;
|
|
14649
|
+
const stored = data.storeSettlement;
|
|
14650
|
+
const legs = unrecordedLegs(data);
|
|
14651
|
+
const again = stored?.kind === "pay" && stored.payments?.length === legs.length ? stored : void 0;
|
|
14652
|
+
const attemptId = again?.state === "sending" ? again.attemptId : uuidv7();
|
|
14653
|
+
const payments = again?.payments ?? legs.map((leg) => ({
|
|
14654
|
+
id: uuidv7(),
|
|
14655
|
+
method: leg.method,
|
|
14656
|
+
amountMinor: leg.amountMinor,
|
|
14657
|
+
...leg.method === "cash" && leg.tenderedMinor !== void 0 ? { tenderedMinor: leg.tenderedMinor } : {}
|
|
14658
|
+
}));
|
|
14659
|
+
const at2 = stamp2();
|
|
14660
|
+
data.storeSettlement = { kind: "pay", state: "sending", attemptId, at: at2, payments };
|
|
14661
|
+
data.updatedAt = at2;
|
|
14662
|
+
request = {
|
|
14663
|
+
storeOrderId: storeOrderLeft(data).orderId,
|
|
14664
|
+
clientOrderId: data.id,
|
|
14665
|
+
attemptId,
|
|
14666
|
+
currency: data.currency,
|
|
14667
|
+
payments: payments.map(({ done: _done, ...payment }) => payment)
|
|
14668
|
+
};
|
|
14669
|
+
return data;
|
|
14670
|
+
});
|
|
14671
|
+
if (!request) return { kind: "not_offered" };
|
|
14672
|
+
const sent = request;
|
|
14673
|
+
const { outcome, recorded } = await deps.pay(sent);
|
|
14674
|
+
if (outcome.kind === "retry") {
|
|
14675
|
+
outboxLogger.info("Recording the rest on the store got no definite answer; it stays sending", { orderId, reason: outcome.reason, recorded: recorded.length });
|
|
14676
|
+
}
|
|
14677
|
+
if (outcome.kind === "refused") outboxLogger.warn("The store refused to record the rest of the order", { orderId, code: outcome.code, message: outcome.message });
|
|
14678
|
+
if (outcome.kind === "changed") {
|
|
14679
|
+
outboxLogger.warn("The store order changed; nothing more was recorded", { orderId, status: outcome.status, capturedMinor: outcome.capturedMinor });
|
|
14680
|
+
}
|
|
14681
|
+
const done = new Set(recorded);
|
|
14682
|
+
await (await deps.orders.findOne(orderId).exec())?.incrementalModify((data) => {
|
|
14683
|
+
const stored = data.storeSettlement;
|
|
14684
|
+
if (stored?.attemptId !== sent.attemptId || stored.state !== "sending") return data;
|
|
14685
|
+
const payments = (stored.payments ?? []).map((payment) => done.has(payment.id) ? { ...payment, done: true } : payment);
|
|
14686
|
+
if (outcome.kind === "retry" && payments.every((payment, index) => payment.done === stored.payments?.[index]?.done)) return data;
|
|
14687
|
+
const at2 = stamp2();
|
|
14688
|
+
const base = { kind: "pay", attemptId: sent.attemptId, at: at2, payments };
|
|
14689
|
+
data.storeSettlement = outcome.kind === "retry" ? { ...stored, payments } : outcome.kind === "done" ? { ...base, state: "done", storeStatus: outcome.status } : outcome.kind === "changed" ? { ...base, state: "changed", storeStatus: outcome.status, capturedMinor: outcome.capturedMinor } : outcome.kind === "refused" ? { ...base, state: "refused", code: outcome.code, message: outcome.message } : { ...base, state: "gone" };
|
|
14690
|
+
data.updatedAt = outcome.kind === "retry" ? data.updatedAt : at2;
|
|
14691
|
+
return data;
|
|
14692
|
+
});
|
|
14693
|
+
return outcome;
|
|
14694
|
+
}
|
|
14695
|
+
|
|
14505
14696
|
// src/outbox/use-register-outbox.ts
|
|
14506
14697
|
import { useEffect as useEffect13, useRef as useRef9, useState as useState12 } from "react";
|
|
14507
14698
|
var idle = { pending: 0, sending: false };
|
|
@@ -14631,6 +14822,38 @@ function useOrderOutbox(options) {
|
|
|
14631
14822
|
const opened = current.current;
|
|
14632
14823
|
return opened && opened.storeKey === storeKey ? opened.outbox.discard(orderId) : false;
|
|
14633
14824
|
},
|
|
14825
|
+
async cancelOnStore(orderId) {
|
|
14826
|
+
const opened = current.current;
|
|
14827
|
+
if (!opened || opened.storeKey !== storeKey) return { kind: "not_offered" };
|
|
14828
|
+
const settlement = latest.current.storeSettlement?.(opened.storeKey);
|
|
14829
|
+
const cancel = settlement?.cancel?.bind(settlement);
|
|
14830
|
+
if (!cancel) return { kind: "not_offered" };
|
|
14831
|
+
try {
|
|
14832
|
+
return await cancelOnStore({ orders: opened.orders, cancel }, orderId);
|
|
14833
|
+
} finally {
|
|
14834
|
+
try {
|
|
14835
|
+
await refreshOutboxState(opened.outbox);
|
|
14836
|
+
} catch (cause) {
|
|
14837
|
+
outboxLogger.warn("Failed to refresh the outbox state", { cause });
|
|
14838
|
+
}
|
|
14839
|
+
}
|
|
14840
|
+
},
|
|
14841
|
+
async payRestOnStore(orderId) {
|
|
14842
|
+
const opened = current.current;
|
|
14843
|
+
if (!opened || opened.storeKey !== storeKey) return { kind: "not_offered" };
|
|
14844
|
+
const settlement = latest.current.storeSettlement?.(opened.storeKey);
|
|
14845
|
+
const pay = settlement?.pay?.bind(settlement);
|
|
14846
|
+
if (!pay) return { kind: "not_offered" };
|
|
14847
|
+
try {
|
|
14848
|
+
return await payRestOnStore({ orders: opened.orders, pay }, orderId);
|
|
14849
|
+
} finally {
|
|
14850
|
+
try {
|
|
14851
|
+
await refreshOutboxState(opened.outbox);
|
|
14852
|
+
} catch (cause) {
|
|
14853
|
+
outboxLogger.warn("Failed to refresh the outbox state", { cause });
|
|
14854
|
+
}
|
|
14855
|
+
}
|
|
14856
|
+
},
|
|
14634
14857
|
savesInFlight: savesInFlightCount,
|
|
14635
14858
|
stuckCommandIds,
|
|
14636
14859
|
async record(posOrder) {
|
|
@@ -15587,9 +15810,12 @@ export {
|
|
|
15587
15810
|
callbackSink,
|
|
15588
15811
|
cameraErrorStatus,
|
|
15589
15812
|
can,
|
|
15813
|
+
canCancelOnStore,
|
|
15590
15814
|
canMoveLeg,
|
|
15591
15815
|
canOpenDrawer,
|
|
15816
|
+
canPayRestOnStore,
|
|
15592
15817
|
canVoidLeg,
|
|
15818
|
+
cancelOnStore,
|
|
15593
15819
|
capturedMinor,
|
|
15594
15820
|
cartQuantities,
|
|
15595
15821
|
cashMovementSchema,
|
|
@@ -15761,6 +15987,7 @@ export {
|
|
|
15761
15987
|
parkedOrderSummaries$,
|
|
15762
15988
|
parseMinor,
|
|
15763
15989
|
parseXml,
|
|
15990
|
+
payRestOnStore,
|
|
15764
15991
|
percentOfMinor,
|
|
15765
15992
|
pickedUnitsMinor,
|
|
15766
15993
|
planLegs,
|
|
@@ -15847,6 +16074,7 @@ export {
|
|
|
15847
16074
|
serialPortIdentity,
|
|
15848
16075
|
sessionOpenCommand,
|
|
15849
16076
|
sessionTransitionCommand,
|
|
16077
|
+
settledOnStore,
|
|
15850
16078
|
shipsToBilling,
|
|
15851
16079
|
sortProducts,
|
|
15852
16080
|
splitUnitLines,
|
|
@@ -15856,6 +16084,7 @@ export {
|
|
|
15856
16084
|
stockOverlay$,
|
|
15857
16085
|
stockOverlayAsOf$,
|
|
15858
16086
|
storeOrderForReopen,
|
|
16087
|
+
storeOrderLeft,
|
|
15859
16088
|
stripBoundary,
|
|
15860
16089
|
submitOrderRefund,
|
|
15861
16090
|
suggestFloat,
|
|
@@ -15888,6 +16117,7 @@ export {
|
|
|
15888
16117
|
unitAllocationsFromLegs,
|
|
15889
16118
|
unitsMinor,
|
|
15890
16119
|
unpaidUnitsByLine,
|
|
16120
|
+
unrecordedLegs,
|
|
15891
16121
|
useAppSettings,
|
|
15892
16122
|
useBarcodeScanner,
|
|
15893
16123
|
useCameraScan,
|
|
@@ -15929,5 +16159,6 @@ export {
|
|
|
15929
16159
|
woocommerce_exports as woocommerceDiscountCodes,
|
|
15930
16160
|
writeAppSetting,
|
|
15931
16161
|
writeClosure,
|
|
16162
|
+
writeOffLeg,
|
|
15932
16163
|
writeOrderDraft
|
|
15933
16164
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tallyui/pos",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.1.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Shared POS business logic for Tally UI — tax, orders, payments, discounts, receipts",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -35,20 +35,20 @@
|
|
|
35
35
|
"mustache": "^4.2.0"
|
|
36
36
|
},
|
|
37
37
|
"peerDependencies": {
|
|
38
|
-
"@tallyui/core": "^5.
|
|
38
|
+
"@tallyui/core": "^5.1.0",
|
|
39
39
|
"react": ">=18",
|
|
40
40
|
"rxdb": "~17.5.0",
|
|
41
41
|
"rxjs": ">=7"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
|
-
"@tallyui/core": "5.
|
|
44
|
+
"@tallyui/core": "5.1.0",
|
|
45
45
|
"@types/react": ">=18",
|
|
46
46
|
"react": "^19.2.4",
|
|
47
47
|
"rxdb": "17.5.0",
|
|
48
48
|
"rxjs": "7.8.2",
|
|
49
|
-
"@tallyui/connector-medusa": "5.
|
|
50
|
-
"@tallyui/connector-woocommerce": "5.
|
|
51
|
-
"@tallyui/database": "5.
|
|
49
|
+
"@tallyui/connector-medusa": "5.1.0",
|
|
50
|
+
"@tallyui/connector-woocommerce": "5.1.0",
|
|
51
|
+
"@tallyui/database": "5.1.0"
|
|
52
52
|
},
|
|
53
53
|
"scripts": {
|
|
54
54
|
"build": "tsup",
|
package/src/index.ts
CHANGED
|
@@ -154,7 +154,7 @@ export type {
|
|
|
154
154
|
export { useSale, DISCOUNTS_UNSUPPORTED, SALE_SAVING, REGISTER_CLOSING, PAYMENT_IN_MOTION, SALE_PARTLY_PAID, SALE_CARD_IN_PROGRESS, SALE_IN_TENDER, SALE_HAS_PAYMENT, SALE_FINISHED, openSales, isPartlyPaid, saleLogger, addEntryToCart, CartError, catalogueEntries, findEntryByCode, variantPriceLabel, woocommerceDiscountCodes, COUPONS_UNSUPPORTED, COUPONS_NEED_CONNECTION, COUPONS_REPRICING, COUPON_CARRIED, COUPON_CARRY_STALE, TENDER_GATE_FAILED, TENDER_SALE_CHANGED, createStorePricedDiscountCodes, cartQuantities, SPLIT_FIXED_DISCOUNT, variantFits, matchVariant, disabledOptions, orderFiltersQuery } from './sale';
|
|
155
155
|
export type { SaleStage, OpenSale, CatalogueEntry, SaleDiscountCodes, SaleDiscountState, StorePricedAccepted, StorePricedCodePricing, StorePricedDiscountCodesOptions, CartQuantityLine, OptionPicks, OrderFilterValue } from './sale';
|
|
156
156
|
|
|
157
|
-
export { uuidv7, AFTER_CLOSE_PAYMENTS_CHANGED, finalizeOrder, toOrderCreateEnvelope, toOrderUpdateEnvelope, UnsupportedOrderVersionError, posOrderSchema, posOrderCollection, addPosOrderCollection, PosOrderOpenClosedError, posOrdersLogger, getDeviceId, needsAttention, markAttentionHandled, moneyDivergence, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE, isReopened, replacedOrderIds, sameSale, OrderContentMismatchError } from './pos-order';
|
|
157
|
+
export { uuidv7, AFTER_CLOSE_PAYMENTS_CHANGED, finalizeOrder, toOrderCreateEnvelope, toOrderUpdateEnvelope, UnsupportedOrderVersionError, posOrderSchema, posOrderCollection, addPosOrderCollection, PosOrderOpenClosedError, posOrdersLogger, getDeviceId, needsAttention, storeOrderLeft, canCancelOnStore, canPayRestOnStore, settledOnStore, unrecordedLegs, markAttentionHandled, moneyDivergence, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE, isReopened, replacedOrderIds, sameSale, OrderContentMismatchError } from './pos-order';
|
|
158
158
|
export { REOPENABLE_CODES, ReopenRefusedOrderError, reopenRefusedOrder, type ReopenRefusal } from './pos-order';
|
|
159
159
|
export { noteDelivery, type NoteDelivery } from './pos-order';
|
|
160
160
|
export { extrasNotSent, type ExtrasNotSent } from './pos-order';
|
|
@@ -162,9 +162,9 @@ export { refundDueOf } from './pos-order';
|
|
|
162
162
|
export { lockedRefundDueMinor, tillLegsTheStoreRefuses } from './pos-order/refund-due';
|
|
163
163
|
export { ADDRESS_CHANGE_REFUSED, NOTHING_DUE, NOTHING_TO_ROUND_AGAINST, CASH_NOT_PAYABLE, CASH_WAITS_FOR_PAYMENT, CASH_PICK_LIMIT, CASH_SETTLE_LIMIT, CASH_PICK_ENTRIES_MAX, VOID_LATER_CASH_FIRST, PAYMENT_TAKEN, CUSTOMER_RETAX_REFUSED, LINE_EDIT_REFUSED, META_CHANGE_REFUSED, META_INVALID, RESTORE_STALE, TAX_IDS_CHANGE_REFUSED, TAX_IDS_INVALID, type SaleRemoval } from './sale/use-sale';
|
|
164
164
|
export { INFORMATIONAL_EXTRAS_ORDER_CREATE_VERSION, TAX_ADDRESS_ORDER_CREATE_VERSION, UNTAXED_ADDRESS_ORDER_CREATE_VERSION } from './pos-order/command';
|
|
165
|
-
export type { PosOrderSyncStatus, PosOrderLine, PosOrderCoupon, PosOrderPayment, PosOrderLocalWarning, PosOrderServerFailures, PosOrder, FinalizeOptions, MoneyDivergence } from './pos-order';
|
|
165
|
+
export type { PosOrderSyncStatus, PosOrderLine, PosOrderCoupon, PosOrderPayment, PosOrderLocalWarning, PosOrderServerFailures, PosOrder, PosOrderStoreSettlement, FinalizeOptions, MoneyDivergence } from './pos-order';
|
|
166
166
|
export type { PosOrderCouponLine } from './pos-order/types';
|
|
167
|
-
export { createHttpCommandTransport, createOrderOutbox, isRequeueable, isRequeueableOrder, useOrderOutbox, outboxLogger } from './outbox';
|
|
167
|
+
export { createHttpCommandTransport, createOrderOutbox, isRequeueable, isRequeueableOrder, useOrderOutbox, outboxLogger, cancelOnStore, payRestOnStore, type CancelOnStoreDeps, type PayRestOnStoreDeps } from './outbox';
|
|
168
168
|
export { needsAdminReasonOf, NEEDS_ADMIN_RETRY_PREFIX, type NeedsAdminAnswer } from './outbox';
|
|
169
169
|
export { createRegisterOutbox, isRegisterRequeueable, useRegisterOutbox, summarizeOutboxHealth, watchOutboxHealth, useOutboxHealth } from './outbox';
|
|
170
170
|
export type { RegisterOutboxOptions, RegisterOutbox, UseRegisterOutboxOptions, UseRegisterOutboxResult } from './outbox';
|
|
@@ -199,7 +199,7 @@ import { minorToDecimal as registerMinorToDecimal } from './register';
|
|
|
199
199
|
/** @deprecated Use `minorToMajor(minor, digits)` from `@tallyui/core`, which also rejects an amount that is not a safe integer. */
|
|
200
200
|
export const minorToDecimal: (minor: number, exponent: number) => string = registerMinorToDecimal;
|
|
201
201
|
export { useRegisterSession, RegisterTenderInProgressError, RegisterSaleSavingError, RegisterSessionAlreadyOpenError, RegisterCloseIncompleteError, RegisterApprovalRequiredError, type ApprovalNeeded, type UseRegisterSessionOptions } from './register';
|
|
202
|
-
export { cashVoidRefusal, type CashVoidRefusal, nearestPayableCash, roundedPickTarget, remainderEntriesMinor, roundedDue, tenderRounding } from './tender';
|
|
202
|
+
export { cashVoidRefusal, type CashVoidRefusal, nearestPayableCash, roundedPickTarget, remainderEntriesMinor, writeOffLeg, roundedDue, tenderRounding } from './tender';
|
|
203
203
|
export type { TenderRounding } from './tender';
|
|
204
204
|
export { suggestFloat, type FloatSuggestion } from './register';
|
|
205
205
|
export { switchWarnings, handoverSlip } from './register';
|
package/src/outbox/index.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export { createHttpCommandTransport } from './http-transport';
|
|
2
2
|
export type { HttpTransportOptions } from './http-transport';
|
|
3
3
|
export { createOrderOutbox, isRequeueable, isRequeueableOrder } from './order-outbox';
|
|
4
|
+
export { cancelOnStore, payRestOnStore, type CancelOnStoreDeps, type PayRestOnStoreDeps } from './store-settlement';
|
|
4
5
|
export type { OrderOutboxOptions, OrderOutbox } from './order-outbox';
|
|
5
6
|
export { createRegisterOutbox, isRegisterRequeueable } from './register-outbox';
|
|
6
7
|
export type { RegisterOutboxOptions, RegisterOutbox } from './register-outbox';
|
|
@@ -3,7 +3,7 @@ import { deepEqual, type RxCollection, type RxDocumentData } from 'rxdb';
|
|
|
3
3
|
import { BehaviorSubject, type Observable, type Subscription } from 'rxjs';
|
|
4
4
|
import { outboxLogger } from './logger';
|
|
5
5
|
import type { LogSyncRecord, SyncRecordOutcome } from '../logging';
|
|
6
|
-
import { toOrderCreateEnvelope, toOrderUpdateEnvelope, UnsupportedOrderVersionError, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE, uuidv7, replacedOrderIds, type PosOrder, type PosOrderServerFailures } from '../pos-order';
|
|
6
|
+
import { toOrderCreateEnvelope, toOrderUpdateEnvelope, UnsupportedOrderVersionError, UPDATE_UNSENDABLE, UPDATE_UNSENDABLE_MESSAGE, uuidv7, replacedOrderIds, settledOnStore, storeOrderLeft, type PosOrder, type PosOrderServerFailures } from '../pos-order';
|
|
7
7
|
import { freezeSentForm } from '../pos-order/finalize';
|
|
8
8
|
import { countFresh, readFresh } from '../rxdb';
|
|
9
9
|
import { createBackendNotFound, type BackendNotFound } from './backend-not-found';
|
|
@@ -26,8 +26,10 @@ export function isRequeueable(code: string | undefined): boolean {
|
|
|
26
26
|
* Whether `requeue()` will send this order again. A rejected order: its code is requeueable, except that a reopened
|
|
27
27
|
* sale (`storeOrderId`) refused with `reopen_required` or `revision_conflict` needs a fresh reopen, not a resend
|
|
28
28
|
* (ADR-090 gate 5). A pending order the outbox could not build as an update (`UPDATE_UNSENDABLE`): yes, it is tried again.
|
|
29
|
+
* An order with a `storeSettlement` (#1101): never; the till is settling its store order instead.
|
|
29
30
|
*/
|
|
30
|
-
export function isRequeueableOrder(order: Pick<PosOrder, 'syncStatus' | 'storeOrderId' | 'error'>): boolean {
|
|
31
|
+
export function isRequeueableOrder(order: Pick<PosOrder, 'syncStatus' | 'storeOrderId' | 'error' | 'storeSettlement'>): boolean {
|
|
32
|
+
if (order.storeSettlement !== undefined) return false;
|
|
31
33
|
return order.syncStatus === 'pending' ? order.error?.code === UPDATE_UNSENDABLE
|
|
32
34
|
: order.syncStatus === 'rejected' && isRequeueable(order.error?.code)
|
|
33
35
|
&& !(order.storeOrderId !== undefined && ['reopen_required', 'revision_conflict'].includes(order.error?.code ?? ''));
|
|
@@ -78,7 +80,8 @@ export interface OrderOutbox {
|
|
|
78
80
|
* Orders isRequeueableOrder refuses are left alone. Resolves to the number requeued. */
|
|
79
81
|
requeue(orderIds?: string[]): Promise<number>;
|
|
80
82
|
/** Removes the rejected order `orderId` from the collection, after any running flush ends. Resolves to true when
|
|
81
|
-
* removed; false, with nothing changed, when the id is unknown
|
|
83
|
+
* removed; false, with nothing changed, when the id is unknown, the order is not rejected, or the store created its
|
|
84
|
+
* order before refusing it (`storeOrderLeft`, #1101). */
|
|
82
85
|
discard(orderId: string): Promise<boolean>;
|
|
83
86
|
/** Watches for pending orders and sends them. */
|
|
84
87
|
start(): void;
|
|
@@ -216,7 +219,8 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
|
216
219
|
const refused = await readFresh(collection, { selector: { syncStatus: 'rejected' } });
|
|
217
220
|
const successors = refused.length ? await readFresh(collection, { selector: { saleId: { $in: refused.map((order) => order.id) } } }) : [];
|
|
218
221
|
const replaced = replacedOrderIds([...refused, ...successors]);
|
|
219
|
-
|
|
222
|
+
// A refused sale whose store order is settled on the store (#1101) no longer counts.
|
|
223
|
+
const rejected = refused.filter((order) => !replaced.has(order.id) && !settledOnStore(order)).length;
|
|
220
224
|
state$.next({ ...state$.value, ...patch, pending, rejected, stuck: stuckState() });
|
|
221
225
|
}
|
|
222
226
|
|
|
@@ -584,7 +588,9 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
|
584
588
|
delete data.sentVersion;
|
|
585
589
|
delete data.downgradedFrom;
|
|
586
590
|
// The server ledger stored the rejection under the old id; replaying it returns that rejection.
|
|
587
|
-
//
|
|
591
|
+
// The create push keys on the order's id (the transport's recordId is clientOrderId), which a requeue leaves
|
|
592
|
+
// unchanged; so the resend of a row whose order the store created (storeOrderLeft, #1101) carries that order's
|
|
593
|
+
// clientOrderId again.
|
|
588
594
|
data.commandId = uuidv7();
|
|
589
595
|
data.updatedAt = new Date(now()).toISOString();
|
|
590
596
|
return data;
|
|
@@ -605,7 +611,8 @@ export function createOrderOutbox(options: OrderOutboxOptions): OrderOutbox {
|
|
|
605
611
|
// requeue that won the race leaves its pending order in place.
|
|
606
612
|
await (await collection.findOne(orderId).exec())?.incrementalModify((data) => {
|
|
607
613
|
// The modifier runs again on a write conflict, so it decides on each run.
|
|
608
|
-
|
|
614
|
+
// A refused sale whose order the store created (storeOrderLeft, #1101) stays: the till settles that order instead.
|
|
615
|
+
commandId = data.syncStatus === 'rejected' && storeOrderLeft(data) === undefined ? data.commandId : undefined;
|
|
609
616
|
if (commandId === undefined) return data;
|
|
610
617
|
data._deleted = true;
|
|
611
618
|
return data;
|