@fayz-ai/plugin-agenda 0.2.0 → 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 (82) 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/data/mock.d.ts.map +1 -1
  6. package/dist/index.cjs +300 -421
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +297 -420
  10. package/dist/index.js.map +1 -1
  11. package/dist/migrations/index.d.ts +2 -0
  12. package/dist/migrations/index.d.ts.map +1 -0
  13. package/dist/public/BookingWidget.d.ts +11 -0
  14. package/dist/public/BookingWidget.d.ts.map +1 -0
  15. package/dist/public/components/BrandHeader.d.ts +6 -0
  16. package/dist/public/components/BrandHeader.d.ts.map +1 -0
  17. package/dist/public/components/ServiceCard.d.ts +5 -0
  18. package/dist/public/components/ServiceCard.d.ts.map +1 -0
  19. package/dist/public/components/SidebarExtras.d.ts +4 -0
  20. package/dist/public/components/SidebarExtras.d.ts.map +1 -0
  21. package/dist/public/components/StepRailItem.d.ts +4 -0
  22. package/dist/public/components/StepRailItem.d.ts.map +1 -0
  23. package/dist/public/components/SuccessPanel.d.ts +4 -0
  24. package/dist/public/components/SuccessPanel.d.ts.map +1 -0
  25. package/dist/public/components/SummaryRail.d.ts +27 -0
  26. package/dist/public/components/SummaryRail.d.ts.map +1 -0
  27. package/dist/public/components/defaults.d.ts +3 -0
  28. package/dist/public/components/defaults.d.ts.map +1 -0
  29. package/dist/public/context.d.ts +51 -0
  30. package/dist/public/context.d.ts.map +1 -0
  31. package/dist/public/createPublicBookingPlugin.d.ts +62 -0
  32. package/dist/public/createPublicBookingPlugin.d.ts.map +1 -0
  33. package/dist/public/data.d.ts +37 -0
  34. package/dist/public/data.d.ts.map +1 -0
  35. package/dist/public/data.supabase.d.ts +7 -0
  36. package/dist/public/data.supabase.d.ts.map +1 -0
  37. package/dist/public/format.d.ts +18 -0
  38. package/dist/public/format.d.ts.map +1 -0
  39. package/dist/public/hooks.d.ts +34 -0
  40. package/dist/public/hooks.d.ts.map +1 -0
  41. package/dist/public/index.cjs +1423 -0
  42. package/dist/public/index.cjs.map +1 -0
  43. package/dist/public/index.d.ts +20 -0
  44. package/dist/public/index.d.ts.map +1 -0
  45. package/dist/public/index.js +1402 -0
  46. package/dist/public/index.js.map +1 -0
  47. package/dist/public/steps/ContactStep.d.ts +30 -0
  48. package/dist/public/steps/ContactStep.d.ts.map +1 -0
  49. package/dist/public/steps/DateTimeStep.d.ts +23 -0
  50. package/dist/public/steps/DateTimeStep.d.ts.map +1 -0
  51. package/dist/public/steps/OverviewStep.d.ts +16 -0
  52. package/dist/public/steps/OverviewStep.d.ts.map +1 -0
  53. package/dist/public/steps/PaymentStep.d.ts +20 -0
  54. package/dist/public/steps/PaymentStep.d.ts.map +1 -0
  55. package/dist/public/types.d.ts +185 -0
  56. package/dist/public/types.d.ts.map +1 -0
  57. package/package.json +20 -14
  58. package/src/data/mock.ts +4 -1
  59. package/src/index.ts +14 -0
  60. package/src/integrations/google-calendar/integration.test.ts +1 -1
  61. package/src/migrations/001_public_booking.sql +278 -0
  62. package/src/migrations/index.ts +282 -0
  63. package/src/public/BookingWidget.tsx +315 -0
  64. package/src/public/components/BrandHeader.tsx +27 -0
  65. package/src/public/components/ServiceCard.tsx +39 -0
  66. package/src/public/components/SidebarExtras.tsx +30 -0
  67. package/src/public/components/StepRailItem.tsx +27 -0
  68. package/src/public/components/SuccessPanel.tsx +27 -0
  69. package/src/public/components/SummaryRail.tsx +90 -0
  70. package/src/public/components/defaults.ts +14 -0
  71. package/src/public/context.tsx +100 -0
  72. package/src/public/createPublicBookingPlugin.ts +265 -0
  73. package/src/public/data.supabase.ts +94 -0
  74. package/src/public/data.ts +99 -0
  75. package/src/public/format.ts +61 -0
  76. package/src/public/hooks.ts +105 -0
  77. package/src/public/index.ts +68 -0
  78. package/src/public/steps/ContactStep.tsx +179 -0
  79. package/src/public/steps/DateTimeStep.tsx +138 -0
  80. package/src/public/steps/OverviewStep.tsx +81 -0
  81. package/src/public/steps/PaymentStep.tsx +180 -0
  82. package/src/public/types.ts +229 -0
package/dist/index.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { createMockAgendaProvider } from './chunk-DRZF6CV2.js';
2
+ export { createMockAgendaProvider } from './chunk-DRZF6CV2.js';
1
3
  import { setAgendaTenantId, getAgendaTenantId } from './chunk-3LJKZQK4.js';
2
4
  import React12, { useState, useEffect, useRef, useMemo, useCallback } from 'react';
3
5
  import { getSupabaseClientOptional, registerTranslations, createSafeDataProvider, usePluginRuntimeOptional, useTranslation, getActiveTenantId, getCurrentLocale, formatCurrency } from '@fayz-ai/core';
@@ -3873,10 +3875,10 @@ function createSupabaseAgendaProvider() {
3873
3875
  },
3874
3876
  async getConfirmationsPending(daysAhead = 2) {
3875
3877
  const { pub } = getClients();
3876
- const now2 = (/* @__PURE__ */ new Date()).toISOString();
3878
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3877
3879
  const cutoff = /* @__PURE__ */ new Date();
3878
3880
  cutoff.setDate(cutoff.getDate() + daysAhead);
3879
- const { data, error } = await pub.from("v_bookings").select("*").eq("status", "scheduled").gte("starts_at", now2).lte("starts_at", cutoff.toISOString()).order("starts_at");
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");
3880
3882
  if (error) throw error;
3881
3883
  return (data ?? []).map(mapBooking);
3882
3884
  },
@@ -3901,423 +3903,6 @@ function createSupabaseAgendaProvider() {
3901
3903
  }
3902
3904
  };
3903
3905
  }
3904
-
3905
- // src/data/mock.ts
3906
- var nextId = 1;
3907
- function uid() {
3908
- return `mock-${nextId++}`;
3909
- }
3910
- function now() {
3911
- return (/* @__PURE__ */ new Date()).toISOString();
3912
- }
3913
- function addMinutes2(date, minutes) {
3914
- const d = new Date(date);
3915
- d.setMinutes(d.getMinutes() + minutes);
3916
- return d.toISOString();
3917
- }
3918
- function timeOverlaps(aStart, aEnd, bStart, bEnd) {
3919
- return aStart < bEnd && aEnd > bStart;
3920
- }
3921
- var SAMPLE_PROFESSIONALS = [
3922
- { id: "prof-1", name: "Ana Silva", avatarUrl: null, locationId: "loc-1", locationName: "Main Branch", isActive: true },
3923
- { id: "prof-2", name: "Carlos Santos", avatarUrl: null, locationId: "loc-1", locationName: "Main Branch", isActive: true },
3924
- { id: "prof-3", name: "Maria Oliveira", avatarUrl: null, locationId: "loc-1", locationName: "Main Branch", isActive: true }
3925
- ];
3926
- function createSampleBookings() {
3927
- const today = /* @__PURE__ */ new Date();
3928
- const year = today.getFullYear();
3929
- const month = today.getMonth();
3930
- const day = today.getDate();
3931
- function dt(hour, minute = 0) {
3932
- return new Date(year, month, day, hour, minute).toISOString();
3933
- }
3934
- return [
3935
- {
3936
- id: "bk-1",
3937
- tenantId: "mock",
3938
- kind: "appointment",
3939
- startsAt: dt(9, 0),
3940
- endsAt: dt(10, 30),
3941
- status: "confirmed",
3942
- notes: null,
3943
- orderId: "ord-1",
3944
- locationId: "loc-1",
3945
- metadata: {},
3946
- clientId: "cl-1",
3947
- clientName: "Sarah Johnson",
3948
- clientPhone: "(11) 99999-1111",
3949
- clientEmail: "sarah@email.com",
3950
- clientAvatarUrl: null,
3951
- professionalId: "prof-1",
3952
- professionalName: "Ana Silva",
3953
- professionalAvatarUrl: null,
3954
- locationName: "Main Branch",
3955
- orderTotal: 250,
3956
- orderStatus: "draft",
3957
- services: [{ id: "bi-1", serviceId: "svc-1", name: "Balayage", durationMinutes: 90, price: 250, assigneeId: "prof-1" }],
3958
- totalDurationMinutes: 90,
3959
- createdAt: now(),
3960
- updatedAt: now()
3961
- },
3962
- {
3963
- id: "bk-2",
3964
- tenantId: "mock",
3965
- kind: "appointment",
3966
- startsAt: dt(10, 0),
3967
- endsAt: dt(11, 0),
3968
- status: "scheduled",
3969
- notes: null,
3970
- orderId: "ord-2",
3971
- locationId: "loc-1",
3972
- metadata: {},
3973
- clientId: "cl-2",
3974
- clientName: "Emily Carter",
3975
- clientPhone: "(11) 99999-2222",
3976
- clientEmail: "emily@email.com",
3977
- clientAvatarUrl: null,
3978
- professionalId: "prof-2",
3979
- professionalName: "Carlos Santos",
3980
- professionalAvatarUrl: null,
3981
- locationName: "Main Branch",
3982
- orderTotal: 80,
3983
- orderStatus: "draft",
3984
- services: [{ id: "bi-2", serviceId: "svc-2", name: "Haircut", durationMinutes: 60, price: 80, assigneeId: "prof-2" }],
3985
- totalDurationMinutes: 60,
3986
- createdAt: now(),
3987
- updatedAt: now()
3988
- },
3989
- {
3990
- id: "bk-3",
3991
- tenantId: "mock",
3992
- kind: "appointment",
3993
- startsAt: dt(14, 0),
3994
- endsAt: dt(15, 0),
3995
- status: "confirmed",
3996
- notes: "First visit",
3997
- orderId: "ord-3",
3998
- locationId: "loc-1",
3999
- metadata: {},
4000
- clientId: "cl-3",
4001
- clientName: "Rachel Kim",
4002
- clientPhone: "(11) 99999-3333",
4003
- clientEmail: null,
4004
- clientAvatarUrl: null,
4005
- professionalId: "prof-3",
4006
- professionalName: "Maria Oliveira",
4007
- professionalAvatarUrl: null,
4008
- locationName: "Main Branch",
4009
- orderTotal: 120,
4010
- orderStatus: "draft",
4011
- services: [{ id: "bi-3", serviceId: "svc-3", name: "Facial Treatment", durationMinutes: 60, price: 120, assigneeId: "prof-3" }],
4012
- totalDurationMinutes: 60,
4013
- createdAt: now(),
4014
- updatedAt: now()
4015
- },
4016
- {
4017
- id: "bk-4",
4018
- tenantId: "mock",
4019
- kind: "appointment",
4020
- startsAt: dt(11, 0),
4021
- endsAt: dt(12, 0),
4022
- status: "scheduled",
4023
- notes: null,
4024
- orderId: "ord-4",
4025
- locationId: "loc-1",
4026
- metadata: {},
4027
- clientId: "cl-4",
4028
- clientName: "Jessica Lima",
4029
- clientPhone: "(11) 99999-4444",
4030
- clientEmail: null,
4031
- clientAvatarUrl: null,
4032
- professionalId: "prof-1",
4033
- professionalName: "Ana Silva",
4034
- professionalAvatarUrl: null,
4035
- locationName: "Main Branch",
4036
- orderTotal: 60,
4037
- orderStatus: "draft",
4038
- services: [{ id: "bi-4", serviceId: "svc-4", name: "Manicure", durationMinutes: 60, price: 60, assigneeId: "prof-1" }],
4039
- totalDurationMinutes: 60,
4040
- createdAt: now(),
4041
- updatedAt: now()
4042
- },
4043
- {
4044
- id: "bk-5",
4045
- tenantId: "mock",
4046
- kind: "appointment",
4047
- startsAt: dt(15, 30),
4048
- endsAt: dt(17, 0),
4049
- status: "confirmed",
4050
- notes: null,
4051
- orderId: "ord-5",
4052
- locationId: "loc-1",
4053
- metadata: {},
4054
- clientId: "cl-5",
4055
- clientName: "Amanda Wright",
4056
- clientPhone: "(11) 99999-5555",
4057
- clientEmail: "amanda@email.com",
4058
- clientAvatarUrl: null,
4059
- professionalId: "prof-2",
4060
- professionalName: "Carlos Santos",
4061
- professionalAvatarUrl: null,
4062
- locationName: "Main Branch",
4063
- orderTotal: 350,
4064
- orderStatus: "draft",
4065
- services: [
4066
- { id: "bi-5", serviceId: "svc-1", name: "Highlights", durationMinutes: 60, price: 200, assigneeId: "prof-2" },
4067
- { id: "bi-6", serviceId: "svc-2", name: "Haircut", durationMinutes: 30, price: 150, assigneeId: "prof-2" }
4068
- ],
4069
- totalDurationMinutes: 90,
4070
- createdAt: now(),
4071
- updatedAt: now()
4072
- }
4073
- ];
4074
- }
4075
- function createSampleSchedules() {
4076
- const schedules = [];
4077
- for (const prof of SAMPLE_PROFESSIONALS) {
4078
- for (let day = 1; day <= 5; day++) {
4079
- schedules.push({
4080
- id: uid(),
4081
- tenantId: "mock",
4082
- kind: "working_hours",
4083
- assigneeId: prof.id,
4084
- locationId: prof.locationId,
4085
- dayOfWeek: day,
4086
- specificDate: null,
4087
- startsAt: "08:00",
4088
- endsAt: "12:00",
4089
- isActive: true,
4090
- metadata: {}
4091
- });
4092
- schedules.push({
4093
- id: uid(),
4094
- tenantId: "mock",
4095
- kind: "working_hours",
4096
- assigneeId: prof.id,
4097
- locationId: prof.locationId,
4098
- dayOfWeek: day,
4099
- specificDate: null,
4100
- startsAt: "13:00",
4101
- endsAt: "18:00",
4102
- isActive: true,
4103
- metadata: {}
4104
- });
4105
- }
4106
- schedules.push({
4107
- id: uid(),
4108
- tenantId: "mock",
4109
- kind: "working_hours",
4110
- assigneeId: prof.id,
4111
- locationId: prof.locationId,
4112
- dayOfWeek: 6,
4113
- specificDate: null,
4114
- startsAt: "08:00",
4115
- endsAt: "14:00",
4116
- isActive: true,
4117
- metadata: {}
4118
- });
4119
- }
4120
- return schedules;
4121
- }
4122
- function createMockAgendaProvider(options) {
4123
- const seed = options?.seed;
4124
- const bookings = seed?.bookings ? [...seed.bookings] : createSampleBookings();
4125
- const schedules = seed?.schedules ? [...seed.schedules] : createSampleSchedules();
4126
- const professionals = seed?.professionals ? [...seed.professionals] : [...SAMPLE_PROFESSIONALS];
4127
- return {
4128
- async getLocations() {
4129
- return [];
4130
- },
4131
- async getBookings(query) {
4132
- return bookings.filter((b) => {
4133
- if (query.kind && b.kind !== query.kind) return false;
4134
- if (query.statuses?.length && !query.statuses.includes(b.status)) return false;
4135
- if (query.professionalIds?.length && !query.professionalIds.includes(b.professionalId ?? "")) return false;
4136
- if (query.locationId && b.locationId !== query.locationId) return false;
4137
- if (query.dateRange) {
4138
- if (b.startsAt > query.dateRange.end || (b.endsAt ?? b.startsAt) < query.dateRange.start) return false;
4139
- }
4140
- return true;
4141
- });
4142
- },
4143
- async getBookingById(id) {
4144
- return bookings.find((b) => b.id === id) ?? null;
4145
- },
4146
- async createBooking(input) {
4147
- const totalDuration = input.services.reduce((sum, s) => sum + s.durationMinutes, 0);
4148
- const totalPrice = input.services.reduce((sum, s) => sum + s.price, 0);
4149
- const booking = {
4150
- id: uid(),
4151
- tenantId: "mock",
4152
- kind: input.kind ?? "appointment",
4153
- startsAt: input.startsAt,
4154
- endsAt: addMinutes2(input.startsAt, totalDuration || 30),
4155
- status: "scheduled",
4156
- notes: input.notes ?? null,
4157
- orderId: input.services.length > 0 ? uid() : null,
4158
- locationId: input.locationId ?? null,
4159
- metadata: {},
4160
- clientId: input.clientId,
4161
- clientName: input.title?.trim() || "New Client",
4162
- clientPhone: null,
4163
- clientEmail: null,
4164
- clientAvatarUrl: null,
4165
- professionalId: input.professionalId,
4166
- professionalName: professionals.find((p) => p.id === input.professionalId)?.name ?? "Unknown",
4167
- professionalAvatarUrl: null,
4168
- locationName: null,
4169
- orderTotal: totalPrice,
4170
- orderStatus: "draft",
4171
- services: input.services.map((s) => ({
4172
- id: uid(),
4173
- serviceId: s.serviceId,
4174
- name: s.name,
4175
- durationMinutes: s.durationMinutes,
4176
- price: s.price,
4177
- assigneeId: s.assigneeId ?? input.professionalId
4178
- })),
4179
- totalDurationMinutes: totalDuration,
4180
- createdAt: now(),
4181
- updatedAt: now()
4182
- };
4183
- bookings.push(booking);
4184
- return booking;
4185
- },
4186
- async updateBooking(id, data) {
4187
- const idx = bookings.findIndex((b) => b.id === id);
4188
- if (idx === -1) throw new Error("Booking not found");
4189
- const existing = bookings[idx];
4190
- const serviceUpdates = {};
4191
- if (data.services) {
4192
- serviceUpdates.services = data.services.map((s) => ({
4193
- id: uid(),
4194
- serviceId: s.serviceId,
4195
- name: s.name,
4196
- durationMinutes: s.durationMinutes,
4197
- price: s.price,
4198
- assigneeId: s.assigneeId ?? existing.professionalId ?? ""
4199
- }));
4200
- serviceUpdates.totalDurationMinutes = data.services.reduce((sum, s) => sum + s.durationMinutes, 0);
4201
- serviceUpdates.orderTotal = data.services.reduce((sum, s) => sum + s.price, 0);
4202
- }
4203
- const updated = {
4204
- ...existing,
4205
- ...data.startsAt && { startsAt: data.startsAt },
4206
- ...data.endsAt && { endsAt: data.endsAt },
4207
- ...data.title !== void 0 && { clientName: data.title },
4208
- ...data.status && { status: data.status },
4209
- ...data.notes !== void 0 && { notes: data.notes ?? null },
4210
- ...data.professionalId && { professionalId: data.professionalId },
4211
- ...data.clientId && { clientId: data.clientId },
4212
- ...data.locationId && { locationId: data.locationId },
4213
- ...serviceUpdates,
4214
- updatedAt: now()
4215
- };
4216
- bookings[idx] = updated;
4217
- return updated;
4218
- },
4219
- async deleteBooking(id) {
4220
- const idx = bookings.findIndex((b) => b.id === id);
4221
- if (idx !== -1) bookings.splice(idx, 1);
4222
- },
4223
- async updateBookingStatus(id, status) {
4224
- const idx = bookings.findIndex((b) => b.id === id);
4225
- if (idx === -1) throw new Error("Booking not found");
4226
- bookings[idx] = { ...bookings[idx], status, updatedAt: now() };
4227
- return bookings[idx];
4228
- },
4229
- async checkConflict(params) {
4230
- return bookings.some((b) => {
4231
- if (params.excludeBookingId && b.id === params.excludeBookingId) return false;
4232
- if (b.professionalId !== params.assigneeId) return false;
4233
- if (b.status === "cancelled" || b.status === "no_show") return false;
4234
- return timeOverlaps(b.startsAt, b.endsAt ?? b.startsAt, params.startsAt, params.endsAt);
4235
- });
4236
- },
4237
- async getAvailableSlots(params) {
4238
- const date = new Date(params.date);
4239
- const dayOfWeek = date.getDay();
4240
- const interval = params.slotInterval ?? 30;
4241
- const daySchedules = schedules.filter(
4242
- (s) => s.assigneeId === params.assigneeId && s.isActive && (s.dayOfWeek === dayOfWeek || s.specificDate === params.date)
4243
- );
4244
- const slots = [];
4245
- for (const sched of daySchedules) {
4246
- const [startH, startM] = sched.startsAt.split(":").map(Number);
4247
- const [endH, endM] = sched.endsAt.split(":").map(Number);
4248
- const schedStart = new Date(date);
4249
- schedStart.setHours(startH, startM, 0, 0);
4250
- const schedEnd = new Date(date);
4251
- schedEnd.setHours(endH, endM, 0, 0);
4252
- let slotStart = new Date(schedStart);
4253
- while (true) {
4254
- const slotEnd = new Date(slotStart.getTime() + params.durationMinutes * 6e4);
4255
- if (slotEnd > schedEnd) break;
4256
- const startIso = slotStart.toISOString();
4257
- const endIso = slotEnd.toISOString();
4258
- const hasConflict = bookings.some((b) => {
4259
- if (b.professionalId !== params.assigneeId) return false;
4260
- if (b.status === "cancelled" || b.status === "no_show") return false;
4261
- return timeOverlaps(b.startsAt, b.endsAt ?? b.startsAt, startIso, endIso);
4262
- });
4263
- if (!hasConflict) {
4264
- slots.push({ start: startIso, end: endIso });
4265
- }
4266
- slotStart = new Date(slotStart.getTime() + interval * 6e4);
4267
- }
4268
- }
4269
- return slots;
4270
- },
4271
- async getSchedules(professionalId) {
4272
- if (professionalId) return schedules.filter((s) => s.assigneeId === professionalId);
4273
- return [...schedules];
4274
- },
4275
- async saveSchedule(input) {
4276
- const schedule = {
4277
- id: uid(),
4278
- tenantId: "mock",
4279
- kind: "working_hours",
4280
- assigneeId: input.assigneeId,
4281
- locationId: input.locationId ?? null,
4282
- dayOfWeek: input.dayOfWeek ?? null,
4283
- specificDate: input.specificDate ?? null,
4284
- startsAt: input.startsAt,
4285
- endsAt: input.endsAt,
4286
- isActive: input.isActive !== false,
4287
- metadata: input.metadata ?? {}
4288
- };
4289
- schedules.push(schedule);
4290
- return schedule;
4291
- },
4292
- async deleteSchedule(id) {
4293
- const idx = schedules.findIndex((s) => s.id === id);
4294
- if (idx !== -1) schedules.splice(idx, 1);
4295
- },
4296
- async getProfessionals() {
4297
- return [...professionals];
4298
- },
4299
- async getConfirmationsPending(daysAhead = 2) {
4300
- const cutoff = /* @__PURE__ */ new Date();
4301
- cutoff.setDate(cutoff.getDate() + daysAhead);
4302
- return bookings.filter(
4303
- (b) => b.status === "scheduled" && new Date(b.startsAt) <= cutoff && new Date(b.startsAt) >= /* @__PURE__ */ new Date()
4304
- );
4305
- },
4306
- async sendConfirmation(bookingId, channel) {
4307
- const booking = bookings.find((b) => b.id === bookingId);
4308
- if (!booking) throw new Error("Booking not found");
4309
- const confirmations = booking.metadata.confirmations ?? [];
4310
- confirmations.push({ channel, sentAt: now(), status: "sent" });
4311
- booking.metadata = { ...booking.metadata, confirmations };
4312
- },
4313
- async completeBooking(bookingId) {
4314
- const idx = bookings.findIndex((b) => b.id === bookingId);
4315
- if (idx === -1) throw new Error("Booking not found");
4316
- bookings[idx] = { ...bookings[idx], status: "completed", updatedAt: now() };
4317
- return { booking: bookings[idx], orderId: bookings[idx].orderId ?? "" };
4318
- }
4319
- };
4320
- }
4321
3906
  function getCurrentBookingQuery(state, dateRange = state.dateRange) {
4322
3907
  return {
4323
3908
  dateRange,
@@ -5066,6 +4651,287 @@ var agendaLocales = {
5066
4651
  en,
5067
4652
  "pt-BR": ptBR
5068
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
+ `;
5069
4935
  function computeCommissionAmount(total, ratePercent) {
5070
4936
  const base = Number(total) || 0;
5071
4937
  const rate = Number(ratePercent) || 0;
@@ -5508,6 +5374,9 @@ function createAgendaPlugin(options) {
5508
5374
  version: "1.0.0",
5509
5375
  scope: options?.scope ?? "universal",
5510
5376
  verticalId: options?.verticalId,
5377
+ // Booking/scheduling is business-ops (clinic, salon, services) — targets
5378
+ // the saas/admin Panel world, not the ecommerce storefront.
5379
+ scaffolds: ["saas"],
5511
5380
  defaultEnabled: true,
5512
5381
  dependencies: [],
5513
5382
  declaredFeatures: [
@@ -5622,10 +5491,18 @@ function createAgendaPlugin(options) {
5622
5491
  permission: { feature: "appointments", action: "read" }
5623
5492
  }
5624
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
+ ],
5625
5502
  locales: agendaLocales
5626
5503
  };
5627
5504
  }
5628
5505
 
5629
- export { bookingToEvent2 as bookingToEvent, computeCommissionAmount, createAgendaPlugin, createFinancialBridge, createGoogleCalendarPlugin, createGoogleCalendarProvider, createMockAgendaProvider, eventToBookingPatch, googleCalendarConnector };
5506
+ export { bookingToEvent2 as bookingToEvent, computeCommissionAmount, createAgendaPlugin, createFinancialBridge, createGoogleCalendarPlugin, createGoogleCalendarProvider, eventToBookingPatch, googleCalendarConnector };
5630
5507
  //# sourceMappingURL=index.js.map
5631
5508
  //# sourceMappingURL=index.js.map