@simplelayer/graniteer-core 0.1.2 → 0.2.1
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/index.js +2 -2
- package/package.json +73 -2
- package/src/agreementCheckout.ts +250 -0
- package/src/agreementPortalEmail.ts +128 -0
- package/src/billingPortalLinkEmail.ts +117 -0
- package/src/bookingAgreementEmail.ts +149 -0
- package/src/bookingEffects.ts +388 -0
- package/src/busClient.ts +268 -0
- package/src/busSignature.ts +71 -0
- package/src/checkoutCoupon.test.ts +675 -0
- package/src/checkoutCoupon.ts +455 -0
- package/src/commonsDeposit.ts +298 -0
- package/src/commonsDepositWebhook.ts +237 -0
- package/src/dayPassConfirmation.ts +230 -0
- package/src/dunningEmails.test.ts +263 -0
- package/src/dunningEmails.ts +203 -0
- package/src/email-templates/brand.ts +93 -0
- package/src/email-templates/magic-link.tsx +59 -0
- package/src/email-templates/recovery.tsx +59 -0
- package/src/email-templates/signup.tsx +67 -0
- package/src/functions/admin-cancel-membership.ts +311 -311
- package/src/functions/admin-change-membership-plan.ts +312 -308
- package/src/functions/admin-charge-guest-print.ts +229 -229
- package/src/functions/admin-correct-booking.ts +333 -333
- package/src/functions/admin-create-booking.ts +460 -0
- package/src/functions/admin-create-commons-event.ts +244 -244
- package/src/functions/admin-debug-boldsign-doc.ts +93 -93
- package/src/functions/admin-door-write.ts +272 -272
- package/src/functions/admin-issue-day-pass.ts +231 -0
- package/src/functions/admin-mark-booking-paid.ts +203 -203
- package/src/functions/admin-mint-billing-portal-link.ts +168 -0
- package/src/functions/admin-mint-portal-link.ts +62 -0
- package/src/functions/admin-photo-upload.ts +128 -128
- package/src/functions/admin-remove-team-member.ts +150 -150
- package/src/functions/admin-request-trial.ts +366 -0
- package/src/functions/admin-resend-commons-deposit-link.ts +323 -0
- package/src/functions/admin-reset-mfa.ts +138 -138
- package/src/functions/admin-retry-invoice-payment.test.ts +567 -0
- package/src/functions/admin-retry-invoice-payment.ts +333 -0
- package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
- package/src/functions/admin-revoke-agreement.ts +467 -0
- package/src/functions/admin-send-commons-agreement.ts +214 -214
- package/src/functions/admin-set-credit-amount.ts +123 -123
- package/src/functions/admin-skip-commons-contract.ts +165 -165
- package/src/functions/admin-undo-membership-cancel.ts +144 -144
- package/src/functions/admin-wall-photo-write.ts +141 -141
- package/src/functions/auth-email-hook.ts +259 -0
- package/src/functions/boldsign-sender-identity.ts +114 -114
- package/src/functions/booking-availability.ts +419 -419
- package/src/functions/booking-member-preview.ts +136 -136
- package/src/functions/booking-status.ts +149 -0
- package/src/functions/conductor.ts +505 -0
- package/src/functions/create-agreement.ts +537 -0
- package/src/functions/create-booking.ts +648 -0
- package/src/functions/create-day-pass-checkout.ts +218 -0
- package/src/functions/create-portal-session.ts +142 -0
- package/src/functions/create-subscription-checkout.test.ts +222 -0
- package/src/functions/create-subscription-checkout.ts +440 -0
- package/src/functions/day-pass-status.ts +89 -89
- package/src/functions/diag-webpush-test.ts +45 -45
- package/src/functions/event-access-admin.ts +277 -0
- package/src/functions/event-access-store.ts +334 -309
- package/src/functions/ezeep-print-webhook.ts +213 -213
- package/src/functions/ezeep-usage-reconcile.ts +299 -299
- package/src/functions/fetch-avatar-original.ts +457 -0
- package/src/functions/get-provider-sign-link.ts +155 -0
- package/src/functions/get-signing-link.ts +211 -211
- package/src/functions/guest-print-setup-confirm.ts +128 -128
- package/src/functions/guest-print-submit.ts +149 -149
- package/src/functions/luma-webhook.ts +165 -165
- package/src/functions/manage-booking.ts +472 -0
- package/src/functions/mcp.ts +67 -0
- package/src/functions/member-door-action.test.ts +1248 -0
- package/src/functions/member-door-action.ts +863 -0
- package/src/functions/member-unifi-mapping.test.ts +516 -0
- package/src/functions/member-unifi-mapping.ts +206 -0
- package/src/functions/membership-door-sync.ts +956 -0
- package/src/functions/migration-collision-alert.copy.ts +232 -232
- package/src/functions/migration-collision-alert.test.ts +349 -349
- package/src/functions/migration-collision-alert.ts +232 -232
- package/src/functions/office-assignment-end.ts +146 -146
- package/src/functions/portal-booking-access.ts +217 -95
- package/src/functions/portal-list-invoices.ts +99 -99
- package/src/functions/portal-request-login.ts +192 -0
- package/src/functions/portal-resend-invite.ts +248 -0
- package/src/functions/portal-submit-event.ts +168 -0
- package/src/functions/print-billing-recover.ts +97 -97
- package/src/functions/print-billing-run.ts +183 -183
- package/src/functions/public-facts.ts +168 -168
- package/src/functions/push-send.ts +348 -0
- package/src/functions/push-test.ts +234 -0
- package/src/functions/request-portal-link.ts +211 -0
- package/src/functions/reschedule-booking.ts +649 -0
- package/src/functions/review-ratings.ts +113 -0
- package/src/functions/space-availability-range.acceptance.test.ts +161 -161
- package/src/functions/space-availability-range.ts +142 -142
- package/src/functions/stripe-db-reconcile.ts +319 -0
- package/src/functions/stripe-webhook.moved-regression.test.ts +78 -0
- package/src/functions/stripe-webhook.ts +2595 -0
- package/src/functions/sync-gcal-blackouts.ts +298 -298
- package/src/functions/timetable-event-register.ts +162 -162
- package/src/functions/timetable-event-status.ts +90 -90
- package/src/functions/timetable-spaces.ts +219 -219
- package/src/functions/touch-pass-reconciler.ts +689 -689
- package/src/functions/touch-pass-signup.ts +478 -0
- package/src/functions/upload-booking-display-image.ts +179 -0
- package/src/functions/virtual-onboarding-purge.ts +134 -134
- package/src/functions/virtual-onboarding-submit.ts +315 -315
- package/src/functions/voice-booking.ts +453 -0
- package/src/functions/voice-day-pass.ts +346 -0
- package/src/functions/voice-inquiry.test.ts +301 -301
- package/src/functions/voice-inquiry.ts +198 -198
- package/src/functions/voice-membership-signup.ts +355 -0
- package/src/functions/voice-tour-availability.ts +204 -204
- package/src/functions/voice-tour-booking.ts +429 -0
- package/src/ghlEventInquiry.ts +143 -0
- package/src/mailArrivalEmail.ts +121 -0
- package/src/manageToken.ts +363 -0
- package/src/membershipBusClient.ts +537 -0
- package/src/membershipWelcome.ts +683 -0
- package/src/migrationCheckout.ts +366 -0
- package/src/pacificDate.ts +54 -0
- package/src/paymentLinkEmail.ts +123 -0
- package/src/signedUnpaidReminderEmail.test.ts +246 -0
- package/src/signedUnpaidReminderEmail.ts +132 -0
- package/src/stripeCoworkingPortal.ts +91 -0
- package/src/supabaseTestFakes.ts +131 -131
- package/src/supportTicketEmail.ts +119 -0
- package/src/unifiAccessPolicies.ts +228 -0
- package/src/unifiGroups.ts +129 -0
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// Staff-triggered "update your billing" email, sent when an admin mints a
|
|
2
|
+
// Stripe billing-portal link for a member from the admin console.
|
|
3
|
+
//
|
|
4
|
+
// Mirrors the GHL request shape, headers, escaping and error classification
|
|
5
|
+
// of sendPaymentLinkEmail in ./paymentLinkEmail.ts -- same transport, same
|
|
6
|
+
// safety properties, different copy (this is for an EXISTING member updating
|
|
7
|
+
// a card on file, not a new signup completing checkout).
|
|
8
|
+
|
|
9
|
+
import type { createClient, SupabaseClient } from 'npm:@supabase/supabase-js@2';
|
|
10
|
+
import { logOps } from './ops.ts';
|
|
11
|
+
|
|
12
|
+
type SupabaseLike = SupabaseClient<any, 'public', any>;
|
|
13
|
+
|
|
14
|
+
export type BillingPortalLinkEmailResult = 'sent' | 'skipped' | 'failed_retryable' | 'failed_permanent';
|
|
15
|
+
|
|
16
|
+
function esc(v: unknown): string {
|
|
17
|
+
return String(v ?? '')
|
|
18
|
+
.replace(/&/g, '&')
|
|
19
|
+
.replace(/</g, '<')
|
|
20
|
+
.replace(/>/g, '>')
|
|
21
|
+
.replace(/"/g, '"')
|
|
22
|
+
.replace(/'/g, ''');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function classifyError(e: unknown): 'failed_retryable' | 'failed_permanent' {
|
|
26
|
+
const name = e instanceof Error ? e.name : '';
|
|
27
|
+
if (name === 'AbortError' || name === 'TimeoutError') return 'failed_retryable';
|
|
28
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
29
|
+
const m = msg.match(/^ghl_(?:upsert|email)_(\d{3})/);
|
|
30
|
+
if (m) {
|
|
31
|
+
const code = Number(m[1]);
|
|
32
|
+
if (code === 429 || code >= 500) return 'failed_retryable';
|
|
33
|
+
}
|
|
34
|
+
return 'failed_permanent';
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function sendBillingPortalLinkEmail(
|
|
38
|
+
supabase: SupabaseLike,
|
|
39
|
+
{ email, name, portalUrl }: {
|
|
40
|
+
email: string;
|
|
41
|
+
name?: string | null;
|
|
42
|
+
portalUrl: string;
|
|
43
|
+
},
|
|
44
|
+
operator: { name: string; shortName: string; domain: string; supportEmail: string },
|
|
45
|
+
): Promise<BillingPortalLinkEmailResult> {
|
|
46
|
+
try {
|
|
47
|
+
const apiKey = Deno.env.get('GHL_API_KEY');
|
|
48
|
+
const locationId = Deno.env.get('GHL_LOCATION_ID');
|
|
49
|
+
if (!apiKey || !locationId) {
|
|
50
|
+
await logOps(supabase, 'billing_portal_link_email_skipped',
|
|
51
|
+
{ email, reason: 'ghl_not_configured' }, { severity: 'warning' }).catch(() => {});
|
|
52
|
+
return 'skipped';
|
|
53
|
+
}
|
|
54
|
+
const GHL_BASE = 'https://services.leadconnectorhq.com';
|
|
55
|
+
const headers = {
|
|
56
|
+
Authorization: `Bearer ${apiKey}`,
|
|
57
|
+
Version: '2021-07-28',
|
|
58
|
+
'Content-Type': 'application/json',
|
|
59
|
+
Accept: 'application/json',
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
const trimmed = (name || '').trim();
|
|
63
|
+
const parts = trimmed.split(/\s+/).filter(Boolean);
|
|
64
|
+
const greetingName = parts[0] || 'there';
|
|
65
|
+
const crmName: { firstName?: string; lastName?: string } = {};
|
|
66
|
+
if (parts[0]) crmName.firstName = parts[0];
|
|
67
|
+
if (parts.length > 1) crmName.lastName = parts.slice(1).join(' ');
|
|
68
|
+
|
|
69
|
+
const upRes = await fetch(`${GHL_BASE}/contacts/upsert`, {
|
|
70
|
+
method: 'POST', headers,
|
|
71
|
+
signal: AbortSignal.timeout(8000),
|
|
72
|
+
body: JSON.stringify({
|
|
73
|
+
locationId, ...crmName, email,
|
|
74
|
+
source: `${operator.shortName} Admin — Billing Update`,
|
|
75
|
+
tags: ['Billing Update', operator.domain],
|
|
76
|
+
}),
|
|
77
|
+
});
|
|
78
|
+
if (!upRes.ok) throw new Error(`ghl_upsert_${upRes.status}: ${await upRes.text()}`);
|
|
79
|
+
const upJson = await upRes.json();
|
|
80
|
+
const contactId = upJson.contact?.id || upJson.id || null;
|
|
81
|
+
if (!contactId) throw new Error('ghl_upsert_no_contact_id');
|
|
82
|
+
|
|
83
|
+
const p = (t: string) =>
|
|
84
|
+
`<p style="margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:22px">${t}</p>`;
|
|
85
|
+
|
|
86
|
+
const html = `<div style="background:#F6F6F6;padding:24px 0;margin:0"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;background:#F6F6F6"><tr><td align="center" style="padding:0 12px"><table role="presentation" width="560" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;max-width:560px;width:100%;background:#FFFFFF;border-radius:10px"><tr><td style="padding:24px">
|
|
87
|
+
<h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">Update your ${operator.shortName} billing details</h2>
|
|
88
|
+
${p(`Hi ${esc(greetingName)},`)}
|
|
89
|
+
${p(`Our team wanted to make it easy for you to update the payment method on your ${operator.name} membership. Use the secure link below:`)}
|
|
90
|
+
${p(`<a href="${esc(portalUrl)}" style="color:#C98A5E">Update payment method →</a>`)}
|
|
91
|
+
${p("This link is unique to your account and takes you straight to our payment processor, Stripe, where you can update your card, view invoices, and manage your subscription. Please don't forward it.")}
|
|
92
|
+
${p(`Questions? Just reply to this email or reach us at <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`)}
|
|
93
|
+
${p(`Thanks,<br />The ${operator.name} team`)}
|
|
94
|
+
</td></tr></table></td></tr></table></div>`;
|
|
95
|
+
|
|
96
|
+
const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
|
|
97
|
+
method: 'POST', headers,
|
|
98
|
+
signal: AbortSignal.timeout(8000),
|
|
99
|
+
body: JSON.stringify({
|
|
100
|
+
type: 'Email',
|
|
101
|
+
contactId,
|
|
102
|
+
subject: `Update your ${operator.shortName} billing details`,
|
|
103
|
+
html,
|
|
104
|
+
}),
|
|
105
|
+
});
|
|
106
|
+
if (!emailRes.ok) throw new Error(`ghl_email_${emailRes.status}: ${await emailRes.text()}`);
|
|
107
|
+
|
|
108
|
+
await logOps(supabase, 'billing_portal_link_email_sent', { email }, { severity: 'info' }).catch(() => {});
|
|
109
|
+
return 'sent';
|
|
110
|
+
} catch (e) {
|
|
111
|
+
const classification = classifyError(e);
|
|
112
|
+
await logOps(supabase, 'billing_portal_link_email_failed',
|
|
113
|
+
{ email, message: e instanceof Error ? e.message : String(e) },
|
|
114
|
+
{ severity: classification === 'failed_permanent' ? 'error' : 'warning' }).catch(() => {});
|
|
115
|
+
return classification;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
// Customer emails for the Tier 2 (day-rate) booking agreement flow.
|
|
2
|
+
//
|
|
3
|
+
// Same GHL transport, headers, timeouts and error classification as
|
|
4
|
+
// _shared/paymentLinkEmail.ts — do not introduce a second email channel.
|
|
5
|
+
import type { createClient, SupabaseClient } from 'npm:@supabase/supabase-js@2';
|
|
6
|
+
import { logOps } from './ops.ts';
|
|
7
|
+
|
|
8
|
+
type SupabaseLike = SupabaseClient<any, 'public', any>;
|
|
9
|
+
|
|
10
|
+
export type BookingAgreementEmailResult = 'sent' | 'skipped' | 'failed_retryable' | 'failed_permanent';
|
|
11
|
+
|
|
12
|
+
type Operator = { name: string; shortName: string; supportEmail: string };
|
|
13
|
+
|
|
14
|
+
function esc(v: unknown): string {
|
|
15
|
+
return String(v ?? '')
|
|
16
|
+
.replace(/&/g, '&')
|
|
17
|
+
.replace(/</g, '<')
|
|
18
|
+
.replace(/>/g, '>')
|
|
19
|
+
.replace(/"/g, '"')
|
|
20
|
+
.replace(/'/g, ''');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function classifyError(e: unknown): 'failed_retryable' | 'failed_permanent' {
|
|
24
|
+
const name = e instanceof Error ? e.name : '';
|
|
25
|
+
if (name === 'AbortError' || name === 'TimeoutError') return 'failed_retryable';
|
|
26
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
27
|
+
const m = msg.match(/^ghl_(?:upsert|email)_(\d{3})/);
|
|
28
|
+
if (m) {
|
|
29
|
+
const code = Number(m[1]);
|
|
30
|
+
if (code === 429 || code >= 500) return 'failed_retryable';
|
|
31
|
+
}
|
|
32
|
+
return 'failed_permanent';
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function sendViaGhl(
|
|
36
|
+
supabase: SupabaseLike,
|
|
37
|
+
opts: { email: string; name?: string | null; subject: string; body: (greeting: string) => string; opsPrefix: string; operator: Operator },
|
|
38
|
+
): Promise<BookingAgreementEmailResult> {
|
|
39
|
+
try {
|
|
40
|
+
const apiKey = Deno.env.get('GHL_API_KEY');
|
|
41
|
+
const locationId = Deno.env.get('GHL_LOCATION_ID');
|
|
42
|
+
if (!apiKey || !locationId) {
|
|
43
|
+
await logOps(supabase, `${opts.opsPrefix}_skipped`,
|
|
44
|
+
{ email: opts.email, reason: 'ghl_not_configured' }, { severity: 'warning' }).catch(() => {});
|
|
45
|
+
return 'skipped';
|
|
46
|
+
}
|
|
47
|
+
const GHL_BASE = 'https://services.leadconnectorhq.com';
|
|
48
|
+
const headers = {
|
|
49
|
+
Authorization: `Bearer ${apiKey}`,
|
|
50
|
+
Version: '2021-07-28',
|
|
51
|
+
'Content-Type': 'application/json',
|
|
52
|
+
Accept: 'application/json',
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const trimmed = (opts.name || '').trim();
|
|
56
|
+
const parts = trimmed.split(/\s+/).filter(Boolean);
|
|
57
|
+
const greetingName = parts[0] || 'there';
|
|
58
|
+
const crmName: { firstName?: string; lastName?: string } = {};
|
|
59
|
+
if (parts[0]) crmName.firstName = parts[0];
|
|
60
|
+
if (parts.length > 1) crmName.lastName = parts.slice(1).join(' ');
|
|
61
|
+
|
|
62
|
+
const upRes = await fetch(`${GHL_BASE}/contacts/upsert`, {
|
|
63
|
+
method: 'POST', headers,
|
|
64
|
+
signal: AbortSignal.timeout(8000),
|
|
65
|
+
body: JSON.stringify({
|
|
66
|
+
locationId, ...crmName, email: opts.email,
|
|
67
|
+
source: `${opts.operator.shortName} Website — Room Booking`,
|
|
68
|
+
}),
|
|
69
|
+
});
|
|
70
|
+
if (!upRes.ok) throw new Error(`ghl_upsert_${upRes.status}: ${await upRes.text()}`);
|
|
71
|
+
const upJson = await upRes.json();
|
|
72
|
+
const contactId = upJson.contact?.id || upJson.id || null;
|
|
73
|
+
if (!contactId) throw new Error('ghl_upsert_no_contact_id');
|
|
74
|
+
|
|
75
|
+
const html = `<div style="background:#F6F6F6;padding:24px 0;margin:0"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;background:#F6F6F6"><tr><td align="center" style="padding:0 12px"><table role="presentation" width="560" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;max-width:560px;width:100%;background:#FFFFFF;border-radius:10px"><tr><td style="padding:24px">
|
|
76
|
+
<h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">${esc(opts.subject)}</h2>
|
|
77
|
+
${opts.body(esc(greetingName))}
|
|
78
|
+
</td></tr></table></td></tr></table></div>`;
|
|
79
|
+
|
|
80
|
+
const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
|
|
81
|
+
method: 'POST', headers,
|
|
82
|
+
signal: AbortSignal.timeout(8000),
|
|
83
|
+
body: JSON.stringify({ type: 'Email', contactId, subject: opts.subject, html }),
|
|
84
|
+
});
|
|
85
|
+
if (!emailRes.ok) throw new Error(`ghl_email_${emailRes.status}: ${await emailRes.text()}`);
|
|
86
|
+
|
|
87
|
+
await logOps(supabase, `${opts.opsPrefix}_sent`, { email: opts.email }, { severity: 'info' }).catch(() => {});
|
|
88
|
+
return 'sent';
|
|
89
|
+
} catch (e) {
|
|
90
|
+
const classification = classifyError(e);
|
|
91
|
+
await logOps(supabase, `${opts.opsPrefix}_failed`,
|
|
92
|
+
{ email: opts.email, message: e instanceof Error ? e.message : String(e) },
|
|
93
|
+
{ severity: classification === 'failed_permanent' ? 'error' : 'warning' }).catch(() => {});
|
|
94
|
+
return classification;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const p = (t: string) =>
|
|
99
|
+
`<p style="margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:22px">${t}</p>`;
|
|
100
|
+
|
|
101
|
+
/** Agreement signed — the customer may now pay for the held slot. */
|
|
102
|
+
export function sendBookingAgreementSignedEmail(
|
|
103
|
+
supabase: SupabaseLike,
|
|
104
|
+
{ email, name, roomName, checkoutUrl }: {
|
|
105
|
+
email: string; name?: string | null; roomName?: string | null; checkoutUrl?: string | null;
|
|
106
|
+
},
|
|
107
|
+
operator: Operator,
|
|
108
|
+
): Promise<BookingAgreementEmailResult> {
|
|
109
|
+
const room = (roomName || '').trim();
|
|
110
|
+
const subject = `Your ${operator.shortName} room agreement is signed — complete payment`;
|
|
111
|
+
return sendViaGhl(supabase, {
|
|
112
|
+
email, name, subject, opsPrefix: 'booking_agreement_signed_email', operator,
|
|
113
|
+
body: (greeting) => [
|
|
114
|
+
p(`Hi ${greeting},`),
|
|
115
|
+
p(`Thanks for signing your room use agreement${room ? ` for ${esc(room)}` : ''} — the last step is payment.`),
|
|
116
|
+
checkoutUrl
|
|
117
|
+
? p(`<a href="${esc(checkoutUrl)}" style="color:#C98A5E">Complete your payment →</a>`)
|
|
118
|
+
: p(`Reply to this email and we'll send you a payment link right away.`),
|
|
119
|
+
p(`Your booking isn't confirmed until payment is complete. This link is unique to your booking, so please don't forward it.`),
|
|
120
|
+
p(`Questions? Reach us at <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`),
|
|
121
|
+
p(`— The ${operator.name} team`),
|
|
122
|
+
].join(''),
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Agreement declined/expired — the held slot was released. */
|
|
127
|
+
export function sendBookingAgreementNotCompletedEmail(
|
|
128
|
+
supabase: SupabaseLike,
|
|
129
|
+
{ email, name, roomName, reason }: {
|
|
130
|
+
email: string; name?: string | null; roomName?: string | null; reason: 'declined' | 'expired';
|
|
131
|
+
},
|
|
132
|
+
operator: Operator,
|
|
133
|
+
): Promise<BookingAgreementEmailResult> {
|
|
134
|
+
const room = (roomName || '').trim();
|
|
135
|
+
const subject = `Your ${operator.shortName} booking wasn't completed`;
|
|
136
|
+
const why = reason === 'declined'
|
|
137
|
+
? 'the room use agreement was declined'
|
|
138
|
+
: 'the room use agreement wasn\'t signed in time';
|
|
139
|
+
return sendViaGhl(supabase, {
|
|
140
|
+
email, name, subject, opsPrefix: 'booking_agreement_not_completed_email', operator,
|
|
141
|
+
body: (greeting) => [
|
|
142
|
+
p(`Hi ${greeting},`),
|
|
143
|
+
p(`We released your hold${room ? ` on ${esc(room)}` : ''} because ${why}. You haven't been charged.`),
|
|
144
|
+
p(`If you'd still like the space, just book again and we'll send a fresh agreement.`),
|
|
145
|
+
p(`Questions? Reach us at <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`),
|
|
146
|
+
p(`— The ${operator.name} team`),
|
|
147
|
+
].join(''),
|
|
148
|
+
});
|
|
149
|
+
}
|
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
// Post-paid booking side effects: notify GHL (upsert contact, set booking
|
|
2
|
+
// custom fields incl. Manage Link, add note, send the confirmation email).
|
|
3
|
+
//
|
|
4
|
+
// Phase 8 of the Graniteer/Granite-City split: the generic half of
|
|
5
|
+
// gc-connect's _shared/bookingEffects.ts. Tenant values (operator identity,
|
|
6
|
+
// the manage-link origin, the GHL custom-field display names) are now passed
|
|
7
|
+
// in as `config` rather than read from a tenant module.
|
|
8
|
+
//
|
|
9
|
+
// createCalendarEvent deliberately did NOT move: it signs the calendar event's
|
|
10
|
+
// extended properties via gc-connect's _shared/busClient.ts (gc_sig /
|
|
11
|
+
// gc_sig_v2, a pinned cross-repo contract with ftw-middleware's reconciler).
|
|
12
|
+
// That whole door/calendar-signing group is deferred to a later phase gated on
|
|
13
|
+
// a dedicated security review, so createCalendarEvent stays in gc-connect,
|
|
14
|
+
// untouched, and imports isDepositOnly/parseTstzRange/formatDollars from here.
|
|
15
|
+
|
|
16
|
+
import type { SupabaseClient } from 'npm:@supabase/supabase-js@2';
|
|
17
|
+
import { buildManageUrl } from './manageToken.ts';
|
|
18
|
+
import { deriveReservationWifiCode, isReservationWifiRoom } from './reservationWifiCode.ts';
|
|
19
|
+
|
|
20
|
+
const LA_TZ = 'America/Los_Angeles';
|
|
21
|
+
const GHL_BASE = 'https://services.leadconnectorhq.com';
|
|
22
|
+
|
|
23
|
+
// Loose generics, matching ./ops.ts. A real createClient(url, key, opts)
|
|
24
|
+
// call infers SupabaseClient<any, 'public', 'public', ...>, which is NOT
|
|
25
|
+
// assignable to the un-inferred ReturnType<typeof createClient> default — that
|
|
26
|
+
// mismatch is what made every call site here fail deno check.
|
|
27
|
+
// deno-lint-ignore no-explicit-any
|
|
28
|
+
type SupabaseLike = SupabaseClient<any, any, any>;
|
|
29
|
+
|
|
30
|
+
export interface BookingRow {
|
|
31
|
+
id: string;
|
|
32
|
+
contact_name: string | null;
|
|
33
|
+
contact_email: string;
|
|
34
|
+
contact_phone: string | null;
|
|
35
|
+
during: string;
|
|
36
|
+
charged_amount_cents: number | null;
|
|
37
|
+
list_amount_cents: number | null;
|
|
38
|
+
google_event_id: string | null;
|
|
39
|
+
ghl_contact_id?: string | null;
|
|
40
|
+
/** Present on callers that select it; used only by isDepositOnly() below. */
|
|
41
|
+
status?: string | null;
|
|
42
|
+
rooms: {
|
|
43
|
+
id: string;
|
|
44
|
+
name: string;
|
|
45
|
+
address: string | null;
|
|
46
|
+
google_calendar_id: string | null;
|
|
47
|
+
slug: string | null;
|
|
48
|
+
/**
|
|
49
|
+
* Free-text "About this room" copy (rooms.usage_instructions). Optional so
|
|
50
|
+
* a caller that doesn't select it simply omits the email section; NULL/
|
|
51
|
+
* absent = this room has no instructions and nothing is rendered.
|
|
52
|
+
*/
|
|
53
|
+
usage_instructions?: string | null;
|
|
54
|
+
} | null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The door credential minted for this reservation, when the door bus issued
|
|
59
|
+
* one. Structurally identical to gc-connect's _shared/busClient.ts `DoorAccess`
|
|
60
|
+
* — declared here so this module carries no dependency on that (deferred,
|
|
61
|
+
* security-reviewed) file.
|
|
62
|
+
*/
|
|
63
|
+
export interface BookingDoorAccess {
|
|
64
|
+
pin: string;
|
|
65
|
+
validFromUtc?: string;
|
|
66
|
+
validToUtc?: string;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* A Commons (tier 3) event that has only paid its 50% deposit. The space is not
|
|
71
|
+
* access-provisioned, the calendar hold is staff-managed and the standard
|
|
72
|
+
* booking-confirmation copy would be wrong, so the whole post-paid chain
|
|
73
|
+
* (busProvision / createCalendarEvent / notifyGhl confirmation) is suppressed.
|
|
74
|
+
* Discriminated on STATUS, never on room slug.
|
|
75
|
+
*/
|
|
76
|
+
export function isDepositOnly(booking: { status?: string | null } | null | undefined): boolean {
|
|
77
|
+
return booking?.status === 'deposit_paid';
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
export function parseTstzRange(range: string): { startISO: string; endISO: string } | null {
|
|
83
|
+
const m = range.match(/[[(]"?([^",)]+)"?,"?([^",)]+)"?[\])]/);
|
|
84
|
+
if (!m) return null;
|
|
85
|
+
const normalize = (raw: string): string => {
|
|
86
|
+
let v = raw.trim().replace(/ /g, 'T');
|
|
87
|
+
v = v.replace(/([+-]\d{2})$/, '$1:00');
|
|
88
|
+
return v;
|
|
89
|
+
};
|
|
90
|
+
const s = new Date(normalize(m[1]));
|
|
91
|
+
const e = new Date(normalize(m[2]));
|
|
92
|
+
if (isNaN(s.getTime()) || isNaN(e.getTime())) return null;
|
|
93
|
+
return { startISO: s.toISOString(), endISO: e.toISOString() };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function formatWhen(startISO: string, endISO: string): string {
|
|
97
|
+
const s = new Date(startISO);
|
|
98
|
+
const e = new Date(endISO);
|
|
99
|
+
const day = new Intl.DateTimeFormat('en-US', {
|
|
100
|
+
timeZone: LA_TZ, weekday: 'short', month: 'short', day: 'numeric',
|
|
101
|
+
}).format(s);
|
|
102
|
+
const timeFmt = (d: Date) => new Intl.DateTimeFormat('en-US', {
|
|
103
|
+
timeZone: LA_TZ, hour: 'numeric', minute: '2-digit', hour12: true,
|
|
104
|
+
}).format(d).replace(/[\u202F\u00A0]/g, ' ');
|
|
105
|
+
const [startTime, startMer] = timeFmt(s).split(' ');
|
|
106
|
+
const [endTime, endMer] = timeFmt(e).split(' ');
|
|
107
|
+
const left = startMer === endMer ? startTime : `${startTime} ${startMer}`;
|
|
108
|
+
return `${day} · ${left}–${endTime} ${endMer} PT`;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Same escaper as every other email module here (dayPassConfirmation.ts,
|
|
112
|
+
// paymentLinkEmail.ts, …). Room usage instructions are staff-entered free text
|
|
113
|
+
// going into an HTML email, so they get escaped, never interpolated raw.
|
|
114
|
+
function esc(v: unknown): string {
|
|
115
|
+
return String(v ?? '')
|
|
116
|
+
.replace(/&/g, '&')
|
|
117
|
+
.replace(/</g, '<')
|
|
118
|
+
.replace(/>/g, '>')
|
|
119
|
+
.replace(/"/g, '"')
|
|
120
|
+
.replace(/'/g, ''');
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Plain text with line breaks preserved — no markdown, by design. */
|
|
124
|
+
function textToHtmlParagraphs(text: string): string {
|
|
125
|
+
return text
|
|
126
|
+
.split(/\n{2,}/)
|
|
127
|
+
.map((block) => block.trim())
|
|
128
|
+
.filter((block) => block.length > 0)
|
|
129
|
+
.map((block) => `<p style='margin:0 0 10px 0;color:#22263B;font-size:14px'>${esc(block).replace(/\n/g, '<br />')}</p>`)
|
|
130
|
+
.join('');
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function formatDollars(cents: number | null | undefined): string {
|
|
134
|
+
const c = cents ?? 0;
|
|
135
|
+
return `$${(c / 100).toFixed(c % 100 === 0 ? 0 : 2)}`;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function googleCalendarUrl(startISO: string, endISO: string, title: string, details: string, location: string): string {
|
|
139
|
+
const compact = (iso: string) => new Date(iso).toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
|
|
140
|
+
const dates = `${compact(startISO)}/${compact(endISO)}`;
|
|
141
|
+
const params = `action=TEMPLATE&text=${encodeURIComponent(title)}&dates=${dates}&details=${encodeURIComponent(details)}&location=${encodeURIComponent(location)}`;
|
|
142
|
+
return `https://calendar.google.com/calendar/render?${params}`;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function ghlHeaders(apiKey: string) {
|
|
146
|
+
return {
|
|
147
|
+
Authorization: `Bearer ${apiKey}`,
|
|
148
|
+
Version: '2021-07-28',
|
|
149
|
+
'Content-Type': 'application/json',
|
|
150
|
+
Accept: 'application/json',
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function ensureCustomFields(
|
|
155
|
+
apiKey: string,
|
|
156
|
+
locationId: string,
|
|
157
|
+
names: readonly string[],
|
|
158
|
+
): Promise<Record<string, string>> {
|
|
159
|
+
const map: Record<string, string> = {};
|
|
160
|
+
const listRes = await fetch(`${GHL_BASE}/locations/${locationId}/customFields`, {
|
|
161
|
+
headers: ghlHeaders(apiKey),
|
|
162
|
+
});
|
|
163
|
+
const existing: Array<{ id: string; name: string; fieldKey?: string }> = listRes.ok
|
|
164
|
+
? ((await listRes.json()).customFields ?? [])
|
|
165
|
+
: [];
|
|
166
|
+
for (const name of names) {
|
|
167
|
+
const found = existing.find((f) => (f.name || '').toLowerCase() === name.toLowerCase());
|
|
168
|
+
if (found) { map[name] = found.id; continue; }
|
|
169
|
+
try {
|
|
170
|
+
const createRes = await fetch(`${GHL_BASE}/locations/${locationId}/customFields`, {
|
|
171
|
+
method: 'POST', headers: ghlHeaders(apiKey),
|
|
172
|
+
body: JSON.stringify({ name, dataType: 'TEXT', position: 0 }),
|
|
173
|
+
});
|
|
174
|
+
if (createRes.ok) {
|
|
175
|
+
const cf = (await createRes.json()).customField;
|
|
176
|
+
if (cf?.id) map[name] = cf.id;
|
|
177
|
+
} else {
|
|
178
|
+
console.warn('[bookingEffects] custom field create failed', name, createRes.status, await createRes.text());
|
|
179
|
+
}
|
|
180
|
+
} catch (e) {
|
|
181
|
+
console.warn('[bookingEffects] custom field create error', name, e);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return map;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Display names of the GHL contact custom fields this module reads/creates in
|
|
189
|
+
* the operator's own GHL location. They are free-text labels a human picked in
|
|
190
|
+
* GHL, so they are tenant config, not platform constants.
|
|
191
|
+
*/
|
|
192
|
+
export type BookingCustomFieldNames = {
|
|
193
|
+
room: string;
|
|
194
|
+
when: string;
|
|
195
|
+
amount: string;
|
|
196
|
+
address: string;
|
|
197
|
+
calendarLink: string;
|
|
198
|
+
manageLink: string;
|
|
199
|
+
reminderWaitHours: string;
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
export type NotifyGhlConfig = {
|
|
203
|
+
operator: {
|
|
204
|
+
/** Full brand name, e.g. "Granite City Workspaces". */
|
|
205
|
+
name: string;
|
|
206
|
+
/** Short brand name used in the GHL contact `source`. */
|
|
207
|
+
shortName: string;
|
|
208
|
+
/** Bare apex domain, applied as a GHL tag. */
|
|
209
|
+
domain: string;
|
|
210
|
+
};
|
|
211
|
+
/** Absolute origin the signed manage-booking link is built against. */
|
|
212
|
+
manageUrlBase: string;
|
|
213
|
+
customFieldNames: BookingCustomFieldNames;
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
export async function notifyGhl(
|
|
217
|
+
supabase: SupabaseLike,
|
|
218
|
+
booking: BookingRow,
|
|
219
|
+
config: NotifyGhlConfig,
|
|
220
|
+
doorAccess?: BookingDoorAccess | null,
|
|
221
|
+
) {
|
|
222
|
+
const { operator, customFieldNames: cf } = config;
|
|
223
|
+
if (isDepositOnly(booking)) {
|
|
224
|
+
console.log('[bookingEffects] deposit-only booking; skip GHL confirmation', booking.id);
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
const apiKey = Deno.env.get('GHL_API_KEY');
|
|
228
|
+
const locationId = Deno.env.get('GHL_LOCATION_ID');
|
|
229
|
+
if (!apiKey || !locationId) { console.log('[bookingEffects] GHL not configured'); return; }
|
|
230
|
+
if (!booking.rooms) { console.log('[bookingEffects] no room joined; skip GHL'); return; }
|
|
231
|
+
|
|
232
|
+
const parsed = parseTstzRange(booking.during);
|
|
233
|
+
if (!parsed) { console.warn('[bookingEffects] could not parse booking.during'); return; }
|
|
234
|
+
const { startISO, endISO } = parsed;
|
|
235
|
+
|
|
236
|
+
const reminderTargetMs = new Date(startISO).getTime() - 24 * 60 * 60 * 1000;
|
|
237
|
+
const hoursUntilReminder = Math.max(1, Math.round((reminderTargetMs - Date.now()) / (60 * 60 * 1000)));
|
|
238
|
+
|
|
239
|
+
const name = (booking.contact_name || '').trim();
|
|
240
|
+
const parts = name.split(/\s+/);
|
|
241
|
+
const firstName = parts[0] || 'Guest';
|
|
242
|
+
const lastName = parts.slice(1).join(' ') || '';
|
|
243
|
+
const roomName = booking.rooms.name;
|
|
244
|
+
const whenStr = formatWhen(startISO, endISO);
|
|
245
|
+
const amountStr = formatDollars(booking.charged_amount_cents ?? booking.list_amount_cents);
|
|
246
|
+
|
|
247
|
+
const gcalTitle = `${roomName} — ${operator.name}`;
|
|
248
|
+
const gcalDetails = `Your booking at ${operator.name}.\nRoom: ${roomName}\nWhen: ${whenStr}\nBooking ID: ${booking.id}`;
|
|
249
|
+
const gcalLocation = booking.rooms?.address || operator.name;
|
|
250
|
+
const gcalUrl = googleCalendarUrl(startISO, endISO, gcalTitle, gcalDetails, gcalLocation);
|
|
251
|
+
|
|
252
|
+
const manageSecret = Deno.env.get('MANAGE_TOKEN_SECRET') ?? '';
|
|
253
|
+
let manageUrl = '';
|
|
254
|
+
if (manageSecret) {
|
|
255
|
+
try {
|
|
256
|
+
const exp = Math.floor(new Date(endISO).getTime() / 1000) + 30 * 24 * 60 * 60;
|
|
257
|
+
manageUrl = await buildManageUrl(
|
|
258
|
+
config.manageUrlBase,
|
|
259
|
+
{ bid: booking.id, eml: (booking.contact_email || '').toLowerCase(), exp },
|
|
260
|
+
manageSecret,
|
|
261
|
+
);
|
|
262
|
+
} catch (e) {
|
|
263
|
+
console.warn('[bookingEffects] manage url build failed', e);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const headers = ghlHeaders(apiKey);
|
|
268
|
+
|
|
269
|
+
let contactId: string | null = null;
|
|
270
|
+
try {
|
|
271
|
+
const upRes = await fetch(`${GHL_BASE}/contacts/upsert`, {
|
|
272
|
+
method: 'POST', headers,
|
|
273
|
+
body: JSON.stringify({
|
|
274
|
+
locationId, firstName, lastName,
|
|
275
|
+
email: booking.contact_email,
|
|
276
|
+
phone: booking.contact_phone || '',
|
|
277
|
+
source: `${operator.shortName} Website — Meeting Room`,
|
|
278
|
+
tags: ['Meeting Room Booking', operator.domain],
|
|
279
|
+
}),
|
|
280
|
+
});
|
|
281
|
+
if (!upRes.ok) {
|
|
282
|
+
console.warn('[bookingEffects] GHL upsert failed', upRes.status, await upRes.text());
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
const j = await upRes.json();
|
|
286
|
+
contactId = j.contact?.id || j.id || null;
|
|
287
|
+
if (!contactId) { console.warn('[bookingEffects] no contact id from upsert'); return; }
|
|
288
|
+
} catch (e) {
|
|
289
|
+
console.warn('[bookingEffects] GHL upsert error', e);
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
try {
|
|
294
|
+
await supabase.from('bookings').update({ ghl_contact_id: contactId }).eq('id', booking.id);
|
|
295
|
+
} catch (e) {
|
|
296
|
+
console.warn('[bookingEffects] save ghl_contact_id failed', e);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
try {
|
|
300
|
+
// Ordered explicitly, not via Object.values(cf), so the create-if-missing
|
|
301
|
+
// order in GHL is a property of this module and not of how a caller
|
|
302
|
+
// happened to spell its config object.
|
|
303
|
+
const cfMap = await ensureCustomFields(apiKey, locationId, [
|
|
304
|
+
cf.room, cf.when, cf.amount,
|
|
305
|
+
cf.address, cf.calendarLink, cf.manageLink,
|
|
306
|
+
cf.reminderWaitHours,
|
|
307
|
+
]);
|
|
308
|
+
const customFields: Array<{ id: string; value: string }> = [];
|
|
309
|
+
if (cfMap[cf.room]) customFields.push({ id: cfMap[cf.room], value: roomName });
|
|
310
|
+
if (cfMap[cf.when]) customFields.push({ id: cfMap[cf.when], value: whenStr });
|
|
311
|
+
if (cfMap[cf.amount]) customFields.push({ id: cfMap[cf.amount], value: amountStr });
|
|
312
|
+
if (cfMap[cf.address]) customFields.push({ id: cfMap[cf.address], value: booking.rooms.address || '' });
|
|
313
|
+
if (cfMap[cf.calendarLink]) customFields.push({ id: cfMap[cf.calendarLink], value: gcalUrl });
|
|
314
|
+
if (cfMap[cf.manageLink] && manageUrl) customFields.push({ id: cfMap[cf.manageLink], value: manageUrl });
|
|
315
|
+
if (cfMap[cf.reminderWaitHours]) customFields.push({ id: cfMap[cf.reminderWaitHours], value: String(hoursUntilReminder) });
|
|
316
|
+
if (customFields.length > 0) {
|
|
317
|
+
const putRes = await fetch(`${GHL_BASE}/contacts/${contactId}`, {
|
|
318
|
+
method: 'PUT', headers, body: JSON.stringify({ customFields }),
|
|
319
|
+
});
|
|
320
|
+
if (!putRes.ok) console.warn('[bookingEffects] contact customFields update failed', putRes.status, await putRes.text());
|
|
321
|
+
}
|
|
322
|
+
} catch (e) {
|
|
323
|
+
console.warn('[bookingEffects] custom fields step error', e);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
try {
|
|
327
|
+
const noteBody =
|
|
328
|
+
`Meeting Room Booking\n` +
|
|
329
|
+
`Room: ${roomName}\n` +
|
|
330
|
+
`When: ${whenStr}\n` +
|
|
331
|
+
`Amount: ${amountStr}\n` +
|
|
332
|
+
`Email: ${booking.contact_email}\n` +
|
|
333
|
+
`Phone: ${booking.contact_phone || '—'}\n` +
|
|
334
|
+
`Booking ID: ${booking.id}`;
|
|
335
|
+
const noteRes = await fetch(`${GHL_BASE}/contacts/${contactId}/notes`, {
|
|
336
|
+
method: 'POST', headers, body: JSON.stringify({ body: noteBody }),
|
|
337
|
+
});
|
|
338
|
+
if (!noteRes.ok) console.warn('[bookingEffects] note create failed', noteRes.status, await noteRes.text());
|
|
339
|
+
} catch (e) {
|
|
340
|
+
console.warn('[bookingEffects] note error', e);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// Confirmation email — sent directly (no GHL workflow exists for this).
|
|
344
|
+
try {
|
|
345
|
+
const address = booking.rooms.address || operator.name;
|
|
346
|
+
const manageParagraph = manageUrl
|
|
347
|
+
? `<p>Need to change plans? <a href='${manageUrl}' style='color:#C98A5E'>Manage your booking</a> — free cancellation with credit up to 48 hours before your start time.</p>`
|
|
348
|
+
: '';
|
|
349
|
+
let doorSection = '';
|
|
350
|
+
if (doorAccess?.pin) {
|
|
351
|
+
const activeLine = (doorAccess.validFromUtc && doorAccess.validToUtc)
|
|
352
|
+
? `<p style='margin:6px 0 0 0;color:#5f6c5d;font-size:13px'>Active ${formatWhen(doorAccess.validFromUtc, doorAccess.validToUtc)}</p>`
|
|
353
|
+
: '';
|
|
354
|
+
doorSection = `<div style='margin:20px 0;padding:16px;border:1px solid #E5E1D8;border-radius:8px'><h3 style='margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:16px'>Door access</h3><p style='margin:0 0 8px 0;font-family:ui-monospace,Menlo,Consolas,monospace;font-size:22px;letter-spacing:4px;color:#22263B'><strong>${doorAccess.pin}</strong></p><p style='margin:0;color:#22263B;font-size:14px'>Your PIN works at the Commons Hub door — the building's main entrance. The other entrances are badge and mobile-unlock only.</p>${activeLine}</div>`;
|
|
355
|
+
}
|
|
356
|
+
// Guest WiFi code — derived fresh (never stored), gated to the 4 hourly
|
|
357
|
+
// meeting rooms per RESERVATION-SCOPED-GUEST-WIFI-DESIGN.md. A cancelled
|
|
358
|
+
// booking needs no special handling here: ftw-middleware only ever
|
|
359
|
+
// validates against currently live/paid bookings, and this whole email
|
|
360
|
+
// only sends on the paid path anyway.
|
|
361
|
+
let wifiSection = '';
|
|
362
|
+
const wifiSecret = Deno.env.get('RESERVATION_WIFI_CODE_SECRET');
|
|
363
|
+
if (wifiSecret && isReservationWifiRoom(booking.rooms.slug)) {
|
|
364
|
+
const wifiCode = await deriveReservationWifiCode(wifiSecret, booking.id);
|
|
365
|
+
wifiSection = `<div style='margin:20px 0;padding:16px;border:1px solid #E5E1D8;border-radius:8px'><h3 style='margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:16px'>Guest WiFi</h3><p style='margin:0 0 8px 0;font-family:ui-monospace,Menlo,Consolas,monospace;font-size:22px;letter-spacing:4px;color:#22263B'><strong>${wifiCode}</strong></p><p style='margin:0;color:#22263B;font-size:14px'>Guest WiFi code for your visit — valid for your reservation window in ${roomName}.</p></div>`;
|
|
366
|
+
}
|
|
367
|
+
// "About this room" — the room's own usage_instructions, when set. Same
|
|
368
|
+
// bordered-card shape as the door/wifi sections above.
|
|
369
|
+
let instructionsSection = '';
|
|
370
|
+
const usageInstructions = booking.rooms.usage_instructions;
|
|
371
|
+
if (typeof usageInstructions === 'string' && usageInstructions.trim().length > 0) {
|
|
372
|
+
instructionsSection = `<div style='margin:20px 0;padding:16px;border:1px solid #E5E1D8;border-radius:8px'><h3 style='margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:16px'>About this room</h3>${textToHtmlParagraphs(usageInstructions)}</div>`;
|
|
373
|
+
}
|
|
374
|
+
const confirmationHtml = `<div style='font-family:Inter,Arial,sans-serif;max-width:560px;margin:0 auto;color:#22263B'><h2 style='color:#22263B'>Your booking is confirmed</h2><p>Hi ${firstName},</p><p>Thanks for booking with ${operator.name}. Here are your details:</p><table style='border-collapse:collapse;width:100%'><tr><td style='padding:6px 0;color:#5f6c5d;width:110px'>Room</td><td style='padding:6px 0'><strong>${roomName}</strong></td></tr><tr><td style='padding:6px 0;color:#5f6c5d'>When</td><td style='padding:6px 0'><strong>${whenStr}</strong></td></tr><tr><td style='padding:6px 0;color:#5f6c5d'>Amount</td><td style='padding:6px 0'><strong>${amountStr}</strong></td></tr><tr><td style='padding:6px 0;color:#5f6c5d'>Address</td><td style='padding:6px 0'>${address}</td></tr></table><p style='margin:20px 0'><a href='${gcalUrl}' style='background:#748272;color:#F6F6F6;padding:10px 18px;text-decoration:none;border-radius:6px;display:inline-block'>Add to Google Calendar</a></p>${doorSection}${wifiSection}${instructionsSection}${manageParagraph}<p style='color:#5f6c5d;font-size:13px;margin-top:28px'>${operator.name} · ${address}</p></div>`;
|
|
375
|
+
const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
|
|
376
|
+
method: 'POST', headers,
|
|
377
|
+
body: JSON.stringify({
|
|
378
|
+
type: 'Email',
|
|
379
|
+
contactId,
|
|
380
|
+
subject: `Your booking is confirmed — ${roomName}, ${whenStr.split(' · ')[0]}`,
|
|
381
|
+
html: confirmationHtml,
|
|
382
|
+
}),
|
|
383
|
+
});
|
|
384
|
+
if (!emailRes.ok) console.warn('[bookingEffects] confirmation email failed', emailRes.status, await emailRes.text());
|
|
385
|
+
} catch (e) {
|
|
386
|
+
console.warn('[bookingEffects] confirmation email error', e);
|
|
387
|
+
}
|
|
388
|
+
}
|