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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions apps/web/src/lib/email-outbox.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,14 @@ describe("outbox maximum age", () => {
expect(outboxMaxAgeDays("plan_reminder")).toBe(3)
expect(outboxMaxAgeDays("plan_followup")).toBe(2)
expect(outboxMaxAgeDays("plan_ended")).toBe(14)
expect(outboxMaxAgeDays("plan_account_swapped")).toBe(14)
})

it("labels every email kind the sender knows", () => {
for (const kind of EMAIL_KINDS) expect(OUTBOX_KIND_LABELS[kind], kind).toBeTruthy()
expect(OUTBOX_SKIP_LABELS.not_payable).toBeTruthy()
expect(OUTBOX_SKIP_LABELS.plan_not_active).toBeTruthy()
expect(OUTBOX_SKIP_LABELS.account_superseded).toBeTruthy()
})

it("counts from the later of queueing and the last deferral", () => {
Expand Down
11 changes: 10 additions & 1 deletion apps/web/src/lib/email-outbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export const OUTBOX_KIND_LABELS: Record<string, string> = {
plan_reminder: "Mã ủng hộ hằng tháng",
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",
}

export const OUTBOX_STATUS_LABELS: Record<string, string> = {
Expand All @@ -39,6 +40,8 @@ export const OUTBOX_SKIP_LABELS: Record<string, string> = {
not_due: "cam kết không còn đến hạn thanh toán",
not_payable:
"khoản ủng hộ hằng tháng không còn chuyển được (kế hoạch đã dừng, hết tháng hoặc chiến dịch không còn nhận)",
plan_not_active: "kế hoạch ủng hộ hằng tháng đã dừng",
account_superseded: "tài khoản nhận đã được thay đổi một lần nữa trước khi gửi",
}

/**
Expand All @@ -53,7 +56,13 @@ export const THROTTLE_HOLD_PREFIX = "THROTTLE:"
export function outboxMaxAgeDays(kind: string): number {
if (kind === "pledge_payment_reminder" || kind === "plan_followup") return 2
if (kind === "plan_reminder") return 3
if (kind === "pledge_payment_due" || kind === "campaign_ended" || kind === "plan_ended") return 14
if (
kind === "pledge_payment_due" ||
kind === "campaign_ended" ||
kind === "plan_ended" ||
kind === "plan_account_swapped"
)
return 14
return 7
}

Expand Down
63 changes: 63 additions & 0 deletions apps/web/src/server/email/outbox.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,69 @@ describe("sendDueEmails", () => {
expect(sent).toHaveLength(1)
expect(sent[0].headers["List-Unsubscribe"]).toBeUndefined()
})

it("signs stop_token and includes unsubscribe link for plan_account_swapped (DOS/Give#291)", async () => {
claims = [
[
row(24, {
kind: "plan_account_swapped",
category: "notification",
unsubscribe_token: UNSUB,
stop_token: STOP,
payload: {
campaign_slug: "nuoc-sach",
campaign_title: "Nước sạch",
changed_date: "2026-11-22",
new_channel: "statement_import",
new_bank_bin: "970422",
new_account_name: "NGUYEN MINH TAM",
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)
const signed = signStopToken(STOP, SECRET)!
expect(sent).toHaveLength(1)
expect(sent[0].headers["List-Unsubscribe"]).toBe(
`<https://give.vn/api/plans/stop?t=${encodeURIComponent(signed)}>`
)
expect(sent[0].headers["List-Unsubscribe-Post"]).toBe("List-Unsubscribe=One-Click")
expect(sent[0].text).toContain(`https://give.vn/plans/stop?t=${encodeURIComponent(signed)}`)
expect(sent[0].text).toContain(`https://give.vn/email/unsubscribe?t=${UNSUB}`)
})

it("marks plan_account_swapped dead when stop_token or unsubscribe_token is missing", async () => {
claims = [
[
row(25, {
kind: "plan_account_swapped",
category: "notification",
unsubscribe_token: UNSUB,
stop_token: null,
payload: { campaign_title: "Nước sạch" },
}),
row(26, {
kind: "plan_account_swapped",
category: "notification",
unsubscribe_token: null,
stop_token: STOP,
payload: { campaign_title: "Nước sạch" },
}),
],
]
completeStatus = "dead"
await sendDueEmails(fakeDb(handler, calls) as never, transport, OPTIONS)
expect(sent).toHaveLength(0)
expect(completes()).toMatchObject([
{ p_id: row(25).id, p_permanent: true, p_error: "render: stop_token_missing" },
{ p_id: row(26).id, p_permanent: true, p_error: "render: unsubscribe_token_missing" },
])
})
})

it("reports a failure without the recipient's address, as permanent only when the provider says so", async () => {
Expand Down
120 changes: 120 additions & 0 deletions apps/web/src/server/email/templates.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,126 @@ describe("renderEmail: monthly plans (DOS/Give#276)", () => {
})
})

describe("renderEmail: plan_account_swapped (DOS/Give#291)", () => {
const SIGNED = `${"cd".repeat(32)}.${"A".repeat(21)}w`
const swap = (payload: Record<string, unknown> = {}, overrides: Partial<OutboxEmail> = {}) =>
email({
kind: "plan_account_swapped",
category: "notification",
tracking_token: null,
reference_code: null,
unsubscribe_token: UNSUB,
stop_token: "cd".repeat(32),
payload: {
campaign_id: CAMPAIGN,
campaign_slug: "nuoc-sach",
campaign_title: "Nước sạch cho bản",
campaign_type: "give",
plan_id: "33333333-3333-4333-8333-333333333333",
swap_request_id: "55555555-5555-4555-8555-555555555555",
new_binding_id: "66666666-6666-4666-8666-666666666666",
changed_at: "2026-11-22T09:00:00Z",
changed_date: "2026-11-22",
new_channel: "statement_import",
new_bank_bin: "970422",
new_chain: null,
new_account_name: "NGUYEN MINH TAM",
new_account_last4: "0002",
new_account_masked: "****0002",
old_bank_bin: "970436",
old_account_last4: "0001",
old_account_masked: "****0001",
...payload,
},
...overrides,
})
const FORBIDDEN = /quá hạn|nợ|còn thiếu/i

it("states holder name, bank, masked last 4 digits, swap date, campaign link, stop link and unsubscribe without asking to transfer", () => {
const r = renderEmail(swap(), ORIGIN, { signedStopToken: SIGNED })
expect(r.subject).toBe("Tài khoản nhận của chiến dịch “Nước sạch cho bản” đã thay đổi")
expect(r.text).toContain("Ngày 22/11/2026, Give đã duyệt thay đổi tài khoản nhận")
expect(r.text).toContain(
"Tài khoản nhận mới: chủ tài khoản NGUYEN MINH TAM, ngân hàng MBBank, số tài khoản •••• 0002."
)
expect(r.text).toContain("không yêu cầu bạn chuyển tiền")
expect(r.text).toContain("tài khoản cũ Vietcombank •••• 0001")
expect(r.text).toContain(`Xem trang chiến dịch: ${ORIGIN}/campaigns/nuoc-sach`)
const stop = `${ORIGIN}/plans/stop?t=${encodeURIComponent(SIGNED)}`
const unsub = `${ORIGIN}/email/unsubscribe?t=${UNSUB}`
expect(r.text).toContain(`Không muốn nhận lời nhắc nữa? Dừng ủng hộ hằng tháng: ${stop}`)
expect(r.text).toContain(`Không muốn nhận các email thông báo như thế này? Hủy đăng ký: ${unsub}`)
expect(r.text).not.toContain("email tổng kết")
expect(r.html).toContain(`href="${stop}"`)
expect(r.html).toContain(`href="${unsub}"`)
expect(r.unsubscribeUrl).toBe(unsub)
expect(r.oneClickUnsubscribeUrl).toBe(`${ORIGIN}/api/plans/stop?t=${encodeURIComponent(SIGNED)}`)
expect(r.text).not.toMatch(FORBIDDEN)
expect(r.text.split("\n--\n")[0]).not.toMatch(/\d{6,}/)
expect(r.html).not.toMatch(/<img|<link|url\(/i)
})

it("formats changed_at in Vietnam time when changed_date is absent and falls back cleanly on missing optional fields", () => {
const r = renderEmail(
swap({
changed_date: null,
changed_at: "2026-11-22T18:30:00Z", // 2026-11-23 01:30 Asia/Ho_Chi_Minh
campaign_slug: null,
old_bank_bin: null,
old_account_last4: null,
old_account_masked: null,
}),
ORIGIN,
{ signedStopToken: SIGNED }
)
expect(r.text).toContain("Ngày 23/11/2026")
expect(r.text).toContain("tài khoản cũ của chiến dịch")
expect(r.text).toContain(`${ORIGIN}/me/contributions`)
})

it("supports crypto channel formatting with masked last 4 characters", () => {
const r = renderEmail(
swap({
new_channel: "crypto",
new_bank_bin: null,
new_account_name: null,
new_chain: "polygon",
new_account_last4: "a9F2",
new_account_masked: "****a9F2",
}),
ORIGIN,
{ signedStopToken: SIGNED }
)
expect(r.text).toContain("Ví nhận mới trên mạng polygon: •••• a9F2.")
})

it("never renders raw multi-digit account numbers even from a malformed payload and escapes HTML", () => {
const r = renderEmail(
swap({
new_account_name: 'TAM <script>alert("x")</script>',
new_account_last4: "291000220002",
new_account_masked: "291000220002",
old_account_last4: "291000110001",
old_account_masked: "291000110001",
}),
ORIGIN,
{ signedStopToken: SIGNED }
)
expect(r.text).not.toContain("291000220002")
expect(r.text).not.toContain("291000110001")
expect(r.html).not.toContain("291000220002")
expect(r.html).not.toContain("<script>")
expect(r.html).toContain("&lt;script&gt;")
})

it("refuses plan_account_swapped without a signed stop token or without an unsubscribe token", () => {
expect(() => renderEmail(swap(), ORIGIN)).toThrow(new EmailRenderError("stop_token_missing"))
expect(() => renderEmail(swap({}, { unsubscribe_token: null }), ORIGIN, { signedStopToken: SIGNED })).toThrow(
new EmailRenderError("unsubscribe_token_missing")
)
})
})

describe("renderEmail", () => {
it("refuses an unknown kind", () => {
expect(() => renderEmail(email({ kind: "marketing" }), ORIGIN)).toThrow(EmailRenderError)
Expand Down
100 changes: 95 additions & 5 deletions apps/web/src/server/email/templates.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { bankByBin } from "@/lib/banks"
import { donationTrackingPath } from "@/lib/contributions"
import { GIVE_CONTACT_EMAIL } from "@/lib/contact"
import { formatVnd } from "@/lib/format"
import { formatDate, formatVnd } from "@/lib/format"
import { isUuid } from "@/lib/ids"
import { describeNotice, planCampaign, planEndedParagraphs } from "@/lib/notices"
import { NEW_CODE_EVERY_MONTH, periodLabel, planStopOneClickPath, planStopPath } from "@/lib/plans"
Expand Down Expand Up @@ -36,6 +37,7 @@ export const EMAIL_KINDS = [
"plan_reminder",
"plan_followup",
"plan_ended",
"plan_account_swapped",
] as const
export type EmailKind = (typeof EMAIL_KINDS)[number]

Expand All @@ -55,12 +57,12 @@ export interface OutboxEmail {
unsubscribe_token: string | null
reference_code: string | null
tracking_token: string | null
/** The plan's stop token (64 hex), minted by claim_outbox for plan_reminder and plan_followup only. */
/** The plan's stop token (64 hex), minted by claim_outbox for plan reminders and swap notices. */
stop_token: string | null
}

/** Kinds whose email carries the plan's stop link and must not go out without it. */
export const STOP_LINK_KINDS: readonly EmailKind[] = ["plan_reminder", "plan_followup"]
export const STOP_LINK_KINDS: readonly EmailKind[] = ["plan_reminder", "plan_followup", "plan_account_swapped"]

export function carriesStopLink(kind: string): boolean {
return (STOP_LINK_KINDS as readonly string[]).includes(kind)
Expand Down Expand Up @@ -317,6 +319,87 @@ function planEnded(email: OutboxEmail): Content {
}
}

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 an email.
*/
function maskedLast4(last4: string | null, masked: string | null): string | null {
if (last4 && LAST4_PATTERN.test(last4)) return `•••• ${last4}`
const match = masked ? MASKED_LAST4_PATTERN.exec(masked) : null
return match ? `•••• ${match[1]}` : null
}

function swapDateLabel(payload: OutboxEmail["payload"]): string | null {
const changedDate = text(payload, "changed_date")
const match = changedDate ? ISO_DATE_PATTERN.exec(changedDate) : null
if (match) return `${match[3]}/${match[2]}/${match[1]}`
const changedAt = text(payload, "changed_at")
if (changedAt && !Number.isNaN(Date.parse(changedAt))) return formatDate(changedAt)
return null
}

/** Receiving-account swap notice for active monthly plan donors (DOS/Give#291). */
function planAccountSwapped(email: OutboxEmail): Content {
const p = email.payload
const campaign = planCampaign(p)
const path = campaignPath(p)
const date = swapDateLabel(p)
const channel = text(p, "new_channel")
const newMasked = maskedLast4(text(p, "new_account_last4"), text(p, "new_account_masked"))

let newAccountLine: string
if (channel === "crypto") {
const rawChain = text(p, "new_chain")
const chain = rawChain && CHAIN_PATTERN.test(rawChain) ? rawChain : null
if (chain && newMasked) newAccountLine = `Ví nhận mới trên mạng ${chain}: ${newMasked}.`
else if (newMasked) newAccountLine = `Ví nhận mới: ${newMasked}.`
else newAccountLine = "Bạn có thể xem thông tin tài khoản nhận mới trên trang chiến dịch."
} else {
const holder = text(p, "new_account_name")
const bank = bankByBin(text(p, "new_bank_bin"))?.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}`)
newAccountLine =
parts.length > 0
? `Tài khoản nhận mới: ${parts.join(", ")}.`
: "Bạn có thể xem thông tin tài khoản nhận mới trên trang chiến dịch."
}

const oldBank = bankByBin(text(p, "old_bank_bin"))?.shortName ?? null
const oldMasked = maskedLast4(text(p, "old_account_last4"), text(p, "old_account_masked"))
const oldTarget = oldMasked
? oldBank
? `tài khoản cũ ${oldBank} ${oldMasked}`
: `tài khoản cũ ${oldMasked}`
: "tài khoản cũ của chiến dịch"

return {
subject: `Tài khoản nhận của ${campaign} đã thay đổi`,
heading: "Tài khoản nhận của chiến dịch đã thay đổi",
paragraphs: [
date
? `Ngày ${date}, Give đã duyệt thay đổi tài khoản nhận cho ${campaign}.`
: `Give đã duyệt thay đổi tài khoản nhận cho ${campaign}.`,
newAccountLine,
"Email này chỉ để thông báo thay đổi tài khoản và không yêu cầu bạn chuyển tiền. Các lời nhắc ủng hộ hằng tháng tiếp theo của bạn sẽ tự động hiển thị mã QR cho tài khoản mới.",
`Nếu bạn đã lưu mẫu chuyển tiền tới ${oldTarget} trong app ngân hàng, hãy xóa mẫu đó: tiền chuyển vào tài khoản cũ sau ngày đổi sẽ không còn được ghi nhận cho chiến dịch này.`,
"Tiền đi thẳng vào tài khoản của người tổ chức; Give không giữ tiền và không tự trừ tiền của bạn.",
],
link: path
? { href: path, label: "Xem trang chiến dịch" }
: { href: "/me/contributions", label: "Xem các khoản ủng hộ của bạn" },
footer: PLAN_FOOTER,
}
}

function content(email: OutboxEmail): Content {
const p = email.payload
switch (email.kind) {
Expand Down Expand Up @@ -369,6 +452,8 @@ function content(email: OutboxEmail): Content {
return planReminder(email)
case "plan_ended":
return planEnded(email)
case "plan_account_swapped":
return planAccountSwapped(email)
default:
throw new EmailRenderError(`unknown_kind:${String(email.kind).slice(0, 40)}`)
}
Expand Down Expand Up @@ -433,11 +518,16 @@ export function renderEmail(email: OutboxEmail, origin: string, options: RenderO
: "Email giao dịch gửi tự động từ Give.")
const help = `Cần hỗ trợ: ${GIVE_CONTACT_EMAIL}.`

const unsubscribePrompt =
email.kind === "campaign_ended"
? "Không muốn nhận email tổng kết như thế này?"
: "Không muốn nhận các email thông báo như thế này?"

const textParts = [c.heading, "", ...c.paragraphs.flatMap((p) => [p, ""])]
if (link) textParts.push(`${link.label}: ${link.href}`, "")
if (c.note) textParts.push(c.note, "")
textParts.push("--", `${footer} ${help}`)
if (unsubscribeUrl) textParts.push(`Không muốn nhận email tổng kết như thế này? Hủy đăng ký: ${unsubscribeUrl}`)
if (unsubscribeUrl) textParts.push(`${unsubscribePrompt} Hủy đăng ký: ${unsubscribeUrl}`)
if (stopUrl) textParts.push(`Không muốn nhận lời nhắc nữa? Dừng ủng hộ hằng tháng: ${stopUrl}`)

const p = (body: string, style = "margin:0 0 16px;font-size:16px;line-height:24px;color:#1f2937") =>
Expand All @@ -463,7 +553,7 @@ export function renderEmail(email: OutboxEmail, origin: string, options: RenderO
p(`${escapeHtml(footer)} ${escapeHtml(help)}`, "margin:16px 0 0;font-size:13px;line-height:20px;color:#57534e"),
unsubscribeUrl
? p(
`Không muốn nhận email tổng kết như thế này? <a href="${escapeHtml(unsubscribeUrl)}" style="color:#57534e">Hủy đăng ký</a>.`,
`${escapeHtml(unsubscribePrompt)} <a href="${escapeHtml(unsubscribeUrl)}" style="color:#57534e">Hủy đăng ký</a>.`,
"margin:8px 0 0;font-size:13px;line-height:20px;color:#57534e"
)
: "",
Expand Down