@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.
@@ -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 客户状态
@@ -15,7 +15,7 @@ export declare class DateModule extends BaseModule implements Module, DateModule
15
15
  getDateRange(): ITime[];
16
16
  getResourceDates(params: IGetAvailableTimeListParams): Promise<ITime[]>;
17
17
  getDateList(): ITime[];
18
- setDateList(dateList: ITime[]): void;
18
+ setDateList(dateList: ITime[], replaceDates?: boolean): void;
19
19
  fetchResourceDates(params: IGetAvailableTimeListParams): Promise<any>;
20
20
  /**
21
21
  * 将时间向上取整到下一个10分钟整数
@@ -8,6 +8,7 @@ var _dayjs = _interopRequireDefault(require("dayjs"));
8
8
  var _BaseModule = require("../BaseModule");
9
9
  var _utils = require("./utils");
10
10
  var _cloneDeep = _interopRequireDefault(require("lodash-es/cloneDeep"));
11
+ var _bookingReadValidation = require("../bookingReadValidation");
11
12
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12
13
  class DateModule extends _BaseModule.BaseModule {
13
14
  defaultName = 'date';
@@ -52,7 +53,7 @@ class DateModule extends _BaseModule.BaseModule {
52
53
  return this.store.dateRange;
53
54
  }
54
55
  async getResourceDates(params) {
55
- if (params.useCache) {
56
+ if (params.useCache && params.errorMode !== 'throw') {
56
57
  // 发请求之前,做一道检测,看 dateList 里是否有对应日期,且对应日期里是否都有对应 resource_ids 的资源
57
58
  const currentDateList = this.getDateList() || [];
58
59
  const currentDateListMap = new Map(currentDateList.map(item => [item.date, item]));
@@ -65,14 +66,26 @@ class DateModule extends _BaseModule.BaseModule {
65
66
  return currentDateList;
66
67
  }
67
68
  }
68
- const dates = await this.getResourceAvailableTimeList(params);
69
- this.setDateList(dates);
69
+ let dates;
70
+ try {
71
+ dates = await this.getResourceAvailableTimeList(params);
72
+ } catch (error) {
73
+ params.assertCurrent?.();
74
+ throw error;
75
+ }
76
+ params.assertCurrent?.();
77
+ this.setDateList(dates, params.errorMode === 'throw');
70
78
  return dates;
71
79
  }
72
80
  getDateList() {
73
81
  return this.store.dateList;
74
82
  }
75
- setDateList(dateList) {
83
+ setDateList(dateList, replaceDates = false) {
84
+ if (replaceDates) {
85
+ const incoming = new Map(dateList.map(date => [date.date, date]));
86
+ this.store.dateList = [...(this.store.dateList || []).filter(date => !incoming.has(date.date)), ...(0, _cloneDeep.default)(dateList)];
87
+ return;
88
+ }
76
89
  // this.store.dateList = dateList;
77
90
  // 并不能直接简单的进行复制
78
91
  // 我们需要把每一天的资源都进行一个合并
@@ -117,8 +130,16 @@ class DateModule extends _BaseModule.BaseModule {
117
130
  resource_ids,
118
131
  front_end_cache_id: useCache && this.cacheId
119
132
  }, {
120
- useCache
133
+ useCache,
134
+ ...(params.bookingRead ? {
135
+ bookingRead: true
136
+ } : {})
121
137
  });
138
+ if (params.errorMode === 'throw') {
139
+ if (!res || res.code !== undefined && Number(res.code) !== 200 || res.status === false || res.success === false || typeof res.status === 'number' && res.status >= 400 || !(0, _bookingReadValidation.isBookingResourceList)(res.data)) {
140
+ throw new Error(res?.message || 'Invalid booking resource response');
141
+ }
142
+ }
122
143
 
123
144
  // 校正资源时间段数据
124
145
  if (res?.data && Array.isArray(res.data)) {
@@ -126,6 +147,7 @@ class DateModule extends _BaseModule.BaseModule {
126
147
  }
127
148
  return res;
128
149
  } catch (error) {
150
+ if (params.errorMode === 'throw') throw error;
129
151
  console.error(error);
130
152
  }
131
153
  }
@@ -244,6 +266,7 @@ class DateModule extends _BaseModule.BaseModule {
244
266
  }
245
267
  return dates;
246
268
  } catch (error) {
269
+ if (params.errorMode === 'throw') throw error;
247
270
  return (0, _utils.disableAllDates)(dates);
248
271
  }
249
272
  }
@@ -44,6 +44,11 @@ export interface DateModuleAPI {
44
44
  getResourceDates: (params: IGetAvailableTimeListParams) => Promise<ITime[]>;
45
45
  }
46
46
  export interface IGetAvailableTimeListParams {
47
+ /** BookingByStep opts in; existing solutions retain unavailable-on-error behavior. */
48
+ errorMode?: 'unavailable' | 'throw';
49
+ bookingRead?: boolean;
50
+ /** Check the selection is still current before committing a response. */
51
+ assertCurrent?: () => void;
47
52
  url?: string;
48
53
  /** 是否使用缓存 */
49
54
  useCache?: boolean;
@@ -14,6 +14,9 @@ export declare class ScheduleModule extends BaseModule implements Module, Schedu
14
14
  private scheduleListRequestVersion;
15
15
  private scheduleCatalogScope;
16
16
  private otherParams;
17
+ private catalogVersion;
18
+ private destroyed;
19
+ private availabilityRequestVersion;
17
20
  constructor(name?: string, version?: string);
18
21
  initialize(core: PisellCore, options: ModuleOptions): Promise<void>;
19
22
  /**
@@ -34,12 +37,15 @@ export declare class ScheduleModule extends BaseModule implements Module, Schedu
34
37
  loadAllSchedule(options?: {
35
38
  useCache?: boolean;
36
39
  }): Promise<void>;
40
+ getScheduleCatalogVersion(): number;
41
+ /** Resolve only after the current scope has a successful catalog. */
42
+ ensureScheduleReady(): Promise<void>;
37
43
  private loadScheduleCatalog;
38
44
  setScheduleList(list: ScheduleItem[]): void;
39
45
  private syncScheduleMap;
40
46
  getScheduleList(): ScheduleItem[];
41
47
  isScheduleListLoaded(): boolean;
42
- loadScheduleAvailableDate({ startDate, endDate, custom_page_id, channel, }: LoadScheduleAvailableDateParams): Promise<import("../Date/types").ITime[]>;
48
+ loadScheduleAvailableDate({ startDate, endDate, custom_page_id, channel, assertCurrent, }: LoadScheduleAvailableDateParams): Promise<import("../Date/types").ITime[]>;
43
49
  getScheduleListByIds(ids: number[]): ScheduleItem[];
44
50
  setAvailabilityScheduleDateList(list: ScheduleAvailabilityDateItem[]): void;
45
51
  getAvailabilityScheduleDateList(): ScheduleAvailabilityDateItem[];
@@ -12,6 +12,7 @@ var _isSameOrAfter = _interopRequireDefault(require("dayjs/plugin/isSameOrAfter"
12
12
  var _utils = require("../Date/utils");
13
13
  var _utils2 = require("./utils");
14
14
  var _getDateIsInSchedule = require("./getDateIsInSchedule");
15
+ var _bookingReadValidation = require("../bookingReadValidation");
15
16
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
16
17
  _dayjs.default.extend(_isSameOrBefore.default);
17
18
  _dayjs.default.extend(_isSameOrAfter.default);
@@ -28,13 +29,17 @@ class ScheduleModule extends _BaseModule.BaseModule {
28
29
  scheduleListRequestVersion = 0;
29
30
  scheduleCatalogScope = '';
30
31
  otherParams = {};
32
+ catalogVersion = 0;
33
+ destroyed = false;
34
+ availabilityRequestVersion = 0;
31
35
  constructor(name, version) {
32
36
  super(name, version);
33
37
  }
34
38
  async initialize(core, options) {
35
39
  // The store proxies initialState, so capture its input before resets write through it.
36
40
  const initialScheduleList = options.initialState?.scheduleList;
37
- const hasInitialScheduleList = Array.isArray(initialScheduleList);
41
+ const hasInitialScheduleList = options.otherParams?.scheduleCatalogCache !== 'memory' && Array.isArray(initialScheduleList);
42
+ this.destroyed = false;
38
43
  this.resetScheduleCatalog();
39
44
  this.core = core;
40
45
 
@@ -89,6 +94,8 @@ class ScheduleModule extends _BaseModule.BaseModule {
89
94
  }
90
95
  }
91
96
  resetScheduleCatalog() {
97
+ this.catalogVersion += 1;
98
+ this.availabilityRequestVersion += 1;
92
99
  this.scheduleListRequestVersion += 1;
93
100
  this.scheduleListPromise = null;
94
101
  this.hasLoadedScheduleList = false;
@@ -96,6 +103,7 @@ class ScheduleModule extends _BaseModule.BaseModule {
96
103
  this.store.map = new Map();
97
104
  }
98
105
  destroy() {
106
+ this.destroyed = true;
99
107
  this.resetScheduleCatalog();
100
108
  super.destroy();
101
109
  }
@@ -123,15 +131,48 @@ class ScheduleModule extends _BaseModule.BaseModule {
123
131
  }
124
132
  }
125
133
  }
134
+ getScheduleCatalogVersion() {
135
+ this.syncScheduleCatalogScope();
136
+ return this.catalogVersion;
137
+ }
138
+
139
+ /** Resolve only after the current scope has a successful catalog. */
140
+ async ensureScheduleReady() {
141
+ while (!this.destroyed) {
142
+ this.syncScheduleCatalogScope();
143
+ const scope = this.scheduleCatalogScope;
144
+ try {
145
+ await this.loadAllSchedule();
146
+ } catch (error) {
147
+ if (this.destroyed) throw Object.assign(new Error('Schedule catalog was closed'), {
148
+ name: 'AbortError'
149
+ });
150
+ this.syncScheduleCatalogScope();
151
+ if (scope === this.scheduleCatalogScope) throw error;
152
+ // A failed old-scope request does not describe the new scope.
153
+ }
154
+ this.syncScheduleCatalogScope();
155
+ if (!this.destroyed && this.hasLoadedScheduleList && !this.scheduleListPromise) return;
156
+ }
157
+ throw Object.assign(new Error('Schedule catalog was closed'), {
158
+ name: 'AbortError'
159
+ });
160
+ }
126
161
  async loadScheduleCatalog(useCache, requestVersion) {
127
162
  const response = await this.request.get(`/schedule`, {
128
163
  num: 999
129
164
  }, {
130
- useCache
165
+ useCache: this.otherParams.scheduleCatalogCache === 'memory' ? false : useCache,
166
+ ...(this.otherParams.bookingRead ? {
167
+ bookingRead: true
168
+ } : {})
131
169
  });
132
170
  if (response.code !== undefined && Number(response.code) !== 200 || response.status === false || typeof response.status === 'number' && response.status >= 400 || response.success === false) {
133
171
  throw new Error(response.message || 'Schedule catalog request failed');
134
172
  }
173
+ if ((this.otherParams.bookingRead || this.otherParams.scheduleCatalogCache === 'memory') && !(0, _bookingReadValidation.isBookingScheduleList)(response?.data?.list)) {
174
+ throw new Error('Invalid schedule catalog response');
175
+ }
135
176
  this.syncScheduleCatalogScope();
136
177
  // A refresh or a different runtime may have superseded this request.
137
178
  if (requestVersion === this.scheduleListRequestVersion) {
@@ -143,6 +184,7 @@ class ScheduleModule extends _BaseModule.BaseModule {
143
184
  this.store.scheduleList = list;
144
185
  this.syncScheduleMap();
145
186
  this.hasLoadedScheduleList = true;
187
+ this.catalogVersion += 1;
146
188
  }
147
189
  syncScheduleMap() {
148
190
  this.store.map = new Map((this.store.scheduleList || []).map(schedule => [Number(schedule.id), schedule]));
@@ -159,8 +201,12 @@ class ScheduleModule extends _BaseModule.BaseModule {
159
201
  startDate,
160
202
  endDate,
161
203
  custom_page_id,
162
- channel
204
+ channel,
205
+ assertCurrent
163
206
  }) {
207
+ this.syncScheduleCatalogScope();
208
+ const requestVersion = ++this.availabilityRequestVersion;
209
+ const scope = this.scheduleCatalogScope;
164
210
  // 前端传递的 startDate,可能是今天之前的,如果 startDate 小于今天,需要把 startDate 置为今天
165
211
  if ((0, _dayjs.default)(startDate).isBefore((0, _dayjs.default)(), 'day')) {
166
212
  startDate = (0, _dayjs.default)().format('YYYY-MM-DD');
@@ -177,7 +223,25 @@ class ScheduleModule extends _BaseModule.BaseModule {
177
223
  end_date: endDate,
178
224
  custom_page_id,
179
225
  channel
226
+ }, this.otherParams.bookingRead ? {
227
+ bookingRead: true
228
+ } : undefined).catch(error => {
229
+ assertCurrent?.();
230
+ throw error;
180
231
  });
232
+ assertCurrent?.();
233
+ if (this.otherParams.bookingRead) {
234
+ const response = res;
235
+ if (!response || response.code !== undefined && Number(response.code) !== 200 || response.status === false || response.success === false || typeof response.status === 'number' && response.status >= 400 || !(0, _bookingReadValidation.isBookingAvailabilityData)(response.data)) {
236
+ throw new Error(response?.message || 'Invalid schedule availability response');
237
+ }
238
+ this.syncScheduleCatalogScope();
239
+ if (this.destroyed || scope !== this.scheduleCatalogScope || requestVersion !== this.availabilityRequestVersion) {
240
+ throw Object.assign(new Error('Schedule availability context changed'), {
241
+ name: 'AbortError'
242
+ });
243
+ }
244
+ }
181
245
  const responseData = res.data || {};
182
246
  const dateList = Array.isArray(responseData.date_list) ? responseData.date_list : [];
183
247
  const otherProductIds = Array.isArray(responseData.other_product_ids) ? responseData.other_product_ids : [];
@@ -232,7 +296,7 @@ class ScheduleModule extends _BaseModule.BaseModule {
232
296
  cacheId: this.cacheId,
233
297
  fatherModule: this.fatherModule,
234
298
  store,
235
- cacheKey: ['scheduleList', 'availabilityDateList', 'otherProductsIds']
299
+ cacheKey: this.otherParams.scheduleCatalogCache === 'memory' ? ['availabilityDateList', 'otherProductsIds'] : ['scheduleList', 'availabilityDateList', 'otherProductsIds']
236
300
  });
237
301
  }
238
302
  }
@@ -15,6 +15,8 @@ export type ScheduleAvailabilityDateItem = {
15
15
  * 加载日程可用日期参数接口
16
16
  */
17
17
  export interface LoadScheduleAvailableDateParams {
18
+ /** Caller lifecycle guard, checked before committing availability. */
19
+ assertCurrent?: () => void;
18
20
  /** 开始日期 */
19
21
  startDate: string;
20
22
  /** 结束日期 */
@@ -0,0 +1,6 @@
1
+ /** Validate only the catalog fields consumed by booking reads, not display metadata. */
2
+ export declare const isBookingScheduleList: (value: unknown) => boolean;
3
+ /** Empty resource/time/event arrays and zero capacity are valid successful results. */
4
+ export declare const isBookingResourceList: (value: unknown) => boolean;
5
+ /** The availability endpoint may return either or both lists. */
6
+ export declare const isBookingAvailabilityData: (value: unknown) => boolean;
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.isBookingScheduleList = exports.isBookingResourceList = exports.isBookingAvailabilityData = void 0;
7
+ var _dayjs = _interopRequireDefault(require("dayjs"));
8
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
9
+ const isRecord = value => value !== null && typeof value === 'object' && !Array.isArray(value);
10
+ const isNumericValue = value => (typeof value === 'number' || typeof value === 'string' && value.trim() !== '') && Number.isFinite(Number(value));
11
+ const isDateValue = value => {
12
+ if (typeof value !== 'string' || !value.trim() || !(0, _dayjs.default)(value).isValid()) return false;
13
+ // dayjs accepts overflowing calendar components; do not turn them into another date.
14
+ const dateParts = /^(\d{4})-(\d{2})-(\d{2})(?:$|[ T])/.exec(value);
15
+ if (!dateParts) return true;
16
+ const [, year, month, date] = dateParts.map(Number);
17
+ const calendarDate = new Date(0);
18
+ calendarDate.setUTCFullYear(year, month - 1, date);
19
+ return calendarDate.getUTCFullYear() === year && calendarDate.getUTCMonth() === month - 1 && calendarDate.getUTCDate() === date;
20
+ };
21
+ const isRecordArray = value => Array.isArray(value) && value.every(isRecord);
22
+
23
+ /** Validate only the catalog fields consumed by booking reads, not display metadata. */
24
+ const isBookingScheduleList = value => Array.isArray(value) && value.every(schedule => {
25
+ if (!isRecord(schedule) || !isNumericValue(schedule.id)) return false;
26
+ if (schedule.type === 'time-slots' && !isRecordArray(schedule.time_slot)) return false;
27
+ if (schedule.type === 'designation' && !isRecord(schedule.designation) && !isRecordArray(schedule.designation)) return false;
28
+ if ((schedule.repeat_type === 'daily' || schedule.repeat_type === 'weekly') && !isRecord(schedule.repeat_rule)) return false;
29
+ if (schedule.repeat_rule !== undefined && schedule.repeat_rule !== null) {
30
+ if (!isRecord(schedule.repeat_rule)) return false;
31
+ const rule = schedule.repeat_rule;
32
+ if (rule.end !== undefined && rule.end !== null && !isRecord(rule.end)) return false;
33
+ for (const key of ['excluded_date', 'included_date', 'frequency_date']) {
34
+ if (rule[key] !== undefined && rule[key] !== null && !Array.isArray(rule[key])) return false;
35
+ }
36
+ }
37
+ return true;
38
+ });
39
+
40
+ /** Empty resource/time/event arrays and zero capacity are valid successful results. */
41
+ exports.isBookingScheduleList = isBookingScheduleList;
42
+ const isBookingResourceList = value => Array.isArray(value) && value.every(resource => {
43
+ if (!isRecord(resource) || !isNumericValue(resource.id) || !isNumericValue(resource.form_id) || !Array.isArray(resource.times)) return false;
44
+ if (resource.capacity !== undefined && !isNumericValue(resource.capacity)) return false;
45
+ return resource.times.every(time => isRecord(time) && isDateValue(time.start_at) && isDateValue(time.end_at) && (time.event_list === undefined || isRecordArray(time.event_list)));
46
+ });
47
+
48
+ /** The availability endpoint may return either or both lists. */
49
+ exports.isBookingResourceList = isBookingResourceList;
50
+ const isBookingAvailabilityData = value => {
51
+ if (!isRecord(value) || value.date_list === undefined && value.other_product_ids === undefined) return false;
52
+ if (value.date_list !== undefined && (!Array.isArray(value.date_list) || !value.date_list.every(date => isRecord(date) && isDateValue(date.date)))) return false;
53
+ if (value.other_product_ids !== undefined && (!Array.isArray(value.other_product_ids) || !value.other_product_ids.every(isNumericValue))) return false;
54
+ return true;
55
+ };
56
+ exports.isBookingAvailabilityData = isBookingAvailabilityData;
@@ -56,6 +56,8 @@ export interface CacheProps {
56
56
  * 请求配置
57
57
  */
58
58
  export interface RequestOptions {
59
+ /** Opt in to the host's bounded retry policy for booking availability GETs. */
60
+ bookingRead?: boolean;
59
61
  /** Customer-only, credential-free GET /open/document/{id} on picoding. */
60
62
  publicInvoiceDocument?: boolean;
61
63
  /** Route through the host's configured picoding environment. */
@@ -425,7 +425,7 @@ function buildRewardClaimUrl(shopInfo, shopOrderNumber) {
425
425
  const default_domain = typeof shopInfo.default_domain === 'string' ? shopInfo.default_domain.trim() : '';
426
426
  const private_domain = typeof shopInfo.private_domain === 'string' ? shopInfo.private_domain.trim() : '';
427
427
  // 私有域名优先于默认域名
428
- const domain = private_domain || default_domain;
428
+ const domain = default_domain;
429
429
  const orderNumber = typeof shopOrderNumber === 'string' ? shopOrderNumber.trim() : typeof shopOrderNumber === 'number' && Number.isFinite(shopOrderNumber) ? String(shopOrderNumber) : '';
430
430
  if (!domain || !orderNumber) return undefined;
431
431
  try {
@@ -20,9 +20,20 @@ export declare class BookingByStepImpl extends BaseModule implements Module {
20
20
  private shopStore;
21
21
  private store;
22
22
  private otherParams;
23
+ private scheduleRuntimeParams;
23
24
  private cacheId;
24
25
  private otherData;
25
26
  private platform;
27
+ private productDetailGeneration;
28
+ private sessionAvailabilityRequestVersion;
29
+ private lifecycleGeneration;
30
+ private disposed;
31
+ private resourcePreparation?;
32
+ private staleSelection;
33
+ private resourceSelectionKey;
34
+ /** Semantic selection token for async UI transitions. */
35
+ getBookingSelectionKey(): string;
36
+ private refreshCurrentProductSchedule;
26
37
  initialize(core: PisellCore, options: any): Promise<void>;
27
38
  initStep(stepList: (keyof BookingByStepState)[]): void;
28
39
  getCurrentStep(): {
@@ -108,7 +119,7 @@ export declare class BookingByStepImpl extends BaseModule implements Module {
108
119
  * }
109
120
  * @memberof BookingByStepImpl
110
121
  */
111
- loadScheduleAvailableDate({ startDate, endDate, custom_page_id, channel, }: LoadScheduleAvailableDateParams): Promise<ITime[]>;
122
+ loadScheduleAvailableDate({ startDate, endDate, custom_page_id, channel, assertCurrent, }: LoadScheduleAvailableDateParams): Promise<ITime[]>;
112
123
  addAccount(account: Account | IHolder, extra?: {
113
124
  type: 'account' | 'holder';
114
125
  customerId: number;
@@ -152,7 +163,10 @@ export declare class BookingByStepImpl extends BaseModule implements Module {
152
163
  startDate?: string;
153
164
  endDate?: string;
154
165
  type?: 'month' | 'day';
166
+ assertCurrent?: () => void;
155
167
  }): Promise<ITime[]>;
168
+ /** Prepare the exact cart/date selection before synchronous resource checks. */
169
+ prepareResourcesForCurrentSelection(): Promise<void>;
156
170
  /**
157
171
  * 获取购物车汇总信息
158
172
  */