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
58 changes: 58 additions & 0 deletions apps/web/src/app/api/cron/issue-plan-donations/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { fakeDb, op, type Call, type Handler } from "@/test/fake-db"

const SECRET = "0123456789abcdef0123"
const PLAN = "10000000-0000-4000-8000-000000000001"
const PLAN_2 = "20000000-0000-4000-8000-000000000002"

const state = vi.hoisted(() => ({
handler: (() => undefined) as Handler,
Expand Down Expand Up @@ -68,6 +69,63 @@ describe("GET /api/cron/issue-plan-donations", () => {
])
})

it("emits a structured zero-PII alert when issue_plan_donations records 'failed' outcomes", async () => {
const error = vi.spyOn(console, "error").mockImplementation(() => {})
state.handler = (call) => {
if (call.target === "rpc:expire_plan_donations") return { data: 2 }
const after = (op(call, "args")?.[0] as { p_after: string | null }).p_after
if (after === null) return { data: [{ plan_id: PLAN, outcome: "failed" }] }
if (after === PLAN) return { data: [{ plan_id: PLAN_2, outcome: "issued" }] }
return { data: [] }
}
const response = await GET(request(`Bearer ${SECRET}`))
expect(response.status).toBe(200)
expect(await response.json()).toEqual({ failed: 1, issued: 1, done: true, expired: 2 })

const parsed = error.mock.calls.map(([arg]) => JSON.parse(String(arg)) as Record<string, unknown>)
expect(parsed).toContainEqual({
event: "plan_cron.failed_outcomes",
route: "issue-plan-donations",
job: "issue_plan_donations",
failed: 1,
calls: 3,
done: true,
})
})

it("flags a stalled expiry batch with done=false and expire_stalled=true", async () => {
const error = vi.spyOn(console, "error").mockImplementation(() => {})
state.handler = (call) => {
if (call.target === "rpc:issue_plan_donations") return { data: [] }
if (call.target === "rpc:expire_plan_donations") return { data: 0 }
if (call.target === "contributions") return { data: [{ id: "99999999-9999-4999-8999-999999999999" }] }
return undefined
}
const response = await GET(request(`Bearer ${SECRET}`))
expect(response.status).toBe(200)
expect(await response.json()).toEqual({ done: false, expired: 0, expire_stalled: true })
expect(error).toHaveBeenCalledTimes(1)
expect(JSON.parse(String(error.mock.calls[0][0]))).toEqual({
event: "plan_job.expire_batch_stalled",
job: "expire_plan_donations",
batches: 1,
expired: 0,
})
})

it("isolates step failures: expiry still runs within budget if issue_plan_donations fails", async () => {
vi.spyOn(console, "error").mockImplementation(() => {})
state.handler = (call) => {
if (call.target === "rpc:issue_plan_donations") return { error: { code: "57014", message: "timeout" } }
if (call.target === "rpc:expire_plan_donations") return { data: 4 }
return undefined
}
const response = await GET(request(`Bearer ${SECRET}`))
expect(response.status).toBe(500)
expect(await response.json()).toEqual({ error: "issue_failed" })
expect(state.calls.map((c) => c.target)).toEqual(["rpc:issue_plan_donations", "rpc:expire_plan_donations"])
})

it("shares one deadline: past the budget the expiry waits for the next run", async () => {
vi.useFakeTimers({ toFake: ["Date"] })
try {
Expand Down
39 changes: 31 additions & 8 deletions apps/web/src/app/api/cron/issue-plan-donations/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@ import { NextResponse, type NextRequest } from "next/server"

import { isAuthorizedCron } from "@/lib/cron"
import { dbService } from "@/lib/supabase"
import { expirePlanDonations, remainingBudget, sweepPlans } from "@/server/plans/jobs"
import {
expirePlanDonations,
logPlanCronFailures,
logPlanStepFailure,
remainingBudget,
sweepPlans,
type PlanSweep,
} from "@/server/plans/jobs"

export const dynamic = "force-dynamic"
export const maxDuration = 60
Expand All @@ -14,21 +21,37 @@ export const maxDuration = 60
* ends the plans of campaigns past their end date; a suspended campaign's
* plans wait. Then give.expire_plan_donations marks past months' unpaid plan
* donations 'expired' (listing only; money that arrives later still matches).
* A run that stops early, or a run missed, is caught up by the next one;
* past months are never issued late.
* Both steps are isolated so a failure in one does not prevent the other from
* running within the shared deadline; a run that stops early or is missed is
* caught up by the next one, and past months are never issued late.
*/
export async function GET(request: NextRequest) {
if (!isAuthorizedCron(request.headers.get("authorization"), process.env.CRON_SECRET)) {
return NextResponse.json({ error: "unauthorized" }, { status: 401 })
}
const db = dbService()
const started = Date.now()
let sweep: PlanSweep | null = null
let sweepFailed = false
try {
const sweep = await sweepPlans(db, "issue_plan_donations")
// Both steps share one deadline; past it the expiry waits for the next run.
const expired = remainingBudget(started) > 0 ? await expirePlanDonations(db) : null
return NextResponse.json({ ...sweep.outcomes, done: sweep.done && expired !== null, expired })
} catch {
sweep = await sweepPlans(db, "issue_plan_donations")
logPlanCronFailures("issue-plan-donations", "issue_plan_donations", sweep)
} catch (error: unknown) {
sweepFailed = true
logPlanStepFailure("issue-plan-donations", "issue_plan_donations", error)
}

// Both steps share one deadline; past it the expiry waits for the next run.
const budgetLeft = remainingBudget(started)
const expire = budgetLeft > 0 ? await expirePlanDonations(db, Date.now, budgetLeft) : null

if (sweepFailed || !sweep || expire?.failed) {
return NextResponse.json({ error: "issue_failed" }, { status: 500 })
}
return NextResponse.json({
...sweep.outcomes,
done: sweep.done && expire !== null && expire.done,
expired: expire ? expire.expired : null,
...(expire?.stalled ? { expire_stalled: true } : {}),
})
}
55 changes: 55 additions & 0 deletions apps/web/src/app/api/cron/plan-notices/route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { fakeDb, op, type Call, type Handler } from "@/test/fake-db"

const SECRET = "0123456789abcdef0123"
const PLAN = "10000000-0000-4000-8000-000000000001"
const PLAN_2 = "20000000-0000-4000-8000-000000000002"

const state = vi.hoisted(() => ({
handler: (() => undefined) as Handler,
Expand Down Expand Up @@ -64,6 +65,60 @@ describe("GET /api/cron/plan-notices", () => {
expect(state.calls.filter((c) => c.target === "rpc:plan_followups")).toHaveLength(2)
})

it("emits structured zero-PII alerts when either sweep records 'failed' outcomes", async () => {
const error = vi.spyOn(console, "error").mockImplementation(() => {})
state.handler = (call) => {
const after = (op(call, "args")?.[0] as { p_after: string | null }).p_after
if (call.target === "rpc:plan_end_notices") {
if (after === null) return { data: [{ plan_id: PLAN, outcome: "failed" }] }
return { data: [] }
}
if (call.target === "rpc:plan_followups") {
if (after === null) return { data: [{ plan_id: PLAN_2, outcome: "failed" }] }
return { data: [] }
}
return { data: [] }
}
const response = await GET(request(`Bearer ${SECRET}`))
expect(response.status).toBe(200)
expect(await response.json()).toEqual({
ended: { failed: 1 },
followups: { failed: 1 },
done: true,
})

const parsed = error.mock.calls.map(([arg]) => JSON.parse(String(arg)) as Record<string, unknown>)
expect(parsed).toContainEqual({
event: "plan_cron.failed_outcomes",
route: "plan-notices",
job: "plan_end_notices",
failed: 1,
calls: 2,
done: true,
})
expect(parsed).toContainEqual({
event: "plan_cron.failed_outcomes",
route: "plan-notices",
job: "plan_followups",
failed: 1,
calls: 2,
done: true,
})
})

it("isolates step failures: plan_followups still runs within budget if plan_end_notices fails", async () => {
vi.spyOn(console, "error").mockImplementation(() => {})
state.handler = (call) => {
if (call.target === "rpc:plan_end_notices") return { error: { code: "57014", message: "timeout" } }
const after = (op(call, "args")?.[0] as { p_after: string | null }).p_after
return { data: after === null ? [{ plan_id: PLAN, outcome: "reminded" }] : [] }
}
const response = await GET(request(`Bearer ${SECRET}`))
expect(response.status).toBe(500)
expect(await response.json()).toEqual({ error: "notices_failed" })
expect(state.calls.filter((c) => c.target === "rpc:plan_followups")).toHaveLength(2)
})

it("shares one deadline: past the budget the second reminders wait for the next run", async () => {
vi.useFakeTimers({ toFake: ["Date"] })
try {
Expand Down
45 changes: 35 additions & 10 deletions apps/web/src/app/api/cron/plan-notices/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@ import { NextResponse, type NextRequest } from "next/server"

import { isAuthorizedCron } from "@/lib/cron"
import { dbService } from "@/lib/supabase"
import { remainingBudget, sweepPlans } from "@/server/plans/jobs"
import {
logPlanCronFailures,
logPlanStepFailure,
remainingBudget,
sweepPlans,
type PlanSweep,
} from "@/server/plans/jobs"

export const dynamic = "force-dynamic"
export const maxDuration = 60
Expand All @@ -15,24 +21,43 @@ export const maxDuration = 60
* off, the end date); give.plan_followups sends the second reminder where
* the campaign's account allows it (none until the Tingee channel lands).
* Both write in-app notices that the outbox turns into emails, exactly once
* each, however often this runs.
* each, however often this runs. Each sweep is isolated so a failure in end
* notices does not block follow-ups within the shared deadline.
*/
export async function GET(request: NextRequest) {
if (!isAuthorizedCron(request.headers.get("authorization"), process.env.CRON_SECRET)) {
return NextResponse.json({ error: "unauthorized" }, { status: 401 })
}
const db = dbService()
const started = Date.now()
let ended: PlanSweep | null = null
let followups: PlanSweep | null = null
let endedFailed = false
let followupsFailed = false

try {
// Both sweeps share one deadline, so the run ends inside maxDuration.
const ended = await sweepPlans(db, "plan_end_notices")
const followups = await sweepPlans(db, "plan_followups", Date.now, remainingBudget(started))
return NextResponse.json({
ended: ended.outcomes,
followups: followups.outcomes,
done: ended.done && followups.done,
})
} catch {
ended = await sweepPlans(db, "plan_end_notices")
logPlanCronFailures("plan-notices", "plan_end_notices", ended)
} catch (error: unknown) {
endedFailed = true
logPlanStepFailure("plan-notices", "plan_end_notices", error)
}

try {
followups = await sweepPlans(db, "plan_followups", Date.now, remainingBudget(started))
logPlanCronFailures("plan-notices", "plan_followups", followups)
} catch (error: unknown) {
followupsFailed = true
logPlanStepFailure("plan-notices", "plan_followups", error)
}

if (endedFailed || followupsFailed || !ended || !followups) {
return NextResponse.json({ error: "notices_failed" }, { status: 500 })
}
return NextResponse.json({
ended: ended.outcomes,
followups: followups.outcomes,
done: ended.done && followups.done,
})
}
25 changes: 14 additions & 11 deletions apps/web/src/app/me/contributions/PlanList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,14 @@ import {
planDayLabel,
planDonationPayable,
planEndedReasonLabel,
vnMonthStart,
} from "@/lib/plans"

import { DONATION_TONES, toneOf } from "../_components/tones"
import { cancelPlan, updatePlan } from "./actions"

export { vnMonthStart }

export interface MyPlan {
id: string
campaign_id: string
Expand Down Expand Up @@ -48,10 +51,16 @@ export function effectiveNextPeriod(nextPeriod: string, month: string): string {
return nextPeriod < month ? month : nextPeriod
}

/** The first day of the current month in Vietnam time (UTC+7), as YYYY-MM-DD. */
export function vnMonthStart(now = new Date()): string {
const vn = new Date(now.getTime() + 7 * 60 * 60 * 1000)
return `${vn.getUTCFullYear()}-${String(vn.getUTCMonth() + 1).padStart(2, "0")}-01`
/**
* This month's plan donation for the campaign: a plan cancelled and signed up
* again in the same month keeps the earlier plan's donation.
*/
export function currentPlanDonation(
campaignId: string,
donations: readonly PlanDonation[],
month: string
): PlanDonation | null {
return donations.find((d) => d.plan_id !== null && d.plan_period === month && d.campaign_id === campaignId) ?? null
}

const DAYS = Array.from({ length: 28 }, (_, i) => i + 1)
Expand Down Expand Up @@ -91,13 +100,7 @@ export function PlanList({
plan={plan}
month={month}
now={now}
// This month's donation of the campaign: a plan cancelled and signed
// up again in the same month keeps the earlier plan's donation.
current={
donations.find(
(d) => d.plan_id !== null && d.plan_period === month && d.campaign_id === plan.campaign_id
) ?? null
}
current={currentPlanDonation(plan.campaign_id, donations, month)}
/>
))}
</ul>
Expand Down
Loading