Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions app/api/internal/missed-report-check/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { NextRequest, NextResponse } from "next/server";
import { checkMissedReportsHandler } from "@/lib/tasks/missedReports/checkMissedReportsHandler";

export const dynamic = "force-dynamic";
export const fetchCache = "force-no-store";
export const revalidate = 0;

/**
* GET /api/internal/missed-report-check — hourly Vercel Cron entrypoint that
* finds scheduled reports that sent no email, tells the owner and alerts the
* team on Telegram. Cron-only (CRON_SECRET bearer).
*
* @param request - The incoming Next.js request.
* @returns A NextResponse with how many runs were checked, missed and notified.
*/
export async function GET(request: NextRequest): Promise<NextResponse> {
return checkMissedReportsHandler(request);
}
3 changes: 3 additions & 0 deletions lib/const.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ export const FOUNDER_FROM_EMAIL = `Patrick from Recoup <sweetman${OUTBOUND_EMAIL
/** Where Reply lands for founder-voiced outreach (personal inbox). */
export const FOUNDER_REPLY_TO_EMAIL = "sweetmantech@gmail.com";

/** Marker in email_send_log.raw_body for a missed scheduled-report notice. */
export const MISSED_REPORT_NOTICE_LOG_TYPE = "missed_report_notice";

/** Marker in email_send_log.raw_body for the abandoned-checkout follow-up. */
export const ABANDONED_CHECKOUT_EMAIL_LOG_TYPE = "abandoned_checkout_email";

Expand Down
10 changes: 2 additions & 8 deletions lib/credits/sendAutoTopUpEmail.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import selectAccountEmails from "@/lib/supabase/account_emails/selectAccountEmails";
import { sendEmailWithResend } from "@/lib/emails/sendEmail";
import { escapeHtml } from "@/lib/emails/escapeHtml";
import { pickAccountRecipient } from "@/lib/emails/pickAccountRecipient";
import { RECOUP_FROM_EMAIL } from "@/lib/const";
import { CREDIT_BILLING_URL } from "@/lib/credits/const";

Expand All @@ -27,20 +28,13 @@ const describeCard = (card?: ChargedCard): string =>

const BILLING_URL = `${CREDIT_BILLING_URL}/billing`;

/** The account's most recently updated non-empty email, or null. */
function pickRecipient(rows: { email: string | null; updated_at?: string }[]): string | null {
const withEmail = rows.filter(r => r.email);
withEmail.sort((a, b) => (b.updated_at ?? "").localeCompare(a.updated_at ?? ""));
return withEmail[0]?.email ?? null;
}

/**
* Receipt after a successful auto top-up charge (the credits land via the
* payment_intent.succeeded webhook moments later), or the notice that a
* decline turned auto top-up off. Silent when the account has no email.
*/
export async function sendAutoTopUpEmail(params: AutoTopUpEmail): Promise<void> {
const to = pickRecipient(await selectAccountEmails({ accountIds: params.accountId }));
const to = pickAccountRecipient(await selectAccountEmails({ accountIds: params.accountId }));
if (!to) {
console.warn(`[sendAutoTopUpEmail] no email for account ${params.accountId}`);
return;
Expand Down
19 changes: 19 additions & 0 deletions lib/emails/__tests__/pickAccountRecipient.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { describe, it, expect } from "vitest";
import { pickAccountRecipient } from "../pickAccountRecipient";

describe("pickAccountRecipient", () => {
it("returns the most recently updated non-empty email", () => {
expect(
pickAccountRecipient([
{ email: "old@example.com", updated_at: "2026-01-01T00:00:00Z" },
{ email: null, updated_at: "2026-09-01T00:00:00Z" },
{ email: "new@example.com", updated_at: "2026-06-01T00:00:00Z" },
]),
).toBe("new@example.com");
});

it("returns null when the account has no email", () => {
expect(pickAccountRecipient([{ email: null }])).toBeNull();
expect(pickAccountRecipient([])).toBeNull();
});
});
11 changes: 11 additions & 0 deletions lib/emails/__tests__/validateSendEmailBody.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,17 @@ describe("validateSendEmailBody", () => {
});
});

it("caps the recipients named in the reason", async () => {
const disallowed = Array.from({ length: 8 }, (_, i) => `r${i}@example.com`);
mockAssertRecipientsAllowed.mockResolvedValue({ allowed: false, disallowed });
const request = createRequest({ to: disallowed, text: "body" }, { "x-api-key": "k" });
const result = await validateSendEmailBody(request);
expect(result).toMatchObject({
reason:
"recipient_not_allowed: r0@example.com, r1@example.com, r2@example.com, r3@example.com, r4@example.com and 3 more",
});
});

it("names the failing field when the body is invalid", async () => {
const request = createRequest({ to: ["d@example.com"], html: " " }, { "x-api-key": "k" });
const result = await validateSendEmailBody(request);
Expand Down
14 changes: 14 additions & 0 deletions lib/emails/pickAccountRecipient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* The account's most recently updated non-empty email, or null — the one
* address an account-level notice goes to.
*
* @param rows - The account's `account_emails` rows.
* @returns The chosen address, or null when the account has none.
*/
export function pickAccountRecipient(
rows: { email: string | null; updated_at?: string }[],
): string | null {
const withEmail = rows.filter(r => r.email);
withEmail.sort((a, b) => (b.updated_at ?? "").localeCompare(a.updated_at ?? ""));
return withEmail[0]?.email ?? null;
}
6 changes: 5 additions & 1 deletion lib/emails/validateSendEmailBody.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,11 @@ export async function validateSendEmailBody(
},
{ status: 403, headers: getCorsHeaders() },
),
reason: `recipient_not_allowed: ${recipientCheck.disallowed.join(", ")}`,
reason: `recipient_not_allowed: ${recipientCheck.disallowed.slice(0, 5).join(", ")}${
recipientCheck.disallowed.length > 5
? ` and ${recipientCheck.disallowed.length - 5} more`
: ""
}`,
accountId: authContext.accountId,
};
}
Expand Down
28 changes: 28 additions & 0 deletions lib/supabase/email_send_log/selectAccountEmailAttempts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import supabase from "../serverClient";
import type { Tables } from "@/types/database.types";

/**
* Every `email_send_log` row for an account since a moment. Unlike
* `selectEmailSendLog`, a read error throws: a caller deciding whether a
* report was sent must not mistake "unknown" for "nothing sent".
*
* @param params - The account and the inclusive ISO lower bound.
* @param params.accountId - The sending account.
* @param params.since - Inclusive lower bound on `created_at`.
* @returns The account's send attempts since then.
*/
export async function selectAccountEmailAttempts({
accountId,
since,
}: {
accountId: string;
since: string;
}): Promise<Tables<"email_send_log">[]> {
const { data, error } = await supabase

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This duplicates the existing selectEmailSendLog table query. Extend that accessor with an opt-in throw-on-error mode and call it with accountId and createdAfter here, so filters and error handling remain centralized.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At lib/supabase/email_send_log/selectAccountEmailAttempts.ts, line 21:

<comment>This duplicates the existing `selectEmailSendLog` table query. Extend that accessor with an opt-in throw-on-error mode and call it with `accountId` and `createdAfter` here, so filters and error handling remain centralized.</comment>

<file context>
@@ -0,0 +1,28 @@
+  accountId: string;
+  since: string;
+}): Promise<Tables<"email_send_log">[]> {
+  const { data, error } = await supabase
+    .from("email_send_log")
+    .select("*")
</file context>

.from("email_send_log")
.select("*")
.eq("account_id", accountId)
.gte("created_at", since);
if (error) throw new Error(`Failed to read email_send_log: ${error.message}`);
return data ?? [];
}
144 changes: 144 additions & 0 deletions lib/tasks/missedReports/__tests__/checkMissedReportsHandler.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { NextRequest, NextResponse } from "next/server";
import { reportRun, reportTask } from "./fixtures";

const mockValidate = vi.fn();
vi.mock("@/lib/internal/validateCronRequest", () => ({
validateCronRequest: (...args: unknown[]) => mockValidate(...args),
}));
const mockListRuns = vi.fn();
vi.mock("../listScheduledReportRuns", () => ({
listScheduledReportRuns: (...args: unknown[]) => mockListRuns(...args),
}));
const mockSelectTasks = vi.fn();
vi.mock("@/lib/supabase/scheduled_actions/selectScheduledActions", () => ({
selectScheduledActions: (...args: unknown[]) => mockSelectTasks(...args),
}));
const mockFindMissed = vi.fn();
vi.mock("../findMissedReport", () => ({
findMissedReport: (...args: unknown[]) => mockFindMissed(...args),
}));
const mockNotice = vi.fn();
vi.mock("../sendMissedReportNotice", () => ({
sendMissedReportNotice: (...args: unknown[]) => mockNotice(...args),
}));
const mockSendMessage = vi.fn();
vi.mock("@/lib/telegram/sendMessage", () => ({
sendMessage: (...args: unknown[]) => mockSendMessage(...args),
}));

const { checkMissedReportsHandler } = await import("../checkMissedReportsHandler");

const request = () => new NextRequest("http://localhost/api/internal/missed-report-check");
const miss = { task: reportTask, run: reportRun, cause: "no_email", detail: "run completed" };

describe("checkMissedReportsHandler", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-11-06T13:17:00.000Z"));
vi.spyOn(console, "error").mockImplementation(() => {});
mockValidate.mockReturnValue(null);
mockListRuns.mockResolvedValue({ runs: [reportRun], unreadable: 0, truncated: false });
mockSelectTasks.mockResolvedValue([reportTask]);
mockFindMissed.mockResolvedValue(null);
mockNotice.mockResolvedValue(true);
});
afterEach(() => vi.useRealTimers());

it("rejects callers other than Vercel Cron", async () => {
mockValidate.mockReturnValue(NextResponse.json({}, { status: 401 }));
const response = await checkMissedReportsHandler(request());
expect(response.status).toBe(401);
expect(mockListRuns).not.toHaveBeenCalled();
});

// Hour-aligned windows ending two hours back: each run lands in one window
// whatever second the cron fires, after a two-hour grace for long reports.
it("checks the clock hour that started two to three hours ago", async () => {
await checkMissedReportsHandler(request());
expect(mockListRuns).toHaveBeenCalledWith({
from: "2026-11-06T10:00:00.000Z",
to: "2026-11-06T10:59:59.999Z",
});
vi.setSystemTime(new Date("2026-11-06T13:17:59.000Z"));
await checkMissedReportsHandler(request());
expect(mockListRuns).toHaveBeenLastCalledWith({
from: "2026-11-06T10:00:00.000Z",
to: "2026-11-06T10:59:59.999Z",
});
});

it("stays quiet when every report went out", async () => {
const response = await checkMissedReportsHandler(request());
expect(await response.json()).toEqual({
status: "ok",
checked: 1,
missed: 0,
notified: 0,
unchecked: 0,
});
expect(mockSendMessage).not.toHaveBeenCalled();
});

it("emails the customer and alerts the team about a missed report", async () => {
mockFindMissed.mockResolvedValue(miss);
const response = await checkMissedReportsHandler(request());
expect(await response.json()).toEqual({
status: "ok",
checked: 1,
missed: 1,
notified: 1,
unchecked: 0,
});
expect(mockNotice).toHaveBeenCalledWith(miss);
expect(mockSendMessage).toHaveBeenCalledTimes(1);
expect(mockSendMessage.mock.calls[0][0]).toContain("customer emailed");
});

it("skips runs whose task was deleted or turned off", async () => {
mockListRuns.mockResolvedValue({
runs: [reportRun, { ...reportRun, runId: "run_2", taskId: "gone" }],
unreadable: 0,
truncated: false,
});
mockSelectTasks.mockImplementation(async ({ id }: { id: string }) =>
id === "gone" ? [] : [{ ...reportTask, enabled: false }],
);
await checkMissedReportsHandler(request());
expect(mockFindMissed).not.toHaveBeenCalled();
});

it("still alerts the team when the customer notice throws", async () => {
mockFindMissed.mockResolvedValue(miss);
mockNotice.mockRejectedValue(new Error("resend down"));
const response = await checkMissedReportsHandler(request());
expect(await response.json()).toMatchObject({ missed: 1, notified: 0 });
expect(mockSendMessage.mock.calls[0][0]).toContain("customer not emailed");
});

it("keeps checking, and still alerts, when one run cannot be checked", async () => {
mockListRuns.mockResolvedValue({
runs: [{ ...reportRun, runId: "run_bad", taskId: "task-bad" }, reportRun],
unreadable: 1,
truncated: false,
});
mockSelectTasks.mockImplementation(async ({ id }: { id: string }) => {
if (id === "task-bad") throw new Error("db down");
return [reportTask];
});
mockFindMissed.mockResolvedValue(miss);

const response = await checkMissedReportsHandler(request());

expect(await response.json()).toMatchObject({ missed: 1, unchecked: 2 });
expect(mockSendMessage.mock.calls[0][0]).toContain("2 scheduled runs could not be checked");
});

it("returns 500 when the run list cannot be read", async () => {
mockListRuns.mockRejectedValue(new Error("trigger down"));
const response = await checkMissedReportsHandler(request());
expect(response.status).toBe(500);
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
expect(await response.json()).toEqual({ status: "error", message: "Internal server error" });
});
});
Loading
Loading