@pisell/pisellos 0.10.74 → 0.10.75

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.
@@ -10,6 +10,15 @@ export type { ProductListStoreQueryParams } from '../../modules/ProductList';
10
10
  export type { AvailabilityAbsoluteRange, AvailabilityAssignment, AvailabilityCell, AvailabilityDateRange, AvailabilityDisplayRange, AvailabilityErrorCode, AvailabilityId, AvailabilityMode, AvailabilityOccupancy, AvailabilityProduct, AvailabilityProductKind, AvailabilityProjection, AvailabilityProjectionInput, AvailabilityProjectionMeta, AvailabilityQuery, AvailabilityQueryResult, AvailabilityRequirementGroup, AvailabilityRequirementGroupResult, AvailabilityRequirementSelection, AvailabilityResource, AvailabilityResourceOption, AvailabilityResourceType, AvailabilityResourceWindow, AvailabilityScheduleMode, AvailabilityScheduleRef, AvailabilityScheduleRule, AvailabilitySelectionValidationParams, AvailabilitySelectionValidationResult, AvailabilitySessionRange, AvailabilityStatus, DateAvailabilityGroup, DateAvailabilityItem, DateAvailabilityQuery, DateAvailabilityQueryResult, GetProductTimeRangesRequest, ProductAvailabilityGroup, ProductAvailabilityItem, ProductAvailabilityQuery, ProductAvailabilityQueryResult, ProductTimeRange, ProductTimeRangeGroup, QueryAvailabilityBaseRequest, ResourceAvailabilityGroup, ResourceAvailabilityQuery, ResourceAvailabilityQueryResult, ResourceAvailabilityRangeGroup, TimeAvailabilityGroup, TimeAvailabilityItem, TimeAvailabilityQuery, TimeAvailabilityQueryResult, } from '../../modules/ResourcePlanner';
11
11
  export interface UnifiedBookingSalesState extends BookingTicketState {
12
12
  }
13
+ /** Read-only preview scope; existing solution queries remain fresh for selection and submission. */
14
+ export interface UnifiedBookingSalesCatalogQueryBatch {
15
+ queryCatalogSnapshot(params: ProductListLoadProductsParams): Promise<ProductData[]>;
16
+ queryCatalogProductDetail(params: ProductListLoadProductsParams & {
17
+ product_id: number;
18
+ }): Promise<ProductData | undefined>;
19
+ /** Releases retained results. A disposed batch cannot be reused. */
20
+ dispose(): void;
21
+ }
13
22
  export interface UnifiedBookingSalesPolicy {
14
23
  id?: AvailabilityId;
15
24
  title?: unknown;
@@ -1,3 +1,5 @@
1
+ /** Read-only preview scope; existing solution queries remain fresh for selection and submission. */
2
+
1
3
  export var UnifiedBookingSalesHooks = /*#__PURE__*/function (UnifiedBookingSalesHooks) {
2
4
  UnifiedBookingSalesHooks["onAvailabilityProjectionPrepared"] = "unifiedBookingSales:onAvailabilityProjectionPrepared";
3
5
  UnifiedBookingSalesHooks["onAvailabilitySelectionCommitted"] = "unifiedBookingSales:onAvailabilitySelectionCommitted";
@@ -0,0 +1,21 @@
1
+ import type { ProductListLoadProductsParams } from '../../modules/ProductList';
2
+ import type { ProductData } from '../../modules/Product/types';
3
+ import type { UnifiedBookingSalesCatalogQueryBatch } from './types';
4
+ type DetailParams = ProductListLoadProductsParams & {
5
+ product_id: number;
6
+ };
7
+ export interface CatalogQueryRuntime {
8
+ references: unknown[];
9
+ values: unknown;
10
+ /** Late-loaded pricing/schedule data may refresh within the same owner. */
11
+ refreshValues?: unknown;
12
+ }
13
+ /** Internal adapter: membership loaders are never accepted from public callers. */
14
+ export declare function createCatalogQueryBatchAdapter(options: {
15
+ runtime(): CatalogQueryRuntime;
16
+ normalize(params: ProductListLoadProductsParams, now: number): ProductListLoadProductsParams;
17
+ key(params: ProductListLoadProductsParams): string;
18
+ snapshot(params: ProductListLoadProductsParams): Promise<ProductData[]>;
19
+ detail(params: DetailParams, snapshot: UnifiedBookingSalesCatalogQueryBatch['queryCatalogSnapshot']): Promise<ProductData | undefined>;
20
+ }): UnifiedBookingSalesCatalogQueryBatch;
21
+ export {};
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.createCatalogQueryBatchAdapter = createCatalogQueryBatchAdapter;
7
+ var _lodashEs = require("lodash-es");
8
+ const BATCH_MAX_AGE_MS = 60 * 1000;
9
+ // Enough for a 42-day calendar with several product details per day, but bounded.
10
+ const BATCH_MAX_ENTRIES = 512;
11
+
12
+ /** Internal adapter: membership loaders are never accepted from public callers. */
13
+ function createCatalogQueryBatchAdapter(options) {
14
+ let disposed = false;
15
+ let epoch;
16
+ const sameOwner = (left, right) => left.references.length === right.references.length && left.references.every((ref, index) => ref === right.references[index]) && (0, _lodashEs.isEqual)(left.values, right.values);
17
+ const fail = code => Object.assign(new Error(code === 'CATALOG_QUERY_BATCH_DISPOSED' ? 'The catalog query batch is closed. Create a new batch before querying.' : 'The catalog context changed while loading. Please retry.'), {
18
+ code
19
+ });
20
+ const current = () => {
21
+ if (disposed) throw fail('CATALOG_QUERY_BATCH_DISPOSED');
22
+ const now = Date.now();
23
+ const runtime = options.runtime();
24
+ if (!epoch || now < epoch.startedAt || now - epoch.startedAt >= BATCH_MAX_AGE_MS || !sameOwner(runtime, epoch.runtime) || !(0, _lodashEs.isEqual)(runtime.refreshValues, epoch.runtime.refreshValues)) {
25
+ epoch?.entries.clear();
26
+ epoch = {
27
+ runtime: {
28
+ references: [...runtime.references],
29
+ values: (0, _lodashEs.cloneDeep)(runtime.values),
30
+ refreshValues: (0, _lodashEs.cloneDeep)(runtime.refreshValues)
31
+ },
32
+ startedAt: now,
33
+ entries: new Map()
34
+ };
35
+ }
36
+ return epoch;
37
+ };
38
+ const assertEpoch = owner => {
39
+ const next = current();
40
+ if (next !== owner) throw Object.assign(fail('CATALOG_QUERY_BATCH_STALE'), {
41
+ retryable: sameOwner(owner.runtime, next.runtime)
42
+ });
43
+ };
44
+ const run = async load => {
45
+ for (let attempt = 0;; attempt++) {
46
+ try {
47
+ return await load(current());
48
+ } catch (error) {
49
+ const failure = error;
50
+ // Drop the old result and reread under the new configuration. Never replay
51
+ // a network error, disposed batch or a request belonging to a different user/store.
52
+ if (attempt >= 2 || failure?.code !== 'CATALOG_QUERY_BATCH_STALE' || !failure.retryable) throw error;
53
+ }
54
+ }
55
+ };
56
+ const read = async (owner, key, load) => {
57
+ assertEpoch(owner);
58
+ let promise = owner.entries.get(key);
59
+ if (promise) {
60
+ owner.entries.delete(key);
61
+ owner.entries.set(key, promise);
62
+ } else {
63
+ promise = Promise.resolve().then(() => {
64
+ assertEpoch(owner);
65
+ return load();
66
+ }).then(value => (0, _lodashEs.cloneDeep)(value));
67
+ owner.entries.set(key, promise);
68
+ while (owner.entries.size > BATCH_MAX_ENTRIES) owner.entries.delete(owner.entries.keys().next().value);
69
+ }
70
+ try {
71
+ const result = await promise;
72
+ assertEpoch(owner);
73
+ return (0, _lodashEs.cloneDeep)(result);
74
+ } catch (error) {
75
+ if (owner.entries.get(key) === promise) owner.entries.delete(key);
76
+ throw error;
77
+ }
78
+ };
79
+ const snapshotFor = async (owner, input) => {
80
+ assertEpoch(owner);
81
+ const {
82
+ product_ids,
83
+ ...scope
84
+ } = options.normalize((0, _lodashEs.cloneDeep)(input), owner.startedAt);
85
+ // The membership scope is always the whole menu; ID filtering is only a detached view.
86
+ const products = await read(owner, `list:${options.key(scope)}`, () => options.snapshot(scope));
87
+ return product_ids?.length ? products.filter(product => product_ids.some(id => Number(id) === Number(product.id))) : products;
88
+ };
89
+ return {
90
+ queryCatalogSnapshot: params => run(owner => snapshotFor(owner, params)),
91
+ queryCatalogProductDetail: input => run(owner => {
92
+ const {
93
+ product_id,
94
+ product_ids: _ignored,
95
+ ...scope
96
+ } = (0, _lodashEs.cloneDeep)(input);
97
+ const params = {
98
+ ...options.normalize(scope, owner.startedAt),
99
+ product_id
100
+ };
101
+ return read(owner, `detail:${options.key(params)}`, () => options.detail(params, query => snapshotFor(owner, query)));
102
+ }),
103
+ dispose: () => {
104
+ disposed = true;
105
+ epoch?.entries.clear();
106
+ epoch = undefined;
107
+ }
108
+ };
109
+ }
@@ -6,7 +6,7 @@ import { type InvoiceLayoutConfig, type InvoiceTemplateSettings, type OpenDataCo
6
6
  import type { LoadScheduleAvailableDateParams, ScheduleItem } from '../../modules/Schedule/types';
7
7
  import type { ProductListLoadProductsParams, ProductListStoreQueryParams } from '../../modules/ProductList';
8
8
  import type { AvailabilityDateRange, AvailabilityOccupancy, AvailabilityProduct, AvailabilityResource, GetProductTimeRangesRequest } from '../../modules/ResourcePlanner';
9
- import type { AvailabilityContextRef, ContextualAvailabilityQuery, ContextualAvailabilityQueryResult, ContextualCommitAvailabilitySelectionParams, ContextualProductTimeRangeGroup, UnifiedBookingSalesAddRetailProductParams, UnifiedBookingSalesApplyPlannerDiscountsParams, UnifiedBookingSalesCommitAvailabilitySelectionResult, UnifiedBookingSalesDiscountResult, UnifiedBookingSalesLoadProductsByScheduleDateParams, UnifiedBookingSalesLoadOpenDataParams, UnifiedBookingSalesPrepareAvailabilityProjectionParams, UnifiedBookingSalesPolicyResponse, UnifiedBookingSalesQueryBookingResourceDetailsParams, UnifiedBookingSalesResourceDetail, UnifiedBookingSalesResolveProductAllergyRequirementParams, UnifiedBookingSalesStageRetailProductsParams, UnifiedBookingSalesState } from './types';
9
+ import type { AvailabilityContextRef, ContextualAvailabilityQuery, ContextualAvailabilityQueryResult, ContextualCommitAvailabilitySelectionParams, ContextualProductTimeRangeGroup, UnifiedBookingSalesAddRetailProductParams, UnifiedBookingSalesCatalogQueryBatch, UnifiedBookingSalesApplyPlannerDiscountsParams, UnifiedBookingSalesCommitAvailabilitySelectionResult, UnifiedBookingSalesDiscountResult, UnifiedBookingSalesLoadProductsByScheduleDateParams, UnifiedBookingSalesLoadOpenDataParams, UnifiedBookingSalesPrepareAvailabilityProjectionParams, UnifiedBookingSalesPolicyResponse, UnifiedBookingSalesQueryBookingResourceDetailsParams, UnifiedBookingSalesResourceDetail, UnifiedBookingSalesResolveProductAllergyRequirementParams, UnifiedBookingSalesStageRetailProductsParams, UnifiedBookingSalesState } from './types';
10
10
  import type { BusinessAvailability } from '../../modules/BusinessAvailability';
11
11
  import { BookingTicket } from '../BookingTicket';
12
12
  import type { AllergyRequirement } from '../../model/strategy/adapter/itemRule';
@@ -225,6 +225,13 @@ export declare class UnifiedBookingSalesImpl extends BookingTicket {
225
225
  queryCatalogProductDetail(params: ProductListLoadProductsParams & {
226
226
  product_id: number;
227
227
  }): Promise<ProductData | undefined>;
228
+ /**
229
+ * Opt-in calendar/card preview batching. Results expire after sixty seconds or a
230
+ * runtime change; the next read starts a fresh clock/cache. Selection and submit
231
+ * must keep using the ordinary fresh query methods. Call dispose on owner cleanup.
232
+ */
233
+ createCatalogQueryBatch(): UnifiedBookingSalesCatalogQueryBatch;
234
+ private loadCatalogProductDetail;
228
235
  private loadCatalogProducts;
229
236
  queryProducts(params?: ProductListStoreQueryParams): Promise<ProductData[]>;
230
237
  /** Date-first entry point. It delegates protocol details and cache ownership to ScheduleModule. */
@@ -64,6 +64,7 @@ Object.keys(_types).forEach(function (key) {
64
64
  });
65
65
  var _remoteOccupancyCache = require("./remoteOccupancyCache");
66
66
  var _businessAvailability = require("./businessAvailability");
67
+ var _catalogQueryBatch = require("./catalogQueryBatch");
67
68
  var _BookingTicket = require("../BookingTicket");
68
69
  var _localClock = require("../../modules/ResourcePlanner/localClock");
69
70
  var _platform = require("../../utils/platform");
@@ -2211,6 +2212,100 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2211
2212
 
2212
2213
  /** Full SKU/bundle detail, after verifying membership in the explicit day/menu scope. */
2213
2214
  async queryCatalogProductDetail(params) {
2215
+ return this.loadCatalogProductDetail(params, query => this.queryCatalogSnapshot(query));
2216
+ }
2217
+
2218
+ /**
2219
+ * Opt-in calendar/card preview batching. Results expire after sixty seconds or a
2220
+ * runtime change; the next read starts a fresh clock/cache. Selection and submit
2221
+ * must keep using the ordinary fresh query methods. Call dispose on owner cleanup.
2222
+ */
2223
+ createCatalogQueryBatch() {
2224
+ return (0, _catalogQueryBatch.createCatalogQueryBatchAdapter)({
2225
+ runtime: () => {
2226
+ if (this.runtimeOpenDataDestroyed) throw new Error('The booking service is closed.');
2227
+ const user = this.core.getPlugin?.('user');
2228
+ const productParams = this.store.products?.otherParams || this.otherParams || {};
2229
+ const fatherModule = String(productParams.fatherModule || '').trim();
2230
+ const schedule = (fatherModule ? this.core.getModule?.(`${fatherModule}_schedule`) : null) || this.core.getModule?.('schedule');
2231
+ const evaluator = this.core.context?.dataVariantEvaluator;
2232
+ // OpenData hydration is not a catalog input. Its temporary null/reload cycle
2233
+ // must not expire a batch while a parallel preview reads sales settings.
2234
+ const {
2235
+ openData: _openData,
2236
+ ...otherParams
2237
+ } = this.otherParams || {};
2238
+ const {
2239
+ openData: _productOpenData,
2240
+ ...productOtherParams
2241
+ } = productParams;
2242
+ return {
2243
+ references: [this.core, this.request, this.store.products, this.core.server, user, this.appPlugin, this.core.getPlugin?.('request'), this.core.getPlugin?.('app'), schedule, evaluator],
2244
+ values: {
2245
+ initialization: this.runtimeInitializationGeneration,
2246
+ scope: this.getRuntimeOpenDataScope(),
2247
+ requestBaseUrl: this.request.baseUrl,
2248
+ customerId: user?.get?.()?.id,
2249
+ otherParams,
2250
+ productOtherParams
2251
+ },
2252
+ refreshValues: {
2253
+ scheduleList: schedule?.getScheduleList?.(),
2254
+ contextScheduleList: this.core.context?.scheduleList,
2255
+ contextMenuList: this.core.context?.menuList,
2256
+ strategyConfigs: evaluator?.getStrategyConfigs?.()
2257
+ }
2258
+ };
2259
+ },
2260
+ normalize: (params, now) => {
2261
+ const date = params.schedule_date || (0, _dayjs.default)(now).format('YYYY-MM-DD');
2262
+ const user = this.core.getPlugin?.('user');
2263
+ const explicitCustomer = params.customer_id;
2264
+ if (explicitCustomer != null && (!Number.isSafeInteger(Number(explicitCustomer)) || Number(explicitCustomer) <= 0)) {
2265
+ throw new Error('Catalog query customer_id must be a positive integer.');
2266
+ }
2267
+ const fallbackCustomer = user?.get?.()?.id;
2268
+ const customer = explicitCustomer ?? (Number.isSafeInteger(Number(fallbackCustomer)) && Number(fallbackCustomer) > 0 ? Number(fallbackCustomer) : undefined);
2269
+ const productParams = this.store.products?.otherParams || this.otherParams || {};
2270
+ const channelMap = {
2271
+ online_store: 'online-store',
2272
+ scan_to_order: 'online-store',
2273
+ 'scan-to-order': 'online-store',
2274
+ scan_to_order_2: 'online-store',
2275
+ scan_to_order_3: 'scantoorder3'
2276
+ };
2277
+ const channel = channelMap[productParams.channel] || productParams.channel;
2278
+ const businessCode = productParams.businessCode ?? productParams.business_code;
2279
+ const sorted = items => [...new Set(items)].sort((a, b) => String(a).localeCompare(String(b)));
2280
+ return {
2281
+ ...params,
2282
+ menu_list_ids: Array.isArray(params.menu_list_ids) ? sorted(params.menu_list_ids) : params.menu_list_ids,
2283
+ category_ids: sorted(params.category_ids || []),
2284
+ collection: Array.isArray(params.collection) ? sorted(params.collection) : params.collection,
2285
+ extension_type: params.extension_type ? sorted(params.extension_type) : undefined,
2286
+ with_count: sorted(params.with_count ?? ['bundleGroup', 'optionGroup']),
2287
+ with_schedule: params.with_schedule ?? 1,
2288
+ status: params.status ?? 'published',
2289
+ schedule_date: date,
2290
+ schedule_datetime: params.schedule_datetime || `${date} ${(0, _dayjs.default)(now).format('HH:mm:ss')}`,
2291
+ customer_id: customer == null ? undefined : Number(customer),
2292
+ strategy_context: {
2293
+ ...(channel ? {
2294
+ channel
2295
+ } : {}),
2296
+ ...(businessCode ? {
2297
+ business_code: businessCode
2298
+ } : {}),
2299
+ ...(params.strategy_context || {})
2300
+ }
2301
+ };
2302
+ },
2303
+ key: params => JSON.stringify(stableValue(params)),
2304
+ snapshot: params => this.queryCatalogSnapshot(params),
2305
+ detail: (params, snapshot) => this.loadCatalogProductDetail(params, snapshot)
2306
+ });
2307
+ }
2308
+ async loadCatalogProductDetail(params, loadSnapshot) {
2214
2309
  const {
2215
2310
  product_id,
2216
2311
  product_ids: _ignoredIds,
@@ -2224,7 +2319,7 @@ class UnifiedBookingSalesImpl extends _BookingTicket.BookingTicket {
2224
2319
  schedule_date,
2225
2320
  schedule_datetime
2226
2321
  };
2227
- const member = (await this.queryCatalogSnapshot(scopedParams)).find(item => Number(item.id) === product_id);
2322
+ const member = (await loadSnapshot(scopedParams)).find(item => Number(item.id) === product_id);
2228
2323
  if (!member) return undefined;
2229
2324
  const baseUrl = String(this.request.baseUrl || ((0, _platform.isCustomerUserPlatform)(this.otherParams?.platform) ? '/h5' : '/shop')).replace(/\/+$/, '');
2230
2325
  const localPath = `/product/query/${product_id}`;
@@ -10,6 +10,15 @@ export type { ProductListStoreQueryParams } from '../../modules/ProductList';
10
10
  export type { AvailabilityAbsoluteRange, AvailabilityAssignment, AvailabilityCell, AvailabilityDateRange, AvailabilityDisplayRange, AvailabilityErrorCode, AvailabilityId, AvailabilityMode, AvailabilityOccupancy, AvailabilityProduct, AvailabilityProductKind, AvailabilityProjection, AvailabilityProjectionInput, AvailabilityProjectionMeta, AvailabilityQuery, AvailabilityQueryResult, AvailabilityRequirementGroup, AvailabilityRequirementGroupResult, AvailabilityRequirementSelection, AvailabilityResource, AvailabilityResourceOption, AvailabilityResourceType, AvailabilityResourceWindow, AvailabilityScheduleMode, AvailabilityScheduleRef, AvailabilityScheduleRule, AvailabilitySelectionValidationParams, AvailabilitySelectionValidationResult, AvailabilitySessionRange, AvailabilityStatus, DateAvailabilityGroup, DateAvailabilityItem, DateAvailabilityQuery, DateAvailabilityQueryResult, GetProductTimeRangesRequest, ProductAvailabilityGroup, ProductAvailabilityItem, ProductAvailabilityQuery, ProductAvailabilityQueryResult, ProductTimeRange, ProductTimeRangeGroup, QueryAvailabilityBaseRequest, ResourceAvailabilityGroup, ResourceAvailabilityQuery, ResourceAvailabilityQueryResult, ResourceAvailabilityRangeGroup, TimeAvailabilityGroup, TimeAvailabilityItem, TimeAvailabilityQuery, TimeAvailabilityQueryResult, } from '../../modules/ResourcePlanner';
11
11
  export interface UnifiedBookingSalesState extends BookingTicketState {
12
12
  }
13
+ /** Read-only preview scope; existing solution queries remain fresh for selection and submission. */
14
+ export interface UnifiedBookingSalesCatalogQueryBatch {
15
+ queryCatalogSnapshot(params: ProductListLoadProductsParams): Promise<ProductData[]>;
16
+ queryCatalogProductDetail(params: ProductListLoadProductsParams & {
17
+ product_id: number;
18
+ }): Promise<ProductData | undefined>;
19
+ /** Releases retained results. A disposed batch cannot be reused. */
20
+ dispose(): void;
21
+ }
13
22
  export interface UnifiedBookingSalesPolicy {
14
23
  id?: AvailabilityId;
15
24
  title?: unknown;
@@ -4,6 +4,7 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.UnifiedBookingSalesHooks = void 0;
7
+ /** Read-only preview scope; existing solution queries remain fresh for selection and submission. */
7
8
  let UnifiedBookingSalesHooks = exports.UnifiedBookingSalesHooks = /*#__PURE__*/function (UnifiedBookingSalesHooks) {
8
9
  UnifiedBookingSalesHooks["onAvailabilityProjectionPrepared"] = "unifiedBookingSales:onAvailabilityProjectionPrepared";
9
10
  UnifiedBookingSalesHooks["onAvailabilitySelectionCommitted"] = "unifiedBookingSales:onAvailabilitySelectionCommitted";
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "private": false,
3
3
  "name": "@pisell/pisellos",
4
- "version": "0.10.74",
4
+ "version": "0.10.75",
5
5
  "description": "一个可扩展的前端模块化SDK框架,支持插件系统",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",