@simplelayer/graniteer-core 0.2.1 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 -334
- 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 -217
- 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
package/src/dunningEmails.ts
CHANGED
|
@@ -1,203 +1,203 @@
|
|
|
1
|
-
// Payment-failed dunning sequence: 3 emails riding the existing 5-day
|
|
2
|
-
// pricing_grace_ends_at window that stripe-webhook/index.ts opens on
|
|
3
|
-
// past_due/canceled/unpaid (see membership.ts's computeEntitlement -- the
|
|
4
|
-
// grace end flips both member pricing AND door/WiFi access off via
|
|
5
|
-
// membership-door-sync; this module changes none of that timing).
|
|
6
|
-
//
|
|
7
|
-
// Follows membershipWelcome.ts's exact GHL upsert+send pattern. esc() and
|
|
8
|
-
// classifyError() are reused verbatim (byte-identical) from that file.
|
|
9
|
-
//
|
|
10
|
-
// Stage naming:
|
|
11
|
-
// grace_start -- fired directly from stripe-webhook the instant the grace
|
|
12
|
-
// window is first opened. NOT decided by stageForGraceWindow
|
|
13
|
-
// below -- see stripe-webhook/index.ts's
|
|
14
|
-
// `isRevoked && !wasRevoked` branch.
|
|
15
|
-
// day_3 -- <=2 days remaining in the grace window.
|
|
16
|
-
// final_notice -- <=1 day remaining.
|
|
17
|
-
|
|
18
|
-
import type { SupabaseClient } from 'npm:@supabase/supabase-js@2';
|
|
19
|
-
import { logOps } from './ops.ts';
|
|
20
|
-
|
|
21
|
-
type SupabaseLike = SupabaseClient<any, 'public', any>;
|
|
22
|
-
|
|
23
|
-
export type DunningStage = 'grace_start' | 'day_3' | 'final_notice';
|
|
24
|
-
export type DunningResult = 'sent' | 'skipped' | 'failed_retryable' | 'failed_permanent';
|
|
25
|
-
|
|
26
|
-
/** Escape untrusted values interpolated into outbound HTML. Identical to membershipWelcome.ts's esc(). */
|
|
27
|
-
function esc(v: unknown): string {
|
|
28
|
-
return String(v ?? '')
|
|
29
|
-
.replace(/&/g, '&')
|
|
30
|
-
.replace(/</g, '<')
|
|
31
|
-
.replace(/>/g, '>')
|
|
32
|
-
.replace(/"/g, '"')
|
|
33
|
-
.replace(/'/g, ''');
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
/** Classify a caught error as transient (worth another event) or hopeless. Identical to membershipWelcome.ts's classifyError(). */
|
|
37
|
-
function classifyError(e: unknown): 'failed_retryable' | 'failed_permanent' {
|
|
38
|
-
const name = e instanceof Error ? e.name : '';
|
|
39
|
-
if (name === 'AbortError' || name === 'TimeoutError') return 'failed_retryable';
|
|
40
|
-
const msg = e instanceof Error ? e.message : String(e);
|
|
41
|
-
const m = msg.match(/^ghl_(?:upsert|email)_(\d{3})/);
|
|
42
|
-
if (m) {
|
|
43
|
-
const code = Number(m[1]);
|
|
44
|
-
if (code === 429 || code >= 500) return 'failed_retryable';
|
|
45
|
-
}
|
|
46
|
-
return 'failed_permanent';
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* Pure day-band classifier for the dunning cadence. Given the grace window's
|
|
51
|
-
* end instant and "now", decides which of the two LATER stages is due:
|
|
52
|
-
*
|
|
53
|
-
* <= 1 day remaining -> 'final_notice'
|
|
54
|
-
* <= 2 days remaining -> 'day_3'
|
|
55
|
-
* otherwise -> null (too early; grace_start already covers day 0
|
|
56
|
-
* and fires from stripe-webhook directly, not here)
|
|
57
|
-
*
|
|
58
|
-
* Boundaries are inclusive of "<=" so a row checked exactly at the 1-day or
|
|
59
|
-
* 2-day mark is not skipped by a daily cron's timing jitter. An unparsable
|
|
60
|
-
* graceEndsAtIso returns null (fail closed -- never guess a stage).
|
|
61
|
-
*/
|
|
62
|
-
export function stageForGraceWindow(
|
|
63
|
-
graceEndsAtIso: string,
|
|
64
|
-
now: Date = new Date(),
|
|
65
|
-
): DunningStage | null {
|
|
66
|
-
const endMs = Date.parse(graceEndsAtIso);
|
|
67
|
-
if (!Number.isFinite(endMs)) return null;
|
|
68
|
-
const ONE_DAY_MS = 24 * 60 * 60 * 1000;
|
|
69
|
-
const msRemaining = endMs - now.getTime();
|
|
70
|
-
if (msRemaining <= ONE_DAY_MS) return 'final_notice';
|
|
71
|
-
if (msRemaining <= 2 * ONE_DAY_MS) return 'day_3';
|
|
72
|
-
return null;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
/**
|
|
76
|
-
* Pure skip-logic for dunning-email-check's per-row loop: a stage is only
|
|
77
|
-
* ever sent once. Extracted out of the Deno.serve handler (which cannot be
|
|
78
|
-
* unit-tested in isolation without a live network/DB) so this decision is
|
|
79
|
-
* independently testable. `stage: null` (too early for either later stage --
|
|
80
|
-
* see stageForGraceWindow) always means "don't send".
|
|
81
|
-
*/
|
|
82
|
-
export function shouldSendDunningStage(
|
|
83
|
-
stage: DunningStage | null,
|
|
84
|
-
dunningEmailsSent: Record<string, boolean> | null | undefined,
|
|
85
|
-
): boolean {
|
|
86
|
-
if (!stage) return false;
|
|
87
|
-
return dunningEmailsSent?.[stage] !== true;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
function stageCopy(stage: DunningStage, endLabel: string, p: (t: string) => string) {
|
|
91
|
-
if (stage === 'grace_start') {
|
|
92
|
-
return {
|
|
93
|
-
subject: `We couldn't process your payment -- action needed by ${endLabel}`,
|
|
94
|
-
bodyLines: [
|
|
95
|
-
p(`We were unable to process your most recent membership payment.`),
|
|
96
|
-
p(`Please update your payment method before <strong>${esc(endLabel)}</strong> to keep your door and WiFi access active. No action is needed if you've already fixed this.`),
|
|
97
|
-
],
|
|
98
|
-
};
|
|
99
|
-
}
|
|
100
|
-
if (stage === 'day_3') {
|
|
101
|
-
return {
|
|
102
|
-
subject: `Reminder: update your payment by ${endLabel}`,
|
|
103
|
-
bodyLines: [
|
|
104
|
-
p(`This is a reminder that your membership payment is still unresolved.`),
|
|
105
|
-
p(`Your door and WiFi access will be turned off on <strong>${esc(endLabel)}</strong> if payment isn't updated before then.`),
|
|
106
|
-
],
|
|
107
|
-
};
|
|
108
|
-
}
|
|
109
|
-
return {
|
|
110
|
-
subject: `Final notice: access ends ${endLabel}`,
|
|
111
|
-
bodyLines: [
|
|
112
|
-
p(`This is a final notice -- your membership payment is still unresolved.`),
|
|
113
|
-
p(`Your door and WiFi access will be turned off on <strong>${esc(endLabel)}</strong> unless payment is updated before then.`),
|
|
114
|
-
],
|
|
115
|
-
};
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
/**
|
|
119
|
-
* Send one dunning-sequence email via GHL (contacts/upsert + conversations/
|
|
120
|
-
* messages), mirroring sendMembershipWelcome's exact pattern. Never throws --
|
|
121
|
-
* every failure is caught, logged via logOps, and classified into a result
|
|
122
|
-
* the caller (dunning-email-check, or stripe-webhook for grace_start) uses
|
|
123
|
-
* to decide whether dunning_emails_sent may be stamped true.
|
|
124
|
-
*/
|
|
125
|
-
export async function sendDunningEmail(
|
|
126
|
-
supabase: SupabaseLike,
|
|
127
|
-
email: string,
|
|
128
|
-
membershipId: string,
|
|
129
|
-
stage: DunningStage,
|
|
130
|
-
graceEndsAtIso: string,
|
|
131
|
-
operator: { name: string; shortName: string; domain: string; supportEmail: string },
|
|
132
|
-
): Promise<DunningResult> {
|
|
133
|
-
try {
|
|
134
|
-
if (!email) return 'skipped';
|
|
135
|
-
|
|
136
|
-
const apiKey = Deno.env.get('GHL_API_KEY');
|
|
137
|
-
const locationId = Deno.env.get('GHL_LOCATION_ID');
|
|
138
|
-
if (!apiKey || !locationId) {
|
|
139
|
-
console.log('[dunningEmails] GHL not configured; skip dunning email', { stage });
|
|
140
|
-
await logOps(supabase, 'dunning_email_skipped',
|
|
141
|
-
{ email, membership_id: membershipId, stage, reason: 'ghl_not_configured' },
|
|
142
|
-
{ severity: 'warning' }).catch(() => {});
|
|
143
|
-
return 'skipped';
|
|
144
|
-
}
|
|
145
|
-
const GHL_BASE = 'https://services.leadconnectorhq.com';
|
|
146
|
-
const headers = {
|
|
147
|
-
Authorization: `Bearer ${apiKey}`,
|
|
148
|
-
Version: '2021-07-28',
|
|
149
|
-
'Content-Type': 'application/json',
|
|
150
|
-
Accept: 'application/json',
|
|
151
|
-
};
|
|
152
|
-
|
|
153
|
-
const upRes = await fetch(`${GHL_BASE}/contacts/upsert`, {
|
|
154
|
-
method: 'POST', headers,
|
|
155
|
-
signal: AbortSignal.timeout(8000),
|
|
156
|
-
body: JSON.stringify({
|
|
157
|
-
locationId, email,
|
|
158
|
-
source: `${operator.shortName} Website — Dunning`,
|
|
159
|
-
tags: ['Dunning', `dunning:${stage}`, operator.domain],
|
|
160
|
-
}),
|
|
161
|
-
});
|
|
162
|
-
if (!upRes.ok) throw new Error(`ghl_upsert_${upRes.status}: ${await upRes.text()}`);
|
|
163
|
-
const upJson = await upRes.json();
|
|
164
|
-
const contactId = upJson.contact?.id || upJson.id || null;
|
|
165
|
-
if (!contactId) throw new Error('ghl_upsert_no_contact_id');
|
|
166
|
-
|
|
167
|
-
const p = (t: string) =>
|
|
168
|
-
`<p style="margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:22px">${t}</p>`;
|
|
169
|
-
|
|
170
|
-
const endInstant = new Date(graceEndsAtIso);
|
|
171
|
-
const endLabel = Number.isFinite(endInstant.getTime())
|
|
172
|
-
? endInstant.toLocaleDateString('en-US', {
|
|
173
|
-
timeZone: 'America/Los_Angeles', weekday: 'long', month: 'long', day: 'numeric',
|
|
174
|
-
})
|
|
175
|
-
: 'the end of your grace period';
|
|
176
|
-
|
|
177
|
-
const { subject, bodyLines } = stageCopy(stage, endLabel, p);
|
|
178
|
-
|
|
179
|
-
const html = `<div style="background:#F6F6F6;padding:24px 0;margin:0"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;background:#F6F6F6"><tr><td align="center" style="padding:0 12px"><table role="presentation" width="560" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;max-width:560px;width:100%;background:#FFFFFF;border-radius:10px"><tr><td style="padding:24px">
|
|
180
|
-
<h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">${esc(subject)}</h2>
|
|
181
|
-
${bodyLines.join('')}
|
|
182
|
-
${p(`Questions? Just reply to this email — it reaches a real person here. You can also write to <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`)}
|
|
183
|
-
<p style="margin:24px 0 0 0;color:#748272;font-family:Inter,Arial,sans-serif;font-size:13px;line-height:20px">${operator.name}</p>
|
|
184
|
-
</td></tr></table></td></tr></table></div>`;
|
|
185
|
-
|
|
186
|
-
const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
|
|
187
|
-
method: 'POST', headers,
|
|
188
|
-
signal: AbortSignal.timeout(8000),
|
|
189
|
-
body: JSON.stringify({ type: 'Email', contactId, subject, html }),
|
|
190
|
-
});
|
|
191
|
-
if (!emailRes.ok) throw new Error(`ghl_email_${emailRes.status}: ${await emailRes.text()}`);
|
|
192
|
-
|
|
193
|
-
await logOps(supabase, 'dunning_email_sent',
|
|
194
|
-
{ email, membership_id: membershipId, stage }, { severity: 'info' }).catch(() => {});
|
|
195
|
-
return 'sent';
|
|
196
|
-
} catch (e) {
|
|
197
|
-
const classification = classifyError(e);
|
|
198
|
-
await logOps(supabase, 'dunning_email_failed',
|
|
199
|
-
{ email, membership_id: membershipId, stage, message: e instanceof Error ? e.message : String(e) },
|
|
200
|
-
{ severity: classification === 'failed_permanent' ? 'error' : 'warning' }).catch(() => {});
|
|
201
|
-
return classification;
|
|
202
|
-
}
|
|
203
|
-
}
|
|
1
|
+
// Payment-failed dunning sequence: 3 emails riding the existing 5-day
|
|
2
|
+
// pricing_grace_ends_at window that stripe-webhook/index.ts opens on
|
|
3
|
+
// past_due/canceled/unpaid (see membership.ts's computeEntitlement -- the
|
|
4
|
+
// grace end flips both member pricing AND door/WiFi access off via
|
|
5
|
+
// membership-door-sync; this module changes none of that timing).
|
|
6
|
+
//
|
|
7
|
+
// Follows membershipWelcome.ts's exact GHL upsert+send pattern. esc() and
|
|
8
|
+
// classifyError() are reused verbatim (byte-identical) from that file.
|
|
9
|
+
//
|
|
10
|
+
// Stage naming:
|
|
11
|
+
// grace_start -- fired directly from stripe-webhook the instant the grace
|
|
12
|
+
// window is first opened. NOT decided by stageForGraceWindow
|
|
13
|
+
// below -- see stripe-webhook/index.ts's
|
|
14
|
+
// `isRevoked && !wasRevoked` branch.
|
|
15
|
+
// day_3 -- <=2 days remaining in the grace window.
|
|
16
|
+
// final_notice -- <=1 day remaining.
|
|
17
|
+
|
|
18
|
+
import type { SupabaseClient } from 'npm:@supabase/supabase-js@2';
|
|
19
|
+
import { logOps } from './ops.ts';
|
|
20
|
+
|
|
21
|
+
type SupabaseLike = SupabaseClient<any, 'public', any>;
|
|
22
|
+
|
|
23
|
+
export type DunningStage = 'grace_start' | 'day_3' | 'final_notice';
|
|
24
|
+
export type DunningResult = 'sent' | 'skipped' | 'failed_retryable' | 'failed_permanent';
|
|
25
|
+
|
|
26
|
+
/** Escape untrusted values interpolated into outbound HTML. Identical to membershipWelcome.ts's esc(). */
|
|
27
|
+
function esc(v: unknown): string {
|
|
28
|
+
return String(v ?? '')
|
|
29
|
+
.replace(/&/g, '&')
|
|
30
|
+
.replace(/</g, '<')
|
|
31
|
+
.replace(/>/g, '>')
|
|
32
|
+
.replace(/"/g, '"')
|
|
33
|
+
.replace(/'/g, ''');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Classify a caught error as transient (worth another event) or hopeless. Identical to membershipWelcome.ts's classifyError(). */
|
|
37
|
+
function classifyError(e: unknown): 'failed_retryable' | 'failed_permanent' {
|
|
38
|
+
const name = e instanceof Error ? e.name : '';
|
|
39
|
+
if (name === 'AbortError' || name === 'TimeoutError') return 'failed_retryable';
|
|
40
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
41
|
+
const m = msg.match(/^ghl_(?:upsert|email)_(\d{3})/);
|
|
42
|
+
if (m) {
|
|
43
|
+
const code = Number(m[1]);
|
|
44
|
+
if (code === 429 || code >= 500) return 'failed_retryable';
|
|
45
|
+
}
|
|
46
|
+
return 'failed_permanent';
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Pure day-band classifier for the dunning cadence. Given the grace window's
|
|
51
|
+
* end instant and "now", decides which of the two LATER stages is due:
|
|
52
|
+
*
|
|
53
|
+
* <= 1 day remaining -> 'final_notice'
|
|
54
|
+
* <= 2 days remaining -> 'day_3'
|
|
55
|
+
* otherwise -> null (too early; grace_start already covers day 0
|
|
56
|
+
* and fires from stripe-webhook directly, not here)
|
|
57
|
+
*
|
|
58
|
+
* Boundaries are inclusive of "<=" so a row checked exactly at the 1-day or
|
|
59
|
+
* 2-day mark is not skipped by a daily cron's timing jitter. An unparsable
|
|
60
|
+
* graceEndsAtIso returns null (fail closed -- never guess a stage).
|
|
61
|
+
*/
|
|
62
|
+
export function stageForGraceWindow(
|
|
63
|
+
graceEndsAtIso: string,
|
|
64
|
+
now: Date = new Date(),
|
|
65
|
+
): DunningStage | null {
|
|
66
|
+
const endMs = Date.parse(graceEndsAtIso);
|
|
67
|
+
if (!Number.isFinite(endMs)) return null;
|
|
68
|
+
const ONE_DAY_MS = 24 * 60 * 60 * 1000;
|
|
69
|
+
const msRemaining = endMs - now.getTime();
|
|
70
|
+
if (msRemaining <= ONE_DAY_MS) return 'final_notice';
|
|
71
|
+
if (msRemaining <= 2 * ONE_DAY_MS) return 'day_3';
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Pure skip-logic for dunning-email-check's per-row loop: a stage is only
|
|
77
|
+
* ever sent once. Extracted out of the Deno.serve handler (which cannot be
|
|
78
|
+
* unit-tested in isolation without a live network/DB) so this decision is
|
|
79
|
+
* independently testable. `stage: null` (too early for either later stage --
|
|
80
|
+
* see stageForGraceWindow) always means "don't send".
|
|
81
|
+
*/
|
|
82
|
+
export function shouldSendDunningStage(
|
|
83
|
+
stage: DunningStage | null,
|
|
84
|
+
dunningEmailsSent: Record<string, boolean> | null | undefined,
|
|
85
|
+
): boolean {
|
|
86
|
+
if (!stage) return false;
|
|
87
|
+
return dunningEmailsSent?.[stage] !== true;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function stageCopy(stage: DunningStage, endLabel: string, p: (t: string) => string) {
|
|
91
|
+
if (stage === 'grace_start') {
|
|
92
|
+
return {
|
|
93
|
+
subject: `We couldn't process your payment -- action needed by ${endLabel}`,
|
|
94
|
+
bodyLines: [
|
|
95
|
+
p(`We were unable to process your most recent membership payment.`),
|
|
96
|
+
p(`Please update your payment method before <strong>${esc(endLabel)}</strong> to keep your door and WiFi access active. No action is needed if you've already fixed this.`),
|
|
97
|
+
],
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
if (stage === 'day_3') {
|
|
101
|
+
return {
|
|
102
|
+
subject: `Reminder: update your payment by ${endLabel}`,
|
|
103
|
+
bodyLines: [
|
|
104
|
+
p(`This is a reminder that your membership payment is still unresolved.`),
|
|
105
|
+
p(`Your door and WiFi access will be turned off on <strong>${esc(endLabel)}</strong> if payment isn't updated before then.`),
|
|
106
|
+
],
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
return {
|
|
110
|
+
subject: `Final notice: access ends ${endLabel}`,
|
|
111
|
+
bodyLines: [
|
|
112
|
+
p(`This is a final notice -- your membership payment is still unresolved.`),
|
|
113
|
+
p(`Your door and WiFi access will be turned off on <strong>${esc(endLabel)}</strong> unless payment is updated before then.`),
|
|
114
|
+
],
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Send one dunning-sequence email via GHL (contacts/upsert + conversations/
|
|
120
|
+
* messages), mirroring sendMembershipWelcome's exact pattern. Never throws --
|
|
121
|
+
* every failure is caught, logged via logOps, and classified into a result
|
|
122
|
+
* the caller (dunning-email-check, or stripe-webhook for grace_start) uses
|
|
123
|
+
* to decide whether dunning_emails_sent may be stamped true.
|
|
124
|
+
*/
|
|
125
|
+
export async function sendDunningEmail(
|
|
126
|
+
supabase: SupabaseLike,
|
|
127
|
+
email: string,
|
|
128
|
+
membershipId: string,
|
|
129
|
+
stage: DunningStage,
|
|
130
|
+
graceEndsAtIso: string,
|
|
131
|
+
operator: { name: string; shortName: string; domain: string; supportEmail: string },
|
|
132
|
+
): Promise<DunningResult> {
|
|
133
|
+
try {
|
|
134
|
+
if (!email) return 'skipped';
|
|
135
|
+
|
|
136
|
+
const apiKey = Deno.env.get('GHL_API_KEY');
|
|
137
|
+
const locationId = Deno.env.get('GHL_LOCATION_ID');
|
|
138
|
+
if (!apiKey || !locationId) {
|
|
139
|
+
console.log('[dunningEmails] GHL not configured; skip dunning email', { stage });
|
|
140
|
+
await logOps(supabase, 'dunning_email_skipped',
|
|
141
|
+
{ email, membership_id: membershipId, stage, reason: 'ghl_not_configured' },
|
|
142
|
+
{ severity: 'warning' }).catch(() => {});
|
|
143
|
+
return 'skipped';
|
|
144
|
+
}
|
|
145
|
+
const GHL_BASE = 'https://services.leadconnectorhq.com';
|
|
146
|
+
const headers = {
|
|
147
|
+
Authorization: `Bearer ${apiKey}`,
|
|
148
|
+
Version: '2021-07-28',
|
|
149
|
+
'Content-Type': 'application/json',
|
|
150
|
+
Accept: 'application/json',
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
const upRes = await fetch(`${GHL_BASE}/contacts/upsert`, {
|
|
154
|
+
method: 'POST', headers,
|
|
155
|
+
signal: AbortSignal.timeout(8000),
|
|
156
|
+
body: JSON.stringify({
|
|
157
|
+
locationId, email,
|
|
158
|
+
source: `${operator.shortName} Website — Dunning`,
|
|
159
|
+
tags: ['Dunning', `dunning:${stage}`, operator.domain],
|
|
160
|
+
}),
|
|
161
|
+
});
|
|
162
|
+
if (!upRes.ok) throw new Error(`ghl_upsert_${upRes.status}: ${await upRes.text()}`);
|
|
163
|
+
const upJson = await upRes.json();
|
|
164
|
+
const contactId = upJson.contact?.id || upJson.id || null;
|
|
165
|
+
if (!contactId) throw new Error('ghl_upsert_no_contact_id');
|
|
166
|
+
|
|
167
|
+
const p = (t: string) =>
|
|
168
|
+
`<p style="margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:22px">${t}</p>`;
|
|
169
|
+
|
|
170
|
+
const endInstant = new Date(graceEndsAtIso);
|
|
171
|
+
const endLabel = Number.isFinite(endInstant.getTime())
|
|
172
|
+
? endInstant.toLocaleDateString('en-US', {
|
|
173
|
+
timeZone: 'America/Los_Angeles', weekday: 'long', month: 'long', day: 'numeric',
|
|
174
|
+
})
|
|
175
|
+
: 'the end of your grace period';
|
|
176
|
+
|
|
177
|
+
const { subject, bodyLines } = stageCopy(stage, endLabel, p);
|
|
178
|
+
|
|
179
|
+
const html = `<div style="background:#F6F6F6;padding:24px 0;margin:0"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;background:#F6F6F6"><tr><td align="center" style="padding:0 12px"><table role="presentation" width="560" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;max-width:560px;width:100%;background:#FFFFFF;border-radius:10px"><tr><td style="padding:24px">
|
|
180
|
+
<h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">${esc(subject)}</h2>
|
|
181
|
+
${bodyLines.join('')}
|
|
182
|
+
${p(`Questions? Just reply to this email — it reaches a real person here. You can also write to <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`)}
|
|
183
|
+
<p style="margin:24px 0 0 0;color:#748272;font-family:Inter,Arial,sans-serif;font-size:13px;line-height:20px">${operator.name}</p>
|
|
184
|
+
</td></tr></table></td></tr></table></div>`;
|
|
185
|
+
|
|
186
|
+
const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
|
|
187
|
+
method: 'POST', headers,
|
|
188
|
+
signal: AbortSignal.timeout(8000),
|
|
189
|
+
body: JSON.stringify({ type: 'Email', contactId, subject, html }),
|
|
190
|
+
});
|
|
191
|
+
if (!emailRes.ok) throw new Error(`ghl_email_${emailRes.status}: ${await emailRes.text()}`);
|
|
192
|
+
|
|
193
|
+
await logOps(supabase, 'dunning_email_sent',
|
|
194
|
+
{ email, membership_id: membershipId, stage }, { severity: 'info' }).catch(() => {});
|
|
195
|
+
return 'sent';
|
|
196
|
+
} catch (e) {
|
|
197
|
+
const classification = classifyError(e);
|
|
198
|
+
await logOps(supabase, 'dunning_email_failed',
|
|
199
|
+
{ email, membership_id: membershipId, stage, message: e instanceof Error ? e.message : String(e) },
|
|
200
|
+
{ severity: classification === 'failed_permanent' ? 'error' : 'warning' }).catch(() => {});
|
|
201
|
+
return classification;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
@@ -1,93 +1,93 @@
|
|
|
1
|
-
/** Email brand tokens (mirrors tailwind.config.ts for the tenant calling this). */
|
|
2
|
-
export interface BrandColors {
|
|
3
|
-
navy: string;
|
|
4
|
-
sage: string;
|
|
5
|
-
sageDark: string;
|
|
6
|
-
cream: string;
|
|
7
|
-
border: string;
|
|
8
|
-
inkSecondary: string;
|
|
9
|
-
inkMuted: string;
|
|
10
|
-
white: string;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
export function buildBrandStyles(colors: BrandColors) {
|
|
14
|
-
const brand = colors;
|
|
15
|
-
|
|
16
|
-
const main = {
|
|
17
|
-
backgroundColor: brand.cream,
|
|
18
|
-
fontFamily: "Georgia, 'Times New Roman', serif",
|
|
19
|
-
margin: 0,
|
|
20
|
-
padding: "32px 0",
|
|
21
|
-
};
|
|
22
|
-
|
|
23
|
-
const container = {
|
|
24
|
-
backgroundColor: brand.white,
|
|
25
|
-
border: `1px solid ${brand.border}`,
|
|
26
|
-
borderRadius: "12px",
|
|
27
|
-
padding: "36px 32px",
|
|
28
|
-
maxWidth: "560px",
|
|
29
|
-
margin: "0 auto",
|
|
30
|
-
};
|
|
31
|
-
|
|
32
|
-
const brandMark = {
|
|
33
|
-
fontSize: "13px",
|
|
34
|
-
letterSpacing: "1.5px",
|
|
35
|
-
textTransform: "uppercase" as const,
|
|
36
|
-
color: brand.sage,
|
|
37
|
-
fontFamily: "Helvetica, Arial, sans-serif",
|
|
38
|
-
margin: "0 0 24px",
|
|
39
|
-
};
|
|
40
|
-
|
|
41
|
-
const h1 = {
|
|
42
|
-
fontSize: "24px",
|
|
43
|
-
fontWeight: "bold" as const,
|
|
44
|
-
color: brand.navy,
|
|
45
|
-
margin: "0 0 16px",
|
|
46
|
-
lineHeight: "1.25",
|
|
47
|
-
};
|
|
48
|
-
|
|
49
|
-
const text = {
|
|
50
|
-
fontSize: "15px",
|
|
51
|
-
color: brand.inkSecondary,
|
|
52
|
-
lineHeight: "1.6",
|
|
53
|
-
fontFamily: "Helvetica, Arial, sans-serif",
|
|
54
|
-
margin: "0 0 24px",
|
|
55
|
-
};
|
|
56
|
-
|
|
57
|
-
const button = {
|
|
58
|
-
backgroundColor: brand.navy,
|
|
59
|
-
color: brand.white,
|
|
60
|
-
fontSize: "15px",
|
|
61
|
-
fontWeight: "bold" as const,
|
|
62
|
-
fontFamily: "Helvetica, Arial, sans-serif",
|
|
63
|
-
borderRadius: "8px",
|
|
64
|
-
padding: "14px 26px",
|
|
65
|
-
textDecoration: "none",
|
|
66
|
-
display: "inline-block",
|
|
67
|
-
};
|
|
68
|
-
|
|
69
|
-
const codeBox = {
|
|
70
|
-
fontSize: "26px",
|
|
71
|
-
letterSpacing: "6px",
|
|
72
|
-
fontWeight: "bold" as const,
|
|
73
|
-
color: brand.navy,
|
|
74
|
-
backgroundColor: brand.cream,
|
|
75
|
-
border: `1px solid ${brand.border}`,
|
|
76
|
-
borderRadius: "8px",
|
|
77
|
-
padding: "16px",
|
|
78
|
-
textAlign: "center" as const,
|
|
79
|
-
margin: "0 0 24px",
|
|
80
|
-
};
|
|
81
|
-
|
|
82
|
-
const footer = {
|
|
83
|
-
fontSize: "12px",
|
|
84
|
-
color: brand.inkMuted,
|
|
85
|
-
fontFamily: "Helvetica, Arial, sans-serif",
|
|
86
|
-
lineHeight: "1.6",
|
|
87
|
-
borderTop: `1px solid ${brand.border}`,
|
|
88
|
-
paddingTop: "20px",
|
|
89
|
-
margin: "32px 0 0",
|
|
90
|
-
};
|
|
91
|
-
|
|
92
|
-
return { brand, main, container, brandMark, h1, text, button, codeBox, footer };
|
|
93
|
-
}
|
|
1
|
+
/** Email brand tokens (mirrors tailwind.config.ts for the tenant calling this). */
|
|
2
|
+
export interface BrandColors {
|
|
3
|
+
navy: string;
|
|
4
|
+
sage: string;
|
|
5
|
+
sageDark: string;
|
|
6
|
+
cream: string;
|
|
7
|
+
border: string;
|
|
8
|
+
inkSecondary: string;
|
|
9
|
+
inkMuted: string;
|
|
10
|
+
white: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function buildBrandStyles(colors: BrandColors) {
|
|
14
|
+
const brand = colors;
|
|
15
|
+
|
|
16
|
+
const main = {
|
|
17
|
+
backgroundColor: brand.cream,
|
|
18
|
+
fontFamily: "Georgia, 'Times New Roman', serif",
|
|
19
|
+
margin: 0,
|
|
20
|
+
padding: "32px 0",
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const container = {
|
|
24
|
+
backgroundColor: brand.white,
|
|
25
|
+
border: `1px solid ${brand.border}`,
|
|
26
|
+
borderRadius: "12px",
|
|
27
|
+
padding: "36px 32px",
|
|
28
|
+
maxWidth: "560px",
|
|
29
|
+
margin: "0 auto",
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const brandMark = {
|
|
33
|
+
fontSize: "13px",
|
|
34
|
+
letterSpacing: "1.5px",
|
|
35
|
+
textTransform: "uppercase" as const,
|
|
36
|
+
color: brand.sage,
|
|
37
|
+
fontFamily: "Helvetica, Arial, sans-serif",
|
|
38
|
+
margin: "0 0 24px",
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
const h1 = {
|
|
42
|
+
fontSize: "24px",
|
|
43
|
+
fontWeight: "bold" as const,
|
|
44
|
+
color: brand.navy,
|
|
45
|
+
margin: "0 0 16px",
|
|
46
|
+
lineHeight: "1.25",
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const text = {
|
|
50
|
+
fontSize: "15px",
|
|
51
|
+
color: brand.inkSecondary,
|
|
52
|
+
lineHeight: "1.6",
|
|
53
|
+
fontFamily: "Helvetica, Arial, sans-serif",
|
|
54
|
+
margin: "0 0 24px",
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const button = {
|
|
58
|
+
backgroundColor: brand.navy,
|
|
59
|
+
color: brand.white,
|
|
60
|
+
fontSize: "15px",
|
|
61
|
+
fontWeight: "bold" as const,
|
|
62
|
+
fontFamily: "Helvetica, Arial, sans-serif",
|
|
63
|
+
borderRadius: "8px",
|
|
64
|
+
padding: "14px 26px",
|
|
65
|
+
textDecoration: "none",
|
|
66
|
+
display: "inline-block",
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
const codeBox = {
|
|
70
|
+
fontSize: "26px",
|
|
71
|
+
letterSpacing: "6px",
|
|
72
|
+
fontWeight: "bold" as const,
|
|
73
|
+
color: brand.navy,
|
|
74
|
+
backgroundColor: brand.cream,
|
|
75
|
+
border: `1px solid ${brand.border}`,
|
|
76
|
+
borderRadius: "8px",
|
|
77
|
+
padding: "16px",
|
|
78
|
+
textAlign: "center" as const,
|
|
79
|
+
margin: "0 0 24px",
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const footer = {
|
|
83
|
+
fontSize: "12px",
|
|
84
|
+
color: brand.inkMuted,
|
|
85
|
+
fontFamily: "Helvetica, Arial, sans-serif",
|
|
86
|
+
lineHeight: "1.6",
|
|
87
|
+
borderTop: `1px solid ${brand.border}`,
|
|
88
|
+
paddingTop: "20px",
|
|
89
|
+
margin: "32px 0 0",
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
return { brand, main, container, brandMark, h1, text, button, codeBox, footer };
|
|
93
|
+
}
|