@pisell/pisellos 2.3.169 → 2.3.171

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 (33) hide show
  1. package/dist/model/strategy/adapter/promotion/evaluator.js +5 -4
  2. package/dist/model/strategy/adapter/promotion/index.js +9 -0
  3. package/dist/modules/Discount/types.d.ts +4 -0
  4. package/dist/modules/Order/index.js +27 -13
  5. package/dist/modules/Order/utils.js +45 -45
  6. package/dist/modules/Product/index.d.ts +1 -1
  7. package/dist/modules/Rules/index.d.ts +3 -10
  8. package/dist/modules/Rules/index.js +169 -87
  9. package/dist/modules/Rules/promotionSelection.d.ts +14 -0
  10. package/dist/modules/Rules/promotionSelection.js +390 -0
  11. package/dist/modules/Rules/types.d.ts +9 -0
  12. package/dist/server/modules/order/index.d.ts +6 -0
  13. package/dist/server/modules/order/index.js +782 -447
  14. package/dist/solution/BaseSales/index.js +41 -21
  15. package/dist/solution/BaseSales/utils/cartPromotion.js +5 -2
  16. package/dist/solution/BookingByStep/index.d.ts +2 -2
  17. package/lib/model/strategy/adapter/promotion/evaluator.js +5 -4
  18. package/lib/model/strategy/adapter/promotion/index.js +1 -46
  19. package/lib/modules/Discount/types.d.ts +4 -0
  20. package/lib/modules/Order/index.js +11 -0
  21. package/lib/modules/Order/utils.js +1 -1
  22. package/lib/modules/Product/index.d.ts +1 -1
  23. package/lib/modules/Rules/index.d.ts +3 -10
  24. package/lib/modules/Rules/index.js +62 -22
  25. package/lib/modules/Rules/promotionSelection.d.ts +14 -0
  26. package/lib/modules/Rules/promotionSelection.js +230 -0
  27. package/lib/modules/Rules/types.d.ts +9 -0
  28. package/lib/server/modules/order/index.d.ts +6 -0
  29. package/lib/server/modules/order/index.js +226 -29
  30. package/lib/solution/BaseSales/index.js +19 -5
  31. package/lib/solution/BaseSales/utils/cartPromotion.js +5 -2
  32. package/lib/solution/BookingByStep/index.d.ts +2 -2
  33. package/package.json +1 -1
@@ -0,0 +1,230 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.calculatePromotionSelection = calculatePromotionSelection;
7
+ exports.getExclusivePromotion = getExclusivePromotion;
8
+ exports.isPromotionDiscountCard = isPromotionDiscountCard;
9
+ var _decimal = _interopRequireDefault(require("decimal.js"));
10
+ var _lodashEs = require("lodash-es");
11
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12
+ function isPromotionDiscountCard(discount) {
13
+ return ['discount_card', 'product_discount_card'].includes(discount?.tag || discount?.type);
14
+ }
15
+
16
+ /** 只处理当前购物车的 X 件 Y 元,历史成交和其他促销继续使用原有规则。 */
17
+ function getExclusivePromotion(product) {
18
+ const promotion = product?.metadata?._promotion;
19
+ if (product?.order_detail_id || product?.orderDetailId || product?.booking_id || product?.metadata?.booking_id || promotion?.actionType !== 'X_ITEMS_FOR_Y_PRICE' || !promotion.strategyId || !(promotion.inPromotion === true || promotion.excludedByDiscountCard === true)) return undefined;
20
+ return promotion;
21
+ }
22
+ /**
23
+ * 以完整策略参与组为单位比较两套实际报价。每次试算都从同一快照开始,
24
+ * 由原引擎重新做卡券校验和整单卡分摊,不能从叠加结果里事后减掉某条优惠。
25
+ */
26
+ function calculatePromotionSelection(params, options, hooks, calculate) {
27
+ const discountList = params.discountList.map(discount => {
28
+ if (discount.isEditMode || !isPromotionDiscountCard(discount)) return discount;
29
+ if (options?.preserveEntitlementSelection === false) {
30
+ return {
31
+ ...discount,
32
+ promotionSelection: undefined,
33
+ promotionSelectionStrategyIds: undefined,
34
+ isManualSelect: false
35
+ };
36
+ }
37
+ if (options?.discountId !== undefined && String(discount.id) === String(options.discountId) && typeof options.isSelected === 'boolean') {
38
+ return {
39
+ ...discount,
40
+ promotionSelection: options.isSelected ? 'card' : 'promotion',
41
+ isSelected: options.isSelected,
42
+ isManualSelect: !options.isSelected
43
+ };
44
+ }
45
+ return {
46
+ ...discount
47
+ };
48
+ });
49
+ // 未凑足促销时也要清理重叠商品上的旧手选,避免再次凑组后切回之前的卡。
50
+ const changedCard = options?.discountId !== undefined && typeof options.isSelected === 'boolean' ? discountList.find(discount => !discount.isEditMode && isPromotionDiscountCard(discount) && String(discount.id) === String(options.discountId)) : undefined;
51
+ if (changedCard) {
52
+ const changedProductIds = new Set(changedCard.applicableProductIds || []);
53
+ for (const product of params.productList) {
54
+ const detail = hooks.getProduct(product);
55
+ if (detail.discount_list?.some(discount => isPromotionDiscountCard(discount) && String(discount.discount?.resource_id ?? discount.id) === String(changedCard.id))) changedProductIds.add(detail.id);
56
+ }
57
+ for (const discount of discountList) {
58
+ if (discount.isEditMode || !isPromotionDiscountCard(discount) || String(discount.id) === String(changedCard.id) || !discount.promotionSelection) continue;
59
+ if (discount.applicableProductIds?.some(id => changedProductIds.has(id))) {
60
+ discount.promotionSelection = undefined;
61
+ discount.promotionSelectionStrategyIds = undefined;
62
+ }
63
+ }
64
+ }
65
+ const strategyIds = new Set();
66
+ for (const product of params.productList) {
67
+ const promotion = getExclusivePromotion(product);
68
+ if (promotion && hooks.getProduct(product).isManualDiscount !== true) {
69
+ strategyIds.add(String(promotion.strategyId));
70
+ }
71
+ }
72
+ if (!strategyIds.size) return calculate({
73
+ ...params,
74
+ discountList
75
+ }, options);
76
+ const applicableGroups = new Map();
77
+ const quote = (blockedStrategyIds, collectApplicable = false) => {
78
+ const productList = (0, _lodashEs.cloneDeep)(params.productList).map(product => {
79
+ const promotion = getExclusivePromotion(product);
80
+ if (!promotion || !strategyIds.has(String(promotion.strategyId))) return product;
81
+ const detail = hooks.getProduct(product);
82
+ if (detail.isManualDiscount === true) return product;
83
+ const keepPromotion = blockedStrategyIds.has(String(promotion.strategyId));
84
+ const originalPrice = Number(promotion.originalPrice ?? detail.price);
85
+ const finalPrice = Number(promotion.finalPrice);
86
+ const promotionDiscount = (detail.discount_list || []).find(discount => discount.type === 'promotion');
87
+ const retainedDiscounts = (detail.discount_list || []).filter(discount => discount.type !== 'promotion' && (!isPromotionDiscountCard(discount) || !keepPromotion && discountList.some(card => !card.isManualSelect && String(card.id) === String(discount.discount?.resource_id ?? discount.id))));
88
+ if (keepPromotion && originalPrice !== finalPrice) {
89
+ retainedDiscounts.push(promotionDiscount || {
90
+ type: 'promotion',
91
+ amount: new _decimal.default(originalPrice).minus(finalPrice).toFixed(2),
92
+ discount: {
93
+ original_amount: String(originalPrice),
94
+ fixed_amount: new _decimal.default(originalPrice).minus(finalPrice).toFixed(2),
95
+ title: promotion.strategyMetadata?.name || '',
96
+ resource_id: ''
97
+ }
98
+ });
99
+ }
100
+ product.metadata._promotion = {
101
+ ...promotion,
102
+ inPromotion: keepPromotion,
103
+ excludedByDiscountCard: !keepPromotion
104
+ };
105
+ return hooks.setProduct(product, {
106
+ discount_list: retainedDiscounts,
107
+ main_product_selling_price: keepPromotion ? finalPrice : originalPrice
108
+ });
109
+ });
110
+ return calculate({
111
+ ...params,
112
+ productList,
113
+ discountList: (0, _lodashEs.cloneDeep)(discountList).map(discount => !discount.isEditMode && isPromotionDiscountCard(discount) && !discount.isManualSelect
114
+ // 自动落选不等于手动禁用;整单卡仍须进入下一轮候选分摊。
115
+ ? {
116
+ ...discount,
117
+ isSelected: discount.isSelected === false ? undefined : discount.isSelected
118
+ } : discount)
119
+ }, options, {
120
+ blockedStrategyIds,
121
+ onApplicableCard: collectApplicable ? (product, discount) => {
122
+ const promotion = getExclusivePromotion(product);
123
+ if (!promotion || !strategyIds.has(String(promotion.strategyId))) return;
124
+ const id = String(discount.id);
125
+ const groups = applicableGroups.get(id) || new Set();
126
+ groups.add(String(promotion.strategyId));
127
+ applicableGroups.set(id, groups);
128
+ } : undefined
129
+ });
130
+ };
131
+
132
+ // 起点保留所有促销;未发生冲突的商品和卡券仍由原引擎正常计算。
133
+ let blockedStrategyIds = new Set(strategyIds);
134
+ let result = quote(blockedStrategyIds, true);
135
+ // 取消已应用的卡时,即使它刚好失效,也应恢复它原来替代的促销组。
136
+ for (const product of params.productList) {
137
+ const promotion = getExclusivePromotion(product);
138
+ if (!promotion || !strategyIds.has(String(promotion.strategyId))) continue;
139
+ for (const detail of hooks.getProduct(product).discount_list || []) {
140
+ if (!isPromotionDiscountCard(detail)) continue;
141
+ const id = String(detail.discount?.resource_id ?? detail.id);
142
+ if (!discountList.some(discount => String(discount.id) === id && (discount.isManualSelect || discount.promotionSelection === 'promotion'))) continue;
143
+ const groups = applicableGroups.get(id) || new Set();
144
+ groups.add(String(promotion.strategyId));
145
+ applicableGroups.set(id, groups);
146
+ }
147
+ }
148
+ // 同一参与组以最近一次手动操作为准,不能让先前选过的另一张卡重新压过取消操作。
149
+ const changedGroups = options?.discountId !== undefined && typeof options.isSelected === 'boolean' ? applicableGroups.get(String(options.discountId)) : undefined;
150
+ if (changedGroups?.size) {
151
+ for (const discount of discountList) {
152
+ if (!discount.isEditMode && String(discount.id) === String(options?.discountId)) {
153
+ discount.promotionSelectionStrategyIds = [...changedGroups];
154
+ continue;
155
+ }
156
+ if (discount.isEditMode || !isPromotionDiscountCard(discount) || String(discount.id) === String(options?.discountId) || !discount.promotionSelection) continue;
157
+ const groups = new Set([...(applicableGroups.get(String(discount.id)) || []), ...(discount.promotionSelectionStrategyIds || [])]);
158
+ if ([...groups].some(group => changedGroups.has(group))) {
159
+ discount.promotionSelection = undefined;
160
+ discount.promotionSelectionStrategyIds = undefined;
161
+ }
162
+ }
163
+ }
164
+ const manualPromotionGroups = new Set();
165
+ const manualCardGroups = new Set();
166
+ for (const discount of discountList) {
167
+ if (!isPromotionDiscountCard(discount) || discount.isEditMode) continue;
168
+ const groups = applicableGroups.get(String(discount.id)) || [];
169
+ if (discount.isManualSelect || discount.promotionSelection === 'promotion') {
170
+ for (const group of groups) manualPromotionGroups.add(group);
171
+ for (const group of discount.promotionSelectionStrategyIds || []) {
172
+ if (strategyIds.has(group)) manualPromotionGroups.add(group);
173
+ }
174
+ } else if (discount.promotionSelection === 'card') {
175
+ for (const group of groups) manualCardGroups.add(group);
176
+ }
177
+ }
178
+ const total = candidate => candidate.productList.reduce((sum, product) => {
179
+ const detail = hooks.getProduct(product);
180
+ const discounts = [...detail.discount_list, ...(detail.bundle || []).flatMap(bundle => (bundle.discount_list || []).filter(discount => !discount.id))];
181
+ // 与订单小计一致:整单卡未计入单价的尾差按行扣一次,不能漏算或再乘数量。
182
+ const difference = discounts.reduce((amount, discount) => amount.plus(discount.metadata?.product_discount_difference || 0), new _decimal.default(0));
183
+ return sum.plus(detail.total).minus(difference);
184
+ }, new _decimal.default(0));
185
+ const hasAppliedCard = (candidate, strategyId) => candidate.productList.some(product => String(getExclusivePromotion(product)?.strategyId) === strategyId && hooks.getProduct(product).discount_list.some(isPromotionDiscountCard));
186
+ // 手动选择先落定,随后只对未手选的参与组比较优惠。
187
+ for (const strategyId of manualCardGroups) {
188
+ const candidateBlocked = new Set(blockedStrategyIds);
189
+ candidateBlocked.delete(strategyId);
190
+ const candidate = quote(candidateBlocked);
191
+ if (hasAppliedCard(candidate, strategyId)) {
192
+ blockedStrategyIds = candidateBlocked;
193
+ result = candidate;
194
+ }
195
+ }
196
+ const automaticGroups = new Set([...strategyIds].filter(id => !manualCardGroups.has(id) && !manualPromotionGroups.has(id) && discountList.some(discount => !discount.isEditMode && !discount.isManualSelect && applicableGroups.get(String(discount.id))?.has(id))));
197
+ // 多组共用整单卡时先选节省最多的一组,再重新试算其余组,避免依赖购物车行顺序。
198
+ while (automaticGroups.size) {
199
+ let bestGroup;
200
+ let bestResult = result;
201
+ let bestTotal = total(result);
202
+ for (const strategyId of automaticGroups) {
203
+ const candidateBlocked = new Set(blockedStrategyIds);
204
+ candidateBlocked.delete(strategyId);
205
+ const candidate = quote(candidateBlocked);
206
+ const candidateTotal = total(candidate);
207
+ // 没有实际可用卡时保持促销;同价继续保留促销。
208
+ if (hasAppliedCard(candidate, strategyId) && candidateTotal.lessThan(bestTotal)) {
209
+ bestGroup = strategyId;
210
+ bestResult = candidate;
211
+ bestTotal = candidateTotal;
212
+ }
213
+ }
214
+ if (bestGroup === undefined) break;
215
+ blockedStrategyIds.delete(bestGroup);
216
+ automaticGroups.delete(bestGroup);
217
+ result = bestResult;
218
+ }
219
+ // 即使最终保留首次报价,也要回写上面清除的旧手动意图。
220
+ result.discountList = result.discountList.map(discount => {
221
+ if (discount.isEditMode || !isPromotionDiscountCard(discount)) return discount;
222
+ const selection = discountList.find(card => !card.isEditMode && String(card.id) === String(discount.id));
223
+ return {
224
+ ...discount,
225
+ promotionSelection: selection?.promotionSelection,
226
+ promotionSelectionStrategyIds: selection?.promotionSelectionStrategyIds
227
+ };
228
+ });
229
+ return result;
230
+ }
@@ -24,6 +24,15 @@ export interface DiscountResult {
24
24
  discountList: any[];
25
25
  }
26
26
  export type RulesFormSubject = boolean | ((product: any) => boolean);
27
+ export interface RulesCalcDiscountParams {
28
+ discountList: Discount[];
29
+ productList: any[];
30
+ holders: {
31
+ form_record_id: number;
32
+ }[];
33
+ isFormSubject: RulesFormSubject;
34
+ orderTotalAmount: number;
35
+ }
27
36
  export interface RulesCalcDiscountOptions {
28
37
  isSelected?: boolean;
29
38
  discountId?: number;
@@ -315,6 +315,8 @@ export declare class OrderModule extends BaseModule implements Module {
315
315
  */
316
316
  private getOrderStorageKey;
317
317
  private getPersistedOrderStorageKey;
318
+ private getRealOrderId;
319
+ private findLocalOrderIndexByIdentity;
318
320
  private getOrderIdentityMatchKeys;
319
321
  private doOrdersShareIdentity;
320
322
  private findOrderIndexByIdentity;
@@ -346,6 +348,10 @@ export declare class OrderModule extends BaseModule implements Module {
346
348
  private getStorageItem;
347
349
  private setStorageItem;
348
350
  private loadOrdersFromSQLite;
351
+ /** 历史记录只按真实订单 ID / 唯一本地编号归组,不使用桌号或小票短号。 */
352
+ private deduplicateStoredOrders;
353
+ private mergeStoredOrderCopies;
354
+ private writeOrderRowsToSQLite;
349
355
  private isPendingSyncOrder;
350
356
  private isDraftOrder;
351
357
  private shouldProtectDraftOrderFromIncoming;
@@ -1235,6 +1235,8 @@ class OrderModule extends _BaseModule.BaseModule {
1235
1235
  this.logInfo('upsertPendingSyncOrders-开始', {
1236
1236
  count: pendingMap.size
1237
1237
  });
1238
+ const storageKeyMigrations = [];
1239
+ const previousStorageKeys = this.store.list.map(order => this.getPersistedOrderStorageKey(order));
1238
1240
  const mergeActions = {};
1239
1241
  const updatedList = this.store.list.map(order => this.normalizeOrderForMemoryList(order, 'upsertPendingSyncOrders.existingMemory'));
1240
1242
 
@@ -1248,7 +1250,7 @@ class OrderModule extends _BaseModule.BaseModule {
1248
1250
  }
1249
1251
  }
1250
1252
  for (const [storageKey, pendingOrder] of memoryPendingMap.entries()) {
1251
- const matchIndex = this.lookupOrderIndexByIdentityKeys(identityKeyToIndex, this.getOrderIdentityMatchKeys(pendingOrder));
1253
+ const matchIndex = this.findLocalOrderIndexByIdentity(identityKeyToIndex, updatedList, pendingOrder);
1252
1254
  if (matchIndex >= 0) {
1253
1255
  const existingOrder = updatedList[matchIndex];
1254
1256
  const mergedOrder = this.mergeOrderRecords(existingOrder, pendingOrder);
@@ -1257,6 +1259,15 @@ class OrderModule extends _BaseModule.BaseModule {
1257
1259
  need_sync: 1,
1258
1260
  is_draft_order: 0
1259
1261
  };
1262
+ const previousStorageKey = previousStorageKeys[matchIndex];
1263
+ if (previousStorageKey && previousStorageKey !== storageKey) {
1264
+ storageKeyMigrations.push({
1265
+ orderId: nextOrder.order_id ?? null,
1266
+ from: previousStorageKey,
1267
+ to: storageKey
1268
+ });
1269
+ delete nextOrder[ORDER_STORAGE_KEY_FIELD];
1270
+ }
1260
1271
  updatedList[matchIndex] = nextOrder;
1261
1272
  const pendingSnapshot = pendingMap.get(storageKey);
1262
1273
  if (pendingSnapshot) {
@@ -1278,7 +1289,10 @@ class OrderModule extends _BaseModule.BaseModule {
1278
1289
  this.store.list = this.runOrderStoreSelfCheck(updatedList, 'upsertPendingSyncOrders.store');
1279
1290
  this.syncOrdersMap();
1280
1291
  try {
1281
- await this.patchOrdersInSQLite(patchedOrders, 'upsertPendingSyncOrders', mergeActions, options);
1292
+ await this.patchOrdersInSQLite(patchedOrders, 'upsertPendingSyncOrders', mergeActions, {
1293
+ ...options,
1294
+ storageKeyMigrations
1295
+ });
1282
1296
  } catch (error) {
1283
1297
  this.store.list = previousList;
1284
1298
  this.syncOrdersMap();
@@ -1327,8 +1341,10 @@ class OrderModule extends _BaseModule.BaseModule {
1327
1341
  memoryDraftCount: memoryDraftMap.size,
1328
1342
  sqliteOnlyDraftCount: draftMap.size - memoryDraftMap.size
1329
1343
  });
1344
+ const storageKeyMigrations = [];
1330
1345
  const mergeActions = {};
1331
1346
  const updatedList = this.store.list.filter(order => this.shouldKeepOrderInMemory(order));
1347
+ const previousStorageKeys = updatedList.map(order => this.getPersistedOrderStorageKey(order));
1332
1348
  const identityKeyToIndex = new Map();
1333
1349
  for (let index = 0; index < updatedList.length; index += 1) {
1334
1350
  for (const key of this.getOrderIdentityMatchKeys(updatedList[index])) {
@@ -1336,9 +1352,10 @@ class OrderModule extends _BaseModule.BaseModule {
1336
1352
  }
1337
1353
  }
1338
1354
  for (const [storageKey, draftOrder] of memoryDraftMap.entries()) {
1339
- const matchIndex = this.lookupOrderIndexByIdentityKeys(identityKeyToIndex, this.getOrderIdentityMatchKeys(draftOrder));
1355
+ const matchIndex = this.findLocalOrderIndexByIdentity(identityKeyToIndex, updatedList, draftOrder);
1340
1356
  if (matchIndex >= 0) {
1341
1357
  const existingOrder = updatedList[matchIndex];
1358
+ const previousStorageKey = previousStorageKeys[matchIndex];
1342
1359
  const reconciledDraftOrder = this.preserveExistingBusinessCodeForDraft(existingOrder, draftOrder);
1343
1360
  this.applyHolderRelationsSnapshot(reconciledDraftOrder, existingOrder, draftOrder);
1344
1361
  const mergedOrder = this.mergeOrderRecords(existingOrder, reconciledDraftOrder);
@@ -1347,6 +1364,14 @@ class OrderModule extends _BaseModule.BaseModule {
1347
1364
  need_sync: 0,
1348
1365
  is_draft_order: 1
1349
1366
  };
1367
+ if (previousStorageKey && previousStorageKey !== storageKey) {
1368
+ storageKeyMigrations.push({
1369
+ orderId: nextOrder.order_id ?? null,
1370
+ from: previousStorageKey,
1371
+ to: storageKey
1372
+ });
1373
+ delete nextOrder[ORDER_STORAGE_KEY_FIELD];
1374
+ }
1350
1375
  updatedList[matchIndex] = nextOrder;
1351
1376
  // SQLite 必须与内存中的草稿保持同一份 business_code,避免下次 hydrate 再次丢失分类。
1352
1377
  draftMap.set(storageKey, reconciledDraftOrder);
@@ -1365,7 +1390,8 @@ class OrderModule extends _BaseModule.BaseModule {
1365
1390
  this.syncOrdersMap();
1366
1391
  try {
1367
1392
  await this.patchOrdersInSQLite(patchedOrders, 'upsertLocalDraftOrders', mergeActions, {
1368
- throwOnError: true
1393
+ throwOnError: true,
1394
+ storageKeyMigrations
1369
1395
  });
1370
1396
  } catch (error) {
1371
1397
  this.store.list = previousList;
@@ -2037,6 +2063,23 @@ class OrderModule extends _BaseModule.BaseModule {
2037
2063
  }
2038
2064
  return this.getOrderStorageKey(order);
2039
2065
  }
2066
+ getRealOrderId(order) {
2067
+ if (this.isBlankIdentityValue(order.order_id)) return '';
2068
+ if (String(order.order_id) === String(order.external_sale_number)) return '';
2069
+ return String(order.order_id);
2070
+ }
2071
+ findLocalOrderIndexByIdentity(identityKeyToIndex, orders, target) {
2072
+ const id = this.getRealOrderId(target);
2073
+ const keys = id ? [`order_id:${id}`] : [];
2074
+ if (!this.isBlankIdentityValue(target.external_sale_number)) {
2075
+ keys.push(`external_sale_number:${target.external_sale_number}`);
2076
+ }
2077
+ const indexes = keys.map(key => identityKeyToIndex.get(key)).filter(index => index !== undefined).sort((left, right) => left - right);
2078
+ return indexes.find(index => {
2079
+ const existingId = this.getRealOrderId(orders[index]);
2080
+ return !id || !existingId || id === existingId;
2081
+ }) ?? -1;
2082
+ }
2040
2083
  getOrderIdentityMatchKeys(order) {
2041
2084
  return this.getOrderIdentityEntries(order).map(entry => `${entry.field}:${entry.key}`);
2042
2085
  }
@@ -2383,23 +2426,190 @@ class OrderModule extends _BaseModule.BaseModule {
2383
2426
  if (!this.dbManager) return [];
2384
2427
  try {
2385
2428
  const loadStartedAt = performance.now();
2386
- const rawReadStartedAt = performance.now();
2387
- const orders = await this.dbManager.getAll(INDEXDB_STORE_NAME);
2388
- const sqliteRawReadMs = +(performance.now() - rawReadStartedAt).toFixed(2);
2389
- const normalizeStartedAt = performance.now();
2390
- const normalizedOrders = (orders || []).map(order => this.normalizeOrderCollectionsForIngress(order, 'loadOrdersFromSQLite'));
2391
- const sqliteNormalizeMs = +(performance.now() - normalizeStartedAt).toFixed(2);
2392
- options.onTiming?.({
2393
- sqliteRawReadMs,
2394
- sqliteNormalizeMs,
2395
- sqliteLoadTotalMs: +(performance.now() - loadStartedAt).toFixed(2)
2429
+ const memoryBeforeLoad = this.store.list;
2430
+ let normalizedOrders = [];
2431
+ // 读修复与普通订单写入共用队列,避免用排队前的旧快照覆盖新的待同步订单。
2432
+ await this.runInOrderSQLiteSaveQueue(async () => {
2433
+ const rawReadStartedAt = performance.now();
2434
+ const orders = await this.dbManager.getAll(INDEXDB_STORE_NAME);
2435
+ const sqliteRawReadMs = +(performance.now() - rawReadStartedAt).toFixed(2);
2436
+ const normalizeStartedAt = performance.now();
2437
+ const {
2438
+ list,
2439
+ repairs,
2440
+ obsoleteKeys
2441
+ } = this.deduplicateStoredOrders(orders || []);
2442
+ normalizedOrders = list;
2443
+ const sqliteNormalizeMs = +(performance.now() - normalizeStartedAt).toFixed(2);
2444
+ if (repairs.length > 0) {
2445
+ try {
2446
+ // 先保存完整的保留记录,成功后才逐个删除旧键;不清空 orders 表。
2447
+ await this.writeOrderRowsToSQLite(repairs);
2448
+ this.recordRecentSqliteWrite('loadOrdersFromSQLite.deduplicate', repairs);
2449
+ for (const key of obsoleteKeys) {
2450
+ await this.dbManager.delete(INDEXDB_STORE_NAME, key);
2451
+ this.recentSqliteWriteByStorageKey.delete(key);
2452
+ }
2453
+ this.logInfo('SQLite重复订单已修复', {
2454
+ beforeCount: orders.length,
2455
+ afterCount: list.length,
2456
+ repairedCount: repairs.length,
2457
+ deletedKeyCount: obsoleteKeys.size
2458
+ });
2459
+ } catch (error) {
2460
+ // 本次仍使用去重后的内存快照;保留磁盘记录,后续读取可重试修复。
2461
+ this.logError('SQLite重复订单修复写入失败', {
2462
+ error: error instanceof Error ? error.message : String(error),
2463
+ repairedCount: repairs.length
2464
+ });
2465
+ }
2466
+ }
2467
+ options.onTiming?.({
2468
+ sqliteRawReadMs,
2469
+ sqliteNormalizeMs,
2470
+ sqliteLoadTotalMs: +(performance.now() - loadStartedAt).toFixed(2)
2471
+ });
2396
2472
  });
2473
+ if (this.store.list !== memoryBeforeLoad) {
2474
+ // 读取期间可能已开始新的本地结账;回灌不能抹掉尚在排队落库的修改。
2475
+ const previousOrders = new Map(memoryBeforeLoad.map(order => [this.getOrderStorageKey(order), order]));
2476
+ const protectedMemoryOrders = this.store.list.filter(order => this.shouldProtectLocalOrderFromRemoteSnapshot(order) && !(0, _lodashEs.isEqual)(previousOrders.get(this.getOrderStorageKey(order)), order));
2477
+ normalizedOrders = this.deduplicateStoredOrders([...normalizedOrders, ...protectedMemoryOrders], new Set(protectedMemoryOrders)).list;
2478
+ }
2397
2479
  return normalizedOrders;
2398
2480
  } catch (error) {
2399
2481
  if (options.throwOnError) throw error;
2400
2482
  return [];
2401
2483
  }
2402
2484
  }
2485
+
2486
+ /** 历史记录只按真实订单 ID / 唯一本地编号归组,不使用桌号或小票短号。 */
2487
+ deduplicateStoredOrders(orders, authoritativeOrders = new Set()) {
2488
+ const idsByExternal = new Map();
2489
+ for (const order of orders) {
2490
+ const id = this.getRealOrderId(order);
2491
+ const external = order.external_sale_number;
2492
+ if (!id || this.isBlankIdentityValue(external)) continue;
2493
+ const key = String(external);
2494
+ const previous = idsByExternal.get(key);
2495
+ idsByExternal.set(key, previous === undefined || previous === id ? id : null);
2496
+ }
2497
+ const groups = new Map();
2498
+ for (const [index, rawOrder] of orders.entries()) {
2499
+ const external = this.isBlankIdentityValue(rawOrder.external_sale_number) ? '' : String(rawOrder.external_sale_number);
2500
+ const id = this.getRealOrderId(rawOrder) || external && idsByExternal.get(external);
2501
+ const identity = id ? `id:${id}` : external ? `external:${external}` : `row:${index}`;
2502
+ const storageKey = this.getPersistedOrderStorageKey(rawOrder);
2503
+ const order = this.normalizeOrderCollectionsForIngress(rawOrder, 'loadOrdersFromSQLite');
2504
+ const group = groups.get(identity);
2505
+ if (group) {
2506
+ group.order = this.mergeStoredOrderCopies(group.order, order, authoritativeOrders.has(rawOrder));
2507
+ group.keys.add(storageKey);
2508
+ group.count += 1;
2509
+ } else {
2510
+ groups.set(identity, {
2511
+ order,
2512
+ keys: new Set([storageKey]),
2513
+ count: 1
2514
+ });
2515
+ }
2516
+ }
2517
+ const canonicalKeyCounts = new Map();
2518
+ for (const {
2519
+ order
2520
+ } of groups.values()) {
2521
+ const key = this.getOrderStorageKey(order);
2522
+ canonicalKeyCounts.set(key, (canonicalKeyCounts.get(key) || 0) + 1);
2523
+ }
2524
+ const list = [];
2525
+ const repairs = [];
2526
+ const obsoleteKeys = new Set();
2527
+ for (const group of groups.values()) {
2528
+ const key = this.getOrderStorageKey(group.order);
2529
+ const needsRepair = group.count > 1 || [...group.keys].some(oldKey => oldKey !== key);
2530
+ // 不同真实订单若错误地共用 external 编号,不允许修复写入互相覆盖。
2531
+ if (needsRepair && key && canonicalKeyCounts.get(key) === 1) {
2532
+ group.order = {
2533
+ ...group.order,
2534
+ [ORDER_STORAGE_KEY_FIELD]: key
2535
+ };
2536
+ repairs.push(group.order);
2537
+ for (const oldKey of group.keys) {
2538
+ if (oldKey && oldKey !== key && !canonicalKeyCounts.has(oldKey)) obsoleteKeys.add(oldKey);
2539
+ }
2540
+ }
2541
+ list.push(group.order);
2542
+ }
2543
+ return {
2544
+ list,
2545
+ repairs,
2546
+ obsoleteKeys
2547
+ };
2548
+ }
2549
+ mergeStoredOrderCopies(left, right, preferIncoming = false) {
2550
+ const priority = order => this.isPendingSyncOrder(order) ? 2 : this.isDraftOrder(order) ? 1 : 0;
2551
+ const leftHasExternal = !this.isBlankIdentityValue(left.external_sale_number);
2552
+ const rightHasExternal = !this.isBlankIdentityValue(right.external_sale_number);
2553
+ let preferred = leftHasExternal !== rightHasExternal ? leftHasExternal ? left : right : this.pickPreferredOrder(left, right);
2554
+ if (preferIncoming) {
2555
+ preferred = right;
2556
+ } else if (priority(left) !== priority(right)) {
2557
+ preferred = priority(left) > priority(right) ? left : right;
2558
+ } else {
2559
+ for (const field of ['updated_at', 'created_at']) {
2560
+ const timestamp = order => {
2561
+ const value = order[field];
2562
+ if (!value) return 0;
2563
+ const parsed = (0, _dayjs.default)(value);
2564
+ return parsed.isValid() ? parsed.valueOf() : 0;
2565
+ };
2566
+ if (timestamp(left) === timestamp(right)) continue;
2567
+ preferred = timestamp(left) > timestamp(right) ? left : right;
2568
+ break;
2569
+ }
2570
+ }
2571
+ const secondary = preferred === left ? right : left;
2572
+ // 复用集合合并中的 pending/finalized 支付保护,但完整业务快照以胜者为准。
2573
+ const reconciled = this.mergeOrderRecords(secondary, preferred);
2574
+ const merged = {
2575
+ ...reconciled,
2576
+ ...(0, _lodashEs.cloneDeep)(preferred)
2577
+ };
2578
+ const realOrder = this.getRealOrderId(preferred) ? preferred : secondary;
2579
+ if (this.getRealOrderId(realOrder)) merged.order_id = realOrder.order_id;
2580
+ for (const {
2581
+ field
2582
+ } of this.getOrderIdentityEntries(reconciled)) {
2583
+ if (this.isBlankIdentityValue(merged[field])) merged[field] = reconciled[field];
2584
+ }
2585
+ for (const field of ORDER_AUTHORITATIVE_COLLECTION_FIELDS) {
2586
+ if (Object.prototype.hasOwnProperty.call(reconciled, field)) merged[field] = reconciled[field];
2587
+ }
2588
+ if ((0, _localEftposState.requiresLocalPaymentRefresh)(secondary)) {
2589
+ merged.metadata = {
2590
+ ...merged.metadata,
2591
+ [_localEftposState.LOCAL_EFTPOS_REFRESH_REQUIRED]: true
2592
+ };
2593
+ }
2594
+ merged.need_sync = this.isPendingSyncOrder(left) || this.isPendingSyncOrder(right) ? 1 : 0;
2595
+ merged.is_draft_order = this.isDraftOrder(preferred) ? 1 : 0;
2596
+ return merged;
2597
+ }
2598
+ async writeOrderRowsToSQLite(orders) {
2599
+ if (typeof this.dbManager.bulkUpdate === 'function') {
2600
+ await this.dbManager.bulkUpdate(INDEXDB_STORE_NAME, orders);
2601
+ return 'bulkUpdate';
2602
+ }
2603
+ if (typeof this.dbManager.bulkAdd === 'function') {
2604
+ await this.dbManager.bulkAdd(INDEXDB_STORE_NAME, orders);
2605
+ return 'bulkAdd';
2606
+ }
2607
+ if (typeof this.dbManager.update === 'function') {
2608
+ for (const order of orders) await this.dbManager.update(INDEXDB_STORE_NAME, order);
2609
+ return 'update';
2610
+ }
2611
+ throw new Error('订单 SQLite 数据库不支持写入');
2612
+ }
2403
2613
  isPendingSyncOrder(order) {
2404
2614
  return Number(order?.need_sync) === 1;
2405
2615
  }
@@ -2496,7 +2706,7 @@ class OrderModule extends _BaseModule.BaseModule {
2496
2706
  const {
2497
2707
  toWrite,
2498
2708
  skipped
2499
- } = this.filterRedundantPatchOrders(source, ordersSnapshot, mergeActions, forceWriteStorageKeys);
2709
+ } = this.filterRedundantPatchOrders(source, ordersSnapshot, mergeActions, new Set([...forceWriteStorageKeys, ...migrationTargetStorageKeys]));
2500
2710
  if (toWrite.length === 0) {
2501
2711
  return;
2502
2712
  }
@@ -2519,20 +2729,7 @@ class OrderModule extends _BaseModule.BaseModule {
2519
2729
  count: compactedToWrite.length,
2520
2730
  dedupedCount: skipped.length
2521
2731
  });
2522
- if (typeof this.dbManager.bulkUpdate === 'function') {
2523
- writeMethod = 'bulkUpdate';
2524
- await this.dbManager.bulkUpdate(INDEXDB_STORE_NAME, compactedToWrite);
2525
- } else if (typeof this.dbManager.bulkAdd === 'function') {
2526
- writeMethod = 'bulkAdd';
2527
- await this.dbManager.bulkAdd(INDEXDB_STORE_NAME, compactedToWrite);
2528
- } else if (typeof this.dbManager.update === 'function') {
2529
- writeMethod = 'update';
2530
- for (const order of compactedToWrite) {
2531
- await this.dbManager.update(INDEXDB_STORE_NAME, order);
2532
- }
2533
- } else if (options.throwOnError) {
2534
- throw new Error('订单 SQLite 数据库不支持写入');
2535
- }
2732
+ writeMethod = await this.writeOrderRowsToSQLite(compactedToWrite);
2536
2733
  this.recordRecentSqliteWrite(source, compactedToWrite);
2537
2734
  if (writeMethod !== 'none') {
2538
2735
  for (const migration of storageKeyMigrations.values()) {