diff --git a/CHANGELOG.md b/CHANGELOG.md index f280c182..e3edccdf 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 / #306). - 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 @@ -433,6 +445,26 @@ trang"` gating, `"Quản lý"`, and `changes_requested` review notes), ### Back campaigns (M3) +- Finance-approved receiving-account swap for `back` campaigns and + `payment_due` pledge notifications: extends `canAskSwap`, `approvalBlock`, + `loadEditorAccounts`, `checkSubmitAccount`, `requestAccountSwap`, + `/me/campaigns/[id]` (`ReceivingAccountSection` / `AccountSwapBlock`), + `/admin/account-swaps`, `/admin` `recoveryAdvice` and `lib/errors.ts` to + support finance-approved receiving-account swaps on `back` campaigns in + `live`, `suspended`, `changes_requested` (with recorded transactions; + zero-transaction bindings still direct to early release) and `succeeded` + when pledges still have payments due (`campaignHasPaymentsDue` / + `campaignsWithPaymentsDue`), while strictly preserving `#264` owner-only + money boundaries so co-organizers never view or submit swap requests. Adds + the `payment_account_changed` in-app notice (`lib/notices.ts`, wired into + `asksForPayment` so `stoppedNoticeCampaigns` suppresses payment CTAs while + payment requests are stopped) and the `pledge_account_swapped` transactional + email template (`server/email/templates.ts`, `lib/email-outbox.ts` 14-day + max age, live net amount due, deadline, `/me/pledges/[code]` CTA, no + unsubscribe/stop links), sharing strict anti-leak masking helpers + (`maskedAccountLast4`, `swappedNewAccountLine`, `swappedOldAccountTarget`) + so raw account numbers never leak, backed by `DOS/DOS.Me#1873` with Vitest + suites (#92 / #310). - Pledge flow, payment page, reminders and lapse (#31 / #88). - Editor: reward tiers and fulfillment updates (#83 / #87); account section and submit guard (#85 / #90). @@ -447,6 +479,38 @@ trang"` gating, `"Quản lý"`, and `changes_requested` review notes), ### Money (M1) +- Monthly donations (plan A) follow-ups from `#290`: adds the deduplicated, + bounded-concurrency `paymentAccounts()` helper (max 5 in flight, + per-campaign error isolation) in `apps/web/src/server/contributions/index.ts`, + skips `give.payment_account` RPCs on `/me/contributions` for ended plans or + plans without a potentially payable current-month donation (sharing + `currentPlanDonation()` with `PlanList` and `vnMonthStart` in + `lib/plans.ts`), runs usable-account and pledge-balance lookups in parallel + with one consistent clock, and fixes the misplaced `ContributionList` JSDoc + block. Hardens `apps/web/src/server/plans/jobs.ts`, + `GET /api/cron/issue-plan-donations` and `GET /api/cron/plan-notices` to + isolate Step 1 and Step 2 within the shared 45 s budget (still returning + HTTP 500 on step failure), drain multi-batch `expire_plan_donations` + (500 rows/batch) with per-batch error isolation and budget-guarded + stalled-batch detection (`expire_stalled: true`, `done: false`), and emit + structured zero-PII JSON error logs (`plan_cron.failed_outcomes`, + `plan_job.plan_failed`, `plan_job.expire_batch_stalled`, + `plan_job.expire_batch_failed`, `plan_cron.step_failed`) on `'failed'` + outcomes or step/batch errors, with Vitest coverage (#308 / #309). +- Monthly plan donor notifications on receiving-account swap: adds the + `plan_account_swapped` email template (`apps/web/src/server/email/templates.ts`) + and admin outbox metadata (`apps/web/src/lib/email-outbox.ts`: + `OUTBOX_KIND_LABELS.plan_account_swapped`, `OUTBOX_SKIP_LABELS.plan_not_active`, + `OUTBOX_SKIP_LABELS.account_superseded`, and 14-day `outboxMaxAgeDays`). + Notifies active monthly plan donors when a campaign's receiving account is + replaced, showing Vietnam-time swap date, new account holder name, bank + short name or crypto chain, and strictly validated masked last 4 digits only + (`•••• XXXX`, never raw account numbers), warning donors to delete saved + bank transfer templates for the old account, requiring both a signed + one-click plan stop link (`/plans/stop?t=...` and RFC 8058 + `List-Unsubscribe`) and notification unsubscribe link + (`/email/unsubscribe?t=...`), and generalizing non-summary unsubscribe copy, + backed by `DOS/DOS.Me#1871` with Vitest suites (#291 / #307). - Monthly donations, plan A (D9): a signed-in donor signs up on a give campaign that allows it (amount, day 1–28, reminder consent, the anonymity warning that a transparent account's statement shows the name @@ -616,6 +680,27 @@ trang"` gating, `"Quản lý"`, and `changes_requested` review notes), ### Platform +- Email outbox follow-ups: `apps/web/src/server/email/outbox.ts` lengthens + `CLAIM_TIMEOUT_MS` from `10_000` ms to `15_000` ms (above PostgREST's 8 s + `statement_timeout` plus pooler/network jitter while remaining under + `RUN_BUDGET_MS` = 30 s) and inspects both `claimSignal.aborted` and + `isAbortError(error)` (excluding Postgres server-side rollback `57014`) to + emit an explicit warning that an aborted `claim_outbox` call may still have + committed and leased rows for 5 minutes. `apps/web/src/server/email/provider.ts` + hardens `usesProductionDatabase(env)` to inspect the JWT `ref` claim of + `SUPABASE_SERVICE_ROLE_KEY` and `NEXT_PUBLIC_SUPABASE_ANON_KEY` in addition + to `PRODUCTION_SUPABASE_HOSTS` / `PRODUCTION_SUPABASE_REF` (cleanly ignoring + opaque `sb_secret_*` keys and malformed tokens), backed by `DOS/DOS.Me#1870` + with Vitest coverage (#273 / #305). +- PO configuration update (`docs/product-owner-config.md`): sets + `promotion_po: any` so both Antigravity PO and Claude Code PO hold equal + Production promotion authority (requiring JOY's popup approval on concrete + steps and rollback plan with zero competing open `main` promotion PRs), + records JOY's 2026-11-22 Antigravity PO takeover across `line:campaigns`, + `line:money` and `line:platform` while Claude PO is quota-limited (preserving + `po:agy` / `po:claude` mutual exclusion), and documents the 2026-11-21 local + DB ban (`Give#294` / `DOS/DOS.Me#1855`, running Give pgTAP and migration + replay in GitHub CI on `DOS/DOS.Me`) (#303 / #304). - Parallel PO configuration (CC-PO v2.18.0): `docs/product-owner-config.md` assigns Antigravity `Campaigns Product Owner` (`acc0`) to `line:campaigns` (replacing paused Qwen Code sessions), enforces `po:agy` / `po:claude` @@ -680,6 +765,52 @@ trang"` gating, `"Quản lý"`, and `changes_requested` review notes), ### Database (DOS.Me) +- Back-campaign receiving-account swap and `payment_due` pledge notices: + extends `give.request_account_swap`, `give.decide_account_swap`, + `give.account_has_swapped_history` and `give.record_bank_transaction` + post-swap outflow cutoff to `back` campaigns (`live`, `suspended`, + `changes_requested` with recorded transactions, and `succeeded` when + `give.campaign_has_payments_due(id)` is true), preserving `#264` owner-only + money boundaries, `#82` / `#119` lock order and self-review guards; adds + in-app notice kind `payment_account_changed` and transactional outbox kind + `pledge_account_swapped` (14-day max age, masked account details only, + `give.claim_outbox` `account_superseded` / 90-day `payment_requests_stopped` + hold / `not_due` / live `pledge_notice_payload` refresh), with 66 pgTAP + assertions (#92 / DOS/DOS.Me#1873, on Beta). Migration + `20261130140000_give_back_campaign_account_swap`. +- Monthly plan donor swap notifications: adds notification outbox kind + `plan_account_swapped` (14-day max age, subject to `give.email_suppressions`), + `give.outbox_on_account_swap` trigger enqueueing one masked, zero-PII row + per active `give.donation_plans` donor on approved account swaps + (`idempotency_key = 'plan_account_swapped::'`), + and `give.claim_outbox` send-time re-checks (`plan_not_active`, + `account_superseded`, `unsubscribed`, `no_recipient`, `expired`) minting a + fresh 60-day one-use stop token in `give.plan_stop_tokens`, with 53 pgTAP + assertions (#291 / DOS/DOS.Me#1871, on Beta). Migration + `20261130130000_give_plan_account_swap_notice`. +- Atomic expected-status guard and pre-launch recovery queue: adds + backwards-compatible `p_expected_status text DEFAULT NULL` to + `give.transition_campaign` (raising `GIVE_CAMPAIGN_STATUS_CHANGED`, SQLSTATE + `40001`, checked after authorization and before idempotent replay while + preserving `#82` / `#120` staff-role lock order), allows non-owner + `moderator`/`admin` `suspended -> changes_requested` recovery for never-live + campaigns with `starts_at > now()` and zero contributions (preserving `#55` + money-history immutability and `#264` owner-only boundaries), and adds + `give.campaigns_needing_recovery()` (disjoint from + `campaigns_waiting_for_account`, listing `approved_past_end` and + `suspended_before_start`), with 62 pgTAP assertions (#77 / DOS/DOS.Me#1872, + on Beta). Migration `20261130120000_give_campaign_sendback_and_suspended_recovery`. +- Email outbox follow-ups: adds partial index `give.outbox_purge_settled_idx`, + `give.contribution_access_tokens_expires_idx` and `FOR UPDATE SKIP LOCKED` + batching in `give.purge_outbox`, restricts `give.claim_outbox` + `to_email_hash` writes to `category = 'notification'` while clearing + deleted-account and legacy transactional hashes on purge, protects active + in-flight sends (`status = 'sending' AND locked_until > now()`) from purge + step 1, caps `pledge_payment_due` / `pledge_payment_reminder` holds under + `payments_stopped_at` at 90 days (`skipped`/`expired`), and recomputes + `pledge_payment_reminder` `payload->'day'` on claim from + `outcome_at + payments_stopped_total`, with 31 pgTAP assertions (#273 / + DOS/DOS.Me#1870, on Beta). Migration `20261130110000_give_outbox_followups`. - Co-organizers and single-use invites: `give.campaign_members` (editors only, blocking owner self-membership) and `give.campaign_member_invites` (32-byte SHA-256 token hashes only, zero direct table grants), 9 `SECURITY DEFINER` diff --git a/apps/web/src/app/admin/account-swaps/actions.ts b/apps/web/src/app/admin/account-swaps/actions.ts index 8e297f1f..5d3f2452 100644 --- a/apps/web/src/app/admin/account-swaps/actions.ts +++ b/apps/web/src/app/admin/account-swaps/actions.ts @@ -26,7 +26,7 @@ type Decision = (typeof DECISIONS)[number] const DONE_MESSAGES: Record = { approved: - "Đã đổi tài khoản nhận: tài khoản cũ đã ngừng và bị khóa, tài khoản mới nhận tiền từ bây giờ. Trang chiến dịch và sao kê hiện thông báo đổi tài khoản khi chiến dịch đang công khai.", + "Đã đổi tài khoản nhận: tài khoản cũ đã ngừng và bị khóa, tài khoản mới nhận tiền từ bây giờ. Trang chiến dịch và sao kê hiện thông báo đổi tài khoản khi chiến dịch đang công khai; nếu là dự án có quà tặng đang chờ thanh toán, người ủng hộ cũng đã được thông báo tài khoản mới.", rejected: "Đã từ chối yêu cầu đổi tài khoản.", } @@ -85,5 +85,7 @@ export async function decideAccountSwap( revalidatePath("/me/campaigns/[id]", "page") revalidatePath("/campaigns/[slug]", "page") revalidatePath("/campaigns/[slug]/statement", "page") + revalidatePath("/me/pledges/[code]", "page") + revalidatePath("/me/notices") return done(DONE_MESSAGES[decision]) } diff --git a/apps/web/src/app/admin/account-swaps/page.test.ts b/apps/web/src/app/admin/account-swaps/page.test.ts new file mode 100644 index 00000000..865d4334 --- /dev/null +++ b/apps/web/src/app/admin/account-swaps/page.test.ts @@ -0,0 +1,118 @@ +import { renderToStaticMarkup } from "react-dom/server" +import { beforeEach, describe, expect, it, vi } from "vitest" + +import type { SwapForReview } from "@/lib/account-swaps" +import { fakeDb, op, type Call, type Handler } from "@/test/fake-db" + +const REVIEWER = "66666666-6666-4666-8666-666666666666" +const OWNER = "11111111-1111-4111-8111-111111111111" +const DUE_CAMPAIGN = "22222222-2222-4222-8222-222222222222" +const PAID_CAMPAIGN = "33333333-3333-4333-8333-333333333333" + +const state = vi.hoisted(() => ({ + handler: (() => undefined) as Handler, + calls: [] as Call[], +})) + +vi.mock("next/navigation", () => ({ + notFound: vi.fn(() => { + throw new Error("NEXT_NOT_FOUND") + }), + usePathname: () => "/admin/account-swaps", +})) +vi.mock("@/lib/auth/session", () => ({ + requireSession: vi.fn(async () => ({ user: { id: REVIEWER, email: null, name: null }, accessToken: "token" })), +})) +vi.mock("@/lib/supabase", () => ({ + dbAs: () => fakeDb((call) => state.handler(call), state.calls), +})) + +const { default: AdminAccountSwapsPage } = await import("./page") + +function pendingSwapRow(id: string, campaignId: string, title: string): SwapForReview { + return { + id, + campaign_id: campaignId, + old_binding_id: `b-${id}`, + new_receiving_account_id: `a-new-${id}`, + new_binding_id: null, + reason: "Ngân hàng đã đóng tài khoản cũ.", + status: "pending", + decided_at: null, + decision_note: null, + public_note: null, + created_at: "2026-11-22T01:00:00Z", + campaign: { + id: campaignId, + slug: `slug-${id}`, + title, + status: "succeeded", + type: "back", + payments_stopped_at: null, + }, + new_account: { + id: `a-new-${id}`, + owner_user_id: OWNER, + channel: "statement_import", + bank_bin: "970422", + account_number: "920002220002", + account_name: "NGUYEN THI DAO", + verification_status: "verified", + review_note: null, + organizer: { legal_name: "Nguyễn Thị Đào", display_name: "Đào", verification_status: "verified" }, + }, + old_binding: { + id: `b-${id}`, + bound_at: "2026-11-01T00:00:00Z", + released_at: null, + account: { + id: `a-old-${id}`, + owner_user_id: OWNER, + channel: "statement_import", + bank_bin: "970436", + account_number: "920001110001", + account_name: "NGUYEN THI DAO", + verification_status: "disabled", + review_note: "Khóa do ngân hàng đóng", + }, + }, + } +} + +beforeEach(() => { + state.calls.length = 0 + state.handler = () => undefined +}) + +describe("AdminAccountSwapsPage (DOS/Give#92)", () => { + it("returns 404 when the caller does not hold a finance or admin role", async () => { + state.handler = (call) => (call.target === "rpc:is_admin" ? { data: false } : undefined) + await expect(AdminAccountSwapsPage()).rejects.toThrow("NEXT_NOT_FOUND") + }) + + it("enables approval for a succeeded back campaign with payments due and blocks one with none", async () => { + const dueSwap = pendingSwapRow("swap-due", DUE_CAMPAIGN, "Đèn ngủ gỗ còn chờ thanh toán") + const paidSwap = pendingSwapRow("swap-paid", PAID_CAMPAIGN, "Đèn ngủ gỗ đã thanh toán đủ") + + state.handler = (call) => { + if (call.target === "rpc:is_admin") return { data: true } + if (call.target === "account_swap_requests") { + return op(call, "eq")?.[1] === "pending" ? { data: [dueSwap, paidSwap] } : { data: [] } + } + if (call.target === "bank_transactions") return { count: 2 } + if (call.target === "contributions") { + return op(call, "eq")?.[1] === DUE_CAMPAIGN ? { data: [{ id: "pledge-1" }] } : { data: [] } + } + return undefined + } + + const html = renderToStaticMarkup(await AdminAccountSwapsPage()) + expect(html).toContain("dự án có quà tặng đã đạt mục tiêu nhưng còn cam kết chờ thanh toán") + expect(html).toContain("Đèn ngủ gỗ còn chờ thanh toán") + expect(html).toContain("Đèn ngủ gỗ đã thanh toán đủ") + expect(html).toContain("Duyệt đổi tài khoản") + expect(html).toContain("không còn cam kết nào đang chờ thanh toán") + // Only the due swap gets an approve button; the settled one gets the block callout instead. + expect(html.match(/>Duyệt đổi tài khoản = { } /** - * Finance queue of account swaps (DOS/Give#55): organizers of give campaigns - * that may hold money ask to replace an account that stopped being usable; + * Finance queue of account swaps (DOS/Give#55, #92): organizers of give or + * back campaigns that may hold money (or succeeded back campaigns with + * payments still due) ask to replace an account that stopped being usable; * finance or an admin approves (the old binding ends and the new one starts - * at the same instant) or rejects. + * at the same instant, and waiting backers are notified) or rejects. */ export default async function AdminAccountSwapsPage() { const session = await requireSession("/admin/account-swaps") @@ -49,22 +51,32 @@ export default async function AdminAccountSwapsPage() { if (!(await isStaff(db, FINANCE_ROLES))) notFound() const [pending, decided] = await Promise.all([listSwapsToReview(db), listDecidedSwaps(db)]) - const counts = await transactionCounts( - db, - pending.map((s) => s.old_binding_id) - ) + const succeededBackCampaigns = pending + .map((s) => s.campaign) + .filter((c): c is NonNullable => + Boolean(c && c.type === "back" && c.status === "succeeded") + ) + const [counts, dueCampaigns] = await Promise.all([ + transactionCounts( + db, + pending.map((s) => s.old_binding_id) + ), + campaignsWithPaymentsDue(db, succeededBackCampaigns), + ]) return ( - Người tổ chức của chiến dịch từ thiện đang gây quỹ, đang tạm dừng, hoặc cần chỉnh sửa mà tài khoản đã nhận - giao dịch, đề nghị thay tài khoản nhận không còn dùng được bằng một tài khoản khác đã xác minh, đứng tên họ. - Chỉ duyệt khi có căn cứ rằng tài khoản cũ không dùng được nữa (thư hoặc thông báo của ngân hàng, kết quả kiểm - tra gian lận). Khi duyệt, tài khoản cũ ngừng nhận cho chiến dịch và bị khóa, tài khoản mới bắt đầu nhận ngay; - tiền đã vào tài khoản cũ trước lúc đó vẫn thuộc chiến dịch. Trang chiến dịch và sao kê công khai ngày đổi. Mọi - thao tác được ghi vào nhật ký kiểm toán. + Người tổ chức của chiến dịch từ thiện hoặc dự án có quà tặng đang gây quỹ, đang tạm dừng, cần chỉnh sửa mà tài + khoản đã nhận giao dịch, hoặc dự án có quà tặng đã đạt mục tiêu nhưng còn cam kết chờ thanh toán, đề nghị thay + tài khoản nhận không còn dùng được bằng một tài khoản khác đã xác minh, đứng tên họ. Chỉ duyệt khi có căn cứ + rằng tài khoản cũ không dùng được nữa (thư hoặc thông báo của ngân hàng, kết quả kiểm tra gian lận). Khi + duyệt, tài khoản cũ ngừng nhận cho chiến dịch và bị khóa, tài khoản mới bắt đầu nhận ngay; tiền đã vào tài + khoản cũ trước lúc đó vẫn thuộc chiến dịch. Với dự án có quà tặng đã đạt mục tiêu, người ủng hộ đang chờ thanh + toán sẽ được thông báo thông tin tài khoản mới. Trang chiến dịch và sao kê công khai ngày đổi. Mọi thao tác + được ghi vào nhật ký kiểm toán.

} > @@ -80,6 +92,7 @@ export default async function AdminAccountSwapsPage() { key={swap.id} swap={swap} oldTransactions={counts.get(swap.old_binding_id) ?? 0} + hasPaymentsDue={Boolean(swap.campaign && dueCampaigns.has(swap.campaign.id))} selfId={session.user.id} /> ))} @@ -93,7 +106,13 @@ export default async function AdminAccountSwapsPage() { ) : ( {decided.map((swap) => ( - + ))} )} @@ -118,17 +137,19 @@ function AccountLine({ account }: { account: NonNullable diff --git a/apps/web/src/app/admin/actions.test.ts b/apps/web/src/app/admin/actions.test.ts index 202e8f5a..64479bb5 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 4d0bdf08..9b0c0268 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 cfa4df38..bb300899 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,119 @@ 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 -> now guides #55/#92 swap with prefilled send-back form + expect(cards[3]!.textContent).toContain("yêu cầu đổi tài khoản") + const backTxForm = cards[3]!.querySelector("form")! + expect(backTxForm.querySelector('input[name="from_status"]')?.getAttribute("value")).toBe("suspended") + expect(backTxForm.querySelector("textarea")?.textContent).toBe(recoveryAdvice(suspendedBackWithTx).sendBackReason) + + // 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 d8f44151..6340eb0d 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ý. + ) : ( + + + +