Tài khoản đang gắn tạm không dùng được: {boundUnusable} Chiến dịch không nhận được tiền qua tài khoản này.
- {type === "back" && (status === "live" || status === "suspended") && (
- <>
- {" "}
- Dự án có quà tặng chưa đổi được tài khoản khi đang gây quỹ hoặc tạm dừng: hãy liên hệ đội ngũ Give qua
- email .
- >
- )}
)}
{releasable ? (
@@ -1197,7 +1199,7 @@ function ReceivingAccountSection({
)}
- {canAskSwap(status, type, boundHasTransactions) && (
-
+ {showSwapBlock && (
+
)}
) : !canPickAccount(status, bound) ? (
@@ -1245,16 +1254,23 @@ function ReceivingAccountSection({
}
/**
- * The organizer's request to replace the bound account of a give campaign
- * that may hold money (DOS/Give#55): finance approves, and the old binding
- * ends and the new one starts at the same instant.
+ * The organizer's request to replace the bound account of a campaign (give or
+ * back) that may hold money or still has backer payments due (DOS/Give#55,
+ * #92): finance approves, and the old binding ends and the new one starts at
+ * the same instant.
*/
function AccountSwapBlock({
campaignId,
+ type,
+ status,
+ canRequest,
choices,
swaps,
}: {
campaignId: string
+ type: CampaignType
+ status: CampaignStatus
+ canRequest: boolean
choices: AccountChoice[]
swaps: AccountSwapRequest[]
}) {
@@ -1274,6 +1290,9 @@ function AccountSwapBlock({
sao kê. Tiền chuyển ra khỏi tài khoản cũ sau lúc đổi (kể cả khi bạn chuyển số dư sang tài khoản mới) vẫn ghi vào
sao kê là khoản chi của chiến dịch, và bạn cần giải trình như mọi khoản chi. Trang chiến dịch công khai ngày đổi
tài khoản.
+ {type === "back" && status === "succeeded"
+ ? " Với dự án có quà tặng đã đạt mục tiêu, người ủng hộ đang chờ thanh toán cam kết sẽ nhận thông báo kèm thông tin tài khoản mới, và trang thanh toán cùng mã VietQR cập nhật ngay theo tài khoản mới."
+ : ""}
{last && last.status === "rejected" && !pending && (
@@ -1304,7 +1323,7 @@ function AccountSwapBlock({
- ) : usable.length === 0 ? (
+ ) : !canRequest ? null : usable.length === 0 ? (
Bạn chưa có tài khoản nào khác dùng được (đã xác minh, chưa gắn với chiến dịch nào). Khai báo và xác minh tài
khoản mới tại trang{" "}
diff --git a/apps/web/src/app/me/campaigns/actions.test.ts b/apps/web/src/app/me/campaigns/actions.test.ts
index 6f06aa7c..a80a68f5 100644
--- a/apps/web/src/app/me/campaigns/actions.test.ts
+++ b/apps/web/src/app/me/campaigns/actions.test.ts
@@ -325,12 +325,22 @@ describe("submitForReview", () => {
expect(transitioned()).toBe(false)
})
- it("tells a back campaign whose unusable account holds money to contact Give, not to swap", async () => {
- const base = reads({
+ it("points a sent-back back campaign whose unusable account holds money to swap, and draft back to contact Give (DOS/Give#92)", async () => {
+ const sentBack = reads({
acct: account({ verification_status: "disabled" }),
campaign: owned({ type: "back", status: "changes_requested" }),
})
- state.userHandler = (call) => (call.target === "bank_transactions" ? { data: [{ id: "t" }] } : base(call))
+ state.userHandler = (call) => (call.target === "bank_transactions" ? { data: [{ id: "t" }] } : sentBack(call))
+ expect(await submitForReview(CAMPAIGN, null, new FormData())).toEqual({
+ ok: false,
+ message: submitUnusableAccount("Tài khoản chưa được xác minh.", true, true),
+ })
+
+ const draftBack = reads({
+ acct: account({ verification_status: "disabled" }),
+ campaign: owned({ type: "back", status: "draft" }),
+ })
+ state.userHandler = (call) => (call.target === "bank_transactions" ? { data: [{ id: "t" }] } : draftBack(call))
expect(await submitForReview(CAMPAIGN, null, new FormData())).toEqual({
ok: false,
message: submitUnusableAccount("Tài khoản chưa được xác minh.", true, false),
diff --git a/apps/web/src/app/me/campaigns/swap-actions.test.ts b/apps/web/src/app/me/campaigns/swap-actions.test.ts
index 46e6a0d7..0c1ff894 100644
--- a/apps/web/src/app/me/campaigns/swap-actions.test.ts
+++ b/apps/web/src/app/me/campaigns/swap-actions.test.ts
@@ -46,6 +46,7 @@ interface Reads {
account?: unknown
bindings?: unknown[]
transactions?: unknown[]
+ pledgesDue?: unknown[]
swaps?: unknown[]
}
@@ -62,6 +63,7 @@ function reads({
},
bindings = [{ id: BINDING, receiving_account_id: OLD_ACCOUNT }],
transactions = [{ id: "t1" }],
+ pledgesDue = [],
swaps = [],
}: Reads = {}): Handler {
return (call) => {
@@ -70,6 +72,7 @@ function reads({
if (call.target === "account_bindings") return { data: bindings }
if (call.target === "organizers") return { data: organizer }
if (call.target === "bank_transactions") return { data: transactions }
+ if (call.target === "contributions") return { data: pledgesDue }
if (call.target === "account_swap_requests") return { data: swaps }
return undefined
}
@@ -104,31 +107,65 @@ describe("requestAccountSwap", () => {
).toEqual(["binding_id", BINDING])
})
- it("lets a suspended campaign ask too", async () => {
- state.userHandler = reads({ campaign: { id: CAMPAIGN, organizer_id: USER, status: "suspended", type: "give" } })
- expect((await requestAccountSwap(CAMPAIGN, null, swapForm()))?.ok).toBe(true)
+ it("lets a suspended campaign (give or back) and live back campaign ask too (DOS/Give#92)", async () => {
+ for (const fields of [
+ { status: "suspended", type: "give" },
+ { status: "live", type: "back" },
+ { status: "suspended", type: "back" },
+ ]) {
+ state.userHandler = reads({ campaign: { id: CAMPAIGN, organizer_id: USER, ...fields } })
+ expect((await requestAccountSwap(CAMPAIGN, null, swapForm()))?.ok).toBe(true)
+ }
})
- it("sends a campaign under changes whose account recorded nothing to release it instead", async () => {
+ it("lets a succeeded back campaign ask only when pledges still have payments due (DOS/Give#92)", async () => {
state.userHandler = reads({
- campaign: { id: CAMPAIGN, organizer_id: USER, status: "changes_requested", type: "give" },
- transactions: [],
+ campaign: { id: CAMPAIGN, organizer_id: USER, status: "succeeded", type: "back", payments_stopped_at: null },
+ pledgesDue: [{ id: "p-1" }],
})
- const result = await requestAccountSwap(CAMPAIGN, null, swapForm())
- expect(result).toEqual({ ok: false, message: expect.stringContaining("nhả tài khoản đó rồi gắn tài khoản khác") })
- expect(state.serviceCalls).toEqual([])
- })
+ expect((await requestAccountSwap(CAMPAIGN, null, swapForm()))?.ok).toBe(true)
- it("lets a campaign under changes ask when its account holds money history", async () => {
+ state.serviceCalls.length = 0
state.userHandler = reads({
- campaign: { id: CAMPAIGN, organizer_id: USER, status: "changes_requested", type: "give" },
+ campaign: { id: CAMPAIGN, organizer_id: USER, status: "succeeded", type: "back", payments_stopped_at: null },
+ pledgesDue: [],
})
- expect((await requestAccountSwap(CAMPAIGN, null, swapForm()))?.ok).toBe(true)
+ const refused = await requestAccountSwap(CAMPAIGN, null, swapForm())
+ expect(refused?.ok).toBe(false)
+ expect(refused?.message).toContain("Chỉ đổi được tài khoản nhận")
+ expect(state.serviceCalls).toEqual([])
+ })
+
+ it("sends a campaign (give or back) under changes whose account recorded nothing to release it instead", async () => {
+ for (const type of ["give", "back"] as const) {
+ state.serviceCalls.length = 0
+ state.userHandler = reads({
+ campaign: { id: CAMPAIGN, organizer_id: USER, status: "changes_requested", type },
+ transactions: [],
+ })
+ const result = await requestAccountSwap(CAMPAIGN, null, swapForm())
+ expect(result).toEqual({
+ ok: false,
+ message: expect.stringContaining("nhả tài khoản đó rồi gắn tài khoản khác"),
+ })
+ expect(state.serviceCalls).toEqual([])
+ }
+ })
+
+ it("lets a campaign (give or back) under changes ask when its account holds money history", async () => {
+ for (const type of ["give", "back"] as const) {
+ state.userHandler = reads({
+ campaign: { id: CAMPAIGN, organizer_id: USER, status: "changes_requested", type },
+ })
+ expect((await requestAccountSwap(CAMPAIGN, null, swapForm()))?.ok).toBe(true)
+ }
})
it.each([
["an approved campaign", { status: "approved", type: "give" }],
- ["a back campaign", { status: "live", type: "back" }],
+ ["an approved back campaign", { status: "approved", type: "back" }],
+ ["a settling back campaign", { status: "settling", type: "back" }],
+ ["a failed back campaign", { status: "failed", type: "back" }],
["a closed campaign", { status: "closed", type: "give" }],
])("refuses %s", async (_label, fields) => {
state.userHandler = reads({ campaign: { id: CAMPAIGN, organizer_id: USER, ...fields } })
@@ -138,9 +175,14 @@ describe("requestAccountSwap", () => {
expect(state.serviceCalls).toEqual([])
})
- it("refuses a campaign of someone else, and an account of someone else", async () => {
+ it("refuses a campaign of someone else (including #264 co-organizers on back campaigns), and an account of someone else", async () => {
state.userHandler = reads({ campaign: { id: CAMPAIGN, organizer_id: OTHER, status: "live", type: "give" } })
expect((await requestAccountSwap(CAMPAIGN, null, swapForm()))?.message).toContain("Không tìm thấy chiến dịch")
+ state.userHandler = reads({
+ campaign: { id: CAMPAIGN, organizer_id: OTHER, status: "succeeded", type: "back" },
+ pledgesDue: [{ id: "p-1" }],
+ })
+ expect((await requestAccountSwap(CAMPAIGN, null, swapForm()))?.message).toContain("Không tìm thấy chiến dịch")
state.userHandler = reads({ account: { id: NEW_ACCOUNT, owner_user_id: OTHER, bindings: [] } })
expect((await requestAccountSwap(CAMPAIGN, null, swapForm()))?.message).toContain("Không tìm thấy tài khoản nhận")
expect(state.serviceCalls).toEqual([])
diff --git a/apps/web/src/app/me/campaigns/swap-actions.ts b/apps/web/src/app/me/campaigns/swap-actions.ts
index a707a413..b6321387 100644
--- a/apps/web/src/app/me/campaigns/swap-actions.ts
+++ b/apps/web/src/app/me/campaigns/swap-actions.ts
@@ -4,6 +4,7 @@ import { revalidatePath } from "next/cache"
import {
bindingHasTransactions,
+ campaignHasPaymentsDue,
canAskSwap,
listCampaignSwaps,
pendingSwap,
@@ -17,9 +18,10 @@ import { accountUnusableReason, activeBinding, activeBindingsOfCampaign, getAcco
import { dbAs, dbService } from "@/lib/supabase"
/**
- * The organizer's side of an account swap (DOS/Give#55): ask finance to
- * replace the receiving account of a give campaign that may hold money, or
- * withdraw the request while it waits.
+ * The organizer's side of an account swap (DOS/Give#55, #92): ask finance to
+ * replace the receiving account of a campaign (give or back) that may hold
+ * money or still has backer payments due, or withdraw the request while it
+ * waits. Strictly owner-only (DOS/Give#264 editors are refused).
*
* Like the other money actions (app/me/accounts/actions.ts), the RPCs run as
* the service role and trust the actor id passed in, so every action first
@@ -70,18 +72,21 @@ export async function requestAccountSwap(
if (!bound) return fail(NO_BINDING)
if (bound.receiving_account_id === account.id) return fail(dbErrorMessage({ message: "GIVE_SWAP_SAME_ACCOUNT" }))
let hasTransactions
+ let hasPaymentsDue = false
try {
- hasTransactions = await bindingHasTransactions(db, bound.id)
+ ;[hasTransactions, hasPaymentsDue] = await Promise.all([
+ bindingHasTransactions(db, bound.id),
+ campaign.status === "succeeded" && campaign.type === "back"
+ ? campaignHasPaymentsDue(db, campaign.id, campaign.payments_stopped_at ?? null)
+ : Promise.resolve(false),
+ ])
} catch (error) {
return fail(dbErrorMessage(error as { message?: string; code?: string }))
}
- if (!canAskSwap(campaign.status, campaign.type, hasTransactions)) {
+ if (!canAskSwap(campaign.status, campaign.type, hasTransactions, hasPaymentsDue)) {
return fail(
dbErrorMessage({
- message:
- campaign.status === "changes_requested" && campaign.type === "give"
- ? "GIVE_SWAP_USE_RELEASE"
- : "GIVE_SWAP_NOT_ALLOWED",
+ message: campaign.status === "changes_requested" ? "GIVE_SWAP_USE_RELEASE" : "GIVE_SWAP_NOT_ALLOWED",
})
)
}
diff --git a/apps/web/src/app/me/contributions/PlanList.tsx b/apps/web/src/app/me/contributions/PlanList.tsx
index 759fe8be..f5ddd725 100644
--- a/apps/web/src/app/me/contributions/PlanList.tsx
+++ b/apps/web/src/app/me/contributions/PlanList.tsx
@@ -14,11 +14,14 @@ import {
planDayLabel,
planDonationPayable,
planEndedReasonLabel,
+ vnMonthStart,
} from "@/lib/plans"
import { DONATION_TONES, toneOf } from "../_components/tones"
import { cancelPlan, updatePlan } from "./actions"
+export { vnMonthStart }
+
export interface MyPlan {
id: string
campaign_id: string
@@ -48,10 +51,16 @@ export function effectiveNextPeriod(nextPeriod: string, month: string): string {
return nextPeriod < month ? month : nextPeriod
}
-/** The first day of the current month in Vietnam time (UTC+7), as YYYY-MM-DD. */
-export function vnMonthStart(now = new Date()): string {
- const vn = new Date(now.getTime() + 7 * 60 * 60 * 1000)
- return `${vn.getUTCFullYear()}-${String(vn.getUTCMonth() + 1).padStart(2, "0")}-01`
+/**
+ * This month's plan donation for the campaign: a plan cancelled and signed up
+ * again in the same month keeps the earlier plan's donation.
+ */
+export function currentPlanDonation(
+ campaignId: string,
+ donations: readonly PlanDonation[],
+ month: string
+): PlanDonation | null {
+ return donations.find((d) => d.plan_id !== null && d.plan_period === month && d.campaign_id === campaignId) ?? null
}
const DAYS = Array.from({ length: 28 }, (_, i) => i + 1)
@@ -91,13 +100,7 @@ export function PlanList({
plan={plan}
month={month}
now={now}
- // This month's donation of the campaign: a plan cancelled and signed
- // up again in the same month keeps the earlier plan's donation.
- current={
- donations.find(
- (d) => d.plan_id !== null && d.plan_period === month && d.campaign_id === plan.campaign_id
- ) ?? null
- }
+ current={currentPlanDonation(plan.campaign_id, donations, month)}
/>
))}
diff --git a/apps/web/src/app/me/contributions/page.test.ts b/apps/web/src/app/me/contributions/page.test.ts
index 16b2d9e0..35accfa3 100644
--- a/apps/web/src/app/me/contributions/page.test.ts
+++ b/apps/web/src/app/me/contributions/page.test.ts
@@ -26,6 +26,7 @@ const state = vi.hoisted(() => ({
calls: [] as Call[],
// The service role's give.payment_account: the campaign's usable account.
service: (() => undefined) as Handler,
+ serviceCalls: [] as Call[],
}))
vi.mock("@/lib/auth/session", () => ({
@@ -33,7 +34,7 @@ vi.mock("@/lib/auth/session", () => ({
}))
vi.mock("@/lib/supabase", () => ({
dbAs: () => fakeDb((call) => state.handler(call), state.calls),
- dbService: () => fakeDb((call) => state.service(call)),
+ dbService: () => fakeDb((call) => state.service(call), state.serviceCalls),
}))
vi.mock("../_components/MePage", () => ({
MePage: ({ children }: { children: ReactNode }) => createElement("main", null, children),
@@ -125,10 +126,12 @@ beforeEach(() => {
vi.useFakeTimers({ toFake: ["Date"] })
vi.setSystemTime(NOW)
state.calls.length = 0
+ state.serviceCalls.length = 0
state.service = (call) => (call.target === "rpc:payment_account" ? { data: ACCOUNT } : undefined)
})
afterEach(() => {
vi.useRealTimers()
+ vi.restoreAllMocks()
})
describe("MyContributionsPage monthly plans (DOS/Give#276)", () => {
@@ -247,4 +250,68 @@ describe("MyContributionsPage monthly plans (DOS/Give#276)", () => {
;({ doc } = await render())
expect(doc.body.textContent).toContain("Bạn chưa ủng hộ chiến dịch hay dự án nào.")
})
+
+ it("skips payment_account lookups when no active plan has a payable current-month donation", async () => {
+ serve(
+ [
+ plan({ id: "a1", campaign_id: CAMPAIGN }),
+ plan({ id: "a2", campaign_id: OTHER_CAMPAIGN, day_of_month: 25, next_period: "2026-11-01" }),
+ plan({ id: "a3", campaign_id: "77777777-7777-4777-8777-777777777777", status: "ended" }),
+ ],
+ [donation({ campaign_id: CAMPAIGN, status: "received", received_amount: 200000 })]
+ )
+ await render()
+ expect(state.serviceCalls.filter((c) => c.target === "rpc:payment_account")).toHaveLength(0)
+ })
+
+ it("deduplicates payment_account lookups across plans and isolates a failing lookup without logging PII", async () => {
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
+ const THIRD_CAMPAIGN = "77777777-7777-4777-8777-777777777777"
+ serve(
+ [
+ plan({ id: PLAN, campaign_id: CAMPAIGN }),
+ plan({ id: "88888888-8888-4888-8888-888888888888", campaign_id: CAMPAIGN }),
+ plan({ id: OLD_PLAN, campaign_id: OTHER_CAMPAIGN }),
+ plan({ id: "99999999-9999-4999-8999-999999999999", campaign_id: THIRD_CAMPAIGN }),
+ ],
+ [
+ donation({ id: "d1", campaign_id: CAMPAIGN, reference_code: "GVCAMP001" }),
+ donation({ id: "d2", campaign_id: OTHER_CAMPAIGN, plan_id: OLD_PLAN, reference_code: "GVCAMP002" }),
+ donation({
+ id: "d3",
+ campaign_id: THIRD_CAMPAIGN,
+ plan_id: "99999999-9999-4999-8999-999999999999",
+ reference_code: "GVCAMP003",
+ }),
+ ]
+ )
+ state.service = (call) => {
+ if (call.target !== "rpc:payment_account") return undefined
+ const id = (call.ops.find(([n]) => n === "args")?.[1] as { p_campaign_id: string }).p_campaign_id
+ if (id === CAMPAIGN) return { data: ACCOUNT }
+ if (id === OTHER_CAMPAIGN) return { data: null }
+ return { error: { code: "57014", message: "donor@example.com secret" } }
+ }
+
+ const { doc } = await render()
+ const accountCalls = state.serviceCalls.filter((c) => c.target === "rpc:payment_account")
+ expect(accountCalls).toHaveLength(3)
+ const section = planSection(doc)!
+ // CAMPAIGN has usable account -> shows transfer button
+ expect(section.querySelector('a[href="/donations/GVCAMP001"]')?.textContent).toBe("Chuyển khoản tháng này")
+ // OTHER_CAMPAIGN has no usable account -> hides transfer button
+ expect(section.querySelector('a[href="/donations/GVCAMP002"]')?.textContent).not.toBe("Chuyển khoản tháng này")
+ // THIRD_CAMPAIGN failed lookup -> stays unknown (shows button; payment page re-checks)
+ expect(section.querySelector('a[href="/donations/GVCAMP003"]')?.textContent).toBe("Chuyển khoản tháng này")
+
+ expect(errorSpy).toHaveBeenCalledTimes(1)
+ const logged = JSON.parse(String(errorSpy.mock.calls[0][0])) as Record
+ expect(logged).toEqual({
+ event: "contributions.payment_account_lookup_failed",
+ campaign_id: THIRD_CAMPAIGN,
+ code: "57014",
+ })
+ expect(JSON.stringify(logged)).not.toContain("donor@example.com")
+ expect(JSON.stringify(logged)).not.toContain(USER)
+ })
})
diff --git a/apps/web/src/app/me/contributions/page.tsx b/apps/web/src/app/me/contributions/page.tsx
index 27b3e56a..7acbefde 100644
--- a/apps/web/src/app/me/contributions/page.tsx
+++ b/apps/web/src/app/me/contributions/page.tsx
@@ -12,17 +12,17 @@ import { SkeletonList } from "@/components/ui/Skeleton"
import { requireSession, type Session } from "@/lib/auth/session"
import { donationStatusLabel } from "@/lib/contributions"
import { formatDate, formatVnd } from "@/lib/format"
-import { periodLabel } from "@/lib/plans"
+import { periodLabel, planDonationPayable, vnMonthStart } from "@/lib/plans"
import { fulfillmentLabel, offersPayment, pledgeListSummary, withoutReplacedPledges } from "@/lib/pledges"
import { dbAs, dbService } from "@/lib/supabase"
-import { paymentAccount } from "@/server/contributions"
+import { paymentAccounts } from "@/server/contributions"
import { pledgeBalances, type PledgeBalance } from "@/server/pledges"
import { MePage } from "../_components/MePage"
import { DONATION_TONES, toneOf } from "../_components/tones"
import { RefCode } from "@/components/ui/RefCode"
-import { PlanList, type MyPlan } from "./PlanList"
+import { currentPlanDonation, PlanList, type MyPlan } from "./PlanList"
export const metadata: Metadata = { title: "Ủng hộ của tôi", robots: { index: false } }
@@ -60,6 +60,46 @@ export default async function MyContributionsPage() {
)
}
+/**
+ * Marks each active plan whose current-month donation is otherwise payable
+ * with whether its campaign has a usable account (give.payment_account, as
+ * the service role, deduped and bounded in parallel), so "Chuyển khoản tháng
+ * này" is offered only when the payment page can show a QR, as
+ * give.plan_donation_payable decides. Plans without an awaiting current-month
+ * donation skip the lookup; a failed lookup leaves it unknown and the payment
+ * page checks again.
+ */
+async function withUsableAccounts(plans: MyPlan[], donations: readonly MyContribution[], now: Date): Promise {
+ const month = vnMonthStart(now)
+ const ids = plans
+ .filter((p) => {
+ if (p.status !== "active" || !p.campaign) return false
+ const current = currentPlanDonation(p.campaign_id, donations, month)
+ return current !== null && planDonationPayable({ ...current, campaign: p.campaign }, now)
+ })
+ .map((p) => p.campaign_id)
+ if (ids.length === 0) return plans
+
+ const accounts = await paymentAccounts(dbService(), ids, {
+ onError: (campaignId, error) => {
+ const rawCode = (error as { code?: unknown } | null)?.code
+ const code = typeof rawCode === "string" && rawCode.length > 0 ? rawCode : undefined
+ console.error(
+ JSON.stringify({
+ event: "contributions.payment_account_lookup_failed",
+ campaign_id: campaignId,
+ ...(code ? { code } : {}),
+ })
+ )
+ },
+ })
+ return plans.map((p) =>
+ p.campaign && accounts.has(p.campaign_id)
+ ? { ...p, campaign: { ...p.campaign, usable_account: accounts.get(p.campaign_id) !== null } }
+ : p
+ )
+}
+
/**
* The signed-in user's donations and pledges, read with their own token under
* RLS. Pledges that change_pledge replaced are hidden; the current one shows
@@ -71,37 +111,6 @@ export default async function MyContributionsPage() {
* Monthly plans (DOS/Give#276) come first, also read under RLS; this month's
* donation of each is among the newest contributions.
*/
-/**
- * Marks each active plan's live campaign with whether it has a usable
- * account (give.payment_account, as the service role, for campaigns the
- * donor's own plans name), so "Chuyển khoản tháng này" is offered only when
- * the payment page can show a QR, as give.plan_donation_payable decides. A
- * failed lookup leaves it unknown; the payment page checks again.
- */
-async function withUsableAccounts(plans: MyPlan[]): Promise {
- const ids = [
- ...new Set(plans.filter((p) => p.status === "active" && p.campaign?.status === "live").map((p) => p.campaign_id)),
- ]
- if (ids.length === 0) return plans
- const service = dbService()
- const usable = new Map(
- await Promise.all(
- ids.map(async (id) => {
- const account = await paymentAccount(service, id).catch((e: unknown) => {
- console.error("contributions: payment account lookup failed", e)
- return undefined
- })
- return [id, account === undefined ? undefined : account !== null] as const
- })
- )
- )
- return plans.map((p) =>
- p.campaign && usable.get(p.campaign_id) !== undefined
- ? { ...p, campaign: { ...p.campaign, usable_account: usable.get(p.campaign_id) } }
- : p
- )
-}
-
async function ContributionList({ session }: { session: Session }) {
const db = dbAs(session.accessToken)
const [{ data, error }, plansRead] = await Promise.all([
@@ -126,15 +135,19 @@ async function ContributionList({ session }: { session: Session }) {
])
if (error) throw error
if (plansRead.error) throw plansRead.error
- const plans = await withUsableAccounts((plansRead.data ?? []) as unknown as MyPlan[])
+ const now = new Date()
const contributions = withoutReplacedPledges((data ?? []) as unknown as MyContribution[])
- const balances: Map = contributions.some((c) => c.kind === "pledge")
- ? await pledgeBalances(dbService(), session.user.id).catch((e: unknown) => {
- // The list still renders; pledge lines leave out what refunds could change.
- console.error("contributions: pledge balances lookup failed", e)
- return new Map()
- })
- : new Map()
+ const planDonations = contributions.filter((c) => c.plan_id !== null)
+ const [plans, balances] = await Promise.all([
+ withUsableAccounts((plansRead.data ?? []) as unknown as MyPlan[], planDonations, now),
+ contributions.some((c) => c.kind === "pledge")
+ ? pledgeBalances(dbService(), session.user.id).catch((e: unknown) => {
+ // The list still renders; pledge lines leave out what refunds could change.
+ console.error("contributions: pledge balances lookup failed", e)
+ return new Map()
+ })
+ : Promise.resolve(new Map()),
+ ])
if (contributions.length === 0 && plans.length === 0) {
return (
@@ -150,7 +163,7 @@ async function ContributionList({ session }: { session: Session }) {
return (
- {plans.length > 0 &&
c.plan_id !== null)} />}
+ {plans.length > 0 && }
{contributions.length > 0 &&
(plans.length > 0 ? (
diff --git a/apps/web/src/app/me/notices/page.test.ts b/apps/web/src/app/me/notices/page.test.ts
index 03d5ec05..f96febb8 100644
--- a/apps/web/src/app/me/notices/page.test.ts
+++ b/apps/web/src/app/me/notices/page.test.ts
@@ -161,4 +161,74 @@ describe("MyNoticesPage (DOS/Give#93)", () => {
expect(html).toContain(`href="/me/campaigns/${ACTIVE_CAMPAIGN}"`)
expect(html).toContain(">Quản lý chiến dịch<")
})
+
+ it("renders payment_account_changed neutrally when stopped and with payment CTA when active (DOS/Give#92)", async () => {
+ state.handler = (call) => {
+ if (call.target === "notices") {
+ if (call.ops.some(([name]) => name === "is")) return { count: 2 }
+ return {
+ data: [
+ {
+ id: "77777777-7777-4777-8777-777777777777",
+ kind: "payment_account_changed",
+ campaign_id: STOPPED_CAMPAIGN,
+ payload: {
+ campaign_title: "Đèn ngủ gỗ",
+ reference_code: "GVSWP234",
+ intended_amount: 500_000,
+ received_amount: 0,
+ changed_date: "2026-11-22",
+ new_bank_bin: "970422",
+ new_account_last4: "0002",
+ },
+ created_at: "2026-11-22T02:00:00Z",
+ read_at: null,
+ },
+ {
+ id: "88888888-8888-4888-8888-888888888888",
+ kind: "payment_account_changed",
+ campaign_id: ACTIVE_CAMPAIGN,
+ payload: {
+ campaign_title: "Bàn phím cơ",
+ reference_code: "GVSWP567",
+ intended_amount: 400_000,
+ received_amount: 0,
+ changed_date: "2026-11-22",
+ new_bank_bin: "970422",
+ new_account_name: "NGUYEN THI DAO",
+ new_account_last4: "0002",
+ old_bank_bin: "970436",
+ old_account_last4: "0001",
+ },
+ created_at: "2026-11-22T01:00:00Z",
+ read_at: null,
+ },
+ ],
+ }
+ }
+ if (call.target === "campaigns") {
+ return {
+ data: [
+ { id: STOPPED_CAMPAIGN, payments_stopped_at: "2026-11-22T03:00:00Z" },
+ { id: ACTIVE_CAMPAIGN, payments_stopped_at: null },
+ ],
+ }
+ }
+ return undefined
+ }
+
+ const html = await renderAsync(await MyNoticesPage())
+ const items = [...html.matchAll(//g)].map((m) => m[0])
+ expect(items).toHaveLength(2)
+
+ expect(items[0]).toContain("Yêu cầu thanh toán đang tạm dừng")
+ expect(items[0]).toContain('href="/me/pledges/GVSWP234"')
+ expect(items[0]).toContain(">Xem cam kết<")
+ expect(items[0]).not.toContain(">Thanh toán ngay<")
+
+ expect(items[1]).toContain("Tài khoản nhận thanh toán đã thay đổi")
+ expect(items[1]).toContain("•••• 0002")
+ expect(items[1]).toContain('href="/me/pledges/GVSWP567"')
+ expect(items[1]).toContain(">Thanh toán ngay<")
+ })
})
diff --git a/apps/web/src/lib/account-swaps.test.ts b/apps/web/src/lib/account-swaps.test.ts
index 8b8eb7e9..d47733b6 100644
--- a/apps/web/src/lib/account-swaps.test.ts
+++ b/apps/web/src/lib/account-swaps.test.ts
@@ -4,6 +4,8 @@ import { fakeDb, op, type Call } from "@/test/fake-db"
import {
approvalBlock,
+ campaignHasPaymentsDue,
+ campaignsWithPaymentsDue,
canAskSwap,
describeAccountChange,
lastDecidedSwap,
@@ -34,21 +36,56 @@ function request(id: string, status: AccountSwapRequest["status"]): AccountSwapR
}
describe("canAskSwap", () => {
- it("offers a swap for a live or suspended give campaign", () => {
- expect(canAskSwap("live", "give", false)).toBe(true)
- expect(canAskSwap("suspended", "give", false)).toBe(true)
+ it("offers a swap for live or suspended give and back campaigns (DOS/Give#55, #92)", () => {
+ for (const type of ["give", "back"] as const) {
+ expect(canAskSwap("live", type, false)).toBe(true)
+ expect(canAskSwap("suspended", type, false)).toBe(true)
+ }
})
- it("offers it to a give campaign under changes only when the account holds money history", () => {
- expect(canAskSwap("changes_requested", "give", true)).toBe(true)
- expect(canAskSwap("changes_requested", "give", false)).toBe(false)
+ it("offers it under changes_requested only when the account holds money history", () => {
+ for (const type of ["give", "back"] as const) {
+ expect(canAskSwap("changes_requested", type, true)).toBe(true)
+ expect(canAskSwap("changes_requested", type, false)).toBe(false)
+ }
})
- it("never offers it to other statuses or to back campaigns", () => {
- for (const status of ["draft", "in_review", "approved", "closed", "cancelled"] as const) {
- expect(canAskSwap(status, "give", true)).toBe(false)
+ it("offers it to a succeeded back campaign only while pledges still have payments due (DOS/Give#92)", () => {
+ expect(canAskSwap("succeeded", "back", false, true)).toBe(true)
+ expect(canAskSwap("succeeded", "back", true, false)).toBe(false)
+ expect(canAskSwap("succeeded", "give", true, true)).toBe(false)
+ })
+
+ it("never offers it to other statuses", () => {
+ for (const status of ["draft", "in_review", "approved", "settling", "failed", "closed", "cancelled"] as const) {
+ expect(canAskSwap(status, "give", true, true)).toBe(false)
+ expect(canAskSwap(status, "back", true, true)).toBe(false)
}
- expect(canAskSwap("live", "back", true)).toBe(false)
+ })
+})
+
+describe("campaignHasPaymentsDue and campaignsWithPaymentsDue (DOS/Give#92)", () => {
+ it("queries active payment_due/partially_paid pledges past payments_stopped_at or now", async () => {
+ const calls: Call[] = []
+ const db = fakeDb(() => ({ data: [{ id: "p-1" }] }), calls)
+ expect(await campaignHasPaymentsDue(db as unknown as Db, "c-1", "2026-11-10T00:00:00Z")).toBe(true)
+ expect(calls[0].target).toBe("contributions")
+ expect(calls[0].ops).toContainEqual(["eq", "campaign_id", "c-1"])
+ expect(calls[0].ops).toContainEqual(["eq", "kind", "pledge"])
+ expect(calls[0].ops).toContainEqual(["in", "status", ["payment_due", "partially_paid"]])
+ expect(calls[0].ops).toContainEqual(["gt", "payment_due_at", "2026-11-10T00:00:00Z"])
+ })
+
+ it("batches unique succeeded back campaigns and returns only those with payments due", async () => {
+ const calls: Call[] = []
+ const db = fakeDb((call) => ({ data: op(call, "eq")?.[1] === "c-1" ? [{ id: "p-1" }] : [] }), calls)
+ const due = await campaignsWithPaymentsDue(db as unknown as Db, [
+ { id: "c-1", payments_stopped_at: null },
+ { id: "c-2", payments_stopped_at: "2026-11-10T00:00:00Z" },
+ { id: "c-1", payments_stopped_at: null },
+ ])
+ expect([...due]).toEqual(["c-1"])
+ expect(calls).toHaveLength(2)
})
})
@@ -88,20 +125,36 @@ function review(overrides: Partial = {}): SwapForReview {
}
describe("approvalBlock", () => {
- it("lets a request that still describes the campaign be approved", () => {
+ it("lets a request that still describes an eligible give or back campaign be approved", () => {
expect(approvalBlock(review(), 3)).toBeNull()
+ expect(approvalBlock(review({ campaign: { ...review().campaign!, type: "back", status: "live" } }), 0)).toBeNull()
+ expect(
+ approvalBlock(review({ campaign: { ...review().campaign!, type: "back", status: "suspended" } }), 0)
+ ).toBeNull()
+ expect(
+ approvalBlock(review({ campaign: { ...review().campaign!, type: "back", status: "succeeded" } }), 0, true)
+ ).toBeNull()
})
it("explains a stale request", () => {
expect(approvalBlock(review({ campaign: { ...review().campaign!, status: "closed" } }), 3)).toContain(
"không còn ở trạng thái"
)
+ expect(
+ approvalBlock(review({ campaign: { ...review().campaign!, type: "back", status: "succeeded" } }), 3, false)
+ ).toContain("không còn cam kết nào đang chờ thanh toán")
+ expect(
+ approvalBlock(review({ campaign: { ...review().campaign!, type: "back", status: "failed" } }), 3, true)
+ ).toContain("không còn ở trạng thái")
expect(
approvalBlock(review({ old_binding: { ...review().old_binding!, released_at: "2026-11-02T00:00:00Z" } }), 3)
).toContain("đã thay đổi")
expect(approvalBlock(review({ campaign: { ...review().campaign!, status: "changes_requested" } }), 0)).toContain(
"tự nhả"
)
+ expect(
+ approvalBlock(review({ campaign: { ...review().campaign!, type: "back", status: "changes_requested" } }), 0)
+ ).toContain("tự nhả")
expect(
approvalBlock(review({ new_account: { ...review().new_account!, verification_status: "disabled" } }), 3)
).toContain("Tài khoản mới")
@@ -122,7 +175,8 @@ describe("approvalBlock", () => {
describe("REVIEW_COLUMNS", () => {
it("never reads campaigns.organizer_id, which authenticated may not select", () => {
const campaignEmbed = /campaign:campaigns\(([^)]*)\)/.exec(REVIEW_COLUMNS)?.[1]
- expect(campaignEmbed).toBe("id, slug, title, status, type")
+ expect(campaignEmbed).toBe("id, slug, title, status, type, payments_stopped_at")
+ expect(campaignEmbed).not.toContain("organizer_id")
expect(REVIEW_COLUMNS).toContain("new_account:receiving_accounts(id, owner_user_id,")
expect(REVIEW_COLUMNS).toContain("organizer:organizers(legal_name, display_name, verification_status)")
expect(REVIEW_COLUMNS).toContain("account_bindings!account_swap_requests_old_binding_id_fkey")
diff --git a/apps/web/src/lib/account-swaps.ts b/apps/web/src/lib/account-swaps.ts
index ac0fbf2f..f89231d0 100644
--- a/apps/web/src/lib/account-swaps.ts
+++ b/apps/web/src/lib/account-swaps.ts
@@ -4,19 +4,23 @@ import { formatDateTime } from "./format"
import type { ReceivingAccount } from "./receiving-accounts"
/**
- * Replacing the receiving account of a give campaign that may hold money
- * (DOS/Give#55; DDL in DOS-Me
- * `supabase/migrations/20261105090000_give_live_campaign_account_swap.sql`).
+ * Replacing the receiving account of a campaign that may hold money
+ * (DOS/Give#55, extended to back campaigns in DOS/Give#92; DDL in DOS-Me
+ * `supabase/migrations/20261105090000_give_live_campaign_account_swap.sql`
+ * and `20261130140000_give_back_campaign_account_swap.sql`).
*
- * A live or suspended give campaign, or one sent back for changes whose
- * account already recorded a bank transaction, cannot release its account.
- * When that account stops being usable, the organizer asks for a swap to
- * another of their verified accounts (give.request_account_swap), and finance
- * or an admin approves it (give.decide_account_swap): in one transaction the
- * old binding ends and the new one starts at the same instant. Transactions
- * keep their campaign by the time the bank booked them, so money that reached
- * the old account before the swap stays the campaign's, and the public pages
- * show the change with its date (give.public_account_changes).
+ * A live or suspended campaign (give or back), one sent back for changes whose
+ * account already recorded a bank transaction, or a succeeded back campaign
+ * that still has pledges awaiting payment cannot release its account. When
+ * that account stops being usable, the organizer asks for a swap to another of
+ * their verified accounts (give.request_account_swap), and finance or an admin
+ * approves it (give.decide_account_swap): in one transaction the old binding
+ * ends and the new one starts at the same instant. Transactions keep their
+ * campaign by the time the bank booked them, so money that reached the old
+ * account before the swap stays the campaign's, public pages show the change
+ * with its date (give.public_account_changes), and for a succeeded back
+ * campaign, backers with payments still due receive a notice and email with
+ * the new payment details.
*/
export type SwapStatus = "pending" | "approved" | "rejected" | "cancelled"
@@ -53,16 +57,63 @@ export const SWAP_PUBLIC_NOTE_MAX = 300
/**
* Campaign statuses a swap is for (give.is_swap_status). A campaign sent back
* for changes swaps only when its bound account recorded a transaction;
- * otherwise the organizer releases it and binds another (DOS/Give#38).
+ * otherwise the organizer releases it and binds another (DOS/Give#38, #77).
+ * A succeeded back campaign may also swap while pledges still have payments
+ * due (DOS/Give#92).
*/
export const SWAP_STATUSES: readonly CampaignStatus[] = ["live", "suspended", "changes_requested"]
/** Whether the organizer may ask to swap the campaign's bound account now. */
-export function canAskSwap(status: CampaignStatus, type: CampaignType, boundHasTransactions: boolean): boolean {
- if (type !== "give" || !SWAP_STATUSES.includes(status)) return false
+export function canAskSwap(
+ status: CampaignStatus,
+ type: CampaignType,
+ boundHasTransactions: boolean,
+ hasPaymentsDue = false
+): boolean {
+ if (status === "succeeded") return type === "back" && hasPaymentsDue
+ if (!SWAP_STATUSES.includes(status)) return false
return status !== "changes_requested" || boundHasTransactions
}
+/**
+ * Whether a succeeded back campaign still has at least one pledge awaiting
+ * payment (mirrors give.campaign_has_payments_due; the database stays the
+ * authority under its locks). Accessible to the campaign's organizer and
+ * finance/admin staff under RLS on give.contributions.
+ */
+export async function campaignHasPaymentsDue(
+ db: Db,
+ campaignId: string,
+ paymentsStoppedAt: string | null = null
+): Promise {
+ const cutoff = paymentsStoppedAt ?? new Date().toISOString()
+ const { data, error } = await db
+ .from("contributions")
+ .select("id")
+ .eq("campaign_id", campaignId)
+ .eq("kind", "pledge")
+ .in("status", ["payment_due", "partially_paid"])
+ .gt("payment_due_at", cutoff)
+ .limit(1)
+ if (error) throw error
+ return (data ?? []).length > 0
+}
+
+/** Which of the given succeeded back campaigns still have pledges awaiting payment. */
+export async function campaignsWithPaymentsDue(
+ db: Db,
+ campaigns: readonly { id: string; payments_stopped_at?: string | null }[]
+): Promise> {
+ const byId = new Map()
+ for (const c of campaigns) {
+ if (!byId.has(c.id)) byId.set(c.id, c.payments_stopped_at ?? null)
+ }
+ const results = await Promise.all(
+ [...byId.entries()].map(async ([id, stoppedAt]) => [id, await campaignHasPaymentsDue(db, id, stoppedAt)] as const)
+ )
+ return new Set(results.filter(([, due]) => due).map(([id]) => id))
+}
+
/** The organizer's pending request, if any (one per campaign). */
export function pendingSwap(requests: readonly AccountSwapRequest[]): AccountSwapRequest | null {
return requests.find((r) => r.status === "pending") ?? null
@@ -108,7 +159,14 @@ type SwapAccount = Pick<
>
export interface SwapForReview extends AccountSwapRequest {
- campaign: { id: string; slug: string; title: string; status: CampaignStatus; type: CampaignType } | null
+ campaign: {
+ id: string
+ slug: string
+ title: string
+ status: CampaignStatus
+ type: CampaignType
+ payments_stopped_at?: string | null
+ } | null
/** The requested account; its owner is the campaign's organizer (the RPCs require it). */
new_account:
| (SwapAccount & {
@@ -129,7 +187,7 @@ const ACCOUNT_FIELDS =
// so the organizer comes through the new account, whose owner it is. Two foreign
// keys point at account_bindings, so the old binding is named by its constraint.
export const REVIEW_COLUMNS = `${SWAP_COLUMNS},
- campaign:campaigns(id, slug, title, status, type),
+ campaign:campaigns(id, slug, title, status, type, payments_stopped_at),
new_account:receiving_accounts(${ACCOUNT_FIELDS},
organizer:organizers(legal_name, display_name, verification_status)),
old_binding:account_bindings!account_swap_requests_old_binding_id_fkey(id, bound_at, released_at,
@@ -184,10 +242,24 @@ export async function transactionCounts(db: Db, bindingIds: readonly string[]):
* checks give.decide_account_swap repeats under its locks; the database stays
* the authority.
*/
-export function approvalBlock(swap: SwapForReview, oldBindingTransactions: number): string | null {
+export function approvalBlock(
+ swap: SwapForReview,
+ oldBindingTransactions: number,
+ hasPaymentsDue = false
+): string | null {
const campaign = swap.campaign
- if (!campaign || campaign.type !== "give" || !SWAP_STATUSES.includes(campaign.status)) {
- return "Chiến dịch không còn ở trạng thái được đổi tài khoản (đang gây quỹ, tạm dừng, hoặc cần chỉnh sửa mà tài khoản đã có giao dịch)."
+ if (!campaign) {
+ return "Chiến dịch không còn ở trạng thái được đổi tài khoản (đang gây quỹ, tạm dừng, cần chỉnh sửa mà tài khoản đã có giao dịch, hoặc dự án có quà tặng đã đạt mục tiêu còn cam kết chờ thanh toán)."
+ }
+ if (campaign.status === "succeeded") {
+ if (campaign.type !== "back") {
+ return "Chiến dịch không còn ở trạng thái được đổi tài khoản (đang gây quỹ, tạm dừng, cần chỉnh sửa mà tài khoản đã có giao dịch, hoặc dự án có quà tặng đã đạt mục tiêu còn cam kết chờ thanh toán)."
+ }
+ if (!hasPaymentsDue) {
+ return "Dự án đã đạt mục tiêu nhưng không còn cam kết nào đang chờ thanh toán để đổi tài khoản."
+ }
+ } else if (!SWAP_STATUSES.includes(campaign.status)) {
+ return "Chiến dịch không còn ở trạng thái được đổi tài khoản (đang gây quỹ, tạm dừng, cần chỉnh sửa mà tài khoản đã có giao dịch, hoặc dự án có quà tặng đã đạt mục tiêu còn cam kết chờ thanh toán)."
}
if (!swap.old_binding || swap.old_binding.released_at !== null) {
return "Tài khoản đang gắn của chiến dịch đã thay đổi từ khi người tổ chức gửi yêu cầu."
diff --git a/apps/web/src/lib/campaign-account.test.ts b/apps/web/src/lib/campaign-account.test.ts
index 0fa2d466..f9919fb8 100644
--- a/apps/web/src/lib/campaign-account.test.ts
+++ b/apps/web/src/lib/campaign-account.test.ts
@@ -264,20 +264,47 @@ describe("loadEditorAccounts", () => {
expect(view.choices.map((c) => [c.account.id, c.blockedReason])).toEqual([["spare", null]])
})
- it("never reads swaps for a back campaign, and words its money-history block without a swap", async () => {
+ it("reads swaps for a sent-back back campaign and points its money-history block to the #55/#92 swap", async () => {
const calls: Call[] = []
const db = fakeDb((call) => {
if (call.target === "receiving_accounts")
return { data: [account("here", { verification_status: "disabled", bindings: bound(CAMPAIGN) })] }
if (call.target === "organizers") return { data: organizer }
if (call.target === "bank_transactions") return { data: [{ id: "t" }] }
+ if (call.target === "account_swap_requests") return { data: [{ id: "s-back", status: "pending" }] }
return undefined
}, calls)
const view = await loadEditorAccounts(db as unknown as Db, "owner", CAMPAIGN, "changes_requested", "back")
expect(view.boundHasTransactions).toBe(true)
- expect(view.swaps).toEqual([])
- expect(calls.map((c) => c.target)).not.toContain("account_swap_requests")
- expect(view.submitBlocked).toBe(submitUnusableAccount("Tài khoản chưa được xác minh.", true, false))
+ expect(view.swaps.map((s) => s.id)).toEqual(["s-back"])
+ expect(calls.map((c) => c.target)).toContain("account_swap_requests")
+ expect(view.submitBlocked).toBe(submitUnusableAccount("Tài khoản chưa được xác minh.", true, true))
+ })
+
+ it("checks payments due and loads swaps for a succeeded back campaign (DOS/Give#92)", async () => {
+ const calls: Call[] = []
+ const db = fakeDb((call) => {
+ if (call.target === "receiving_accounts") return { data: [account("here", { bindings: bound(CAMPAIGN) })] }
+ if (call.target === "organizers") return { data: organizer }
+ if (call.target === "contributions") return { data: [{ id: "pledge-1" }] }
+ if (call.target === "account_swap_requests") return { data: [{ id: "s-1", status: "pending" }] }
+ return undefined
+ }, calls)
+ const view = await loadEditorAccounts(
+ db as unknown as Db,
+ "owner",
+ CAMPAIGN,
+ "succeeded",
+ "back",
+ "2026-11-10T00:00:00Z"
+ )
+ expect(view.hasPaymentsDue).toBe(true)
+ expect(view.swaps.map((s) => s.id)).toEqual(["s-1"])
+ expect(calls.find((c) => c.target === "contributions")?.ops).toContainEqual([
+ "gt",
+ "payment_due_at",
+ "2026-11-10T00:00:00Z",
+ ])
})
})
@@ -334,7 +361,7 @@ describe("checkSubmitAccount", () => {
).toEqual(["binding_id", "b-1"])
})
- it("tells drafts and back campaigns with money history to contact Give instead of swapping (DOS/Give#77)", async () => {
+ it("tells drafts with money history to contact Give, and sent-back back campaigns to swap (DOS/Give#77, #92)", async () => {
const db = fakeDb((call) => {
if (call.target === "account_bindings") return { data: [{ id: "b-1", receiving_account_id: "a" }] }
if (call.target === "receiving_accounts") return { data: account("a", { verification_status: "disabled" }) }
@@ -345,9 +372,12 @@ describe("checkSubmitAccount", () => {
expect(await checkSubmitAccount(db as unknown as Db, CAMPAIGN, OWNER, "give", "draft")).toBe(
submitUnusableAccount("Tài khoản chưa được xác minh.", true, false)
)
- expect(await checkSubmitAccount(db as unknown as Db, CAMPAIGN, OWNER, "back", "changes_requested")).toBe(
+ expect(await checkSubmitAccount(db as unknown as Db, CAMPAIGN, OWNER, "back", "draft")).toBe(
submitUnusableAccount("Tài khoản chưa được xác minh.", true, false)
)
+ expect(await checkSubmitAccount(db as unknown as Db, CAMPAIGN, OWNER, "back", "changes_requested")).toBe(
+ submitUnusableAccount("Tài khoản chưa được xác minh.", true, true)
+ )
})
it("treats a binding to an account the organizer does not own as missing without checking transactions", async () => {
diff --git a/apps/web/src/lib/campaign-account.ts b/apps/web/src/lib/campaign-account.ts
index 54a50536..7356977d 100644
--- a/apps/web/src/lib/campaign-account.ts
+++ b/apps/web/src/lib/campaign-account.ts
@@ -1,5 +1,6 @@
import {
bindingHasTransactions,
+ campaignHasPaymentsDue,
canAskSwap,
listCampaignSwaps,
SWAP_STATUSES,
@@ -40,9 +41,9 @@ export const SUBMIT_NO_ACCOUNT =
* Refusal when the bound account can no longer receive money. An account that
* already recorded a bank transaction holds the campaign's money history and
* is never released early (GIVE_BINDING_NOT_RELEASABLE), so when `canSwap`
- * holds (`canAskSwap`: a sent-back give campaign, DOS/Give#55, #77) the
- * organizer asks finance to swap it instead; drafts and back campaigns have
- * no swap (`canSwap` false), so their organizer contacts Give.
+ * holds (`canAskSwap`: a sent-back give or back campaign, DOS/Give#55, #77,
+ * #92) the organizer asks finance to swap it instead; drafts have no swap
+ * (`canSwap` false), so their organizer contacts Give.
*/
export function submitUnusableAccount(reason: string, boundHasTransactions = false, canSwap = true): string {
if (boundHasTransactions && !canSwap) {
@@ -153,7 +154,9 @@ export interface EditorAccounts {
boundUnusable: string | null
/** Whether the bound account recorded a bank transaction (money history: never released early). */
boundHasTransactions: boolean
- /** The campaign's account swap requests, newest first (DOS/Give#55). */
+ /** Whether a succeeded back campaign still has pledges awaiting payment (DOS/Give#92). */
+ hasPaymentsDue: boolean
+ /** The campaign's account swap requests, newest first (DOS/Give#55, #92). */
swaps: AccountSwapRequest[]
choices: AccountChoice[]
/** Why the campaign cannot be sent for review because of its account, or null. */
@@ -176,13 +179,14 @@ export function openingBlock(
return accounts.boundUnusable !== null ? "unusable" : null
}
-/** Everything the editor shows about a campaign's receiving account (both types, DOS/Give#85). */
+/** Everything the editor shows about a campaign's receiving account (both types, DOS/Give#85, #92). */
export async function loadEditorAccounts(
db: Db,
organizerId: string,
campaignId: string,
status: CampaignStatus,
- type: CampaignType
+ type: CampaignType,
+ paymentsStoppedAt: string | null = null
): Promise {
const [accounts, organizer] = await Promise.all([listMyAccounts(db, organizerId), getOrganizer(db, organizerId)])
const bound = boundAccountOf(accounts, campaignId)
@@ -190,34 +194,38 @@ export async function loadEditorAccounts(
.map((a) => activeBinding(a)?.campaign_id)
.filter((id): id is string => Boolean(id) && id !== campaignId)
const binding = bound ? activeBinding(bound) : null
+ const maySwapStatus = SWAP_STATUSES.includes(status) || (type === "back" && status === "succeeded")
// Money history matters to an editable campaign (draft or changes_requested,
// where a transaction prevents early release and may allow a swap), and swaps
- // only where a swap can happen (give, DOS/Give#55, #77). A failed read of
- // either shows the section without them rather than hiding it; the database
- // refuses anything they would have prevented. Where a swap can happen, an
- // unknown money history counts as some so the editor offers the swap (which
- // the database turns into "release instead" if wrong) rather than a release
- // it refuses; where no swap exists, it leaves the release button visible.
- const [refs, boundHasTransactions, swaps] = await Promise.all([
+ // apply to both give and back campaigns (DOS/Give#55, #77, #92). A failed
+ // read of either shows the section without them rather than hiding it; the
+ // database refuses anything they would have prevented. Where a swap can
+ // happen, an unknown money history counts as some so the editor offers the
+ // swap (which the database turns into "release instead" if wrong) rather
+ // than a release it refuses; where no swap exists, it leaves the release
+ // button visible.
+ const [refs, boundHasTransactions, hasPaymentsDue, swaps] = await Promise.all([
campaignRefs(db, holders),
binding && isEditableStatus(status)
? bindingHasTransactions(db, binding.id).catch(() => canAskSwap(status, type, true))
: Promise.resolve(false),
- type === "give" && SWAP_STATUSES.includes(status)
- ? listCampaignSwaps(db, campaignId).catch(() => [])
- : Promise.resolve([]),
+ type === "back" && status === "succeeded"
+ ? campaignHasPaymentsDue(db, campaignId, paymentsStoppedAt).catch(() => false)
+ : Promise.resolve(false),
+ maySwapStatus ? listCampaignSwaps(db, campaignId).catch(() => []) : Promise.resolve([]),
])
return {
bound,
boundUnusable: bound ? accountUnusableReason(bound, organizer) : null,
boundHasTransactions,
+ hasPaymentsDue,
swaps,
choices: accountChoices(accounts, campaignId, organizer, refs),
submitBlocked: submitAccountProblem(
bound,
organizer,
boundHasTransactions,
- canAskSwap(status, type, boundHasTransactions)
+ canAskSwap(status, type, boundHasTransactions, hasPaymentsDue)
),
}
}
diff --git a/apps/web/src/lib/campaigns.test.ts b/apps/web/src/lib/campaigns.test.ts
index ad9ef66e..7351ca89 100644
--- a/apps/web/src/lib/campaigns.test.ts
+++ b/apps/web/src/lib/campaigns.test.ts
@@ -12,9 +12,11 @@ import {
fundingModelFor,
isEditableStatus,
isPublicStatus,
+ listCampaignsNeedingRecovery,
listOrganizersToVerify,
listPublicCampaigns,
listWaitingForAccount,
+ recoveryAdvice,
waitingAdvice,
normalizeSearch,
organizerCanCancel,
@@ -709,3 +711,182 @@ describe("waitingAdvice", () => {
)
})
})
+
+describe("listCampaignsNeedingRecovery (DOS/Give#77)", () => {
+ const A = "7700c000-0000-4000-8000-000000000001"
+ const B = "7700c000-0000-4000-8000-000000000002"
+ const GONE = "7700c000-0000-4000-8000-000000000003"
+
+ it("preserves database order, drops disappeared rows, and skips managed_campaigns when empty", async () => {
+ const emptyLog: Call[] = []
+ const emptyDb = fakeDb(() => ({ data: [] }), emptyLog)
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ expect(await listCampaignsNeedingRecovery(emptyDb as any)).toEqual([])
+ expect(emptyLog.map((c) => c.target)).toEqual(["rpc:campaigns_needing_recovery"])
+
+ const db = fakeDb((call) => {
+ if (call.target === "rpc:campaigns_needing_recovery") {
+ return {
+ data: [
+ {
+ campaign_id: B,
+ recovery_kind: "approved_past_end",
+ account_problem: null,
+ account_has_transactions: false,
+ },
+ {
+ campaign_id: GONE,
+ recovery_kind: "suspended_before_start",
+ account_problem: "no_account",
+ account_has_transactions: false,
+ },
+ {
+ campaign_id: A,
+ recovery_kind: "suspended_before_start",
+ account_problem: "account_not_verified",
+ account_has_transactions: true,
+ },
+ ],
+ }
+ }
+ if (call.target === "rpc:managed_campaigns") {
+ return {
+ data: [
+ { id: A, title: "A" },
+ { id: B, title: "B" },
+ ],
+ }
+ }
+ return undefined
+ })
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const items = await listCampaignsNeedingRecovery(db as any)
+ expect(items.map((r) => [r.id, r.recovery_kind, r.account_problem, r.account_has_transactions])).toEqual([
+ [B, "approved_past_end", null, false],
+ [A, "suspended_before_start", "account_not_verified", true],
+ ])
+ })
+
+ it("throws when the RPC or managed_campaigns lookup fails", async () => {
+ const rpcErr = fakeDb(() => ({ error: { code: "42501", message: "denied" } }))
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await expect(listCampaignsNeedingRecovery(rpcErr as any)).rejects.toMatchObject({ code: "42501" })
+
+ const readErr = fakeDb((call) =>
+ call.target === "rpc:campaigns_needing_recovery"
+ ? {
+ data: [
+ {
+ campaign_id: A,
+ recovery_kind: "approved_past_end",
+ account_problem: null,
+ account_has_transactions: false,
+ },
+ ],
+ }
+ : { error: { code: "57014", message: "timeout" } }
+ )
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ await expect(listCampaignsNeedingRecovery(readErr as any)).rejects.toMatchObject({ code: "57014" })
+ })
+})
+
+describe("recoveryAdvice (DOS/Give#77)", () => {
+ const advise = (
+ recovery_kind: "approved_past_end" | "suspended_before_start",
+ overrides: Partial<{
+ type: "give" | "back"
+ account_problem: string | null
+ account_has_transactions: boolean
+ verified: boolean
+ }> = {}
+ ) =>
+ recoveryAdvice({
+ recovery_kind,
+ type: overrides.type ?? "give",
+ account_problem: overrides.account_problem === undefined ? null : overrides.account_problem,
+ account_has_transactions: overrides.account_has_transactions ?? false,
+ organizer: { verification_status: overrides.verified === false ? "pending" : "verified" },
+ })
+
+ it("sends back approved_past_end campaigns to update dates", () => {
+ const res = advise("approved_past_end")
+ expect(res.note).toContain("quá ngày kết thúc")
+ expect(res.sendBackReason).toContain("sửa ngày kết thúc rồi gửi duyệt lại")
+ })
+
+ it("offers a free-text send-back form for suspended_before_start with a usable account", () => {
+ const res = advise("suspended_before_start", { account_problem: null })
+ expect(res.sendBackReason).toBe("")
+ expect(res.note).toContain("tài khoản nhận tiền vẫn dùng được")
+ })
+
+ it("guides account release/binding when suspended_before_start has no transactions", () => {
+ const disabled = advise("suspended_before_start", { account_problem: "account_not_verified" })
+ expect(disabled.note).toBeNull()
+ expect(disabled.sendBackReason).toContain("nhả tài khoản đang gắn")
+ expect(disabled.sendBackReason).toContain("hi@give.vn")
+
+ const noAccount = advise("suspended_before_start", { account_problem: "no_account" })
+ expect(noAccount.sendBackReason).toContain("gắn một tài khoản đã xác minh đứng tên bạn")
+
+ const foreign = advise("suspended_before_start", { account_problem: "account_not_owned" })
+ expect(foreign.note).toContain("bộ phận tài chính hoặc quản trị viên nhả tài khoản đó")
+ expect(foreign.sendBackReason).toContain("chờ đội ngũ Give nhả tài khoản không đứng tên bạn")
+
+ const unverified = advise("suspended_before_start", { account_problem: "name_mismatch", verified: false })
+ expect(unverified.note).toContain("Xác minh người tổ chức")
+ expect(unverified.sendBackReason).toContain("Tên chủ tài khoản nhận tiền đang gắn không còn trùng")
+ expect(unverified.sendBackReason).toContain("cần được xác minh lại")
+
+ const orgReset = advise("suspended_before_start", { account_problem: "organizer_not_verified", verified: false })
+ expect(orgReset.note).toContain("xác minh lại hồ sơ")
+ expect(orgReset.sendBackReason).toContain("cần được xác minh lại")
+ })
+
+ it("guides #55/#92 swap for both give and back campaigns with transactions", () => {
+ for (const type of ["give", "back"] as const) {
+ const withTx = advise("suspended_before_start", {
+ type,
+ account_problem: "account_not_verified",
+ account_has_transactions: true,
+ })
+ expect(withTx.note).toContain("yêu cầu đổi tài khoản")
+ expect(withTx.sendBackReason).toContain("để bộ phận tài chính duyệt")
+ }
+
+ // Foreign account with transactions cannot be swapped in editor or released early (give or back).
+ for (const type of ["give", "back"] as const) {
+ const foreignTx = advise("suspended_before_start", {
+ type,
+ account_problem: "account_not_owned",
+ account_has_transactions: true,
+ })
+ expect(foreignTx.sendBackReason).toBeNull()
+ expect(foreignTx.note).toContain("quản trị viên hệ thống")
+ }
+
+ // Campaign with transactions + unverified organizer must ask to re-verify organizer first.
+ for (const type of ["give", "back"] as const) {
+ const txUnverified = advise("suspended_before_start", {
+ type,
+ account_problem: "account_not_verified",
+ account_has_transactions: true,
+ verified: false,
+ })
+ expect(txUnverified.note).toContain("Xác minh người tổ chức")
+ expect(txUnverified.sendBackReason).toContain("cần được xác minh lại trước khi gửi yêu cầu đổi tài khoản")
+
+ // organizer_not_verified with transactions never suggests direct rebinding.
+ const orgResetTx = advise("suspended_before_start", {
+ type,
+ account_problem: "organizer_not_verified",
+ account_has_transactions: true,
+ verified: false,
+ })
+ expect(orgResetTx.note).not.toContain("gắn tài khoản mới")
+ expect(orgResetTx.note).toContain("yêu cầu đổi tài khoản")
+ expect(orgResetTx.sendBackReason).toContain("yêu cầu đổi tài khoản")
+ }
+ })
+})
diff --git a/apps/web/src/lib/campaigns.ts b/apps/web/src/lib/campaigns.ts
index 2207f2df..79905cc8 100644
--- a/apps/web/src/lib/campaigns.ts
+++ b/apps/web/src/lib/campaigns.ts
@@ -82,6 +82,7 @@ export interface Campaign {
submitted_at: string | null
approved_at: string | null
outcome_at: string | null
+ payments_stopped_at?: string | null
created_at: string
updated_at: string
}
@@ -765,6 +766,37 @@ export interface WaitingForAccount extends ReviewItem {
account_has_transactions: boolean
}
+export type RecoveryKind = "approved_past_end" | "suspended_before_start"
+
+export interface RecoveryCampaign extends ReviewItem {
+ recovery_kind: RecoveryKind
+ /** Why the bound receiving account is unusable, or null when usable. */
+ account_problem: string | null
+ /** The bound account already recorded a bank transaction, so the organizer cannot release it. */
+ account_has_transactions: boolean
+}
+
+/** Hydrates full review rows (with organizer) for a list of campaign ids. */
+async function loadReviewItemsByIds(db: Db, ids: readonly string[]): Promise