@jay-framework/wix-bookings 0.25.5 → 0.26.1

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.d.ts CHANGED
@@ -1,5 +1,5 @@
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';
1
+ import { W as WixBookingsConfig, a as WixBookingsService } from './index.client-oaMPI34g.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-oaMPI34g.js';
3
3
  import { WixClient } from '@wix/sdk';
4
4
  import '@jay-framework/fullstack-component';
5
5
  import '@jay-framework/component';
package/dist/index.js CHANGED
@@ -1,104 +1,10 @@
1
1
  import { createJayService, makeJayInit, makeJayStackComponent, phaseOutput, RenderPipeline, makeJayQuery, makeJayAction } from "@jay-framework/fullstack-component";
2
2
  import { registerService, getService } from "@jay-framework/stack-server-runtime";
3
3
  import { WIX_CLIENT_SERVICE } from "@jay-framework/wix-server-client";
4
- import { l as loadWixBookingsConfig } from "./config-loader-sfgwfXPV.js";
4
+ import { g as getBookingServiceById, p as paymentPreferenceFromService, l as localDateStrInTimeZone, m as mapAppointmentSlot, a as mapClassSlot, q as queryBookingServices, b as mapService, M as MAX_SLOTS_PER_QUERY, c as loadWixBookingsConfig } from "./query-services-B1MS77NZ.js";
5
5
  import { wixFetch, WixApiError } from "@jay-framework/wix-server-client/client";
6
6
  import { createJayContext } from "@jay-framework/runtime";
7
7
  const WIX_BOOKINGS_SERVICE = createJayService("WixBookingsService");
8
- const MAX_SLOTS_PER_QUERY = 200;
9
- const SERVICES_PAGE_SIZE = 100;
10
- function formatPrice(service) {
11
- const price = service.payment?.fixed?.price;
12
- if (!price?.value) {
13
- return "Free";
14
- }
15
- const amount = parseFloat(price.value);
16
- return `${price.currency ?? ""} ${amount.toFixed(2)}`.trim();
17
- }
18
- function formatDurationMinutes(service) {
19
- const minutes = service.schedule?.availabilityConstraints?.sessionDurations?.[0];
20
- if (!minutes) {
21
- return "";
22
- }
23
- return `${minutes} min`;
24
- }
25
- function mapService(raw) {
26
- const duration = formatDurationMinutes(raw);
27
- return {
28
- id: raw._id ?? raw.id ?? "",
29
- name: raw.name ?? "Service",
30
- type: raw.type ?? "APPOINTMENT",
31
- description: raw.description ?? "",
32
- priceLabel: formatPrice(raw),
33
- durationLabel: duration,
34
- formId: raw.form?._id ?? ""
35
- };
36
- }
37
- function createSlotId(resourceId, localStartDate) {
38
- return `${resourceId}:${localStartDate}`;
39
- }
40
- function formatSlotLabel(localStartDate) {
41
- const date = new Date(localStartDate);
42
- return date.toLocaleString([], {
43
- weekday: "short",
44
- month: "short",
45
- day: "numeric",
46
- hour: "2-digit",
47
- minute: "2-digit"
48
- });
49
- }
50
- function mapAppointmentSlot(slot) {
51
- if (!slot.scheduleId || !slot.localStartDate || !slot.localEndDate) {
52
- return null;
53
- }
54
- return {
55
- id: createSlotId(slot.scheduleId, slot.localStartDate),
56
- localStartDate: slot.localStartDate,
57
- localEndDate: slot.localEndDate,
58
- label: formatSlotLabel(slot.localStartDate),
59
- scheduleId: slot.scheduleId,
60
- serviceType: "APPOINTMENT"
61
- };
62
- }
63
- function mapClassSlot(slot) {
64
- const eventId = slot.eventInfo?.eventId;
65
- if (!eventId || !slot.localStartDate || !slot.localEndDate) {
66
- return null;
67
- }
68
- return {
69
- id: createSlotId(eventId, slot.localStartDate),
70
- localStartDate: slot.localStartDate,
71
- localEndDate: slot.localEndDate,
72
- label: formatSlotLabel(slot.localStartDate),
73
- eventId,
74
- serviceType: "CLASS"
75
- };
76
- }
77
- function localDateStrInTimeZone(date, timeZone) {
78
- const parts = new Intl.DateTimeFormat("en-US", {
79
- timeZone,
80
- year: "numeric",
81
- month: "2-digit",
82
- day: "2-digit",
83
- hour: "2-digit",
84
- minute: "2-digit",
85
- second: "2-digit",
86
- hour12: false
87
- }).formatToParts(date);
88
- const read = (type) => parts.find((part) => part.type === type)?.value ?? "00";
89
- const hour = read("hour") === "24" ? "00" : read("hour");
90
- return `${read("year")}-${read("month")}-${read("day")}T${hour}:${read("minute")}:${read("second")}`;
91
- }
92
- function paymentPreferenceFromService(service) {
93
- const opts = service.payment?.options ?? {};
94
- if (opts.online && !opts.inPerson) {
95
- return "ONLINE";
96
- }
97
- if (!opts.online && opts.inPerson) {
98
- return "OFFLINE";
99
- }
100
- return "ONLINE";
101
- }
102
8
  async function createBookingRecord(client, body) {
103
9
  return wixFetch(client, "/bookings/v2/bookings", { method: "POST", body });
104
10
  }
@@ -142,46 +48,6 @@ async function getBookingCheckoutUrl(client, cartId) {
142
48
  body: {}
143
49
  });
144
50
  }
145
- async function queryBookingServices(client, bookingAppId) {
146
- const allServices = [];
147
- let offset = 0;
148
- let hasMorePages = true;
149
- while (hasMorePages) {
150
- const result = await wixFetch(
151
- client,
152
- "/bookings/v2/services/query",
153
- {
154
- method: "POST",
155
- body: {
156
- query: {
157
- filter: { appId: bookingAppId },
158
- paging: { limit: SERVICES_PAGE_SIZE, offset }
159
- },
160
- conditionalFields: ["STAFF_MEMBER_DETAILS"]
161
- }
162
- }
163
- );
164
- const batch = result.services ?? [];
165
- allServices.push(...batch);
166
- hasMorePages = batch.length >= SERVICES_PAGE_SIZE;
167
- if (hasMorePages) {
168
- offset += SERVICES_PAGE_SIZE;
169
- }
170
- }
171
- return allServices;
172
- }
173
- async function getBookingServiceById(client, serviceId) {
174
- const result = await wixFetch(client, "/bookings/v2/services/query", {
175
- method: "POST",
176
- body: {
177
- query: {
178
- filter: { _id: serviceId },
179
- paging: { limit: 1 }
180
- }
181
- }
182
- });
183
- return result.services?.[0];
184
- }
185
51
  const AVAILABILITY_PAGE_SIZE = 100;
186
52
  async function listAvailabilityTimeSlots(client, input, options) {
187
53
  const allSlots = [];
@@ -372,15 +238,62 @@ const init = makeJayInit().withServer(async () => {
372
238
  console.log("[wix-bookings] Server initialization complete");
373
239
  return { config };
374
240
  });
241
+ var ServicesFailure = /* @__PURE__ */ ((ServicesFailure2) => {
242
+ ServicesFailure2[ServicesFailure2["NONE"] = 0] = "NONE";
243
+ ServicesFailure2[ServicesFailure2["PERMISSION"] = 1] = "PERMISSION";
244
+ ServicesFailure2[ServicesFailure2["UNKNOWN"] = 2] = "UNKNOWN";
245
+ return ServicesFailure2;
246
+ })(ServicesFailure || {});
247
+ var SlotsFailure = /* @__PURE__ */ ((SlotsFailure2) => {
248
+ SlotsFailure2[SlotsFailure2["NONE"] = 0] = "NONE";
249
+ SlotsFailure2[SlotsFailure2["UNKNOWN"] = 1] = "UNKNOWN";
250
+ return SlotsFailure2;
251
+ })(SlotsFailure || {});
252
+ var BookingState = /* @__PURE__ */ ((BookingState2) => {
253
+ BookingState2[BookingState2["IDLE"] = 0] = "IDLE";
254
+ BookingState2[BookingState2["BOOKING"] = 1] = "BOOKING";
255
+ BookingState2[BookingState2["CONFIRMED"] = 2] = "CONFIRMED";
256
+ BookingState2[BookingState2["FAILED"] = 3] = "FAILED";
257
+ return BookingState2;
258
+ })(BookingState || {});
259
+ var BookingFailure = /* @__PURE__ */ ((BookingFailure2) => {
260
+ BookingFailure2[BookingFailure2["NONE"] = 0] = "NONE";
261
+ BookingFailure2[BookingFailure2["VALIDATION"] = 1] = "VALIDATION";
262
+ BookingFailure2[BookingFailure2["FORM_UNAVAILABLE"] = 2] = "FORM_UNAVAILABLE";
263
+ BookingFailure2[BookingFailure2["CHECKOUT_PERMISSION"] = 3] = "CHECKOUT_PERMISSION";
264
+ BookingFailure2[BookingFailure2["CHECKOUT_REDIRECT_REJECTED"] = 4] = "CHECKOUT_REDIRECT_REJECTED";
265
+ BookingFailure2[BookingFailure2["SITE_NOT_PUBLISHED"] = 5] = "SITE_NOT_PUBLISHED";
266
+ BookingFailure2[BookingFailure2["UNKNOWN"] = 6] = "UNKNOWN";
267
+ return BookingFailure2;
268
+ })(BookingFailure || {});
269
+ const SLOW_RENDER_TTL = 600;
270
+ const SLOW_RENDER_GRACE = 3600;
271
+ const SLOW_RENDER_ERROR_TTL = 30;
272
+ function describeServicesError(error) {
273
+ const rawMessage = error instanceof Error ? error.message : "";
274
+ if (rawMessage.includes("403")) {
275
+ return {
276
+ failure: ServicesFailure.PERMISSION,
277
+ message: "Bookings API access denied. Add Wix Bookings permission to your API key in the Wix dashboard."
278
+ };
279
+ }
280
+ return {
281
+ failure: ServicesFailure.UNKNOWN,
282
+ message: rawMessage || "Could not load booking services."
283
+ };
284
+ }
285
+ function bookingStateOf(state) {
286
+ if (state.failure !== BookingFailure.NONE) return BookingState.FAILED;
287
+ return BookingState.IDLE;
288
+ }
375
289
  async function renderSlowlyChanging(_props, bookings) {
376
290
  try {
377
291
  const services = await bookings.listServices();
378
- return phaseOutput({ services }, { services });
292
+ return phaseOutput({ services }, { services }, { ttl: SLOW_RENDER_TTL, grace: SLOW_RENDER_GRACE });
379
293
  } catch (error) {
380
- const rawMessage = error instanceof Error ? error.message : "Could not load booking services.";
381
- 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.";
294
+ const { failure, message } = describeServicesError(error);
382
295
  console.error("[booking-flow] listServices failed:", error);
383
- return phaseOutput({ services: [] }, { services: [], servicesError: message });
296
+ return phaseOutput({ services: [] }, { services: [], servicesError: message, servicesFailure: failure }, { ttl: SLOW_RENDER_ERROR_TTL });
384
297
  }
385
298
  }
386
299
  async function renderFastChanging(_props, carryForward) {
@@ -390,6 +303,7 @@ async function renderFastChanging(_props, carryForward) {
390
303
  services: carryForward.services,
391
304
  servicesLoading: false,
392
305
  servicesError: carryForward.servicesError ?? "",
306
+ servicesFailure: carryForward.servicesFailure ?? ServicesFailure.NONE,
393
307
  showNoServices: carryForward.services.length === 0 && !carryForward.servicesError,
394
308
  hasSlots: false,
395
309
  showServices: true,
@@ -399,16 +313,18 @@ async function renderFastChanging(_props, carryForward) {
399
313
  slots: [],
400
314
  slotsLoading: false,
401
315
  slotsMessage: "",
316
+ slotsFailure: SlotsFailure.NONE,
402
317
  formFields: [],
403
318
  formLoading: false,
404
319
  isBooking: false,
405
320
  bookingStatus: "",
406
- bookingError: ""
321
+ bookingError: "",
322
+ bookingState: bookingStateOf({
323
+ failure: BookingFailure.NONE
324
+ }),
325
+ bookingFailure: BookingFailure.NONE
407
326
  },
408
- carryForward: {
409
- services: carryForward.services,
410
- servicesError: carryForward.servicesError
411
- }
327
+ carryForward
412
328
  }));
413
329
  }
414
330
  const bookingFlow = makeJayStackComponent().withProps().withServices(WIX_BOOKINGS_SERVICE).withSlowlyRender(renderSlowlyChanging).withFastRender(renderFastChanging).withInteractiveMark();
@@ -0,0 +1,176 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import yaml from "js-yaml";
4
+ import { wixFetch } from "@jay-framework/wix-server-client/client";
5
+ const CONFIG_FILE = ".wix-bookings.yaml";
6
+ const WIX_BOOKINGS_APP_ID = "13d21c63-b5ec-5912-8397-c3a5ddb27a97";
7
+ const DEFAULTS = {
8
+ bookingAppId: WIX_BOOKINGS_APP_ID,
9
+ staffResourceTypeId: "",
10
+ slotWindowDays: 14,
11
+ postCheckoutUrl: "/"
12
+ };
13
+ function loadWixBookingsConfig(projectRoot) {
14
+ const configPath = path.join(projectRoot, "config", CONFIG_FILE);
15
+ if (!fs.existsSync(configPath)) {
16
+ return { ...DEFAULTS };
17
+ }
18
+ const raw = yaml.load(fs.readFileSync(configPath, "utf-8"));
19
+ return {
20
+ bookingAppId: raw.bookingAppId || DEFAULTS.bookingAppId,
21
+ staffResourceTypeId: raw.staffResourceTypeId ?? DEFAULTS.staffResourceTypeId,
22
+ slotWindowDays: raw.slotWindowDays ?? DEFAULTS.slotWindowDays,
23
+ postCheckoutUrl: raw.postCheckoutUrl ?? DEFAULTS.postCheckoutUrl
24
+ };
25
+ }
26
+ const MAX_SLOTS_PER_QUERY = 200;
27
+ const SERVICES_PAGE_SIZE = 100;
28
+ const DEFAULT_FORM_ID = "00000000-0000-0000-0000-000000000000";
29
+ function participantFormId(form) {
30
+ const id = form?.id ?? form?._id ?? "";
31
+ return id === DEFAULT_FORM_ID ? "" : id;
32
+ }
33
+ function formatPrice(service) {
34
+ const price = service.payment?.fixed?.price;
35
+ if (!price?.value) {
36
+ return "Free";
37
+ }
38
+ const amount = parseFloat(price.value);
39
+ return `${price.currency ?? ""} ${amount.toFixed(2)}`.trim();
40
+ }
41
+ function formatDurationMinutes(service) {
42
+ const minutes = service.schedule?.availabilityConstraints?.sessionDurations?.[0];
43
+ if (!minutes) {
44
+ return "";
45
+ }
46
+ return `${minutes} min`;
47
+ }
48
+ function mapService(raw) {
49
+ const duration = formatDurationMinutes(raw);
50
+ return {
51
+ id: raw._id ?? raw.id ?? "",
52
+ name: raw.name ?? "Service",
53
+ type: raw.type ?? "APPOINTMENT",
54
+ description: raw.description ?? "",
55
+ priceLabel: formatPrice(raw),
56
+ durationLabel: duration,
57
+ formId: participantFormId(raw.form)
58
+ };
59
+ }
60
+ function createSlotId(resourceId, localStartDate) {
61
+ return `${resourceId}:${localStartDate}`;
62
+ }
63
+ function formatSlotLabel(localStartDate) {
64
+ const date = new Date(localStartDate);
65
+ return date.toLocaleString([], {
66
+ weekday: "short",
67
+ month: "short",
68
+ day: "numeric",
69
+ hour: "2-digit",
70
+ minute: "2-digit"
71
+ });
72
+ }
73
+ function mapAppointmentSlot(slot) {
74
+ if (!slot.scheduleId || !slot.localStartDate || !slot.localEndDate) {
75
+ return null;
76
+ }
77
+ return {
78
+ id: createSlotId(slot.scheduleId, slot.localStartDate),
79
+ localStartDate: slot.localStartDate,
80
+ localEndDate: slot.localEndDate,
81
+ label: formatSlotLabel(slot.localStartDate),
82
+ scheduleId: slot.scheduleId,
83
+ serviceType: "APPOINTMENT"
84
+ };
85
+ }
86
+ function mapClassSlot(slot) {
87
+ const eventId = slot.eventInfo?.eventId;
88
+ if (!eventId || !slot.localStartDate || !slot.localEndDate) {
89
+ return null;
90
+ }
91
+ return {
92
+ id: createSlotId(eventId, slot.localStartDate),
93
+ localStartDate: slot.localStartDate,
94
+ localEndDate: slot.localEndDate,
95
+ label: formatSlotLabel(slot.localStartDate),
96
+ eventId,
97
+ serviceType: "CLASS"
98
+ };
99
+ }
100
+ function localDateStrInTimeZone(date, timeZone) {
101
+ const parts = new Intl.DateTimeFormat("en-US", {
102
+ timeZone,
103
+ year: "numeric",
104
+ month: "2-digit",
105
+ day: "2-digit",
106
+ hour: "2-digit",
107
+ minute: "2-digit",
108
+ second: "2-digit",
109
+ hour12: false
110
+ }).formatToParts(date);
111
+ const read = (type) => parts.find((part) => part.type === type)?.value ?? "00";
112
+ const hour = read("hour") === "24" ? "00" : read("hour");
113
+ return `${read("year")}-${read("month")}-${read("day")}T${hour}:${read("minute")}:${read("second")}`;
114
+ }
115
+ function paymentPreferenceFromService(service) {
116
+ const opts = service.payment?.options ?? {};
117
+ if (opts.online && !opts.inPerson) {
118
+ return "ONLINE";
119
+ }
120
+ if (!opts.online && opts.inPerson) {
121
+ return "OFFLINE";
122
+ }
123
+ return "ONLINE";
124
+ }
125
+ async function queryBookingServices(client, bookingAppId) {
126
+ const allServices = [];
127
+ let offset = 0;
128
+ let hasMorePages = true;
129
+ while (hasMorePages) {
130
+ const result = await wixFetch(
131
+ client,
132
+ "/bookings/v2/services/query",
133
+ {
134
+ method: "POST",
135
+ body: {
136
+ query: {
137
+ filter: { appId: bookingAppId },
138
+ paging: { limit: SERVICES_PAGE_SIZE, offset }
139
+ },
140
+ conditionalFields: ["STAFF_MEMBER_DETAILS"]
141
+ }
142
+ }
143
+ );
144
+ const batch = result.services ?? [];
145
+ allServices.push(...batch);
146
+ hasMorePages = batch.length >= SERVICES_PAGE_SIZE;
147
+ if (hasMorePages) {
148
+ offset += SERVICES_PAGE_SIZE;
149
+ }
150
+ }
151
+ return allServices;
152
+ }
153
+ async function getBookingServiceById(client, serviceId) {
154
+ const result = await wixFetch(client, "/bookings/v2/services/query", {
155
+ method: "POST",
156
+ body: {
157
+ query: {
158
+ filter: { _id: serviceId },
159
+ paging: { limit: 1 }
160
+ }
161
+ }
162
+ });
163
+ return result.services?.[0];
164
+ }
165
+ export {
166
+ MAX_SLOTS_PER_QUERY as M,
167
+ mapClassSlot as a,
168
+ mapService as b,
169
+ loadWixBookingsConfig as c,
170
+ participantFormId as d,
171
+ getBookingServiceById as g,
172
+ localDateStrInTimeZone as l,
173
+ mapAppointmentSlot as m,
174
+ paymentPreferenceFromService as p,
175
+ queryBookingServices as q
176
+ };
package/dist/tools.d.ts CHANGED
@@ -1,6 +1,8 @@
1
- import { PluginSetupContext, PluginSetupResult } from '@jay-framework/stack-server-runtime';
1
+ import { PluginAgentKitContext, PluginAgentKitResult, PluginSetupContext, PluginSetupResult } from '@jay-framework/stack-server-runtime';
2
+
3
+ declare function generateWixBookingsAgentKit(ctx: PluginAgentKitContext): Promise<PluginAgentKitResult>;
2
4
 
3
5
  declare function setupWixBookings(ctx: PluginSetupContext): Promise<PluginSetupResult>;
4
6
  declare const setup: typeof setupWixBookings;
5
7
 
6
- export { setup, setupWixBookings };
8
+ export { generateWixBookingsAgentKit, setup, setupWixBookings };
package/dist/tools.js CHANGED
@@ -1,27 +1,143 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { hasService } from "@jay-framework/stack-server-runtime";
3
+ import yaml from "js-yaml";
4
+ import { getService, hasService } from "@jay-framework/stack-server-runtime";
5
+ import { WIX_CLIENT_SERVICE, serverClientSetupBlocker } from "@jay-framework/wix-server-client";
6
+ import { d as participantFormId, c as loadWixBookingsConfig, q as queryBookingServices } from "./query-services-B1MS77NZ.js";
7
+ import { wixFetch } from "@jay-framework/wix-server-client/client";
4
8
  import { WIX_FORMS_SERVICE } from "@jay-framework/wix-forms";
5
- import { l as loadWixBookingsConfig } from "./config-loader-sfgwfXPV.js";
9
+ const DESCRIPTION = "Wix Bookings services for agent discovery. Use serviceId with dashboard path bookings/services/form/<serviceId>.";
10
+ function serviceId(service) {
11
+ return service._id ?? service.id ?? "";
12
+ }
13
+ function buildServicesReference(services) {
14
+ const visible = services.filter((s) => !s.hidden);
15
+ return {
16
+ _description: DESCRIPTION,
17
+ totalServices: services.length,
18
+ visibleServices: visible.length,
19
+ services: visible.map((service) => {
20
+ const id = serviceId(service);
21
+ return {
22
+ serviceId: id,
23
+ name: service.name ?? "",
24
+ type: service.type ?? "",
25
+ formId: participantFormId(service.form),
26
+ dashboardPath: id ? `bookings/services/form/${id}` : "",
27
+ payment: {
28
+ online: service.payment?.options?.online ?? false,
29
+ inPerson: service.payment?.options?.inPerson ?? false,
30
+ currency: service.payment?.fixed?.price?.currency ?? ""
31
+ }
32
+ };
33
+ })
34
+ };
35
+ }
36
+ function buildSiteReference(input) {
37
+ return {
38
+ _description: "Site-level Bookings config and staff resources. staffResourceTypeId is required for ANY_RESOURCE slot queries; setup fills it from Wix when empty.",
39
+ staffResourceTypeId: input.staffResourceTypeId,
40
+ staffMembers: input.staffMembers
41
+ };
42
+ }
43
+ const PAGE_LIMIT = 100;
44
+ async function queryAllPages(client, url, itemsKey) {
45
+ const items = [];
46
+ let cursor;
47
+ do {
48
+ const page = await wixFetch(client, url, {
49
+ method: "POST",
50
+ body: { query: { cursorPaging: { limit: PAGE_LIMIT, ...cursor && { cursor } } } }
51
+ });
52
+ items.push(...page[itemsKey] ?? []);
53
+ cursor = page.pagingMetadata?.cursors?.next || void 0;
54
+ } while (cursor);
55
+ return items;
56
+ }
57
+ async function queryStaffMembers(client) {
58
+ const staffMembers = await queryAllPages(
59
+ client,
60
+ "/bookings/v1/staff-members/query",
61
+ "staffMembers"
62
+ );
63
+ return staffMembers.map((member) => ({ id: member.id ?? "", resourceId: member.resourceId ?? "" })).filter((member) => member.id && member.resourceId);
64
+ }
65
+ async function discoverStaffResourceTypeId(client) {
66
+ const staffMembers = await queryStaffMembers(client);
67
+ const staffResourceIds = new Set(staffMembers.map((member) => member.resourceId));
68
+ if (!staffResourceIds.size) return void 0;
69
+ const resources = await queryAllPages(
70
+ client,
71
+ "/bookings/v2/resources/query",
72
+ "resources"
73
+ );
74
+ return resources.find((resource) => resource.id && staffResourceIds.has(resource.id))?.typeId;
75
+ }
76
+ async function generateWixBookingsAgentKit(ctx) {
77
+ if (ctx.initError) {
78
+ throw new Error(`init failed: ${ctx.initError.message}`);
79
+ }
80
+ const client = getService(WIX_CLIENT_SERVICE);
81
+ const config = loadWixBookingsConfig(ctx.projectRoot);
82
+ const [services, staffMembers, discoveredStaffResourceTypeId] = await Promise.all([
83
+ queryBookingServices(client, config.bookingAppId),
84
+ queryStaffMembers(client),
85
+ discoverStaffResourceTypeId(client)
86
+ ]);
87
+ const servicesRef = buildServicesReference(services);
88
+ const siteRef = buildSiteReference({
89
+ staffResourceTypeId: config.staffResourceTypeId || discoveredStaffResourceTypeId || "",
90
+ staffMembers
91
+ });
92
+ fs.mkdirSync(ctx.referencesDir, { recursive: true });
93
+ const servicesPath = path.join(ctx.referencesDir, "services.yaml");
94
+ const sitePath = path.join(ctx.referencesDir, "site.yaml");
95
+ const yamlOpts = { indent: 2, lineWidth: 120, noRefs: true };
96
+ fs.writeFileSync(
97
+ servicesPath,
98
+ yaml.dump({ _generated: (/* @__PURE__ */ new Date()).toISOString(), ...servicesRef }, yamlOpts),
99
+ "utf-8"
100
+ );
101
+ fs.writeFileSync(
102
+ sitePath,
103
+ yaml.dump(
104
+ {
105
+ _generated: (/* @__PURE__ */ new Date()).toISOString(),
106
+ staffResourceTypeIdFromConfig: config.staffResourceTypeId,
107
+ staffResourceTypeIdDiscovered: discoveredStaffResourceTypeId ?? "",
108
+ ...siteRef
109
+ },
110
+ yamlOpts
111
+ ),
112
+ "utf-8"
113
+ );
114
+ const agentKitCreated = [
115
+ `agent-kit/references/${ctx.pluginName}/services.yaml`,
116
+ `agent-kit/references/${ctx.pluginName}/site.yaml`
117
+ ];
118
+ const siteNote = siteRef.staffResourceTypeId ? "" : " (staffResourceTypeId missing — run jay-stack setup wix-bookings)";
119
+ return {
120
+ agentKitCreated,
121
+ message: `${servicesRef.visibleServices} services indexed${siteNote}`
122
+ };
123
+ }
6
124
  const CONFIG_FILE = ".wix-bookings.yaml";
7
125
  const CONFIG_TEMPLATE = `# Wix Bookings Configuration
8
126
  #
9
- # bookingAppId — Wix Bookings app ID on your site
127
+ # bookingAppId — the app that owns the bookings services (empty = the Wix Bookings app;
128
+ # each service in POST /bookings/v2/services/query carries it as appId)
10
129
  bookingAppId: ""
11
130
 
12
- # staffResourceTypeId — resource type for staff selection (site-specific)
131
+ # staffResourceTypeId — resource type of the site's staff (site-specific). Setup fills it:
132
+ # the typeId of a staff member's resource in POST /bookings/v2/resources/query
13
133
  staffResourceTypeId: ""
14
134
 
15
135
  slotWindowDays: 14
16
136
  postCheckoutUrl: "/book"
17
137
  `;
18
138
  async function setupWixBookings(ctx) {
19
- if (ctx.initError) {
20
- return {
21
- status: "error",
22
- message: `Service init failed (is wix-server-client configured?). ${ctx.initError.message}`
23
- };
24
- }
139
+ const blocker = serverClientSetupBlocker(ctx.initError);
140
+ if (blocker) return blocker;
25
141
  if (!hasService(WIX_FORMS_SERVICE)) {
26
142
  return {
27
143
  status: "error",
@@ -38,28 +154,39 @@ async function setupWixBookings(ctx) {
38
154
  configCreated.push(`config/${CONFIG_FILE}`);
39
155
  }
40
156
  const config = loadWixBookingsConfig(ctx.projectRoot);
41
- const missing = [];
42
- if (!config.bookingAppId) {
43
- missing.push("bookingAppId");
44
- }
157
+ let filled = "";
45
158
  if (!config.staffResourceTypeId) {
46
- missing.push("staffResourceTypeId");
47
- }
48
- if (missing.length) {
49
- return {
50
- status: "needs-config",
51
- configCreated,
52
- message: `Set ${missing.join(", ")} in config/${CONFIG_FILE}`
53
- };
159
+ const staffResourceTypeId = await discoverStaffResourceTypeId(
160
+ getService(WIX_CLIENT_SERVICE)
161
+ );
162
+ if (!staffResourceTypeId) {
163
+ return {
164
+ status: "needs-config",
165
+ configCreated,
166
+ message: `Set staffResourceTypeId in config/${CONFIG_FILE}: Wix returned no staff resource. Add a staff member in the Bookings dashboard and run setup again, or copy the typeId of a staff resource from POST /bookings/v2/resources/query.`
167
+ };
168
+ }
169
+ writeConfigValue(configPath, "staffResourceTypeId", staffResourceTypeId);
170
+ filled = `, staffResourceTypeId filled from Wix: ${staffResourceTypeId}`;
54
171
  }
55
172
  return {
56
173
  status: "configured",
57
174
  configCreated,
58
- message: `Wix Bookings configured (app: ${config.bookingAppId})`
175
+ message: `Wix Bookings configured (app: ${config.bookingAppId}${filled})`
59
176
  };
60
177
  }
178
+ function writeConfigValue(configPath, key, value) {
179
+ const text = fs.readFileSync(configPath, "utf-8");
180
+ const line = `${key}: ${JSON.stringify(value)}`;
181
+ const keyLine = new RegExp(`^${key}:.*$`, "m");
182
+ const updated = keyLine.test(text) ? text.replace(keyLine, line) : `${text.trimEnd()}
183
+ ${line}
184
+ `;
185
+ fs.writeFileSync(configPath, updated, "utf-8");
186
+ }
61
187
  const setup = setupWixBookings;
62
188
  export {
189
+ generateWixBookingsAgentKit,
63
190
  setup,
64
191
  setupWixBookings
65
192
  };