@simplelayer/graniteer-core 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/index.js +2 -2
  2. package/package.json +73 -2
  3. package/src/agreementCheckout.ts +250 -0
  4. package/src/agreementPortalEmail.ts +128 -0
  5. package/src/billingPortalLinkEmail.ts +117 -0
  6. package/src/bookingAgreementEmail.ts +149 -0
  7. package/src/bookingEffects.ts +388 -0
  8. package/src/busClient.ts +268 -0
  9. package/src/busSignature.ts +71 -0
  10. package/src/checkoutCoupon.test.ts +675 -0
  11. package/src/checkoutCoupon.ts +455 -0
  12. package/src/commonsDeposit.ts +298 -0
  13. package/src/commonsDepositWebhook.ts +237 -0
  14. package/src/dayPassConfirmation.ts +230 -0
  15. package/src/dunningEmails.test.ts +263 -0
  16. package/src/dunningEmails.ts +203 -0
  17. package/src/email-templates/brand.ts +93 -0
  18. package/src/email-templates/magic-link.tsx +59 -0
  19. package/src/email-templates/recovery.tsx +59 -0
  20. package/src/email-templates/signup.tsx +67 -0
  21. package/src/functions/admin-cancel-membership.ts +311 -311
  22. package/src/functions/admin-change-membership-plan.ts +312 -308
  23. package/src/functions/admin-charge-guest-print.ts +229 -229
  24. package/src/functions/admin-correct-booking.ts +333 -333
  25. package/src/functions/admin-create-booking.ts +460 -0
  26. package/src/functions/admin-create-commons-event.ts +244 -244
  27. package/src/functions/admin-debug-boldsign-doc.ts +93 -93
  28. package/src/functions/admin-door-write.ts +272 -272
  29. package/src/functions/admin-issue-day-pass.ts +231 -0
  30. package/src/functions/admin-mark-booking-paid.ts +203 -203
  31. package/src/functions/admin-mint-billing-portal-link.ts +168 -0
  32. package/src/functions/admin-mint-portal-link.ts +62 -0
  33. package/src/functions/admin-photo-upload.ts +128 -128
  34. package/src/functions/admin-remove-team-member.ts +150 -150
  35. package/src/functions/admin-request-trial.ts +366 -0
  36. package/src/functions/admin-resend-commons-deposit-link.ts +323 -0
  37. package/src/functions/admin-reset-mfa.ts +138 -138
  38. package/src/functions/admin-retry-invoice-payment.test.ts +567 -0
  39. package/src/functions/admin-retry-invoice-payment.ts +333 -0
  40. package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
  41. package/src/functions/admin-revoke-agreement.ts +467 -0
  42. package/src/functions/admin-send-commons-agreement.ts +214 -214
  43. package/src/functions/admin-set-credit-amount.ts +123 -123
  44. package/src/functions/admin-skip-commons-contract.ts +165 -165
  45. package/src/functions/admin-undo-membership-cancel.ts +144 -144
  46. package/src/functions/admin-wall-photo-write.ts +141 -141
  47. package/src/functions/auth-email-hook.ts +259 -0
  48. package/src/functions/boldsign-sender-identity.ts +114 -114
  49. package/src/functions/booking-availability.ts +419 -419
  50. package/src/functions/booking-member-preview.ts +136 -136
  51. package/src/functions/booking-status.ts +149 -0
  52. package/src/functions/conductor.ts +505 -0
  53. package/src/functions/create-agreement.ts +537 -0
  54. package/src/functions/create-booking.ts +648 -0
  55. package/src/functions/create-day-pass-checkout.ts +218 -0
  56. package/src/functions/create-portal-session.ts +142 -0
  57. package/src/functions/create-subscription-checkout.test.ts +222 -0
  58. package/src/functions/create-subscription-checkout.ts +440 -0
  59. package/src/functions/day-pass-status.ts +89 -89
  60. package/src/functions/diag-webpush-test.ts +45 -45
  61. package/src/functions/event-access-admin.ts +277 -0
  62. package/src/functions/event-access-store.ts +309 -309
  63. package/src/functions/ezeep-print-webhook.ts +213 -213
  64. package/src/functions/ezeep-usage-reconcile.ts +299 -299
  65. package/src/functions/fetch-avatar-original.ts +457 -0
  66. package/src/functions/get-provider-sign-link.ts +155 -0
  67. package/src/functions/get-signing-link.ts +211 -211
  68. package/src/functions/guest-print-setup-confirm.ts +128 -128
  69. package/src/functions/guest-print-submit.ts +149 -149
  70. package/src/functions/luma-webhook.ts +165 -165
  71. package/src/functions/manage-booking.ts +472 -0
  72. package/src/functions/mcp.ts +67 -0
  73. package/src/functions/member-door-action.test.ts +1248 -0
  74. package/src/functions/member-door-action.ts +863 -0
  75. package/src/functions/member-unifi-mapping.test.ts +516 -0
  76. package/src/functions/member-unifi-mapping.ts +206 -0
  77. package/src/functions/membership-door-sync.ts +956 -0
  78. package/src/functions/migration-collision-alert.copy.ts +232 -232
  79. package/src/functions/migration-collision-alert.test.ts +349 -349
  80. package/src/functions/migration-collision-alert.ts +232 -232
  81. package/src/functions/office-assignment-end.ts +146 -146
  82. package/src/functions/portal-booking-access.ts +95 -95
  83. package/src/functions/portal-list-invoices.ts +99 -99
  84. package/src/functions/portal-request-login.ts +192 -0
  85. package/src/functions/portal-resend-invite.ts +248 -0
  86. package/src/functions/portal-submit-event.ts +168 -0
  87. package/src/functions/print-billing-recover.ts +97 -97
  88. package/src/functions/print-billing-run.ts +183 -183
  89. package/src/functions/public-facts.ts +168 -168
  90. package/src/functions/push-send.ts +348 -0
  91. package/src/functions/push-test.ts +234 -0
  92. package/src/functions/request-portal-link.ts +211 -0
  93. package/src/functions/reschedule-booking.ts +649 -0
  94. package/src/functions/review-ratings.ts +113 -0
  95. package/src/functions/space-availability-range.acceptance.test.ts +161 -161
  96. package/src/functions/space-availability-range.ts +142 -142
  97. package/src/functions/stripe-db-reconcile.ts +319 -0
  98. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -0
  99. package/src/functions/stripe-webhook.ts +2595 -0
  100. package/src/functions/sync-gcal-blackouts.ts +298 -298
  101. package/src/functions/timetable-event-register.ts +162 -162
  102. package/src/functions/timetable-event-status.ts +90 -90
  103. package/src/functions/timetable-spaces.ts +219 -219
  104. package/src/functions/touch-pass-reconciler.ts +689 -689
  105. package/src/functions/touch-pass-signup.ts +478 -0
  106. package/src/functions/upload-booking-display-image.ts +179 -0
  107. package/src/functions/virtual-onboarding-purge.ts +134 -134
  108. package/src/functions/virtual-onboarding-submit.ts +315 -315
  109. package/src/functions/voice-booking.ts +453 -0
  110. package/src/functions/voice-day-pass.ts +346 -0
  111. package/src/functions/voice-inquiry.test.ts +301 -301
  112. package/src/functions/voice-inquiry.ts +198 -198
  113. package/src/functions/voice-membership-signup.ts +355 -0
  114. package/src/functions/voice-tour-availability.ts +204 -204
  115. package/src/functions/voice-tour-booking.ts +429 -0
  116. package/src/ghlEventInquiry.ts +143 -0
  117. package/src/mailArrivalEmail.ts +121 -0
  118. package/src/manageToken.ts +363 -0
  119. package/src/membershipBusClient.ts +537 -0
  120. package/src/membershipWelcome.ts +683 -0
  121. package/src/migrationCheckout.ts +366 -0
  122. package/src/pacificDate.ts +54 -0
  123. package/src/paymentLinkEmail.ts +123 -0
  124. package/src/signedUnpaidReminderEmail.test.ts +246 -0
  125. package/src/signedUnpaidReminderEmail.ts +132 -0
  126. package/src/stripeCoworkingPortal.ts +91 -0
  127. package/src/supabaseTestFakes.ts +131 -131
  128. package/src/supportTicketEmail.ts +119 -0
  129. package/src/unifiAccessPolicies.ts +228 -0
  130. package/src/unifiGroups.ts +129 -0
@@ -1,219 +1,219 @@
1
- // Timetable — Spaces. Read-only "what's open right now?" for the bookable
2
- // rooms, used by the member portal.
3
- //
4
- // PRIVACY: this payload is deliberately anonymous. Busy periods are bare
5
- // start/end pairs. No emails, names, phones, booking ids, blackout reasons or
6
- // Google event titles/ids, no Stripe references — the `blackouts` table
7
- // mirrors calendars shared with outside businesses and none of that text may
8
- // ever leave this function. Room rates ARE included, but only the public
9
- // hourly/half-day/day list prices already published on the marketing site;
10
- // per-member pricing is retired, so nothing here varies by caller. Never add
11
- // a field whose value depends on who is asking.
12
- //
13
- // All "is this room busy" logic comes from _shared/availability.ts. Do not add
14
- // a second implementation here.
15
- import { corsHeaders } from 'npm:@supabase/supabase-js@2/cors';
16
- import { createClient } from 'npm:@supabase/supabase-js@2';
17
- import { z } from 'npm:zod@3.23.8';
18
- import {
19
- getBusinessHoursRow,
20
- getBusyRangesDetailed,
21
- laDateStr,
22
- laWallToUtc,
23
- laWeekday,
24
- } from 'npm:@simplelayer/graniteer-core/availability';
25
-
26
- const Body = z.object({ at: z.string().datetime({ offset: true }).optional() });
27
-
28
- /** Cheap freshness hint for the client; the UI also refetches on a timer. */
29
- const VALID_FOR_MS = 60_000;
30
- const SOON_MS = 30 * 60 * 1000;
31
-
32
- interface SpaceOut {
33
- room_id: string;
34
- name: string;
35
- slug: string | null;
36
- booking_mode: string;
37
- seats: number;
38
- tagline: string | null;
39
- status: 'free' | 'busy' | 'closing_soon' | 'closed';
40
- until: string | null;
41
- /** Public enquiry URL for quote-mode spaces (never customer data). */
42
- quote_url: string | null;
43
- /**
44
- * PUBLIC list rate for the room, already published on the marketing site.
45
- * Every booker — member or not — is charged off these columns
46
- * (_shared/pricing.ts: the member-rate mechanism is retired), so this is
47
- * still not per-member data. Do NOT extend this payload with anything that
48
- * varies by caller; the endpoint stays anonymous.
49
- */
50
- hourly_cents: number | null;
51
- half_day_cents: number | null;
52
- day_cents: number | null;
53
- today: Array<{ start: string; end: string }>;
54
- }
55
-
56
- /** Merge overlapping/adjacent [start,end) pairs, sorted ascending. */
57
- function mergeRanges(ranges: [number, number][]): [number, number][] {
58
- const sorted = [...ranges].sort((a, b) => a[0] - b[0]);
59
- const out: [number, number][] = [];
60
- for (const [s, e] of sorted) {
61
- const last = out[out.length - 1];
62
- if (last && s <= last[1]) last[1] = Math.max(last[1], e);
63
- else out.push([s, e]);
64
- }
65
- return out;
66
- }
67
-
68
- export async function handle(req: Request): Promise<Response> {
69
- if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
70
-
71
- try {
72
- const raw = await req.json().catch(() => ({}));
73
- const parsed = Body.safeParse(raw);
74
- if (!parsed.success) {
75
- return new Response(JSON.stringify({ error: parsed.error.flatten().fieldErrors }), {
76
- status: 400,
77
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
78
- });
79
- }
80
-
81
- const at = parsed.data.at ? new Date(parsed.data.at) : new Date();
82
- if (Number.isNaN(at.getTime())) {
83
- return new Response(JSON.stringify({ error: 'invalid_at' }), {
84
- status: 400,
85
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
86
- });
87
- }
88
- const atMs = at.getTime();
89
-
90
- const supabase = createClient(
91
- Deno.env.get('SUPABASE_URL')!,
92
- Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
93
- );
94
-
95
- const { data: rooms, error: rErr } = await supabase
96
- .from('rooms')
97
- .select(
98
- 'id,name,slug,booking_mode,seats,tagline,quote_url,hourly_cents,half_day_cents,day_cents',
99
- )
100
- .eq('active', true)
101
- .order('sort_order');
102
- if (rErr) throw rErr;
103
-
104
- const { data: sync } = await supabase
105
- .from('sync_state')
106
- .select('updated_at')
107
- .eq('key', 'gcal-blackouts')
108
- .maybeSingle();
109
-
110
- const dateStr = laDateStr(at);
111
- const weekday = laWeekday(dateStr);
112
-
113
- const spaces: SpaceOut[] = [];
114
- const changePoints: number[] = [];
115
-
116
- for (const room of rooms ?? []) {
117
- const base = {
118
- room_id: room.id as string,
119
- name: room.name as string,
120
- slug: (room.slug as string | null) ?? null,
121
- booking_mode: room.booking_mode as string,
122
- seats: room.seats as number,
123
- tagline: (room.tagline as string | null) ?? null,
124
- quote_url: (room.quote_url as string | null) ?? null,
125
- hourly_cents: (room.hourly_cents as number | null) ?? null,
126
- half_day_cents: (room.half_day_cents as number | null) ?? null,
127
- day_cents: (room.day_cents as number | null) ?? null,
128
- };
129
-
130
- // Quote-mode space (The Commons): booked by conversation, not by the
131
- // hourly/day-block engine, so free/busy is not a meaningful question.
132
- if (room.booking_mode === 'quote') {
133
- spaces.push({ ...base, status: 'free', until: null, today: [] });
134
- continue;
135
- }
136
-
137
- const hours = await getBusinessHoursRow(supabase, room.id as string, weekday);
138
- if (!hours) {
139
- spaces.push({ ...base, status: 'closed', until: null, today: [] });
140
- continue;
141
- }
142
-
143
- const [openH, openM] = hours.open_time.split(':').map(Number);
144
- const [closeH, closeM] = hours.close_time.split(':').map(Number);
145
- const openMs = laWallToUtc(dateStr, openH, openM).getTime();
146
- const closeMs = laWallToUtc(dateStr, closeH, closeM).getTime();
147
- const rangeLiteral = `[${new Date(openMs).toISOString()},${new Date(closeMs).toISOString()})`;
148
-
149
- const { busy, unparsed } = await getBusyRangesDetailed(
150
- supabase,
151
- room.id as string,
152
- rangeLiteral,
153
- );
154
-
155
- // Fail safe: if any row's range could not be parsed we cannot prove the
156
- // room is free, so the whole open period reads as busy.
157
- const raw = unparsed > 0 ? [[openMs, closeMs] as [number, number]] : busy;
158
- const blocks = mergeRanges(
159
- raw
160
- .map(([s, e]) => [Math.max(s, openMs), Math.min(e, closeMs)] as [number, number])
161
- .filter(([s, e]) => e > s),
162
- );
163
-
164
- const today = blocks.map(([s, e]) => ({
165
- start: new Date(s).toISOString(),
166
- end: new Date(e).toISOString(),
167
- }));
168
-
169
- let status: SpaceOut['status'];
170
- let until: string | null = null;
171
-
172
- if (atMs < openMs) {
173
- status = 'closed';
174
- until = new Date(openMs).toISOString();
175
- changePoints.push(openMs);
176
- } else if (atMs >= closeMs) {
177
- status = 'closed';
178
- } else {
179
- const current = blocks.find(([s, e]) => atMs >= s && atMs < e);
180
- if (current) {
181
- status = 'busy';
182
- until = new Date(current[1]).toISOString();
183
- changePoints.push(current[1]);
184
- } else {
185
- const next = blocks.find(([s]) => s > atMs);
186
- if (next) {
187
- status = next[0] - atMs <= SOON_MS ? 'closing_soon' : 'free';
188
- until = new Date(next[0]).toISOString();
189
- changePoints.push(next[0]);
190
- } else {
191
- status = 'free';
192
- until = null;
193
- changePoints.push(closeMs);
194
- }
195
- }
196
- }
197
-
198
- spaces.push({ ...base, status, until, today });
199
- }
200
-
201
- const validUntilMs = Math.min(atMs + VALID_FOR_MS, ...changePoints.filter((t) => t > atMs));
202
-
203
- return new Response(
204
- JSON.stringify({
205
- generated_at: new Date(atMs).toISOString(),
206
- valid_until: new Date(validUntilMs).toISOString(),
207
- gcal_synced_at: (sync?.updated_at as string | null) ?? null,
208
- spaces,
209
- }),
210
- { headers: { ...corsHeaders, 'Content-Type': 'application/json' } },
211
- );
212
- } catch (e) {
213
- console.error('timetable-spaces failed', e);
214
- return new Response(JSON.stringify({ error: 'internal_error' }), {
215
- status: 500,
216
- headers: { ...corsHeaders, 'Content-Type': 'application/json' },
217
- });
218
- }
219
- }
1
+ // Timetable — Spaces. Read-only "what's open right now?" for the bookable
2
+ // rooms, used by the member portal.
3
+ //
4
+ // PRIVACY: this payload is deliberately anonymous. Busy periods are bare
5
+ // start/end pairs. No emails, names, phones, booking ids, blackout reasons or
6
+ // Google event titles/ids, no Stripe references — the `blackouts` table
7
+ // mirrors calendars shared with outside businesses and none of that text may
8
+ // ever leave this function. Room rates ARE included, but only the public
9
+ // hourly/half-day/day list prices already published on the marketing site;
10
+ // per-member pricing is retired, so nothing here varies by caller. Never add
11
+ // a field whose value depends on who is asking.
12
+ //
13
+ // All "is this room busy" logic comes from _shared/availability.ts. Do not add
14
+ // a second implementation here.
15
+ import { corsHeaders } from 'npm:@supabase/supabase-js@2/cors';
16
+ import { createClient } from 'npm:@supabase/supabase-js@2';
17
+ import { z } from 'npm:zod@3.23.8';
18
+ import {
19
+ getBusinessHoursRow,
20
+ getBusyRangesDetailed,
21
+ laDateStr,
22
+ laWallToUtc,
23
+ laWeekday,
24
+ } from 'npm:@simplelayer/graniteer-core/availability';
25
+
26
+ const Body = z.object({ at: z.string().datetime({ offset: true }).optional() });
27
+
28
+ /** Cheap freshness hint for the client; the UI also refetches on a timer. */
29
+ const VALID_FOR_MS = 60_000;
30
+ const SOON_MS = 30 * 60 * 1000;
31
+
32
+ interface SpaceOut {
33
+ room_id: string;
34
+ name: string;
35
+ slug: string | null;
36
+ booking_mode: string;
37
+ seats: number;
38
+ tagline: string | null;
39
+ status: 'free' | 'busy' | 'closing_soon' | 'closed';
40
+ until: string | null;
41
+ /** Public enquiry URL for quote-mode spaces (never customer data). */
42
+ quote_url: string | null;
43
+ /**
44
+ * PUBLIC list rate for the room, already published on the marketing site.
45
+ * Every booker — member or not — is charged off these columns
46
+ * (_shared/pricing.ts: the member-rate mechanism is retired), so this is
47
+ * still not per-member data. Do NOT extend this payload with anything that
48
+ * varies by caller; the endpoint stays anonymous.
49
+ */
50
+ hourly_cents: number | null;
51
+ half_day_cents: number | null;
52
+ day_cents: number | null;
53
+ today: Array<{ start: string; end: string }>;
54
+ }
55
+
56
+ /** Merge overlapping/adjacent [start,end) pairs, sorted ascending. */
57
+ function mergeRanges(ranges: [number, number][]): [number, number][] {
58
+ const sorted = [...ranges].sort((a, b) => a[0] - b[0]);
59
+ const out: [number, number][] = [];
60
+ for (const [s, e] of sorted) {
61
+ const last = out[out.length - 1];
62
+ if (last && s <= last[1]) last[1] = Math.max(last[1], e);
63
+ else out.push([s, e]);
64
+ }
65
+ return out;
66
+ }
67
+
68
+ export async function handle(req: Request): Promise<Response> {
69
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
70
+
71
+ try {
72
+ const raw = await req.json().catch(() => ({}));
73
+ const parsed = Body.safeParse(raw);
74
+ if (!parsed.success) {
75
+ return new Response(JSON.stringify({ error: parsed.error.flatten().fieldErrors }), {
76
+ status: 400,
77
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
78
+ });
79
+ }
80
+
81
+ const at = parsed.data.at ? new Date(parsed.data.at) : new Date();
82
+ if (Number.isNaN(at.getTime())) {
83
+ return new Response(JSON.stringify({ error: 'invalid_at' }), {
84
+ status: 400,
85
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
86
+ });
87
+ }
88
+ const atMs = at.getTime();
89
+
90
+ const supabase = createClient(
91
+ Deno.env.get('SUPABASE_URL')!,
92
+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
93
+ );
94
+
95
+ const { data: rooms, error: rErr } = await supabase
96
+ .from('rooms')
97
+ .select(
98
+ 'id,name,slug,booking_mode,seats,tagline,quote_url,hourly_cents,half_day_cents,day_cents',
99
+ )
100
+ .eq('active', true)
101
+ .order('sort_order');
102
+ if (rErr) throw rErr;
103
+
104
+ const { data: sync } = await supabase
105
+ .from('sync_state')
106
+ .select('updated_at')
107
+ .eq('key', 'gcal-blackouts')
108
+ .maybeSingle();
109
+
110
+ const dateStr = laDateStr(at);
111
+ const weekday = laWeekday(dateStr);
112
+
113
+ const spaces: SpaceOut[] = [];
114
+ const changePoints: number[] = [];
115
+
116
+ for (const room of rooms ?? []) {
117
+ const base = {
118
+ room_id: room.id as string,
119
+ name: room.name as string,
120
+ slug: (room.slug as string | null) ?? null,
121
+ booking_mode: room.booking_mode as string,
122
+ seats: room.seats as number,
123
+ tagline: (room.tagline as string | null) ?? null,
124
+ quote_url: (room.quote_url as string | null) ?? null,
125
+ hourly_cents: (room.hourly_cents as number | null) ?? null,
126
+ half_day_cents: (room.half_day_cents as number | null) ?? null,
127
+ day_cents: (room.day_cents as number | null) ?? null,
128
+ };
129
+
130
+ // Quote-mode space (The Commons): booked by conversation, not by the
131
+ // hourly/day-block engine, so free/busy is not a meaningful question.
132
+ if (room.booking_mode === 'quote') {
133
+ spaces.push({ ...base, status: 'free', until: null, today: [] });
134
+ continue;
135
+ }
136
+
137
+ const hours = await getBusinessHoursRow(supabase, room.id as string, weekday);
138
+ if (!hours) {
139
+ spaces.push({ ...base, status: 'closed', until: null, today: [] });
140
+ continue;
141
+ }
142
+
143
+ const [openH, openM] = hours.open_time.split(':').map(Number);
144
+ const [closeH, closeM] = hours.close_time.split(':').map(Number);
145
+ const openMs = laWallToUtc(dateStr, openH, openM).getTime();
146
+ const closeMs = laWallToUtc(dateStr, closeH, closeM).getTime();
147
+ const rangeLiteral = `[${new Date(openMs).toISOString()},${new Date(closeMs).toISOString()})`;
148
+
149
+ const { busy, unparsed } = await getBusyRangesDetailed(
150
+ supabase,
151
+ room.id as string,
152
+ rangeLiteral,
153
+ );
154
+
155
+ // Fail safe: if any row's range could not be parsed we cannot prove the
156
+ // room is free, so the whole open period reads as busy.
157
+ const raw = unparsed > 0 ? [[openMs, closeMs] as [number, number]] : busy;
158
+ const blocks = mergeRanges(
159
+ raw
160
+ .map(([s, e]) => [Math.max(s, openMs), Math.min(e, closeMs)] as [number, number])
161
+ .filter(([s, e]) => e > s),
162
+ );
163
+
164
+ const today = blocks.map(([s, e]) => ({
165
+ start: new Date(s).toISOString(),
166
+ end: new Date(e).toISOString(),
167
+ }));
168
+
169
+ let status: SpaceOut['status'];
170
+ let until: string | null = null;
171
+
172
+ if (atMs < openMs) {
173
+ status = 'closed';
174
+ until = new Date(openMs).toISOString();
175
+ changePoints.push(openMs);
176
+ } else if (atMs >= closeMs) {
177
+ status = 'closed';
178
+ } else {
179
+ const current = blocks.find(([s, e]) => atMs >= s && atMs < e);
180
+ if (current) {
181
+ status = 'busy';
182
+ until = new Date(current[1]).toISOString();
183
+ changePoints.push(current[1]);
184
+ } else {
185
+ const next = blocks.find(([s]) => s > atMs);
186
+ if (next) {
187
+ status = next[0] - atMs <= SOON_MS ? 'closing_soon' : 'free';
188
+ until = new Date(next[0]).toISOString();
189
+ changePoints.push(next[0]);
190
+ } else {
191
+ status = 'free';
192
+ until = null;
193
+ changePoints.push(closeMs);
194
+ }
195
+ }
196
+ }
197
+
198
+ spaces.push({ ...base, status, until, today });
199
+ }
200
+
201
+ const validUntilMs = Math.min(atMs + VALID_FOR_MS, ...changePoints.filter((t) => t > atMs));
202
+
203
+ return new Response(
204
+ JSON.stringify({
205
+ generated_at: new Date(atMs).toISOString(),
206
+ valid_until: new Date(validUntilMs).toISOString(),
207
+ gcal_synced_at: (sync?.updated_at as string | null) ?? null,
208
+ spaces,
209
+ }),
210
+ { headers: { ...corsHeaders, 'Content-Type': 'application/json' } },
211
+ );
212
+ } catch (e) {
213
+ console.error('timetable-spaces failed', e);
214
+ return new Response(JSON.stringify({ error: 'internal_error' }), {
215
+ status: 500,
216
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
217
+ });
218
+ }
219
+ }