Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
91 changes: 89 additions & 2 deletions apps/web/src/app/admin/actions.test.ts
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -40,17 +40,55 @@ 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() } }
: undefined
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")
Expand Down Expand Up @@ -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"],
Expand Down Expand Up @@ -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", () => {
Expand Down
35 changes: 27 additions & 8 deletions apps/web/src/app/admin/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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."
Expand All @@ -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<ActionResult> {
const session = await getSession()
Expand All @@ -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
Expand All @@ -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")
Expand Down
Loading