@fire-spark/core 0.53.0 → 0.55.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 +88 -13
- package/dist/index.js +678 -216
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -5058,9 +5058,10 @@ const fitRedeems = (order) => {
|
|
|
5058
5058
|
const net = nonFixedCap(order, true);
|
|
5059
5059
|
let used = moneyZero();
|
|
5060
5060
|
const fit = (item, line, lineUsed) => {
|
|
5061
|
-
if (!hasRedeemPayment(item)
|
|
5061
|
+
if (!hasRedeemPayment(item)) return moneyZero();
|
|
5062
5062
|
if (!(item.amount > 0)) return moneyZero();
|
|
5063
|
-
const
|
|
5063
|
+
const defaultBeforeTaxes = !isProductReward(item);
|
|
5064
|
+
const beforeTaxes = item.before_taxes ?? defaultBeforeTaxes;
|
|
5064
5065
|
let room = (beforeTaxes ? net : gross).minus(used);
|
|
5065
5066
|
if (line) {
|
|
5066
5067
|
const left = coverableOf(line, beforeTaxes).minus(lineUsed);
|
|
@@ -5087,9 +5088,12 @@ const fitRedeems = (order) => {
|
|
|
5087
5088
|
};
|
|
5088
5089
|
const keepFitted = (items, fitted) => {
|
|
5089
5090
|
return items.flatMap((item, index) => {
|
|
5090
|
-
if (isProductReward(item)) return [item];
|
|
5091
|
+
if (isProductReward(item) && !(item.amount > 0)) return [item];
|
|
5091
5092
|
const fits = fitted[index] ?? moneyZero();
|
|
5092
|
-
if (fits.lte(0)) return [
|
|
5093
|
+
if (fits.lte(0)) return isProductReward(item) ? [{
|
|
5094
|
+
...item,
|
|
5095
|
+
amount: 0
|
|
5096
|
+
}] : [];
|
|
5093
5097
|
if (fits.eq(item.amount)) return [item];
|
|
5094
5098
|
return [{
|
|
5095
5099
|
...item,
|
|
@@ -9339,6 +9343,120 @@ var PaymentSession = class {
|
|
|
9339
9343
|
}
|
|
9340
9344
|
};
|
|
9341
9345
|
//#endregion
|
|
9346
|
+
//#region src/order/productCoupon.ts
|
|
9347
|
+
/** Infers tax-inclusivity from an existing line; defaults true when $0. */
|
|
9348
|
+
const inferTaxInclusive = (line) => {
|
|
9349
|
+
if (!((line.tax_rate ?? 0) > 0)) return true;
|
|
9350
|
+
if (!(line.unit_subtotal > 0)) return true;
|
|
9351
|
+
const net = new Big(line.unit_subtotal).minus(line.unit_discount);
|
|
9352
|
+
return new Big(line.unit_total).lte(net);
|
|
9353
|
+
};
|
|
9354
|
+
/**
|
|
9355
|
+
* Reprices a line's unit and line-level money fields to `unitPrice` using
|
|
9356
|
+
* exact Big.js arithmetic (same formula as `toOrderLines`). Caller should
|
|
9357
|
+
* run `rebuildRootGroups` afterward to refresh group totals.
|
|
9358
|
+
*/
|
|
9359
|
+
const repriceLineUnit = (line, unitPrice, isTaxInclusive) => {
|
|
9360
|
+
const price = new Big(unitPrice);
|
|
9361
|
+
const qty = new Big(line.quantity);
|
|
9362
|
+
const taxRate = line.tax_rate ?? 0;
|
|
9363
|
+
const discountRate = line.discount_rate ?? 0;
|
|
9364
|
+
const unitDiscount = price.times(discountRate);
|
|
9365
|
+
const net = price.minus(unitDiscount);
|
|
9366
|
+
let unitTax = net.times(taxRate);
|
|
9367
|
+
let unitTotal = net.plus(unitTax);
|
|
9368
|
+
if (isTaxInclusive) {
|
|
9369
|
+
const divisor = new Big(1).plus(taxRate);
|
|
9370
|
+
unitTax = net.times(taxRate).div(divisor);
|
|
9371
|
+
unitTotal = net;
|
|
9372
|
+
}
|
|
9373
|
+
const r1 = { unit_subtotal: price.toNumber() };
|
|
9374
|
+
const r2 = { unit_discount: unitDiscount.toNumber() };
|
|
9375
|
+
const r3 = { unit_tax_total: unitTax.toNumber() };
|
|
9376
|
+
const r4 = { unit_total: unitTotal.toNumber() };
|
|
9377
|
+
const r5 = { subtotal: price.times(qty).toNumber() };
|
|
9378
|
+
const r6 = { discount_total: unitDiscount.times(qty).toNumber() };
|
|
9379
|
+
const r7 = { tax_total: unitTax.times(qty).toNumber() };
|
|
9380
|
+
const r8 = { total: unitTotal.times(qty).toNumber() };
|
|
9381
|
+
const m1 = {
|
|
9382
|
+
...r1,
|
|
9383
|
+
...r2,
|
|
9384
|
+
...r3,
|
|
9385
|
+
...r4
|
|
9386
|
+
};
|
|
9387
|
+
const m2 = {
|
|
9388
|
+
...r5,
|
|
9389
|
+
...r6,
|
|
9390
|
+
...r7,
|
|
9391
|
+
...r8
|
|
9392
|
+
};
|
|
9393
|
+
return {
|
|
9394
|
+
...line,
|
|
9395
|
+
...m1,
|
|
9396
|
+
...m2
|
|
9397
|
+
};
|
|
9398
|
+
};
|
|
9399
|
+
const captureUnitPricing = (line) => {
|
|
9400
|
+
const b1 = {
|
|
9401
|
+
tax_rate: line.tax_rate,
|
|
9402
|
+
discount_rate: line.discount_rate
|
|
9403
|
+
};
|
|
9404
|
+
const b2 = { unit_subtotal: line.unit_subtotal };
|
|
9405
|
+
const b3 = { unit_discount: line.unit_discount };
|
|
9406
|
+
const b4 = { unit_tax_total: line.unit_tax_total };
|
|
9407
|
+
return {
|
|
9408
|
+
...b1,
|
|
9409
|
+
...b2,
|
|
9410
|
+
...b3,
|
|
9411
|
+
...b4,
|
|
9412
|
+
unit_total: line.unit_total
|
|
9413
|
+
};
|
|
9414
|
+
};
|
|
9415
|
+
/** Restores previously captured unit pricing scaled to the line's quantity. */
|
|
9416
|
+
const restoreUnitPricing = (line, saved) => {
|
|
9417
|
+
const qty = new Big(line.quantity);
|
|
9418
|
+
const m = {
|
|
9419
|
+
subtotal: new Big(saved.unit_subtotal).times(qty).toNumber(),
|
|
9420
|
+
discount_total: new Big(saved.unit_discount).times(qty).toNumber(),
|
|
9421
|
+
tax_total: new Big(saved.unit_tax_total).times(qty).toNumber(),
|
|
9422
|
+
total: new Big(saved.unit_total).times(qty).toNumber()
|
|
9423
|
+
};
|
|
9424
|
+
return {
|
|
9425
|
+
...line,
|
|
9426
|
+
...saved,
|
|
9427
|
+
...m
|
|
9428
|
+
};
|
|
9429
|
+
};
|
|
9430
|
+
/** Exact Big.js REDEMPTION amount covering up to `quantity` gifted units. */
|
|
9431
|
+
const addProductRedeemAmount = (line, quantity, beforeTaxes) => {
|
|
9432
|
+
const units = Math.min(quantity, line.quantity);
|
|
9433
|
+
return new Big(beforeTaxes ? line.unit_subtotal : line.unit_total).times(units).toNumber();
|
|
9434
|
+
};
|
|
9435
|
+
const lineSkuOf = (line) => {
|
|
9436
|
+
const meta = line.metadata;
|
|
9437
|
+
if (!meta || typeof meta !== "object" || Array.isArray(meta)) return null;
|
|
9438
|
+
const raw = meta.sku;
|
|
9439
|
+
if (typeof raw !== "string") return null;
|
|
9440
|
+
const trimmed = raw.trim();
|
|
9441
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
9442
|
+
};
|
|
9443
|
+
/** Captures a pre-replace product snapshot from a root line. */
|
|
9444
|
+
const snapshotReplacedLine = (line, quantity) => {
|
|
9445
|
+
const qty = quantity ?? line.quantity;
|
|
9446
|
+
let baseSub = line.subtotal;
|
|
9447
|
+
if (Number.isFinite(line.group_subtotal)) baseSub = line.group_subtotal;
|
|
9448
|
+
let sub = new Big(baseSub).toNumber();
|
|
9449
|
+
if (qty !== line.quantity) sub = new Big(baseSub).times(qty).div(line.quantity).toNumber();
|
|
9450
|
+
const snapshot = {
|
|
9451
|
+
id: line.id,
|
|
9452
|
+
quantity: qty,
|
|
9453
|
+
group_subtotal: sub
|
|
9454
|
+
};
|
|
9455
|
+
const sku = lineSkuOf(line);
|
|
9456
|
+
if (sku) snapshot.sku = sku;
|
|
9457
|
+
return snapshot;
|
|
9458
|
+
};
|
|
9459
|
+
//#endregion
|
|
9342
9460
|
//#region src/schedule/schedule.ts
|
|
9343
9461
|
const DAY_OF_WEEK = [
|
|
9344
9462
|
"sunday",
|
|
@@ -9665,10 +9783,30 @@ const REWARD_TYPES = /* @__PURE__ */ new Set([
|
|
|
9665
9783
|
"DISCOUNT",
|
|
9666
9784
|
"PRODUCT"
|
|
9667
9785
|
]);
|
|
9786
|
+
const validateReplaced = (replaced) => {
|
|
9787
|
+
if (!Array.isArray(replaced) || replaced.length === 0) throw new Error("Redeem replaced must be a non-empty array");
|
|
9788
|
+
return replaced.map((item) => {
|
|
9789
|
+
if (typeof item.id !== "string" || !item.id.trim()) throw new Error("Replaced product requires id");
|
|
9790
|
+
if (!Number.isInteger(item.quantity) || item.quantity < 1) throw new Error("Replaced product quantity must be an integer ≥ 1");
|
|
9791
|
+
const sub = item.group_subtotal;
|
|
9792
|
+
if (typeof sub !== "number" || !Number.isFinite(sub) || sub < 0) throw new Error("Replaced product group_subtotal must be ≥ 0");
|
|
9793
|
+
const base = {
|
|
9794
|
+
id: item.id,
|
|
9795
|
+
quantity: item.quantity,
|
|
9796
|
+
group_subtotal: sub
|
|
9797
|
+
};
|
|
9798
|
+
if (item.sku !== void 0) {
|
|
9799
|
+
const trimmed = typeof item.sku === "string" ? item.sku.trim() : "";
|
|
9800
|
+
if (!trimmed) throw new Error("Replaced product sku must be non-empty");
|
|
9801
|
+
base.sku = trimmed;
|
|
9802
|
+
}
|
|
9803
|
+
return base;
|
|
9804
|
+
});
|
|
9805
|
+
};
|
|
9668
9806
|
/** Same rules as `vOrders.redeem()`; throws on invalid input. */
|
|
9669
9807
|
const buildRedeem = (input) => {
|
|
9670
9808
|
const { reward_id, quantity, payment_id, type } = input;
|
|
9671
|
-
const { before_taxes, expires_at } = input;
|
|
9809
|
+
const { before_taxes, expires_at, full_price, replaced } = input;
|
|
9672
9810
|
if (typeof reward_id !== "string" || !reward_id.trim()) throw new Error("Redeem requires reward_id");
|
|
9673
9811
|
if (!Number.isInteger(quantity) || quantity < 1) throw new Error("Redeem quantity must be an integer ≥ 1");
|
|
9674
9812
|
if (typeof payment_id !== "string" || !payment_id.trim()) throw new Error("Redeem requires payment_id");
|
|
@@ -9678,7 +9816,15 @@ const buildRedeem = (input) => {
|
|
|
9678
9816
|
if (product) {
|
|
9679
9817
|
if (amount === void 0) amount = 0;
|
|
9680
9818
|
if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0) throw new Error("Product reward amount must be ≥ 0");
|
|
9681
|
-
|
|
9819
|
+
if (replaced !== void 0 && amount > 0) throw new Error("Replace product reward amount must be 0");
|
|
9820
|
+
if (full_price !== void 0) {
|
|
9821
|
+
if (!(typeof full_price === "number" && Number.isFinite(full_price) && full_price >= 0)) throw new Error("Product reward full_price must be ≥ 0");
|
|
9822
|
+
}
|
|
9823
|
+
} else {
|
|
9824
|
+
if (full_price !== void 0) throw new Error("full_price is only valid on PRODUCT redeems");
|
|
9825
|
+
if (replaced !== void 0) throw new Error("replaced is only valid on PRODUCT redeems");
|
|
9826
|
+
if (typeof amount !== "number" || !(amount > 0)) throw new Error("Redeem requires amount > 0");
|
|
9827
|
+
}
|
|
9682
9828
|
if (expires_at !== void 0 && Number.isNaN(Date.parse(expires_at))) throw new Error("Redeem expires_at must be an ISO datetime");
|
|
9683
9829
|
if (typeof amount !== "number") throw new Error("Redeem requires amount > 0");
|
|
9684
9830
|
const redeem = {
|
|
@@ -9690,6 +9836,8 @@ const buildRedeem = (input) => {
|
|
|
9690
9836
|
if (type !== void 0) redeem.type = type;
|
|
9691
9837
|
if (before_taxes !== void 0) redeem.before_taxes = before_taxes;
|
|
9692
9838
|
if (expires_at !== void 0) redeem.expires_at = expires_at;
|
|
9839
|
+
if (full_price !== void 0) redeem.full_price = full_price;
|
|
9840
|
+
if (replaced !== void 0) redeem.replaced = validateReplaced(replaced);
|
|
9693
9841
|
return redeem;
|
|
9694
9842
|
};
|
|
9695
9843
|
/**
|
|
@@ -9758,15 +9906,17 @@ const subtractRedeem = (items, reward_id, quantity) => {
|
|
|
9758
9906
|
return kept;
|
|
9759
9907
|
};
|
|
9760
9908
|
/**
|
|
9761
|
-
* Money
|
|
9762
|
-
*
|
|
9763
|
-
*
|
|
9764
|
-
*
|
|
9909
|
+
* Money redeems cover (Σ `amount`), including ADD PRODUCT rewards with
|
|
9910
|
+
* `amount > 0`. REPLACE or legacy PRODUCT rewards with `amount === 0` add 0.
|
|
9911
|
+
* The sum is paid by REDEMPTION tenders, so it is never subtracted from
|
|
9912
|
+
* line or order totals.
|
|
9765
9913
|
*/
|
|
9766
9914
|
const redeemedTotal = (redeem = []) => {
|
|
9767
9915
|
return (redeem ?? []).reduce((sum, item) => {
|
|
9768
|
-
if (!hasRedeemPayment(item)
|
|
9769
|
-
|
|
9916
|
+
if (!hasRedeemPayment(item)) return sum;
|
|
9917
|
+
const amount = item.amount ?? 0;
|
|
9918
|
+
if (!(amount > 0)) return sum;
|
|
9919
|
+
return sum.plus(amount);
|
|
9770
9920
|
}, new Big(0)).toNumber();
|
|
9771
9921
|
};
|
|
9772
9922
|
/** Redeemed money of every redeem of the order (order + root lines). */
|
|
@@ -9887,8 +10037,9 @@ const redemptionSteps = (order) => {
|
|
|
9887
10037
|
reward_quantity: item.quantity
|
|
9888
10038
|
};
|
|
9889
10039
|
const s2 = { payment_id: item.payment_id };
|
|
10040
|
+
const isAddProduct = item.type === "PRODUCT" && item.amount > 0;
|
|
9890
10041
|
const s3 = {
|
|
9891
|
-
before_taxes: item.before_taxes ??
|
|
10042
|
+
before_taxes: item.before_taxes ?? !isAddProduct,
|
|
9892
10043
|
action
|
|
9893
10044
|
};
|
|
9894
10045
|
const s4 = { discount_amount: moneyNumber(fits) };
|
|
@@ -10240,6 +10391,7 @@ var Order = class Order {
|
|
|
10240
10391
|
/** Real tenders chosen with `setTenders`; REDEMPTION ones come from redeem. */
|
|
10241
10392
|
realTenders = null;
|
|
10242
10393
|
redemptionProviders = /* @__PURE__ */ new Map();
|
|
10394
|
+
originalProductPricing = /* @__PURE__ */ new Map();
|
|
10243
10395
|
/**
|
|
10244
10396
|
* Redeems as applied, before the D18 cap trims payment amounts. The cap
|
|
10245
10397
|
* is re-derived from these on every edit, so a redeem trimmed while the
|
|
@@ -10656,11 +10808,16 @@ var Order = class Order {
|
|
|
10656
10808
|
*/
|
|
10657
10809
|
applyRedeem(input) {
|
|
10658
10810
|
if (this.deleted) return;
|
|
10659
|
-
const { line_uid, provider,
|
|
10660
|
-
const
|
|
10661
|
-
|
|
10662
|
-
if (
|
|
10811
|
+
const { line_uid, provider, action, is_tax_inclusive, full_price } = input;
|
|
10812
|
+
const { replaced, ...rest } = input;
|
|
10813
|
+
const isProduct = rest.type === "PRODUCT";
|
|
10814
|
+
if (isProduct && line_uid === void 0) throw new Error("Product reward requires a root product line");
|
|
10815
|
+
if (provider) this.redemptionProviders.set(rest.payment_id, provider);
|
|
10663
10816
|
if (line_uid === void 0) {
|
|
10817
|
+
const redeem = buildRedeem({
|
|
10818
|
+
...rest,
|
|
10819
|
+
replaced
|
|
10820
|
+
});
|
|
10664
10821
|
this.commitLines({ redeem: [...this.appliedRedeem(), redeem] });
|
|
10665
10822
|
return;
|
|
10666
10823
|
}
|
|
@@ -10670,8 +10827,40 @@ var Order = class Order {
|
|
|
10670
10827
|
const msg = `Redeem on a FEE line requires a shipping fee, got ${line_uid}`;
|
|
10671
10828
|
throw new Error(msg);
|
|
10672
10829
|
}
|
|
10673
|
-
if (
|
|
10674
|
-
const hasFullPrice =
|
|
10830
|
+
if (isProduct && line.type !== "PRODUCT") throw new Error("Product reward requires a root product line");
|
|
10831
|
+
const hasFullPrice = isProduct && typeof full_price === "number" && Number.isFinite(full_price) && full_price >= 0;
|
|
10832
|
+
if (isProduct && action !== "REPLACE" && !replaced && (action === "ADD" || typeof rest.amount === "number" && rest.amount > 0)) {
|
|
10833
|
+
let targetLine = line;
|
|
10834
|
+
if (hasFullPrice) {
|
|
10835
|
+
if (!this.originalProductPricing.has(line_uid)) this.originalProductPricing.set(line_uid, captureUnitPricing(line));
|
|
10836
|
+
targetLine = repriceLineUnit(line, full_price, is_tax_inclusive ?? inferTaxInclusive(line));
|
|
10837
|
+
}
|
|
10838
|
+
const beforeTaxes = rest.before_taxes ?? false;
|
|
10839
|
+
const amount = rest.amount ?? addProductRedeemAmount(targetLine, rest.quantity, beforeTaxes);
|
|
10840
|
+
const b1 = {
|
|
10841
|
+
...rest,
|
|
10842
|
+
amount,
|
|
10843
|
+
before_taxes: beforeTaxes
|
|
10844
|
+
};
|
|
10845
|
+
const b2 = hasFullPrice ? { full_price } : {};
|
|
10846
|
+
const addRedeem = buildRedeem({
|
|
10847
|
+
...b1,
|
|
10848
|
+
...b2
|
|
10849
|
+
});
|
|
10850
|
+
const lines = this.draft.lines.map((item) => {
|
|
10851
|
+
if (item.uid !== line_uid) return item;
|
|
10852
|
+
return {
|
|
10853
|
+
...targetLine,
|
|
10854
|
+
redeem: [...item.redeem ?? [], addRedeem]
|
|
10855
|
+
};
|
|
10856
|
+
});
|
|
10857
|
+
this.commitLines({ lines });
|
|
10858
|
+
return;
|
|
10859
|
+
}
|
|
10860
|
+
const redeem = buildRedeem({
|
|
10861
|
+
...rest,
|
|
10862
|
+
replaced
|
|
10863
|
+
});
|
|
10675
10864
|
const lines = this.draft.lines.map((item) => {
|
|
10676
10865
|
if (item.uid !== line_uid) return item;
|
|
10677
10866
|
const updated = {
|
|
@@ -10690,6 +10879,53 @@ var Order = class Order {
|
|
|
10690
10879
|
this.commitLines({ lines });
|
|
10691
10880
|
}
|
|
10692
10881
|
/**
|
|
10882
|
+
* Applies a Masivo REPLACE `PRODUCT` coupon: captures a pre-replace
|
|
10883
|
+
* snapshot of `replaced_line_uid`, swaps it with `replacement_lines`,
|
|
10884
|
+
* and attaches the `PRODUCT` redeem (`amount: 0`, `replaced: [snapshot]`)
|
|
10885
|
+
* onto the replacement root line.
|
|
10886
|
+
*/
|
|
10887
|
+
applyReplaceRedeem(input) {
|
|
10888
|
+
if (this.deleted) return;
|
|
10889
|
+
const { replaced_line_uid, replacement_lines } = input;
|
|
10890
|
+
const oldLine = this.draft.lines.find((item) => item.uid === replaced_line_uid);
|
|
10891
|
+
if (!oldLine || oldLine.parent_uid != null || oldLine.type !== "PRODUCT") {
|
|
10892
|
+
const msg = `Replace requires a root product line, got ${replaced_line_uid}`;
|
|
10893
|
+
throw new Error(msg);
|
|
10894
|
+
}
|
|
10895
|
+
const newRoot = replacement_lines.find((item) => item.parent_uid == null);
|
|
10896
|
+
if (!newRoot || newRoot.type !== "PRODUCT") throw new Error("Replacement requires a root product line");
|
|
10897
|
+
const snapshot = snapshotReplacedLine(oldLine, input.quantity);
|
|
10898
|
+
const nextLines = replaceLine(...[this.draft.lines, replaced_line_uid], replacement_lines);
|
|
10899
|
+
this.commitLines({ lines: nextLines });
|
|
10900
|
+
const b1 = {
|
|
10901
|
+
reward_id: input.reward_id,
|
|
10902
|
+
quantity: input.quantity
|
|
10903
|
+
};
|
|
10904
|
+
const b2 = {
|
|
10905
|
+
type: "PRODUCT",
|
|
10906
|
+
action: "REPLACE"
|
|
10907
|
+
};
|
|
10908
|
+
const b3 = {
|
|
10909
|
+
line_uid: newRoot.uid,
|
|
10910
|
+
payment_id: input.payment_id
|
|
10911
|
+
};
|
|
10912
|
+
const b4 = {
|
|
10913
|
+
provider: input.provider,
|
|
10914
|
+
expires_at: input.expires_at
|
|
10915
|
+
};
|
|
10916
|
+
const b5 = {
|
|
10917
|
+
full_price: input.full_price,
|
|
10918
|
+
replaced: [snapshot]
|
|
10919
|
+
};
|
|
10920
|
+
this.applyRedeem({
|
|
10921
|
+
...b1,
|
|
10922
|
+
...b2,
|
|
10923
|
+
...b3,
|
|
10924
|
+
...b4,
|
|
10925
|
+
...b5
|
|
10926
|
+
});
|
|
10927
|
+
}
|
|
10928
|
+
/**
|
|
10693
10929
|
* Removes `quantity` units of `reward_id` from `line_uid` or the order,
|
|
10694
10930
|
* latest applied first. Removing more units than applied clears them all
|
|
10695
10931
|
* (and their REDEMPTION tender). A redeem that keeps some units keeps
|
|
@@ -10714,10 +10950,17 @@ var Order = class Order {
|
|
|
10714
10950
|
reward_id,
|
|
10715
10951
|
quantity
|
|
10716
10952
|
]);
|
|
10717
|
-
|
|
10953
|
+
let updated = {
|
|
10718
10954
|
...item,
|
|
10719
10955
|
redeem: nextRedeem
|
|
10720
10956
|
};
|
|
10957
|
+
if (!nextRedeem.some((r) => {
|
|
10958
|
+
return r.type === "PRODUCT" && r.amount > 0 && r.full_price != null;
|
|
10959
|
+
}) && this.originalProductPricing.has(line_uid)) {
|
|
10960
|
+
const saved = this.originalProductPricing.get(line_uid);
|
|
10961
|
+
updated = restoreUnitPricing(updated, saved);
|
|
10962
|
+
this.originalProductPricing.delete(line_uid);
|
|
10963
|
+
}
|
|
10721
10964
|
if (nextRedeem.some((r) => r.type === "PRODUCT")) return updated;
|
|
10722
10965
|
return withLineRewardSavings(updated, null);
|
|
10723
10966
|
});
|
|
@@ -12720,15 +12963,92 @@ const checkRootProductQuantities = (roots, lookup, out) => {
|
|
|
12720
12963
|
}
|
|
12721
12964
|
}
|
|
12722
12965
|
};
|
|
12723
|
-
const
|
|
12966
|
+
const productSkuOf = (product) => {
|
|
12967
|
+
const meta = product.metadata;
|
|
12968
|
+
if (!meta || typeof meta !== "object" || Array.isArray(meta)) return null;
|
|
12969
|
+
const raw = meta.sku;
|
|
12970
|
+
if (typeof raw !== "string") return null;
|
|
12971
|
+
const trimmed = raw.trim();
|
|
12972
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
12973
|
+
};
|
|
12974
|
+
const resolveAddProductFullPrice = (root, fullPrices) => {
|
|
12975
|
+
for (const r of root.redeem ?? []) {
|
|
12976
|
+
if (!isProductReward(r) || !(r.amount > 0)) continue;
|
|
12977
|
+
const auth = fullPrices?.[r.reward_id];
|
|
12978
|
+
if (auth !== void 0) return auth;
|
|
12979
|
+
if (r.full_price !== void 0) return r.full_price;
|
|
12980
|
+
}
|
|
12981
|
+
};
|
|
12982
|
+
const validateReplacedSnapshots = (root, lookup, out) => {
|
|
12983
|
+
(root.redeem ?? []).forEach((r, rIndex) => {
|
|
12984
|
+
if (!isProductReward(r) || !r.replaced?.length) return;
|
|
12985
|
+
r.replaced.forEach((snap, sIndex) => {
|
|
12986
|
+
const prefix = `redeem.${rIndex}.replaced.${sIndex}`;
|
|
12987
|
+
const product = lookup.productsById[snap.id];
|
|
12988
|
+
if (!product) {
|
|
12989
|
+
const b1 = { code: "PRODUCT_NOT_FOUND" };
|
|
12990
|
+
const b2 = {
|
|
12991
|
+
field: `${prefix}.id`,
|
|
12992
|
+
actual: snap.id
|
|
12993
|
+
};
|
|
12994
|
+
pushLineIssue(out, root.uid, {
|
|
12995
|
+
...b1,
|
|
12996
|
+
...b2
|
|
12997
|
+
});
|
|
12998
|
+
return;
|
|
12999
|
+
}
|
|
13000
|
+
if (isVariantBase(product)) {
|
|
13001
|
+
const b1 = { code: "VARIANT_BASE_NOT_ORDERABLE" };
|
|
13002
|
+
const b2 = {
|
|
13003
|
+
field: `${prefix}.id`,
|
|
13004
|
+
actual: snap.id
|
|
13005
|
+
};
|
|
13006
|
+
pushLineIssue(out, root.uid, {
|
|
13007
|
+
...b1,
|
|
13008
|
+
...b2
|
|
13009
|
+
});
|
|
13010
|
+
return;
|
|
13011
|
+
}
|
|
13012
|
+
const expectedSub = new Big(product.pricing.price).times(snap.quantity).toNumber();
|
|
13013
|
+
if (!bigEq(snap.group_subtotal, expectedSub)) {
|
|
13014
|
+
const b1 = { code: "PRICE_MISMATCH" };
|
|
13015
|
+
const b2 = { field: `${prefix}.group_subtotal` };
|
|
13016
|
+
const b3 = { expected: bigStr(expectedSub) };
|
|
13017
|
+
const b4 = { actual: bigStr(snap.group_subtotal) };
|
|
13018
|
+
pushLineIssue(out, root.uid, {
|
|
13019
|
+
...b1,
|
|
13020
|
+
...b2,
|
|
13021
|
+
...b3,
|
|
13022
|
+
...b4
|
|
13023
|
+
});
|
|
13024
|
+
}
|
|
13025
|
+
if (snap.sku !== void 0) {
|
|
13026
|
+
const expectedSku = productSkuOf(product) ?? product.id;
|
|
13027
|
+
if (snap.sku !== expectedSku) {
|
|
13028
|
+
const b1 = { code: "STRUCTURE_MISMATCH" };
|
|
13029
|
+
const b2 = {
|
|
13030
|
+
field: `${prefix}.sku`,
|
|
13031
|
+
expected: expectedSku
|
|
13032
|
+
};
|
|
13033
|
+
pushLineIssue(out, root.uid, {
|
|
13034
|
+
...b1,
|
|
13035
|
+
...b2,
|
|
13036
|
+
actual: snap.sku
|
|
13037
|
+
});
|
|
13038
|
+
}
|
|
13039
|
+
}
|
|
13040
|
+
});
|
|
13041
|
+
});
|
|
13042
|
+
};
|
|
13043
|
+
const validateProductRoot = (root, lines, lookup, locale, out, at, timeZone, fullPrices) => {
|
|
12724
13044
|
const product = lookup.productsById[root.id];
|
|
12725
13045
|
if (!product) {
|
|
12726
13046
|
pushLineIssue(out, root.uid, { code: "PRODUCT_NOT_FOUND" });
|
|
12727
|
-
return;
|
|
13047
|
+
return null;
|
|
12728
13048
|
}
|
|
12729
13049
|
if (isVariantBase(product)) {
|
|
12730
13050
|
pushLineIssue(out, root.uid, { code: "VARIANT_BASE_NOT_ORDERABLE" });
|
|
12731
|
-
return;
|
|
13051
|
+
return null;
|
|
12732
13052
|
}
|
|
12733
13053
|
if ((product.pricing.variants ?? []).length > 0 && !isOfferedVariant(lookup, product)) pushLineIssue(out, root.uid, { code: "VARIANT_NOT_OFFERED" });
|
|
12734
13054
|
const status = product.availability.status;
|
|
@@ -12737,6 +13057,7 @@ const validateProductRoot = (root, lines, lookup, locale, out, at, timeZone) =>
|
|
|
12737
13057
|
const hours = product.availability.schedules;
|
|
12738
13058
|
if (!isOnSchedule(hours, at, timeZone)) pushLineIssue(out, root.uid, { code: "OUTSIDE_HOURS" });
|
|
12739
13059
|
collectUnmatchedModifiers(lines, lookup, root.id, root.uid, out);
|
|
13060
|
+
validateReplacedSnapshots(root, lookup, out);
|
|
12740
13061
|
let expected;
|
|
12741
13062
|
if (needsSlotPlacement(lines, root.uid, lookup)) {
|
|
12742
13063
|
const placed = placeCartLines(root, lines, lookup, locale);
|
|
@@ -12748,12 +13069,20 @@ const validateProductRoot = (root, lines, lookup, locale, out, at, timeZone) =>
|
|
|
12748
13069
|
if (session.validate() !== "VALID") pushLineIssue(out, root.uid, { code: "MODIFIER_RULES_INVALID" });
|
|
12749
13070
|
expected = toOrderLines(session.root, locale);
|
|
12750
13071
|
}
|
|
12751
|
-
|
|
13072
|
+
let expectedRoot = expected.find((line) => line.parent_uid == null);
|
|
12752
13073
|
if (!expectedRoot) {
|
|
12753
13074
|
pushLineIssue(out, root.uid, { code: "STRUCTURE_MISMATCH" });
|
|
12754
|
-
return;
|
|
13075
|
+
return null;
|
|
13076
|
+
}
|
|
13077
|
+
const fullPrice = resolveAddProductFullPrice(root, fullPrices);
|
|
13078
|
+
if (fullPrice !== void 0) {
|
|
13079
|
+
const inclusive = product.pricing.is_tax_inclusive;
|
|
13080
|
+
const repriced = repriceLineUnit(expectedRoot, fullPrice, inclusive);
|
|
13081
|
+
expected = rebuildRootGroups(expected.map((l) => l.uid === expectedRoot.uid ? repriced : l));
|
|
13082
|
+
expectedRoot = expected.find((line) => line.parent_uid == null);
|
|
12755
13083
|
}
|
|
12756
13084
|
compareTrees(lines, expected, root.uid, expectedRoot.uid, out);
|
|
13085
|
+
return expectedRoot;
|
|
12757
13086
|
};
|
|
12758
13087
|
const isExpired = (redeem, now) => {
|
|
12759
13088
|
if (redeem.expires_at === void 0) return false;
|
|
@@ -12787,7 +13116,7 @@ const paymentProblem = (payment_id, payments) => {
|
|
|
12787
13116
|
* money. With `payments`, the payment must exist, be active and be a
|
|
12788
13117
|
* REDEMPTION method.
|
|
12789
13118
|
*/
|
|
12790
|
-
const redeemIssues = (items, fitted, payments) => {
|
|
13119
|
+
const redeemIssues = (items, fitted, payments, expectedLine) => {
|
|
12791
13120
|
const issues = [];
|
|
12792
13121
|
items.forEach((item, index) => {
|
|
12793
13122
|
const prefix = `redeem.${index}`;
|
|
@@ -12801,15 +13130,47 @@ const redeemIssues = (items, fitted, payments) => {
|
|
|
12801
13130
|
}
|
|
12802
13131
|
if (isProductReward(item)) {
|
|
12803
13132
|
const problem = payments ? paymentProblem(payment_id, payments) : null;
|
|
12804
|
-
if (
|
|
13133
|
+
if (problem) {
|
|
13134
|
+
const b1 = {
|
|
13135
|
+
code: "REDEEM_PAYMENT_METHOD_NOT_CONFIGURED",
|
|
13136
|
+
field: `${prefix}.payment_id`
|
|
13137
|
+
};
|
|
13138
|
+
issues.push({
|
|
13139
|
+
...b1,
|
|
13140
|
+
expected: REDEMPTION_METHOD,
|
|
13141
|
+
actual: problem
|
|
13142
|
+
});
|
|
13143
|
+
return;
|
|
13144
|
+
}
|
|
13145
|
+
if (!(item.amount > 0)) return;
|
|
13146
|
+
if (item.replaced && item.replaced.length > 0) {
|
|
13147
|
+
const b1 = {
|
|
13148
|
+
code: "REDEEM_AMOUNT_MISMATCH",
|
|
13149
|
+
field: `${prefix}.amount`,
|
|
13150
|
+
expected: "0"
|
|
13151
|
+
};
|
|
13152
|
+
issues.push({
|
|
13153
|
+
...b1,
|
|
13154
|
+
actual: bigStr(item.amount)
|
|
13155
|
+
});
|
|
13156
|
+
return;
|
|
13157
|
+
}
|
|
13158
|
+
let expected = fitted[index];
|
|
13159
|
+
if (expectedLine) {
|
|
13160
|
+
const beforeTaxes = item.before_taxes ?? false;
|
|
13161
|
+
const raw = new Big(addProductRedeemAmount(expectedLine, item.quantity, beforeTaxes));
|
|
13162
|
+
expected = expected && expected.lt(raw) ? expected : raw;
|
|
13163
|
+
}
|
|
13164
|
+
if (expected && expected.eq(item.amount)) return;
|
|
12805
13165
|
const b1 = {
|
|
12806
|
-
code: "
|
|
12807
|
-
field: `${prefix}.
|
|
13166
|
+
code: "REDEEM_AMOUNT_MISMATCH",
|
|
13167
|
+
field: `${prefix}.amount`
|
|
12808
13168
|
};
|
|
13169
|
+
const b2 = { expected: bigStr(expected?.toNumber() ?? 0) };
|
|
12809
13170
|
issues.push({
|
|
12810
13171
|
...b1,
|
|
12811
|
-
|
|
12812
|
-
actual:
|
|
13172
|
+
...b2,
|
|
13173
|
+
actual: bigStr(item.amount)
|
|
12813
13174
|
});
|
|
12814
13175
|
return;
|
|
12815
13176
|
}
|
|
@@ -12925,7 +13286,7 @@ const stepIssues = (submitted, expected) => {
|
|
|
12925
13286
|
});
|
|
12926
13287
|
return issues;
|
|
12927
13288
|
};
|
|
12928
|
-
const validateRedemptions = (input, issues, lineIssues) => {
|
|
13289
|
+
const validateRedemptions = (input, issues, lineIssues, expectedRoots) => {
|
|
12929
13290
|
const redeem = input.redeem ?? [];
|
|
12930
13291
|
const now = input.now ?? input.asOf?.getTime() ?? Date.now();
|
|
12931
13292
|
const p1 = {
|
|
@@ -12961,12 +13322,13 @@ const validateRedemptions = (input, issues, lineIssues) => {
|
|
|
12961
13322
|
...b2
|
|
12962
13323
|
});
|
|
12963
13324
|
});
|
|
13325
|
+
const expRoot = expectedRoots.get(line.uid) ?? null;
|
|
12964
13326
|
const p2 = [
|
|
12965
13327
|
items,
|
|
12966
13328
|
fitted.lines[index] ?? [],
|
|
12967
13329
|
input.payments
|
|
12968
13330
|
];
|
|
12969
|
-
for (const issue of redeemIssues(...p2)) pushLineIssue(lineIssues, line.uid, issue);
|
|
13331
|
+
for (const issue of redeemIssues(...p2, expRoot)) pushLineIssue(lineIssues, line.uid, issue);
|
|
12970
13332
|
});
|
|
12971
13333
|
if (input.redemptionSteps === void 0) return;
|
|
12972
13334
|
const expected = redemptionSteps(p1);
|
|
@@ -13028,6 +13390,7 @@ const validateOrderAgainstMenu = (input) => {
|
|
|
13028
13390
|
};
|
|
13029
13391
|
}
|
|
13030
13392
|
const lookup = indexMenu(input.menu);
|
|
13393
|
+
const expectedRoots = /* @__PURE__ */ new Map();
|
|
13031
13394
|
for (const root of roots) {
|
|
13032
13395
|
if (root.type === "FEE") {
|
|
13033
13396
|
checkFeeSelfConsistency(root, lineIssues);
|
|
@@ -13042,13 +13405,15 @@ const validateOrderAgainstMenu = (input) => {
|
|
|
13042
13405
|
const p2 = [
|
|
13043
13406
|
lineIssues,
|
|
13044
13407
|
at,
|
|
13045
|
-
zone
|
|
13408
|
+
zone,
|
|
13409
|
+
input.productRewardFullPrices
|
|
13046
13410
|
];
|
|
13047
|
-
validateProductRoot(...p1, ...p2);
|
|
13411
|
+
const expRoot = validateProductRoot(...p1, ...p2);
|
|
13412
|
+
if (expRoot) expectedRoots.set(root.uid, expRoot);
|
|
13048
13413
|
}
|
|
13049
13414
|
checkRootProductQuantities(roots, lookup, lineIssues);
|
|
13050
13415
|
if (input.expectedFeeLines) compareExpectedFeeLines(input.lines, input.expectedFeeLines, lineIssues);
|
|
13051
|
-
validateRedemptions(input, issues, lineIssues);
|
|
13416
|
+
validateRedemptions(input, issues, lineIssues, expectedRoots);
|
|
13052
13417
|
compareRootGroups(input.lines, menuLines, lineIssues);
|
|
13053
13418
|
const expectedTotals = recomputeTotals(menuLines, input.totals.currency);
|
|
13054
13419
|
for (const field of TOTALS_FIELDS) {
|
|
@@ -16301,6 +16666,194 @@ const processStateNode = async (ports, config) => {
|
|
|
16301
16666
|
}
|
|
16302
16667
|
};
|
|
16303
16668
|
//#endregion
|
|
16669
|
+
//#region src/fulfillment/engine/finalize.ts
|
|
16670
|
+
const HARD_FAILED_CODES = /* @__PURE__ */ new Set([CALLBACK_MISSING_LOCAL_URL, WORKFLOW_TIMEOUT]);
|
|
16671
|
+
const terminalRunStatusForNode = (node, order) => {
|
|
16672
|
+
if (isInterruptTerminalStatus(order?.status)) return "CANCELLED";
|
|
16673
|
+
const mapped = node?.data.mappedStatus?.trim().toUpperCase();
|
|
16674
|
+
if (isInterruptTerminalStatus(mapped)) return "CANCELLED";
|
|
16675
|
+
return "SUCCESS";
|
|
16676
|
+
};
|
|
16677
|
+
const terminalRunStatusForEnter = (ran) => {
|
|
16678
|
+
if (ran.failed) return "CANCELLED";
|
|
16679
|
+
const mapped = ran.next.mappedStatus?.trim().toUpperCase();
|
|
16680
|
+
if (isInterruptTerminalStatus(mapped)) return "CANCELLED";
|
|
16681
|
+
return "SUCCESS";
|
|
16682
|
+
};
|
|
16683
|
+
const engineOrderStatusForFailedRun = (order, isPaymentCaptured = defaultIsPaymentCaptured) => {
|
|
16684
|
+
if (!order) return null;
|
|
16685
|
+
if (isInterruptTerminalStatus(order.status) || order.status === "COMPLETED") return null;
|
|
16686
|
+
return isPaymentCaptured(order) ? "REVERSED" : "VOIDED";
|
|
16687
|
+
};
|
|
16688
|
+
const syncOrderFromSittingTerminal = async (ports, orderFulfillmentId) => {
|
|
16689
|
+
const row = await ports.storage.getOrderFulfillment(orderFulfillmentId);
|
|
16690
|
+
if (!row) return;
|
|
16691
|
+
const sitting = sittingWorkflowNode(row.workflow, row.current_node_ids);
|
|
16692
|
+
if (!sitting || sitting.data.kind !== "terminal") return;
|
|
16693
|
+
const order = await ports.storage.getOrder(row.order_id);
|
|
16694
|
+
const isCaptured = ports.execution.isPaymentCaptured ?? defaultIsPaymentCaptured;
|
|
16695
|
+
const fields = orderFieldsFromNode(sitting, void 0, order ? isCaptured(order) : false);
|
|
16696
|
+
const patch = {
|
|
16697
|
+
fulfillment_status: sitting.data.mappedStatus,
|
|
16698
|
+
...fields
|
|
16699
|
+
};
|
|
16700
|
+
await ports.storage.updateOrderStatusAndSettle(row.order_id, patch);
|
|
16701
|
+
};
|
|
16702
|
+
const emitFinalizeChanged = async (ports, orderFulfillmentId, error) => {
|
|
16703
|
+
const row = await ports.storage.getOrderFulfillment(orderFulfillmentId);
|
|
16704
|
+
const orderId = row?.order_id;
|
|
16705
|
+
const order = orderId ? await ports.storage.getOrder(orderId) : null;
|
|
16706
|
+
if (row && order) {
|
|
16707
|
+
await ports.execution.onOrderChanged?.({
|
|
16708
|
+
orderFulfillmentId,
|
|
16709
|
+
row,
|
|
16710
|
+
order,
|
|
16711
|
+
error
|
|
16712
|
+
});
|
|
16713
|
+
return;
|
|
16714
|
+
}
|
|
16715
|
+
await ports.execution.onOrderChanged?.({
|
|
16716
|
+
orderFulfillmentId,
|
|
16717
|
+
error
|
|
16718
|
+
});
|
|
16719
|
+
};
|
|
16720
|
+
const finalizePlaceOrder = async (ports, config) => {
|
|
16721
|
+
const { storage, execution: execPort } = ports;
|
|
16722
|
+
const { orderFulfillmentId, status, failureMessage } = config;
|
|
16723
|
+
const { errorCode, errorDetails } = config;
|
|
16724
|
+
const now = execPort.now;
|
|
16725
|
+
const row = await storage.getOrderFulfillment(orderFulfillmentId);
|
|
16726
|
+
const steps_logs = row?.steps_logs ?? [];
|
|
16727
|
+
const isHardFailed = Boolean(errorCode && HARD_FAILED_CODES.has(errorCode));
|
|
16728
|
+
let msg = "Fulfillment failed";
|
|
16729
|
+
if (status === "SUCCESS") msg = "Fulfillment completed";
|
|
16730
|
+
else if (status === "CANCELLED") msg = "Fulfillment cancelled";
|
|
16731
|
+
if (status === "FAILED") {
|
|
16732
|
+
const peekOrderId = (row ?? await storage.getOrderFulfillment(orderFulfillmentId))?.order_id;
|
|
16733
|
+
const peekOrder = peekOrderId ? await storage.getOrder(peekOrderId) : null;
|
|
16734
|
+
if (!isHardFailed && isInterruptTerminalStatus(peekOrder?.status)) {
|
|
16735
|
+
beginEngineStepLog(steps_logs, "FINALIZE", void 0, now);
|
|
16736
|
+
completeEngineStepLog(steps_logs, "FINALIZE", "Fulfillment cancelled", now);
|
|
16737
|
+
const cancelled = {
|
|
16738
|
+
steps_logs,
|
|
16739
|
+
step: "FINALIZE",
|
|
16740
|
+
status: "CANCELLED"
|
|
16741
|
+
};
|
|
16742
|
+
await storage.updateOrderFulfillment(orderFulfillmentId, cancelled);
|
|
16743
|
+
await emitFinalizeChanged(ports, orderFulfillmentId);
|
|
16744
|
+
return { failed: false };
|
|
16745
|
+
}
|
|
16746
|
+
if (failureMessage) failActiveEngineStepLog(steps_logs, failureMessage, {
|
|
16747
|
+
code: errorCode,
|
|
16748
|
+
details: errorDetails,
|
|
16749
|
+
now
|
|
16750
|
+
});
|
|
16751
|
+
beginEngineStepLog(steps_logs, "FINALIZE", void 0, now);
|
|
16752
|
+
if (isHardFailed && failureMessage) appendEngineStepLog(steps_logs, "FINALIZE", {
|
|
16753
|
+
type: "error",
|
|
16754
|
+
message: failureMessage,
|
|
16755
|
+
code: errorCode,
|
|
16756
|
+
details: errorDetails
|
|
16757
|
+
});
|
|
16758
|
+
completeEngineStepLog(steps_logs, "FINALIZE", msg, now);
|
|
16759
|
+
if (isHardFailed && peekOrder) {
|
|
16760
|
+
const resolvedAt = (now ? now() : /* @__PURE__ */ new Date()).toISOString();
|
|
16761
|
+
await storage.updateOrderStatusAndSettle(peekOrder.id, {
|
|
16762
|
+
fulfillment_status: "FAILED",
|
|
16763
|
+
status: "FAILED",
|
|
16764
|
+
resolved_at: resolvedAt
|
|
16765
|
+
});
|
|
16766
|
+
const key = `${orderFulfillmentId}:${errorCode}`;
|
|
16767
|
+
const reviewMsg = failureMessage ?? `${errorCode}: Fulfillment failed`;
|
|
16768
|
+
await storage.flagOrderForReview?.({
|
|
16769
|
+
order: peekOrder,
|
|
16770
|
+
key,
|
|
16771
|
+
message: reviewMsg
|
|
16772
|
+
});
|
|
16773
|
+
} else if (peekOrder) {
|
|
16774
|
+
const isCaptured = execPort.isPaymentCaptured ?? defaultIsPaymentCaptured;
|
|
16775
|
+
const closed = engineOrderStatusForFailedRun(peekOrder, isCaptured);
|
|
16776
|
+
if (closed) await storage.updateOrderStatusAndSettle(peekOrder.id, {
|
|
16777
|
+
fulfillment_status: closed,
|
|
16778
|
+
status: closed
|
|
16779
|
+
});
|
|
16780
|
+
}
|
|
16781
|
+
} else {
|
|
16782
|
+
beginEngineStepLog(steps_logs, "FINALIZE", void 0, now);
|
|
16783
|
+
completeEngineStepLog(steps_logs, "FINALIZE", msg, now);
|
|
16784
|
+
}
|
|
16785
|
+
const errorFields = status === "FAILED" ? {
|
|
16786
|
+
error_code: errorCode ?? null,
|
|
16787
|
+
error_message: failureMessage ?? "Fulfillment failed"
|
|
16788
|
+
} : {};
|
|
16789
|
+
await storage.updateOrderFulfillment(orderFulfillmentId, {
|
|
16790
|
+
steps_logs,
|
|
16791
|
+
step: "FINALIZE",
|
|
16792
|
+
status,
|
|
16793
|
+
...errorFields
|
|
16794
|
+
});
|
|
16795
|
+
if (status === "CANCELLED") {
|
|
16796
|
+
await emitFinalizeChanged(ports, orderFulfillmentId);
|
|
16797
|
+
return { failed: false };
|
|
16798
|
+
}
|
|
16799
|
+
if (status === "SUCCESS") {
|
|
16800
|
+
await syncOrderFromSittingTerminal(ports, orderFulfillmentId);
|
|
16801
|
+
await emitFinalizeChanged(ports, orderFulfillmentId);
|
|
16802
|
+
return { failed: false };
|
|
16803
|
+
}
|
|
16804
|
+
const raw = failureMessage ?? "Fulfillment failed";
|
|
16805
|
+
await emitFinalizeChanged(ports, orderFulfillmentId, errorCode ? {
|
|
16806
|
+
message: raw,
|
|
16807
|
+
code: errorCode
|
|
16808
|
+
} : { message: raw });
|
|
16809
|
+
if (row?.order_id) await execPort.onInjectionFailed?.({
|
|
16810
|
+
orderId: row.order_id,
|
|
16811
|
+
message: raw,
|
|
16812
|
+
code: errorCode
|
|
16813
|
+
});
|
|
16814
|
+
return { failed: true };
|
|
16815
|
+
};
|
|
16816
|
+
const warnNoEdge = async (ports, config) => {
|
|
16817
|
+
const { storage, execution: execPort } = ports;
|
|
16818
|
+
const { orderFulfillmentId, fulfillmentStatus } = config;
|
|
16819
|
+
const now = execPort.now;
|
|
16820
|
+
const row = await storage.getOrderFulfillment(orderFulfillmentId);
|
|
16821
|
+
if (!row || row.current_node_ids.length === 0) return;
|
|
16822
|
+
const orderPromise = storage.getOrder(row.order_id);
|
|
16823
|
+
const message = `No outgoing edge matches ${fulfillmentStatus}`;
|
|
16824
|
+
const nodesById = new Map(row.workflow.nodes.map((node) => [node.id, node]));
|
|
16825
|
+
for (const id of row.current_node_ids) {
|
|
16826
|
+
const node = nodesById.get(id) ?? findNodeById(row.workflow, id);
|
|
16827
|
+
if (node) appendNodeLog(node, "warning", message);
|
|
16828
|
+
}
|
|
16829
|
+
const steps_logs = row.steps_logs;
|
|
16830
|
+
beginEngineStepLog(steps_logs, "WARN_NO_EDGE", void 0, now);
|
|
16831
|
+
appendEngineStepLog(steps_logs, "WARN_NO_EDGE", {
|
|
16832
|
+
type: "warning",
|
|
16833
|
+
message
|
|
16834
|
+
});
|
|
16835
|
+
completeEngineStepLog(steps_logs, "WARN_NO_EDGE", "Kept waiting", now);
|
|
16836
|
+
const warning_count = (row.warning_count ?? 0) + 1;
|
|
16837
|
+
const patch = {
|
|
16838
|
+
workflow: row.workflow,
|
|
16839
|
+
steps_logs,
|
|
16840
|
+
warning_count,
|
|
16841
|
+
status: "WAITING"
|
|
16842
|
+
};
|
|
16843
|
+
await storage.updateOrderFulfillment(orderFulfillmentId, patch);
|
|
16844
|
+
const order = await orderPromise;
|
|
16845
|
+
if (!order) return;
|
|
16846
|
+
const patched = {
|
|
16847
|
+
...row,
|
|
16848
|
+
...patch
|
|
16849
|
+
};
|
|
16850
|
+
await execPort.onOrderChanged?.({
|
|
16851
|
+
orderFulfillmentId,
|
|
16852
|
+
row: patched,
|
|
16853
|
+
order
|
|
16854
|
+
});
|
|
16855
|
+
};
|
|
16856
|
+
//#endregion
|
|
16304
16857
|
//#region src/fulfillment/engine/pauseForAdvance.ts
|
|
16305
16858
|
const WAITING_STEP = "PAUSE_FOR_ADVANCE";
|
|
16306
16859
|
const isWaitingPaymentNode = (row) => {
|
|
@@ -16311,18 +16864,56 @@ const isWaitingPaymentNode = (row) => {
|
|
|
16311
16864
|
}
|
|
16312
16865
|
return false;
|
|
16313
16866
|
};
|
|
16867
|
+
const isTerminalRunStatus = (status) => {
|
|
16868
|
+
return status === "SUCCESS" || status === "FAILED" || status === "CANCELLED";
|
|
16869
|
+
};
|
|
16314
16870
|
const pauseForAdvance = async (ports, config) => {
|
|
16315
16871
|
const { storage, execution: execPort } = ports;
|
|
16316
16872
|
const { orderFulfillmentId } = config;
|
|
16317
16873
|
const now = execPort.now;
|
|
16318
16874
|
const row = await storage.getOrderFulfillment(orderFulfillmentId);
|
|
16319
16875
|
if (!row) throw new Error("Order fulfillment not found");
|
|
16320
|
-
if (row.status
|
|
16876
|
+
if (isTerminalRunStatus(row.status)) return {
|
|
16877
|
+
closed: true,
|
|
16878
|
+
status: row.status
|
|
16879
|
+
};
|
|
16880
|
+
const sitting = sittingWorkflowNode(row.workflow, row.current_node_ids);
|
|
16881
|
+
if (sitting?.data.kind === "terminal") {
|
|
16882
|
+
const order = await storage.getOrder(row.order_id);
|
|
16883
|
+
const closedStatus = terminalRunStatusForNode(sitting, order);
|
|
16884
|
+
const msg = closedStatus === "CANCELLED" ? "Fulfillment cancelled" : "Fulfillment completed";
|
|
16885
|
+
const steps_logs = row.steps_logs;
|
|
16886
|
+
if (steps_logs.some((entry) => entry.step === WAITING_STEP && !entry.ended_at)) completeEngineStepLog(steps_logs, WAITING_STEP, msg, now);
|
|
16887
|
+
beginEngineStepLog(steps_logs, "FINALIZE", void 0, now);
|
|
16888
|
+
completeEngineStepLog(steps_logs, "FINALIZE", msg, now);
|
|
16889
|
+
const patch = {
|
|
16890
|
+
steps_logs,
|
|
16891
|
+
step: "FINALIZE",
|
|
16892
|
+
status: closedStatus
|
|
16893
|
+
};
|
|
16894
|
+
await storage.updateOrderFulfillment(orderFulfillmentId, patch);
|
|
16895
|
+
if (order) {
|
|
16896
|
+
const patched = {
|
|
16897
|
+
...row,
|
|
16898
|
+
...patch
|
|
16899
|
+
};
|
|
16900
|
+
await execPort.onOrderChanged?.({
|
|
16901
|
+
orderFulfillmentId,
|
|
16902
|
+
row: patched,
|
|
16903
|
+
order
|
|
16904
|
+
});
|
|
16905
|
+
}
|
|
16906
|
+
return {
|
|
16907
|
+
closed: true,
|
|
16908
|
+
status: closedStatus
|
|
16909
|
+
};
|
|
16910
|
+
}
|
|
16911
|
+
if (row.status === "PROCESSING" && row.step === WAITING_STEP) return { closed: false };
|
|
16321
16912
|
const already = row.status === "WAITING" && row.step === WAITING_STEP;
|
|
16322
16913
|
const steps_logs = row.steps_logs;
|
|
16323
16914
|
let order = null;
|
|
16324
16915
|
if (!already) {
|
|
16325
|
-
if (row.status !== "PROCESSING") return;
|
|
16916
|
+
if (row.status !== "PROCESSING") return { closed: false };
|
|
16326
16917
|
beginEngineStepLog(steps_logs, WAITING_STEP, void 0, now);
|
|
16327
16918
|
const at = (now ? now() : /* @__PURE__ */ new Date()).toISOString();
|
|
16328
16919
|
markNodesReady({
|
|
@@ -16335,7 +16926,7 @@ const pauseForAdvance = async (ports, config) => {
|
|
|
16335
16926
|
workflow: row.workflow
|
|
16336
16927
|
};
|
|
16337
16928
|
const [paused, loaded] = await Promise.all([storage.casPauseOrderFulfillment(orderFulfillmentId, patch), storage.getOrder(row.order_id)]);
|
|
16338
|
-
if (!paused) return;
|
|
16929
|
+
if (!paused) return { closed: false };
|
|
16339
16930
|
order = loaded;
|
|
16340
16931
|
}
|
|
16341
16932
|
const u2 = {
|
|
@@ -16353,6 +16944,7 @@ const pauseForAdvance = async (ports, config) => {
|
|
|
16353
16944
|
order
|
|
16354
16945
|
});
|
|
16355
16946
|
if (isWaitingPaymentNode(patched)) await execPort.onWaitingPayment?.(row.order_id);
|
|
16947
|
+
return { closed: false };
|
|
16356
16948
|
};
|
|
16357
16949
|
const resumeFromAdvance = async (ports, config) => {
|
|
16358
16950
|
const { storage, execution: execPort } = ports;
|
|
@@ -16388,14 +16980,21 @@ const resumeFromAdvance = async (ports, config) => {
|
|
|
16388
16980
|
requestedAt
|
|
16389
16981
|
});
|
|
16390
16982
|
}
|
|
16983
|
+
const alreadyTerminal = sittingWorkflowNode(row.workflow, row.current_node_ids)?.data.kind === "terminal";
|
|
16391
16984
|
const patch = {
|
|
16392
16985
|
steps_logs,
|
|
16393
16986
|
status: "PROCESSING",
|
|
16394
16987
|
workflow: row.workflow
|
|
16395
16988
|
};
|
|
16396
16989
|
await storage.updateOrderFulfillment(orderFulfillmentId, patch);
|
|
16397
|
-
if (!order) return {
|
|
16398
|
-
|
|
16990
|
+
if (!order) return {
|
|
16991
|
+
edges: null,
|
|
16992
|
+
alreadyTerminal
|
|
16993
|
+
};
|
|
16994
|
+
if (config.emit === false) return {
|
|
16995
|
+
edges,
|
|
16996
|
+
alreadyTerminal
|
|
16997
|
+
};
|
|
16399
16998
|
const patched = {
|
|
16400
16999
|
...row,
|
|
16401
17000
|
...patch
|
|
@@ -16405,7 +17004,10 @@ const resumeFromAdvance = async (ports, config) => {
|
|
|
16405
17004
|
row: patched,
|
|
16406
17005
|
order
|
|
16407
17006
|
});
|
|
16408
|
-
return {
|
|
17007
|
+
return {
|
|
17008
|
+
edges,
|
|
17009
|
+
alreadyTerminal
|
|
17010
|
+
};
|
|
16409
17011
|
};
|
|
16410
17012
|
//#endregion
|
|
16411
17013
|
//#region src/fulfillment/engine/enterAndPause.ts
|
|
@@ -16431,7 +17033,7 @@ const enterAndPause = async (ports, config) => {
|
|
|
16431
17033
|
};
|
|
16432
17034
|
const advanceAndEnter = async (ports, config) => {
|
|
16433
17035
|
const { fulfillmentStatus, requestedAt, terminalStatus, ...scope } = config;
|
|
16434
|
-
const { edges } = await resumeFromAdvance(ports, {
|
|
17036
|
+
const { edges, alreadyTerminal } = await resumeFromAdvance(ports, {
|
|
16435
17037
|
...scope,
|
|
16436
17038
|
fulfillmentStatus,
|
|
16437
17039
|
requestedAt,
|
|
@@ -16439,7 +17041,10 @@ const advanceAndEnter = async (ports, config) => {
|
|
|
16439
17041
|
});
|
|
16440
17042
|
if (!edges) throw new Error("Fulfillment or order missing during advance");
|
|
16441
17043
|
const target = pickAdvanceTarget(edges);
|
|
16442
|
-
if (!target) return {
|
|
17044
|
+
if (!target) return {
|
|
17045
|
+
noEdge: true,
|
|
17046
|
+
alreadyTerminal
|
|
17047
|
+
};
|
|
16443
17048
|
const e1 = {
|
|
16444
17049
|
...scope,
|
|
16445
17050
|
nodeId: target.targetId,
|
|
@@ -16620,6 +17225,16 @@ const defaultPublicOrder = (order) => {
|
|
|
16620
17225
|
for (const key of INTERNAL_ORDER_KEYS$1) delete copy[key];
|
|
16621
17226
|
return copy;
|
|
16622
17227
|
};
|
|
17228
|
+
const replacedByOrderIdOf = (order) => {
|
|
17229
|
+
const meta = order.metadata;
|
|
17230
|
+
if (!meta || typeof meta !== "object") return null;
|
|
17231
|
+
const reopen = meta.reopen;
|
|
17232
|
+
if (!reopen || typeof reopen !== "object") return null;
|
|
17233
|
+
const raw = reopen.as_order_id;
|
|
17234
|
+
if (typeof raw !== "string") return null;
|
|
17235
|
+
const trimmed = raw.trim();
|
|
17236
|
+
return trimmed.length > 0 ? trimmed : null;
|
|
17237
|
+
};
|
|
16623
17238
|
const webhookScope = (order) => {
|
|
16624
17239
|
const b0 = order.merchant_id ? { merchant_id: order.merchant_id } : {};
|
|
16625
17240
|
const b1 = {
|
|
@@ -16632,12 +17247,15 @@ const webhookScope = (order) => {
|
|
|
16632
17247
|
};
|
|
16633
17248
|
const b3 = { brand_id: order.brand_id ?? null };
|
|
16634
17249
|
const b4 = { customer_id: order.customer_id };
|
|
17250
|
+
const replacedBy = replacedByOrderIdOf(order);
|
|
17251
|
+
const b5 = replacedBy ? { replaced_by_order_id: replacedBy } : {};
|
|
16635
17252
|
return {
|
|
16636
17253
|
...b0,
|
|
16637
17254
|
...b1,
|
|
16638
17255
|
...b2,
|
|
16639
17256
|
...b3,
|
|
16640
|
-
...b4
|
|
17257
|
+
...b4,
|
|
17258
|
+
...b5
|
|
16641
17259
|
};
|
|
16642
17260
|
};
|
|
16643
17261
|
/** Target URL for a webhook given cloud / local-online / offline mode. */
|
|
@@ -17501,171 +18119,6 @@ const resolveCallbackFailTerminal = async (ports, config) => {
|
|
|
17501
18119
|
return null;
|
|
17502
18120
|
};
|
|
17503
18121
|
//#endregion
|
|
17504
|
-
//#region src/fulfillment/engine/finalize.ts
|
|
17505
|
-
const HARD_FAILED_CODES = /* @__PURE__ */ new Set([CALLBACK_MISSING_LOCAL_URL, WORKFLOW_TIMEOUT]);
|
|
17506
|
-
const engineOrderStatusForFailedRun = (order, isPaymentCaptured = defaultIsPaymentCaptured) => {
|
|
17507
|
-
if (!order) return null;
|
|
17508
|
-
if (isInterruptTerminalStatus(order.status) || order.status === "COMPLETED") return null;
|
|
17509
|
-
return isPaymentCaptured(order) ? "REVERSED" : "VOIDED";
|
|
17510
|
-
};
|
|
17511
|
-
const syncOrderFromSittingTerminal = async (ports, orderFulfillmentId) => {
|
|
17512
|
-
const row = await ports.storage.getOrderFulfillment(orderFulfillmentId);
|
|
17513
|
-
if (!row) return;
|
|
17514
|
-
const sitting = sittingWorkflowNode(row.workflow, row.current_node_ids);
|
|
17515
|
-
if (!sitting || sitting.data.kind !== "terminal") return;
|
|
17516
|
-
const order = await ports.storage.getOrder(row.order_id);
|
|
17517
|
-
const isCaptured = ports.execution.isPaymentCaptured ?? defaultIsPaymentCaptured;
|
|
17518
|
-
const fields = orderFieldsFromNode(sitting, void 0, order ? isCaptured(order) : false);
|
|
17519
|
-
const patch = {
|
|
17520
|
-
fulfillment_status: sitting.data.mappedStatus,
|
|
17521
|
-
...fields
|
|
17522
|
-
};
|
|
17523
|
-
await ports.storage.updateOrderStatusAndSettle(row.order_id, patch);
|
|
17524
|
-
};
|
|
17525
|
-
const emitFinalizeChanged = async (ports, orderFulfillmentId, error) => {
|
|
17526
|
-
const row = await ports.storage.getOrderFulfillment(orderFulfillmentId);
|
|
17527
|
-
const orderId = row?.order_id;
|
|
17528
|
-
const order = orderId ? await ports.storage.getOrder(orderId) : null;
|
|
17529
|
-
if (row && order) {
|
|
17530
|
-
await ports.execution.onOrderChanged?.({
|
|
17531
|
-
orderFulfillmentId,
|
|
17532
|
-
row,
|
|
17533
|
-
order,
|
|
17534
|
-
error
|
|
17535
|
-
});
|
|
17536
|
-
return;
|
|
17537
|
-
}
|
|
17538
|
-
await ports.execution.onOrderChanged?.({
|
|
17539
|
-
orderFulfillmentId,
|
|
17540
|
-
error
|
|
17541
|
-
});
|
|
17542
|
-
};
|
|
17543
|
-
const finalizePlaceOrder = async (ports, config) => {
|
|
17544
|
-
const { storage, execution: execPort } = ports;
|
|
17545
|
-
const { orderFulfillmentId, status, failureMessage } = config;
|
|
17546
|
-
const { errorCode, errorDetails } = config;
|
|
17547
|
-
const now = execPort.now;
|
|
17548
|
-
const row = await storage.getOrderFulfillment(orderFulfillmentId);
|
|
17549
|
-
const steps_logs = row?.steps_logs ?? [];
|
|
17550
|
-
const isHardFailed = Boolean(errorCode && HARD_FAILED_CODES.has(errorCode));
|
|
17551
|
-
if (status === "FAILED" && failureMessage) failActiveEngineStepLog(steps_logs, failureMessage, {
|
|
17552
|
-
code: errorCode,
|
|
17553
|
-
details: errorDetails,
|
|
17554
|
-
now
|
|
17555
|
-
});
|
|
17556
|
-
beginEngineStepLog(steps_logs, "FINALIZE", void 0, now);
|
|
17557
|
-
if (status === "FAILED" && isHardFailed && failureMessage) appendEngineStepLog(steps_logs, "FINALIZE", {
|
|
17558
|
-
type: "error",
|
|
17559
|
-
message: failureMessage,
|
|
17560
|
-
code: errorCode,
|
|
17561
|
-
details: errorDetails
|
|
17562
|
-
});
|
|
17563
|
-
completeEngineStepLog(steps_logs, "FINALIZE", status === "SUCCESS" ? "Fulfillment completed" : "Fulfillment failed", now);
|
|
17564
|
-
if (status === "FAILED") {
|
|
17565
|
-
const peekOrderId = (row ?? await storage.getOrderFulfillment(orderFulfillmentId))?.order_id;
|
|
17566
|
-
const peekOrder = peekOrderId ? await storage.getOrder(peekOrderId) : null;
|
|
17567
|
-
if (!isHardFailed && isInterruptTerminalStatus(peekOrder?.status)) {
|
|
17568
|
-
const ok = {
|
|
17569
|
-
steps_logs,
|
|
17570
|
-
step: "FINALIZE",
|
|
17571
|
-
status: "SUCCESS"
|
|
17572
|
-
};
|
|
17573
|
-
await storage.updateOrderFulfillment(orderFulfillmentId, ok);
|
|
17574
|
-
await syncOrderFromSittingTerminal(ports, orderFulfillmentId);
|
|
17575
|
-
await emitFinalizeChanged(ports, orderFulfillmentId);
|
|
17576
|
-
return { failed: false };
|
|
17577
|
-
}
|
|
17578
|
-
if (isHardFailed && peekOrder) {
|
|
17579
|
-
const resolvedAt = (now ? now() : /* @__PURE__ */ new Date()).toISOString();
|
|
17580
|
-
await storage.updateOrderStatusAndSettle(peekOrder.id, {
|
|
17581
|
-
fulfillment_status: "FAILED",
|
|
17582
|
-
status: "FAILED",
|
|
17583
|
-
resolved_at: resolvedAt
|
|
17584
|
-
});
|
|
17585
|
-
const key = `${orderFulfillmentId}:${errorCode}`;
|
|
17586
|
-
const reviewMsg = failureMessage ?? `${errorCode}: Fulfillment failed`;
|
|
17587
|
-
await storage.flagOrderForReview?.({
|
|
17588
|
-
order: peekOrder,
|
|
17589
|
-
key,
|
|
17590
|
-
message: reviewMsg
|
|
17591
|
-
});
|
|
17592
|
-
} else if (peekOrder) {
|
|
17593
|
-
const isCaptured = execPort.isPaymentCaptured ?? defaultIsPaymentCaptured;
|
|
17594
|
-
const closed = engineOrderStatusForFailedRun(peekOrder, isCaptured);
|
|
17595
|
-
if (closed) await storage.updateOrderStatusAndSettle(peekOrder.id, {
|
|
17596
|
-
fulfillment_status: closed,
|
|
17597
|
-
status: closed
|
|
17598
|
-
});
|
|
17599
|
-
}
|
|
17600
|
-
}
|
|
17601
|
-
const errorFields = status === "FAILED" ? {
|
|
17602
|
-
error_code: errorCode ?? null,
|
|
17603
|
-
error_message: failureMessage ?? "Fulfillment failed"
|
|
17604
|
-
} : {};
|
|
17605
|
-
await storage.updateOrderFulfillment(orderFulfillmentId, {
|
|
17606
|
-
steps_logs,
|
|
17607
|
-
step: "FINALIZE",
|
|
17608
|
-
status,
|
|
17609
|
-
...errorFields
|
|
17610
|
-
});
|
|
17611
|
-
if (status !== "FAILED") {
|
|
17612
|
-
await syncOrderFromSittingTerminal(ports, orderFulfillmentId);
|
|
17613
|
-
await emitFinalizeChanged(ports, orderFulfillmentId);
|
|
17614
|
-
return { failed: false };
|
|
17615
|
-
}
|
|
17616
|
-
const raw = failureMessage ?? "Fulfillment failed";
|
|
17617
|
-
await emitFinalizeChanged(ports, orderFulfillmentId, errorCode ? {
|
|
17618
|
-
message: raw,
|
|
17619
|
-
code: errorCode
|
|
17620
|
-
} : { message: raw });
|
|
17621
|
-
if (row?.order_id) await execPort.onInjectionFailed?.({
|
|
17622
|
-
orderId: row.order_id,
|
|
17623
|
-
message: raw,
|
|
17624
|
-
code: errorCode
|
|
17625
|
-
});
|
|
17626
|
-
return { failed: true };
|
|
17627
|
-
};
|
|
17628
|
-
const warnNoEdge = async (ports, config) => {
|
|
17629
|
-
const { storage, execution: execPort } = ports;
|
|
17630
|
-
const { orderFulfillmentId, fulfillmentStatus } = config;
|
|
17631
|
-
const now = execPort.now;
|
|
17632
|
-
const row = await storage.getOrderFulfillment(orderFulfillmentId);
|
|
17633
|
-
if (!row || row.current_node_ids.length === 0) return;
|
|
17634
|
-
const orderPromise = storage.getOrder(row.order_id);
|
|
17635
|
-
const message = `No outgoing edge matches ${fulfillmentStatus}`;
|
|
17636
|
-
const nodesById = new Map(row.workflow.nodes.map((node) => [node.id, node]));
|
|
17637
|
-
for (const id of row.current_node_ids) {
|
|
17638
|
-
const node = nodesById.get(id) ?? findNodeById(row.workflow, id);
|
|
17639
|
-
if (node) appendNodeLog(node, "warning", message);
|
|
17640
|
-
}
|
|
17641
|
-
const steps_logs = row.steps_logs;
|
|
17642
|
-
beginEngineStepLog(steps_logs, "WARN_NO_EDGE", void 0, now);
|
|
17643
|
-
appendEngineStepLog(steps_logs, "WARN_NO_EDGE", {
|
|
17644
|
-
type: "warning",
|
|
17645
|
-
message
|
|
17646
|
-
});
|
|
17647
|
-
completeEngineStepLog(steps_logs, "WARN_NO_EDGE", "Kept waiting", now);
|
|
17648
|
-
const warning_count = (row.warning_count ?? 0) + 1;
|
|
17649
|
-
const patch = {
|
|
17650
|
-
workflow: row.workflow,
|
|
17651
|
-
steps_logs,
|
|
17652
|
-
warning_count,
|
|
17653
|
-
status: "WAITING"
|
|
17654
|
-
};
|
|
17655
|
-
await storage.updateOrderFulfillment(orderFulfillmentId, patch);
|
|
17656
|
-
const order = await orderPromise;
|
|
17657
|
-
if (!order) return;
|
|
17658
|
-
const patched = {
|
|
17659
|
-
...row,
|
|
17660
|
-
...patch
|
|
17661
|
-
};
|
|
17662
|
-
await execPort.onOrderChanged?.({
|
|
17663
|
-
orderFulfillmentId,
|
|
17664
|
-
row: patched,
|
|
17665
|
-
order
|
|
17666
|
-
});
|
|
17667
|
-
};
|
|
17668
|
-
//#endregion
|
|
17669
18122
|
//#region src/fulfillment/engine/runner.ts
|
|
17670
18123
|
const pendingWebhooksOf = (next) => {
|
|
17671
18124
|
if (!next.entered || next.alreadyTerminal) return null;
|
|
@@ -17794,15 +18247,17 @@ const finalizeOrPause = async (ports, scope, settled) => {
|
|
|
17794
18247
|
};
|
|
17795
18248
|
}
|
|
17796
18249
|
if (runIsTerminal(settled)) {
|
|
18250
|
+
const terminalStatus = terminalRunStatusForEnter(settled);
|
|
17797
18251
|
await finalizePlaceOrder(ports, {
|
|
17798
18252
|
orderFulfillmentId: scope.orderFulfillmentId,
|
|
17799
|
-
status:
|
|
18253
|
+
status: terminalStatus
|
|
17800
18254
|
});
|
|
17801
18255
|
await dispatchPendingWebhooks(ports, scope, settled.pending);
|
|
17802
|
-
return { status:
|
|
18256
|
+
return { status: terminalStatus };
|
|
17803
18257
|
}
|
|
17804
|
-
await pauseForAdvance(ports, { orderFulfillmentId: scope.orderFulfillmentId });
|
|
18258
|
+
const paused = await pauseForAdvance(ports, { orderFulfillmentId: scope.orderFulfillmentId });
|
|
17805
18259
|
await dispatchPendingWebhooks(ports, scope, settled.pending);
|
|
18260
|
+
if (paused.closed) return { status: paused.status };
|
|
17806
18261
|
return { status: "WAITING" };
|
|
17807
18262
|
};
|
|
17808
18263
|
const handlePausedNode = async (ports, scope, ran, terminalStatus) => {
|
|
@@ -17840,11 +18295,17 @@ const executeAdvance = async (ports, scope, event) => {
|
|
|
17840
18295
|
terminalStatus: event.status
|
|
17841
18296
|
});
|
|
17842
18297
|
if (advanced.noEdge) {
|
|
18298
|
+
if (advanced.alreadyTerminal) {
|
|
18299
|
+
const paused = await pauseForAdvance(ports, { orderFulfillmentId: scope.orderFulfillmentId });
|
|
18300
|
+
if (paused.closed) return { status: paused.status };
|
|
18301
|
+
return { status: "WAITING" };
|
|
18302
|
+
}
|
|
17843
18303
|
await warnNoEdge(ports, {
|
|
17844
18304
|
orderFulfillmentId: scope.orderFulfillmentId,
|
|
17845
18305
|
fulfillmentStatus: event.fulfillment_status
|
|
17846
18306
|
});
|
|
17847
|
-
await pauseForAdvance(ports, { orderFulfillmentId: scope.orderFulfillmentId });
|
|
18307
|
+
const paused = await pauseForAdvance(ports, { orderFulfillmentId: scope.orderFulfillmentId });
|
|
18308
|
+
if (paused.closed) return { status: paused.status };
|
|
17848
18309
|
return { status: "WAITING" };
|
|
17849
18310
|
}
|
|
17850
18311
|
if (advanced.paused) return handlePausedNode(ports, scope, advanced.ran, event.status);
|
|
@@ -17864,7 +18325,8 @@ const executeScheduledWake = async (ports, scope, nodeId, terminalStatus) => {
|
|
|
17864
18325
|
orderFulfillmentId: scope.orderFulfillmentId,
|
|
17865
18326
|
fulfillmentStatus: SCHEDULED_STATUS
|
|
17866
18327
|
});
|
|
17867
|
-
await pauseForAdvance(ports, { orderFulfillmentId: scope.orderFulfillmentId });
|
|
18328
|
+
const paused = await pauseForAdvance(ports, { orderFulfillmentId: scope.orderFulfillmentId });
|
|
18329
|
+
if (paused.closed) return { status: paused.status };
|
|
17868
18330
|
return { status: "WAITING" };
|
|
17869
18331
|
}
|
|
17870
18332
|
return executeAdvance(ports, scope, {
|
|
@@ -18392,4 +18854,4 @@ const validateTaxId = (country, type, raw) => {
|
|
|
18392
18854
|
};
|
|
18393
18855
|
};
|
|
18394
18856
|
//#endregion
|
|
18395
|
-
export { CALLBACK_MISSING_LOCAL_URL, CANONICAL_MAX_DEPTH, CANONICAL_MAX_EXPONENT, CARD_BRANDS, CUSTOMER_INFO_PLACEHOLDERS, DEFAULT_LOCALE, DEFAULT_MAX_INCOMPLETE_MINUTES, DEFAULT_MAX_SNAPSHOT_AGE_MS, DEFAULT_RECOMMENDATION_TYPES, DEFAULT_ROUTE_COOLDOWN_MS, DEFAULT_WEBHOOK_TIMEOUT_S, DelegatedSessionExpiredError, FULFILLMENT_WORKFLOW_TERMINAL_STATUSES, HPKE_ALG, ID_HASH_FORMATS, INVOICE_COUNTRIES, LosslessNumber, MAX_MAX_INCOMPLETE_MINUTES, MAX_SUPPORTED_WORKFLOW_SCHEMA_VERSION, MIN_MAX_INCOMPLETE_MINUTES, MODE_HINT_HEADER, OFFLINE_NO_LOCAL_URL, ORIGIN_HEADER, Order, OrderAuthPinnedError, OrderNotOpenError, OrderPaymentRequiredError, OrderRouteUnavailableError, OrderSyncPendingError, OrderSyncRejectedError, OrderValidationError, RESERVED_FULFILLMENT_STATUSES, REWARD_SAVINGS_METADATA_KEY, RecurringDateCron, RulesEngine, SCHEDULED_AT_ERROR_CODES, SCHEDULED_ORDER_MAX_HORIZON_HOURS, SCHEDULED_ORDER_MAX_HORIZON_MINUTES, SCHEDULED_ORDER_MIN_LEAD_MINUTES, SCHEDULED_ORDER_SLOT_MINUTES, SCHEDULED_STATUS, SDK_PAYMENT_ELIGIBILITY_CEILINGS, STATE_ALGO, STATE_HASH_PREFIX, StorefrontHttpError, TLS_FINGERPRINT_RESPONSE_HEADER, TLS_PIN_HEADER, TlsFingerprintMismatchError, TokenExchangeError, WORKFLOW_SCHEMA_VERSION, WORKFLOW_TIMEOUT, WorkflowSchemaVersionError, addLines, advanceAndEnter, appendEngineStepLog, appendNodeLog, applyCmsVisibility, applyFees, applyManualAdvanceNote, applyRewardSavingsToLines, assertSupportedWorkflowSchemaVersion, auth, autoEnterSuccessTerminal, base64UrlDecode, base64UrlEncode, beginEngineStepLog, buildCustomerSnapshot, buildEngineCallbackError, buildEngineCallbackRun, buildRouteHttpOptions, buildRulesEngineFromOrder, buildScheduleSlots, buildWorkflowTimeoutDetails, callbackIdsFromNode, canEnterJoin, canPauseNow, cancelTypeOf, canonicalNumber, canonicalString, canonicalize, canonicalizeJson, capRedeems, cappedRedeems, cardBrandSpec, cardDigits, cardNumberGaps, cardNumberMaxLength, cardPreviewGroups, caretAfterDigits, certFingerprintsMatch, certMatchesAnyPin, classifyRouteFailure, clearDeviceSecrets, clearEdgeTaken, clearNodeVisit, cmsVisibilityNeedsTimezone, collectCheckoutIssues, collectOrderLineDiffs, completeEngineStepLog, computeOrderExpiresAt, computeProductRewardSavings, computeStartingPrice, computeTaxBreakdown, configureDeviceSecrets, configureLocalTlsPinning, countCartProducts, coveredAmount, createCanonicalizationError, createDeunaWidgetApi, createDeviceSecretsStore, createNodePinnedFetch, createSession, currentNodes, cvcMaxLength, defaultConditionError, defaultIsPaymentCaptured, defaultOutgoingEdge, defaultWebhookEventsForStatus, defaultWebhookRetryDelayMs, detectCardBrand, dispatchOrderWebhooks, dispatchPendingWebhooks, engineHmacSha256Hex, engineOrderStatusForFailedRun, engineWebhookDeliveryId, engineWebhookRunsForEnteredNodes, engineWebhookStatusKey, engineWebhookTransitionStates, enterAndPause, enterWorkflowNode, executeAdvance, executeScheduledWake, executeStart, failActiveEngineStepLog, finalizePlaceOrder, findFirstState, findLocaleKey, findMappedStatusNode, findNodeById, findShippingFeeLine, findStartNode, fitRedeems, flattenMenuCategories, flushLogs, formatCardNumber, formatCvc, formatExpiry, formatLocalServerUrl, formatRecurringDateCronSummary, fromOrderLines, fulfillmentStatusesEqual, genId, genOrderId, getInvoiceCountry, getLineRewardSavings, getLocalTlsPinning, getLogContext, getOrigin, getRouteHealth, getScheduleWindow, getSecret, hasInFlightPayment, hasLocalTlsPinning, hasSmartRouting, hpkeOpen, hpkeSeal, incomingEdges, indexMenu, indexOutgoingBySource, injectingMetadataFromCallback, invokeCallbackAttempt, isCanonicalizationError, isCardNumberComplete, isCardNumberDefinitelyInvalid, isCheckoutFieldFilled, isCustomerInfoFieldFilled, isCustomerInfoPlaceholder, isCustomerInfoValueValid, isCvcComplete, isDelegatedSessionExpiredError, isDeliveryFee, isDeviceCharged, isDeviceNotLinked, isExpiredFulfillment, isExpiryComplete, isGenId, isInterruptTerminalStatus, isKioskUnauthorized, isLocalOrderUnknown, isMilestoneStepDone, isNodeRuntime, isOnSchedule, isOrderNotOpenError, isOrderPaymentRequiredError, isOrderRouteUnavailableError, isOrderValidationError, isPosDeviceNotLinked, isPosUnauthorized, isRealPaymentMethod, isReservedFulfillmentStatus, isRouteCircuitOpen, isScheduleSlot, isScheduledAtError, isShippingFeeLine, isStateHash, isStorefrontNotFound, isSupportedWorkflowSchemaVersion, isTerminalFulfillmentStatus, isTerminalMappedStatus, isTlsFingerprintMismatchError, isVariantBase, lineCartValue, linePayableTotal, listMenusStream, listSecretKeys, localizePosError, log, logError, luhnCheck, markEdgeTaken, markNodeEntered, markNodeExited, markNodeSkipped, markNodesAdvance, markNodesReady, markRouteDown, markRouteHealthy, matchAbsoluteDateOperator, matchBooleanOperator, matchCurrencyOperator, matchEnumOperator, matchNumberOperator, matchRecurringDateOperator, matchRelativeDateOperator, matchStringOperator, matchingPrimaryOutgoing, milestoneSteps, milestoneTrack, nestMenuCategories, nextCurrentNodeIds, normalizeCardholderName, normalizeCertFingerprint, normalizeCustomerPhone, normalizeFulfillmentStatus, normalizeLocaleKey, normalizeMaxIncompleteMinutes, normalizePickupName, normalizeStateScope, onOriginChange, onRouteHealth, orderFactsFromOrder, orderFieldsFromNode, orderPayableTotal, orderRedeemedTotal, orderRedeems, orderStatusForFulfillmentStatus, outgoingEdges, parseExpiry, parseLosslessJson, pathKindForTargetNode, pauseForAdvance, paymentMatchesClientConditions, pendingWebhooksOf, pickAdvanceTarget, pickLocalizedText, pickMultiLanguageText, placeCartLines, probeLocalRouteHealth, processStateNode, rebuildOrderLinesWithFees, rebuildRootGroups, recomputeTotals, redeemedTotal, redeemsForPayment, redemptionCap, redemptionSteps, remainingAmount, removeLine, replaceLine, rescaleLineRewardSavings, resolveAdvanceEdge, resolveAdvanceEdges, resolveCallbackFailTerminal, resolveCheckout, resolveFailureTerminalEdge, resolveLocalPins, resolveLocalRouteUrl, resolveModifierImageUrl, resolveOrderRouteEligibility, resolvePaymentEligibility, resolveSchedulePrepMinutes, resolveSdkPaymentEligibilityCeiling, resolveSuccessTerminalEdges, resolveWebhookTargetUrl, resumeFromAdvance, reversePayment, reversedWhenCaptured, roundFeeAmount, runIsTerminal, runNodeCallbacks, runPaymentAttempt, runStateGoldenVectors, scheduledInstant, scheduledSuccessorStatus, selectMatchingFees, selectablePayments, serializeError, services, setLineQuantity, settleEnter, sha256Hex, sha256HexOfString, sittingWorkflowNode, stateRootHash, stateScopeKey, stateSectionHash, stateSectionHashOfJson, storefrontJson, stripFeeLines, stubUnsupportedFeeAmount, summarizeRecurringDateCron, syncDeviceSecrets, testLocalServerHealth, toOrderLines, toPaymentCardBrand, unusedOutgoing, utf8Encode, validateCardNumber, validateCardholderName, validateCvc, validateEcuadorCedula, validateEcuadorRuc, validateExpiry, validateOrderAgainstMenu, validatePickupName, validateTaxId, verifyLocalRoutePin, verifyWebhookSignature, visitedStates, warnNoEdge, withLineRewardSavings, workflowSchemaVersionOf };
|
|
18857
|
+
export { CALLBACK_MISSING_LOCAL_URL, CANONICAL_MAX_DEPTH, CANONICAL_MAX_EXPONENT, CARD_BRANDS, CUSTOMER_INFO_PLACEHOLDERS, DEFAULT_LOCALE, DEFAULT_MAX_INCOMPLETE_MINUTES, DEFAULT_MAX_SNAPSHOT_AGE_MS, DEFAULT_RECOMMENDATION_TYPES, DEFAULT_ROUTE_COOLDOWN_MS, DEFAULT_WEBHOOK_TIMEOUT_S, DelegatedSessionExpiredError, FULFILLMENT_WORKFLOW_TERMINAL_STATUSES, HPKE_ALG, ID_HASH_FORMATS, INVOICE_COUNTRIES, LosslessNumber, MAX_MAX_INCOMPLETE_MINUTES, MAX_SUPPORTED_WORKFLOW_SCHEMA_VERSION, MIN_MAX_INCOMPLETE_MINUTES, MODE_HINT_HEADER, OFFLINE_NO_LOCAL_URL, ORIGIN_HEADER, Order, OrderAuthPinnedError, OrderNotOpenError, OrderPaymentRequiredError, OrderRouteUnavailableError, OrderSyncPendingError, OrderSyncRejectedError, OrderValidationError, RESERVED_FULFILLMENT_STATUSES, REWARD_SAVINGS_METADATA_KEY, RecurringDateCron, RulesEngine, SCHEDULED_AT_ERROR_CODES, SCHEDULED_ORDER_MAX_HORIZON_HOURS, SCHEDULED_ORDER_MAX_HORIZON_MINUTES, SCHEDULED_ORDER_MIN_LEAD_MINUTES, SCHEDULED_ORDER_SLOT_MINUTES, SCHEDULED_STATUS, SDK_PAYMENT_ELIGIBILITY_CEILINGS, STATE_ALGO, STATE_HASH_PREFIX, StorefrontHttpError, TLS_FINGERPRINT_RESPONSE_HEADER, TLS_PIN_HEADER, TlsFingerprintMismatchError, TokenExchangeError, WORKFLOW_SCHEMA_VERSION, WORKFLOW_TIMEOUT, WorkflowSchemaVersionError, addLines, advanceAndEnter, appendEngineStepLog, appendNodeLog, applyCmsVisibility, applyFees, applyManualAdvanceNote, applyRewardSavingsToLines, assertSupportedWorkflowSchemaVersion, auth, autoEnterSuccessTerminal, base64UrlDecode, base64UrlEncode, beginEngineStepLog, buildCustomerSnapshot, buildEngineCallbackError, buildEngineCallbackRun, buildRouteHttpOptions, buildRulesEngineFromOrder, buildScheduleSlots, buildWorkflowTimeoutDetails, callbackIdsFromNode, canEnterJoin, canPauseNow, cancelTypeOf, canonicalNumber, canonicalString, canonicalize, canonicalizeJson, capRedeems, cappedRedeems, cardBrandSpec, cardDigits, cardNumberGaps, cardNumberMaxLength, cardPreviewGroups, caretAfterDigits, certFingerprintsMatch, certMatchesAnyPin, classifyRouteFailure, clearDeviceSecrets, clearEdgeTaken, clearNodeVisit, cmsVisibilityNeedsTimezone, collectCheckoutIssues, collectOrderLineDiffs, completeEngineStepLog, computeOrderExpiresAt, computeProductRewardSavings, computeStartingPrice, computeTaxBreakdown, configureDeviceSecrets, configureLocalTlsPinning, countCartProducts, coveredAmount, createCanonicalizationError, createDeunaWidgetApi, createDeviceSecretsStore, createNodePinnedFetch, createSession, currentNodes, cvcMaxLength, defaultConditionError, defaultIsPaymentCaptured, defaultOutgoingEdge, defaultWebhookEventsForStatus, defaultWebhookRetryDelayMs, detectCardBrand, dispatchOrderWebhooks, dispatchPendingWebhooks, engineHmacSha256Hex, engineOrderStatusForFailedRun, engineWebhookDeliveryId, engineWebhookRunsForEnteredNodes, engineWebhookStatusKey, engineWebhookTransitionStates, enterAndPause, enterWorkflowNode, executeAdvance, executeScheduledWake, executeStart, failActiveEngineStepLog, finalizePlaceOrder, findFirstState, findLocaleKey, findMappedStatusNode, findNodeById, findShippingFeeLine, findStartNode, fitRedeems, flattenMenuCategories, flushLogs, formatCardNumber, formatCvc, formatExpiry, formatLocalServerUrl, formatRecurringDateCronSummary, fromOrderLines, fulfillmentStatusesEqual, genId, genOrderId, getInvoiceCountry, getLineRewardSavings, getLocalTlsPinning, getLogContext, getOrigin, getRouteHealth, getScheduleWindow, getSecret, hasInFlightPayment, hasLocalTlsPinning, hasSmartRouting, hpkeOpen, hpkeSeal, incomingEdges, indexMenu, indexOutgoingBySource, injectingMetadataFromCallback, invokeCallbackAttempt, isCanonicalizationError, isCardNumberComplete, isCardNumberDefinitelyInvalid, isCheckoutFieldFilled, isCustomerInfoFieldFilled, isCustomerInfoPlaceholder, isCustomerInfoValueValid, isCvcComplete, isDelegatedSessionExpiredError, isDeliveryFee, isDeviceCharged, isDeviceNotLinked, isExpiredFulfillment, isExpiryComplete, isGenId, isInterruptTerminalStatus, isKioskUnauthorized, isLocalOrderUnknown, isMilestoneStepDone, isNodeRuntime, isOnSchedule, isOrderNotOpenError, isOrderPaymentRequiredError, isOrderRouteUnavailableError, isOrderValidationError, isPosDeviceNotLinked, isPosUnauthorized, isRealPaymentMethod, isReservedFulfillmentStatus, isRouteCircuitOpen, isScheduleSlot, isScheduledAtError, isShippingFeeLine, isStateHash, isStorefrontNotFound, isSupportedWorkflowSchemaVersion, isTerminalFulfillmentStatus, isTerminalMappedStatus, isTlsFingerprintMismatchError, isVariantBase, lineCartValue, linePayableTotal, listMenusStream, listSecretKeys, localizePosError, log, logError, luhnCheck, markEdgeTaken, markNodeEntered, markNodeExited, markNodeSkipped, markNodesAdvance, markNodesReady, markRouteDown, markRouteHealthy, matchAbsoluteDateOperator, matchBooleanOperator, matchCurrencyOperator, matchEnumOperator, matchNumberOperator, matchRecurringDateOperator, matchRelativeDateOperator, matchStringOperator, matchingPrimaryOutgoing, milestoneSteps, milestoneTrack, nestMenuCategories, nextCurrentNodeIds, normalizeCardholderName, normalizeCertFingerprint, normalizeCustomerPhone, normalizeFulfillmentStatus, normalizeLocaleKey, normalizeMaxIncompleteMinutes, normalizePickupName, normalizeStateScope, onOriginChange, onRouteHealth, orderFactsFromOrder, orderFieldsFromNode, orderPayableTotal, orderRedeemedTotal, orderRedeems, orderStatusForFulfillmentStatus, outgoingEdges, parseExpiry, parseLosslessJson, pathKindForTargetNode, pauseForAdvance, paymentMatchesClientConditions, pendingWebhooksOf, pickAdvanceTarget, pickLocalizedText, pickMultiLanguageText, placeCartLines, probeLocalRouteHealth, processStateNode, rebuildOrderLinesWithFees, rebuildRootGroups, recomputeTotals, redeemedTotal, redeemsForPayment, redemptionCap, redemptionSteps, remainingAmount, removeLine, replaceLine, rescaleLineRewardSavings, resolveAdvanceEdge, resolveAdvanceEdges, resolveCallbackFailTerminal, resolveCheckout, resolveFailureTerminalEdge, resolveLocalPins, resolveLocalRouteUrl, resolveModifierImageUrl, resolveOrderRouteEligibility, resolvePaymentEligibility, resolveSchedulePrepMinutes, resolveSdkPaymentEligibilityCeiling, resolveSuccessTerminalEdges, resolveWebhookTargetUrl, resumeFromAdvance, reversePayment, reversedWhenCaptured, roundFeeAmount, runIsTerminal, runNodeCallbacks, runPaymentAttempt, runStateGoldenVectors, scheduledInstant, scheduledSuccessorStatus, selectMatchingFees, selectablePayments, serializeError, services, setLineQuantity, settleEnter, sha256Hex, sha256HexOfString, sittingWorkflowNode, stateRootHash, stateScopeKey, stateSectionHash, stateSectionHashOfJson, storefrontJson, stripFeeLines, stubUnsupportedFeeAmount, summarizeRecurringDateCron, syncDeviceSecrets, terminalRunStatusForEnter, terminalRunStatusForNode, testLocalServerHealth, toOrderLines, toPaymentCardBrand, unusedOutgoing, utf8Encode, validateCardNumber, validateCardholderName, validateCvc, validateEcuadorCedula, validateEcuadorRuc, validateExpiry, validateOrderAgainstMenu, validatePickupName, validateTaxId, verifyLocalRoutePin, verifyWebhookSignature, visitedStates, warnNoEdge, withLineRewardSavings, workflowSchemaVersionOf };
|