Add email sent/failed structured logging
All checks were successful
Deploy / deploy (push) Successful in 1m38s
All checks were successful
Deploy / deploy (push) Successful in 1m38s
Implement email logging per observability spec: - Add structured logging for email sent (info level) and failed (error level) - Include userId, type, and recipient fields in log events - Add userId parameter to email functions (sendDailyEmail, sendPeriodConfirmationEmail, sendTokenExpirationWarning) - Update cron routes (notifications, garmin-sync) to pass userId 6 new tests added to email.test.ts (now 30 tests total) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -4,14 +4,14 @@ This file is maintained by Ralph. Run `./ralph-sandbox.sh plan 3` to generate ta
|
|||||||
|
|
||||||
## Current State Summary
|
## Current State Summary
|
||||||
|
|
||||||
### Overall Status: 835 tests passing across 44 test files
|
### Overall Status: 841 tests passing across 44 test files
|
||||||
|
|
||||||
### Library Implementation
|
### Library Implementation
|
||||||
| File | Status | Gap Analysis |
|
| File | Status | Gap Analysis |
|
||||||
|------|--------|--------------|
|
|------|--------|--------------|
|
||||||
| `cycle.ts` | **COMPLETE** | 22 tests covering all functions including dynamic phase boundaries for variable cycle lengths |
|
| `cycle.ts` | **COMPLETE** | 22 tests covering all functions including dynamic phase boundaries for variable cycle lengths |
|
||||||
| `nutrition.ts` | **COMPLETE** | 17 tests covering getNutritionGuidance, getSeedSwitchAlert, phase-specific carb ranges, keto guidance |
|
| `nutrition.ts` | **COMPLETE** | 17 tests covering getNutritionGuidance, getSeedSwitchAlert, phase-specific carb ranges, keto guidance |
|
||||||
| `email.ts` | **COMPLETE** | 24 tests covering sendDailyEmail, sendPeriodConfirmationEmail, sendTokenExpirationWarning, email formatting, subject lines |
|
| `email.ts` | **COMPLETE** | 30 tests covering sendDailyEmail, sendPeriodConfirmationEmail, sendTokenExpirationWarning, email formatting, subject lines, structured logging |
|
||||||
| `ics.ts` | **COMPLETE** | 33 tests covering generateIcsFeed (90 days of phase events), ICS format validation, timezone handling, period prediction feedback, CATEGORIES for calendar colors |
|
| `ics.ts` | **COMPLETE** | 33 tests covering generateIcsFeed (90 days of phase events), ICS format validation, timezone handling, period prediction feedback, CATEGORIES for calendar colors |
|
||||||
| `encryption.ts` | **COMPLETE** | 14 tests covering AES-256-GCM encrypt/decrypt round-trip, error handling, key validation |
|
| `encryption.ts` | **COMPLETE** | 14 tests covering AES-256-GCM encrypt/decrypt round-trip, error handling, key validation |
|
||||||
| `decision-engine.ts` | **COMPLETE** | 8 priority rules + override handling with `getDecisionWithOverrides()`, 24 tests |
|
| `decision-engine.ts` | **COMPLETE** | 8 priority rules + override handling with `getDecisionWithOverrides()`, 24 tests |
|
||||||
@@ -94,7 +94,7 @@ This file is maintained by Ralph. Run `./ralph-sandbox.sh plan 3` to generate ta
|
|||||||
| `src/app/login/page.test.tsx` | **EXISTS** - 32 tests (form rendering, auth flow, error handling, validation, accessibility, rate limiting) |
|
| `src/app/login/page.test.tsx` | **EXISTS** - 32 tests (form rendering, auth flow, error handling, validation, accessibility, rate limiting) |
|
||||||
| `src/app/page.test.tsx` | **EXISTS** - 28 tests (data fetching, component rendering, override toggles, error handling) |
|
| `src/app/page.test.tsx` | **EXISTS** - 28 tests (data fetching, component rendering, override toggles, error handling) |
|
||||||
| `src/lib/nutrition.test.ts` | **EXISTS** - 17 tests (seed cycling, carb ranges, keto guidance by phase) |
|
| `src/lib/nutrition.test.ts` | **EXISTS** - 17 tests (seed cycling, carb ranges, keto guidance by phase) |
|
||||||
| `src/lib/email.test.ts` | **EXISTS** - 24 tests (email content, subject lines, formatting, token expiration warnings) |
|
| `src/lib/email.test.ts` | **EXISTS** - 30 tests (email content, subject lines, formatting, token expiration warnings, structured logging) |
|
||||||
| `src/lib/ics.test.ts` | **EXISTS** - 33 tests (ICS format validation, 90-day event generation, timezone handling, period prediction feedback, CATEGORIES for colors) |
|
| `src/lib/ics.test.ts` | **EXISTS** - 33 tests (ICS format validation, 90-day event generation, timezone handling, period prediction feedback, CATEGORIES for colors) |
|
||||||
| `src/lib/encryption.test.ts` | **EXISTS** - 14 tests (encrypt/decrypt round-trip, error handling, key validation) |
|
| `src/lib/encryption.test.ts` | **EXISTS** - 14 tests (encrypt/decrypt round-trip, error handling, key validation) |
|
||||||
| `src/lib/garmin.test.ts` | **EXISTS** - 33 tests (fetchGarminData, fetchHrvStatus, fetchBodyBattery, fetchIntensityMinutes, token expiry, error handling) |
|
| `src/lib/garmin.test.ts` | **EXISTS** - 33 tests (fetchGarminData, fetchHrvStatus, fetchBodyBattery, fetchIntensityMinutes, token expiry, error handling) |
|
||||||
@@ -892,7 +892,7 @@ P4.* UX Polish ────────> After core functionality complete
|
|||||||
- [x] **decision-engine.ts** - Complete with 24 tests (`getTrainingDecision` + `getDecisionWithOverrides`)
|
- [x] **decision-engine.ts** - Complete with 24 tests (`getTrainingDecision` + `getDecisionWithOverrides`)
|
||||||
- [x] **pocketbase.ts** - Complete with 9 tests (`createPocketBaseClient`, `isAuthenticated`, `getCurrentUser`, `loadAuthFromCookies`)
|
- [x] **pocketbase.ts** - Complete with 9 tests (`createPocketBaseClient`, `isAuthenticated`, `getCurrentUser`, `loadAuthFromCookies`)
|
||||||
- [x] **nutrition.ts** - Complete with 17 tests (`getNutritionGuidance`, `getSeedSwitchAlert`, phase-specific carb ranges, keto guidance) (P3.2)
|
- [x] **nutrition.ts** - Complete with 17 tests (`getNutritionGuidance`, `getSeedSwitchAlert`, phase-specific carb ranges, keto guidance) (P3.2)
|
||||||
- [x] **email.ts** - Complete with 24 tests (`sendDailyEmail`, `sendPeriodConfirmationEmail`, `sendTokenExpirationWarning`, email formatting) (P3.3, P3.9)
|
- [x] **email.ts** - Complete with 30 tests (`sendDailyEmail`, `sendPeriodConfirmationEmail`, `sendTokenExpirationWarning`, email formatting, structured logging for sent/failed events) (P3.3, P3.9)
|
||||||
- [x] **ics.ts** - Complete with 33 tests (`generateIcsFeed`, ICS format validation, 90-day event generation, period prediction feedback, CATEGORIES for calendar colors) (P3.4, P4.5)
|
- [x] **ics.ts** - Complete with 33 tests (`generateIcsFeed`, ICS format validation, 90-day event generation, period prediction feedback, CATEGORIES for calendar colors) (P3.4, P4.5)
|
||||||
- [x] **encryption.ts** - Complete with 14 tests (AES-256-GCM encrypt/decrypt, round-trip validation, error handling) (P3.5)
|
- [x] **encryption.ts** - Complete with 14 tests (AES-256-GCM encrypt/decrypt, round-trip validation, error handling) (P3.5)
|
||||||
- [x] **garmin.ts** - Complete with 33 tests (`fetchGarminData`, `fetchHrvStatus`, `fetchBodyBattery`, `fetchIntensityMinutes`, `isTokenExpired`, `daysUntilExpiry`, error handling) (P2.1, P3.6)
|
- [x] **garmin.ts** - Complete with 33 tests (`fetchGarminData`, `fetchHrvStatus`, `fetchBodyBattery`, `fetchIntensityMinutes`, `isTokenExpired`, `daysUntilExpiry`, error handling) (P2.1, P3.6)
|
||||||
@@ -945,7 +945,7 @@ P4.* UX Polish ────────> After core functionality complete
|
|||||||
### P3: Quality and Testing
|
### P3: Quality and Testing
|
||||||
- [x] **P3.1: Decision Engine Tests** - Complete with 24 tests covering all 8 priority rules and override combinations
|
- [x] **P3.1: Decision Engine Tests** - Complete with 24 tests covering all 8 priority rules and override combinations
|
||||||
- [x] **P3.2: Nutrition Tests** - Complete with 17 tests covering seed cycling, carb ranges, keto guidance by phase
|
- [x] **P3.2: Nutrition Tests** - Complete with 17 tests covering seed cycling, carb ranges, keto guidance by phase
|
||||||
- [x] **P3.3: Email Tests** - Complete with 24 tests covering daily emails, period confirmation, token expiration warnings
|
- [x] **P3.3: Email Tests** - Complete with 30 tests covering daily emails, period confirmation, token expiration warnings, structured logging
|
||||||
- [x] **P3.4: ICS Tests** - Complete with 28 tests covering ICS format validation, 90-day event generation, timezone handling, period prediction feedback
|
- [x] **P3.4: ICS Tests** - Complete with 28 tests covering ICS format validation, 90-day event generation, timezone handling, period prediction feedback
|
||||||
- [x] **P3.5: Encryption Tests** - Complete with 14 tests covering AES-256-GCM round-trip, error handling, key validation
|
- [x] **P3.5: Encryption Tests** - Complete with 14 tests covering AES-256-GCM round-trip, error handling, key validation
|
||||||
- [x] **P3.6: Garmin Tests** - Complete with 33 tests covering API interactions, token expiry, error handling
|
- [x] **P3.6: Garmin Tests** - Complete with 33 tests covering API interactions, token expiry, error handling
|
||||||
@@ -975,7 +975,7 @@ Analysis of all specs vs implementation revealed these gaps:
|
|||||||
|-----|------|--------|-------|
|
|-----|------|--------|-------|
|
||||||
| Logout functionality | authentication.md | **COMPLETE** | Added POST /api/auth/logout + settings button |
|
| Logout functionality | authentication.md | **COMPLETE** | Added POST /api/auth/logout + settings button |
|
||||||
| Garmin sync structured logging | observability.md | **COMPLETE** | Added sync start/complete/failure logging |
|
| Garmin sync structured logging | observability.md | **COMPLETE** | Added sync start/complete/failure logging |
|
||||||
| Email sent/failed logging | observability.md | **PENDING** | Email events should be logged |
|
| Email sent/failed logging | observability.md | **COMPLETE** | Email events now logged (info for success, error for failure) with structured data (userId, emailType, success) |
|
||||||
| Period history UI | cycle-tracking.md | **PENDING** | UI for viewing/editing past periods |
|
| Period history UI | cycle-tracking.md | **PENDING** | UI for viewing/editing past periods |
|
||||||
| Dashboard color-coded backgrounds | dashboard.md | **PENDING** | Phase-based background colors |
|
| Dashboard color-coded backgrounds | dashboard.md | **PENDING** | Phase-based background colors |
|
||||||
| Toast notifications | dashboard.md | **PENDING** | Success/error toasts for user actions |
|
| Toast notifications | dashboard.md | **PENDING** | Success/error toasts for user actions |
|
||||||
|
|||||||
@@ -424,6 +424,7 @@ describe("POST /api/cron/garmin-sync", () => {
|
|||||||
expect(mockSendTokenExpirationWarning).toHaveBeenCalledWith(
|
expect(mockSendTokenExpirationWarning).toHaveBeenCalledWith(
|
||||||
"user@example.com",
|
"user@example.com",
|
||||||
14,
|
14,
|
||||||
|
"user123",
|
||||||
);
|
);
|
||||||
const body = await response.json();
|
const body = await response.json();
|
||||||
expect(body.warningsSent).toBe(1);
|
expect(body.warningsSent).toBe(1);
|
||||||
@@ -438,6 +439,7 @@ describe("POST /api/cron/garmin-sync", () => {
|
|||||||
expect(mockSendTokenExpirationWarning).toHaveBeenCalledWith(
|
expect(mockSendTokenExpirationWarning).toHaveBeenCalledWith(
|
||||||
"user@example.com",
|
"user@example.com",
|
||||||
7,
|
7,
|
||||||
|
"user123",
|
||||||
);
|
);
|
||||||
const body = await response.json();
|
const body = await response.json();
|
||||||
expect(body.warningsSent).toBe(1);
|
expect(body.warningsSent).toBe(1);
|
||||||
@@ -493,10 +495,12 @@ describe("POST /api/cron/garmin-sync", () => {
|
|||||||
expect(mockSendTokenExpirationWarning).toHaveBeenCalledWith(
|
expect(mockSendTokenExpirationWarning).toHaveBeenCalledWith(
|
||||||
"user1@example.com",
|
"user1@example.com",
|
||||||
14,
|
14,
|
||||||
|
"user1",
|
||||||
);
|
);
|
||||||
expect(mockSendTokenExpirationWarning).toHaveBeenCalledWith(
|
expect(mockSendTokenExpirationWarning).toHaveBeenCalledWith(
|
||||||
"user2@example.com",
|
"user2@example.com",
|
||||||
7,
|
7,
|
||||||
|
"user2",
|
||||||
);
|
);
|
||||||
const body = await response.json();
|
const body = await response.json();
|
||||||
expect(body.warningsSent).toBe(2);
|
expect(body.warningsSent).toBe(2);
|
||||||
|
|||||||
@@ -82,7 +82,7 @@ export async function POST(request: Request) {
|
|||||||
const daysRemaining = daysUntilExpiry(tokens);
|
const daysRemaining = daysUntilExpiry(tokens);
|
||||||
if (daysRemaining === 14 || daysRemaining === 7) {
|
if (daysRemaining === 14 || daysRemaining === 7) {
|
||||||
try {
|
try {
|
||||||
await sendTokenExpirationWarning(user.email, daysRemaining);
|
await sendTokenExpirationWarning(user.email, daysRemaining, user.id);
|
||||||
result.warningsSent++;
|
result.warningsSent++;
|
||||||
} catch {
|
} catch {
|
||||||
// Continue processing even if warning email fails
|
// Continue processing even if warning email fails
|
||||||
|
|||||||
@@ -121,25 +121,28 @@ export async function POST(request: Request) {
|
|||||||
const nutrition = getNutritionGuidance(dailyLog.cycleDay);
|
const nutrition = getNutritionGuidance(dailyLog.cycleDay);
|
||||||
|
|
||||||
// Send email
|
// Send email
|
||||||
await sendDailyEmail({
|
await sendDailyEmail(
|
||||||
to: user.email,
|
{
|
||||||
cycleDay: dailyLog.cycleDay,
|
to: user.email,
|
||||||
phase: dailyLog.phase,
|
cycleDay: dailyLog.cycleDay,
|
||||||
decision: {
|
phase: dailyLog.phase,
|
||||||
status: dailyLog.trainingDecision,
|
decision: {
|
||||||
reason: dailyLog.decisionReason,
|
status: dailyLog.trainingDecision,
|
||||||
icon: getDecisionIcon(dailyLog.trainingDecision as DecisionStatus),
|
reason: dailyLog.decisionReason,
|
||||||
|
icon: getDecisionIcon(dailyLog.trainingDecision as DecisionStatus),
|
||||||
|
},
|
||||||
|
bodyBatteryCurrent: dailyLog.bodyBatteryCurrent,
|
||||||
|
bodyBatteryYesterdayLow: dailyLog.bodyBatteryYesterdayLow,
|
||||||
|
hrvStatus: dailyLog.hrvStatus,
|
||||||
|
weekIntensity: dailyLog.weekIntensityMinutes,
|
||||||
|
phaseLimit: dailyLog.phaseLimit,
|
||||||
|
remainingMinutes: dailyLog.remainingMinutes,
|
||||||
|
seeds: nutrition.seeds,
|
||||||
|
carbRange: nutrition.carbRange,
|
||||||
|
ketoGuidance: nutrition.ketoGuidance,
|
||||||
},
|
},
|
||||||
bodyBatteryCurrent: dailyLog.bodyBatteryCurrent,
|
user.id,
|
||||||
bodyBatteryYesterdayLow: dailyLog.bodyBatteryYesterdayLow,
|
);
|
||||||
hrvStatus: dailyLog.hrvStatus,
|
|
||||||
weekIntensity: dailyLog.weekIntensityMinutes,
|
|
||||||
phaseLimit: dailyLog.phaseLimit,
|
|
||||||
remainingMinutes: dailyLog.remainingMinutes,
|
|
||||||
seeds: nutrition.seeds,
|
|
||||||
carbRange: nutrition.carbRange,
|
|
||||||
ketoGuidance: nutrition.ketoGuidance,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Update notificationSentAt timestamp
|
// Update notificationSentAt timestamp
|
||||||
await pb.collection("dailyLogs").update(dailyLog.id, {
|
await pb.collection("dailyLogs").update(dailyLog.id, {
|
||||||
|
|||||||
@@ -2,8 +2,10 @@
|
|||||||
// ABOUTME: Tests email composition, subject lines, and Resend integration.
|
// ABOUTME: Tests email composition, subject lines, and Resend integration.
|
||||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
const { mockSend } = vi.hoisted(() => ({
|
const { mockSend, mockLoggerInfo, mockLoggerError } = vi.hoisted(() => ({
|
||||||
mockSend: vi.fn().mockResolvedValue({ id: "mock-email-id" }),
|
mockSend: vi.fn().mockResolvedValue({ id: "mock-email-id" }),
|
||||||
|
mockLoggerInfo: vi.fn(),
|
||||||
|
mockLoggerError: vi.fn(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// Mock the resend module before importing email utilities
|
// Mock the resend module before importing email utilities
|
||||||
@@ -13,6 +15,14 @@ vi.mock("resend", () => ({
|
|||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
// Mock the logger
|
||||||
|
vi.mock("@/lib/logger", () => ({
|
||||||
|
logger: {
|
||||||
|
info: mockLoggerInfo,
|
||||||
|
error: mockLoggerError,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
import type { DailyEmailData } from "./email";
|
import type { DailyEmailData } from "./email";
|
||||||
import {
|
import {
|
||||||
sendDailyEmail,
|
sendDailyEmail,
|
||||||
@@ -277,3 +287,135 @@ describe("sendTokenExpirationWarning", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("email structured logging", () => {
|
||||||
|
afterEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
const sampleDailyEmailData: DailyEmailData = {
|
||||||
|
to: "user@example.com",
|
||||||
|
cycleDay: 15,
|
||||||
|
phase: "OVULATION",
|
||||||
|
decision: {
|
||||||
|
status: "TRAIN",
|
||||||
|
reason: "Body battery high",
|
||||||
|
icon: "💪",
|
||||||
|
},
|
||||||
|
bodyBatteryCurrent: 85,
|
||||||
|
bodyBatteryYesterdayLow: 45,
|
||||||
|
hrvStatus: "Balanced",
|
||||||
|
weekIntensity: 60,
|
||||||
|
phaseLimit: 80,
|
||||||
|
remainingMinutes: 20,
|
||||||
|
seeds: "Sesame",
|
||||||
|
carbRange: "100-150g",
|
||||||
|
ketoGuidance: "No",
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("sendDailyEmail logging", () => {
|
||||||
|
it("logs email sent with info level on success", async () => {
|
||||||
|
await sendDailyEmail(sampleDailyEmailData, "user-123");
|
||||||
|
expect(mockLoggerInfo).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
userId: "user-123",
|
||||||
|
type: "daily",
|
||||||
|
recipient: "user@example.com",
|
||||||
|
}),
|
||||||
|
"Email sent",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("logs email failed with error level on failure", async () => {
|
||||||
|
const error = new Error("Resend API failed");
|
||||||
|
mockSend.mockRejectedValueOnce(error);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
sendDailyEmail(sampleDailyEmailData, "user-123"),
|
||||||
|
).rejects.toThrow("Resend API failed");
|
||||||
|
|
||||||
|
expect(mockLoggerError).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
userId: "user-123",
|
||||||
|
type: "daily",
|
||||||
|
err: error,
|
||||||
|
}),
|
||||||
|
"Email failed",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("sendPeriodConfirmationEmail logging", () => {
|
||||||
|
it("logs email sent with info level on success", async () => {
|
||||||
|
await sendPeriodConfirmationEmail(
|
||||||
|
"user@example.com",
|
||||||
|
new Date("2025-01-15"),
|
||||||
|
31,
|
||||||
|
"user-456",
|
||||||
|
);
|
||||||
|
expect(mockLoggerInfo).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
userId: "user-456",
|
||||||
|
type: "period_confirmation",
|
||||||
|
recipient: "user@example.com",
|
||||||
|
}),
|
||||||
|
"Email sent",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("logs email failed with error level on failure", async () => {
|
||||||
|
const error = new Error("Resend API failed");
|
||||||
|
mockSend.mockRejectedValueOnce(error);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
sendPeriodConfirmationEmail(
|
||||||
|
"user@example.com",
|
||||||
|
new Date("2025-01-15"),
|
||||||
|
31,
|
||||||
|
"user-456",
|
||||||
|
),
|
||||||
|
).rejects.toThrow("Resend API failed");
|
||||||
|
|
||||||
|
expect(mockLoggerError).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
userId: "user-456",
|
||||||
|
type: "period_confirmation",
|
||||||
|
err: error,
|
||||||
|
}),
|
||||||
|
"Email failed",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("sendTokenExpirationWarning logging", () => {
|
||||||
|
it("logs email sent with info level on success", async () => {
|
||||||
|
await sendTokenExpirationWarning("user@example.com", 14, "user-789");
|
||||||
|
expect(mockLoggerInfo).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
userId: "user-789",
|
||||||
|
type: "warning",
|
||||||
|
recipient: "user@example.com",
|
||||||
|
}),
|
||||||
|
"Email sent",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("logs email failed with error level on failure", async () => {
|
||||||
|
const error = new Error("Resend API failed");
|
||||||
|
mockSend.mockRejectedValueOnce(error);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
sendTokenExpirationWarning("user@example.com", 14, "user-789"),
|
||||||
|
).rejects.toThrow("Resend API failed");
|
||||||
|
|
||||||
|
expect(mockLoggerError).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
userId: "user-789",
|
||||||
|
type: "warning",
|
||||||
|
err: error,
|
||||||
|
}),
|
||||||
|
"Email failed",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
// ABOUTME: Sends daily training notifications and period confirmation emails.
|
// ABOUTME: Sends daily training notifications and period confirmation emails.
|
||||||
import { Resend } from "resend";
|
import { Resend } from "resend";
|
||||||
|
|
||||||
|
import { logger } from "@/lib/logger";
|
||||||
import { emailSentTotal } from "@/lib/metrics";
|
import { emailSentTotal } from "@/lib/metrics";
|
||||||
|
|
||||||
const resend = new Resend(process.env.RESEND_API_KEY);
|
const resend = new Resend(process.env.RESEND_API_KEY);
|
||||||
@@ -28,7 +29,10 @@ export interface DailyEmailData {
|
|||||||
ketoGuidance: string;
|
ketoGuidance: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function sendDailyEmail(data: DailyEmailData): Promise<void> {
|
export async function sendDailyEmail(
|
||||||
|
data: DailyEmailData,
|
||||||
|
userId?: string,
|
||||||
|
): Promise<void> {
|
||||||
const subject = `Today's Training: ${data.decision.icon} ${data.decision.status}`;
|
const subject = `Today's Training: ${data.decision.icon} ${data.decision.status}`;
|
||||||
|
|
||||||
const body = `Good morning!
|
const body = `Good morning!
|
||||||
@@ -53,20 +57,27 @@ ${data.decision.icon} ${data.decision.reason}
|
|||||||
---
|
---
|
||||||
Auto-generated by PhaseFlow`;
|
Auto-generated by PhaseFlow`;
|
||||||
|
|
||||||
await resend.emails.send({
|
try {
|
||||||
from: EMAIL_FROM,
|
await resend.emails.send({
|
||||||
to: data.to,
|
from: EMAIL_FROM,
|
||||||
subject,
|
to: data.to,
|
||||||
text: body,
|
subject,
|
||||||
});
|
text: body,
|
||||||
|
});
|
||||||
|
|
||||||
emailSentTotal.inc({ type: "daily" });
|
logger.info({ userId, type: "daily", recipient: data.to }, "Email sent");
|
||||||
|
emailSentTotal.inc({ type: "daily" });
|
||||||
|
} catch (err) {
|
||||||
|
logger.error({ userId, type: "daily", err }, "Email failed");
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function sendPeriodConfirmationEmail(
|
export async function sendPeriodConfirmationEmail(
|
||||||
to: string,
|
to: string,
|
||||||
lastPeriodDate: Date,
|
lastPeriodDate: Date,
|
||||||
cycleLength: number,
|
cycleLength: number,
|
||||||
|
userId?: string,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const subject = "🔵 Period Tracking Updated";
|
const subject = "🔵 Period Tracking Updated";
|
||||||
|
|
||||||
@@ -78,17 +89,28 @@ Your calendar will update automatically within 24 hours.
|
|||||||
---
|
---
|
||||||
Auto-generated by PhaseFlow`;
|
Auto-generated by PhaseFlow`;
|
||||||
|
|
||||||
await resend.emails.send({
|
try {
|
||||||
from: EMAIL_FROM,
|
await resend.emails.send({
|
||||||
to,
|
from: EMAIL_FROM,
|
||||||
subject,
|
to,
|
||||||
text: body,
|
subject,
|
||||||
});
|
text: body,
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
{ userId, type: "period_confirmation", recipient: to },
|
||||||
|
"Email sent",
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
logger.error({ userId, type: "period_confirmation", err }, "Email failed");
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function sendTokenExpirationWarning(
|
export async function sendTokenExpirationWarning(
|
||||||
to: string,
|
to: string,
|
||||||
daysUntilExpiry: number,
|
daysUntilExpiry: number,
|
||||||
|
userId?: string,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const isUrgent = daysUntilExpiry <= 7;
|
const isUrgent = daysUntilExpiry <= 7;
|
||||||
|
|
||||||
@@ -112,12 +134,18 @@ This will ensure your training recommendations continue to use fresh Garmin data
|
|||||||
---
|
---
|
||||||
Auto-generated by PhaseFlow`;
|
Auto-generated by PhaseFlow`;
|
||||||
|
|
||||||
await resend.emails.send({
|
try {
|
||||||
from: EMAIL_FROM,
|
await resend.emails.send({
|
||||||
to,
|
from: EMAIL_FROM,
|
||||||
subject,
|
to,
|
||||||
text: body,
|
subject,
|
||||||
});
|
text: body,
|
||||||
|
});
|
||||||
|
|
||||||
emailSentTotal.inc({ type: "warning" });
|
logger.info({ userId, type: "warning", recipient: to }, "Email sent");
|
||||||
|
emailSentTotal.inc({ type: "warning" });
|
||||||
|
} catch (err) {
|
||||||
|
logger.error({ userId, type: "warning", err }, "Email failed");
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user