diff --git a/app/api/internal/missed-report-check/route.ts b/app/api/internal/missed-report-check/route.ts new file mode 100644 index 000000000..518c96713 --- /dev/null +++ b/app/api/internal/missed-report-check/route.ts @@ -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 { + return checkMissedReportsHandler(request); +} diff --git a/lib/const.ts b/lib/const.ts index 9f2da08b5..899e905fc 100644 --- a/lib/const.ts +++ b/lib/const.ts @@ -50,6 +50,9 @@ export const FOUNDER_FROM_EMAIL = `Patrick from Recoup 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 { - 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; diff --git a/lib/emails/__tests__/pickAccountRecipient.test.ts b/lib/emails/__tests__/pickAccountRecipient.test.ts new file mode 100644 index 000000000..c471fc89a --- /dev/null +++ b/lib/emails/__tests__/pickAccountRecipient.test.ts @@ -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(); + }); +}); diff --git a/lib/emails/__tests__/validateSendEmailBody.test.ts b/lib/emails/__tests__/validateSendEmailBody.test.ts index 05a428459..cebeb86cf 100644 --- a/lib/emails/__tests__/validateSendEmailBody.test.ts +++ b/lib/emails/__tests__/validateSendEmailBody.test.ts @@ -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); diff --git a/lib/emails/pickAccountRecipient.ts b/lib/emails/pickAccountRecipient.ts new file mode 100644 index 000000000..ded179837 --- /dev/null +++ b/lib/emails/pickAccountRecipient.ts @@ -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; +} diff --git a/lib/emails/validateSendEmailBody.ts b/lib/emails/validateSendEmailBody.ts index bcec16611..b65b4b171 100644 --- a/lib/emails/validateSendEmailBody.ts +++ b/lib/emails/validateSendEmailBody.ts @@ -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, }; } diff --git a/lib/supabase/email_send_log/selectAccountEmailAttempts.ts b/lib/supabase/email_send_log/selectAccountEmailAttempts.ts new file mode 100644 index 000000000..0a9c107a3 --- /dev/null +++ b/lib/supabase/email_send_log/selectAccountEmailAttempts.ts @@ -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[]> { + 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 ?? []; +} diff --git a/lib/tasks/missedReports/__tests__/checkMissedReportsHandler.test.ts b/lib/tasks/missedReports/__tests__/checkMissedReportsHandler.test.ts new file mode 100644 index 000000000..fc4955f30 --- /dev/null +++ b/lib/tasks/missedReports/__tests__/checkMissedReportsHandler.test.ts @@ -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); + expect(await response.json()).toEqual({ status: "error", message: "Internal server error" }); + }); +}); diff --git a/lib/tasks/missedReports/__tests__/findMissedReport.test.ts b/lib/tasks/missedReports/__tests__/findMissedReport.test.ts new file mode 100644 index 000000000..68de2c2ba --- /dev/null +++ b/lib/tasks/missedReports/__tests__/findMissedReport.test.ts @@ -0,0 +1,111 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { reportRun, reportTask } from "./fixtures"; + +const mockSelectEmailSendLog = vi.fn(); +vi.mock("@/lib/supabase/email_send_log/selectAccountEmailAttempts", () => ({ + selectAccountEmailAttempts: (...args: unknown[]) => mockSelectEmailSendLog(...args), +})); + +const mockGetTaskRunBlock = vi.fn(); +vi.mock("@/lib/plans/getTaskRunBlock", () => ({ + getTaskRunBlock: (...args: unknown[]) => mockGetTaskRunBlock(...args), +})); + +const { findMissedReport } = await import("../findMissedReport"); + +const row = (status: string, created_at: string, reason: string | null = null) => ({ + id: created_at, + account_id: "acc-1", + chat_id: null, + created_at, + raw_body: "{}", + reason, + resend_id: null, + status, +}); + +describe("findMissedReport", () => { + beforeEach(() => { + vi.clearAllMocks(); + mockSelectEmailSendLog.mockResolvedValue([]); + mockGetTaskRunBlock.mockResolvedValue(null); + }); + + it("ignores a task whose prompt never asks for an email", async () => { + const result = await findMissedReport({ + run: reportRun, + task: { ...reportTask, prompt: "Summarize this week's streams in the chat." }, + }); + expect(result).toBeNull(); + expect(mockSelectEmailSendLog).not.toHaveBeenCalled(); + }); + + it("is not missed when the account sent an email after the run started", async () => { + mockSelectEmailSendLog.mockResolvedValue([row("sent", "2026-11-06T10:50:00.000Z")]); + expect(await findMissedReport({ run: reportRun, task: reportTask })).toBeNull(); + expect(mockSelectEmailSendLog).toHaveBeenCalledWith({ + accountId: "acc-1", + since: reportRun.createdAt, + }); + }); + + it("names the plan limit when the plan blocked the run", async () => { + mockGetTaskRunBlock.mockResolvedValue({ + message: "Free includes 1 task. Starter includes 3, Pro is unlimited.", + billingUrl: "https://app.recoupable.dev/plan", + }); + expect(await findMissedReport({ run: reportRun, task: reportTask })).toEqual({ + task: reportTask, + run: reportRun, + cause: "plan_blocked", + detail: "Free includes 1 task. Starter includes 3, Pro is unlimited.", + billingUrl: "https://app.recoupable.dev/plan", + }); + }); + + it("reports the latest rejection reason when the send was refused", async () => { + mockSelectEmailSendLog.mockResolvedValue([ + row("rejected", "2026-11-06T10:40:00.000Z", "invalid_body: html: empty"), + row("rejected", "2026-11-06T10:45:00.000Z", "recipient_not_allowed: a@example.com"), + ]); + const result = await findMissedReport({ run: reportRun, task: reportTask }); + expect(result).toMatchObject({ + cause: "email_rejected", + detail: "recipient_not_allowed: a@example.com", + }); + }); + + // The block is read at check time; a send attempt proves the run went ahead. + it("reports the rejection, not the plan, when the run attempted a send", async () => { + mockGetTaskRunBlock.mockResolvedValue({ message: "Free includes 1 task.", billingUrl: "x" }); + mockSelectEmailSendLog.mockResolvedValue([ + row("rejected", "2026-11-06T10:40:00.000Z", "invalid_body: html: empty"), + ]); + const result = await findMissedReport({ run: reportRun, task: reportTask }); + expect(result).toMatchObject({ cause: "email_rejected" }); + expect(mockGetTaskRunBlock).not.toHaveBeenCalled(); + }); + + // An unreadable log is unknown, not "nothing sent": never tell a customer + // their report failed because of our own read error. + it("throws when the email log cannot be read", async () => { + mockSelectEmailSendLog.mockRejectedValue(new Error("db down")); + await expect(findMissedReport({ run: reportRun, task: reportTask })).rejects.toThrow("db down"); + }); + + it("names a stalled run that is still executing", async () => { + const result = await findMissedReport({ + run: { ...reportRun, status: "EXECUTING" }, + task: reportTask, + }); + expect(result).toMatchObject({ cause: "no_email", detail: "no send attempted; run executing" }); + }); + + it("falls back to the run status when no send was attempted", async () => { + const result = await findMissedReport({ + run: { ...reportRun, status: "FAILED" }, + task: reportTask, + }); + expect(result).toMatchObject({ cause: "no_email", detail: "no send attempted; run failed" }); + }); +}); diff --git a/lib/tasks/missedReports/__tests__/fixtures.ts b/lib/tasks/missedReports/__tests__/fixtures.ts new file mode 100644 index 000000000..25dfe6acf --- /dev/null +++ b/lib/tasks/missedReports/__tests__/fixtures.ts @@ -0,0 +1,23 @@ +import type { Tables } from "@/types/database.types"; +import type { ScheduledReportRun } from "../types"; + +export const reportTask: Tables<"scheduled_actions"> = { + id: "task-1", + account_id: "acc-1", + artist_account_id: "artist-1", + created_at: "2026-10-01T00:00:00.000Z", + enabled: true, + model: null, + prompt: "Generate a monthly report, then email it to owner@example.com.", + schedule: "20 15 6 * *", + title: "Monthly Catalog Report: Luh Tyler", + trigger_schedule_id: "sched_1", + updated_at: null, +}; + +export const reportRun: ScheduledReportRun = { + runId: "run_1", + taskId: "task-1", + createdAt: "2026-11-06T10:20:00.000Z", + status: "COMPLETED", +}; diff --git a/lib/tasks/missedReports/__tests__/formatMissedReportsAlert.test.ts b/lib/tasks/missedReports/__tests__/formatMissedReportsAlert.test.ts new file mode 100644 index 000000000..79d02557d --- /dev/null +++ b/lib/tasks/missedReports/__tests__/formatMissedReportsAlert.test.ts @@ -0,0 +1,101 @@ +import { describe, it, expect } from "vitest"; +import { formatMissedReportsAlert } from "../formatMissedReportsAlert"; +import { reportRun, reportTask } from "./fixtures"; + +describe("formatMissedReportsAlert", () => { + it("lists each missed report with its cause, account, run and notice state", () => { + const text = formatMissedReportsAlert( + [ + { + task: reportTask, + run: reportRun, + cause: "email_rejected", + detail: "recipient_not_allowed: a@example.com", + customerNotified: true, + }, + { + task: { ...reportTask, id: "task-2", title: "Daily fan digest", account_id: "acc-2" }, + run: { ...reportRun, runId: "run_2" }, + cause: "no_email", + detail: "no send attempted; run completed", + customerNotified: false, + }, + ], + { unchecked: 0, truncated: false }, + ); + + expect(text).toContain("2 scheduled reports did not send"); + expect(text).toContain( + "Monthly Catalog Report: Luh Tyler: email rejected (recipient_not_allowed: a@example.com)", + ); + expect(text).toContain("account acc-1, run run_1, customer emailed"); + expect(text).toContain("Daily fan digest: no email (no send attempted; run completed)"); + expect(text).toContain("account acc-2, run run_2, customer not emailed"); + }); + + it("uses the singular for one report", () => { + const text = formatMissedReportsAlert( + [ + { + task: reportTask, + run: reportRun, + cause: "plan_blocked", + detail: "Free includes 1 task.", + customerNotified: false, + }, + ], + { unchecked: 0, truncated: false }, + ); + expect(text).toContain("1 scheduled report did not send"); + expect(text).toContain("plan blocked (Free includes 1 task.)"); + }); + + it("says how many runs could not be checked", () => { + const text = formatMissedReportsAlert([], { unchecked: 2, truncated: false }); + expect(text).toContain("2 scheduled runs could not be checked"); + expect(text).not.toContain("0 scheduled reports did not send"); + expect(formatMissedReportsAlert([], { unchecked: 1, truncated: false })).toContain( + "1 scheduled run could not be checked", + ); + }); + + // Telegram cuts messages at 4,000 characters; keep every alert readable. + it("lists at most 10 reports and counts the rest", () => { + const miss = { + task: reportTask, + run: reportRun, + cause: "no_email" as const, + detail: "no send attempted; run completed", + customerNotified: false, + }; + const text = formatMissedReportsAlert(Array(25).fill(miss), { + unchecked: 0, + truncated: false, + }); + expect(text.match(/^• /gm)).toHaveLength(10); + expect(text).toContain("…and 15 more"); + expect(text.length).toBeLessThan(4000); + }); + + it("says when the hour held more runs than one page", () => { + expect(formatMissedReportsAlert([], { unchecked: 0, truncated: true })).toContain( + "More than 100 runs started in that hour", + ); + }); + + it("shortens long titles and details so the alert stays within Telegram's limit", () => { + const miss = { + task: { ...reportTask, title: "T".repeat(500) }, + run: reportRun, + cause: "email_rejected" as const, + detail: "D".repeat(1000), + customerNotified: false, + }; + const text = formatMissedReportsAlert(Array(20).fill(miss), { + unchecked: 0, + truncated: false, + }); + expect(text.length).toBeLessThan(4000); + expect(text).toContain("…"); + }); +}); diff --git a/lib/tasks/missedReports/__tests__/listScheduledReportRuns.test.ts b/lib/tasks/missedReports/__tests__/listScheduledReportRuns.test.ts new file mode 100644 index 000000000..bb07009b3 --- /dev/null +++ b/lib/tasks/missedReports/__tests__/listScheduledReportRuns.test.ts @@ -0,0 +1,109 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mockFetchTriggerRuns = vi.fn(); +vi.mock("@/lib/trigger/fetchTriggerRuns", () => ({ + fetchTriggerRuns: (...args: unknown[]) => mockFetchTriggerRuns(...args), +})); + +const mockRetrieveTaskRun = vi.fn(); +vi.mock("@/lib/trigger/retrieveTaskRun", () => ({ + retrieveTaskRun: (...args: unknown[]) => mockRetrieveTaskRun(...args), +})); + +const { listScheduledReportRuns } = await import("../listScheduledReportRuns"); + +const window = { from: "2026-11-06T10:00:00.000Z", to: "2026-11-06T11:00:00.000Z" }; + +describe("listScheduledReportRuns", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.spyOn(console, "error").mockImplementation(() => {}); + vi.spyOn(console, "warn").mockImplementation(() => {}); + }); + + it("lists the scheduled task's runs in the window and resolves each to its task", async () => { + mockFetchTriggerRuns.mockResolvedValue([ + { id: "run_1", status: "COMPLETED", createdAt: "2026-11-06T10:20:00.000Z" }, + ]); + mockRetrieveTaskRun.mockResolvedValue({ schedule: { externalId: "task-1" } }); + + const { runs } = await listScheduledReportRuns(window); + + expect(mockFetchTriggerRuns).toHaveBeenCalledWith( + { + "filter[taskIdentifier]": "customer-prompt-task", + "filter[createdAt][from]": window.from, + "filter[createdAt][to]": window.to, + }, + 100, + ); + expect(runs).toEqual([ + { + runId: "run_1", + taskId: "task-1", + createdAt: "2026-11-06T10:20:00.000Z", + status: "COMPLETED", + }, + ]); + }); + + it("skips runs with no task id and runs that cannot be read", async () => { + mockFetchTriggerRuns.mockResolvedValue([ + { id: "run_manual", status: "COMPLETED", createdAt: "2026-11-06T10:01:00.000Z" }, + { id: "run_broken", status: "COMPLETED", createdAt: "2026-11-06T10:02:00.000Z" }, + { id: "run_ok", status: "FAILED", createdAt: "2026-11-06T10:03:00.000Z" }, + { id: "run_gone", status: "COMPLETED", createdAt: "2026-11-06T10:04:00.000Z" }, + ]); + mockRetrieveTaskRun.mockImplementation(async (id: string) => { + if (id === "run_manual") return { schedule: undefined }; + if (id === "run_gone") return null; + if (id === "run_broken") throw new Error("trigger down"); + return { schedule: { externalId: "task-2" } }; + }); + + const { runs, unreadable } = await listScheduledReportRuns(window); + + expect(runs.map(run => run.runId)).toEqual(["run_ok"]); + // run_broken threw and run_gone came back empty; a manual run is simply not scheduled. + expect(unreadable).toBe(2); + expect(console.error).toHaveBeenCalled(); + }); + + it("warns when the window may hold more runs than one page", async () => { + mockFetchTriggerRuns.mockResolvedValue( + Array.from({ length: 100 }, (_, i) => ({ + id: `run_${i}`, + status: "COMPLETED", + createdAt: "2026-11-06T10:00:00.000Z", + })), + ); + mockRetrieveTaskRun.mockResolvedValue(null); + + const { truncated } = await listScheduledReportRuns(window); + + expect(truncated).toBe(true); + expect(console.warn).toHaveBeenCalled(); + }); + + // One hung Trigger.dev read must not stall the whole check. + it("gives up on a run read that does not answer in time", async () => { + vi.useFakeTimers(); + mockFetchTriggerRuns.mockResolvedValue([ + { id: "run_hung", status: "COMPLETED", createdAt: "2026-11-06T10:01:00.000Z" }, + { id: "run_ok", status: "COMPLETED", createdAt: "2026-11-06T10:02:00.000Z" }, + ]); + mockRetrieveTaskRun.mockImplementation((id: string) => + id === "run_hung" + ? new Promise(() => {}) + : Promise.resolve({ schedule: { externalId: "task-1" } }), + ); + + const pending = listScheduledReportRuns(window); + await vi.advanceTimersByTimeAsync(5_000); + const { runs, unreadable } = await pending; + + expect(runs.map(run => run.runId)).toEqual(["run_ok"]); + expect(unreadable).toBe(1); + vi.useRealTimers(); + }); +}); diff --git a/lib/tasks/missedReports/__tests__/sendMissedReportNotice.test.ts b/lib/tasks/missedReports/__tests__/sendMissedReportNotice.test.ts new file mode 100644 index 000000000..c1690940b --- /dev/null +++ b/lib/tasks/missedReports/__tests__/sendMissedReportNotice.test.ts @@ -0,0 +1,130 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { NextResponse } from "next/server"; +import { reportRun, reportTask } from "./fixtures"; +import type { MissedReport } from "../types"; + +const mockSelectAccountEmails = vi.fn(); +vi.mock("@/lib/supabase/account_emails/selectAccountEmails", () => ({ + default: (...args: unknown[]) => mockSelectAccountEmails(...args), +})); + +const mockSend = vi.fn(); +vi.mock("@/lib/emails/sendEmail", () => ({ + sendEmailWithResend: (...args: unknown[]) => mockSend(...args), +})); + +const mockSelectEmailSendLog = vi.fn(); +vi.mock("@/lib/supabase/email_send_log/selectEmailSendLog", () => ({ + selectEmailSendLog: (...args: unknown[]) => mockSelectEmailSendLog(...args), +})); + +const mockLogEmailAttempt = vi.fn(); +vi.mock("@/lib/emails/logEmailAttempt", () => ({ + logEmailAttempt: (...args: unknown[]) => mockLogEmailAttempt(...args), +})); + +const { sendMissedReportNotice } = await import("../sendMissedReportNotice"); + +const rejected: MissedReport = { + task: reportTask, + run: reportRun, + cause: "email_rejected", + detail: "recipient_not_allowed: a@example.com", +}; +const blocked: MissedReport = { + task: { ...reportTask, title: "Daily digest" }, + run: reportRun, + cause: "plan_blocked", + detail: "Free runs tasks weekly at most. Starter runs daily, Pro runs hourly.", + billingUrl: "https://app.recoupable.dev/plan", +}; + +describe("sendMissedReportNotice", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.stubEnv("MISSED_REPORT_CUSTOMER_NOTICES", "true"); + mockSelectAccountEmails.mockResolvedValue([{ email: "owner@example.com" }]); + mockSend.mockResolvedValue({ id: "re_1" }); + mockSelectEmailSendLog.mockResolvedValue([]); + }); + afterEach(() => vi.unstubAllEnvs()); + + it("sends nothing while customer notices are switched off", async () => { + vi.stubEnv("MISSED_REPORT_CUSTOMER_NOTICES", ""); + expect(await sendMissedReportNotice(rejected)).toBe(false); + expect(mockSend).not.toHaveBeenCalled(); + }); + + it("tells the account owner a report did not arrive", async () => { + expect(await sendMissedReportNotice(rejected)).toBe(true); + expect(mockSelectAccountEmails).toHaveBeenCalledWith({ accountIds: "acc-1" }); + const email = mockSend.mock.calls[0][0]; + expect(email.to).toBe("owner@example.com"); + expect(email.subject).toBe("Your report didn't go out: Monthly Catalog Report: Luh Tyler"); + expect(email.html).toContain("We've been alerted"); + expect(email.html).not.toMatch(/reply/i); + // A duplicate cron delivery for the same run must not email twice. + expect(mockSend.mock.calls[0][1]).toEqual({ idempotencyKey: "missed-report/run_1" }); + }); + + // A blocked task fires on every scheduled run; tell the owner once a month, + // not every hour. The notice log row carries no account_id, so it never + // counts as the account's report being sent. + it("sends a plan-block notice once per task per 30 days and logs it without an account", async () => { + expect(await sendMissedReportNotice(blocked)).toBe(true); + expect(mockSelectEmailSendLog).toHaveBeenCalledWith( + expect.objectContaining({ + rawBodyLike: "missed_report_notice:task-1:plan_blocked", + limit: 1, + }), + ); + expect(mockLogEmailAttempt).toHaveBeenCalledWith({ + rawBody: JSON.stringify({ + type: "missed_report_notice:task-1:plan_blocked", + account_id: "acc-1", + run_id: "run_1", + }), + status: "sent", + resendId: "re_1", + }); + + vi.clearAllMocks(); + mockSelectEmailSendLog.mockResolvedValue([{ id: "earlier-notice" }]); + expect(await sendMissedReportNotice(blocked)).toBe(false); + expect(mockSend).not.toHaveBeenCalled(); + }); + + it("explains a plan block with the upgrade link, escaping the task title", async () => { + expect(await sendMissedReportNotice(blocked)).toBe(true); + const email = mockSend.mock.calls[0][0]; + expect(email.subject).toBe("Your task didn't run: Daily digest"); + expect(email.html).toContain("Daily <fan> digest"); + expect(email.html).toContain("Free runs tasks weekly at most."); + expect(email.html).toContain('href="https://app.recoupable.dev/plan"'); + }); + + it("only emails about other failures for the catalog report tasks", async () => { + const custom = { ...rejected, task: { ...reportTask, title: "Daily fan digest" } }; + expect(await sendMissedReportNotice(custom)).toBe(false); + expect(mockSend).not.toHaveBeenCalled(); + }); + + it("returns false when the account has no email or the send fails", async () => { + mockSelectAccountEmails.mockResolvedValue([]); + expect(await sendMissedReportNotice(rejected)).toBe(false); + + mockSelectAccountEmails.mockResolvedValue([{ email: "owner@example.com" }]); + mockSend.mockResolvedValue(NextResponse.json({ error: "x" }, { status: 502 })); + expect(await sendMissedReportNotice(rejected)).toBe(false); + }); + + it("keeps line breaks in a task title out of the subject", async () => { + await sendMissedReportNotice({ + ...rejected, + task: { ...reportTask, title: "Monthly Catalog Report: A\r\nBcc: x@example.com" }, + }); + expect(mockSend.mock.calls[0][0].subject).toBe( + "Your report didn't go out: Monthly Catalog Report: A Bcc: x@example.com", + ); + }); +}); diff --git a/lib/tasks/missedReports/checkMissedReportsHandler.ts b/lib/tasks/missedReports/checkMissedReportsHandler.ts new file mode 100644 index 000000000..8ddf5e741 --- /dev/null +++ b/lib/tasks/missedReports/checkMissedReportsHandler.ts @@ -0,0 +1,80 @@ +import { NextRequest, NextResponse } from "next/server"; +import { validateCronRequest } from "@/lib/internal/validateCronRequest"; +import { selectScheduledActions } from "@/lib/supabase/scheduled_actions/selectScheduledActions"; +import { sendMessage } from "@/lib/telegram/sendMessage"; +import { listScheduledReportRuns } from "./listScheduledReportRuns"; +import { findMissedReport } from "./findMissedReport"; +import { sendMissedReportNotice } from "./sendMissedReportNotice"; +import { formatMissedReportsAlert } from "./formatMissedReportsAlert"; +import type { NotifiedMissedReport } from "./types"; + +const HOUR_MS = 60 * 60_000; +/** Long reports finish well inside two hours; checking the hour that began three hours ago leaves at least that. */ +const HOURS_BACK = 3; + +/** + * Handler for `GET /api/internal/missed-report-check` (recoupable/app#1949, + * #2022). Cron-only. Finds scheduled runs that started 2-3 hours ago and + * asked for an email but sent none — plan-blocked, stalled, rejected or + * simply skipped — then emails the owner (see `sendMissedReportNotice`) and + * posts one Telegram alert. The window is the clock hour that started three + * hours ago, so each run lands in exactly one window whatever second the cron + * fires; a duplicated cron delivery re-alerts the team, but the customer + * notice carries a per-run idempotency key. One run that cannot be checked + * is counted and skipped rather than ending the batch. + * + * @param request - The incoming Next.js request. + * @returns A NextResponse with how many runs were checked, missed and notified. + */ +export async function checkMissedReportsHandler(request: NextRequest): Promise { + const unauthorized = validateCronRequest(request); + if (unauthorized) return unauthorized; + + try { + const currentHour = Math.floor(Date.now() / HOUR_MS) * HOUR_MS; + const windowStart = currentHour - HOURS_BACK * HOUR_MS; + const { runs, unreadable, truncated } = await listScheduledReportRuns({ + from: new Date(windowStart).toISOString(), + to: new Date(windowStart + HOUR_MS - 1).toISOString(), + }); + + const misses: NotifiedMissedReport[] = []; + let unchecked = unreadable; + for (const run of runs) { + try { + const [task] = await selectScheduledActions({ id: run.taskId }); + if (!task || task.enabled === false) continue; + + const miss = await findMissedReport({ run, task }); + if (!miss) continue; + + const customerNotified = await sendMissedReportNotice(miss).catch(error => { + console.error(`[missed-report-check] notice failed for task ${task.id}:`, error); + return false; + }); + misses.push({ ...miss, customerNotified }); + } catch (error) { + unchecked += 1; + console.error(`[missed-report-check] could not check run ${run.runId}:`, error); + } + } + + if (misses.length > 0 || unchecked > 0 || truncated) { + await sendMessage(formatMissedReportsAlert(misses, { unchecked, truncated })); + } + + return NextResponse.json({ + status: "ok", + checked: runs.length, + missed: misses.length, + notified: misses.filter(miss => miss.customerNotified).length, + unchecked, + }); + } catch (error) { + console.error("[ERROR] checkMissedReportsHandler:", error); + return NextResponse.json( + { status: "error", message: "Internal server error" }, + { status: 500 }, + ); + } +} diff --git a/lib/tasks/missedReports/findMissedReport.ts b/lib/tasks/missedReports/findMissedReport.ts new file mode 100644 index 000000000..bfd7ea454 --- /dev/null +++ b/lib/tasks/missedReports/findMissedReport.ts @@ -0,0 +1,63 @@ +import type { Tables } from "@/types/database.types"; +import { selectAccountEmailAttempts } from "@/lib/supabase/email_send_log/selectAccountEmailAttempts"; +import { getTaskRunBlock } from "@/lib/plans/getTaskRunBlock"; +import type { MissedReport, ScheduledReportRun } from "./types"; + +/** Only tasks that ask for an email can be checked against email_send_log. */ +const EMAILS = /\bemail/i; + +/** + * Whether a scheduled run that asked for an email failed to send one, and + * why. "Sent" is any successful send from the task's account after the run + * started, so two of an account's tasks firing together can mask each other. + * The plan is read now, not at run time, so it only explains a run that + * attempted no send. Throws when the email log cannot be read. + * + * @param input - The run and the task it ran. + * @param input.run - The scheduled run. + * @param input.task - Its `scheduled_actions` row. + * @returns The miss and its cause, or null when nothing is missing. + */ +export async function findMissedReport({ + run, + task, +}: { + run: ScheduledReportRun; + task: Tables<"scheduled_actions">; +}): Promise { + if (!EMAILS.test(task.prompt)) return null; + + const attempts = await selectAccountEmailAttempts({ + accountId: task.account_id, + since: run.createdAt, + }); + if (attempts.some(attempt => attempt.status === "sent")) return null; + + const block = attempts.length === 0 ? await getTaskRunBlock(task) : null; + if (block) { + return { + task, + run, + cause: "plan_blocked", + detail: block.message, + billingUrl: block.billingUrl, + }; + } + + const [latestFailure] = attempts.sort((a, b) => b.created_at.localeCompare(a.created_at)); + if (latestFailure) { + return { + task, + run, + cause: "email_rejected", + detail: latestFailure.reason ?? latestFailure.status, + }; + } + + return { + task, + run, + cause: "no_email", + detail: `no send attempted; run ${run.status.toLowerCase()}`, + }; +} diff --git a/lib/tasks/missedReports/formatMissedReportsAlert.ts b/lib/tasks/missedReports/formatMissedReportsAlert.ts new file mode 100644 index 000000000..9b80b9d17 --- /dev/null +++ b/lib/tasks/missedReports/formatMissedReportsAlert.ts @@ -0,0 +1,53 @@ +import type { MissedReportCause, NotifiedMissedReport } from "./types"; + +const CAUSE_LABELS: Record = { + plan_blocked: "plan blocked", + email_rejected: "email rejected", + no_email: "no email", +}; + +/** Telegram cuts messages at 4,000 characters; with the field caps below, ten lines stay inside it. */ +const MAX_LISTED = 10; +const MAX_TITLE = 80; +const MAX_DETAIL = 120; + +const clip = (text: string, max: number): string => + text.length > max ? `${text.slice(0, max - 1)}…` : text; + +/** + * The team's Telegram alert for scheduled reports that did not send: one + * line per report with its cause, then the ids needed to look it up, plus + * what could not be checked. + * + * @param misses - The missed reports and whether each customer was emailed. + * @param coverage - What the check could not cover. + * @param coverage.unchecked - Runs that could not be read or checked. + * @param coverage.truncated - True when the hour held more runs than one page. + * @returns Plain text for `sendMessage`. + */ +export function formatMissedReportsAlert( + misses: NotifiedMissedReport[], + { unchecked, truncated }: { unchecked: number; truncated: boolean }, +): string { + const count = misses.length; + const header = + count > 0 + ? `⚠️ ${count} scheduled report${count === 1 ? "" : "s"} did not send (runs started 2-3 hours ago)` + : "⚠️ Missed-report check could not cover every run (runs started 2-3 hours ago)"; + const lines = misses + .slice(0, MAX_LISTED) + .map( + miss => + `• ${clip(miss.task.title, MAX_TITLE)}: ${CAUSE_LABELS[miss.cause]} (${clip(miss.detail, MAX_DETAIL)})\n account ${miss.task.account_id}, run ${miss.run.runId}, customer ${miss.customerNotified ? "emailed" : "not emailed"}`, + ); + const notes = [ + ...(count > MAX_LISTED ? [`…and ${count - MAX_LISTED} more`] : []), + ...(unchecked > 0 + ? [ + `${unchecked} scheduled run${unchecked === 1 ? "" : "s"} could not be checked; see the api logs.`, + ] + : []), + ...(truncated ? ["More than 100 runs started in that hour; later ones were not checked."] : []), + ]; + return [header, ...lines, ...notes].join("\n"); +} diff --git a/lib/tasks/missedReports/listScheduledReportRuns.ts b/lib/tasks/missedReports/listScheduledReportRuns.ts new file mode 100644 index 000000000..69f2661b1 --- /dev/null +++ b/lib/tasks/missedReports/listScheduledReportRuns.ts @@ -0,0 +1,79 @@ +import { fetchTriggerRuns } from "@/lib/trigger/fetchTriggerRuns"; +import { retrieveTaskRun } from "@/lib/trigger/retrieveTaskRun"; +import type { ScheduledReportRun } from "./types"; + +/** The Trigger.dev task every customer schedule runs (tasks repo). */ +const SCHEDULED_TASK_ID = "customer-prompt-task"; +/** One page of the runs API; an hour of schedules fits well inside it. */ +const MAX_RUNS = 100; +/** A hung Trigger.dev read must not stall the check (same budget as retrieveScheduleInfo). */ +const READ_TIMEOUT_MS = 5000; + +export interface ScheduledReportRunList { + runs: ScheduledReportRun[]; + /** Runs that could not be read in time or at all. */ + unreadable: number; + /** True when the window may hold more runs than one page. */ + truncated: boolean; +} + +/** + * Scheduled customer-task runs created inside a window, each resolved to its + * `scheduled_actions` id. The list endpoint omits schedule details, so each + * run is read once more, within a time budget; a run that cannot be read is + * counted and logged rather than holding up the rest. + * + * @param window - ISO bounds on the runs' `createdAt`. + * @param window.from - Inclusive lower bound. + * @param window.to - Upper bound. + * @returns The runs that belong to a task, plus what could not be checked. + */ +export async function listScheduledReportRuns({ + from, + to, +}: { + from: string; + to: string; +}): Promise { + const listed = await fetchTriggerRuns( + { + "filter[taskIdentifier]": SCHEDULED_TASK_ID, + "filter[createdAt][from]": from, + "filter[createdAt][to]": to, + }, + MAX_RUNS, + ); + const truncated = listed.length === MAX_RUNS; + if (truncated) { + console.warn(`[missed-report-check] ${MAX_RUNS}+ runs in ${from}..${to}; later ones unchecked`); + } + + let unreadable = 0; + const resolved = await Promise.all( + listed.map(async run => { + try { + const detail = await Promise.race([ + retrieveTaskRun(run.id), + new Promise((_, reject) => + setTimeout(() => reject(new Error("run read timed out")), READ_TIMEOUT_MS), + ), + ]); + // A listed run that cannot be found is unchecked; one without a schedule + // (a manual run) simply is not a scheduled report. + if (!detail) throw new Error("run not found"); + const taskId = detail.schedule?.externalId; + if (!taskId) return null; + return { runId: run.id, taskId, createdAt: run.createdAt, status: run.status }; + } catch (error) { + unreadable += 1; + console.error(`[missed-report-check] could not read run ${run.id}:`, error); + return null; + } + }), + ); + return { + runs: resolved.filter((run): run is ScheduledReportRun => run !== null), + unreadable, + truncated, + }; +} diff --git a/lib/tasks/missedReports/sendMissedReportNotice.ts b/lib/tasks/missedReports/sendMissedReportNotice.ts new file mode 100644 index 000000000..81d9d4df4 --- /dev/null +++ b/lib/tasks/missedReports/sendMissedReportNotice.ts @@ -0,0 +1,80 @@ +import { NextResponse } from "next/server"; +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 { logEmailAttempt } from "@/lib/emails/logEmailAttempt"; +import { selectEmailSendLog } from "@/lib/supabase/email_send_log/selectEmailSendLog"; +import { MISSED_REPORT_NOTICE_LOG_TYPE, RECOUP_FROM_EMAIL } from "@/lib/const"; +import type { MissedReport } from "./types"; + +/** + * Onboarding and the homepage card create these; they always email, so a run + * without a send is a real failure. Other tasks may email conditionally, so + * only a plan block (certain) reaches their owners. + */ +const REPORT_TASK_TITLE = /Catalog Report:/; +/** A blocked task fires on every scheduled run; remind its owner at most this often. */ +const PLAN_NOTICE_INTERVAL_MS = 30 * 24 * 60 * 60_000; + +/** + * Tells the account owner that a scheduled report did not arrive: why and + * where to upgrade when the plan blocked it, otherwise that the team has been + * alerted. Off unless `MISSED_REPORT_CUSTOMER_NOTICES` is "true", so the team + * alert can run alone until the volume is known. Each run's notice carries an + * idempotency key; plan-block notices are logged (without an account, so they + * never count as the report being sent) and repeat at most monthly per task. + * + * @param miss - The missed report. + * @returns Whether a notice was sent. + */ +export async function sendMissedReportNotice(miss: MissedReport): Promise { + if (process.env.MISSED_REPORT_CUSTOMER_NOTICES !== "true") return false; + if (miss.cause !== "plan_blocked" && !REPORT_TASK_TITLE.test(miss.task.title)) return false; + + const noticeType = `${MISSED_REPORT_NOTICE_LOG_TYPE}:${miss.task.id}:${miss.cause}`; + if (miss.cause === "plan_blocked") { + const earlier = await selectEmailSendLog({ + rawBodyLike: noticeType, + createdAfter: new Date(Date.now() - PLAN_NOTICE_INTERVAL_MS).toISOString(), + limit: 1, + }); + if (earlier.length > 0) return false; + } + + const to = pickAccountRecipient(await selectAccountEmails({ accountIds: miss.task.account_id })); + if (!to) return false; + + // Titles are account-entered; keep control characters out of the header. + const plainTitle = miss.task.title.replace(/[\u0000-\u001f\u007f]+/g, " ").trim(); + const title = escapeHtml(miss.task.title); + const { subject, html } = + miss.cause === "plan_blocked" + ? { + subject: `Your task didn't run: ${plainTitle}`, + html: `

Your scheduled task “${title}” was due and didn't run, because your plan doesn't cover it. ${escapeHtml(miss.detail)}

Upgrade or change your tasks at ${miss.billingUrl}, and it will run at its next scheduled time.

`, + } + : { + subject: `Your report didn't go out: ${plainTitle}`, + html: `

Your scheduled report “${title}” was due and didn't reach your inbox. We've been alerted and are looking into it.

It will run again at its next scheduled time.

`, + }; + + const result = await sendEmailWithResend( + { from: RECOUP_FROM_EMAIL, to, subject, html }, + { idempotencyKey: `missed-report/${miss.run.runId}` }, + ); + if (result instanceof NextResponse) return false; + + if (miss.cause === "plan_blocked") { + await logEmailAttempt({ + rawBody: JSON.stringify({ + type: noticeType, + account_id: miss.task.account_id, + run_id: miss.run.runId, + }), + status: "sent", + resendId: result.id, + }); + } + return true; +} diff --git a/lib/tasks/missedReports/types.ts b/lib/tasks/missedReports/types.ts new file mode 100644 index 000000000..236c449e6 --- /dev/null +++ b/lib/tasks/missedReports/types.ts @@ -0,0 +1,31 @@ +import type { Tables } from "@/types/database.types"; + +/** A run of the scheduled `customer-prompt-task`, resolved to the task it ran. */ +export interface ScheduledReportRun { + runId: string; + /** `scheduled_actions.id`, the schedule's external id. */ + taskId: string; + createdAt: string; + /** Trigger.dev run status, e.g. COMPLETED or FAILED. */ + status: string; +} + +/** + * Why a scheduled run sent no email: the plan blocked the task, the send + * reached POST /api/emails and was refused, or no send was attempted. + */ +export type MissedReportCause = "plan_blocked" | "email_rejected" | "no_email"; + +export interface MissedReport { + task: Tables<"scheduled_actions">; + run: ScheduledReportRun; + cause: MissedReportCause; + /** The plan message, the latest rejection reason, or the run status. */ + detail: string; + /** Where to upgrade, when the plan blocked the task. */ + billingUrl?: string; +} + +export interface NotifiedMissedReport extends MissedReport { + customerNotified: boolean; +} diff --git a/lib/trigger/__tests__/fetchTriggerRuns.test.ts b/lib/trigger/__tests__/fetchTriggerRuns.test.ts new file mode 100644 index 000000000..7d8a6ec8e --- /dev/null +++ b/lib/trigger/__tests__/fetchTriggerRuns.test.ts @@ -0,0 +1,30 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { fetchTriggerRuns } from "../fetchTriggerRuns"; + +describe("fetchTriggerRuns", () => { + beforeEach(() => { + vi.stubEnv("TRIGGER_SECRET_KEY", "tr_test"); + global.fetch = vi.fn().mockResolvedValue({ + ok: true, + json: vi.fn().mockResolvedValue({ data: [{ id: "run_1" }] }), + }) as unknown as typeof fetch; + }); + + it("lists one task's runs created inside a time window", async () => { + const runs = await fetchTriggerRuns( + { + "filter[taskIdentifier]": "customer-prompt-task", + "filter[createdAt][from]": "2026-11-06T10:00:00.000Z", + "filter[createdAt][to]": "2026-11-06T11:00:00.000Z", + }, + 100, + ); + + expect(runs).toEqual([{ id: "run_1" }]); + const url = new URL(vi.mocked(fetch).mock.calls[0][0] as string); + expect(url.searchParams.get("filter[taskIdentifier]")).toBe("customer-prompt-task"); + expect(url.searchParams.get("filter[createdAt][from]")).toBe("2026-11-06T10:00:00.000Z"); + expect(url.searchParams.get("filter[createdAt][to]")).toBe("2026-11-06T11:00:00.000Z"); + expect(url.searchParams.get("page[size]")).toBe("100"); + }); +}); diff --git a/lib/trigger/fetchTriggerRuns.ts b/lib/trigger/fetchTriggerRuns.ts index 2fd11e6b5..21ea309d7 100644 --- a/lib/trigger/fetchTriggerRuns.ts +++ b/lib/trigger/fetchTriggerRuns.ts @@ -8,12 +8,19 @@ export interface TriggerRun { durationMs: number | null; } -export type TriggerRunFilter = { "filter[tag]": string } | { "filter[schedule]": string }; +export type TriggerRunFilter = + | { "filter[tag]": string } + | { "filter[schedule]": string } + | { + "filter[taskIdentifier]": string; + "filter[createdAt][from]": string; + "filter[createdAt][to]": string; + }; /** * Fetches runs from the Trigger.dev Management REST API. * - * @param params - Filter params (tag or schedule) + * @param params - Filter params (tag, schedule, or one task within a created-at window) * @param limit - Maximum number of runs to return * @returns Array of run objects */ diff --git a/vercel.json b/vercel.json index b5721252b..074ffea96 100644 --- a/vercel.json +++ b/vercel.json @@ -16,6 +16,10 @@ { "path": "/api/internal/context-guest-maintenance", "schedule": "0 8 * * *" + }, + { + "path": "/api/internal/missed-report-check", + "schedule": "17 * * * *" } ] }