@pisell/pisellos 0.0.566 → 0.0.568

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 (230) hide show
  1. package/dist/core/index.js +6 -9
  2. package/dist/model/strategy/adapter/walletPass/evaluator.js +0 -2
  3. package/dist/model/strategy/adapter/walletPass/example.js +3 -26
  4. package/dist/model/strategy/adapter/walletPass/utils.js +0 -3
  5. package/dist/model/strategy/strategy-example.js +5 -19
  6. package/dist/modules/Cart/index.js +0 -3
  7. package/dist/modules/Cart/utils/cartProduct.js +0 -1
  8. package/dist/modules/Date/index.js +1 -5
  9. package/dist/modules/Discount/index.js +1 -4
  10. package/dist/modules/OpenData/index.js +0 -2
  11. package/dist/modules/Order/index.d.ts +1 -1
  12. package/dist/modules/Order/index.js +14 -41
  13. package/dist/modules/Payment/index.js +142 -270
  14. package/dist/modules/Payment/walletpass.js +4 -5
  15. package/dist/modules/Rules/index.js +0 -7
  16. package/dist/modules/SalesSummary/utils.js +4 -2
  17. package/dist/modules/Schedule/utils.js +0 -1
  18. package/dist/modules/Step/index.js +0 -1
  19. package/dist/modules/Summary/utils.js +2 -2
  20. package/dist/plugins/request.js +1 -4
  21. package/dist/plugins/window.js +2 -6
  22. package/dist/server/index.js +88 -121
  23. package/dist/server/modules/menu/index.js +32 -41
  24. package/dist/server/modules/products/index.js +29 -49
  25. package/dist/server/modules/quotation/index.js +29 -38
  26. package/dist/server/modules/resource/index.js +3 -4
  27. package/dist/server/modules/schedule/index.js +32 -40
  28. package/dist/server/utils/product.js +0 -1
  29. package/dist/solution/BookingByStep/index.d.ts +1 -1
  30. package/dist/solution/BookingByStep/index.js +7 -59
  31. package/dist/solution/BookingByStep/utils/capacity.js +1 -11
  32. package/dist/solution/BookingByStep/utils/resources.js +1 -3
  33. package/dist/solution/BookingByStep/utils/timeslots.js +2 -43
  34. package/dist/solution/BookingTicket/index.d.ts +1 -1
  35. package/dist/solution/BookingTicket/index.js +5 -7
  36. package/dist/solution/BookingTicket/utils/scan/handleScan.js +25 -31
  37. package/dist/solution/BookingTicket/utils/scan/index.js +6 -10
  38. package/dist/solution/BuyTickets/index.js +9 -12
  39. package/dist/solution/Checkout/index.js +177 -246
  40. package/dist/solution/Checkout/utils/index.js +4 -16
  41. package/dist/solution/RegisterAndLogin/index.js +30 -76
  42. package/dist/solution/ScanOrder/index.js +50 -60
  43. package/dist/solution/ShopDiscount/index.js +2 -7
  44. package/dist/solution/VenueBooking/index.d.ts +5 -0
  45. package/dist/solution/VenueBooking/index.js +364 -327
  46. package/dist/utils/task.js +15 -18
  47. package/dist/utils/watch.js +0 -1
  48. package/lib/apis/picoding.js +2 -0
  49. package/lib/core/index.js +130 -131
  50. package/lib/effects/index.js +46 -57
  51. package/lib/index.js +92 -53
  52. package/lib/model/index.js +14 -21
  53. package/lib/model/strategy/adapter/dataVariant/adapter.js +38 -50
  54. package/lib/model/strategy/adapter/dataVariant/evaluator.js +162 -236
  55. package/lib/model/strategy/adapter/dataVariant/examples.js +229 -237
  56. package/lib/model/strategy/adapter/dataVariant/index.js +39 -34
  57. package/lib/model/strategy/adapter/dataVariant/type.js +57 -28
  58. package/lib/model/strategy/adapter/index.js +100 -64
  59. package/lib/model/strategy/adapter/itemRule/adapter.js +156 -144
  60. package/lib/model/strategy/adapter/itemRule/evaluator.js +36 -48
  61. package/lib/model/strategy/adapter/itemRule/examples.js +295 -225
  62. package/lib/model/strategy/adapter/itemRule/index.js +83 -57
  63. package/lib/model/strategy/adapter/itemRule/type.js +97 -36
  64. package/lib/model/strategy/adapter/promotion/adapter.js +84 -63
  65. package/lib/model/strategy/adapter/promotion/evaluator.js +381 -231
  66. package/lib/model/strategy/adapter/promotion/examples.js +139 -159
  67. package/lib/model/strategy/adapter/promotion/index.js +1 -0
  68. package/lib/model/strategy/adapter/promotion/type.js +199 -35
  69. package/lib/model/strategy/adapter/type.js +4 -16
  70. package/lib/model/strategy/adapter/walletPass/evaluator.js +180 -152
  71. package/lib/model/strategy/adapter/walletPass/example.js +217 -190
  72. package/lib/model/strategy/adapter/walletPass/index.js +75 -51
  73. package/lib/model/strategy/adapter/walletPass/locales.js +36 -58
  74. package/lib/model/strategy/adapter/walletPass/type.js +4 -16
  75. package/lib/model/strategy/adapter/walletPass/utils.js +652 -402
  76. package/lib/model/strategy/engine.js +270 -168
  77. package/lib/model/strategy/index.js +49 -34
  78. package/lib/model/strategy/strategy-example.js +243 -239
  79. package/lib/model/strategy/type.js +100 -40
  80. package/lib/modules/Account/index.js +39 -53
  81. package/lib/modules/Account/types.js +20 -33
  82. package/lib/modules/AccountList/index.js +116 -154
  83. package/lib/modules/AccountList/types.js +30 -31
  84. package/lib/modules/AccountList/utils.js +18 -30
  85. package/lib/modules/BaseModule.js +22 -45
  86. package/lib/modules/Cart/index.js +170 -124
  87. package/lib/modules/Cart/types.js +46 -51
  88. package/lib/modules/Cart/utils/cartAccount.js +40 -39
  89. package/lib/modules/Cart/utils/cartDate.js +56 -61
  90. package/lib/modules/Cart/utils/cartDiscount.js +28 -33
  91. package/lib/modules/Cart/utils/cartNote.js +27 -32
  92. package/lib/modules/Cart/utils/cartProduct.js +306 -241
  93. package/lib/modules/Cart/utils/cartRelationForms.js +29 -35
  94. package/lib/modules/Cart/utils/cartResource.js +72 -78
  95. package/lib/modules/Cart/utils/changePrice.js +26 -62
  96. package/lib/modules/Cart/utils/index.js +106 -48
  97. package/lib/modules/Customer/constants.js +13 -34
  98. package/lib/modules/Customer/index.js +216 -153
  99. package/lib/modules/Customer/types.js +38 -35
  100. package/lib/modules/Date/index.js +116 -115
  101. package/lib/modules/Date/types.js +16 -28
  102. package/lib/modules/Date/utils.js +174 -123
  103. package/lib/modules/Discount/index.js +117 -113
  104. package/lib/modules/Discount/types.js +9 -31
  105. package/lib/modules/Guests/index.js +30 -56
  106. package/lib/modules/Guests/types.js +23 -33
  107. package/lib/modules/Holder/index.js +209 -189
  108. package/lib/modules/Holder/types.js +4 -16
  109. package/lib/modules/Holder/utils.js +20 -49
  110. package/lib/modules/OpenData/index.js +63 -74
  111. package/lib/modules/OpenData/types.js +4 -16
  112. package/lib/modules/OpenData/utils.js +44 -78
  113. package/lib/modules/Order/index.d.ts +1 -1
  114. package/lib/modules/Order/index.js +332 -320
  115. package/lib/modules/Order/types.js +24 -33
  116. package/lib/modules/Order/utils.js +350 -284
  117. package/lib/modules/Payment/cash.js +20 -33
  118. package/lib/modules/Payment/cashRecommendationAlgorithm.js +145 -76
  119. package/lib/modules/Payment/eftpos.js +16 -30
  120. package/lib/modules/Payment/index.js +566 -432
  121. package/lib/modules/Payment/mx51.js +1 -0
  122. package/lib/modules/Payment/types.js +216 -107
  123. package/lib/modules/Payment/utils.js +50 -47
  124. package/lib/modules/Payment/walletpass.js +221 -203
  125. package/lib/modules/Product/index.js +51 -46
  126. package/lib/modules/Product/types.js +4 -16
  127. package/lib/modules/Product/utils.js +32 -33
  128. package/lib/modules/ProductList/index.js +111 -110
  129. package/lib/modules/ProductList/types.js +9 -31
  130. package/lib/modules/Quotation/index.js +60 -82
  131. package/lib/modules/Quotation/types.js +4 -16
  132. package/lib/modules/Resource/index.js +27 -59
  133. package/lib/modules/Resource/types.js +22 -32
  134. package/lib/modules/Resource/utils.js +30 -38
  135. package/lib/modules/Rules/index.js +1172 -872
  136. package/lib/modules/Rules/types.js +17 -40
  137. package/lib/modules/SalesSummary/index.js +59 -68
  138. package/lib/modules/SalesSummary/types.js +4 -16
  139. package/lib/modules/SalesSummary/utils.js +178 -193
  140. package/lib/modules/ScanOrderLogger/index.js +59 -79
  141. package/lib/modules/ScanOrderLogger/providers/feishu.js +54 -78
  142. package/lib/modules/ScanOrderLogger/providers/grafana.js +13 -36
  143. package/lib/modules/ScanOrderLogger/types.js +4 -16
  144. package/lib/modules/Schedule/getDateIsInSchedule.js +334 -167
  145. package/lib/modules/Schedule/index.js +97 -107
  146. package/lib/modules/Schedule/type.js +4 -16
  147. package/lib/modules/Schedule/types.js +4 -16
  148. package/lib/modules/Schedule/utils.js +433 -291
  149. package/lib/modules/Step/index.js +40 -52
  150. package/lib/modules/Step/tyeps.js +4 -16
  151. package/lib/modules/Summary/index.js +66 -70
  152. package/lib/modules/Summary/types.js +4 -16
  153. package/lib/modules/Summary/utils.js +782 -429
  154. package/lib/modules/index.js +212 -57
  155. package/lib/plugins/app.js +4 -16
  156. package/lib/plugins/index.js +36 -25
  157. package/lib/plugins/request.js +137 -126
  158. package/lib/plugins/shopStore.js +4 -16
  159. package/lib/plugins/user.js +4 -16
  160. package/lib/plugins/window.js +171 -179
  161. package/lib/server/index.js +882 -623
  162. package/lib/server/modules/index.js +85 -59
  163. package/lib/server/modules/menu/index.js +146 -122
  164. package/lib/server/modules/menu/types.js +18 -31
  165. package/lib/server/modules/order/index.js +195 -231
  166. package/lib/server/modules/order/types.js +107 -32
  167. package/lib/server/modules/order/utils/filterBookings.js +174 -140
  168. package/lib/server/modules/order/utils/filterOrders.js +89 -60
  169. package/lib/server/modules/products/index.js +430 -335
  170. package/lib/server/modules/products/types.js +41 -34
  171. package/lib/server/modules/quotation/index.js +76 -77
  172. package/lib/server/modules/quotation/types.js +21 -31
  173. package/lib/server/modules/resource/index.js +216 -187
  174. package/lib/server/modules/resource/types.js +42 -33
  175. package/lib/server/modules/schedule/index.js +134 -119
  176. package/lib/server/modules/schedule/types.js +14 -21
  177. package/lib/server/modules/schedule/utils.js +334 -163
  178. package/lib/server/types.js +4 -16
  179. package/lib/server/utils/index.js +25 -23
  180. package/lib/server/utils/product.js +196 -139
  181. package/lib/server/utils/schedule.js +34 -41
  182. package/lib/server/utils/time.js +40 -49
  183. package/lib/solution/BookingByStep/index.d.ts +1 -1
  184. package/lib/solution/BookingByStep/index.js +1530 -1343
  185. package/lib/solution/BookingByStep/types.js +40 -99
  186. package/lib/solution/BookingByStep/utils/capacity.js +192 -160
  187. package/lib/solution/BookingByStep/utils/products.js +42 -52
  188. package/lib/solution/BookingByStep/utils/resources.js +527 -330
  189. package/lib/solution/BookingByStep/utils/stock.js +65 -44
  190. package/lib/solution/BookingByStep/utils/timeslots.js +129 -131
  191. package/lib/solution/BookingTicket/index.d.ts +1 -1
  192. package/lib/solution/BookingTicket/index.js +147 -122
  193. package/lib/solution/BookingTicket/types.js +38 -64
  194. package/lib/solution/BookingTicket/utils/scan/cloudSearch.js +64 -80
  195. package/lib/solution/BookingTicket/utils/scan/handleScan.js +82 -80
  196. package/lib/solution/BookingTicket/utils/scan/index.js +90 -94
  197. package/lib/solution/BookingTicket/utils/scan/scanCache.js +90 -43
  198. package/lib/solution/BuyTickets/index.js +67 -70
  199. package/lib/solution/BuyTickets/types.js +22 -38
  200. package/lib/solution/Checkout/index.js +1451 -1158
  201. package/lib/solution/Checkout/types.js +91 -61
  202. package/lib/solution/Checkout/utils/index.js +227 -158
  203. package/lib/solution/PlaceOrder/index.js +55 -0
  204. package/lib/solution/RegisterAndLogin/config.js +493 -460
  205. package/lib/solution/RegisterAndLogin/index.js +633 -630
  206. package/lib/solution/RegisterAndLogin/types.js +189 -76
  207. package/lib/solution/RegisterAndLogin/utils.js +183 -125
  208. package/lib/solution/Sales/index.js +218 -200
  209. package/lib/solution/Sales/types.js +27 -33
  210. package/lib/solution/ScanOrder/index.js +803 -840
  211. package/lib/solution/ScanOrder/types.js +34 -34
  212. package/lib/solution/ScanOrder/utils.js +372 -331
  213. package/lib/solution/ShopDiscount/index.js +230 -236
  214. package/lib/solution/ShopDiscount/types.js +15 -37
  215. package/lib/solution/ShopDiscount/utils.js +309 -172
  216. package/lib/solution/VenueBooking/index.d.ts +5 -0
  217. package/lib/solution/VenueBooking/index.js +886 -929
  218. package/lib/solution/VenueBooking/types.js +20 -40
  219. package/lib/solution/VenueBooking/utils/dateSummary.js +22 -54
  220. package/lib/solution/VenueBooking/utils/resource.js +31 -54
  221. package/lib/solution/VenueBooking/utils/slotMerge.js +88 -106
  222. package/lib/solution/VenueBooking/utils/smartPricing.js +112 -100
  223. package/lib/solution/VenueBooking/utils/timeSlot.js +133 -132
  224. package/lib/solution/VenueBooking/utils.js +130 -67
  225. package/lib/solution/index.js +102 -37
  226. package/lib/store/createStore.js +32 -29
  227. package/lib/types/index.js +4 -16
  228. package/lib/utils/task.js +36 -36
  229. package/lib/utils/watch.js +81 -47
  230. package/package.json +2 -1
@@ -1,67 +1,43 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
- // If the importer is in node compatibility mode or this is not an ESM
21
- // file that has been converted to a CommonJS file using a Babel-
22
- // compatible transform (i.e. "__esModule" has not been set), then set
23
- // "default" to the CommonJS "module.exports" for node compatibility.
24
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
- mod
26
- ));
27
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1
+ "use strict";
28
2
 
29
- // src/modules/Order/index.ts
30
- var Order_exports = {};
31
- __export(Order_exports, {
32
- OrderModule: () => OrderModule
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
33
5
  });
34
- module.exports = __toCommonJS(Order_exports);
35
- var import_BaseModule = require("../BaseModule");
36
- var import_utils = require("./utils");
37
- var import_utils2 = require("../Product/utils");
38
- var import_dayjs = __toESM(require("dayjs"));
39
- var import_utils3 = require("../../solution/ScanOrder/utils");
40
- var import_Discount = require("../Discount");
41
- var import_Rules = require("../Rules");
42
- var import_types = require("../Rules/types");
43
- var import_decimal = __toESM(require("decimal.js"));
44
- var OrderModule = class extends import_BaseModule.BaseModule {
45
- constructor(name, version) {
46
- super(name || "order", version);
47
- this.defaultName = "order";
48
- this.defaultVersion = "1.0.0";
49
- }
6
+ exports.OrderModule = void 0;
7
+ var _BaseModule = require("../BaseModule");
8
+ var _utils = require("./utils");
9
+ var _utils2 = require("../Product/utils");
10
+ var _dayjs = _interopRequireDefault(require("dayjs"));
11
+ var _utils3 = require("../../solution/ScanOrder/utils");
12
+ var _Discount = require("../Discount");
13
+ var _Rules = require("../Rules");
14
+ var _types = require("../Rules/types");
15
+ var _decimal = _interopRequireDefault(require("decimal.js"));
16
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17
+ class OrderModule extends _BaseModule.BaseModule {
18
+ defaultName = 'order';
19
+ defaultVersion = '1.0.0';
20
+ store;
21
+ request;
22
+ logger; // LoggerManager 实例
23
+ window;
24
+ cacheId;
25
+ salesSummaryModuleName;
26
+ rulesHooksOverride;
27
+
50
28
  /**
51
29
  * Populate `savedAmount` on each discount based on product-level discount details.
52
30
  * Only selected discounts get a non-zero value.
53
31
  */
54
32
  static populateSavedAmounts(productList, discountList) {
55
- var _a, _b;
56
- const savedMap = /* @__PURE__ */ new Map();
33
+ const savedMap = new Map();
57
34
  for (const product of productList) {
58
35
  const qty = product.num || 1;
59
36
  for (const pd of product.discount_list || []) {
60
- const discountKey = ((_a = pd.discount) == null ? void 0 : _a.resource_id) || pd.id;
61
- if (discountKey == null)
62
- continue;
63
- const amount = new import_decimal.default(pd.amount || 0).times(qty).plus(((_b = pd.metadata) == null ? void 0 : _b.product_discount_difference) || 0);
64
- savedMap.set(discountKey, (savedMap.get(discountKey) || new import_decimal.default(0)).plus(amount));
37
+ const discountKey = pd.discount?.resource_id || pd.id;
38
+ if (discountKey == null) continue;
39
+ const amount = new _decimal.default(pd.amount || 0).times(qty).plus(pd.metadata?.product_discount_difference || 0);
40
+ savedMap.set(discountKey, (savedMap.get(discountKey) || new _decimal.default(0)).plus(amount));
65
41
  }
66
42
  }
67
43
  for (const d of discountList) {
@@ -69,8 +45,10 @@ var OrderModule = class extends import_BaseModule.BaseModule {
69
45
  d.savedAmount = d.isSelected && key != null && savedMap.has(key) ? savedMap.get(key).toNumber() : 0;
70
46
  }
71
47
  }
48
+ constructor(name, version) {
49
+ super(name || "order", version);
50
+ }
72
51
  async initialize(core, options) {
73
- var _a;
74
52
  this.core = core;
75
53
  this.store = options.store;
76
54
  if (!this.store.tempOrder) {
@@ -79,60 +57,64 @@ var OrderModule = class extends import_BaseModule.BaseModule {
79
57
  if (!Array.isArray(this.store.availableWalletIds)) {
80
58
  this.store.availableWalletIds = [];
81
59
  }
82
- this.request = this.core.getPlugin("request");
83
- this.window = this.core.getPlugin("window");
60
+ this.request = this.core.getPlugin('request');
61
+ this.window = this.core.getPlugin('window');
84
62
  const otherParams = options.otherParams || {};
85
63
  this.cacheId = otherParams.cacheId;
86
64
  this.salesSummaryModuleName = otherParams.salesSummaryModuleName;
87
- this.rulesHooksOverride = (_a = otherParams.rules) == null ? void 0 : _a.hooks;
65
+ this.rulesHooksOverride = otherParams.rules?.hooks;
88
66
  this.registerDiscountModules(options);
89
67
  this.restoreTempOrderFromStorage();
90
- const appPlugin = this.core.getPlugin("app");
68
+ const appPlugin = this.core.getPlugin('app');
91
69
  if (!appPlugin) {
92
- console.warn("Order 模块需要 app 插件支持");
70
+ console.warn('Order 模块需要 app 插件支持');
93
71
  }
94
- const app = appPlugin == null ? void 0 : appPlugin.getApp();
95
- if (app)
96
- this.logger = app.logger;
97
- this.logInfo("OrderModule initialized successfully");
72
+ const app = appPlugin?.getApp();
73
+ if (app) this.logger = app.logger;
74
+ this.logInfo('OrderModule initialized successfully');
98
75
  }
76
+
99
77
  /**
100
78
  * 记录信息日志
101
79
  */
102
80
  logInfo(title, metadata) {
103
81
  if (this.logger) {
104
82
  this.logger.addLog({
105
- type: "info",
83
+ type: 'info',
106
84
  title: `[OrderModule] ${title}`,
107
85
  metadata: metadata || {}
108
86
  });
109
87
  }
110
88
  }
89
+
111
90
  /**
112
91
  * 记录警告日志
113
92
  */
114
93
  logWarning(title, metadata) {
115
94
  if (this.logger) {
116
95
  this.logger.addLog({
117
- type: "warning",
96
+ type: 'warning',
118
97
  title: `[OrderModule] ${title}`,
119
98
  metadata: metadata || {}
120
99
  });
121
100
  }
122
101
  }
102
+
123
103
  /**
124
104
  * 记录错误日志
125
105
  */
126
106
  logError(title, metadata) {
127
107
  if (this.logger) {
128
108
  this.logger.addLog({
129
- type: "error",
109
+ type: 'error',
130
110
  title: `[OrderModule] ${title}`,
131
111
  metadata: metadata || {}
132
112
  });
133
113
  }
134
114
  }
115
+
135
116
  // ─── Discount: 子模块注册 ───
117
+
136
118
  registerDiscountModules(options) {
137
119
  let targetCacheData = {};
138
120
  if (this.cacheId && this.window) {
@@ -140,14 +122,15 @@ var OrderModule = class extends import_BaseModule.BaseModule {
140
122
  if (sessionData) {
141
123
  try {
142
124
  const data = JSON.parse(sessionData);
143
- targetCacheData = (data == null ? void 0 : data[this.cacheId]) || {};
125
+ targetCacheData = data?.[this.cacheId] || {};
144
126
  } catch {
127
+ // sessionStorage 损坏则忽略,按空 initialState 走
145
128
  }
146
129
  }
147
130
  }
148
- const discount = new import_Discount.DiscountModule(`${this.name}_discount`);
131
+ const discount = new _Discount.DiscountModule(`${this.name}_discount`);
149
132
  this.core.registerModule(discount, {
150
- initialState: targetCacheData == null ? void 0 : targetCacheData[discount.name],
133
+ initialState: targetCacheData?.[discount.name],
151
134
  otherParams: {
152
135
  fatherModule: this.name,
153
136
  openCache: !!this.cacheId,
@@ -155,192 +138,214 @@ var OrderModule = class extends import_BaseModule.BaseModule {
155
138
  }
156
139
  });
157
140
  this.store.discount = discount;
158
- const rules = new import_Rules.RulesModule(`${this.name}_rules`);
141
+ const rules = new _Rules.RulesModule(`${this.name}_rules`);
159
142
  this.core.registerModule(rules, {
160
143
  hooks: this.rulesHooksOverride || this.createDefaultRulesHooks()
161
144
  });
162
145
  this.store.rules = rules;
163
146
  }
164
147
  createDefaultRulesHooks() {
165
- return (0, import_utils.createDefaultOrderRulesHooks)();
148
+ return (0, _utils.createDefaultOrderRulesHooks)();
166
149
  }
150
+
167
151
  // ─── Discount: 公共 API ───
152
+
168
153
  async loadDiscountConfig(params) {
169
- var _a, _b, _c, _d;
170
- const prepareConfig = await ((_a = this.store.discount) == null ? void 0 : _a.loadPrepareConfig({
154
+ const prepareConfig = await this.store.discount?.loadPrepareConfig({
171
155
  customer_id: params.customerId,
172
- action: params.action || "create",
156
+ action: params.action || 'create',
173
157
  with_good_pass: 1,
174
158
  with_discount_card: 1,
175
159
  with_wallet_pass_holder: 1,
176
160
  with_available_wallet_flag: 1,
177
161
  with_available_wallet_pass_flag: 1,
178
162
  request_timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
179
- }));
180
- const discountList = prepareConfig == null ? void 0 : prepareConfig.discountList;
181
- this.store.availableWalletIds = (prepareConfig == null ? void 0 : prepareConfig.availableWalletIds) || [];
163
+ });
164
+ const discountList = prepareConfig?.discountList;
165
+ this.store.availableWalletIds = prepareConfig?.availableWalletIds || [];
182
166
  if (discountList) {
183
- (_b = this.store.discount) == null ? void 0 : _b.setDiscountList(discountList);
167
+ this.store.discount?.setDiscountList(discountList);
184
168
  }
185
- if ((_d = (_c = this.store.tempOrder) == null ? void 0 : _c.products) == null ? void 0 : _d.length) {
169
+ if (this.store.tempOrder?.products?.length) {
186
170
  this.applyDiscount();
187
171
  }
188
172
  }
189
173
  getDiscountList() {
190
- var _a;
191
- return ((_a = this.store.discount) == null ? void 0 : _a.getDiscountList()) || [];
174
+ return this.store.discount?.getDiscountList() || [];
192
175
  }
193
176
  getAvailableWalletIds() {
194
177
  return this.store.availableWalletIds || [];
195
178
  }
196
179
  async scanCode(code, customerId) {
197
- var _a, _b, _c, _d, _e;
198
- const resultDiscountWithReason = await ((_a = this.store.discount) == null ? void 0 : _a.batchSearch(code, { customerId })) || { discountList: [], unavailableReasonKey: null };
199
- const { discountList: resultDiscountList, unavailableReasonKey } = resultDiscountWithReason;
180
+ const resultDiscountWithReason = (await this.store.discount?.batchSearch(code, {
181
+ customerId
182
+ })) || {
183
+ discountList: [],
184
+ unavailableReasonKey: null
185
+ };
186
+ const {
187
+ discountList: resultDiscountList,
188
+ unavailableReasonKey
189
+ } = resultDiscountWithReason;
200
190
  const rulesModule = this.store.rules;
201
191
  if (!rulesModule) {
202
192
  return {
203
- type: "clientCalc",
193
+ type: 'clientCalc',
204
194
  isAvailable: false,
205
195
  discountList: this.getDiscountList(),
206
- unavailableReason: import_types.UnavailableReason.Unknown
196
+ unavailableReason: _types.UnavailableReason.Unknown
207
197
  };
208
198
  }
209
199
  if (!resultDiscountList.length) {
210
200
  return {
211
- type: "server",
201
+ type: 'server',
212
202
  isAvailable: false,
213
203
  discountList: this.getDiscountList(),
214
204
  unavailableReasonKey
215
205
  };
216
206
  }
217
- const withScanList = resultDiscountList.map((item) => ({ ...item, isScan: true }));
218
- const currentSelected = this.getDiscountList().filter((n) => n.isSelected);
219
- if (currentSelected.length && currentSelected.some((n) => withScanList.some((m) => m.id === n.id))) {
207
+ const withScanList = resultDiscountList.map(item => ({
208
+ ...item,
209
+ isScan: true
210
+ }));
211
+ const currentSelected = this.getDiscountList().filter(n => n.isSelected);
212
+ if (currentSelected.length && currentSelected.some(n => withScanList.some(m => m.id === n.id))) {
220
213
  return {
221
- type: "clientCalc",
214
+ type: 'clientCalc',
222
215
  isAvailable: true,
223
216
  discountList: this.getDiscountList()
224
217
  };
225
218
  }
226
219
  const tempOrder = this.store.tempOrder;
227
- const holders = ((_b = tempOrder == null ? void 0 : tempOrder.holder) == null ? void 0 : _b.form_record_id) ? [{ form_record_id: tempOrder.holder.form_record_id }] : [];
228
- const { isAvailable, discountList: newDiscountList, unavailableReason } = rulesModule.isDiscountListAvailable({
229
- productList: (tempOrder == null ? void 0 : tempOrder.products) || [],
220
+ const holders = tempOrder?.holder?.form_record_id ? [{
221
+ form_record_id: tempOrder.holder.form_record_id
222
+ }] : [];
223
+ const {
224
+ isAvailable,
225
+ discountList: newDiscountList,
226
+ unavailableReason
227
+ } = rulesModule.isDiscountListAvailable({
228
+ productList: tempOrder?.products || [],
230
229
  oldDiscountList: this.getDiscountList(),
231
230
  newDiscountList: withScanList,
232
231
  holders,
233
- isFormSubject: !!((_c = tempOrder == null ? void 0 : tempOrder.holder) == null ? void 0 : _c.type) && tempOrder.holder.type === "form",
234
- orderTotalAmount: Number(((_d = tempOrder == null ? void 0 : tempOrder.summary) == null ? void 0 : _d.total_amount) || 0)
235
- }) || { isAvailable: false, discountList: this.getDiscountList() };
232
+ isFormSubject: !!tempOrder?.holder?.type && tempOrder.holder.type === 'form',
233
+ orderTotalAmount: Number(tempOrder?.summary?.total_amount || 0)
234
+ }) || {
235
+ isAvailable: false,
236
+ discountList: this.getDiscountList()
237
+ };
236
238
  if (isAvailable && newDiscountList) {
237
- (_e = this.store.discount) == null ? void 0 : _e.setDiscountList(newDiscountList);
239
+ this.store.discount?.setDiscountList(newDiscountList);
238
240
  this.applyDiscount();
239
241
  }
240
242
  return {
241
- type: "clientCalc",
243
+ type: 'clientCalc',
242
244
  isAvailable: isAvailable || false,
243
245
  discountList: newDiscountList || this.getDiscountList(),
244
246
  unavailableReason
245
247
  };
246
248
  }
247
249
  applyDiscount() {
248
- var _a, _b, _c, _d, _e;
249
250
  const tempOrder = this.store.tempOrder;
250
- if (!tempOrder)
251
- return;
251
+ // 任意 products CRUD 后都应当重算 discount 状态;即使 products 为空,
252
+ // 也需要让 Rules.calcDiscount 把 DiscountModule 的 isSelected / isAvailable /
253
+ // appliedProductDetails / savedAmount 以及 tempOrder.discount_list 复位。
254
+ if (!tempOrder) return;
252
255
  const rulesModule = this.store.rules;
253
- if (!rulesModule)
254
- return;
255
- const discountList = ((_a = this.store.discount) == null ? void 0 : _a.getDiscountList()) || [];
256
- const holders = ((_b = tempOrder.holder) == null ? void 0 : _b.form_record_id) ? [{ form_record_id: tempOrder.holder.form_record_id }] : [];
256
+ if (!rulesModule) return;
257
+ const discountList = this.store.discount?.getDiscountList() || [];
258
+ const holders = tempOrder.holder?.form_record_id ? [{
259
+ form_record_id: tempOrder.holder.form_record_id
260
+ }] : [];
257
261
  const result = rulesModule.calcDiscount({
258
262
  productList: tempOrder.products,
259
263
  discountList,
260
264
  holders,
261
- isFormSubject: !!((_c = tempOrder.holder) == null ? void 0 : _c.type) && tempOrder.holder.type === "form",
262
- orderTotalAmount: Number(((_d = tempOrder == null ? void 0 : tempOrder.summary) == null ? void 0 : _d.total_amount) || 0)
265
+ isFormSubject: !!tempOrder.holder?.type && tempOrder.holder.type === 'form',
266
+ orderTotalAmount: Number(tempOrder?.summary?.total_amount || 0)
263
267
  });
264
- if (result == null ? void 0 : result.productList) {
268
+ if (result?.productList) {
265
269
  tempOrder.products = result.productList;
266
270
  }
267
- if (result == null ? void 0 : result.discountList) {
271
+ if (result?.discountList) {
268
272
  OrderModule.populateSavedAmounts(result.productList || tempOrder.products, result.discountList);
269
- (_e = this.store.discount) == null ? void 0 : _e.setDiscountList(result.discountList);
270
- tempOrder.discount_list = result.discountList.filter((d) => d.isSelected);
273
+ this.store.discount?.setDiscountList(result.discountList);
274
+ tempOrder.discount_list = result.discountList.filter(d => d.isSelected);
271
275
  }
272
276
  }
277
+
273
278
  // ─── TempOrder: 初始化入口 ───
279
+
274
280
  initTempOrder(params) {
275
- if (params.cacheId !== void 0)
276
- this.cacheId = params.cacheId;
277
- if (params.salesSummaryModuleName !== void 0)
278
- this.salesSummaryModuleName = params.salesSummaryModuleName;
281
+ if (params.cacheId !== undefined) this.cacheId = params.cacheId;
282
+ if (params.salesSummaryModuleName !== undefined) this.salesSummaryModuleName = params.salesSummaryModuleName;
279
283
  this.restoreTempOrderFromStorage();
280
284
  }
285
+
281
286
  // ─── TempOrder: localStorage 持久化 ───
287
+
282
288
  getTempOrderStorageKey() {
283
- if (!this.cacheId)
284
- return null;
289
+ if (!this.cacheId) return null;
285
290
  return `scanOrder:tempOrder:${this.cacheId}`;
286
291
  }
287
292
  restoreTempOrderFromStorage() {
288
- var _a, _b;
289
293
  const key = this.getTempOrderStorageKey();
290
- if (!key)
291
- return;
292
- if (!this.window)
293
- return;
294
+ if (!key) return;
295
+ if (!this.window) return;
294
296
  const cachedData = this.window.localStorage.getItem(key);
295
- if (!cachedData)
296
- return;
297
+ if (!cachedData) return;
297
298
  try {
298
299
  const parsedData = JSON.parse(cachedData);
299
- if (!(0, import_utils.isTempOrder)(parsedData)) {
300
+ if (!(0, _utils.isTempOrder)(parsedData)) {
300
301
  this.window.localStorage.removeItem(key);
301
302
  return;
302
303
  }
303
304
  if (Array.isArray(parsedData.products)) {
304
305
  for (let i = 0; i < parsedData.products.length; i++) {
305
306
  const p = parsedData.products[i];
306
- if (!p || typeof p !== "object")
307
- continue;
307
+ if (!p || typeof p !== 'object') continue;
308
308
  if (!Array.isArray(p.product_option_item)) {
309
309
  p.product_option_item = [];
310
310
  }
311
311
  if (!Array.isArray(p.product_bundle)) {
312
312
  p.product_bundle = [];
313
313
  }
314
+ // 不透明 identity 契约:旧缓存里可能没有 identity_key,
315
+ // 此处统一回填 UUID 并同步 metadata.unique_identification_number,
316
+ // 避免升级后 UI 侧持有的 rowKey 找不到对应行。
314
317
  const row = p;
315
- if (typeof row.identity_key !== "string" || row.identity_key.length === 0) {
316
- const newKey = (0, import_utils.createUuidV4)();
318
+ if (typeof row.identity_key !== 'string' || row.identity_key.length === 0) {
319
+ const newKey = (0, _utils.createUuidV4)();
317
320
  row.identity_key = newKey;
318
- if (!row.metadata || typeof row.metadata !== "object") {
321
+ if (!row.metadata || typeof row.metadata !== 'object') {
319
322
  row.metadata = {};
320
323
  }
321
324
  if (!row.metadata.unique_identification_number) {
322
325
  row.metadata.unique_identification_number = newKey;
323
326
  }
324
327
  }
325
- parsedData.products[i] = (0, import_utils3.normalizeOrderProduct)(row);
328
+ // 价格 schema 迁移:重跑 normalizeOrderProduct。
329
+ // `metadata.price_schema_version === 2` → 已是新语义,保留现有 main_product_* 折扣;
330
+ // 否则(v1 或无 metadata)→ 走 legacyDiscount 反推分支,基于新的 source + options
331
+ // 重算出含 option 的 main_product_*,并打上 price_schema_version: 2。
332
+ // 幂等:多次 restore 不会重复叠加 option/bundle。
333
+ parsedData.products[i] = (0, _utils3.normalizeOrderProduct)(row);
326
334
  }
327
335
  }
328
336
  this.store.tempOrder = parsedData;
329
337
  } catch {
330
- (_b = (_a = this.window) == null ? void 0 : _a.localStorage) == null ? void 0 : _b.removeItem(key);
338
+ this.window?.localStorage?.removeItem(key);
331
339
  }
332
340
  }
333
341
  persistTempOrder() {
334
342
  const key = this.getTempOrderStorageKey();
335
- if (!key || !this.store.tempOrder)
336
- return;
337
- if (!this.window)
338
- return;
343
+ if (!key || !this.store.tempOrder) return;
344
+ if (!this.window) return;
339
345
  this.window.localStorage.setItem(key, JSON.stringify(this.store.tempOrder));
340
346
  }
341
347
  notifyTempOrderChanged() {
342
- if (!this.store.tempOrder)
343
- return;
348
+ if (!this.store.tempOrder) return;
344
349
  this.store.tempOrder = {
345
350
  ...this.store.tempOrder,
346
351
  products: [...this.store.tempOrder.products],
@@ -348,16 +353,17 @@ var OrderModule = class extends import_BaseModule.BaseModule {
348
353
  };
349
354
  this.persistTempOrder();
350
355
  }
356
+
351
357
  // ─── TempOrder: 创建 & 获取 ───
358
+
352
359
  createDefaultTempOrderInstance() {
353
- return (0, import_utils.createDefaultTempOrder)({
354
- now: (0, import_utils.formatDateTime)(/* @__PURE__ */ new Date()),
355
- summary: (0, import_utils.createEmptySummary)()
360
+ return (0, _utils.createDefaultTempOrder)({
361
+ now: (0, _utils.formatDateTime)(new Date()),
362
+ summary: (0, _utils.createEmptySummary)()
356
363
  });
357
364
  }
358
365
  ensureTempOrder() {
359
- if (this.store.tempOrder)
360
- return this.store.tempOrder;
366
+ if (this.store.tempOrder) return this.store.tempOrder;
361
367
  const newOrder = this.createDefaultTempOrderInstance();
362
368
  this.store.tempOrder = newOrder;
363
369
  this.persistTempOrder();
@@ -374,7 +380,9 @@ var OrderModule = class extends import_BaseModule.BaseModule {
374
380
  }
375
381
  async addNewOrder() {
376
382
  const tempOrder = this.ensureTempOrder();
377
- await this.recalculateSummary({ createIfMissing: true });
383
+ await this.recalculateSummary({
384
+ createIfMissing: true
385
+ });
378
386
  this.persistTempOrder();
379
387
  return tempOrder;
380
388
  }
@@ -382,19 +390,19 @@ var OrderModule = class extends import_BaseModule.BaseModule {
382
390
  const tempOrder = this.ensureTempOrder();
383
391
  return tempOrder.products;
384
392
  }
393
+
385
394
  // ─── TempOrder: 金额汇总 ───
395
+
386
396
  getSalesSummary() {
387
- if (!this.salesSummaryModuleName)
388
- return null;
397
+ if (!this.salesSummaryModuleName) return null;
389
398
  return this.core.getModule(this.salesSummaryModuleName);
390
399
  }
391
400
  async recalculateSummary(options) {
392
- const tempOrder = (options == null ? void 0 : options.createIfMissing) ? this.ensureTempOrder() : this.store.tempOrder;
393
- if (!tempOrder)
394
- return null;
401
+ const tempOrder = options?.createIfMissing ? this.ensureTempOrder() : this.store.tempOrder;
402
+ if (!tempOrder) return null;
395
403
  const salesSummary = this.getSalesSummary();
396
404
  if (!salesSummary) {
397
- tempOrder.summary = (0, import_utils.createEmptySummary)();
405
+ tempOrder.summary = (0, _utils.createEmptySummary)();
398
406
  tempOrder.surcharge_fee = tempOrder.summary.surcharge_fee;
399
407
  return tempOrder.summary;
400
408
  }
@@ -402,36 +410,39 @@ var OrderModule = class extends import_BaseModule.BaseModule {
402
410
  products: tempOrder.products
403
411
  });
404
412
  tempOrder.summary = summary;
405
- if (summary.is_price_include_tax !== void 0) {
413
+ if (summary.is_price_include_tax !== undefined) {
406
414
  tempOrder.is_price_include_tax = summary.is_price_include_tax;
407
415
  }
408
- if (typeof summary.tax_title === "string") {
416
+ if (typeof summary.tax_title === 'string') {
409
417
  tempOrder.tax_title = summary.tax_title;
410
418
  }
411
419
  tempOrder.surcharge_fee = summary.surcharge_fee;
412
420
  tempOrder.surcharges = summary.surcharges || [];
413
- tempOrder.deposit_amount = summary.deposit_amount || "0.00";
414
- tempOrder.is_deposit = summary.deposit_amount !== "0.00" ? 1 : 0;
415
- tempOrder.shop_discount = summary.discount_amount || "0.00";
421
+ tempOrder.deposit_amount = summary.deposit_amount || '0.00';
422
+ tempOrder.is_deposit = summary.deposit_amount !== '0.00' ? 1 : 0;
423
+ tempOrder.shop_discount = summary.discount_amount || '0.00';
416
424
  return tempOrder.summary;
417
425
  }
418
426
  async getScanOrderSummary() {
419
- const summary = await this.recalculateSummary({ createIfMissing: true });
420
- if (!summary)
421
- return (0, import_utils.createEmptySummary)();
427
+ const summary = await this.recalculateSummary({
428
+ createIfMissing: true
429
+ });
430
+ if (!summary) return (0, _utils.createEmptySummary)();
422
431
  this.persistTempOrder();
423
432
  return summary;
424
433
  }
434
+
425
435
  // ─── TempOrder: 备注 ───
436
+
426
437
  updateTempOrderNote(note) {
427
438
  const tempOrder = this.ensureTempOrder();
428
- tempOrder.note = String(note || "");
439
+ tempOrder.note = String(note || '');
429
440
  this.persistTempOrder();
430
441
  return tempOrder.note;
431
442
  }
432
443
  updateTempOrderBuzzer(buzzer) {
433
444
  const tempOrder = this.ensureTempOrder();
434
- tempOrder.buzzer = String(buzzer || "");
445
+ tempOrder.buzzer = String(buzzer || '');
435
446
  this.persistTempOrder();
436
447
  return tempOrder.buzzer;
437
448
  }
@@ -441,16 +452,16 @@ var OrderModule = class extends import_BaseModule.BaseModule {
441
452
  this.persistTempOrder();
442
453
  return tempOrder.contacts_info;
443
454
  }
455
+
444
456
  // ─── TempOrder: 商品 CRUD ───
457
+
445
458
  async addProductToOrder(product) {
446
459
  const tempOrder = this.ensureTempOrder();
447
- const hasExplicitIdentityKey = typeof product.identity_key === "string" && product.identity_key.length > 0;
460
+ const hasExplicitIdentityKey = typeof product.identity_key === 'string' && product.identity_key.length > 0;
448
461
  if (hasExplicitIdentityKey) {
449
- const normalizedProduct = (0, import_utils3.normalizeOrderProduct)(product);
450
- const productIndex = (0, import_utils3.getProductIdentityIndex)(
451
- tempOrder.products,
452
- normalizedProduct
453
- );
462
+ // 调用方自持 identity_key(如 VenueBooking 外部生成)→ 走严格 identity 合并。
463
+ const normalizedProduct = (0, _utils3.normalizeOrderProduct)(product);
464
+ const productIndex = (0, _utils3.getProductIdentityIndex)(tempOrder.products, normalizedProduct);
454
465
  if (productIndex === -1) {
455
466
  tempOrder.products.push(normalizedProduct);
456
467
  } else {
@@ -458,32 +469,26 @@ var OrderModule = class extends import_BaseModule.BaseModule {
458
469
  tempOrder.products[productIndex] = {
459
470
  ...targetProduct,
460
471
  ...normalizedProduct,
461
- num: (0, import_utils3.getSafeProductNum)(targetProduct.num + normalizedProduct.num),
472
+ num: (0, _utils3.getSafeProductNum)(targetProduct.num + normalizedProduct.num),
462
473
  _origin: normalizedProduct._origin || targetProduct._origin
463
474
  };
464
475
  }
465
476
  } else {
466
- const incomingFingerprint = (0, import_utils3.buildProductLineFingerprint)(
467
- product.product_option_item,
468
- product.product_bundle
469
- );
470
- const matchedIndex = tempOrder.products.findIndex((item) => {
471
- if (item.product_id !== product.product_id)
472
- return false;
473
- if (item.product_variant_id !== product.product_variant_id)
474
- return false;
475
- const existedFingerprint = (0, import_utils3.buildProductLineFingerprint)(
476
- item.product_option_item,
477
- item.product_bundle
478
- );
477
+ // 无 identity_key:按 SKU + 内容指纹(options + bundle)匹配既有行以累加数量;
478
+ // 命中时保留已有 identity_key,未命中才由 normalizeOrderProduct 自动生成 UUID。
479
+ const incomingFingerprint = (0, _utils3.buildProductLineFingerprint)(product.product_option_item, product.product_bundle);
480
+ const matchedIndex = tempOrder.products.findIndex(item => {
481
+ if (item.product_id !== product.product_id) return false;
482
+ if (item.product_variant_id !== product.product_variant_id) return false;
483
+ const existedFingerprint = (0, _utils3.buildProductLineFingerprint)(item.product_option_item, item.product_bundle);
479
484
  return existedFingerprint === incomingFingerprint;
480
485
  });
481
486
  if (matchedIndex === -1) {
482
- const normalizedProduct = (0, import_utils3.normalizeOrderProduct)(product);
487
+ const normalizedProduct = (0, _utils3.normalizeOrderProduct)(product);
483
488
  tempOrder.products.push(normalizedProduct);
484
489
  } else {
485
490
  const targetProduct = tempOrder.products[matchedIndex];
486
- const normalizedProduct = (0, import_utils3.normalizeOrderProduct)({
491
+ const normalizedProduct = (0, _utils3.normalizeOrderProduct)({
487
492
  ...product,
488
493
  identity_key: targetProduct.identity_key
489
494
  });
@@ -491,18 +496,19 @@ var OrderModule = class extends import_BaseModule.BaseModule {
491
496
  ...targetProduct,
492
497
  ...normalizedProduct,
493
498
  identity_key: targetProduct.identity_key,
494
- num: (0, import_utils3.getSafeProductNum)(targetProduct.num + normalizedProduct.num),
499
+ num: (0, _utils3.getSafeProductNum)(targetProduct.num + normalizedProduct.num),
495
500
  _origin: normalizedProduct._origin || targetProduct._origin
496
501
  };
497
502
  }
498
503
  }
499
504
  this.applyDiscount();
500
- await this.recalculateSummary({ createIfMissing: true });
505
+ await this.recalculateSummary({
506
+ createIfMissing: true
507
+ });
501
508
  this.persistTempOrder();
502
509
  return tempOrder.products;
503
510
  }
504
511
  async updateProductInOrder(params) {
505
- var _a, _b, _c;
506
512
  const {
507
513
  product_id,
508
514
  product_variant_id,
@@ -516,15 +522,12 @@ var OrderModule = class extends import_BaseModule.BaseModule {
516
522
  product_id,
517
523
  product_variant_id
518
524
  };
519
- if (identity_key !== void 0)
520
- identityLookup.identity_key = identity_key;
521
- if (product_option_item !== void 0)
522
- identityLookup.product_option_item = product_option_item;
523
- if (product_bundle !== void 0)
524
- identityLookup.product_bundle = product_bundle;
525
- const productIndex = (0, import_utils3.getProductIdentityIndex)(tempOrder.products, identityLookup);
525
+ if (identity_key !== undefined) identityLookup.identity_key = identity_key;
526
+ if (product_option_item !== undefined) identityLookup.product_option_item = product_option_item;
527
+ if (product_bundle !== undefined) identityLookup.product_bundle = product_bundle;
528
+ const productIndex = (0, _utils3.getProductIdentityIndex)(tempOrder.products, identityLookup);
526
529
  if (productIndex === -1) {
527
- throw new Error("[Order] 目标商品不存在,无法更新");
530
+ throw new Error('[Order] 目标商品不存在,无法更新');
528
531
  }
529
532
  const targetProduct = tempOrder.products[productIndex];
530
533
  const nextProduct = {
@@ -533,54 +536,68 @@ var OrderModule = class extends import_BaseModule.BaseModule {
533
536
  product_id,
534
537
  product_variant_id
535
538
  };
536
- nextProduct.num = (0, import_utils3.getSafeProductNum)(nextProduct.num);
537
- const callerUpdatesTopPrice = Object.prototype.hasOwnProperty.call(updates || {}, "selling_price") || Object.prototype.hasOwnProperty.call(updates || {}, "original_price");
538
- const callerUpdatesMainMeta = ((_a = updates == null ? void 0 : updates.metadata) == null ? void 0 : _a.main_product_selling_price) !== void 0 || ((_b = updates == null ? void 0 : updates.metadata) == null ? void 0 : _b.main_product_original_price) !== void 0 || ((_c = updates == null ? void 0 : updates.metadata) == null ? void 0 : _c.source_product_price) !== void 0;
539
+ nextProduct.num = (0, _utils3.getSafeProductNum)(nextProduct.num);
540
+ // 兜底:caller 通过 updates 直接改了 selling_price / original_price 时,
541
+ // 视为 "重新给 source-level 主价"(caller 侧旧约定仍是 main-only 单价)。
542
+ // 清掉 metadata 里的 source_product_price / main_product_* / price_schema_version,
543
+ // 让 normalize 把顶层 selling_price 当作 source 来重算 main_original(=source+options) /
544
+ // main_selling / composite;否则旧 metadata 会反压顶层新值,触发口径不一致。
545
+ // 如果 caller 走推荐路径(updates.metadata.* 显式指定主价),保留 metadata 由 normalize 认它。
546
+ const callerUpdatesTopPrice = Object.prototype.hasOwnProperty.call(updates || {}, 'selling_price') || Object.prototype.hasOwnProperty.call(updates || {}, 'original_price');
547
+ const callerUpdatesMainMeta = updates?.metadata?.main_product_selling_price !== undefined || updates?.metadata?.main_product_original_price !== undefined || updates?.metadata?.source_product_price !== undefined;
539
548
  if (callerUpdatesTopPrice && !callerUpdatesMainMeta) {
540
549
  const existedMeta = nextProduct.metadata || {};
541
- nextProduct.metadata = { ...existedMeta };
550
+ nextProduct.metadata = {
551
+ ...existedMeta
552
+ };
542
553
  delete nextProduct.metadata.source_product_price;
543
554
  delete nextProduct.metadata.main_product_selling_price;
544
555
  delete nextProduct.metadata.main_product_original_price;
545
556
  delete nextProduct.metadata.price_schema_version;
546
557
  }
547
- tempOrder.products[productIndex] = (0, import_utils3.normalizeOrderProduct)(nextProduct);
558
+ // normalizeOrderProduct 幂等:v2 metadata 存在 → 保留 main_product_* 折扣重算 composite;
559
+ // 否则 → 把顶层 selling_price 视作 source,派生 main_product_* 并写 price_schema_version: 2。
560
+ tempOrder.products[productIndex] = (0, _utils3.normalizeOrderProduct)(nextProduct);
548
561
  this.applyDiscount();
549
- await this.recalculateSummary({ createIfMissing: true });
562
+ await this.recalculateSummary({
563
+ createIfMissing: true
564
+ });
550
565
  this.persistTempOrder();
551
566
  return tempOrder.products;
552
567
  }
553
568
  async removeProductFromOrder(identity) {
554
569
  const tempOrder = this.ensureTempOrder();
555
- tempOrder.products = tempOrder.products.filter(
556
- (item) => !(0, import_utils3.isIdentityMatch)(item, identity)
557
- );
570
+ tempOrder.products = tempOrder.products.filter(item => !(0, _utils3.isIdentityMatch)(item, identity));
558
571
  this.applyDiscount();
559
- await this.recalculateSummary({ createIfMissing: true });
572
+ await this.recalculateSummary({
573
+ createIfMissing: true
574
+ });
560
575
  this.persistTempOrder();
561
576
  return tempOrder.products;
562
577
  }
578
+
563
579
  // ─── TempOrder: 提交 ───
580
+
564
581
  async submitTempOrder(params) {
565
582
  const tempOrder = this.ensureTempOrder();
566
583
  this.persistTempOrder();
567
- const effectiveCacheId = (params == null ? void 0 : params.cacheId) ?? this.cacheId;
568
- const payload = (0, import_utils.buildSubmitPayload)({
584
+ const effectiveCacheId = params?.cacheId ?? this.cacheId;
585
+ const payload = (0, _utils.buildSubmitPayload)({
569
586
  tempOrder,
570
587
  cacheId: effectiveCacheId,
571
- platform: params == null ? void 0 : params.platform,
572
- businessCode: params == null ? void 0 : params.businessCode,
573
- channel: params == null ? void 0 : params.channel,
574
- type: params == null ? void 0 : params.type,
575
- enhance: params == null ? void 0 : params.enhancePayload
588
+ platform: params?.platform,
589
+ businessCode: params?.businessCode,
590
+ channel: params?.channel,
591
+ type: params?.type,
592
+ enhance: params?.enhancePayload
576
593
  });
577
594
  let result;
578
595
  if (tempOrder.order_id) {
579
- const products = (0, import_utils.filterProductsForScanOrderMore)(payload.products);
596
+ const products = (0, _utils.filterProductsForScanOrderMore)(payload.products);
580
597
  const moreResult = await this.scanOrderMore({
581
598
  query: {
582
599
  order_id: tempOrder.order_id,
583
- products,
600
+ products: products,
584
601
  request_unique_idempotency_token: payload.request_unique_idempotency_token
585
602
  }
586
603
  });
@@ -599,58 +616,60 @@ var OrderModule = class extends import_BaseModule.BaseModule {
599
616
  return result;
600
617
  }
601
618
  createOrder(params) {
602
- var _a;
603
619
  const order = {
604
- type: (params == null ? void 0 : params.type) || "appointment_booking",
620
+ type: params?.type || 'appointment_booking',
605
621
  // 要从外面拿,virtual
606
- platform: (params == null ? void 0 : params.platform) === "pc" ? "PC" : "H5",
607
- sales_channel: "my_pisel",
608
- order_sales_channel: "online_store",
622
+ platform: params?.platform === 'pc' ? 'PC' : 'H5',
623
+ sales_channel: 'my_pisel',
624
+ order_sales_channel: 'online_store',
609
625
  bookings: [],
610
- shop_note: "",
611
- schedule_date: "",
626
+ shop_note: '',
627
+ schedule_date: '',
612
628
  is_deposit: 0,
613
629
  relation_products: [],
614
630
  relation_forms: [],
615
- business_code: params == null ? void 0 : params.business_code,
616
- ...(params == null ? void 0 : params.extraData) || {}
631
+ business_code: params?.business_code,
632
+ ...(params?.extraData || {})
617
633
  };
618
- let is_deposit = 0;
634
+ let is_deposit = 0; // 是否存在定金,0 不存在,1 存在
619
635
  if (params.cartItems.length > 0) {
620
- params.cartItems.forEach((item) => {
621
- var _a2;
636
+ params.cartItems.forEach(item => {
622
637
  if (!item._origin.duration) {
623
- const { duration, durationType } = (0, import_utils.generateDuration)(item);
638
+ const {
639
+ duration,
640
+ durationType
641
+ } = (0, _utils.generateDuration)(item);
624
642
  item._origin.duration = duration;
625
643
  item._origin.sub_type = durationType;
626
644
  }
627
- const discountList = (0, import_utils.getAllDiscountList)(item);
645
+ const discountList = (0, _utils.getAllDiscountList)(item);
628
646
  item._origin.product.discount_list = discountList;
629
- if ((_a2 = params == null ? void 0 : params.extraData) == null ? void 0 : _a2.is_add_holder_info) {
630
- (0, import_utils.ensureCartItemOriginHolder)(item, this.window);
647
+
648
+ // 为预约补齐 holder 信息
649
+ if (params?.extraData?.is_add_holder_info) {
650
+ (0, _utils.ensureCartItemOriginHolder)(item, this.window);
631
651
  }
632
- if ((0, import_utils2.isNormalProduct)(item._origin)) {
652
+
653
+ // 购物车是否为普通商品
654
+ if ((0, _utils2.isNormalProduct)(item._origin)) {
633
655
  order.relation_products.push(item._origin.product);
634
656
  const relationForms = item._origin.relation_forms || [];
635
657
  order.relation_forms.push(...relationForms);
636
658
  delete item._origin.relation_forms;
637
659
  } else {
638
- const relationForms = (0, import_utils.mergeRelationForms)(
639
- item._origin.relation_forms || []
640
- );
660
+ // 合并关联表单
661
+ const relationForms = (0, _utils.mergeRelationForms)(item._origin.relation_forms || []);
641
662
  item._origin.relation_forms = relationForms;
642
663
  order.bookings.push(item._origin);
643
664
  }
644
- if (item == null ? void 0 : item.deposit) {
665
+ if (item?.deposit) {
645
666
  is_deposit = 1;
646
667
  }
647
668
  });
648
- if (order.type === "appointment_booking") {
649
- const firstAppointmentCartItem = (_a = params.cartItems.filter(
650
- (n) => !(0, import_utils2.isNormalProduct)(n._productOrigin)
651
- )) == null ? void 0 : _a[0];
669
+ if (order.type === 'appointment_booking') {
670
+ const firstAppointmentCartItem = params.cartItems.filter(n => !(0, _utils2.isNormalProduct)(n._productOrigin))?.[0];
652
671
  if (firstAppointmentCartItem) {
653
- order.schedule_date = firstAppointmentCartItem.start_date + " " + firstAppointmentCartItem.start_time + ":00";
672
+ order.schedule_date = firstAppointmentCartItem.start_date + ' ' + firstAppointmentCartItem.start_time + ':00';
654
673
  }
655
674
  }
656
675
  order.is_deposit = is_deposit;
@@ -658,14 +677,17 @@ var OrderModule = class extends import_BaseModule.BaseModule {
658
677
  return order;
659
678
  }
660
679
  checkBeforeSubmitOrder(params) {
661
- var _a;
662
- this.logInfo("checkBeforeSubmitOrder called", {
663
- cartItemsCount: ((_a = params.cartItems) == null ? void 0 : _a.length) || 0,
680
+ this.logInfo('checkBeforeSubmitOrder called', {
681
+ cartItemsCount: params.cartItems?.length || 0,
664
682
  type: params.type
665
683
  });
666
- const { cartItems, type } = params;
667
- if (type === "holder") {
668
- const hasNoHolderId = cartItems.some((item) => !item.holder_id);
684
+ const {
685
+ cartItems,
686
+ type
687
+ } = params;
688
+ if (type === 'holder') {
689
+ // 判断cartItems中是否有不存在holder_id的商品,如果有则返回false
690
+ const hasNoHolderId = cartItems.some(item => !item.holder_id);
669
691
  if (hasNoHolderId) {
670
692
  return false;
671
693
  }
@@ -673,27 +695,30 @@ var OrderModule = class extends import_BaseModule.BaseModule {
673
695
  return true;
674
696
  }
675
697
  async submitOrder(order) {
676
- var _a, _b, _c;
677
- this.logInfo("submitOrder called", {
698
+ this.logInfo('submitOrder called', {
678
699
  url: order.url,
679
700
  orderType: order.query.type,
680
701
  platform: order.query.platform,
681
- cartItemsCount: ((_a = order.query.cartItems) == null ? void 0 : _a.length) || 0
702
+ cartItemsCount: order.query.cartItems?.length || 0
682
703
  });
683
- const { url, query } = order;
684
- const fetchUrl = url || "/order/appointment";
704
+ const {
705
+ url,
706
+ query
707
+ } = order;
708
+ const fetchUrl = url || '/order/appointment';
685
709
  const params = this.createOrder(query);
686
- this.logInfo("Calling backend order API", {
710
+ this.logInfo('Calling backend order API', {
687
711
  url: fetchUrl,
688
712
  orderType: params.type,
689
713
  platform: params.platform,
690
714
  isDeposit: params.is_deposit,
691
- bookingsCount: ((_b = params.bookings) == null ? void 0 : _b.length) || 0,
692
- relationProductsCount: ((_c = params.relation_products) == null ? void 0 : _c.length) || 0,
715
+ bookingsCount: params.bookings?.length || 0,
716
+ relationProductsCount: params.relation_products?.length || 0,
693
717
  scheduleDate: params.schedule_date
694
718
  });
695
719
  return this.request.post(fetchUrl, params);
696
720
  }
721
+
697
722
  /**
698
723
  * Checkout 专用:创建订单到后端
699
724
  *
@@ -705,126 +730,117 @@ var OrderModule = class extends import_BaseModule.BaseModule {
705
730
  * @returns 后端返回的订单数据(包含订单ID等)
706
731
  */
707
732
  async createOrderByCheckout(params) {
708
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;
709
- const onlineStorePaymentCodeList = ["WXPAY", "WECHAT", "ALIPAY", "APPLE_PAY", "CREDIT_CARD_3DS", "CREDIT_CARD_TOKEN", "GOOGLE_PAY", "GOOGLE_PAY_3DS", "CREDIT_CARD"];
710
- params.payments = (_a = params.payments) == null ? void 0 : _a.filter((p) => !onlineStorePaymentCodeList.includes(p.code));
711
- this.logInfo("createOrderByCheckout called", {
733
+ // 过滤掉由在线店铺下单的 payment 支付数据
734
+ const onlineStorePaymentCodeList = ['WXPAY', 'WECHAT', 'ALIPAY', 'APPLE_PAY', 'CREDIT_CARD_3DS', 'CREDIT_CARD_TOKEN', 'GOOGLE_PAY', 'GOOGLE_PAY_3DS', 'CREDIT_CARD'];
735
+ params.payments = params.payments?.filter(p => !onlineStorePaymentCodeList.includes(p.code));
736
+ this.logInfo('createOrderByCheckout called', {
712
737
  type: params.type,
713
738
  platform: params.platform,
714
739
  is_deposit: params.is_deposit,
715
740
  customer_id: params.customer_id,
716
- bookingsCount: ((_b = params.bookings) == null ? void 0 : _b.length) || 0,
717
- relationProductsCount: ((_c = params.relation_products) == null ? void 0 : _c.length) || 0,
718
- paymentsCount: ((_d = params.payments) == null ? void 0 : _d.length) || 0,
741
+ bookingsCount: params.bookings?.length || 0,
742
+ relationProductsCount: params.relation_products?.length || 0,
743
+ paymentsCount: params.payments?.length || 0,
719
744
  depositAmount: params.deposit_amount,
720
745
  productTaxFee: params.product_tax_fee,
721
746
  note: params.note,
722
747
  scheduleDate: params.schedule_date,
723
748
  hasOrderId: !!params.order_id,
724
749
  orderIdIncluded: params.order_id,
725
- paymentMethods: ((_e = params.payments) == null ? void 0 : _e.map((p) => p.code)) || []
726
- });
727
- console.log("[Order] createOrderByCheckout 开始创建订单:", {
728
- type: params.type,
729
- platform: params.platform,
730
- is_deposit: params.is_deposit,
731
- customer_id: params.customer_id,
732
- bookingsCount: ((_f = params.bookings) == null ? void 0 : _f.length) || 0,
733
- relationProductsCount: ((_g = params.relation_products) == null ? void 0 : _g.length) || 0,
734
- paymentsCount: ((_h = params.payments) == null ? void 0 : _h.length) || 0
750
+ paymentMethods: params.payments?.map(p => p.code) || []
735
751
  });
736
752
  try {
753
+ // 构建订单数据,设置默认值并允许 params 覆盖
737
754
  const orderData = {
738
- sales_channel: "my_pisel",
739
- order_sales_channel: "online_store",
740
- shop_note: "",
741
- schedule_date: "",
755
+ sales_channel: 'my_pisel',
756
+ order_sales_channel: 'online_store',
757
+ shop_note: '',
758
+ schedule_date: '',
742
759
  is_deposit: 0,
743
760
  bookings: [],
744
761
  relation_products: [],
745
762
  relation_forms: [],
746
763
  payments: [],
747
764
  is_full_overwrite_flag: 1,
748
- ...params
749
- // 使用传入的参数覆盖默认值
765
+ ...params // 使用传入的参数覆盖默认值
750
766
  };
751
- if ((_i = orderData.payments) == null ? void 0 : _i.length) {
767
+ if (orderData.payments?.length) {
752
768
  orderData.small_ticket_data_flag = 1;
753
769
  }
770
+
771
+ // 兜底策略,如果是第一次下单,没有 order_id,且没有 schedule_date,则设置为当前时间
754
772
  if (!params.order_id && !orderData.schedule_date) {
755
- orderData.schedule_date = (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss");
773
+ orderData.schedule_date = (0, _dayjs.default)().format('YYYY-MM-DD HH:mm:ss');
756
774
  }
757
- console.log("[Order] 调用后端接口创建订单:", {
758
- url: "/order/checkout",
759
- orderType: orderData.type,
760
- platform: orderData.platform,
761
- isDeposit: orderData.is_deposit,
762
- customerId: orderData.customer_id,
763
- bookingsCount: ((_j = orderData.bookings) == null ? void 0 : _j.length) || 0,
764
- relationProductsCount: ((_k = orderData.relation_products) == null ? void 0 : _k.length) || 0,
765
- paymentsCount: ((_l = orderData.payments) == null ? void 0 : _l.length) || 0,
766
- paymentsMethods: ((_m = orderData.payments) == null ? void 0 : _m.map((p) => p.code)) || []
767
- });
768
- this.logInfo("Calling backend checkout API", {
769
- url: "/order/checkout",
775
+ // 记录接口调用详情
776
+ this.logInfo('Calling backend checkout API', {
777
+ url: '/order/checkout',
770
778
  orderType: orderData.type,
771
779
  platform: orderData.platform,
772
780
  isDeposit: orderData.is_deposit,
773
781
  customerId: orderData.customer_id,
774
782
  depositAmount: orderData.deposit_amount,
775
- bookingsCount: ((_n = orderData.bookings) == null ? void 0 : _n.length) || 0,
776
- relationProductsCount: ((_o = orderData.relation_products) == null ? void 0 : _o.length) || 0,
777
- paymentsCount: ((_p = orderData.payments) == null ? void 0 : _p.length) || 0,
778
- paymentMethods: ((_q = orderData.payments) == null ? void 0 : _q.map((p) => ({
783
+ bookingsCount: orderData.bookings?.length || 0,
784
+ relationProductsCount: orderData.relation_products?.length || 0,
785
+ paymentsCount: orderData.payments?.length || 0,
786
+ paymentMethods: orderData.payments?.map(p => ({
779
787
  code: p.code,
780
788
  amount: p.amount,
781
789
  type: p.type,
782
790
  hasVoucherId: !!p.voucher_id,
783
791
  orderPaymentType: p.order_payment_type
784
- }))) || [],
792
+ })) || [],
785
793
  productTaxFee: orderData.product_tax_fee,
786
794
  note: orderData.note,
787
795
  scheduleDate: orderData.schedule_date,
788
796
  hasOrderId: !!orderData.order_id,
789
797
  smallTicketDataFlag: orderData.small_ticket_data_flag
790
798
  });
791
- const response = await this.request.post("/order/checkout", orderData);
792
- this.logInfo("Order API called successfully", {
799
+
800
+ // 调用后端接口
801
+ const response = await this.request.post('/order/checkout', orderData);
802
+ this.logInfo('Order API called successfully', {
793
803
  response
794
804
  });
795
- console.log("[Order] 订单创建成功,后端响应:", {
796
- success: !!response,
797
- hasOrderId: !!(((_r = response == null ? void 0 : response.data) == null ? void 0 : _r.order_id) || (response == null ? void 0 : response.order_id))
798
- });
799
805
  return response;
800
806
  } catch (error) {
801
- console.error("[Order] createOrderByCheckout 创建订单失败:", error);
802
- this.logInfo("Order API called failed", {
807
+ console.error('[Order] createOrderByCheckout 创建订单失败:', error);
808
+ this.logInfo('Order API called failed', {
803
809
  error: error instanceof Error ? error.message : String(error)
804
810
  });
805
811
  throw error;
806
812
  }
807
813
  }
808
814
  async submitScanOrder(params) {
809
- const { url, query } = params;
810
- const fetchUrl = url || "/order/sales/checkout";
811
- return this.request.post(fetchUrl, query, { customToast: () => {
812
- } });
815
+ const {
816
+ url,
817
+ query
818
+ } = params;
819
+ const fetchUrl = url || '/order/sales/checkout';
820
+ return this.request.post(fetchUrl, query, {
821
+ customToast: () => {}
822
+ });
813
823
  }
814
824
  async scanOrderMore(params) {
815
- const { url, query } = params;
825
+ const {
826
+ url,
827
+ query
828
+ } = params;
816
829
  const fetchUrl = url || `/order/order/product/${query.order_id}`;
817
830
  const requestBody = {
818
831
  products: query.products,
819
832
  request_unique_idempotency_token: query.request_unique_idempotency_token
820
833
  };
821
- return this.request.put(fetchUrl, requestBody, { customToast: () => {
822
- } });
834
+ return this.request.put(fetchUrl, requestBody, {
835
+ customToast: () => {}
836
+ });
823
837
  }
838
+
824
839
  // TODO 获取详情的接口
825
840
  async getOrderInfoByRemote(order_id) {
841
+ // 读取到后端以后,存在 tempOrder 内的 lastOrderInfo
826
842
  const res = await this.request.get(`/order/sales/${order_id}`, {
827
- with: ["products", "scheduleEvents"]
843
+ with: ['products', 'scheduleEvents']
828
844
  });
829
845
  if (res.code === 200 && this.store.tempOrder) {
830
846
  this.store.tempOrder.lastOrderInfo = res.data;
@@ -832,11 +848,7 @@ var OrderModule = class extends import_BaseModule.BaseModule {
832
848
  return res;
833
849
  }
834
850
  getLastOrderInfo() {
835
- var _a, _b;
836
- return (_b = (_a = this.store) == null ? void 0 : _a.tempOrder) == null ? void 0 : _b.lastOrderInfo;
851
+ return this.store?.tempOrder?.lastOrderInfo;
837
852
  }
838
- };
839
- // Annotate the CommonJS export names for ESM import in node:
840
- 0 && (module.exports = {
841
- OrderModule
842
- });
853
+ }
854
+ exports.OrderModule = OrderModule;