@pisell/pisellos 0.10.94 → 0.10.95

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.
@@ -38,6 +38,7 @@ class SalesSummaryModule extends _BaseModule.BaseModule {
38
38
  surchargeListModuleName = 'surchargeList';
39
39
  otherParams = {};
40
40
  surchargeListChannel = DEFAULT_SURCHARGE_CHANNEL;
41
+ surchargeLoads = new Map();
41
42
  constructor(name, version) {
42
43
  super(name, version);
43
44
  }
@@ -47,6 +48,7 @@ class SalesSummaryModule extends _BaseModule.BaseModule {
47
48
  this.appPlugin = this.core.getPlugin('app');
48
49
  this.request = this.core.getPlugin('request');
49
50
  this.otherParams = options.otherParams || {};
51
+ this.surchargeLoads = new Map();
50
52
  this.store.surchargeList = options.initialState?.surchargeList || [];
51
53
  this.store.summary = options.initialState?.summary || (0, _utils.createEmptySalesSummary)();
52
54
  this.surchargeListModuleName = this.otherParams?.surchargeListModuleName || 'surchargeList';
@@ -70,10 +72,11 @@ class SalesSummaryModule extends _BaseModule.BaseModule {
70
72
  const previousChannel = this.resolveChannel();
71
73
  const nextSurchargeListModuleName = params?.surchargeListModuleName || 'surchargeList';
72
74
  const nextChannel = this.resolveChannel(params);
73
- const shouldReload = nextSurchargeListModuleName !== this.surchargeListModuleName || nextChannel !== previousChannel;
75
+ const sourceChanged = nextSurchargeListModuleName !== this.surchargeListModuleName || (params?.shopId ?? params?.shop_id) !== (this.otherParams.shopId ?? this.otherParams.shop_id) || (params?.tenantId ?? params?.tenant_id) !== (this.otherParams.tenantId ?? this.otherParams.tenant_id);
74
76
  this.otherParams = params || {};
75
77
  this.surchargeListModuleName = nextSurchargeListModuleName;
76
- if (shouldReload) {
78
+ if (sourceChanged) this.surchargeLoads = new Map();
79
+ if (sourceChanged || nextChannel !== previousChannel) {
77
80
  await this.getSurchargeList(nextChannel);
78
81
  }
79
82
  }
@@ -81,14 +84,33 @@ class SalesSummaryModule extends _BaseModule.BaseModule {
81
84
  return params?.channel || DEFAULT_SURCHARGE_CHANNEL;
82
85
  }
83
86
  async getSurchargeList(channel = this.resolveChannel()) {
87
+ await this.loadSurcharges(channel);
88
+ }
89
+ loadSurcharges(channel) {
90
+ this.surchargeListChannel = channel;
91
+ const loads = this.surchargeLoads;
92
+ const pending = loads.get(channel);
93
+ if (pending) return pending;
94
+
95
+ // The core exposes the summary module while initialization is still pending.
96
+ // All calculations for this channel must wait for the same configuration, even when it is empty.
97
+ const load = this.fetchSurcharges(channel).then(list => {
98
+ loads.delete(channel);
99
+ if (loads === this.surchargeLoads && channel === this.surchargeListChannel) {
100
+ this.store.surchargeList = list;
101
+ }
102
+ return list;
103
+ });
104
+ loads.set(channel, load);
105
+ return load;
106
+ }
107
+ async fetchSurcharges(channel) {
84
108
  try {
85
109
  const surchargeListModule = this.core.getModule(this.surchargeListModuleName);
86
110
  if (surchargeListModule?.getSurchargeList) {
87
- this.store.surchargeList = await surchargeListModule.getSurchargeList({
111
+ return await surchargeListModule.getSurchargeList({
88
112
  channel
89
113
  });
90
- this.surchargeListChannel = channel;
91
- return;
92
114
  }
93
115
  const surchargeList = await this.request.get('/order/custom-surcharge/available/v2', {
94
116
  channel,
@@ -96,12 +118,10 @@ class SalesSummaryModule extends _BaseModule.BaseModule {
96
118
  is_assemble_schedule_data: 1,
97
119
  with: ['relationSchedule']
98
120
  });
99
- this.store.surchargeList = surchargeList?.data || [];
100
- this.surchargeListChannel = channel;
121
+ return surchargeList?.data || [];
101
122
  } catch (error) {
102
123
  console.warn('[SalesSummaryModule] 加载附加费配置失败', error);
103
- this.store.surchargeList = [];
104
- this.surchargeListChannel = channel;
124
+ return [];
105
125
  }
106
126
  }
107
127
  getAppData(key) {
@@ -130,14 +150,13 @@ class SalesSummaryModule extends _BaseModule.BaseModule {
130
150
  virtualSettlementMode = false
131
151
  } = params;
132
152
  const summaryChannel = channel || this.resolveChannel();
133
- if (summaryChannel !== this.surchargeListChannel) {
134
- await this.getSurchargeList(summaryChannel);
135
- }
153
+ const loads = this.surchargeLoads;
154
+ const surchargeList = loads.has(summaryChannel) || summaryChannel !== this.surchargeListChannel ? await this.loadSurcharges(summaryChannel) : this.store.surchargeList;
136
155
  const taxConfig = this.getTaxConfig();
137
156
  const fatherModuleName = this.otherParams?.fatherModule || this.name.replace(/_salesSummary$/, '');
138
157
  const scheduleModuleName = `${fatherModuleName}_schedule`;
139
158
  const summarySchedule = this.core.getModule(scheduleModuleName);
140
- const needScheduleIds = (this.store.surchargeList?.map(item => item.available_schedule_ids)?.flat() || []).filter(id => id !== undefined && id !== null && id !== '');
159
+ const needScheduleIds = (surchargeList?.map(item => item.available_schedule_ids)?.flat() || []).filter(id => id !== undefined && id !== null && id !== '');
141
160
  const scheduleList = needScheduleIds.length > 0 ? summarySchedule?.getScheduleListByIds(needScheduleIds) : [];
142
161
  const scheduleById = {};
143
162
  if (Array.isArray(scheduleList)) {
@@ -149,7 +168,7 @@ class SalesSummaryModule extends _BaseModule.BaseModule {
149
168
  products,
150
169
  isPriceIncludeTax: isPriceIncludeTax ?? taxConfig.isPriceIncludeTax ?? 1,
151
170
  taxRate: taxRate ?? taxConfig.taxRate,
152
- surchargeList: this.store.surchargeList,
171
+ surchargeList,
153
172
  scheduleById,
154
173
  isInScheduleByDate: _Schedule.ScheduleModule.isInScheduleByDate,
155
174
  shopDiscount,
@@ -161,7 +180,9 @@ class SalesSummaryModule extends _BaseModule.BaseModule {
161
180
  tax_rate: taxRate ?? taxConfig.taxRate,
162
181
  tax_country_code: taxConfig.taxCountryCode || ''
163
182
  };
164
- this.store.summary = summaryWithTaxMeta;
183
+ if (loads === this.surchargeLoads && summaryChannel === this.surchargeListChannel) {
184
+ this.store.summary = summaryWithTaxMeta;
185
+ }
165
186
  return summaryWithTaxMeta;
166
187
  }
167
188
  }
@@ -361,7 +361,7 @@ export declare class BookingByStepImpl extends BaseModule implements Module {
361
361
  count: number;
362
362
  left: number;
363
363
  summaryCount: number;
364
- status: "lots_of_space" | "filling_up_fast" | "sold_out";
364
+ status: "sold_out" | "lots_of_space" | "filling_up_fast";
365
365
  }[];
366
366
  /**
367
367
  * 找到多个资源的公共可用时间段
@@ -389,7 +389,7 @@ export declare class BookingByStepImpl extends BaseModule implements Module {
389
389
  };
390
390
  setOtherData(key: string, value: any): void;
391
391
  getOtherData(key: string): any;
392
- getProductTypeById(id: number): Promise<"duration" | "normal" | "session">;
392
+ getProductTypeById(id: number): Promise<"normal" | "duration" | "session">;
393
393
  /**
394
394
  * 提供给 UI 的方法,减轻 UI 层的计算压力,UI 层只需要传递 cartItemId 和 resourceCode 即返回对应的 renderList
395
395
  *
@@ -366,7 +366,7 @@ export declare class BookingTicketImpl extends BaseSalesImpl implements Module {
366
366
  * 获取当前的客户搜索条件
367
367
  * @returns 当前搜索条件
368
368
  */
369
- getCurrentCustomerSearchParams(): Omit<import("../../modules").ShopGetCustomerListParams, "skip" | "num">;
369
+ getCurrentCustomerSearchParams(): Omit<import("../../modules").ShopGetCustomerListParams, "num" | "skip">;
370
370
  /**
371
371
  * 获取客户列表状态(包含滚动加载相关状态)
372
372
  * @returns 客户状态
@@ -24,13 +24,17 @@ export declare function buildArrivalCheckoutQuery(order: OrderTempOrder, summary
24
24
  products: import("../../../modules/Order/types").OrderSubmitProduct[];
25
25
  notes?: import("../../../modules/Order/types").SalesNote[] | undefined;
26
26
  summary?: import("../../../modules/Order/types").OrderSummary | undefined;
27
- bookings: any[];
27
+ metadata: Record<string, any>;
28
+ type: string;
29
+ note: string;
30
+ holder: Record<string, any> | null;
31
+ relation_forms: any[];
32
+ holder_relations?: import("../../../modules/Order/types").OrderHolderRelation[] | undefined;
28
33
  order_id: number | null;
29
34
  external_sale_number: string;
30
35
  order_number: string | null;
31
36
  shop_order_number: string | null;
32
37
  shop_full_order_number: string | null;
33
- type: string;
34
38
  business_code?: string | undefined;
35
39
  sales_channel: string;
36
40
  order_sales_channel: string;
@@ -51,21 +55,17 @@ export declare function buildArrivalCheckoutQuery(order: OrderTempOrder, summary
51
55
  deposit_amount: string;
52
56
  shop_discount: string;
53
57
  surcharge_fee: string;
54
- note: string;
55
58
  buzzer?: string | undefined;
56
59
  delivery_type?: string | undefined;
57
60
  table_number?: Record<string, any> | undefined;
58
61
  schedule_date: string;
59
- holder_relations?: import("../../../modules/Order/types").OrderHolderRelation[] | undefined;
62
+ bookings: any[];
60
63
  payments: any[];
64
+ contacts_info: Record<string, any> | null;
65
+ order_meta_list?: import("../../../modules/Order/types").OrderMetaList | undefined;
61
66
  refunds?: any[] | undefined;
62
67
  surcharges: any[];
63
- relation_forms: any[];
64
68
  contacts: any[];
65
- contacts_info: Record<string, any> | null;
66
- holder: Record<string, any> | null;
67
- order_meta_list?: import("../../../modules/Order/types").OrderMetaList | undefined;
68
- metadata: Record<string, any>;
69
69
  };
70
70
  export declare function describeChangedBookings(before: OrderTempOrder['bookings'], after: OrderTempOrder['bookings']): {
71
71
  schedule_event_id: any;
@@ -91,6 +91,7 @@ export declare class UnifiedBookingSalesImpl extends BookingTicket {
91
91
  private availabilityProjectionRefreshInFlight;
92
92
  private availabilityRemoteOccupancyCache;
93
93
  private availabilitySessionResourceCache;
94
+ private readonly fetchAvailabilitySessionResources;
94
95
  private availabilityRemoteResourceQueryInFlight;
95
96
  private availabilityRemoteResourceQuerySequence;
96
97
  private availabilityRemoteResourceEpoch;
@@ -1308,6 +1308,10 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
1308
1308
  availabilityProjectionRefreshInFlight = new Map();
1309
1309
  availabilityRemoteOccupancyCache = new _remoteOccupancyCache.AvailabilityRemoteOccupancyCache(MAX_REMOTE_OCCUPANCY_RESOURCE_DATE_CELLS);
1310
1310
  availabilitySessionResourceCache = new _sessionResourceCache.AvailabilitySessionResourceCache();
1311
+ fetchAvailabilitySessionResources = query => this.fetchAvailabilityResourcesV2({
1312
+ ...query,
1313
+ strictResponse: true
1314
+ });
1311
1315
  availabilityRemoteResourceQueryInFlight = new Map();
1312
1316
  availabilityRemoteResourceQuerySequence = 0;
1313
1317
  availabilityRemoteResourceEpoch = 0;
@@ -2855,8 +2859,11 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2855
2859
  throw (0, _venueCatalogSession.venueCatalogError)('VENUE_CATALOG_DATETIME_INVALID', 'Choose a valid venue catalog date and time.');
2856
2860
  }
2857
2861
  const menus = (0, _venueCatalogSession.activeVenueMenus)(pool.menus, this.getAvailabilityScheduleCatalog(), datetime, Boolean(input.schedule_date && !input.schedule_datetime));
2858
- let products = pool.products.filter(product => menus.some(menu => (0, _venueCatalogSession.productMatchesVenueMenu)(product, menu))).map(product => this.getVenueCatalogHydratedProduct(product));
2862
+ let products = pool.products.filter(product => menus.some(menu => (0, _venueCatalogSession.productMatchesVenueMenu)(product, menu)));
2859
2863
  if (input.product_ids?.length) products = products.filter(product => input.product_ids.some(id => Number(id) === Number(product.id)));
2864
+ // Detail/quote reads must not deep-clone every other member of the pool.
2865
+ // Hydration owns a fresh copy of each selected product, including variants.
2866
+ products = products.map(product => this.getVenueCatalogHydratedProduct(product));
2860
2867
  const user = this.core.getPlugin?.('user');
2861
2868
  const queryPayload = {
2862
2869
  schedule_date: datetime.slice(0, 10),
@@ -2870,7 +2877,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2870
2877
  const result = (0, _clientDataVariants.tryResolveClientDataVariants)({
2871
2878
  core: this.core,
2872
2879
  otherParams: this.otherParams,
2873
- products: (0, _lodashEs.cloneDeep)(products),
2880
+ products,
2874
2881
  queryPayload,
2875
2882
  handledByOsServer: false,
2876
2883
  scheduleList: this.getAvailabilityScheduleCatalog(),
@@ -3848,10 +3855,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3848
3855
  scopeKey: `${scope}:${this.buildAvailabilityRemoteResourceScopeKey(timezone)}`,
3849
3856
  timezoneName: timezone,
3850
3857
  ...resourceQuery,
3851
- fetch: query => this.fetchAvailabilityResourcesV2({
3852
- ...query,
3853
- strictResponse: true
3854
- })
3858
+ fetch: this.fetchAvailabilitySessionResources
3855
3859
  }) : await this.fetchAvailabilityResourcesV2({
3856
3860
  ...resourceQuery,
3857
3861
  strictResponse: true
@@ -3978,10 +3982,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
3978
3982
  timezoneName: params.timezone,
3979
3983
  resourceIds,
3980
3984
  dateRange: params.dateRange,
3981
- fetch: query => this.fetchAvailabilityResourcesV2({
3982
- ...query,
3983
- strictResponse: true
3984
- })
3985
+ fetch: this.fetchAvailabilitySessionResources
3985
3986
  });
3986
3987
  return buildAvailabilityResourcesFromV2({
3987
3988
  rawResources,
@@ -21,7 +21,11 @@ export declare class AvailabilitySessionResourceCache {
21
21
  private readonly cells;
22
22
  private readonly pending;
23
23
  private generation;
24
+ private queuedBatches;
25
+ private batchFlushScheduled;
24
26
  clear(): void;
27
+ private enqueueFetch;
28
+ private flushFetchBatches;
25
29
  load(params: AvailabilitySessionResourceLoadParams): Promise<RawResource[]>;
26
30
  }
27
31
  export {};
@@ -6,6 +6,11 @@ Object.defineProperty(exports, "__esModule", {
6
6
  exports.AvailabilitySessionResourceCache = void 0;
7
7
  var _lodashEs = require("lodash-es");
8
8
  var _localClock = require("../../modules/ResourcePlanner/localClock");
9
+ function sessionChangedError() {
10
+ return Object.assign(new Error('Resource session changed while loading. Please prepare again.'), {
11
+ code: 'AVAILABILITY_CONTEXT_NOT_FOUND'
12
+ });
13
+ }
9
14
  function datesInRange(range) {
10
15
  const count = (0, _localClock.dateOrdinalFromLocalDate)(range.endDate) - (0, _localClock.dateOrdinalFromLocalDate)(range.startDate) + 1;
11
16
  // A legal 90-business-day projection may include its preceding opening and overnight tail.
@@ -67,18 +72,78 @@ class AvailabilitySessionResourceCache {
67
72
  cells = new Map();
68
73
  pending = new Map();
69
74
  generation = 0;
75
+ queuedBatches = [];
76
+ batchFlushScheduled = false;
70
77
  clear() {
71
78
  this.generation += 1;
72
79
  this.cells.clear();
73
80
  this.pending.clear();
81
+ // A queued request has not reached the transport yet. Settle its waiters
82
+ // now, rather than leaving them pending or dispatching it in the new scope.
83
+ const queued = this.queuedBatches;
84
+ this.queuedBatches = [];
85
+ queued.forEach(batch => batch.reject(sessionChangedError()));
86
+ }
87
+ enqueueFetch(params, query, generation) {
88
+ let batch = this.queuedBatches.find(entry => entry.generation === generation && entry.scopeKey === params.scopeKey && entry.timezoneName === params.timezoneName && entry.fetch === params.fetch && entry.dateRange.startDate === query.dateRange.startDate && entry.dateRange.endDate === query.dateRange.endDate);
89
+ if (!batch) {
90
+ let resolve;
91
+ let reject;
92
+ const promise = new Promise((resolvePromise, rejectPromise) => {
93
+ resolve = resolvePromise;
94
+ reject = rejectPromise;
95
+ });
96
+ batch = {
97
+ generation,
98
+ scopeKey: params.scopeKey,
99
+ timezoneName: params.timezoneName,
100
+ dateRange: {
101
+ ...query.dateRange
102
+ },
103
+ fetch: params.fetch,
104
+ resourceIds: new Map(),
105
+ promise,
106
+ resolve,
107
+ reject
108
+ };
109
+ this.queuedBatches.push(batch);
110
+ }
111
+ query.resourceIds.forEach(id => batch.resourceIds.set(String(id), id));
112
+ if (!this.batchFlushScheduled) {
113
+ this.batchFlushScheduled = true;
114
+ // Fetching was already asynchronous. Collect requests from this turn only;
115
+ // do not add a timer or broaden their physical date coverage.
116
+ void Promise.resolve().then(() => this.flushFetchBatches());
117
+ }
118
+ return batch.promise;
119
+ }
120
+ flushFetchBatches() {
121
+ this.batchFlushScheduled = false;
122
+ const queued = this.queuedBatches;
123
+ this.queuedBatches = [];
124
+ queued.forEach(batch => {
125
+ if (batch.generation !== this.generation) {
126
+ batch.reject(sessionChangedError());
127
+ return;
128
+ }
129
+ const query = {
130
+ resourceIds: Array.from(batch.resourceIds.values()).sort((left, right) => String(left).localeCompare(String(right))),
131
+ dateRange: {
132
+ ...batch.dateRange
133
+ }
134
+ };
135
+ try {
136
+ Promise.resolve(batch.fetch((0, _lodashEs.cloneDeep)(query))).then(batch.resolve, batch.reject);
137
+ } catch (error) {
138
+ batch.reject(error);
139
+ }
140
+ });
74
141
  }
75
142
  async load(params) {
76
143
  const generation = this.generation;
77
144
  const assertCurrent = () => {
78
145
  if (generation !== this.generation) {
79
- throw Object.assign(new Error('Resource session changed while loading. Please prepare again.'), {
80
- code: 'AVAILABILITY_CONTEXT_NOT_FOUND'
81
- });
146
+ throw sessionChangedError();
82
147
  }
83
148
  };
84
149
  const resources = Array.from(new Map(params.resourceIds.filter(id => id !== undefined && id !== null && id !== '').map(id => [String(id), id])).values());
@@ -121,7 +186,7 @@ class AvailabilitySessionResourceCache {
121
186
  const cellKeys = query.resourceIds.flatMap(id => queryDates.map(date => key(id, date)));
122
187
  const promise = Promise.resolve().then(async () => {
123
188
  assertCurrent();
124
- const response = await params.fetch((0, _lodashEs.cloneDeep)(query));
189
+ const response = await this.enqueueFetch(params, query, generation);
125
190
  assertCurrent();
126
191
  if (!Array.isArray(response)) throw new Error('Booking resources returned an invalid response.');
127
192
  const byId = new Map();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "private": false,
3
3
  "name": "@pisell/pisellos",
4
- "version": "0.10.94",
4
+ "version": "0.10.95",
5
5
  "description": "一个可扩展的前端模块化SDK框架,支持插件系统",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",