@jay-framework/wix-bookings 0.24.0 → 0.24.2

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.
package/dist/index.js ADDED
@@ -0,0 +1,503 @@
1
+ import { createJayService, makeJayInit, makeJayStackComponent, phaseOutput, RenderPipeline, makeJayQuery, makeJayAction } from "@jay-framework/fullstack-component";
2
+ import { registerService, getService, hasService } from "@jay-framework/stack-server-runtime";
3
+ import { wixFetch, WixApiError, WIX_CLIENT_SERVICE } from "@jay-framework/wix-server-client";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import yaml from "js-yaml";
7
+ import { WIX_FORMS_SERVICE } from "@jay-framework/wix-forms";
8
+ const CONFIG_FILE$1 = ".wix-bookings.yaml";
9
+ const DEFAULTS = {
10
+ bookingAppId: "",
11
+ staffResourceTypeId: "",
12
+ slotWindowDays: 14,
13
+ postCheckoutUrl: "/"
14
+ };
15
+ function loadWixBookingsConfig(projectRoot) {
16
+ const configPath = path.join(projectRoot, "config", CONFIG_FILE$1);
17
+ if (!fs.existsSync(configPath)) {
18
+ return { ...DEFAULTS };
19
+ }
20
+ const raw = yaml.load(fs.readFileSync(configPath, "utf-8"));
21
+ return {
22
+ bookingAppId: raw.bookingAppId ?? DEFAULTS.bookingAppId,
23
+ staffResourceTypeId: raw.staffResourceTypeId ?? DEFAULTS.staffResourceTypeId,
24
+ slotWindowDays: raw.slotWindowDays ?? DEFAULTS.slotWindowDays,
25
+ postCheckoutUrl: raw.postCheckoutUrl ?? DEFAULTS.postCheckoutUrl
26
+ };
27
+ }
28
+ const MAX_SLOTS_PER_QUERY = 200;
29
+ const SERVICES_PAGE_SIZE = 100;
30
+ const WIX_BOOKINGS_SERVICE = createJayService("WixBookingsService");
31
+ function formatPrice(service) {
32
+ const price = service.payment?.fixed?.price;
33
+ if (!price?.value) {
34
+ return "Free";
35
+ }
36
+ const amount = parseFloat(price.value);
37
+ return `${price.currency ?? ""} ${amount.toFixed(2)}`.trim();
38
+ }
39
+ function formatDurationMinutes(service) {
40
+ const minutes = service.schedule?.availabilityConstraints?.sessionDurations?.[0];
41
+ if (!minutes) {
42
+ return "";
43
+ }
44
+ return `${minutes} min`;
45
+ }
46
+ function mapService(raw) {
47
+ const duration = formatDurationMinutes(raw);
48
+ return {
49
+ id: raw._id ?? raw.id ?? "",
50
+ name: raw.name ?? "Service",
51
+ type: raw.type ?? "APPOINTMENT",
52
+ description: raw.description ?? "",
53
+ priceLabel: formatPrice(raw),
54
+ durationLabel: duration,
55
+ formId: raw.form?._id ?? ""
56
+ };
57
+ }
58
+ function createSlotId(resourceId, localStartDate) {
59
+ return `${resourceId}:${localStartDate}`;
60
+ }
61
+ function formatSlotLabel(localStartDate) {
62
+ const date = new Date(localStartDate);
63
+ return date.toLocaleString([], {
64
+ weekday: "short",
65
+ month: "short",
66
+ day: "numeric",
67
+ hour: "2-digit",
68
+ minute: "2-digit"
69
+ });
70
+ }
71
+ function mapAppointmentSlot(slot) {
72
+ if (!slot.scheduleId || !slot.localStartDate || !slot.localEndDate) {
73
+ return null;
74
+ }
75
+ return {
76
+ id: createSlotId(slot.scheduleId, slot.localStartDate),
77
+ localStartDate: slot.localStartDate,
78
+ localEndDate: slot.localEndDate,
79
+ label: formatSlotLabel(slot.localStartDate),
80
+ scheduleId: slot.scheduleId,
81
+ serviceType: "APPOINTMENT"
82
+ };
83
+ }
84
+ function mapClassSlot(slot) {
85
+ const eventId = slot.eventInfo?.eventId;
86
+ if (!eventId || !slot.localStartDate || !slot.localEndDate) {
87
+ return null;
88
+ }
89
+ return {
90
+ id: createSlotId(eventId, slot.localStartDate),
91
+ localStartDate: slot.localStartDate,
92
+ localEndDate: slot.localEndDate,
93
+ label: formatSlotLabel(slot.localStartDate),
94
+ eventId,
95
+ serviceType: "CLASS"
96
+ };
97
+ }
98
+ function localDateStrInTimeZone(date, timeZone) {
99
+ const parts = new Intl.DateTimeFormat("en-US", {
100
+ timeZone,
101
+ year: "numeric",
102
+ month: "2-digit",
103
+ day: "2-digit",
104
+ hour: "2-digit",
105
+ minute: "2-digit",
106
+ second: "2-digit",
107
+ hour12: false
108
+ }).formatToParts(date);
109
+ const read = (type) => parts.find((part) => part.type === type)?.value ?? "00";
110
+ const hour = read("hour") === "24" ? "00" : read("hour");
111
+ return `${read("year")}-${read("month")}-${read("day")}T${hour}:${read("minute")}:${read("second")}`;
112
+ }
113
+ function paymentPreferenceFromService(service) {
114
+ const opts = service.payment?.options ?? {};
115
+ if (opts.online && !opts.inPerson) {
116
+ return "ONLINE";
117
+ }
118
+ if (!opts.online && opts.inPerson) {
119
+ return "OFFLINE";
120
+ }
121
+ return "ONLINE";
122
+ }
123
+ async function createBookingRecord(client, body) {
124
+ return wixFetch(client, "/bookings/v2/bookings", { method: "POST", body });
125
+ }
126
+ async function createBookingCart(client, bookingId, bookingAppId) {
127
+ return wixFetch(client, "/ecom/v2/carts", {
128
+ method: "POST",
129
+ body: {
130
+ catalogItems: [
131
+ {
132
+ quantity: 1,
133
+ catalogReference: { catalogItemId: bookingId, appId: bookingAppId }
134
+ }
135
+ ],
136
+ cart: { source: { channelType: "WEB" } }
137
+ }
138
+ });
139
+ }
140
+ async function calculateBookingCart(client, cartId) {
141
+ return wixFetch(client, `/ecom/v2/carts/${cartId}/calculate`, { method: "POST", body: {} });
142
+ }
143
+ async function placeBookingOrder(client, cartId) {
144
+ await wixFetch(client, `/ecom/v2/carts/${cartId}/place-order`, { method: "POST", body: {} });
145
+ }
146
+ async function createBookingRedirectSession(client, cartId, postFlowUrl) {
147
+ return wixFetch(client, "/headless/v1/redirect-session", {
148
+ method: "POST",
149
+ body: {
150
+ ecomCheckout: { checkoutId: cartId },
151
+ callbacks: { postFlowUrl }
152
+ }
153
+ });
154
+ }
155
+ async function getBookingCheckoutUrl(client, cartId) {
156
+ return wixFetch(client, `/ecom/v2/carts/${cartId}/get-checkout-url`, {
157
+ method: "POST",
158
+ body: {}
159
+ });
160
+ }
161
+ async function queryBookingServices(client, bookingAppId) {
162
+ const allServices = [];
163
+ let offset = 0;
164
+ let hasMorePages = true;
165
+ while (hasMorePages) {
166
+ const result = await wixFetch(
167
+ client,
168
+ "/bookings/v2/services/query",
169
+ {
170
+ method: "POST",
171
+ body: {
172
+ query: {
173
+ filter: { appId: bookingAppId },
174
+ paging: { limit: SERVICES_PAGE_SIZE, offset }
175
+ },
176
+ conditionalFields: ["STAFF_MEMBER_DETAILS"]
177
+ }
178
+ }
179
+ );
180
+ const batch = result.services ?? [];
181
+ allServices.push(...batch);
182
+ hasMorePages = batch.length >= SERVICES_PAGE_SIZE;
183
+ if (hasMorePages) {
184
+ offset += SERVICES_PAGE_SIZE;
185
+ }
186
+ }
187
+ return allServices;
188
+ }
189
+ async function getBookingServiceById(client, serviceId) {
190
+ const result = await wixFetch(client, "/bookings/v2/services/query", {
191
+ method: "POST",
192
+ body: {
193
+ query: {
194
+ filter: { _id: serviceId },
195
+ paging: { limit: 1 }
196
+ }
197
+ }
198
+ });
199
+ return result.services?.[0];
200
+ }
201
+ const AVAILABILITY_PAGE_SIZE = 100;
202
+ async function listAvailabilityTimeSlots(client, input, options) {
203
+ const allSlots = [];
204
+ const maxSlots = options?.maxSlots;
205
+ let cursor;
206
+ let hasMorePages = true;
207
+ while (hasMorePages) {
208
+ const result = await wixFetch(
209
+ client,
210
+ "/_api/service-availability/v2/time-slots",
211
+ {
212
+ method: "POST",
213
+ body: {
214
+ serviceId: input.serviceId,
215
+ fromLocalDate: input.fromLocalDate,
216
+ toLocalDate: input.toLocalDate,
217
+ timeZone: input.timeZone,
218
+ bookable: true,
219
+ cursorPaging: cursor ? { cursor, limit: AVAILABILITY_PAGE_SIZE } : { limit: AVAILABILITY_PAGE_SIZE }
220
+ }
221
+ }
222
+ );
223
+ allSlots.push(...result.timeSlots ?? []);
224
+ if (allSlots.length >= maxSlots) {
225
+ return allSlots.slice(0, maxSlots);
226
+ }
227
+ cursor = result.pagingMetadata?.cursors?.next;
228
+ hasMorePages = !!cursor && result.pagingMetadata?.hasNext !== false;
229
+ }
230
+ return allSlots;
231
+ }
232
+ const EVENT_SLOTS_PAGE_SIZE = 100;
233
+ async function listEventTimeSlots(client, input, options) {
234
+ const allSlots = [];
235
+ const maxSlots = options?.maxSlots;
236
+ let cursor;
237
+ let hasMorePages = true;
238
+ while (hasMorePages) {
239
+ const result = await wixFetch(
240
+ client,
241
+ "/_api/service-availability/v2/time-slots/event",
242
+ {
243
+ method: "POST",
244
+ body: {
245
+ serviceIds: input.serviceIds,
246
+ fromLocalDate: input.fromLocalDate,
247
+ toLocalDate: input.toLocalDate,
248
+ timeZone: input.timeZone,
249
+ includeNonBookable: false,
250
+ cursorPaging: cursor ? { cursor, limit: EVENT_SLOTS_PAGE_SIZE } : { limit: EVENT_SLOTS_PAGE_SIZE }
251
+ }
252
+ }
253
+ );
254
+ allSlots.push(...result.timeSlots ?? []);
255
+ if (allSlots.length >= maxSlots) {
256
+ return allSlots.slice(0, maxSlots);
257
+ }
258
+ cursor = result.pagingMetadata?.cursors?.next;
259
+ hasMorePages = !!cursor && result.pagingMetadata?.hasNext !== false;
260
+ }
261
+ return allSlots;
262
+ }
263
+ async function resolvePaidCheckoutRedirectUrl(wixClient, cartId, postFlowUrl) {
264
+ try {
265
+ const redirectData = await createBookingRedirectSession(wixClient, cartId, postFlowUrl);
266
+ const redirectUrl = redirectData.redirectSession?.fullUrl;
267
+ if (redirectUrl) {
268
+ return redirectUrl;
269
+ }
270
+ } catch (error) {
271
+ if (!(error instanceof WixApiError) || error.status !== 400 && error.status !== 404) {
272
+ throw error;
273
+ }
274
+ }
275
+ const checkoutUrlData = await getBookingCheckoutUrl(wixClient, cartId);
276
+ const checkoutUrl = checkoutUrlData.checkoutUrl;
277
+ if (!checkoutUrl) {
278
+ throw new Error(
279
+ "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."
280
+ );
281
+ }
282
+ return checkoutUrl;
283
+ }
284
+ function provideWixBookingsService(wixClient, config) {
285
+ const service = {
286
+ async listServices() {
287
+ const items = await queryBookingServices(wixClient, config.bookingAppId);
288
+ return items.filter((item) => !item.hidden).map((item) => mapService(item));
289
+ },
290
+ async listSlots({ serviceId, serviceType, timezone, windowDays }) {
291
+ const now = /* @__PURE__ */ new Date();
292
+ const tz = timezone ?? "UTC";
293
+ const from = localDateStrInTimeZone(now, tz);
294
+ const days = windowDays ?? config.slotWindowDays;
295
+ const to = new Date(now.getTime() + days * 24 * 60 * 60 * 1e3);
296
+ const toStr = localDateStrInTimeZone(to, tz);
297
+ const slotQueryOptions = { maxSlots: MAX_SLOTS_PER_QUERY };
298
+ if (serviceType === "APPOINTMENT") {
299
+ const timeSlots2 = await listAvailabilityTimeSlots(
300
+ wixClient,
301
+ {
302
+ serviceId,
303
+ fromLocalDate: from,
304
+ toLocalDate: toStr,
305
+ timeZone: tz
306
+ },
307
+ slotQueryOptions
308
+ );
309
+ return timeSlots2.map((slot) => mapAppointmentSlot(slot)).filter((slot) => slot !== null);
310
+ }
311
+ const timeSlots = await listEventTimeSlots(
312
+ wixClient,
313
+ {
314
+ serviceIds: [serviceId],
315
+ fromLocalDate: from,
316
+ toLocalDate: toStr,
317
+ timeZone: tz
318
+ },
319
+ slotQueryOptions
320
+ );
321
+ return timeSlots.map((slot) => mapClassSlot(slot)).filter((slot) => slot !== null);
322
+ },
323
+ async createBooking(input) {
324
+ const rawService = await getBookingServiceById(wixClient, input.serviceId);
325
+ const paymentPreference = input.paymentPreference ?? (rawService ? paymentPreferenceFromService(
326
+ rawService
327
+ ) : "ONLINE");
328
+ const slotData = {
329
+ serviceId: input.serviceId,
330
+ startDate: input.slot.localStartDate,
331
+ endDate: input.slot.localEndDate,
332
+ timezone: input.timezone,
333
+ location: { locationType: "OWNER_BUSINESS" },
334
+ resourceSelections: [
335
+ {
336
+ resourceTypeId: config.staffResourceTypeId,
337
+ selectionMethod: "ANY_RESOURCE"
338
+ }
339
+ ]
340
+ };
341
+ if (input.serviceType === "APPOINTMENT") {
342
+ slotData.scheduleId = input.slot.scheduleId;
343
+ } else {
344
+ slotData.eventId = input.slot.eventId;
345
+ }
346
+ const bookingData = await createBookingRecord(wixClient, {
347
+ booking: {
348
+ bookedEntity: { slot: slotData },
349
+ selectedPaymentOption: paymentPreference,
350
+ totalParticipants: 1
351
+ },
352
+ formSubmission: input.formValues
353
+ });
354
+ const bookingId = bookingData.booking.id;
355
+ const cartData = await createBookingCart(wixClient, bookingId, config.bookingAppId);
356
+ const cartId = cartData.cart.id;
357
+ const calcData = await calculateBookingCart(wixClient, cartId);
358
+ const total = parseFloat(calcData.summary?.priceSummary?.total?.amount ?? "0");
359
+ if (total > 0) {
360
+ const postFlowUrl = new URL(config.postCheckoutUrl, input.siteOrigin).href;
361
+ const redirectUrl = await resolvePaidCheckoutRedirectUrl(
362
+ wixClient,
363
+ cartId,
364
+ postFlowUrl
365
+ );
366
+ return { outcome: "redirect", redirectUrl };
367
+ }
368
+ await placeBookingOrder(wixClient, cartId);
369
+ return { outcome: "confirmed" };
370
+ }
371
+ };
372
+ registerService(WIX_BOOKINGS_SERVICE, service);
373
+ return service;
374
+ }
375
+ const init = makeJayInit().withServer(async () => {
376
+ console.log("[wix-bookings] Initializing server-side bookings service...");
377
+ const wixClient = getService(WIX_CLIENT_SERVICE);
378
+ const config = loadWixBookingsConfig(process.cwd());
379
+ provideWixBookingsService(wixClient, config);
380
+ console.log(`[wix-bookings] Booking app ID: ${config.bookingAppId}`);
381
+ console.log("[wix-bookings] Server initialization complete");
382
+ return {};
383
+ });
384
+ const CONFIG_FILE = ".wix-bookings.yaml";
385
+ const CONFIG_TEMPLATE = `# Wix Bookings Configuration
386
+ #
387
+ # bookingAppId — Wix Bookings app ID on your site
388
+ bookingAppId: ""
389
+
390
+ # staffResourceTypeId — resource type for staff selection (site-specific)
391
+ staffResourceTypeId: ""
392
+
393
+ slotWindowDays: 14
394
+ postCheckoutUrl: "/book"
395
+ `;
396
+ async function setupWixBookings(ctx) {
397
+ if (ctx.initError) {
398
+ return {
399
+ status: "error",
400
+ message: `Service init failed (is wix-server-client configured?). ${ctx.initError.message}`
401
+ };
402
+ }
403
+ if (!hasService(WIX_FORMS_SERVICE)) {
404
+ return {
405
+ status: "error",
406
+ message: "wix-bookings requires the wix-forms plugin. Add wix-forms to your project plugins and run setup before wix-bookings."
407
+ };
408
+ }
409
+ const configCreated = [];
410
+ const configPath = path.join(ctx.configDir, CONFIG_FILE);
411
+ if (!fs.existsSync(configPath)) {
412
+ if (!fs.existsSync(ctx.configDir)) {
413
+ fs.mkdirSync(ctx.configDir, { recursive: true });
414
+ }
415
+ fs.writeFileSync(configPath, CONFIG_TEMPLATE, "utf-8");
416
+ configCreated.push(`config/${CONFIG_FILE}`);
417
+ }
418
+ const config = loadWixBookingsConfig(ctx.projectRoot);
419
+ const missing = [];
420
+ if (!config.bookingAppId) {
421
+ missing.push("bookingAppId");
422
+ }
423
+ if (!config.staffResourceTypeId) {
424
+ missing.push("staffResourceTypeId");
425
+ }
426
+ if (missing.length) {
427
+ return {
428
+ status: "needs-config",
429
+ configCreated,
430
+ message: `Set ${missing.join(", ")} in config/${CONFIG_FILE}`
431
+ };
432
+ }
433
+ return {
434
+ status: "configured",
435
+ configCreated,
436
+ message: `Wix Bookings configured (app: ${config.bookingAppId})`
437
+ };
438
+ }
439
+ const setup = setupWixBookings;
440
+ async function renderSlowlyChanging(_props, bookings) {
441
+ try {
442
+ const services = await bookings.listServices();
443
+ return phaseOutput({ services }, { services });
444
+ } catch (error) {
445
+ const rawMessage = error instanceof Error ? error.message : "Could not load booking services.";
446
+ const message = rawMessage.includes("403") ? "Bookings API access denied. Add Wix Bookings permission to your API key in the Wix dashboard." : rawMessage || "Could not load booking services.";
447
+ console.error("[booking-flow] listServices failed:", error);
448
+ return phaseOutput({ services: [] }, { services: [], servicesError: message });
449
+ }
450
+ }
451
+ async function renderFastChanging(_props, carryForward) {
452
+ const Pipeline = RenderPipeline.for();
453
+ return Pipeline.ok(null).toPhaseOutput(() => ({
454
+ viewState: {
455
+ services: carryForward.services,
456
+ servicesLoading: false,
457
+ servicesError: carryForward.servicesError ?? "",
458
+ showNoServices: carryForward.services.length === 0 && !carryForward.servicesError,
459
+ hasSlots: false,
460
+ showServices: true,
461
+ showSlots: false,
462
+ showForm: false,
463
+ selectedServiceName: "",
464
+ slots: [],
465
+ slotsLoading: false,
466
+ slotsMessage: "",
467
+ formFields: [],
468
+ formLoading: false,
469
+ isBooking: false,
470
+ bookingStatus: "",
471
+ bookingError: ""
472
+ },
473
+ carryForward: {
474
+ services: carryForward.services,
475
+ servicesError: carryForward.servicesError
476
+ }
477
+ }));
478
+ }
479
+ const bookingFlow = makeJayStackComponent().withProps().withServices(WIX_BOOKINGS_SERVICE).withSlowlyRender(renderSlowlyChanging).withFastRender(renderFastChanging).withInteractiveMark();
480
+ const listServices = makeJayQuery("wixBookings.listServices").withServices(WIX_BOOKINGS_SERVICE).withCaching({ maxAge: 300 }).withHandler(async (_input, bookings) => {
481
+ const services = await bookings.listServices();
482
+ return { services };
483
+ });
484
+ const listSlots = makeJayQuery("wixBookings.listSlots").withServices(WIX_BOOKINGS_SERVICE).withHandler(
485
+ async (input, bookings) => {
486
+ const slots = await bookings.listSlots(input);
487
+ return { slots };
488
+ }
489
+ );
490
+ const createBooking = makeJayAction("wixBookings.createBooking").withServices(WIX_BOOKINGS_SERVICE).withHandler(
491
+ async (input, bookings) => bookings.createBooking(input)
492
+ );
493
+ export {
494
+ WIX_BOOKINGS_SERVICE,
495
+ bookingFlow,
496
+ createBooking,
497
+ init,
498
+ listServices,
499
+ listSlots,
500
+ provideWixBookingsService,
501
+ setup,
502
+ setupWixBookings
503
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jay-framework/wix-bookings",
3
- "version": "0.24.0",
3
+ "version": "0.24.2",
4
4
  "type": "module",
5
5
  "description": "Wix Bookings package for Jay Framework — browse services, pick slots, submit participant details, complete checkout",
6
6
  "license": "Apache-2.0",
@@ -39,15 +39,15 @@
39
39
  "test": "vitest run"
40
40
  },
41
41
  "dependencies": {
42
- "@jay-framework/component": "^0.24.0",
43
- "@jay-framework/fullstack-component": "^0.24.0",
44
- "@jay-framework/reactive": "^0.24.0",
45
- "@jay-framework/runtime": "^0.24.0",
46
- "@jay-framework/secure": "^0.24.0",
47
- "@jay-framework/stack-client-runtime": "^0.24.0",
48
- "@jay-framework/stack-server-runtime": "^0.24.0",
49
- "@jay-framework/wix-forms": "^0.24.0",
50
- "@jay-framework/wix-server-client": "^0.24.0",
42
+ "@jay-framework/component": "^0.24.2",
43
+ "@jay-framework/fullstack-component": "^0.24.2",
44
+ "@jay-framework/reactive": "^0.24.2",
45
+ "@jay-framework/runtime": "^0.24.2",
46
+ "@jay-framework/secure": "^0.24.2",
47
+ "@jay-framework/stack-client-runtime": "^0.24.2",
48
+ "@jay-framework/stack-server-runtime": "^0.24.2",
49
+ "@jay-framework/wix-forms": "^0.24.2",
50
+ "@jay-framework/wix-server-client": "^0.24.2",
51
51
  "@wix/sdk": "^1.21.5",
52
52
  "js-yaml": "^4.1.0"
53
53
  },
@@ -55,10 +55,10 @@
55
55
  "@babel/core": "^7.23.7",
56
56
  "@babel/preset-env": "^7.23.8",
57
57
  "@babel/preset-typescript": "^7.23.3",
58
- "@jay-framework/compiler-jay-stack": "^0.24.0",
59
- "@jay-framework/jay-cli": "^0.24.0",
60
- "@jay-framework/jay-stack-cli": "^0.24.0",
61
- "@jay-framework/vite-plugin": "^0.24.0",
58
+ "@jay-framework/compiler-jay-stack": "^0.24.2",
59
+ "@jay-framework/jay-cli": "^0.24.2",
60
+ "@jay-framework/jay-stack-cli": "^0.24.2",
61
+ "@jay-framework/vite-plugin": "^0.24.2",
62
62
  "@jay-framework/wix-dev-environment": "^0.6.12",
63
63
  "nodemon": "^3.0.3",
64
64
  "rimraf": "^5.0.5",