From c0202efb2c43b7d01676990b4bb7fad4d1012f8c Mon Sep 17 00:00:00 2001 From: JOY <5027251+JOY@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:50:33 +0700 Subject: [PATCH 1/7] docs(po): set promotion_po to any and record Antigravity takeover (#304) * docs(po): set promotion_po to any and record Antigravity takeover * docs(po): clarify takeover label swap, claim release, and acceptance scope --- docs/product-owner-config.md | 97 ++++++++++++++++++++++++------------ 1 file changed, 64 insertions(+), 33 deletions(-) diff --git a/docs/product-owner-config.md b/docs/product-owner-config.md index 28af70e..ff802b1 100644 --- a/docs/product-owner-config.md +++ b/docs/product-owner-config.md @@ -55,29 +55,35 @@ Lines follow risk and ownership, not campaign type: give (charity) and back stricter review and legal track. Two parallel POs work this repository (split 2026-11-14, updated by JOY on -2026-11-21). The Antigravity PO session `Campaigns Product Owner` (profile -`acc0`, replacing paused Qwen Code sessions) runs Campaigns; the Claude Code -PO session `Give Product Owner` keeps Money, Platform, and exclusive -Production (`main` / `give.vn`) ownership (`promotion_po: claude`), so the -owner still approves Production in one chat. Parallel POs enforce mutual -exclusion via `po_labels` (`claude: po:claude, antigravity: po:agy`): each -PO dispatches only issues of its own lines that carry its own runtime label -or none of these labels, adds its own label on dispatch, checks the latest -protocol comment for another session's claim before taking an issue, and runs -the acceptance gate only on its own PRs. Neither PO merges, accepts or posts -an acceptance on the other's PR. Production promotions (`DOS/Give` `main` / -`give.vn` and `DOS/DOS.Me` `main`) and all other `DOS/DOS.Me` migration steps -remain Platform's and strictly exclusive to `Give Product Owner` (Claude Code) -with JOY's approval; as one explicit exception authorized by JOY (2026-11-21), -Antigravity PO is authorized to pick up unclaimed `DOS/DOS.Me` DB -prerequisites `#261`–`#264` for `DOS/DOS.Me` `dev` migrations/PRs only to -unblock `#250`–`#253` (never `DOS/DOS.Me` `main` / Production promotions). - -| Line | Label | Product Line option id | PO session | -| ------------------------------------------------------ | ---------------- | ---------------------- | ----------------------------------------------------------------------------------- | -| Campaigns | `line:campaigns` | `ef952ffb` | `Campaigns Product Owner` (Antigravity `acc0`, replacing paused Qwen Code sessions) | -| Money | `line:money` | `2640fb7c` | `Give Product Owner` | -| Platform (CI, release, auth, infra, DOS.Me migrations) | `line:platform` | `9a434f49` | none (covered by `Give Product Owner`) | +2026-11-21 and 2026-11-22). Normally, Antigravity PO +(`Give Product Owner (Antigravity)`, profile `acc0`; formerly +`Campaigns Product Owner`, replacing paused Qwen Code sessions) runs Campaigns +and Claude Code PO (`Give Product Owner`) runs Money and Platform. Under JOY's +2026-11-22 instruction, while Claude Code PO is quota-limited, Antigravity PO +proactively covers all three lines (`line:campaigns`, `line:money`, +`line:platform`), including taking over Claude PO's unfinished `line:money` and +`line:platform` tasks and `DOS/DOS.Me` migrations. Parallel POs keep mutual +exclusion active via `po_labels` (`claude: po:claude, antigravity: po:agy`) so +both POs cooperate without duplicating tasks when Claude resumes: each PO +dispatches only issues carrying its own runtime label or none of these labels +(except when Antigravity explicitly takes over a quota-stalled issue with no +live Claude session under JOY's 2026-11-22 takeover instruction, in which case +it replaces `po:claude` with `po:agy` and posts a take-over `release:` of any +stalled Claude claim before re-claiming), adds its own label on dispatch, checks +the latest protocol comment for another session's claim before taking an issue, +and runs the acceptance gate only on its own PRs. Neither PO merges, accepts or +posts an acceptance on the other's PR. Both Antigravity PO and Claude Code PO +hold equal Production promotion authority (`promotion_po: any`, updated by JOY +on 2026-11-22) for `DOS/Give` `main` / `give.vn` and `DOS/DOS.Me` `main`; every +Production promotion still requires JOY's explicit popup approval on a concrete +step list plus rollback plan, and the promoting PO must confirm zero competing +open `main` promotion PRs before starting. + +| Line | Label | Product Line option id | PO session | +| ------------------------------------------------------ | ---------------- | ---------------------- | ------------------------------------------------------------------------------------------------------- | +| Campaigns | `line:campaigns` | `ef952ffb` | `Give Product Owner (Antigravity)` (profile `acc0`; formerly `Campaigns Product Owner`, replacing Qwen) | +| Money | `line:money` | `2640fb7c` | `Give Product Owner` (Claude Code; covered by `Give Product Owner (Antigravity)` while quota-limited) | +| Platform (CI, release, auth, infra, DOS.Me migrations) | `line:platform` | `9a434f49` | none (covered by `Give Product Owner`, and by `Give Product Owner (Antigravity)` while quota-limited) | - Campaigns: organizer onboarding, campaign editor and review, discovery, campaign pages, updates, milestones, reward tiers and fulfillment status, @@ -101,8 +107,9 @@ unblock `#250`–`#253` (never `DOS/DOS.Me` `main` / Production promotions). ## Rule documents - agent_instructions: `AGENTS.md` (`QWEN.md` and `GEMINI.md` point to it). No - local Docker or local Supabase for Give work (JOY, 2026-11-21); pgTAP tests - and migration replay run in GitHub CI on the DOS/DOS.Me PR. + local Docker or local Supabase for Give work (JOY, 2026-11-21; `Give#294` / + `DOS/DOS.Me#1855`); Give pgTAP tests and migration replay run in GitHub CI + on the `DOS/DOS.Me` PR. - task_scope: none - tracking_doc: none - review_rules: none @@ -125,11 +132,14 @@ unblock `#250`–`#253` (never `DOS/DOS.Me` `main` / Production promotions). - production_merge: merge commit - production_effect: a merge into `main` deploys Production: Vercel (project `give`, team `metados`) builds `main` and serves it at - https://give.vn. It is a Production step: only the Give Product Owner - runs it, after JOY approves it, and only once every DOS.Me migration the - app code needs is on DOS.Me `main`. give.vn already served `main` before - this was recorded; #224 (2026-11-17) is the first promotion run as a - Production step. + https://give.vn. It is a Production step (`promotion_po: any`, updated + 2026-11-22): either Antigravity PO (`Give Product Owner (Antigravity)`) or + Claude Code PO (`Give Product Owner`) may run it, only after JOY's explicit + popup approval on a concrete step list plus rollback plan, after confirming + zero competing open `main` promotion PRs, and only once every DOS.Me + migration the app code needs is on DOS.Me `main`. give.vn already served + `main` before this was recorded; #224 (2026-11-17) is the first promotion + run as a Production step. - test_environment: Vercel preview deployments of the `give` project. The `dev` branch is served at https://beta.give.vn and each PR branch gets its own `give-git--metados.vercel.app` preview, both behind Vercel @@ -151,7 +161,7 @@ unblock `#250`–`#253` (never `DOS/DOS.Me` `main` / Production promotions). ## Claim lock and parallel POs - po_labels: claude: po:claude, antigravity: po:agy -- promotion_po: claude +- promotion_po: any ## Sessions @@ -184,7 +194,9 @@ unblock `#250`–`#253` (never `DOS/DOS.Me` `main` / Production promotions). project đi. Việc của ai người đó nghiệm thu."; and, on the PO's proposal to split by line (Qwen: Campaigns; Claude Code: Money and Platform): "Chia như vậy". A `PO acceptance:` comment counts only from the PO that - owns the PR's line. (Campaigns runtime superseded 2026-11-21, below.) + owns the PR's line. (Campaigns runtime superseded 2026-11-21; line-only + acceptance widened to the PR-owning PO via `po_labels` during the 2026-11-22 + Claude quota takeover, below.) - JOY (2026-11-16), on empty-site discovery links: "Giữ nguyeyen" — with no live campaign, keep the header, "Hai cách" and footer "Khám phá" links to `/campaigns` (its empty state) as they are. @@ -199,7 +211,26 @@ unblock `#250`–`#253` (never `DOS/DOS.Me` `main` / Production promotions). picks up unclaimed `DOS/DOS.Me` DB prerequisites `#261`–`#264` for `DOS/DOS.Me` `dev` migrations/PRs only to unblock `#250`–`#253` (`DOS/DOS.Me` `main` / Production promotions remain strictly exclusive to - `Give Product Owner` (Claude Code) with JOY's approval). + `Give Product Owner` (Claude Code) with JOY's approval). (Production + exclusivity, single-line limit, and `DOS/DOS.Me` dev-only migration scope + superseded 2026-11-22, below.) +- JOY (2026-11-21), on local databases (`Give#294` / `DOS/DOS.Me#1855`): no + local Docker or local Supabase for Give work; run Give pgTAP tests and + migration replay in GitHub CI on `DOS/DOS.Me`. +- JOY (2026-11-22), via PO `ask_question` popup on `promotion_po`: approved + changing `promotion_po` from `claude` to `any` so Antigravity PO and Claude + Code PO hold equal Production promotion authority (`DOS/Give` `main` / + `give.vn` and `DOS/DOS.Me` `main`), always requiring JOY's popup approval on + a concrete step list plus rollback plan and zero competing open `main` + promotion PRs before starting. +- JOY (2026-11-22), in PO chat on Claude PO quota takeover: "PO claude hết + limit rồi nên mày chủ động nhé. Takover các task đang dở của nó luôn." + Antigravity PO (`Give Product Owner (Antigravity)`, profile `acc0`) + proactively covers all three lines (`line:campaigns`, `line:money`, + `line:platform`) and takes over Claude PO's unfinished `line:money` and + `line:platform` tasks while Claude is out of quota, keeping + `po_labels: claude: po:claude, antigravity: po:agy` active so both POs + cooperate without duplicating tasks when Claude resumes. Screenshot branches (`assets/pr--screenshots`): every commit on them adds `apps/web/vercel.json` with `{"git":{"deploymentEnabled":false}}`, so Vercel From 6c69036641fbffe87be6144324edbaa40678ec0f Mon Sep 17 00:00:00 2001 From: JOY <5027251+JOY@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:17:17 +0700 Subject: [PATCH 2/7] fix(email): lengthen claim timeout with abort logging and harden prod DB JWT ref check (#273) (#305) --- apps/web/src/server/email/outbox.test.ts | 54 ++++++++++++++++++++++ apps/web/src/server/email/outbox.ts | 35 +++++++++++--- apps/web/src/server/email/provider.test.ts | 52 +++++++++++++++++++++ apps/web/src/server/email/provider.ts | 37 +++++++++++++-- 4 files changed, 168 insertions(+), 10 deletions(-) diff --git a/apps/web/src/server/email/outbox.test.ts b/apps/web/src/server/email/outbox.test.ts index cd5c275..4bc2f8f 100644 --- a/apps/web/src/server/email/outbox.test.ts +++ b/apps/web/src/server/email/outbox.test.ts @@ -4,8 +4,10 @@ import { fakeDb, op, type Call, type Handler } from "@/test/fake-db" import { CLAIM_BATCH, + CLAIM_TIMEOUT_MS, COMPLETE_TRIES, RPC_TIMEOUT_MS, + RUN_BUDGET_MS, RUN_LIMIT_MS, SEND_DEADLINE_MS, SEND_TIMEOUT_MS, @@ -339,6 +341,58 @@ describe("sendDueEmails", () => { await expect(sendDueEmails(db as never, transport, OPTIONS)).rejects.toMatchObject({ code: "42501" }) }) + it("uses a 15 s claim timeout above PostgREST's 8 s statement timeout and logs aborted claims (DOS/Give#273)", async () => { + expect(CLAIM_TIMEOUT_MS).toBe(15_000) + expect(CLAIM_TIMEOUT_MS).toBeLessThan(RUN_BUDGET_MS) + + const errorSpy = vi.mocked(console.error) + errorSpy.mockClear() + const abortDb = fakeDb( + () => ({ error: { code: "", message: "TimeoutError: The operation was aborted due to timeout" } }), + calls + ) + await expect(sendDueEmails(abortDb as never, transport, OPTIONS)).rejects.toMatchObject({ + message: expect.stringMatching(/aborted due to timeout/), + }) + expect(errorSpy).toHaveBeenCalledWith( + expect.stringMatching(/claim_outbox aborted after timeout; DB transaction may still have committed/), + "", + expect.stringMatching(/TimeoutError/) + ) + + // Subsequent claim abort logs the committed-lease warning and stops without losing earlier counts. + errorSpy.mockClear() + let claimCount = 0 + const secondAbortDb = fakeDb((call) => { + if (call.target === "rpc:claim_outbox") { + claimCount += 1 + if (claimCount === 1) return { data: Array.from({ length: CLAIM_BATCH }, (_, i) => row(100 + i)) } + return { error: { code: "", message: "AbortError: This operation was aborted" } } + } + return handler(call) + }, calls) + const outcome = await sendDueEmails(secondAbortDb as never, transport, OPTIONS) + expect(outcome).toMatchObject({ claimed: CLAIM_BATCH, sent: CLAIM_BATCH }) + expect(errorSpy).toHaveBeenCalledWith( + expect.stringMatching(/claim_outbox aborted after timeout; DB transaction may still have committed/), + "", + expect.stringMatching(/AbortError/) + ) + + // Server-side Postgres statement_timeout (57014) rolled back cleanly: log ordinary failure, not abort warning. + errorSpy.mockClear() + const pgTimeoutDb = fakeDb( + () => ({ error: { code: "57014", message: "canceling statement due to statement timeout" } }), + calls + ) + await expect(sendDueEmails(pgTimeoutDb as never, transport, OPTIONS)).rejects.toMatchObject({ code: "57014" }) + expect(errorSpy).toHaveBeenCalledWith( + "claim_outbox failed", + "57014", + "canceling statement due to statement timeout" + ) + }) + it("skips a malformed row", async () => { claims = [[{ id: "x" }, row(8)]] const outcome = await sendDueEmails(fakeDb(handler, calls) as never, transport, OPTIONS) diff --git a/apps/web/src/server/email/outbox.ts b/apps/web/src/server/email/outbox.ts index cc299b0..316828a 100644 --- a/apps/web/src/server/email/outbox.ts +++ b/apps/web/src/server/email/outbox.ts @@ -40,8 +40,12 @@ const COMPLETE_RETRY_MS = [250, 1_000] const NO_HOLD_FUNCTION = new Set(["PGRST202", "42883"]) /** Each RPC after a send (complete, release) is abandoned after this long. */ export const RPC_TIMEOUT_MS = 5_000 -/** A claim is abandoned after this long (it may wait on locks while it settles rows). */ -export const CLAIM_TIMEOUT_MS = 10_000 +/** + * A claim is abandoned after this long. Kept well above PostgREST's 8 s + * statement timeout plus connection-pooler / network jitter so a committing + * claim_outbox call is not aborted in flight (DOS/Give#273 item 5). + */ +export const CLAIM_TIMEOUT_MS = 15_000 /** * No retry or release starts unless it can finish by this point, under the * 60 s function limit: a run killed mid-batch loses its results and leaves @@ -296,6 +300,18 @@ async function release(db: Db, rows: OutboxEmail[], clock: Clock): Promise { missing: ["NON_PRODUCTION_DEPLOYMENT_ON_PRODUCTION_DATABASE"], }) }) + + it("catches the Production database via JWT ref even behind an unlisted custom domain (DOS/Give#273)", () => { + const fakeJwt = (payload: unknown) => + `eyJhbGciOiJIUzI1NiJ9.${Buffer.from(JSON.stringify(payload)).toString("base64url")}.sig` + const prodServiceJwt = fakeJwt({ iss: "supabase", ref: "gulptwduchsjcsbndmua", role: "service_role" }) + const prodAnonJwt = fakeJwt({ iss: "supabase", ref: "GULPTWDUCHSJCSBNDMUA", role: "anon" }) + const betaServiceJwt = fakeJwt({ iss: "supabase", ref: "oyajkbadsykigtfrpdpg", role: "service_role" }) + + expect( + usesProductionDatabase({ + NEXT_PUBLIC_SUPABASE_URL: "https://db.custom-dos.example", + SUPABASE_SERVICE_ROLE_KEY: prodServiceJwt, + }) + ).toBe(true) + expect( + usesProductionDatabase({ + NEXT_PUBLIC_SUPABASE_URL: "https://db.custom-dos.example", + NEXT_PUBLIC_SUPABASE_ANON_KEY: prodAnonJwt, + }) + ).toBe(true) + expect(usesProductionDatabase({ SUPABASE_SERVICE_ROLE_KEY: prodServiceJwt })).toBe(true) + expect( + emailSettingsFromEnv({ + ...BETA, + NEXT_PUBLIC_SUPABASE_URL: "https://db.custom-dos.example", + SUPABASE_SERVICE_ROLE_KEY: prodServiceJwt, + }) + ).toMatchObject({ + ok: false, + missing: ["NON_PRODUCTION_DEPLOYMENT_ON_PRODUCTION_DATABASE"], + }) + + // Non-production JWT and opaque sb_secret_ keys do not trigger false positives. + expect( + usesProductionDatabase({ + NEXT_PUBLIC_SUPABASE_URL: "https://db.custom-beta.example", + SUPABASE_SERVICE_ROLE_KEY: betaServiceJwt, + }) + ).toBe(false) + expect( + usesProductionDatabase({ + NEXT_PUBLIC_SUPABASE_URL: "https://db.custom-beta.example", + SUPABASE_SERVICE_ROLE_KEY: "sb_secret_not_a_jwt", + }) + ).toBe(false) + expect( + usesProductionDatabase({ + NEXT_PUBLIC_SUPABASE_URL: "https://db.custom-beta.example", + SUPABASE_SERVICE_ROLE_KEY: "a.not-valid-json.c", + }) + ).toBe(false) + }) }) diff --git a/apps/web/src/server/email/provider.ts b/apps/web/src/server/email/provider.ts index 3c919e2..8e51d70 100644 --- a/apps/web/src/server/email/provider.ts +++ b/apps/web/src/server/email/provider.ts @@ -71,15 +71,44 @@ export function emailLinkOrigin(env: Env = process.env): string | null { return production ? PRODUCTION_ORIGIN : null } +/** + * Extracts the Supabase project ref from a legacy JWT key (`header.payload.sig`), + * or null for opaque keys (`sb_secret_*` / `sb_publishable_*`) and invalid strings. + */ +function jwtProjectRef(token: string | undefined): string | null { + if (!token) return null + const parts = token.trim().split(".") + if (parts.length !== 3 || !parts[1]) return null + try { + const payload: unknown = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8")) + if (!payload || typeof payload !== "object") return null + const ref = (payload as { ref?: unknown }).ref + return typeof ref === "string" ? ref.trim().toLowerCase() : null + } catch { + return null + } +} + +/** + * Whether env points at the Production DOS Supabase project (DOS/Give#273 item 6). + * Checks both the URL host (project host + vanity domains in PRODUCTION_SUPABASE_HOSTS) + * and the JWT `ref` claim of the Supabase keys so a newly added custom domain is + * still caught when JWT keys are used. We intentionally do not query the DB for an + * environment tag: Production, Beta, and Preview branches replay the same committed + * DOS.Me migrations, so an in-DB marker would be inherited by Preview/Beta. + */ export function usesProductionDatabase(env: Env = process.env): boolean { - let host: string try { // A trailing dot (fully qualified name) reaches the same host. - host = new URL(env.NEXT_PUBLIC_SUPABASE_URL ?? "").hostname.toLowerCase().replace(/\.+$/, "") + const host = new URL(env.NEXT_PUBLIC_SUPABASE_URL ?? "").hostname.toLowerCase().replace(/\.+$/, "") + if (PRODUCTION_SUPABASE_HOSTS.includes(host) || host.split(".")[0] === PRODUCTION_SUPABASE_REF) return true } catch { - return false + // Missing or malformed URL; still check JWT keys below. } - return PRODUCTION_SUPABASE_HOSTS.includes(host) || host.split(".")[0] === PRODUCTION_SUPABASE_REF + return ( + jwtProjectRef(env.SUPABASE_SERVICE_ROLE_KEY) === PRODUCTION_SUPABASE_REF || + jwtProjectRef(env.NEXT_PUBLIC_SUPABASE_ANON_KEY) === PRODUCTION_SUPABASE_REF + ) } export function emailDelivery(env: Env = process.env): EmailDelivery { From 9deab36a1e140c72a3d24cef11e39eb409479d41 Mon Sep 17 00:00:00 2001 From: JOY <5027251+JOY@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:28:15 +0700 Subject: [PATCH 3/7] feat(admin): atomic expected-status guard and pre-launch recovery queue (#77) (#306) * feat(admin): wire expected-status guard and pre-launch recovery queue (Refs #77) * fix(admin): handle foreign/unverified transaction edge cases in recoveryAdvice (#77) --- CHANGELOG.md | 12 ++ apps/web/src/app/admin/actions.test.ts | 91 ++++++++++- apps/web/src/app/admin/actions.ts | 35 ++++- apps/web/src/app/admin/page.test.ts | 161 ++++++++++++++++++- apps/web/src/app/admin/page.tsx | 113 +++++++++++++- apps/web/src/lib/campaigns.test.ts | 195 +++++++++++++++++++++++ apps/web/src/lib/campaigns.ts | 208 +++++++++++++++++++++++-- apps/web/src/lib/errors.ts | 7 + 8 files changed, 794 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f280c18..d635159 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,18 @@ they reach Production with a separate, approved promotion of DOS.Me `main`. ### Design system and screens +- Atomic moderator status-transition race guard and pre-launch recovery queue: + `apps/web/src/app/admin/actions.ts` passes `p_expected_status` on + `approveCampaign` (`in_review` -> `approved`, `approved` -> `live`) and + `requestChanges` (`in_review`, `approved`, `suspended`) and maps + `GIVE_CAMPAIGN_STATUS_CHANGED` (`40001`) and `suspended -> changes_requested` + refusals in `apps/web/src/lib/errors.ts`; `/admin` adds the `#recovery` + (`"Cần xử lý trước khi mở"`) section backed by + `give.campaigns_needing_recovery()` (`listCampaignsNeedingRecovery`, + `recoveryAdvice`) so moderators can see and recover approved campaigns past + `ends_at` with usable accounts and campaigns suspended before `starts_at` + (never live, no contributions), with unit and RSC Vitest coverage, backed by + `DOS/DOS.Me#1872` (#77). - Co-organizers (campaign editors), single-use invites, workspace guards and public team block: `/me/campaigns/[id]?tab=team` (`TeamTab`, `CreateInviteForm`, `member-actions.ts`) lets the owning organizer create diff --git a/apps/web/src/app/admin/actions.test.ts b/apps/web/src/app/admin/actions.test.ts index 202e8f5..64479bb 100644 --- a/apps/web/src/app/admin/actions.test.ts +++ b/apps/web/src/app/admin/actions.test.ts @@ -1,6 +1,6 @@ import { beforeEach, describe, expect, it, vi } from "vitest" -import { OPEN_MESSAGES, REVIEW_MESSAGES, SEND_BACK_MESSAGES } from "@/lib/errors" +import { OPEN_MESSAGES, REVIEW_MESSAGES, SEND_BACK_MESSAGES, SUSPENDED_SEND_BACK_MESSAGES } from "@/lib/errors" import { fakeDb, op, type Call, type Handler } from "@/test/fake-db" const CAMPAIGN = "22222222-2222-4222-8222-222222222222" @@ -40,7 +40,7 @@ describe("approveCampaign", () => { ["/"], ] - it("approves and opens a campaign whose start time has come", async () => { + it("approves and opens a campaign whose start time has come with atomic expected-status guards", async () => { state.handler = (call) => op(call, "maybeSingle") ? { data: { slug: "a-b", starts_at: null, ends_at: new Date(Date.now() + 30 * day).toISOString() } } @@ -48,9 +48,47 @@ describe("approveCampaign", () => { const result = await approveCampaign(CAMPAIGN, null, new FormData()) expect(result).toEqual({ ok: true, message: "Đã duyệt và mở chiến dịch công khai." }) expect(transitions()).toEqual(["approved", "live"]) + const rpcArgs = state.calls.filter((c) => c.target === "rpc:transition_campaign").map((c) => op(c, "args")?.[0]) + expect(rpcArgs).toEqual([ + { p_campaign_id: CAMPAIGN, p_to_status: "approved", p_expected_status: "in_review" }, + { p_campaign_id: CAMPAIGN, p_to_status: "live", p_expected_status: "approved" }, + ]) expect(revalidatePathMock.mock.calls).toEqual(expectedApprovalRevalidations) }) + it("maps GIVE_CAMPAIGN_STATUS_CHANGED when another moderator moves the campaign before approval or opening (DOS/Give#77)", async () => { + state.handler = (call) => + op(call, "maybeSingle") + ? { data: { slug: "a-b", starts_at: null, ends_at: new Date(Date.now() + 30 * day).toISOString() } } + : call.target === "rpc:transition_campaign" + ? { + error: { + code: "40001", + message: "GIVE_CAMPAIGN_STATUS_CHANGED: expected in_review, got changes_requested", + }, + } + : undefined + expect(await approveCampaign(CAMPAIGN, null, new FormData())).toEqual({ + ok: false, + message: "Chiến dịch đã đổi trạng thái từ khi trang này tải. Hãy tải lại trang rồi xem lại.", + }) + expect(revalidatePathMock).not.toHaveBeenCalled() + + state.calls.length = 0 + state.handler = (call) => + op(call, "maybeSingle") + ? { data: { slug: "a-b", starts_at: null, ends_at: new Date(Date.now() + 30 * day).toISOString() } } + : call.target === "rpc:transition_campaign" && + (op(call, "args")?.[0] as { p_to_status: string }).p_to_status === "live" + ? { error: { code: "40001", message: "GIVE_CAMPAIGN_STATUS_CHANGED: expected approved, got suspended" } } + : undefined + expect(await approveCampaign(CAMPAIGN, null, new FormData())).toEqual({ + ok: true, + message: + "Đã duyệt, nhưng chưa mở được: Chiến dịch đã đổi trạng thái từ khi trang này tải. Hãy tải lại trang rồi xem lại.", + }) + }) + it("only approves a campaign scheduled for later and still revalidates organizer and campaign routes", async () => { state.handler = (call) => op(call, "maybeSingle") @@ -165,6 +203,7 @@ describe("requestChanges", () => { p_campaign_id: CAMPAIGN, p_to_status: "changes_requested", p_reason: "Bind another account.", + p_expected_status: "approved", }) expect(revalidatePathMock.mock.calls).toEqual([ ["/admin"], @@ -256,6 +295,54 @@ describe("requestChanges", () => { }) expect(transitions()).toEqual([]) }) + + it("maps GIVE_CAMPAIGN_STATUS_CHANGED when another moderator transitions the campaign between read and RPC (DOS/Give#77)", async () => { + state.handler = statusIs("in_review", (call) => + call.target === "rpc:transition_campaign" + ? { error: { code: "40001", message: "GIVE_CAMPAIGN_STATUS_CHANGED: expected in_review, got approved" } } + : undefined + ) + expect(await requestChanges(CAMPAIGN, null, form("Fix story.", "in_review"))).toEqual({ + ok: false, + message: "Chiến dịch đã đổi trạng thái từ khi trang này tải. Hãy tải lại trang rồi xem lại.", + }) + expect(revalidatePathMock).not.toHaveBeenCalled() + }) + + it("sends back a suspended-before-start campaign with p_expected_status='suspended' and maps ineligible refusals (DOS/Give#77)", async () => { + state.handler = statusIs("suspended", undefined, "a-b") + expect(await requestChanges(CAMPAIGN, null, form("Replace disabled account.", "suspended"))).toEqual({ + ok: true, + message: "Đã gửi yêu cầu chỉnh sửa cho người tổ chức.", + }) + const call = state.calls.find((c) => c.target === "rpc:transition_campaign") + expect(op(call, "args")?.[0]).toEqual({ + p_campaign_id: CAMPAIGN, + p_to_status: "changes_requested", + p_reason: "Replace disabled account.", + p_expected_status: "suspended", + }) + expect(revalidatePathMock.mock.calls).toEqual([ + ["/admin"], + [`/me/campaigns/${CAMPAIGN}`], + ["/me/campaigns"], + ["/me/notices"], + ["/campaigns/a-b"], + ]) + + revalidatePathMock.mockClear() + state.calls.length = 0 + state.handler = statusIs("suspended", (c) => + c.target === "rpc:transition_campaign" + ? { error: { code: "42501", message: "GIVE_TRANSITION_NOT_ALLOWED: suspended -> changes_requested" } } + : undefined + ) + expect(await requestChanges(CAMPAIGN, null, form("Replace disabled account.", "suspended"))).toEqual({ + ok: false, + message: SUSPENDED_SEND_BACK_MESSAGES.GIVE_TRANSITION_NOT_ALLOWED, + }) + expect(revalidatePathMock).not.toHaveBeenCalled() + }) }) describe("setVerification", () => { diff --git a/apps/web/src/app/admin/actions.ts b/apps/web/src/app/admin/actions.ts index 4d0bdf0..9b0c026 100644 --- a/apps/web/src/app/admin/actions.ts +++ b/apps/web/src/app/admin/actions.ts @@ -10,6 +10,7 @@ import { OPEN_MESSAGES, REVIEW_MESSAGES, SEND_BACK_MESSAGES, + SUSPENDED_SEND_BACK_MESSAGES, type ActionResult, } from "@/lib/errors" import { isUuid } from "@/lib/ids" @@ -49,12 +50,20 @@ export async function approveCampaign( return fail("Chiến dịch đã quá ngày kết thúc. Hãy yêu cầu người tổ chức sửa ngày thay vì duyệt.") } - const approved = await db.rpc("transition_campaign", { p_campaign_id: campaignId, p_to_status: "approved" }) + const approved = await db.rpc("transition_campaign", { + p_campaign_id: campaignId, + p_to_status: "approved", + p_expected_status: "in_review", + }) if (approved.error) return fail(dbErrorMessage(approved.error, REVIEW_MESSAGES)) let message = "Đã duyệt. Chiến dịch sẽ tự mở khi tới ngày bắt đầu." if (!campaign.starts_at || new Date(campaign.starts_at) <= new Date()) { - const live = await db.rpc("transition_campaign", { p_campaign_id: campaignId, p_to_status: "live" }) + const live = await db.rpc("transition_campaign", { + p_campaign_id: campaignId, + p_to_status: "live", + p_expected_status: "approved", + }) message = live.error ? `Đã duyệt, nhưng chưa mở được: ${dbErrorMessage(live.error, OPEN_MESSAGES)}` : "Đã duyệt và mở chiến dịch công khai." @@ -71,10 +80,11 @@ export async function approveCampaign( } /** - * Sends a campaign back for changes, from review or (give campaigns) after - * approval. Each form says which status it was shown for, so a form left - * open while another moderator approved the campaign does not send the - * approved campaign back by mistake. The database still decides. + * Sends a campaign back for changes, from review, after approval (DOS/Give#64, + * #85), or when suspended before its start (DOS/Give#77). Each form says which + * status it was shown for, and give.transition_campaign checks + * p_expected_status atomically under its row lock so a stale form left open + * while another moderator moved the campaign cannot overwrite their decision. */ export async function requestChanges(campaignId: string, _state: ActionResult, form: FormData): Promise { const session = await getSession() @@ -85,7 +95,7 @@ export async function requestChanges(campaignId: string, _state: ActionResult, f .slice(0, 2000) if (!reason) return fail("Ghi rõ người tổ chức cần sửa gì.") const fromStatus = String(form.get("from_status") ?? "") - if (fromStatus !== "in_review" && fromStatus !== "approved") return fail(STATUS_CHANGED) + if (fromStatus !== "in_review" && fromStatus !== "approved" && fromStatus !== "suspended") return fail(STATUS_CHANGED) const db = dbAs(session.accessToken) const { data, error: readError } = await db @@ -102,8 +112,17 @@ export async function requestChanges(campaignId: string, _state: ActionResult, f p_campaign_id: campaignId, p_to_status: "changes_requested", p_reason: reason, + p_expected_status: fromStatus, }) - if (error) return fail(dbErrorMessage(error, fromStatus === "approved" ? SEND_BACK_MESSAGES : undefined)) + if (error) { + const overrides = + fromStatus === "approved" + ? SEND_BACK_MESSAGES + : fromStatus === "suspended" + ? SUSPENDED_SEND_BACK_MESSAGES + : undefined + return fail(dbErrorMessage(error, overrides)) + } revalidatePath("/admin") revalidatePath(`/me/campaigns/${campaignId}`) revalidatePath("/me/campaigns") diff --git a/apps/web/src/app/admin/page.test.ts b/apps/web/src/app/admin/page.test.ts index cfa4df3..6172ef8 100644 --- a/apps/web/src/app/admin/page.test.ts +++ b/apps/web/src/app/admin/page.test.ts @@ -16,9 +16,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" import { accountProblemLabel, + recoveryAdvice, STATUS_LABELS, waitingAdvice, type Organizer, + type RecoveryCampaign, + type RecoveryKind, type ReviewItem, type WaitingForAccount, } from "@/lib/campaigns" @@ -130,6 +133,26 @@ function waitingRow(id: string, problem: string, overrides: Partial = {} +): RecoveryCampaign { + return { + ...reviewRow(id, { + status: kind === "suspended_before_start" ? "suspended" : "approved", + approved_at: "2026-11-12T09:00:00.000Z", + starts_at: kind === "suspended_before_start" ? "2099-01-01T00:00:00.000Z" : "2026-10-01T00:00:00.000Z", + ends_at: kind === "suspended_before_start" ? "2099-02-01T00:00:00.000Z" : "2026-11-01T00:00:00.000Z", + ...overrides, + }), + recovery_kind: kind, + account_problem: problem, + account_has_transactions: overrides.account_has_transactions ?? false, + } +} + function organizerRow(userId: string, overrides: Partial = {}): Organizer { return { user_id: userId, @@ -150,6 +173,8 @@ function setupAdmin({ queue = [] as ReviewItem[], waiting = [] as WaitingForAccount[], waitingError = null as { code?: string; message?: string } | null, + recovery = [] as RecoveryCampaign[], + recoveryError = null as { code?: string; message?: string } | null, organizers = [] as Organizer[], statusEvents = [] as CampaignStatusEvent[], statusEventsError = null as { code?: string; message?: string } | null, @@ -169,12 +194,28 @@ function setupAdmin({ })), } } + if (call.target === "rpc:campaigns_needing_recovery") { + if (recoveryError) return { error: recoveryError } + return { + data: recovery.map((r) => ({ + campaign_id: r.id, + recovery_kind: r.recovery_kind, + account_problem: r.account_problem, + account_has_transactions: r.account_has_transactions, + })), + } + } if (call.target === "rpc:managed_campaigns") { if (op(call, "eq")?.[0] === "status") return { data: queue } if (op(call, "in")?.[0] === "id") { - return { - data: waiting.map(({ account_problem: _p, account_has_transactions: _t, ...campaign }) => campaign), - } + const ids = (op(call, "in")?.[1] ?? []) as string[] + const pool = [ + ...waiting.map(({ account_problem: _p, account_has_transactions: _t, ...campaign }) => campaign), + ...recovery.map( + ({ recovery_kind: _k, account_problem: _p, account_has_transactions: _t, ...campaign }) => campaign + ), + ] + return { data: pool.filter((c) => ids.includes(c.id)) } } } if (call.target === "campaign_status_events") { @@ -209,6 +250,7 @@ async function renderAdmin() { doc, queueSection: doc.querySelector('section[aria-labelledby="queue"]')!, waitingSection: doc.querySelector('section[aria-labelledby="waiting"]')!, + recoverySection: doc.querySelector('section[aria-labelledby="recovery"]')!, organizersSection: doc.querySelector('section[aria-labelledby="organizers"]')!, } } @@ -680,4 +722,117 @@ describe("AdminReviewPage (/admin, DOS/Give#218)", () => { expect(waitingSection.querySelector("details")).toBeNull() }) }) + + describe("pre-launch recovery section (#recovery, DOS/Give#77)", () => { + it("renders EmptyState when no campaign needs pre-launch recovery and isolates RPC errors", async () => { + setupAdmin({ recovery: [] }) + const { recoverySection } = await renderAdmin() + expect(recoverySection.querySelector("h2")?.textContent).toContain("0") + expect(recoverySection.querySelector("h3")?.textContent.trim()).toBe( + "Không có chiến dịch nào cần xử lý trước khi mở." + ) + + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}) + const queued = reviewRow("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", { title: "Áo ấm vùng cao" }) + setupAdmin({ + queue: [queued], + recoveryError: { code: "42501", message: "permission denied" }, + }) + const rendered = await renderAdmin() + expect(errorSpy).toHaveBeenCalledWith("campaigns_needing_recovery failed", "42501", "permission denied") + expect(rendered.recoverySection.querySelector(".bg-danger-soft")?.textContent).toContain( + "Chưa tải được danh sách này." + ) + expect(rendered.queueSection.textContent).toContain("Áo ấm vùng cao") + }) + + it("renders approved_past_end and suspended_before_start items with from_status guards, self-review guards, and StatusHistory", async () => { + const pastEnd = recoveryRow("77111111-1111-4111-8111-111111111111", "approved_past_end", null, { + title: "Học bổng mùa thu", + }) + const suspendedDisabled = recoveryRow( + "77222222-2222-4222-8222-222222222222", + "suspended_before_start", + "account_not_verified", + { + title: "Trạm nước sạch", + review_note: "Kiểm tra lại giấy tờ thụ hưởng.", + } + ) + const suspendedUsable = recoveryRow("77333333-3333-4333-8333-333333333333", "suspended_before_start", null, { + title: "Tủ sách bản cao", + }) + const suspendedBackWithTx = recoveryRow( + "77444444-4444-4444-8444-444444444444", + "suspended_before_start", + "account_not_verified", + { + type: "back", + funding_model: "all_or_nothing", + title: "Sách ảnh thủ công", + account_has_transactions: true, + } + ) + const ownSuspended = recoveryRow("77555555-5555-4555-8555-555555555555", "suspended_before_start", "no_account", { + organizer_id: STAFF_USER, + title: "Chiến dịch tạm dừng của kiểm duyệt viên", + }) + + setupAdmin({ + recovery: [pastEnd, suspendedDisabled, suspendedUsable, suspendedBackWithTx, ownSuspended], + statusEvents: [ + { + id: 99, + campaign_id: suspendedDisabled.id, + from_status: "approved", + to_status: "suspended", + reason: "Kiểm tra lại giấy tờ thụ hưởng.", + created_at: "2026-11-19T10:00:00.000Z", + }, + ], + }) + + const { recoverySection } = await renderAdmin() + expect(recoverySection.querySelector("h2")?.textContent).toContain("5") + expect(recoverySection.querySelectorAll(".btn-primary")).toHaveLength(0) + + const cards = Array.from(recoverySection.querySelectorAll("ul > li")) + expect(cards).toHaveLength(5) + + // 1) approved_past_end -> from_status="approved" + prefilled reason + expect(cards[0]!.textContent).toContain("Học bổng mùa thu") + expect(cards[0]!.textContent).toContain("Đã duyệt nhưng quá ngày kết thúc") + const pastEndForm = cards[0]!.querySelector("form")! + expect(pastEndForm.querySelector('input[name="from_status"]')?.getAttribute("value")).toBe("approved") + expect(pastEndForm.querySelector("textarea")?.textContent).toBe(recoveryAdvice(pastEnd).sendBackReason) + + // 2) suspended_before_start with disabled account -> from_status="suspended", shows review_note + StatusHistory + expect(cards[1]!.textContent).toContain("Trạm nước sạch") + expect(cards[1]!.textContent).toContain("Tạm dừng trước ngày bắt đầu") + expect(cards[1]!.textContent).toContain(accountProblemLabel("account_not_verified")) + expect(cards[1]!.textContent).toContain("Kiểm tra lại giấy tờ thụ hưởng.") + expect(cards[1]!.querySelector("details summary")?.textContent).toContain( + "Lịch sử trạng thái (1): Trạm nước sạch" + ) + const suspendedForm = cards[1]!.querySelector("form")! + expect(suspendedForm.querySelector('input[name="from_status"]')?.getAttribute("value")).toBe("suspended") + expect(suspendedForm.querySelector("textarea")?.textContent).toBe( + recoveryAdvice(suspendedDisabled).sendBackReason + ) + + // 3) suspended_before_start with usable account -> empty textarea with placeholder, from_status="suspended" + const usableForm = cards[2]!.querySelector("form")! + expect(usableForm.querySelector('input[name="from_status"]')?.getAttribute("value")).toBe("suspended") + expect(usableForm.querySelector("textarea")?.textContent).toBe("") + expect(usableForm.querySelector("textarea")?.getAttribute("placeholder")).toContain("Người tổ chức cần sửa gì") + + // 4) back campaign with transactions -> guidance Callout only, no send-back form + expect(cards[3]!.textContent).toContain("dự án có quà tặng chưa hỗ trợ đổi tài khoản") + expect(cards[3]!.querySelectorAll("form")).toHaveLength(0) + + // 5) moderator's own suspended campaign -> self-review guard, no form + expect(cards[4]!.textContent).toContain("Đây là chiến dịch của bạn; một kiểm duyệt viên khác cần xử lý.") + expect(cards[4]!.querySelectorAll("form")).toHaveLength(0) + }) + }) }) diff --git a/apps/web/src/app/admin/page.tsx b/apps/web/src/app/admin/page.tsx index d8f4415..6340eb0 100644 --- a/apps/web/src/app/admin/page.tsx +++ b/apps/web/src/app/admin/page.tsx @@ -17,11 +17,14 @@ import { requireSession } from "@/lib/auth/session" import { accountProblemLabel, isStaff, + listCampaignsNeedingRecovery, listOrganizersToVerify, listReviewQueue, listWaitingForAccount, + recoveryAdvice, waitingAdvice, type CampaignType, + type RecoveryCampaign, type WaitingForAccount, } from "@/lib/campaigns" import { formatDate, formatVnd } from "@/lib/format" @@ -45,19 +48,26 @@ export default async function AdminReviewPage() { } // Links to the other admin pages are the admin layout's tabs. - const [queue, waiting, organizers] = await Promise.all([ + const [queue, waiting, recovery, organizers] = await Promise.all([ listReviewQueue(db), // A read error hides only this section, not the review queue. listWaitingForAccount(db).catch((e: { code?: string; message?: string } | null): WaitingForAccount[] | null => { console.error("campaigns_waiting_for_account failed", e?.code, e?.message) return null }), + listCampaignsNeedingRecovery(db).catch( + (e: { code?: string; message?: string } | null): RecoveryCampaign[] | null => { + console.error("campaigns_needing_recovery failed", e?.code, e?.message) + return null + } + ), listOrganizersToVerify(db), ]) const statusEventsByCampaign = await listStatusEventsByCampaign(db, [ ...queue.map((campaign) => campaign.id), ...(waiting ?? []).map((campaign) => campaign.id), + ...(recovery ?? []).map((campaign) => campaign.id), ]).catch(() => new Map()) return ( @@ -229,6 +239,107 @@ export default async function AdminReviewPage() { )} + + {recovery === null ? ( + + Các phần khác của trang vẫn dùng được. Hãy tải lại trang sau. + + ) : recovery.length === 0 ? ( + + ) : ( + + {recovery.map((campaign) => { + const own = campaign.organizer_id === session.user.id + const isSuspended = campaign.recovery_kind === "suspended_before_start" + const advice = recoveryAdvice(campaign) + return ( + + + {isSuspended ? "Tạm dừng trước ngày bắt đầu" : "Đã duyệt nhưng quá ngày kết thúc"} + + } + > + {campaign.account_problem !== null ? ( +

{accountProblemLabel(campaign.account_problem)}

+ ) : !isSuspended ? ( +

+ Chiến dịch đã quá ngày kết thúc nên hệ thống không tự mở. +

+ ) : null} +
+ + + {campaign.starts_at ? formatDate(campaign.starts_at) : "Khi duyệt"} + + + {formatDate(campaign.ends_at)} + {!isSuspended ? " (đã qua)" : ""} + + {formatDate(campaign.approved_at)} + {isSuspended && campaign.review_note && ( + + {campaign.review_note} + + )} + {campaign.organizer && ( + + + {campaign.organizer.display_name} (tên pháp lý: {campaign.organizer.legal_name}) + + + + )} + + + {advice.note && {advice.note}} + {advice.sendBackReason === null ? null : own ? ( + Đây là chiến dịch của bạn; một kiểm duyệt viên khác cần xử lý. + ) : ( + + + +