@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.
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 +334 -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 +217 -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,211 @@
1
+ import { createClient, type SupabaseClient } from 'npm:@supabase/supabase-js@2';
2
+ import { z } from 'npm:zod@3.23.8';
3
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
4
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
5
+ import { buildMemberManageUrl } from 'npm:@simplelayer/graniteer-core/manageToken';
6
+
7
+ const corsHeaders = {
8
+ 'Access-Control-Allow-Origin': '*',
9
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
10
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
11
+ };
12
+
13
+ const GHL_BASE = 'https://services.leadconnectorhq.com';
14
+ const TAG = 'Membership Portal Requested';
15
+ const GENERIC_OK = {
16
+ ok: true,
17
+ message: "If that email has an active membership, we've sent a manage link to it.",
18
+ };
19
+
20
+ const Body = z.object({ email: z.string().email().max(255) });
21
+
22
+ function json(status: number, body: unknown) {
23
+ return new Response(JSON.stringify(body), {
24
+ status,
25
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
26
+ });
27
+ }
28
+
29
+ function ghlHeaders(apiKey: string) {
30
+ return {
31
+ Authorization: `Bearer ${apiKey}`,
32
+ Version: '2021-07-28',
33
+ 'Content-Type': 'application/json',
34
+ Accept: 'application/json',
35
+ };
36
+ }
37
+
38
+ type Operator = { operatorName: string; operatorShortName: string; domain: string };
39
+
40
+ function portalEmailHtml(manageUrl: string, operator: Operator): string {
41
+ return [
42
+ '<p>Hi there,</p>',
43
+ `<p>Here's your secure link to manage your ${operator.operatorName} membership — update your card, view invoices, or make changes anytime:</p>`,
44
+ `<p><a href="${manageUrl}">Manage my membership →</a></p>`,
45
+ "<p>This secure link is unique to you and expires in 30 days — please don't forward it.</p>",
46
+ `<p>Questions? Just reply to this email.<br>— ${operator.operatorName}</p>`,
47
+ ].join('');
48
+ }
49
+
50
+ async function deliverPortalLink(
51
+ admin: SupabaseClient<any, 'public', any>,
52
+ email: string,
53
+ secret: string,
54
+ operator: Operator,
55
+ ): Promise<void> {
56
+ const apiKey = Deno.env.get('GHL_API_KEY');
57
+ const locationId = Deno.env.get('GHL_LOCATION_ID');
58
+ if (!apiKey || !locationId) {
59
+ console.warn('[request-portal-link] GHL not configured — cannot deliver link');
60
+ return;
61
+ }
62
+ const headers = ghlHeaders(apiKey);
63
+
64
+ const manageUrl = await buildMemberManageUrl(
65
+ `https://${operator.domain}`,
66
+ { mbr: email, exp: Math.floor(Date.now() / 1000) + 30 * 24 * 60 * 60 },
67
+ secret,
68
+ );
69
+
70
+ let contactId: string | null = null;
71
+ try {
72
+ const upRes = await fetch(`${GHL_BASE}/contacts/upsert`, {
73
+ method: 'POST',
74
+ headers,
75
+ body: JSON.stringify({
76
+ locationId,
77
+ email,
78
+ source: `${operator.operatorShortName} Website — Membership Portal`,
79
+ tags: [TAG, operator.domain],
80
+ }),
81
+ });
82
+ if (!upRes.ok) {
83
+ console.warn('[request-portal-link] GHL upsert failed', upRes.status, await upRes.text());
84
+ return;
85
+ }
86
+ const j = await upRes.json();
87
+ contactId = j.contact?.id || j.contact?.contact?.id || j.id || null;
88
+ } catch (e) {
89
+ console.warn('[request-portal-link] GHL upsert error', e);
90
+ return;
91
+ }
92
+ if (!contactId) return;
93
+
94
+ // Send the portal email directly via GHL Conversations API.
95
+ try {
96
+ const sendRes = await fetch(`${GHL_BASE}/conversations/messages`, {
97
+ method: 'POST',
98
+ headers,
99
+ body: JSON.stringify({
100
+ type: 'Email',
101
+ contactId,
102
+ emailTo: email,
103
+ subject: `Manage your ${operator.operatorName} membership`,
104
+ html: portalEmailHtml(manageUrl, operator),
105
+ }),
106
+ });
107
+ if (!sendRes.ok) {
108
+ const txt = await sendRes.text();
109
+ console.warn('[request-portal-link] GHL email send failed', sendRes.status, txt);
110
+ await logOps(
111
+ admin,
112
+ 'portal_email_send_failed',
113
+ { email, status: sendRes.status, body: txt.slice(0, 500) },
114
+ { severity: 'warning' },
115
+ );
116
+ } else {
117
+ await logOps(admin, 'portal_email_sent', { email }, { severity: 'info' });
118
+ }
119
+ } catch (e) {
120
+ console.warn('[request-portal-link] GHL email send error', e);
121
+ await logOps(
122
+ admin,
123
+ 'portal_email_send_failed',
124
+ { email, message: e instanceof Error ? e.message : String(e) },
125
+ { severity: 'warning' },
126
+ );
127
+ }
128
+
129
+ // Best-effort tag apply (harmless CRM marker; delivery no longer depends on it).
130
+ try {
131
+ await fetch(`${GHL_BASE}/contacts/${contactId}/tags`, {
132
+ method: 'POST',
133
+ headers,
134
+ body: JSON.stringify({ tags: [TAG] }),
135
+ });
136
+ } catch (e) {
137
+ console.warn('[request-portal-link] tag add error', e);
138
+ }
139
+ }
140
+
141
+ export async function handle(req: Request, operator: Operator): Promise<Response> {
142
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
143
+ if (req.method !== 'POST') return json(405, { error: 'method_not_allowed' });
144
+
145
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
146
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
147
+ const secret = Deno.env.get('MANAGE_TOKEN_SECRET');
148
+ // Missing secret should never happen in prod; fail closed to generic OK so
149
+ // callers can't distinguish this from "no membership found".
150
+ if (!secret) {
151
+ console.warn('[request-portal-link] MANAGE_TOKEN_SECRET not configured');
152
+ }
153
+
154
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
155
+ auth: { persistSession: false, autoRefreshToken: false },
156
+ });
157
+
158
+ // Parse first so we can rate-limit by email; but rate-limit BEFORE any DB row lookup.
159
+ let email = '';
160
+ try {
161
+ const raw = await req.json();
162
+ const parsed = Body.safeParse(raw);
163
+ if (!parsed.success) return json(200, GENERIC_OK); // don't leak validation state
164
+ email = parsed.data.email.toLowerCase();
165
+ } catch {
166
+ return json(200, GENERIC_OK);
167
+ }
168
+
169
+ const ip = clientIp(req);
170
+ const [ipOk, emailOk] = await Promise.all([
171
+ checkRateLimit(admin, 'portal-link-ip', ip, 20, 300),
172
+ checkRateLimit(admin, 'portal-link-email', email, 10, 300),
173
+ ]);
174
+ if (!ipOk || !emailOk) return json(429, { error: 'rate_limited' });
175
+
176
+ // PLURALITY: never .maybeSingle() here -- supabase-js returns data:null when
177
+ // >1 row matches, which would silently deny a portal link to exactly the
178
+ // member holding two memberships. Oldest-first + limit(1), matching
179
+ // _shared/membership.ts's "THE OLDEST ENTITLED MEMBERSHIP PAYS" intent.
180
+ const { data: membershipRows, error: membershipErr } = await admin
181
+ .from('memberships')
182
+ .select('id,email,status,stripe_customer_id')
183
+ .eq('email', email)
184
+ .in('status', ['active', 'trialing', 'past_due'])
185
+ .not('stripe_customer_id', 'is', null)
186
+ .order('created_at', { ascending: true })
187
+ .limit(1);
188
+ if (membershipErr) {
189
+ await logOps(admin, 'portal_link_membership_lookup_failed',
190
+ { email, message: membershipErr.message }, { severity: 'error' });
191
+ // Same shape/timing as every other outcome (no existence leak).
192
+ return json(200, GENERIC_OK);
193
+ }
194
+ const membership = (membershipRows ?? [])[0];
195
+
196
+ if (!membership || !secret) {
197
+ // Same shape/timing as the found path (no existence leak).
198
+ return json(200, GENERIC_OK);
199
+ }
200
+
201
+ try {
202
+ await deliverPortalLink(admin, email, secret, operator);
203
+ await logOps(admin, 'portal_link_requested', { email }, { severity: 'info' });
204
+ } catch (e) {
205
+ await logOps(admin, 'portal_link_delivery_failed',
206
+ { message: e instanceof Error ? e.message : String(e), email },
207
+ { severity: 'error' });
208
+ }
209
+
210
+ return json(200, GENERIC_OK);
211
+ }