@pisell/pisellos 2.3.130 → 2.3.131

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.
Files changed (36) hide show
  1. package/dist/modules/BusinessAvailability/index.d.ts +30 -0
  2. package/dist/modules/BusinessAvailability/index.js +204 -0
  3. package/dist/modules/OpenData/types.d.ts +2 -0
  4. package/dist/modules/Order/index.d.ts +5 -2
  5. package/dist/modules/Order/index.js +315 -241
  6. package/dist/modules/Order/types.d.ts +8 -0
  7. package/dist/solution/BaseSales/index.d.ts +4 -15
  8. package/dist/solution/BaseSales/index.js +151 -89
  9. package/dist/solution/BaseSales/types.d.ts +11 -0
  10. package/dist/solution/BookingByStep/index.d.ts +1 -1
  11. package/dist/solution/BookingTicket/index.d.ts +1 -1
  12. package/dist/solution/BookingTicket/index.js +41 -13
  13. package/dist/solution/UnifiedBookingSales/businessAvailability.d.ts +27 -0
  14. package/dist/solution/UnifiedBookingSales/businessAvailability.js +292 -0
  15. package/dist/solution/UnifiedBookingSales/index.d.ts +11 -0
  16. package/dist/solution/UnifiedBookingSales/index.js +154 -75
  17. package/dist/solution/UnifiedBookingSales/types.d.ts +2 -0
  18. package/lib/model/strategy/adapter/promotion/index.js +46 -1
  19. package/lib/modules/BusinessAvailability/index.d.ts +30 -0
  20. package/lib/modules/BusinessAvailability/index.js +146 -0
  21. package/lib/modules/OpenData/types.d.ts +2 -0
  22. package/lib/modules/Order/index.d.ts +5 -2
  23. package/lib/modules/Order/index.js +62 -6
  24. package/lib/modules/Order/types.d.ts +8 -0
  25. package/lib/solution/BaseSales/index.d.ts +4 -15
  26. package/lib/solution/BaseSales/index.js +64 -24
  27. package/lib/solution/BaseSales/types.d.ts +11 -0
  28. package/lib/solution/BookingByStep/index.d.ts +1 -1
  29. package/lib/solution/BookingTicket/index.d.ts +1 -1
  30. package/lib/solution/BookingTicket/index.js +37 -4
  31. package/lib/solution/UnifiedBookingSales/businessAvailability.d.ts +27 -0
  32. package/lib/solution/UnifiedBookingSales/businessAvailability.js +138 -0
  33. package/lib/solution/UnifiedBookingSales/index.d.ts +11 -0
  34. package/lib/solution/UnifiedBookingSales/index.js +54 -0
  35. package/lib/solution/UnifiedBookingSales/types.d.ts +2 -0
  36. package/package.json +1 -1
@@ -216,6 +216,8 @@ export interface UnifiedBookingSalesDiscountResult {
216
216
  summaryAfter?: unknown;
217
217
  }
218
218
  export interface UnifiedBookingSalesApi {
219
+ /** Uses cached business settings and evaluates the current store-local clock. */
220
+ getBusinessAvailability: () => Promise<import('../../modules/BusinessAvailability').BusinessAvailability>;
219
221
  loadOpenData: (params: UnifiedBookingSalesLoadOpenDataParams) => Promise<OpenDataConfig>;
220
222
  /** Returns the latest OpenData payload cached by this solution instance. */
221
223
  getOpenData: () => Promise<OpenDataConfig | null>;
@@ -1 +1,46 @@
1
- "use strict";
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ Object.defineProperty(exports, "BUY_X_GET_Y_FREE_STRATEGY", {
7
+ enumerable: true,
8
+ get: function () {
9
+ return _examples.BUY_X_GET_Y_FREE_STRATEGY;
10
+ }
11
+ });
12
+ Object.defineProperty(exports, "ITEM_REWARD_STRATEGY", {
13
+ enumerable: true,
14
+ get: function () {
15
+ return _examples.ITEM_REWARD_STRATEGY;
16
+ }
17
+ });
18
+ Object.defineProperty(exports, "PromotionAdapter", {
19
+ enumerable: true,
20
+ get: function () {
21
+ return _adapter.PromotionAdapter;
22
+ }
23
+ });
24
+ Object.defineProperty(exports, "PromotionEvaluator", {
25
+ enumerable: true,
26
+ get: function () {
27
+ return _evaluator.PromotionEvaluator;
28
+ }
29
+ });
30
+ Object.defineProperty(exports, "X_ITEMS_FOR_Y_PRICE_STRATEGY", {
31
+ enumerable: true,
32
+ get: function () {
33
+ return _examples.X_ITEMS_FOR_Y_PRICE_STRATEGY;
34
+ }
35
+ });
36
+ Object.defineProperty(exports, "default", {
37
+ enumerable: true,
38
+ get: function () {
39
+ return _adapter.default;
40
+ }
41
+ });
42
+ var _evaluator = require("./evaluator");
43
+ var _adapter = _interopRequireWildcard(require("./adapter"));
44
+ var _examples = require("./examples");
45
+ function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
46
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
@@ -0,0 +1,30 @@
1
+ import type { MultiLangObject } from '../OpenData/types';
2
+ import type { ScheduleItem } from '../Schedule/types';
3
+ export type BusinessClosedBehavior = 'show_menu_disabled' | 'hide_all';
4
+ export interface BusinessAvailability {
5
+ status: 'open' | 'paused' | 'closed' | 'error';
6
+ behavior: BusinessClosedBehavior | null;
7
+ message: string | MultiLangObject | null;
8
+ /** Epoch milliseconds. Re-evaluate the cached configuration at this time. */
9
+ nextChangeAt: number;
10
+ requirePaymentOnSubmit: boolean;
11
+ error?: string;
12
+ }
13
+ export interface BusinessAvailabilityConfig {
14
+ paused: boolean;
15
+ pauseBehavior: BusinessClosedBehavior;
16
+ closedBehavior: BusinessClosedBehavior;
17
+ pauseMessage: BusinessAvailability['message'];
18
+ closedMessage: BusinessAvailability['message'];
19
+ scheduleIds: number[];
20
+ invalidScheduleIds: boolean;
21
+ requirePaymentOnSubmit: boolean;
22
+ }
23
+ export declare function normalizeBusinessAvailabilityConfig(data: Record<string, unknown>): BusinessAvailabilityConfig;
24
+ /** Business ordering is independent of reservation switches and Pickup slot availability. */
25
+ export declare function computeBusinessAvailability(input: {
26
+ config: BusinessAvailabilityConfig;
27
+ schedules: ScheduleItem[];
28
+ timezone: string;
29
+ now: Date;
30
+ }): BusinessAvailability;
@@ -0,0 +1,146 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.computeBusinessAvailability = computeBusinessAvailability;
7
+ exports.normalizeBusinessAvailabilityConfig = normalizeBusinessAvailabilityConfig;
8
+ var _dayjs = _interopRequireDefault(require("dayjs"));
9
+ var _isSameOrAfter = _interopRequireDefault(require("dayjs/plugin/isSameOrAfter"));
10
+ var _isSameOrBefore = _interopRequireDefault(require("dayjs/plugin/isSameOrBefore"));
11
+ var _getDateIsInSchedule = require("../Schedule/getDateIsInSchedule");
12
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
13
+ _dayjs.default.extend(_isSameOrAfter.default);
14
+ _dayjs.default.extend(_isSameOrBefore.default);
15
+ const DAY = 86_400_000;
16
+ const behavior = value => value === 'show_menu_disabled' ? value : 'hide_all';
17
+ const message = value => typeof value === 'string' || value !== null && typeof value === 'object' && !Array.isArray(value) ? value : null;
18
+ function normalizeBusinessAvailabilityConfig(data) {
19
+ const rawIds = data['availability.operating_hours'];
20
+ const ids = Array.isArray(rawIds) ? rawIds.map(id => typeof id === 'number' || typeof id === 'string' ? Number(id) : NaN) : [];
21
+ const validIds = ids.filter(id => Number.isInteger(id) && id > 0);
22
+ const paused = data['availability.paused'];
23
+ return {
24
+ paused: paused === true || paused === 1 || paused === 'true' || paused === '1',
25
+ pauseBehavior: behavior(data['availability.pause_behavior']),
26
+ closedBehavior: behavior(data['availability.closed_behavior']),
27
+ pauseMessage: message(data['availability.pause_message']),
28
+ closedMessage: message(data['availability.closed_message']),
29
+ scheduleIds: [...new Set(validIds)],
30
+ invalidScheduleIds: rawIds != null && (!Array.isArray(rawIds) || validIds.length !== ids.length),
31
+ // Only an explicitly disabled setting changes the existing payment flow.
32
+ requirePaymentOnSubmit: data['sale.require_payment_on_submit'] !== false
33
+ };
34
+ }
35
+ function createClock(timezone) {
36
+ if (!timezone) throw new Error('Store timezone is unavailable.');
37
+ const formatter = new Intl.DateTimeFormat('en-GB', {
38
+ timeZone: timezone,
39
+ year: 'numeric',
40
+ month: '2-digit',
41
+ day: '2-digit',
42
+ hour: '2-digit',
43
+ minute: '2-digit',
44
+ second: '2-digit',
45
+ hourCycle: 'h23'
46
+ });
47
+ const local = timestamp => {
48
+ const parts = {};
49
+ formatter.formatToParts(timestamp).forEach(part => {
50
+ parts[part.type] = part.value;
51
+ });
52
+ const date = `${parts.year}-${parts.month}-${parts.day}`;
53
+ return {
54
+ date,
55
+ scalar: Date.parse(`${date}T${parts.hour}:${parts.minute}:${parts.second}Z`)
56
+ };
57
+ };
58
+ const offsets = new Set();
59
+ const instants = scalar => {
60
+ offsets.clear();
61
+ for (let hours = -36; hours <= 36; hours += 6) {
62
+ const sample = scalar + hours * 3_600_000;
63
+ offsets.add(local(sample).scalar - sample);
64
+ }
65
+ return [...offsets].map(offset => scalar - offset).filter(instant => local(instant).scalar === scalar).sort((a, b) => a - b);
66
+ };
67
+ return {
68
+ local,
69
+ instants
70
+ };
71
+ }
72
+
73
+ /** Business ordering is independent of reservation switches and Pickup slot availability. */
74
+ function computeBusinessAvailability(input) {
75
+ const {
76
+ config,
77
+ schedules,
78
+ timezone,
79
+ now
80
+ } = input;
81
+ const nowAt = now.getTime();
82
+ const base = {
83
+ requirePaymentOnSubmit: config.requirePaymentOnSubmit,
84
+ nextChangeAt: nowAt + DAY
85
+ };
86
+ if (config.paused) {
87
+ return {
88
+ ...base,
89
+ status: 'paused',
90
+ behavior: config.pauseBehavior,
91
+ message: config.pauseMessage
92
+ };
93
+ }
94
+ if (config.invalidScheduleIds) throw new Error('Business operating-hours configuration is invalid.');
95
+ if (!config.scheduleIds.length) return {
96
+ ...base,
97
+ status: 'open',
98
+ behavior: null,
99
+ message: null
100
+ };
101
+ const selected = schedules.filter(schedule => config.scheduleIds.includes(Number(schedule.id)));
102
+ if (config.scheduleIds.some(id => !selected.some(schedule => Number(schedule.id) === id))) {
103
+ throw new Error('A configured business operating-hours schedule is unavailable.');
104
+ }
105
+ const clock = createClock(timezone);
106
+ const current = clock.local(nowAt);
107
+ const today = Date.parse(`${current.date}T00:00:00Z`);
108
+ const nextMidnight = clock.instants(today + DAY).find(instant => instant > nowAt);
109
+ let nextChangeAt = nextMidnight ?? nowAt + 60_000;
110
+ let open = false;
111
+ // Yesterday contributes the tail of overnight windows; today supplies the next boundary.
112
+ for (const dateAt of [today - DAY, today]) {
113
+ const date = new Date(dateAt).toISOString().slice(0, 10);
114
+ // Schedule's resolver merges by time-of-day, so resolve each schedule independently.
115
+ for (const schedule of selected) {
116
+ for (const window of (0, _getDateIsInSchedule.getScheduleStartEndTimePoints)(date, [schedule])) {
117
+ const toMinutes = value => {
118
+ if (!/^(?:[01]\d|2[0-3]):[0-5]\d$/.test(value) && value !== '24:00') {
119
+ throw new Error('Business operating-hours schedule contains an invalid time.');
120
+ }
121
+ const [hours, minutes] = value.split(':').map(Number);
122
+ return hours * 60 + minutes;
123
+ };
124
+ const start = dateAt + toMinutes(window.start_time) * 60_000;
125
+ let end = dateAt + toMinutes(window.end_time) * 60_000;
126
+ if (end <= start) end += DAY;
127
+ if (current.scalar >= start && current.scalar < end) open = true;
128
+ for (const boundary of [start, end]) {
129
+ for (const instant of clock.instants(boundary)) {
130
+ if (instant > nowAt) nextChangeAt = Math.min(nextChangeAt, instant);
131
+ }
132
+ }
133
+ }
134
+ }
135
+ }
136
+ // A timezone offset change can repeat/skip a wall-clock boundary. A local-only safety
137
+ // check also covers throttled timers; it does not fetch either configuration source.
138
+ nextChangeAt = Math.min(nextChangeAt, nowAt + 60_000);
139
+ return {
140
+ ...base,
141
+ nextChangeAt,
142
+ status: open ? 'open' : 'closed',
143
+ behavior: open ? null : config.closedBehavior,
144
+ message: open ? null : config.closedMessage
145
+ };
146
+ }
@@ -69,6 +69,8 @@ export interface OpenDataConfig {
69
69
  'reservation.time_slice'?: number | string;
70
70
  'sale.allow_item_notes'?: boolean;
71
71
  'sale.allow_order_notes'?: boolean;
72
+ /** False submits an order without starting or confirming payment. */
73
+ 'sale.require_payment_on_submit'?: boolean | null;
72
74
  'sale.enable_item_rules'?: boolean;
73
75
  'sale.enable_short_number'?: boolean;
74
76
  'sale.short_number_daily_reset'?: boolean;
@@ -4,7 +4,7 @@ import { OrderModuleAPI, CommitOrderParams, UpdateOrderBookingParams, UpdateOrde
4
4
  import { CartItem } from '../Cart/types';
5
5
  import { type SubmitPayloadEnhancer } from './utils';
6
6
  import { type PickupTimingBooking, type PickupTimingBookingInput } from './pickupTiming';
7
- import type { OrderAmountSnapshot, AddProductBookingInput, AddProductToOrderOptions, OrderIdentitySnapshot, OrderPaymentSource, OrderSnapshot, OrderSyncState, SyncPaymentsToOrderParams, SyncPaymentsToOrderResult, SubmitSalesOrderParams, OrderProduct, OrderProductIdentity, OrderSummary, OrderTempOrder, OrderPaymentData, OrderPaymentUpdateOptions, OrderPaymentUpdateResult, SendCustomerPayLinkParams, UpdateTempOrderCustomerInput, OrderCustomerPatch, OrderCustomerView, ReplaceTempOrderOptions, OrderPromotionEvaluator, OrderGiftSelectResolver, OrderUnfulfilledPromotion, OrderLastGiftActions, RemoveProductsFromOrderOptions, SalesNote, SalesNotesMutationSnapshot, SetSalesNoteInput, PickupReferenceMode, PointCardSnapshotMergeContext, PointCardSnapshotItem, ShopServiceData, ShopServiceType } from './types';
7
+ import type { OrderAmountSnapshot, AddProductBookingInput, AddProductToOrderOptions, OrderIdentitySnapshot, OrderPaymentSource, OrderSnapshot, OrderSyncState, SyncPaymentsToOrderParams, SyncPaymentsToOrderResult, SubmitSalesOrderParams, OrderProduct, OrderProductIdentity, OrderSummary, OrderTempOrder, OrderPaymentData, OrderPaymentUpdateOptions, OrderPaymentUpdateResult, SendCustomerPayLinkParams, UpdateTempOrderCustomerInput, OrderCustomerPatch, OrderCustomerView, OrderCartIntentCommitContext, ReplaceTempOrderOptions, OrderPromotionEvaluator, OrderGiftSelectResolver, OrderUnfulfilledPromotion, OrderLastGiftActions, RemoveProductsFromOrderOptions, SalesNote, SalesNotesMutationSnapshot, SetSalesNoteInput, PickupReferenceMode, PointCardSnapshotMergeContext, PointCardSnapshotItem, ShopServiceData, ShopServiceType } from './types';
8
8
  import type { ICustomer } from '../AccountList/types';
9
9
  import type { Discount } from '../Discount/types';
10
10
  import { UnavailableReason } from '../Rules/types';
@@ -67,6 +67,8 @@ export declare class OrderModule extends BaseModule implements Module, OrderModu
67
67
  * orderModule.updateOtherParams({ cacheId: 'cache-2', channel: 'pos' });
68
68
  */
69
69
  updateOtherParams(params: Record<string, any>): void;
70
+ /** Internal intent boundary shared with asynchronous scanner/detail flows. */
71
+ createCartIntentCommitGuard(action: OrderCartIntentCommitContext['action'], tempOrder?: OrderTempOrder | null): () => void;
70
72
  /** PC/H5 属于在线店铺;其它或缺失平台统一沿用 POS 行为。 */
71
73
  isOnlineStorePlatform(): boolean;
72
74
  /**
@@ -502,6 +504,7 @@ export declare class OrderModule extends BaseModule implements Module, OrderModu
502
504
  private hasSameEntitlementMergePriceConfig;
503
505
  private getBundleRuntimeIdentity;
504
506
  private preservePersistedBundlePriceFields;
507
+ private isRestrictedCartProductUpdate;
505
508
  private applyOrderProductUpdateToTempOrder;
506
509
  updateOrderProduct(params: UpdateOrderProductParams): Promise<OrderProduct[]>;
507
510
  updateOrderProducts(paramsList: UpdateOrderProductParams[]): Promise<OrderProduct[]>;
@@ -589,7 +592,7 @@ export declare class OrderModule extends BaseModule implements Module, OrderModu
589
592
  generateIdempotencyToken(): string;
590
593
  syncPaymentsToOrder<T = any>(params: SyncPaymentsToOrderParams): Promise<SyncPaymentsToOrderResult<T>>;
591
594
  createOrder(params: CommitOrderParams['query']): {
592
- type: "appointment_booking" | "virtual";
595
+ type: "virtual" | "appointment_booking";
593
596
  platform: string;
594
597
  sales_channel: string;
595
598
  order_sales_channel: string;
@@ -441,6 +441,29 @@ class OrderModule extends _BaseModule.BaseModule {
441
441
  this.otherParams = otherParams;
442
442
  }
443
443
 
444
+ /** Internal intent boundary shared with asynchronous scanner/detail flows. */
445
+ createCartIntentCommitGuard(action, tempOrder = this.store.tempOrder) {
446
+ const hook = this.orderHooks?.beforeCartIntentCommit;
447
+ if (!hook) return () => {};
448
+ const getScope = this.orderHooks?.getCartIntentScope;
449
+ const scope = getScope?.();
450
+ const otherParams = this.otherParams;
451
+ let committed = false;
452
+ return () => {
453
+ if (this.store.tempOrder !== tempOrder || this.otherParams !== otherParams || this.orderHooks?.beforeCartIntentCommit !== hook || this.orderHooks?.getCartIntentScope !== getScope || getScope?.() !== scope) {
454
+ throw new Error('[Order] Cart intent belongs to a previous order or business');
455
+ }
456
+ // Derived gifts, discounts and persistence belong to the accepted intent,
457
+ // but an asynchronous continuation must never target a different cart.
458
+ if (committed) return;
459
+ hook({
460
+ action,
461
+ tempOrder
462
+ });
463
+ committed = true;
464
+ };
465
+ }
466
+
444
467
  /** PC/H5 属于在线店铺;其它或缺失平台统一沿用 POS 行为。 */
445
468
  isOnlineStorePlatform() {
446
469
  const platform = String(this.otherParams?.platform || '').trim().toLowerCase();
@@ -669,6 +692,7 @@ class OrderModule extends _BaseModule.BaseModule {
669
692
  });
670
693
  }
671
694
  async scanCode(code, customerId) {
695
+ const beforeCommit = this.createCartIntentCommitGuard('scan_promotion');
672
696
  if (this.isActiveVirtualSettlementOrder(this.store.tempOrder)) {
673
697
  return {
674
698
  type: 'clientCalc',
@@ -716,6 +740,7 @@ class OrderModule extends _BaseModule.BaseModule {
716
740
  }));
717
741
  const currentSelected = this.getDiscountList().filter(n => n.isSelected);
718
742
  if (currentSelected.length && currentSelected.some(n => withScanList.some(m => m.id === n.id))) {
743
+ beforeCommit();
719
744
  await this.syncScannedDiscountsToOriginalDiscountList(this.getDiscountList());
720
745
  return {
721
746
  type: 'clientCalc',
@@ -749,6 +774,7 @@ class OrderModule extends _BaseModule.BaseModule {
749
774
  const normalizedNewDiscountList = newDiscountList ? markScannedDiscounts(newDiscountList, withScanList) : undefined;
750
775
  let resolvedDiscountList = normalizedNewDiscountList || this.getDiscountList();
751
776
  if (isAvailable && normalizedNewDiscountList) {
777
+ beforeCommit();
752
778
  await this.store.discount?.setDiscountList(normalizedNewDiscountList);
753
779
  // 实际写回商品时沿用扫码试算的优先级,避免旧商品行的选卡覆盖本次扫码。
754
780
  this.applyDiscount({
@@ -757,6 +783,7 @@ class OrderModule extends _BaseModule.BaseModule {
757
783
  await this.syncScannedDiscountsToOriginalDiscountList(this.getDiscountList());
758
784
  resolvedDiscountList = this.getDiscountList();
759
785
  } else if (shouldRetainForLater) {
786
+ beforeCommit();
760
787
  // 只合并本次识别的卡券;不把试算产生的其他选券状态写回订单。
761
788
  const retainedDiscounts = new Map(this.getDiscountList().map(discount => [String(discount.id), discount]));
762
789
  evaluatedScannedDiscounts.forEach(discount => {
@@ -3463,7 +3490,6 @@ class OrderModule extends _BaseModule.BaseModule {
3463
3490
  booking
3464
3491
  }) : null;
3465
3492
  const productToAdd = linked?.product || product;
3466
- this.assertAndLockProductSettlement(tempOrder, productToAdd);
3467
3493
  const disableMerge = options?.disableMerge === true;
3468
3494
  const incomingFingerprint = disableMerge ? '' : (0, _utils3.buildProductLineFingerprint)((0, _utils.getProductSkuOptions)(productToAdd), productToAdd.product_bundle);
3469
3495
  const normalizedIncoming = this.normalizeVirtualSettlementProductIfEnabled((0, _utils.mergeOrderProductDisplayFields)(productToAdd, (0, _utils3.normalizeOrderProduct)(productToAdd)));
@@ -3525,6 +3551,8 @@ class OrderModule extends _BaseModule.BaseModule {
3525
3551
  const matchedProduct = matchedIndex === -1 ? null : tempOrder.products[matchedIndex];
3526
3552
  const existedFingerprint = matchedProduct ? (0, _utils3.buildProductLineFingerprint)((0, _utils.getProductSkuOptions)(matchedProduct), matchedProduct.product_bundle) : '';
3527
3553
  const commitProductLine = shouldMerge => {
3554
+ options?.beforeCommit?.();
3555
+ this.assertAndLockProductSettlement(tempOrder, productToAdd);
3528
3556
  let committedProduct;
3529
3557
  if (matchedIndex === -1 || !matchedProduct || !shouldMerge) {
3530
3558
  this.captureProductRuntime(tempOrder, productToAdd, normalizedIncoming);
@@ -3677,6 +3705,7 @@ class OrderModule extends _BaseModule.BaseModule {
3677
3705
  */
3678
3706
  async addProductToOrder(product, booking, options) {
3679
3707
  const tempOrder = this.ensureTempOrder();
3708
+ const beforeCommit = this.createCartIntentCommitGuard('add_product', tempOrder);
3680
3709
  const salesNoteDrafts = (options?.salesNotes || []).map(draft => ({
3681
3710
  note_type: String(draft.note_type || '').trim(),
3682
3711
  text: {
@@ -3747,7 +3776,8 @@ class OrderModule extends _BaseModule.BaseModule {
3747
3776
  }
3748
3777
  const committedProduct = await this.appendProductLineToTempOrder(tempOrder, splitLine.product, splitLine.booking, {
3749
3778
  insertAtIndex,
3750
- disableMerge: options?.disableMerge
3779
+ disableMerge: options?.disableMerge,
3780
+ beforeCommit
3751
3781
  });
3752
3782
  attachSalesNoteDrafts(committedProduct);
3753
3783
  if (insertAtIndex !== undefined) insertAtIndex += 1;
@@ -3755,14 +3785,16 @@ class OrderModule extends _BaseModule.BaseModule {
3755
3785
  } else {
3756
3786
  const committedProduct = await this.appendProductLineToTempOrder(tempOrder, product, (0, _lodashEs.cloneDeep)(booking), {
3757
3787
  insertAtIndex,
3758
- disableMerge: options?.disableMerge
3788
+ disableMerge: options?.disableMerge,
3789
+ beforeCommit
3759
3790
  });
3760
3791
  attachSalesNoteDrafts(committedProduct);
3761
3792
  }
3762
3793
  } else {
3763
3794
  const committedProduct = await this.appendProductLineToTempOrder(tempOrder, product, undefined, {
3764
3795
  insertAtIndex,
3765
- disableMerge: options?.disableMerge
3796
+ disableMerge: options?.disableMerge,
3797
+ beforeCommit
3766
3798
  });
3767
3799
  attachSalesNoteDrafts(committedProduct);
3768
3800
  }
@@ -3790,6 +3822,7 @@ class OrderModule extends _BaseModule.BaseModule {
3790
3822
  async addProductsToOrder(items, options) {
3791
3823
  const tempOrder = this.ensureTempOrder();
3792
3824
  if (!Array.isArray(items) || items.length === 0) return tempOrder.products;
3825
+ const beforeCommit = this.createCartIntentCommitGuard('add_product', tempOrder);
3793
3826
  for (const item of items || []) {
3794
3827
  const {
3795
3828
  product,
@@ -3802,13 +3835,17 @@ class OrderModule extends _BaseModule.BaseModule {
3802
3835
  if (splitCount > 1) {
3803
3836
  for (let i = 0; i < splitCount; i += 1) {
3804
3837
  const splitLine = this.createSplitBookingLine(productRecord, booking, i, splitCount);
3805
- const appendResult = this.appendProductLineToTempOrder(tempOrder, splitLine.product, splitLine.booking);
3838
+ const appendResult = this.appendProductLineToTempOrder(tempOrder, splitLine.product, splitLine.booking, {
3839
+ beforeCommit
3840
+ });
3806
3841
  if (appendResult) await appendResult;
3807
3842
  }
3808
3843
  continue;
3809
3844
  }
3810
3845
  }
3811
- const appendResult = this.appendProductLineToTempOrder(tempOrder, product, booking);
3846
+ const appendResult = this.appendProductLineToTempOrder(tempOrder, product, booking, {
3847
+ beforeCommit
3848
+ });
3812
3849
  if (appendResult) await appendResult;
3813
3850
  }
3814
3851
  await this.finalizeProductOrderMutation(tempOrder, options);
@@ -3893,6 +3930,16 @@ class OrderModule extends _BaseModule.BaseModule {
3893
3930
  };
3894
3931
  });
3895
3932
  }
3933
+ isRestrictedCartProductUpdate(tempOrder, params) {
3934
+ if (!this.orderHooks?.beforeCartIntentCommit) return false;
3935
+ if (params.booking || Object.keys(params.updates || {}).some(key => key !== 'num')) {
3936
+ return true;
3937
+ }
3938
+ if (params.updates?.num === undefined) return false;
3939
+ const uid = params.unique_identification_number;
3940
+ const product = uid !== undefined ? tempOrder.products.find(item => String(item.metadata?.unique_identification_number || item.unique_identification_number || '') === String(uid)) : tempOrder.products[(0, _utils3.getProductIdentityIndex)(tempOrder.products, params)];
3941
+ return !product || (0, _utils3.getSafeProductNum)(params.updates.num) > product.num;
3942
+ }
3896
3943
  applyOrderProductUpdateToTempOrder(tempOrder, params, reapplyWeighedDiscountProductUids) {
3897
3944
  const {
3898
3945
  product_id,
@@ -4144,6 +4191,9 @@ class OrderModule extends _BaseModule.BaseModule {
4144
4191
  }
4145
4192
  async updateOrderProduct(params) {
4146
4193
  const tempOrder = this.ensureTempOrder();
4194
+ if (this.isRestrictedCartProductUpdate(tempOrder, params)) {
4195
+ this.createCartIntentCommitGuard('update_product', tempOrder)();
4196
+ }
4147
4197
  const reapplyWeighedDiscountProductUids = [];
4148
4198
  const updatedProductUid = this.applyOrderProductUpdateToTempOrder(tempOrder, params, reapplyWeighedDiscountProductUids);
4149
4199
  const promotionPayload = await this.evaluatePromotion();
@@ -4167,6 +4217,9 @@ class OrderModule extends _BaseModule.BaseModule {
4167
4217
  if (!paramsList.length) {
4168
4218
  return tempOrder.products;
4169
4219
  }
4220
+ if (paramsList.some(params => this.isRestrictedCartProductUpdate(tempOrder, params))) {
4221
+ this.createCartIntentCommitGuard('update_product', tempOrder)();
4222
+ }
4170
4223
  const reapplyWeighedDiscountProductUids = [];
4171
4224
  const reapplyBookingDiscountProductUids = paramsList.reduce((acc, params) => {
4172
4225
  const updatedProductUid = this.applyOrderProductUpdateToTempOrder(tempOrder, params, reapplyWeighedDiscountProductUids);
@@ -4251,6 +4304,9 @@ class OrderModule extends _BaseModule.BaseModule {
4251
4304
  throw new _virtualSettlement.VirtualCurrencyBalanceError(balance.toFixed(2), requiredAmount.toFixed(2));
4252
4305
  }
4253
4306
  }
4307
+ if (normalizedProduct.num > targetProduct.num) {
4308
+ this.createCartIntentCommitGuard('increase_quantity', tempOrder)();
4309
+ }
4254
4310
  tempOrder.products[productIndex] = normalizedProduct;
4255
4311
  this.prepareVirtualSettlementTempOrder(tempOrder);
4256
4312
  const isVirtualSettlement = this.isActiveVirtualSettlementOrder(tempOrder);
@@ -517,7 +517,15 @@ export type OrderProductMergeDecisionResult = boolean | {
517
517
  reason?: string;
518
518
  [key: string]: any;
519
519
  };
520
+ export interface OrderCartIntentCommitContext {
521
+ action: 'add_product' | 'update_product' | 'increase_quantity' | 'scan_promotion';
522
+ tempOrder: OrderTempOrder | null;
523
+ }
520
524
  export interface OrderHooksConfig {
525
+ /** Optional customer-order guard; called synchronously before the first cart write. */
526
+ beforeCartIntentCommit?: (context: OrderCartIntentCommitContext) => void;
527
+ /** Captures tenant/business runtime identity for asynchronous cart intents. */
528
+ getCartIntentScope?: () => unknown;
521
529
  onBeforeMergeProductToOrder?: (context: OrderProductMergeDecisionContext) => OrderProductMergeDecisionResult | Promise<OrderProductMergeDecisionResult>;
522
530
  }
523
531
  /**
@@ -1,6 +1,6 @@
1
1
  import { Module, ModuleOptions, PisellCore } from '../../types';
2
2
  import { BaseModule } from '../../modules/BaseModule';
3
- import { BaseSalesOrderProduct, BaseSalesOrderProductIdentity, BaseSalesPaymentStatus, BaseSalesUpdateOrderProductQuantityParams, BaseSalesCalculateProductBookingPriceParams, BaseSalesPriceRecalculationContextChange, BaseSalesProductBookingPriceResult, BaseSalesQuotationCustomerScopeInfo, BaseSalesScanCodeResult, BaseSalesCashPaymentOptions, BaseSalesCashPaymentConfig, BaseSalesPayCashParams, BaseSalesPayCashResult, BaseSalesCommitPaymentMethodParams, BaseSalesCommitPaymentMethodResult, BaseSalesConfirmWalletPaymentResult } from './types';
3
+ import { BaseSalesOrderProduct, BaseSalesOrderProductIdentity, BaseSalesPaymentStatus, BaseSalesSubmitSalesOrderParams, BaseSalesUpdateOrderProductQuantityParams, BaseSalesCalculateProductBookingPriceParams, BaseSalesPriceRecalculationContextChange, BaseSalesProductBookingPriceResult, BaseSalesQuotationCustomerScopeInfo, BaseSalesScanCodeResult, BaseSalesCashPaymentOptions, BaseSalesCashPaymentConfig, BaseSalesPayCashParams, BaseSalesPayCashResult, BaseSalesCommitPaymentMethodParams, BaseSalesCommitPaymentMethodResult, BaseSalesConfirmWalletPaymentResult } from './types';
4
4
  import { OrderModule } from '../../modules/Order';
5
5
  import { type PickupTimingBookingInput } from '../../modules/Order/pickupTiming';
6
6
  import type { PickupTimingAvailability, PickupTimingSelection, PickupTimingValidationResult } from '../../modules/FulfillmentTiming';
@@ -339,13 +339,8 @@ export declare class BaseSalesImpl extends BaseModule implements Module {
339
339
  productList?: Record<string, any>[];
340
340
  discountList?: Discount[];
341
341
  }): Promise<void>;
342
- submitScanOrder<T = any>(params?: {
343
- payments?: OrderPaymentSource[];
344
- paymentStatus?: BaseSalesPaymentStatus;
345
- smallTicketDataFlag?: number;
346
- confirmPendingVoucherPayments?: boolean;
347
- enhancePayload?: SubmitPayloadEnhancer;
348
- }): Promise<T>;
342
+ submitScanOrder<T = any>(params?: BaseSalesSubmitSalesOrderParams): Promise<T>;
343
+ private buildVirtualSettlementOrderData;
349
344
  private buildVirtualSettlementSubmitData;
350
345
  /**
351
346
  * 提交当前 Sales 订单。
@@ -353,13 +348,7 @@ export declare class BaseSalesImpl extends BaseModule implements Module {
353
348
  * PaymentModal 场景通过 smallTicketDataFlag=1 请求 B 端小票数据;
354
349
  * payments 会交给 OrderModule 统一映射为 Sales 协议支付项。
355
350
  */
356
- submitSalesOrder<T = any>(params?: {
357
- payments?: OrderPaymentSource[];
358
- paymentStatus?: BaseSalesPaymentStatus;
359
- smallTicketDataFlag?: number;
360
- confirmPendingVoucherPayments?: boolean;
361
- enhancePayload?: SubmitPayloadEnhancer;
362
- }): Promise<T>;
351
+ submitSalesOrder<T = any>(params?: BaseSalesSubmitSalesOrderParams): Promise<T>;
363
352
  saveSalesOrderDraft<T = any>(params?: {
364
353
  platform?: string;
365
354
  businessCode?: string;