Skip to content

Commit 0e6958e

Browse files
authored
feat(billing): add logging to balance alert trigger and email send (#3012)
1 parent 5f135d0 commit 0e6958e

2 files changed

Lines changed: 17 additions & 2 deletions

File tree

apps/web/src/lib/email.ts

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { getMagicLinkUrl, type MagicLinkTokenWithPlaintext } from '@/lib/auth/ma
55
import { NEXTAUTH_URL } from '@/lib/config.server';
66
import { sendViaMailgun } from '@/lib/email-mailgun';
77
import { verifyEmail } from '@/lib/email-neverbounce';
8+
import { logExceptInTest, warnExceptInTest } from '@/lib/utils.server';
89

910
// Subject lines for each template — also serves as the canonical list of template names
1011
export const subjects = {
@@ -247,15 +248,26 @@ export async function sendBalanceAlertEmail(props: SendBalanceAlertEmailProps):
247248

248249
const organization_url = `${NEXTAUTH_URL}/organizations/${organizationId}`;
249250

250-
const sendToRecipient = (email: string) =>
251-
send({
251+
const sendToRecipient = async (email: string) => {
252+
const result = await send({
252253
to: email,
253254
templateName: 'balanceAlert',
254255
templateVars: {
255256
minimum_balance: String(minimum_balance),
256257
organization_url,
257258
},
258259
});
260+
if (result.sent) {
261+
logExceptInTest(
262+
`[sendBalanceAlertEmail] Sent to ${email} for org ${organizationId} (threshold: $${minimum_balance})`
263+
);
264+
} else {
265+
warnExceptInTest(
266+
`[sendBalanceAlertEmail] Failed to send to ${email} for org ${organizationId}: reason=${result.reason}`
267+
);
268+
}
269+
return result;
270+
};
259271

260272
const BATCH_SIZE = 10;
261273
for (let i = 0; i < to.length; i += BATCH_SIZE) {

apps/web/src/lib/organizations/organization-usage.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,9 @@ export async function ingestOrganizationTokenUsage(usage: MicrodollarUsage): Pro
234234
// Check if balance is crossing the minimum_balance threshold
235235
if (minimumBalance != null && currentBalance >= minimumBalance && newBalance < minimumBalance) {
236236
const alertEmails = orgData?.settings?.minimum_balance_alert_email ?? [];
237+
logExceptInTest(
238+
`[ingestOrganizationTokenUsage] Balance alert triggered for org ${organization_id}: currentBalance=${fromMicrodollars(currentBalance)} newBalance=${fromMicrodollars(newBalance)} threshold=${fromMicrodollars(minimumBalance)} recipients=${alertEmails.length}`
239+
);
237240
// Send email notification about low balance (don't block the transaction, but do make Vercel wait on the Promise before shutting down)
238241
after(
239242
sendBalanceAlertEmail({

0 commit comments

Comments
 (0)