@simplelayer/graniteer-core 0.2.1 → 0.2.2

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 (124) hide show
  1. package/index.js +2 -2
  2. package/package.json +1 -1
  3. package/src/agreementCheckout.ts +250 -250
  4. package/src/agreementPortalEmail.ts +128 -128
  5. package/src/billingPortalLinkEmail.ts +117 -117
  6. package/src/bookingAgreementEmail.ts +149 -149
  7. package/src/bookingEffects.ts +388 -388
  8. package/src/busClient.ts +268 -268
  9. package/src/busSignature.ts +71 -71
  10. package/src/checkoutCoupon.test.ts +675 -675
  11. package/src/checkoutCoupon.ts +455 -455
  12. package/src/commonsDeposit.ts +298 -298
  13. package/src/commonsDepositWebhook.ts +237 -237
  14. package/src/dayPassConfirmation.ts +230 -230
  15. package/src/dunningEmails.test.ts +263 -263
  16. package/src/dunningEmails.ts +203 -203
  17. package/src/email-templates/brand.ts +93 -93
  18. package/src/email-templates/magic-link.tsx +59 -59
  19. package/src/email-templates/recovery.tsx +59 -59
  20. package/src/email-templates/signup.tsx +67 -67
  21. package/src/functions/admin-cancel-membership.ts +311 -311
  22. package/src/functions/admin-change-membership-plan.ts +312 -312
  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 -460
  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 -231
  30. package/src/functions/admin-mark-booking-paid.ts +203 -203
  31. package/src/functions/admin-mint-billing-portal-link.ts +168 -168
  32. package/src/functions/admin-mint-portal-link.ts +62 -62
  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 -366
  36. package/src/functions/admin-resend-commons-deposit-link.ts +323 -323
  37. package/src/functions/admin-reset-mfa.ts +138 -138
  38. package/src/functions/admin-retry-invoice-payment.ts +333 -333
  39. package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
  40. package/src/functions/admin-revoke-agreement.ts +467 -467
  41. package/src/functions/admin-send-commons-agreement.ts +214 -214
  42. package/src/functions/admin-set-credit-amount.ts +123 -123
  43. package/src/functions/admin-skip-commons-contract.ts +165 -165
  44. package/src/functions/admin-undo-membership-cancel.ts +144 -144
  45. package/src/functions/admin-wall-photo-write.ts +141 -141
  46. package/src/functions/auth-email-hook.ts +259 -259
  47. package/src/functions/boldsign-sender-identity.ts +114 -114
  48. package/src/functions/booking-availability.ts +419 -419
  49. package/src/functions/booking-member-preview.ts +136 -136
  50. package/src/functions/booking-status.ts +149 -149
  51. package/src/functions/create-booking.ts +648 -648
  52. package/src/functions/create-day-pass-checkout.ts +218 -218
  53. package/src/functions/create-portal-session.ts +142 -142
  54. package/src/functions/create-subscription-checkout.test.ts +222 -222
  55. package/src/functions/create-subscription-checkout.ts +440 -440
  56. package/src/functions/day-pass-status.ts +89 -89
  57. package/src/functions/diag-webpush-test.ts +45 -45
  58. package/src/functions/event-access-admin.ts +277 -277
  59. package/src/functions/event-access-store.ts +334 -334
  60. package/src/functions/ezeep-print-webhook.ts +213 -213
  61. package/src/functions/ezeep-usage-reconcile.ts +299 -299
  62. package/src/functions/fetch-avatar-original.ts +457 -457
  63. package/src/functions/get-provider-sign-link.ts +155 -155
  64. package/src/functions/get-signing-link.ts +211 -211
  65. package/src/functions/guest-print-setup-confirm.ts +128 -128
  66. package/src/functions/guest-print-submit.ts +149 -149
  67. package/src/functions/luma-webhook.ts +165 -165
  68. package/src/functions/mcp.ts +67 -67
  69. package/src/functions/member-door-action.test.ts +1248 -1248
  70. package/src/functions/member-door-action.ts +863 -863
  71. package/src/functions/member-unifi-mapping.test.ts +516 -516
  72. package/src/functions/member-unifi-mapping.ts +206 -206
  73. package/src/functions/membership-door-sync.ts +956 -956
  74. package/src/functions/migration-collision-alert.copy.ts +232 -232
  75. package/src/functions/migration-collision-alert.test.ts +349 -349
  76. package/src/functions/migration-collision-alert.ts +232 -232
  77. package/src/functions/office-assignment-end.ts +146 -146
  78. package/src/functions/portal-booking-access.ts +217 -217
  79. package/src/functions/portal-list-invoices.ts +99 -99
  80. package/src/functions/portal-request-login.ts +219 -192
  81. package/src/functions/portal-resend-invite.ts +248 -248
  82. package/src/functions/portal-submit-event.ts +168 -168
  83. package/src/functions/print-billing-recover.ts +97 -97
  84. package/src/functions/print-billing-run.ts +183 -183
  85. package/src/functions/public-facts.ts +168 -168
  86. package/src/functions/push-send.ts +348 -348
  87. package/src/functions/push-test.ts +234 -234
  88. package/src/functions/request-portal-link.ts +211 -211
  89. package/src/functions/review-ratings.ts +113 -113
  90. package/src/functions/space-availability-range.acceptance.test.ts +161 -161
  91. package/src/functions/space-availability-range.ts +142 -142
  92. package/src/functions/stripe-db-reconcile.ts +319 -319
  93. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -78
  94. package/src/functions/stripe-webhook.ts +2595 -2595
  95. package/src/functions/sync-gcal-blackouts.ts +298 -298
  96. package/src/functions/timetable-event-register.ts +162 -162
  97. package/src/functions/timetable-event-status.ts +90 -90
  98. package/src/functions/timetable-spaces.ts +219 -219
  99. package/src/functions/touch-pass-reconciler.ts +689 -689
  100. package/src/functions/touch-pass-signup.ts +478 -478
  101. package/src/functions/upload-booking-display-image.ts +179 -179
  102. package/src/functions/virtual-onboarding-purge.ts +134 -134
  103. package/src/functions/virtual-onboarding-submit.ts +315 -315
  104. package/src/functions/voice-booking.ts +453 -453
  105. package/src/functions/voice-day-pass.ts +346 -346
  106. package/src/functions/voice-inquiry.test.ts +301 -301
  107. package/src/functions/voice-inquiry.ts +198 -198
  108. package/src/functions/voice-membership-signup.ts +355 -355
  109. package/src/functions/voice-tour-availability.ts +204 -204
  110. package/src/functions/voice-tour-booking.ts +429 -429
  111. package/src/ghlEventInquiry.ts +143 -143
  112. package/src/mailArrivalEmail.ts +121 -121
  113. package/src/manageToken.ts +363 -363
  114. package/src/membershipBusClient.ts +537 -537
  115. package/src/membershipWelcome.ts +683 -683
  116. package/src/migrationCheckout.ts +366 -366
  117. package/src/paymentLinkEmail.ts +123 -123
  118. package/src/signedUnpaidReminderEmail.test.ts +246 -246
  119. package/src/signedUnpaidReminderEmail.ts +132 -132
  120. package/src/stripeCoworkingPortal.ts +91 -91
  121. package/src/supabaseTestFakes.ts +131 -131
  122. package/src/supportTicketEmail.ts +119 -119
  123. package/src/unifiAccessPolicies.ts +228 -228
  124. package/src/unifiGroups.ts +129 -129
@@ -1,211 +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
- }
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
+ }
@@ -1,113 +1,113 @@
1
- // Public, read-only review-ratings endpoint.
2
- //
3
- // Fetches the Google Places and Yelp Fusion ratings for the business and
4
- // returns a small JSON payload. Exists so granitecity.io — a prerendered
5
- // SPA where everything in the client bundle is public — never has to embed
6
- // a vendor API key or a hand-typed review number in src/. Vendor keys live
7
- // only in this function's environment (see env var names below).
8
- //
9
- // SCOPE: Google + Yelp only. No third platform is fetched here, by design.
10
- //
11
- // CACHING: in-memory, module-scope (the `cache` variable below), TTL_MS.
12
- // Ratings change slowly, so there is no need to hit either vendor API per
13
- // page view. This lives in the Deno isolate's global scope, so it persists
14
- // across invocations for the lifetime of one warm instance and resets on a
15
- // cold start or redeploy — a best-effort cache, not a durable one, which is
16
- // fine here because the worst case on a cold start is a handful of extra
17
- // vendor calls, never a per-page-view call. If a fresh fetch for one
18
- // platform fails, the last good cached value for that platform (even if
19
- // stale) is served instead of failing the whole response; only a platform
20
- // that has never successfully resolved returns null.
21
- import { corsHeaders } from 'npm:@supabase/supabase-js@2/cors';
22
-
23
- const TTL_MS = 6 * 60 * 60 * 1000; // 6 hours
24
-
25
- interface PlatformRating {
26
- rating: number;
27
- reviewCount: number;
28
- fetchedAt: string;
29
- }
30
-
31
- interface Payload {
32
- google: PlatformRating | null;
33
- yelp: PlatformRating | null;
34
- }
35
-
36
- let cache: { data: Payload; expiresAt: number } | null = null;
37
-
38
- const json = (status: number, body: unknown) =>
39
- new Response(JSON.stringify(body), {
40
- status,
41
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
42
- });
43
-
44
- // Env vars (set in the Supabase project's function environment — never in
45
- // this repo): GOOGLE_PLACES_API_KEY, GOOGLE_PLACE_ID.
46
- async function fetchGoogle(): Promise<PlatformRating | null> {
47
- const apiKey = Deno.env.get('GOOGLE_PLACES_API_KEY');
48
- const placeId = Deno.env.get('GOOGLE_PLACE_ID');
49
- if (!apiKey || !placeId) return null;
50
-
51
- try {
52
- const res = await fetch(`https://places.googleapis.com/v1/places/${placeId}`, {
53
- headers: {
54
- 'X-Goog-Api-Key': apiKey,
55
- 'X-Goog-FieldMask': 'rating,userRatingCount',
56
- },
57
- });
58
- if (!res.ok) {
59
- console.error('[review-ratings] google http error', res.status);
60
- return null;
61
- }
62
- const data = await res.json();
63
- if (typeof data.rating !== 'number' || typeof data.userRatingCount !== 'number') return null;
64
- return { rating: data.rating, reviewCount: data.userRatingCount, fetchedAt: new Date().toISOString() };
65
- } catch (e) {
66
- console.error('[review-ratings] google fetch failed', e);
67
- return null;
68
- }
69
- }
70
-
71
- // Env vars (set in the Supabase project's function environment — never in
72
- // this repo): YELP_API_KEY, YELP_BUSINESS_ID.
73
- async function fetchYelp(): Promise<PlatformRating | null> {
74
- const apiKey = Deno.env.get('YELP_API_KEY');
75
- const businessId = Deno.env.get('YELP_BUSINESS_ID');
76
- if (!apiKey || !businessId) return null;
77
-
78
- try {
79
- const res = await fetch(`https://api.yelp.com/v3/businesses/${businessId}`, {
80
- headers: { Authorization: `Bearer ${apiKey}` },
81
- });
82
- if (!res.ok) {
83
- console.error('[review-ratings] yelp http error', res.status);
84
- return null;
85
- }
86
- const data = await res.json();
87
- if (typeof data.rating !== 'number' || typeof data.review_count !== 'number') return null;
88
- return { rating: data.rating, reviewCount: data.review_count, fetchedAt: new Date().toISOString() };
89
- } catch (e) {
90
- console.error('[review-ratings] yelp fetch failed', e);
91
- return null;
92
- }
93
- }
94
-
95
- export async function handle(req: Request): Promise<Response> {
96
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
97
-
98
- const now = Date.now();
99
- if (cache && cache.expiresAt > now) {
100
- return json(200, cache.data);
101
- }
102
-
103
- const [google, yelp] = await Promise.all([fetchGoogle(), fetchYelp()]);
104
-
105
- const data: Payload = {
106
- google: google ?? cache?.data.google ?? null,
107
- yelp: yelp ?? cache?.data.yelp ?? null,
108
- };
109
-
110
- cache = { data, expiresAt: now + TTL_MS };
111
-
112
- return json(200, data);
113
- }
1
+ // Public, read-only review-ratings endpoint.
2
+ //
3
+ // Fetches the Google Places and Yelp Fusion ratings for the business and
4
+ // returns a small JSON payload. Exists so granitecity.io — a prerendered
5
+ // SPA where everything in the client bundle is public — never has to embed
6
+ // a vendor API key or a hand-typed review number in src/. Vendor keys live
7
+ // only in this function's environment (see env var names below).
8
+ //
9
+ // SCOPE: Google + Yelp only. No third platform is fetched here, by design.
10
+ //
11
+ // CACHING: in-memory, module-scope (the `cache` variable below), TTL_MS.
12
+ // Ratings change slowly, so there is no need to hit either vendor API per
13
+ // page view. This lives in the Deno isolate's global scope, so it persists
14
+ // across invocations for the lifetime of one warm instance and resets on a
15
+ // cold start or redeploy — a best-effort cache, not a durable one, which is
16
+ // fine here because the worst case on a cold start is a handful of extra
17
+ // vendor calls, never a per-page-view call. If a fresh fetch for one
18
+ // platform fails, the last good cached value for that platform (even if
19
+ // stale) is served instead of failing the whole response; only a platform
20
+ // that has never successfully resolved returns null.
21
+ import { corsHeaders } from 'npm:@supabase/supabase-js@2/cors';
22
+
23
+ const TTL_MS = 6 * 60 * 60 * 1000; // 6 hours
24
+
25
+ interface PlatformRating {
26
+ rating: number;
27
+ reviewCount: number;
28
+ fetchedAt: string;
29
+ }
30
+
31
+ interface Payload {
32
+ google: PlatformRating | null;
33
+ yelp: PlatformRating | null;
34
+ }
35
+
36
+ let cache: { data: Payload; expiresAt: number } | null = null;
37
+
38
+ const json = (status: number, body: unknown) =>
39
+ new Response(JSON.stringify(body), {
40
+ status,
41
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
42
+ });
43
+
44
+ // Env vars (set in the Supabase project's function environment — never in
45
+ // this repo): GOOGLE_PLACES_API_KEY, GOOGLE_PLACE_ID.
46
+ async function fetchGoogle(): Promise<PlatformRating | null> {
47
+ const apiKey = Deno.env.get('GOOGLE_PLACES_API_KEY');
48
+ const placeId = Deno.env.get('GOOGLE_PLACE_ID');
49
+ if (!apiKey || !placeId) return null;
50
+
51
+ try {
52
+ const res = await fetch(`https://places.googleapis.com/v1/places/${placeId}`, {
53
+ headers: {
54
+ 'X-Goog-Api-Key': apiKey,
55
+ 'X-Goog-FieldMask': 'rating,userRatingCount',
56
+ },
57
+ });
58
+ if (!res.ok) {
59
+ console.error('[review-ratings] google http error', res.status);
60
+ return null;
61
+ }
62
+ const data = await res.json();
63
+ if (typeof data.rating !== 'number' || typeof data.userRatingCount !== 'number') return null;
64
+ return { rating: data.rating, reviewCount: data.userRatingCount, fetchedAt: new Date().toISOString() };
65
+ } catch (e) {
66
+ console.error('[review-ratings] google fetch failed', e);
67
+ return null;
68
+ }
69
+ }
70
+
71
+ // Env vars (set in the Supabase project's function environment — never in
72
+ // this repo): YELP_API_KEY, YELP_BUSINESS_ID.
73
+ async function fetchYelp(): Promise<PlatformRating | null> {
74
+ const apiKey = Deno.env.get('YELP_API_KEY');
75
+ const businessId = Deno.env.get('YELP_BUSINESS_ID');
76
+ if (!apiKey || !businessId) return null;
77
+
78
+ try {
79
+ const res = await fetch(`https://api.yelp.com/v3/businesses/${businessId}`, {
80
+ headers: { Authorization: `Bearer ${apiKey}` },
81
+ });
82
+ if (!res.ok) {
83
+ console.error('[review-ratings] yelp http error', res.status);
84
+ return null;
85
+ }
86
+ const data = await res.json();
87
+ if (typeof data.rating !== 'number' || typeof data.review_count !== 'number') return null;
88
+ return { rating: data.rating, reviewCount: data.review_count, fetchedAt: new Date().toISOString() };
89
+ } catch (e) {
90
+ console.error('[review-ratings] yelp fetch failed', e);
91
+ return null;
92
+ }
93
+ }
94
+
95
+ export async function handle(req: Request): Promise<Response> {
96
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
97
+
98
+ const now = Date.now();
99
+ if (cache && cache.expiresAt > now) {
100
+ return json(200, cache.data);
101
+ }
102
+
103
+ const [google, yelp] = await Promise.all([fetchGoogle(), fetchYelp()]);
104
+
105
+ const data: Payload = {
106
+ google: google ?? cache?.data.google ?? null,
107
+ yelp: yelp ?? cache?.data.yelp ?? null,
108
+ };
109
+
110
+ cache = { data, expiresAt: now + TTL_MS };
111
+
112
+ return json(200, data);
113
+ }