@wix/headless-bookings 0.0.95 → 0.0.97

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.
@@ -9,9 +9,8 @@
9
9
  */
10
10
  import { defineService, implementService } from '@wix/services-definitions';
11
11
  import { SignalsServiceDefinition, } from '@wix/services-definitions/core-services/signals';
12
- import { FormServiceDefinition } from '@wix/headless-forms/services';
13
12
  import { BookingServiceDefinition, } from '../booking/booking.js';
14
- import { hasForm, extractFormIdFromConfig } from './utils.js';
13
+ import { hasForm, extractFormIdFromConfig, hasFormId } from './utils.js';
15
14
  // ============================================================================
16
15
  // Constants
17
16
  // ============================================================================
@@ -20,6 +19,7 @@ import { hasForm, extractFormIdFromConfig } from './utils.js';
20
19
  * All booking forms must belong to this namespace.
21
20
  */
22
21
  export const BOOKING_FORM_NAMESPACE = 'wix.bookings.v2.bookings';
22
+ const DEFAULT_FORM_ID = '00000000-0000-0000-0000-000000000000';
23
23
  /**
24
24
  * Error thrown when BookingFormService cannot be initialized due to missing configuration.
25
25
  * This occurs when:
@@ -54,32 +54,51 @@ export const BookingFormServiceDefinition = defineService('bookingForm');
54
54
  // ============================================================================
55
55
  /**
56
56
  * Validates that a form belongs to the bookings namespace.
57
- * @param form The form to validate
57
+ * @param config The service config that may contain a pre-loaded form
58
58
  * @throws Error if the form is not from the bookings namespace
59
59
  */
60
60
  function validateBookingFormNamespace(form) {
61
- // Check if form has namespace property and validate it
62
- // The namespace might be in different locations depending on the form structure
63
- const formNamespace = form.namespace ||
64
- form._namespace;
61
+ const formNamespace = form.namespace;
65
62
  if (formNamespace && formNamespace !== BOOKING_FORM_NAMESPACE) {
66
63
  throw new Error(`BookingFormService: Invalid form namespace. ` +
67
64
  `Expected "${BOOKING_FORM_NAMESPACE}", but received "${formNamespace}". ` +
68
65
  `Ensure the form is a booking form.`);
69
66
  }
70
67
  }
68
+ function validateBookingFormConfig({ config, services, }) {
69
+ if (!config) {
70
+ return;
71
+ }
72
+ if (hasForm(config)) {
73
+ validateBookingFormNamespace(config.form);
74
+ const servicesFormId = services.length > 1 ? DEFAULT_FORM_ID : services?.[0]?.form?._id;
75
+ if (servicesFormId !== config.form._id) {
76
+ throw new Error(`BookingFormService: Invalid form ID. ` +
77
+ `Expected "${config.form._id}", but received "${servicesFormId}". ` +
78
+ `Ensure the form is the same as the selected services form.`);
79
+ }
80
+ }
81
+ }
71
82
  /**
72
83
  * Extracts the form ID from either config type or from services.
84
+ *
85
+ * Extraction priority:
86
+ * 1. From config (if formId is provided directly or extracted from pre-loaded form)
87
+ * 2. From services:
88
+ * - If multiple services: use DEFAULT_FORM_ID
89
+ * - If single service: use the service's form ID
90
+ *
73
91
  * @param config The service config (optional)
74
92
  * @param services The list of services to extract formId from if config is not provided
75
93
  * @returns The form ID
94
+ * @throws BookingFormConfigurationError if no formId can be extracted
76
95
  */
77
96
  function extractFormId(config, services) {
78
97
  // Try to extract from config first
79
98
  let formId = extractFormIdFromConfig(config);
80
99
  // Fallback to extracting from services
81
100
  if (!formId) {
82
- formId = services.find((s) => s.form?._id)?.form?._id;
101
+ formId = services.length > 1 ? DEFAULT_FORM_ID : services?.[0]?.form?._id;
83
102
  }
84
103
  if (!formId) {
85
104
  throw new BookingFormConfigurationError('BookingFormService: no formId found in config or services. ' +
@@ -87,6 +106,23 @@ function extractFormId(config, services) {
87
106
  }
88
107
  return formId;
89
108
  }
109
+ /**
110
+ * Extracts service IDs from config or services.
111
+ *
112
+ * Extraction priority:
113
+ * 1. From config.serviceIds if config has formId and serviceIds are provided
114
+ * 2. From services array (extract _id from each service)
115
+ *
116
+ * @param config The service config (optional)
117
+ * @param services The list of services to extract IDs from if config doesn't provide them
118
+ * @returns Array of service IDs
119
+ */
120
+ function getServiceIds(config, services) {
121
+ if (hasFormId(config) && config.serviceIds) {
122
+ return config.serviceIds;
123
+ }
124
+ return services.map((s) => s._id).filter(Boolean);
125
+ }
90
126
  // ============================================================================
91
127
  // Service Implementation
92
128
  // ============================================================================
@@ -98,8 +134,16 @@ function extractFormId(config, services) {
98
134
  * 1. Client-side: formId is provided, form is loaded dynamically
99
135
  * 2. SSR/SSG: Pre-loaded form is provided (must be from bookings namespace)
100
136
  *
101
- * NOTE: The Form.Fields ref is managed internally - the core component passes
102
- * a validate callback that the service stores and calls when validateFormSubmission() is invoked.
137
+ * Initialization:
138
+ * - Requires either a config (formId or form) OR BookingService with selected services
139
+ * - If config is not provided, formId is extracted from selected services
140
+ * - For multiple services, uses DEFAULT_FORM_ID; for single service, uses service's form ID
141
+ * - Service IDs are extracted from config.serviceIds or from selected services
142
+ *
143
+ * Validation:
144
+ * - The Form.Fields core component registers a validation callback via setValidateCallback
145
+ * - The validateFormSubmission() method calls this registered callback
146
+ * - The callback may be null initially until the core component registers it
103
147
  *
104
148
  * @example
105
149
  * ```tsx
@@ -108,24 +152,33 @@ function extractFormId(config, services) {
108
152
  * BookingFormServiceDefinition.withConfig({ formId: 'form-123' })
109
153
  * );
110
154
  *
155
+ * // Pattern 1b: Client-side loading with service IDs
156
+ * const bookingFormService = useService(
157
+ * BookingFormServiceDefinition.withConfig({
158
+ * formId: 'form-123',
159
+ * serviceIds: ['service-1', 'service-2']
160
+ * })
161
+ * );
162
+ *
111
163
  * // Pattern 2: SSR with pre-loaded form
112
164
  * const bookingFormService = useService(
113
165
  * BookingFormServiceDefinition.withConfig({ form: preloadedForm })
114
166
  * );
115
167
  *
116
- * // Store form submission
117
- * bookingFormService.setFormSubmission(formValues);
168
+ * // Pattern 3: No config - formId extracted from BookingService
169
+ * const bookingFormService = useService(
170
+ * BookingFormServiceDefinition.withConfig(undefined)
171
+ * );
118
172
  *
119
- * // Validate form
120
- * const result = await bookingFormService.validateFormSubmission();
121
- * if (result.valid) {
173
+ * // Validate form (callback must be registered by core component first)
174
+ * const result = await bookingFormService.validateFormSubmission?.();
175
+ * if (result?.valid) {
122
176
  * // Proceed with booking
123
177
  * }
124
178
  * ```
125
179
  */
126
180
  export const BookingFormService = implementService.withConfig()(BookingFormServiceDefinition, ({ getService, config }) => {
127
181
  const signalsService = getService(SignalsServiceDefinition);
128
- const formService = getService(FormServiceDefinition);
129
182
  // BookingService is optional - may not be available if not wrapped with Booking.Root
130
183
  let bookingService = null;
131
184
  try {
@@ -135,6 +188,10 @@ export const BookingFormService = implementService.withConfig()(BookingFormServi
135
188
  // BookingService not available - that's ok if formId was provided explicitly
136
189
  bookingService = null;
137
190
  }
191
+ /**
192
+ * Helper to extract services from BookingService.
193
+ * Returns empty array if BookingService is not available.
194
+ */
138
195
  const getServices = () => {
139
196
  if (!bookingService) {
140
197
  return [];
@@ -150,64 +207,37 @@ export const BookingFormService = implementService.withConfig()(BookingFormServi
150
207
  if (!config && (!bookingService || !hasServiceSelections)) {
151
208
  throw new BookingFormConfigurationError();
152
209
  }
153
- // Determine if we have a pre-loaded form
154
- const hasPreloadedForm = hasForm(config);
155
- // If form is provided, validate namespace
156
- if (hasPreloadedForm) {
157
- validateBookingFormNamespace(config.form);
158
- }
159
- // Extract formId from config (either directly or from form object)
160
- const formIdValue = extractFormId(config, getServices());
161
- // Initialize formSubmission signal (stores form data to be submitted)
162
- const formSubmission = signalsService.signal(null);
163
- // Initialize submissionId signal (for future use)
164
- const formSubmissionId = signalsService.signal(null);
165
- // formId signal - readonly
166
- const formId = signalsService.signal(formIdValue);
167
- // form signal - contains pre-loaded form if provided
168
- const form = signalsService.signal(hasForm(config) ? config.form : null);
169
- // Internal: Store validate callback (set by core component, not exposed publicly)
170
- let _validateCallback = null;
171
- // Internal: Register validate callback (called by core component via closure)
172
- const _setValidateCallback = (callback) => {
173
- _validateCallback = callback;
174
- };
175
- // Action to set form submission data
176
- const setFormSubmission = (formValues) => {
177
- formSubmission.set(formValues);
178
- };
179
- // Action to validate form - delegates to internally registered callback
180
- const validateFormSubmission = async () => {
181
- if (!_validateCallback) {
182
- console.error('BookingFormService: Validate callback not registered. ' +
183
- 'Ensure BookingForm component is mounted.');
184
- return { valid: false, validationFailures: ['Form not initialized'] };
185
- }
186
- return _validateCallback();
187
- };
188
- // Auto-sync formValues to BookingService.formSubmission (client-side only)
189
- // This keeps Booking.Data.formSubmission updated as the user types
190
- // and ensures the book action gets the latest form values
191
- // Only set up sync if BookingService is available
192
- if (bookingService) {
193
- signalsService.effect(() => {
194
- const formValues = formService.formValuesSignal.get();
195
- if (formValues && Object.keys(formValues).length > 0) {
196
- bookingService.actions.setFormSubmission(formValues);
197
- }
210
+ const serviceSelections = getServices();
211
+ // Validate config
212
+ validateBookingFormConfig({ config, services: serviceSelections });
213
+ // Extract formId from config (either directly or from form object) or from services
214
+ const formIdValue = extractFormId(config, serviceSelections);
215
+ // Extract service IDs to pass to FormService (from config or services)
216
+ const serviceIds = getServiceIds(config, serviceSelections);
217
+ /**
218
+ * Form service config signal.
219
+ *
220
+ * If pre-loaded form is provided (SSR/SSG):
221
+ * - Creates config with the form object
222
+ *
223
+ * Otherwise (client-side loading):
224
+ * - Creates config with formId, namespace, and metadata
225
+ * - Includes serviceIds in additionalMetadata for FormService
226
+ */
227
+ const formServiceConfig = signalsService.signal(hasForm(config)
228
+ ? { form: config.form }
229
+ : {
230
+ formId: formIdValue,
231
+ namespace: BOOKING_FORM_NAMESPACE,
232
+ additionalMetadata: {
233
+ ...config?.additionalMetadata,
234
+ serviceIds,
235
+ },
198
236
  });
199
- }
200
- // Public API (what's exposed in BookingFormServiceAPI interface)
201
- const publicApi = {
202
- formValues: formService.formValuesSignal,
203
- formSubmission,
204
- formSubmissionId,
205
- formId,
206
- form,
207
- setFormSubmission,
208
- validateFormSubmission,
209
- // Internal method for core component access
210
- _setValidateCallback,
237
+ /**
238
+ * Public API implementation.
239
+ */
240
+ return {
241
+ formServiceConfig,
211
242
  };
212
- return publicApi;
213
243
  });
@@ -8,7 +8,7 @@ export { TimeSlotListService, TimeSlotListServiceDefinition, TimeSlotService, Ti
8
8
  export { ServiceListService, ServiceListServiceDefinition, type ServiceListServiceAPI, type ServiceListServiceConfig, type ServiceListActions, type QueryOptions, loadServiceListServiceInitialData, type SuccessServiceListServiceConfigResult, type ErrorServiceListServiceConfigResult, } from './service-list/service-list.js';
9
9
  export { SYNTHETIC_CUSTOM_ID, SYNTHETIC_CUSTOMER_ID, } from '../api/query-services/index.js';
10
10
  export { executeBookAction, canBook, buildBookingRequest, buildCheckoutRequest, type CanBookParams, type BookResult, type BookingError, type BookActionParams, type BookChildProps, type BookProps, type BuildCheckoutParams, } from './booking/book-action/index.js';
11
- export { BookingFormService, BookingFormServiceDefinition, type BookingFormServiceAPI, type BookingFormServiceConfig, type BookingFormServiceInternalAPI, type ValidationResult, } from './booking-form/booking-form.js';
11
+ export { BookingFormService, BookingFormServiceDefinition, type BookingFormServiceAPI, type BookingFormServiceConfig, } from './booking-form/booking-form.js';
12
12
  export { PaymentService, PaymentServiceDefinition, type PaymentServiceAPI, type PaymentServiceConfig, type PaymentDetails, type PricingServiceSelection, type LineItemAdditionalInfo, loadPaymentConfig, type SuccessPaymentConfigResult, type ErrorPaymentConfigResult, } from './payment/payment.js';
13
13
  export { LocationListService, LocationListServiceDefinition, LocationType, loadLocationListServiceInitialData, locationListServiceBinding, type LocationListServiceAPI, type LocationListServiceConfig, type LocationListActions, type Location, type LoadLocationListServiceResult, getLocationById, } from './location-list/location-list.js';
14
14
  export { StaffMemberListService, StaffMemberListServiceDefinition, loadStaffMemberListServiceInitialData, staffMemberListServiceBinding, type StaffMemberListServiceAPI, type StaffMemberListServiceConfig, type StaffMemberListActions, type StaffMemberData, type LoadStaffMemberListServiceResult, } from './staff-member-list/staff-member-list.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wix/headless-bookings",
3
- "version": "0.0.95",
3
+ "version": "0.0.97",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "scripts": {
@@ -37,7 +37,7 @@
37
37
  "@wix/auto_sdk_bookings_event-time-slots": "^1.0.64",
38
38
  "@wix/auto_sdk_ecom_checkout": "^1.0.104",
39
39
  "@wix/form-public": "^0.104.0",
40
- "@wix/headless-forms": "0.0.27",
40
+ "@wix/headless-forms": "0.0.28",
41
41
  "@wix/headless-media": "0.0.20",
42
42
  "@wix/headless-utils": "0.0.8",
43
43
  "@wix/services-definitions": "^1.0.1",
@@ -72,5 +72,5 @@
72
72
  "groupId": "com.wixpress.headless-components"
73
73
  }
74
74
  },
75
- "falconPackageHash": "b1d1e8e7d9368179561ed8e5826b30fda9f2cba44fa3467581c70b4a"
75
+ "falconPackageHash": "7e4084020a17ac4efa052dae5a1a2a9ace583d3ea7ed88f9ff71cc9f"
76
76
  }