@simplelayer/graniteer-core 0.0.1 → 0.1.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 (100) hide show
  1. package/index.js +2 -2
  2. package/package.json +98 -15
  3. package/src/adminBookingCredit.test.ts +451 -0
  4. package/src/adminBookingCredit.ts +239 -0
  5. package/src/availability.test.ts +25 -0
  6. package/src/availability.ts +201 -0
  7. package/src/bookingHoldReclaim.ts +94 -0
  8. package/src/checkoutSessionParams.ts +56 -0
  9. package/src/commonsContract.ts +175 -0
  10. package/src/conductorAdmin.ts +141 -0
  11. package/src/email-templates/email-change.tsx +92 -0
  12. package/src/email-templates/invite.tsx +79 -0
  13. package/src/email-templates/reauthentication.tsx +60 -0
  14. package/src/functions/admin-cancel-membership.ts +311 -0
  15. package/src/functions/admin-change-membership-plan.ts +308 -0
  16. package/src/functions/admin-charge-guest-print.ts +229 -0
  17. package/src/functions/admin-correct-booking.ts +333 -0
  18. package/src/functions/admin-create-commons-event.ts +244 -0
  19. package/src/functions/admin-debug-boldsign-doc.ts +93 -0
  20. package/src/functions/admin-door-write.ts +272 -0
  21. package/src/functions/admin-mark-booking-paid.ts +203 -0
  22. package/src/functions/admin-photo-upload.ts +128 -0
  23. package/src/functions/admin-remove-team-member.ts +150 -0
  24. package/src/functions/admin-reset-mfa.ts +138 -0
  25. package/src/functions/admin-reverse-coupon-redemption.ts +98 -0
  26. package/src/functions/admin-send-commons-agreement.ts +214 -0
  27. package/src/functions/admin-set-credit-amount.ts +123 -0
  28. package/src/functions/admin-skip-commons-contract.ts +165 -0
  29. package/src/functions/admin-undo-membership-cancel.ts +144 -0
  30. package/src/functions/admin-wall-photo-write.ts +141 -0
  31. package/src/functions/boldsign-sender-identity.ts +114 -0
  32. package/src/functions/booking-availability.ts +419 -0
  33. package/src/functions/booking-member-preview.ts +136 -0
  34. package/src/functions/day-pass-status.ts +89 -0
  35. package/src/functions/dayStatus.ts +71 -0
  36. package/src/functions/diag-webpush-test.ts +45 -0
  37. package/src/functions/event-access-store.ts +309 -0
  38. package/src/functions/ezeep-print-webhook.ts +213 -0
  39. package/src/functions/ezeep-usage-reconcile.ts +299 -0
  40. package/src/functions/get-signing-link.ts +211 -0
  41. package/src/functions/guest-print-setup-confirm.ts +128 -0
  42. package/src/functions/guest-print-submit.ts +149 -0
  43. package/src/functions/luma-webhook.ts +165 -0
  44. package/src/functions/migration-collision-alert.copy.ts +232 -0
  45. package/src/functions/migration-collision-alert.test.ts +349 -0
  46. package/src/functions/migration-collision-alert.ts +232 -0
  47. package/src/functions/office-assignment-end.ts +146 -0
  48. package/src/functions/portal-booking-access.ts +95 -0
  49. package/src/functions/portal-list-invoices.ts +99 -0
  50. package/src/functions/print-billing-recover.ts +97 -0
  51. package/src/functions/print-billing-run.ts +183 -0
  52. package/src/functions/public-facts.ts +168 -0
  53. package/src/functions/space-availability-range.acceptance.test.ts +161 -0
  54. package/src/functions/space-availability-range.ts +142 -0
  55. package/src/functions/sync-gcal-blackouts.ts +298 -0
  56. package/src/functions/timetable-event-register.ts +162 -0
  57. package/src/functions/timetable-event-status.ts +90 -0
  58. package/src/functions/timetable-spaces.ts +219 -0
  59. package/src/functions/touch-pass-reconciler.ts +689 -0
  60. package/src/functions/virtual-onboarding-purge.ts +134 -0
  61. package/src/functions/virtual-onboarding-submit.ts +315 -0
  62. package/src/functions/voice-inquiry.test.ts +301 -0
  63. package/src/functions/voice-inquiry.ts +198 -0
  64. package/src/functions/voice-tour-availability.ts +204 -0
  65. package/src/gcalSync.ts +142 -0
  66. package/src/ghlNote.ts +34 -0
  67. package/src/ghlTask.ts +48 -0
  68. package/src/ghlVoiceInquiry.ts +90 -0
  69. package/src/guestPrintCapture.test.ts +722 -0
  70. package/src/guestPrintCapture.ts +538 -0
  71. package/src/lumaGhl.ts +195 -0
  72. package/src/membership.ts +109 -0
  73. package/src/money.ts +36 -0
  74. package/src/ops.ts +97 -0
  75. package/src/pacificDate.ts +34 -0
  76. package/src/policyAcknowledgment.test.ts +50 -0
  77. package/src/policyAcknowledgment.ts +96 -0
  78. package/src/portalSession.ts +46 -0
  79. package/src/pricing.test.ts +660 -0
  80. package/src/pricing.ts +1025 -0
  81. package/src/printBilling.test.ts +750 -0
  82. package/src/printBilling.ts +891 -0
  83. package/src/printBillingAdapters.ts +169 -0
  84. package/src/printCorrections.test.ts +348 -0
  85. package/src/printCorrections.ts +496 -0
  86. package/src/rateLimit.ts +82 -0
  87. package/src/referralCredits.test.ts +31 -0
  88. package/src/referralCredits.ts +34 -0
  89. package/src/referralGrant.ts +321 -0
  90. package/src/rescheduleCredit.test.ts +521 -0
  91. package/src/rescheduleCredit.ts +337 -0
  92. package/src/reservationWifiCode.test.ts +69 -0
  93. package/src/reservationWifiCode.ts +81 -0
  94. package/src/retellCallAnalyzed.test.ts +167 -0
  95. package/src/retellCallAnalyzed.ts +113 -0
  96. package/src/retellSignature.test.ts +137 -0
  97. package/src/retellSignature.ts +82 -0
  98. package/src/slackAlert.ts +38 -0
  99. package/src/supabaseTestFakes.ts +131 -0
  100. package/src/tier1Agreement.ts +125 -0
package/src/lumaGhl.ts ADDED
@@ -0,0 +1,195 @@
1
+ import type { logOps as LogOpsFn } from './ops.ts';
2
+ import { logOps } from './ops.ts';
3
+
4
+ /**
5
+ * Lu.ma guest -> GHL (LeadConnector) contact sync. DATA SYNC ONLY.
6
+ *
7
+ * Creates/updates a CRM contact and its tags so Kyle can build workflows off
8
+ * those tags inside GHL. This module never sends email, SMS, or any outbound
9
+ * message. Never throws — failures are logged to ops_events and swallowed so
10
+ * the webhook response is unaffected.
11
+ *
12
+ * GHL API notes (verified live):
13
+ * - Auth: `Authorization: Bearer <key>` + `Version: 2021-07-28` on every call.
14
+ * - Search: GET /contacts/?locationId=..&query=<email> -> { contacts: [{id, email, tags}] }
15
+ * The search index lags ~10-20s behind writes — expected, not a bug.
16
+ * - Upsert: POST /contacts/upsert -> 201 { new, contact: { id, tags } }.
17
+ * The `tags` array is REPLACED, not merged — so we merge client-side.
18
+ */
19
+
20
+ type SupabaseLike = Parameters<typeof LogOpsFn>[0];
21
+
22
+ const GHL_BASE = 'https://services.leadconnectorhq.com';
23
+ const GHL_VERSION = '2021-07-28';
24
+
25
+ function slugify(name: string): string {
26
+ return name
27
+ .toLowerCase()
28
+ .replace(/[^a-z0-9]+/g, '-')
29
+ .replace(/^-+|-+$/g, '')
30
+ .slice(0, 60)
31
+ .replace(/-+$/g, '');
32
+ }
33
+
34
+ function formatStartAt(startAt: unknown): string | null {
35
+ if (typeof startAt !== 'string' || !startAt) return null;
36
+ const d = new Date(startAt);
37
+ if (Number.isNaN(d.getTime())) return null;
38
+ try {
39
+ return new Intl.DateTimeFormat('en-US', {
40
+ timeZone: 'America/Los_Angeles',
41
+ dateStyle: 'medium',
42
+ timeStyle: 'short',
43
+ }).format(d);
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+
49
+ export async function syncLumaGuestToGhl(
50
+ guestData: unknown,
51
+ eventType: string,
52
+ supabase: SupabaseLike,
53
+ ): Promise<void> {
54
+ try {
55
+ const apiKey = Deno.env.get('GHL_GC_API_KEY');
56
+ const locationId = Deno.env.get('GHL_GC_LOCATION_ID');
57
+ if (!apiKey || !locationId) {
58
+ await logOps(supabase, 'luma_ghl_not_configured', {}, { severity: 'warning' });
59
+ return;
60
+ }
61
+
62
+ const data = (guestData ?? {}) as Record<string, unknown>;
63
+ const email = data.user_email;
64
+ if (typeof email !== 'string' || !email.trim()) {
65
+ await logOps(
66
+ supabase,
67
+ 'luma_ghl_sync_failed',
68
+ { event_type: eventType, reason: 'missing_user_email' },
69
+ { severity: 'warning' },
70
+ );
71
+ return;
72
+ }
73
+
74
+ const event = (data.event ?? {}) as Record<string, unknown>;
75
+ const eventName = typeof event.name === 'string' ? event.name : null;
76
+ const userName = typeof data.user_name === 'string' ? data.user_name.trim() : '';
77
+ const checkedInAt = data.checked_in_at;
78
+
79
+ let firstName: string | undefined;
80
+ let lastName: string | undefined;
81
+ if (userName) {
82
+ const idx = userName.indexOf(' ');
83
+ if (idx === -1) {
84
+ firstName = userName;
85
+ } else {
86
+ firstName = userName.slice(0, idx);
87
+ lastName = userName.slice(idx + 1).trim() || undefined;
88
+ }
89
+ }
90
+
91
+ const slug = eventName ? slugify(eventName) : '';
92
+
93
+ const headers = {
94
+ Authorization: `Bearer ${apiKey}`,
95
+ Version: GHL_VERSION,
96
+ 'Content-Type': 'application/json',
97
+ };
98
+
99
+ // 1) Look up the existing contact so we can merge tags (upsert replaces them).
100
+ let contactId: string | null = null;
101
+ const existingTags: string[] = [];
102
+ try {
103
+ const searchUrl =
104
+ `${GHL_BASE}/contacts/?locationId=${encodeURIComponent(locationId)}` +
105
+ `&query=${encodeURIComponent(email)}`;
106
+ const res = await fetch(searchUrl, { headers });
107
+ if (res.ok) {
108
+ const payload = (await res.json()) as { contacts?: Array<Record<string, unknown>> };
109
+ const match = (payload.contacts ?? []).find(
110
+ (c) =>
111
+ typeof c.email === 'string' &&
112
+ c.email.toLowerCase() === email.toLowerCase(),
113
+ );
114
+ if (match) {
115
+ if (typeof match.id === 'string') contactId = match.id;
116
+ if (Array.isArray(match.tags)) {
117
+ for (const t of match.tags) {
118
+ if (typeof t === 'string' && t.trim()) existingTags.push(t.toLowerCase());
119
+ }
120
+ }
121
+ }
122
+ }
123
+ } catch {
124
+ // Search is best-effort; fall through to a fresh upsert.
125
+ }
126
+
127
+ const tagSet = new Set<string>(existingTags);
128
+ tagSet.add('luma-guest');
129
+ if (slug) tagSet.add(`event:${slug}`);
130
+ if (checkedInAt !== null && checkedInAt !== undefined && checkedInAt !== '') {
131
+ tagSet.add('luma-checked-in');
132
+ }
133
+ const mergedTags = Array.from(tagSet);
134
+
135
+ const upsertBody: Record<string, unknown> = {
136
+ locationId,
137
+ email,
138
+ tags: mergedTags,
139
+ };
140
+ if (firstName) upsertBody.firstName = firstName;
141
+ if (lastName) upsertBody.lastName = lastName;
142
+
143
+ const upsertRes = await fetch(`${GHL_BASE}/contacts/upsert`, {
144
+ method: 'POST',
145
+ headers,
146
+ body: JSON.stringify(upsertBody),
147
+ });
148
+
149
+ if (!upsertRes.ok) {
150
+ const text = await upsertRes.text().catch(() => '');
151
+ await logOps(
152
+ supabase,
153
+ 'luma_ghl_sync_failed',
154
+ {
155
+ event_type: eventType,
156
+ step: 'upsert',
157
+ status: upsertRes.status,
158
+ message: text.slice(0, 500),
159
+ },
160
+ { severity: 'warning' },
161
+ );
162
+ return;
163
+ }
164
+
165
+ const upserted = (await upsertRes.json().catch(() => ({}))) as {
166
+ contact?: { id?: unknown };
167
+ };
168
+ const upsertedId = typeof upserted.contact?.id === 'string' ? upserted.contact.id : contactId;
169
+
170
+ // 2) Registration note — only on first registration, never on guest.updated.
171
+ if (eventType === 'guest.registered' && upsertedId && eventName) {
172
+ try {
173
+ const when = formatStartAt(event.start_at);
174
+ const noteBody = `Registered for "${eventName}"${when ? ` (${when})` : ''} via Lu.ma.`;
175
+ await fetch(`${GHL_BASE}/contacts/${upsertedId}/notes`, {
176
+ method: 'POST',
177
+ headers,
178
+ body: JSON.stringify({ body: noteBody }),
179
+ });
180
+ } catch {
181
+ // A note failure must not undo the tag sync that already succeeded.
182
+ }
183
+ }
184
+ } catch (e) {
185
+ await logOps(
186
+ supabase,
187
+ 'luma_ghl_sync_failed',
188
+ {
189
+ event_type: eventType,
190
+ message: (e instanceof Error ? e.message : String(e)).slice(0, 500),
191
+ },
192
+ { severity: 'warning' },
193
+ );
194
+ }
195
+ }
@@ -0,0 +1,109 @@
1
+ // Server-authoritative membership eligibility check for booking pricing.
2
+ // A membership grants member pricing when either
3
+ // (a) status IN ('active', 'trialing'), OR
4
+ // (b) status IN ('past_due', 'canceled', 'unpaid') AND
5
+ // pricing_grace_ends_at > now()
6
+ // (Phase 3 revoke loop v1 — 5-day grace once a Stripe sub enters a
7
+ // dunning/terminal state; the grace clock starts at the FIRST such
8
+ // state (usually past_due) and does not extend as the sub progresses
9
+ // past_due → canceled/unpaid. Grace start/clear is driven by
10
+ // stripe-webhook's upsertMembershipFromSubscription).
11
+ //
12
+ // Called from every server-side booking pricing decision (create-booking,
13
+ // admin-create-booking, reschedule-booking). NEVER trust a client-side flag.
14
+ //
15
+ // The per-row entitlement predicate is exported as computeEntitlement() so
16
+ // that door/WiFi sync (membership-door-sync) uses the IDENTICAL rule as
17
+ // pricing. Keeping a single source of truth is the whole point — never fork
18
+ // this predicate. resolveIsMember() delegates to computeEntitlement() and
19
+ // its observable behavior (signature, query filter, fail-closed-on-error,
20
+ // error log) is unchanged.
21
+
22
+ import type { SupabaseClient } from 'npm:@supabase/supabase-js@2';
23
+ import { logOps } from './ops.ts';
24
+
25
+ // Loose generics, matching _shared/ops.ts. A real createClient(url, key, opts)
26
+ // call infers SupabaseClient<any, 'public', 'public', ...>, which is NOT
27
+ // assignable to the un-inferred ReturnType<typeof createClient> default — that
28
+ // mismatch is what made every call site here fail deno check.
29
+ // deno-lint-ignore no-explicit-any
30
+ type SupabaseLike = SupabaseClient<any, any, any>;
31
+
32
+ export type EntitlementRow = {
33
+ status: string;
34
+ pricing_grace_ends_at: string | null;
35
+ };
36
+
37
+ type MembershipLookupRow = EntitlementRow & { email: string | null };
38
+
39
+ export function computeEntitlement(m: EntitlementRow, now: number = Date.now()): boolean {
40
+ if (m.status === 'active' || m.status === 'trialing') return true;
41
+ if (m.status === 'past_due' || m.status === 'canceled' || m.status === 'unpaid') {
42
+ return !!m.pricing_grace_ends_at && new Date(m.pricing_grace_ends_at).getTime() > now;
43
+ }
44
+ return false;
45
+ }
46
+
47
+ export async function resolveIsMember(supabase: SupabaseLike, email: string): Promise<boolean> {
48
+ return (await resolveMembershipContext(supabase, email)).isMember;
49
+ }
50
+
51
+ /**
52
+ * Same lookup as resolveIsMember(), but also returns the membership row id so
53
+ * callers can address the period-based credit RPCs (credit_hold, coupon_*).
54
+ * membershipId is the id of the first entitled row; null when the email has no
55
+ * membership row at all (or when the lookup failed — fail-closed, same as
56
+ * resolveIsMember).
57
+ */
58
+ export async function resolveMembershipContext(
59
+ supabase: SupabaseLike,
60
+ email: string,
61
+ ): Promise<{ isMember: boolean; membershipId: string | null }> {
62
+ const emailKey = (email ?? '').toLowerCase();
63
+ if (!emailKey) return { isMember: false, membershipId: null };
64
+ const { data, error } = await supabase
65
+ .from('memberships')
66
+ .select('id,email,status,pricing_grace_ends_at,created_at')
67
+ // memberships.email is plain text (not citext) — match case-insensitively
68
+ // so a mixed-case stored email still resolves member pricing. ilike is a
69
+ // broad prefilter only (`_` is a wildcard AND a legal email character),
70
+ // so every row is re-checked with strict lowercase equality below.
71
+ .ilike('email', emailKey)
72
+ .in('status', ['active', 'trialing', 'past_due', 'canceled', 'unpaid']);
73
+ if (error) {
74
+ // Fail-closed for pricing (returns false = public rate) — but log so a
75
+ // DB outage doesn't silently strip member pricing without a trace.
76
+ console.error('[membership.resolveIsMember] lookup failed', { email: emailKey, error });
77
+ return { isMember: false, membershipId: null };
78
+ }
79
+ if (!data || data.length === 0) return { isMember: false, membershipId: null };
80
+ const now = Date.now();
81
+ const rows = (data as (MembershipLookupRow & { id: string; created_at: string | null })[])
82
+ .filter((m) => (m.email ?? '').toLowerCase() === emailKey)
83
+ // Deterministic order. Under ratified plurality 2+ entitled rows on one
84
+ // email is NORMAL, and which one a booking's credits draw against must
85
+ // never depend on PostgREST's row order. Stated intent, not a default:
86
+ // THE OLDEST ENTITLED MEMBERSHIP PAYS, and there is NO fallthrough to a
87
+ // newer membership when the oldest one's credits are exhausted.
88
+ .sort((a, b) =>
89
+ (a.created_at ?? '') < (b.created_at ?? '') ? -1
90
+ : (a.created_at ?? '') > (b.created_at ?? '') ? 1
91
+ : a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
92
+ const entitledRows = rows.filter((m) => computeEntitlement(m, now));
93
+ const entitled = entitledRows[0];
94
+ if (entitledRows.length > 1) {
95
+ await logOps(supabase, 'membership_context_ambiguous',
96
+ { email_lower: emailKey, chosen_membership_id: entitled.id,
97
+ candidate_ids: entitledRows.map((m) => m.id) },
98
+ { severity: 'warning',
99
+ // Once-ever per email, forever: this runs on the UNAUTHENTICATED
100
+ // booking-pricing path (create-booking has verify_jwt=false and a
101
+ // client-supplied email), so an unkeyed emission here is an
102
+ // unbounded, anonymously-triggerable ops_events INSERT.
103
+ dedupeKey: 'ambiguous_membership:' + emailKey });
104
+ }
105
+ return {
106
+ isMember: !!entitled,
107
+ membershipId: entitled?.id ?? rows[0]?.id ?? null,
108
+ };
109
+ }
package/src/money.ts ADDED
@@ -0,0 +1,36 @@
1
+ /** Parse a money-ish value the exact same way everywhere. Never throws. */
2
+ export const centsFrom = (v: unknown): number => {
3
+ const n = Number(v);
4
+ if (!Number.isFinite(n)) return 0;
5
+ return Math.round(n * 100);
6
+ };
7
+
8
+ export type RetainerConfig =
9
+ | { ok: true; cents: number; waived: boolean }
10
+ | { ok: false; code: 'service_retainer_must_be_positive' | 'service_retainer_unparseable' | 'service_retainer_absent' };
11
+
12
+ /**
13
+ * The ONE place that decides "is this retainer positive, or a deliberately
14
+ * waived zero?" Fails closed: a blank, negative, or unparseable value is
15
+ * NEVER treated as zero, regardless of any waiver flag. `retainer_waived`
16
+ * must be exactly boolean true or string "true" -- anything else means "not
17
+ * waived." `service_retainer_absent` is distinct from `_must_be_positive` so
18
+ * callers where the field is optional (legacy checkout builder) can tell
19
+ * "not provided" apart from "provided but invalid."
20
+ */
21
+ export function parseRetainerConfig(v: Record<string, unknown>): RetainerConfig {
22
+ const raw = v.service_retainer;
23
+ if (raw === undefined || raw === null || String(raw).trim() === '') {
24
+ return { ok: false, code: 'service_retainer_absent' };
25
+ }
26
+ const n = Number(raw);
27
+ if (!Number.isFinite(n)) return { ok: false, code: 'service_retainer_unparseable' };
28
+ const cents = Math.round(n * 100);
29
+ if (cents < 0) return { ok: false, code: 'service_retainer_must_be_positive' };
30
+ if (cents === 0) {
31
+ const waived = v.retainer_waived === true || v.retainer_waived === 'true';
32
+ if (!waived) return { ok: false, code: 'service_retainer_must_be_positive' };
33
+ return { ok: true, cents: 0, waived: true };
34
+ }
35
+ return { ok: true, cents, waived: false };
36
+ }
package/src/ops.ts ADDED
@@ -0,0 +1,97 @@
1
+ import type { SupabaseClient } from 'npm:@supabase/supabase-js@2';
2
+
3
+ type SupabaseLike = SupabaseClient<any, any, any>;
4
+ type Severity = 'info' | 'warning' | 'error';
5
+
6
+ /**
7
+ * HARD CONTRACT: logOps NEVER THROWS. It returns
8
+ * `{ ok: true } | { ok: false, error }`; no caller may be written assuming it
9
+ * can throw. This is load-bearing, not stylistic: stripe-webhook's outer
10
+ * `catch` calls logOps BEFORE its `stripe_events` idempotency-ledger cleanup,
11
+ * so a throwing logOps would skip that cleanup, Stripe's retry would hit the
12
+ * ledger and receive `{received:true, duplicate:true}` / HTTP 200, and the
13
+ * event would be permanently and silently dropped on a money path.
14
+ *
15
+ * Every caller that emits a safeguard flag MUST check the returned `ok` and
16
+ * escalate on false — an unchecked emission is indistinguishable from
17
+ * "no problem found".
18
+ */
19
+ export async function logOps(
20
+ supabase: SupabaseLike,
21
+ kind: string,
22
+ detail: Record<string, unknown> = {},
23
+ opts: { severity?: Severity; bookingId?: string | null; dedupeKey?: string | null } = {},
24
+ ): Promise<{ ok: true } | { ok: false; error: string }> {
25
+ const severity: Severity = opts.severity ?? 'error';
26
+ const bookingId = opts.bookingId ?? null;
27
+ // `||` not `??`: an empty-string dedupeKey is not a real key. Treated as one
28
+ // it would collide with itself under ops_events_dedupe_key_uidx and, via
29
+ // ON CONFLICT DO NOTHING, silently swallow every subsequent emission.
30
+ const dedupeKey = opts.dedupeKey || null;
31
+ let outcome: { ok: true } | { ok: false; error: string } = { ok: true };
32
+
33
+ try {
34
+ console.error(JSON.stringify({ level: severity, kind, booking_id: bookingId, ...detail }));
35
+ } catch { /* ignore */ }
36
+
37
+ try {
38
+ // Cast: the generated Database types are not wired into edge functions,
39
+ // so the insert payload widens to `never` without it.
40
+ // `dedupe_key` has a unique partial index (WHERE dedupe_key IS NOT NULL).
41
+ // A 23505 on it does NOT throw — supabase-js resolves with { error } for
42
+ // a Postgres error, so the try/catch below is irrelevant to it and the
43
+ // returned error must be inspected instead. Callers that pass a dedupeKey
44
+ // WANT the collision, so it is the success case (see below).
45
+ const { error } = await supabase.from('ops_events').insert({
46
+ kind,
47
+ severity,
48
+ booking_id: bookingId,
49
+ detail,
50
+ ...(dedupeKey === null ? {} : { dedupe_key: dedupeKey }),
51
+ } as never);
52
+ // A dedupe_key collision under ops_events_dedupe_key_uidx is the SUCCESS
53
+ // case for a once-ever emission -- never report it as a failure.
54
+ if (error && (error as { code?: string }).code !== '23505') {
55
+ outcome = { ok: false, error: error.message };
56
+ }
57
+ } catch (e) { outcome = { ok: false, error: String(e) }; }
58
+
59
+ if (severity === 'error') {
60
+ const text = `:rotating_light: GC Connect *${kind}* — ${JSON.stringify(detail).slice(0, 500)}`;
61
+
62
+ const url = Deno.env.get('OPS_ALERT_WEBHOOK_URL');
63
+ if (url) {
64
+ try {
65
+ await fetch(url, {
66
+ method: 'POST',
67
+ headers: { 'Content-Type': 'application/json' },
68
+ body: JSON.stringify({ text }),
69
+ });
70
+ } catch { /* ignore */ }
71
+ }
72
+
73
+ // Slack fallback so error-severity events land somewhere staff actually
74
+ // look, not just an ops_events row. Same bot-token pattern the day-pass
75
+ // notifier already uses. No-op until OPS_ALERT_SLACK_CHANNEL_ID is set.
76
+ const slackToken = Deno.env.get('SLACK_BOT_TOKEN');
77
+ const slackChannel = Deno.env.get('OPS_ALERT_SLACK_CHANNEL_ID');
78
+ if (slackToken && slackChannel) {
79
+ try {
80
+ const res = await fetch('https://slack.com/api/chat.postMessage', {
81
+ method: 'POST',
82
+ headers: {
83
+ 'Content-Type': 'application/json; charset=utf-8',
84
+ Authorization: `Bearer ${slackToken}`,
85
+ },
86
+ body: JSON.stringify({ channel: slackChannel, text }),
87
+ });
88
+ const body = await res.json().catch(() => null);
89
+ if (!body?.ok) {
90
+ console.warn('[ops] slack chat.postMessage failed:', body?.error ?? `http_${res.status}`);
91
+ }
92
+ } catch { /* ignore */ }
93
+ }
94
+ }
95
+
96
+ return outcome;
97
+ }
@@ -0,0 +1,34 @@
1
+ // Pacific-calendar date helpers, extracted from
2
+ // create-subscription-checkout/index.ts (plan v13 §2.4 header, round-3 S3-1).
3
+ //
4
+ // These were private, unexported functions inside that file, so the migration
5
+ // plan's claim of "reusing" them was impossible without either duplicating
6
+ // them (drift risk) or modifying that file. Resolution: extract all three —
7
+ // both functions AND the MAX_START_DATE_DAYS constant (round-4 S4-2) —
8
+ // verbatim into this module; create-subscription-checkout now imports them
9
+ // from here in place of its own copies. That is a PURE REFACTOR: identical
10
+ // bodies, identical comments, nothing that function does changes.
11
+ //
12
+ // The migration checkout functions (migration-checkout-confirm /
13
+ // migration-checkout-redirect, via _shared/migrationStartDate.ts) import from
14
+ // the same place, which is what makes §2.4's "no clamp-vs-validation conflict"
15
+ // property literally true rather than merely intended.
16
+
17
+ // Stripe Checkout requires subscription_data.billing_cycle_anchor to fall within
18
+ // one billing period from now. These plans are always billing_interval 'month',
19
+ // so 27 days is a safe margin under the shortest possible month.
20
+ export const MAX_START_DATE_DAYS = 27;
21
+
22
+ // The window check is done on Pacific CALENDAR DATE STRINGS, not on instants vs
23
+ // a raw millisecond offset -- zero-padded YYYY-MM-DD sorts lexicographically =
24
+ // chronologically, so the client (which offers the same Pacific calendar days)
25
+ // and the server agree by construction rather than by coincidence.
26
+ export function pacificDateStr(d: Date): string {
27
+ return new Intl.DateTimeFormat('en-CA', {
28
+ timeZone: 'America/Los_Angeles', year: 'numeric', month: '2-digit', day: '2-digit',
29
+ }).format(d); // yields "YYYY-MM-DD"
30
+ }
31
+ export function addDaysStr(dateStr: string, days: number): string {
32
+ const [y, m, d] = dateStr.split('-').map(Number);
33
+ return new Date(Date.UTC(y, m - 1, d + days)).toISOString().slice(0, 10);
34
+ }
@@ -0,0 +1,50 @@
1
+ import { assertEquals } from 'https://deno.land/std@0.224.0/assert/mod.ts';
2
+ import { checkPolicyAcceptance, policyTextSha256 } from './policyAcknowledgment.ts';
3
+
4
+ // (a) No policy text on the room => never required, always ok, whatever the
5
+ // client sent. This is the OFF switch for every room that has not been given a
6
+ // checkout agreement.
7
+ Deno.test('checkPolicyAcceptance: null policy text is never required, ok regardless of the flag', () => {
8
+ for (const accepted of [undefined, false, true] as const) {
9
+ assertEquals(
10
+ checkPolicyAcceptance({ checkout_agreement_text: null }, accepted),
11
+ { required: false, ok: true },
12
+ );
13
+ }
14
+ });
15
+
16
+ // (b) Policy text present, acknowledgment missing or refused => gated.
17
+ Deno.test('checkPolicyAcceptance: policy text with a missing or false flag is required and not ok', () => {
18
+ assertEquals(
19
+ checkPolicyAcceptance({ checkout_agreement_text: 'No pets. Clean up.' }, undefined),
20
+ { required: true, ok: false },
21
+ );
22
+ assertEquals(
23
+ checkPolicyAcceptance({ checkout_agreement_text: 'No pets. Clean up.' }, false),
24
+ { required: true, ok: false },
25
+ );
26
+ });
27
+
28
+ // (c) Policy text present and explicitly accepted => gated but satisfied.
29
+ Deno.test('checkPolicyAcceptance: policy text with agreementAccepted=true is required and ok', () => {
30
+ assertEquals(
31
+ checkPolicyAcceptance({ checkout_agreement_text: 'No pets. Clean up.' }, true),
32
+ { required: true, ok: true },
33
+ );
34
+ });
35
+
36
+ // A whitespace-only column is an empty policy, not a policy nobody can satisfy.
37
+ Deno.test('checkPolicyAcceptance: whitespace-only policy text behaves like NULL', () => {
38
+ assertEquals(
39
+ checkPolicyAcceptance({ checkout_agreement_text: ' \n\t ' }, undefined),
40
+ { required: false, ok: true },
41
+ );
42
+ });
43
+
44
+ // Known-answer vector: `printf 'abc' | sha256sum`.
45
+ Deno.test('policyTextSha256: lowercase hex SHA-256 of the exact text bytes', async () => {
46
+ assertEquals(
47
+ await policyTextSha256('abc'),
48
+ 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad',
49
+ );
50
+ });
@@ -0,0 +1,96 @@
1
+ // Per-room checkout agreement ("room use policy") acknowledgment.
2
+ //
3
+ // SEPARATE MECHANISM from _shared/tier1Agreement.ts / public.booking_agreements
4
+ // (Tier 1 click-through, Tier 2-3 BoldSign) and from the Commons Event Contract
5
+ // tier-3 flow. Nothing in this file reads or writes booking_agreements,
6
+ // booking_contract_violations, or any BoldSign state, and nothing here gates
7
+ // door provisioning. It records one plain fact: at booking time the customer
8
+ // was shown this room's own free-text `rooms.checkout_agreement_text` and
9
+ // ticked the box. Do not merge the two mechanisms.
10
+ //
11
+ // The feature's off switch is NULL: a room with checkout_agreement_text IS NULL
12
+ // requires nothing and produces no acknowledgment row.
13
+
14
+ import type { SupabaseClient } from 'npm:@supabase/supabase-js@2';
15
+
16
+ // Loose generics, matching _shared/ops.ts and _shared/bookingEffects.ts — a
17
+ // real createClient(url, key) call is not assignable to the un-inferred
18
+ // ReturnType<typeof createClient> default.
19
+ // deno-lint-ignore no-explicit-any
20
+ type SupabaseLike = SupabaseClient<any, any, any>;
21
+
22
+ export interface RoomForPolicyAcknowledgment {
23
+ checkout_agreement_text: string | null;
24
+ }
25
+
26
+ export interface PolicyAcceptanceCheck {
27
+ /** True when this room has a policy at all, i.e. the box must be shown. */
28
+ required: boolean;
29
+ /** True when the request may proceed: not required, or required and accepted. */
30
+ ok: boolean;
31
+ }
32
+
33
+ /**
34
+ * Pure. The single authority on "does this booking need the room use policy
35
+ * ticked, and was it". A room with no policy text is never gated, whatever the
36
+ * client sent; a room with policy text is gated on an explicit `true` — an
37
+ * omitted, false, or non-boolean truthy value is a refusal, so a client that
38
+ * simply forgets the field can never book past the policy.
39
+ */
40
+ export function checkPolicyAcceptance(
41
+ room: RoomForPolicyAcknowledgment,
42
+ agreementAccepted: boolean | undefined,
43
+ ): PolicyAcceptanceCheck {
44
+ const text = room.checkout_agreement_text;
45
+ const required = typeof text === 'string' && text.trim().length > 0;
46
+ if (!required) return { required: false, ok: true };
47
+ return { required: true, ok: agreementAccepted === true };
48
+ }
49
+
50
+ /** Customer-facing 400 message for a failed check. */
51
+ export const POLICY_NOT_ACCEPTED_ERROR =
52
+ 'You must accept the room use policy to book this room.';
53
+
54
+ /**
55
+ * Hex SHA-256 of the policy text the customer actually ticked. Same Web Crypto
56
+ * pattern as tier1Agreement.ts's own content_sha256 (crypto.subtle.digest over
57
+ * the exact bytes, lowercase hex) so the two hashes are directly comparable by
58
+ * eye, even though the tables are unrelated.
59
+ */
60
+ export async function policyTextSha256(text: string): Promise<string> {
61
+ const bytes = new TextEncoder().encode(text);
62
+ const digest = await crypto.subtle.digest('SHA-256', bytes as unknown as BufferSource);
63
+ return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, '0')).join('');
64
+ }
65
+
66
+ export interface PolicyAcknowledgmentInput {
67
+ bookingId: string;
68
+ roomId: string;
69
+ /** The room's CURRENT checkout_agreement_text, hashed here — never client-supplied. */
70
+ agreementText: string;
71
+ acceptedEmail: string | null;
72
+ acceptedIp: string | null;
73
+ }
74
+
75
+ /**
76
+ * Records the acknowledgment. Returns the error message instead of throwing so
77
+ * the caller decides whether a failure is fatal — the booking itself is not
78
+ * legally dependent on this row (that is booking_agreements' job), so callers
79
+ * log rather than roll back.
80
+ */
81
+ export async function insertPolicyAcknowledgment(
82
+ supabase: SupabaseLike,
83
+ input: PolicyAcknowledgmentInput,
84
+ ): Promise<{ error: string | null }> {
85
+ const { error } = await supabase.from('booking_policy_acknowledgments').insert({
86
+ booking_id: input.bookingId,
87
+ room_id: input.roomId,
88
+ agreement_text_sha256: await policyTextSha256(input.agreementText),
89
+ accepted_at: new Date().toISOString(),
90
+ accepted_email: input.acceptedEmail,
91
+ // inet rejects the 'unknown' sentinel _shared/rateLimit.ts's clientIp()
92
+ // returns when no forwarding header is present — store NULL instead.
93
+ accepted_ip: input.acceptedIp && input.acceptedIp !== 'unknown' ? input.acceptedIp : null,
94
+ } as never);
95
+ return { error: error ? error.message : null };
96
+ }
@@ -0,0 +1,46 @@
1
+ // Second accepted auth mode for the customer-facing booking functions.
2
+ //
3
+ // The original mode — the HMAC manage token (`_shared/manageToken.ts`) — is
4
+ // unchanged and remains the emailed-link credential. This adds a parallel
5
+ // mode for signed-in member-portal sessions: an `Authorization: Bearer <jwt>`
6
+ // header verified against Supabase Auth with a service-role client. The
7
+ // verified email is then fed into the SAME contact_email equality check the
8
+ // token path already performs; no side-effect logic is forked.
9
+ import type { SupabaseClient } from 'npm:@supabase/supabase-js@2';
10
+
11
+ type SupabaseLike = SupabaseClient<any, any, any>;
12
+
13
+ /**
14
+ * Returns the verified auth user id AND email of the caller's portal session,
15
+ * or null when there is no bearer token or it doesn't validate.
16
+ */
17
+ export async function resolvePortalSession(
18
+ req: Request,
19
+ admin: SupabaseLike,
20
+ ): Promise<{ id: string; email: string } | null> {
21
+ const header = req.headers.get('Authorization') ?? '';
22
+ const m = header.match(/^Bearer\s+(.+)$/i);
23
+ if (!m) return null;
24
+ const jwt = m[1].trim();
25
+ if (!jwt) return null;
26
+ // The anon/publishable key is also sent as a bearer by supabase-js clients
27
+ // in some call shapes; getUser simply fails on it, which is what we want.
28
+ try {
29
+ const { data, error } = await admin.auth.getUser(jwt);
30
+ if (error || !data?.user?.email) return null;
31
+ return { id: data.user.id, email: data.user.email.toLowerCase() };
32
+ } catch (e) {
33
+ console.warn('[portalSession] getUser threw', e);
34
+ return null;
35
+ }
36
+ }
37
+
38
+ /**
39
+ * Back-compat wrapper: verified email only. Unchanged signature/behaviour.
40
+ */
41
+ export async function resolvePortalSessionEmail(
42
+ req: Request,
43
+ admin: SupabaseLike,
44
+ ): Promise<string | null> {
45
+ return (await resolvePortalSession(req, admin))?.email ?? null;
46
+ }