@simplelayer/graniteer-core 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/index.js +2 -2
  2. package/package.json +73 -2
  3. package/src/agreementCheckout.ts +250 -0
  4. package/src/agreementPortalEmail.ts +128 -0
  5. package/src/billingPortalLinkEmail.ts +117 -0
  6. package/src/bookingAgreementEmail.ts +149 -0
  7. package/src/bookingEffects.ts +388 -0
  8. package/src/busClient.ts +268 -0
  9. package/src/busSignature.ts +71 -0
  10. package/src/checkoutCoupon.test.ts +675 -0
  11. package/src/checkoutCoupon.ts +455 -0
  12. package/src/commonsDeposit.ts +298 -0
  13. package/src/commonsDepositWebhook.ts +237 -0
  14. package/src/dayPassConfirmation.ts +230 -0
  15. package/src/dunningEmails.test.ts +263 -0
  16. package/src/dunningEmails.ts +203 -0
  17. package/src/email-templates/brand.ts +93 -0
  18. package/src/email-templates/magic-link.tsx +59 -0
  19. package/src/email-templates/recovery.tsx +59 -0
  20. package/src/email-templates/signup.tsx +67 -0
  21. package/src/functions/admin-cancel-membership.ts +311 -311
  22. package/src/functions/admin-change-membership-plan.ts +312 -308
  23. package/src/functions/admin-charge-guest-print.ts +229 -229
  24. package/src/functions/admin-correct-booking.ts +333 -333
  25. package/src/functions/admin-create-booking.ts +460 -0
  26. package/src/functions/admin-create-commons-event.ts +244 -244
  27. package/src/functions/admin-debug-boldsign-doc.ts +93 -93
  28. package/src/functions/admin-door-write.ts +272 -272
  29. package/src/functions/admin-issue-day-pass.ts +231 -0
  30. package/src/functions/admin-mark-booking-paid.ts +203 -203
  31. package/src/functions/admin-mint-billing-portal-link.ts +168 -0
  32. package/src/functions/admin-mint-portal-link.ts +62 -0
  33. package/src/functions/admin-photo-upload.ts +128 -128
  34. package/src/functions/admin-remove-team-member.ts +150 -150
  35. package/src/functions/admin-request-trial.ts +366 -0
  36. package/src/functions/admin-resend-commons-deposit-link.ts +323 -0
  37. package/src/functions/admin-reset-mfa.ts +138 -138
  38. package/src/functions/admin-retry-invoice-payment.test.ts +567 -0
  39. package/src/functions/admin-retry-invoice-payment.ts +333 -0
  40. package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
  41. package/src/functions/admin-revoke-agreement.ts +467 -0
  42. package/src/functions/admin-send-commons-agreement.ts +214 -214
  43. package/src/functions/admin-set-credit-amount.ts +123 -123
  44. package/src/functions/admin-skip-commons-contract.ts +165 -165
  45. package/src/functions/admin-undo-membership-cancel.ts +144 -144
  46. package/src/functions/admin-wall-photo-write.ts +141 -141
  47. package/src/functions/auth-email-hook.ts +259 -0
  48. package/src/functions/boldsign-sender-identity.ts +114 -114
  49. package/src/functions/booking-availability.ts +419 -419
  50. package/src/functions/booking-member-preview.ts +136 -136
  51. package/src/functions/booking-status.ts +149 -0
  52. package/src/functions/conductor.ts +505 -0
  53. package/src/functions/create-agreement.ts +537 -0
  54. package/src/functions/create-booking.ts +648 -0
  55. package/src/functions/create-day-pass-checkout.ts +218 -0
  56. package/src/functions/create-portal-session.ts +142 -0
  57. package/src/functions/create-subscription-checkout.test.ts +222 -0
  58. package/src/functions/create-subscription-checkout.ts +440 -0
  59. package/src/functions/day-pass-status.ts +89 -89
  60. package/src/functions/diag-webpush-test.ts +45 -45
  61. package/src/functions/event-access-admin.ts +277 -0
  62. package/src/functions/event-access-store.ts +309 -309
  63. package/src/functions/ezeep-print-webhook.ts +213 -213
  64. package/src/functions/ezeep-usage-reconcile.ts +299 -299
  65. package/src/functions/fetch-avatar-original.ts +457 -0
  66. package/src/functions/get-provider-sign-link.ts +155 -0
  67. package/src/functions/get-signing-link.ts +211 -211
  68. package/src/functions/guest-print-setup-confirm.ts +128 -128
  69. package/src/functions/guest-print-submit.ts +149 -149
  70. package/src/functions/luma-webhook.ts +165 -165
  71. package/src/functions/manage-booking.ts +472 -0
  72. package/src/functions/mcp.ts +67 -0
  73. package/src/functions/member-door-action.test.ts +1248 -0
  74. package/src/functions/member-door-action.ts +863 -0
  75. package/src/functions/member-unifi-mapping.test.ts +516 -0
  76. package/src/functions/member-unifi-mapping.ts +206 -0
  77. package/src/functions/membership-door-sync.ts +956 -0
  78. package/src/functions/migration-collision-alert.copy.ts +232 -232
  79. package/src/functions/migration-collision-alert.test.ts +349 -349
  80. package/src/functions/migration-collision-alert.ts +232 -232
  81. package/src/functions/office-assignment-end.ts +146 -146
  82. package/src/functions/portal-booking-access.ts +95 -95
  83. package/src/functions/portal-list-invoices.ts +99 -99
  84. package/src/functions/portal-request-login.ts +192 -0
  85. package/src/functions/portal-resend-invite.ts +248 -0
  86. package/src/functions/portal-submit-event.ts +168 -0
  87. package/src/functions/print-billing-recover.ts +97 -97
  88. package/src/functions/print-billing-run.ts +183 -183
  89. package/src/functions/public-facts.ts +168 -168
  90. package/src/functions/push-send.ts +348 -0
  91. package/src/functions/push-test.ts +234 -0
  92. package/src/functions/request-portal-link.ts +211 -0
  93. package/src/functions/reschedule-booking.ts +649 -0
  94. package/src/functions/review-ratings.ts +113 -0
  95. package/src/functions/space-availability-range.acceptance.test.ts +161 -161
  96. package/src/functions/space-availability-range.ts +142 -142
  97. package/src/functions/stripe-db-reconcile.ts +319 -0
  98. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -0
  99. package/src/functions/stripe-webhook.ts +2595 -0
  100. package/src/functions/sync-gcal-blackouts.ts +298 -298
  101. package/src/functions/timetable-event-register.ts +162 -162
  102. package/src/functions/timetable-event-status.ts +90 -90
  103. package/src/functions/timetable-spaces.ts +219 -219
  104. package/src/functions/touch-pass-reconciler.ts +689 -689
  105. package/src/functions/touch-pass-signup.ts +478 -0
  106. package/src/functions/upload-booking-display-image.ts +179 -0
  107. package/src/functions/virtual-onboarding-purge.ts +134 -134
  108. package/src/functions/virtual-onboarding-submit.ts +315 -315
  109. package/src/functions/voice-booking.ts +453 -0
  110. package/src/functions/voice-day-pass.ts +346 -0
  111. package/src/functions/voice-inquiry.test.ts +301 -301
  112. package/src/functions/voice-inquiry.ts +198 -198
  113. package/src/functions/voice-membership-signup.ts +355 -0
  114. package/src/functions/voice-tour-availability.ts +204 -204
  115. package/src/functions/voice-tour-booking.ts +429 -0
  116. package/src/ghlEventInquiry.ts +143 -0
  117. package/src/mailArrivalEmail.ts +121 -0
  118. package/src/manageToken.ts +363 -0
  119. package/src/membershipBusClient.ts +537 -0
  120. package/src/membershipWelcome.ts +683 -0
  121. package/src/migrationCheckout.ts +366 -0
  122. package/src/pacificDate.ts +54 -0
  123. package/src/paymentLinkEmail.ts +123 -0
  124. package/src/signedUnpaidReminderEmail.test.ts +246 -0
  125. package/src/signedUnpaidReminderEmail.ts +132 -0
  126. package/src/stripeCoworkingPortal.ts +91 -0
  127. package/src/supabaseTestFakes.ts +131 -131
  128. package/src/supportTicketEmail.ts +119 -0
  129. package/src/unifiAccessPolicies.ts +228 -0
  130. package/src/unifiGroups.ts +129 -0
@@ -0,0 +1,537 @@
1
+ import { createClient } from 'npm:@supabase/supabase-js@2';
2
+ import { jwtVerify, createRemoteJWKSet } from 'npm:jose@5.9.6';
3
+ import JSZip from 'https://esm.sh/jszip@3.10.1';
4
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
5
+ import { centsFrom } from 'npm:@simplelayer/graniteer-core/agreementCheckout';
6
+ import { parseRetainerConfig } from 'npm:@simplelayer/graniteer-core/money';
7
+ import { buildAgreementPortalUrl } from 'npm:@simplelayer/graniteer-core/manageToken';
8
+ import { sendAgreementPortalEmail } from 'npm:@simplelayer/graniteer-core/agreementPortalEmail';
9
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
10
+
11
+ const corsHeaders = {
12
+ 'Access-Control-Allow-Origin': '*',
13
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
14
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
15
+ };
16
+
17
+ interface CallerClaims {
18
+ sub: string;
19
+ email?: string;
20
+ aal?: string;
21
+ }
22
+
23
+ const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
24
+ let jwksCache: ReturnType<typeof createRemoteJWKSet> | null = null;
25
+ function getJwks(supabaseUrl: string) {
26
+ if (!jwksCache) jwksCache = createRemoteJWKSet(new URL(`${supabaseUrl}${JWKS_URL_SUFFIX}`));
27
+ return jwksCache;
28
+ }
29
+
30
+ async function verifyCaller(authHeader: string | null, supabaseUrl: string): Promise<CallerClaims | null> {
31
+ if (!authHeader?.toLowerCase().startsWith('bearer ')) return null;
32
+ const token = authHeader.slice(7).trim();
33
+ try {
34
+ const { payload } = await jwtVerify(token, getJwks(supabaseUrl));
35
+ const claims = payload as unknown as CallerClaims;
36
+ if (!claims.sub) return null;
37
+ return claims;
38
+ } catch {
39
+ return null;
40
+ }
41
+ }
42
+
43
+ function json(status: number, body: unknown) {
44
+ return new Response(JSON.stringify(body), {
45
+ status,
46
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
47
+ });
48
+ }
49
+
50
+ type FieldValues = Record<string, unknown>;
51
+
52
+ interface AddonRow {
53
+ label?: string;
54
+ amount?: string;
55
+ notes?: string;
56
+ }
57
+
58
+ const str = (v: unknown): string => (v == null ? '' : String(v));
59
+
60
+ function escapeXml(s: string): string {
61
+ return s
62
+ .replace(/&/g, '&amp;')
63
+ .replace(/</g, '&lt;')
64
+ .replace(/>/g, '&gt;');
65
+ }
66
+
67
+ function replaceAllLiteral(haystack: string, needle: string, replacement: string): string {
68
+ return haystack.split(needle).join(replacement);
69
+ }
70
+
71
+ function replaceFirstLiteral(haystack: string, needle: string, replacement: string): string {
72
+ const i = haystack.indexOf(needle);
73
+ if (i === -1) return haystack;
74
+ return haystack.slice(0, i) + replacement + haystack.slice(i + needle.length);
75
+ }
76
+
77
+ function bytesToBase64(bytes: Uint8Array): string {
78
+ let binary = '';
79
+ const chunk = 0x8000;
80
+ for (let i = 0; i < bytes.length; i += chunk) {
81
+ binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
82
+ }
83
+ return btoa(binary);
84
+ }
85
+
86
+ /** Make every <w:r> run containing '{{' render in white so tags do not print. */
87
+ function whitenTagRuns(xml: string): string {
88
+ return xml.replace(/<w:r>[\s\S]*?<\/w:r>/g, (run) => {
89
+ if (!run.includes('{{')) return run;
90
+ if (run.includes('<w:color ')) {
91
+ return run.replace(/<w:color w:val="[0-9A-Fa-f]{6}"\/>/g, '<w:color w:val="FFFFFF"/>');
92
+ }
93
+ if (run.includes('<w:rPr>')) {
94
+ return replaceFirstLiteral(run, '<w:rPr>', '<w:rPr><w:color w:val="FFFFFF"/>');
95
+ }
96
+ return replaceFirstLiteral(run, '<w:r>', '<w:r><w:rPr><w:color w:val="FFFFFF"/></w:rPr>');
97
+ });
98
+ }
99
+
100
+ function buildXml(xmlIn: string, v: FieldValues): { xml: string; missing: string[] } {
101
+ let xml = xmlIn;
102
+ const missing: string[] = [];
103
+
104
+ const subs: Array<[string, string]> = [
105
+ ['[Select: 705 Gold Lake Drive, Suite 250 / 722 Sutter Street]', str(v.location_street)],
106
+ ['[Office Number(s)]', str(v.office_number)],
107
+ ['[Start Date]', str(v.start_date)],
108
+ ['[Term Length]', str(v.term_months)],
109
+ ['[Expiration Date]', str(v.expiration_date)],
110
+ ['[Monthly Fee]', str(v.monthly_fee)],
111
+ ['[Recurring Add-ons or $0]', str(v.addons_total)],
112
+ ['[Service Retainer]', str(v.service_retainer)],
113
+ ['[Number]', str(v.authorized_users)],
114
+ ['[24/7 / extended hours / other approved access]', str(v.access_schedule)],
115
+ ['[Credit Amount in Agreement Summary]', '$' + str(v.credit_amount)],
116
+ ['[Credit Amount]', str(v.credit_amount)],
117
+ ['[Included / Not Included]', str(v.mail_service)],
118
+ ['[Furnished / Unfurnished]', str(v.furnishings)],
119
+ ['[Location and Office Number]', str(v.location_street) + ' - Office ' + str(v.office_number)],
120
+ ['[Date]', str(v.start_date)],
121
+ ];
122
+
123
+ for (const [needle, value] of subs) {
124
+ if (!xml.includes(needle)) {
125
+ missing.push(needle);
126
+ continue;
127
+ }
128
+ xml = replaceAllLiteral(xml, needle, escapeXml(value));
129
+ }
130
+
131
+ const addons = Array.isArray(v.addons) ? (v.addons as AddonRow[]) : [];
132
+ const rows: AddonRow[] = [0, 1, 2].map((i) => addons[i] ?? {});
133
+ for (const row of rows) {
134
+ if (!xml.includes('[Add-On]')) break;
135
+ xml = replaceFirstLiteral(xml, '[Add-On]', escapeXml(row.label || '-'));
136
+ xml = replaceFirstLiteral(xml, '$[Amount]', row.amount ? '$' + escapeXml(String(row.amount)) : '-');
137
+ xml = replaceFirstLiteral(xml, '[Terms / Notes]', escapeXml(row.notes || '-'));
138
+ }
139
+
140
+ const tagSubs: Array<[string, string]> = [
141
+ ['[Member Legal Name and Entity Type]', '{{text|1|*|Legal name and entity type|member_legal_name}}'],
142
+ ['[DBA or None]', '{{text|1|*|DBA or None|member_dba}}'],
143
+ ['[Notice Email and Mailing Address]', '{{text|1|*|Notice email and mailing address|member_notices}}'],
144
+ ['[Member Legal Name]', '{{text|1|*|Legal name|member_legal_name_exb}}'],
145
+ ];
146
+ for (const [needle, value] of tagSubs) {
147
+ if (!xml.includes(needle)) {
148
+ missing.push(needle);
149
+ continue;
150
+ }
151
+ xml = replaceAllLiteral(xml, needle, value);
152
+ }
153
+
154
+ const legalName = 'Legal name: ______________________________';
155
+ if (xml.includes(legalName)) {
156
+ xml = replaceFirstLiteral(xml, legalName, 'Legal name: {{text|1|*|Legal name}}');
157
+ } else {
158
+ missing.push(legalName);
159
+ }
160
+
161
+ const pairs: Array<[string, string, string | null]> = [
162
+ ['By: _____________________________________', 'By: {{sign|1|*}}', 'By: {{sign|2|*}}'],
163
+ ['Name/Title: ______________________________', 'Name/Title: {{text|1|*|Title}}', null],
164
+ ['Date: ____________________________________', 'Date: {{date|1|*}}', 'Date: {{date|2|*}}'],
165
+ ];
166
+ for (const [needle, memberTag, providerTag] of pairs) {
167
+ if (!xml.includes(needle)) {
168
+ missing.push(needle);
169
+ continue;
170
+ }
171
+ xml = replaceFirstLiteral(xml, needle, memberTag);
172
+ if (providerTag === null) continue;
173
+ if (xml.includes(needle)) {
174
+ xml = replaceFirstLiteral(xml, needle, providerTag);
175
+ } else {
176
+ missing.push(needle + ' (provider)');
177
+ }
178
+ }
179
+
180
+ xml = whitenTagRuns(xml);
181
+ return { xml, missing };
182
+ }
183
+
184
+ /**
185
+ * Pre-flight check: an agreement with no positive monthly fee or no positive
186
+ * retainer cannot go through the unified sign+pay flow at all -- it would
187
+ * mint a $0 retainer PaymentIntent or a $0 subscription later, which is not
188
+ * a real error state Stripe rejects loudly; it just silently does nothing
189
+ * billable. Catch it here instead, before anything gets sent.
190
+ */
191
+ function validateAgreementBillability(v: FieldValues): string | null {
192
+ if (!v.plan_id || String(v.plan_id).trim() === '') return 'missing_plan_id';
193
+ if (!v.room_id || !/^[0-9a-f-]{36}$/i.test(String(v.room_id))) return 'missing_or_invalid_room_id';
194
+ try {
195
+ if (centsFrom(v.monthly_fee) <= 0) return 'monthly_fee_must_be_positive';
196
+ } catch {
197
+ return 'monthly_fee_unparseable';
198
+ }
199
+ const retainer = parseRetainerConfig(v);
200
+ if (!retainer.ok) return retainer.code === 'service_retainer_absent' ? 'service_retainer_must_be_positive' : retainer.code;
201
+ return null;
202
+ }
203
+
204
+ export async function handle(
205
+ req: Request,
206
+ operator: {
207
+ operatorName: string;
208
+ operatorShortName: string;
209
+ domain: string;
210
+ supportEmail: string;
211
+ providerRepresentativeName: string;
212
+ providerSignerEmail: string;
213
+ },
214
+ ): Promise<Response> {
215
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
216
+ if (req.method !== 'POST') return json(405, { ok: false, error: 'method_not_allowed' });
217
+
218
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
219
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
220
+
221
+ const authHeader = req.headers.get('Authorization') || req.headers.get('authorization');
222
+ const caller = await verifyCaller(authHeader, SUPABASE_URL);
223
+ if (!caller) return json(401, { ok: false, error: 'unauthenticated' });
224
+ if (caller.aal !== 'aal2') return json(403, { ok: false, error: 'mfa_required' });
225
+ const callerEmail = (caller.email ?? '').toLowerCase();
226
+ if (!callerEmail) return json(403, { ok: false, error: 'no_email' });
227
+
228
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
229
+ auth: { persistSession: false, autoRefreshToken: false },
230
+ });
231
+
232
+ const [ipOk, emailOk] = await Promise.all([
233
+ checkRateLimit(admin, 'create-agreement-ip', clientIp(req), 30, 300),
234
+ checkRateLimit(admin, 'create-agreement-email', callerEmail, 20, 300),
235
+ ]);
236
+ if (!ipOk || !emailOk) return json(429, { ok: false, error: 'rate_limited' });
237
+
238
+ const { data: allow, error: allowErr } = await admin
239
+ .from('admin_users').select('email').eq('email', callerEmail).maybeSingle();
240
+ if (allowErr) return json(500, { ok: false, error: 'allowlist_lookup_failed' });
241
+ if (!allow) return json(403, { ok: false, error: 'not_authorized' });
242
+
243
+ let body: { signature_document_id?: string };
244
+ try {
245
+ body = await req.json();
246
+ } catch {
247
+ return json(400, { ok: false, error: 'invalid_json' });
248
+ }
249
+ const docId = (body.signature_document_id ?? '').trim();
250
+ if (!/^[0-9a-f-]{36}$/i.test(docId)) {
251
+ return json(400, { ok: false, error: 'invalid_signature_document_id' });
252
+ }
253
+
254
+ const markFailed = async (reason: string) => {
255
+ await admin
256
+ .from('signature_documents')
257
+ .update({ status: 'failed', failure_reason: reason.slice(0, 500) })
258
+ .eq('id', docId);
259
+ };
260
+
261
+ // Undo an office_assignments reservation if something downstream fails
262
+ // after it was created. Safe to call even if no row was ever inserted.
263
+ const releaseRoomReservation = async () => {
264
+ await admin.from('office_assignments').delete().eq('signature_document_id', docId);
265
+ };
266
+
267
+ // 1. Atomic send-claim -- prevents two concurrent "Send" clicks (or a retry
268
+ // racing a still-in-flight first attempt) from both proceeding.
269
+ const { data: claimed, error: claimErr } = await admin.rpc('claim_agreement_for_send', { p_id: docId });
270
+ if (claimErr) return json(500, { ok: false, error: 'claim_rpc_failed', detail: claimErr.message });
271
+ if (!claimed) {
272
+ // Distinguish not-found from not-draft for a useful error, without this
273
+ // being part of the atomic guarantee itself (the RPC already decided).
274
+ const { data: existing } = await admin
275
+ .from('signature_documents').select('id,status').eq('id', docId).maybeSingle();
276
+ if (!existing) return json(404, { ok: false, error: 'not_found' });
277
+ return json(409, {
278
+ ok: false,
279
+ error: 'not_draft',
280
+ detail: `Document status is "${existing.status}"; only draft documents can be sent.`,
281
+ });
282
+ }
283
+
284
+ const releaseToDraft = async (reason: string) => {
285
+ await admin.from('signature_documents').update({ status: 'draft' }).eq('id', docId);
286
+ return json(422, { ok: false, error: 'validation_failed', detail: reason });
287
+ };
288
+
289
+ // Whether this document's type reserves the room at all -- read from
290
+ // tpl.reserves_room !== false (template row, step 5) once known, and used
291
+ // to gate the two room-reservation steps below (conflict check + insert).
292
+ let reservesRoom = true;
293
+
294
+ try {
295
+ // 2. Reload the now-claimed row.
296
+ const { data: row, error: rowErr } = await admin
297
+ .from('signature_documents')
298
+ .select('id,document_type,status,signer_name,signer_email,field_values,start_date')
299
+ .eq('id', docId)
300
+ .maybeSingle();
301
+ if (rowErr || !row) {
302
+ await markFailed('row_reload_failed_after_claim');
303
+ return json(500, { ok: false, error: 'row_reload_failed' });
304
+ }
305
+
306
+ const v = (row.field_values ?? {}) as FieldValues;
307
+
308
+ // 3. Pre-flight billability check -- reversible, goes back to draft so
309
+ // staff can just fix the field and hit Send again.
310
+ const billabilityError = validateAgreementBillability(v);
311
+ if (billabilityError) return await releaseToDraft(billabilityError);
312
+
313
+ // 4. Room must still exist (defends against a room being deleted between
314
+ // draft creation and send).
315
+ const roomId = String(v.room_id);
316
+ const { data: room, error: roomErr } = await admin
317
+ .from('rooms').select('id').eq('id', roomId).maybeSingle();
318
+ if (roomErr) return await releaseToDraft('room_lookup_failed: ' + roomErr.message);
319
+ if (!room) return await releaseToDraft('room_not_found');
320
+
321
+ // 5. Template row -- fetched ahead of the queue guard below so
322
+ // reserves_room is known before we decide whether that check (and the
323
+ // later office_assignments reservation in step 10) even applies.
324
+ const { data: tpl, error: tplErr } = await admin
325
+ .from('document_templates')
326
+ .select('*')
327
+ .eq('document_type', row.document_type)
328
+ .eq('active', true)
329
+ .maybeSingle();
330
+ if (tplErr || !tpl) {
331
+ await markFailed('template_not_configured: ' + (tplErr?.message ?? 'no active template'));
332
+ return json(500, { ok: false, error: 'template_not_configured', detail: tplErr?.message ?? 'no active template' });
333
+ }
334
+ reservesRoom = tpl.reserves_room !== false;
335
+
336
+ // 6. Server-side queue guard -- the admin form has a client-side version
337
+ // of this same check, but that one is a UX convenience only and cannot
338
+ // be trusted against a genuine race. Only applies to document types
339
+ // that actually reserve the room: a record-only document (e.g.
340
+ // secondary_record, reserves_room=false) must not be blocked by, or
341
+ // block, another incoming tenant for the room.
342
+ //
343
+ // An existing 'active' occupant is NOT a conflict: staff routinely need
344
+ // to draft/send/collect payment on the next tenant's agreement while the
345
+ // current one is still moving out. The real safety property (never two
346
+ // simultaneously 'active' rows per room) is enforced by the
347
+ // office_assignments_one_active_per_room unique index plus the
348
+ // end_office_assignment_and_promote RPC. What we still block here is a
349
+ // SECOND incoming tenant: only one row per room may sit in
350
+ // 'pending_activation' or 'awaiting_handoff'
351
+ // (office_assignments_one_incoming_per_room).
352
+ if (reservesRoom) {
353
+ const { data: conflicts, error: conflictErr } = await admin
354
+ .from('office_assignments')
355
+ .select('id,status,signature_document_id')
356
+ .eq('room_id', roomId)
357
+ .in('status', ['pending_activation', 'awaiting_handoff'])
358
+ .neq('signature_document_id', docId);
359
+ if (conflictErr) return await releaseToDraft('occupancy_check_failed: ' + conflictErr.message);
360
+ if (conflicts && conflicts.length > 0) {
361
+ return await releaseToDraft('room_already_reserved_by_' + conflicts[0].signature_document_id);
362
+ }
363
+ }
364
+
365
+ // 7. Download the DOCX template.
366
+ const { data: file, error: dlErr } = await admin.storage
367
+ .from('contract-templates')
368
+ .download('private_office_agreement_v1.docx');
369
+ if (dlErr || !file) {
370
+ await markFailed('template_download_failed: ' + (dlErr?.message ?? 'no file'));
371
+ return json(500, { ok: false, error: 'template_download_failed', detail: dlErr?.message ?? 'no file' });
372
+ }
373
+ const buf = await file.arrayBuffer();
374
+
375
+ // 8. Open with JSZip.
376
+ const zip = await JSZip.loadAsync(buf);
377
+ const docXmlFile = zip.file('word/document.xml');
378
+ if (!docXmlFile) {
379
+ await markFailed('template_malformed');
380
+ return json(500, { ok: false, error: 'template_malformed' });
381
+ }
382
+ const originalXml = await docXmlFile.async('string');
383
+
384
+ // 9. Substitutions.
385
+ const { xml, missing } = buildXml(originalXml, v);
386
+
387
+ const tagCount = (xml.match(/\{\{(text|sign|date|init)\|/g) ?? []).length;
388
+ if (tagCount !== 10) {
389
+ const detail = `Tag sanity check failed: found ${tagCount} BoldSign tags, expected 10. Missing literals: ${JSON.stringify(missing)}`;
390
+ await markFailed(detail);
391
+ return json(500, { ok: false, error: 'tag_sanity_check_failed', detail: detail.slice(0, 500), missing });
392
+ }
393
+
394
+ // 10. Reserve the room now that we know the document itself is valid --
395
+ // before the BoldSign call, so a concurrent second send attempt for
396
+ // the same room fails the occupancy check above rather than also
397
+ // emailing signers. Skipped entirely when reserves_room is false --
398
+ // a record-only document has nothing to reserve.
399
+ if (reservesRoom) {
400
+ const monthlyRateCents = centsFrom(v.monthly_fee); // already validated positive in step 3
401
+ const { error: assignErr } = await admin.from('office_assignments').insert({
402
+ room_id: roomId,
403
+ signature_document_id: docId,
404
+ contact_name: row.signer_name,
405
+ contact_email: row.signer_email,
406
+ monthly_rate_cents: monthlyRateCents,
407
+ addons: Array.isArray(v.addons) ? v.addons : [],
408
+ start_date: row.start_date,
409
+ status: 'pending_activation',
410
+ });
411
+ if (assignErr) {
412
+ await markFailed('office_assignment_insert_failed: ' + assignErr.message);
413
+ return json(500, { ok: false, error: 'office_assignment_insert_failed', detail: assignErr.message });
414
+ }
415
+ }
416
+
417
+ const retainerCheck = parseRetainerConfig(v);
418
+ if (retainerCheck.ok && retainerCheck.waived) {
419
+ try {
420
+ await logOps(admin, 'agreement_zero_retainer_waived', {
421
+ signature_document_id: docId, office_number: String(v.office_number ?? ''), actor: callerEmail,
422
+ }, { severity: 'warning' });
423
+ } catch (e) {
424
+ console.error('[create-agreement] audit log failed (non-fatal)', e);
425
+ }
426
+ }
427
+
428
+ // 11. Rebuild the docx.
429
+ zip.file('word/document.xml', xml);
430
+ const out: Uint8Array = await zip.generateAsync({ type: 'uint8array', compression: 'DEFLATE' });
431
+ const b64 = bytesToBase64(out);
432
+
433
+ // 12. Send to BoldSign.
434
+ const apiKey = Deno.env.get('BOLDSIGN_API_KEY');
435
+ if (!apiKey) {
436
+ await markFailed('BOLDSIGN_API_KEY is not configured');
437
+ await releaseRoomReservation();
438
+ return json(500, { ok: false, error: 'boldsign_not_configured' });
439
+ }
440
+
441
+ const payload = {
442
+ Title: 'Private Office Agreement - ' + row.signer_name,
443
+ DocumentTitle: 'Private Office Membership and License Agreement',
444
+ EnableSigningOrder: false,
445
+ Files: ['data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,' + b64],
446
+ UseTextTags: true,
447
+ OnBehalfOf: operator.supportEmail,
448
+ Signers: [
449
+ { Name: row.signer_name, EmailAddress: row.signer_email, SignerOrder: 1, SignerType: 'Signer' },
450
+ {
451
+ Name: operator.providerRepresentativeName,
452
+ EmailAddress: operator.providerSignerEmail,
453
+ SignerOrder: 2,
454
+ SignerType: 'Signer',
455
+ },
456
+ ],
457
+ };
458
+
459
+ const res = await fetch('https://api.boldsign.com/v1/document/send', {
460
+ method: 'POST',
461
+ headers: {
462
+ 'X-API-KEY': apiKey,
463
+ 'Content-Type': 'application/json',
464
+ accept: 'application/json',
465
+ },
466
+ body: JSON.stringify(payload),
467
+ });
468
+
469
+ const text = await res.text();
470
+ if (!res.ok) {
471
+ const detail = `BoldSign ${res.status}: ${text}`.slice(0, 500);
472
+ await markFailed(detail);
473
+ await releaseRoomReservation();
474
+ return json(500, { ok: false, error: 'boldsign_failed', detail });
475
+ }
476
+
477
+ let documentId: string | null = null;
478
+ try {
479
+ documentId = (JSON.parse(text) as { documentId?: string }).documentId ?? null;
480
+ } catch {
481
+ documentId = null;
482
+ }
483
+
484
+ // 13. Success -- flip both rows to "in flight". flow is 'unified' by
485
+ // migration default for any row created without an explicit flow,
486
+ // but write it explicitly here so this function's own contract
487
+ // doesn't silently depend on that default never changing.
488
+ await admin
489
+ .from('signature_documents')
490
+ .update({
491
+ boldsign_document_id: documentId,
492
+ status: 'sent',
493
+ sent_at: new Date().toISOString(),
494
+ failure_reason: null,
495
+ flow: 'unified',
496
+ })
497
+ .eq('id', docId);
498
+
499
+ // Portal "sign and pay" email. Strictly non-fatal: the agreement is already
500
+ // validly sent and status-updated above, so nothing here may change the
501
+ // 200 response. Only sent for a billable document_type -- its copy talks
502
+ // about reviewing and paying a retainer, which doesn't apply to a
503
+ // record-only document (e.g. secondary_record) that never bills. BoldSign's
504
+ // own native signing email is unaffected and still goes out either way.
505
+ if (tpl.fires_stripe) {
506
+ try {
507
+ const tokenSecret = Deno.env.get('MANAGE_TOKEN_SECRET');
508
+ if (tokenSecret) {
509
+ const portalUrl = await buildAgreementPortalUrl(`https://${operator.domain}`, docId, row.signer_email, tokenSecret);
510
+ const emailResult = await sendAgreementPortalEmail(admin, {
511
+ email: row.signer_email, name: row.signer_name, portalUrl, officeNumber: String(v.office_number ?? '') || undefined,
512
+ }, {
513
+ name: operator.operatorName,
514
+ shortName: operator.operatorShortName,
515
+ domain: operator.domain,
516
+ supportEmail: operator.supportEmail,
517
+ });
518
+ await admin.from('signature_documents').update({ portal_issued_at: new Date().toISOString() }).eq('id', docId);
519
+ if (emailResult !== 'sent') console.warn('[create-agreement] portal email not sent:', emailResult);
520
+ } else {
521
+ console.error('[create-agreement] MANAGE_TOKEN_SECRET not configured -- portal email not sent');
522
+ }
523
+ } catch (e) {
524
+ console.error('[create-agreement] portal email dispatch failed (non-fatal)', e);
525
+ }
526
+ } else {
527
+ console.log('[create-agreement] portal email skipped -- document_type', row.document_type, 'is not billable');
528
+ }
529
+
530
+ return json(200, { ok: true, documentId });
531
+ } catch (e) {
532
+ const detail = String(e).slice(0, 500);
533
+ await markFailed(detail);
534
+ await releaseRoomReservation();
535
+ return json(500, { ok: false, error: 'unhandled', detail });
536
+ }
537
+ }