@fayz-ai/plugin-agenda 0.2.1 → 0.3.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 (83) hide show
  1. package/dist/chunk-DRZF6CV2.js +421 -0
  2. package/dist/chunk-DRZF6CV2.js.map +1 -0
  3. package/dist/chunk-LFUELUIT.cjs +423 -0
  4. package/dist/chunk-LFUELUIT.cjs.map +1 -0
  5. package/dist/index.cjs +741 -10
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +741 -10
  9. package/dist/index.js.map +1 -1
  10. package/dist/migrations/index.d.ts +2 -0
  11. package/dist/migrations/index.d.ts.map +1 -0
  12. package/dist/public/BookingWidget.d.ts +4 -2
  13. package/dist/public/BookingWidget.d.ts.map +1 -1
  14. package/dist/public/components/BrandHeader.d.ts +6 -0
  15. package/dist/public/components/BrandHeader.d.ts.map +1 -0
  16. package/dist/public/components/ServiceCard.d.ts +5 -0
  17. package/dist/public/components/ServiceCard.d.ts.map +1 -0
  18. package/dist/public/components/SidebarExtras.d.ts +4 -0
  19. package/dist/public/components/SidebarExtras.d.ts.map +1 -0
  20. package/dist/public/components/StepRailItem.d.ts +4 -0
  21. package/dist/public/components/StepRailItem.d.ts.map +1 -0
  22. package/dist/public/components/SuccessPanel.d.ts +4 -0
  23. package/dist/public/components/SuccessPanel.d.ts.map +1 -0
  24. package/dist/public/components/SummaryRail.d.ts +27 -0
  25. package/dist/public/components/SummaryRail.d.ts.map +1 -0
  26. package/dist/public/components/defaults.d.ts +3 -0
  27. package/dist/public/components/defaults.d.ts.map +1 -0
  28. package/dist/public/context.d.ts +22 -8
  29. package/dist/public/context.d.ts.map +1 -1
  30. package/dist/public/createPublicBookingPlugin.d.ts +27 -10
  31. package/dist/public/createPublicBookingPlugin.d.ts.map +1 -1
  32. package/dist/public/data.d.ts +37 -0
  33. package/dist/public/data.d.ts.map +1 -0
  34. package/dist/public/data.supabase.d.ts +7 -0
  35. package/dist/public/data.supabase.d.ts.map +1 -0
  36. package/dist/public/format.d.ts +18 -0
  37. package/dist/public/format.d.ts.map +1 -0
  38. package/dist/public/hooks.d.ts +13 -11
  39. package/dist/public/hooks.d.ts.map +1 -1
  40. package/dist/public/index.cjs +1016 -613
  41. package/dist/public/index.cjs.map +1 -1
  42. package/dist/public/index.d.ts +15 -4
  43. package/dist/public/index.d.ts.map +1 -1
  44. package/dist/public/index.js +1006 -616
  45. package/dist/public/index.js.map +1 -1
  46. package/dist/public/steps/ContactStep.d.ts +30 -0
  47. package/dist/public/steps/ContactStep.d.ts.map +1 -0
  48. package/dist/public/steps/DateTimeStep.d.ts +23 -0
  49. package/dist/public/steps/DateTimeStep.d.ts.map +1 -0
  50. package/dist/public/steps/OverviewStep.d.ts +16 -0
  51. package/dist/public/steps/OverviewStep.d.ts.map +1 -0
  52. package/dist/public/steps/PaymentStep.d.ts +20 -0
  53. package/dist/public/steps/PaymentStep.d.ts.map +1 -0
  54. package/dist/public/types.d.ts +134 -0
  55. package/dist/public/types.d.ts.map +1 -1
  56. package/package.json +12 -12
  57. package/src/index.ts +11 -0
  58. package/src/migrations/001_public_booking.sql +278 -0
  59. package/src/migrations/index.ts +282 -0
  60. package/src/public/BookingWidget.tsx +136 -713
  61. package/src/public/components/BrandHeader.tsx +27 -0
  62. package/src/public/components/ServiceCard.tsx +39 -0
  63. package/src/public/components/SidebarExtras.tsx +30 -0
  64. package/src/public/components/StepRailItem.tsx +27 -0
  65. package/src/public/components/SuccessPanel.tsx +27 -0
  66. package/src/public/components/SummaryRail.tsx +90 -0
  67. package/src/public/components/defaults.ts +14 -0
  68. package/src/public/context.tsx +64 -7
  69. package/src/public/createPublicBookingPlugin.ts +131 -21
  70. package/src/public/data.supabase.ts +94 -0
  71. package/src/public/data.ts +99 -0
  72. package/src/public/format.ts +61 -0
  73. package/src/public/hooks.ts +22 -34
  74. package/src/public/index.ts +57 -4
  75. package/src/public/steps/ContactStep.tsx +179 -0
  76. package/src/public/steps/DateTimeStep.tsx +138 -0
  77. package/src/public/steps/OverviewStep.tsx +81 -0
  78. package/src/public/steps/PaymentStep.tsx +180 -0
  79. package/src/public/types.ts +169 -3
  80. package/dist/chunk-GAJVIEXM.cjs +0 -870
  81. package/dist/chunk-GAJVIEXM.cjs.map +0 -1
  82. package/dist/chunk-U6VTLOHN.js +0 -867
  83. package/dist/chunk-U6VTLOHN.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import { createSupabaseAgendaProvider, createMockAgendaProvider } from './chunk-U6VTLOHN.js';
2
- export { createMockAgendaProvider } from './chunk-U6VTLOHN.js';
3
- import { setAgendaTenantId } from './chunk-3LJKZQK4.js';
1
+ import { createMockAgendaProvider } from './chunk-DRZF6CV2.js';
2
+ export { createMockAgendaProvider } from './chunk-DRZF6CV2.js';
3
+ import { setAgendaTenantId, getAgendaTenantId } from './chunk-3LJKZQK4.js';
4
4
  import React12, { useState, useEffect, useRef, useMemo, useCallback } from 'react';
5
- import { getSupabaseClientOptional, registerTranslations, createSafeDataProvider, usePluginRuntimeOptional, useTranslation, getCurrentLocale, formatCurrency } from '@fayz-ai/core';
5
+ import { getSupabaseClientOptional, registerTranslations, createSafeDataProvider, usePluginRuntimeOptional, useTranslation, getActiveTenantId, getCurrentLocale, formatCurrency } from '@fayz-ai/core';
6
6
  import { createPluginContext, setScheduleBlockConfig, getScheduleBlockConfig, PluginSettingsPanel, dedup, SettingsGroup, ToggleRow, SelectRow, usePluginPrefs, PersonLink, CrudFormPage, CrudDetailPage } from '@fayz-ai/saas';
7
7
  import FullCalendar from '@fullcalendar/react';
8
8
  import dayGridPlugin from '@fullcalendar/daygrid';
@@ -1714,8 +1714,8 @@ function AppointmentModal({ open, mode, bookingId, prefill, initialTab, external
1714
1714
  onCancel: () => setClientEditing(false),
1715
1715
  onSubmit: async (data) => {
1716
1716
  try {
1717
- const { getSupabaseClientOptional: getSupabaseClientOptional3 } = await import('@fayz-ai/core');
1718
- const supabase = getSupabaseClientOptional3();
1717
+ const { getSupabaseClientOptional: getSupabaseClientOptional4 } = await import('@fayz-ai/core');
1718
+ const supabase = getSupabaseClientOptional4();
1719
1719
  if (!supabase) return;
1720
1720
  const dbData = {};
1721
1721
  for (const [k, v] of Object.entries(data)) {
@@ -1876,10 +1876,10 @@ function AppointmentModal({ open, mode, bookingId, prefill, initialTab, external
1876
1876
  onClick: async () => {
1877
1877
  setCreatingClient(true);
1878
1878
  try {
1879
- const { getSupabaseClientOptional: getSupabaseClientOptional3 } = await import('@fayz-ai/core');
1880
- const { getAgendaTenantId } = await import('./tenant-LAUWVUYB.js');
1881
- const supabase = getSupabaseClientOptional3();
1882
- const tenantId = getAgendaTenantId();
1879
+ const { getSupabaseClientOptional: getSupabaseClientOptional4 } = await import('@fayz-ai/core');
1880
+ const { getAgendaTenantId: getAgendaTenantId2 } = await import('./tenant-LAUWVUYB.js');
1881
+ const supabase = getSupabaseClientOptional4();
1882
+ const tenantId = getAgendaTenantId2();
1883
1883
  if (!supabase || !tenantId) throw new Error("Not initialized");
1884
1884
  const { data: personRow, error: personError } = await supabase.schema("saas_core").from("persons").insert({
1885
1885
  tenant_id: tenantId,
@@ -3461,6 +3461,448 @@ function AgendaPage({ config, provider: provider2, store }) {
3461
3461
  }, [tenantId]);
3462
3462
  return /* @__PURE__ */ jsx(AgendaContextProvider, { config, provider: provider2, store, children: /* @__PURE__ */ jsx(CalendarView, {}) });
3463
3463
  }
3464
+ function getTenantId() {
3465
+ return getAgendaTenantId() ?? getActiveTenantId();
3466
+ }
3467
+ function snakeToCamel(obj) {
3468
+ const result = {};
3469
+ for (const [key, value] of Object.entries(obj)) {
3470
+ result[key.replace(/_([a-z])/g, (_, c) => c.toUpperCase())] = value;
3471
+ }
3472
+ return result;
3473
+ }
3474
+ function getClients() {
3475
+ const supabase = getSupabaseClientOptional();
3476
+ if (!supabase) throw new Error("Supabase not initialized");
3477
+ return { core: supabase.schema("saas_core"), pub: supabase };
3478
+ }
3479
+ function mapBooking(row) {
3480
+ return snakeToCamel(row);
3481
+ }
3482
+ function mapSchedule(row) {
3483
+ return snakeToCamel(row);
3484
+ }
3485
+ function addMinutes(iso, minutes) {
3486
+ const d = new Date(iso);
3487
+ d.setMinutes(d.getMinutes() + minutes);
3488
+ return d.toISOString();
3489
+ }
3490
+ function unique(values) {
3491
+ return Array.from(new Set(values.filter((value) => !!value)));
3492
+ }
3493
+ function indexById(rows) {
3494
+ return new Map((rows ?? []).filter((row) => row?.id).map((row) => [row.id, row]));
3495
+ }
3496
+ function groupBy(rows, getKey) {
3497
+ const grouped = /* @__PURE__ */ new Map();
3498
+ for (const row of rows) {
3499
+ const key = getKey(row);
3500
+ if (!key) continue;
3501
+ grouped.set(key, [...grouped.get(key) ?? [], row]);
3502
+ }
3503
+ return grouped;
3504
+ }
3505
+ function getDurationMinutes(startsAt, endsAt) {
3506
+ if (!endsAt) return null;
3507
+ return Math.round((new Date(endsAt).getTime() - new Date(startsAt).getTime()) / 6e4);
3508
+ }
3509
+ function mergeBookings(viewBookings, canonicalBookings) {
3510
+ const canonicalIds = new Set(canonicalBookings.map((booking) => booking.id));
3511
+ const canonicalOrderIds = new Set(canonicalBookings.map((booking) => booking.orderId).filter(Boolean));
3512
+ const merged = [
3513
+ ...canonicalBookings,
3514
+ ...viewBookings.filter((booking) => {
3515
+ if (canonicalIds.has(booking.id)) return false;
3516
+ if (booking.orderId && canonicalOrderIds.has(booking.orderId)) return false;
3517
+ if (canonicalOrderIds.has(booking.id)) return false;
3518
+ return true;
3519
+ })
3520
+ ];
3521
+ return merged.sort((a, b) => new Date(a.startsAt).getTime() - new Date(b.startsAt).getTime());
3522
+ }
3523
+ async function hydrateCanonicalBookings(core, bookings) {
3524
+ const personIds = unique(bookings.flatMap((booking) => [booking.party_id, booking.assignee_id]));
3525
+ const locationIds = unique(bookings.map((booking) => booking.location_id));
3526
+ const orderIds = unique(bookings.map((booking) => booking.order_id));
3527
+ unique(bookings.map((booking) => booking.id));
3528
+ const [
3529
+ { data: persons, error: personsError },
3530
+ { data: locations, error: locationsError },
3531
+ { data: orders, error: ordersError },
3532
+ { data: items, error: itemsError }
3533
+ ] = await Promise.all([
3534
+ personIds.length ? core.from("persons").select("id, name, phone, email, avatar_url").in("id", personIds) : Promise.resolve({ data: [], error: null }),
3535
+ locationIds.length ? core.from("locations").select("id, name").in("id", locationIds) : Promise.resolve({ data: [], error: null }),
3536
+ orderIds.length ? core.from("orders").select("id, total, status").in("id", orderIds) : Promise.resolve({ data: [], error: null }),
3537
+ orderIds.length ? core.from("order_items").select("id, order_id, service_id, name, duration_minutes, unit_price, assignee_id, sort_order").in("order_id", orderIds) : Promise.resolve({ data: [], error: null })
3538
+ ]);
3539
+ if (personsError) throw personsError;
3540
+ if (locationsError) throw locationsError;
3541
+ if (ordersError) throw ordersError;
3542
+ if (itemsError) throw itemsError;
3543
+ const personsById = indexById(persons);
3544
+ const locationsById = indexById(locations);
3545
+ const ordersById = indexById(orders);
3546
+ const itemsByOrderId = groupBy(items ?? [], (item) => item.order_id);
3547
+ return bookings.map((booking) => {
3548
+ const client = booking.party_id ? personsById.get(booking.party_id) : null;
3549
+ const professional = booking.assignee_id ? personsById.get(booking.assignee_id) : null;
3550
+ const location = booking.location_id ? locationsById.get(booking.location_id) : null;
3551
+ const order = booking.order_id ? ordersById.get(booking.order_id) : null;
3552
+ const bookingItems = ((booking.order_id ? itemsByOrderId.get(booking.order_id) : null) ?? []).sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0)).map((item) => ({
3553
+ id: item.id,
3554
+ serviceId: item.service_id,
3555
+ name: item.name,
3556
+ durationMinutes: item.duration_minutes,
3557
+ price: item.unit_price,
3558
+ assigneeId: item.assignee_id
3559
+ }));
3560
+ const itemDuration = bookingItems.reduce((sum, item) => sum + (item.durationMinutes ?? 0), 0);
3561
+ return {
3562
+ id: booking.id,
3563
+ tenantId: booking.tenant_id,
3564
+ kind: booking.kind,
3565
+ startsAt: booking.starts_at,
3566
+ endsAt: booking.ends_at,
3567
+ status: booking.status,
3568
+ notes: booking.notes,
3569
+ orderId: booking.order_id,
3570
+ locationId: booking.location_id,
3571
+ metadata: booking.metadata ?? {},
3572
+ clientId: booking.party_id,
3573
+ // Simple events (no party) fall back to the title stored in metadata.
3574
+ clientName: client?.name ?? booking.metadata?.title ?? null,
3575
+ clientPhone: client?.phone ?? null,
3576
+ clientEmail: client?.email ?? null,
3577
+ clientAvatarUrl: client?.avatar_url ?? null,
3578
+ professionalId: booking.assignee_id,
3579
+ professionalName: professional?.name ?? null,
3580
+ professionalAvatarUrl: professional?.avatar_url ?? null,
3581
+ locationName: location?.name ?? null,
3582
+ orderTotal: order?.total ?? null,
3583
+ orderStatus: order?.status ?? null,
3584
+ services: bookingItems.length ? bookingItems : null,
3585
+ totalDurationMinutes: itemDuration || getDurationMinutes(booking.starts_at, booking.ends_at),
3586
+ createdAt: booking.created_at,
3587
+ updatedAt: booking.updated_at
3588
+ };
3589
+ });
3590
+ }
3591
+ async function getCanonicalBookings(core, query) {
3592
+ let q = core.from("bookings").select("id, tenant_id, kind, starts_at, ends_at, status, notes, order_id, location_id, metadata, party_id, assignee_id, created_at, updated_at").gte("starts_at", query.dateRange.start).lte("starts_at", query.dateRange.end);
3593
+ if (query.kind) q = q.eq("kind", query.kind);
3594
+ if (query.statuses?.length) q = q.in("status", query.statuses);
3595
+ if (query.professionalIds?.length) q = q.in("assignee_id", query.professionalIds);
3596
+ if (query.locationId) q = q.eq("location_id", query.locationId);
3597
+ const { data, error } = await q.order("starts_at", { ascending: true });
3598
+ if (error) throw error;
3599
+ return hydrateCanonicalBookings(core, data ?? []);
3600
+ }
3601
+ async function getCanonicalBookingById(core, id) {
3602
+ const columns = "id, tenant_id, kind, starts_at, ends_at, status, notes, order_id, location_id, metadata, party_id, assignee_id, created_at, updated_at";
3603
+ let { data, error } = await core.from("bookings").select(columns).eq("id", id).maybeSingle();
3604
+ if (error) throw error;
3605
+ if (!data) {
3606
+ const fallback = await core.from("bookings").select(columns).eq("order_id", id).maybeSingle();
3607
+ if (fallback.error) throw fallback.error;
3608
+ data = fallback.data;
3609
+ }
3610
+ if (!data) return null;
3611
+ const [booking] = await hydrateCanonicalBookings(core, [data]);
3612
+ return booking ?? null;
3613
+ }
3614
+ function createSupabaseAgendaProvider() {
3615
+ return {
3616
+ // v_bookings is in public schema (PostgREST default)
3617
+ async getBookings(query) {
3618
+ const { core, pub } = getClients();
3619
+ let q = pub.from("v_bookings").select("*").gte("starts_at", query.dateRange.start).lte("starts_at", query.dateRange.end);
3620
+ if (query.kind) q = q.eq("kind", query.kind);
3621
+ if (query.statuses?.length) q = q.in("status", query.statuses);
3622
+ if (query.professionalIds?.length) q = q.in("professional_id", query.professionalIds);
3623
+ if (query.locationId) q = q.eq("location_id", query.locationId);
3624
+ q = q.order("starts_at", { ascending: true });
3625
+ const { data, error } = await q;
3626
+ if (error) throw error;
3627
+ const viewBookings = (data ?? []).map(mapBooking);
3628
+ const canonicalBookings = await getCanonicalBookings(core, query);
3629
+ return mergeBookings(viewBookings, canonicalBookings);
3630
+ },
3631
+ async getBookingById(id) {
3632
+ const { core, pub } = getClients();
3633
+ const { data, error } = await pub.from("v_bookings").select("*").eq("id", id).maybeSingle();
3634
+ if (error) throw error;
3635
+ if (data) return mapBooking(data);
3636
+ return getCanonicalBookingById(core, id);
3637
+ },
3638
+ async createBooking(input) {
3639
+ const { core } = getClients();
3640
+ const tenantId = getTenantId();
3641
+ if (!tenantId) throw new Error("No active tenant");
3642
+ const hasServices = input.services.length > 0;
3643
+ const totalDuration = input.services.reduce((sum, s) => sum + s.durationMinutes, 0);
3644
+ const totalPrice = input.services.reduce((sum, s) => sum + s.price, 0);
3645
+ const endsAt = addMinutes(input.startsAt, totalDuration || 30);
3646
+ const serviceNames = input.services.map((s) => s.name).join(", ");
3647
+ let contactName;
3648
+ if (input.clientId) {
3649
+ const { data: person } = await core.from("persons").select("name").eq("id", input.clientId).single();
3650
+ contactName = person?.name;
3651
+ }
3652
+ const eventTitle = input.title?.trim() || void 0;
3653
+ const { data: order, error: orderErr } = await core.from("orders").insert({
3654
+ tenant_id: tenantId,
3655
+ kind: input.kind ?? "appointment",
3656
+ status: "scheduled",
3657
+ party_id: input.clientId || null,
3658
+ assignee_id: input.professionalId,
3659
+ location_id: input.locationId ?? null,
3660
+ subtotal: totalPrice,
3661
+ total: totalPrice,
3662
+ notes: input.notes ?? null,
3663
+ metadata: {
3664
+ source: "agenda",
3665
+ ...serviceNames ? { serviceNames, itemsSummary: serviceNames } : {},
3666
+ ...contactName ? { contactName } : {},
3667
+ ...eventTitle ? { title: eventTitle } : {}
3668
+ }
3669
+ }).select("id").single();
3670
+ if (orderErr) throw orderErr;
3671
+ const { data: booking, error: bookingErr } = await core.from("bookings").insert({
3672
+ tenant_id: tenantId,
3673
+ kind: input.kind ?? "appointment",
3674
+ party_id: input.clientId || null,
3675
+ assignee_id: input.professionalId,
3676
+ location_id: input.locationId ?? null,
3677
+ order_id: order.id,
3678
+ starts_at: input.startsAt,
3679
+ ends_at: endsAt,
3680
+ status: "scheduled",
3681
+ notes: input.notes ?? null,
3682
+ metadata: {
3683
+ source: "agenda",
3684
+ ...serviceNames ? { serviceNames, itemsSummary: serviceNames } : {},
3685
+ ...contactName ? { contactName } : {},
3686
+ ...eventTitle ? { title: eventTitle } : {}
3687
+ }
3688
+ }).select("id").single();
3689
+ if (bookingErr) throw bookingErr;
3690
+ if (hasServices) {
3691
+ const orderItems = input.services.map((s, i) => ({
3692
+ order_id: order.id,
3693
+ service_id: s.serviceId,
3694
+ name: s.name,
3695
+ quantity: 1,
3696
+ unit_price: s.price,
3697
+ total: s.price,
3698
+ sort_order: i,
3699
+ duration_minutes: s.durationMinutes,
3700
+ assignee_id: s.assigneeId ?? input.professionalId
3701
+ }));
3702
+ const { error: oiErr } = await core.from("order_items").insert(orderItems);
3703
+ if (oiErr) throw oiErr;
3704
+ }
3705
+ const createdBooking = await this.getBookingById(booking.id);
3706
+ if (!createdBooking) throw new Error("Created booking did not resolve from agenda read model");
3707
+ return createdBooking;
3708
+ },
3709
+ async updateBooking(id, data) {
3710
+ const { core } = getClients();
3711
+ const { data: existing, error: existingErr } = await core.from("bookings").select("id, order_id, starts_at, assignee_id, metadata").eq("id", id).single();
3712
+ if (existingErr) throw existingErr;
3713
+ const updates = {};
3714
+ if (data.startsAt) updates.starts_at = data.startsAt;
3715
+ if (data.endsAt) updates.ends_at = data.endsAt;
3716
+ if (data.title !== void 0) {
3717
+ updates.metadata = { ...existing?.metadata ?? {}, title: data.title };
3718
+ }
3719
+ if (data.status) {
3720
+ updates.status = data.status;
3721
+ }
3722
+ if (data.notes !== void 0) updates.notes = data.notes;
3723
+ if (data.professionalId) updates.assignee_id = data.professionalId;
3724
+ if (data.clientId) updates.party_id = data.clientId;
3725
+ if (data.locationId) updates.location_id = data.locationId;
3726
+ if (data.services) {
3727
+ const totalDuration = data.services.reduce((s, svc) => s + svc.durationMinutes, 0);
3728
+ data.services.reduce((s, svc) => s + svc.price, 0);
3729
+ const startsAt = data.startsAt ?? existing?.starts_at;
3730
+ if (startsAt) {
3731
+ const ends = new Date(new Date(startsAt).getTime() + totalDuration * 6e4);
3732
+ updates.ends_at = ends.toISOString();
3733
+ }
3734
+ }
3735
+ const effectiveAssigneeId = data.professionalId ?? existing?.assignee_id ?? null;
3736
+ const { error } = await core.from("bookings").update(updates).eq("id", id);
3737
+ if (error) throw error;
3738
+ const orderId = existing?.order_id;
3739
+ if (orderId) {
3740
+ const orderUpdates = {};
3741
+ if (data.notes !== void 0) orderUpdates.notes = data.notes;
3742
+ if (data.professionalId) orderUpdates.assignee_id = data.professionalId;
3743
+ if (data.clientId) orderUpdates.party_id = data.clientId;
3744
+ if (data.locationId) orderUpdates.location_id = data.locationId;
3745
+ if (data.services) {
3746
+ const totalPrice = data.services.reduce((s, svc) => s + svc.price, 0);
3747
+ orderUpdates.subtotal = totalPrice;
3748
+ orderUpdates.total = totalPrice;
3749
+ }
3750
+ if (Object.keys(orderUpdates).length > 0) {
3751
+ const { error: orderErr } = await core.from("orders").update(orderUpdates).eq("id", orderId);
3752
+ if (orderErr) throw orderErr;
3753
+ }
3754
+ if (data.services) {
3755
+ await core.from("order_items").delete().eq("order_id", orderId);
3756
+ if (data.services.length > 0) {
3757
+ const items = data.services.map((svc, idx) => ({
3758
+ order_id: orderId,
3759
+ service_id: svc.serviceId || null,
3760
+ name: svc.name,
3761
+ quantity: 1,
3762
+ unit_price: svc.price,
3763
+ total: svc.price,
3764
+ sort_order: idx,
3765
+ duration_minutes: svc.durationMinutes,
3766
+ assignee_id: svc.assigneeId ?? effectiveAssigneeId
3767
+ }));
3768
+ const { error: itemErr } = await core.from("order_items").insert(items);
3769
+ if (itemErr) throw itemErr;
3770
+ }
3771
+ }
3772
+ }
3773
+ return await this.getBookingById(id);
3774
+ },
3775
+ async deleteBooking(id) {
3776
+ const { core, pub } = getClients();
3777
+ const { data: booking, error: bookingErr } = await core.from("bookings").select("order_id").eq("id", id).single();
3778
+ if (bookingErr) throw bookingErr;
3779
+ const orderId = booking?.order_id;
3780
+ const { count, error: movementErr } = orderId ? await pub.from("financial_movements").select("id", { count: "exact", head: true }).eq("invoice_id", orderId) : { count: 0, error: null };
3781
+ if (movementErr) throw movementErr;
3782
+ if (orderId && (count ?? 0) > 0) {
3783
+ await pub.from("financial_movements").update({ status: "cancelled" }).eq("invoice_id", orderId);
3784
+ await core.from("orders").update({ status: "cancelled" }).eq("id", orderId);
3785
+ const { error } = await core.from("bookings").update({ status: "cancelled" }).eq("id", id);
3786
+ if (error) throw error;
3787
+ } else {
3788
+ if (orderId) {
3789
+ await pub.from("financial_movements").delete().eq("invoice_id", orderId);
3790
+ }
3791
+ const { error } = await core.from("bookings").delete().eq("id", id);
3792
+ if (error) throw error;
3793
+ if (orderId) {
3794
+ const { error: orderErr } = await core.from("orders").delete().eq("id", orderId);
3795
+ if (orderErr) throw orderErr;
3796
+ }
3797
+ }
3798
+ },
3799
+ async updateBookingStatus(id, status) {
3800
+ return this.updateBooking(id, { status });
3801
+ },
3802
+ async checkConflict(params) {
3803
+ const { core } = getClients();
3804
+ let q = core.from("bookings").select("id", { count: "exact", head: true }).eq("assignee_id", params.assigneeId).eq("kind", "appointment").not("status", "in", '("cancelled","no_show")').not("starts_at", "is", null).lt("starts_at", params.endsAt).gt("ends_at", params.startsAt);
3805
+ if (params.excludeBookingId) {
3806
+ q = q.neq("id", params.excludeBookingId);
3807
+ }
3808
+ const { count, error } = await q;
3809
+ if (error) throw error;
3810
+ return (count ?? 0) > 0;
3811
+ },
3812
+ async getAvailableSlots(params) {
3813
+ const { pub } = getClients();
3814
+ const { data, error } = await pub.rpc("get_available_slots", {
3815
+ p_tenant_id: getTenantId(),
3816
+ p_assignee_id: params.assigneeId,
3817
+ p_date: params.date,
3818
+ p_duration_minutes: params.durationMinutes,
3819
+ p_slot_interval: params.slotInterval ?? 30
3820
+ });
3821
+ if (error) throw error;
3822
+ return (data ?? []).map((row) => ({ start: row.slot_start, end: row.slot_end }));
3823
+ },
3824
+ async getSchedules(professionalId) {
3825
+ const { core } = getClients();
3826
+ let q = core.from("schedules").select("*").eq("kind", "working_hours");
3827
+ if (professionalId) q = q.eq("assignee_id", professionalId);
3828
+ q = q.order("day_of_week").order("starts_at");
3829
+ const { data, error } = await q;
3830
+ if (error) throw error;
3831
+ return (data ?? []).map(mapSchedule);
3832
+ },
3833
+ async saveSchedule(input) {
3834
+ const { core } = getClients();
3835
+ const tenantId = getTenantId();
3836
+ if (!tenantId) throw new Error("No active tenant");
3837
+ const { data, error } = await core.from("schedules").insert({
3838
+ tenant_id: tenantId,
3839
+ kind: "working_hours",
3840
+ assignee_id: input.assigneeId,
3841
+ location_id: input.locationId ?? null,
3842
+ day_of_week: input.dayOfWeek ?? null,
3843
+ specific_date: input.specificDate ?? null,
3844
+ starts_at: input.startsAt,
3845
+ ends_at: input.endsAt,
3846
+ is_active: input.isActive !== false,
3847
+ metadata: input.metadata ?? {}
3848
+ }).select("*").single();
3849
+ if (error) throw error;
3850
+ return mapSchedule(data);
3851
+ },
3852
+ async deleteSchedule(id) {
3853
+ const { core } = getClients();
3854
+ const { error } = await core.from("schedules").delete().eq("id", id);
3855
+ if (error) throw error;
3856
+ },
3857
+ async getProfessionals() {
3858
+ const { core } = getClients();
3859
+ const { data, error } = await core.from("persons").select("id, name, avatar_url, is_active").eq("kind", "staff").eq("is_active", true).order("name");
3860
+ if (error) throw error;
3861
+ return (data ?? []).map((p) => ({
3862
+ id: p.id,
3863
+ name: p.name,
3864
+ avatarUrl: p.avatar_url,
3865
+ locationId: null,
3866
+ locationName: null,
3867
+ isActive: p.is_active
3868
+ }));
3869
+ },
3870
+ async getLocations() {
3871
+ const { core } = getClients();
3872
+ const { data, error } = await core.from("locations").select("id, name").eq("is_active", true).order("name");
3873
+ if (error) throw error;
3874
+ return (data ?? []).map((l) => ({ id: l.id, name: l.name }));
3875
+ },
3876
+ async getConfirmationsPending(daysAhead = 2) {
3877
+ const { pub } = getClients();
3878
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3879
+ const cutoff = /* @__PURE__ */ new Date();
3880
+ cutoff.setDate(cutoff.getDate() + daysAhead);
3881
+ const { data, error } = await pub.from("v_bookings").select("*").eq("status", "scheduled").gte("starts_at", now).lte("starts_at", cutoff.toISOString()).order("starts_at");
3882
+ if (error) throw error;
3883
+ return (data ?? []).map(mapBooking);
3884
+ },
3885
+ async sendConfirmation(bookingId, channel) {
3886
+ const { core } = getClients();
3887
+ const { data: booking } = await core.from("bookings").select("metadata").eq("id", bookingId).single();
3888
+ const metadata = booking?.metadata ?? {};
3889
+ const confirmations = metadata.confirmations ?? [];
3890
+ confirmations.push({ channel, sentAt: (/* @__PURE__ */ new Date()).toISOString(), status: "sent" });
3891
+ await core.from("bookings").update({ metadata: { ...metadata, confirmations } }).eq("id", bookingId);
3892
+ },
3893
+ async completeBooking(bookingId) {
3894
+ const { core } = getClients();
3895
+ const { data: existing, error: existingErr } = await core.from("bookings").select("order_id").eq("id", bookingId).single();
3896
+ if (existingErr) throw existingErr;
3897
+ const { error } = await core.from("bookings").update({ status: "completed" }).eq("id", bookingId);
3898
+ if (error) throw error;
3899
+ const orderId = existing?.order_id;
3900
+ const booking = await this.getBookingById(bookingId);
3901
+ if (!booking) throw new Error("Booking not found");
3902
+ return { booking, orderId: orderId ?? bookingId };
3903
+ }
3904
+ };
3905
+ }
3464
3906
  function getCurrentBookingQuery(state, dateRange = state.dateRange) {
3465
3907
  return {
3466
3908
  dateRange,
@@ -4209,6 +4651,287 @@ var agendaLocales = {
4209
4651
  en,
4210
4652
  "pt-BR": ptBR
4211
4653
  };
4654
+
4655
+ // src/migrations/index.ts
4656
+ var MIGRATION_001_PUBLIC_BOOKING = `-- ============================================================================
4657
+ -- plugin-agenda 001: booking read model + public (anon) booking surface
4658
+ --
4659
+ -- Ships the objects the agenda providers reference but the spine (packages/db
4660
+ -- migrations 001\u2013008) does not define:
4661
+ -- \xA71 order_items columns the admin provider writes (duration/assignee)
4662
+ -- \xA72 public.v_bookings \u2014 admin read model (authenticated, RLS applies)
4663
+ -- \xA73 public.v_public_services \u2014 anon-readable service catalog
4664
+ -- \xA74 public.get_available_slots \u2014 anon RPC (mirrors the mock algorithm)
4665
+ -- \xA75 public.create_public_booking \u2014 anon RPC (validated, race-safe write)
4666
+ --
4667
+ -- Anon-access design: public booking pages run with the publishable key and no
4668
+ -- session, so the canonical tenant RLS yields nothing. Anon access is granted
4669
+ -- ONLY via the column-whitelisted view (\xA73) and SECURITY DEFINER RPCs (\xA74, \xA75)
4670
+ -- with tight input validation and hardcoded statuses.
4671
+ -- ============================================================================
4672
+
4673
+ -- \xA71 \u2014 columns the agenda provider writes but 004_archetypes lacks
4674
+ ALTER TABLE saas_core.order_items
4675
+ ADD COLUMN IF NOT EXISTS duration_minutes integer,
4676
+ ADD COLUMN IF NOT EXISTS assignee_id uuid REFERENCES saas_core.persons(id) ON DELETE SET NULL;
4677
+
4678
+ -- Upsert key for public customers (per tenant, by normalized phone)
4679
+ CREATE UNIQUE INDEX IF NOT EXISTS persons_tenant_customer_phone
4680
+ ON saas_core.persons(tenant_id, phone)
4681
+ WHERE kind = 'customer' AND phone IS NOT NULL;
4682
+
4683
+ -- Slot-conflict scan
4684
+ CREATE INDEX IF NOT EXISTS bookings_assignee_time
4685
+ ON saas_core.bookings(assignee_id, starts_at, ends_at)
4686
+ WHERE status NOT IN ('cancelled', 'no_show');
4687
+
4688
+ -- \xA72 \u2014 admin read model (security_invoker \u2192 underlying RLS applies; anon sees 0 rows)
4689
+ CREATE OR REPLACE VIEW public.v_bookings
4690
+ WITH (security_invoker = true) AS
4691
+ SELECT
4692
+ b.id, b.tenant_id, b.kind, b.starts_at, b.ends_at, b.status, b.notes,
4693
+ b.order_id, b.location_id, b.metadata, b.created_at, b.updated_at,
4694
+ b.party_id AS client_id,
4695
+ COALESCE(pc.name, b.metadata->>'title') AS client_name,
4696
+ pc.phone AS client_phone,
4697
+ pc.email AS client_email,
4698
+ pc.avatar_url AS client_avatar_url,
4699
+ b.assignee_id AS professional_id,
4700
+ ps.name AS professional_name,
4701
+ ps.avatar_url AS professional_avatar_url,
4702
+ l.name AS location_name,
4703
+ o.total AS order_total,
4704
+ o.status AS order_status,
4705
+ (EXTRACT(EPOCH FROM (COALESCE(b.ends_at, b.starts_at) - b.starts_at))::int / 60)
4706
+ AS total_duration_minutes
4707
+ FROM saas_core.bookings b
4708
+ LEFT JOIN saas_core.persons pc ON pc.id = b.party_id
4709
+ LEFT JOIN saas_core.persons ps ON ps.id = b.assignee_id
4710
+ LEFT JOIN saas_core.locations l ON l.id = b.location_id
4711
+ LEFT JOIN saas_core.orders o ON o.id = b.order_id;
4712
+
4713
+ GRANT SELECT ON public.v_bookings TO authenticated, service_role;
4714
+ REVOKE SELECT ON public.v_bookings FROM anon;
4715
+
4716
+ -- \xA73 \u2014 anon-readable public catalog (owner-rights view = deliberate, whitelisted)
4717
+ CREATE OR REPLACE VIEW public.v_public_services AS
4718
+ SELECT
4719
+ s.id, s.tenant_id, s.name, s.description, s.price, s.currency,
4720
+ COALESCE(s.duration_minutes, 30) AS duration_minutes,
4721
+ s.image_url,
4722
+ COALESCE((s.metadata->>'sort_order')::int, 0) AS sort_order
4723
+ FROM saas_core.services s
4724
+ WHERE s.is_active AND s.status = 'active';
4725
+
4726
+ GRANT SELECT ON public.v_public_services TO anon, authenticated, service_role;
4727
+
4728
+ -- \xA74 \u2014 availability RPC (mirrors plugin-agenda/src/data/mock.ts getAvailableSlots)
4729
+ CREATE OR REPLACE FUNCTION public.get_available_slots(
4730
+ p_tenant_id uuid,
4731
+ p_date date,
4732
+ p_duration_minutes integer,
4733
+ p_assignee_id uuid DEFAULT NULL,
4734
+ p_slot_interval integer DEFAULT 30
4735
+ ) RETURNS TABLE (slot_start timestamptz, slot_end timestamptz)
4736
+ LANGUAGE plpgsql STABLE SECURITY DEFINER
4737
+ SET search_path = saas_core, public
4738
+ AS $$
4739
+ DECLARE
4740
+ v_tz text;
4741
+ BEGIN
4742
+ -- tight validation: this function is anon-callable
4743
+ IF p_duration_minutes IS NULL OR p_duration_minutes NOT BETWEEN 5 AND 480 THEN
4744
+ RAISE EXCEPTION 'invalid duration';
4745
+ END IF;
4746
+ IF p_slot_interval IS NULL OR p_slot_interval NOT BETWEEN 5 AND 240 THEN
4747
+ RAISE EXCEPTION 'invalid interval';
4748
+ END IF;
4749
+ IF p_date IS NULL OR p_date < current_date OR p_date > current_date + 90 THEN
4750
+ RETURN;
4751
+ END IF;
4752
+
4753
+ SELECT COALESCE(t.settings->>'timezone', 'America/Sao_Paulo') INTO v_tz
4754
+ FROM tenants t WHERE t.id = p_tenant_id;
4755
+ IF v_tz IS NULL THEN RETURN; END IF; -- unknown tenant \u2192 empty, not an error
4756
+
4757
+ RETURN QUERY
4758
+ WITH day_schedules AS (
4759
+ SELECT sc.assignee_id, sc.starts_at AS win_start, sc.ends_at AS win_end
4760
+ FROM schedules sc
4761
+ WHERE sc.tenant_id = p_tenant_id
4762
+ AND sc.kind = 'working_hours'
4763
+ AND sc.is_active
4764
+ AND (p_assignee_id IS NULL OR sc.assignee_id = p_assignee_id)
4765
+ AND (
4766
+ sc.specific_date = p_date
4767
+ OR (sc.specific_date IS NULL AND sc.day_of_week = EXTRACT(dow FROM p_date)::smallint)
4768
+ )
4769
+ ),
4770
+ candidate AS (
4771
+ SELECT
4772
+ ds.assignee_id,
4773
+ gs AS s_start,
4774
+ gs + make_interval(mins => p_duration_minutes) AS s_end
4775
+ FROM day_schedules ds
4776
+ CROSS JOIN LATERAL generate_series(
4777
+ (p_date + ds.win_start) AT TIME ZONE v_tz,
4778
+ ((p_date + ds.win_end) AT TIME ZONE v_tz) - make_interval(mins => p_duration_minutes),
4779
+ make_interval(mins => p_slot_interval)
4780
+ ) AS gs
4781
+ )
4782
+ SELECT DISTINCT c.s_start, c.s_end
4783
+ FROM candidate c
4784
+ WHERE NOT EXISTS (
4785
+ SELECT 1 FROM bookings b
4786
+ WHERE b.tenant_id = p_tenant_id
4787
+ AND b.assignee_id = c.assignee_id
4788
+ AND b.status NOT IN ('cancelled', 'no_show')
4789
+ AND b.starts_at < c.s_end
4790
+ AND COALESCE(b.ends_at, b.starts_at) > c.s_start
4791
+ )
4792
+ ORDER BY 1;
4793
+ END;
4794
+ $$;
4795
+
4796
+ REVOKE ALL ON FUNCTION public.get_available_slots(uuid, date, integer, uuid, integer) FROM public;
4797
+ GRANT EXECUTE ON FUNCTION public.get_available_slots(uuid, date, integer, uuid, integer)
4798
+ TO anon, authenticated, service_role;
4799
+
4800
+ -- \xA75 \u2014 public booking write RPC (validated, race-safe, hardcoded statuses)
4801
+ CREATE OR REPLACE FUNCTION public.create_public_booking(
4802
+ p_tenant_id uuid,
4803
+ p_service_id uuid,
4804
+ p_starts_at timestamptz,
4805
+ p_name text,
4806
+ p_phone text,
4807
+ p_email text DEFAULT NULL,
4808
+ p_notes text DEFAULT NULL
4809
+ ) RETURNS TABLE (booking_id uuid, starts_at timestamptz, ends_at timestamptz)
4810
+ LANGUAGE plpgsql SECURITY DEFINER
4811
+ SET search_path = saas_core, public
4812
+ AS $$
4813
+ DECLARE
4814
+ v_service record;
4815
+ v_person_id uuid;
4816
+ v_assignee uuid;
4817
+ v_ends timestamptz;
4818
+ v_order uuid;
4819
+ v_booking uuid;
4820
+ v_phone text;
4821
+ v_tz text;
4822
+ v_notes text;
4823
+ BEGIN
4824
+ -- validation: anon-callable, everything tight
4825
+ IF p_name IS NULL OR length(trim(p_name)) NOT BETWEEN 2 AND 120 THEN
4826
+ RAISE EXCEPTION 'invalid name';
4827
+ END IF;
4828
+ v_phone := regexp_replace(COALESCE(p_phone, ''), '\\D', '', 'g');
4829
+ IF length(v_phone) NOT BETWEEN 8 AND 15 THEN
4830
+ RAISE EXCEPTION 'invalid phone';
4831
+ END IF;
4832
+ IF p_email IS NOT NULL AND (length(p_email) > 254 OR p_email !~ '^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$') THEN
4833
+ RAISE EXCEPTION 'invalid email';
4834
+ END IF;
4835
+ v_notes := left(p_notes, 500);
4836
+ IF p_starts_at IS NULL OR p_starts_at <= now() OR p_starts_at > now() + interval '90 days' THEN
4837
+ RAISE EXCEPTION 'invalid start';
4838
+ END IF;
4839
+
4840
+ SELECT s.id, s.name, s.price, COALESCE(s.duration_minutes, 30) AS duration_minutes
4841
+ INTO v_service
4842
+ FROM services s
4843
+ WHERE s.id = p_service_id AND s.tenant_id = p_tenant_id
4844
+ AND s.is_active AND s.status = 'active';
4845
+ IF NOT FOUND THEN RAISE EXCEPTION 'unknown service'; END IF;
4846
+
4847
+ v_ends := p_starts_at + make_interval(mins => v_service.duration_minutes);
4848
+ SELECT COALESCE(t.settings->>'timezone', 'America/Sao_Paulo') INTO v_tz
4849
+ FROM tenants t WHERE t.id = p_tenant_id;
4850
+ IF v_tz IS NULL THEN RAISE EXCEPTION 'unknown tenant'; END IF;
4851
+
4852
+ -- pick the assignee whose working hours cover the slot
4853
+ SELECT sc.assignee_id INTO v_assignee
4854
+ FROM schedules sc
4855
+ WHERE sc.tenant_id = p_tenant_id
4856
+ AND sc.kind = 'working_hours'
4857
+ AND sc.is_active
4858
+ AND (
4859
+ sc.specific_date = (p_starts_at AT TIME ZONE v_tz)::date
4860
+ OR (sc.specific_date IS NULL
4861
+ AND sc.day_of_week = EXTRACT(dow FROM p_starts_at AT TIME ZONE v_tz)::smallint)
4862
+ )
4863
+ AND (p_starts_at AT TIME ZONE v_tz)::time >= sc.starts_at
4864
+ AND (v_ends AT TIME ZONE v_tz)::time <= sc.ends_at
4865
+ ORDER BY sc.assignee_id
4866
+ LIMIT 1;
4867
+ IF v_assignee IS NULL THEN RAISE EXCEPTION 'slot outside working hours'; END IF;
4868
+
4869
+ -- serialize per (tenant, assignee) to kill the double-book race
4870
+ PERFORM pg_advisory_xact_lock(hashtextextended(p_tenant_id::text || v_assignee::text, 0));
4871
+
4872
+ IF EXISTS (
4873
+ SELECT 1 FROM bookings b
4874
+ WHERE b.tenant_id = p_tenant_id
4875
+ AND b.assignee_id = v_assignee
4876
+ AND b.status NOT IN ('cancelled', 'no_show')
4877
+ AND b.starts_at < v_ends
4878
+ AND COALESCE(b.ends_at, b.starts_at) > p_starts_at
4879
+ ) THEN
4880
+ RAISE EXCEPTION 'slot no longer available';
4881
+ END IF;
4882
+
4883
+ -- anti-spam: cap open future public bookings per phone per tenant
4884
+ IF (
4885
+ SELECT count(*) FROM bookings b
4886
+ JOIN persons p ON p.id = b.party_id
4887
+ WHERE b.tenant_id = p_tenant_id
4888
+ AND p.phone = v_phone
4889
+ AND b.starts_at > now()
4890
+ AND b.status = 'scheduled'
4891
+ ) >= 3 THEN
4892
+ RAISE EXCEPTION 'too many open bookings for this phone';
4893
+ END IF;
4894
+
4895
+ -- upsert the customer by (tenant, phone) \u2014 matches persons_tenant_customer_phone
4896
+ INSERT INTO persons (tenant_id, kind, name, phone, email, metadata)
4897
+ VALUES (p_tenant_id, 'customer', trim(p_name), v_phone, p_email,
4898
+ jsonb_build_object('source', 'public_booking'))
4899
+ ON CONFLICT (tenant_id, phone) WHERE kind = 'customer' AND phone IS NOT NULL
4900
+ DO UPDATE SET
4901
+ name = EXCLUDED.name,
4902
+ email = COALESCE(EXCLUDED.email, persons.email),
4903
+ updated_at = now()
4904
+ RETURNING id INTO v_person_id;
4905
+
4906
+ -- order + booking + order_item (statuses hardcoded \u2014 caller cannot set)
4907
+ INSERT INTO orders (tenant_id, kind, status, party_id, assignee_id, subtotal, total, notes, metadata)
4908
+ VALUES (p_tenant_id, 'appointment', 'scheduled', v_person_id, v_assignee,
4909
+ v_service.price, v_service.price, v_notes,
4910
+ jsonb_build_object('source', 'public_booking',
4911
+ 'serviceNames', v_service.name,
4912
+ 'contactName', trim(p_name)))
4913
+ RETURNING id INTO v_order;
4914
+
4915
+ INSERT INTO bookings (tenant_id, kind, party_id, assignee_id, order_id,
4916
+ starts_at, ends_at, status, notes, metadata)
4917
+ VALUES (p_tenant_id, 'appointment', v_person_id, v_assignee, v_order,
4918
+ p_starts_at, v_ends, 'scheduled', v_notes,
4919
+ jsonb_build_object('source', 'public_booking', 'serviceNames', v_service.name))
4920
+ RETURNING id INTO v_booking;
4921
+
4922
+ INSERT INTO order_items (order_id, service_id, name, quantity, unit_price, total,
4923
+ sort_order, duration_minutes, assignee_id)
4924
+ VALUES (v_order, v_service.id, v_service.name, 1, v_service.price, v_service.price,
4925
+ 0, v_service.duration_minutes, v_assignee);
4926
+
4927
+ RETURN QUERY SELECT v_booking, p_starts_at, v_ends;
4928
+ END;
4929
+ $$;
4930
+
4931
+ REVOKE ALL ON FUNCTION public.create_public_booking(uuid, uuid, timestamptz, text, text, text, text) FROM public;
4932
+ GRANT EXECUTE ON FUNCTION public.create_public_booking(uuid, uuid, timestamptz, text, text, text, text)
4933
+ TO anon, authenticated, service_role;
4934
+ `;
4212
4935
  function computeCommissionAmount(total, ratePercent) {
4213
4936
  const base = Number(total) || 0;
4214
4937
  const rate = Number(ratePercent) || 0;
@@ -4768,6 +5491,14 @@ function createAgendaPlugin(options) {
4768
5491
  permission: { feature: "appointments", action: "read" }
4769
5492
  }
4770
5493
  ],
5494
+ migrations: [
5495
+ {
5496
+ id: "agenda-001-public-booking",
5497
+ version: "0.3.0",
5498
+ sql: MIGRATION_001_PUBLIC_BOOKING,
5499
+ description: "Booking read model (v_bookings) + anon public booking surface (v_public_services, get_available_slots, create_public_booking) + order_items duration/assignee columns"
5500
+ }
5501
+ ],
4771
5502
  locales: agendaLocales
4772
5503
  };
4773
5504
  }