@pisell/pisellos 2.3.198 → 2.3.199

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.
@@ -33,14 +33,90 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
33
33
  shopStore;
34
34
  store;
35
35
  otherParams = {};
36
+ scheduleRuntimeParams = {};
36
37
  cacheId;
37
38
  otherData = {}; // 提供给 UI 层的临时数据存储,会进缓存
38
39
  platform; // 平台类型,用于判断是 PC / H5
40
+ productDetailGeneration = 0;
41
+ sessionAvailabilityRequestVersion = 0;
42
+ lifecycleGeneration = 0;
43
+ disposed = false;
44
+ resourcePreparation;
45
+ staleSelection() {
46
+ return Object.assign(new Error('Booking selection changed'), {
47
+ name: 'AbortError'
48
+ });
49
+ }
50
+ resourceSelectionKey() {
51
+ const items = this.store.cart.getItems();
52
+ const sessionDates = items.filter(item => (0, _products.isSessionProduct)(item._productOrigin)).flatMap(item => [item.start_date, item.end_date]).filter(Boolean);
53
+ return JSON.stringify({
54
+ lifecycle: this.lifecycleGeneration,
55
+ dates: sessionDates.length ? [...new Set(sessionDates)].sort() : (this.store.date.getDateRange() || []).map(date => date.date).sort(),
56
+ cart: items.map(item => ({
57
+ id: item._id,
58
+ num: item.num,
59
+ holder: item.holder_id,
60
+ start: [item.start_date, item.start_time],
61
+ end: [item.end_date, item.end_time],
62
+ resources: item._origin?.resources,
63
+ capacity: (0, _capacity.getCapacityInfoByCartItem)(item).currentCapacity,
64
+ product: {
65
+ id: item._productOrigin?.id,
66
+ schedules: item._productOrigin?.['schedule.ids'],
67
+ resources: item._productOrigin?.product_resource?.resources?.map(resource => ({
68
+ id: resource.id,
69
+ resource_type_id: resource.resource_type_id,
70
+ status: resource.status,
71
+ code: resource.code,
72
+ type: resource.type,
73
+ default_resource: resource.default_resource || [],
74
+ // Resource rendering removes required IDs from the optional list in place.
75
+ // Compare the same effective inputs before and after that normalization.
76
+ optional_resource: (resource.optional_resource || []).filter(id => !(resource.default_resource || []).includes(id)),
77
+ select_type: resource.select_type && {
78
+ type: resource.select_type.type,
79
+ min: resource.select_type.min,
80
+ max: resource.select_type.max
81
+ }
82
+ })),
83
+ duration: item._productOrigin?.duration,
84
+ cutoff: item._productOrigin?.cut_off_time
85
+ },
86
+ bundle: item._bundleOrigin,
87
+ options: item._optionsOrigin
88
+ }))
89
+ });
90
+ }
39
91
 
92
+ /** Semantic selection token for async UI transitions. */
93
+ getBookingSelectionKey() {
94
+ return this.resourceSelectionKey();
95
+ }
96
+ refreshCurrentProductSchedule() {
97
+ const product = this.store.currentProduct;
98
+ if (!product?.['schedule.ids'] || !this.store.schedule.isScheduleListLoaded()) return;
99
+ const version = this.store.schedule.getScheduleCatalogVersion();
100
+ const meta = this.store.currentProductMeta || {};
101
+ if (meta.scheduleCatalogVersion !== version) {
102
+ this.store.currentProductMeta = {
103
+ ...meta,
104
+ schedule: this.getScheduleDataByIds(product['schedule.ids']),
105
+ scheduleCatalogVersion: version,
106
+ timeSlotBySchedule: undefined
107
+ };
108
+ }
109
+ }
40
110
  async initialize(core, options) {
111
+ this.disposed = false;
112
+ this.lifecycleGeneration += 1;
113
+ this.productDetailGeneration += 1;
41
114
  this.core = core;
42
115
  this.store = options.store || {};
43
116
  this.otherParams = options.otherParams || {};
117
+ this.scheduleRuntimeParams = {
118
+ ...this.otherParams
119
+ };
44
120
  // 获取依赖的插件
45
121
  this.request = core.getPlugin('request');
46
122
  this.window = core.getPlugin('window');
@@ -78,14 +154,20 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
78
154
  ...this.otherParams,
79
155
  fatherModule: this.name,
80
156
  openCache: this.otherParams?.cacheId ? true : false,
81
- cacheId: this.otherParams?.cacheId
157
+ cacheId: this.otherParams?.cacheId,
158
+ ...(step === 'schedule' ? {
159
+ scheduleCatalogCache: 'memory',
160
+ bookingRead: true
161
+ } : {})
82
162
  }
83
163
  });
84
164
  } else {
85
165
  throw new Error(`模块 ${step} 不存在`);
86
166
  }
87
167
  });
88
- this.store.schedule.loadAllSchedule();
168
+ this.store.schedule.ensureScheduleReady().catch(error => {
169
+ if (error?.name !== 'AbortError') console.error('[BookingByStep] Schedule preload failed', error);
170
+ });
89
171
  this.core.effects.emit(`${this.name}:onInited`, {});
90
172
  }
91
173
  // 初始化step
@@ -174,6 +256,8 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
174
256
  startDate: schedule_date || (0, _dayjs.default)().format('YYYY-MM-DD'),
175
257
  endDate: schedule_date || (0, _dayjs.default)().format('YYYY-MM-DD'),
176
258
  products: [...res]
259
+ }).catch(error => {
260
+ if (error?.name !== 'AbortError') console.error('[BookingByStep] Resource preload failed', error);
177
261
  });
178
262
  return res;
179
263
  }
@@ -283,13 +367,15 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
283
367
  startDate,
284
368
  endDate,
285
369
  custom_page_id,
286
- channel
370
+ channel,
371
+ assertCurrent
287
372
  }) {
288
373
  return await this.store.schedule.loadScheduleAvailableDate({
289
374
  startDate,
290
375
  endDate,
291
376
  custom_page_id,
292
- channel
377
+ channel,
378
+ assertCurrent
293
379
  });
294
380
  }
295
381
 
@@ -431,6 +517,24 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
431
517
  startDate = (0, _dayjs.default)().format('YYYY-MM-DD');
432
518
  }
433
519
  let tempProducts = products || this.store.cart.getItems().map(p => p._productOrigin);
520
+ const generation = this.productDetailGeneration;
521
+ const lifecycle = this.lifecycleGeneration;
522
+ const selectionKey = products ? undefined : this.resourceSelectionKey();
523
+ const assertCurrent = () => {
524
+ if (this.disposed || lifecycle !== this.lifecycleGeneration || (!products || !params.assertCurrent) && generation !== this.productDetailGeneration || selectionKey !== undefined && selectionKey !== this.resourceSelectionKey()) throw this.staleSelection();
525
+ params.assertCurrent?.();
526
+ };
527
+ const requiresSchedule = tempProducts.some(product => product?.['schedule.ids']?.length) || !products && !!this.store.currentProduct?.['schedule.ids']?.length;
528
+ if (requiresSchedule) {
529
+ try {
530
+ await this.store.schedule.ensureScheduleReady();
531
+ } catch (error) {
532
+ assertCurrent();
533
+ throw error;
534
+ }
535
+ assertCurrent();
536
+ this.refreshCurrentProductSchedule();
537
+ }
434
538
  if (tempProducts.length) {
435
539
  tempProducts.forEach(p => {
436
540
  if (p?.['schedule.ids']) {
@@ -440,7 +544,7 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
440
544
  });
441
545
  }
442
546
  // 如果当前打开了某个的商品详情弹窗,则应该默认用这个商品
443
- if (this.store.currentProduct) {
547
+ if (!products && this.store.currentProduct) {
444
548
  tempProducts = [{
445
549
  ...this.store.currentProduct,
446
550
  _schedule: this.store.currentProductMeta?.['schedule']
@@ -460,6 +564,7 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
460
564
  resourcesMap
461
565
  } = (0, _products.getAvailableProductResources)(tempProducts) || {};
462
566
  this.otherParams.currentResourcesMap = resourcesMap;
567
+ const catalogVersion = this.store.schedule.getScheduleCatalogVersion();
463
568
  const res = await this.store.date.getResourceDates({
464
569
  url: params.url,
465
570
  query: {
@@ -469,11 +574,56 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
469
574
  },
470
575
  rules,
471
576
  type,
472
- useCache
577
+ useCache,
578
+ bookingRead: true,
579
+ errorMode: 'throw',
580
+ assertCurrent: () => {
581
+ assertCurrent();
582
+ if (requiresSchedule && catalogVersion !== this.store.schedule.getScheduleCatalogVersion()) throw this.staleSelection();
583
+ }
473
584
  });
474
585
  return res;
475
586
  }
476
587
 
588
+ /** Prepare the exact cart/date selection before synchronous resource checks. */
589
+ prepareResourcesForCurrentSelection() {
590
+ const key = this.resourceSelectionKey();
591
+ if (this.resourcePreparation?.key === key) return this.resourcePreparation.promise;
592
+ const selected = (0, _lodashEs.cloneDeep)(this.store.date.getDateRange() || []);
593
+ const cart = this.store.cart.getItems().filter(item => !(0, _utils5.isNormalProduct)(item._productOrigin));
594
+ const sessionDates = cart.filter(item => (0, _products.isSessionProduct)(item._productOrigin)).flatMap(item => [item.start_date, item.end_date]).filter(Boolean);
595
+ const selectedDates = sessionDates.length ? [...new Set(sessionDates)].sort() : selected.map(date => date.date).sort();
596
+ const dates = selectedDates;
597
+ if (!cart.length || !dates.length) return Promise.resolve();
598
+ const assertCurrent = () => {
599
+ if (this.disposed || key !== this.resourceSelectionKey()) throw this.staleSelection();
600
+ };
601
+ const promise = (async () => {
602
+ const available = await this.getAvailableDate({
603
+ startDate: dates[0],
604
+ endDate: dates[dates.length - 1],
605
+ products: cart.map(item => item._productOrigin),
606
+ assertCurrent
607
+ });
608
+ assertCurrent();
609
+ this.store.date.setDateRange(selectedDates.map(date => available.find(item => item.date === date) || {
610
+ date,
611
+ week: (0, _dayjs.default)(date).format('ddd'),
612
+ weekNum: (0, _dayjs.default)(date).day(),
613
+ status: 'unavailable',
614
+ resource: []
615
+ }));
616
+ })();
617
+ this.resourcePreparation = {
618
+ key,
619
+ promise
620
+ };
621
+ void promise.finally(() => {
622
+ if (this.resourcePreparation?.promise === promise) this.resourcePreparation = undefined;
623
+ }).catch(() => {});
624
+ return promise;
625
+ }
626
+
477
627
  /**
478
628
  * 获取购物车汇总信息
479
629
  */
@@ -610,6 +760,10 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
610
760
  async setOtherParams(params, {
611
761
  cover = false
612
762
  } = {}) {
763
+ this.scheduleRuntimeParams = {
764
+ ...this.scheduleRuntimeParams,
765
+ ...params
766
+ };
613
767
  if (cover) {
614
768
  this.otherParams = params;
615
769
  } else {
@@ -618,6 +772,13 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
618
772
  ...params
619
773
  };
620
774
  }
775
+ this.store.schedule?.updateOtherParams({
776
+ ...this.scheduleRuntimeParams,
777
+ fatherModule: this.name,
778
+ openCache: !!this.scheduleRuntimeParams.cacheId,
779
+ scheduleCatalogCache: 'memory',
780
+ bookingRead: true
781
+ });
621
782
  }
622
783
  async getOtherParams() {
623
784
  return this.otherParams;
@@ -948,6 +1109,11 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
948
1109
  return errorCartItemIds;
949
1110
  }
950
1111
  destroy() {
1112
+ this.disposed = true;
1113
+ this.lifecycleGeneration += 1;
1114
+ this.productDetailGeneration += 1;
1115
+ this.resourcePreparation = undefined;
1116
+ this.store.schedule?.destroy();
951
1117
  this.store.cart?.destroy();
952
1118
  this.store.step?.destroy();
953
1119
  this.store.products?.destroy();
@@ -1955,7 +2121,17 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
1955
2121
  }
1956
2122
  // 打开某个商品详情的弹窗,OS 层这边会记录当前选中的商品,适用于 session 类商品预约
1957
2123
  async openProductDetail(productId) {
1958
- const targetProductData = await this.store.products.getProduct(productId);
2124
+ const generation = ++this.productDetailGeneration;
2125
+ let targetProductData;
2126
+ try {
2127
+ targetProductData = await this.store.products.getProduct(productId);
2128
+ if (targetProductData?.['schedule.ids']?.length) await this.store.schedule.ensureScheduleReady();
2129
+ } catch (error) {
2130
+ if (this.disposed || generation !== this.productDetailGeneration) throw this.staleSelection();
2131
+ throw error;
2132
+ }
2133
+ if (this.disposed || generation !== this.productDetailGeneration) throw this.staleSelection();
2134
+ if (!targetProductData) throw new Error('Booking product is unavailable');
1959
2135
  if (targetProductData) {
1960
2136
  this.store.currentProduct = targetProductData;
1961
2137
  this.store.currentProductMeta = {};
@@ -1964,6 +2140,7 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
1964
2140
  const newScheduleArr = this.getScheduleDataByIds(targetProductData['schedule.ids']);
1965
2141
  if (!this.store.currentProductMeta) this.store.currentProductMeta = {};
1966
2142
  this.store.currentProductMeta.schedule = newScheduleArr;
2143
+ this.store.currentProductMeta.scheduleCatalogVersion = this.store.schedule.getScheduleCatalogVersion();
1967
2144
  } else if (targetProductData.duration) {
1968
2145
  const dateRange = this.store.date.getDateRange();
1969
2146
  // 如果不是先选日期的流程 duration 商品就啥也不做
@@ -1979,14 +2156,15 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
1979
2156
  startDate: dateRange[0].date,
1980
2157
  endDate: dateRange[dateRange.length - 1].date,
1981
2158
  products: [targetProductData]
2159
+ }).catch(error => {
2160
+ if (error?.name !== 'AbortError') console.error('[BookingByStep] Product resource preload failed', error);
1982
2161
  });
1983
2162
  }
1984
2163
  }
1985
2164
  }
1986
2165
  closeProductDetail() {
1987
- if (this.store.currentProductMeta) {
1988
- this.store.currentProductMeta.schedule = [];
1989
- }
2166
+ this.productDetailGeneration += 1;
2167
+ this.store.currentProductMeta = {};
1990
2168
  this.store.currentProduct = undefined;
1991
2169
  }
1992
2170
 
@@ -3134,6 +3312,20 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
3134
3312
  return results;
3135
3313
  }
3136
3314
  async getAvailableDateForSessionOptimize(params = {}) {
3315
+ const requestVersion = ++this.sessionAvailabilityRequestVersion;
3316
+ const generation = this.productDetailGeneration;
3317
+ try {
3318
+ await this.store.schedule.ensureScheduleReady();
3319
+ } catch (error) {
3320
+ if (this.disposed || generation !== this.productDetailGeneration || requestVersion !== this.sessionAvailabilityRequestVersion) throw this.staleSelection();
3321
+ throw error;
3322
+ }
3323
+ if (this.disposed || generation !== this.productDetailGeneration || requestVersion !== this.sessionAvailabilityRequestVersion || !this.store.currentProduct) throw this.staleSelection();
3324
+ this.refreshCurrentProductSchedule();
3325
+ const catalogVersion = this.store.schedule.getScheduleCatalogVersion();
3326
+ const assertCurrent = () => {
3327
+ if (this.disposed || generation !== this.productDetailGeneration || requestVersion !== this.sessionAvailabilityRequestVersion || catalogVersion !== this.store.schedule.getScheduleCatalogVersion()) throw this.staleSelection();
3328
+ };
3137
3329
  // 开始日期如果小于今天,直接以今天当做开始日期
3138
3330
  let {
3139
3331
  startDate,
@@ -3164,7 +3356,8 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
3164
3356
  if (cache) {
3165
3357
  // 开始日期大于等于缓存的开始日期,且结束日期小于等于缓存的结束日期,则直接返回缓存结果
3166
3358
  if ((0, _dayjs.default)(params.startDate).isSameOrAfter((0, _dayjs.default)(cache.startDate), 'day') && (0, _dayjs.default)(params.endDate).isSameOrBefore((0, _dayjs.default)(cache.endDate), 'day')) {
3167
- this.store.date.setDateList(cache.dateList);
3359
+ assertCurrent();
3360
+ this.store.date.setDateList(cache.dateList, true);
3168
3361
  return {
3169
3362
  dateList: cache.dateList,
3170
3363
  firstAvailableDate: cache.firstAvailableDate
@@ -3179,12 +3372,18 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
3179
3372
  // 1.后端返回的数据,确定资源在每一天的可用和使用情况
3180
3373
  const tempResourceIds = (0, _capacity.getResourcesIdsByProduct)(tempProducts);
3181
3374
  const res = await this.store.date.fetchResourceDates({
3375
+ errorMode: 'throw',
3376
+ bookingRead: true,
3182
3377
  query: {
3183
3378
  start_date: startDate || '',
3184
3379
  end_date: endDate || '',
3185
3380
  resource_ids: tempResourceIds
3186
3381
  }
3382
+ }).catch(error => {
3383
+ assertCurrent();
3384
+ throw error;
3187
3385
  });
3386
+ assertCurrent();
3188
3387
  // 2. 商品 schedule 数据,确定日程在每一天的时间片
3189
3388
  // 3. 把后端返回的和 schedule 的数据进行合并,确定每一天的可用和使用情况
3190
3389
  let dates = [];
@@ -3364,7 +3563,8 @@ class BookingByStepImpl extends _BaseModule.BaseModule {
3364
3563
  }
3365
3564
  // 最终把资源数据也加到日期内
3366
3565
  dates = (0, _utils4.handleAvailableDateByResource)(res.data, dates);
3367
- this.store.date.setDateList(dates);
3566
+ assertCurrent();
3567
+ this.store.date.setDateList(dates, true);
3368
3568
 
3369
3569
  // 缓存这次结果,以防后面他小幅度范围内去修改天数
3370
3570
  if (!this.store.currentProductMeta) this.store.currentProductMeta = {};
@@ -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, "num" | "skip">;
369
+ getCurrentCustomerSearchParams(): Omit<import("../../modules").ShopGetCustomerListParams, "skip" | "num">;
370
370
  /**
371
371
  * 获取客户列表状态(包含滚动加载相关状态)
372
372
  * @returns 客户状态
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "private": false,
3
3
  "name": "@pisell/pisellos",
4
- "version": "2.3.198",
4
+ "version": "2.3.199",
5
5
  "description": "一个可扩展的前端模块化SDK框架,支持插件系统",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",