diff --git a/CHANGELOG.md b/CHANGELOG.md index f280c182..d6351590 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 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..6172ef8f 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 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ý. + ) : ( + + + +