@wix/agent-skills 1.7.0 → 1.9.0

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.
Files changed (126) hide show
  1. package/README.md +3 -7
  2. package/package.json +1 -1
  3. package/skills/wix-app/SKILL.md +2 -0
  4. package/skills/wix-app/references/EDITOR_REACT_COMPONENT.md +2 -1
  5. package/skills/wix-app/references/STORES_VERSIONING.md +1 -0
  6. package/skills/wix-app/references/editor-react-component/ACCESSIBILITY.md +14 -0
  7. package/skills/wix-app/references/editor-react-component/REACT-GUIDELINES.md +11 -6
  8. package/skills/wix-app/references/editor-react-component/REACT-PATTERNS.md +3 -17
  9. package/skills/wix-app/references/editor-react-component/SSR.md +119 -0
  10. package/skills/wix-design-system/SKILL.md +5 -1
  11. package/skills/wix-headless/SKILL.md +55 -32
  12. package/skills/wix-headless/references/BUILD-astro.md +244 -0
  13. package/skills/wix-headless/references/BUILD-own-build.md +167 -0
  14. package/skills/wix-headless/references/BUILD.md +50 -252
  15. package/skills/wix-headless/references/DESIGN_SYSTEM.md +94 -34
  16. package/skills/wix-headless/references/DISCOVERY-connect.md +55 -0
  17. package/skills/wix-headless/references/DISCOVERY-create.md +238 -0
  18. package/skills/wix-headless/references/DISCOVERY.md +41 -422
  19. package/skills/wix-headless/references/PLAN-connect.md +19 -0
  20. package/skills/wix-headless/references/PLAN-create.md +17 -0
  21. package/skills/wix-headless/references/PLAN.md +37 -27
  22. package/skills/wix-headless/references/SEED.md +27 -18
  23. package/skills/wix-headless/references/SETUP.md +32 -213
  24. package/skills/wix-headless/references/astro/blog/BLOG_PAGES.md +5 -4
  25. package/skills/wix-headless/references/astro/bookings/COMPONENTS.md +45 -0
  26. package/skills/wix-headless/references/astro/bookings/SERVICES_PAGES.md +58 -0
  27. package/skills/wix-headless/references/astro/cms/CMS_FOUNDATIONS.md +5 -5
  28. package/skills/wix-headless/references/astro/cms/FAQ_KNOWLEDGE_BASE.md +10 -10
  29. package/skills/wix-headless/references/astro/cms/PORTFOLIO.md +12 -13
  30. package/skills/wix-headless/references/astro/cms/RESOURCE_LIBRARY.md +10 -12
  31. package/skills/wix-headless/references/astro/cms/TEAM_DIRECTORY.md +8 -8
  32. package/skills/wix-headless/references/astro/designer/INSTRUCTIONS.md +47 -27
  33. package/skills/wix-headless/references/astro/ecom/CART_PAGES.md +7 -8
  34. package/skills/wix-headless/references/astro/ecom/CART_WIRING.md +5 -5
  35. package/skills/wix-headless/references/astro/ecom/COMPONENTS_CSS.md +3 -3
  36. package/skills/wix-headless/references/astro/forms/CONTACT_FORM.md +5 -19
  37. package/skills/wix-headless/references/astro/gift-cards/COMPONENTS.md +2 -2
  38. package/skills/wix-headless/references/astro/gift-cards/PAGES.md +1 -1
  39. package/skills/wix-headless/references/astro/stores/BACK_IN_STOCK.md +6 -6
  40. package/skills/wix-headless/references/astro/stores/CATEGORY_PAGES.md +4 -4
  41. package/skills/wix-headless/references/astro/stores/COMPONENTS_CSS.md +3 -3
  42. package/skills/wix-headless/references/astro/stores/HOME_AND_NAV.md +3 -3
  43. package/skills/wix-headless/references/astro/stores/PRODUCT_PAGES.md +9 -9
  44. package/skills/wix-headless/references/astro/stores/SHARED_WIRING.md +5 -4
  45. package/skills/wix-headless/references/astro/templates/Footer.astro +1 -1
  46. package/skills/wix-headless/references/astro/templates/Layout.astro +1 -1
  47. package/skills/wix-headless/references/astro/templates/Navigation.astro +1 -1
  48. package/skills/wix-headless/references/astro/templates/astro.config.mjs +1 -1
  49. package/skills/wix-headless/references/astro/templates/bookings/AvailabilityCalendar.tsx +233 -0
  50. package/skills/wix-headless/references/astro/templates/bookings/BookingForm.tsx +136 -0
  51. package/skills/wix-headless/references/astro/templates/bookings/SeoTags.astro +25 -0
  52. package/skills/wix-headless/references/astro/templates/bookings/ServiceBookingFlow.tsx +54 -0
  53. package/skills/wix-headless/references/astro/templates/bookings/ServiceCard.astro +45 -0
  54. package/skills/wix-headless/references/astro/templates/bookings/booking-confirmation.astro +49 -0
  55. package/skills/wix-headless/references/astro/templates/bookings/bookingDriver.ts +245 -0
  56. package/skills/wix-headless/references/astro/templates/bookings/components-bookings.css +356 -0
  57. package/skills/wix-headless/references/astro/templates/bookings/services/[slug].astro +133 -0
  58. package/skills/wix-headless/references/astro/templates/bookings/services/index.astro +73 -0
  59. package/skills/wix-headless/references/astro/templates/global.css +2 -2
  60. package/skills/wix-headless/references/astro/templates/index.astro +1 -1
  61. package/skills/wix-headless/references/blog/BLOG_CONTENT.md +19 -9
  62. package/skills/wix-headless/references/blog/INSTRUCTIONS.md +3 -3
  63. package/skills/wix-headless/references/bookings/FLOW.md +185 -0
  64. package/skills/wix-headless/references/bookings/INSTRUCTIONS.md +90 -0
  65. package/skills/wix-headless/references/bookings/SERVICES_DATA.md +295 -0
  66. package/skills/wix-headless/references/cms/CMS_FOUNDATIONS.md +4 -2
  67. package/skills/wix-headless/references/cms/INSTRUCTIONS.md +27 -1
  68. package/skills/wix-headless/references/commands/known-apps.json +2 -1
  69. package/skills/wix-headless/references/custom/CONNECTION_PLAN.md +142 -0
  70. package/skills/wix-headless/references/custom/INSTRUCTIONS.md +71 -21
  71. package/skills/wix-headless/references/custom/blog/WIRING.md +52 -0
  72. package/skills/wix-headless/references/custom/bookings/WIRING.md +146 -0
  73. package/skills/wix-headless/references/custom/cms/WIRING.md +97 -0
  74. package/skills/wix-headless/references/custom/ecom/WIRING.md +67 -0
  75. package/skills/wix-headless/references/custom/forms/WIRING.md +101 -0
  76. package/skills/wix-headless/references/custom/stores/WIRING.md +80 -0
  77. package/skills/wix-headless/references/ecom/INSTRUCTIONS.md +5 -5
  78. package/skills/wix-headless/references/forms/INSTRUCTIONS.md +2 -2
  79. package/skills/wix-headless/references/gift-cards/INSTRUCTIONS.md +3 -3
  80. package/skills/wix-headless/references/images/INSTRUCTIONS.md +16 -15
  81. package/skills/wix-headless/references/seed-recipes.md +2 -2
  82. package/skills/wix-headless/references/shared/AGENTS_MD.md +47 -0
  83. package/skills/wix-headless/references/shared/AUTHENTICATION.md +3 -5
  84. package/skills/wix-headless/references/shared/DESIGN_MD.md +85 -0
  85. package/skills/wix-headless/references/shared/IMAGE_GENERATION.md +29 -28
  86. package/skills/wix-headless/references/shared/IMPLEMENTER.md +87 -27
  87. package/skills/wix-headless/references/shared/PRODUCTION_SHARP_EDGES.md +2 -2
  88. package/skills/wix-headless/references/shared/RETURN_CONTRACT.md +24 -313
  89. package/skills/wix-headless/references/shared/STYLING.md +8 -18
  90. package/skills/wix-headless/references/stores/INSTRUCTIONS.md +39 -9
  91. package/skills/wix-headless/references/stores/PRODUCT_CATALOG_DATA.md +17 -14
  92. package/skills/wix-headless/references/verticals/_schema.json +1 -1
  93. package/skills/wix-headless/references/verticals/_schema.md +3 -3
  94. package/skills/wix-headless/references/verticals/blog.md +1 -1
  95. package/skills/wix-headless/references/verticals/bookings.md +39 -0
  96. package/skills/wix-headless/references/verticals/cms.md +1 -1
  97. package/skills/wix-headless/references/verticals/ecom.md +2 -2
  98. package/skills/wix-headless/references/verticals/gift-cards.md +1 -1
  99. package/skills/wix-headless/references/verticals/stores.md +1 -1
  100. package/skills/wix-headless/scripts/check-manifest.mjs +143 -6
  101. package/skills/wix-headless/scripts/compose.mjs +540 -0
  102. package/skills/wix-headless/scripts/emit-design-tokens.mjs +128 -51
  103. package/skills/wix-headless/scripts/flatten.sh +61 -0
  104. package/skills/wix-headless/scripts/generate-images.mjs +242 -0
  105. package/skills/wix-headless/scripts/scaffold.sh +47 -16
  106. package/skills/wix-headless/scripts/write-decorative-json.mjs +62 -0
  107. package/skills/wix-manage/SKILL.md +13 -1
  108. package/skills/wix-manage/references/app-installation/install-wix-apps.md +3 -27
  109. package/skills/wix-manage/references/blog/how-to-create-blog-posts.md +1 -1
  110. package/skills/wix-manage/references/bookings/create-appointment-service.md +266 -0
  111. package/skills/wix-manage/references/bookings/create-booking-service-from-prompt.md +37 -0
  112. package/skills/wix-manage/references/bookings/create-class-service.md +245 -0
  113. package/skills/wix-manage/references/bookings/create-course-service.md +249 -0
  114. package/skills/wix-manage/references/cms/cms-data-items-crud.md +3 -2
  115. package/skills/wix-manage/references/cms/cms-references-and-relationships.md +1 -1
  116. package/skills/wix-manage/references/cms/cms-schema-management.md +2 -2
  117. package/skills/wix-manage/references/domains/domain-search-and-purchase.md +10 -7
  118. package/skills/wix-manage/references/forms/create-form.md +49 -1
  119. package/skills/wix-manage/references/stores/bulk-create-products-with-options.md +1 -1
  120. package/skills/wix-manage/references/stores/create-product-from-image.md +154 -2
  121. package/skills/wix-manage/references/stores/setup-online-store-catalog-v3.md +1 -1
  122. package/skills/wix-headless/references/astro/COMPOSE.md +0 -142
  123. package/skills/wix-headless/scripts/finalize-run-json.mjs +0 -141
  124. package/skills/wix-headless/scripts/init-site-json.mjs +0 -101
  125. package/skills/wix-headless/scripts/preview.sh +0 -45
  126. package/skills/wix-headless/scripts/release.sh +0 -73
@@ -0,0 +1,136 @@
1
+ import { useState } from "react";
2
+ import { book, navigateToCheckout, BookResultType } from "./bookingDriver";
3
+ import type { SelectedSlot } from "./bookingDriver";
4
+
5
+ // BookingForm.tsx — client:only="react" island. Renders the service's booking
6
+ // form SCHEMA (from @wix/forms, fetched server-side and passed in as `fields`),
7
+ // collects the values keyed by each field's `target`, and drives the booking
8
+ // sequence in bookingDriver.book(). This is the same schema-driven renderer the
9
+ // forms vertical uses (references/astro/forms/CONTACT_FORM.md) — generic inputs
10
+ // chosen by `componentType` — so it adapts to whatever fields the booking form
11
+ // defines, rather than hardcoding first/last/email/phone.
12
+ //
13
+ // On submit: book() returns CheckoutRequired (paid → hand off to the Wix-hosted
14
+ // checkout) or CheckoutSkipped (free / pay-in-person → straight to confirmation).
15
+
16
+ export interface BookingFormField {
17
+ label: string;
18
+ target: string; // the key createBooking expects in formSubmission
19
+ required: boolean;
20
+ componentType: string; // "TEXT_INPUT" | "DROPDOWN" | "PHONE_INPUT"
21
+ identifier?: string;
22
+ options?: { value: string; label: string }[];
23
+ }
24
+
25
+ interface Props {
26
+ service: any; // SSR-fetched service — bookingDriver reads payment + bookingPolicy
27
+ serviceName: string;
28
+ slot: SelectedSlot;
29
+ fields: BookingFormField[];
30
+ onSuccess: (id: string, startDate?: string) => void;
31
+ onCancel: () => void;
32
+ }
33
+
34
+ const friendlyError = (err: any): string => {
35
+ // Surface field validation (e.g. a malformed phone number) rather than crashing.
36
+ const violations = err?.details?.validationError?.fieldViolations ?? [];
37
+ const first = violations[0]?.description ?? violations[0]?.data?.errors?.[0]?.errorMessage;
38
+ if (first) return first;
39
+ if (typeof err?.message === "string") return err.message;
40
+ return "Something went wrong completing your booking. Please try again.";
41
+ };
42
+
43
+ export default function BookingForm({ service, serviceName, slot, fields, onSuccess, onCancel }: Props) {
44
+ const [values, setValues] = useState<Record<string, string>>({});
45
+ const [status, setStatus] = useState<"idle" | "submitting">("idle");
46
+ const [error, setError] = useState<string | null>(null);
47
+
48
+ const set = (target: string, v: string) =>
49
+ setValues((prev) => ({ ...prev, [target]: v }));
50
+
51
+ const when = new Date(slot.localStartDate).toLocaleString([], {
52
+ weekday: "long", month: "long", day: "numeric", hour: "2-digit", minute: "2-digit",
53
+ });
54
+
55
+ const handleSubmit = async (e: React.FormEvent) => {
56
+ e.preventDefault();
57
+ setStatus("submitting"); setError(null);
58
+ try {
59
+ const result = await book({
60
+ service,
61
+ slot,
62
+ formSubmission: values, // keyed by each field's `target`
63
+ timezone: slot.timezone,
64
+ });
65
+ if (result.type === BookResultType.CheckoutRequired) {
66
+ // Paid: hand the cart to the Wix-hosted checkout; it returns to /booking-confirmation.
67
+ // Carry service + start time on the return URL so the confirmation can show them
68
+ // (the in-memory selection is lost across the full-page redirect to Wix and back).
69
+ await navigateToCheckout(
70
+ result.cartId,
71
+ `${window.location.origin}/booking-confirmation?service=${encodeURIComponent(serviceName)}&startDate=${encodeURIComponent(slot.localStartDate)}`,
72
+ );
73
+ return; // redirect in progress
74
+ }
75
+ onSuccess(result.orderId, slot.localStartDate); // free / pay-in-person
76
+ } catch (err) {
77
+ console.error("[booking] failed:", err);
78
+ setError(friendlyError(err));
79
+ setStatus("idle");
80
+ }
81
+ };
82
+
83
+ return (
84
+ <form className="booking-form" onSubmit={handleSubmit}>
85
+ <div className="booking-form-summary">
86
+ <strong>{serviceName}</strong>
87
+ <span>{when}</span>
88
+ <button type="button" className="booking-form-change" onClick={onCancel}>Choose another time</button>
89
+ </div>
90
+
91
+ {fields.map((field) => (
92
+ <div key={field.target} className="booking-field">
93
+ <label className="booking-label">
94
+ {field.label}
95
+ {field.required && <span className="booking-required" aria-hidden="true"> *</span>}
96
+ </label>
97
+ {field.componentType === "DROPDOWN" && field.options ? (
98
+ <select
99
+ className="booking-input"
100
+ required={field.required}
101
+ value={values[field.target] ?? ""}
102
+ onChange={(e) => set(field.target, e.target.value)}
103
+ >
104
+ <option value="">Select an option</option>
105
+ {field.options.map((o) => (
106
+ <option key={o.value} value={o.value}>{o.label}</option>
107
+ ))}
108
+ </select>
109
+ ) : field.identifier === "TEXT_AREA" || field.target?.includes("message") ? (
110
+ <textarea
111
+ className="booking-input"
112
+ required={field.required}
113
+ rows={4}
114
+ value={values[field.target] ?? ""}
115
+ onChange={(e) => set(field.target, e.target.value)}
116
+ />
117
+ ) : (
118
+ <input
119
+ className="booking-input"
120
+ type={field.target === "email" ? "email" : field.componentType === "PHONE_INPUT" ? "tel" : "text"}
121
+ required={field.required}
122
+ value={values[field.target] ?? ""}
123
+ onChange={(e) => set(field.target, e.target.value)}
124
+ />
125
+ )}
126
+ </div>
127
+ ))}
128
+
129
+ {error && <p className="booking-error" role="alert">{error}</p>}
130
+
131
+ <button type="submit" className="booking-cta" disabled={status === "submitting"}>
132
+ {status === "submitting" ? "Booking…" : "Confirm booking"}
133
+ </button>
134
+ </form>
135
+ );
136
+ }
@@ -0,0 +1,25 @@
1
+ ---
2
+ // SeoTags.astro — renders Wix-resolved SEO tags into <head> for service pages.
3
+ // Pass `service.seoData.tags` (Services V2) — title/meta/link/script — so the
4
+ // service detail page ships Wix's sitemap/SEO/social tags. Mirrors the stores
5
+ // SeoTags template. Mount inside the Layout's `head` slot on `/services/[slug]`.
6
+ interface SeoTag {
7
+ type?: string;
8
+ props?: Record<string, any> | null;
9
+ children?: string;
10
+ disabled?: boolean;
11
+ }
12
+ interface Props { tags?: SeoTag[]; }
13
+ const { tags = [] } = Astro.props;
14
+ const visibleTags = tags.filter((t) => !t.disabled);
15
+ ---
16
+ {
17
+ visibleTags.map((tag) => {
18
+ const props = tag.props ?? {};
19
+ if (tag.type === "title") return <title set:html={tag.children ?? ""} />;
20
+ if (tag.type === "meta") return <meta {...props} />;
21
+ if (tag.type === "link") return <link {...props} />;
22
+ if (tag.type === "script") return <script {...props} is:inline set:html={tag.children ?? ""} />;
23
+ return null;
24
+ })
25
+ }
@@ -0,0 +1,54 @@
1
+ import { useState } from "react";
2
+ import AvailabilityCalendar from "./AvailabilityCalendar";
3
+ import BookingForm, { type BookingFormField } from "./BookingForm";
4
+ import type { SelectedSlot } from "./bookingDriver";
5
+
6
+ // ServiceBookingFlow.tsx — client:only="react" coordinator island. Holds the
7
+ // selected-slot state shared between the calendar and the form, transitions
8
+ // between them, and redirects to the confirmation page on success. The SSR
9
+ // detail page passes the full `service` (the driver reads its payment/policy)
10
+ // and the booking-form `fields` (the @wix/forms schema) through to the form.
11
+ //
12
+ // This is the framework-agnostic flow shape (a step coordinator + shared
13
+ // selection state). On another framework, the same two steps + shared state can
14
+ // be route-driven instead — see references/bookings/FLOW.md.
15
+
16
+ interface Props {
17
+ service: any;
18
+ serviceName: string;
19
+ serviceType: "APPOINTMENT" | "CLASS";
20
+ fields: BookingFormField[];
21
+ }
22
+
23
+ export default function ServiceBookingFlow({ service, serviceName, serviceType, fields }: Props) {
24
+ const [selectedSlot, setSelectedSlot] = useState<SelectedSlot | null>(null);
25
+
26
+ const handleSuccess = (_orderId: string, startDate?: string) => {
27
+ const params = new URLSearchParams();
28
+ if (startDate) params.set("startDate", startDate);
29
+ if (serviceName) params.set("service", serviceName);
30
+ window.location.href = `/booking-confirmation?${params.toString()}`;
31
+ };
32
+
33
+ if (!selectedSlot) {
34
+ return (
35
+ <AvailabilityCalendar
36
+ serviceId={service._id}
37
+ serviceName={serviceName}
38
+ serviceType={serviceType}
39
+ onSlotSelected={setSelectedSlot}
40
+ />
41
+ );
42
+ }
43
+
44
+ return (
45
+ <BookingForm
46
+ service={service}
47
+ serviceName={serviceName}
48
+ slot={selectedSlot}
49
+ fields={fields}
50
+ onSuccess={handleSuccess}
51
+ onCancel={() => setSelectedSlot(null)}
52
+ />
53
+ );
54
+ }
@@ -0,0 +1,45 @@
1
+ ---
2
+ // ServiceCard.astro — static card for the services listing grid.
3
+ // Props in, HTML out; no client-side interactivity. Works for APPOINTMENT and
4
+ // CLASS services. Classes (.service-card, .service-card-image,
5
+ // .service-card-meta, .service-card-price, …) are owned by
6
+ // src/styles/components-bookings.css (pre-copied by the orchestrator).
7
+ interface Props {
8
+ id: string;
9
+ slug: string;
10
+ name: string;
11
+ tagLine?: string;
12
+ durationMinutes: number;
13
+ price?: string; // formatted string, e.g. "$75.00" — already formatted by caller
14
+ currency?: string;
15
+ imageUrl?: string;
16
+ type: "APPOINTMENT" | "CLASS";
17
+ }
18
+
19
+ const { slug, name, tagLine, durationMinutes, price, imageUrl } = Astro.props;
20
+ ---
21
+
22
+ <a href={`/services/${slug}`} class="service-card">
23
+ {
24
+ imageUrl ? (
25
+ <div class="service-card-image">
26
+ <img src={imageUrl} alt={name} loading="lazy" />
27
+ </div>
28
+ ) : (
29
+ <div
30
+ class="service-card-image service-card-image--placeholder"
31
+ aria-hidden="true"
32
+ style="background-color: var(--color-surface-secondary, var(--color-paper-warm, var(--color-cream)));"
33
+ />
34
+ )
35
+ }
36
+
37
+ <div class="service-card-meta">
38
+ <h3 class="service-card-name">{name}</h3>
39
+ {tagLine && <p class="service-card-tagline">{tagLine}</p>}
40
+ <div class="service-card-price">
41
+ <span>{durationMinutes} min</span>
42
+ {price && <span>{price}</span>}
43
+ </div>
44
+ </div>
45
+ </a>
@@ -0,0 +1,49 @@
1
+ ---
2
+ // src/pages/booking-confirmation.astro — post-booking confirmation.
3
+ //
4
+ // Renders from the redirect query params (service name + start date) that the
5
+ // booking step passes through. The Wix-hosted checkout returns here after a paid
6
+ // booking; a free / pay-in-person booking lands here directly. Do not re-fetch a
7
+ // stranger's booking from this public page — show what the flow passed in.
8
+ import Layout from "../layouts/Layout.astro";
9
+
10
+ const serviceName = Astro.url.searchParams.get("service") ?? "your service";
11
+ const startDateParam = Astro.url.searchParams.get("startDate");
12
+ const formattedDate = startDateParam
13
+ ? new Date(startDateParam).toLocaleString("en-US", {
14
+ weekday: "long", month: "long", day: "numeric", hour: "2-digit", minute: "2-digit",
15
+ })
16
+ : null;
17
+ ---
18
+
19
+ <!-- `max-w-prose` (built-in literal = 65ch), not a bare max-w-<size> that could
20
+ collapse to the spacing scale. -->
21
+ <Layout title="Booking confirmed">
22
+ <section class="max-w-prose mx-auto px-lg py-4xl text-center">
23
+ <div class="w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-xl"
24
+ style="background-color: var(--color-accent);" aria-hidden="true">
25
+ <span class="text-2xl" style="color: var(--color-paper);">✓</span>
26
+ </div>
27
+ <hr class="editorial-rule w-16 mx-auto mb-lg" />
28
+ <h1 class="font-display text-4xl md:text-5xl leading-tight mb-md">Thank you for booking</h1>
29
+
30
+ {
31
+ formattedDate ? (
32
+ <p class="text-lg text-mute leading-relaxed mb-md">
33
+ Your spot in <strong class="text-ink">{serviceName}</strong> is <strong class="text-ink">confirmed</strong> for{" "}
34
+ <strong class="text-ink">{formattedDate}</strong>. We've sent the details to your email.
35
+ </p>
36
+ ) : (
37
+ <p class="text-lg text-mute leading-relaxed mb-md">
38
+ Your booking for <strong class="text-ink">{serviceName}</strong> is <strong class="text-ink">confirmed</strong>. We've sent the details to your email.
39
+ </p>
40
+ )
41
+ }
42
+
43
+ <div class="flex flex-col gap-md items-center">
44
+ <a href="/services" class="inline-block font-display text-base px-xl py-md rounded-sm"
45
+ style="background-color: var(--color-accent); color: var(--color-paper);">Browse more services</a>
46
+ <a href="/" class="text-sm text-mute hover:text-ink">Return home</a>
47
+ </div>
48
+ </section>
49
+ </Layout>
@@ -0,0 +1,245 @@
1
+ // bookingDriver.ts — the booking sequence in plain @wix SDK calls.
2
+ // Framework-agnostic: no React, no signals, no UI. Any framework's booking step
3
+ // imports book()/navigateToCheckout() and drives them; APPOINTMENT and CLASS
4
+ // share the same sequence.
5
+ //
6
+ // Mechanism = ecom Cart V2 on every path: createBooking leaves the booking
7
+ // CREATED, then the cart holds the seat — a paid service hands off to the
8
+ // Wix-hosted checkout, a free / pay-in-person service places the order directly.
9
+ //
10
+ // On @wix/astro the SDK calls run ambiently (the visitor client is provided by
11
+ // @wix/essentials, like the ecom CartView island) — no createClient/OAuthStrategy
12
+ // needed. On an own/own-build SPA, acquire a visitor client with
13
+ // createClient({ modules, auth: OAuthStrategy({ clientId }) }) and call the same
14
+ // functions through it. Keep the SDK calls, payload shapes, and the sequence;
15
+ // adapt only brand copy/styling in the UI that drives this module.
16
+
17
+ import { bookings } from "@wix/bookings";
18
+ import { createCart, calculateCart, placeOrder } from "@wix/auto_sdk_ecom_cart-v-2";
19
+ import { redirects } from "@wix/redirects";
20
+
21
+ // ── Constants (C:src/services/constants.ts) ────────────────────────────────
22
+ export const BOOKING_APP_ID = "13d21c63-b5ec-5912-8397-c3a5ddb27a97";
23
+ export const STAFF_MEMBER_RESOURCE_TYPE_ID = "1cd44cf8-756f-41c3-bd90-3e2ffcaf1155";
24
+
25
+ // ── Types ───────────────────────────────────────────────────────────────────
26
+ // FormValues = the submitted booking-form values, keyed by each field's `target`
27
+ // (NOT hardcoded field names). The default booking form's targets are snake_case
28
+ // `first_name`/`last_name`/`email`/`phone`; read them from the form schema and key
29
+ // the values by `target` — never hardcode the keys here.
30
+ export type FormValues = Record<string, unknown>;
31
+
32
+ export interface SelectedSlot {
33
+ serviceType: "APPOINTMENT" | "CLASS";
34
+ serviceId: string;
35
+ localStartDate: string; // local "YYYY-MM-DDTHH:mm:ss" (NOT UTC) — maps to slot.startDate
36
+ localEndDate: string; // " " → slot.endDate
37
+ timezone: string;
38
+ // APPOINTMENT:
39
+ scheduleId?: string;
40
+ locationId?: string; // from slot.location._id (the id field is `_id`, not `.id`)
41
+ locationType?: string; // "BUSINESS" | "CUSTOMER" | "CUSTOM"
42
+ // CLASS:
43
+ eventId?: string;
44
+ // Resource chosen on the slot (flow 5). When absent the driver emits the
45
+ // ANY_RESOURCE fallback so Wix auto-assigns a bookable staff member.
46
+ resource?: { _id: string; name?: string };
47
+ }
48
+
49
+ export interface BookParams {
50
+ service: any; // the @wix/bookings Service (read payment.options + bookingPolicy)
51
+ slot: SelectedSlot;
52
+ formSubmission: FormValues; // values from the @wix/forms Form, keyed by target
53
+ timezone: string;
54
+ totalParticipants?: number;
55
+ /** consumer override; when omitted, derived from service.payment.options */
56
+ selectedPaymentOption?: "ONLINE" | "OFFLINE";
57
+ }
58
+
59
+ export const BookResultType = {
60
+ CheckoutRequired: "checkout_required",
61
+ CheckoutSkipped: "checkout_skipped",
62
+ } as const;
63
+ export type BookResult =
64
+ | { type: typeof BookResultType.CheckoutRequired; cartId: string }
65
+ | { type: typeof BookResultType.CheckoutSkipped; orderId: string };
66
+
67
+ // ── Payment derivation ───────────────────────────────────────────────────────
68
+ function deriveSelectedPaymentOption(service: any): "ONLINE" | "OFFLINE" {
69
+ const options = service?.payment?.options;
70
+ if (options?.online && !options?.inPerson) return "ONLINE";
71
+ if (!options?.online && options?.inPerson) return "OFFLINE";
72
+ return "ONLINE"; // both / neither → ONLINE (consumer override wins, see below)
73
+ }
74
+
75
+ // LocationType maps from the availability slot's type → the booking endpoint enum.
76
+ function mapLocationType(slotType?: string): string {
77
+ switch (slotType) {
78
+ case "BUSINESS":
79
+ return "OWNER_BUSINESS";
80
+ case "CUSTOMER":
81
+ return "CUSTOM";
82
+ case "CUSTOM":
83
+ return "OWNER_CUSTOM";
84
+ default:
85
+ return "OWNER_BUSINESS";
86
+ }
87
+ }
88
+
89
+ // ── buildBookingRequest ───────────────────────────────────────────────────────
90
+ function buildBookingRequest(params: BookParams) {
91
+ const { service, slot, formSubmission, timezone } = params;
92
+ const resource = slot.resource; // prefer the slot's chosen resource when present
93
+
94
+ return {
95
+ booking: {
96
+ // Consumer override wins over the service-config heuristic.
97
+ selectedPaymentOption:
98
+ params.selectedPaymentOption ?? deriveSelectedPaymentOption(service),
99
+ totalParticipants: params.totalParticipants || 1,
100
+ bookedEntity: {
101
+ slot: {
102
+ serviceId: slot.serviceId,
103
+ // APPOINTMENT carries scheduleId; CLASS carries eventId (Wix derives the rest).
104
+ scheduleId: slot.scheduleId ?? undefined,
105
+ startDate: slot.localStartDate,
106
+ endDate: slot.localEndDate,
107
+ timezone,
108
+ eventId: slot.eventId ?? undefined,
109
+ // Resource: use the chosen one, else the ANY_RESOURCE fallback so Wix
110
+ // auto-assigns a bookable staff member. Appointment availability slots
111
+ // return availableResources:[] yet book fine via ANY_RESOURCE.
112
+ ...(resource
113
+ ? { resource: { _id: resource._id, name: resource.name } }
114
+ : {
115
+ resourceSelections: [
116
+ {
117
+ resourceTypeId: STAFF_MEMBER_RESOURCE_TYPE_ID,
118
+ selectionMethod: "ANY_RESOURCE",
119
+ },
120
+ ],
121
+ }),
122
+ location:
123
+ slot.locationId || slot.locationType
124
+ ? {
125
+ ...(slot.locationId ? { _id: slot.locationId } : {}),
126
+ locationType: mapLocationType(slot.locationType),
127
+ }
128
+ : { locationType: "OWNER_BUSINESS" },
129
+ },
130
+ },
131
+ },
132
+ participantNotification: {
133
+ metadata: { channels: "EMAIL,SMS" },
134
+ notifyParticipants: true,
135
+ },
136
+ sendSmsReminder: true,
137
+ formSubmission,
138
+ };
139
+ }
140
+
141
+ // ── buildCartRequest ──────────────────────────────────────────────────────────
142
+ function buildCartRequest(args: {
143
+ bookingIds: string[];
144
+ contactDetails?: any;
145
+ businessLocationId?: string | null;
146
+ }) {
147
+ const cart: any = { source: { channelType: "WEB" } };
148
+ if (args.businessLocationId)
149
+ cart.businessInfo = { locationId: args.businessLocationId };
150
+ if (args.contactDetails) {
151
+ cart.customerInfo = args.contactDetails.email
152
+ ? { email: args.contactDetails.email }
153
+ : {};
154
+ if (args.contactDetails.fullAddress?.country) {
155
+ cart.deliveryInfo = { address: { ...args.contactDetails.fullAddress } };
156
+ cart.paymentInfo = {
157
+ billingAddress: { ...args.contactDetails.fullAddress },
158
+ };
159
+ }
160
+ }
161
+ return {
162
+ catalogItems: args.bookingIds.map((id) => ({
163
+ quantity: 1,
164
+ catalogReference: { catalogItemId: id, appId: BOOKING_APP_ID },
165
+ })),
166
+ cart,
167
+ };
168
+ }
169
+
170
+ // ── isCheckoutRequired ────────────────────────────────────────────────────────
171
+ function isCheckoutRequired(cart: any, summary: any, service: any): boolean {
172
+ if (service?.bookingPolicy?.cancellationFeePolicy?.enabled) return true;
173
+ const total = Number(summary?.priceSummary?.total?.amount ?? 0);
174
+ if (total === 0) return false;
175
+ if (cart?.lineItems?.[0]?.paymentConfig?.paymentOption === "FULL_PAYMENT_OFFLINE")
176
+ return false;
177
+ return true;
178
+ }
179
+
180
+ // ── canBook ───────────────────────────────────────────────────────────────────
181
+ function canBook(params: BookParams): boolean {
182
+ const slotOk =
183
+ !!params.slot &&
184
+ !!params.slot.localStartDate &&
185
+ (params.slot.serviceType === "CLASS"
186
+ ? !!params.slot.eventId
187
+ : !!params.slot.scheduleId);
188
+ return slotOk && params.formSubmission != null;
189
+ }
190
+
191
+ // ── book — the full sequence ──────────────────────────────────────────────────
192
+ export async function book(params: BookParams): Promise<BookResult> {
193
+ if (!canBook(params))
194
+ throw new Error("Cannot book: missing slot or form submission");
195
+
196
+ // 1. createBooking → CREATED (the cart holds the seat)
197
+ const req = buildBookingRequest(params);
198
+ const created = await bookings.createBooking(req.booking as any, {
199
+ participantNotification: req.participantNotification,
200
+ sendSmsReminder: req.sendSmsReminder,
201
+ formSubmission: req.formSubmission as any,
202
+ });
203
+ const bookingId = created?.booking?._id;
204
+ if (!bookingId) throw new Error("Failed to create booking");
205
+ const contactDetails = created?.booking?.contactDetails;
206
+
207
+ // 2. createCart — one catalog item per booking id (channel WEB, bookings appId)
208
+ const businessLocationId = params.slot.locationId ?? undefined;
209
+ const cart = await createCart(
210
+ buildCartRequest({ bookingIds: [bookingId], contactDetails, businessLocationId }),
211
+ );
212
+ const cartId = cart?._id;
213
+ if (!cartId) throw new Error("Failed to create cart");
214
+
215
+ // 3. calculateCart → totals (not stored on the Cart V2 entity)
216
+ const { cart: calculatedCart, summary } = await calculateCart(cartId);
217
+ if (!calculatedCart || !summary) throw new Error("Failed to calculate cart");
218
+
219
+ // 4. checkout required? → redirect (paid) ; else placeOrder (free/offline)
220
+ if (isCheckoutRequired(calculatedCart, summary, params.service)) {
221
+ return { type: BookResultType.CheckoutRequired, cartId };
222
+ }
223
+ const order = await placeOrder(cartId);
224
+ const orderId = order?.orderId;
225
+ if (!orderId) throw new Error("Failed to place order");
226
+ return { type: BookResultType.CheckoutSkipped, orderId };
227
+ }
228
+
229
+ // ── navigateToCheckout ────────────────────────────────────────────────────────
230
+ // Paid services: hand the cart to the Wix-hosted ecom checkout. Same shape on
231
+ // every path — ecomCheckout.checkoutId = the cartId.
232
+ export async function navigateToCheckout(
233
+ cartId: string,
234
+ postFlowUrl: string,
235
+ ): Promise<void> {
236
+ const { redirectSession } = await redirects.createRedirectSession({
237
+ ecomCheckout: { checkoutId: cartId },
238
+ callbacks: { postFlowUrl },
239
+ });
240
+ if (redirectSession?.fullUrl) {
241
+ window.location.href = redirectSession.fullUrl;
242
+ } else {
243
+ throw new Error("Failed to create redirect session");
244
+ }
245
+ }