@aglyn/plugins-bookings 1.0.0-beta.232 → 1.0.0-beta.233

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/plugins-bookings",
3
- "version": "1.0.0-beta.232",
3
+ "version": "1.0.0-beta.233",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,16 +25,16 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.0.0-beta.232",
29
- "@aglyn/shared-data-mdi": "1.0.0-beta.232",
30
- "@aglyn/shared-ui-jsx": "1.0.0-beta.232",
31
- "@aglyn/shared-ui-snackstack": "1.0.0-beta.232",
32
- "@aglyn/shared-util-email": "1.0.0-beta.232",
33
- "@aglyn/shared-util-http": "1.0.0-beta.232",
34
- "@aglyn/shared-util-timestamp": "1.0.0-beta.232",
35
- "@aglyn/tenant-data-admin": "1.0.0-beta.232",
36
- "@aglyn/tenant-feature-instance": "1.0.0-beta.232",
37
- "@aglyn/tenant-runtime": "1.0.0-beta.232",
28
+ "@aglyn/aglyn": "1.0.0-beta.233",
29
+ "@aglyn/shared-data-mdi": "1.0.0-beta.233",
30
+ "@aglyn/shared-ui-jsx": "1.0.0-beta.233",
31
+ "@aglyn/shared-ui-snackstack": "1.0.0-beta.233",
32
+ "@aglyn/shared-util-email": "1.0.0-beta.233",
33
+ "@aglyn/shared-util-http": "1.0.0-beta.233",
34
+ "@aglyn/shared-util-timestamp": "1.0.0-beta.233",
35
+ "@aglyn/tenant-data-admin": "1.0.0-beta.233",
36
+ "@aglyn/tenant-feature-instance": "1.0.0-beta.233",
37
+ "@aglyn/tenant-runtime": "1.0.0-beta.233",
38
38
  "@swc/helpers": "0.5.23"
39
39
  },
40
40
  "peerDependencies": {
@@ -24,8 +24,9 @@ import { BOOKINGS_TRANSFER_RESOURCE, bookerBookingsFilterValue, upcomingBookings
24
24
  import { PLATFORM_BRAND_NAME } from "@aglyn/aglyn/app-utils/platform-brand";
25
25
  import { describePaymentRisk } from "@aglyn/aglyn/app-utils/payment-risk";
26
26
  import { isBookingReminderDue } from "../model/index.js";
27
+ import { BOOKING_WEEKDAYS, bookingServiceDraftFrom, bookingServiceFields, newBookingServiceDraft } from "../model/booking-service-form.js";
27
28
  import { bookingServiceStatus } from "../model/bookings.js";
28
- import { BOOKING_FIELD_ASKS, bookingContactAsks } from "../model/booking-contact-fields.js";
29
+ import { BOOKING_FIELD_ASKS } from "../model/booking-contact-fields.js";
29
30
  import { BOOKING_PRICE_DISPLAYS, BOOKING_PRICE_LABELS, bookingPriceDisplay, bookingPriceText } from "../model/booking-price.js";
30
31
  import { AppLink, CardDisplay, HelpTip, useConfirmationContext } from "@aglyn/shared-ui-jsx";
31
32
  import QuotaReadoutComponent from "@aglyn/shared-ui-jsx/components/quota-readout.component";
@@ -37,33 +38,7 @@ import { useParams, useSearchParams } from "next/navigation";
37
38
  import { useCallback, useState } from "react";
38
39
  import { useFirestore, useFirestoreCollection, useHostResourceApi, useUser, writeGuardedBySeed } from "@aglyn/tenant-feature-instance";
39
40
  import { authorizedFetch } from "@aglyn/shared-util-http/authorized-token";
40
- const WEEKDAYS = [
41
- 'Sun',
42
- 'Mon',
43
- 'Tue',
44
- 'Wed',
45
- 'Thu',
46
- 'Fri',
47
- 'Sat'
48
- ];
49
- /** "09:00-12:00, 13:00-17:00" → open intervals in minutes. */ function parseWindows(input) {
50
- const windows = [];
51
- for (const chunk of input.split(',')){
52
- const match = chunk.trim().match(/^(\d{1,2}):(\d{2})\s*-\s*(\d{1,2}):(\d{2})$/);
53
- if (!match) continue;
54
- const start = Number(match[1]) * 60 + Number(match[2]);
55
- const end = Number(match[3]) * 60 + Number(match[4]);
56
- if (end > start && end <= 24 * 60) windows.push({
57
- start,
58
- end
59
- });
60
- }
61
- return windows;
62
- }
63
- function formatWindows(windows) {
64
- const pad = (minutes)=>`${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`;
65
- return (windows != null ? windows : []).map((window)=>`${pad(window.start)}-${pad(window.end)}`).join(', ');
66
- }
41
+ const WEEKDAYS = BOOKING_WEEKDAYS;
67
42
  /** How each way of stating the price reads in the service dialog's picker. */ const PRICE_DISPLAY_LABELS = _extends({
68
43
  fixed: 'The price'
69
44
  }, BOOKING_PRICE_LABELS);
@@ -215,22 +190,9 @@ function formatWindows(windows) {
215
190
  persist: false
216
191
  });
217
192
  }
218
- setDraft({
219
- id: null,
220
- name: '',
221
- durationMinutes: '30',
222
- priceUsd: '0',
223
- timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC',
224
- description: '',
225
- windowText: WEEKDAYS.map((_, index)=>index >= 1 && index <= 5 ? '09:00-17:00' : ''),
226
- // A booking is a meeting the record has; the follow-up is opt-in.
227
- crmMeetingActivity: true,
228
- crmFollowUpTask: false,
229
- // Name and email only, until the service says otherwise.
230
- askPhone: 'off',
231
- askAddress: 'off',
232
- priceDisplay: 'fixed'
233
- });
193
+ setDraft(_extends({
194
+ id: null
195
+ }, newBookingServiceDraft(Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC')));
234
196
  }, [
235
197
  entitled,
236
198
  org,
@@ -239,31 +201,8 @@ function formatWindows(windows) {
239
201
  ]);
240
202
  const handleSave = useCallback(async ()=>{
241
203
  if (!draft || !draft.name.trim()) return;
242
- const windows = {};
243
- draft.windowText.forEach((text, weekday)=>{
244
- const parsed = parseWindows(text);
245
- if (parsed.length) windows[weekday] = parsed;
246
- });
247
- const fields = _extends({
248
- name: draft.name.trim().slice(0, 80),
249
- durationMinutes: Math.max(5, Math.min(480, Math.round(Number(draft.durationMinutes) || 30))),
250
- priceUsd: Math.max(0, Math.round(Number(draft.priceUsd) || 0)),
251
- timezone: draft.timezone.trim() || 'UTC'
252
- }, draft.description.trim() && {
253
- description: draft.description.trim().slice(0, 500)
254
- }, {
255
- windows,
256
- // Written explicitly rather than only when on: an edit that switches
257
- // the meeting off has to land a `false`, and `merge: true` would keep
258
- // an absent key exactly as it was.
259
- crmMeetingActivity: draft.crmMeetingActivity,
260
- crmFollowUpTask: draft.crmFollowUpTask,
261
- // Written explicitly for the same reason: switching a field back off
262
- // has to land `'off'` over the stored answer.
263
- askPhone: draft.askPhone,
264
- askAddress: draft.askAddress,
265
- priceDisplay: draft.priceDisplay
266
- });
204
+ // The one rule for what a save stores, which the native editors share.
205
+ const fields = bookingServiceFields(draft);
267
206
  try {
268
207
  if (draft.id) {
269
208
  /**
@@ -559,29 +498,9 @@ function formatWindows(windows) {
559
498
  }),
560
499
  /*#__PURE__*/ _jsx(Button, {
561
500
  size: "small",
562
- onClick: ()=>{
563
- var _service_name, _service_durationMinutes, _service_priceUsd, _service_timezone, _service_description;
564
- return setDraft({
565
- id: service.$id,
566
- name: (_service_name = service.name) != null ? _service_name : '',
567
- durationMinutes: String((_service_durationMinutes = service.durationMinutes) != null ? _service_durationMinutes : 30),
568
- priceUsd: String((_service_priceUsd = service.priceUsd) != null ? _service_priceUsd : 0),
569
- timezone: (_service_timezone = service.timezone) != null ? _service_timezone : 'UTC',
570
- description: (_service_description = service.description) != null ? _service_description : '',
571
- windowText: WEEKDAYS.map((_, index)=>{
572
- var _service_windows;
573
- return formatWindows((_service_windows = service.windows) == null ? void 0 : _service_windows[index]);
574
- }),
575
- // Absent reads as ON for the meeting and OFF for the
576
- // follow-up — the model's defaults, seeded so the
577
- // switches show what the service actually does.
578
- crmMeetingActivity: service.crmMeetingActivity !== false,
579
- crmFollowUpTask: service.crmFollowUpTask === true,
580
- askPhone: bookingContactAsks(service).phone,
581
- askAddress: bookingContactAsks(service).address,
582
- priceDisplay: bookingPriceDisplay(service.priceDisplay)
583
- });
584
- },
501
+ onClick: ()=>setDraft(_extends({
502
+ id: service.$id
503
+ }, bookingServiceDraftFrom(service))),
585
504
  children: 'Edit'
586
505
  }),
587
506
  bookingServiceStatus(service.status) === 'draft' ? /*#__PURE__*/ _jsx(Button, {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/components/bookings-console-page.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { checkQuota, pluginDocsHelp, useTransferLauncher } from '@aglyn/aglyn'\nimport { normalizeContactEmail } from '@aglyn/aglyn'\nimport { pluginRecordByEmailHref } from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport { BOOKINGS_BOOKER_PARAM } from '../model/bookings-record-routes'\nimport {\n BOOKINGS_TRANSFER_RESOURCE,\n bookerBookingsFilterValue,\n upcomingBookingsFilterValue,\n} from '../transfer/bookings-transfer-common'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { describePaymentRisk, type PaymentRisk } from '@aglyn/aglyn/app-utils/payment-risk'\nimport { type ConsolePluginPageProps } from '@aglyn/aglyn'\nimport { type HostBookingService, isBookingReminderDue } from '../model'\nimport { type BookingServiceStatus, bookingServiceStatus } from '../model/bookings'\nimport {\n BOOKING_FIELD_ASKS,\n type BookingFieldAsk,\n bookingContactAsks,\n} from '../model/booking-contact-fields'\nimport {\n BOOKING_PRICE_DISPLAYS,\n BOOKING_PRICE_LABELS,\n type BookingPriceDisplay,\n bookingPriceDisplay,\n bookingPriceText,\n} from '../model/booking-price'\nimport { AppLink, CardDisplay, HelpTip, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport QuotaReadoutComponent from '@aglyn/shared-ui-jsx/components/quota-readout.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Timestamp } from '@aglyn/shared-util-timestamp'\nimport {\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n FormControlLabel,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n doc,\n limit,\n orderBy,\n query,\n setDoc,\n updateDoc,\n} from 'firebase/firestore'\nimport { useParams, useSearchParams } from 'next/navigation'\nimport { useCallback, useState } from 'react'\nimport {\n useFirestore,\n useFirestoreCollection,\n useHostResourceApi,\n useUser,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\n\nconst WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']\n\n/** \"09:00-12:00, 13:00-17:00\" → open intervals in minutes. */\nfunction parseWindows(input: string): Array<{ start: number; end: number }> {\n const windows: Array<{ start: number; end: number }> = []\n for (const chunk of input.split(',')) {\n const match = chunk.trim().match(/^(\\d{1,2}):(\\d{2})\\s*-\\s*(\\d{1,2}):(\\d{2})$/)\n if (!match) continue\n const start = Number(match[1]) * 60 + Number(match[2])\n const end = Number(match[3]) * 60 + Number(match[4])\n if (end > start && end <= 24 * 60) windows.push({ start, end })\n }\n return windows\n}\n\nfunction formatWindows(\n windows: Array<{ start: number; end: number }> | undefined,\n): string {\n const pad = (minutes: number) =>\n `${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(\n minutes % 60,\n ).padStart(2, '0')}`\n return (windows ?? [])\n .map((window) => `${pad(window.start)}-${pad(window.end)}`)\n .join(', ')\n}\n\ninterface ServiceDraft {\n id: string | null\n name: string\n durationMinutes: string\n priceUsd: string\n timezone: string\n description: string\n /** Per-weekday window text, e.g. \"09:00-17:00\". */\n windowText: string[]\n /** The service's two CRM switches (AGL-2660) — see `HostBookingService`. */\n crmMeetingActivity: boolean\n crmFollowUpTask: boolean\n /** What the widget asks the booker for (AGL-3493). */\n askPhone: BookingFieldAsk\n askAddress: BookingFieldAsk\n /** How the price is stated (AGL-3475); a label books with no charge. */\n priceDisplay: BookingPriceDisplay\n}\n\n/** How each way of stating the price reads in the service dialog's picker. */\nconst PRICE_DISPLAY_LABELS: Record<BookingPriceDisplay, string> = {\n fixed: 'The price',\n ...BOOKING_PRICE_LABELS,\n}\n\n/** How each answer reads in the service dialog's two pickers. */\nconst FIELD_ASK_LABELS: Record<BookingFieldAsk, string> = {\n off: \"Don't ask\",\n optional: 'Optional',\n required: 'Required',\n}\n\n/** A fraud warning, review or chargeback on the booking's payment (AGL-3360). */\nfunction PaymentRiskChip({ risk }: { risk: PaymentRisk | undefined }) {\n const described = describePaymentRisk(risk)\n if (!described) return null\n return (\n <Tooltip title={described.detail}>\n <Chip label={described.label} size=\"small\" color=\"warning\" />\n </Tooltip>\n )\n}\n\n/**\n * Bookings manager (AGL-159): bookable services with weekly availability\n * windows, and the upcoming-bookings list with cancel. Visitors book via\n * the org /api/bookings endpoints; confirmations email through the\n * env-gated Resend path. Plan-gated (`bookings` flag + `servicesPerHost`).\n */\nexport function BookingsConsolePage(props: ConsolePluginPageProps) {\n const { hostId, entitled, org } = props\n const firestore = useFirestore()\n const createHostResource = useHostResourceApi()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n // The id token the refund route authenticates with (AGL-2315).\n const { data: user } = useUser()\n /*\n * Where a booker's CONTACT is (AGL-2622). A booking updated a person in\n * the CRM by the address it carried, and the row links there by that\n * address — the Contacts list holds the id nothing here does and opens\n * the record on one match. The address is the one the plugin that keeps\n * contacts publishes, asked of the record-route registry the way the\n * commerce dialog asks: a plugin importing a sibling is a cycle waiting\n * for its third edge. `null` until the route params settle, and where no\n * plugin keeps contacts, so no row renders a link to nowhere.\n */\n const params = useParams<{ orgSlug?: string; host?: string }>()\n const siteContext =\n params?.orgSlug && params?.host\n ? { orgSlug: String(params.orgSlug), host: String(params.host) }\n : null\n const contactHrefOf = (email: unknown): string | null =>\n siteContext && email ? pluginRecordByEmailHref('contact', siteContext, String(email)) : null\n /*\n * The list narrowed to one booker (AGL-2660): a contact's record links\n * here with `?email=`, and the page answers with every booking that\n * address holds — past ones too, because that link asks about a\n * person's history rather than the week ahead. The same match rule as\n * the row's own \"View in CRM\": the address, normalized, equal. `null`\n * outside a router, where there is no query to read.\n */\n const searchParams = useSearchParams()\n const bookerFilter = normalizeContactEmail(searchParams?.get(BOOKINGS_BOOKER_PARAM))\n const { basePath } = props\n /*\n * Export, opened on the list as it stands: one booker's bookings when the\n * page is narrowed to them, otherwise the upcoming ones from this moment.\n * `null` outside the console shell, where there is nothing to export into.\n * No Import: a booking is only ever made on the booking page.\n */\n const transferLauncher = useTransferLauncher()\n const handleExport = useCallback(() => {\n transferLauncher?.openExport({\n resource: BOOKINGS_TRANSFER_RESOURCE,\n scope: 'host',\n hostId,\n filter: bookerFilter\n ? { label: `Bookings for ${bookerFilter}`, value: bookerBookingsFilterValue(bookerFilter) }\n : { label: 'Upcoming bookings', value: upcomingBookingsFilterValue(Date.now()) },\n })\n }, [transferLauncher, hostId, bookerFilter])\n\n const {\n data: serviceDocs,\n status: servicesStatus,\n /**\n * The rows this editor is seeded from are unconfirmed by the server\n * (AGL-1358). Editing copies a whole stored service into `draft` and\n * writes all of it back, so `merge: true` protects nothing. `windows` is\n * the weekly availability map, rebuilt in full on every save: a cached\n * seed re-opens slots that were closed and closes ones customers can\n * already book, and `priceUsd` goes back to whatever that snapshot\n * charged.\n */\n fromCache: servicesFromCache,\n } = useFirestoreCollection<any>(\n () =>\n query(collection(firestore, 'hosts', hostId, 'services'), limit(100)),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { data: bookingDocs } = useFirestoreCollection<any>(\n () =>\n query(\n collection(firestore, 'hosts', hostId, 'bookings'),\n orderBy('startsAtMs', 'desc'),\n limit(100),\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const services = [...(serviceDocs ?? [])]\n .filter((service: any) => !service.deletedAt)\n .sort((a: any, b: any) =>\n String(a.name ?? '').localeCompare(String(b.name ?? '')),\n )\n const upcoming = [...(bookingDocs ?? [])]\n .filter((booking: any) => booking.endsAtMs >= Date.now())\n .sort((a: any, b: any) => a.startsAtMs - b.startsAtMs)\n // Newest first when narrowed to a booker — the listener already orders\n // by start, descending — so the history reads down from the latest.\n const shown = bookerFilter\n ? (bookingDocs ?? []).filter(\n (booking: any) => normalizeContactEmail(booking.email) === bookerFilter,\n )\n : upcoming\n\n /**\n * The 24-hour reminder queue (AGL-2431).\n *\n * Reminders are sent by the `booking-reminders` beat, not by anything on\n * this page, and until that beat existed they were never sent at all — the\n * feature had a designed email template, white-label branding and an\n * `x-cron-secret` door, and no scheduler pointed at it. So the merchant had\n * no way to tell working from broken, and still would not if this card\n * merely asserted that reminders happen.\n *\n * READ-ONLY, and deliberately no \"send now\" button: the beat runs hourly\n * and stamps `reminderSentAt`, so a manual sender would race it for a\n * reminder nobody can un-send. Same call AGL-2227 made for the recovery\n * queue.\n *\n * `isBookingReminderDue` is the sender's own predicate, against one instant\n * shared by both counts, so this is the queue the next pass will drain\n * rather than an approximation of it.\n */\n const reminderNowMs = Date.now()\n const reminderQueue = (bookingDocs ?? []).filter((booking: any) =>\n isBookingReminderDue(booking, reminderNowMs),\n ).length\n const remindersSent = (bookingDocs ?? []).filter(\n (booking: any) => booking.reminderSentAt,\n ).length\n\n const [draft, setDraft] = useState<ServiceDraft | null>(null)\n\n const handleAdd = useCallback(() => {\n if (!entitled) {\n return void enqueueSnackbar(\n 'Bookings require a Starter plan — see Billing to upgrade',\n { variant: 'warning', persist: false },\n )\n }\n const quota = checkQuota(org, 'servicesPerHost', services.length)\n if (!quota.allowed) {\n return void enqueueSnackbar(\n `Service limit reached (${quota.limit}) — upgrade in Billing`,\n { variant: 'warning', persist: false },\n )\n }\n setDraft({\n id: null,\n name: '',\n durationMinutes: '30',\n priceUsd: '0',\n timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC',\n description: '',\n windowText: WEEKDAYS.map((_, index) =>\n index >= 1 && index <= 5 ? '09:00-17:00' : '',\n ),\n // A booking is a meeting the record has; the follow-up is opt-in.\n crmMeetingActivity: true,\n crmFollowUpTask: false,\n // Name and email only, until the service says otherwise.\n askPhone: 'off',\n askAddress: 'off',\n priceDisplay: 'fixed',\n })\n }, [entitled, org, services.length, enqueueSnackbar])\n\n const handleSave = useCallback(async () => {\n if (!draft || !draft.name.trim()) return\n const windows: HostBookingService['windows'] = {}\n draft.windowText.forEach((text, weekday) => {\n const parsed = parseWindows(text)\n if (parsed.length) windows[weekday] = parsed\n })\n const fields = {\n name: draft.name.trim().slice(0, 80),\n durationMinutes: Math.max(\n 5,\n Math.min(480, Math.round(Number(draft.durationMinutes) || 30)),\n ),\n priceUsd: Math.max(0, Math.round(Number(draft.priceUsd) || 0)),\n timezone: draft.timezone.trim() || 'UTC',\n ...(draft.description.trim() && {\n description: draft.description.trim().slice(0, 500),\n }),\n windows,\n // Written explicitly rather than only when on: an edit that switches\n // the meeting off has to land a `false`, and `merge: true` would keep\n // an absent key exactly as it was.\n crmMeetingActivity: draft.crmMeetingActivity,\n crmFollowUpTask: draft.crmFollowUpTask,\n // Written explicitly for the same reason: switching a field back off\n // has to land `'off'` over the stored answer.\n askPhone: draft.askPhone,\n askAddress: draft.askAddress,\n priceDisplay: draft.priceDisplay,\n }\n try {\n if (draft.id) {\n /**\n * Edit stays client-direct (no quota consumed) — and is refused when\n * its seed was never confirmed by the server (AGL-1358). `fields` is\n * every editable key of the stored service, `windows` included, so\n * `merge: true` has nothing left to protect.\n *\n * The guard WRAPS the write. An early return is a shape you can keep\n * while losing the protection; here the write is only reachable\n * through the verdict.\n */\n const verdict = await writeGuardedBySeed(\n {\n subject: 'service',\n unreadable: servicesStatus === 'error',\n fromCache: servicesFromCache,\n },\n async () => {\n await setDoc(\n doc(firestore, 'hosts', hostId, 'services', draft.id),\n { ...fields, updatedAt: Timestamp.now() },\n { merge: true },\n )\n },\n )\n // Before `setDraft(null)`, so a refusal keeps the dialog open with\n // every window that was typed. A save that silently does nothing\n // sends the user back to retype a form that will be refused again\n // just as quietly.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n } else {\n // New service rides the quota-enforcing resources API (AGL-473) —\n // it also re-checks the `bookings` entitlement server-side.\n await createHostResource({ hostId, resource: 'service', data: fields })\n }\n setDraft(null)\n enqueueSnackbar('Service saved', { variant: 'success', persist: false })\n } catch (error: any) {\n console.error(error)\n enqueueSnackbar(error?.message ?? 'An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n }, [\n draft,\n firestore,\n hostId,\n createHostResource,\n enqueueSnackbar,\n servicesStatus,\n servicesFromCache,\n ])\n\n /**\n * A draft is activated here, and only here (AGL-3616): a service a draft\n * writer made is set up and offered nowhere until a person looks at it and\n * says it takes bookings. Deactivating sends a live one back to draft,\n * which takes it off the site without deleting it; bookings it already\n * holds stand. One field, so the seed guard the dialog's whole-document\n * save needs has nothing to protect here.\n */\n const handleServiceStatus = useCallback(\n (service: any, status: BookingServiceStatus) => async () => {\n try {\n await updateDoc(doc(firestore, 'hosts', hostId, 'services', service.$id), {\n status,\n updatedAt: Timestamp.now(),\n })\n enqueueSnackbar(\n status === 'active'\n ? `${service.name} now takes bookings`\n : `${service.name} is a draft — it takes no bookings until activated`,\n { variant: 'success', persist: false },\n )\n } catch (error: any) {\n console.error(error)\n enqueueSnackbar(error?.message ?? 'An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n },\n [firestore, hostId, enqueueSnackbar],\n )\n\n const handleDeleteService = useCallback(\n (service: any) => async () => {\n const confirmed = await confirm({\n title: 'Delete this service?',\n description: `\"${service.name}\" stops accepting bookings.`,\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await updateDoc(doc(firestore, 'hosts', hostId, 'services', service.$id), {\n deletedAt: Timestamp.now(),\n })\n },\n [confirm, firestore, hostId],\n )\n\n /**\n * Cancelling a PAID booking refunds the guest (AGL-2315).\n *\n * This used to be one `updateDoc` writing `status: 'canceled'`, for a paid\n * booking exactly as for a free one. The slot reopened, the appointment was\n * gone, and the guest had paid for it — the money moved nowhere and nothing\n * in the console said so. That was survivable only while the charge settled\n * in Aglyn's own balance and could be given back by hand; a paid booking is\n * a destination charge now, so the funds are at the MERCHANT and there is no\n * later opportunity to notice.\n *\n * So a paid booking cancels through the refund route, which reverses the\n * merchant's share and Aglyn's fee, and which sets `canceled` itself once\n * the money is actually back. A FAILED refund deliberately leaves the\n * booking standing: a cancelled-and-unrefunded appointment is the worst of\n * the three outcomes, and an admin who sees the row still there knows the\n * cancel did not happen.\n */\n const handleCancelBooking = useCallback(\n (booking: any) => async () => {\n const paidCents = Math.max(0, Number(booking.paidAmountCents ?? 0))\n const refundedCents = Math.max(0, Number(booking.refundedCents ?? 0))\n const outstandingCents = Math.max(0, paidCents - refundedCents)\n const refundable = outstandingCents > 0\n const confirmed = await confirm({\n title: 'Cancel this booking?',\n description:\n `${booking.name} (${booking.email}) — the slot reopens.` +\n (refundable\n ? ` $${(outstandingCents / 100).toFixed(2)} is refunded to them` +\n ' through Stripe.'\n : ''),\n confirmationText: refundable ? 'Cancel and refund' : 'Cancel booking',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n\n if (refundable) {\n // `randomUUID` needs a secure context, which the console always is,\n // but fall back rather than throw on a refund.\n const attemptKey =\n globalThis.crypto?.randomUUID?.() ??\n `${Date.now()}-${Math.random().toString(36).slice(2)}`\n try {\n const response = await authorizedFetch(user, '/api/bookings/refund', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Idempotency-Key': attemptKey,\n },\n body: JSON.stringify({ hostId, bookingId: booking.$id }),\n })\n const payload = await response.json().catch(() => null)\n if (!response.ok) {\n // A 409 is a guard REFUSING with a body that says what to do\n // instead — a booking paid before the PaymentIntent was recorded\n // names the Stripe dashboard — not the refund machinery failing.\n // It surfaces verbatim, the AGL-1818 rule.\n enqueueSnackbar(payload?.error ?? 'Refund failed', {\n variant: response.status === 409 ? 'warning' : 'error',\n allowDuplicate: true,\n })\n // The booking stays. See the note above: cancelled-and-unrefunded\n // is worse than not cancelled.\n return\n }\n // The route wrote `canceled` itself once the money was back.\n enqueueSnackbar('Booking canceled and refunded', {\n variant: 'success',\n persist: false,\n })\n return\n } catch {\n enqueueSnackbar('Refund failed — the booking was not canceled', {\n variant: 'error',\n allowDuplicate: true,\n })\n return\n }\n }\n\n // Through the cancel route (AGL-3643), not a direct write: the route\n // holds the rule that a paid booking cancels through its refund, and\n // tells the plugins listening for `booking.canceled`.\n try {\n const response = await authorizedFetch(user, '/api/bookings/cancel', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId, bookingId: booking.$id }),\n })\n const payload = await response.json().catch(() => null)\n if (!response.ok) {\n enqueueSnackbar(payload?.error ?? 'The booking was not canceled', {\n variant: response.status === 409 ? 'warning' : 'error',\n allowDuplicate: true,\n })\n return\n }\n } catch {\n enqueueSnackbar('The booking was not canceled', {\n variant: 'error',\n allowDuplicate: true,\n })\n return\n }\n enqueueSnackbar('Booking canceled', {\n variant: 'success',\n persist: false,\n })\n },\n [confirm, hostId, enqueueSnackbar, user],\n )\n\n return (\n <Stack spacing={3}>\n <CardDisplay\n header={'Services'}\n help={pluginDocsHelp('bookings', {\n anchor: '#set-up-bookings',\n excerpt:\n 'The bookable services this site offers — how long each takes, ' +\n 'what it costs, and the hours it can be booked in.',\n })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n {services.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Define a bookable service — duration, price, and weekly ' +\n 'availability — then visitors can book from your site.'}\n </Typography>\n ) : (\n services.map((service: any) => (\n <Stack\n key={service.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center', minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {service.name}\n </Typography>\n {bookingServiceStatus(service.status) === 'draft' ? (\n <Tooltip title=\"Set up, and offered nowhere until you activate it\">\n <Chip label=\"Draft\" size=\"small\" />\n </Tooltip>\n ) : null}\n </Stack>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {`${service.durationMinutes} min · ${bookingPriceText(service).replace(/^Free$/, 'free')}` +\n ` · ${service.timezone ?? 'UTC'}`}\n </Typography>\n </Stack>\n <Button\n size=\"small\"\n onClick={() =>\n setDraft({\n id: service.$id,\n name: service.name ?? '',\n durationMinutes: String(service.durationMinutes ?? 30),\n priceUsd: String(service.priceUsd ?? 0),\n timezone: service.timezone ?? 'UTC',\n description: service.description ?? '',\n windowText: WEEKDAYS.map((_, index) =>\n formatWindows(service.windows?.[index]),\n ),\n // Absent reads as ON for the meeting and OFF for the\n // follow-up — the model's defaults, seeded so the\n // switches show what the service actually does.\n crmMeetingActivity: service.crmMeetingActivity !== false,\n crmFollowUpTask: service.crmFollowUpTask === true,\n askPhone: bookingContactAsks(service).phone,\n askAddress: bookingContactAsks(service).address,\n priceDisplay: bookingPriceDisplay(service.priceDisplay),\n })\n }\n >\n {'Edit'}\n </Button>\n {bookingServiceStatus(service.status) === 'draft' ? (\n <Button\n size=\"small\"\n color=\"primary\"\n onClick={handleServiceStatus(service, 'active')}\n >\n {'Activate'}\n </Button>\n ) : (\n <Button size=\"small\" onClick={handleServiceStatus(service, 'draft')}>\n {'Deactivate'}\n </Button>\n )}\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleDeleteService(service)}\n >\n {'Delete'}\n </Button>\n </Stack>\n ))\n )}\n <Button\n size=\"small\"\n color=\"primary\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={handleAdd}\n >\n {'Add service'}\n </Button>\n {/* The cap, standing rather than only on refusal (AGL-2113).\n `services.length` is the same count `handleAdd` hands to\n `checkQuota`, so the readout and the gate cannot disagree. */}\n <QuotaReadoutComponent\n ready={org != null}\n used={services.length}\n limit={checkQuota(org, 'servicesPerHost', services.length).limit}\n noun=\"service\"\n />\n </Stack>\n </CardDisplay>\n\n <CardDisplay\n header={bookerFilter ? `Bookings for ${bookerFilter}` : 'Upcoming bookings'}\n help={pluginDocsHelp('bookings', {\n anchor: '#manage',\n excerpt:\n 'Bookings taken on this site, with the customer and the slot each ' +\n 'one holds.',\n })}\n contentGutterX\n contentGutterY\n HeaderProps={{\n action: transferLauncher?.can('export', { resource: BOOKINGS_TRANSFER_RESOURCE, scope: 'host', hostId }) ? (\n <Button size=\"small\" color=\"primary\" onClick={handleExport}>\n {'Export'}\n </Button>\n ) : undefined,\n }}\n >\n {bookerFilter ? (\n <Typography\n variant=\"caption\"\n color=\"text.secondary\"\n component=\"div\"\n sx={{ mb: 1 }}\n >\n {'Every booking this address holds, newest first. '}\n {basePath ? <AppLink href={basePath}>{'Show upcoming bookings'}</AppLink> : null}\n </Typography>\n ) : null}\n {/* What the reminder beat will do next, and what it has done. Named\n \"24-hour reminders\" rather than \"emails\" because that is the only\n mail this queue governs — confirmations go out on booking. */}\n <Typography\n variant=\"caption\"\n color=\"text.secondary\"\n component=\"div\"\n sx={{ mb: 1 }}\n >\n {`24-hour reminders · ${reminderQueue} due in the next pass · ` +\n `${remindersSent} already sent`}\n {/* Its OWN heading, not the card's `#manage`: a merchant reading\n this line wants the timing and the once-only rule, and landing\n them on \"manage your bookings\" is the presence-not-correctness\n failure a help-coverage check cannot see. */}\n <HelpTip\n {...pluginDocsHelp('bookings', { anchor: '#reminders' })}\n sx={{ ml: 0.5, fontSize: '0.9em' }}\n />\n </Typography>\n {shown.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {bookerFilter ? 'No bookings for this address.' : 'No upcoming bookings.'}\n </Typography>\n ) : (\n <Stack spacing={1}>\n {shown.map((booking: any) => (\n <Stack\n key={booking.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {`${booking.serviceName} — ${booking.name}`}\n {booking.status === 'canceled' ? ' (canceled)' : ''}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {`${new Date(booking.startsAtMs).toLocaleString()} · ${\n booking.email\n }`}\n {typeof booking.phone === 'string' && booking.phone\n ? ` · ${booking.phone}`\n : ''}\n </Typography>\n {/* Where the job is, when the service asked (AGL-3493).\n Wrapped rather than cut: an address read to its end is\n the one a crew can drive to. */}\n {typeof booking.address === 'string' && booking.address ? (\n <Typography\n variant=\"caption\"\n color=\"text.secondary\"\n sx={{ whiteSpace: 'pre-line' }}\n >\n {booking.address}\n </Typography>\n ) : null}\n </Stack>\n <PaymentRiskChip risk={booking.paymentRisk} />\n {contactHrefOf(booking.email) ? (\n <Button\n component={AppLink as any}\n {...({ componentVariant: 'naked', nativeButton: false } as any)}\n href={contactHrefOf(booking.email) ?? undefined}\n size=\"small\"\n >\n {'View in CRM'}\n </Button>\n ) : null}\n {booking.status !== 'canceled' ? (\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleCancelBooking(booking)}\n >\n {'Cancel'}\n </Button>\n ) : null}\n </Stack>\n ))}\n </Stack>\n )}\n </CardDisplay>\n\n <Dialog\n open={Boolean(draft)}\n onClose={() => setDraft(null)}\n maxWidth=\"sm\"\n fullWidth\n >\n <DialogTitle>{draft?.id ? 'Edit service' : 'Add service'}</DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 1.5, pt: 1 }}\n >\n <TextField\n label=\"Name\"\n value={draft?.name ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, name: event.target.value } : prev,\n )\n }\n size=\"small\"\n autoFocus\n sx={{ mt: 1 }}\n />\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Duration (minutes)\"\n value={draft?.durationMinutes ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? {\n ...prev,\n durationMinutes: event.target.value.replace(\n /[^0-9]/g,\n '',\n ),\n }\n : prev,\n )\n }\n size=\"small\"\n />\n <TextField\n label=\"Price (USD, 0 = free)\"\n // WHAT THIS PRICE DOES NOT INCLUDE (AGL-2028).\n //\n // A paid booking is charged exactly this figure: the handler\n // sends no tax parameter at all, by a stated decision (AGL-2000)\n // — whether a service is taxable is jurisdiction-specific and\n // frequently the opposite answer from goods, so applying the\n // commerce plugin's GOODS sales rate would be confidently wrong\n // rather than merely absent.\n //\n // That decision was recorded in the source and in the\n // `storefrontTaxCollected` ledger, and in neither place can the\n // merchant see it. A service business is one of the three named\n // ICPs, and one who configured a rate in Commerce → Settings →\n // Taxes has every reason to assume it covers the appointments\n // they sell on the same site. Saying so here is the half of\n // AGL-2028 that holds however the rate question is answered.\n //\n // States the MECHANISM and makes no remittance determination —\n // the same line `describeOrderTaxMode` holds. Who owes which\n // authority what attaches by operation of law and is counsel's\n // call (AGL-1904/AGL-1956).\n helperText={\n draft && draft.priceDisplay !== 'fixed'\n ? `Not charged: this service shows “${BOOKING_PRICE_LABELS[draft.priceDisplay]}” and books with no charge.`\n : `${PLATFORM_BRAND_NAME} charges this price as typed — no tax is added. Your Commerce tax settings are a goods sales rate and do not apply to bookings.`\n }\n value={draft?.priceUsd ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? {\n ...prev,\n priceUsd: event.target.value.replace(/[^0-9]/g, ''),\n }\n : prev,\n )\n }\n size=\"small\"\n />\n {/*\n A contractor who quotes at the job states the price as a label\n instead (AGL-3475). Any label books with no charge, like an\n estimate appointment, and the stored price is neither shown nor\n charged.\n */}\n <TextField\n select\n label=\"Show the price as\"\n value={draft?.priceDisplay ?? 'fixed'}\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? { ...prev, priceDisplay: bookingPriceDisplay(event.target.value) }\n : prev,\n )\n }\n size=\"small\"\n sx={{ minWidth: 180 }}\n >\n {BOOKING_PRICE_DISPLAYS.map((display) => (\n <MenuItem key={display} value={display}>\n {PRICE_DISPLAY_LABELS[display]}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n label=\"Timezone\"\n value={draft?.timezone ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, timezone: event.target.value } : prev,\n )\n }\n size=\"small\"\n sx={{ minWidth: 180 }}\n />\n </Stack>\n <TextField\n label=\"Description (optional)\"\n value={draft?.description ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, description: event.target.value } : prev,\n )\n }\n size=\"small\"\n multiline\n minRows={2}\n />\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Weekly availability'}\n </Typography>\n {WEEKDAYS.map((day, index) => (\n <TextField\n key={day}\n label={day}\n placeholder=\"09:00-12:00, 13:00-17:00 (empty = closed)\"\n value={draft?.windowText[index] ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? {\n ...prev,\n windowText: prev.windowText.map((text, i) =>\n i === index ? event.target.value : text,\n ),\n }\n : prev,\n )\n }\n size=\"small\"\n />\n ))}\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Booking form'}\n </Typography>\n {/*\n What the widget asks for beyond a name and an email (AGL-3493).\n Off by default; an on-site service asks for both, required.\n */}\n <Stack direction={{ xs: 'column', sm: 'row' }} spacing={1}>\n {(\n [\n ['askPhone', 'Phone number'],\n ['askAddress', 'Address'],\n ] as const\n ).map(([key, label]) => (\n <TextField\n key={key}\n select\n label={label}\n value={draft?.[key] ?? 'off'}\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? { ...prev, [key]: event.target.value as BookingFieldAsk }\n : prev,\n )\n }\n size=\"small\"\n fullWidth\n >\n {BOOKING_FIELD_ASKS.map((ask) => (\n <MenuItem key={ask} value={ask}>\n {FIELD_ASK_LABELS[ask]}\n </MenuItem>\n ))}\n </TextField>\n ))}\n </Stack>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'CRM'}\n </Typography>\n {/*\n What a booking of this service does to the booker's CRM record\n (AGL-2660). The meeting is on by default — a booking IS a\n meeting the record has — and the follow-up is the service's\n choice, because not every service earns a call afterwards.\n */}\n <FormControlLabel\n control={\n <Switch\n checked={draft?.crmMeetingActivity ?? true}\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? { ...prev, crmMeetingActivity: event.target.checked }\n : prev,\n )\n }\n size=\"small\"\n />\n }\n label=\"Log a meeting on the CRM record when this service is booked\"\n />\n <FormControlLabel\n control={\n <Switch\n checked={draft?.crmFollowUpTask ?? false}\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? { ...prev, crmFollowUpTask: event.target.checked }\n : prev,\n )\n }\n size=\"small\"\n />\n }\n label=\"Create a follow-up task on the CRM record when this service is booked\"\n />\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'The follow-up is due one business day after the slot, on whoever ' +\n 'owns the record. Nothing is filed on a site whose CRM is off.'}\n </Typography>\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!draft?.name.trim()}\n onClick={handleSave}\n >\n {'Save service'}\n </Button>\n </DialogActions>\n </Dialog>\n </Stack>\n )\n}\nBookingsConsolePage.displayName = 'BookingsConsolePage'\n\nexport default BookingsConsolePage\n"],"names":["checkQuota","pluginDocsHelp","useTransferLauncher","normalizeContactEmail","pluginRecordByEmailHref","BOOKINGS_BOOKER_PARAM","BOOKINGS_TRANSFER_RESOURCE","bookerBookingsFilterValue","upcomingBookingsFilterValue","PLATFORM_BRAND_NAME","describePaymentRisk","isBookingReminderDue","bookingServiceStatus","BOOKING_FIELD_ASKS","bookingContactAsks","BOOKING_PRICE_DISPLAYS","BOOKING_PRICE_LABELS","bookingPriceDisplay","bookingPriceText","AppLink","CardDisplay","HelpTip","useConfirmationContext","QuotaReadoutComponent","useSnackbar","Timestamp","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","FormControlLabel","MenuItem","Stack","Switch","TextField","Tooltip","Typography","collection","doc","limit","orderBy","query","setDoc","updateDoc","useParams","useSearchParams","useCallback","useState","useFirestore","useFirestoreCollection","useHostResourceApi","useUser","writeGuardedBySeed","authorizedFetch","WEEKDAYS","parseWindows","input","windows","chunk","split","match","trim","start","Number","end","push","formatWindows","pad","minutes","String","Math","floor","padStart","map","window","join","PRICE_DISPLAY_LABELS","fixed","FIELD_ASK_LABELS","off","optional","required","PaymentRiskChip","risk","described","title","detail","label","size","color","BookingsConsolePage","props","hostId","entitled","org","firestore","createHostResource","enqueueSnackbar","confirm","data","user","params","siteContext","orgSlug","host","contactHrefOf","email","searchParams","bookerFilter","get","basePath","transferLauncher","handleExport","openExport","resource","scope","filter","value","Date","now","serviceDocs","status","servicesStatus","fromCache","servicesFromCache","idField","bookingDocs","services","service","deletedAt","sort","a","b","name","localeCompare","upcoming","booking","endsAtMs","startsAtMs","shown","reminderNowMs","reminderQueue","length","remindersSent","reminderSentAt","draft","setDraft","handleAdd","variant","persist","quota","allowed","id","durationMinutes","priceUsd","timezone","Intl","DateTimeFormat","resolvedOptions","timeZone","description","windowText","_","index","crmMeetingActivity","crmFollowUpTask","askPhone","askAddress","priceDisplay","handleSave","forEach","text","weekday","parsed","fields","slice","max","min","round","verdict","subject","unreadable","updatedAt","merge","ok","message","error","console","allowDuplicate","handleServiceStatus","$id","handleDeleteService","confirmed","confirmationText","confirmationButtonProps","then","catch","handleCancelBooking","paidCents","paidAmountCents","refundedCents","outstandingCents","refundable","toFixed","globalThis","attemptKey","crypto","randomUUID","random","toString","response","method","headers","body","JSON","stringify","bookingId","payload","json","spacing","header","help","anchor","excerpt","contentGutterX","contentGutterY","direction","sx","alignItems","flex","minWidth","noWrap","replace","onClick","phone","address","alignSelf","ready","used","noun","HeaderProps","action","can","undefined","component","mb","href","ml","fontSize","serviceName","toLocaleString","whiteSpace","paymentRisk","componentVariant","nativeButton","open","Boolean","onClose","maxWidth","fullWidth","display","flexDirection","gap","pt","onChange","event","prev","target","autoFocus","mt","helperText","select","multiline","minRows","day","placeholder","i","xs","sm","key","ask","control","checked","disabled","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,UAAU,EAAEC,cAAc,EAAEC,mBAAmB,QAAQ,eAAc;AAC9E,SAASC,qBAAqB,QAAQ,eAAc;AACpD,SAASC,uBAAuB,QAAQ,mDAAkD;AAC1F,SAASC,qBAAqB,QAAQ,qCAAiC;AACvE,SACEC,0BAA0B,EAC1BC,yBAAyB,EACzBC,2BAA2B,QACtB,0CAAsC;AAC7C,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,mBAAmB,QAA0B,sCAAqC;AAE3F,SAAkCC,oBAAoB,QAAQ,oBAAU;AACxE,SAAoCC,oBAAoB,QAAQ,uBAAmB;AACnF,SACEC,kBAAkB,EAElBC,kBAAkB,QACb,qCAAiC;AACxC,SACEC,sBAAsB,EACtBC,oBAAoB,EAEpBC,mBAAmB,EACnBC,gBAAgB,QACX,4BAAwB;AAC/B,SAASC,OAAO,EAAEC,WAAW,EAAEC,OAAO,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC5F,OAAOC,2BAA2B,0DAAyD;AAC3F,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,SAAS,QAAQ,+BAA8B;AACxD,SACEC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,gBAAgB,EAChBC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,SAAS,EACTC,OAAO,EACPC,UAAU,QACL,gBAAe;AACtB,SACEC,UAAU,EACVC,GAAG,EACHC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,MAAM,EACNC,SAAS,QACJ,qBAAoB;AAC3B,SAASC,SAAS,EAAEC,eAAe,QAAQ,kBAA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sBX,KAACnP;gCAAWgH,SAAQ;gCAAW3D,OAAM;0CAClC;;0CAQH,KAAC3D;gCACC2P,uBACE,KAACxP;oCACCyP,OAAO,WAAEzI,yBAAAA,MAAOmB,kBAAkB,oBAAI;oCACtCoG,UAAU,CAACC,QACTvH,SAAS,CAACwH,OACRA,OACI,aAAKA;gDAAMtG,oBAAoBqG,MAAME,MAAM,CAACe,OAAO;iDACnDhB;oCAGRlL,MAAK;;gCAGTD,OAAM;;0CAER,KAACzD;gCACC2P,uBACE,KAACxP;oCACCyP,OAAO,WAAEzI,yBAAAA,MAAOoB,eAAe,oBAAI;oCACnCmG,UAAU,CAACC,QACTvH,SAAS,CAACwH,OACRA,OACI,aAAKA;gDAAMrG,iBAAiBoG,MAAME,MAAM,CAACe,OAAO;iDAChDhB;oCAGRlL,MAAK;;gCAGTD,OAAM;;0CAER,KAACnD;gCAAWgH,SAAQ;gCAAU3D,OAAM;0CACjC,sEACC;;;;kCAGN,MAAC9D;;0CACC,KAACH;gCAAOiN,SAAS,IAAMvF,SAAS;0CAAQ;;0CACxC,KAAC1H;gCACC4H,SAAQ;gCACR3D,OAAM;gCACNkM,UAAU,EAAC1I,yBAAAA,MAAOZ,IAAI,CAACxE,IAAI;gCAC3B4K,SAAShE;0CAER;;;;;;;;AAMb;AACA/E,oBAAoBkM,WAAW,GAAG;AAElC,eAAelM,oBAAmB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/components/bookings-console-page.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { checkQuota, pluginDocsHelp, useTransferLauncher } from '@aglyn/aglyn'\nimport { normalizeContactEmail } from '@aglyn/aglyn'\nimport { pluginRecordByEmailHref } from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport { BOOKINGS_BOOKER_PARAM } from '../model/bookings-record-routes'\nimport {\n BOOKINGS_TRANSFER_RESOURCE,\n bookerBookingsFilterValue,\n upcomingBookingsFilterValue,\n} from '../transfer/bookings-transfer-common'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { describePaymentRisk, type PaymentRisk } from '@aglyn/aglyn/app-utils/payment-risk'\nimport { type ConsolePluginPageProps } from '@aglyn/aglyn'\nimport { isBookingReminderDue } from '../model'\nimport {\n BOOKING_WEEKDAYS,\n type BookingServiceDraft,\n bookingServiceDraftFrom,\n bookingServiceFields,\n newBookingServiceDraft,\n} from '../model/booking-service-form'\nimport { type BookingServiceStatus, bookingServiceStatus } from '../model/bookings'\nimport {\n BOOKING_FIELD_ASKS,\n type BookingFieldAsk,\n} from '../model/booking-contact-fields'\nimport {\n BOOKING_PRICE_DISPLAYS,\n BOOKING_PRICE_LABELS,\n type BookingPriceDisplay,\n bookingPriceDisplay,\n bookingPriceText,\n} from '../model/booking-price'\nimport { AppLink, CardDisplay, HelpTip, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport QuotaReadoutComponent from '@aglyn/shared-ui-jsx/components/quota-readout.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Timestamp } from '@aglyn/shared-util-timestamp'\nimport {\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n FormControlLabel,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n doc,\n limit,\n orderBy,\n query,\n setDoc,\n updateDoc,\n} from 'firebase/firestore'\nimport { useParams, useSearchParams } from 'next/navigation'\nimport { useCallback, useState } from 'react'\nimport {\n useFirestore,\n useFirestoreCollection,\n useHostResourceApi,\n useUser,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\n\nconst WEEKDAYS = BOOKING_WEEKDAYS\n\n/** The dialog's fields, and the service it edits (`null` for a new one). */\ninterface ServiceDraft extends BookingServiceDraft {\n id: string | null\n}\n\n/** How each way of stating the price reads in the service dialog's picker. */\nconst PRICE_DISPLAY_LABELS: Record<BookingPriceDisplay, string> = {\n fixed: 'The price',\n ...BOOKING_PRICE_LABELS,\n}\n\n/** How each answer reads in the service dialog's two pickers. */\nconst FIELD_ASK_LABELS: Record<BookingFieldAsk, string> = {\n off: \"Don't ask\",\n optional: 'Optional',\n required: 'Required',\n}\n\n/** A fraud warning, review or chargeback on the booking's payment (AGL-3360). */\nfunction PaymentRiskChip({ risk }: { risk: PaymentRisk | undefined }) {\n const described = describePaymentRisk(risk)\n if (!described) return null\n return (\n <Tooltip title={described.detail}>\n <Chip label={described.label} size=\"small\" color=\"warning\" />\n </Tooltip>\n )\n}\n\n/**\n * Bookings manager (AGL-159): bookable services with weekly availability\n * windows, and the upcoming-bookings list with cancel. Visitors book via\n * the org /api/bookings endpoints; confirmations email through the\n * env-gated Resend path. Plan-gated (`bookings` flag + `servicesPerHost`).\n */\nexport function BookingsConsolePage(props: ConsolePluginPageProps) {\n const { hostId, entitled, org } = props\n const firestore = useFirestore()\n const createHostResource = useHostResourceApi()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n // The id token the refund route authenticates with (AGL-2315).\n const { data: user } = useUser()\n /*\n * Where a booker's CONTACT is (AGL-2622). A booking updated a person in\n * the CRM by the address it carried, and the row links there by that\n * address — the Contacts list holds the id nothing here does and opens\n * the record on one match. The address is the one the plugin that keeps\n * contacts publishes, asked of the record-route registry the way the\n * commerce dialog asks: a plugin importing a sibling is a cycle waiting\n * for its third edge. `null` until the route params settle, and where no\n * plugin keeps contacts, so no row renders a link to nowhere.\n */\n const params = useParams<{ orgSlug?: string; host?: string }>()\n const siteContext =\n params?.orgSlug && params?.host\n ? { orgSlug: String(params.orgSlug), host: String(params.host) }\n : null\n const contactHrefOf = (email: unknown): string | null =>\n siteContext && email ? pluginRecordByEmailHref('contact', siteContext, String(email)) : null\n /*\n * The list narrowed to one booker (AGL-2660): a contact's record links\n * here with `?email=`, and the page answers with every booking that\n * address holds — past ones too, because that link asks about a\n * person's history rather than the week ahead. The same match rule as\n * the row's own \"View in CRM\": the address, normalized, equal. `null`\n * outside a router, where there is no query to read.\n */\n const searchParams = useSearchParams()\n const bookerFilter = normalizeContactEmail(searchParams?.get(BOOKINGS_BOOKER_PARAM))\n const { basePath } = props\n /*\n * Export, opened on the list as it stands: one booker's bookings when the\n * page is narrowed to them, otherwise the upcoming ones from this moment.\n * `null` outside the console shell, where there is nothing to export into.\n * No Import: a booking is only ever made on the booking page.\n */\n const transferLauncher = useTransferLauncher()\n const handleExport = useCallback(() => {\n transferLauncher?.openExport({\n resource: BOOKINGS_TRANSFER_RESOURCE,\n scope: 'host',\n hostId,\n filter: bookerFilter\n ? { label: `Bookings for ${bookerFilter}`, value: bookerBookingsFilterValue(bookerFilter) }\n : { label: 'Upcoming bookings', value: upcomingBookingsFilterValue(Date.now()) },\n })\n }, [transferLauncher, hostId, bookerFilter])\n\n const {\n data: serviceDocs,\n status: servicesStatus,\n /**\n * The rows this editor is seeded from are unconfirmed by the server\n * (AGL-1358). Editing copies a whole stored service into `draft` and\n * writes all of it back, so `merge: true` protects nothing. `windows` is\n * the weekly availability map, rebuilt in full on every save: a cached\n * seed re-opens slots that were closed and closes ones customers can\n * already book, and `priceUsd` goes back to whatever that snapshot\n * charged.\n */\n fromCache: servicesFromCache,\n } = useFirestoreCollection<any>(\n () =>\n query(collection(firestore, 'hosts', hostId, 'services'), limit(100)),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { data: bookingDocs } = useFirestoreCollection<any>(\n () =>\n query(\n collection(firestore, 'hosts', hostId, 'bookings'),\n orderBy('startsAtMs', 'desc'),\n limit(100),\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const services = [...(serviceDocs ?? [])]\n .filter((service: any) => !service.deletedAt)\n .sort((a: any, b: any) =>\n String(a.name ?? '').localeCompare(String(b.name ?? '')),\n )\n const upcoming = [...(bookingDocs ?? [])]\n .filter((booking: any) => booking.endsAtMs >= Date.now())\n .sort((a: any, b: any) => a.startsAtMs - b.startsAtMs)\n // Newest first when narrowed to a booker — the listener already orders\n // by start, descending — so the history reads down from the latest.\n const shown = bookerFilter\n ? (bookingDocs ?? []).filter(\n (booking: any) => normalizeContactEmail(booking.email) === bookerFilter,\n )\n : upcoming\n\n /**\n * The 24-hour reminder queue (AGL-2431).\n *\n * Reminders are sent by the `booking-reminders` beat, not by anything on\n * this page, and until that beat existed they were never sent at all — the\n * feature had a designed email template, white-label branding and an\n * `x-cron-secret` door, and no scheduler pointed at it. So the merchant had\n * no way to tell working from broken, and still would not if this card\n * merely asserted that reminders happen.\n *\n * READ-ONLY, and deliberately no \"send now\" button: the beat runs hourly\n * and stamps `reminderSentAt`, so a manual sender would race it for a\n * reminder nobody can un-send. Same call AGL-2227 made for the recovery\n * queue.\n *\n * `isBookingReminderDue` is the sender's own predicate, against one instant\n * shared by both counts, so this is the queue the next pass will drain\n * rather than an approximation of it.\n */\n const reminderNowMs = Date.now()\n const reminderQueue = (bookingDocs ?? []).filter((booking: any) =>\n isBookingReminderDue(booking, reminderNowMs),\n ).length\n const remindersSent = (bookingDocs ?? []).filter(\n (booking: any) => booking.reminderSentAt,\n ).length\n\n const [draft, setDraft] = useState<ServiceDraft | null>(null)\n\n const handleAdd = useCallback(() => {\n if (!entitled) {\n return void enqueueSnackbar(\n 'Bookings require a Starter plan — see Billing to upgrade',\n { variant: 'warning', persist: false },\n )\n }\n const quota = checkQuota(org, 'servicesPerHost', services.length)\n if (!quota.allowed) {\n return void enqueueSnackbar(\n `Service limit reached (${quota.limit}) — upgrade in Billing`,\n { variant: 'warning', persist: false },\n )\n }\n setDraft({\n id: null,\n ...newBookingServiceDraft(\n Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC',\n ),\n })\n }, [entitled, org, services.length, enqueueSnackbar])\n\n const handleSave = useCallback(async () => {\n if (!draft || !draft.name.trim()) return\n // The one rule for what a save stores, which the native editors share.\n const fields = bookingServiceFields(draft)\n try {\n if (draft.id) {\n /**\n * Edit stays client-direct (no quota consumed) — and is refused when\n * its seed was never confirmed by the server (AGL-1358). `fields` is\n * every editable key of the stored service, `windows` included, so\n * `merge: true` has nothing left to protect.\n *\n * The guard WRAPS the write. An early return is a shape you can keep\n * while losing the protection; here the write is only reachable\n * through the verdict.\n */\n const verdict = await writeGuardedBySeed(\n {\n subject: 'service',\n unreadable: servicesStatus === 'error',\n fromCache: servicesFromCache,\n },\n async () => {\n await setDoc(\n doc(firestore, 'hosts', hostId, 'services', draft.id),\n { ...fields, updatedAt: Timestamp.now() },\n { merge: true },\n )\n },\n )\n // Before `setDraft(null)`, so a refusal keeps the dialog open with\n // every window that was typed. A save that silently does nothing\n // sends the user back to retype a form that will be refused again\n // just as quietly.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n } else {\n // New service rides the quota-enforcing resources API (AGL-473) —\n // it also re-checks the `bookings` entitlement server-side.\n await createHostResource({ hostId, resource: 'service', data: fields })\n }\n setDraft(null)\n enqueueSnackbar('Service saved', { variant: 'success', persist: false })\n } catch (error: any) {\n console.error(error)\n enqueueSnackbar(error?.message ?? 'An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n }, [\n draft,\n firestore,\n hostId,\n createHostResource,\n enqueueSnackbar,\n servicesStatus,\n servicesFromCache,\n ])\n\n /**\n * A draft is activated here, and only here (AGL-3616): a service a draft\n * writer made is set up and offered nowhere until a person looks at it and\n * says it takes bookings. Deactivating sends a live one back to draft,\n * which takes it off the site without deleting it; bookings it already\n * holds stand. One field, so the seed guard the dialog's whole-document\n * save needs has nothing to protect here.\n */\n const handleServiceStatus = useCallback(\n (service: any, status: BookingServiceStatus) => async () => {\n try {\n await updateDoc(doc(firestore, 'hosts', hostId, 'services', service.$id), {\n status,\n updatedAt: Timestamp.now(),\n })\n enqueueSnackbar(\n status === 'active'\n ? `${service.name} now takes bookings`\n : `${service.name} is a draft — it takes no bookings until activated`,\n { variant: 'success', persist: false },\n )\n } catch (error: any) {\n console.error(error)\n enqueueSnackbar(error?.message ?? 'An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n },\n [firestore, hostId, enqueueSnackbar],\n )\n\n const handleDeleteService = useCallback(\n (service: any) => async () => {\n const confirmed = await confirm({\n title: 'Delete this service?',\n description: `\"${service.name}\" stops accepting bookings.`,\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await updateDoc(doc(firestore, 'hosts', hostId, 'services', service.$id), {\n deletedAt: Timestamp.now(),\n })\n },\n [confirm, firestore, hostId],\n )\n\n /**\n * Cancelling a PAID booking refunds the guest (AGL-2315).\n *\n * This used to be one `updateDoc` writing `status: 'canceled'`, for a paid\n * booking exactly as for a free one. The slot reopened, the appointment was\n * gone, and the guest had paid for it — the money moved nowhere and nothing\n * in the console said so. That was survivable only while the charge settled\n * in Aglyn's own balance and could be given back by hand; a paid booking is\n * a destination charge now, so the funds are at the MERCHANT and there is no\n * later opportunity to notice.\n *\n * So a paid booking cancels through the refund route, which reverses the\n * merchant's share and Aglyn's fee, and which sets `canceled` itself once\n * the money is actually back. A FAILED refund deliberately leaves the\n * booking standing: a cancelled-and-unrefunded appointment is the worst of\n * the three outcomes, and an admin who sees the row still there knows the\n * cancel did not happen.\n */\n const handleCancelBooking = useCallback(\n (booking: any) => async () => {\n const paidCents = Math.max(0, Number(booking.paidAmountCents ?? 0))\n const refundedCents = Math.max(0, Number(booking.refundedCents ?? 0))\n const outstandingCents = Math.max(0, paidCents - refundedCents)\n const refundable = outstandingCents > 0\n const confirmed = await confirm({\n title: 'Cancel this booking?',\n description:\n `${booking.name} (${booking.email}) — the slot reopens.` +\n (refundable\n ? ` $${(outstandingCents / 100).toFixed(2)} is refunded to them` +\n ' through Stripe.'\n : ''),\n confirmationText: refundable ? 'Cancel and refund' : 'Cancel booking',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n\n if (refundable) {\n // `randomUUID` needs a secure context, which the console always is,\n // but fall back rather than throw on a refund.\n const attemptKey =\n globalThis.crypto?.randomUUID?.() ??\n `${Date.now()}-${Math.random().toString(36).slice(2)}`\n try {\n const response = await authorizedFetch(user, '/api/bookings/refund', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Idempotency-Key': attemptKey,\n },\n body: JSON.stringify({ hostId, bookingId: booking.$id }),\n })\n const payload = await response.json().catch(() => null)\n if (!response.ok) {\n // A 409 is a guard REFUSING with a body that says what to do\n // instead — a booking paid before the PaymentIntent was recorded\n // names the Stripe dashboard — not the refund machinery failing.\n // It surfaces verbatim, the AGL-1818 rule.\n enqueueSnackbar(payload?.error ?? 'Refund failed', {\n variant: response.status === 409 ? 'warning' : 'error',\n allowDuplicate: true,\n })\n // The booking stays. See the note above: cancelled-and-unrefunded\n // is worse than not cancelled.\n return\n }\n // The route wrote `canceled` itself once the money was back.\n enqueueSnackbar('Booking canceled and refunded', {\n variant: 'success',\n persist: false,\n })\n return\n } catch {\n enqueueSnackbar('Refund failed — the booking was not canceled', {\n variant: 'error',\n allowDuplicate: true,\n })\n return\n }\n }\n\n // Through the cancel route (AGL-3643), not a direct write: the route\n // holds the rule that a paid booking cancels through its refund, and\n // tells the plugins listening for `booking.canceled`.\n try {\n const response = await authorizedFetch(user, '/api/bookings/cancel', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId, bookingId: booking.$id }),\n })\n const payload = await response.json().catch(() => null)\n if (!response.ok) {\n enqueueSnackbar(payload?.error ?? 'The booking was not canceled', {\n variant: response.status === 409 ? 'warning' : 'error',\n allowDuplicate: true,\n })\n return\n }\n } catch {\n enqueueSnackbar('The booking was not canceled', {\n variant: 'error',\n allowDuplicate: true,\n })\n return\n }\n enqueueSnackbar('Booking canceled', {\n variant: 'success',\n persist: false,\n })\n },\n [confirm, hostId, enqueueSnackbar, user],\n )\n\n return (\n <Stack spacing={3}>\n <CardDisplay\n header={'Services'}\n help={pluginDocsHelp('bookings', {\n anchor: '#set-up-bookings',\n excerpt:\n 'The bookable services this site offers — how long each takes, ' +\n 'what it costs, and the hours it can be booked in.',\n })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n {services.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Define a bookable service — duration, price, and weekly ' +\n 'availability — then visitors can book from your site.'}\n </Typography>\n ) : (\n services.map((service: any) => (\n <Stack\n key={service.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center', minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {service.name}\n </Typography>\n {bookingServiceStatus(service.status) === 'draft' ? (\n <Tooltip title=\"Set up, and offered nowhere until you activate it\">\n <Chip label=\"Draft\" size=\"small\" />\n </Tooltip>\n ) : null}\n </Stack>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {`${service.durationMinutes} min · ${bookingPriceText(service).replace(/^Free$/, 'free')}` +\n ` · ${service.timezone ?? 'UTC'}`}\n </Typography>\n </Stack>\n <Button\n size=\"small\"\n onClick={() =>\n setDraft({\n id: service.$id,\n ...bookingServiceDraftFrom(service),\n })\n }\n >\n {'Edit'}\n </Button>\n {bookingServiceStatus(service.status) === 'draft' ? (\n <Button\n size=\"small\"\n color=\"primary\"\n onClick={handleServiceStatus(service, 'active')}\n >\n {'Activate'}\n </Button>\n ) : (\n <Button size=\"small\" onClick={handleServiceStatus(service, 'draft')}>\n {'Deactivate'}\n </Button>\n )}\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleDeleteService(service)}\n >\n {'Delete'}\n </Button>\n </Stack>\n ))\n )}\n <Button\n size=\"small\"\n color=\"primary\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={handleAdd}\n >\n {'Add service'}\n </Button>\n {/* The cap, standing rather than only on refusal (AGL-2113).\n `services.length` is the same count `handleAdd` hands to\n `checkQuota`, so the readout and the gate cannot disagree. */}\n <QuotaReadoutComponent\n ready={org != null}\n used={services.length}\n limit={checkQuota(org, 'servicesPerHost', services.length).limit}\n noun=\"service\"\n />\n </Stack>\n </CardDisplay>\n\n <CardDisplay\n header={bookerFilter ? `Bookings for ${bookerFilter}` : 'Upcoming bookings'}\n help={pluginDocsHelp('bookings', {\n anchor: '#manage',\n excerpt:\n 'Bookings taken on this site, with the customer and the slot each ' +\n 'one holds.',\n })}\n contentGutterX\n contentGutterY\n HeaderProps={{\n action: transferLauncher?.can('export', { resource: BOOKINGS_TRANSFER_RESOURCE, scope: 'host', hostId }) ? (\n <Button size=\"small\" color=\"primary\" onClick={handleExport}>\n {'Export'}\n </Button>\n ) : undefined,\n }}\n >\n {bookerFilter ? (\n <Typography\n variant=\"caption\"\n color=\"text.secondary\"\n component=\"div\"\n sx={{ mb: 1 }}\n >\n {'Every booking this address holds, newest first. '}\n {basePath ? <AppLink href={basePath}>{'Show upcoming bookings'}</AppLink> : null}\n </Typography>\n ) : null}\n {/* What the reminder beat will do next, and what it has done. Named\n \"24-hour reminders\" rather than \"emails\" because that is the only\n mail this queue governs — confirmations go out on booking. */}\n <Typography\n variant=\"caption\"\n color=\"text.secondary\"\n component=\"div\"\n sx={{ mb: 1 }}\n >\n {`24-hour reminders · ${reminderQueue} due in the next pass · ` +\n `${remindersSent} already sent`}\n {/* Its OWN heading, not the card's `#manage`: a merchant reading\n this line wants the timing and the once-only rule, and landing\n them on \"manage your bookings\" is the presence-not-correctness\n failure a help-coverage check cannot see. */}\n <HelpTip\n {...pluginDocsHelp('bookings', { anchor: '#reminders' })}\n sx={{ ml: 0.5, fontSize: '0.9em' }}\n />\n </Typography>\n {shown.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {bookerFilter ? 'No bookings for this address.' : 'No upcoming bookings.'}\n </Typography>\n ) : (\n <Stack spacing={1}>\n {shown.map((booking: any) => (\n <Stack\n key={booking.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {`${booking.serviceName} — ${booking.name}`}\n {booking.status === 'canceled' ? ' (canceled)' : ''}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {`${new Date(booking.startsAtMs).toLocaleString()} · ${\n booking.email\n }`}\n {typeof booking.phone === 'string' && booking.phone\n ? ` · ${booking.phone}`\n : ''}\n </Typography>\n {/* Where the job is, when the service asked (AGL-3493).\n Wrapped rather than cut: an address read to its end is\n the one a crew can drive to. */}\n {typeof booking.address === 'string' && booking.address ? (\n <Typography\n variant=\"caption\"\n color=\"text.secondary\"\n sx={{ whiteSpace: 'pre-line' }}\n >\n {booking.address}\n </Typography>\n ) : null}\n </Stack>\n <PaymentRiskChip risk={booking.paymentRisk} />\n {contactHrefOf(booking.email) ? (\n <Button\n component={AppLink as any}\n {...({ componentVariant: 'naked', nativeButton: false } as any)}\n href={contactHrefOf(booking.email) ?? undefined}\n size=\"small\"\n >\n {'View in CRM'}\n </Button>\n ) : null}\n {booking.status !== 'canceled' ? (\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleCancelBooking(booking)}\n >\n {'Cancel'}\n </Button>\n ) : null}\n </Stack>\n ))}\n </Stack>\n )}\n </CardDisplay>\n\n <Dialog\n open={Boolean(draft)}\n onClose={() => setDraft(null)}\n maxWidth=\"sm\"\n fullWidth\n >\n <DialogTitle>{draft?.id ? 'Edit service' : 'Add service'}</DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 1.5, pt: 1 }}\n >\n <TextField\n label=\"Name\"\n value={draft?.name ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, name: event.target.value } : prev,\n )\n }\n size=\"small\"\n autoFocus\n sx={{ mt: 1 }}\n />\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Duration (minutes)\"\n value={draft?.durationMinutes ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? {\n ...prev,\n durationMinutes: event.target.value.replace(\n /[^0-9]/g,\n '',\n ),\n }\n : prev,\n )\n }\n size=\"small\"\n />\n <TextField\n label=\"Price (USD, 0 = free)\"\n // WHAT THIS PRICE DOES NOT INCLUDE (AGL-2028).\n //\n // A paid booking is charged exactly this figure: the handler\n // sends no tax parameter at all, by a stated decision (AGL-2000)\n // — whether a service is taxable is jurisdiction-specific and\n // frequently the opposite answer from goods, so applying the\n // commerce plugin's GOODS sales rate would be confidently wrong\n // rather than merely absent.\n //\n // That decision was recorded in the source and in the\n // `storefrontTaxCollected` ledger, and in neither place can the\n // merchant see it. A service business is one of the three named\n // ICPs, and one who configured a rate in Commerce → Settings →\n // Taxes has every reason to assume it covers the appointments\n // they sell on the same site. Saying so here is the half of\n // AGL-2028 that holds however the rate question is answered.\n //\n // States the MECHANISM and makes no remittance determination —\n // the same line `describeOrderTaxMode` holds. Who owes which\n // authority what attaches by operation of law and is counsel's\n // call (AGL-1904/AGL-1956).\n helperText={\n draft && draft.priceDisplay !== 'fixed'\n ? `Not charged: this service shows “${BOOKING_PRICE_LABELS[draft.priceDisplay]}” and books with no charge.`\n : `${PLATFORM_BRAND_NAME} charges this price as typed — no tax is added. Your Commerce tax settings are a goods sales rate and do not apply to bookings.`\n }\n value={draft?.priceUsd ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? {\n ...prev,\n priceUsd: event.target.value.replace(/[^0-9]/g, ''),\n }\n : prev,\n )\n }\n size=\"small\"\n />\n {/*\n A contractor who quotes at the job states the price as a label\n instead (AGL-3475). Any label books with no charge, like an\n estimate appointment, and the stored price is neither shown nor\n charged.\n */}\n <TextField\n select\n label=\"Show the price as\"\n value={draft?.priceDisplay ?? 'fixed'}\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? { ...prev, priceDisplay: bookingPriceDisplay(event.target.value) }\n : prev,\n )\n }\n size=\"small\"\n sx={{ minWidth: 180 }}\n >\n {BOOKING_PRICE_DISPLAYS.map((display) => (\n <MenuItem key={display} value={display}>\n {PRICE_DISPLAY_LABELS[display]}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n label=\"Timezone\"\n value={draft?.timezone ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, timezone: event.target.value } : prev,\n )\n }\n size=\"small\"\n sx={{ minWidth: 180 }}\n />\n </Stack>\n <TextField\n label=\"Description (optional)\"\n value={draft?.description ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev ? { ...prev, description: event.target.value } : prev,\n )\n }\n size=\"small\"\n multiline\n minRows={2}\n />\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Weekly availability'}\n </Typography>\n {WEEKDAYS.map((day, index) => (\n <TextField\n key={day}\n label={day}\n placeholder=\"09:00-12:00, 13:00-17:00 (empty = closed)\"\n value={draft?.windowText[index] ?? ''}\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? {\n ...prev,\n windowText: prev.windowText.map((text, i) =>\n i === index ? event.target.value : text,\n ),\n }\n : prev,\n )\n }\n size=\"small\"\n />\n ))}\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Booking form'}\n </Typography>\n {/*\n What the widget asks for beyond a name and an email (AGL-3493).\n Off by default; an on-site service asks for both, required.\n */}\n <Stack direction={{ xs: 'column', sm: 'row' }} spacing={1}>\n {(\n [\n ['askPhone', 'Phone number'],\n ['askAddress', 'Address'],\n ] as const\n ).map(([key, label]) => (\n <TextField\n key={key}\n select\n label={label}\n value={draft?.[key] ?? 'off'}\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? { ...prev, [key]: event.target.value as BookingFieldAsk }\n : prev,\n )\n }\n size=\"small\"\n fullWidth\n >\n {BOOKING_FIELD_ASKS.map((ask) => (\n <MenuItem key={ask} value={ask}>\n {FIELD_ASK_LABELS[ask]}\n </MenuItem>\n ))}\n </TextField>\n ))}\n </Stack>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'CRM'}\n </Typography>\n {/*\n What a booking of this service does to the booker's CRM record\n (AGL-2660). The meeting is on by default — a booking IS a\n meeting the record has — and the follow-up is the service's\n choice, because not every service earns a call afterwards.\n */}\n <FormControlLabel\n control={\n <Switch\n checked={draft?.crmMeetingActivity ?? true}\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? { ...prev, crmMeetingActivity: event.target.checked }\n : prev,\n )\n }\n size=\"small\"\n />\n }\n label=\"Log a meeting on the CRM record when this service is booked\"\n />\n <FormControlLabel\n control={\n <Switch\n checked={draft?.crmFollowUpTask ?? false}\n onChange={(event) =>\n setDraft((prev) =>\n prev\n ? { ...prev, crmFollowUpTask: event.target.checked }\n : prev,\n )\n }\n size=\"small\"\n />\n }\n label=\"Create a follow-up task on the CRM record when this service is booked\"\n />\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'The follow-up is due one business day after the slot, on whoever ' +\n 'owns the record. Nothing is filed on a site whose CRM is off.'}\n </Typography>\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!draft?.name.trim()}\n onClick={handleSave}\n >\n {'Save service'}\n </Button>\n </DialogActions>\n </Dialog>\n </Stack>\n )\n}\nBookingsConsolePage.displayName = 'BookingsConsolePage'\n\nexport default BookingsConsolePage\n"],"names":["checkQuota","pluginDocsHelp","useTransferLauncher","normalizeContactEmail","pluginRecordByEmailHref","BOOKINGS_BOOKER_PARAM","BOOKINGS_TRANSFER_RESOURCE","bookerBookingsFilterValue","upcomingBookingsFilterValue","PLATFORM_BRAND_NAME","describePaymentRisk","isBookingReminderDue","BOOKING_WEEKDAYS","bookingServiceDraftFrom","bookingServiceFields","newBookingServiceDraft","bookingServiceStatus","BOOKING_FIELD_ASKS","BOOKING_PRICE_DISPLAYS","BOOKING_PRICE_LABELS","bookingPriceDisplay","bookingPriceText","AppLink","CardDisplay","HelpTip","useConfirmationContext","QuotaReadoutComponent","useSnackbar","Timestamp","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","FormControlLabel","MenuItem","Stack","Switch","TextField","Tooltip","Typography","collection","doc","limit","orderBy","query","setDoc","updateDoc","useParams","useSearchParams","useCallback","useState","useFirestore","useFirestoreCollection","useHostResourceApi","useUser","writeGuardedBySeed","authorizedFetch","WEEKDAYS","PRICE_DISPLAY_LABELS","fixed","FIELD_ASK_LABELS","off","optional","required","PaymentRiskChip","risk","described","title","detail","label","size","color","BookingsConsolePage","props","hostId","entitled","org","firestore","createHostResource","enqueueSnackbar","confirm","data","user","params","siteContext","orgSlug","host","String","contactHrefOf","email","searchParams","bookerFilter","get","basePath","transferLauncher","handleExport","openExport","resource","scope","filter","value","Date","now","serviceDocs","status","servicesStatus","fromCache","servicesFromCache","idField","bookingDocs","services","service","deletedAt","sort","a","b","name","localeCompare","upcoming","booking","endsAtMs","startsAtMs","shown","reminderNowMs","reminderQueue","length","remindersSent","reminderSentAt","draft","setDraft","handleAdd","variant","persist","quota","allowed","id","Intl","DateTimeFormat","resolvedOptions","timeZone","handleSave","trim","fields","verdict","subject","unreadable","updatedAt","merge","ok","message","error","console","allowDuplicate","handleServiceStatus","$id","handleDeleteService","confirmed","description","confirmationText","confirmationButtonProps","then","catch","handleCancelBooking","paidCents","Math","max","Number","paidAmountCents","refundedCents","outstandingCents","refundable","toFixed","globalThis","attemptKey","crypto","randomUUID","random","toString","slice","response","method","headers","body","JSON","stringify","bookingId","payload","json","spacing","header","help","anchor","excerpt","contentGutterX","contentGutterY","map","direction","sx","alignItems","flex","minWidth","noWrap","durationMinutes","replace","timezone","onClick","alignSelf","ready","used","noun","HeaderProps","action","can","undefined","component","mb","href","ml","fontSize","serviceName","toLocaleString","phone","address","whiteSpace","paymentRisk","componentVariant","nativeButton","open","Boolean","onClose","maxWidth","fullWidth","display","flexDirection","gap","pt","onChange","event","prev","target","autoFocus","mt","helperText","priceDisplay","priceUsd","select","multiline","minRows","day","index","placeholder","windowText","text","i","xs","sm","key","ask","control","checked","crmMeetingActivity","crmFollowUpTask","disabled","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAASA,UAAU,EAAEC,cAAc,EAAEC,mBAAmB,QAAQ,eAAc;AAC9E,SAASC,qBAAqB,QAAQ,eAAc;AACpD,SAASC,uBAAuB,QAAQ,mDAAkD;AAC1F,SAASC,qBAAqB,QAAQ,qCAAiC;AACvE,SACEC,0BAA0B,EAC1BC,yBAAyB,EACzBC,2BAA2B,QACtB,0CAAsC;AAC7C,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,mBAAmB,QAA0B,sCAAqC;AAE3F,SAASC,oBAAoB,QAAQ,oBAAU;AAC/C,SACEC,gBAAgB,EAEhBC,uBAAuB,EACvBC,oBAAoB,EACpBC,sBAAsB,QACjB,mCAA+B;AACtC,SAAoCC,oBAAoB,QAAQ,uBAAmB;AACnF,SACEC,kBAAkB,QAEb,qCAAiC;AACxC,SACEC,sBAAsB,EACtBC,oBAAoB,EAEpBC,mBAAmB,EACnBC,gBAAgB,QACX,4BAAwB;AAC/B,SAASC,OAAO,EAAEC,WAAW,EAAEC,OAAO,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC5F,OAAOC,2BAA2B,0DAAyD;AAC3F,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,SAAS,QAAQ,+BAA8B;AACxD,SACEC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,gBAA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tC;gCACCiO,uBACE,KAAC9N;oCACC+N,OAAO,WAAEnI,yBAAAA,MAAOoI,kBAAkB,oBAAI;oCACtCxB,UAAU,CAACC,QACT5G,SAAS,CAAC6G,OACRA,OACI,aAAKA;gDAAMsB,oBAAoBvB,MAAME,MAAM,CAACoB,OAAO;iDACnDrB;oCAGRxK,MAAK;;gCAGTD,OAAM;;0CAER,KAACpC;gCACCiO,uBACE,KAAC9N;oCACC+N,OAAO,WAAEnI,yBAAAA,MAAOqI,eAAe,oBAAI;oCACnCzB,UAAU,CAACC,QACT5G,SAAS,CAAC6G,OACRA,OACI,aAAKA;gDAAMuB,iBAAiBxB,MAAME,MAAM,CAACoB,OAAO;iDAChDrB;oCAGRxK,MAAK;;gCAGTD,OAAM;;0CAER,KAAC9B;gCAAW4F,SAAQ;gCAAU5D,OAAM;0CACjC,sEACC;;;;kCAGN,MAACzC;;0CACC,KAACH;gCAAOkL,SAAS,IAAM5E,SAAS;0CAAQ;;0CACxC,KAACtG;gCACCwG,SAAQ;gCACR5D,OAAM;gCACN+L,UAAU,EAACtI,yBAAAA,MAAOZ,IAAI,CAACyB,IAAI;gCAC3BgE,SAASjE;0CAER;;;;;;;;AAMb;AACApE,oBAAoB+L,WAAW,GAAG;AAElC,eAAe/L,oBAAmB"}
@@ -0,0 +1,104 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { type BookingFieldAsk } from './booking-contact-fields';
18
+ import { type BookingPriceDisplay } from './booking-price';
19
+ /**
20
+ * THE SERVICE DIALOG'S RULES: what a service's editor starts from and what
21
+ * one save stores in `hosts/{hostId}/services/{id}`. The console's Bookings
22
+ * page and the native apps' service editors both hand their form to
23
+ * {@link bookingServiceFields} and store exactly what it answers (the apps
24
+ * replay its cases), so a duration is clamped, a price rounded and an
25
+ * hours line read the same way whichever of them saved it.
26
+ *
27
+ * Pure: no Firestore, no clock, no React.
28
+ */
29
+ /** The weekday names the dialog labels each hours line with, Sunday first (`windows` keys 0–6). */
30
+ export declare const BOOKING_WEEKDAYS: readonly string[];
31
+ /** One open interval on a weekday, in minutes since midnight in the service's zone. */
32
+ export interface BookingWindow {
33
+ start: number;
34
+ end: number;
35
+ }
36
+ /** Longest stored service name. */
37
+ export declare const BOOKING_SERVICE_NAME_MAX = 80;
38
+ /** Longest stored service description. */
39
+ export declare const BOOKING_SERVICE_DESCRIPTION_MAX = 500;
40
+ /** The service dialog's fields as typed: numbers and hours are text until saved. */
41
+ export interface BookingServiceDraft {
42
+ name: string;
43
+ durationMinutes: string;
44
+ priceUsd: string;
45
+ timezone: string;
46
+ description: string;
47
+ /** Per-weekday hours, Sunday first, e.g. "09:00-12:00, 13:00-17:00". */
48
+ windowText: string[];
49
+ crmMeetingActivity: boolean;
50
+ crmFollowUpTask: boolean;
51
+ askPhone: BookingFieldAsk;
52
+ askAddress: BookingFieldAsk;
53
+ priceDisplay: BookingPriceDisplay;
54
+ }
55
+ /** What one save stores: every editable key of the service, written explicitly. */
56
+ export type BookingServiceFields = {
57
+ name: string;
58
+ durationMinutes: number;
59
+ priceUsd: number;
60
+ timezone: string;
61
+ /** `''` when cleared, so a merge does not keep the old text. */
62
+ description: string;
63
+ /** Every weekday, 0–6, with `[]` for a closed day. */
64
+ windows: Record<string, BookingWindow[]>;
65
+ crmMeetingActivity: boolean;
66
+ crmFollowUpTask: boolean;
67
+ askPhone: BookingFieldAsk;
68
+ askAddress: BookingFieldAsk;
69
+ priceDisplay: BookingPriceDisplay;
70
+ };
71
+ /** "09:00-12:00, 13:00-17:00" → open intervals in minutes; anything unreadable is skipped. */
72
+ export declare function parseBookingWindows(input: string): BookingWindow[];
73
+ /** Open intervals → "09:00-12:00, 13:00-17:00". */
74
+ export declare function formatBookingWindows(windows: readonly BookingWindow[] | null | undefined): string;
75
+ /**
76
+ * A new service's dialog: thirty minutes, free, the editor's own zone, open
77
+ * nine to five on weekdays, a meeting on the contact's record and no
78
+ * follow-up, and only name and email asked.
79
+ */
80
+ export declare function newBookingServiceDraft(timeZone: string): BookingServiceDraft;
81
+ /** The dialog seeded from a stored service, so its switches show what the service does. */
82
+ export declare function bookingServiceDraftFrom(service: {
83
+ name?: unknown;
84
+ durationMinutes?: unknown;
85
+ priceUsd?: unknown;
86
+ timezone?: unknown;
87
+ description?: unknown;
88
+ windows?: Partial<Record<number | string, BookingWindow[]>> | null;
89
+ crmMeetingActivity?: unknown;
90
+ crmFollowUpTask?: unknown;
91
+ askPhone?: unknown;
92
+ askAddress?: unknown;
93
+ priceDisplay?: unknown;
94
+ }): BookingServiceDraft;
95
+ /** Why the dialog cannot save, or null. */
96
+ export declare function bookingServiceDraftProblem(draft: Pick<BookingServiceDraft, 'name'>): string | null;
97
+ /**
98
+ * What one save stores. Every editable key is written explicitly, because
99
+ * the edit is a `merge` and an absent key would keep its stored value: a
100
+ * switch turned off has to land `false`, and a weekday cleared has to land
101
+ * `[]`, or the old hours would go on taking bookings; a description
102
+ * cleared lands `''` for the same reason.
103
+ */
104
+ export declare function bookingServiceFields(draft: BookingServiceDraft): BookingServiceFields;
@@ -0,0 +1,131 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ import { bookingContactAsks } from "./booking-contact-fields.js";
17
+ import { bookingPriceDisplay } from "./booking-price.js";
18
+ /**
19
+ * THE SERVICE DIALOG'S RULES: what a service's editor starts from and what
20
+ * one save stores in `hosts/{hostId}/services/{id}`. The console's Bookings
21
+ * page and the native apps' service editors both hand their form to
22
+ * {@link bookingServiceFields} and store exactly what it answers (the apps
23
+ * replay its cases), so a duration is clamped, a price rounded and an
24
+ * hours line read the same way whichever of them saved it.
25
+ *
26
+ * Pure: no Firestore, no clock, no React.
27
+ */ /** The weekday names the dialog labels each hours line with, Sunday first (`windows` keys 0–6). */ export const BOOKING_WEEKDAYS = [
28
+ 'Sun',
29
+ 'Mon',
30
+ 'Tue',
31
+ 'Wed',
32
+ 'Thu',
33
+ 'Fri',
34
+ 'Sat'
35
+ ];
36
+ /** Longest stored service name. */ export const BOOKING_SERVICE_NAME_MAX = 80;
37
+ /** Longest stored service description. */ export const BOOKING_SERVICE_DESCRIPTION_MAX = 500;
38
+ /** "09:00-12:00, 13:00-17:00" → open intervals in minutes; anything unreadable is skipped. */ export function parseBookingWindows(input) {
39
+ const windows = [];
40
+ for (const chunk of String(input != null ? input : '').split(',')){
41
+ const match = chunk.trim().match(/^(\d{1,2}):(\d{2})\s*-\s*(\d{1,2}):(\d{2})$/);
42
+ if (!match) continue;
43
+ const start = Number(match[1]) * 60 + Number(match[2]);
44
+ const end = Number(match[3]) * 60 + Number(match[4]);
45
+ if (end > start && end <= 24 * 60) windows.push({
46
+ start,
47
+ end
48
+ });
49
+ }
50
+ return windows;
51
+ }
52
+ /** Open intervals → "09:00-12:00, 13:00-17:00". */ export function formatBookingWindows(windows) {
53
+ const pad = (minutes)=>`${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`;
54
+ return (windows != null ? windows : []).map((window)=>`${pad(window.start)}-${pad(window.end)}`).join(', ');
55
+ }
56
+ /**
57
+ * A new service's dialog: thirty minutes, free, the editor's own zone, open
58
+ * nine to five on weekdays, a meeting on the contact's record and no
59
+ * follow-up, and only name and email asked.
60
+ */ export function newBookingServiceDraft(timeZone) {
61
+ return {
62
+ name: '',
63
+ durationMinutes: '30',
64
+ priceUsd: '0',
65
+ timezone: timeZone || 'UTC',
66
+ description: '',
67
+ windowText: BOOKING_WEEKDAYS.map((_, index)=>index >= 1 && index <= 5 ? '09:00-17:00' : ''),
68
+ crmMeetingActivity: true,
69
+ crmFollowUpTask: false,
70
+ askPhone: 'off',
71
+ askAddress: 'off',
72
+ priceDisplay: 'fixed'
73
+ };
74
+ }
75
+ /** The dialog seeded from a stored service, so its switches show what the service does. */ export function bookingServiceDraftFrom(service) {
76
+ var _service_durationMinutes, _service_priceUsd;
77
+ const asks = bookingContactAsks(service);
78
+ return {
79
+ name: typeof service.name === 'string' ? service.name : '',
80
+ durationMinutes: String((_service_durationMinutes = service.durationMinutes) != null ? _service_durationMinutes : 30),
81
+ priceUsd: String((_service_priceUsd = service.priceUsd) != null ? _service_priceUsd : 0),
82
+ timezone: typeof service.timezone === 'string' ? service.timezone : 'UTC',
83
+ description: typeof service.description === 'string' ? service.description : '',
84
+ windowText: BOOKING_WEEKDAYS.map((_, index)=>{
85
+ var _service_windows;
86
+ return formatBookingWindows((_service_windows = service.windows) == null ? void 0 : _service_windows[index]);
87
+ }),
88
+ // Absent reads as ON for the meeting and OFF for the follow-up: the
89
+ // model's defaults.
90
+ crmMeetingActivity: service.crmMeetingActivity !== false,
91
+ crmFollowUpTask: service.crmFollowUpTask === true,
92
+ askPhone: asks.phone,
93
+ askAddress: asks.address,
94
+ priceDisplay: bookingPriceDisplay(service.priceDisplay)
95
+ };
96
+ }
97
+ /** Why the dialog cannot save, or null. */ export function bookingServiceDraftProblem(draft) {
98
+ var _draft_name;
99
+ return String((_draft_name = draft.name) != null ? _draft_name : '').trim() ? null : 'A service needs a name.';
100
+ }
101
+ /**
102
+ * What one save stores. Every editable key is written explicitly, because
103
+ * the edit is a `merge` and an absent key would keep its stored value: a
104
+ * switch turned off has to land `false`, and a weekday cleared has to land
105
+ * `[]`, or the old hours would go on taking bookings; a description
106
+ * cleared lands `''` for the same reason.
107
+ */ export function bookingServiceFields(draft) {
108
+ var _draft_description, _draft_name, _draft_timezone;
109
+ const windows = {};
110
+ BOOKING_WEEKDAYS.forEach((_, weekday)=>{
111
+ var _ref;
112
+ var _draft_windowText;
113
+ windows[String(weekday)] = parseBookingWindows((_ref = (_draft_windowText = draft.windowText) == null ? void 0 : _draft_windowText[weekday]) != null ? _ref : '');
114
+ });
115
+ const description = String((_draft_description = draft.description) != null ? _draft_description : '').trim();
116
+ return {
117
+ name: String((_draft_name = draft.name) != null ? _draft_name : '').trim().slice(0, BOOKING_SERVICE_NAME_MAX),
118
+ durationMinutes: Math.max(5, Math.min(480, Math.round(Number(draft.durationMinutes) || 30))),
119
+ priceUsd: Math.max(0, Math.round(Number(draft.priceUsd) || 0)),
120
+ timezone: String((_draft_timezone = draft.timezone) != null ? _draft_timezone : '').trim() || 'UTC',
121
+ description: description.slice(0, BOOKING_SERVICE_DESCRIPTION_MAX),
122
+ windows,
123
+ crmMeetingActivity: draft.crmMeetingActivity,
124
+ crmFollowUpTask: draft.crmFollowUpTask,
125
+ askPhone: draft.askPhone,
126
+ askAddress: draft.askAddress,
127
+ priceDisplay: draft.priceDisplay
128
+ };
129
+ }
130
+
131
+ //# sourceMappingURL=booking-service-form.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/model/booking-service-form.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type BookingFieldAsk, bookingContactAsks } from './booking-contact-fields'\nimport { type BookingPriceDisplay, bookingPriceDisplay } from './booking-price'\n\n/**\n * THE SERVICE DIALOG'S RULES: what a service's editor starts from and what\n * one save stores in `hosts/{hostId}/services/{id}`. The console's Bookings\n * page and the native apps' service editors both hand their form to\n * {@link bookingServiceFields} and store exactly what it answers (the apps\n * replay its cases), so a duration is clamped, a price rounded and an\n * hours line read the same way whichever of them saved it.\n *\n * Pure: no Firestore, no clock, no React.\n */\n\n/** The weekday names the dialog labels each hours line with, Sunday first (`windows` keys 0–6). */\nexport const BOOKING_WEEKDAYS: readonly string[] = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']\n\n/** One open interval on a weekday, in minutes since midnight in the service's zone. */\nexport interface BookingWindow {\n start: number\n end: number\n}\n\n/** Longest stored service name. */\nexport const BOOKING_SERVICE_NAME_MAX = 80\n/** Longest stored service description. */\nexport const BOOKING_SERVICE_DESCRIPTION_MAX = 500\n\n/** The service dialog's fields as typed: numbers and hours are text until saved. */\nexport interface BookingServiceDraft {\n name: string\n durationMinutes: string\n priceUsd: string\n timezone: string\n description: string\n /** Per-weekday hours, Sunday first, e.g. \"09:00-12:00, 13:00-17:00\". */\n windowText: string[]\n crmMeetingActivity: boolean\n crmFollowUpTask: boolean\n askPhone: BookingFieldAsk\n askAddress: BookingFieldAsk\n priceDisplay: BookingPriceDisplay\n}\n\n/** What one save stores: every editable key of the service, written explicitly. */\nexport type BookingServiceFields = {\n name: string\n durationMinutes: number\n priceUsd: number\n timezone: string\n /** `''` when cleared, so a merge does not keep the old text. */\n description: string\n /** Every weekday, 0–6, with `[]` for a closed day. */\n windows: Record<string, BookingWindow[]>\n crmMeetingActivity: boolean\n crmFollowUpTask: boolean\n askPhone: BookingFieldAsk\n askAddress: BookingFieldAsk\n priceDisplay: BookingPriceDisplay\n}\n\n/** \"09:00-12:00, 13:00-17:00\" → open intervals in minutes; anything unreadable is skipped. */\nexport function parseBookingWindows(input: string): BookingWindow[] {\n const windows: BookingWindow[] = []\n for (const chunk of String(input ?? '').split(',')) {\n const match = chunk.trim().match(/^(\\d{1,2}):(\\d{2})\\s*-\\s*(\\d{1,2}):(\\d{2})$/)\n if (!match) continue\n const start = Number(match[1]) * 60 + Number(match[2])\n const end = Number(match[3]) * 60 + Number(match[4])\n if (end > start && end <= 24 * 60) windows.push({ start, end })\n }\n return windows\n}\n\n/** Open intervals → \"09:00-12:00, 13:00-17:00\". */\nexport function formatBookingWindows(windows: readonly BookingWindow[] | null | undefined): string {\n const pad = (minutes: number) =>\n `${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`\n return (windows ?? []).map((window) => `${pad(window.start)}-${pad(window.end)}`).join(', ')\n}\n\n/**\n * A new service's dialog: thirty minutes, free, the editor's own zone, open\n * nine to five on weekdays, a meeting on the contact's record and no\n * follow-up, and only name and email asked.\n */\nexport function newBookingServiceDraft(timeZone: string): BookingServiceDraft {\n return {\n name: '',\n durationMinutes: '30',\n priceUsd: '0',\n timezone: timeZone || 'UTC',\n description: '',\n windowText: BOOKING_WEEKDAYS.map((_, index) => (index >= 1 && index <= 5 ? '09:00-17:00' : '')),\n crmMeetingActivity: true,\n crmFollowUpTask: false,\n askPhone: 'off',\n askAddress: 'off',\n priceDisplay: 'fixed',\n }\n}\n\n/** The dialog seeded from a stored service, so its switches show what the service does. */\nexport function bookingServiceDraftFrom(service: {\n name?: unknown\n durationMinutes?: unknown\n priceUsd?: unknown\n timezone?: unknown\n description?: unknown\n windows?: Partial<Record<number | string, BookingWindow[]>> | null\n crmMeetingActivity?: unknown\n crmFollowUpTask?: unknown\n askPhone?: unknown\n askAddress?: unknown\n priceDisplay?: unknown\n}): BookingServiceDraft {\n const asks = bookingContactAsks(service)\n return {\n name: typeof service.name === 'string' ? service.name : '',\n durationMinutes: String(service.durationMinutes ?? 30),\n priceUsd: String(service.priceUsd ?? 0),\n timezone: typeof service.timezone === 'string' ? service.timezone : 'UTC',\n description: typeof service.description === 'string' ? service.description : '',\n windowText: BOOKING_WEEKDAYS.map((_, index) => formatBookingWindows(service.windows?.[index])),\n // Absent reads as ON for the meeting and OFF for the follow-up: the\n // model's defaults.\n crmMeetingActivity: service.crmMeetingActivity !== false,\n crmFollowUpTask: service.crmFollowUpTask === true,\n askPhone: asks.phone,\n askAddress: asks.address,\n priceDisplay: bookingPriceDisplay(service.priceDisplay),\n }\n}\n\n/** Why the dialog cannot save, or null. */\nexport function bookingServiceDraftProblem(draft: Pick<BookingServiceDraft, 'name'>): string | null {\n return String(draft.name ?? '').trim() ? null : 'A service needs a name.'\n}\n\n/**\n * What one save stores. Every editable key is written explicitly, because\n * the edit is a `merge` and an absent key would keep its stored value: a\n * switch turned off has to land `false`, and a weekday cleared has to land\n * `[]`, or the old hours would go on taking bookings; a description\n * cleared lands `''` for the same reason.\n */\nexport function bookingServiceFields(draft: BookingServiceDraft): BookingServiceFields {\n const windows: Record<string, BookingWindow[]> = {}\n BOOKING_WEEKDAYS.forEach((_, weekday) => {\n windows[String(weekday)] = parseBookingWindows(draft.windowText?.[weekday] ?? '')\n })\n const description = String(draft.description ?? '').trim()\n return {\n name: String(draft.name ?? '').trim().slice(0, BOOKING_SERVICE_NAME_MAX),\n durationMinutes: Math.max(5, Math.min(480, Math.round(Number(draft.durationMinutes) || 30))),\n priceUsd: Math.max(0, Math.round(Number(draft.priceUsd) || 0)),\n timezone: String(draft.timezone ?? '').trim() || 'UTC',\n description: description.slice(0, BOOKING_SERVICE_DESCRIPTION_MAX),\n windows,\n crmMeetingActivity: draft.crmMeetingActivity,\n crmFollowUpTask: draft.crmFollowUpTask,\n askPhone: draft.askPhone,\n askAddress: draft.askAddress,\n priceDisplay: draft.priceDisplay,\n }\n}\n"],"names":["bookingContactAsks","bookingPriceDisplay","BOOKING_WEEKDAYS","BOOKING_SERVICE_NAME_MAX","BOOKING_SERVICE_DESCRIPTION_MAX","parseBookingWindows","input","windows","chunk","String","split","match","trim","start","Number","end","push","formatBookingWindows","pad","minutes","Math","floor","padStart","map","window","join","newBookingServiceDraft","timeZone","name","durationMinutes","priceUsd","timezone","description","windowText","_","index","crmMeetingActivity","crmFollowUpTask","askPhone","askAddress","priceDisplay","bookingServiceDraftFrom","service","asks","phone","address","bookingServiceDraftProblem","draft","bookingServiceFields","forEach","weekday","slice","max","min","round"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAA+BA,kBAAkB,QAAQ,8BAA0B;AACnF,SAAmCC,mBAAmB,QAAQ,qBAAiB;AAE/E;;;;;;;;;CASC,GAED,iGAAiG,GACjG,OAAO,MAAMC,mBAAsC;IAAC;IAAO;IAAO;IAAO;IAAO;IAAO;IAAO;CAAM,CAAA;AAQpG,iCAAiC,GACjC,OAAO,MAAMC,2BAA2B,GAAE;AAC1C,wCAAwC,GACxC,OAAO,MAAMC,kCAAkC,IAAG;AAmClD,4FAA4F,GAC5F,OAAO,SAASC,oBAAoBC,KAAa;IAC/C,MAAMC,UAA2B,EAAE;IACnC,KAAK,MAAMC,SAASC,OAAOH,gBAAAA,QAAS,IAAII,KAAK,CAAC,KAAM;QAClD,MAAMC,QAAQH,MAAMI,IAAI,GAAGD,KAAK,CAAC;QACjC,IAAI,CAACA,OAAO;QACZ,MAAME,QAAQC,OAAOH,KAAK,CAAC,EAAE,IAAI,KAAKG,OAAOH,KAAK,CAAC,EAAE;QACrD,MAAMI,MAAMD,OAAOH,KAAK,CAAC,EAAE,IAAI,KAAKG,OAAOH,KAAK,CAAC,EAAE;QACnD,IAAII,MAAMF,SAASE,OAAO,KAAK,IAAIR,QAAQS,IAAI,CAAC;YAAEH;YAAOE;QAAI;IAC/D;IACA,OAAOR;AACT;AAEA,iDAAiD,GACjD,OAAO,SAASU,qBAAqBV,OAAoD;IACvF,MAAMW,MAAM,CAACC,UACX,GAAGV,OAAOW,KAA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