@jay-framework/wix-bookings 0.25.4 → 0.25.5

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.
@@ -1,9 +1,476 @@
1
1
  import { makeJayInit, makeJayStackComponent } from "@jay-framework/fullstack-component";
2
+ import { createJayContext, useGlobalContext, registerGlobalContext } from "@jay-framework/runtime";
3
+ import { wixFetch, WixApiError, WIX_CLIENT_CONTEXT } from "@jay-framework/wix-server-client/client";
2
4
  import { createSignal } from "@jay-framework/component";
3
5
  import { createActionCaller } from "@jay-framework/stack-client-runtime";
4
- import { WixApiError } from "@jay-framework/wix-server-client/client";
5
- const init = makeJayInit().withClient(async () => {
6
- console.log("[wix-bookings] Client ready (no client context required)");
6
+ const MAX_SLOTS_PER_QUERY = 200;
7
+ const SERVICES_PAGE_SIZE = 100;
8
+ async function queryBookingServices(client, bookingAppId) {
9
+ const allServices = [];
10
+ let offset = 0;
11
+ let hasMorePages = true;
12
+ while (hasMorePages) {
13
+ const result = await wixFetch(
14
+ client,
15
+ "/bookings/v2/services/query",
16
+ {
17
+ method: "POST",
18
+ body: {
19
+ query: {
20
+ filter: { appId: bookingAppId },
21
+ paging: { limit: SERVICES_PAGE_SIZE, offset }
22
+ },
23
+ conditionalFields: ["STAFF_MEMBER_DETAILS"]
24
+ }
25
+ }
26
+ );
27
+ const batch = result.services ?? [];
28
+ allServices.push(...batch);
29
+ hasMorePages = batch.length >= SERVICES_PAGE_SIZE;
30
+ if (hasMorePages) {
31
+ offset += SERVICES_PAGE_SIZE;
32
+ }
33
+ }
34
+ return allServices;
35
+ }
36
+ async function getBookingServiceById(client, serviceId) {
37
+ const result = await wixFetch(client, "/bookings/v2/services/query", {
38
+ method: "POST",
39
+ body: {
40
+ query: {
41
+ filter: { _id: serviceId },
42
+ paging: { limit: 1 }
43
+ }
44
+ }
45
+ });
46
+ return result.services?.[0];
47
+ }
48
+ function formatPrice(service) {
49
+ const price = service.payment?.fixed?.price;
50
+ if (!price?.value) {
51
+ return "Free";
52
+ }
53
+ const amount = parseFloat(price.value);
54
+ return `${price.currency ?? ""} ${amount.toFixed(2)}`.trim();
55
+ }
56
+ function formatDurationMinutes(service) {
57
+ const minutes = service.schedule?.availabilityConstraints?.sessionDurations?.[0];
58
+ if (!minutes) {
59
+ return "";
60
+ }
61
+ return `${minutes} min`;
62
+ }
63
+ function mapService(raw) {
64
+ const duration = formatDurationMinutes(raw);
65
+ return {
66
+ id: raw._id ?? raw.id ?? "",
67
+ name: raw.name ?? "Service",
68
+ type: raw.type ?? "APPOINTMENT",
69
+ description: raw.description ?? "",
70
+ priceLabel: formatPrice(raw),
71
+ durationLabel: duration,
72
+ formId: raw.form?._id ?? ""
73
+ };
74
+ }
75
+ function createSlotId(resourceId, localStartDate) {
76
+ return `${resourceId}:${localStartDate}`;
77
+ }
78
+ function formatSlotLabel(localStartDate) {
79
+ const date = new Date(localStartDate);
80
+ return date.toLocaleString([], {
81
+ weekday: "short",
82
+ month: "short",
83
+ day: "numeric",
84
+ hour: "2-digit",
85
+ minute: "2-digit"
86
+ });
87
+ }
88
+ function mapAppointmentSlot(slot) {
89
+ if (!slot.scheduleId || !slot.localStartDate || !slot.localEndDate) {
90
+ return null;
91
+ }
92
+ return {
93
+ id: createSlotId(slot.scheduleId, slot.localStartDate),
94
+ localStartDate: slot.localStartDate,
95
+ localEndDate: slot.localEndDate,
96
+ label: formatSlotLabel(slot.localStartDate),
97
+ scheduleId: slot.scheduleId,
98
+ serviceType: "APPOINTMENT"
99
+ };
100
+ }
101
+ function mapClassSlot(slot) {
102
+ const eventId = slot.eventInfo?.eventId;
103
+ if (!eventId || !slot.localStartDate || !slot.localEndDate) {
104
+ return null;
105
+ }
106
+ return {
107
+ id: createSlotId(eventId, slot.localStartDate),
108
+ localStartDate: slot.localStartDate,
109
+ localEndDate: slot.localEndDate,
110
+ label: formatSlotLabel(slot.localStartDate),
111
+ eventId,
112
+ serviceType: "CLASS"
113
+ };
114
+ }
115
+ function localDateStrInTimeZone(date, timeZone) {
116
+ const parts = new Intl.DateTimeFormat("en-US", {
117
+ timeZone,
118
+ year: "numeric",
119
+ month: "2-digit",
120
+ day: "2-digit",
121
+ hour: "2-digit",
122
+ minute: "2-digit",
123
+ second: "2-digit",
124
+ hour12: false
125
+ }).formatToParts(date);
126
+ const read = (type) => parts.find((part) => part.type === type)?.value ?? "00";
127
+ const hour = read("hour") === "24" ? "00" : read("hour");
128
+ return `${read("year")}-${read("month")}-${read("day")}T${hour}:${read("minute")}:${read("second")}`;
129
+ }
130
+ function paymentPreferenceFromService(service) {
131
+ const opts = service.payment?.options ?? {};
132
+ if (opts.online && !opts.inPerson) {
133
+ return "ONLINE";
134
+ }
135
+ if (!opts.online && opts.inPerson) {
136
+ return "OFFLINE";
137
+ }
138
+ return "ONLINE";
139
+ }
140
+ async function createBookingRecord(client, body) {
141
+ return wixFetch(client, "/bookings/v2/bookings", { method: "POST", body });
142
+ }
143
+ async function createBookingCart(client, bookingId, bookingAppId) {
144
+ return wixFetch(client, "/ecom/v2/carts", {
145
+ method: "POST",
146
+ body: {
147
+ catalogItems: [
148
+ {
149
+ quantity: 1,
150
+ catalogReference: { catalogItemId: bookingId, appId: bookingAppId }
151
+ }
152
+ ],
153
+ cart: { source: { channelType: "WEB" } }
154
+ }
155
+ });
156
+ }
157
+ async function calculateBookingCart(client, cartId) {
158
+ return wixFetch(client, `/ecom/v2/carts/${cartId}/calculate`, { method: "POST", body: {} });
159
+ }
160
+ async function placeBookingOrder(client, cartId) {
161
+ const res = await wixFetch(
162
+ client,
163
+ `/ecom/v2/carts/${cartId}/place-order`,
164
+ { method: "POST", body: {} }
165
+ );
166
+ return { orderId: res?.orderId };
167
+ }
168
+ async function createBookingRedirectSession(client, cartId, postFlowUrl) {
169
+ return wixFetch(client, "/headless/v1/redirect-session", {
170
+ method: "POST",
171
+ body: {
172
+ ecomCheckout: { checkoutId: cartId },
173
+ callbacks: { postFlowUrl }
174
+ }
175
+ });
176
+ }
177
+ async function getBookingCheckoutUrl(client, cartId) {
178
+ return wixFetch(client, `/ecom/v2/carts/${cartId}/get-checkout-url`, {
179
+ method: "POST",
180
+ body: {}
181
+ });
182
+ }
183
+ const AVAILABILITY_PAGE_SIZE = 100;
184
+ async function listAvailabilityTimeSlots(client, input, options) {
185
+ const allSlots = [];
186
+ const maxSlots = options?.maxSlots;
187
+ let cursor;
188
+ let hasMorePages = true;
189
+ while (hasMorePages) {
190
+ const result = await wixFetch(
191
+ client,
192
+ "/_api/service-availability/v2/time-slots",
193
+ {
194
+ method: "POST",
195
+ body: {
196
+ serviceId: input.serviceId,
197
+ fromLocalDate: input.fromLocalDate,
198
+ toLocalDate: input.toLocalDate,
199
+ timeZone: input.timeZone,
200
+ bookable: true,
201
+ cursorPaging: cursor ? { cursor, limit: AVAILABILITY_PAGE_SIZE } : { limit: AVAILABILITY_PAGE_SIZE }
202
+ }
203
+ }
204
+ );
205
+ allSlots.push(...result.timeSlots ?? []);
206
+ if (allSlots.length >= maxSlots) {
207
+ return allSlots.slice(0, maxSlots);
208
+ }
209
+ cursor = result.pagingMetadata?.cursors?.next;
210
+ hasMorePages = !!cursor && result.pagingMetadata?.hasNext !== false;
211
+ }
212
+ return allSlots;
213
+ }
214
+ const EVENT_SLOTS_PAGE_SIZE = 100;
215
+ async function listEventTimeSlots(client, input, options) {
216
+ const allSlots = [];
217
+ const maxSlots = options?.maxSlots;
218
+ let cursor;
219
+ let hasMorePages = true;
220
+ while (hasMorePages) {
221
+ const result = await wixFetch(
222
+ client,
223
+ "/_api/service-availability/v2/time-slots/event",
224
+ {
225
+ method: "POST",
226
+ body: {
227
+ serviceIds: input.serviceIds,
228
+ fromLocalDate: input.fromLocalDate,
229
+ toLocalDate: input.toLocalDate,
230
+ timeZone: input.timeZone,
231
+ includeNonBookable: false,
232
+ cursorPaging: cursor ? { cursor, limit: EVENT_SLOTS_PAGE_SIZE } : { limit: EVENT_SLOTS_PAGE_SIZE }
233
+ }
234
+ }
235
+ );
236
+ allSlots.push(...result.timeSlots ?? []);
237
+ if (allSlots.length >= maxSlots) {
238
+ return allSlots.slice(0, maxSlots);
239
+ }
240
+ cursor = result.pagingMetadata?.cursors?.next;
241
+ hasMorePages = !!cursor && result.pagingMetadata?.hasNext !== false;
242
+ }
243
+ return allSlots;
244
+ }
245
+ async function resolvePaidCheckoutRedirectUrl(wixClient, cartId, postFlowUrl) {
246
+ try {
247
+ const redirectData = await createBookingRedirectSession(wixClient, cartId, postFlowUrl);
248
+ const redirectUrl = redirectData.redirectSession?.fullUrl;
249
+ if (redirectUrl) {
250
+ return redirectUrl;
251
+ }
252
+ } catch (error) {
253
+ if (!(error instanceof WixApiError) || error.status !== 400 && error.status !== 404) {
254
+ throw error;
255
+ }
256
+ }
257
+ const checkoutUrlData = await getBookingCheckoutUrl(wixClient, cartId);
258
+ const checkoutUrl = checkoutUrlData.checkoutUrl;
259
+ if (!checkoutUrl) {
260
+ throw new Error(
261
+ "Checkout redirect failed. Add your site origin to Allowed redirect domains in Wix Headless Settings, or publish the site so get-checkout-url can return a checkout page."
262
+ );
263
+ }
264
+ return checkoutUrl;
265
+ }
266
+ function createWixBookingsService(wixClient, config) {
267
+ return {
268
+ async listServices() {
269
+ const items = await queryBookingServices(wixClient, config.bookingAppId);
270
+ return items.filter((item) => !item.hidden).map((item) => mapService(item));
271
+ },
272
+ async listSlots({ serviceId, serviceType, timezone, windowDays }) {
273
+ const now = /* @__PURE__ */ new Date();
274
+ const tz = timezone ?? "UTC";
275
+ const from = localDateStrInTimeZone(now, tz);
276
+ const days = windowDays ?? config.slotWindowDays;
277
+ const to = new Date(now.getTime() + days * 24 * 60 * 60 * 1e3);
278
+ const toStr = localDateStrInTimeZone(to, tz);
279
+ const slotQueryOptions = { maxSlots: MAX_SLOTS_PER_QUERY };
280
+ if (serviceType === "APPOINTMENT") {
281
+ const timeSlots2 = await listAvailabilityTimeSlots(
282
+ wixClient,
283
+ {
284
+ serviceId,
285
+ fromLocalDate: from,
286
+ toLocalDate: toStr,
287
+ timeZone: tz
288
+ },
289
+ slotQueryOptions
290
+ );
291
+ return timeSlots2.map((slot) => mapAppointmentSlot(slot)).filter((slot) => slot !== null);
292
+ }
293
+ const timeSlots = await listEventTimeSlots(
294
+ wixClient,
295
+ {
296
+ serviceIds: [serviceId],
297
+ fromLocalDate: from,
298
+ toLocalDate: toStr,
299
+ timeZone: tz
300
+ },
301
+ slotQueryOptions
302
+ );
303
+ return timeSlots.map((slot) => mapClassSlot(slot)).filter((slot) => slot !== null);
304
+ },
305
+ async createBooking(input) {
306
+ const rawService = await getBookingServiceById(wixClient, input.serviceId);
307
+ const paymentPreference = input.paymentPreference ?? (rawService ? paymentPreferenceFromService(
308
+ rawService
309
+ ) : "ONLINE");
310
+ const slotData = {
311
+ serviceId: input.serviceId,
312
+ startDate: input.slot.localStartDate,
313
+ endDate: input.slot.localEndDate,
314
+ timezone: input.timezone,
315
+ location: { locationType: "OWNER_BUSINESS" },
316
+ // Any staff member of the configured staff resource type; without one, the slot's own (a class
317
+ // session names its staff; Wix rejects an empty resource type id).
318
+ ...config.staffResourceTypeId ? {
319
+ resourceSelections: [
320
+ {
321
+ resourceTypeId: config.staffResourceTypeId,
322
+ selectionMethod: "ANY_RESOURCE"
323
+ }
324
+ ]
325
+ } : {}
326
+ };
327
+ if (input.serviceType === "APPOINTMENT") {
328
+ slotData.scheduleId = input.slot.scheduleId;
329
+ } else {
330
+ slotData.eventId = input.slot.eventId;
331
+ }
332
+ const bookingData = await createBookingRecord(wixClient, {
333
+ booking: {
334
+ bookedEntity: { slot: slotData },
335
+ selectedPaymentOption: paymentPreference,
336
+ totalParticipants: 1
337
+ },
338
+ formSubmission: input.formValues
339
+ });
340
+ const bookingId = bookingData.booking.id;
341
+ const cartData = await createBookingCart(wixClient, bookingId, config.bookingAppId);
342
+ const cartId = cartData.cart.id;
343
+ const calcData = await calculateBookingCart(wixClient, cartId);
344
+ const total = parseFloat(calcData.summary?.priceSummary?.total?.amount ?? "0");
345
+ if (total > 0) {
346
+ const postFlowUrl = new URL(config.postCheckoutUrl, input.siteOrigin).href;
347
+ const redirectUrl = await resolvePaidCheckoutRedirectUrl(
348
+ wixClient,
349
+ cartId,
350
+ postFlowUrl
351
+ );
352
+ return { outcome: "redirect", redirectUrl };
353
+ }
354
+ const { orderId } = await placeBookingOrder(wixClient, cartId);
355
+ return { outcome: "confirmed", ...orderId ? { orderId } : {} };
356
+ }
357
+ };
358
+ }
359
+ function canBookOnline(features, type, step) {
360
+ if (type === "COURSE") return step !== "form" || features.courses;
361
+ return type === "CLASS" ? features.groups : features.appointments;
362
+ }
363
+ const WIX_BOOKINGS_CONTEXT = createJayContext("wix:bookings");
364
+ function createWixBookingsContext(wixClient, config) {
365
+ let settings;
366
+ const readSettings = () => {
367
+ if (!settings) {
368
+ settings = wixFetch(
369
+ wixClient,
370
+ "/_api/bookings-settings/v2/settings?fields=FEATURES&fields=SITE_PROPERTIES"
371
+ ).then((res) => res.bookingsSettings).catch(() => {
372
+ settings = void 0;
373
+ return void 0;
374
+ });
375
+ }
376
+ return settings;
377
+ };
378
+ const service = createWixBookingsService(wixClient, config);
379
+ const ownBookings = async (filter) => {
380
+ const res = await wixFetch(wixClient, "/_api/bookings-reader/v2/extended-bookings/query", {
381
+ method: "POST",
382
+ body: {
383
+ query: { filter, cursorPaging: { limit: 100 } },
384
+ withBookingAllowedActions: false
385
+ }
386
+ }).catch(() => ({ extendedBookings: [] }));
387
+ return (res.extendedBookings ?? []).map((e) => e.booking ?? {});
388
+ };
389
+ return {
390
+ async features() {
391
+ const f = (await readSettings())?.features ?? {};
392
+ return {
393
+ groups: Boolean(f.bookingsGroups?.enabled),
394
+ appointments: Boolean(f.bookingsAppointments?.enabled),
395
+ courses: Boolean(f.bookingsCourses?.enabled),
396
+ payments: Boolean(f.bookingsPayments?.enabled)
397
+ };
398
+ },
399
+ async timeZone() {
400
+ return (await readSettings())?.siteProperties?.timeZone ?? "UTC";
401
+ },
402
+ async serviceBySlug(slug) {
403
+ const res = await wixFetch(
404
+ wixClient,
405
+ "/bookings/v2/services/query",
406
+ {
407
+ method: "POST",
408
+ body: {
409
+ query: {
410
+ filter: { "supportedSlugs.name": slug, hidden: false },
411
+ paging: { limit: 1 }
412
+ }
413
+ }
414
+ }
415
+ );
416
+ return res.services?.[0];
417
+ },
418
+ serviceById(id) {
419
+ return getBookingServiceById(wixClient, id);
420
+ },
421
+ async timeSlots(query) {
422
+ const res = await wixFetch(
423
+ wixClient,
424
+ "/_api/service-availability/v2/time-slots/event",
425
+ {
426
+ method: "POST",
427
+ body: {
428
+ serviceIds: query.serviceIds,
429
+ timeZone: query.timeZone,
430
+ fromLocalDate: query.fromLocalDate,
431
+ toLocalDate: query.toLocalDate,
432
+ includeNonBookable: query.includeNonBookable ?? true,
433
+ ...query.maxSlotsPerDay ? { maxSlotsPerDay: query.maxSlotsPerDay } : {},
434
+ eventFilter: {},
435
+ cursorPaging: { limit: query.limit ?? 1e3 }
436
+ }
437
+ }
438
+ );
439
+ return res.timeSlots ?? [];
440
+ },
441
+ createBooking: service.createBooking,
442
+ async serviceBookings(serviceId) {
443
+ return (await ownBookings({
444
+ "bookedEntity.slot.serviceId": serviceId,
445
+ status: { $in: ["CONFIRMED", "PENDING"] }
446
+ })).filter((b) => b.id || b.startDate);
447
+ },
448
+ async bookingById(bookingId) {
449
+ return (await ownBookings({ id: bookingId }))[0];
450
+ },
451
+ async orderById(orderId) {
452
+ try {
453
+ const res = await wixFetch(
454
+ wixClient,
455
+ `/ecom/v1/orders/${encodeURIComponent(orderId)}`
456
+ );
457
+ return res.order;
458
+ } catch (error) {
459
+ if (error instanceof WixApiError) return void 0;
460
+ throw error;
461
+ }
462
+ }
463
+ };
464
+ }
465
+ function provideWixBookingsContext(config) {
466
+ const client = useGlobalContext(WIX_CLIENT_CONTEXT)?.client;
467
+ if (!client) return void 0;
468
+ const context = createWixBookingsContext(client, config);
469
+ registerGlobalContext(WIX_BOOKINGS_CONTEXT, context);
470
+ return context;
471
+ }
472
+ const init = makeJayInit().withClient(async ({ config }) => {
473
+ provideWixBookingsContext(config);
7
474
  });
8
475
  const listServices = createActionCaller("wixBookings.listServices", "GET");
9
476
  const listSlots = createActionCaller("wixBookings.listSlots", "GET");
@@ -416,8 +883,11 @@ function BookingFlowInteractive(_props, refs, viewStateSignals, _carryForward) {
416
883
  }
417
884
  const bookingFlow = makeJayStackComponent().withProps().withInteractive(BookingFlowInteractive);
418
885
  export {
886
+ WIX_BOOKINGS_CONTEXT,
419
887
  bookingFlow,
888
+ canBookOnline,
420
889
  createBooking,
890
+ createWixBookingsContext,
421
891
  init,
422
892
  listServices,
423
893
  listSlots
package/dist/index.d.ts CHANGED
@@ -1,17 +1,10 @@
1
- import { W as WixBookingsService } from './index.client-CBlxQDjy.js';
2
- export { f as BookingFormFieldView, B as BookingServiceView, e as BookingSlotView, C as CreateBookingOutcome, d as WIX_BOOKINGS_SERVICE, b as bookingFlow, c as createBooking, i as init, l as listServices, a as listSlots } from './index.client-CBlxQDjy.js';
1
+ import { W as WixBookingsConfig, a as WixBookingsService } from './index.client-DHSnbb5_.js';
2
+ export { m as BookingFeatures, g as BookingFormFieldView, B as BookingServiceView, f as BookingSlotView, n as BookingStep, C as CreateBookingOutcome, T as TimeSlot, o as TimeSlotsQuery, h as WIX_BOOKINGS_CONTEXT, e as WIX_BOOKINGS_SERVICE, p as WixBookingsContext, b as bookingFlow, j as canBookOnline, d as createBooking, k as createWixBookingsContext, i as init, l as listServices, c as listSlots } from './index.client-DHSnbb5_.js';
3
3
  import { WixClient } from '@wix/sdk';
4
4
  import '@jay-framework/fullstack-component';
5
5
  import '@jay-framework/component';
6
6
  import '@jay-framework/runtime';
7
7
 
8
- interface WixBookingsConfig {
9
- bookingAppId: string;
10
- staffResourceTypeId: string;
11
- slotWindowDays: number;
12
- postCheckoutUrl: string;
13
- }
14
-
15
8
  declare function provideWixBookingsService(wixClient: WixClient, config: WixBookingsConfig): WixBookingsService;
16
9
 
17
10
  export { WixBookingsService, provideWixBookingsService };