@jay-framework/wix-bookings 0.26.0 → 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.
@@ -46,7 +46,7 @@ No inspector result → fallback.
46
46
  | `K.services` (or `services` inside a `booking-flow` region) | `id` | service id |
47
47
 
48
48
  Use the first match. `slots` and `formFields` frames are **not** services — skip them and keep going outward.
49
- 2. **No match** — the click is on the slot picker, the booking form, or the selected service's name (`{K.selectedServiceName}`): there is **no service id** in the inspector result. Don't look one up by name. Use the services-list link and name the service from the visible text.
49
+ 2. **No match** — the click is on the slot picker, the booking form, or the selected service's name (`{K.selectedServiceName}`): there is **no service id** in the inspector result. Don't guess from markup alone. If the user **named** a service in chat, you may match `name` → `serviceId` in `agent-kit/references/wix-bookings/services.yaml` (from `jay-stack agent-kit`) and then build the single-service link; otherwise use the services-list link and name the service from the visible text.
50
50
  3. **Build the link** with `wix-server-client/getDashboardUrl`: service → `{ "path": "bookings/services/form/<serviceId>" }`. Run from the project root: `npx jay-stack-cli action wix-server-client/getDashboardUrl --input '{"path":"bookings/services/form/<serviceId>"}'`; the output's `url` is the link. Never read `config/.wix.yaml` or other credential files to build it.
51
51
  4. **Reply** (see [Agent behavior](#agent-behavior)): plain language only — e.g. “This service is set up in your Wix Bookings dashboard; you can change the name here: <url>” or “I updated the service name to …; you can review it here: <url>”.
52
52
 
@@ -30,12 +30,40 @@ postCheckoutUrl: "/book"
30
30
 
31
31
  | Field | Purpose |
32
32
  |-------|---------|
33
- | `bookingAppId` | Wix Bookings app ID on the site |
34
- | `staffResourceTypeId` | Resource type for `ANY_RESOURCE` staff selection |
33
+ | `bookingAppId` | Wix Bookings app ID on the site (empty = default Wix Bookings app) |
34
+ | `staffResourceTypeId` | Site-specific resource **typeId** for staff — required when slot queries use `ANY_RESOURCE` staff selection |
35
35
  | `slotWindowDays` | How far ahead to query slots (default 14) |
36
36
  | `postCheckoutUrl` | Relative path after paid checkout (e.g. `/book`) |
37
37
 
38
- ### 2. API key permissions
38
+ #### `staffResourceTypeId` — setup auto-fill
39
+
40
+ Each Wix site has its own staff resource type. `jay-stack setup wix-bookings` tries to fill an empty value from live Bookings data:
41
+
42
+ 1. `POST /bookings/v1/staff-members/query` — collect each service-provider staff member's `resourceId`
43
+ 2. `POST /bookings/v2/resources/query` — find a resource in that set and take its `typeId`
44
+
45
+ `POST /bookings/v2/resources/resource-types/query` is **not** used (it can return an empty list on a fresh site).
46
+
47
+ | Outcome | What to do |
48
+ |---------|------------|
49
+ | Setup writes `staffResourceTypeId` | Re-run `jay-stack setup` only when staff or resource types change on the site |
50
+ | Setup returns `needs-config` (no staff) | Add at least one staff member in the Wix Bookings dashboard, run setup again, **or** copy a staff resource's `typeId` from `POST /bookings/v2/resources/query` into `config/.wix-bookings.yaml` |
51
+ | Value already in YAML | Setup leaves it unchanged (no Wix calls) |
52
+
53
+ ### 2. Agent-kit references (`jay-stack agent-kit`)
54
+
55
+ After setup and a working API key, run `jay-stack agent-kit` to refresh:
56
+
57
+ | File | Contents |
58
+ |------|----------|
59
+ | `agent-kit/references/wix-bookings/services.yaml` | Visible services — `serviceId`, `name`, `type`, `formId`, `dashboardPath` (`bookings/services/form/<id>`) |
60
+ | `agent-kit/references/wix-bookings/site.yaml` | `staffResourceTypeId`, staff members (`id`, `resourceId`), config vs discovered type for troubleshooting |
61
+
62
+ Same pattern as `wix-forms` → `forms.yaml` and `wix-data` → `collections.yaml`: agents resolve **which service** or **which staff resource type** without guessing from page markup alone.
63
+
64
+ Staff and services are **not** edited in Jay — the index is for discovery and dashboard links. Service field changes stay in the Wix dashboard (see `wix-bookings-dashboard-content.md`).
65
+
66
+ ### 3. API key permissions
39
67
 
40
68
  Configure in [Wix API Keys Manager](https://manage.wix.com/account/api-keys). Each step needs its own permission; Wix returns **403** until the right scope is granted.
41
69
 
@@ -47,7 +75,7 @@ Configure in [Wix API Keys Manager](https://manage.wix.com/account/api-keys). Ea
47
75
 
48
76
  Also enable **Wix Forms** on the API key (via `wix-forms` plugin) for participant field schema.
49
77
 
50
- ### 3. Headless settings (not API key)
78
+ ### 4. Headless settings (not API key)
51
79
 
52
80
  Under **Dashboard → Settings → Development & integrations → Headless Settings → your client** (same `clientId` as `config/.wix.yaml`):
53
81
 
@@ -60,7 +88,7 @@ For local dev, add **`localhost:3000`** under **Allowed redirect domains** (doma
60
88
 
61
89
  The Wix site must be **published** — hosted checkout uses the published site.
62
90
 
63
- ### 4. Booking page
91
+ ### 5. Booking page
64
92
 
65
93
  ```html
66
94
  <script type="application/jay-headless"
@@ -40,7 +40,20 @@ For local smoke tests, **All site permissions** is acceptable temporarily.
40
40
  Bookings loads participant fields via `getFormSummary` from `@jay-framework/wix-forms`:
41
41
 
42
42
  - Ensure `wix-forms` is set up and API key has **Wix Forms** permission
43
- - Service must have a `form._id` in the Wix Bookings schema
43
+ - A service's participant form is `form.id` in the Wix Bookings service. The all-zero id
44
+ (`00000000-0000-0000-0000-000000000000`) means the site default form: the plugin then shows its
45
+ built-in First name / Last name / Email fields and does not call `getFormSummary`
46
+ - `formId` in `agent-kit/references/wix-bookings/services.yaml` is empty for those default-form services
47
+ - Changed a service in the dashboard (e.g. assigned a custom form) and the page still shows the old
48
+ data: the services list is slow-rendered and stays fresh for 10 minutes. Restart the dev server,
49
+ or wait, before re-testing
50
+ - Fields show `required: false` even when Wix requires them: the Form Summary API does not
51
+ carry `required`. **`createBooking` does not enforce it either** — QA 2026-11-10 booked a form
52
+ with a required Address and got 200 without one
53
+ - **Known gap — fields are dropped:** only text, email, phone, number and URL fields are shown.
54
+ Address (and other non-text fields) are silently left out of the participant form, even when
55
+ required. Wix checkout does not ask for them either, so the booking is confirmed without them.
56
+ Do not put address or other non-text fields on a booking form until this is fixed
44
57
 
45
58
  ## Do not assume success from redirect alone
46
59
 
@@ -50,6 +63,19 @@ Bookings loads participant fields via `getFormSummary` from `@jay-framework/wix-
50
63
 
51
64
  | Symptom | Check |
52
65
  |---------|-------|
53
- | No services | `bookingAppId` in `config/.wix-bookings.yaml` |
54
- | Slot query fails | `staffResourceTypeId` matches site resource type |
66
+ | No services | `bookingAppId` in `config/.wix-bookings.yaml`; API key **Wix Bookings** permission |
67
+ | Slot query fails / no availability | `staffResourceTypeId` in config — must be the staff resource's `typeId` on this site |
68
+ | Setup could not fill `staffResourceTypeId` | No staff on site — add staff in Bookings dashboard and re-run `jay-stack setup wix-bookings` |
69
+ | `staffResourceTypeId` looks wrong | Compare `staffResourceTypeIdFromConfig` vs `staffResourceTypeIdDiscovered` in `agent-kit/references/wix-bookings/site.yaml` after `jay-stack agent-kit` |
70
+ | Agent cannot name a service | Refresh `agent-kit/references/wix-bookings/services.yaml` (`jay-stack agent-kit`) |
55
71
  | Wrong return URL after checkout | `postCheckoutUrl` in config |
72
+
73
+ ### `staffResourceTypeId` manual recovery
74
+
75
+ When setup returns `needs-config` for staff:
76
+
77
+ 1. In Wix Bookings, ensure at least one **staff member** exists.
78
+ 2. Re-run `jay-stack setup wix-bookings`, **or**
79
+ 3. Call `POST /bookings/v2/resources/query`, find a resource linked to staff, and set `staffResourceTypeId` to that resource's `typeId` in `config/.wix-bookings.yaml`.
80
+
81
+ Runtime slot queries pass this value as `resourceTypeId` when the service allows any staff member (`ANY_RESOURCE`). An empty or wrong value causes Wix to reject the slot request.
@@ -238,6 +238,11 @@ declare const createBooking: _jay_framework_fullstack_component.JayAction<{
238
238
  paymentPreference?: "ONLINE" | "OFFLINE";
239
239
  }, CreateBookingOutcome, [WixBookingsService]>;
240
240
 
241
+ interface ServiceForm {
242
+ id?: string;
243
+ _id?: string;
244
+ }
245
+
241
246
  interface RawBookingService {
242
247
  _id?: string;
243
248
  id?: string;
@@ -262,9 +267,7 @@ interface RawBookingService {
262
267
  sessionDurations?: number[];
263
268
  };
264
269
  };
265
- form?: {
266
- _id?: string;
267
- };
270
+ form?: ServiceForm;
268
271
  }
269
272
 
270
273
  /**
@@ -1,4 +1,4 @@
1
- export { m as BookingFeatures, g as BookingFormFieldView, q as BookingOrder, B as BookingServiceView, f as BookingSlotView, n as BookingStep, C as CreateBookingOutcome, T as TimeSlot, o as TimeSlotsQuery, h as WIX_BOOKINGS_CONTEXT, 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-gTd3Cezm.js';
1
+ export { m as BookingFeatures, g as BookingFormFieldView, q as BookingOrder, B as BookingServiceView, f as BookingSlotView, n as BookingStep, C as CreateBookingOutcome, T as TimeSlot, o as TimeSlotsQuery, h as WIX_BOOKINGS_CONTEXT, 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';
2
2
  import '@jay-framework/fullstack-component';
3
3
  import '@jay-framework/component';
4
4
  import '@jay-framework/runtime';
@@ -1,7 +1,7 @@
1
1
  import { makeJayInit, makeJayStackComponent } from "@jay-framework/fullstack-component";
2
2
  import { createJayContext, useGlobalContext, registerGlobalContext } from "@jay-framework/runtime";
3
3
  import { wixFetch, WixApiError, WIX_CLIENT_CONTEXT, ensureSessionFresh } from "@jay-framework/wix-server-client/client";
4
- import { createSignal, createEffect } from "@jay-framework/component";
4
+ import { createSignal, createEffect, useReactive } from "@jay-framework/component";
5
5
  import { createActionCaller } from "@jay-framework/stack-client-runtime";
6
6
  const MAX_SLOTS_PER_QUERY = 200;
7
7
  const SERVICES_PAGE_SIZE = 100;
@@ -45,6 +45,11 @@ async function getBookingServiceById(client, serviceId) {
45
45
  });
46
46
  return result.services?.[0];
47
47
  }
48
+ const DEFAULT_FORM_ID = "00000000-0000-0000-0000-000000000000";
49
+ function participantFormId(form) {
50
+ const id = form?.id ?? form?._id ?? "";
51
+ return id === DEFAULT_FORM_ID ? "" : id;
52
+ }
48
53
  function formatPrice(service) {
49
54
  const price = service.payment?.fixed?.price;
50
55
  if (!price?.value) {
@@ -69,7 +74,7 @@ function mapService(raw) {
69
74
  description: raw.description ?? "",
70
75
  priceLabel: formatPrice(raw),
71
76
  durationLabel: duration,
72
- formId: raw.form?._id ?? ""
77
+ formId: participantFormId(raw.form)
73
78
  };
74
79
  }
75
80
  function createSlotId(resourceId, localStartDate) {
@@ -639,6 +644,12 @@ function emptyStoreFor(fields) {
639
644
  }
640
645
  return store;
641
646
  }
647
+ function toggleSelection(field, { current, optionValue, checked }) {
648
+ const selected = new Set(Array.isArray(current) ? current : []);
649
+ if (checked) selected.add(optionValue);
650
+ else selected.delete(optionValue);
651
+ return field.options.map((option) => option.value).filter((value) => selected.has(value));
652
+ }
642
653
  function seedControlValues(store, seeds) {
643
654
  const seeded = { ...store };
644
655
  for (const { target, value, dirty } of seeds) {
@@ -891,7 +902,8 @@ function WixFormInteractive(_props, refs, _viewStateSignals, carryForward) {
891
902
  setInvalidByTarget((current) => ({ ...current, [field.target]: false }));
892
903
  }
893
904
  function reflectToInput(field, value) {
894
- refs[contractTagName(field.target)]?.input?.exec$((element) => {
905
+ const fieldRef = refs[contractTagName(field.target)];
906
+ fieldRef?.input?.exec$((element) => {
895
907
  if (field.inputType === "checkbox") {
896
908
  element.checked = value === true;
897
909
  } else if (field.inputType === "multiselect") {
@@ -903,6 +915,12 @@ function WixFormInteractive(_props, refs, _viewStateSignals, carryForward) {
903
915
  element.value = typeof value === "string" ? value : "";
904
916
  }
905
917
  });
918
+ if (field.inputType === "multiselect") {
919
+ const selected = Array.isArray(value) ? value : [];
920
+ fieldRef?.options?.toggle?.map((option, item) => void option.exec$((element) => {
921
+ element.checked = selected.includes(item.value);
922
+ }));
923
+ }
906
924
  }
907
925
  function handleNativeInput(field, event) {
908
926
  dirtyTargets.add(field.target);
@@ -916,10 +934,16 @@ function WixFormInteractive(_props, refs, _viewStateSignals, carryForward) {
916
934
  reflectToInput(field, value);
917
935
  validateField(field);
918
936
  }
937
+ function handleOptionToggle(field, change) {
938
+ dirtyTargets.add(field.target);
939
+ setFieldValue(field.target, toggleSelection(field, { current: values()[field.target], ...change }));
940
+ validateField(field);
941
+ }
919
942
  wireFieldEvents(refs, carryForward.fields, {
920
943
  onNativeInput: handleNativeInput,
921
944
  onNativeBlur: validateField,
922
- onControl: handleControl
945
+ onControl: handleControl,
946
+ onOptionToggle: handleOptionToggle
923
947
  });
924
948
  wireHoneypot(refs, (value) => {
925
949
  honeypotValue = value;
@@ -927,6 +951,10 @@ function WixFormInteractive(_props, refs, _viewStateSignals, carryForward) {
927
951
  createEffect(() => {
928
952
  void seedControlsIntoStore(refs, carryForward.fields, dirtyTargets, setValues);
929
953
  });
954
+ const reactive = useReactive();
955
+ function afterRemount(work) {
956
+ void reactive.toBeClean().then(work);
957
+ }
930
958
  afterRemount(() => wireNativeFormSubmit(refs, submit));
931
959
  function resetForm() {
932
960
  submitFlight.invalidate();
@@ -1054,16 +1082,28 @@ function wireFieldEvents(refs, fields, handlers) {
1054
1082
  fieldRef.input?.onblur(() => handlers.onNativeBlur(field));
1055
1083
  fieldRef.control?.onclick(({ event }) => handlers.onControl(field, event));
1056
1084
  fieldRef.control?.oninput(({ event }) => handlers.onControl(field, event));
1085
+ if (field.inputType === "multiselect") {
1086
+ fieldRef.options?.toggle?.onchange(({ event, viewState }) => handlers.onOptionToggle(field, {
1087
+ optionValue: viewState.value,
1088
+ checked: event.target.checked
1089
+ }));
1090
+ }
1057
1091
  }
1058
1092
  }
1059
- function afterRemount(work) {
1060
- queueMicrotask(work);
1061
- }
1062
1093
  function focusFirstFieldInput(refs, fields, matches) {
1063
- const field = fields.find((candidate) => !candidate.hidden && matches(candidate) && refs[contractTagName(candidate.target)]?.input);
1094
+ const field = fields.find((candidate) => !candidate.hidden && matches(candidate) && focusableRef(refs, candidate));
1064
1095
  if (!field)
1065
1096
  return;
1066
- void refs[contractTagName(field.target)].input.exec$((element) => element.focus());
1097
+ void focusableRef(refs, field).exec$((element) => element.focus());
1098
+ }
1099
+ function focusableRef(refs, field) {
1100
+ const fieldRef = refs[contractTagName(field.target)];
1101
+ if (field.inputType === "multiselect") {
1102
+ const firstChip = fieldRef?.options?.toggle?.find(() => true);
1103
+ if (firstChip)
1104
+ return firstChip;
1105
+ }
1106
+ return fieldRef?.input;
1067
1107
  }
1068
1108
  function owningSubmitForm(target) {
1069
1109
  const button = target?.closest?.("button");
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { W as WixBookingsConfig, a as WixBookingsService } from './index.client-gTd3Cezm.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-gTd3Cezm.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 = [];
@@ -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
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jay-framework/wix-bookings",
3
- "version": "0.26.0",
3
+ "version": "0.26.1",
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",
@@ -43,15 +43,15 @@
43
43
  "test": "vitest run"
44
44
  },
45
45
  "dependencies": {
46
- "@jay-framework/component": "^0.26.0",
47
- "@jay-framework/fullstack-component": "^0.26.0",
48
- "@jay-framework/reactive": "^0.26.0",
49
- "@jay-framework/runtime": "^0.26.0",
50
- "@jay-framework/secure": "^0.26.0",
51
- "@jay-framework/stack-client-runtime": "^0.26.0",
52
- "@jay-framework/stack-server-runtime": "^0.26.0",
53
- "@jay-framework/wix-forms": "^0.26.0",
54
- "@jay-framework/wix-server-client": "^0.26.0",
46
+ "@jay-framework/component": "^0.26.1",
47
+ "@jay-framework/fullstack-component": "^0.26.1",
48
+ "@jay-framework/reactive": "^0.26.1",
49
+ "@jay-framework/runtime": "^0.26.1",
50
+ "@jay-framework/secure": "^0.26.1",
51
+ "@jay-framework/stack-client-runtime": "^0.26.1",
52
+ "@jay-framework/stack-server-runtime": "^0.26.1",
53
+ "@jay-framework/wix-forms": "^0.26.1",
54
+ "@jay-framework/wix-server-client": "^0.26.1",
55
55
  "@wix/sdk": "^1.21.5",
56
56
  "js-yaml": "^4.1.0"
57
57
  },
@@ -59,10 +59,10 @@
59
59
  "@babel/core": "^7.23.7",
60
60
  "@babel/preset-env": "^7.23.8",
61
61
  "@babel/preset-typescript": "^7.23.3",
62
- "@jay-framework/compiler-jay-stack": "^0.26.0",
63
- "@jay-framework/jay-cli": "^0.26.0",
64
- "@jay-framework/jay-stack-cli": "^0.26.0",
65
- "@jay-framework/vite-plugin": "^0.26.0",
62
+ "@jay-framework/compiler-jay-stack": "^0.26.1",
63
+ "@jay-framework/jay-cli": "^0.26.1",
64
+ "@jay-framework/jay-stack-cli": "^0.26.1",
65
+ "@jay-framework/vite-plugin": "^0.26.1",
66
66
  "@jay-framework/wix-dev-environment": "^0.6.12",
67
67
  "nodemon": "^3.0.3",
68
68
  "rimraf": "^5.0.5",
package/plugin.yaml CHANGED
@@ -22,3 +22,5 @@ actions:
22
22
  action: create-booking.jay-action
23
23
 
24
24
  setup: setupWixBookings
25
+ agentkit: generateWixBookingsAgentKit
26
+ description: Bookings setup and agent-kit service index for dashboard links
@@ -1,27 +0,0 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
- import yaml from "js-yaml";
4
- const CONFIG_FILE = ".wix-bookings.yaml";
5
- const WIX_BOOKINGS_APP_ID = "13d21c63-b5ec-5912-8397-c3a5ddb27a97";
6
- const DEFAULTS = {
7
- bookingAppId: WIX_BOOKINGS_APP_ID,
8
- staffResourceTypeId: "",
9
- slotWindowDays: 14,
10
- postCheckoutUrl: "/"
11
- };
12
- function loadWixBookingsConfig(projectRoot) {
13
- const configPath = path.join(projectRoot, "config", CONFIG_FILE);
14
- if (!fs.existsSync(configPath)) {
15
- return { ...DEFAULTS };
16
- }
17
- const raw = yaml.load(fs.readFileSync(configPath, "utf-8"));
18
- return {
19
- bookingAppId: raw.bookingAppId || DEFAULTS.bookingAppId,
20
- staffResourceTypeId: raw.staffResourceTypeId ?? DEFAULTS.staffResourceTypeId,
21
- slotWindowDays: raw.slotWindowDays ?? DEFAULTS.slotWindowDays,
22
- postCheckoutUrl: raw.postCheckoutUrl ?? DEFAULTS.postCheckoutUrl
23
- };
24
- }
25
- export {
26
- loadWixBookingsConfig as l
27
- };