@simplelayer/graniteer-core 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +2 -2
- package/package.json +1 -1
- package/src/agreementCheckout.ts +250 -250
- package/src/agreementPortalEmail.ts +128 -128
- package/src/billingPortalLinkEmail.ts +117 -117
- package/src/bookingAgreementEmail.ts +149 -149
- package/src/bookingEffects.ts +388 -388
- package/src/busClient.ts +268 -268
- package/src/busSignature.ts +71 -71
- package/src/checkoutCoupon.test.ts +675 -675
- package/src/checkoutCoupon.ts +455 -455
- package/src/commonsDeposit.ts +298 -298
- package/src/commonsDepositWebhook.ts +237 -237
- package/src/dayPassConfirmation.ts +230 -230
- package/src/dunningEmails.test.ts +263 -263
- package/src/dunningEmails.ts +203 -203
- package/src/email-templates/brand.ts +93 -93
- package/src/email-templates/magic-link.tsx +59 -59
- package/src/email-templates/recovery.tsx +59 -59
- package/src/email-templates/signup.tsx +67 -67
- package/src/functions/admin-cancel-membership.ts +311 -311
- package/src/functions/admin-change-membership-plan.ts +312 -312
- package/src/functions/admin-charge-guest-print.ts +229 -229
- package/src/functions/admin-correct-booking.ts +333 -333
- package/src/functions/admin-create-booking.ts +460 -460
- package/src/functions/admin-create-commons-event.ts +244 -244
- package/src/functions/admin-debug-boldsign-doc.ts +93 -93
- package/src/functions/admin-door-write.ts +272 -272
- package/src/functions/admin-issue-day-pass.ts +231 -231
- package/src/functions/admin-mark-booking-paid.ts +203 -203
- package/src/functions/admin-mint-billing-portal-link.ts +168 -168
- package/src/functions/admin-mint-portal-link.ts +62 -62
- package/src/functions/admin-photo-upload.ts +128 -128
- package/src/functions/admin-remove-team-member.ts +150 -150
- package/src/functions/admin-request-trial.ts +366 -366
- package/src/functions/admin-resend-commons-deposit-link.ts +323 -323
- package/src/functions/admin-reset-mfa.ts +138 -138
- package/src/functions/admin-retry-invoice-payment.ts +333 -333
- package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
- package/src/functions/admin-revoke-agreement.ts +467 -467
- package/src/functions/admin-send-commons-agreement.ts +214 -214
- package/src/functions/admin-set-credit-amount.ts +123 -123
- package/src/functions/admin-skip-commons-contract.ts +165 -165
- package/src/functions/admin-undo-membership-cancel.ts +144 -144
- package/src/functions/admin-wall-photo-write.ts +141 -141
- package/src/functions/auth-email-hook.ts +259 -259
- package/src/functions/boldsign-sender-identity.ts +114 -114
- package/src/functions/booking-availability.ts +419 -419
- package/src/functions/booking-member-preview.ts +136 -136
- package/src/functions/booking-status.ts +149 -149
- package/src/functions/create-booking.ts +648 -648
- package/src/functions/create-day-pass-checkout.ts +218 -218
- package/src/functions/create-portal-session.ts +142 -142
- package/src/functions/create-subscription-checkout.test.ts +222 -222
- package/src/functions/create-subscription-checkout.ts +440 -440
- package/src/functions/day-pass-status.ts +89 -89
- package/src/functions/diag-webpush-test.ts +45 -45
- package/src/functions/event-access-admin.ts +277 -277
- package/src/functions/event-access-store.ts +334 -309
- package/src/functions/ezeep-print-webhook.ts +213 -213
- package/src/functions/ezeep-usage-reconcile.ts +299 -299
- package/src/functions/fetch-avatar-original.ts +457 -457
- package/src/functions/get-provider-sign-link.ts +155 -155
- package/src/functions/get-signing-link.ts +211 -211
- package/src/functions/guest-print-setup-confirm.ts +128 -128
- package/src/functions/guest-print-submit.ts +149 -149
- package/src/functions/luma-webhook.ts +165 -165
- package/src/functions/mcp.ts +67 -67
- package/src/functions/member-door-action.test.ts +1248 -1248
- package/src/functions/member-door-action.ts +863 -863
- package/src/functions/member-unifi-mapping.test.ts +516 -516
- package/src/functions/member-unifi-mapping.ts +206 -206
- package/src/functions/membership-door-sync.ts +956 -956
- package/src/functions/migration-collision-alert.copy.ts +232 -232
- package/src/functions/migration-collision-alert.test.ts +349 -349
- package/src/functions/migration-collision-alert.ts +232 -232
- package/src/functions/office-assignment-end.ts +146 -146
- package/src/functions/portal-booking-access.ts +217 -95
- package/src/functions/portal-list-invoices.ts +99 -99
- package/src/functions/portal-request-login.ts +219 -192
- package/src/functions/portal-resend-invite.ts +248 -248
- package/src/functions/portal-submit-event.ts +168 -168
- package/src/functions/print-billing-recover.ts +97 -97
- package/src/functions/print-billing-run.ts +183 -183
- package/src/functions/public-facts.ts +168 -168
- package/src/functions/push-send.ts +348 -348
- package/src/functions/push-test.ts +234 -234
- package/src/functions/request-portal-link.ts +211 -211
- package/src/functions/review-ratings.ts +113 -113
- package/src/functions/space-availability-range.acceptance.test.ts +161 -161
- package/src/functions/space-availability-range.ts +142 -142
- package/src/functions/stripe-db-reconcile.ts +319 -319
- package/src/functions/stripe-webhook.moved-regression.test.ts +78 -78
- package/src/functions/stripe-webhook.ts +2595 -2595
- package/src/functions/sync-gcal-blackouts.ts +298 -298
- package/src/functions/timetable-event-register.ts +162 -162
- package/src/functions/timetable-event-status.ts +90 -90
- package/src/functions/timetable-spaces.ts +219 -219
- package/src/functions/touch-pass-reconciler.ts +689 -689
- package/src/functions/touch-pass-signup.ts +478 -478
- package/src/functions/upload-booking-display-image.ts +179 -179
- package/src/functions/virtual-onboarding-purge.ts +134 -134
- package/src/functions/virtual-onboarding-submit.ts +315 -315
- package/src/functions/voice-booking.ts +453 -453
- package/src/functions/voice-day-pass.ts +346 -346
- package/src/functions/voice-inquiry.test.ts +301 -301
- package/src/functions/voice-inquiry.ts +198 -198
- package/src/functions/voice-membership-signup.ts +355 -355
- package/src/functions/voice-tour-availability.ts +204 -204
- package/src/functions/voice-tour-booking.ts +429 -429
- package/src/ghlEventInquiry.ts +143 -143
- package/src/mailArrivalEmail.ts +121 -121
- package/src/manageToken.ts +363 -363
- package/src/membershipBusClient.ts +537 -537
- package/src/membershipWelcome.ts +683 -683
- package/src/migrationCheckout.ts +366 -366
- package/src/paymentLinkEmail.ts +123 -123
- package/src/signedUnpaidReminderEmail.test.ts +246 -246
- package/src/signedUnpaidReminderEmail.ts +132 -132
- package/src/stripeCoworkingPortal.ts +91 -91
- package/src/supabaseTestFakes.ts +131 -131
- package/src/supportTicketEmail.ts +119 -119
- package/src/unifiAccessPolicies.ts +228 -228
- package/src/unifiGroups.ts +129 -129
|
@@ -1,237 +1,237 @@
|
|
|
1
|
-
// Tier 3 (Commons) "contract completed -> collect the 50% deposit" branch of
|
|
2
|
-
// the boldsign-webhook booking-agreement handler.
|
|
3
|
-
//
|
|
4
|
-
// Contract with the caller (bookingAgreementWebhook.ts):
|
|
5
|
-
// - returns { processed: true } -> caller may mark the boldsign_events row processed
|
|
6
|
-
// - returns { processed: false } -> caller MUST leave the ledger row unprocessed
|
|
7
|
-
// so the existing stale-row reprocessing retries the side effect.
|
|
8
|
-
// Either way the caller returns 200 to BoldSign.
|
|
9
|
-
import type { createClient, SupabaseClient } from 'npm:@supabase/supabase-js@2';
|
|
10
|
-
import Stripe from 'npm:stripe@17.5.0';
|
|
11
|
-
import { logOps } from './ops.ts';
|
|
12
|
-
import {
|
|
13
|
-
buildCommonsDepositSessionParams,
|
|
14
|
-
commonsDepositIdempotencyKey,
|
|
15
|
-
longDateFromIso,
|
|
16
|
-
longDateFromYmd,
|
|
17
|
-
sendCommonsDepositLinkEmail,
|
|
18
|
-
type CommonsSnapshot,
|
|
19
|
-
} from './commonsDeposit.ts';
|
|
20
|
-
|
|
21
|
-
type Supa = SupabaseClient<any, 'public', any>;
|
|
22
|
-
|
|
23
|
-
const HOLD_EXTENSION_MS = 7 * 24 * 60 * 60 * 1000;
|
|
24
|
-
|
|
25
|
-
export interface CommonsAgreementRow {
|
|
26
|
-
id: string;
|
|
27
|
-
booking_id: string;
|
|
28
|
-
signer_email: string | null;
|
|
29
|
-
signer_name: string | null;
|
|
30
|
-
metadata: Record<string, unknown> | null;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
export interface CommonsBookingRow {
|
|
34
|
-
id: string;
|
|
35
|
-
status: string;
|
|
36
|
-
deposit_amount_cents: number | null;
|
|
37
|
-
list_amount_cents: number | null;
|
|
38
|
-
hold_expires_at: string | null;
|
|
39
|
-
contact_email: string | null;
|
|
40
|
-
contact_name: string | null;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export interface CommonsDepositOutcome {
|
|
44
|
-
processed: boolean;
|
|
45
|
-
result: string;
|
|
46
|
-
detail?: Record<string, unknown>;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
async function fail(
|
|
50
|
-
supabase: Supa,
|
|
51
|
-
agreementId: string,
|
|
52
|
-
bookingId: string,
|
|
53
|
-
kind: string,
|
|
54
|
-
message: string,
|
|
55
|
-
detail: Record<string, unknown>,
|
|
56
|
-
): Promise<CommonsDepositOutcome> {
|
|
57
|
-
await supabase.from('booking_agreements')
|
|
58
|
-
.update({ last_error: message.slice(0, 500) })
|
|
59
|
-
.eq('id', agreementId);
|
|
60
|
-
await logOps(supabase, kind, { agreement_id: agreementId, ...detail },
|
|
61
|
-
{ severity: 'error', bookingId }).catch(() => {});
|
|
62
|
-
return { processed: false, result: kind, detail };
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
/**
|
|
66
|
-
* Runs on a genuine tier-3 `Completed` transition. Never throws.
|
|
67
|
-
*/
|
|
68
|
-
export async function handleCommonsDepositCompleted(
|
|
69
|
-
supabase: Supa,
|
|
70
|
-
agreement: CommonsAgreementRow,
|
|
71
|
-
booking: CommonsBookingRow | null,
|
|
72
|
-
opts: {
|
|
73
|
-
baseUrl?: string;
|
|
74
|
-
defaultBaseUrl: string;
|
|
75
|
-
operator: { name: string; shortName: string; supportEmail: string };
|
|
76
|
-
staffCc: string[];
|
|
77
|
-
},
|
|
78
|
-
): Promise<CommonsDepositOutcome> {
|
|
79
|
-
const bookingId = String(agreement.booking_id);
|
|
80
|
-
|
|
81
|
-
if (!booking) {
|
|
82
|
-
return await fail(supabase, agreement.id, bookingId, 'commons_deposit_session_failed',
|
|
83
|
-
'booking_not_found', { reason: 'booking_not_found' });
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
// Guard 1 — only a live hold gets a deposit link. Anything else (already
|
|
87
|
-
// deposit_paid, cancelled, expired) is a no-op with no side effects.
|
|
88
|
-
if (booking.status !== 'pending') {
|
|
89
|
-
console.log(`[commons-deposit] booking ${bookingId} status=${booking.status} — skipping deposit session`);
|
|
90
|
-
return { processed: true, result: 'booking_not_pending', detail: { status: booking.status } };
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
const deposit = booking.deposit_amount_cents;
|
|
94
|
-
if (deposit == null || !Number.isFinite(Number(deposit)) || Number(deposit) <= 0) {
|
|
95
|
-
// Never guess an amount.
|
|
96
|
-
return await fail(supabase, agreement.id, bookingId, 'commons_deposit_amount_missing',
|
|
97
|
-
'deposit_amount_missing', { deposit_amount_cents: deposit });
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
const snapshot = ((agreement.metadata ?? {}) as Record<string, unknown>).commons as
|
|
101
|
-
| CommonsSnapshot
|
|
102
|
-
| undefined;
|
|
103
|
-
if (!snapshot) {
|
|
104
|
-
return await fail(supabase, agreement.id, bookingId, 'commons_deposit_amount_drift',
|
|
105
|
-
'commons_snapshot_missing', { reason: 'metadata_commons_missing' });
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
// Tamper check — the money on the booking must still match what the signed
|
|
109
|
-
// document says. Any drift means the document and the charge disagree: stop.
|
|
110
|
-
const totalCents = Number(booking.list_amount_cents ?? -1);
|
|
111
|
-
if (Number(deposit) !== Number(snapshot.deposit_cents) ||
|
|
112
|
-
totalCents !== Number(snapshot.total_cents)) {
|
|
113
|
-
return await fail(supabase, agreement.id, bookingId, 'commons_deposit_amount_drift',
|
|
114
|
-
'commons_amount_drift', {
|
|
115
|
-
booking_deposit_cents: Number(deposit),
|
|
116
|
-
snapshot_deposit_cents: snapshot.deposit_cents ?? null,
|
|
117
|
-
booking_total_cents: totalCents,
|
|
118
|
-
snapshot_total_cents: snapshot.total_cents ?? null,
|
|
119
|
-
});
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
const depositCents = Number(deposit);
|
|
123
|
-
const balanceCents = Number(snapshot.balance_cents ?? Math.max(0, totalCents - depositCents));
|
|
124
|
-
const eventDateLabel = longDateFromYmd(snapshot.event_date) ??
|
|
125
|
-
longDateFromIso(snapshot.arrival_at) ?? 'your event date';
|
|
126
|
-
const balanceDueLabel = longDateFromYmd(snapshot.balance_due_date) ??
|
|
127
|
-
'the date shown in your agreement';
|
|
128
|
-
|
|
129
|
-
const signerEmail = String(agreement.signer_email ?? booking.contact_email ?? '').trim();
|
|
130
|
-
if (!signerEmail) {
|
|
131
|
-
return await fail(supabase, agreement.id, bookingId, 'commons_deposit_session_failed',
|
|
132
|
-
'signer_email_missing', { reason: 'signer_email_missing' });
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
const base = opts.baseUrl ?? opts.defaultBaseUrl;
|
|
136
|
-
const params = buildCommonsDepositSessionParams({
|
|
137
|
-
bookingId,
|
|
138
|
-
agreementId: String(agreement.id),
|
|
139
|
-
signerEmail,
|
|
140
|
-
depositCents,
|
|
141
|
-
totalCents,
|
|
142
|
-
balanceCents,
|
|
143
|
-
eventDateLabel,
|
|
144
|
-
balanceDueLabel,
|
|
145
|
-
successUrl: `${base}/booking/confirmation?session_id={CHECKOUT_SESSION_ID}`,
|
|
146
|
-
cancelUrl: `${base}/contact?commons_deposit=canceled`,
|
|
147
|
-
});
|
|
148
|
-
const idempotencyKey = commonsDepositIdempotencyKey(bookingId);
|
|
149
|
-
|
|
150
|
-
// Dry-run escape hatch used during staged rollout / verification: log the
|
|
151
|
-
// exact payload that WOULD be sent and take no live Stripe action.
|
|
152
|
-
if (Deno.env.get('COMMONS_DEPOSIT_DRY_RUN') === '1') {
|
|
153
|
-
console.log('[commons-deposit][dry-run] checkout.sessions.create',
|
|
154
|
-
JSON.stringify({ params, idempotencyKey }));
|
|
155
|
-
return { processed: false, result: 'dry_run', detail: { idempotency_key: idempotencyKey } };
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
|
|
159
|
-
if (!stripeKey) {
|
|
160
|
-
return await fail(supabase, agreement.id, bookingId, 'commons_deposit_session_failed',
|
|
161
|
-
'stripe_not_configured', { reason: 'stripe_not_configured' });
|
|
162
|
-
}
|
|
163
|
-
const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
|
|
164
|
-
|
|
165
|
-
let session: Stripe.Checkout.Session;
|
|
166
|
-
try {
|
|
167
|
-
session = await stripe.checkout.sessions.create(params, { idempotencyKey });
|
|
168
|
-
} catch (e) {
|
|
169
|
-
return await fail(supabase, agreement.id, bookingId, 'commons_deposit_session_failed',
|
|
170
|
-
e instanceof Error ? e.message : String(e), { step: 'checkout_session_create' });
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
// CAS: only claim the session slot while it is still empty, so a concurrent
|
|
174
|
-
// invocation cannot overwrite an already-persisted session id.
|
|
175
|
-
const { data: claimed } = await supabase
|
|
176
|
-
.from('bookings')
|
|
177
|
-
.update({ stripe_session_id: session.id })
|
|
178
|
-
.eq('id', bookingId)
|
|
179
|
-
.is('stripe_session_id', null)
|
|
180
|
-
.select('id')
|
|
181
|
-
.maybeSingle();
|
|
182
|
-
if (!claimed) {
|
|
183
|
-
console.log(`[commons-deposit] booking ${bookingId} already had a stripe_session_id — keeping the existing one`);
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
// Relative extension only — never shrink a hold that is already longer.
|
|
187
|
-
const target = new Date(Date.now() + HOLD_EXTENSION_MS);
|
|
188
|
-
const currentHold = booking.hold_expires_at ? new Date(booking.hold_expires_at) : null;
|
|
189
|
-
const extended = currentHold && currentHold.getTime() > target.getTime() ? currentHold : target;
|
|
190
|
-
await supabase.from('bookings')
|
|
191
|
-
.update({ hold_expires_at: extended.toISOString() })
|
|
192
|
-
.eq('id', bookingId)
|
|
193
|
-
.eq('status', 'pending');
|
|
194
|
-
|
|
195
|
-
// CAS-guarded send authorization: the same conditional update that stamps
|
|
196
|
-
// deposit_link_email_sent_at is what grants the right to send.
|
|
197
|
-
const claimTs = new Date().toISOString();
|
|
198
|
-
const { data: emailClaim } = await supabase
|
|
199
|
-
.from('booking_agreements')
|
|
200
|
-
.update({ deposit_link_email_sent_at: claimTs })
|
|
201
|
-
.eq('id', agreement.id)
|
|
202
|
-
.is('deposit_link_email_sent_at', null)
|
|
203
|
-
.select('id')
|
|
204
|
-
.maybeSingle();
|
|
205
|
-
|
|
206
|
-
if (emailClaim) {
|
|
207
|
-
const outcome = await sendCommonsDepositLinkEmail(supabase, {
|
|
208
|
-
email: signerEmail,
|
|
209
|
-
name: agreement.signer_name ?? booking.contact_name ?? null,
|
|
210
|
-
checkoutUrl: String(session.url ?? ''),
|
|
211
|
-
eventDateLabel,
|
|
212
|
-
depositCents,
|
|
213
|
-
balanceCents,
|
|
214
|
-
balanceDueLabel,
|
|
215
|
-
bookingId,
|
|
216
|
-
}, opts.operator, opts.staffCc).catch((e) => {
|
|
217
|
-
console.error('[commons-deposit] deposit link email threw', e);
|
|
218
|
-
return 'failed_permanent' as const;
|
|
219
|
-
});
|
|
220
|
-
|
|
221
|
-
if (outcome !== 'sent') {
|
|
222
|
-
// Release the claim so a retry can send, and leave the ledger unprocessed.
|
|
223
|
-
await supabase.from('booking_agreements')
|
|
224
|
-
.update({ deposit_link_email_sent_at: null })
|
|
225
|
-
.eq('id', agreement.id)
|
|
226
|
-
.eq('deposit_link_email_sent_at', claimTs);
|
|
227
|
-
return await fail(supabase, agreement.id, bookingId, 'commons_deposit_session_failed',
|
|
228
|
-
`deposit_link_email_${outcome}`, { step: 'deposit_link_email', session_id: session.id });
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
return {
|
|
233
|
-
processed: true,
|
|
234
|
-
result: 'deposit_session_created',
|
|
235
|
-
detail: { session_id: session.id, deposit_cents: depositCents },
|
|
236
|
-
};
|
|
237
|
-
}
|
|
1
|
+
// Tier 3 (Commons) "contract completed -> collect the 50% deposit" branch of
|
|
2
|
+
// the boldsign-webhook booking-agreement handler.
|
|
3
|
+
//
|
|
4
|
+
// Contract with the caller (bookingAgreementWebhook.ts):
|
|
5
|
+
// - returns { processed: true } -> caller may mark the boldsign_events row processed
|
|
6
|
+
// - returns { processed: false } -> caller MUST leave the ledger row unprocessed
|
|
7
|
+
// so the existing stale-row reprocessing retries the side effect.
|
|
8
|
+
// Either way the caller returns 200 to BoldSign.
|
|
9
|
+
import type { createClient, SupabaseClient } from 'npm:@supabase/supabase-js@2';
|
|
10
|
+
import Stripe from 'npm:stripe@17.5.0';
|
|
11
|
+
import { logOps } from './ops.ts';
|
|
12
|
+
import {
|
|
13
|
+
buildCommonsDepositSessionParams,
|
|
14
|
+
commonsDepositIdempotencyKey,
|
|
15
|
+
longDateFromIso,
|
|
16
|
+
longDateFromYmd,
|
|
17
|
+
sendCommonsDepositLinkEmail,
|
|
18
|
+
type CommonsSnapshot,
|
|
19
|
+
} from './commonsDeposit.ts';
|
|
20
|
+
|
|
21
|
+
type Supa = SupabaseClient<any, 'public', any>;
|
|
22
|
+
|
|
23
|
+
const HOLD_EXTENSION_MS = 7 * 24 * 60 * 60 * 1000;
|
|
24
|
+
|
|
25
|
+
export interface CommonsAgreementRow {
|
|
26
|
+
id: string;
|
|
27
|
+
booking_id: string;
|
|
28
|
+
signer_email: string | null;
|
|
29
|
+
signer_name: string | null;
|
|
30
|
+
metadata: Record<string, unknown> | null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface CommonsBookingRow {
|
|
34
|
+
id: string;
|
|
35
|
+
status: string;
|
|
36
|
+
deposit_amount_cents: number | null;
|
|
37
|
+
list_amount_cents: number | null;
|
|
38
|
+
hold_expires_at: string | null;
|
|
39
|
+
contact_email: string | null;
|
|
40
|
+
contact_name: string | null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface CommonsDepositOutcome {
|
|
44
|
+
processed: boolean;
|
|
45
|
+
result: string;
|
|
46
|
+
detail?: Record<string, unknown>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function fail(
|
|
50
|
+
supabase: Supa,
|
|
51
|
+
agreementId: string,
|
|
52
|
+
bookingId: string,
|
|
53
|
+
kind: string,
|
|
54
|
+
message: string,
|
|
55
|
+
detail: Record<string, unknown>,
|
|
56
|
+
): Promise<CommonsDepositOutcome> {
|
|
57
|
+
await supabase.from('booking_agreements')
|
|
58
|
+
.update({ last_error: message.slice(0, 500) })
|
|
59
|
+
.eq('id', agreementId);
|
|
60
|
+
await logOps(supabase, kind, { agreement_id: agreementId, ...detail },
|
|
61
|
+
{ severity: 'error', bookingId }).catch(() => {});
|
|
62
|
+
return { processed: false, result: kind, detail };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Runs on a genuine tier-3 `Completed` transition. Never throws.
|
|
67
|
+
*/
|
|
68
|
+
export async function handleCommonsDepositCompleted(
|
|
69
|
+
supabase: Supa,
|
|
70
|
+
agreement: CommonsAgreementRow,
|
|
71
|
+
booking: CommonsBookingRow | null,
|
|
72
|
+
opts: {
|
|
73
|
+
baseUrl?: string;
|
|
74
|
+
defaultBaseUrl: string;
|
|
75
|
+
operator: { name: string; shortName: string; supportEmail: string };
|
|
76
|
+
staffCc: string[];
|
|
77
|
+
},
|
|
78
|
+
): Promise<CommonsDepositOutcome> {
|
|
79
|
+
const bookingId = String(agreement.booking_id);
|
|
80
|
+
|
|
81
|
+
if (!booking) {
|
|
82
|
+
return await fail(supabase, agreement.id, bookingId, 'commons_deposit_session_failed',
|
|
83
|
+
'booking_not_found', { reason: 'booking_not_found' });
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Guard 1 — only a live hold gets a deposit link. Anything else (already
|
|
87
|
+
// deposit_paid, cancelled, expired) is a no-op with no side effects.
|
|
88
|
+
if (booking.status !== 'pending') {
|
|
89
|
+
console.log(`[commons-deposit] booking ${bookingId} status=${booking.status} — skipping deposit session`);
|
|
90
|
+
return { processed: true, result: 'booking_not_pending', detail: { status: booking.status } };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const deposit = booking.deposit_amount_cents;
|
|
94
|
+
if (deposit == null || !Number.isFinite(Number(deposit)) || Number(deposit) <= 0) {
|
|
95
|
+
// Never guess an amount.
|
|
96
|
+
return await fail(supabase, agreement.id, bookingId, 'commons_deposit_amount_missing',
|
|
97
|
+
'deposit_amount_missing', { deposit_amount_cents: deposit });
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const snapshot = ((agreement.metadata ?? {}) as Record<string, unknown>).commons as
|
|
101
|
+
| CommonsSnapshot
|
|
102
|
+
| undefined;
|
|
103
|
+
if (!snapshot) {
|
|
104
|
+
return await fail(supabase, agreement.id, bookingId, 'commons_deposit_amount_drift',
|
|
105
|
+
'commons_snapshot_missing', { reason: 'metadata_commons_missing' });
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Tamper check — the money on the booking must still match what the signed
|
|
109
|
+
// document says. Any drift means the document and the charge disagree: stop.
|
|
110
|
+
const totalCents = Number(booking.list_amount_cents ?? -1);
|
|
111
|
+
if (Number(deposit) !== Number(snapshot.deposit_cents) ||
|
|
112
|
+
totalCents !== Number(snapshot.total_cents)) {
|
|
113
|
+
return await fail(supabase, agreement.id, bookingId, 'commons_deposit_amount_drift',
|
|
114
|
+
'commons_amount_drift', {
|
|
115
|
+
booking_deposit_cents: Number(deposit),
|
|
116
|
+
snapshot_deposit_cents: snapshot.deposit_cents ?? null,
|
|
117
|
+
booking_total_cents: totalCents,
|
|
118
|
+
snapshot_total_cents: snapshot.total_cents ?? null,
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const depositCents = Number(deposit);
|
|
123
|
+
const balanceCents = Number(snapshot.balance_cents ?? Math.max(0, totalCents - depositCents));
|
|
124
|
+
const eventDateLabel = longDateFromYmd(snapshot.event_date) ??
|
|
125
|
+
longDateFromIso(snapshot.arrival_at) ?? 'your event date';
|
|
126
|
+
const balanceDueLabel = longDateFromYmd(snapshot.balance_due_date) ??
|
|
127
|
+
'the date shown in your agreement';
|
|
128
|
+
|
|
129
|
+
const signerEmail = String(agreement.signer_email ?? booking.contact_email ?? '').trim();
|
|
130
|
+
if (!signerEmail) {
|
|
131
|
+
return await fail(supabase, agreement.id, bookingId, 'commons_deposit_session_failed',
|
|
132
|
+
'signer_email_missing', { reason: 'signer_email_missing' });
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const base = opts.baseUrl ?? opts.defaultBaseUrl;
|
|
136
|
+
const params = buildCommonsDepositSessionParams({
|
|
137
|
+
bookingId,
|
|
138
|
+
agreementId: String(agreement.id),
|
|
139
|
+
signerEmail,
|
|
140
|
+
depositCents,
|
|
141
|
+
totalCents,
|
|
142
|
+
balanceCents,
|
|
143
|
+
eventDateLabel,
|
|
144
|
+
balanceDueLabel,
|
|
145
|
+
successUrl: `${base}/booking/confirmation?session_id={CHECKOUT_SESSION_ID}`,
|
|
146
|
+
cancelUrl: `${base}/contact?commons_deposit=canceled`,
|
|
147
|
+
});
|
|
148
|
+
const idempotencyKey = commonsDepositIdempotencyKey(bookingId);
|
|
149
|
+
|
|
150
|
+
// Dry-run escape hatch used during staged rollout / verification: log the
|
|
151
|
+
// exact payload that WOULD be sent and take no live Stripe action.
|
|
152
|
+
if (Deno.env.get('COMMONS_DEPOSIT_DRY_RUN') === '1') {
|
|
153
|
+
console.log('[commons-deposit][dry-run] checkout.sessions.create',
|
|
154
|
+
JSON.stringify({ params, idempotencyKey }));
|
|
155
|
+
return { processed: false, result: 'dry_run', detail: { idempotency_key: idempotencyKey } };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
|
|
159
|
+
if (!stripeKey) {
|
|
160
|
+
return await fail(supabase, agreement.id, bookingId, 'commons_deposit_session_failed',
|
|
161
|
+
'stripe_not_configured', { reason: 'stripe_not_configured' });
|
|
162
|
+
}
|
|
163
|
+
const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
|
|
164
|
+
|
|
165
|
+
let session: Stripe.Checkout.Session;
|
|
166
|
+
try {
|
|
167
|
+
session = await stripe.checkout.sessions.create(params, { idempotencyKey });
|
|
168
|
+
} catch (e) {
|
|
169
|
+
return await fail(supabase, agreement.id, bookingId, 'commons_deposit_session_failed',
|
|
170
|
+
e instanceof Error ? e.message : String(e), { step: 'checkout_session_create' });
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// CAS: only claim the session slot while it is still empty, so a concurrent
|
|
174
|
+
// invocation cannot overwrite an already-persisted session id.
|
|
175
|
+
const { data: claimed } = await supabase
|
|
176
|
+
.from('bookings')
|
|
177
|
+
.update({ stripe_session_id: session.id })
|
|
178
|
+
.eq('id', bookingId)
|
|
179
|
+
.is('stripe_session_id', null)
|
|
180
|
+
.select('id')
|
|
181
|
+
.maybeSingle();
|
|
182
|
+
if (!claimed) {
|
|
183
|
+
console.log(`[commons-deposit] booking ${bookingId} already had a stripe_session_id — keeping the existing one`);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Relative extension only — never shrink a hold that is already longer.
|
|
187
|
+
const target = new Date(Date.now() + HOLD_EXTENSION_MS);
|
|
188
|
+
const currentHold = booking.hold_expires_at ? new Date(booking.hold_expires_at) : null;
|
|
189
|
+
const extended = currentHold && currentHold.getTime() > target.getTime() ? currentHold : target;
|
|
190
|
+
await supabase.from('bookings')
|
|
191
|
+
.update({ hold_expires_at: extended.toISOString() })
|
|
192
|
+
.eq('id', bookingId)
|
|
193
|
+
.eq('status', 'pending');
|
|
194
|
+
|
|
195
|
+
// CAS-guarded send authorization: the same conditional update that stamps
|
|
196
|
+
// deposit_link_email_sent_at is what grants the right to send.
|
|
197
|
+
const claimTs = new Date().toISOString();
|
|
198
|
+
const { data: emailClaim } = await supabase
|
|
199
|
+
.from('booking_agreements')
|
|
200
|
+
.update({ deposit_link_email_sent_at: claimTs })
|
|
201
|
+
.eq('id', agreement.id)
|
|
202
|
+
.is('deposit_link_email_sent_at', null)
|
|
203
|
+
.select('id')
|
|
204
|
+
.maybeSingle();
|
|
205
|
+
|
|
206
|
+
if (emailClaim) {
|
|
207
|
+
const outcome = await sendCommonsDepositLinkEmail(supabase, {
|
|
208
|
+
email: signerEmail,
|
|
209
|
+
name: agreement.signer_name ?? booking.contact_name ?? null,
|
|
210
|
+
checkoutUrl: String(session.url ?? ''),
|
|
211
|
+
eventDateLabel,
|
|
212
|
+
depositCents,
|
|
213
|
+
balanceCents,
|
|
214
|
+
balanceDueLabel,
|
|
215
|
+
bookingId,
|
|
216
|
+
}, opts.operator, opts.staffCc).catch((e) => {
|
|
217
|
+
console.error('[commons-deposit] deposit link email threw', e);
|
|
218
|
+
return 'failed_permanent' as const;
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
if (outcome !== 'sent') {
|
|
222
|
+
// Release the claim so a retry can send, and leave the ledger unprocessed.
|
|
223
|
+
await supabase.from('booking_agreements')
|
|
224
|
+
.update({ deposit_link_email_sent_at: null })
|
|
225
|
+
.eq('id', agreement.id)
|
|
226
|
+
.eq('deposit_link_email_sent_at', claimTs);
|
|
227
|
+
return await fail(supabase, agreement.id, bookingId, 'commons_deposit_session_failed',
|
|
228
|
+
`deposit_link_email_${outcome}`, { step: 'deposit_link_email', session_id: session.id });
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
return {
|
|
233
|
+
processed: true,
|
|
234
|
+
result: 'deposit_session_created',
|
|
235
|
+
detail: { session_id: session.id, deposit_cents: depositCents },
|
|
236
|
+
};
|
|
237
|
+
}
|