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/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 433b46ff..7351ca89 100644
--- a/apps/web/src/lib/campaigns.test.ts
+++ b/apps/web/src/lib/campaigns.test.ts
@@ -844,22 +844,16 @@ describe("recoveryAdvice (DOS/Give#77)", () => {
expect(orgReset.sendBackReason).toContain("cần được xác minh lại")
})
- it("guides #55 swap for give campaigns with transactions and blocks send-back for back campaigns with transactions", () => {
- const giveTx = advise("suspended_before_start", {
- type: "give",
- account_problem: "account_not_verified",
- account_has_transactions: true,
- })
- expect(giveTx.note).toContain("yêu cầu đổi tài khoản")
- expect(giveTx.sendBackReason).toContain("để bộ phận tài chính duyệt")
-
- const backTx = advise("suspended_before_start", {
- type: "back",
- account_problem: "account_not_verified",
- account_has_transactions: true,
- })
- expect(backTx.sendBackReason).toBeNull()
- expect(backTx.note).toContain("dự án có quà tặng chưa hỗ trợ đổi tài khoản")
+ 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) {
@@ -872,35 +866,27 @@ describe("recoveryAdvice (DOS/Give#77)", () => {
expect(foreignTx.note).toContain("quản trị viên hệ thống")
}
- // Give campaign with transactions + unverified organizer must ask to re-verify organizer first.
- const giveTxUnverified = advise("suspended_before_start", {
- type: "give",
- account_problem: "account_not_verified",
- account_has_transactions: true,
- verified: false,
- })
- expect(giveTxUnverified.note).toContain("Xác minh người tổ chức")
- expect(giveTxUnverified.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 giveOrgResetTx = advise("suspended_before_start", {
- type: "give",
- account_problem: "organizer_not_verified",
- account_has_transactions: true,
- verified: false,
- })
- expect(giveOrgResetTx.note).not.toContain("gắn tài khoản mới")
- expect(giveOrgResetTx.note).toContain("yêu cầu đổi tài khoản")
- expect(giveOrgResetTx.sendBackReason).toContain("yêu cầu đổi tài khoản")
+ // 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")
- const backOrgResetTx = advise("suspended_before_start", {
- type: "back",
- account_problem: "organizer_not_verified",
- account_has_transactions: true,
- verified: false,
- })
- expect(backOrgResetTx.sendBackReason).toBeNull()
- expect(backOrgResetTx.note).not.toContain("gắn tài khoản mới")
- expect(backOrgResetTx.note).toContain("Xác minh người tổ chức")
+ // 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 ad342685..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
}
@@ -868,9 +869,8 @@ export async function listCampaignsNeedingRecovery(db: Db): Promise changes_requested) to fix
* issues or replace an unusable account without cancelling. Replacing a
* receiving account stays owner-only (DOS/Give#264), and bindings with
- * recorded transactions still cannot be released early (give campaigns use
- * the #55 finance-approved swap; back campaigns with transactions have no
- * swap yet).
+ * recorded transactions still cannot be released early (both give and back
+ * campaigns use the #55/#92 finance-approved swap).
*/
export function recoveryAdvice(
row: Pick & {
@@ -898,16 +898,10 @@ export function recoveryAdvice(
if (problem === "organizer_not_verified") {
if (money) {
- if (row.type === "give") {
- return {
- note: "Hồ sơ người tổ chức chưa được xác minh và tài khoản đang gắn đã nhận giao dịch (lịch sử tiền của chiến dịch, không nhả sớm được): hãy xác minh lại hồ sơ ở mục Xác minh người tổ chức trước. Nếu tên pháp lý đã đổi, chủ chiến dịch cần gửi yêu cầu đổi tài khoản (bộ phận tài chính duyệt) sau khi hồ sơ được xác minh.",
- sendBackReason:
- "Chiến dịch đang tạm dừng trước ngày bắt đầu và hồ sơ người tổ chức của bạn cần được xác minh lại trước khi dùng tài khoản nhận tiền. Tài khoản đang gắn đã nhận giao dịch nên không nhả được; nếu cần đổi tài khoản sau khi hồ sơ được xác minh, hãy gửi yêu cầu đổi tài khoản trong mục Tài khoản nhận tiền để bộ phận tài chính duyệt, rồi gửi duyệt lại.",
- }
- }
return {
- note: "Hồ sơ người tổ chức chưa được xác minh và tài khoản đang gắn đã nhận giao dịch (lịch sử tiền của chiến dịch, không nhả sớm được; dự án có quà tặng chưa hỗ trợ đổi tài khoản): hãy xác minh lại hồ sơ với tên pháp lý hiện tại ở mục Xác minh người tổ chức để tài khoản dùng được trở lại; nếu tên pháp lý đã đổi, hãy liên hệ quản trị viên hệ thống hoặc hủy chiến dịch.",
- sendBackReason: null,
+ note: "Hồ sơ người tổ chức chưa được xác minh và tài khoản đang gắn đã nhận giao dịch (lịch sử tiền của chiến dịch, không nhả sớm được): hãy xác minh lại hồ sơ ở mục Xác minh người tổ chức trước. Nếu tên pháp lý đã đổi, chủ chiến dịch cần gửi yêu cầu đổi tài khoản (bộ phận tài chính duyệt) sau khi hồ sơ được xác minh.",
+ sendBackReason:
+ "Chiến dịch đang tạm dừng trước ngày bắt đầu và hồ sơ người tổ chức của bạn cần được xác minh lại trước khi dùng tài khoản nhận tiền. Tài khoản đang gắn đã nhận giao dịch nên không nhả được; nếu cần đổi tài khoản sau khi hồ sơ được xác minh, hãy gửi yêu cầu đổi tài khoản trong mục Tài khoản nhận tiền để bộ phận tài chính duyệt, rồi gửi duyệt lại.",
}
}
return {
@@ -924,27 +918,21 @@ export function recoveryAdvice(
sendBackReason: null,
}
}
- if (row.type === "give") {
- const notes = [
- "Tài khoản đang gắn đã nhận giao dịch (lịch sử tiền của chiến dịch, không nhả sớm được). Sau khi yêu cầu chỉnh sửa, chủ chiến dịch có thể gửi yêu cầu đổi tài khoản (bộ phận tài chính duyệt) trong mục Tài khoản nhận tiền.",
- ]
- const parts = [
- "Chiến dịch đang tạm dừng trước ngày bắt đầu và tài khoản nhận tiền đang gắn không còn dùng được. Vì tài khoản đã nhận giao dịch nên không nhả được, hãy gửi yêu cầu đổi tài khoản trong mục Tài khoản nhận tiền của chiến dịch để bộ phận tài chính duyệt, rồi gửi duyệt lại.",
- ]
- if (!verified) {
- notes.unshift(
- "Hồ sơ người tổ chức chưa được xác minh: hãy xác minh lại hồ sơ (với tên pháp lý hiện tại) ở mục Xác minh người tổ chức trước để chủ chiến dịch có thể gửi yêu cầu đổi tài khoản."
- )
- parts.push("Hồ sơ người tổ chức của bạn cần được xác minh lại trước khi gửi yêu cầu đổi tài khoản.")
- }
- return {
- note: notes.join(" "),
- sendBackReason: parts.join(" "),
- }
+ const notes = [
+ "Tài khoản đang gắn đã nhận giao dịch (lịch sử tiền của chiến dịch, không nhả sớm được). Sau khi yêu cầu chỉnh sửa, chủ chiến dịch có thể gửi yêu cầu đổi tài khoản (bộ phận tài chính duyệt) trong mục Tài khoản nhận tiền.",
+ ]
+ const parts = [
+ "Chiến dịch đang tạm dừng trước ngày bắt đầu và tài khoản nhận tiền đang gắn không còn dùng được. Vì tài khoản đã nhận giao dịch nên không nhả được, hãy gửi yêu cầu đổi tài khoản trong mục Tài khoản nhận tiền của chiến dịch để bộ phận tài chính duyệt, rồi gửi duyệt lại.",
+ ]
+ if (!verified) {
+ notes.unshift(
+ "Hồ sơ người tổ chức chưa được xác minh: hãy xác minh lại hồ sơ (với tên pháp lý hiện tại) ở mục Xác minh người tổ chức trước để chủ chiến dịch có thể gửi yêu cầu đổi tài khoản."
+ )
+ parts.push("Hồ sơ người tổ chức của bạn cần được xác minh lại trước khi gửi yêu cầu đổi tài khoản.")
}
return {
- note: "Tài khoản đang gắn đã nhận giao dịch (lịch sử tiền của chiến dịch, không nhả sớm được) và dự án có quà tặng chưa hỗ trợ đổi tài khoản. Hãy liên hệ bộ phận tài chính hoặc quản trị viên hệ thống; nếu không xử lý được, hãy hủy chiến dịch.",
- sendBackReason: null,
+ note: notes.join(" "),
+ sendBackReason: parts.join(" "),
}
}
diff --git a/apps/web/src/lib/email-outbox.test.ts b/apps/web/src/lib/email-outbox.test.ts
index d763d851..9006f565 100644
--- a/apps/web/src/lib/email-outbox.test.ts
+++ b/apps/web/src/lib/email-outbox.test.ts
@@ -24,6 +24,7 @@ describe("outbox maximum age", () => {
expect(outboxMaxAgeDays("plan_followup")).toBe(2)
expect(outboxMaxAgeDays("plan_ended")).toBe(14)
expect(outboxMaxAgeDays("plan_account_swapped")).toBe(14)
+ expect(outboxMaxAgeDays("pledge_account_swapped")).toBe(14)
})
it("labels every email kind the sender knows", () => {
diff --git a/apps/web/src/lib/email-outbox.ts b/apps/web/src/lib/email-outbox.ts
index 2c973a5b..accf4ec1 100644
--- a/apps/web/src/lib/email-outbox.ts
+++ b/apps/web/src/lib/email-outbox.ts
@@ -21,6 +21,7 @@ export const OUTBOX_KIND_LABELS: Record = {
plan_followup: "Nhắc lại mã ủng hộ hằng tháng",
plan_ended: "Kế hoạch hằng tháng đã dừng",
plan_account_swapped: "Thay đổi tài khoản nhận của kế hoạch hằng tháng",
+ pledge_account_swapped: "Thay đổi tài khoản nhận của cam kết thanh toán",
}
export const OUTBOX_STATUS_LABELS: Record = {
@@ -60,7 +61,8 @@ export function outboxMaxAgeDays(kind: string): number {
kind === "pledge_payment_due" ||
kind === "campaign_ended" ||
kind === "plan_ended" ||
- kind === "plan_account_swapped"
+ kind === "plan_account_swapped" ||
+ kind === "pledge_account_swapped"
)
return 14
return 7
diff --git a/apps/web/src/lib/errors.ts b/apps/web/src/lib/errors.ts
index 1c1a109b..0d69e397 100644
--- a/apps/web/src/lib/errors.ts
+++ b/apps/web/src/lib/errors.ts
@@ -53,7 +53,7 @@ const GIVE_MESSAGES: Record = {
GIVE_ACCOUNT_ALREADY_BOUND:
"Tài khoản này đang gắn với một chiến dịch khác. Hãy nhả tài khoản khỏi chiến dịch đó trước: bản nháp, hay chiến dịch được yêu cầu chỉnh sửa mà tài khoản chưa nhận giao dịch nào, nhả được ngay; các chiến dịch khác đã gửi duyệt chỉ nhả được khi đã xong hẳn phần tiền.",
GIVE_BINDING_NOT_FOUND: "Tài khoản này hiện không gắn với chiến dịch nào.",
- GIVE_BINDING_NOT_RELEASABLE: `Chưa nhả được tài khoản: chiến dịch phải là bản nháp, được yêu cầu chỉnh sửa, hoặc đã hủy, mà tài khoản chưa nhận giao dịch nào; hoặc đã kết thúc và xong hẳn phần tiền (chiến dịch từ thiện cần kết thúc ít nhất 30 ngày). Giao dịch đã vào tài khoản là lịch sử tiền của chiến dịch nên tài khoản không nhả sớm được. Nếu tài khoản không dùng được nữa khi chiến dịch từ thiện đang gây quỹ, tạm dừng hoặc cần chỉnh sửa, hãy gửi yêu cầu đổi tài khoản ở mục Tài khoản nhận tiền của chiến dịch; với dự án có quà tặng, hãy liên hệ đội ngũ Give ${VIA_CONTACT_EMAIL}.`,
+ GIVE_BINDING_NOT_RELEASABLE: `Chưa nhả được tài khoản: chiến dịch phải là bản nháp, được yêu cầu chỉnh sửa, hoặc đã hủy, mà tài khoản chưa nhận giao dịch nào; hoặc đã kết thúc và xong hẳn phần tiền (chiến dịch từ thiện cần kết thúc ít nhất 30 ngày). Giao dịch đã vào tài khoản là lịch sử tiền của chiến dịch nên tài khoản không nhả sớm được. Nếu tài khoản không dùng được nữa khi chiến dịch đang gây quỹ, tạm dừng, cần chỉnh sửa, hoặc dự án có quà tặng đã đạt mục tiêu còn cam kết chờ thanh toán, hãy gửi yêu cầu đổi tài khoản ở mục Tài khoản nhận tiền của chiến dịch; trong các trường hợp khác, hãy liên hệ đội ngũ Give ${VIA_CONTACT_EMAIL}.`,
GIVE_BINDING_HAS_OPEN_TRANSACTIONS:
"Chưa nhả được tài khoản: còn giao dịch của chiến dịch chưa được đối chiếu hoặc chưa được giải trình.",
GIVE_CAMPAIGN_ALREADY_BOUND: "Chiến dịch này đã có tài khoản nhận khác.",
@@ -96,9 +96,9 @@ const GIVE_MESSAGES: Record = {
GIVE_EVIDENCE_PATH_INVALID:
"Ảnh chứng từ không nằm đúng thư mục của khoản chi này, hoặc đã được lưu trước đó. Hãy tải lại ảnh.",
GIVE_EVIDENCE_LIMIT: "Mỗi khoản chi có tối đa 20 ảnh chứng từ (không tính ảnh đã bị ẩn).",
- // Account swaps of give campaigns that may hold money (DOS/Give#55).
+ // Account swaps of campaigns that may hold money (DOS/Give#55, #92).
GIVE_SWAP_NOT_ALLOWED:
- "Chỉ đổi được tài khoản nhận 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 cũ đã nhận giao dịch.",
+ "Chỉ đổi được tài khoản nhận khi chiến dịch đang gây quỹ, đang tạm dừng, cần chỉnh sửa mà tài khoản cũ đã nhận giao dịch, hoặc dự án có quà tặng đã đạt mục tiêu nhưng vẫn còn cam kết chờ thanh toán.",
GIVE_SWAP_USE_RELEASE:
"Tài khoản đang gắn chưa nhận giao dịch nào: bạn nhả tài khoản đó rồi gắn tài khoản khác được ngay, không cần chờ tài chính duyệt.",
GIVE_SWAP_SAME_ACCOUNT: "Hãy chọn một tài khoản khác với tài khoản đang gắn.",
@@ -132,7 +132,7 @@ const GIVE_MESSAGES: Record = {
"Khoản tiền vào này đã được ghi nhận là tiền bị trả lại, với khoản chuyển đi gốc, lý do hoặc bằng chứng khác. Ghi nhận đã lưu thì không sửa được.",
GIVE_ORIGINAL_ALREADY_RETURNED: "Khoản chuyển đi gốc này đã được ghi nhận là bị trả lại bởi một khoản tiền vào khác.",
GIVE_ACCOUNT_HISTORY_OPEN:
- "Tài khoản này đã được đổi ra khỏi một chiến dịch mà phần tiền chưa xong (chiến dịch chưa kết thúc đủ 30 ngày, hoặc còn giao dịch chưa đối chiếu, chưa giải trình, hoặc còn dòng sao kê chưa ghi nhận), nên chưa dùng cho chiến dịch khác được.",
+ "Tài khoản này đã được đổi ra khỏi một chiến dịch mà phần tiền chưa xong (chiến dịch từ thiện chưa kết thúc đủ 30 ngày, hoặc còn cam kết chờ thanh toán, hoàn tiền, giao dịch chưa đối chiếu, chưa giải trình, hay dòng sao kê chưa ghi nhận), nên chưa dùng cho chiến dịch khác được.",
// Transfers between a campaign's own accounts after a swap (DOS/Give#84);
// the finance action words them for its context (OWN_TRANSFER_MESSAGES).
GIVE_TRANSACTION_OWN_TRANSFER:
@@ -253,7 +253,7 @@ export function dbErrorMessage(error: DbErrorLike | null | undefined, overrides:
* organizer's own name.
*/
export const SUBMIT_MESSAGES: Record = {
- GIVE_CAMPAIGN_NO_RECEIVING_ACCOUNT: `Chưa gửi duyệt được: chiến dịch cần một tài khoản nhận tiền đã xác minh, đứng tên bạn, gắn vào chiến dịch. Vào mục Tài khoản nhận tiền để khai báo, xác minh và gắn tài khoản; nếu tài khoản đang gắn đã bị khóa hoặc không còn dùng được, hãy nhả nó rồi gắn tài khoản khác (tài khoản đã nhận giao dịch thì không nhả được: với chiến dịch từ thiện, gửi yêu cầu đổi tài khoản trong cùng mục; với dự án có quà tặng, liên hệ đội ngũ Give ${VIA_CONTACT_EMAIL}). Nếu bạn vừa đổi tên pháp lý, hồ sơ người tổ chức cần được xác minh lại, và tài khoản nhận tiền phải đứng tên pháp lý mới.`,
+ GIVE_CAMPAIGN_NO_RECEIVING_ACCOUNT: `Chưa gửi duyệt được: chiến dịch cần một tài khoản nhận tiền đã xác minh, đứng tên bạn, gắn vào chiến dịch. Vào mục Tài khoản nhận tiền để khai báo, xác minh và gắn tài khoản; nếu tài khoản đang gắn đã bị khóa hoặc không còn dùng được, hãy nhả nó rồi gắn tài khoản khác (tài khoản đã nhận giao dịch thì không nhả được: khi chiến dịch đang ở trạng thái cần chỉnh sửa, hãy gửi yêu cầu đổi tài khoản trong cùng mục; nếu là bản nháp, hãy liên hệ đội ngũ Give ${VIA_CONTACT_EMAIL}). Nếu bạn vừa đổi tên pháp lý, hồ sơ người tổ chức cần được xác minh lại, và tài khoản nhận tiền phải đứng tên pháp lý mới.`,
}
/** The same code worded for a moderator approving or opening a campaign. */
diff --git a/apps/web/src/lib/notices.test.ts b/apps/web/src/lib/notices.test.ts
index 9209c9be..a1cffa8b 100644
--- a/apps/web/src/lib/notices.test.ts
+++ b/apps/web/src/lib/notices.test.ts
@@ -82,6 +82,7 @@ describe("stoppedNoticeCampaigns (DOS/Give#93)", () => {
const stopped = await stoppedNoticeCampaigns(asDb(db), [
notice({ kind: "payment_due", campaign_id: CAMPAIGN }),
notice({ kind: "payment_reminder", campaign_id: CAMPAIGN }),
+ notice({ kind: "payment_account_changed", campaign_id: CAMPAIGN }),
notice({ kind: "payment_requests_resumed", campaign_id: OTHER, payload: { reference_code: "GVAB12CD" } }),
])
expect([...stopped]).toEqual([CAMPAIGN])
@@ -545,3 +546,82 @@ describe("planTemplateAccount", () => {
expect(planTemplateAccount({ account_last4: "12345" })).toBeNull()
})
})
+
+describe("payment_account_changed notice (DOS/Give#92)", () => {
+ const payload = {
+ campaign_slug: "den-ngu-go",
+ campaign_title: "Đèn ngủ gỗ",
+ reference_code: "GVAB23CD",
+ intended_amount: 500_000,
+ received_amount: 150_000,
+ refunded_amount: 50_000,
+ payment_due_at: "2026-11-29T03:00:00Z",
+ changed_date: "2026-11-22",
+ new_channel: "statement_import",
+ new_bank_bin: "970422",
+ new_account_name: "NGUYEN THI DAO",
+ new_account_last4: "0002",
+ new_account_masked: "****0002",
+ old_bank_bin: "970436",
+ old_account_last4: "0001",
+ old_account_masked: "****0001",
+ public_note: "Ngân hàng đóng tài khoản cũ.",
+ }
+
+ it("shows the masked new account, old-account warning, live net due, deadline, public note and payment link", () => {
+ const view = describeNotice(notice({ kind: "payment_account_changed", payload }))
+ expect(view.title).toBe("Tài khoản nhận thanh toán đã thay đổi")
+ expect(view.body).toContain("dự án “Đèn ngủ gỗ”")
+ expect(view.body).toContain("ngày 22/11/2026")
+ expect(view.body).toContain("chủ tài khoản NGUYEN THI DAO")
+ expect(view.body).toContain("ngân hàng MBBank")
+ expect(view.body).toContain("số tài khoản •••• 0002")
+ expect(view.body).toContain("tài khoản cũ Vietcombank •••• 0001")
+ expect(view.body).toContain(formatVnd(400_000))
+ expect(view.body).toContain("29/11/2026")
+ expect(view.body).toContain("GVAB23CD")
+ expect(view.body).toContain("Ngân hàng đóng tài khoản cũ.")
+ expect(view).toMatchObject({ href: "/me/pledges/GVAB23CD", linkLabel: "Thanh toán ngay" })
+ })
+
+ it("hides payment CTA and warns neutrally while payment requests are stopped (DOS/Give#93)", () => {
+ const view = describeNotice(notice({ kind: "payment_account_changed", payload }), { paymentRequestsStopped: true })
+ expect(view.title).toBe("Yêu cầu thanh toán đang tạm dừng")
+ expect(view.body).toContain("đừng chuyển tiền")
+ expect(view.body).not.toContain("Hãy thanh toán")
+ expect(view).toMatchObject({ href: "/me/pledges/GVAB23CD", linkLabel: "Xem cam kết" })
+ })
+
+ it("never leaks raw multi-digit account numbers even from malformed payloads and supports crypto", () => {
+ const leaked = describeNotice(
+ notice({
+ kind: "payment_account_changed",
+ payload: {
+ ...payload,
+ new_account_last4: "920002220002",
+ new_account_masked: "920002220002",
+ old_account_last4: "920001110001",
+ old_account_masked: "920001110001",
+ },
+ })
+ )
+ expect(leaked.body).not.toContain("920002220002")
+ expect(leaked.body).not.toContain("920001110001")
+ expect(leaked.body).toContain("tài khoản cũ của dự án")
+
+ const crypto = describeNotice(
+ notice({
+ kind: "payment_account_changed",
+ payload: {
+ ...payload,
+ new_channel: "crypto",
+ new_bank_bin: null,
+ new_account_name: null,
+ new_chain: "polygon",
+ new_account_last4: "a9F2",
+ },
+ })
+ )
+ expect(crypto.body).toContain("Ví nhận mới trên mạng polygon: •••• a9F2.")
+ })
+})
diff --git a/apps/web/src/lib/notices.ts b/apps/web/src/lib/notices.ts
index 4443c855..423cb76a 100644
--- a/apps/web/src/lib/notices.ts
+++ b/apps/web/src/lib/notices.ts
@@ -121,8 +121,65 @@ export function planEndedParagraphs(payload: Notice["payload"]): string[] {
]
}
+const LAST4_PATTERN = /^[0-9A-Za-z]{1,4}$/
+const MASKED_LAST4_PATTERN = /^\*{4}([0-9A-Za-z]{1,4})$/
+const CHAIN_PATTERN = /^[a-z0-9-]{2,32}$/
+const ISO_DATE_PATTERN = /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/
+
+/**
+ * Formats strictly the last 1-4 characters as "•••• XXXX". Rejects longer
+ * values so a malformed payload can never leak a raw account number or wallet
+ * address into a notice or email.
+ */
+export function maskedAccountLast4(last4: string | null, masked: string | null): string | null {
+ const cleanLast4 = last4?.trim() ?? null
+ if (cleanLast4 && LAST4_PATTERN.test(cleanLast4)) return `•••• ${cleanLast4}`
+ const cleanMasked = masked?.trim() ?? null
+ const match = cleanMasked ? MASKED_LAST4_PATTERN.exec(cleanMasked) : null
+ return match ? `•••• ${match[1]}` : null
+}
+
+/** Date of an approved account swap as DD/MM/YYYY, from changed_date or changed_at. */
+export function swapDateLabel(payload: Notice["payload"]): string | null {
+ const changedDate = text(payload, "changed_date")?.trim() ?? null
+ const match = changedDate ? ISO_DATE_PATTERN.exec(changedDate) : null
+ if (match) return `${match[3]}/${match[2]}/${match[1]}`
+ const changedAt = text(payload, "changed_at")?.trim() ?? null
+ if (changedAt && !Number.isNaN(Date.parse(changedAt))) return formatDate(changedAt)
+ return null
+}
+
+/** One sentence describing the new receiving account after a swap, strictly masked. */
+export function swappedNewAccountLine(payload: Notice["payload"], fallback: string): string {
+ const channel = text(payload, "new_channel")?.trim() ?? null
+ const newMasked = maskedAccountLast4(text(payload, "new_account_last4"), text(payload, "new_account_masked"))
+ if (channel === "crypto") {
+ const rawChain = text(payload, "new_chain")?.trim() ?? null
+ const chain = rawChain && CHAIN_PATTERN.test(rawChain) ? rawChain : null
+ if (chain && newMasked) return `Ví nhận mới trên mạng ${chain}: ${newMasked}.`
+ if (newMasked) return `Ví nhận mới: ${newMasked}.`
+ return fallback
+ }
+ const holder = text(payload, "new_account_name")?.trim() ?? null
+ const bank = bankByBin(text(payload, "new_bank_bin")?.trim() ?? null)?.shortName ?? null
+ const parts: string[] = []
+ if (holder) parts.push(`chủ tài khoản ${holder}`)
+ if (bank) parts.push(`ngân hàng ${bank}`)
+ if (newMasked) parts.push(`số tài khoản ${newMasked}`)
+ return parts.length > 0 ? `Tài khoản nhận mới: ${parts.join(", ")}.` : fallback
+}
+
+/** "tài khoản cũ Vietcombank •••• 1234", or a neutral fallback when unmasked/missing. */
+export function swappedOldAccountTarget(payload: Notice["payload"], noun = "chiến dịch"): string {
+ const oldBank = bankByBin(text(payload, "old_bank_bin")?.trim() ?? null)?.shortName ?? null
+ const oldMasked = maskedAccountLast4(text(payload, "old_account_last4"), text(payload, "old_account_masked"))
+ if (!oldMasked) return `tài khoản cũ của ${noun}`
+ return oldBank ? `tài khoản cũ ${oldBank} ${oldMasked}` : `tài khoản cũ ${oldMasked}`
+}
+
function asksForPayment(notice: Pick): boolean {
- if (notice.kind === "payment_due" || notice.kind === "payment_reminder") return true
+ if (notice.kind === "payment_due" || notice.kind === "payment_reminder" || notice.kind === "payment_account_changed")
+ return true
return notice.kind === "payment_requests_resumed" && text(notice.payload, "reference_code") !== null
}
@@ -179,6 +236,47 @@ export function describeNotice(notice: Notice, options?: NoticeRenderOptions): N
...pledgeLink(p, "Thanh toán ngay"),
}
}
+ case "payment_account_changed": {
+ // Backer with a pledge awaiting payment whose campaign swapped receiving account (DOS/Give#92).
+ if (options?.paymentRequestsStopped) {
+ return {
+ title: "Yêu cầu thanh toán đang tạm dừng",
+ body: `Give đang tạm dừng yêu cầu thanh toán của ${campaignName(p, "dự án")}. Thông báo đổi tài khoản nhận này được gửi trước khi tạm dừng; đừng chuyển tiền cho cam kết của bạn trong lúc tạm dừng.`,
+ ...pledgeLink(p, "Xem cam kết"),
+ }
+ }
+ const intended = count(p, "intended_amount")
+ const received = count(p, "received_amount") ?? 0
+ const refunded = count(p, "refunded_amount") ?? 0
+ const due =
+ count(p, "amount_due") ?? (intended !== null ? Math.max(0, intended - Math.max(0, received - refunded)) : null)
+ const rawDueAt = text(p, "payment_due_at")?.trim() ?? null
+ const dueAt = rawDueAt && !Number.isNaN(Date.parse(rawDueAt)) ? formatDateTime(rawDueAt) : null
+ const rawCode = text(p, "reference_code")?.trim() ?? null
+ const code = rawCode && /^GV[0-9A-Z]{6,7}$/.test(rawCode) ? rawCode : null
+ const date = swapDateLabel(p)
+ const newAccount = swappedNewAccountLine(p, "Xem thông tin tài khoản nhận mới và mã VietQR trên trang cam kết.")
+ const oldTarget = swappedOldAccountTarget(p, "dự án")
+ const publicNote = text(p, "public_note")?.trim() ?? null
+
+ let body = `Tài khoản nhận tiền của ${campaignName(p, "dự án")} đã được Give duyệt đổi`
+ body += date ? ` ngày ${date}.` : "."
+ body += ` ${newAccount}`
+ body += " Hãy thanh toán"
+ if (due) body += ` ${formatVnd(due)}`
+ body += " cho cam kết của bạn"
+ if (dueAt) body += ` trước ${dueAt}`
+ body += " bằng tài khoản mới"
+ body += code ? ` (giữ nguyên mã chuyển khoản ${code}).` : "."
+ body += ` Đừng chuyển tiền vào ${oldTarget}: tiền chuyển vào tài khoản cũ sau khi đổi không được ghi nhận cho cam kết của bạn.`
+ if (publicNote) body += ` Ghi chú công khai: ${publicNote}`
+
+ return {
+ title: "Tài khoản nhận thanh toán đã thay đổi",
+ body,
+ ...pledgeLink(p, "Thanh toán ngay"),
+ }
+ }
case "pledge_cancelled": {
const reason = text(p, "reason")
const why =
diff --git a/apps/web/src/server/email/outbox.test.ts b/apps/web/src/server/email/outbox.test.ts
index fffdefb7..62194693 100644
--- a/apps/web/src/server/email/outbox.test.ts
+++ b/apps/web/src/server/email/outbox.test.ts
@@ -213,6 +213,44 @@ describe("sendDueEmails", () => {
expect(sent[0].text).toContain(`https://give.vn/email/unsubscribe?t=${UNSUB}`)
})
+ it("sends transactional pledge_account_swapped without stop or unsubscribe headers (DOS/Give#92)", async () => {
+ claims = [
+ [
+ row(27, {
+ kind: "pledge_account_swapped",
+ category: "transactional",
+ unsubscribe_token: null,
+ stop_token: null,
+ reference_code: "GV92ABC23",
+ payload: {
+ campaign_slug: "den-ngu-go",
+ campaign_title: "Đèn ngủ gỗ",
+ reference_code: "GV92ABC23",
+ intended_amount: 500_000,
+ received_amount: 0,
+ refunded_amount: 0,
+ payment_due_at: "2026-11-29T03:00:00Z",
+ changed_date: "2026-11-22",
+ new_channel: "statement_import",
+ new_bank_bin: "970422",
+ new_account_name: "NGUYEN THI DAO",
+ new_account_last4: "0002",
+ new_account_masked: "****0002",
+ old_bank_bin: "970436",
+ old_account_last4: "0001",
+ old_account_masked: "****0001",
+ },
+ }),
+ ],
+ ]
+ await sendDueEmails(fakeDb(handler, calls) as never, transport, OPTIONS)
+ expect(sent).toHaveLength(1)
+ expect(sent[0].headers["List-Unsubscribe"]).toBeUndefined()
+ expect(sent[0].headers["List-Unsubscribe-Post"]).toBeUndefined()
+ expect(sent[0].text).toContain("https://give.vn/me/pledges/GV92ABC23")
+ expect(sent[0].text).toContain("•••• 0002")
+ })
+
it("marks plan_account_swapped dead when stop_token or unsubscribe_token is missing", async () => {
claims = [
[
diff --git a/apps/web/src/server/email/templates.test.ts b/apps/web/src/server/email/templates.test.ts
index 65fcf647..8642fe24 100644
--- a/apps/web/src/server/email/templates.test.ts
+++ b/apps/web/src/server/email/templates.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest"
+import { formatVnd } from "@/lib/format"
import { NEW_CODE_EVERY_MONTH } from "@/lib/plans"
import { EmailRenderError, escapeHtml, renderEmail, type OutboxEmail } from "./templates"
@@ -397,6 +398,101 @@ describe("renderEmail: plan_account_swapped (DOS/Give#291)", () => {
})
})
+describe("pledge_account_swapped email (DOS/Give#92)", () => {
+ const pledgeSwap = (payload: Record = {}, overrides: Partial = {}) =>
+ email({
+ kind: "pledge_account_swapped",
+ category: "transactional",
+ unsubscribe_token: null,
+ stop_token: null,
+ reference_code: "GV92ABC23",
+ payload: {
+ campaign_slug: "den-ngu-go",
+ campaign_title: "Đèn ngủ gỗ",
+ reference_code: "GV92ABC23",
+ intended_amount: 500_000,
+ received_amount: 150_000,
+ refunded_amount: 50_000,
+ payment_due_at: "2026-11-29T03:00:00Z",
+ changed_date: "2026-11-22",
+ new_channel: "statement_import",
+ new_bank_bin: "970422",
+ new_account_name: "NGUYEN THI DAO",
+ new_account_last4: "0002",
+ new_account_masked: "****0002",
+ old_bank_bin: "970436",
+ old_account_last4: "0001",
+ old_account_masked: "****0001",
+ public_note: "Ngân hàng đã đóng tài khoản cũ.",
+ ...payload,
+ },
+ ...overrides,
+ })
+
+ it("renders transactional payment-account change email with masked details, net due, deadline and pledge link", () => {
+ const r = renderEmail(pledgeSwap(), ORIGIN)
+ expect(r.subject).toBe("Tài khoản nhận thanh toán của dự án “Đèn ngủ gỗ” đã thay đổi")
+ expect(r.unsubscribeUrl).toBeNull()
+ expect(r.oneClickUnsubscribeUrl).toBeNull()
+ expect(r.text).toContain("Ngày 22/11/2026")
+ expect(r.text).toContain("chủ tài khoản NGUYEN THI DAO")
+ expect(r.text).toContain("ngân hàng MBBank")
+ expect(r.text).toContain("số tài khoản •••• 0002")
+ expect(r.text).toContain("Ghi chú công khai: Ngân hàng đã đóng tài khoản cũ.")
+ expect(r.text).toContain(formatVnd(400_000))
+ expect(r.text).toContain("29/11/2026")
+ expect(r.text).toContain("GV92ABC23")
+ expect(r.text).toContain("Đừng chuyển tiền vào tài khoản cũ Vietcombank •••• 0001")
+ expect(r.text).toContain(`${ORIGIN}/me/pledges/GV92ABC23`)
+ expect(r.text).not.toContain("/email/unsubscribe")
+ expect(r.text).not.toContain("/plans/stop")
+ })
+
+ it("falls back to /me/contributions when reference_code is missing or invalid and supports crypto", () => {
+ const r = renderEmail(
+ pledgeSwap(
+ {
+ reference_code: "../evil",
+ new_channel: "crypto",
+ new_bank_bin: null,
+ new_account_name: null,
+ new_chain: "polygon",
+ new_account_last4: "a9F2",
+ public_note: null,
+ },
+ { reference_code: null }
+ ),
+ ORIGIN
+ )
+ expect(r.text).toContain("Ví nhận mới trên mạng polygon: •••• a9F2.")
+ expect(r.text).toContain(`${ORIGIN}/me/contributions`)
+ expect(r.text).not.toContain("../evil")
+ })
+
+ it("never leaks raw multi-digit account numbers, escapes HTML, and strips CR/LF from subject", () => {
+ const r = renderEmail(
+ pledgeSwap({
+ campaign_title: "Đèn\r\nBcc: evil@example.com",
+ new_account_name: 'DAO ',
+ public_note: '
',
+ new_account_last4: "920002220002",
+ new_account_masked: "920002220002",
+ old_account_last4: "920001110001",
+ old_account_masked: "920001110001",
+ }),
+ ORIGIN
+ )
+ expect(r.subject).not.toMatch(/[\r\n]/)
+ expect(r.text).not.toContain("920002220002")
+ expect(r.text).not.toContain("920001110001")
+ expect(r.html).not.toContain("920002220002")
+ expect(r.html).not.toContain("