Repository navigation
Alert when a scheduled report sends no email #1236
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
10b21f9
Alert when a scheduled report sends no email
sidneyswift 18e77bf
Merge branch 'codex/email-send-reason' into codex/missed-report-check
sidneyswift a49a373
Harden the missed-report check from review
sidneyswift 5d23d0f
Merge remote-tracking branch 'origin/main' into codex/missed-report-c…
sidneyswift ed4f762
Keep the missed-report alert complete and readable
sidneyswift 2db073f
Count missing runs as unchecked and bound alert lines
sidneyswift File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| .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
144
lib/tasks/missedReports/__tests__/checkMissedReportsHandler.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
|
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
|
||
| expect(await response.json()).toEqual({ status: "error", message: "Internal server error" }); | ||
| }); | ||
| }); | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
selectEmailSendLogtable query. Extend that accessor with an opt-in throw-on-error mode and call it withaccountIdandcreatedAfterhere, so filters and error handling remain centralized.Prompt for AI agents