@aglyn/plugins-bookings 1.0.0-beta.285 → 1.0.0-beta.287

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.285",
3
+ "version": "1.0.0-beta.287",
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.285",
29
- "@aglyn/shared-data-mdi": "1.0.0-beta.285",
30
- "@aglyn/shared-ui-jsx": "1.0.0-beta.285",
31
- "@aglyn/shared-ui-snackstack": "1.0.0-beta.285",
32
- "@aglyn/shared-util-email": "1.0.0-beta.285",
33
- "@aglyn/shared-util-http": "1.0.0-beta.285",
34
- "@aglyn/shared-util-timestamp": "1.0.0-beta.285",
35
- "@aglyn/tenant-data-admin": "1.0.0-beta.285",
36
- "@aglyn/tenant-feature-instance": "1.0.0-beta.285",
37
- "@aglyn/tenant-runtime": "1.0.0-beta.285",
28
+ "@aglyn/aglyn": "1.0.0-beta.287",
29
+ "@aglyn/shared-data-mdi": "1.0.0-beta.287",
30
+ "@aglyn/shared-ui-jsx": "1.0.0-beta.287",
31
+ "@aglyn/shared-ui-snackstack": "1.0.0-beta.287",
32
+ "@aglyn/shared-util-email": "1.0.0-beta.287",
33
+ "@aglyn/shared-util-http": "1.0.0-beta.287",
34
+ "@aglyn/shared-util-timestamp": "1.0.0-beta.287",
35
+ "@aglyn/tenant-data-admin": "1.0.0-beta.287",
36
+ "@aglyn/tenant-feature-instance": "1.0.0-beta.287",
37
+ "@aglyn/tenant-runtime": "1.0.0-beta.287",
38
38
  "@swc/helpers": "0.5.23"
39
39
  },
40
40
  "peerDependencies": {
@@ -0,0 +1,27 @@
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
+ /**
18
+ * The plugin's DECLARATIONS (AGL-4047): its permission keys (taking a
19
+ * booking's payment in person and refunding a booking, whose preset is the
20
+ * site role), which the one permission catalog lists beside the core keys.
21
+ * Loaded eagerly by the console (client and server) and the tenant's server
22
+ * through the generated declarations manifest, so the role editor offers the
23
+ * keys, a custom role or a per-member override keeps them, and the site's
24
+ * stamp carries them. Light by construction: nothing here reaches a
25
+ * provider, Firestore or React.
26
+ */
27
+ export declare function registerBookingsDeclarations(): void;
@@ -0,0 +1,38 @@
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 { registerPluginEntitlements } from "@aglyn/aglyn/plugin-manager/plugin-entitlements";
17
+ import { BOOKINGS_SITE_PERMISSIONS } from "./model/bookings-permissions.js";
18
+ let declared = false;
19
+ /**
20
+ * The plugin's DECLARATIONS (AGL-4047): its permission keys (taking a
21
+ * booking's payment in person and refunding a booking, whose preset is the
22
+ * site role), which the one permission catalog lists beside the core keys.
23
+ * Loaded eagerly by the console (client and server) and the tenant's server
24
+ * through the generated declarations manifest, so the role editor offers the
25
+ * keys, a custom role or a per-member override keeps them, and the site's
26
+ * stamp carries them. Light by construction: nothing here reaches a
27
+ * provider, Firestore or React.
28
+ */ export function registerBookingsDeclarations() {
29
+ if (declared) return;
30
+ declared = true;
31
+ registerPluginEntitlements({
32
+ pluginId: 'bookings',
33
+ orgPermissions: BOOKINGS_SITE_PERMISSIONS
34
+ });
35
+ }
36
+ registerBookingsDeclarations();
37
+
38
+ //# sourceMappingURL=declarations.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../libs/plugins/bookings/src/lib/declarations.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 { registerPluginEntitlements } from '@aglyn/aglyn/plugin-manager/plugin-entitlements'\nimport { BOOKINGS_SITE_PERMISSIONS } from './model/bookings-permissions'\n\nlet declared = false\n\n/**\n * The plugin's DECLARATIONS (AGL-4047): its permission keys (taking a\n * booking's payment in person and refunding a booking, whose preset is the\n * site role), which the one permission catalog lists beside the core keys.\n * Loaded eagerly by the console (client and server) and the tenant's server\n * through the generated declarations manifest, so the role editor offers the\n * keys, a custom role or a per-member override keeps them, and the site's\n * stamp carries them. Light by construction: nothing here reaches a\n * provider, Firestore or React.\n */\nexport function registerBookingsDeclarations(): void {\n if (declared) return\n declared = true\n registerPluginEntitlements({ pluginId: 'bookings', orgPermissions: BOOKINGS_SITE_PERMISSIONS })\n}\n\nregisterBookingsDeclarations()\n"],"names":["registerPluginEntitlements","BOOKINGS_SITE_PERMISSIONS","declared","registerBookingsDeclarations","pluginId","orgPermissions"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,0BAA0B,QAAQ,kDAAiD;AAC5F,SAASC,yBAAyB,QAAQ,kCAA8B;AAExE,IAAIC,WAAW;AAEf;;;;;;;;;CASC,GACD,OAAO,SAASC;IACd,IAAID,UAAU;IACdA,WAAW;IACXF,2BAA2B;QAAEI,UAAU;QAAYC,gBAAgBJ;IAA0B;AAC/F;AAEAE"}
@@ -0,0 +1,28 @@
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 { HostAccessRole } from '@aglyn/aglyn/foundation/definitions/organization.types';
18
+ import type { PluginOrgPermissionDeclaration } from '@aglyn/aglyn/plugin-manager/plugin-entitlements';
19
+ /** Bookings' keys whose preset is the site role. */
20
+ export type BookingsSitePermission = 'bookings.payments' | 'bookings.refunds';
21
+ /** Who took a booking's payment in person before it was a key: the site's Admin and Editor. */
22
+ export declare const BOOKING_PAYMENTS_SITE_ROLE_PRESET: Readonly<Record<HostAccessRole, boolean>>;
23
+ /** Who refunded a booking before it was a key: the site's Admin. */
24
+ export declare const BOOKING_REFUNDS_SITE_ROLE_PRESET: Readonly<Record<HostAccessRole, boolean>>;
25
+ /** The bookings keys as the plugin declares them into the org permission catalog (AGL-4047). */
26
+ export declare const BOOKINGS_SITE_PERMISSIONS: readonly PluginOrgPermissionDeclaration[];
27
+ /** The refusal a door answers when a bookings key is not held: names the permission, never a role. */
28
+ export declare function bookingsSitePermissionRefusal(key: BookingsSitePermission): string;
@@ -0,0 +1,68 @@
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 { _ as _extends } from "@swc/helpers/_/_extends";
17
+ /** Who took a booking's payment in person before it was a key: the site's Admin and Editor. */ export const BOOKING_PAYMENTS_SITE_ROLE_PRESET = {
18
+ admin: true,
19
+ editor: true,
20
+ author: false,
21
+ viewer: false
22
+ };
23
+ /** Who refunded a booking before it was a key: the site's Admin. */ export const BOOKING_REFUNDS_SITE_ROLE_PRESET = {
24
+ admin: true,
25
+ editor: false,
26
+ author: false,
27
+ viewer: false
28
+ };
29
+ /** The bookings keys as the plugin declares them into the org permission catalog (AGL-4047). */ export const BOOKINGS_SITE_PERMISSIONS = [
30
+ {
31
+ key: 'bookings.payments',
32
+ label: 'Take booking payments in person',
33
+ description: 'Take a booking’s payment at the desk on a card reader. Follows the site role unless a role or member sets it.',
34
+ roleDefaults: {
35
+ owner: true,
36
+ admin: true,
37
+ editor: true,
38
+ viewer: false
39
+ },
40
+ hostRoleDefaults: _extends({}, BOOKING_PAYMENTS_SITE_ROLE_PRESET),
41
+ group: 'bookings',
42
+ groupLabel: 'Bookings',
43
+ presetFromSiteRole: true
44
+ },
45
+ {
46
+ key: 'bookings.refunds',
47
+ label: 'Refund bookings',
48
+ description: 'Refund a paid booking, in full or in part. Follows the site role unless a role or member sets it.',
49
+ roleDefaults: {
50
+ owner: true,
51
+ admin: true,
52
+ editor: false,
53
+ viewer: false
54
+ },
55
+ hostRoleDefaults: _extends({}, BOOKING_REFUNDS_SITE_ROLE_PRESET),
56
+ group: 'bookings',
57
+ groupLabel: 'Bookings',
58
+ presetFromSiteRole: true
59
+ }
60
+ ];
61
+ /** The refusal a door answers when a bookings key is not held: names the permission, never a role. */ export function bookingsSitePermissionRefusal(key) {
62
+ var _ref;
63
+ var _BOOKINGS_SITE_PERMISSIONS_find;
64
+ const label = (_ref = (_BOOKINGS_SITE_PERMISSIONS_find = BOOKINGS_SITE_PERMISSIONS.find((entry)=>entry.key === key)) == null ? void 0 : _BOOKINGS_SITE_PERMISSIONS_find.label) != null ? _ref : key;
65
+ return `Your role does not include "${label}" — ask an organization admin`;
66
+ }
67
+
68
+ //# sourceMappingURL=bookings-permissions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/model/bookings-permissions.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 { HostAccessRole } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport type { PluginOrgPermissionDeclaration } from '@aglyn/aglyn/plugin-manager/plugin-entitlements'\n\n/*\n * BOOKINGS' KEYS (AGL-4047).\n *\n * Taking a booking's payment at the desk and refunding a booking were decided\n * by the member's role ON THE SITE: an Admin or an Editor took payments in\n * person, and only an Admin refunded. Those are now keys whose preset is that\n * site role (`presetFromSiteRole`), so every member keeps exactly the access\n * they had, and a custom role, a member's own permissions or a site's toggle\n * can grant or refuse either one.\n */\n\n/** Bookings' keys whose preset is the site role. */\nexport type BookingsSitePermission = 'bookings.payments' | 'bookings.refunds'\n\n/** Who took a booking's payment in person before it was a key: the site's Admin and Editor. */\nexport const BOOKING_PAYMENTS_SITE_ROLE_PRESET: Readonly<Record<HostAccessRole, boolean>> = {\n admin: true,\n editor: true,\n author: false,\n viewer: false,\n}\n\n/** Who refunded a booking before it was a key: the site's Admin. */\nexport const BOOKING_REFUNDS_SITE_ROLE_PRESET: Readonly<Record<HostAccessRole, boolean>> = {\n admin: true,\n editor: false,\n author: false,\n viewer: false,\n}\n\n/** The bookings keys as the plugin declares them into the org permission catalog (AGL-4047). */\nexport const BOOKINGS_SITE_PERMISSIONS: readonly PluginOrgPermissionDeclaration[] = [\n {\n key: 'bookings.payments',\n label: 'Take booking payments in person',\n description:\n 'Take a booking’s payment at the desk on a card reader. Follows the site role unless a role or member sets it.',\n roleDefaults: { owner: true, admin: true, editor: true, viewer: false },\n hostRoleDefaults: { ...BOOKING_PAYMENTS_SITE_ROLE_PRESET },\n group: 'bookings',\n groupLabel: 'Bookings',\n presetFromSiteRole: true,\n },\n {\n key: 'bookings.refunds',\n label: 'Refund bookings',\n description: 'Refund a paid booking, in full or in part. Follows the site role unless a role or member sets it.',\n roleDefaults: { owner: true, admin: true, editor: false, viewer: false },\n hostRoleDefaults: { ...BOOKING_REFUNDS_SITE_ROLE_PRESET },\n group: 'bookings',\n groupLabel: 'Bookings',\n presetFromSiteRole: true,\n },\n]\n\n/** The refusal a door answers when a bookings key is not held: names the permission, never a role. */\nexport function bookingsSitePermissionRefusal(key: BookingsSitePermission): string {\n const label = BOOKINGS_SITE_PERMISSIONS.find((entry) => entry.key === key)?.label ?? key\n return `Your role does not include \"${label}\" — ask an organization admin`\n}\n"],"names":["BOOKING_PAYMENTS_SITE_ROLE_PRESET","admin","editor","author","viewer","BOOKING_REFUNDS_SITE_ROLE_PRESET","BOOKINGS_SITE_PERMISSIONS","key","label","description","roleDefaults","owner","hostRoleDefaults","group","groupLabel","presetFromSiteRole","bookingsSitePermissionRefusal","find","entry"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAmBD,6FAA6F,GAC7F,OAAO,MAAMA,oCAA+E;IAC1FC,OAAO;IACPC,QAAQ;IACRC,QAAQ;IACRC,QAAQ;AACV,EAAC;AAED,kEAAkE,GAClE,OAAO,MAAMC,mCAA8E;IACzFJ,OAAO;IACPC,QAAQ;IACRC,QAAQ;IACRC,QAAQ;AACV,EAAC;AAED,8FAA8F,GAC9F,OAAO,MAAME,4BAAuE;IAClF;QACEC,KAAK;QACLC,OAAO;QACPC,aACE;QACFC,cAAc;YAAEC,OAAO;YAAMV,OAAO;YAAMC,QAAQ;YAAME,QAAQ;QAAM;QACtEQ,kBAAkB,aAAKZ;QACvBa,OAAO;QACPC,YAAY;QACZC,oBAAoB;IACtB;IACA;QACER,KAAK;QACLC,OAAO;QACPC,aAAa;QACbC,cAAc;YAAEC,OAAO;YAAMV,OAAO;YAAMC,QAAQ;YAAOE,QAAQ;QAAM;QACvEQ,kBAAkB,aAAKP;QACvBQ,OAAO;QACPC,YAAY;QACZC,oBAAoB;IACtB;CACD,CAAA;AAED,oGAAoG,GACpG,OAAO,SAASC,8BAA8BT,GAA2B;;QACzDD;IAAd,MAAME,iBAAQF,kCAAAA,0BAA0BW,IAAI,CAAC,CAACC,QAAUA,MAAMX,GAAG,KAAKA,yBAAxDD,gCAA8DE,KAAK,mBAAID;IACrF,OAAO,CAAC,4BAA4B,EAAEC,MAAM,6BAA6B,CAAC;AAC5E"}
@@ -14,7 +14,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
14
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
- */ import { hostRoleCanWrite } from "@aglyn/aglyn/app-utils/organizations";
17
+ */ import { holdsSiteKey, siteKeyRefusal } from "@aglyn/aglyn/app-utils/host-permissions";
18
18
  import { isEmailConfigured, sendEmail } from "@aglyn/shared-util-email";
19
19
  import { firebaseAdmin, getOrgForHost, hostSendingIdentity, meterHostEmail, renderHostEmailWithTokens } from "@aglyn/tenant-data-admin";
20
20
  import { getSiteLockdown } from "@aglyn/tenant-data-admin/server/tenant-write-lockdown";
@@ -48,7 +48,6 @@ const bodyOf = (req)=>{
48
48
  return (_req_body = req.body) != null ? _req_body : {};
49
49
  };
50
50
  /** The member, their right to write this site's bookings, and the site being open. */ async function authorize(deps, req, hostId) {
51
- var _host_get;
52
51
  const token = bearerOf(req);
53
52
  if (!token) throw new Refusal(401, 'Unauthenticated');
54
53
  let uid;
@@ -60,8 +59,7 @@ const bodyOf = (req)=>{
60
59
  }
61
60
  const host = await deps.firestore().doc(`hosts/${hostId}`).get();
62
61
  if (!host.exists) throw new Refusal(404, 'Unknown site');
63
- const role = ((_host_get = host.get('memberRoles')) != null ? _host_get : {})[uid];
64
- if (!hostRoleCanWrite(role)) throw new Refusal(403, 'Your role on this site cannot change bookings');
62
+ if (!holdsSiteKey(host, uid, 'site.edit')) throw new Refusal(403, siteKeyRefusal('site.edit'));
65
63
  if (await deps.siteLocked(hostId)) throw new Refusal(423, 'This site is locked and cannot take changes right now');
66
64
  return {
67
65
  uid
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/booking-manage.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 { hostRoleCanWrite } from '@aglyn/aglyn/app-utils/organizations'\nimport type { PluginApiHandler, PluginApiRequest } from '@aglyn/aglyn/app-utils/api-plugins'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport {\n firebaseAdmin,\n getOrgForHost,\n hostSendingIdentity,\n meterHostEmail,\n renderHostEmailWithTokens,\n} from '@aglyn/tenant-data-admin'\nimport { getSiteLockdown } from '@aglyn/tenant-data-admin/server/tenant-write-lockdown'\nimport { resolveBrandingProfile } from '@aglyn/aglyn/server'\nimport {\n bookingDurationMs,\n bookingState,\n cancelRefusal,\n checkInRefusal,\n type ManagedBooking,\n rescheduleRefusal,\n} from '../model/booking-manage'\nimport { type BookedInterval, type HostBookingService, isSlotOpen } from '../model/bookings'\nimport { bookingTimeZone, formatBookingWhen, storedBookingTimeZone } from '../model/booking-time'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { type BookingEventInput, raiseBookingEvent } from './booking-events'\n\n/*\n * Checking a guest in and moving a booking (AGL-3621), for the site's team.\n *\n * The native Aglyn app's bookings calendar calls these; any console surface\n * may too. Each is a member route: the caller's ID token names them, the\n * host's `memberRoles` must give them a content-writing role (the same roles the rules let write\n * a booking directly), and a locked-down site refuses. Each decides inside\n * ONE transaction, re-reading the booking, so two phones acting at once\n * cannot both move it or check in a guest whose booking was just canceled.\n *\n * Moving a booking re-checks the new slot against the service's hours and\n * every other live booking of that service in the same transaction the\n * public booking route uses, so a move can never double-book. It keeps the\n * booking's own length, clears the reminder stamp so the 24-hour reminder\n * goes out for the new time, and tells the guest by email.\n */\n\n/** The Firestore surface these routes use: the Admin SDK's, narrowed so a spec can hand in a double. */\nexport interface ManageDocSnapshot {\n readonly exists: boolean\n readonly id?: string\n get(field: string): unknown\n data(): Record<string, unknown> | undefined\n}\nexport interface ManageDocRef {\n readonly id: string\n}\nexport interface ManageQuery {\n where(field: string, op: '==' | '>=' | '<', value: unknown): ManageQuery\n limit(count: number): ManageQuery\n}\nexport interface ManageTransaction {\n get(ref: ManageDocRef): Promise<ManageDocSnapshot>\n get(query: ManageQuery): Promise<{ docs: ManageDocSnapshot[] }>\n update(ref: ManageDocRef, data: Record<string, unknown>): unknown\n}\nexport interface ManageFirestore {\n doc(path: string): ManageDocRef & { get(): Promise<ManageDocSnapshot> }\n collection(path: string): ManageQuery\n runTransaction<T>(fn: (transaction: ManageTransaction) => Promise<T>): Promise<T>\n}\n\nexport interface RescheduleNotice {\n hostId: string\n bookingId: string\n to: string\n name: string\n serviceName: string\n when: string\n previousWhen: string\n timezone: string\n}\n\nexport interface BookingManageDeps {\n firestore: () => ManageFirestore\n verifyIdToken: (token: string) => Promise<{ uid: string }>\n /** True when the site is locked down and must not take writes. */\n siteLocked: (hostId: string) => Promise<boolean>\n /** The zone a booking is told in when the document carries none. */\n timeZoneFor: (hostId: string, service: HostBookingService | undefined) => Promise<string>\n notifyRescheduled: (notice: RescheduleNotice) => Promise<void>\n now: () => number\n /**\n * Raises a booking event once the change is written (AGL-3643): the move,\n * the cancel. Never throws. Absent, nothing is raised.\n */\n raiseEvent?: (input: BookingEventInput) => Promise<void>\n}\n\n/** Field the booking stamps when the guest arrives. */\nexport const CHECKED_IN_AT = 'checkedInAtMs'\nexport const CHECKED_IN_BY = 'checkedInBy'\n\nclass Refusal extends Error {\n constructor(\n readonly status: number,\n message: string,\n ) {\n super(message)\n }\n}\n\nconst bearerOf = (req: PluginApiRequest): string => {\n const header = String(req.headers['authorization'] ?? req.headers['Authorization'] ?? '')\n return header.startsWith('Bearer ') ? header.slice('Bearer '.length) : ''\n}\n\nconst bodyOf = (req: PluginApiRequest): Record<string, unknown> => {\n if (typeof req.body === 'string') {\n try {\n return JSON.parse(req.body) as Record<string, unknown>\n } catch {\n return {}\n }\n }\n return (req.body ?? {}) as Record<string, unknown>\n}\n\n/** The member, their right to write this site's bookings, and the site being open. */\nasync function authorize(\n deps: BookingManageDeps,\n req: PluginApiRequest,\n hostId: string,\n): Promise<{ uid: string }> {\n const token = bearerOf(req)\n if (!token) throw new Refusal(401, 'Unauthenticated')\n let uid: string\n try {\n uid = (await deps.verifyIdToken(token)).uid\n } catch (error) {\n if (!isRefusedIdToken(error)) throw error\n throw new Refusal(401, 'Unauthenticated')\n }\n const host = await deps.firestore().doc(`hosts/${hostId}`).get()\n if (!host.exists) throw new Refusal(404, 'Unknown site')\n const role = ((host.get('memberRoles') ?? {}) as Record<string, unknown>)[uid]\n if (!hostRoleCanWrite(role)) throw new Refusal(403, 'Your role on this site cannot change bookings')\n if (await deps.siteLocked(hostId)) throw new Refusal(423, 'This site is locked and cannot take changes right now')\n return { uid }\n}\n\nfunction answer(res: Parameters<PluginApiHandler>[1], error: unknown): void {\n if (error instanceof Refusal) {\n res.status(error.status).json({ error: error.message })\n return\n }\n console.error('[bookings/manage]', error)\n res.status(500).json({ error: 'That did not go through. Try again.' })\n}\n\nexport function createBookingCheckInHandler(deps: BookingManageDeps): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const body = bodyOf(req)\n const hostId = String(body['hostId'] ?? '')\n const bookingId = String(body['bookingId'] ?? '')\n const checkedIn = body['checkedIn'] !== false\n if (!hostId || !bookingId) return res.status(400).json({ error: 'Missing hostId or bookingId' })\n try {\n const { uid } = await authorize(deps, req, hostId)\n const firestore = deps.firestore()\n const ref = firestore.doc(`hosts/${hostId}/bookings/${bookingId}`)\n const result = await firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new Refusal(404, 'Unknown booking')\n const booking = (snapshot.data() ?? {}) as ManagedBooking\n const nowMs = deps.now()\n const refusal = checkInRefusal(booking, checkedIn, nowMs)\n if (refusal) throw new Refusal(409, refusal)\n const already = Number(booking.checkedInAtMs ?? 0) > 0\n // Already where it was asked to be: a retried tap changes nothing.\n if (already === checkedIn) return { checkedInAtMs: already ? Number(booking.checkedInAtMs) : null }\n if (checkedIn) {\n transaction.update(ref, { [CHECKED_IN_AT]: nowMs, [CHECKED_IN_BY]: uid })\n return { checkedInAtMs: nowMs }\n }\n transaction.update(ref, { [CHECKED_IN_AT]: null, [CHECKED_IN_BY]: null })\n return { checkedInAtMs: null }\n })\n return res.status(200).json({ ok: true, ...result })\n } catch (error) {\n return answer(res, error)\n }\n }\n}\n\nexport function createBookingRescheduleHandler(deps: BookingManageDeps): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const body = bodyOf(req)\n const hostId = String(body['hostId'] ?? '')\n const bookingId = String(body['bookingId'] ?? '')\n const startsAtMs = Number(body['startsAtMs'])\n if (!hostId || !bookingId) return res.status(400).json({ error: 'Missing hostId or bookingId' })\n if (!Number.isFinite(startsAtMs) || startsAtMs <= 0) return res.status(400).json({ error: 'Pick a new time' })\n try {\n const { uid } = await authorize(deps, req, hostId)\n const firestore = deps.firestore()\n const ref = firestore.doc(`hosts/${hostId}/bookings/${bookingId}`)\n const first = await ref.get()\n if (!first.exists) throw new Refusal(404, 'Unknown booking')\n const serviceId = String(first.get('serviceId') ?? '')\n const serviceSnapshot = serviceId ? await firestore.doc(`hosts/${hostId}/services/${serviceId}`).get() : null\n const service = serviceSnapshot?.exists ? (serviceSnapshot.data() as unknown as HostBookingService) : undefined\n if (!service || serviceSnapshot?.get('deletedAt')) {\n throw new Refusal(409, 'This booking’s service no longer exists, so it cannot move')\n }\n\n const moved = await firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new Refusal(404, 'Unknown booking')\n const booking = (snapshot.data() ?? {}) as ManagedBooking & Record<string, unknown>\n const nowMs = deps.now()\n const refusal = rescheduleRefusal(booking, startsAtMs, nowMs)\n if (refusal) throw new Refusal(409, refusal)\n const previousStartsAtMs = Number(booking.startsAtMs ?? 0)\n // Already at that time: a retried move writes nothing and tells no one twice.\n if (previousStartsAtMs === startsAtMs) return null\n const durationMs = bookingDurationMs(booking, service.durationMinutes)\n // The public booking route's own read: every booking of this service\n // from a day before the new time, so one running into it counts.\n const nearby = await transaction.get(\n firestore\n .collection(`hosts/${hostId}/bookings`)\n .where('serviceId', '==', serviceId)\n .where('startsAtMs', '>=', startsAtMs - 24 * 60 * 60_000)\n .limit(500),\n )\n const booked: BookedInterval[] = nearby.docs\n .filter((doc) => doc.id !== bookingId)\n .filter((doc) => {\n const status = doc.get('status')\n if (status === 'canceled') return false\n return !(status === 'pendingPayment' && Number(doc.get('expiresAtMs') ?? 0) < nowMs)\n })\n .map((doc) => ({ startsAtMs: Number(doc.get('startsAtMs') ?? 0), endsAtMs: Number(doc.get('endsAtMs') ?? 0) }))\n if (!isSlotOpen(service, startsAtMs, booked)) throw new Refusal(409, 'That time is not open. Pick another.')\n const endsAtMs = startsAtMs + durationMs\n transaction.update(ref, {\n startsAtMs,\n endsAtMs,\n rescheduledAtMs: nowMs,\n rescheduledBy: uid,\n rescheduledFromMs: previousStartsAtMs,\n // The reminder is owed again, for the new time.\n reminderSentAt: null,\n })\n return { booking, previousStartsAtMs, endsAtMs }\n })\n\n if (!moved) {\n return res.status(200).json({ ok: true, startsAtMs, endsAtMs: Number(first.get('endsAtMs') ?? 0), notified: false })\n }\n // Keyed by the booking and its new time: a retried move raises it once.\n await deps.raiseEvent?.({\n event: 'booking.rescheduled',\n hostId,\n bookingId,\n booking: {\n ...moved.booking,\n startsAtMs,\n endsAtMs: moved.endsAtMs,\n rescheduledFromMs: moved.previousStartsAtMs,\n },\n })\n const to = String(moved.booking['email'] ?? '').trim()\n let notified = false\n if (to) {\n const timezone = storedBookingTimeZone({ timezone: moved.booking['timezone'] }) ?? (await deps.timeZoneFor(hostId, service))\n try {\n await deps.notifyRescheduled({\n hostId,\n bookingId,\n to,\n name: String(moved.booking['name'] ?? ''),\n serviceName: String(moved.booking['serviceName'] ?? service.name ?? ''),\n when: formatBookingWhen(startsAtMs, timezone),\n previousWhen: formatBookingWhen(moved.previousStartsAtMs, timezone),\n timezone,\n })\n notified = true\n } catch (error) {\n // The booking has moved whatever the mail did; the screen says the guest was not told.\n console.error('[bookings/reschedule] notice failed', hostId, bookingId, error)\n }\n }\n return res.status(200).json({ ok: true, startsAtMs, endsAtMs: moved.endsAtMs, notified })\n } catch (error) {\n return answer(res, error)\n }\n }\n}\n\n/**\n * Canceling a booking that has no money on it (AGL-3643): a free booking, or\n * a paid one already refunded in full. The site's team used to write\n * `status: 'canceled'` straight from the console; a route is where the\n * cancel can be told to the plugins that listen for it (`booking.canceled`),\n * and where the rule that a paid booking cancels through its refund is held\n * rather than trusted to the screen. One transaction: a booking checked in\n * or paid a moment ago is refused, and canceling it twice changes nothing.\n */\nexport function createBookingCancelHandler(deps: BookingManageDeps): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const body = bodyOf(req)\n const hostId = String(body['hostId'] ?? '')\n const bookingId = String(body['bookingId'] ?? '')\n if (!hostId || !bookingId) return res.status(400).json({ error: 'Missing hostId or bookingId' })\n try {\n const { uid } = await authorize(deps, req, hostId)\n const firestore = deps.firestore()\n const ref = firestore.doc(`hosts/${hostId}/bookings/${bookingId}`)\n const canceled = await firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new Refusal(404, 'Unknown booking')\n const booking = (snapshot.data() ?? {}) as ManagedBooking & Record<string, unknown>\n const nowMs = deps.now()\n const refusal = cancelRefusal(booking, nowMs)\n if (refusal) throw new Refusal(409, refusal)\n // Already canceled: a retried tap writes nothing and tells no one twice.\n if (bookingState(booking, nowMs) === 'canceled') return null\n transaction.update(ref, { status: 'canceled', canceledAtMs: nowMs, canceledBy: uid })\n return { ...booking, status: 'canceled', canceledAtMs: nowMs }\n })\n if (canceled) {\n await deps.raiseEvent?.({ event: 'booking.canceled', hostId, bookingId, booking: canceled })\n }\n return res.status(200).json({ ok: true, canceled: true })\n } catch (error) {\n return answer(res, error)\n }\n }\n}\n\n/** The email that tells a guest their booking moved, as the confirmation is sent. */\nexport async function sendRescheduledNotice(notice: RescheduleNotice): Promise<void> {\n if (!isEmailConfigured()) throw new Error('Email is not configured')\n const firestore = firebaseAdmin.app().firestore()\n const fallbackText =\n `Hi ${notice.name},\\n\\nYour booking for \"${notice.serviceName}\" is now on ` +\n `${notice.when} (${notice.timezone}). It was on ${notice.previousWhen}.\\n\\n` +\n `Reference: ${notice.bookingId}`\n const designed = await renderHostEmailWithTokens(firestore, notice.hostId, 'booking-rescheduled', {\n name: notice.name,\n 'service.name': notice.serviceName,\n when: notice.when,\n previousWhen: notice.previousWhen,\n timezone: notice.timezone,\n 'booking.ref': notice.bookingId,\n })\n const branding = resolveBrandingProfile((await getOrgForHost(notice.hostId).catch(() => null))?.org as never)\n await sendEmail({\n to: notice.to,\n subject: designed?.subject ?? `New time for ${notice.serviceName}`,\n text: designed?.text || fallbackText,\n ...(designed?.html ? { html: designed.html } : {}),\n fromName: branding.fromName,\n sendingIdentity: await hostSendingIdentity(notice.hostId),\n audience: 'tenant',\n context: 'booking rescheduled',\n owedFor: 'booking',\n })\n await meterHostEmail(notice.hostId)\n}\n\n/** The production wiring: the Admin SDK, the site lockdown verdict and the real send. */\nexport function bookingManageDeps(): BookingManageDeps {\n return {\n firestore: () => firebaseAdmin.app().firestore() as unknown as ManageFirestore,\n verifyIdToken: (token) => firebaseAdmin.app().auth().verifyIdToken(token),\n siteLocked: async (hostId) => Boolean(await getSiteLockdown(hostId)),\n timeZoneFor: async (hostId, service) => {\n const firestore = firebaseAdmin.app().firestore()\n const [host, owner] = await Promise.all([\n firestore.collection('hosts').doc(hostId).get(),\n getOrgForHost(hostId).catch(() => null),\n ])\n return bookingTimeZone({\n service: service ?? null,\n host: host.data() as { timeZone?: string } | undefined,\n org: owner?.org as { timeZone?: string } | null | undefined,\n })\n },\n notifyRescheduled: sendRescheduledNotice,\n now: () => Date.now(),\n raiseEvent: (input) => raiseBookingEvent(firebaseAdmin.app().firestore(), input),\n }\n}\n"],"names":["hostRoleCanWrite","isEmailConfigured","sendEmail","firebaseAdmin","getOrgForHost","hostSendingIdentity","meterHostEmail","renderHostEmailWithTokens","getSiteLockdown","resolveBrandingProfile","bookingDurationMs","bookingState","cancelRefusal","checkInRefusal","rescheduleRefusal","isSlotOpen","bookingTimeZone","formatBookingWhen","storedBookingTimeZone","isRefusedIdToken","raiseBookingEvent","CHECKED_IN_AT","CHECKED_IN_BY","Refusal","Error","status","message","bearerOf","req","header","String","headers","startsWith","slice","length","bodyOf","body","JSON","parse","authorize","deps","hostId","host","token","uid","verifyIdToken","error","firestore","doc","get","exists","role","siteLocked","answer","res","json","console","createBookingCheckInHandler","method","bookingId","checkedIn","ref","result","runTransaction","transaction","snapshot","booking","data","nowMs","now","refusal","already","Number","checkedInAtMs","update","ok","createBookingRescheduleHandler","startsAtMs","isFinite","first","moved","serviceId","serviceSnapshot","service","undefined","previousStartsAtMs","durationMs","durationMinutes","nearby","collection","where","limit","booked","docs","filter","id","map","endsAtMs","rescheduledAtMs","rescheduledBy","rescheduledFromMs","reminderSentAt","notified","raiseEvent","event","to","trim","timezone","timeZoneFor","notifyRescheduled","name","serviceName","when","previousWhen","createBookingCancelHandler","canceled","canceledAtMs","canceledBy","sendRescheduledNotice","notice","app","fallbackText","designed","branding","catch","org","subject","text","html","fromName","sendingIdentity","audience","context","owedFor","bookingManageDeps","auth","Boolean","owner","Promise","all","Date","input"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,QAAQ,uCAAsC;AAEvE,SAASC,iBAAiB,EAAEC,SAAS,QAAQ,2BAA0B;AACvE,SACEC,aAAa,EACbC,aAAa,EACbC,mBAAmB,EACnBC,cAAc,EACdC,yBAAyB,QACpB,2BAA0B;AACjC,SAASC,eAAe,QAAQ,wDAAuD;AACvF,SAASC,sBAAsB,QAAQ,sBAAqB;AAC5D,SACEC,iBAAiB,EACjBC,YAAY,EACZC,aAAa,EACbC,cAAc,EAEdC,iBAAiB,QACZ,6BAAyB;AAChC,SAAuDC,UAAU,QAAQ,uBAAmB;AAC5F,SAASC,eAAe,EAAEC,iBAAiB,EAAEC,qBAAqB,QAAQ,2BAAuB;AACjG,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,S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AAMpC,YAAY5C,cAAcqH,GAAG,GAAGzE,SAAS;YAC/C,MAAM,CAACL,MAAM+F,MAAM,GAAG,MAAMC,QAAQC,GAAG,CAAC;gBACtC5F,UAAU0C,UAAU,CAAC,SAASzC,GAAG,CAACP,QAAQQ,GAAG;gBAC7C7C,cAAcqC,QAAQmF,KAAK,CAAC,IAAM;aACnC;YACD,OAAO5G,gBAAgB;gBACrBmE,OAAO,EAAEA,kBAAAA,UAAW;gBACpBzC,MAAMA,KAAKyB,IAAI;gBACf0D,GAAG,EAAEY,yBAAAA,MAAOZ,GAAG;YACjB;QACF;QACAhB,mBAAmBS;QACnBjD,KAAK,IAAMuE,KAAKvE,GAAG;QACnBkC,YAAY,CAACsC,QAAUzH,kBAAkBjB,cAAcqH,GAAG,GAAGzE,SAAS,IAAI8F;IAC5E;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/booking-manage.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 { holdsSiteKey, siteKeyRefusal } from '@aglyn/aglyn/app-utils/host-permissions'\nimport type { PluginApiHandler, PluginApiRequest } from '@aglyn/aglyn/app-utils/api-plugins'\nimport { isEmailConfigured, sendEmail } from '@aglyn/shared-util-email'\nimport {\n firebaseAdmin,\n getOrgForHost,\n hostSendingIdentity,\n meterHostEmail,\n renderHostEmailWithTokens,\n} from '@aglyn/tenant-data-admin'\nimport { getSiteLockdown } from '@aglyn/tenant-data-admin/server/tenant-write-lockdown'\nimport { resolveBrandingProfile } from '@aglyn/aglyn/server'\nimport {\n bookingDurationMs,\n bookingState,\n cancelRefusal,\n checkInRefusal,\n type ManagedBooking,\n rescheduleRefusal,\n} from '../model/booking-manage'\nimport { type BookedInterval, type HostBookingService, isSlotOpen } from '../model/bookings'\nimport { bookingTimeZone, formatBookingWhen, storedBookingTimeZone } from '../model/booking-time'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { type BookingEventInput, raiseBookingEvent } from './booking-events'\n\n/*\n * Checking a guest in and moving a booking (AGL-3621), for the site's team.\n *\n * The native Aglyn app's bookings calendar calls these; any console surface\n * may too. Each is a member route: the caller's ID token names them, they\n * must hold \"Edit site content\" on the site (`site.edit`, AGL-4047: the key\n * the rules ask to write a booking directly, whose preset is the\n * content-writing roles that did before), and a locked-down site refuses. Each decides inside\n * ONE transaction, re-reading the booking, so two phones acting at once\n * cannot both move it or check in a guest whose booking was just canceled.\n *\n * Moving a booking re-checks the new slot against the service's hours and\n * every other live booking of that service in the same transaction the\n * public booking route uses, so a move can never double-book. It keeps the\n * booking's own length, clears the reminder stamp so the 24-hour reminder\n * goes out for the new time, and tells the guest by email.\n */\n\n/** The Firestore surface these routes use: the Admin SDK's, narrowed so a spec can hand in a double. */\nexport interface ManageDocSnapshot {\n readonly exists: boolean\n readonly id?: string\n get(field: string): unknown\n data(): Record<string, unknown> | undefined\n}\nexport interface ManageDocRef {\n readonly id: string\n}\nexport interface ManageQuery {\n where(field: string, op: '==' | '>=' | '<', value: unknown): ManageQuery\n limit(count: number): ManageQuery\n}\nexport interface ManageTransaction {\n get(ref: ManageDocRef): Promise<ManageDocSnapshot>\n get(query: ManageQuery): Promise<{ docs: ManageDocSnapshot[] }>\n update(ref: ManageDocRef, data: Record<string, unknown>): unknown\n}\nexport interface ManageFirestore {\n doc(path: string): ManageDocRef & { get(): Promise<ManageDocSnapshot> }\n collection(path: string): ManageQuery\n runTransaction<T>(fn: (transaction: ManageTransaction) => Promise<T>): Promise<T>\n}\n\nexport interface RescheduleNotice {\n hostId: string\n bookingId: string\n to: string\n name: string\n serviceName: string\n when: string\n previousWhen: string\n timezone: string\n}\n\nexport interface BookingManageDeps {\n firestore: () => ManageFirestore\n verifyIdToken: (token: string) => Promise<{ uid: string }>\n /** True when the site is locked down and must not take writes. */\n siteLocked: (hostId: string) => Promise<boolean>\n /** The zone a booking is told in when the document carries none. */\n timeZoneFor: (hostId: string, service: HostBookingService | undefined) => Promise<string>\n notifyRescheduled: (notice: RescheduleNotice) => Promise<void>\n now: () => number\n /**\n * Raises a booking event once the change is written (AGL-3643): the move,\n * the cancel. Never throws. Absent, nothing is raised.\n */\n raiseEvent?: (input: BookingEventInput) => Promise<void>\n}\n\n/** Field the booking stamps when the guest arrives. */\nexport const CHECKED_IN_AT = 'checkedInAtMs'\nexport const CHECKED_IN_BY = 'checkedInBy'\n\nclass Refusal extends Error {\n constructor(\n readonly status: number,\n message: string,\n ) {\n super(message)\n }\n}\n\nconst bearerOf = (req: PluginApiRequest): string => {\n const header = String(req.headers['authorization'] ?? req.headers['Authorization'] ?? '')\n return header.startsWith('Bearer ') ? header.slice('Bearer '.length) : ''\n}\n\nconst bodyOf = (req: PluginApiRequest): Record<string, unknown> => {\n if (typeof req.body === 'string') {\n try {\n return JSON.parse(req.body) as Record<string, unknown>\n } catch {\n return {}\n }\n }\n return (req.body ?? {}) as Record<string, unknown>\n}\n\n/** The member, their right to write this site's bookings, and the site being open. */\nasync function authorize(\n deps: BookingManageDeps,\n req: PluginApiRequest,\n hostId: string,\n): Promise<{ uid: string }> {\n const token = bearerOf(req)\n if (!token) throw new Refusal(401, 'Unauthenticated')\n let uid: string\n try {\n uid = (await deps.verifyIdToken(token)).uid\n } catch (error) {\n if (!isRefusedIdToken(error)) throw error\n throw new Refusal(401, 'Unauthenticated')\n }\n const host = await deps.firestore().doc(`hosts/${hostId}`).get()\n if (!host.exists) throw new Refusal(404, 'Unknown site')\n if (!holdsSiteKey(host, uid, 'site.edit')) throw new Refusal(403, siteKeyRefusal('site.edit'))\n if (await deps.siteLocked(hostId)) throw new Refusal(423, 'This site is locked and cannot take changes right now')\n return { uid }\n}\n\nfunction answer(res: Parameters<PluginApiHandler>[1], error: unknown): void {\n if (error instanceof Refusal) {\n res.status(error.status).json({ error: error.message })\n return\n }\n console.error('[bookings/manage]', error)\n res.status(500).json({ error: 'That did not go through. Try again.' })\n}\n\nexport function createBookingCheckInHandler(deps: BookingManageDeps): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const body = bodyOf(req)\n const hostId = String(body['hostId'] ?? '')\n const bookingId = String(body['bookingId'] ?? '')\n const checkedIn = body['checkedIn'] !== false\n if (!hostId || !bookingId) return res.status(400).json({ error: 'Missing hostId or bookingId' })\n try {\n const { uid } = await authorize(deps, req, hostId)\n const firestore = deps.firestore()\n const ref = firestore.doc(`hosts/${hostId}/bookings/${bookingId}`)\n const result = await firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new Refusal(404, 'Unknown booking')\n const booking = (snapshot.data() ?? {}) as ManagedBooking\n const nowMs = deps.now()\n const refusal = checkInRefusal(booking, checkedIn, nowMs)\n if (refusal) throw new Refusal(409, refusal)\n const already = Number(booking.checkedInAtMs ?? 0) > 0\n // Already where it was asked to be: a retried tap changes nothing.\n if (already === checkedIn) return { checkedInAtMs: already ? Number(booking.checkedInAtMs) : null }\n if (checkedIn) {\n transaction.update(ref, { [CHECKED_IN_AT]: nowMs, [CHECKED_IN_BY]: uid })\n return { checkedInAtMs: nowMs }\n }\n transaction.update(ref, { [CHECKED_IN_AT]: null, [CHECKED_IN_BY]: null })\n return { checkedInAtMs: null }\n })\n return res.status(200).json({ ok: true, ...result })\n } catch (error) {\n return answer(res, error)\n }\n }\n}\n\nexport function createBookingRescheduleHandler(deps: BookingManageDeps): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const body = bodyOf(req)\n const hostId = String(body['hostId'] ?? '')\n const bookingId = String(body['bookingId'] ?? '')\n const startsAtMs = Number(body['startsAtMs'])\n if (!hostId || !bookingId) return res.status(400).json({ error: 'Missing hostId or bookingId' })\n if (!Number.isFinite(startsAtMs) || startsAtMs <= 0) return res.status(400).json({ error: 'Pick a new time' })\n try {\n const { uid } = await authorize(deps, req, hostId)\n const firestore = deps.firestore()\n const ref = firestore.doc(`hosts/${hostId}/bookings/${bookingId}`)\n const first = await ref.get()\n if (!first.exists) throw new Refusal(404, 'Unknown booking')\n const serviceId = String(first.get('serviceId') ?? '')\n const serviceSnapshot = serviceId ? await firestore.doc(`hosts/${hostId}/services/${serviceId}`).get() : null\n const service = serviceSnapshot?.exists ? (serviceSnapshot.data() as unknown as HostBookingService) : undefined\n if (!service || serviceSnapshot?.get('deletedAt')) {\n throw new Refusal(409, 'This booking’s service no longer exists, so it cannot move')\n }\n\n const moved = await firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new Refusal(404, 'Unknown booking')\n const booking = (snapshot.data() ?? {}) as ManagedBooking & Record<string, unknown>\n const nowMs = deps.now()\n const refusal = rescheduleRefusal(booking, startsAtMs, nowMs)\n if (refusal) throw new Refusal(409, refusal)\n const previousStartsAtMs = Number(booking.startsAtMs ?? 0)\n // Already at that time: a retried move writes nothing and tells no one twice.\n if (previousStartsAtMs === startsAtMs) return null\n const durationMs = bookingDurationMs(booking, service.durationMinutes)\n // The public booking route's own read: every booking of this service\n // from a day before the new time, so one running into it counts.\n const nearby = await transaction.get(\n firestore\n .collection(`hosts/${hostId}/bookings`)\n .where('serviceId', '==', serviceId)\n .where('startsAtMs', '>=', startsAtMs - 24 * 60 * 60_000)\n .limit(500),\n )\n const booked: BookedInterval[] = nearby.docs\n .filter((doc) => doc.id !== bookingId)\n .filter((doc) => {\n const status = doc.get('status')\n if (status === 'canceled') return false\n return !(status === 'pendingPayment' && Number(doc.get('expiresAtMs') ?? 0) < nowMs)\n })\n .map((doc) => ({ startsAtMs: Number(doc.get('startsAtMs') ?? 0), endsAtMs: Number(doc.get('endsAtMs') ?? 0) }))\n if (!isSlotOpen(service, startsAtMs, booked)) throw new Refusal(409, 'That time is not open. Pick another.')\n const endsAtMs = startsAtMs + durationMs\n transaction.update(ref, {\n startsAtMs,\n endsAtMs,\n rescheduledAtMs: nowMs,\n rescheduledBy: uid,\n rescheduledFromMs: previousStartsAtMs,\n // The reminder is owed again, for the new time.\n reminderSentAt: null,\n })\n return { booking, previousStartsAtMs, endsAtMs }\n })\n\n if (!moved) {\n return res.status(200).json({ ok: true, startsAtMs, endsAtMs: Number(first.get('endsAtMs') ?? 0), notified: false })\n }\n // Keyed by the booking and its new time: a retried move raises it once.\n await deps.raiseEvent?.({\n event: 'booking.rescheduled',\n hostId,\n bookingId,\n booking: {\n ...moved.booking,\n startsAtMs,\n endsAtMs: moved.endsAtMs,\n rescheduledFromMs: moved.previousStartsAtMs,\n },\n })\n const to = String(moved.booking['email'] ?? '').trim()\n let notified = false\n if (to) {\n const timezone = storedBookingTimeZone({ timezone: moved.booking['timezone'] }) ?? (await deps.timeZoneFor(hostId, service))\n try {\n await deps.notifyRescheduled({\n hostId,\n bookingId,\n to,\n name: String(moved.booking['name'] ?? ''),\n serviceName: String(moved.booking['serviceName'] ?? service.name ?? ''),\n when: formatBookingWhen(startsAtMs, timezone),\n previousWhen: formatBookingWhen(moved.previousStartsAtMs, timezone),\n timezone,\n })\n notified = true\n } catch (error) {\n // The booking has moved whatever the mail did; the screen says the guest was not told.\n console.error('[bookings/reschedule] notice failed', hostId, bookingId, error)\n }\n }\n return res.status(200).json({ ok: true, startsAtMs, endsAtMs: moved.endsAtMs, notified })\n } catch (error) {\n return answer(res, error)\n }\n }\n}\n\n/**\n * Canceling a booking that has no money on it (AGL-3643): a free booking, or\n * a paid one already refunded in full. The site's team used to write\n * `status: 'canceled'` straight from the console; a route is where the\n * cancel can be told to the plugins that listen for it (`booking.canceled`),\n * and where the rule that a paid booking cancels through its refund is held\n * rather than trusted to the screen. One transaction: a booking checked in\n * or paid a moment ago is refused, and canceling it twice changes nothing.\n */\nexport function createBookingCancelHandler(deps: BookingManageDeps): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const body = bodyOf(req)\n const hostId = String(body['hostId'] ?? '')\n const bookingId = String(body['bookingId'] ?? '')\n if (!hostId || !bookingId) return res.status(400).json({ error: 'Missing hostId or bookingId' })\n try {\n const { uid } = await authorize(deps, req, hostId)\n const firestore = deps.firestore()\n const ref = firestore.doc(`hosts/${hostId}/bookings/${bookingId}`)\n const canceled = await firestore.runTransaction(async (transaction) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists) throw new Refusal(404, 'Unknown booking')\n const booking = (snapshot.data() ?? {}) as ManagedBooking & Record<string, unknown>\n const nowMs = deps.now()\n const refusal = cancelRefusal(booking, nowMs)\n if (refusal) throw new Refusal(409, refusal)\n // Already canceled: a retried tap writes nothing and tells no one twice.\n if (bookingState(booking, nowMs) === 'canceled') return null\n transaction.update(ref, { status: 'canceled', canceledAtMs: nowMs, canceledBy: uid })\n return { ...booking, status: 'canceled', canceledAtMs: nowMs }\n })\n if (canceled) {\n await deps.raiseEvent?.({ event: 'booking.canceled', hostId, bookingId, booking: canceled })\n }\n return res.status(200).json({ ok: true, canceled: true })\n } catch (error) {\n return answer(res, error)\n }\n }\n}\n\n/** The email that tells a guest their booking moved, as the confirmation is sent. */\nexport async function sendRescheduledNotice(notice: RescheduleNotice): Promise<void> {\n if (!isEmailConfigured()) throw new Error('Email is not configured')\n const firestore = firebaseAdmin.app().firestore()\n const fallbackText =\n `Hi ${notice.name},\\n\\nYour booking for \"${notice.serviceName}\" is now on ` +\n `${notice.when} (${notice.timezone}). It was on ${notice.previousWhen}.\\n\\n` +\n `Reference: ${notice.bookingId}`\n const designed = await renderHostEmailWithTokens(firestore, notice.hostId, 'booking-rescheduled', {\n name: notice.name,\n 'service.name': notice.serviceName,\n when: notice.when,\n previousWhen: notice.previousWhen,\n timezone: notice.timezone,\n 'booking.ref': notice.bookingId,\n })\n const branding = resolveBrandingProfile((await getOrgForHost(notice.hostId).catch(() => null))?.org as never)\n await sendEmail({\n to: notice.to,\n subject: designed?.subject ?? `New time for ${notice.serviceName}`,\n text: designed?.text || fallbackText,\n ...(designed?.html ? { html: designed.html } : {}),\n fromName: branding.fromName,\n sendingIdentity: await hostSendingIdentity(notice.hostId),\n audience: 'tenant',\n context: 'booking rescheduled',\n owedFor: 'booking',\n })\n await meterHostEmail(notice.hostId)\n}\n\n/** The production wiring: the Admin SDK, the site lockdown verdict and the real send. */\nexport function bookingManageDeps(): BookingManageDeps {\n return {\n firestore: () => firebaseAdmin.app().firestore() as unknown as ManageFirestore,\n verifyIdToken: (token) => firebaseAdmin.app().auth().verifyIdToken(token),\n siteLocked: async (hostId) => Boolean(await getSiteLockdown(hostId)),\n timeZoneFor: async (hostId, service) => {\n const firestore = firebaseAdmin.app().firestore()\n const [host, owner] = await Promise.all([\n firestore.collection('hosts').doc(hostId).get(),\n getOrgForHost(hostId).catch(() => null),\n ])\n return bookingTimeZone({\n service: service ?? null,\n host: host.data() as { timeZone?: string } | undefined,\n org: owner?.org as { timeZone?: string } | null | undefined,\n })\n },\n notifyRescheduled: sendRescheduledNotice,\n now: () => Date.now(),\n raiseEvent: (input) => raiseBookingEvent(firebaseAdmin.app().firestore(), input),\n }\n}\n"],"names":["holdsSiteKey","siteKeyRefusal","isEmailConfigured","sendEmail","firebaseAdmin","getOrgForHost","hostSendingIdentity","meterHostEmail","renderHostEmailWithTokens","getSiteLockdown","resolveBrandingProfile","bookingDurationMs","bookingState","cancelRefusal","checkInRefusal","rescheduleRefusal","isSlotOpen","bookingTimeZone","formatBookingWhen","storedBookingTimeZone","isRefusedIdToken","raiseBookingEvent","CHECKED_IN_AT","CHECKED_IN_BY","Refusal","Error","status","message","bearerOf","req","header","String","headers","startsWith","slice","length","bodyOf","body","JSON","parse","authorize","deps","hostId","token","uid","verifyIdToken","error","host","firestore","doc","get","exists","siteLocked","answer","res","json","console","createBookingCheckInHandler","method","bookingId","checkedIn","ref","result","runTransaction","transaction","snapshot","booking","data","nowMs","now","refusal","already","Number","checkedInAtMs","update","ok","createBookingRescheduleHandler","startsAtMs","isFinite","first","moved","serviceId","serviceSnapshot","service","undefined","previousStartsAtMs","durationMs","durationMinutes","nearby","collection","where","limit","booked","docs","filter","id","map","endsAtMs","rescheduledAtMs","rescheduledBy","rescheduledFromMs","reminderSentAt","notified","raiseEvent","event","to","trim","timezone","timeZoneFor","notifyRescheduled","name","serviceName","when","previousWhen","createBookingCancelHandler","canceled","canceledAtMs","canceledBy","sendRescheduledNotice","notice","app","fallbackText","designed","branding","catch","org","subject","text","html","fromName","sendingIdentity","audience","context","owedFor","bookingManageDeps","auth","Boolean","owner","Promise","all","Date","input"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,YAAY,EAAEC,cAAc,QAAQ,0CAAyC;AAEtF,SAASC,iBAAiB,EAAEC,SAAS,QAAQ,2BAA0B;AACvE,SACEC,aAAa,EACbC,aAAa,EACbC,mBAAmB,EACnBC,cAAc,EACdC,yBAAyB,QACpB,2BAA0B;AACjC,SAASC,eAAe,QAAQ,wDAAuD;AACvF,SAASC,sBAAsB,QAAQ,sBAAqB;AAC5D,SACEC,iBAAiB,EACjBC,YAAY,EACZC,aAAa,EACbC,cAAc,EAEdC,iBAAiB,QACZ,6BAAyB;AAChC,SAAuDC,UAAU,QAAQ,uBAAmB;AAC5F,SAASC,eAAe,EAAEC,iBAAiB,EAAEC,qBAAqB,QAAQ,2BAAuB;AACjG,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAAiCC,iBAAiB,QAAQ,sBAAkB;AAwE5E,qDAAqD,GACrD,OAAO,MAAMC,gBAAgB,gBAAe;AAC5C,OAAO,MAAMC,gBAAgB,cAAa;AAE1C,IAAA,AAAMC,UAAN,MAAMA,gBAAgBC;IACpB,YACE,AAASC,MA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EA,kBAAAA,UAAW;gBACpBpC,MAAMA,KAAKoB,IAAI;gBACf0D,GAAG,EAAEY,yBAAAA,MAAOZ,GAAG;YACjB;QACF;QACAhB,mBAAmBS;QACnBjD,KAAK,IAAMuE,KAAKvE,GAAG;QACnBkC,YAAY,CAACsC,QAAUxH,kBAAkBjB,cAAcoH,GAAG,GAAGxE,SAAS,IAAI6F;IAC5E;AACF"}
@@ -53,7 +53,8 @@ export declare const BOOKING_SERVICE_WINDOWS_PER_DAY_MAX = 12;
53
53
  /** The highest fixed price a draft may state, in whole dollars. */
54
54
  export declare const BOOKING_SERVICE_PRICE_MAX_USD = 100000;
55
55
  /** The resources route's refusal for a member who may not write the site. */
56
- export declare const BOOKING_SERVICE_ROLE_REFUSAL = "Editing requires the editor role";
56
+ /** Names "Edit site content" (`site.edit`, AGL-4047), never a role. */
57
+ export declare const BOOKING_SERVICE_ROLE_REFUSAL: string;
57
58
  /** The resources route's refusal for a plan without the feature. */
58
59
  export declare const BOOKING_SERVICE_PLAN_REFUSAL = "This feature is not included in your plan \u2014 see Billing";
59
60
  /** The resources route's refusal at the plan's allowance. */
@@ -14,8 +14,8 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
14
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
- */ import { hostRoleCanWrite } from "@aglyn/aglyn/app-utils/organizations";
18
- import { checkEntitlement, checkQuota } from "@aglyn/aglyn/app-utils/plan-entitlements";
17
+ */ import { checkEntitlement, checkQuota } from "@aglyn/aglyn/app-utils/plan-entitlements";
18
+ import { holdsSiteKey, siteKeyRefusal } from "@aglyn/aglyn/app-utils/host-permissions";
19
19
  import { countLiveDocuments } from "@aglyn/aglyn/app-utils/live-document-count";
20
20
  import { registerPluginResourceDraftWriter } from "@aglyn/aglyn/plugin-manager/plugin-resource-drafts";
21
21
  import { isValidTimeZone } from "@aglyn/shared-util-timestamp/zoned-time";
@@ -29,7 +29,7 @@ import { BOOKING_MAX_DURATION_MINUTES, BOOKING_MIN_DURATION_MINUTES } from "../m
29
29
  /** The longest description the console's dialog keeps. */ export const BOOKING_SERVICE_DESCRIPTION_MAX = 500;
30
30
  /** The most open intervals one weekday holds. */ export const BOOKING_SERVICE_WINDOWS_PER_DAY_MAX = 12;
31
31
  /** The highest fixed price a draft may state, in whole dollars. */ export const BOOKING_SERVICE_PRICE_MAX_USD = 100000;
32
- /** The resources route's refusal for a member who may not write the site. */ export const BOOKING_SERVICE_ROLE_REFUSAL = 'Editing requires the editor role';
32
+ /** The resources route's refusal for a member who may not write the site. */ /** Names "Edit site content" (`site.edit`, AGL-4047), never a role. */ export const BOOKING_SERVICE_ROLE_REFUSAL = siteKeyRefusal('site.edit');
33
33
  /** The resources route's refusal for a plan without the feature. */ export const BOOKING_SERVICE_PLAN_REFUSAL = 'This feature is not included in your plan — see Billing';
34
34
  /** The resources route's refusal at the plan's allowance. */ export function bookingServiceLimitRefusal(limit) {
35
35
  return `Your plan includes ${limit} ${limit === 1 ? 'service' : 'services'} — ` + 'upgrade in Billing for more';
@@ -204,9 +204,7 @@ function recordOf(service) {
204
204
  };
205
205
  }
206
206
  function roleRefusal(host, uid) {
207
- var _host_get;
208
- const role = ((_host_get = host.get('memberRoles')) != null ? _host_get : {})[uid];
209
- return hostRoleCanWrite(role) ? null : {
207
+ return holdsSiteKey(host, uid, 'site.edit') ? null : {
210
208
  status: 403,
211
209
  error: BOOKING_SERVICE_ROLE_REFUSAL
212
210
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/booking-service-drafts.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 { hostRoleCanWrite } from '@aglyn/aglyn/app-utils/organizations'\nimport { checkEntitlement, checkQuota } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { countLiveDocuments } from '@aglyn/aglyn/app-utils/live-document-count'\nimport {\n registerPluginResourceDraftWriter,\n type PluginDraftCheck,\n type PluginDraftContext,\n type PluginDraftRecord,\n type PluginDraftRefusal,\n type PluginDraftWrite,\n type PluginResourceDraftWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport { isValidTimeZone } from '@aglyn/shared-util-timestamp/zoned-time'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport { BOOKING_FIELD_ASKS, type BookingFieldAsk } from '../model/booking-contact-fields'\nimport {\n BOOKING_PRICE_DISPLAYS,\n type BookingPriceDisplay,\n bookingPriceText,\n} from '../model/booking-price'\nimport {\n BOOKING_MAX_DURATION_MINUTES,\n BOOKING_MIN_DURATION_MINUTES,\n type HostBookingService,\n} from '../model/bookings'\n\n/**\n * A BOOKING SERVICE ANOTHER PLUGIN ASKS FOR (AGL-3616).\n *\n * The draft writer this plugin registers for the `booking-service` resource\n * on the core's resource-drafts seam. A plugin that sets a site up from a\n * brief asks for the writer by name and gets this plugin's rules:\n *\n * - THE DOCUMENT is a `hosts/{hostId}/services/{id}` service in the shape\n * the console's service dialog saves, born `status: 'draft'`. A draft is\n * offered nowhere — not in the Booking block's list, not by its slots, not\n * by the booking route — until a person activates it on the Bookings page.\n * - THE ROOM is the `servicesPerHost` allowance, counted the way the\n * resources route counts it and inside the transaction that creates, so\n * two writes at once cannot both take the last slot. Free includes none.\n * - THE PLAN is the `bookings` feature, and THE ROLE is a member who may\n * write the site's content — the resources route's two gates, refused in\n * its words.\n * - THE PRICE is a label (`contact`, `varies`, `estimate`) unless the\n * content states a fixed price, so nothing the caller did not say is\n * charged. No price stated and no label asked for is `contact`.\n *\n * Nothing is published or charged. The writer touches the one new document.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** The resource name this writer is registered under. */\nexport const BOOKING_SERVICE_DRAFT_RESOURCE = 'booking-service'\n\n/** The longest name the console's dialog keeps. */\nexport const BOOKING_SERVICE_NAME_MAX = 80\n/** The longest description the console's dialog keeps. */\nexport const BOOKING_SERVICE_DESCRIPTION_MAX = 500\n/** The most open intervals one weekday holds. */\nexport const BOOKING_SERVICE_WINDOWS_PER_DAY_MAX = 12\n/** The highest fixed price a draft may state, in whole dollars. */\nexport const BOOKING_SERVICE_PRICE_MAX_USD = 100_000\n\n/** The resources route's refusal for a member who may not write the site. */\nexport const BOOKING_SERVICE_ROLE_REFUSAL = 'Editing requires the editor role'\n/** The resources route's refusal for a plan without the feature. */\nexport const BOOKING_SERVICE_PLAN_REFUSAL =\n 'This feature is not included in your plan — see Billing'\n\n/** The resources route's refusal at the plan's allowance. */\nexport function bookingServiceLimitRefusal(limit: number): string {\n return `Your plan includes ${limit} ${limit === 1 ? 'service' : 'services'} — ` +\n 'upgrade in Billing for more'\n}\n\n/**\n * What a caller sends as `content`. `windows` is keyed by weekday\n * (0 = Sunday … 6 = Saturday), each a list of `{ start, end }` in minutes\n * since midnight in `timezone`. `priceUsd` is read only with\n * `priceDisplay: 'fixed'`, which needs it.\n */\nexport interface BookingServiceDraftContent {\n name: string\n durationMinutes: number\n description?: string\n windows: Partial<Record<number, Array<{ start: number; end: number }>>>\n timezone: string\n priceDisplay?: BookingPriceDisplay\n priceUsd?: number\n askPhone?: BookingFieldAsk\n askAddress?: BookingFieldAsk\n crmFollowUpTask?: boolean\n crmMeetingActivity?: boolean\n}\n\n/** The service document's editable fields, as the writer stores them. */\nexport type BookingServiceDraftFields = Required<\n Pick<HostBookingService, 'name' | 'durationMinutes' | 'windows' | 'timezone' | 'priceDisplay' | 'priceUsd' | 'askPhone' | 'askAddress' | 'crmFollowUpTask' | 'crmMeetingActivity'>\n> &\n Pick<HostBookingService, 'description'>\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Text on one line: controls and runs of space folded to one space. */\nfunction line(value: unknown): string {\n return typeof value === 'string' ? value.replace(/[\\p{Cc}\\s]+/gu, ' ').trim() : ''\n}\n\n/** The weekly windows, or what is wrong with them. */\nfunction readWindows(\n value: unknown,\n problems: string[],\n): BookingServiceDraftFields['windows'] {\n const windows: BookingServiceDraftFields['windows'] = {}\n if (!isRecord(value)) {\n problems.push('The service needs weekly hours: at least one open window on one weekday')\n return windows\n }\n for (const [key, raw] of Object.entries(value)) {\n const weekday = Number(key)\n if (!/^[0-6]$/.test(key) || !Number.isInteger(weekday)) {\n problems.push(`\"${key}\" is not a weekday: weekdays are 0 (Sunday) to 6 (Saturday)`)\n continue\n }\n if (!Array.isArray(raw)) {\n problems.push(`The hours for weekday ${key} are not a list of windows`)\n continue\n }\n if (!raw.length) continue\n if (raw.length > BOOKING_SERVICE_WINDOWS_PER_DAY_MAX) {\n problems.push(`Weekday ${key} has more than ${BOOKING_SERVICE_WINDOWS_PER_DAY_MAX} windows`)\n continue\n }\n const day: Array<{ start: number; end: number }> = []\n for (const window of raw) {\n const start = isRecord(window) ? window['start'] : undefined\n const end = isRecord(window) ? window['end'] : undefined\n if (\n typeof start !== 'number' ||\n typeof end !== 'number' ||\n !Number.isInteger(start) ||\n !Number.isInteger(end) ||\n start < 0 ||\n end > 24 * 60 ||\n end <= start\n ) {\n problems.push(\n `A window on weekday ${key} is not a start before its end, in whole minutes from 0 to 1440`,\n )\n continue\n }\n day.push({ start, end })\n }\n day.sort((a, b) => a.start - b.start)\n if (day.some((window, index) => index > 0 && window.start < day[index - 1].end)) {\n problems.push(`Two windows on weekday ${key} overlap`)\n }\n if (day.length) windows[weekday] = day\n }\n if (!Object.keys(windows).length && !problems.length) {\n problems.push('The service needs weekly hours: at least one open window on one weekday')\n }\n return windows\n}\n\nfunction readAsk(label: string, value: unknown, problems: string[]): BookingFieldAsk {\n if (value === undefined) return 'off'\n if ((BOOKING_FIELD_ASKS as readonly unknown[]).includes(value)) return value as BookingFieldAsk\n problems.push(`Asking for ${label} is off, optional or required`)\n return 'off'\n}\n\nfunction readSwitch(label: string, value: unknown, fallback: boolean, problems: string[]): boolean {\n if (value === undefined) return fallback\n if (typeof value === 'boolean') return value\n problems.push(`${label} is on or off`)\n return fallback\n}\n\nexport type BookingServiceContentRead =\n | { ok: true; value: BookingServiceDraftFields }\n | { ok: false; problems: string[] }\n\n/** The content as the writer stores it, or every problem that stops it. */\nexport function readBookingServiceContent(\n content: Readonly<Record<string, unknown>>,\n): BookingServiceContentRead {\n const problems: string[] = []\n const name = line(content['name'])\n if (!name) problems.push('The service needs a name')\n else if (name.length > BOOKING_SERVICE_NAME_MAX) {\n problems.push(`The name is longer than ${BOOKING_SERVICE_NAME_MAX} characters`)\n }\n const duration = content['durationMinutes']\n if (\n typeof duration !== 'number' ||\n !Number.isInteger(duration) ||\n duration < BOOKING_MIN_DURATION_MINUTES ||\n duration > BOOKING_MAX_DURATION_MINUTES\n ) {\n problems.push(\n `The length is whole minutes from ${BOOKING_MIN_DURATION_MINUTES} to ${BOOKING_MAX_DURATION_MINUTES}`,\n )\n }\n const rawDescription = content['description']\n const description = typeof rawDescription === 'string' ? rawDescription.trim() : ''\n if (rawDescription !== undefined && typeof rawDescription !== 'string') {\n problems.push('The description is text')\n } else if (description.length > BOOKING_SERVICE_DESCRIPTION_MAX) {\n problems.push(`The description is longer than ${BOOKING_SERVICE_DESCRIPTION_MAX} characters`)\n }\n const timezone = line(content['timezone'])\n if (!isValidTimeZone(timezone)) {\n problems.push('The time zone is an IANA zone, such as America/Chicago')\n }\n const windows = readWindows(content['windows'], problems)\n\n // No price stated and no label asked for is \"Contact for price\": a draft\n // never charges what the caller did not say.\n const rawPrice = content['priceUsd']\n const askedDisplay = content['priceDisplay']\n let priceDisplay: BookingPriceDisplay = 'contact'\n let priceUsd = 0\n if (askedDisplay !== undefined) {\n if ((BOOKING_PRICE_DISPLAYS as readonly unknown[]).includes(askedDisplay)) {\n priceDisplay = askedDisplay as BookingPriceDisplay\n } else {\n problems.push('The price is stated as fixed, varies, estimate or contact')\n }\n } else if (rawPrice !== undefined) {\n priceDisplay = 'fixed'\n }\n if (priceDisplay === 'fixed') {\n if (\n typeof rawPrice !== 'number' ||\n !Number.isInteger(rawPrice) ||\n rawPrice < 0 ||\n rawPrice > BOOKING_SERVICE_PRICE_MAX_USD\n ) {\n problems.push(\n `A fixed price is whole dollars from 0 to ${BOOKING_SERVICE_PRICE_MAX_USD}; ` +\n 'state it, or say the price varies, is a free estimate, or is on request',\n )\n } else {\n priceUsd = rawPrice\n }\n }\n const askPhone = readAsk('a phone number', content['askPhone'], problems)\n const askAddress = readAsk('an address', content['askAddress'], problems)\n // The model's defaults: a booking files a meeting, and owes no follow-up.\n const crmMeetingActivity = readSwitch('Filing a meeting', content['crmMeetingActivity'], true, problems)\n const crmFollowUpTask = readSwitch('A follow-up task', content['crmFollowUpTask'], false, problems)\n if (problems.length) return { ok: false, problems: [...new Set(problems)] }\n return {\n ok: true,\n value: {\n name,\n durationMinutes: duration as number,\n ...(description ? { description } : {}),\n windows,\n timezone,\n priceDisplay,\n priceUsd,\n askPhone,\n askAddress,\n crmMeetingActivity,\n crmFollowUpTask,\n },\n }\n}\n\n/** What a caller is told about a service, written or about to be. */\nfunction factsOf(value: Pick<HostBookingService, 'durationMinutes' | 'priceUsd' | 'priceDisplay' | 'timezone' | 'windows'>) {\n return {\n status: 'draft',\n durationMinutes: value.durationMinutes,\n priceDisplay: value.priceDisplay ?? 'fixed',\n priceText: bookingPriceText(value),\n timezone: value.timezone ?? 'UTC',\n openWeekdays: Object.keys(value.windows ?? {})\n .map(Number)\n .sort((a, b) => a - b),\n }\n}\n\n/** Whether content is a service this plugin would store, with what it says about it. Pure. */\nexport function checkBookingServiceContent(\n content: Readonly<Record<string, unknown>>,\n): PluginDraftCheck {\n const read = readBookingServiceContent(content)\n if (read.ok === false) return read\n return { ok: true, facts: factsOf(read.value) }\n}\n\nfunction recordOf(service: FirebaseFirestore.DocumentSnapshot): PluginDraftRecord {\n const data = (service.data() ?? {}) as HostBookingService\n return {\n id: service.id,\n name: String(data.name ?? ''),\n versionId: null,\n facts: { ...factsOf(data), status: data.status === 'draft' ? 'draft' : 'active' },\n }\n}\n\nfunction roleRefusal(host: FirebaseFirestore.DocumentSnapshot, uid: string): PluginDraftRefusal | null {\n const role = (host.get('memberRoles') ?? {})[uid]\n return hostRoleCanWrite(role) ? null : { status: 403, error: BOOKING_SERVICE_ROLE_REFUSAL }\n}\n\nfunction planRefusal(org: PluginDraftContext['org']): PluginDraftRefusal | null {\n return checkEntitlement(org as never, 'bookings')\n ? null\n : { status: 403, error: BOOKING_SERVICE_PLAN_REFUSAL }\n}\n\n/**\n * The allowance, counted as `/api/hosts/resources` counts a service create:\n * every document in the collection.\n */\nfunction roomRefusal(org: PluginDraftContext['org'], used: number): PluginDraftRefusal | null {\n const quota = checkQuota(org as never, 'servicesPerHost', used)\n return quota.allowed ? null : { status: 403, error: bookingServiceLimitRefusal(quota.limit) }\n}\n\nexport interface BookingServiceDraftWriterDeps {\n /** The Admin SDK handle; specs hand in a double. */\n firestore?: () => Firestore\n}\n\nexport function createBookingServiceDraftWriter(\n deps: BookingServiceDraftWriterDeps = {},\n): PluginResourceDraftWriter {\n const firestore = deps.firestore ?? (() => firebaseAdmin.app().firestore() as unknown as Firestore)\n return {\n refusal: async (context) => {\n const hostRef = firestore().collection('hosts').doc(context.hostId)\n const host = await hostRef.get()\n if (!host.exists) return { status: 404, error: 'Unknown site' }\n const early = roleRefusal(host, context.uid) ?? planRefusal(context.org)\n if (early) return early\n const used = await countLiveDocuments(hostRef.collection('services'))\n return roomRefusal(context.org, Number(used) || 0)\n },\n\n check: (content) => checkBookingServiceContent(content),\n\n read: async ({ hostId, id }) => {\n const service = await firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('services')\n .doc(id)\n .get()\n return service.exists ? recordOf(service) : null\n },\n\n write: async (request): Promise<PluginDraftWrite> => {\n // The request's name is the one asked for; the content's stands in.\n const asked = line(request.name)\n const read = readBookingServiceContent(asked ? { ...request.content, name: asked } : request.content)\n if (read.ok === false) return { ok: false, status: 400, error: read.problems[0] }\n const db = firestore()\n const hostRef = db.collection('hosts').doc(request.hostId)\n const servicesRef = hostRef.collection('services')\n const serviceRef = servicesRef.doc(request.id)\n return db.runTransaction(async (tx): Promise<PluginDraftWrite> => {\n // Every read before any write, which Firestore requires.\n const [host, existing] = await Promise.all([tx.get(hostRef), tx.get(serviceRef)])\n if (!host.exists) return { ok: false, status: 404, error: 'Unknown site' }\n // Asked again under the same id: the draft it already wrote.\n if (existing.exists) return { ok: true, replayed: true, ...recordOf(existing) }\n const early = roleRefusal(host, request.uid) ?? planRefusal(request.org)\n if (early) return { ok: false, ...early }\n const used = await countLiveDocuments(servicesRef, (aggregate) => tx.get(aggregate))\n const room = roomRefusal(request.org, Number(used) || 0)\n if (room) return { ok: false, ...room }\n tx.create(serviceRef, {\n ...read.value,\n status: 'draft',\n createdAt: request.now,\n updatedAt: request.now,\n createdBy: request.uid,\n })\n return {\n ok: true,\n replayed: false,\n id: request.id,\n name: read.value.name,\n versionId: null,\n facts: factsOf(read.value),\n }\n })\n },\n }\n}\n\nexport const bookingServiceDraftWriter = createBookingServiceDraftWriter()\n\n/**\n * Registers the writer; the console surface calls it, since only the console\n * runs AI jobs (AGL-3026). Idempotent: a second call replaces the first.\n */\nexport function registerBookingServiceDraftWriter(): void {\n registerPluginResourceDraftWriter(BOOKING_SERVICE_DRAFT_RESOURCE, bookingServiceDraftWriter, {\n pluginId: BUNDLE_ID,\n })\n}\n"],"names":["hostRoleCanWrite","checkEntitlement","checkQuota","countLiveDocuments","registerPluginResourceDraftWriter","isValidTimeZone","firebaseAdmin","BUNDLE_ID","BOOKING_FIELD_ASKS","BOOKING_PRICE_DISPLAYS","bookingPriceText","BOOKING_MAX_DURATION_MINUTES","BOOKING_MIN_DURATION_MINUTES","BOOKING_SERVICE_DRAFT_RESOURCE","BOOKING_SERVICE_NAME_MAX","BOOKING_SERVICE_DESCRIPTION_MAX","BOOKING_SERVICE_WINDOWS_PER_DAY_MAX","BOOKING_SERVICE_PRICE_MAX_USD","BOOKING_SERVICE_ROLE_REFUSAL","BOOKING_SERVICE_PLAN_REFUSAL","bookingServiceLimitRefusal","limit","isRecord","value","Array","isArray","line","replace","trim","readWindows","problems","windows","push","key","raw","Object","entries","weekday","Number","test","isInteger","length","day","window","start","undefined","end","sort","a","b","some","index","keys","readAsk","label","includes","readSwitch","fallback","readBookingServiceContent","content","name","duration","rawDescription","description","timezone","rawPrice","askedDisplay","priceDisplay","priceUsd","askPhone","askAddress","crmMeetingActivity","crmFollowUpTask","ok","Set","durationMinutes","factsOf","status","priceText","openWeekdays","map","checkBookingServiceContent","read","facts","recordOf","service","data","id","String","versionId","roleRefusal","host","uid","role","get","error","planRefusal","org","roomRefusal","used","quota","allowed","createBookingServiceDraftWriter","deps","firestore","app","refusal","context","hostRef","collection","doc","hostId","exists","early","check","write","request","asked","db","servicesRef","serviceRef","runTransaction","tx","existing","Promise","all","replayed","aggregate","room","create","createdAt","now","updatedAt","createdBy","bookingServiceDraftWriter","registerBookingServiceDraftWriter","pluginId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,QAAQ,uCAAsC;AACvE,SAASC,gBAAgB,EAAEC,UAAU,QAAQ,2CAA0C;AACvF,SAASC,kBAAkB,QAAQ,6CAA4C;AAC/E,SACEC,iCAAiC,QAO5B,qDAAoD;AAC3D,SAASC,eAAe,QAAQ,0CAAyC;AACzE,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SAASC,kBAAkB,QAA8B,qCAAiC;AAC1F,SACEC,sBAAsB,EAEtBC,gBAAgB,QACX,4BA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AAO6D,SAAS;gBACtD,IAAI6B,MAAM,OAAO;oBAAEvD,IAAI;mBAAUuD;gBACjCN,GAAGO,MAAM,CAACT,YAAY,aACjBtC,KAAK3D,KAAK;oBACbsD,QAAQ;oBACRqD,WAAWd,QAAQe,GAAG;oBACtBC,WAAWhB,QAAQe,GAAG;oBACtBE,WAAWjB,QAAQxB,GAAG;;gBAExB,OAAO;oBACLnB,IAAI;oBACJqD,UAAU;oBACVvC,IAAI6B,QAAQ7B,EAAE;oBACd3B,MAAMsB,KAAK3D,KAAK,CAACqC,IAAI;oBACrB6B,WAAW;oBACXN,OAAOP,QAAQM,KAAK3D,KAAK;gBAC3B;YACF;QACF;IACF;AACF;AAEA,OAAO,MAAM+G,4BAA4BhC,kCAAiC;AAE1E;;;CAGC,GACD,OAAO,SAASiC;IACdnI,kCAAkCS,gCAAgCyH,2BAA2B;QAC3FE,UAAUjI;IACZ;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/booking-service-drafts.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 { checkEntitlement, checkQuota } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { holdsSiteKey, siteKeyRefusal } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { countLiveDocuments } from '@aglyn/aglyn/app-utils/live-document-count'\nimport {\n registerPluginResourceDraftWriter,\n type PluginDraftCheck,\n type PluginDraftContext,\n type PluginDraftRecord,\n type PluginDraftRefusal,\n type PluginDraftWrite,\n type PluginResourceDraftWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport { isValidTimeZone } from '@aglyn/shared-util-timestamp/zoned-time'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport { BOOKING_FIELD_ASKS, type BookingFieldAsk } from '../model/booking-contact-fields'\nimport {\n BOOKING_PRICE_DISPLAYS,\n type BookingPriceDisplay,\n bookingPriceText,\n} from '../model/booking-price'\nimport {\n BOOKING_MAX_DURATION_MINUTES,\n BOOKING_MIN_DURATION_MINUTES,\n type HostBookingService,\n} from '../model/bookings'\n\n/**\n * A BOOKING SERVICE ANOTHER PLUGIN ASKS FOR (AGL-3616).\n *\n * The draft writer this plugin registers for the `booking-service` resource\n * on the core's resource-drafts seam. A plugin that sets a site up from a\n * brief asks for the writer by name and gets this plugin's rules:\n *\n * - THE DOCUMENT is a `hosts/{hostId}/services/{id}` service in the shape\n * the console's service dialog saves, born `status: 'draft'`. A draft is\n * offered nowhere — not in the Booking block's list, not by its slots, not\n * by the booking route — until a person activates it on the Bookings page.\n * - THE ROOM is the `servicesPerHost` allowance, counted the way the\n * resources route counts it and inside the transaction that creates, so\n * two writes at once cannot both take the last slot. Free includes none.\n * - THE PLAN is the `bookings` feature, and THE ROLE is a member who may\n * write the site's content — the resources route's two gates, refused in\n * its words.\n * - THE PRICE is a label (`contact`, `varies`, `estimate`) unless the\n * content states a fixed price, so nothing the caller did not say is\n * charged. No price stated and no label asked for is `contact`.\n *\n * Nothing is published or charged. The writer touches the one new document.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** The resource name this writer is registered under. */\nexport const BOOKING_SERVICE_DRAFT_RESOURCE = 'booking-service'\n\n/** The longest name the console's dialog keeps. */\nexport const BOOKING_SERVICE_NAME_MAX = 80\n/** The longest description the console's dialog keeps. */\nexport const BOOKING_SERVICE_DESCRIPTION_MAX = 500\n/** The most open intervals one weekday holds. */\nexport const BOOKING_SERVICE_WINDOWS_PER_DAY_MAX = 12\n/** The highest fixed price a draft may state, in whole dollars. */\nexport const BOOKING_SERVICE_PRICE_MAX_USD = 100_000\n\n/** The resources route's refusal for a member who may not write the site. */\n/** Names \"Edit site content\" (`site.edit`, AGL-4047), never a role. */\nexport const BOOKING_SERVICE_ROLE_REFUSAL = siteKeyRefusal('site.edit')\n/** The resources route's refusal for a plan without the feature. */\nexport const BOOKING_SERVICE_PLAN_REFUSAL =\n 'This feature is not included in your plan — see Billing'\n\n/** The resources route's refusal at the plan's allowance. */\nexport function bookingServiceLimitRefusal(limit: number): string {\n return `Your plan includes ${limit} ${limit === 1 ? 'service' : 'services'} — ` +\n 'upgrade in Billing for more'\n}\n\n/**\n * What a caller sends as `content`. `windows` is keyed by weekday\n * (0 = Sunday … 6 = Saturday), each a list of `{ start, end }` in minutes\n * since midnight in `timezone`. `priceUsd` is read only with\n * `priceDisplay: 'fixed'`, which needs it.\n */\nexport interface BookingServiceDraftContent {\n name: string\n durationMinutes: number\n description?: string\n windows: Partial<Record<number, Array<{ start: number; end: number }>>>\n timezone: string\n priceDisplay?: BookingPriceDisplay\n priceUsd?: number\n askPhone?: BookingFieldAsk\n askAddress?: BookingFieldAsk\n crmFollowUpTask?: boolean\n crmMeetingActivity?: boolean\n}\n\n/** The service document's editable fields, as the writer stores them. */\nexport type BookingServiceDraftFields = Required<\n Pick<HostBookingService, 'name' | 'durationMinutes' | 'windows' | 'timezone' | 'priceDisplay' | 'priceUsd' | 'askPhone' | 'askAddress' | 'crmFollowUpTask' | 'crmMeetingActivity'>\n> &\n Pick<HostBookingService, 'description'>\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** Text on one line: controls and runs of space folded to one space. */\nfunction line(value: unknown): string {\n return typeof value === 'string' ? value.replace(/[\\p{Cc}\\s]+/gu, ' ').trim() : ''\n}\n\n/** The weekly windows, or what is wrong with them. */\nfunction readWindows(\n value: unknown,\n problems: string[],\n): BookingServiceDraftFields['windows'] {\n const windows: BookingServiceDraftFields['windows'] = {}\n if (!isRecord(value)) {\n problems.push('The service needs weekly hours: at least one open window on one weekday')\n return windows\n }\n for (const [key, raw] of Object.entries(value)) {\n const weekday = Number(key)\n if (!/^[0-6]$/.test(key) || !Number.isInteger(weekday)) {\n problems.push(`\"${key}\" is not a weekday: weekdays are 0 (Sunday) to 6 (Saturday)`)\n continue\n }\n if (!Array.isArray(raw)) {\n problems.push(`The hours for weekday ${key} are not a list of windows`)\n continue\n }\n if (!raw.length) continue\n if (raw.length > BOOKING_SERVICE_WINDOWS_PER_DAY_MAX) {\n problems.push(`Weekday ${key} has more than ${BOOKING_SERVICE_WINDOWS_PER_DAY_MAX} windows`)\n continue\n }\n const day: Array<{ start: number; end: number }> = []\n for (const window of raw) {\n const start = isRecord(window) ? window['start'] : undefined\n const end = isRecord(window) ? window['end'] : undefined\n if (\n typeof start !== 'number' ||\n typeof end !== 'number' ||\n !Number.isInteger(start) ||\n !Number.isInteger(end) ||\n start < 0 ||\n end > 24 * 60 ||\n end <= start\n ) {\n problems.push(\n `A window on weekday ${key} is not a start before its end, in whole minutes from 0 to 1440`,\n )\n continue\n }\n day.push({ start, end })\n }\n day.sort((a, b) => a.start - b.start)\n if (day.some((window, index) => index > 0 && window.start < day[index - 1].end)) {\n problems.push(`Two windows on weekday ${key} overlap`)\n }\n if (day.length) windows[weekday] = day\n }\n if (!Object.keys(windows).length && !problems.length) {\n problems.push('The service needs weekly hours: at least one open window on one weekday')\n }\n return windows\n}\n\nfunction readAsk(label: string, value: unknown, problems: string[]): BookingFieldAsk {\n if (value === undefined) return 'off'\n if ((BOOKING_FIELD_ASKS as readonly unknown[]).includes(value)) return value as BookingFieldAsk\n problems.push(`Asking for ${label} is off, optional or required`)\n return 'off'\n}\n\nfunction readSwitch(label: string, value: unknown, fallback: boolean, problems: string[]): boolean {\n if (value === undefined) return fallback\n if (typeof value === 'boolean') return value\n problems.push(`${label} is on or off`)\n return fallback\n}\n\nexport type BookingServiceContentRead =\n | { ok: true; value: BookingServiceDraftFields }\n | { ok: false; problems: string[] }\n\n/** The content as the writer stores it, or every problem that stops it. */\nexport function readBookingServiceContent(\n content: Readonly<Record<string, unknown>>,\n): BookingServiceContentRead {\n const problems: string[] = []\n const name = line(content['name'])\n if (!name) problems.push('The service needs a name')\n else if (name.length > BOOKING_SERVICE_NAME_MAX) {\n problems.push(`The name is longer than ${BOOKING_SERVICE_NAME_MAX} characters`)\n }\n const duration = content['durationMinutes']\n if (\n typeof duration !== 'number' ||\n !Number.isInteger(duration) ||\n duration < BOOKING_MIN_DURATION_MINUTES ||\n duration > BOOKING_MAX_DURATION_MINUTES\n ) {\n problems.push(\n `The length is whole minutes from ${BOOKING_MIN_DURATION_MINUTES} to ${BOOKING_MAX_DURATION_MINUTES}`,\n )\n }\n const rawDescription = content['description']\n const description = typeof rawDescription === 'string' ? rawDescription.trim() : ''\n if (rawDescription !== undefined && typeof rawDescription !== 'string') {\n problems.push('The description is text')\n } else if (description.length > BOOKING_SERVICE_DESCRIPTION_MAX) {\n problems.push(`The description is longer than ${BOOKING_SERVICE_DESCRIPTION_MAX} characters`)\n }\n const timezone = line(content['timezone'])\n if (!isValidTimeZone(timezone)) {\n problems.push('The time zone is an IANA zone, such as America/Chicago')\n }\n const windows = readWindows(content['windows'], problems)\n\n // No price stated and no label asked for is \"Contact for price\": a draft\n // never charges what the caller did not say.\n const rawPrice = content['priceUsd']\n const askedDisplay = content['priceDisplay']\n let priceDisplay: BookingPriceDisplay = 'contact'\n let priceUsd = 0\n if (askedDisplay !== undefined) {\n if ((BOOKING_PRICE_DISPLAYS as readonly unknown[]).includes(askedDisplay)) {\n priceDisplay = askedDisplay as BookingPriceDisplay\n } else {\n problems.push('The price is stated as fixed, varies, estimate or contact')\n }\n } else if (rawPrice !== undefined) {\n priceDisplay = 'fixed'\n }\n if (priceDisplay === 'fixed') {\n if (\n typeof rawPrice !== 'number' ||\n !Number.isInteger(rawPrice) ||\n rawPrice < 0 ||\n rawPrice > BOOKING_SERVICE_PRICE_MAX_USD\n ) {\n problems.push(\n `A fixed price is whole dollars from 0 to ${BOOKING_SERVICE_PRICE_MAX_USD}; ` +\n 'state it, or say the price varies, is a free estimate, or is on request',\n )\n } else {\n priceUsd = rawPrice\n }\n }\n const askPhone = readAsk('a phone number', content['askPhone'], problems)\n const askAddress = readAsk('an address', content['askAddress'], problems)\n // The model's defaults: a booking files a meeting, and owes no follow-up.\n const crmMeetingActivity = readSwitch('Filing a meeting', content['crmMeetingActivity'], true, problems)\n const crmFollowUpTask = readSwitch('A follow-up task', content['crmFollowUpTask'], false, problems)\n if (problems.length) return { ok: false, problems: [...new Set(problems)] }\n return {\n ok: true,\n value: {\n name,\n durationMinutes: duration as number,\n ...(description ? { description } : {}),\n windows,\n timezone,\n priceDisplay,\n priceUsd,\n askPhone,\n askAddress,\n crmMeetingActivity,\n crmFollowUpTask,\n },\n }\n}\n\n/** What a caller is told about a service, written or about to be. */\nfunction factsOf(value: Pick<HostBookingService, 'durationMinutes' | 'priceUsd' | 'priceDisplay' | 'timezone' | 'windows'>) {\n return {\n status: 'draft',\n durationMinutes: value.durationMinutes,\n priceDisplay: value.priceDisplay ?? 'fixed',\n priceText: bookingPriceText(value),\n timezone: value.timezone ?? 'UTC',\n openWeekdays: Object.keys(value.windows ?? {})\n .map(Number)\n .sort((a, b) => a - b),\n }\n}\n\n/** Whether content is a service this plugin would store, with what it says about it. Pure. */\nexport function checkBookingServiceContent(\n content: Readonly<Record<string, unknown>>,\n): PluginDraftCheck {\n const read = readBookingServiceContent(content)\n if (read.ok === false) return read\n return { ok: true, facts: factsOf(read.value) }\n}\n\nfunction recordOf(service: FirebaseFirestore.DocumentSnapshot): PluginDraftRecord {\n const data = (service.data() ?? {}) as HostBookingService\n return {\n id: service.id,\n name: String(data.name ?? ''),\n versionId: null,\n facts: { ...factsOf(data), status: data.status === 'draft' ? 'draft' : 'active' },\n }\n}\n\nfunction roleRefusal(host: FirebaseFirestore.DocumentSnapshot, uid: string): PluginDraftRefusal | null {\n return holdsSiteKey(host, uid, 'site.edit') ? null : { status: 403, error: BOOKING_SERVICE_ROLE_REFUSAL }\n}\n\nfunction planRefusal(org: PluginDraftContext['org']): PluginDraftRefusal | null {\n return checkEntitlement(org as never, 'bookings')\n ? null\n : { status: 403, error: BOOKING_SERVICE_PLAN_REFUSAL }\n}\n\n/**\n * The allowance, counted as `/api/hosts/resources` counts a service create:\n * every document in the collection.\n */\nfunction roomRefusal(org: PluginDraftContext['org'], used: number): PluginDraftRefusal | null {\n const quota = checkQuota(org as never, 'servicesPerHost', used)\n return quota.allowed ? null : { status: 403, error: bookingServiceLimitRefusal(quota.limit) }\n}\n\nexport interface BookingServiceDraftWriterDeps {\n /** The Admin SDK handle; specs hand in a double. */\n firestore?: () => Firestore\n}\n\nexport function createBookingServiceDraftWriter(\n deps: BookingServiceDraftWriterDeps = {},\n): PluginResourceDraftWriter {\n const firestore = deps.firestore ?? (() => firebaseAdmin.app().firestore() as unknown as Firestore)\n return {\n refusal: async (context) => {\n const hostRef = firestore().collection('hosts').doc(context.hostId)\n const host = await hostRef.get()\n if (!host.exists) return { status: 404, error: 'Unknown site' }\n const early = roleRefusal(host, context.uid) ?? planRefusal(context.org)\n if (early) return early\n const used = await countLiveDocuments(hostRef.collection('services'))\n return roomRefusal(context.org, Number(used) || 0)\n },\n\n check: (content) => checkBookingServiceContent(content),\n\n read: async ({ hostId, id }) => {\n const service = await firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('services')\n .doc(id)\n .get()\n return service.exists ? recordOf(service) : null\n },\n\n write: async (request): Promise<PluginDraftWrite> => {\n // The request's name is the one asked for; the content's stands in.\n const asked = line(request.name)\n const read = readBookingServiceContent(asked ? { ...request.content, name: asked } : request.content)\n if (read.ok === false) return { ok: false, status: 400, error: read.problems[0] }\n const db = firestore()\n const hostRef = db.collection('hosts').doc(request.hostId)\n const servicesRef = hostRef.collection('services')\n const serviceRef = servicesRef.doc(request.id)\n return db.runTransaction(async (tx): Promise<PluginDraftWrite> => {\n // Every read before any write, which Firestore requires.\n const [host, existing] = await Promise.all([tx.get(hostRef), tx.get(serviceRef)])\n if (!host.exists) return { ok: false, status: 404, error: 'Unknown site' }\n // Asked again under the same id: the draft it already wrote.\n if (existing.exists) return { ok: true, replayed: true, ...recordOf(existing) }\n const early = roleRefusal(host, request.uid) ?? planRefusal(request.org)\n if (early) return { ok: false, ...early }\n const used = await countLiveDocuments(servicesRef, (aggregate) => tx.get(aggregate))\n const room = roomRefusal(request.org, Number(used) || 0)\n if (room) return { ok: false, ...room }\n tx.create(serviceRef, {\n ...read.value,\n status: 'draft',\n createdAt: request.now,\n updatedAt: request.now,\n createdBy: request.uid,\n })\n return {\n ok: true,\n replayed: false,\n id: request.id,\n name: read.value.name,\n versionId: null,\n facts: factsOf(read.value),\n }\n })\n },\n }\n}\n\nexport const bookingServiceDraftWriter = createBookingServiceDraftWriter()\n\n/**\n * Registers the writer; the console surface calls it, since only the console\n * runs AI jobs (AGL-3026). Idempotent: a second call replaces the first.\n */\nexport function registerBookingServiceDraftWriter(): void {\n registerPluginResourceDraftWriter(BOOKING_SERVICE_DRAFT_RESOURCE, bookingServiceDraftWriter, {\n pluginId: BUNDLE_ID,\n })\n}\n"],"names":["checkEntitlement","checkQuota","holdsSiteKey","siteKeyRefusal","countLiveDocuments","registerPluginResourceDraftWriter","isValidTimeZone","firebaseAdmin","BUNDLE_ID","BOOKING_FIELD_ASKS","BOOKING_PRICE_DISPLAYS","bookingPriceText","BOOKING_MAX_DURATION_MINUTES","BOOKING_MIN_DURATION_MINUTES","BOOKING_SERVICE_DRAFT_RESOURCE","BOOKING_SERVICE_NAME_MAX","BOOKING_SERVICE_DESCRIPTION_MAX","BOOKING_SERVICE_WINDOWS_PER_DAY_MAX","BOOKING_SERVICE_PRICE_MAX_USD","BOOKING_SERVICE_ROLE_REFUSAL","BOOKING_SERVICE_PLAN_REFUSAL","bookingServiceLimitRefusal","limit","isRecord","value","Array","isArray","line","replace","trim","readWindows","problems","windows","push","key","raw","Object","entries","weekday","Number","test","isInteger","length","day","window","start","undefined","end","sort","a","b","some","index","keys","readAsk","label","includes","readSwitch","fallback","readBookingServiceContent","content","name","duration","rawDescription","description","timezone","rawPrice","askedDisplay","priceDisplay","priceUsd","askPhone","askAddress","crmMeetingActivity","crmFollowUpTask","ok","Set","durationMinutes","factsOf","status","priceText","openWeekdays","map","checkBookingServiceContent","read","facts","recordOf","service","data","id","String","versionId","roleRefusal","host","uid","error","planRefusal","org","roomRefusal","used","quota","allowed","createBookingServiceDraftWriter","deps","firestore","app","refusal","context","hostRef","collection","doc","hostId","get","exists","early","check","write","request","asked","db","servicesRef","serviceRef","runTransaction","tx","existing","Promise","all","replayed","aggregate","room","create","createdAt","now","updatedAt","createdBy","bookingServiceDraftWriter","registerBookingServiceDraftWriter","pluginId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,EAAEC,UAAU,QAAQ,2CAA0C;AACvF,SAASC,YAAY,EAAEC,cAAc,QAAQ,0CAAyC;AACtF,SAASC,kBAAkB,QAAQ,6CAA4C;AAC/E,SACEC,iCAAiC,QAO5B,qDAAoD;AAC3D,SAASC,eAAe,QAAQ,0CAAyC;AACzE,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SAASC,kBAAkB,QAA8B,qCAAiC;AAC1F,SACEC,sBAAsB,EAEtBC,gBAAgB,QACX,4BAAwB;AAC/B,SACEC,4BAA4B,EAC5BC,4BAA4B,QAEvB,uBAAmB;AA4B1B,uDAAuD,GACvD,OAAO,MAAMC,iCAAiC,kBAAiB;AAE/D,iDAAiD,GACjD,OAAO,MAAMC,2BAA2B,GAAE;AAC1C,wDAAwD,GACxD,OAAO,MAAMC,kCAAkC,IAAG;AAClD,+CAA+C,GAC/C,OAAO,MAAMC,sCAAsC,GAAE;AACrD,iEAAiE,GACjE,OAAO,MAAMC,gCAAgC,OAAO;AAEpD,2EAA2E,GAC3E,qEAA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B;YACF;QACF;IACF;AACF;AAEA,OAAO,MAAM8G,4BAA4BjC,kCAAiC;AAE1E;;;CAGC,GACD,OAAO,SAASkC;IACdlI,kCAAkCS,gCAAgCwH,2BAA2B;QAC3FE,UAAUhI;IACZ;AACF"}
@@ -0,0 +1,29 @@
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 BookingsSitePermission } from '../model/bookings-permissions';
18
+ /**
19
+ * Does this member hold one of bookings' keys on this site, as the rules
20
+ * would read a site key (AGL-4047): the site's `memberPermissions` stamp,
21
+ * else the preset of their `memberRoles` entry. `hostDoc` is the host
22
+ * snapshot or its data, which every door here reads already.
23
+ */
24
+ export declare function holdsBookingsSiteKey(hostDoc: {
25
+ get(field: string): unknown;
26
+ } | {
27
+ memberPermissions?: unknown;
28
+ memberRoles?: unknown;
29
+ } | null | undefined, uid: string, key: BookingsSitePermission): boolean;
@@ -0,0 +1,40 @@
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 { hostStampedSitePermission } from "@aglyn/aglyn/app-utils/host-permissions";
17
+ import { BOOKINGS_SITE_PERMISSIONS } from "../model/bookings-permissions.js";
18
+ const BOOKINGS_SITE_PRESETS = Object.fromEntries(BOOKINGS_SITE_PERMISSIONS.map((entry)=>{
19
+ var _entry_hostRoleDefaults;
20
+ return [
21
+ entry.key,
22
+ (_entry_hostRoleDefaults = entry.hostRoleDefaults) != null ? _entry_hostRoleDefaults : {}
23
+ ];
24
+ }));
25
+ /**
26
+ * Does this member hold one of bookings' keys on this site, as the rules
27
+ * would read a site key (AGL-4047): the site's `memberPermissions` stamp,
28
+ * else the preset of their `memberRoles` entry. `hostDoc` is the host
29
+ * snapshot or its data, which every door here reads already.
30
+ */ export function holdsBookingsSiteKey(hostDoc, uid, key) {
31
+ var _BOOKINGS_SITE_PRESETS_key;
32
+ if (!hostDoc || !uid) return false;
33
+ const read = (field)=>typeof hostDoc.get === 'function' ? hostDoc.get(field) : hostDoc[field];
34
+ return hostStampedSitePermission({
35
+ memberPermissions: read('memberPermissions'),
36
+ memberRoles: read('memberRoles')
37
+ }, uid, key, (_BOOKINGS_SITE_PRESETS_key = BOOKINGS_SITE_PRESETS[key]) != null ? _BOOKINGS_SITE_PRESETS_key : {});
38
+ }
39
+
40
+ //# sourceMappingURL=bookings-site-keys.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/bookings-site-keys.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 { hostStampedSitePermission } from '@aglyn/aglyn/app-utils/host-permissions'\nimport type { HostAccessRole } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport { BOOKINGS_SITE_PERMISSIONS, type BookingsSitePermission } from '../model/bookings-permissions'\n\nconst BOOKINGS_SITE_PRESETS: Readonly<Record<string, Readonly<Partial<Record<HostAccessRole, boolean>>>>> =\n Object.fromEntries(BOOKINGS_SITE_PERMISSIONS.map((entry) => [entry.key, entry.hostRoleDefaults ?? {}]))\n\n/**\n * Does this member hold one of bookings' keys on this site, as the rules\n * would read a site key (AGL-4047): the site's `memberPermissions` stamp,\n * else the preset of their `memberRoles` entry. `hostDoc` is the host\n * snapshot or its data, which every door here reads already.\n */\nexport function holdsBookingsSiteKey(\n hostDoc: { get(field: string): unknown } | { memberPermissions?: unknown; memberRoles?: unknown } | null | undefined,\n uid: string,\n key: BookingsSitePermission,\n): boolean {\n if (!hostDoc || !uid) return false\n const read = (field: string): unknown =>\n typeof (hostDoc as { get?: unknown }).get === 'function'\n ? (hostDoc as { get(field: string): unknown }).get(field)\n : (hostDoc as Record<string, unknown>)[field]\n return hostStampedSitePermission(\n { memberPermissions: read('memberPermissions'), memberRoles: read('memberRoles') },\n uid,\n key,\n BOOKINGS_SITE_PRESETS[key] ?? {},\n )\n}\n"],"names":["hostStampedSitePermission","BOOKINGS_SITE_PERMISSIONS","BOOKINGS_SITE_PRESETS","Object","fromEntries","map","entry","key","hostRoleDefaults","holdsBookingsSiteKey","hostDoc","uid","read","field","get","memberPermissions","memberRoles"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,yBAAyB,QAAQ,0CAAyC;AAEnF,SAASC,yBAAyB,QAAqC,mCAA+B;AAEtG,MAAMC,wBACJC,OAAOC,WAAW,CAACH,0BAA0BI,GAAG,CAAC,CAACC;QAAsBA;WAAZ;QAACA,MAAMC,GAAG;SAAED,0BAAAA,MAAME,gBAAgB,YAAtBF,0BAA0B,CAAC;KAAE;;AAEvG;;;;;CAKC,GACD,OAAO,SAASG,qBACdC,OAAoH,EACpHC,GAAW,EACXJ,GAA2B;QAWzBL;IATF,IAAI,CAACQ,WAAW,CAACC,KAAK,OAAO;IAC7B,MAAMC,OAAO,CAACC,QACZ,OAAO,AAACH,QAA8BI,GAAG,KAAK,aAC1C,AAACJ,QAA4CI,GAAG,CAACD,SACjD,AAACH,OAAmC,CAACG,MAAM;IACjD,OAAOb,0BACL;QAAEe,mBAAmBH,KAAK;QAAsBI,aAAaJ,KAAK;IAAe,GACjFD,KACAJ,MACAL,6BAAAA,qBAAqB,CAACK,IAAI,YAA1BL,6BAA8B,CAAC;AAEnC"}
@@ -20,6 +20,8 @@ import { merchantAccountIsReady } from "@aglyn/tenant-data-admin/server/payment-
20
20
  import { checkEntitlement, resolveTransactionFeeCents } from "@aglyn/aglyn/server";
21
21
  import { pluginTaxProfile } from "@aglyn/aglyn/plugin-manager/plugin-tax-profile";
22
22
  import { bookingInPersonAmountProblem, bookingInPersonState } from "../model/booking-in-person.js";
23
+ import { bookingsSitePermissionRefusal } from "../model/bookings-permissions.js";
24
+ import { holdsBookingsSiteKey } from "./bookings-site-keys.js";
23
25
  import { isRefusedIdToken } from "@aglyn/tenant-data-admin/server/id-token-refusal";
24
26
  /*==========================================
25
27
  * `POST /api/bookings/in-person-payment` (AGL-3618).
@@ -97,7 +99,7 @@ function stripeMessage(body, fallback) {
97
99
  return typeof message === 'string' && message ? message : fallback;
98
100
  }
99
101
  async function authorize(req, hostId) {
100
- var _req_headers_authorization, _host_get, _ref;
102
+ var _req_headers_authorization, _ref;
101
103
  var _this;
102
104
  const authorization = String((_req_headers_authorization = req.headers.authorization) != null ? _req_headers_authorization : '');
103
105
  const idToken = authorization.startsWith('Bearer ') ? authorization.slice(7) : '';
@@ -128,12 +130,15 @@ async function authorize(req, hostId) {
128
130
  status: 404,
129
131
  error: 'Unknown site'
130
132
  };
131
- const role = ((_host_get = host.get('memberRoles')) != null ? _host_get : {})[uid];
132
- if (role !== 'admin' && role !== 'editor') return {
133
- ok: false,
134
- status: 403,
135
- error: 'Not permitted'
136
- };
133
+ // "Take booking payments in person" (AGL-4047), whose preset is the site
134
+ // Admin and Editor who took them before.
135
+ if (!holdsBookingsSiteKey(host, uid, 'bookings.payments')) {
136
+ return {
137
+ ok: false,
138
+ status: 403,
139
+ error: bookingsSitePermissionRefusal('bookings.payments')
140
+ };
141
+ }
137
142
  const org = (_ref = (_this = await getOrgForHost(hostId)) == null ? void 0 : _this.org) != null ? _ref : null;
138
143
  if (!checkEntitlement(org, 'bookings') || !checkEntitlement(org, 'pos')) {
139
144
  return {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/in-person-payment.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 { createHash } from 'crypto'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { merchantAccountIsReady } from '@aglyn/tenant-data-admin/server/payment-provider'\nimport {\n checkEntitlement,\n resolveTransactionFeeCents,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport { pluginTaxProfile } from '@aglyn/aglyn/plugin-manager/plugin-tax-profile'\nimport {\n bookingInPersonAmountProblem,\n bookingInPersonState,\n type BookingInPersonPayment,\n} from '../model/booking-in-person'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\n\n/*==========================================\n * `POST /api/bookings/in-person-payment` (AGL-3618).\n *\n * Takes payment for a booking at the counter, on the card reader the native\n * Aglyn POS app has connected (Tap to Pay or a Bluetooth reader). The server\n * owns the money; the app only presents the card:\n *\n * - `start` prices the charge (the amount staff typed, plus the merchant's\n * own service tax), and creates a card-present PaymentIntent: a\n * DESTINATION charge to the merchant, settled on Aglyn's platform account\n * with no `on_behalf_of` (ToS §10.7, AGL-3607), with the take and\n * Stripe's card cost as `application_fee_amount` — exactly the fee a paid\n * booking already carries online (`resolveTransactionFeeCents`, `service`).\n * Returns the intent's client secret for the app's Terminal SDK.\n * - `settle` re-reads the intent from Stripe (never trusting the app's word),\n * captures an authorized one, and records the booking paid with the same\n * fields an online payment writes, so the console's refund and the dispute\n * handling work on it unchanged.\n * - `cancel` releases an intent that was not collected.\n *\n * MANUAL capture, so a card that authorizes but whose booking was changed in\n * between is released rather than charged. On-reader tipping is not offered\n * here; the amount is the amount.\n *\n * Gate: a site `admin` or `editor`, and the owning org's `bookings` and\n * `pos` entitlements (taking card-present payments is a POS capability).\n *=========================================*/\n\nconst BOOKING_ID = /^[A-Za-z0-9_-]{1,128}$/\nconst PAYMENT_INTENT_ID = /^pi_[A-Za-z0-9_]{6,128}$/\n\ntype Res = Parameters<PluginApiHandler>[1]\n\ninterface Staff {\n uid: string\n hostId: string\n org: Record<string, any> | null\n}\n\nfunction requestBody(req: Parameters<PluginApiHandler>[0]): Record<string, any> {\n if (typeof req.body === 'string') {\n try {\n const parsed = JSON.parse(req.body)\n return parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n return {}\n }\n }\n return req.body && typeof req.body === 'object' ? req.body : {}\n}\n\n/** Card-present payments: always in test mode, in live mode once switched on. */\nexport function inPersonCardsAvailable(): boolean {\n const key = String(process.env.STRIPE_SECRET_KEY ?? '')\n if (!key) return false\n return (\n key.startsWith('sk_test_') ||\n String(process.env.STRIPE_TERMINAL_LIVE_ENABLED ?? '').toLowerCase() === 'true'\n )\n}\n\nasync function stripe(\n method: 'GET' | 'POST',\n path: string,\n options: { params?: Record<string, string | number | boolean | undefined>; idempotencyKey?: string } = {},\n): Promise<{ ok: boolean; status: number; body: any }> {\n const form = new URLSearchParams()\n for (const [key, value] of Object.entries(options.params ?? {})) {\n if (value !== undefined) form.append(key, String(value))\n }\n const query = method === 'GET' && form.toString() ? `?${form}` : ''\n const response = await fetch(`https://api.stripe.com/v1/${path}${query}`, {\n method,\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...(options.idempotencyKey ? { 'Idempotency-Key': options.idempotencyKey } : {}),\n },\n ...(method === 'POST' ? { body: form.toString() } : {}),\n })\n const body = await response.json().catch(() => null)\n return { ok: response.ok, status: response.status, body }\n}\n\nfunction stripeMessage(body: any, fallback: string): string {\n const message = body?.error?.message\n return typeof message === 'string' && message ? message : fallback\n}\n\nasync function authorize(\n req: Parameters<PluginApiHandler>[0],\n hostId: string,\n): Promise<{ ok: true; staff: Staff } | { ok: false; status: number; error: string }> {\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ') ? authorization.slice(7) : ''\n if (!idToken) return { ok: false, status: 401, error: 'Unauthenticated' }\n if (!hostId) return { ok: false, status: 400, error: 'Missing hostId' }\n let uid: string\n try {\n uid = (await firebaseAdmin.app().auth().verifyIdToken(idToken)).uid\n } catch (error) {\n if (!isRefusedIdToken(error)) throw error\n return { ok: false, status: 401, error: 'Unauthenticated' }\n }\n const host = await firebaseAdmin.app().firestore().collection('hosts').doc(hostId).get()\n if (!host.exists) return { ok: false, status: 404, error: 'Unknown site' }\n const role = (host.get('memberRoles') ?? {})[uid]\n if (role !== 'admin' && role !== 'editor') return { ok: false, status: 403, error: 'Not permitted' }\n const org = ((await getOrgForHost(hostId))?.org as Record<string, any> | undefined) ?? null\n if (!checkEntitlement(org as never, 'bookings') || !checkEntitlement(org as never, 'pos')) {\n return { ok: false, status: 403, error: 'Taking booking payments in person needs the POS plan.' }\n }\n return { ok: true, staff: { uid, hostId, org } }\n}\n\nexport const bookingInPersonPaymentHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const body = requestBody(req)\n const hostId = String(body['hostId'] ?? '')\n const bookingId = String(body['bookingId'] ?? '')\n const gate = await authorize(req, hostId)\n if ('error' in gate) return res.status(gate.status).json({ error: gate.error })\n if (!BOOKING_ID.test(bookingId)) return res.status(400).json({ error: 'Missing bookingId' })\n if (!inPersonCardsAvailable()) {\n return res.status(409).json({ error: 'Card readers are not available yet.' })\n }\n const action = String(body['action'] ?? '')\n try {\n switch (action) {\n case 'start':\n return await start(gate.staff, bookingId, body, req, res)\n case 'settle':\n return await settle(gate.staff, bookingId, res)\n case 'cancel':\n return await cancel(gate.staff, bookingId, res)\n default:\n return res.status(400).json({ error: 'Unknown action' })\n }\n } catch (error) {\n console.error('[bookings/in-person-payment]', action, error)\n return res.status(500).json({ error: 'The payment could not be updated. Check the booking before trying again.' })\n }\n}\n\nfunction bookingRef(hostId: string, bookingId: string) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('bookings')\n .doc(bookingId)\n}\n\nasync function merchantAccount(org: Record<string, any> | null, hostId: string): Promise<string | null> {\n const ownerUid = String(org?.['ownerUid'] ?? '')\n if (!ownerUid) return null\n const profile = await firebaseAdmin.app().firestore().collection('profiles').doc(ownerUid).get()\n const accountId = String(profile.get('stripeAccountId') ?? '')\n return merchantAccountIsReady(\n {\n accountId,\n chargesEnabled: profile.get('stripeChargesEnabled'),\n accountLivemode: profile.get('stripeAccountLivemode'),\n },\n { subject: `booking in-person host ${hostId}` },\n )\n ? accountId\n : null\n}\n\nasync function start(\n staff: Staff,\n bookingId: string,\n body: Record<string, any>,\n req: Parameters<PluginApiHandler>[0],\n res: Res,\n) {\n const attemptKey = String(req.headers['idempotency-key'] ?? req.headers['Idempotency-Key'] ?? '')\n .trim()\n .slice(0, 200)\n if (!attemptKey) return res.status(400).json({ error: 'Missing Idempotency-Key' })\n const serviceCents = typeof body['amountCents'] === 'number' ? body['amountCents'] : NaN\n const problem = bookingInPersonAmountProblem(serviceCents)\n if (problem) return res.status(400).json({ error: problem })\n\n const ref = bookingRef(staff.hostId, bookingId)\n const snapshot = await ref.get()\n if (!snapshot.exists) return res.status(404).json({ error: 'Unknown booking' })\n const booking = snapshot.data() as Record<string, any>\n const state = bookingInPersonState(booking)\n const existing = booking['inPersonPayment'] as BookingInPersonPayment | undefined\n const attempt = createHash('sha256').update(`${bookingId}:${attemptKey}`).digest('hex').slice(0, 40)\n\n if (state === 'paid') return res.status(409).json({ error: 'This booking is already paid.' })\n if (state === 'canceled') return res.status(409).json({ error: 'This booking was canceled.' })\n if (state === 'awaiting-online') {\n return res.status(409).json({ error: 'The customer is paying for this booking online right now.' })\n }\n\n const destination = await merchantAccount(staff.org, staff.hostId)\n if (!destination) return res.status(409).json({ error: 'Finish setting up payments before taking cards.' })\n\n // The merchant's own service tax, off unless they set one (AGL-2028): the\n // same rate a paid booking is charged online.\n const tax = pluginTaxProfile().flatTax(\n await pluginTaxProfile().flatRate(staff.hostId, 'service'),\n serviceCents,\n 'Service tax',\n )\n const amountCents = serviceCents + tax.taxCents\n const feeCents = resolveTransactionFeeCents(staff.org as never, 'service', serviceCents, amountCents)\n\n // A pending intent for this booking that is not this attempt's: release it\n // first, so one booking never has two cards in flight.\n if (existing?.status === 'pending' && existing.paymentIntentId) {\n const sameAttempt = existing.attempt === attempt\n if (sameAttempt) {\n const replay = await stripe('GET', `payment_intents/${existing.paymentIntentId}`)\n if (replay.ok && replay.body?.client_secret) {\n return res.status(200).json(startAnswer(existing, String(replay.body.client_secret)))\n }\n } else {\n const released = await releaseIntent(existing.paymentIntentId)\n if (!released) {\n return res.status(409).json({\n error: 'A card was already authorized for this booking. Settle it before starting another payment.',\n })\n }\n }\n }\n\n const intent = await stripe('POST', 'payment_intents', {\n idempotencyKey: `booking-in-person:${attempt}`,\n params: {\n amount: amountCents,\n currency: 'usd',\n 'payment_method_types[]': 'card_present',\n capture_method: 'manual',\n 'transfer_data[destination]': destination,\n ...(feeCents > 0 ? { application_fee_amount: feeCents } : {}),\n description: `Booking: ${String(booking['serviceName'] ?? 'appointment').slice(0, 80)}`,\n 'metadata[type]': 'booking-in-person',\n 'metadata[hostId]': staff.hostId,\n 'metadata[bookingId]': bookingId,\n 'metadata[feeCents]': feeCents,\n 'metadata[cashierId]': staff.uid,\n ...(tax.taxCents > 0 ? { 'metadata[taxCents]': tax.taxCents, 'metadata[taxPct]': tax.pct } : {}),\n },\n })\n if (!intent.ok || !intent.body?.id || !intent.body?.client_secret) {\n return res.status(502).json({ error: stripeMessage(intent.body, 'The card payment could not be started.') })\n }\n const payment: BookingInPersonPayment = {\n paymentIntentId: String(intent.body.id),\n amountCents,\n serviceCents,\n taxCents: tax.taxCents,\n feeCents,\n status: 'pending',\n startedAtMs: Date.now(),\n startedBy: staff.uid,\n attempt,\n }\n // Recorded in a transaction that re-checks the booking: a payment that\n // landed meanwhile (online, or on another device) wins, and this intent is\n // released instead of left to authorize a second charge.\n const recorded = await firebaseAdmin.app().firestore().runTransaction(async (transaction: any) => {\n const fresh = await transaction.get(ref)\n const freshState = bookingInPersonState((fresh.data() ?? {}) as Record<string, any>)\n const freshPending = fresh.get('inPersonPayment') as BookingInPersonPayment | undefined\n if (freshState === 'paid' || freshState === 'canceled' || freshState === 'awaiting-online') return false\n if (\n freshPending?.status === 'pending' &&\n freshPending.paymentIntentId !== payment.paymentIntentId &&\n freshPending.paymentIntentId !== existing?.paymentIntentId\n ) {\n return false\n }\n transaction.set(ref, { inPersonPayment: payment }, { merge: true })\n return true\n })\n if (!recorded) {\n await releaseIntent(payment.paymentIntentId)\n return res.status(409).json({ error: 'This booking changed while the payment started. Open it again.' })\n }\n return res.status(200).json(startAnswer(payment, String(intent.body.client_secret)))\n}\n\nfunction startAnswer(payment: BookingInPersonPayment, clientSecret: string) {\n return {\n paymentIntentId: payment.paymentIntentId,\n clientSecret,\n amountCents: payment.amountCents,\n serviceCents: payment.serviceCents,\n taxCents: payment.taxCents,\n }\n}\n\n/** Cancels an intent that holds no money yet; false when it does. */\nasync function releaseIntent(paymentIntentId: string): Promise<boolean> {\n const current = await stripe('GET', `payment_intents/${paymentIntentId}`)\n const status = String(current.body?.status ?? '')\n if (status === 'canceled') return true\n if (status === 'succeeded' || status === 'requires_capture' || status === 'processing') return false\n const canceled = await stripe('POST', `payment_intents/${paymentIntentId}/cancel`, {\n idempotencyKey: `booking-in-person-cancel:${paymentIntentId}`,\n })\n return canceled.ok || String(canceled.body?.status ?? '') === 'canceled'\n}\n\nasync function settle(staff: Staff, bookingId: string, res: Res) {\n const ref = bookingRef(staff.hostId, bookingId)\n const snapshot = await ref.get()\n if (!snapshot.exists) return res.status(404).json({ error: 'Unknown booking' })\n const payment = snapshot.get('inPersonPayment') as BookingInPersonPayment | undefined\n if (payment?.status === 'paid') return res.status(200).json({ status: 'paid', amountCents: payment.amountCents })\n if (!payment || payment.status !== 'pending' || !PAYMENT_INTENT_ID.test(String(payment.paymentIntentId))) {\n return res.status(409).json({ error: 'No card payment is in progress for this booking.' })\n }\n let intent = (await stripe('GET', `payment_intents/${payment.paymentIntentId}`)).body\n // The intent must be the one this route made for THIS booking on THIS site.\n if (\n intent?.metadata?.type !== 'booking-in-person' ||\n intent?.metadata?.hostId !== staff.hostId ||\n intent?.metadata?.bookingId !== bookingId\n ) {\n return res.status(409).json({ error: 'That payment is not for this booking.' })\n }\n if (intent.status === 'requires_capture') {\n const captured = await stripe('POST', `payment_intents/${payment.paymentIntentId}/capture`, {\n idempotencyKey: `booking-in-person-capture:${payment.paymentIntentId}`,\n params: payment.feeCents > 0 ? { application_fee_amount: payment.feeCents } : {},\n })\n if (!captured.ok) {\n return res.status(502).json({ error: stripeMessage(captured.body, 'The card could not be charged. Try again.') })\n }\n intent = captured.body\n }\n if (intent?.status !== 'succeeded') {\n // Not collected yet, declined, or canceled: the booking stays payable.\n const status = intent?.status === 'canceled' ? 'canceled' : 'pending'\n if (status === 'canceled') {\n await ref.set({ inPersonPayment: { ...payment, status: 'canceled' } }, { merge: true })\n }\n return res.status(200).json({ status })\n }\n const paidAmountCents = Math.max(0, Math.round(Number(intent.amount_received ?? intent.amount ?? 0)))\n const paidAtMs = Date.now()\n await firebaseAdmin.app().firestore().runTransaction(async (transaction: any) => {\n const fresh = await transaction.get(ref)\n if (fresh.get('paymentIntentId')) return\n transaction.set(\n ref,\n {\n // The same fields an online payment writes (billing-webhook.ts), so\n // the console's refund and dispute handling read it unchanged.\n paidAmountCents,\n paymentIntentId: payment.paymentIntentId,\n feeCents: payment.feeCents,\n taxMode: pluginTaxProfile().taxModeOf(intent, payment.taxCents),\n ...(payment.taxCents > 0 ? { taxCents: payment.taxCents } : {}),\n paidInPerson: true,\n inPersonPayment: { ...payment, status: 'paid', paidAtMs },\n },\n { merge: true },\n )\n })\n return res.status(200).json({ status: 'paid', amountCents: paidAmountCents })\n}\n\nasync function cancel(staff: Staff, bookingId: string, res: Res) {\n const ref = bookingRef(staff.hostId, bookingId)\n const snapshot = await ref.get()\n if (!snapshot.exists) return res.status(404).json({ error: 'Unknown booking' })\n const payment = snapshot.get('inPersonPayment') as BookingInPersonPayment | undefined\n if (!payment || payment.status !== 'pending') return res.status(200).json({ status: 'none' })\n if (!(await releaseIntent(payment.paymentIntentId))) {\n return res.status(409).json({ error: 'The card was already authorized. Settle the payment instead.' })\n }\n await ref.set({ inPersonPayment: { ...payment, status: 'canceled' } }, { merge: true })\n return res.status(200).json({ status: 'canceled' })\n}\n"],"names":["createHash","firebaseAdmin","getOrgForHost","merchantAccountIsReady","checkEntitlement","resolveTransactionFeeCents","pluginTaxProfile","bookingInPersonAmountProblem","bookingInPersonState","isRefusedIdToken","BOOKING_ID","PAYMENT_INTENT_ID","requestBody","req","body","parsed","JSON","parse","inPersonCardsAvailable","process","key","String","env","STRIPE_SECRET_KEY","startsWith","STRIPE_TERMINAL_LIVE_ENABLED","toLowerCase","stripe","method","path","options","form","URLSearchParams","value","Object","entries","params","undefined","append","query","toString","response","fetch","headers","Authorization","idempotencyKey","json","catch","ok","status","stripeMessage","fallback","message","error","authorize","hostId","host","authorization","idToken","slice","uid","app","auth","verifyIdToken","firestore","collection","doc","get","exists","role","org","staff","bookingInPersonPaymentHandler","res","bookingId","gate","test","action","start","settle","cancel","console","bookingRef","merchantAccount","profile","ownerUid","accountId","chargesEnabled","accountLivemode","subject","booking","intent","attemptKey","trim","serviceCents","NaN","problem","ref","snapshot","data","state","existing","attempt","update","digest","destination","tax","flatTax","flatRate","amountCents","taxCents","feeCents","paymentIntentId","sameAttempt","replay","client_secret","startAnswer","released","releaseIntent","amount","currency","capture_method","application_fee_amount","description","pct","id","payment","startedAtMs","Date","now","startedBy","recorded","runTransaction","transaction","fresh","freshState","freshPending","set","inPersonPayment","merge","clientSecret","current","canceled","metadata","type","captured","paidAmountCents","Math","max","round","Number","amount_received","paidAtMs","taxMode","taxModeOf","paidInPerson"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,SAAQ;AACnC,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,sBAAsB,QAAQ,mDAAkD;AACzF,SACEC,gBAAgB,EAChBC,0BAA0B,QAErB,sBAAqB;AAC5B,SAASC,gBAAgB,QAAQ,iDAAgD;AACjF,SACEC,4BAA4B,EAC5BC,oBAAoB,QAEf,gCAA4B;AACnC,SAASC,gBAAgB,QAAQ,mDAAkD;AAEnF;;;;;;;;;;;;;;;;;;;;;;;;;;2CA0B2C,GAE3C,MAAMC,aAAa;AACnB,MAAMC,oBAAoB;AAU1B,SAASC,YAAYC,GAAoC;IACvD,IAAI,OAAOA,IAAIC,IAAI,KAAK,UAAU;QAChC,IAAI;YACF,MAAMC,SAASC,KAAKC,KAAK,CAACJ,IAAIC,IAAI;YAClC,OAAOC,UAAU,OAAOA,WAAW,WAAWA,SAAS,CAAC;QAC1D,EAAE,eAAM;YACN,OAAO,CAAC;QACV;IACF;IACA,OAAOF,IAAIC,IAAI,IAAI,OAAOD,IAAIC,IAAI,KAAK,WAAWD,IAAIC,IAAI,GAAG,C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AmBoJ,SAAS,CAAC/D,QAAQmC,QAAQhB,QAAQ;WAC1DgB,QAAQhB,QAAQ,GAAG,IAAI;YAAEA,UAAUgB,QAAQhB,QAAQ;QAAC,IAAI,CAAC;YAC7D6C,cAAc;YACdjB,iBAAiB,aAAKZ;gBAAS7E,QAAQ;gBAAQuG;;YAEjD;YAAEb,OAAO;QAAK;IAElB;IACA,OAAOlE,IAAIxB,MAAM,CAAC,KAAKH,IAAI,CAAC;QAAEG,QAAQ;QAAQ4D,aAAaqC;IAAgB;AAC7E;AAEA,eAAelE,OAAOT,KAAY,EAAEG,SAAiB,EAAED,GAAQ;IAC7D,MAAMwB,MAAMf,WAAWX,MAAMhB,MAAM,EAAEmB;IACrC,MAAMwB,WAAW,MAAMD,IAAI9B,GAAG;IAC9B,IAAI,CAAC+B,SAAS9B,MAAM,EAAE,OAAOK,IAAIxB,MAAM,CAAC,KAAKH,IAAI,CAAC;QAAEO,OAAO;IAAkB;IAC7E,MAAMyE,UAAU5B,SAAS/B,GAAG,CAAC;IAC7B,IAAI,CAAC2D,WAAWA,QAAQ7E,MAAM,KAAK,WAAW,OAAOwB,IAAIxB,MAAM,CAAC,KAAKH,IAAI,CAAC;QAAEG,QAAQ;IAAO;IAC3F,IAAI,CAAE,MAAMqE,cAAcQ,QAAQd,eAAe,GAAI;QACnD,OAAOvC,IAAIxB,MAAM,CAAC,KAAKH,IAAI,CAAC;YAAEO,OAAO;QAA+D;IACtG;IACA,MAAM4C,IAAIwC,GAAG,CAAC;QAAEC,iBAAiB,aAAKZ;YAAS7E,QAAQ;;IAAa,GAAG;QAAE0F,OAAO;IAAK;IACrF,OAAOlE,IAAIxB,MAAM,CAAC,KAAKH,IAAI,CAAC;QAAEG,QAAQ;IAAW;AACnD"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/in-person-payment.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 { createHash } from 'crypto'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { merchantAccountIsReady } from '@aglyn/tenant-data-admin/server/payment-provider'\nimport {\n checkEntitlement,\n resolveTransactionFeeCents,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport { pluginTaxProfile } from '@aglyn/aglyn/plugin-manager/plugin-tax-profile'\nimport {\n bookingInPersonAmountProblem,\n bookingInPersonState,\n type BookingInPersonPayment,\n} from '../model/booking-in-person'\nimport { bookingsSitePermissionRefusal } from '../model/bookings-permissions'\nimport { holdsBookingsSiteKey } from './bookings-site-keys'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\n\n/*==========================================\n * `POST /api/bookings/in-person-payment` (AGL-3618).\n *\n * Takes payment for a booking at the counter, on the card reader the native\n * Aglyn POS app has connected (Tap to Pay or a Bluetooth reader). The server\n * owns the money; the app only presents the card:\n *\n * - `start` prices the charge (the amount staff typed, plus the merchant's\n * own service tax), and creates a card-present PaymentIntent: a\n * DESTINATION charge to the merchant, settled on Aglyn's platform account\n * with no `on_behalf_of` (ToS §10.7, AGL-3607), with the take and\n * Stripe's card cost as `application_fee_amount` — exactly the fee a paid\n * booking already carries online (`resolveTransactionFeeCents`, `service`).\n * Returns the intent's client secret for the app's Terminal SDK.\n * - `settle` re-reads the intent from Stripe (never trusting the app's word),\n * captures an authorized one, and records the booking paid with the same\n * fields an online payment writes, so the console's refund and the dispute\n * handling work on it unchanged.\n * - `cancel` releases an intent that was not collected.\n *\n * MANUAL capture, so a card that authorizes but whose booking was changed in\n * between is released rather than charged. On-reader tipping is not offered\n * here; the amount is the amount.\n *\n * Gate: a site `admin` or `editor`, and the owning org's `bookings` and\n * `pos` entitlements (taking card-present payments is a POS capability).\n *=========================================*/\n\nconst BOOKING_ID = /^[A-Za-z0-9_-]{1,128}$/\nconst PAYMENT_INTENT_ID = /^pi_[A-Za-z0-9_]{6,128}$/\n\ntype Res = Parameters<PluginApiHandler>[1]\n\ninterface Staff {\n uid: string\n hostId: string\n org: Record<string, any> | null\n}\n\nfunction requestBody(req: Parameters<PluginApiHandler>[0]): Record<string, any> {\n if (typeof req.body === 'string') {\n try {\n const parsed = JSON.parse(req.body)\n return parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n return {}\n }\n }\n return req.body && typeof req.body === 'object' ? req.body : {}\n}\n\n/** Card-present payments: always in test mode, in live mode once switched on. */\nexport function inPersonCardsAvailable(): boolean {\n const key = String(process.env.STRIPE_SECRET_KEY ?? '')\n if (!key) return false\n return (\n key.startsWith('sk_test_') ||\n String(process.env.STRIPE_TERMINAL_LIVE_ENABLED ?? '').toLowerCase() === 'true'\n )\n}\n\nasync function stripe(\n method: 'GET' | 'POST',\n path: string,\n options: { params?: Record<string, string | number | boolean | undefined>; idempotencyKey?: string } = {},\n): Promise<{ ok: boolean; status: number; body: any }> {\n const form = new URLSearchParams()\n for (const [key, value] of Object.entries(options.params ?? {})) {\n if (value !== undefined) form.append(key, String(value))\n }\n const query = method === 'GET' && form.toString() ? `?${form}` : ''\n const response = await fetch(`https://api.stripe.com/v1/${path}${query}`, {\n method,\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...(options.idempotencyKey ? { 'Idempotency-Key': options.idempotencyKey } : {}),\n },\n ...(method === 'POST' ? { body: form.toString() } : {}),\n })\n const body = await response.json().catch(() => null)\n return { ok: response.ok, status: response.status, body }\n}\n\nfunction stripeMessage(body: any, fallback: string): string {\n const message = body?.error?.message\n return typeof message === 'string' && message ? message : fallback\n}\n\nasync function authorize(\n req: Parameters<PluginApiHandler>[0],\n hostId: string,\n): Promise<{ ok: true; staff: Staff } | { ok: false; status: number; error: string }> {\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ') ? authorization.slice(7) : ''\n if (!idToken) return { ok: false, status: 401, error: 'Unauthenticated' }\n if (!hostId) return { ok: false, status: 400, error: 'Missing hostId' }\n let uid: string\n try {\n uid = (await firebaseAdmin.app().auth().verifyIdToken(idToken)).uid\n } catch (error) {\n if (!isRefusedIdToken(error)) throw error\n return { ok: false, status: 401, error: 'Unauthenticated' }\n }\n const host = await firebaseAdmin.app().firestore().collection('hosts').doc(hostId).get()\n if (!host.exists) return { ok: false, status: 404, error: 'Unknown site' }\n // \"Take booking payments in person\" (AGL-4047), whose preset is the site\n // Admin and Editor who took them before.\n if (!holdsBookingsSiteKey(host, uid, 'bookings.payments')) {\n return { ok: false, status: 403, error: bookingsSitePermissionRefusal('bookings.payments') }\n }\n const org = ((await getOrgForHost(hostId))?.org as Record<string, any> | undefined) ?? null\n if (!checkEntitlement(org as never, 'bookings') || !checkEntitlement(org as never, 'pos')) {\n return { ok: false, status: 403, error: 'Taking booking payments in person needs the POS plan.' }\n }\n return { ok: true, staff: { uid, hostId, org } }\n}\n\nexport const bookingInPersonPaymentHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const body = requestBody(req)\n const hostId = String(body['hostId'] ?? '')\n const bookingId = String(body['bookingId'] ?? '')\n const gate = await authorize(req, hostId)\n if ('error' in gate) return res.status(gate.status).json({ error: gate.error })\n if (!BOOKING_ID.test(bookingId)) return res.status(400).json({ error: 'Missing bookingId' })\n if (!inPersonCardsAvailable()) {\n return res.status(409).json({ error: 'Card readers are not available yet.' })\n }\n const action = String(body['action'] ?? '')\n try {\n switch (action) {\n case 'start':\n return await start(gate.staff, bookingId, body, req, res)\n case 'settle':\n return await settle(gate.staff, bookingId, res)\n case 'cancel':\n return await cancel(gate.staff, bookingId, res)\n default:\n return res.status(400).json({ error: 'Unknown action' })\n }\n } catch (error) {\n console.error('[bookings/in-person-payment]', action, error)\n return res.status(500).json({ error: 'The payment could not be updated. Check the booking before trying again.' })\n }\n}\n\nfunction bookingRef(hostId: string, bookingId: string) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('bookings')\n .doc(bookingId)\n}\n\nasync function merchantAccount(org: Record<string, any> | null, hostId: string): Promise<string | null> {\n const ownerUid = String(org?.['ownerUid'] ?? '')\n if (!ownerUid) return null\n const profile = await firebaseAdmin.app().firestore().collection('profiles').doc(ownerUid).get()\n const accountId = String(profile.get('stripeAccountId') ?? '')\n return merchantAccountIsReady(\n {\n accountId,\n chargesEnabled: profile.get('stripeChargesEnabled'),\n accountLivemode: profile.get('stripeAccountLivemode'),\n },\n { subject: `booking in-person host ${hostId}` },\n )\n ? accountId\n : null\n}\n\nasync function start(\n staff: Staff,\n bookingId: string,\n body: Record<string, any>,\n req: Parameters<PluginApiHandler>[0],\n res: Res,\n) {\n const attemptKey = String(req.headers['idempotency-key'] ?? req.headers['Idempotency-Key'] ?? '')\n .trim()\n .slice(0, 200)\n if (!attemptKey) return res.status(400).json({ error: 'Missing Idempotency-Key' })\n const serviceCents = typeof body['amountCents'] === 'number' ? body['amountCents'] : NaN\n const problem = bookingInPersonAmountProblem(serviceCents)\n if (problem) return res.status(400).json({ error: problem })\n\n const ref = bookingRef(staff.hostId, bookingId)\n const snapshot = await ref.get()\n if (!snapshot.exists) return res.status(404).json({ error: 'Unknown booking' })\n const booking = snapshot.data() as Record<string, any>\n const state = bookingInPersonState(booking)\n const existing = booking['inPersonPayment'] as BookingInPersonPayment | undefined\n const attempt = createHash('sha256').update(`${bookingId}:${attemptKey}`).digest('hex').slice(0, 40)\n\n if (state === 'paid') return res.status(409).json({ error: 'This booking is already paid.' })\n if (state === 'canceled') return res.status(409).json({ error: 'This booking was canceled.' })\n if (state === 'awaiting-online') {\n return res.status(409).json({ error: 'The customer is paying for this booking online right now.' })\n }\n\n const destination = await merchantAccount(staff.org, staff.hostId)\n if (!destination) return res.status(409).json({ error: 'Finish setting up payments before taking cards.' })\n\n // The merchant's own service tax, off unless they set one (AGL-2028): the\n // same rate a paid booking is charged online.\n const tax = pluginTaxProfile().flatTax(\n await pluginTaxProfile().flatRate(staff.hostId, 'service'),\n serviceCents,\n 'Service tax',\n )\n const amountCents = serviceCents + tax.taxCents\n const feeCents = resolveTransactionFeeCents(staff.org as never, 'service', serviceCents, amountCents)\n\n // A pending intent for this booking that is not this attempt's: release it\n // first, so one booking never has two cards in flight.\n if (existing?.status === 'pending' && existing.paymentIntentId) {\n const sameAttempt = existing.attempt === attempt\n if (sameAttempt) {\n const replay = await stripe('GET', `payment_intents/${existing.paymentIntentId}`)\n if (replay.ok && replay.body?.client_secret) {\n return res.status(200).json(startAnswer(existing, String(replay.body.client_secret)))\n }\n } else {\n const released = await releaseIntent(existing.paymentIntentId)\n if (!released) {\n return res.status(409).json({\n error: 'A card was already authorized for this booking. Settle it before starting another payment.',\n })\n }\n }\n }\n\n const intent = await stripe('POST', 'payment_intents', {\n idempotencyKey: `booking-in-person:${attempt}`,\n params: {\n amount: amountCents,\n currency: 'usd',\n 'payment_method_types[]': 'card_present',\n capture_method: 'manual',\n 'transfer_data[destination]': destination,\n ...(feeCents > 0 ? { application_fee_amount: feeCents } : {}),\n description: `Booking: ${String(booking['serviceName'] ?? 'appointment').slice(0, 80)}`,\n 'metadata[type]': 'booking-in-person',\n 'metadata[hostId]': staff.hostId,\n 'metadata[bookingId]': bookingId,\n 'metadata[feeCents]': feeCents,\n 'metadata[cashierId]': staff.uid,\n ...(tax.taxCents > 0 ? { 'metadata[taxCents]': tax.taxCents, 'metadata[taxPct]': tax.pct } : {}),\n },\n })\n if (!intent.ok || !intent.body?.id || !intent.body?.client_secret) {\n return res.status(502).json({ error: stripeMessage(intent.body, 'The card payment could not be started.') })\n }\n const payment: BookingInPersonPayment = {\n paymentIntentId: String(intent.body.id),\n amountCents,\n serviceCents,\n taxCents: tax.taxCents,\n feeCents,\n status: 'pending',\n startedAtMs: Date.now(),\n startedBy: staff.uid,\n attempt,\n }\n // Recorded in a transaction that re-checks the booking: a payment that\n // landed meanwhile (online, or on another device) wins, and this intent is\n // released instead of left to authorize a second charge.\n const recorded = await firebaseAdmin.app().firestore().runTransaction(async (transaction: any) => {\n const fresh = await transaction.get(ref)\n const freshState = bookingInPersonState((fresh.data() ?? {}) as Record<string, any>)\n const freshPending = fresh.get('inPersonPayment') as BookingInPersonPayment | undefined\n if (freshState === 'paid' || freshState === 'canceled' || freshState === 'awaiting-online') return false\n if (\n freshPending?.status === 'pending' &&\n freshPending.paymentIntentId !== payment.paymentIntentId &&\n freshPending.paymentIntentId !== existing?.paymentIntentId\n ) {\n return false\n }\n transaction.set(ref, { inPersonPayment: payment }, { merge: true })\n return true\n })\n if (!recorded) {\n await releaseIntent(payment.paymentIntentId)\n return res.status(409).json({ error: 'This booking changed while the payment started. Open it again.' })\n }\n return res.status(200).json(startAnswer(payment, String(intent.body.client_secret)))\n}\n\nfunction startAnswer(payment: BookingInPersonPayment, clientSecret: string) {\n return {\n paymentIntentId: payment.paymentIntentId,\n clientSecret,\n amountCents: payment.amountCents,\n serviceCents: payment.serviceCents,\n taxCents: payment.taxCents,\n }\n}\n\n/** Cancels an intent that holds no money yet; false when it does. */\nasync function releaseIntent(paymentIntentId: string): Promise<boolean> {\n const current = await stripe('GET', `payment_intents/${paymentIntentId}`)\n const status = String(current.body?.status ?? '')\n if (status === 'canceled') return true\n if (status === 'succeeded' || status === 'requires_capture' || status === 'processing') return false\n const canceled = await stripe('POST', `payment_intents/${paymentIntentId}/cancel`, {\n idempotencyKey: `booking-in-person-cancel:${paymentIntentId}`,\n })\n return canceled.ok || String(canceled.body?.status ?? '') === 'canceled'\n}\n\nasync function settle(staff: Staff, bookingId: string, res: Res) {\n const ref = bookingRef(staff.hostId, bookingId)\n const snapshot = await ref.get()\n if (!snapshot.exists) return res.status(404).json({ error: 'Unknown booking' })\n const payment = snapshot.get('inPersonPayment') as BookingInPersonPayment | undefined\n if (payment?.status === 'paid') return res.status(200).json({ status: 'paid', amountCents: payment.amountCents })\n if (!payment || payment.status !== 'pending' || !PAYMENT_INTENT_ID.test(String(payment.paymentIntentId))) {\n return res.status(409).json({ error: 'No card payment is in progress for this booking.' })\n }\n let intent = (await stripe('GET', `payment_intents/${payment.paymentIntentId}`)).body\n // The intent must be the one this route made for THIS booking on THIS site.\n if (\n intent?.metadata?.type !== 'booking-in-person' ||\n intent?.metadata?.hostId !== staff.hostId ||\n intent?.metadata?.bookingId !== bookingId\n ) {\n return res.status(409).json({ error: 'That payment is not for this booking.' })\n }\n if (intent.status === 'requires_capture') {\n const captured = await stripe('POST', `payment_intents/${payment.paymentIntentId}/capture`, {\n idempotencyKey: `booking-in-person-capture:${payment.paymentIntentId}`,\n params: payment.feeCents > 0 ? { application_fee_amount: payment.feeCents } : {},\n })\n if (!captured.ok) {\n return res.status(502).json({ error: stripeMessage(captured.body, 'The card could not be charged. Try again.') })\n }\n intent = captured.body\n }\n if (intent?.status !== 'succeeded') {\n // Not collected yet, declined, or canceled: the booking stays payable.\n const status = intent?.status === 'canceled' ? 'canceled' : 'pending'\n if (status === 'canceled') {\n await ref.set({ inPersonPayment: { ...payment, status: 'canceled' } }, { merge: true })\n }\n return res.status(200).json({ status })\n }\n const paidAmountCents = Math.max(0, Math.round(Number(intent.amount_received ?? intent.amount ?? 0)))\n const paidAtMs = Date.now()\n await firebaseAdmin.app().firestore().runTransaction(async (transaction: any) => {\n const fresh = await transaction.get(ref)\n if (fresh.get('paymentIntentId')) return\n transaction.set(\n ref,\n {\n // The same fields an online payment writes (billing-webhook.ts), so\n // the console's refund and dispute handling read it unchanged.\n paidAmountCents,\n paymentIntentId: payment.paymentIntentId,\n feeCents: payment.feeCents,\n taxMode: pluginTaxProfile().taxModeOf(intent, payment.taxCents),\n ...(payment.taxCents > 0 ? { taxCents: payment.taxCents } : {}),\n paidInPerson: true,\n inPersonPayment: { ...payment, status: 'paid', paidAtMs },\n },\n { merge: true },\n )\n })\n return res.status(200).json({ status: 'paid', amountCents: paidAmountCents })\n}\n\nasync function cancel(staff: Staff, bookingId: string, res: Res) {\n const ref = bookingRef(staff.hostId, bookingId)\n const snapshot = await ref.get()\n if (!snapshot.exists) return res.status(404).json({ error: 'Unknown booking' })\n const payment = snapshot.get('inPersonPayment') as BookingInPersonPayment | undefined\n if (!payment || payment.status !== 'pending') return res.status(200).json({ status: 'none' })\n if (!(await releaseIntent(payment.paymentIntentId))) {\n return res.status(409).json({ error: 'The card was already authorized. Settle the payment instead.' })\n }\n await ref.set({ inPersonPayment: { ...payment, status: 'canceled' } }, { merge: true })\n return res.status(200).json({ status: 'canceled' })\n}\n"],"names":["createHash","firebaseAdmin","getOrgForHost","merchantAccountIsReady","checkEntitlement","resolveTransactionFeeCents","pluginTaxProfile","bookingInPersonAmountProblem","bookingInPersonState","bookingsSitePermissionRefusal","holdsBookingsSiteKey","isRefusedIdToken","BOOKING_ID","PAYMENT_INTENT_ID","requestBody","req","body","parsed","JSON","parse","inPersonCardsAvailable","process","key","String","env","STRIPE_SECRET_KEY","startsWith","STRIPE_TERMINAL_LIVE_ENABLED","toLowerCase","stripe","method","path","options","form","URLSearchParams","value","Object","entries","params","undefined","append","query","toString","response","fetch","headers","Authorization","idempotencyKey","json","catch","ok","status","stripeMessage","fallback","message","error","authorize","hostId","authorization","idToken","slice","uid","app","auth","verifyIdToken","host","firestore","collection","doc","get","exists","org","staff","bookingInPersonPaymentHandler","res","bookingId","gate","test","action","start","settle","cancel","console","bookingRef","merchantAccount","profile","ownerUid","accountId","chargesEnabled","accountLivemode","subject","booking","intent","attemptKey","trim","serviceCents","NaN","problem","ref","snapshot","data","state","existing","attempt","update","digest","destination","tax","flatTax","flatRate","amountCents","taxCents","feeCents","paymentIntentId","sameAttempt","replay","client_secret","startAnswer","released","releaseIntent","amount","currency","capture_method","application_fee_amount","description","pct","id","payment","startedAtMs","Date","now","startedBy","recorded","runTransaction","transaction","fresh","freshState","freshPending","set","inPersonPayment","merge","clientSecret","current","canceled","metadata","type","captured","paidAmountCents","Math","max","round","Number","amount_received","paidAtMs","taxMode","taxModeOf","paidInPerson"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,SAAQ;AACnC,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,sBAAsB,QAAQ,mDAAkD;AACzF,SACEC,gBAAgB,EAChBC,0BAA0B,QAErB,sBAAqB;AAC5B,SAASC,gBAAgB,QAAQ,iDAAgD;AACjF,SACEC,4BAA4B,EAC5BC,oBAAoB,QAEf,gCAA4B;AACnC,SAASC,6BAA6B,QAAQ,mCAA+B;AAC7E,SAASC,oBAAoB,QAAQ,0BAAsB;AAC3D,SAASC,gBAAgB,QAAQ,mDAAkD;AAEnF;;;;;;;;;;;;;;;;;;;;;;;;;;2CA0B2C,GAE3C,MAAMC,aAAa;AACnB,MAAMC,oBAAoB;AAU1B,SAASC,YAAYC,GAAoC;IACvD,IAAI,OAAOA,IAAIC,IAAI,KAAK,UAAU;QAChC,IAAI;YACF,MAAMC,SAASC,KAAKC,KAAK,CAACJ,IAAIC,IAAI;YAClC,OAAOC,UAAU,OAAOA,WAAW,WAAWA,SAAS,CAAC;QAC1D,EAAE,eAAM;YACN,OAAO,CAAC;QACV;IACF;IACA,OAAOF,IAAIC,IAAI,IAAI,OAAOD,IAAIC,IAAI,KAAK,WAAWD,IAAIC,IAAI,GAAG,CAAC;AAChE;AAEA,+EAA+E,GAC/E,OAAO,SAASI;QACKC,gCAIVA;IAJT,MAAMC,MAAMC,QAAOF,iCAAAA,QAAQG,GAAG,CAACC,iBAAiB,YAA7BJ,iCAAiC;IACpD,IAAI,CAACC,KAAK,OAAO;IACjB,OACEA,IAAII,UAAU,CAAC,eACfH,QAAOF,4CAAAA,QAAQG,GAAG,CAACG,4BAA4B,YAAx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D,aAAaqC;IAAgB;AAC7E;AAEA,eAAelE,OAAOT,KAAY,EAAEG,SAAiB,EAAED,GAAQ;IAC7D,MAAMwB,MAAMf,WAAWX,MAAMf,MAAM,EAAEkB;IACrC,MAAMwB,WAAW,MAAMD,IAAI7B,GAAG;IAC9B,IAAI,CAAC8B,SAAS7B,MAAM,EAAE,OAAOI,IAAIvB,MAAM,CAAC,KAAKH,IAAI,CAAC;QAAEO,OAAO;IAAkB;IAC7E,MAAMwE,UAAU5B,SAAS9B,GAAG,CAAC;IAC7B,IAAI,CAAC0D,WAAWA,QAAQ5E,MAAM,KAAK,WAAW,OAAOuB,IAAIvB,MAAM,CAAC,KAAKH,IAAI,CAAC;QAAEG,QAAQ;IAAO;IAC3F,IAAI,CAAE,MAAMoE,cAAcQ,QAAQd,eAAe,GAAI;QACnD,OAAOvC,IAAIvB,MAAM,CAAC,KAAKH,IAAI,CAAC;YAAEO,OAAO;QAA+D;IACtG;IACA,MAAM2C,IAAIwC,GAAG,CAAC;QAAEC,iBAAiB,aAAKZ;YAAS5E,QAAQ;;IAAa,GAAG;QAAEyF,OAAO;IAAK;IACrF,OAAOlE,IAAIvB,MAAM,CAAC,KAAKH,IAAI,CAAC;QAAEG,QAAQ;IAAW;AACnD"}
@@ -21,6 +21,8 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
21
21
  import { reverseOrderConversion } from "@aglyn/aglyn/plugin-manager/plugin-conversion-credit";
22
22
  import { createHash } from "crypto";
23
23
  import { apiIdempotencyExpiry } from "@aglyn/aglyn/app-utils/api-idempotency";
24
+ import { bookingsSitePermissionRefusal } from "../model/bookings-permissions.js";
25
+ import { holdsBookingsSiteKey } from "./bookings-site-keys.js";
24
26
  import { raiseBookingEvent } from "./booking-events.js";
25
27
  /**
26
28
  * Refund a paid booking (AGL-2315), full or partial, site-admin only.
@@ -104,7 +106,7 @@ import { raiseBookingEvent } from "./booking-events.js";
104
106
  });
105
107
  }
106
108
  try {
107
- var _hostSnapshot_get, _bookingSnapshot_data, _bookingSnapshot_get, _bookingSnapshot_get1;
109
+ var _bookingSnapshot_data, _bookingSnapshot_get, _bookingSnapshot_get1;
108
110
  const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken);
109
111
  const firestore = firebaseAdmin.app().firestore();
110
112
  const hostRef = firestore.collection('hosts').doc(hostId);
@@ -114,12 +116,11 @@ import { raiseBookingEvent } from "./booking-events.js";
114
116
  error: 'Unknown site'
115
117
  });
116
118
  }
117
- // Site ADMIN, not merely a member: this moves money. The same gate
118
- // `commerce/refund.ts` applies.
119
- const memberRole = ((_hostSnapshot_get = hostSnapshot.get('memberRoles')) != null ? _hostSnapshot_get : {})[decoded.uid];
120
- if (memberRole !== 'admin') {
119
+ // "Refund bookings" (AGL-4047), not merely a member: this moves money.
120
+ // Its preset is the site Admin, the gate `commerce/refund.ts` applies.
121
+ if (!holdsBookingsSiteKey(hostSnapshot, decoded.uid, 'bookings.refunds')) {
121
122
  return res.status(403).json({
122
- error: 'Refunds require a site admin'
123
+ error: bookingsSitePermissionRefusal('bookings.refunds')
123
124
  });
124
125
  }
125
126
  const bookingRef = hostRef.collection('bookings').doc(bookingId);
@@ -161,7 +162,7 @@ import { raiseBookingEvent } from "./booking-events.js";
161
162
  return res.status(Number((_prior_get = prior.get('responseStatus')) != null ? _prior_get : 200)).json(priorResponse);
162
163
  }
163
164
  try {
164
- var _hostSnapshot_get1;
165
+ var _hostSnapshot_get;
165
166
  // The claim's shape is every claim's (`claimApiIdempotency`): its
166
167
  // kind, scope and org name it on the staff claims list, `createdAtMs`
167
168
  // ages it there, and `expiresAt` lets the TTL policy reap it — a
@@ -169,7 +170,7 @@ import { raiseBookingEvent } from "./booking-events.js";
169
170
  await claimRef.create({
170
171
  kind: 'booking-refund',
171
172
  scopeId: hostId,
172
- orgId: String((_hostSnapshot_get1 = hostSnapshot.get('orgId')) != null ? _hostSnapshot_get1 : '') || null,
173
+ orgId: String((_hostSnapshot_get = hostSnapshot.get('orgId')) != null ? _hostSnapshot_get : '') || null,
173
174
  bookingId,
174
175
  status: 'pending',
175
176
  createdAtMs: Date.now(),
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/refund.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 { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\n// Leaf import, not the barrel: the specs in this library mock\n// `@aglyn/tenant-data-admin` wholesale, and a permissive stub would turn a\n// reversal that never happened green.\nimport { reverseOrderConversion } from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit'\nimport { createHash } from 'crypto'\nimport { apiIdempotencyExpiry } from '@aglyn/aglyn/app-utils/api-idempotency'\nimport { raiseBookingEvent } from './booking-events'\n\n/**\n * Refund a paid booking (AGL-2315), full or partial, site-admin only.\n *\n * This route exists BECAUSE of the destination charge, not alongside it. While\n * a paid booking settled in Aglyn's own balance there was nothing here to get\n * wrong: cancelling a booking refunded the guest nothing at all, and any\n * refund issued by hand simply gave back money Aglyn was already holding. Once\n * the charge goes to the merchant's connected account that stops being true in\n * two directions at once, and both are money:\n *\n * - **The guest.** Cancelling a paid booking wrote `status: 'canceled'` from\n * the console and moved no money. The slot reopened, the appointment was\n * gone, and the guest had paid for it. That was survivable only because the\n * platform still held the funds and could be made to give them back; with\n * the money at the merchant it is a silent, unrecoverable overcharge.\n * - **Aglyn.** A refund on a destination charge that does NOT set\n * `reverse_transfer` is paid entirely out of the PLATFORM's balance while\n * the merchant keeps the transfer in full. The merchant cancels, the guest\n * is made whole, and Aglyn funds the whole concession out of a cut that was\n * at most 5% of it. This repo has shipped that exact bug once already, on a\n * marketplace partial refund.\n *\n * So both switches are sent, and they are two different decisions:\n *\n * - `reverse_transfer` pulls the refunded share back OUT of the merchant's\n * account. Stripe prorates it against a partial refund, so a $30 refund on\n * a $75 booking claws back $30 of the merchant's $71.25, not all of it.\n * - `refund_application_fee` returns Aglyn's commission on the refunded\n * share. A refunded appointment earned the platform nothing, and this\n * matches `commerce/refund.ts`, which has sent both since AGL-287. The\n * DISPUTE path deliberately sends only the reversal — that asymmetry is\n * AGL-1809's and is not copied here.\n *\n * Two SEPARATE controls guard the money, the AGL-1696 lesson from the order\n * refund, and conflating them is how that one originally went wrong:\n *\n * - The idempotency key stops a DUPLICATE refund — one attempt sent twice\n * because the response was lost or the admin double-clicked. It is minted\n * per attempt by the console and deliberately not derived from the booking\n * or the amount: two $10 refunds on a $75 booking are two real refunds.\n * - The cap stops an OVER-refund — several partials summing past what was\n * captured, including two admins refunding at once, where the attempts are\n * genuinely distinct and no key can help. That needs the counter read and\n * written inside one transaction, BEFORE Stripe is called, so a lost\n * response leaves the amount counted and the retry refunds less, never\n * more.\n */\nexport const bookingRefundHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res.status(501).json({ error: 'Payments are not configured.' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n const bookingId = String(body.bookingId ?? '')\n // `null`/absent means \"everything still refundable\"; a number is a partial.\n const amountCents = body.amountCents == null ? null : Number(body.amountCents)\n // Node lowercases incoming headers, but read both spellings — the plugin API\n // request type makes no promise about casing.\n const idempotencyKey = String(\n req.headers['idempotency-key'] ?? req.headers['Idempotency-Key'] ?? '',\n )\n .trim()\n .slice(0, 200)\n if (!hostId || !bookingId) {\n return res.status(400).json({ error: 'Missing hostId or bookingId' })\n }\n if (amountCents != null && !(Number.isFinite(amountCents) && amountCents > 0)) {\n return res.status(400).json({ error: 'Invalid refund amount' })\n }\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // Site ADMIN, not merely a member: this moves money. The same gate\n // `commerce/refund.ts` applies.\n const memberRole = (hostSnapshot.get('memberRoles') ?? {})[decoded.uid]\n if (memberRole !== 'admin') {\n return res.status(403).json({ error: 'Refunds require a site admin' })\n }\n const bookingRef = hostRef.collection('bookings').doc(bookingId)\n const bookingSnapshot = await bookingRef.get()\n if (!bookingSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown booking' })\n }\n // As it stood before this refund, for the event a full refund raises.\n const bookingBefore = (bookingSnapshot.data() ?? {}) as Record<string, unknown>\n const paymentIntentId = String(bookingSnapshot.get('paymentIntentId') ?? '')\n const paidCents = Math.max(\n 0,\n Math.round(Number(bookingSnapshot.get('paidAmountCents') ?? 0)),\n )\n if (!paidCents) {\n return res.status(409).json({ error: 'This booking was never paid' })\n }\n if (!paymentIntentId) {\n // A booking paid BEFORE the webhook began recording the PaymentIntent\n // (AGL-2315). Refundable, but only by hand — and saying so beats a 500\n // an admin cannot act on.\n return res.status(409).json({\n error:\n 'This booking was paid before refunds were supported here. ' +\n 'Refund it in the Stripe dashboard, and tick “Reverse transfer” ' +\n 'so the amount comes back from the merchant account.',\n })\n }\n\n // Replay a settled attempt before anything else can reject it. This read\n // is only a short-circuit, never the dedupe primitive — the atomic\n // `create()` below is.\n const claimRef = idempotencyKey\n ? firestore.collection('apiIdempotency').doc(\n createHash('sha256')\n // Scoped by the BOOKING, so a client that reused one key across\n // two bookings cannot dedupe two legitimately distinct refunds.\n // NOT by the amount: that would swallow a real second partial.\n .update(`booking-refund:${hostId}:${bookingId}:${idempotencyKey}`)\n .digest('hex'),\n )\n : null\n if (claimRef) {\n const prior = await claimRef.get()\n const priorResponse = prior.get('response')\n if (priorResponse) {\n return res\n .status(Number(prior.get('responseStatus') ?? 200))\n .json(priorResponse)\n }\n try {\n // The claim's shape is every claim's (`claimApiIdempotency`): its\n // kind, scope and org name it on the staff claims list, `createdAtMs`\n // ages it there, and `expiresAt` lets the TTL policy reap it — a\n // claim stranded by a killed process otherwise holds its key forever.\n await claimRef.create({\n kind: 'booking-refund',\n scopeId: hostId,\n orgId: String(hostSnapshot.get('orgId') ?? '') || null,\n bookingId,\n status: 'pending',\n createdAtMs: Date.now(),\n expiresAt: apiIdempotencyExpiry(),\n })\n } catch {\n // Another attempt with this key is in flight.\n return res\n .status(409)\n .json({ error: 'This refund is already being processed' })\n }\n }\n\n // RESERVE. Read and write the counter in ONE transaction so two concurrent\n // refunds cannot both see the same `refundedCents` and each send a full\n // amount to Stripe — the failure the order refund shipped with.\n let refundCents = 0\n let alreadyRefunded = 0\n await firestore.runTransaction(async (transaction) => {\n const fresh = await transaction.get(bookingRef)\n alreadyRefunded = Math.max(\n 0,\n Math.round(Number(fresh.get('refundedCents') ?? 0)),\n )\n const remaining = paidCents - alreadyRefunded\n refundCents =\n amountCents == null\n ? remaining\n : Math.min(Math.round(amountCents), remaining)\n if (!(refundCents > 0)) {\n refundCents = 0\n return\n }\n transaction.set(\n bookingRef,\n { refundedCents: alreadyRefunded + refundCents },\n { merge: true },\n )\n })\n if (!(refundCents > 0)) {\n await claimRef?.delete().catch(() => undefined)\n return res.status(400).json({ error: 'Nothing left to refund' })\n }\n\n const params = new URLSearchParams({\n payment_intent: paymentIntentId,\n amount: String(refundCents),\n // THE SELLER SHARE COMES BACK. Without this the merchant keeps their\n // transfer in full and Aglyn funds the entire refund.\n reverse_transfer: 'true',\n // ...and so does Aglyn's commission on the refunded share. A refunded\n // appointment earned the platform nothing.\n refund_application_fee: 'true',\n })\n const response = await fetch('https://api.stripe.com/v1/refunds', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...(claimRef ? { 'Idempotency-Key': claimRef.id } : {}),\n },\n body: params.toString(),\n })\n const refund = await response.json().catch(() => ({}) as any)\n if (!response.ok) {\n console.error('Stripe booking refund error', (refund as any)?.error)\n // Stripe said no, so we KNOW no money moved: give the reservation back\n // and let the same attempt be retried.\n await firestore\n .runTransaction(async (transaction) => {\n const current = Number(\n (await transaction.get(bookingRef)).get('refundedCents') ?? 0,\n )\n transaction.set(\n bookingRef,\n { refundedCents: Math.max(0, current - refundCents) },\n { merge: true },\n )\n })\n .catch(() => undefined)\n await claimRef?.delete().catch(() => undefined)\n return res.status(502).json({ error: 'Refund failed' })\n }\n\n // A FULL refund ends the appointment; a partial leaves it standing. The\n // guest who got half their money back still has the slot, and moving the\n // booking off `confirmed` would reopen a time the merchant is still\n // committed to.\n const totalRefunded = alreadyRefunded + refundCents\n const fullyRefunded = totalRefunded >= paidCents\n await bookingRef\n .set(\n {\n refundedCents: totalRefunded,\n ...(fullyRefunded ? { status: 'canceled' } : {}),\n },\n { merge: true },\n )\n .catch(() => undefined)\n // The full refund is what cancels a paid booking (AGL-3643). Keyed by the\n // booking, so a booking canceled before is not announced again.\n if (fullyRefunded && bookingBefore['status'] !== 'canceled') {\n await raiseBookingEvent(firestore, {\n event: 'booking.canceled',\n hostId,\n bookingId,\n booking: {\n ...bookingBefore,\n refundedCents: totalRefunded,\n status: 'canceled',\n },\n })\n }\n\n const payload = {\n refundedCents: refundCents,\n totalRefundedCents: totalRefunded,\n fullyRefunded,\n }\n await claimRef\n ?.set(\n {\n status: 'done',\n responseStatus: 200,\n response: payload,\n settledAtMs: Date.now(),\n },\n { merge: true },\n )\n .catch(() => undefined)\n /*\n * The campaign's side of the ledger.\n *\n * A paid booking is credited to the campaign that led to it — the sale\n * announces itself through `upsertHostContact` with a `purchaseCents` and\n * this booking's id, exactly as a store order does — so a refunded one\n * has to stop counting. Without this, a booking site's campaign revenue\n * could only ever rise.\n *\n * Keyed by the BOOKING id, which is what the credit was filed under, so\n * this needs no email and works for a guest who never became a contact.\n * Recorded beside the credit rather than subtracted from it, and swallowed\n * whole: the money has already left the merchant's account and the booking\n * already records it, so nothing here may fail a refund.\n */\n await reverseOrderConversion({\n hostId,\n orderId: bookingId,\n amountCents: refundCents,\n closedTheOrder: fullyRefunded,\n })\n return res.status(200).json(payload)\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Refund failed' })\n }\n}\n"],"names":["firebaseAdmin","reverseOrderConversion","createHash","apiIdempotencyExpiry","raiseBookingEvent","bookingRefundHandler","req","res","body","method","status","json","error","process","env","STRIPE_SECRET_KEY","authorization","String","headers","idToken","startsWith","slice","length","undefined","JSON","parse","hostId","bookingId","amountCents","Number","idempotencyKey","trim","isFinite","hostSnapshot","bookingSnapshot","decoded","app","auth","verifyIdToken","firestore","hostRef","collection","doc","get","exists","memberRole","uid","bookingRef","bookingBefore","data","paymentIntentId","paidCents","Math","max","round","claimRef","update","digest","prior","priorResponse","create","kind","scopeId","orgId","createdAtMs","Date","now","expiresAt","refundCents","alreadyRefunded","runTransaction","transaction","fresh","remaining","min","set","refundedCents","merge","delete","catch","params","URLSearchParams","payment_intent","amount","reverse_transfer","refund_application_fee","response","fetch","Authorization","id","toString","refund","ok","console","current","totalRefunded","fullyRefunded","event","booking","payload","totalRefundedCents","responseStatus","settledAtMs","orderId","closedTheOrder"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,QAAQ,2BAA0B;AAExD,8DAA8D;AAC9D,2EAA2E;AAC3E,sCAAsC;AACtC,SAASC,sBAAsB,QAAQ,uDAAsD;AAC7F,SAASC,UAAU,QAAQ,SAAQ;AAC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AAiBhD,aAAa,CAAC,SAAS,KAAK,YAAY;YAC3D,MAAM5C,kBAAkBmC,WAAW;gBACjC0D,OAAO;gBACPvE;gBACAC;gBACAuE,SAAS,aACJlD;oBACH4B,eAAemB;oBACfrF,QAAQ;;YAEZ;QACF;QAEA,MAAMyF,UAAU;YACdvB,eAAeR;YACfgC,oBAAoBL;YACpBC;QACF;QACA,OAAMzC,4BAAAA,SACFoB,GAAG,CACH;YACEjE,QAAQ;YACR2F,gBAAgB;YAChBf,UAAUa;YACVG,aAAarC,KAAKC,GAAG;QACvB,GACA;YAAEW,OAAO;QAAK,GAEfE,KAAK,CAAC,IAAMxD;QACf;;;;;;;;;;;;;;KAcC,GACD,MAAMtB,uBAAuB;YAC3ByB;YACA6E,SAAS5E;YACTC,aAAawC;YACboC,gBAAgBR;QAClB;QACA,OAAOzF,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAACwF;IAC9B,EAAE,OAAOvF,OAAO;QACdiF,QAAQjF,KAAK,CAACA;QACd,OAAOL,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAgB;IACvD;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/bookings/src/lib/server/refund.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 { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\n// Leaf import, not the barrel: the specs in this library mock\n// `@aglyn/tenant-data-admin` wholesale, and a permissive stub would turn a\n// reversal that never happened green.\nimport { reverseOrderConversion } from '@aglyn/aglyn/plugin-manager/plugin-conversion-credit'\nimport { createHash } from 'crypto'\nimport { apiIdempotencyExpiry } from '@aglyn/aglyn/app-utils/api-idempotency'\nimport { bookingsSitePermissionRefusal } from '../model/bookings-permissions'\nimport { holdsBookingsSiteKey } from './bookings-site-keys'\nimport { raiseBookingEvent } from './booking-events'\n\n/**\n * Refund a paid booking (AGL-2315), full or partial, site-admin only.\n *\n * This route exists BECAUSE of the destination charge, not alongside it. While\n * a paid booking settled in Aglyn's own balance there was nothing here to get\n * wrong: cancelling a booking refunded the guest nothing at all, and any\n * refund issued by hand simply gave back money Aglyn was already holding. Once\n * the charge goes to the merchant's connected account that stops being true in\n * two directions at once, and both are money:\n *\n * - **The guest.** Cancelling a paid booking wrote `status: 'canceled'` from\n * the console and moved no money. The slot reopened, the appointment was\n * gone, and the guest had paid for it. That was survivable only because the\n * platform still held the funds and could be made to give them back; with\n * the money at the merchant it is a silent, unrecoverable overcharge.\n * - **Aglyn.** A refund on a destination charge that does NOT set\n * `reverse_transfer` is paid entirely out of the PLATFORM's balance while\n * the merchant keeps the transfer in full. The merchant cancels, the guest\n * is made whole, and Aglyn funds the whole concession out of a cut that was\n * at most 5% of it. This repo has shipped that exact bug once already, on a\n * marketplace partial refund.\n *\n * So both switches are sent, and they are two different decisions:\n *\n * - `reverse_transfer` pulls the refunded share back OUT of the merchant's\n * account. Stripe prorates it against a partial refund, so a $30 refund on\n * a $75 booking claws back $30 of the merchant's $71.25, not all of it.\n * - `refund_application_fee` returns Aglyn's commission on the refunded\n * share. A refunded appointment earned the platform nothing, and this\n * matches `commerce/refund.ts`, which has sent both since AGL-287. The\n * DISPUTE path deliberately sends only the reversal — that asymmetry is\n * AGL-1809's and is not copied here.\n *\n * Two SEPARATE controls guard the money, the AGL-1696 lesson from the order\n * refund, and conflating them is how that one originally went wrong:\n *\n * - The idempotency key stops a DUPLICATE refund — one attempt sent twice\n * because the response was lost or the admin double-clicked. It is minted\n * per attempt by the console and deliberately not derived from the booking\n * or the amount: two $10 refunds on a $75 booking are two real refunds.\n * - The cap stops an OVER-refund — several partials summing past what was\n * captured, including two admins refunding at once, where the attempts are\n * genuinely distinct and no key can help. That needs the counter read and\n * written inside one transaction, BEFORE Stripe is called, so a lost\n * response leaves the amount counted and the retry refunds less, never\n * more.\n */\nexport const bookingRefundHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return res.status(501).json({ error: 'Payments are not configured.' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n const body =\n typeof req.body === 'string' ? JSON.parse(req.body) : (req.body ?? {})\n const hostId = String(body.hostId ?? '')\n const bookingId = String(body.bookingId ?? '')\n // `null`/absent means \"everything still refundable\"; a number is a partial.\n const amountCents = body.amountCents == null ? null : Number(body.amountCents)\n // Node lowercases incoming headers, but read both spellings — the plugin API\n // request type makes no promise about casing.\n const idempotencyKey = String(\n req.headers['idempotency-key'] ?? req.headers['Idempotency-Key'] ?? '',\n )\n .trim()\n .slice(0, 200)\n if (!hostId || !bookingId) {\n return res.status(400).json({ error: 'Missing hostId or bookingId' })\n }\n if (amountCents != null && !(Number.isFinite(amountCents) && amountCents > 0)) {\n return res.status(400).json({ error: 'Invalid refund amount' })\n }\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n // \"Refund bookings\" (AGL-4047), not merely a member: this moves money.\n // Its preset is the site Admin, the gate `commerce/refund.ts` applies.\n if (!holdsBookingsSiteKey(hostSnapshot, decoded.uid, 'bookings.refunds')) {\n return res.status(403).json({ error: bookingsSitePermissionRefusal('bookings.refunds') })\n }\n const bookingRef = hostRef.collection('bookings').doc(bookingId)\n const bookingSnapshot = await bookingRef.get()\n if (!bookingSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown booking' })\n }\n // As it stood before this refund, for the event a full refund raises.\n const bookingBefore = (bookingSnapshot.data() ?? {}) as Record<string, unknown>\n const paymentIntentId = String(bookingSnapshot.get('paymentIntentId') ?? '')\n const paidCents = Math.max(\n 0,\n Math.round(Number(bookingSnapshot.get('paidAmountCents') ?? 0)),\n )\n if (!paidCents) {\n return res.status(409).json({ error: 'This booking was never paid' })\n }\n if (!paymentIntentId) {\n // A booking paid BEFORE the webhook began recording the PaymentIntent\n // (AGL-2315). Refundable, but only by hand — and saying so beats a 500\n // an admin cannot act on.\n return res.status(409).json({\n error:\n 'This booking was paid before refunds were supported here. ' +\n 'Refund it in the Stripe dashboard, and tick “Reverse transfer” ' +\n 'so the amount comes back from the merchant account.',\n })\n }\n\n // Replay a settled attempt before anything else can reject it. This read\n // is only a short-circuit, never the dedupe primitive — the atomic\n // `create()` below is.\n const claimRef = idempotencyKey\n ? firestore.collection('apiIdempotency').doc(\n createHash('sha256')\n // Scoped by the BOOKING, so a client that reused one key across\n // two bookings cannot dedupe two legitimately distinct refunds.\n // NOT by the amount: that would swallow a real second partial.\n .update(`booking-refund:${hostId}:${bookingId}:${idempotencyKey}`)\n .digest('hex'),\n )\n : null\n if (claimRef) {\n const prior = await claimRef.get()\n const priorResponse = prior.get('response')\n if (priorResponse) {\n return res\n .status(Number(prior.get('responseStatus') ?? 200))\n .json(priorResponse)\n }\n try {\n // The claim's shape is every claim's (`claimApiIdempotency`): its\n // kind, scope and org name it on the staff claims list, `createdAtMs`\n // ages it there, and `expiresAt` lets the TTL policy reap it — a\n // claim stranded by a killed process otherwise holds its key forever.\n await claimRef.create({\n kind: 'booking-refund',\n scopeId: hostId,\n orgId: String(hostSnapshot.get('orgId') ?? '') || null,\n bookingId,\n status: 'pending',\n createdAtMs: Date.now(),\n expiresAt: apiIdempotencyExpiry(),\n })\n } catch {\n // Another attempt with this key is in flight.\n return res\n .status(409)\n .json({ error: 'This refund is already being processed' })\n }\n }\n\n // RESERVE. Read and write the counter in ONE transaction so two concurrent\n // refunds cannot both see the same `refundedCents` and each send a full\n // amount to Stripe — the failure the order refund shipped with.\n let refundCents = 0\n let alreadyRefunded = 0\n await firestore.runTransaction(async (transaction) => {\n const fresh = await transaction.get(bookingRef)\n alreadyRefunded = Math.max(\n 0,\n Math.round(Number(fresh.get('refundedCents') ?? 0)),\n )\n const remaining = paidCents - alreadyRefunded\n refundCents =\n amountCents == null\n ? remaining\n : Math.min(Math.round(amountCents), remaining)\n if (!(refundCents > 0)) {\n refundCents = 0\n return\n }\n transaction.set(\n bookingRef,\n { refundedCents: alreadyRefunded + refundCents },\n { merge: true },\n )\n })\n if (!(refundCents > 0)) {\n await claimRef?.delete().catch(() => undefined)\n return res.status(400).json({ error: 'Nothing left to refund' })\n }\n\n const params = new URLSearchParams({\n payment_intent: paymentIntentId,\n amount: String(refundCents),\n // THE SELLER SHARE COMES BACK. Without this the merchant keeps their\n // transfer in full and Aglyn funds the entire refund.\n reverse_transfer: 'true',\n // ...and so does Aglyn's commission on the refunded share. A refunded\n // appointment earned the platform nothing.\n refund_application_fee: 'true',\n })\n const response = await fetch('https://api.stripe.com/v1/refunds', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n ...(claimRef ? { 'Idempotency-Key': claimRef.id } : {}),\n },\n body: params.toString(),\n })\n const refund = await response.json().catch(() => ({}) as any)\n if (!response.ok) {\n console.error('Stripe booking refund error', (refund as any)?.error)\n // Stripe said no, so we KNOW no money moved: give the reservation back\n // and let the same attempt be retried.\n await firestore\n .runTransaction(async (transaction) => {\n const current = Number(\n (await transaction.get(bookingRef)).get('refundedCents') ?? 0,\n )\n transaction.set(\n bookingRef,\n { refundedCents: Math.max(0, current - refundCents) },\n { merge: true },\n )\n })\n .catch(() => undefined)\n await claimRef?.delete().catch(() => undefined)\n return res.status(502).json({ error: 'Refund failed' })\n }\n\n // A FULL refund ends the appointment; a partial leaves it standing. The\n // guest who got half their money back still has the slot, and moving the\n // booking off `confirmed` would reopen a time the merchant is still\n // committed to.\n const totalRefunded = alreadyRefunded + refundCents\n const fullyRefunded = totalRefunded >= paidCents\n await bookingRef\n .set(\n {\n refundedCents: totalRefunded,\n ...(fullyRefunded ? { status: 'canceled' } : {}),\n },\n { merge: true },\n )\n .catch(() => undefined)\n // The full refund is what cancels a paid booking (AGL-3643). Keyed by the\n // booking, so a booking canceled before is not announced again.\n if (fullyRefunded && bookingBefore['status'] !== 'canceled') {\n await raiseBookingEvent(firestore, {\n event: 'booking.canceled',\n hostId,\n bookingId,\n booking: {\n ...bookingBefore,\n refundedCents: totalRefunded,\n status: 'canceled',\n },\n })\n }\n\n const payload = {\n refundedCents: refundCents,\n totalRefundedCents: totalRefunded,\n fullyRefunded,\n }\n await claimRef\n ?.set(\n {\n status: 'done',\n responseStatus: 200,\n response: payload,\n settledAtMs: Date.now(),\n },\n { merge: true },\n )\n .catch(() => undefined)\n /*\n * The campaign's side of the ledger.\n *\n * A paid booking is credited to the campaign that led to it — the sale\n * announces itself through `upsertHostContact` with a `purchaseCents` and\n * this booking's id, exactly as a store order does — so a refunded one\n * has to stop counting. Without this, a booking site's campaign revenue\n * could only ever rise.\n *\n * Keyed by the BOOKING id, which is what the credit was filed under, so\n * this needs no email and works for a guest who never became a contact.\n * Recorded beside the credit rather than subtracted from it, and swallowed\n * whole: the money has already left the merchant's account and the booking\n * already records it, so nothing here may fail a refund.\n */\n await reverseOrderConversion({\n hostId,\n orderId: bookingId,\n amountCents: refundCents,\n closedTheOrder: fullyRefunded,\n })\n return res.status(200).json(payload)\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Refund failed' })\n }\n}\n"],"names":["firebaseAdmin","reverseOrderConversion","createHash","apiIdempotencyExpiry","bookingsSitePermissionRefusal","holdsBookingsSiteKey","raiseBookingEvent","bookingRefundHandler","req","res","body","method","status","json","error","process","env","STRIPE_SECRET_KEY","authorization","String","headers","idToken","startsWith","slice","length","undefined","JSON","parse","hostId","bookingId","amountCents","Number","idempotencyKey","trim","isFinite","bookingSnapshot","decoded","app","auth","verifyIdToken","firestore","hostRef","collection","doc","hostSnapshot","get","exists","uid","bookingRef","bookingBefore","data","paymentIntentId","paidCents","Math","max","round","claimRef","update","digest","prior","priorResponse","create","kind","scopeId","orgId","createdAtMs","Date","now","expiresAt","refundCents","alreadyRefunded","runTransaction","transaction","fresh","remaining","min","set","refundedCents","merge","delete","catch","params","URLSearchParams","payment_intent","amount","reverse_transfer","refund_application_fee","response","fetch","Authorization","id","toString","refund","ok","console","current","totalRefunded","fullyRefunded","event","booking","payload","totalRefundedCents","responseStatus","settledAtMs","orderId","closedTheOrder"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,QAAQ,2BAA0B;AAExD,8DAA8D;AAC9D,2EAA2E;AAC3E,sCAAsC;AACtC,SAASC,sBAAsB,QAAQ,uDAAsD;AAC7F,SAASC,UAAU,QAAQ,SAAQ;AACnC,SAASC,oBAAoB,QAAQ,yCAAwC;AAC7E,SAASC,6BAA6B,QAAQ,mCAA+B;AAC7E,SAASC,oBAAoB,QAAQ,0BAAsB;AAC3D,SAASC,iBAAiB,QAAQ,sBAAkB;AAEpD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8CC,GACD,OAAO,MAAMC,uBAAyC,OAAOC,KAAKC;QAOnCD,4BAM4BA,WACnCE,cACGA,iBAMvBF,MAAAA;IApBF,IAAIA,IAAIG,MAAM,KAAK,QAAQ;QACzB,OAAOF,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,IAAI,CAACC,QAAQC,GAAG,CAACC,iBAAiB,EAAE;Q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