@simplelayer/graniteer-core 0.0.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +169 -15
- package/src/adminBookingCredit.test.ts +451 -0
- package/src/adminBookingCredit.ts +239 -0
- package/src/agreementCheckout.ts +250 -0
- package/src/agreementPortalEmail.ts +128 -0
- package/src/availability.test.ts +25 -0
- package/src/availability.ts +201 -0
- package/src/billingPortalLinkEmail.ts +117 -0
- package/src/bookingAgreementEmail.ts +149 -0
- package/src/bookingEffects.ts +388 -0
- package/src/bookingHoldReclaim.ts +94 -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/checkoutSessionParams.ts +56 -0
- package/src/commonsContract.ts +175 -0
- package/src/commonsDeposit.ts +298 -0
- package/src/commonsDepositWebhook.ts +237 -0
- package/src/conductorAdmin.ts +141 -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/email-change.tsx +92 -0
- package/src/email-templates/invite.tsx +79 -0
- package/src/email-templates/magic-link.tsx +59 -0
- package/src/email-templates/reauthentication.tsx +60 -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 -0
- package/src/functions/admin-change-membership-plan.ts +312 -0
- package/src/functions/admin-charge-guest-print.ts +229 -0
- package/src/functions/admin-correct-booking.ts +333 -0
- package/src/functions/admin-create-booking.ts +460 -0
- package/src/functions/admin-create-commons-event.ts +244 -0
- package/src/functions/admin-debug-boldsign-doc.ts +93 -0
- package/src/functions/admin-door-write.ts +272 -0
- package/src/functions/admin-issue-day-pass.ts +231 -0
- package/src/functions/admin-mark-booking-paid.ts +203 -0
- 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 -0
- package/src/functions/admin-remove-team-member.ts +150 -0
- 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 -0
- 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 -0
- package/src/functions/admin-revoke-agreement.ts +467 -0
- package/src/functions/admin-send-commons-agreement.ts +214 -0
- package/src/functions/admin-set-credit-amount.ts +123 -0
- package/src/functions/admin-skip-commons-contract.ts +165 -0
- package/src/functions/admin-undo-membership-cancel.ts +144 -0
- package/src/functions/admin-wall-photo-write.ts +141 -0
- package/src/functions/auth-email-hook.ts +259 -0
- package/src/functions/boldsign-sender-identity.ts +114 -0
- package/src/functions/booking-availability.ts +419 -0
- package/src/functions/booking-member-preview.ts +136 -0
- 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 -0
- package/src/functions/dayStatus.ts +71 -0
- package/src/functions/diag-webpush-test.ts +45 -0
- package/src/functions/event-access-admin.ts +277 -0
- package/src/functions/event-access-store.ts +309 -0
- package/src/functions/ezeep-print-webhook.ts +213 -0
- package/src/functions/ezeep-usage-reconcile.ts +299 -0
- 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 -0
- package/src/functions/guest-print-setup-confirm.ts +128 -0
- package/src/functions/guest-print-submit.ts +149 -0
- package/src/functions/luma-webhook.ts +165 -0
- 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 -0
- package/src/functions/migration-collision-alert.test.ts +349 -0
- package/src/functions/migration-collision-alert.ts +232 -0
- package/src/functions/office-assignment-end.ts +146 -0
- package/src/functions/portal-booking-access.ts +95 -0
- package/src/functions/portal-list-invoices.ts +99 -0
- 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 -0
- package/src/functions/print-billing-run.ts +183 -0
- package/src/functions/public-facts.ts +168 -0
- 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 -0
- package/src/functions/space-availability-range.ts +142 -0
- 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 -0
- package/src/functions/timetable-event-register.ts +162 -0
- package/src/functions/timetable-event-status.ts +90 -0
- package/src/functions/timetable-spaces.ts +219 -0
- package/src/functions/touch-pass-reconciler.ts +689 -0
- 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 -0
- package/src/functions/virtual-onboarding-submit.ts +315 -0
- 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 -0
- package/src/functions/voice-inquiry.ts +198 -0
- package/src/functions/voice-membership-signup.ts +355 -0
- package/src/functions/voice-tour-availability.ts +204 -0
- package/src/functions/voice-tour-booking.ts +429 -0
- package/src/gcalSync.ts +142 -0
- package/src/ghlEventInquiry.ts +143 -0
- package/src/ghlNote.ts +34 -0
- package/src/ghlTask.ts +48 -0
- package/src/ghlVoiceInquiry.ts +90 -0
- package/src/guestPrintCapture.test.ts +722 -0
- package/src/guestPrintCapture.ts +538 -0
- package/src/lumaGhl.ts +195 -0
- package/src/mailArrivalEmail.ts +121 -0
- package/src/manageToken.ts +363 -0
- package/src/membership.ts +109 -0
- package/src/membershipBusClient.ts +537 -0
- package/src/membershipWelcome.ts +683 -0
- package/src/migrationCheckout.ts +366 -0
- package/src/money.ts +36 -0
- package/src/ops.ts +97 -0
- package/src/pacificDate.ts +88 -0
- package/src/paymentLinkEmail.ts +123 -0
- package/src/policyAcknowledgment.test.ts +50 -0
- package/src/policyAcknowledgment.ts +96 -0
- package/src/portalSession.ts +46 -0
- package/src/pricing.test.ts +660 -0
- package/src/pricing.ts +1025 -0
- package/src/printBilling.test.ts +750 -0
- package/src/printBilling.ts +891 -0
- package/src/printBillingAdapters.ts +169 -0
- package/src/printCorrections.test.ts +348 -0
- package/src/printCorrections.ts +496 -0
- package/src/rateLimit.ts +82 -0
- package/src/referralCredits.test.ts +31 -0
- package/src/referralCredits.ts +34 -0
- package/src/referralGrant.ts +321 -0
- package/src/rescheduleCredit.test.ts +521 -0
- package/src/rescheduleCredit.ts +337 -0
- package/src/reservationWifiCode.test.ts +69 -0
- package/src/reservationWifiCode.ts +81 -0
- package/src/retellCallAnalyzed.test.ts +167 -0
- package/src/retellCallAnalyzed.ts +113 -0
- package/src/retellSignature.test.ts +137 -0
- package/src/retellSignature.ts +82 -0
- package/src/signedUnpaidReminderEmail.test.ts +246 -0
- package/src/signedUnpaidReminderEmail.ts +132 -0
- package/src/slackAlert.ts +38 -0
- package/src/stripeCoworkingPortal.ts +91 -0
- package/src/supabaseTestFakes.ts +131 -0
- package/src/supportTicketEmail.ts +119 -0
- package/src/tier1Agreement.ts +125 -0
- package/src/unifiAccessPolicies.ts +228 -0
- package/src/unifiGroups.ts +129 -0
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import { corsHeaders } from 'npm:@supabase/supabase-js@2/cors';
|
|
2
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
3
|
+
import { JWT } from 'npm:google-auth-library@9';
|
|
4
|
+
import {
|
|
5
|
+
eventToRange,
|
|
6
|
+
shouldSkipEvent,
|
|
7
|
+
type GcalEvent,
|
|
8
|
+
} from 'npm:@simplelayer/graniteer-core/gcalSync';
|
|
9
|
+
import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
|
|
10
|
+
|
|
11
|
+
// 90-day sync window
|
|
12
|
+
const WINDOW_DAYS = 90;
|
|
13
|
+
|
|
14
|
+
function timingSafeEq(a: string, b: string): boolean {
|
|
15
|
+
if (a.length !== b.length) return false;
|
|
16
|
+
let diff = 0;
|
|
17
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
18
|
+
return diff === 0;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function getGoogleAccessToken(): Promise<string | null> {
|
|
22
|
+
const clientEmail = Deno.env.get('GOOGLE_SA_CLIENT_EMAIL');
|
|
23
|
+
const rawKey = Deno.env.get('GOOGLE_SA_PRIVATE_KEY');
|
|
24
|
+
if (!clientEmail || !rawKey) return null;
|
|
25
|
+
const jwt = new JWT({
|
|
26
|
+
email: clientEmail,
|
|
27
|
+
key: rawKey.replace(/\\n/g, '\n'),
|
|
28
|
+
scopes: ['https://www.googleapis.com/auth/calendar.readonly'],
|
|
29
|
+
});
|
|
30
|
+
const tok = await jwt.getAccessToken();
|
|
31
|
+
return tok?.token ?? null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function fetchAllEvents(
|
|
35
|
+
accessToken: string,
|
|
36
|
+
calendarId: string,
|
|
37
|
+
timeMinIso: string,
|
|
38
|
+
timeMaxIso: string,
|
|
39
|
+
): Promise<GcalEvent[]> {
|
|
40
|
+
const out: GcalEvent[] = [];
|
|
41
|
+
let pageToken: string | undefined;
|
|
42
|
+
const fields =
|
|
43
|
+
'nextPageToken,items(id,status,summary,transparency,start,end,extendedProperties)';
|
|
44
|
+
// Cap pagination defensively
|
|
45
|
+
const MAX_PAGES = 20;
|
|
46
|
+
let page = 0;
|
|
47
|
+
for (; page < MAX_PAGES; page++) {
|
|
48
|
+
const u = new URL(
|
|
49
|
+
`https://www.googleapis.com/calendar/v3/calendars/${encodeURIComponent(calendarId)}/events`,
|
|
50
|
+
);
|
|
51
|
+
u.searchParams.set('singleEvents', 'true');
|
|
52
|
+
u.searchParams.set('timeMin', timeMinIso);
|
|
53
|
+
u.searchParams.set('timeMax', timeMaxIso);
|
|
54
|
+
u.searchParams.set('maxResults', '2500');
|
|
55
|
+
u.searchParams.set('fields', fields);
|
|
56
|
+
if (pageToken) u.searchParams.set('pageToken', pageToken);
|
|
57
|
+
const res = await fetch(u.toString(), {
|
|
58
|
+
headers: { Authorization: `Bearer ${accessToken}` },
|
|
59
|
+
signal: AbortSignal.timeout(15000),
|
|
60
|
+
});
|
|
61
|
+
if (!res.ok) {
|
|
62
|
+
const body = await res.text().catch(() => '');
|
|
63
|
+
throw new Error(`events.list ${res.status}: ${body.slice(0, 300)}`);
|
|
64
|
+
}
|
|
65
|
+
const data = await res.json();
|
|
66
|
+
for (const it of data.items ?? []) out.push(it as GcalEvent);
|
|
67
|
+
pageToken = data.nextPageToken;
|
|
68
|
+
if (!pageToken) break;
|
|
69
|
+
}
|
|
70
|
+
// If we exhausted the cap while a pageToken is still set, the result is
|
|
71
|
+
// under-populated and must be treated as a fetch failure — otherwise the
|
|
72
|
+
// caller's delete phase would drop still-valid google blackouts.
|
|
73
|
+
if (pageToken) {
|
|
74
|
+
throw new Error(`events.list truncated after ${MAX_PAGES} pages (pageToken still present)`);
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export async function handle(req: Request): Promise<Response> {
|
|
80
|
+
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
81
|
+
if (req.method !== 'POST' && req.method !== 'GET') {
|
|
82
|
+
return new Response(JSON.stringify({ error: 'method_not_allowed' }), {
|
|
83
|
+
status: 405,
|
|
84
|
+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const expected = Deno.env.get('SYNC_JOB_SECRET');
|
|
89
|
+
const provided = req.headers.get('x-sync-secret') ?? '';
|
|
90
|
+
if (!expected || !timingSafeEq(expected, provided)) {
|
|
91
|
+
return new Response(JSON.stringify({ error: 'forbidden' }), {
|
|
92
|
+
status: 403,
|
|
93
|
+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const supabase = createClient(
|
|
98
|
+
Deno.env.get('SUPABASE_URL')!,
|
|
99
|
+
Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
|
|
100
|
+
);
|
|
101
|
+
|
|
102
|
+
// Bootstrap: mirror our SYNC_JOB_SECRET into private.sync_secrets so pg_cron
|
|
103
|
+
// can read it. Idempotent upsert.
|
|
104
|
+
try {
|
|
105
|
+
await supabase.rpc('set_sync_secret', {
|
|
106
|
+
p_name: 'SYNC_JOB_SECRET',
|
|
107
|
+
p_value: expected,
|
|
108
|
+
});
|
|
109
|
+
} catch { /* ignore */ }
|
|
110
|
+
|
|
111
|
+
// Overlap lock: 4-minute window (cron every 5 minutes).
|
|
112
|
+
const { data: locked, error: lockErr } = await supabase
|
|
113
|
+
.from('sync_state')
|
|
114
|
+
.update({ locked_until: new Date(Date.now() + 4 * 60 * 1000).toISOString() })
|
|
115
|
+
.eq('key', 'gcal-blackouts')
|
|
116
|
+
.lt('locked_until', new Date().toISOString())
|
|
117
|
+
.select('key')
|
|
118
|
+
.maybeSingle();
|
|
119
|
+
if (lockErr) {
|
|
120
|
+
await logOps(supabase, 'gcal_sync_failed', { message: `lock: ${lockErr.message}` }, { severity: 'error' });
|
|
121
|
+
return new Response(JSON.stringify({ error: 'lock_failed' }), {
|
|
122
|
+
status: 500,
|
|
123
|
+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
if (!locked) {
|
|
127
|
+
return new Response(JSON.stringify({ skipped: 'locked' }), {
|
|
128
|
+
status: 200,
|
|
129
|
+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const now = new Date();
|
|
134
|
+
const timeMin = now.toISOString();
|
|
135
|
+
const timeMax = new Date(now.getTime() + WINDOW_DAYS * 86400000).toISOString();
|
|
136
|
+
|
|
137
|
+
const [{ data: rooms, error: rErr }, { data: bookings, error: bErr }] = await Promise.all([
|
|
138
|
+
supabase
|
|
139
|
+
.from('rooms')
|
|
140
|
+
.select('id,name,google_calendar_id')
|
|
141
|
+
.eq('active', true)
|
|
142
|
+
.not('google_calendar_id', 'is', null),
|
|
143
|
+
supabase
|
|
144
|
+
.from('bookings')
|
|
145
|
+
.select('google_event_id')
|
|
146
|
+
.not('google_event_id', 'is', null),
|
|
147
|
+
]);
|
|
148
|
+
if (rErr || bErr) {
|
|
149
|
+
const msg = rErr?.message || bErr?.message || 'load failed';
|
|
150
|
+
await logOps(supabase, 'gcal_sync_failed', { message: msg }, { severity: 'error' });
|
|
151
|
+
return new Response(JSON.stringify({ error: msg }), {
|
|
152
|
+
status: 500,
|
|
153
|
+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const selfIds = new Set<string>();
|
|
158
|
+
for (const b of bookings ?? []) if (b.google_event_id) selfIds.add(b.google_event_id);
|
|
159
|
+
|
|
160
|
+
let accessToken: string | null = null;
|
|
161
|
+
try {
|
|
162
|
+
accessToken = await getGoogleAccessToken();
|
|
163
|
+
} catch (e) {
|
|
164
|
+
await logOps(supabase, 'gcal_sync_failed', { message: `google auth: ${e instanceof Error ? e.message : String(e)}` }, { severity: 'error' });
|
|
165
|
+
}
|
|
166
|
+
if (!accessToken) {
|
|
167
|
+
return new Response(JSON.stringify({ error: 'no_google_auth' }), {
|
|
168
|
+
status: 500,
|
|
169
|
+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const summary: Record<string, { upserted: number; deleted: number; skipped_self: number; failed?: string }> = {};
|
|
174
|
+
|
|
175
|
+
for (const room of rooms ?? []) {
|
|
176
|
+
const gcalId = room.google_calendar_id as string;
|
|
177
|
+
const key = String(room.id);
|
|
178
|
+
let events: GcalEvent[] = [];
|
|
179
|
+
try {
|
|
180
|
+
events = await fetchAllEvents(accessToken, gcalId, timeMin, timeMax);
|
|
181
|
+
} catch (e) {
|
|
182
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
183
|
+
summary[key] = { upserted: 0, deleted: 0, skipped_self: 0, failed: message };
|
|
184
|
+
await logOps(
|
|
185
|
+
supabase,
|
|
186
|
+
'gcal_sync_failed',
|
|
187
|
+
{ room_id: key, room_name: room.name, message },
|
|
188
|
+
{ severity: 'error' },
|
|
189
|
+
);
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
let skippedSelf = 0;
|
|
194
|
+
let upserted = 0;
|
|
195
|
+
const fetchedIds: string[] = [];
|
|
196
|
+
// Track ids that we actually keep — used for the delete step.
|
|
197
|
+
const keepIds = new Set<string>();
|
|
198
|
+
|
|
199
|
+
for (const ev of events) {
|
|
200
|
+
if (shouldSkipEvent(ev, selfIds)) {
|
|
201
|
+
if (ev.id && (selfIds.has(ev.id) || ev.extendedProperties?.private?.gc_source === 'gc-connect')) {
|
|
202
|
+
skippedSelf++;
|
|
203
|
+
}
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
const range = eventToRange(ev);
|
|
207
|
+
if (!range) continue;
|
|
208
|
+
fetchedIds.push(ev.id);
|
|
209
|
+
keepIds.add(ev.id);
|
|
210
|
+
const rangeLit = `[${range.startIso},${range.endIso})`;
|
|
211
|
+
const reason = `GCal: ${ev.summary || 'busy'}`.slice(0, 500);
|
|
212
|
+
|
|
213
|
+
const { data: upserted_row, error: upErr } = await supabase
|
|
214
|
+
.from('blackouts')
|
|
215
|
+
.upsert(
|
|
216
|
+
{ room_id: key, during: rangeLit, reason, source: 'google', google_event_id: ev.id },
|
|
217
|
+
{ onConflict: 'room_id,google_event_id' },
|
|
218
|
+
)
|
|
219
|
+
.select('id')
|
|
220
|
+
.maybeSingle();
|
|
221
|
+
if (upErr) {
|
|
222
|
+
await logOps(
|
|
223
|
+
supabase,
|
|
224
|
+
'gcal_sync_failed',
|
|
225
|
+
{ room_id: key, event_id: ev.id, message: `upsert: ${upErr.message}` },
|
|
226
|
+
{ severity: 'error' },
|
|
227
|
+
);
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
upserted++;
|
|
231
|
+
|
|
232
|
+
// Overlap warning against active bookings
|
|
233
|
+
const { data: overlaps } = await supabase
|
|
234
|
+
.from('bookings')
|
|
235
|
+
.select('id,status')
|
|
236
|
+
.eq('room_id', key)
|
|
237
|
+
.in('status', ['pending', 'paid'])
|
|
238
|
+
.filter('during', 'ov', rangeLit);
|
|
239
|
+
if (overlaps && overlaps.length > 0) {
|
|
240
|
+
await logOps(
|
|
241
|
+
supabase,
|
|
242
|
+
'gcal_blackout_overlaps_booking',
|
|
243
|
+
{
|
|
244
|
+
room_id: key,
|
|
245
|
+
room_name: room.name,
|
|
246
|
+
event_id: ev.id,
|
|
247
|
+
blackout_id: upserted_row?.id ?? null,
|
|
248
|
+
booking_ids: overlaps.map((r) => r.id),
|
|
249
|
+
},
|
|
250
|
+
{ severity: 'warning' },
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// Delete stale google blackouts within the sync window whose ids we didn't see.
|
|
256
|
+
// Only for rooms whose fetch succeeded (we're in the success branch).
|
|
257
|
+
const winStart = timeMin;
|
|
258
|
+
const winEnd = timeMax;
|
|
259
|
+
const windowLit = `[${winStart},${winEnd})`;
|
|
260
|
+
let deleted = 0;
|
|
261
|
+
{
|
|
262
|
+
const q = supabase
|
|
263
|
+
.from('blackouts')
|
|
264
|
+
.delete({ count: 'exact' })
|
|
265
|
+
.eq('room_id', key)
|
|
266
|
+
.eq('source', 'google')
|
|
267
|
+
.filter('during', 'ov', windowLit);
|
|
268
|
+
const finalQ = keepIds.size > 0
|
|
269
|
+
? q.not('google_event_id', 'in', `(${Array.from(keepIds).map((id) => `"${id.replace(/"/g, '\\"')}"`).join(',')})`)
|
|
270
|
+
: q;
|
|
271
|
+
const { count, error: delErr } = await finalQ;
|
|
272
|
+
if (delErr) {
|
|
273
|
+
await logOps(
|
|
274
|
+
supabase,
|
|
275
|
+
'gcal_sync_failed',
|
|
276
|
+
{ room_id: key, message: `delete: ${delErr.message}` },
|
|
277
|
+
{ severity: 'error' },
|
|
278
|
+
);
|
|
279
|
+
} else {
|
|
280
|
+
deleted = count ?? 0;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
summary[key] = { upserted, deleted, skipped_self: skippedSelf };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// Release the lock so the next run can proceed as soon as its schedule fires.
|
|
288
|
+
// Also stamp updated_at = last successful sync completion (the digest's staleness signal).
|
|
289
|
+
await supabase
|
|
290
|
+
.from('sync_state')
|
|
291
|
+
.update({ locked_until: new Date().toISOString(), updated_at: new Date().toISOString() })
|
|
292
|
+
.eq('key', 'gcal-blackouts');
|
|
293
|
+
|
|
294
|
+
return new Response(JSON.stringify({ ok: true, window_days: WINDOW_DAYS, rooms: summary }), {
|
|
295
|
+
status: 200,
|
|
296
|
+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
297
|
+
});
|
|
298
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// Timetable — Event registration. Lets a signed-in member register for, or
|
|
2
|
+
// cancel their registration on, one of our own Commons-calendar Luma events
|
|
3
|
+
// without leaving the portal.
|
|
4
|
+
//
|
|
5
|
+
// SCOPE: only works for events owned by OUR Luma calendar (the same
|
|
6
|
+
// LUMA_API_KEY that timetable-events already uses to read them) — Luma's own
|
|
7
|
+
// key-scoping means a guest can't be added to (or found on) a calendar this
|
|
8
|
+
// key doesn't own, so a community/ICS event id simply fails here. The client
|
|
9
|
+
// only shows Register/Cancel for events with `source: null` (Commons-owned).
|
|
10
|
+
//
|
|
11
|
+
// AUTH: portal bearer session only (resolvePortalSession). The registering/
|
|
12
|
+
// cancelling email is ALWAYS the verified session email — never
|
|
13
|
+
// client-supplied — so this can't be used as an open relay against
|
|
14
|
+
// arbitrary addresses.
|
|
15
|
+
//
|
|
16
|
+
// CANCEL: looks up the caller's own guest record via guests/list (matching
|
|
17
|
+
// on verified session email server-side, never trusting a client-supplied
|
|
18
|
+
// guest_id), then flips it to declined with send_email: false — a self
|
|
19
|
+
// service undo, not a notified cancellation.
|
|
20
|
+
//
|
|
21
|
+
// NOT PERSISTED: Luma stays the system of record for RSVPs, same as the read
|
|
22
|
+
// side (timetable-events). Nothing is written to Supabase here.
|
|
23
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
24
|
+
import { resolvePortalSession } from 'npm:@simplelayer/graniteer-core/portalSession';
|
|
25
|
+
import { checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
|
|
26
|
+
import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
|
|
27
|
+
|
|
28
|
+
const corsHeaders = {
|
|
29
|
+
'Access-Control-Allow-Origin': '*',
|
|
30
|
+
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
31
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const LUMA_BASE = 'https://api.lu.ma/public/v1';
|
|
35
|
+
const BROWSER_UA =
|
|
36
|
+
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124.0 Safari/537.36';
|
|
37
|
+
|
|
38
|
+
function json(status: number, body: unknown) {
|
|
39
|
+
return new Response(JSON.stringify(body), {
|
|
40
|
+
status,
|
|
41
|
+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function lumaFetch(path: string, apiKey: string, init: RequestInit = {}) {
|
|
46
|
+
return fetch(`${LUMA_BASE}${path}`, {
|
|
47
|
+
...init,
|
|
48
|
+
headers: {
|
|
49
|
+
'x-luma-api-key': apiKey,
|
|
50
|
+
'User-Agent': BROWSER_UA,
|
|
51
|
+
'Content-Type': 'application/json',
|
|
52
|
+
Accept: 'application/json',
|
|
53
|
+
...(init.headers ?? {}),
|
|
54
|
+
},
|
|
55
|
+
signal: AbortSignal.timeout(10_000),
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Finds the caller's own guest record on an event by verified email — never
|
|
60
|
+
* trusts a client-supplied guest_id. Paginates like the read side does. */
|
|
61
|
+
async function findOwnGuest(eventId: string, email: string, apiKey: string) {
|
|
62
|
+
let cursor: string | null = null;
|
|
63
|
+
for (let page = 0; page < 5; page++) {
|
|
64
|
+
const qs = new URLSearchParams({ event_id: eventId, pagination_limit: '100' });
|
|
65
|
+
if (cursor) qs.set('pagination_cursor', cursor);
|
|
66
|
+
const res = await lumaFetch(`/events/guests/list?${qs.toString()}`, apiKey);
|
|
67
|
+
if (!res.ok) return { error: res.status };
|
|
68
|
+
const data = await res.json();
|
|
69
|
+
const entries = data.entries ?? [];
|
|
70
|
+
for (const ent of entries) {
|
|
71
|
+
const g = ent.guest ?? ent;
|
|
72
|
+
if ((g.user_email ?? '').toLowerCase() === email) {
|
|
73
|
+
return { guest: g };
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
cursor = data.has_more ? data.next_cursor : null;
|
|
77
|
+
if (!cursor) break;
|
|
78
|
+
}
|
|
79
|
+
return { guest: null };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export async function handle(req: Request): Promise<Response> {
|
|
83
|
+
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
84
|
+
if (req.method !== 'POST') return json(405, { error: 'method_not_allowed' });
|
|
85
|
+
|
|
86
|
+
const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
|
|
87
|
+
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
|
88
|
+
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
|
|
89
|
+
auth: { persistSession: false, autoRefreshToken: false },
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
try {
|
|
93
|
+
const session = await resolvePortalSession(req, admin);
|
|
94
|
+
if (!session) return json(401, { error: 'unauthorized' });
|
|
95
|
+
|
|
96
|
+
const ok = await checkRateLimit(admin, 'timetable-event-register', session.email, 15, 600);
|
|
97
|
+
if (!ok) return json(429, { error: 'rate_limited' });
|
|
98
|
+
|
|
99
|
+
const payload = await req.json().catch(() => ({}));
|
|
100
|
+
const eventId = typeof payload?.event_id === 'string' ? payload.event_id.trim() : '';
|
|
101
|
+
const action = payload?.action === 'cancel' ? 'cancel' : 'register';
|
|
102
|
+
if (!eventId) return json(400, { error: 'missing_event_id' });
|
|
103
|
+
|
|
104
|
+
const apiKey = Deno.env.get('LUMA_API_KEY');
|
|
105
|
+
if (!apiKey) {
|
|
106
|
+
console.error('timetable-event-register: LUMA_API_KEY is not set');
|
|
107
|
+
return json(503, { error: 'not_configured' });
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (action === 'cancel') {
|
|
111
|
+
const found = await findOwnGuest(eventId, session.email, apiKey);
|
|
112
|
+
if ('error' in found) {
|
|
113
|
+
console.error('timetable-event-register: guest lookup failed', found.error);
|
|
114
|
+
return json(502, { error: 'cancel_failed' });
|
|
115
|
+
}
|
|
116
|
+
if (!found.guest) {
|
|
117
|
+
return json(200, { ok: true, message: "You're not registered for this event." });
|
|
118
|
+
}
|
|
119
|
+
const res = await lumaFetch('/events/guests/update-status', apiKey, {
|
|
120
|
+
method: 'POST',
|
|
121
|
+
body: JSON.stringify({
|
|
122
|
+
event_id: eventId,
|
|
123
|
+
guest_id: found.guest.id,
|
|
124
|
+
status: 'declined',
|
|
125
|
+
send_email: false,
|
|
126
|
+
}),
|
|
127
|
+
});
|
|
128
|
+
if (!res.ok) {
|
|
129
|
+
const detail = await res.text().catch(() => '');
|
|
130
|
+
console.error('timetable-event-register: cancel failed', res.status, detail.slice(0, 300));
|
|
131
|
+
await logOps(admin, 'timetable_event_cancel_failed', {
|
|
132
|
+
event_id: eventId, status: res.status, detail: detail.slice(0, 300),
|
|
133
|
+
}, { severity: 'warning' });
|
|
134
|
+
return json(502, { error: 'cancel_failed' });
|
|
135
|
+
}
|
|
136
|
+
return json(200, { ok: true, message: 'Registration cancelled.' });
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const res = await lumaFetch('/events/guests/add', apiKey, {
|
|
140
|
+
method: 'POST',
|
|
141
|
+
body: JSON.stringify({
|
|
142
|
+
event_id: eventId,
|
|
143
|
+
guests: [{ email: session.email }],
|
|
144
|
+
send_email: true,
|
|
145
|
+
}),
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
if (!res.ok) {
|
|
149
|
+
const detail = await res.text().catch(() => '');
|
|
150
|
+
console.error('timetable-event-register: luma responded', res.status, detail.slice(0, 300));
|
|
151
|
+
await logOps(admin, 'timetable_event_register_failed', {
|
|
152
|
+
event_id: eventId, status: res.status, detail: detail.slice(0, 300),
|
|
153
|
+
}, { severity: 'warning' });
|
|
154
|
+
return json(502, { error: 'registration_failed' });
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
return json(200, { ok: true, message: "You're registered — check your email for details." });
|
|
158
|
+
} catch (e) {
|
|
159
|
+
console.error('timetable-event-register: failed', e);
|
|
160
|
+
return json(502, { error: 'registration_failed' });
|
|
161
|
+
}
|
|
162
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// Timetable — Registration status lookup. Given a list of our own Commons
|
|
2
|
+
// event ids, tells the caller which ones they're already an approved guest
|
|
3
|
+
// on, so the portal can show "Registered" (with a Cancel action) instead of
|
|
4
|
+
// always defaulting back to "Register" after a page refresh.
|
|
5
|
+
//
|
|
6
|
+
// AUTH: portal bearer session only. Reflects the VERIFIED session email —
|
|
7
|
+
// never a client-supplied one. Read-only against Luma; nothing written,
|
|
8
|
+
// nothing persisted in Supabase.
|
|
9
|
+
import { createClient } from 'npm:@supabase/supabase-js@2';
|
|
10
|
+
import { resolvePortalSession } from 'npm:@simplelayer/graniteer-core/portalSession';
|
|
11
|
+
import { checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
|
|
12
|
+
|
|
13
|
+
const corsHeaders = {
|
|
14
|
+
'Access-Control-Allow-Origin': '*',
|
|
15
|
+
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
|
16
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
const LUMA_BASE = 'https://api.lu.ma/public/v1';
|
|
20
|
+
const BROWSER_UA =
|
|
21
|
+
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124.0 Safari/537.36';
|
|
22
|
+
const MAX_EVENT_IDS = 20;
|
|
23
|
+
|
|
24
|
+
function json(status: number, body: unknown) {
|
|
25
|
+
return new Response(JSON.stringify(body), {
|
|
26
|
+
status,
|
|
27
|
+
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function isRegistered(eventId: string, email: string, apiKey: string): Promise<boolean> {
|
|
32
|
+
let cursor: string | null = null;
|
|
33
|
+
for (let page = 0; page < 5; page++) {
|
|
34
|
+
const qs = new URLSearchParams({ event_id: eventId, pagination_limit: '100' });
|
|
35
|
+
if (cursor) qs.set('pagination_cursor', cursor);
|
|
36
|
+
const res = await fetch(`${LUMA_BASE}/events/guests/list?${qs.toString()}`, {
|
|
37
|
+
headers: { 'x-luma-api-key': apiKey, 'User-Agent': BROWSER_UA, Accept: 'application/json' },
|
|
38
|
+
signal: AbortSignal.timeout(10_000),
|
|
39
|
+
});
|
|
40
|
+
if (!res.ok) return false;
|
|
41
|
+
const data = await res.json();
|
|
42
|
+
const entries = data.entries ?? [];
|
|
43
|
+
for (const ent of entries) {
|
|
44
|
+
const g = ent.guest ?? ent;
|
|
45
|
+
if ((g.user_email ?? '').toLowerCase() === email && g.approval_status === 'approved') {
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
cursor = data.has_more ? data.next_cursor : null;
|
|
50
|
+
if (!cursor) break;
|
|
51
|
+
}
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function handle(req: Request): Promise<Response> {
|
|
56
|
+
if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
|
|
57
|
+
if (req.method !== 'POST') return json(405, { error: 'method_not_allowed' });
|
|
58
|
+
|
|
59
|
+
const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
|
|
60
|
+
const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
|
|
61
|
+
const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
|
|
62
|
+
auth: { persistSession: false, autoRefreshToken: false },
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
try {
|
|
66
|
+
const session = await resolvePortalSession(req, admin);
|
|
67
|
+
if (!session) return json(401, { error: 'unauthorized' });
|
|
68
|
+
|
|
69
|
+
const ok = await checkRateLimit(admin, 'timetable-event-status', session.email, 30, 600);
|
|
70
|
+
if (!ok) return json(429, { error: 'rate_limited' });
|
|
71
|
+
|
|
72
|
+
const payload = await req.json().catch(() => ({}));
|
|
73
|
+
const eventIds: string[] = Array.isArray(payload?.event_ids)
|
|
74
|
+
? payload.event_ids.filter((x: unknown) => typeof x === 'string').slice(0, MAX_EVENT_IDS)
|
|
75
|
+
: [];
|
|
76
|
+
if (eventIds.length === 0) return json(200, { statuses: {} });
|
|
77
|
+
|
|
78
|
+
const apiKey = Deno.env.get('LUMA_API_KEY');
|
|
79
|
+
if (!apiKey) return json(503, { error: 'not_configured' });
|
|
80
|
+
|
|
81
|
+
const entries = await Promise.all(
|
|
82
|
+
eventIds.map(async (id) => [id, await isRegistered(id, session.email, apiKey)] as const),
|
|
83
|
+
);
|
|
84
|
+
const statuses = Object.fromEntries(entries);
|
|
85
|
+
return json(200, { statuses });
|
|
86
|
+
} catch (e) {
|
|
87
|
+
console.error('timetable-event-status: failed', e);
|
|
88
|
+
return json(502, { error: 'status_failed' });
|
|
89
|
+
}
|
|
90
|
+
}
|