@pisell/pisellos 2.3.28 → 2.3.29

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 (84) hide show
  1. package/dist/model/strategy/adapter/dataVariant/adapter.d.ts +50 -0
  2. package/dist/model/strategy/adapter/dataVariant/adapter.js +167 -0
  3. package/dist/model/strategy/adapter/dataVariant/evaluator.d.ts +89 -0
  4. package/dist/model/strategy/adapter/dataVariant/evaluator.js +780 -0
  5. package/dist/model/strategy/adapter/dataVariant/examples.d.ts +39 -0
  6. package/dist/model/strategy/adapter/dataVariant/examples.js +277 -0
  7. package/dist/model/strategy/adapter/dataVariant/index.d.ts +4 -0
  8. package/dist/model/strategy/adapter/dataVariant/index.js +4 -0
  9. package/dist/model/strategy/adapter/dataVariant/type.d.ts +148 -0
  10. package/dist/model/strategy/adapter/dataVariant/type.js +54 -0
  11. package/dist/model/strategy/adapter/index.d.ts +4 -0
  12. package/dist/model/strategy/adapter/index.js +5 -1
  13. package/dist/model/strategy/adapter/promotion/index.js +0 -9
  14. package/dist/modules/Discount/index.d.ts +5 -2
  15. package/dist/modules/Discount/index.js +30 -7
  16. package/dist/modules/Discount/types.d.ts +4 -0
  17. package/dist/modules/Order/index.d.ts +7 -1
  18. package/dist/modules/Order/index.js +187 -74
  19. package/dist/modules/Order/types.d.ts +2 -0
  20. package/dist/modules/Order/utils/orderCollectionIdentity.d.ts +53 -0
  21. package/dist/modules/Order/utils/orderCollectionIdentity.js +405 -0
  22. package/dist/modules/Order/utils.d.ts +2 -1
  23. package/dist/modules/Order/utils.js +2 -8
  24. package/dist/modules/Product/types.d.ts +22 -0
  25. package/dist/modules/ProductList/index.d.ts +1 -1
  26. package/dist/modules/ProductList/index.js +4 -2
  27. package/dist/modules/ProductList/types.d.ts +2 -0
  28. package/dist/server/index.d.ts +50 -0
  29. package/dist/server/index.js +995 -749
  30. package/dist/server/modules/order/index.d.ts +10 -4
  31. package/dist/server/modules/order/index.js +404 -399
  32. package/dist/server/modules/products/index.d.ts +26 -7
  33. package/dist/server/modules/products/index.js +167 -76
  34. package/dist/server/modules/products/types.d.ts +14 -0
  35. package/dist/solution/BaseSales/index.d.ts +9 -1
  36. package/dist/solution/BaseSales/index.js +998 -756
  37. package/dist/solution/BaseSales/utils/parseSalesResponse.d.ts +3 -3
  38. package/dist/solution/BaseSales/utils/parseSalesResponse.js +6 -8
  39. package/dist/solution/BookingByStep/index.d.ts +1 -1
  40. package/dist/solution/BookingTicket/index.d.ts +14 -2
  41. package/dist/solution/BookingTicket/types.d.ts +2 -0
  42. package/dist/solution/ShopDiscount/index.js +15 -14
  43. package/lib/model/strategy/adapter/dataVariant/adapter.d.ts +50 -0
  44. package/lib/model/strategy/adapter/dataVariant/adapter.js +149 -0
  45. package/lib/model/strategy/adapter/dataVariant/evaluator.d.ts +89 -0
  46. package/lib/model/strategy/adapter/dataVariant/evaluator.js +583 -0
  47. package/lib/model/strategy/adapter/dataVariant/examples.d.ts +39 -0
  48. package/lib/model/strategy/adapter/dataVariant/examples.js +293 -0
  49. package/lib/model/strategy/adapter/dataVariant/index.d.ts +4 -0
  50. package/lib/model/strategy/adapter/dataVariant/index.js +38 -0
  51. package/lib/model/strategy/adapter/dataVariant/type.d.ts +148 -0
  52. package/lib/model/strategy/adapter/dataVariant/type.js +31 -0
  53. package/lib/model/strategy/adapter/index.d.ts +4 -0
  54. package/lib/model/strategy/adapter/index.js +13 -2
  55. package/lib/modules/Discount/index.d.ts +5 -2
  56. package/lib/modules/Discount/index.js +23 -3
  57. package/lib/modules/Discount/types.d.ts +4 -0
  58. package/lib/modules/Order/index.d.ts +7 -1
  59. package/lib/modules/Order/index.js +104 -6
  60. package/lib/modules/Order/types.d.ts +2 -0
  61. package/lib/modules/Order/utils/orderCollectionIdentity.d.ts +53 -0
  62. package/lib/modules/Order/utils/orderCollectionIdentity.js +415 -0
  63. package/lib/modules/Order/utils.d.ts +2 -1
  64. package/lib/modules/Order/utils.js +4 -11
  65. package/lib/modules/Product/types.d.ts +22 -0
  66. package/lib/modules/ProductList/index.d.ts +1 -1
  67. package/lib/modules/ProductList/index.js +4 -2
  68. package/lib/modules/ProductList/types.d.ts +2 -0
  69. package/lib/server/index.d.ts +50 -0
  70. package/lib/server/index.js +206 -29
  71. package/lib/server/modules/order/index.d.ts +10 -4
  72. package/lib/server/modules/order/index.js +198 -139
  73. package/lib/server/modules/products/index.d.ts +26 -7
  74. package/lib/server/modules/products/index.js +114 -35
  75. package/lib/server/modules/products/types.d.ts +14 -0
  76. package/lib/solution/BaseSales/index.d.ts +9 -1
  77. package/lib/solution/BaseSales/index.js +229 -54
  78. package/lib/solution/BaseSales/utils/parseSalesResponse.d.ts +3 -3
  79. package/lib/solution/BaseSales/utils/parseSalesResponse.js +4 -5
  80. package/lib/solution/BookingByStep/index.d.ts +1 -1
  81. package/lib/solution/BookingTicket/index.d.ts +14 -2
  82. package/lib/solution/BookingTicket/types.d.ts +2 -0
  83. package/lib/solution/ShopDiscount/index.js +2 -1
  84. package/package.json +1 -1
@@ -41,6 +41,7 @@ var import_cartPromotion = require("../../solution/BaseSales/utils/cartPromotion
41
41
  var import_utils3 = require("../../solution/ScanOrder/utils");
42
42
  var import_manualProductDiscount = require("./utils/manualProductDiscount");
43
43
  var import_bundleDiscountHydration = require("./utils/bundleDiscountHydration");
44
+ var import_orderCollectionIdentity = require("./utils/orderCollectionIdentity");
44
45
  var import_Discount = require("../Discount");
45
46
  var import_Rules = require("../Rules");
46
47
  var import_types2 = require("../Rules/types");
@@ -308,6 +309,9 @@ var OrderModule = class extends import_BaseModule.BaseModule {
308
309
  if (!this.store.summary) {
309
310
  this.store.summary = (0, import_utils.createEmptySummary)();
310
311
  }
312
+ if (!Array.isArray(this.store.availableWalletIds)) {
313
+ this.store.availableWalletIds = [];
314
+ }
311
315
  this.request = this.core.getPlugin("request");
312
316
  const appPlugin = this.core.getPlugin("app");
313
317
  if (!appPlugin) {
@@ -435,15 +439,19 @@ var OrderModule = class extends import_BaseModule.BaseModule {
435
439
  async loadDiscountConfig(params) {
436
440
  var _a, _b, _c, _d, _e, _f, _g;
437
441
  const orderId = params.orderId || ((_a = this.store.tempOrder) == null ? void 0 : _a.order_id) || void 0;
438
- const discountList = await ((_b = this.store.discount) == null ? void 0 : _b.loadPrepareConfig({
442
+ const prepareConfigResult = await ((_b = this.store.discount) == null ? void 0 : _b.loadPrepareConfig({
439
443
  customer_id: params.customerId,
440
444
  action: params.action || (orderId ? "edit" : "create"),
441
445
  with_good_pass: 1,
442
446
  with_discount_card: 1,
443
447
  with_wallet_pass_holder: 1,
448
+ with_available_wallet_flag: 1,
449
+ with_available_wallet_pass_flag: 1,
444
450
  request_timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
445
451
  ...orderId ? { order_id: orderId } : {}
446
452
  }));
453
+ const discountList = prepareConfigResult == null ? void 0 : prepareConfigResult.discountList;
454
+ this.store.availableWalletIds = (prepareConfigResult == null ? void 0 : prepareConfigResult.availableWalletIds) || [];
447
455
  if (discountList) {
448
456
  const currentDiscountList = ((_c = this.store.discount) == null ? void 0 : _c.getDiscountList()) || [];
449
457
  const currentEditDiscounts = currentDiscountList.filter((discount) => discount == null ? void 0 : discount.isEditMode);
@@ -477,6 +485,9 @@ var OrderModule = class extends import_BaseModule.BaseModule {
477
485
  var _a;
478
486
  return ((_a = this.store.discount) == null ? void 0 : _a.getDiscountList()) || [];
479
487
  }
488
+ getAvailableWalletIds() {
489
+ return Array.isArray(this.store.availableWalletIds) ? [...this.store.availableWalletIds] : [];
490
+ }
480
491
  async syncScannedDiscountsToOriginalDiscountList(discountList) {
481
492
  var _a, _b, _c, _d;
482
493
  const scanDiscounts = (discountList || []).filter((discount) => discount == null ? void 0 : discount.isScan);
@@ -2401,6 +2412,7 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2401
2412
  }
2402
2413
  const nextCustomerId = tempOrder.customer_id ?? null;
2403
2414
  if (String(previousCustomerId ?? "") !== String(nextCustomerId ?? "")) {
2415
+ this.store.availableWalletIds = [];
2404
2416
  (0, import_utils.clearTempOrderHolderAssignments)(tempOrder);
2405
2417
  this.clearCustomerBoundDiscounts(tempOrder);
2406
2418
  this.applyDiscount();
@@ -2440,6 +2452,7 @@ var OrderModule = class extends import_BaseModule.BaseModule {
2440
2452
  tempOrder.customer = null;
2441
2453
  if (tempOrder._extend)
2442
2454
  delete tempOrder._extend.customerSnapshot;
2455
+ this.store.availableWalletIds = [];
2443
2456
  this.clearCustomerBoundDiscounts(tempOrder);
2444
2457
  this.persistTempOrder();
2445
2458
  this.saveDraftInBackground();
@@ -4030,7 +4043,35 @@ var OrderModule = class extends import_BaseModule.BaseModule {
4030
4043
  */
4031
4044
  async hydrateTempOrderFromRecord(record, options) {
4032
4045
  var _a, _b, _c;
4033
- const raw = record && typeof record === "object" && record.data && record.order_id == null ? record.data : record || {};
4046
+ const sourceRaw = record && typeof record === "object" && record.data && record.order_id == null ? record.data : record || {};
4047
+ const identityReadySource = this.seedAnonymousBookingUidsFromProducts(
4048
+ sourceRaw
4049
+ );
4050
+ const normalizedCollections = (0, import_orderCollectionIdentity.normalizeOrderCollections)(identityReadySource);
4051
+ const raw = normalizedCollections.order;
4052
+ const hasIdentityChanges = Object.values(normalizedCollections.stats).some(
4053
+ (stats) => stats.backfilledUidCount > 0 || stats.collapsedDuplicateCount > 0 || stats.uidConflictCount > 0 || stats.anonymousRowCount > 0
4054
+ );
4055
+ if (hasIdentityChanges) {
4056
+ const identityLogMetadata = {
4057
+ collections: normalizedCollections.stats,
4058
+ uidRemapCount: normalizedCollections.uidRemaps.length
4059
+ };
4060
+ const hasIdentityWarnings = Object.values(normalizedCollections.stats).some(
4061
+ (stats) => stats.uidConflictCount > 0 || stats.anonymousRowCount > 0
4062
+ );
4063
+ if (hasIdentityWarnings) {
4064
+ this.logWarning(
4065
+ "Normalized hydrated order collection identities",
4066
+ identityLogMetadata
4067
+ );
4068
+ } else {
4069
+ this.logInfo(
4070
+ "Normalized hydrated order collection identities",
4071
+ identityLogMetadata
4072
+ );
4073
+ }
4074
+ }
4034
4075
  const nextTempOrder = this.normalizeTempOrderForRuntime(raw, { makeEditMark: true });
4035
4076
  const rawSummary = raw.summary && typeof raw.summary === "object" ? raw.summary : {};
4036
4077
  const summarySurcharges = Array.isArray(rawSummary.surcharges) ? rawSummary.surcharges.map((s) => ({ ...s || {} })) : (0, import_lodash_es.cloneDeep)(nextTempOrder.surcharges || []);
@@ -4045,13 +4086,14 @@ var OrderModule = class extends import_BaseModule.BaseModule {
4045
4086
  originalSalesSnapshot: {
4046
4087
  summary: (0, import_lodash_es.cloneDeep)(this.store.summary),
4047
4088
  products: (0, import_lodash_es.cloneDeep)(nextTempOrder.products || []),
4089
+ bookings: (0, import_lodash_es.cloneDeep)(nextTempOrder.bookings || []),
4048
4090
  payments: (0, import_lodash_es.cloneDeep)(nextTempOrder.payments || []),
4049
4091
  surcharges: (0, import_lodash_es.cloneDeep)(nextTempOrder.surcharges || []),
4050
4092
  shop_discount: nextTempOrder.shop_discount || "0.00",
4051
4093
  productFingerprint: this.buildOrderProductsFingerprint(nextTempOrder.products || [])
4052
4094
  }
4053
4095
  };
4054
- this.store.lastOrderInfo = raw.lastOrderInfo || raw;
4096
+ this.store.lastOrderInfo = sourceRaw.lastOrderInfo || sourceRaw;
4055
4097
  const hydratedEditDiscounts = this.collectHydratedEditDiscounts(nextTempOrder.products);
4056
4098
  const currentDiscounts = typeof ((_a = this.store.discount) == null ? void 0 : _a.getDiscountList) === "function" ? this.store.discount.getDiscountList() || [] : [];
4057
4099
  const currentScanDiscounts = currentDiscounts.filter((discount) => discount == null ? void 0 : discount.isScan);
@@ -4104,6 +4146,64 @@ var OrderModule = class extends import_BaseModule.BaseModule {
4104
4146
  }
4105
4147
  return next;
4106
4148
  }
4149
+ /**
4150
+ * 匿名 booking 没有服务端行 ID 时,商品侧已有的 booking_uid 就是唯一可用的强引用。
4151
+ * 在统一规范化生成 UUID 前先复用它;已落库 booking 仍按 schedule_event_id 派生稳定 UID。
4152
+ */
4153
+ seedAnonymousBookingUidsFromProducts(raw) {
4154
+ var _a, _b;
4155
+ if (!raw || typeof raw !== "object")
4156
+ return {};
4157
+ if (!Array.isArray(raw.bookings) || !Array.isArray(raw.products))
4158
+ return raw;
4159
+ const bookingUidsByProductUid = /* @__PURE__ */ new Map();
4160
+ for (const product of raw.products) {
4161
+ const productUid = (0, import_orderCollectionIdentity.getOrderCollectionUid)("product", product);
4162
+ const bookingUid = (product == null ? void 0 : product.booking_uid) || ((_a = product == null ? void 0 : product.metadata) == null ? void 0 : _a.booking_uid);
4163
+ if (!productUid || bookingUid === void 0 || bookingUid === null || bookingUid === "") {
4164
+ continue;
4165
+ }
4166
+ const candidates = bookingUidsByProductUid.get(productUid) || /* @__PURE__ */ new Set();
4167
+ candidates.add(String(bookingUid));
4168
+ bookingUidsByProductUid.set(productUid, candidates);
4169
+ }
4170
+ if (bookingUidsByProductUid.size === 0)
4171
+ return raw;
4172
+ const anonymousBookingCountByProductUid = /* @__PURE__ */ new Map();
4173
+ for (const booking of raw.bookings) {
4174
+ if ((0, import_orderCollectionIdentity.getOrderCollectionPersistentId)("booking", booking) || (0, import_orderCollectionIdentity.getOrderCollectionUid)("booking", booking)) {
4175
+ continue;
4176
+ }
4177
+ const productUid = (booking == null ? void 0 : booking.product_uid) || ((_b = booking == null ? void 0 : booking.metadata) == null ? void 0 : _b.product_uid);
4178
+ if (productUid === void 0 || productUid === null || productUid === "")
4179
+ continue;
4180
+ const key = String(productUid);
4181
+ anonymousBookingCountByProductUid.set(
4182
+ key,
4183
+ (anonymousBookingCountByProductUid.get(key) || 0) + 1
4184
+ );
4185
+ }
4186
+ return {
4187
+ ...raw,
4188
+ bookings: raw.bookings.map((booking) => {
4189
+ var _a2;
4190
+ if ((0, import_orderCollectionIdentity.getOrderCollectionPersistentId)("booking", booking) || (0, import_orderCollectionIdentity.getOrderCollectionUid)("booking", booking)) {
4191
+ return booking;
4192
+ }
4193
+ const productUid = (booking == null ? void 0 : booking.product_uid) || ((_a2 = booking == null ? void 0 : booking.metadata) == null ? void 0 : _a2.product_uid);
4194
+ if (productUid === void 0 || productUid === null || productUid === "") {
4195
+ return booking;
4196
+ }
4197
+ const productUidKey = String(productUid);
4198
+ if (anonymousBookingCountByProductUid.get(productUidKey) !== 1) {
4199
+ return booking;
4200
+ }
4201
+ const bookingUidCandidates = bookingUidsByProductUid.get(productUidKey);
4202
+ const bookingUid = (bookingUidCandidates == null ? void 0 : bookingUidCandidates.size) === 1 ? [...bookingUidCandidates][0] : null;
4203
+ return bookingUid ? (0, import_orderCollectionIdentity.setOrderCollectionUid)("booking", booking, bookingUid) : booking;
4204
+ })
4205
+ };
4206
+ }
4107
4207
  normalizeTempOrderForRuntime(raw, options) {
4108
4208
  var _a, _b;
4109
4209
  const nextTempOrder = {
@@ -4218,9 +4318,7 @@ var OrderModule = class extends import_BaseModule.BaseModule {
4218
4318
  if (!product.metadata || typeof product.metadata !== "object") {
4219
4319
  product.metadata = {};
4220
4320
  }
4221
- const linkedBookingUid = String(
4222
- product.booking_uid || product.metadata.booking_uid || bookingUid
4223
- );
4321
+ const linkedBookingUid = String(bookingUid);
4224
4322
  product.booking_uid = linkedBookingUid;
4225
4323
  product.metadata.booking_uid = linkedBookingUid;
4226
4324
  });
@@ -309,6 +309,7 @@ export interface OrderState {
309
309
  lastOrderInfo?: Record<string, any>;
310
310
  syncState?: OrderSyncState;
311
311
  discountList: any[];
312
+ availableWalletIds?: number[];
312
313
  discount: DiscountModule | null;
313
314
  rules: RulesModule | null;
314
315
  }
@@ -775,6 +776,7 @@ export interface OrderModuleAPI {
775
776
  apply?: boolean;
776
777
  }) => Promise<Discount[]>;
777
778
  getDiscountList: () => Discount[];
779
+ getAvailableWalletIds: () => number[];
778
780
  applyDiscount: () => void;
779
781
  /**
780
782
  * 注入促销评估器。
@@ -0,0 +1,53 @@
1
+ export type OrderCollectionKind = 'product' | 'booking' | 'payment';
2
+ export interface OrderCollectionIdentityStats {
3
+ backfilledUidCount: number;
4
+ collapsedDuplicateCount: number;
5
+ uidConflictCount: number;
6
+ anonymousRowCount: number;
7
+ }
8
+ export interface OrderCollectionUidRemap {
9
+ kind: OrderCollectionKind;
10
+ from: string;
11
+ to: string;
12
+ persistentId: string | null;
13
+ /** 默认全局迁移;UID 冲突时只能迁移能由另一侧 UID 明确定位的引用。 */
14
+ scope?: 'global' | 'linked-owner';
15
+ referenceOwnerUid?: string | null;
16
+ }
17
+ export interface NormalizeOrderCollectionResult<T> {
18
+ items: T[];
19
+ stats: OrderCollectionIdentityStats;
20
+ uidRemaps: OrderCollectionUidRemap[];
21
+ }
22
+ export interface NormalizeOrderCollectionsResult<T> {
23
+ order: T;
24
+ stats: Record<OrderCollectionKind, OrderCollectionIdentityStats>;
25
+ uidRemaps: OrderCollectionUidRemap[];
26
+ }
27
+ export declare function createUuidV4(): string;
28
+ export declare function isBlankOrderCollectionIdentity(value: unknown): boolean;
29
+ export declare function getOrderCollectionPersistentId(kind: OrderCollectionKind, item: unknown): string | null;
30
+ export declare function getOrderCollectionUid(kind: OrderCollectionKind, item: unknown): string | null;
31
+ export declare function buildOrderCollectionFallbackUid(kind: OrderCollectionKind, persistentId: string | number): string;
32
+ export declare function getOrderCollectionReferenceUid(kind: OrderCollectionKind, item: unknown): string | null;
33
+ export declare function setOrderCollectionUid<T>(kind: OrderCollectionKind, item: T, uid: string): T;
34
+ /**
35
+ * 持久化行 ID 是服务端事实主键;只有至少一侧尚未持久化时,才允许用 runtime UID 对齐。
36
+ */
37
+ export declare function isSameOrderCollectionItem(kind: OrderCollectionKind, left: unknown, right: unknown): boolean;
38
+ export declare function mergeOrderCollectionItems<T>(kind: OrderCollectionKind, currentItem: T, incomingItem: T, options?: {
39
+ ensureUid?: boolean;
40
+ createAnonymousUid?: () => string;
41
+ }): T;
42
+ /**
43
+ * 规范化单一数组:强身份重复时保留首次位置、用最后一条业务字段覆盖,并统一补 UID。
44
+ */
45
+ export declare function normalizeOrderCollection<T>(kind: OrderCollectionKind, items: T[] | null | undefined, options?: {
46
+ ensureUid?: boolean;
47
+ createAnonymousUid?: () => string;
48
+ }): NormalizeOrderCollectionResult<T>;
49
+ export declare function applyOrderCollectionUidRemaps<T extends Record<string, any>>(sourceOrder: T, uidRemaps: OrderCollectionUidRemap[]): T;
50
+ export declare function normalizeOrderCollections<T extends Record<string, any>>(sourceOrder: T, options?: {
51
+ ensureUid?: boolean;
52
+ createAnonymousUid?: () => string;
53
+ }): NormalizeOrderCollectionsResult<T>;
@@ -0,0 +1,415 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/modules/Order/utils/orderCollectionIdentity.ts
20
+ var orderCollectionIdentity_exports = {};
21
+ __export(orderCollectionIdentity_exports, {
22
+ applyOrderCollectionUidRemaps: () => applyOrderCollectionUidRemaps,
23
+ buildOrderCollectionFallbackUid: () => buildOrderCollectionFallbackUid,
24
+ createUuidV4: () => createUuidV4,
25
+ getOrderCollectionPersistentId: () => getOrderCollectionPersistentId,
26
+ getOrderCollectionReferenceUid: () => getOrderCollectionReferenceUid,
27
+ getOrderCollectionUid: () => getOrderCollectionUid,
28
+ isBlankOrderCollectionIdentity: () => isBlankOrderCollectionIdentity,
29
+ isSameOrderCollectionItem: () => isSameOrderCollectionItem,
30
+ mergeOrderCollectionItems: () => mergeOrderCollectionItems,
31
+ normalizeOrderCollection: () => normalizeOrderCollection,
32
+ normalizeOrderCollections: () => normalizeOrderCollections,
33
+ setOrderCollectionUid: () => setOrderCollectionUid
34
+ });
35
+ module.exports = __toCommonJS(orderCollectionIdentity_exports);
36
+ var import_lodash_es = require("lodash-es");
37
+ var IDENTITY_CONFIG = {
38
+ product: {
39
+ persistentIdField: "order_detail_id",
40
+ uidField: "unique_identification_number",
41
+ fallbackPrefix: "os-fallback:product:order-detail"
42
+ },
43
+ booking: {
44
+ persistentIdField: "schedule_event_id",
45
+ uidField: "unique_identification_number",
46
+ fallbackPrefix: "os-fallback:booking:schedule-event"
47
+ },
48
+ payment: {
49
+ persistentIdField: "order_payment_id",
50
+ uidField: "unique_payment_number",
51
+ fallbackPrefix: "os-fallback:payment:order-payment"
52
+ }
53
+ };
54
+ function createUuidV4() {
55
+ const template = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
56
+ return template.replace(/[xy]/g, (char) => {
57
+ const randomValue = Math.floor(Math.random() * 16);
58
+ const value = char === "x" ? randomValue : randomValue & 3 | 8;
59
+ return value.toString(16);
60
+ });
61
+ }
62
+ function isBlankOrderCollectionIdentity(value) {
63
+ return value === void 0 || value === null || value === "";
64
+ }
65
+ function getOrderCollectionPersistentId(kind, item) {
66
+ const record = item;
67
+ if (!record)
68
+ return null;
69
+ const value = record[IDENTITY_CONFIG[kind].persistentIdField];
70
+ if (isBlankOrderCollectionIdentity(value))
71
+ return null;
72
+ return String(value);
73
+ }
74
+ function getOrderCollectionUid(kind, item) {
75
+ var _a;
76
+ const record = item;
77
+ if (!record)
78
+ return null;
79
+ const uidField = IDENTITY_CONFIG[kind].uidField;
80
+ const metadataValue = (_a = record.metadata) == null ? void 0 : _a[uidField];
81
+ if (!isBlankOrderCollectionIdentity(metadataValue))
82
+ return String(metadataValue);
83
+ const topLevelValue = record[uidField];
84
+ if (isBlankOrderCollectionIdentity(topLevelValue))
85
+ return null;
86
+ return String(topLevelValue);
87
+ }
88
+ function buildOrderCollectionFallbackUid(kind, persistentId) {
89
+ return `${IDENTITY_CONFIG[kind].fallbackPrefix}:${String(persistentId)}`;
90
+ }
91
+ function getOrderCollectionReferenceUid(kind, item) {
92
+ const uid = getOrderCollectionUid(kind, item);
93
+ if (uid)
94
+ return uid;
95
+ const persistentId = getOrderCollectionPersistentId(kind, item);
96
+ return persistentId ? buildOrderCollectionFallbackUid(kind, persistentId) : null;
97
+ }
98
+ function setOrderCollectionUid(kind, item, uid) {
99
+ const record = (0, import_lodash_es.cloneDeep)(item || {});
100
+ const uidField = IDENTITY_CONFIG[kind].uidField;
101
+ record.metadata = {
102
+ ...record.metadata && typeof record.metadata === "object" ? record.metadata : {},
103
+ [uidField]: uid
104
+ };
105
+ delete record[uidField];
106
+ return record;
107
+ }
108
+ function isSameOrderCollectionItem(kind, left, right) {
109
+ const leftPersistentId = getOrderCollectionPersistentId(kind, left);
110
+ const rightPersistentId = getOrderCollectionPersistentId(kind, right);
111
+ if (leftPersistentId && rightPersistentId) {
112
+ return leftPersistentId === rightPersistentId;
113
+ }
114
+ const leftUid = getOrderCollectionUid(kind, left);
115
+ const rightUid = getOrderCollectionUid(kind, right);
116
+ return Boolean(leftUid && rightUid && leftUid === rightUid);
117
+ }
118
+ function mergeOrderCollectionItems(kind, currentItem, incomingItem, options) {
119
+ var _a;
120
+ const current = (0, import_lodash_es.cloneDeep)(currentItem || {});
121
+ const incoming = (0, import_lodash_es.cloneDeep)(incomingItem || {});
122
+ const persistentIdField = IDENTITY_CONFIG[kind].persistentIdField;
123
+ const currentPersistentIdValue = current[persistentIdField];
124
+ const incomingPersistentIdValue = incoming[persistentIdField];
125
+ const incomingUid = getOrderCollectionUid(kind, incoming);
126
+ const currentUid = getOrderCollectionUid(kind, current);
127
+ const persistentId = getOrderCollectionPersistentId(kind, incoming) || getOrderCollectionPersistentId(kind, current);
128
+ const merged = {
129
+ ...current,
130
+ ...incoming,
131
+ metadata: {
132
+ ...current.metadata && typeof current.metadata === "object" ? current.metadata : {},
133
+ ...incoming.metadata && typeof incoming.metadata === "object" ? incoming.metadata : {}
134
+ }
135
+ };
136
+ if (!isBlankOrderCollectionIdentity(incomingPersistentIdValue)) {
137
+ merged[persistentIdField] = incomingPersistentIdValue;
138
+ } else if (!isBlankOrderCollectionIdentity(currentPersistentIdValue)) {
139
+ merged[persistentIdField] = currentPersistentIdValue;
140
+ }
141
+ const incomingUidIsDerived = Boolean(
142
+ incomingUid && persistentId && (incomingUid === buildOrderCollectionFallbackUid(kind, persistentId) || incomingUid.startsWith(`${buildOrderCollectionFallbackUid(kind, persistentId)}:conflict:`))
143
+ );
144
+ const uid = (incomingUid && !incomingUidIsDerived ? incomingUid : null) || currentUid || incomingUid || ((options == null ? void 0 : options.ensureUid) === false ? null : persistentId ? buildOrderCollectionFallbackUid(kind, persistentId) : ((_a = options == null ? void 0 : options.createAnonymousUid) == null ? void 0 : _a.call(options)) || createUuidV4());
145
+ return uid ? setOrderCollectionUid(kind, merged, uid) : merged;
146
+ }
147
+ function createEmptyIdentityStats() {
148
+ return {
149
+ backfilledUidCount: 0,
150
+ collapsedDuplicateCount: 0,
151
+ uidConflictCount: 0,
152
+ anonymousRowCount: 0
153
+ };
154
+ }
155
+ function allocateAnonymousUid(occupiedUids, createAnonymousUid) {
156
+ let uid = createAnonymousUid();
157
+ while (occupiedUids.has(uid))
158
+ uid = createAnonymousUid();
159
+ return uid;
160
+ }
161
+ function allocatePersistentConflictUid(kind, persistentId, occupiedUids) {
162
+ const fallbackUid = buildOrderCollectionFallbackUid(kind, persistentId);
163
+ if (!occupiedUids.has(fallbackUid))
164
+ return fallbackUid;
165
+ let suffix = 1;
166
+ let candidate = `${fallbackUid}:conflict:${suffix}`;
167
+ while (occupiedUids.has(candidate)) {
168
+ suffix += 1;
169
+ candidate = `${fallbackUid}:conflict:${suffix}`;
170
+ }
171
+ return candidate;
172
+ }
173
+ function normalizeOrderCollection(kind, items, options) {
174
+ var _a, _b;
175
+ const stats = createEmptyIdentityStats();
176
+ const uidRemaps = [];
177
+ const result = [];
178
+ const ensureUid = (options == null ? void 0 : options.ensureUid) !== false;
179
+ const createAnonymousUid = (options == null ? void 0 : options.createAnonymousUid) || createUuidV4;
180
+ for (const rawItem of items || []) {
181
+ const item = (0, import_lodash_es.cloneDeep)(rawItem);
182
+ const existingIndex = result.findIndex(
183
+ (existing) => isSameOrderCollectionItem(kind, existing, item)
184
+ );
185
+ if (existingIndex === -1) {
186
+ result.push(item);
187
+ continue;
188
+ }
189
+ const previousReferenceUid = getOrderCollectionReferenceUid(
190
+ kind,
191
+ result[existingIndex]
192
+ );
193
+ const incomingReferenceUid = getOrderCollectionReferenceUid(kind, item);
194
+ result[existingIndex] = mergeOrderCollectionItems(
195
+ kind,
196
+ result[existingIndex],
197
+ item,
198
+ { ensureUid: false }
199
+ );
200
+ const nextUid = getOrderCollectionUid(kind, result[existingIndex]);
201
+ if (nextUid) {
202
+ for (const from of /* @__PURE__ */ new Set([previousReferenceUid, incomingReferenceUid])) {
203
+ if (!from || from === nextUid)
204
+ continue;
205
+ uidRemaps.push({
206
+ kind,
207
+ from,
208
+ to: nextUid,
209
+ persistentId: getOrderCollectionPersistentId(kind, result[existingIndex])
210
+ });
211
+ }
212
+ }
213
+ stats.collapsedDuplicateCount += 1;
214
+ }
215
+ if (!ensureUid)
216
+ return { items: result, stats, uidRemaps };
217
+ const occupiedUids = /* @__PURE__ */ new Set();
218
+ for (let index = 0; index < result.length; index += 1) {
219
+ let item = result[index];
220
+ const persistentId = getOrderCollectionPersistentId(kind, item);
221
+ let uid = getOrderCollectionUid(kind, item);
222
+ if (!uid) {
223
+ uid = persistentId ? buildOrderCollectionFallbackUid(kind, persistentId) : allocateAnonymousUid(occupiedUids, createAnonymousUid);
224
+ item = setOrderCollectionUid(kind, item, uid);
225
+ result[index] = item;
226
+ stats.backfilledUidCount += 1;
227
+ if (!persistentId)
228
+ stats.anonymousRowCount += 1;
229
+ }
230
+ if (occupiedUids.has(uid)) {
231
+ const replacementUid = persistentId ? allocatePersistentConflictUid(kind, persistentId, occupiedUids) : allocateAnonymousUid(occupiedUids, createAnonymousUid);
232
+ result[index] = setOrderCollectionUid(kind, item, replacementUid);
233
+ uidRemaps.push({
234
+ kind,
235
+ from: uid,
236
+ to: replacementUid,
237
+ persistentId,
238
+ scope: "linked-owner",
239
+ referenceOwnerUid: kind === "product" ? String(
240
+ (item == null ? void 0 : item.booking_uid) || ((_a = item == null ? void 0 : item.metadata) == null ? void 0 : _a.booking_uid) || ""
241
+ ) || null : kind === "booking" ? String(
242
+ (item == null ? void 0 : item.product_uid) || ((_b = item == null ? void 0 : item.metadata) == null ? void 0 : _b.product_uid) || ""
243
+ ) || null : null
244
+ });
245
+ uid = replacementUid;
246
+ stats.uidConflictCount += 1;
247
+ }
248
+ occupiedUids.add(uid);
249
+ }
250
+ return { items: result, stats, uidRemaps };
251
+ }
252
+ function applyOrderCollectionUidRemaps(sourceOrder, uidRemaps) {
253
+ var _a, _b, _c, _d, _e;
254
+ if (!uidRemaps.length)
255
+ return sourceOrder;
256
+ const order = (0, import_lodash_es.cloneDeep)(sourceOrder);
257
+ const hasAmbiguousLinkedOwner = (remap) => {
258
+ if (remap.scope !== "linked-owner" || !remap.referenceOwnerUid)
259
+ return false;
260
+ const ownerKind = remap.kind === "product" ? "booking" : remap.kind === "booking" ? "product" : null;
261
+ if (!ownerKind)
262
+ return false;
263
+ return uidRemaps.some(
264
+ (candidate) => candidate.scope === "linked-owner" && candidate.kind === ownerKind && candidate.from === remap.referenceOwnerUid
265
+ );
266
+ };
267
+ for (const remap of uidRemaps) {
268
+ if (remap.from === remap.to)
269
+ continue;
270
+ const linkedOwnerIsAmbiguous = hasAmbiguousLinkedOwner(remap);
271
+ if (remap.kind === "product") {
272
+ for (const booking of order.bookings || []) {
273
+ if (remap.scope === "linked-owner" && (linkedOwnerIsAmbiguous || getOrderCollectionUid("booking", booking) !== remap.referenceOwnerUid)) {
274
+ continue;
275
+ }
276
+ if (String((booking == null ? void 0 : booking.product_uid) || "") === remap.from) {
277
+ booking.product_uid = remap.to;
278
+ }
279
+ if (String(((_a = booking == null ? void 0 : booking.metadata) == null ? void 0 : _a.product_uid) || "") === remap.from) {
280
+ booking.metadata = { ...booking.metadata || {}, product_uid: remap.to };
281
+ }
282
+ }
283
+ if (remap.scope !== "linked-owner") {
284
+ for (const product of order.products || []) {
285
+ if (String(((_b = product == null ? void 0 : product.metadata) == null ? void 0 : _b.parent_unique_identification_number) || "") === remap.from) {
286
+ product.metadata = {
287
+ ...product.metadata || {},
288
+ parent_unique_identification_number: remap.to
289
+ };
290
+ }
291
+ const giftInfo = (_c = product == null ? void 0 : product.metadata) == null ? void 0 : _c._giftInfo;
292
+ if (giftInfo && typeof giftInfo === "object") {
293
+ const sourceProductIds = Array.isArray(giftInfo.sourceProductIds) ? giftInfo.sourceProductIds.map(
294
+ (uid) => String(uid) === remap.from ? remap.to : uid
295
+ ) : giftInfo.sourceProductIds;
296
+ const sourceProductId = String(giftInfo.sourceProductId || "") === remap.from ? remap.to : giftInfo.sourceProductId;
297
+ product.metadata = {
298
+ ...product.metadata || {},
299
+ _giftInfo: {
300
+ ...giftInfo,
301
+ ...sourceProductIds !== void 0 ? { sourceProductIds } : {},
302
+ ...sourceProductId !== void 0 ? { sourceProductId } : {}
303
+ }
304
+ };
305
+ }
306
+ }
307
+ }
308
+ const productsByUid = (_d = order._extend) == null ? void 0 : _d.productsByUid;
309
+ const cachedProduct = productsByUid == null ? void 0 : productsByUid[remap.from];
310
+ const cachedPersistentId = getOrderCollectionPersistentId(
311
+ "product",
312
+ (cachedProduct == null ? void 0 : cachedProduct.origin) || cachedProduct
313
+ );
314
+ if (productsByUid && remap.scope === "linked-owner") {
315
+ const retainedProduct = (order.products || []).find(
316
+ (product) => getOrderCollectionUid("product", product) === remap.from
317
+ );
318
+ const remappedProduct = (order.products || []).find(
319
+ (product) => getOrderCollectionUid("product", product) === remap.to
320
+ );
321
+ if (cachedProduct && remap.persistentId && cachedPersistentId === remap.persistentId) {
322
+ productsByUid[remap.to] = {
323
+ ...cachedProduct || {},
324
+ ...productsByUid[remap.to] || {}
325
+ };
326
+ if (retainedProduct) {
327
+ productsByUid[remap.from] = {
328
+ ...cachedProduct || {},
329
+ origin: (0, import_lodash_es.cloneDeep)(retainedProduct)
330
+ };
331
+ }
332
+ } else if (remappedProduct && !productsByUid[remap.to]) {
333
+ productsByUid[remap.to] = { origin: (0, import_lodash_es.cloneDeep)(remappedProduct) };
334
+ }
335
+ continue;
336
+ }
337
+ if (cachedProduct && remap.scope !== "linked-owner") {
338
+ productsByUid[remap.to] = {
339
+ ...cachedProduct || {},
340
+ ...productsByUid[remap.to] || {}
341
+ };
342
+ delete productsByUid[remap.from];
343
+ }
344
+ }
345
+ if (remap.kind === "booking") {
346
+ for (const product of order.products || []) {
347
+ if (remap.scope === "linked-owner" && (linkedOwnerIsAmbiguous || getOrderCollectionUid("product", product) !== remap.referenceOwnerUid)) {
348
+ continue;
349
+ }
350
+ if (String((product == null ? void 0 : product.booking_uid) || "") === remap.from) {
351
+ product.booking_uid = remap.to;
352
+ }
353
+ if (String(((_e = product == null ? void 0 : product.metadata) == null ? void 0 : _e.booking_uid) || "") === remap.from) {
354
+ product.metadata = { ...product.metadata || {}, booking_uid: remap.to };
355
+ }
356
+ }
357
+ }
358
+ }
359
+ return order;
360
+ }
361
+ function normalizeOrderCollections(sourceOrder, options) {
362
+ let order = (0, import_lodash_es.cloneDeep)(sourceOrder || {});
363
+ const orderRecord = order;
364
+ const productResult = normalizeOrderCollection(
365
+ "product",
366
+ Array.isArray(orderRecord.products) ? orderRecord.products : [],
367
+ options
368
+ );
369
+ const bookingResult = normalizeOrderCollection(
370
+ "booking",
371
+ Array.isArray(orderRecord.bookings) ? orderRecord.bookings : [],
372
+ options
373
+ );
374
+ const paymentResult = normalizeOrderCollection(
375
+ "payment",
376
+ Array.isArray(orderRecord.payments) ? orderRecord.payments : [],
377
+ options
378
+ );
379
+ if (Array.isArray(orderRecord.products))
380
+ orderRecord.products = productResult.items;
381
+ if (Array.isArray(orderRecord.bookings))
382
+ orderRecord.bookings = bookingResult.items;
383
+ if (Array.isArray(orderRecord.payments))
384
+ orderRecord.payments = paymentResult.items;
385
+ const uidRemaps = [
386
+ ...productResult.uidRemaps,
387
+ ...bookingResult.uidRemaps,
388
+ ...paymentResult.uidRemaps
389
+ ];
390
+ order = applyOrderCollectionUidRemaps(order, uidRemaps);
391
+ return {
392
+ order,
393
+ stats: {
394
+ product: productResult.stats,
395
+ booking: bookingResult.stats,
396
+ payment: paymentResult.stats
397
+ },
398
+ uidRemaps
399
+ };
400
+ }
401
+ // Annotate the CommonJS export names for ESM import in node:
402
+ 0 && (module.exports = {
403
+ applyOrderCollectionUidRemaps,
404
+ buildOrderCollectionFallbackUid,
405
+ createUuidV4,
406
+ getOrderCollectionPersistentId,
407
+ getOrderCollectionReferenceUid,
408
+ getOrderCollectionUid,
409
+ isBlankOrderCollectionIdentity,
410
+ isSameOrderCollectionItem,
411
+ mergeOrderCollectionItems,
412
+ normalizeOrderCollection,
413
+ normalizeOrderCollections,
414
+ setOrderCollectionUid
415
+ });