diff --git a/apps/web/src/app/(public)/donations/[code]/page.test.ts b/apps/web/src/app/(public)/donations/[code]/page.test.ts index 87400a6b..47cba1dc 100644 --- a/apps/web/src/app/(public)/donations/[code]/page.test.ts +++ b/apps/web/src/app/(public)/donations/[code]/page.test.ts @@ -109,6 +109,7 @@ describe("DonationPage (/donations/[code], DOS/Give#50)", () => { expect(html).toContain("Bữa trưa cho em") expect(html).toContain("GVABCDEFG") expect(html).toContain("Đã nhận") + expect(html).toContain("Tải thẻ “Tôi đã chung tay”") expect(html).toContain("Sao chép đường dẫn") expect(html).toContain("Lưu đường dẫn theo dõi") // Neither the SSR DOM attributes/text nor the DB select list exposes personal data or raw token. @@ -247,5 +248,16 @@ describe("DonationPage for a monthly plan's donation (DOS/Give#276)", () => { expect(html).toContain("Chiến dịch hiện không nhận chuyển khoản") expect(html).not.toContain("0123456789") + expect(html).not.toContain("Tải thẻ “Tôi đã chung tay”") + }) + + it("hides the thank-you card button while awaiting transfer and shows it once received (DOS/Give#313)", async () => { + setUp(ownRow({ status: "awaiting_transfer", received_amount: 0 })) + const awaitingHtml = await render() + expect(awaitingHtml).not.toContain("Tải thẻ “Tôi đã chung tay”") + + setUp(ownRow({ status: "received", received_amount: 200000, public_name: "Nguyễn Minh", is_anonymous: false })) + const receivedHtml = await render() + expect(receivedHtml).toContain("Tải thẻ “Tôi đã chung tay”") }) }) diff --git a/apps/web/src/app/(public)/donations/[code]/page.tsx b/apps/web/src/app/(public)/donations/[code]/page.tsx index 791b3b5c..f5d7afbc 100644 --- a/apps/web/src/app/(public)/donations/[code]/page.tsx +++ b/apps/web/src/app/(public)/donations/[code]/page.tsx @@ -10,6 +10,7 @@ import { Money } from "@/components/ui/Money" import { RefCode } from "@/components/ui/RefCode" import { siteOrigin } from "@/lib/auth/origin" import { getSession } from "@/lib/auth/session" +import { isPublicStatus, type CampaignStatus } from "@/lib/campaigns" import { donationTrackingPath, qrExpiresAt } from "@/lib/contributions" import { NEW_CODE_EVERY_MONTH, periodEnd, periodLabel, planDonationPayable, planQrUntil } from "@/lib/plans" import { dbAs, dbService } from "@/lib/supabase" @@ -65,13 +66,15 @@ function planQrCaption(until: Date, period: string): string { * back; anyone else gets the not-found page, which explains where the page * can be opened. */ -async function loadDonation(code: string): Promise<{ donation: PaymentContribution; guestToken: string | null }> { +async function loadDonation( + code: string +): Promise<{ donation: PaymentContribution; guestToken: string | null; donorDisplayName: string | null }> { const session = await getSession() let sessionRejected = false if (session) { try { const own = await ownContribution(dbAs(session.accessToken), session.user.id, code) - if (own) return { donation: own, guestToken: null } + if (own) return { donation: own, guestToken: null, donorDisplayName: session.user.name ?? null } } catch (error) { if (!isSessionRejected(error)) throw error sessionRejected = true @@ -79,7 +82,7 @@ async function loadDonation(code: string): Promise<{ donation: PaymentContributi } const token = donationCookieToken(await cookies(), code, hostnameFrom((await headers()).get("host"))) const guest = token ? await guestContribution(dbService(), code, token) : null - if (guest && token) return { donation: guest, guestToken: token } + if (guest && token) return { donation: guest, guestToken: token, donorDisplayName: null } if (sessionRejected) redirect(`/auth/login?return_path=${encodeURIComponent(`/donations/${code}`)}`) notFound() } @@ -87,7 +90,7 @@ async function loadDonation(code: string): Promise<{ donation: PaymentContributi export default async function DonationPage({ params }: { params: Promise<{ code: string }> }) { const { code } = await params if (!isDonationCode(code)) notFound() - const { donation, guestToken } = await loadDonation(code) + const { donation, guestToken, donorDisplayName } = await loadDonation(code) const service = dbService() const campaign = await paymentCampaign(service, donation.campaign_id) @@ -180,6 +183,21 @@ export default async function DonationPage({ params }: { params: Promise<{ code: instructions = closedNote } + const origin = siteOrigin() + const thankYou = isPublicStatus(campaign.status as CampaignStatus) + ? { + kind: "donation" as const, + campaignTitle: campaign.title, + campaignSlug: campaign.slug, + campaignType: campaign.type, + // Guest tracking views never expose donor PII; signed-in owners respect anonymity. + donorName: guestToken ? null : donation.is_anonymous ? null : donation.public_name?.trim() || donorDisplayName, + isAnonymous: guestToken ? false : donation.is_anonymous === true, + createdAt: donation.created_at, + origin, + } + : null + return (
@@ -227,10 +245,7 @@ export default async function DonationPage({ params }: { params: Promise<{ code: Lưu đường dẫn theo dõi để xem trạng thái khoản ủng hộ này trên thiết bị khác trong 7 ngày. Đường dẫn không chứa thông tin cá nhân.

- +
)} @@ -241,6 +256,7 @@ export default async function DonationPage({ params }: { params: Promise<{ code: qrExpired={qrExpired} qrMsLeft={expiresAt ? Math.max(0, expiresAt.getTime() - now.getTime()) : 0} expiredNote={expiredNote} + thankYou={thankYou} > {instructions} diff --git a/apps/web/src/app/campaigns/[slug]/opengraph-image.test.ts b/apps/web/src/app/campaigns/[slug]/opengraph-image.test.ts new file mode 100644 index 00000000..a869632d --- /dev/null +++ b/apps/web/src/app/campaigns/[slug]/opengraph-image.test.ts @@ -0,0 +1,149 @@ +import { beforeEach, describe, expect, it, vi } from "vitest" + +import type { CampaignStatus, PublicCampaign } from "@/lib/campaigns" +import { PUBLIC_COVER_CACHE } from "@/lib/cover-route" +import { fakeDb, type Call, type Handler } from "@/test/fake-db" + +const CAMPAIGN = "33333333-3333-4333-8333-333333333333" +const SLUG = "xay-truong-ban-may" + +const state = vi.hoisted(() => ({ + anonHandler: (() => undefined) as Handler, + anonCalls: [] as Call[], + dbAsTokens: [] as (string | undefined)[], +})) + +vi.mock("@/lib/supabase", () => ({ + dbAs: (token?: string) => { + state.dbAsTokens.push(token) + return fakeDb((call) => state.anonHandler(call), state.anonCalls) + }, +})) + +const { default: CampaignOpenGraphImage, contentType, size } = await import("./opengraph-image") + +function campaignFixture(status: CampaignStatus = "live", overrides: Partial = {}): PublicCampaign { + return { + id: CAMPAIGN, + slug: SLUG, + type: "give", + funding_model: "flexible", + category_id: "cat-1", + title: "Xây trường Bản Mây — Hỗ trợ bữa ăn đủ chất cho trẻ em vùng cao", + summary: "Cùng dựng lớp học mới.", + story: null, + beneficiary_name: null, + beneficiary_relation: null, + cover_media_id: null, + asset: "VND", + goal_amount: 100_000_000, + min_contribution: 20_000, + stretch_goal_amount: null, + display_options: { progress_bar: true, backers_count: true, time_remaining: true }, + starts_at: null, + ends_at: "2099-12-31T00:00:00.000Z", + payment_window_days: 7, + status, + submitted_at: "2026-11-10T00:00:00.000Z", + approved_at: "2026-11-11T00:00:00.000Z", + outcome_at: null, + created_at: "2026-11-01T00:00:00.000Z", + updated_at: "2026-11-11T00:00:00.000Z", + category: { id: "cat-1", slug: "giao-duc", name: "Giáo dục", icon: null, color: null }, + cover: null, + ...overrides, + } +} + +beforeEach(() => { + state.anonCalls.length = 0 + state.dbAsTokens.length = 0 + state.anonHandler = (call) => { + if (call.target === "campaigns") return { data: campaignFixture("live") } + if (call.target === "public_campaigns") { + return { + data: { + id: CAMPAIGN, + type: "give", + asset: "VND", + goal_amount: 100_000_000, + pledged_amount: 0, + paid_amount: 45_000_000, + disbursable_amount: 45_000_000, + disbursed_amount: 0, + refunded_amount: 0, + unexplained_out_amount: 0, + unexplained_out_count: 0, + supporters_count: 18, + other_in_amount: 5_000_000, + refund_owed_amount: 0, + backers_count: 0, + payments_stopped_at: null, + payments_stopped_note: null, + own_transfer_amount: 0, + }, + } + } + if (call.target === "rpc:public_organizer") { + return { data: [{ display_name: "Quỹ Bản Mây", kind: "organization", verification_status: "verified" }] } + } + return undefined + } +}) + +describe("CampaignOpenGraphImage (/campaigns/[slug]/opengraph-image, DOS/Give#313)", () => { + it("declares standard 1200x630 PNG metadata", () => { + expect(size).toEqual({ width: 1200, height: 630 }) + expect(contentType).toBe("image/png") + }) + + it("renders a valid PNG with bundled Vietnamese font and public cache headers for public give and back campaigns", async () => { + const giveResponse = await CampaignOpenGraphImage({ params: Promise.resolve({ slug: SLUG }) }) + expect(giveResponse.status).toBe(200) + expect(giveResponse.headers.get("content-type")).toContain("image/png") + expect(giveResponse.headers.get("cache-control")).toBe(PUBLIC_COVER_CACHE) + expect(giveResponse.headers.get("x-content-type-options")).toBe("nosniff") + // Anonymous dbAs() only — never reads authenticated session. + expect(state.dbAsTokens).toEqual([undefined]) + + const bytes = new Uint8Array(await giveResponse.arrayBuffer()) + expect(bytes.length).toBeGreaterThan(1000) + // PNG magic header: 89 50 4E 47 0D 0A 1A 0A + expect(Array.from(bytes.slice(0, 8))).toEqual([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]) + + // Also renders cleanly for a succeeded back campaign. + const base = state.anonHandler + state.anonHandler = (call) => + call.target === "campaigns" + ? { data: campaignFixture("succeeded", { type: "back", funding_model: "all_or_nothing" }) } + : base(call) + const backResponse = await CampaignOpenGraphImage({ params: Promise.resolve({ slug: SLUG }) }) + expect(backResponse.status).toBe(200) + const backBytes = new Uint8Array(await backResponse.arrayBuffer()) + expect(Array.from(backBytes.slice(0, 4))).toEqual([0x89, 0x50, 0x4e, 0x47]) + }) + + it.each(["draft", "in_review", "changes_requested", "approved", "suspended", "cancelled"] as const)( + "strictly returns 404 with no-store for non-public campaign status %s", + async (status) => { + state.anonHandler = (call) => (call.target === "campaigns" ? { data: campaignFixture(status) } : undefined) + + const response = await CampaignOpenGraphImage({ params: Promise.resolve({ slug: SLUG }) }) + expect(response.status).toBe(404) + expect(response.headers.get("cache-control")).toBe("no-store") + } + ) + + it("returns 404 for nonexistent campaigns and invalid slugs without querying the database for invalid slugs", async () => { + state.anonHandler = () => ({ data: null }) + const missing = await CampaignOpenGraphImage({ params: Promise.resolve({ slug: SLUG }) }) + expect(missing.status).toBe(404) + expect(missing.headers.get("cache-control")).toBe("no-store") + + state.anonCalls.length = 0 + const invalid = await CampaignOpenGraphImage({ params: Promise.resolve({ slug: "BAD SLUG/.." }) }) + expect(invalid.status).toBe(404) + expect(invalid.headers.get("cache-control")).toBe("no-store") + expect(state.anonCalls).toHaveLength(0) + }) +}) diff --git a/apps/web/src/app/campaigns/[slug]/opengraph-image.tsx b/apps/web/src/app/campaigns/[slug]/opengraph-image.tsx new file mode 100644 index 00000000..ad8ab700 --- /dev/null +++ b/apps/web/src/app/campaigns/[slug]/opengraph-image.tsx @@ -0,0 +1,306 @@ +import { readFile } from "node:fs/promises" +import { ImageResponse } from "next/og" + +import { getCampaignBySlug, getPublicOrganizer } from "@/lib/campaigns" +import { PUBLIC_COVER_CACHE } from "@/lib/cover-route" +import { SLUG_PATTERN } from "@/lib/slug" +import { getMoneyTotals } from "@/lib/statement" +import { dbAs } from "@/lib/supabase" +import { buildOgCampaignCardModel, isOgEligible } from "@/lib/viral-sharing" + +export const alt = "Chiến dịch gây quỹ minh bạch trên Give" +export const size = { width: 1200, height: 630 } +export const contentType = "image/png" + +interface FontBuffers { + regular: Buffer + bold: Buffer +} + +let fontPromise: Promise | null = null + +function loadFonts(): Promise { + if (!fontPromise) { + fontPromise = Promise.all([ + readFile(new URL("../../../assets/fonts/BeVietnamPro-Regular.ttf", import.meta.url)), + readFile(new URL("../../../assets/fonts/BeVietnamPro-Bold.ttf", import.meta.url)), + ]) + .then(([regular, bold]) => ({ regular, bold })) + .catch((error: unknown) => { + fontPromise = null + throw error + }) + } + return fontPromise +} + +function notFoundResponse(): Response { + return new Response("Not Found", { + status: 404, + headers: { "Cache-Control": "no-store" }, + }) +} + +/** + * Dynamic Open Graph card for public /campaigns/[slug] pages (DOS/Give#313). + * + * Security invariants: + * - Reads anonymously via dbAs() only and returns 404 for drafts, previews, + * suspended, cancelled, invalid, or nonexistent campaigns. + * - Zero SSRF: never fetches any remote URL; renders with local bundled + * Be Vietnam Pro TTF fonts for crisp Vietnamese diacritics. + */ +export default async function CampaignOpenGraphImage({ params }: { params: Promise<{ slug: string }> }) { + const { slug } = await params + if (!SLUG_PATTERN.test(slug) || slug.length > 80) return notFoundResponse() + + const anon = dbAs() + const campaign = await getCampaignBySlug(anon, slug) + if (!isOgEligible(campaign) || !campaign) return notFoundResponse() + + const [totals, organizer, fonts] = await Promise.all([ + getMoneyTotals(anon, campaign.id).catch(() => null), + getPublicOrganizer(anon, campaign.id).catch(() => null), + loadFonts(), + ]) + + const model = buildOgCampaignCardModel({ campaign, totals, organizer }) + if (!model) return notFoundResponse() + + const isGive = model.type === "give" + const barColor = isGive ? "#047857" : "#C2410C" + const badgeBg = isGive ? "#ECFDF5" : "#FFF7ED" + const badgeColor = isGive ? "#047857" : "#C2410C" + const progressWidth = `${Math.max(0, Math.min(100, model.percent))}%` + + return new ImageResponse( +
+
+
+ {/* Top row: badges and Give wordmark */} +
+
+
+ {model.typeBadge} +
+ {model.verifiedStatementBadge && ( +
+ + + + + {model.verifiedStatementBadge} +
+ )} + {model.statusBadge && ( +
+ {model.statusBadge} +
+ )} +
+ +
+
+ G +
+
Give
+
+
+ + {/* Title & organizer */} +
+
62 ? "40px" : "46px", + fontWeight: 700, + lineHeight: 1.24, + color: "#111318", + }} + > + {model.title} +
+ {model.organizerName && ( +
+ {model.organizerName} + {model.organizerVerified && ( + + · Đã xác minh + + )} +
+ )} +
+ + {/* Funding summary panel */} +
+
+
+ + {model.raisedText} + + + {model.raisedLabel} + +
+
+ {model.goalText} + + {model.percent}% + +
+
+ + {model.showProgressBar && ( +
+
+
+ )} + +
+ {model.supportersText ?? "Theo dõi sao kê công khai"} + {model.footerText} +
+
+
+
, + { + ...size, + headers: { + "Cache-Control": PUBLIC_COVER_CACHE, + "X-Content-Type-Options": "nosniff", + }, + fonts: [ + { name: "Be Vietnam Pro", data: fonts.regular, weight: 400, style: "normal" }, + { name: "Be Vietnam Pro", data: fonts.bold, weight: 700, style: "normal" }, + ], + } + ) +} diff --git a/apps/web/src/app/campaigns/[slug]/page.test.ts b/apps/web/src/app/campaigns/[slug]/page.test.ts index 056418af..47a23263 100644 --- a/apps/web/src/app/campaigns/[slug]/page.test.ts +++ b/apps/web/src/app/campaigns/[slug]/page.test.ts @@ -255,8 +255,8 @@ describe("CampaignPage report flow (DOS/Give#98)", () => { }) }) -describe("generateMetadata (/campaigns/[slug], DOS/Give#232)", () => { - it("emits canonical URL and complete OpenGraph card with cover image for a public live campaign", async () => { +describe("generateMetadata (/campaigns/[slug], DOS/Give#232, DOS/Give#313)", () => { + it("emits canonical URL and OpenGraph metadata without overriding the dynamic opengraph-image route", async () => { state.anonHandler = (call) => { if (call.target === "campaigns") { return { @@ -282,7 +282,6 @@ describe("generateMetadata (/campaigns/[slug], DOS/Give#232)", () => { title: "Xây trường Bản Mây", description: "Cùng dựng lớp học mới.", url: `/campaigns/${SLUG}`, - images: ["/media/public/campaigns/3333/cover.jpg"], }, }) }) @@ -1517,3 +1516,48 @@ describe("CampaignPage comments section (DOS/Give#250)", () => { expect(soloDoc.querySelector("section#doi-ngu")).toBeNull() }) }) + +describe("CampaignPage downloadable QR poster (DOS/Give#313)", () => { + it("renders 'Tải poster QR' on public campaigns without leaking raw account numbers or holder names", async () => { + state.serviceHandler = (call) => + call.target === "rpc:payment_account" + ? { + data: { + channel: "statement_import", + bank_bin: "970436", + account_number: "0011012345678", + account_name: "NGUYEN VAN SECRET", + }, + } + : undefined + + const html = renderToStaticMarkup(await CampaignPage({ params: Promise.resolve({ slug: SLUG }) })) + const doc = parseDoc(html) + const posterBtn = [...doc.querySelectorAll("button")].find((b) => b.textContent?.includes("Tải poster QR")) + expect(posterBtn).toBeDefined() + expect(posterBtn?.className).toContain("btn-secondary") + expect(html).not.toContain("0011012345678") + expect(html).not.toContain("NGUYEN VAN SECRET") + }) + + it("hides 'Tải poster QR' on non-public preview pages", async () => { + state.session = { + user: { id: VIEWER, email: "org@dos.me", name: "Người tổ chức" }, + accessToken: "org-token", + } + state.anonHandler = () => ({ data: null }) + state.userHandler = (call) => { + if (call.target === "campaigns") return { data: campaignFixture("draft") } + if ( + call.target === "campaign_milestones" || + call.target === "campaign_updates" || + call.target === "campaign_media" + ) + return { data: [] } + return undefined + } + + const html = renderToStaticMarkup(await CampaignPage({ params: Promise.resolve({ slug: SLUG }) })) + expect(html).not.toContain("Tải poster QR") + }) +}) diff --git a/apps/web/src/app/campaigns/[slug]/page.tsx b/apps/web/src/app/campaigns/[slug]/page.tsx index a4624bf2..91917670 100644 --- a/apps/web/src/app/campaigns/[slug]/page.tsx +++ b/apps/web/src/app/campaigns/[slug]/page.tsx @@ -16,6 +16,7 @@ import { StatementPreview } from "@/components/campaign/StatementPreview" import { StickyAside } from "@/components/campaign/StickyAside" import { Markdown } from "@/components/Markdown" import { ProgressBar } from "@/components/ProgressBar" +import { QrPosterButton } from "@/components/QrPosterButton" import { RewardTiers } from "@/components/RewardTiers" import { ShareButtons } from "@/components/ShareButtons" import { Button, ButtonLink, buttonClass } from "@/components/ui/Button" @@ -58,6 +59,7 @@ import { getMoneyTotals, listStatement, raisedAmount, statementHref } from "@/li import { dbAs, dbService } from "@/lib/supabase" import { acceptsDonations, paymentAccount } from "@/server/contributions" import { listPublicTiers, organizesCampaign } from "@/server/pledges" +import { buildServerPosterData } from "@/server/viral-sharing" import { CampaignComments } from "./CampaignComments" import { DonateForm } from "./DonateForm" @@ -114,7 +116,6 @@ export async function generateMetadata({ params }: { params: Promise<{ slug: str title: campaign.title, ...(description ? { description } : {}), url: canonicalPath, - ...(campaign.cover?.storage_path ? { images: [publicCoverUrl(campaign.cover.storage_path)] } : {}), }, } } @@ -432,6 +433,7 @@ export default async function CampaignPage({ ].filter((stat) => stat !== null) const origin = siteOrigin() const breadcrumbJsonLd = !preview && !halted ? buildBreadcrumbJsonLd(campaign, origin) : null + const posterData = !preview ? buildServerPosterData({ campaign, totals, organizer, account, origin }) : null return (
@@ -660,6 +662,7 @@ export default async function CampaignPage({ origin={origin} campaignId={campaign.id} /> + {posterData && } {!ownCampaign && ( )} diff --git a/apps/web/src/app/me/contributions/page.test.ts b/apps/web/src/app/me/contributions/page.test.ts index 35accfa3..e720f0fc 100644 --- a/apps/web/src/app/me/contributions/page.test.ts +++ b/apps/web/src/app/me/contributions/page.test.ts @@ -106,7 +106,7 @@ function donation(overrides: Record = {}) { created_at: "2026-11-05T01:00:00.000Z", plan_id: PLAN, plan_period: "2026-11-01", - campaign: { slug: campaign.slug, title: campaign.title }, + campaign: { slug: campaign.slug, title: campaign.title, status: campaign.status }, ...overrides, } } @@ -315,3 +315,93 @@ describe("MyContributionsPage monthly plans (DOS/Give#276)", () => { expect(JSON.stringify(logged)).not.toContain(USER) }) }) + +describe("MyContributionsPage 'Tôi đã chung tay' thank-you card (DOS/Give#313)", () => { + it("shows the thank-you card action only for received donations and paid pledges on public campaigns, including string bigint amounts", async () => { + serve( + [], + [ + donation({ + id: "d-received", + reference_code: "GVRECV01", + status: "received", + // PostgREST may serialize bigint columns as strings. + received_amount: "250000" as unknown as number, + public_name: "Nguyễn Minh", + plan_id: null, + plan_period: null, + }), + donation({ + id: "d-awaiting", + reference_code: "GVAWAIT1", + status: "awaiting_transfer", + received_amount: 0, + plan_id: null, + plan_period: null, + }), + donation({ + id: "p-paid", + kind: "pledge", + reference_code: "GVPAID01", + status: "paid", + intended_amount: 500000, + received_amount: 500000, + plan_id: null, + plan_period: null, + }), + donation({ + id: "d-private", + reference_code: "GVPRIV01", + status: "received", + received_amount: 100000, + campaign: null, + plan_id: null, + plan_period: null, + }), + donation({ + id: "d-suspended", + reference_code: "GVSUSP01", + status: "received", + received_amount: 150000, + // Staff/organizer RLS still returns the embedded row for a suspended campaign. + campaign: { slug: campaign.slug, title: campaign.title, status: "suspended" }, + plan_id: null, + plan_period: null, + }), + ] + ) + const baseService = state.service + state.service = (call) => { + if (call.target === "rpc:pledge_balances") { + return { + data: [ + { + contribution_id: "p-paid", + intended_amount: 500000, + received_amount: 500000, + refunded_amount: 0, + payments_stopped_at: null, + }, + ], + } + } + return baseService(call) + } + + const { doc } = await render() + const items = [...doc.querySelectorAll("ul.card > li")] + expect(items).toHaveLength(5) + + // Received donation on public campaign (string bigint amount) -> shows thank-you card button + expect(items[0].textContent).toContain("Thẻ “Tôi đã chung tay”") + // Awaiting donation -> no thank-you card button + expect(items[1].textContent).not.toContain("Thẻ “Tôi đã chung tay”") + // Paid pledge on public campaign -> shows thank-you card button alongside "Xem cam kết" + expect(items[2].textContent).toContain("Thẻ “Tôi đã chung tay”") + expect(items[2].textContent).toContain("Xem cam kết") + // Received donation on null campaign -> no thank-you card button + expect(items[3].textContent).not.toContain("Thẻ “Tôi đã chung tay”") + // Received donation on suspended campaign (staff/organizer RLS visibility) -> no thank-you card button + expect(items[4].textContent).not.toContain("Thẻ “Tôi đã chung tay”") + }) +}) diff --git a/apps/web/src/app/me/contributions/page.tsx b/apps/web/src/app/me/contributions/page.tsx index 7acbefde..d84ad841 100644 --- a/apps/web/src/app/me/contributions/page.tsx +++ b/apps/web/src/app/me/contributions/page.tsx @@ -2,6 +2,7 @@ import type { Metadata } from "next" import Link from "next/link" import { Suspense } from "react" +import { ThankYouCardButton } from "@/components/ThankYouCardButton" import { Badge } from "@/components/ui/Badge" import { ButtonLink } from "@/components/ui/Button" import { EmptyState } from "@/components/ui/EmptyState" @@ -9,12 +10,15 @@ import { HeartIcon, SparkIcon } from "@/components/ui/icons" import { PageHeader } from "@/components/ui/PageHeader" import { PledgeStatusBadge } from "@/components/ui/PledgeStatusBadge" import { SkeletonList } from "@/components/ui/Skeleton" +import { siteOrigin } from "@/lib/auth/origin" import { requireSession, type Session } from "@/lib/auth/session" +import { isPublicStatus, type CampaignStatus } from "@/lib/campaigns" import { donationStatusLabel } from "@/lib/contributions" import { formatDate, formatVnd } from "@/lib/format" import { periodLabel, planDonationPayable, vnMonthStart } from "@/lib/plans" import { fulfillmentLabel, offersPayment, pledgeListSummary, withoutReplacedPledges } from "@/lib/pledges" import { dbAs, dbService } from "@/lib/supabase" +import { isThankYouCardEligible } from "@/lib/viral-sharing" import { paymentAccounts } from "@/server/contributions" import { pledgeBalances, type PledgeBalance } from "@/server/pledges" @@ -34,6 +38,7 @@ interface MyContribution { intended_amount: number received_amount: number status: string + public_name?: string | null is_anonymous: boolean payment_due_at: string | null fulfillment_status: string | null @@ -42,7 +47,7 @@ interface MyContribution { /** Set on a monthly plan's donation (DOS/Give#276). */ plan_id: string | null plan_period: string | null - campaign: { slug: string; title: string } | null + campaign: { slug: string; title: string; status: CampaignStatus } | null } export default async function MyContributionsPage() { @@ -117,8 +122,8 @@ async function ContributionList({ session }: { session: Session }) { db .from("contributions") .select( - "id, kind, campaign_id, reference_code, intended_amount, received_amount, status, is_anonymous, payment_due_at, " + - "fulfillment_status, reward_tier_id, created_at, plan_id, plan_period, campaign:campaigns(slug, title)" + "id, kind, campaign_id, reference_code, intended_amount, received_amount, status, public_name, is_anonymous, payment_due_at, " + + "fulfillment_status, reward_tier_id, created_at, plan_id, plan_period, campaign:campaigns(slug, title, status)" ) .eq("contributor_user_id", session.user.id) .order("created_at", { ascending: false }) @@ -161,6 +166,8 @@ async function ContributionList({ session }: { session: Session }) { ) } + const origin = siteOrigin() + return (
{plans.length > 0 && } @@ -170,10 +177,20 @@ async function ContributionList({ session }: { session: Session }) {

Tất cả lượt ủng hộ

- + ) : ( - + ))}
) @@ -182,15 +199,47 @@ async function ContributionList({ session }: { session: Session }) { function MyContributionItems({ contributions, balances, + donorFallbackName, + origin, }: { contributions: MyContribution[] balances: Map + donorFallbackName: string | null + origin?: string }) { return (
    {contributions.map((c) => { const pledge = c.kind === "pledge" const Icon = pledge ? SparkIcon : HeartIcon + const balance = balances.get(c.id) ?? null + const receivedAmount = Number(c.received_amount) + const cardAmount = + pledge && balance + ? Math.max(0, Number(balance.received_amount) - Number(balance.refunded_amount)) + : receivedAmount + const hasPublicCampaign = c.campaign !== null && isPublicStatus(c.campaign.status) + const canShareThankYou = isThankYouCardEligible({ + kind: c.kind, + status: c.status, + receivedAmount: cardAmount, + hasPublicCampaign, + }) + const thankYouCard = + canShareThankYou && c.campaign + ? { + kind: c.kind, + referenceCode: c.reference_code, + amount: cardAmount, + campaignTitle: c.campaign.title, + campaignSlug: c.campaign.slug, + campaignType: pledge ? ("back" as const) : ("give" as const), + donorName: c.is_anonymous ? null : c.public_name?.trim() || donorFallbackName, + isAnonymous: c.is_anonymous, + createdAt: c.created_at, + origin, + } + : null return (
  • @@ -228,7 +277,7 @@ function MyContributionItems({ )}

    {pledge - ? pledgeListSummary(c, balances.get(c.id) ?? null) + ? pledgeListSummary(c, balance) : c.status === "received" ? `Đã nhận ${formatVnd(c.received_amount)}` : `Dự định ${formatVnd(c.intended_amount)}`} @@ -239,13 +288,20 @@ function MyContributionItems({

{pledge ? ( - - {offersPayment(c, balances.get(c.id) ?? null) ? "Thanh toán" : "Xem cam kết"} - +
+ {thankYouCard && ( + + )} + + {offersPayment(c, balance) ? "Thanh toán" : "Xem cam kết"} + +
+ ) : thankYouCard ? ( + ) : ( c.status !== "received" && ( diff --git a/apps/web/src/assets/fonts/BeVietnamPro-Bold.ttf b/apps/web/src/assets/fonts/BeVietnamPro-Bold.ttf new file mode 100644 index 00000000..52aadc6d Binary files /dev/null and b/apps/web/src/assets/fonts/BeVietnamPro-Bold.ttf differ diff --git a/apps/web/src/assets/fonts/BeVietnamPro-Regular.ttf b/apps/web/src/assets/fonts/BeVietnamPro-Regular.ttf new file mode 100644 index 00000000..dfa34c09 Binary files /dev/null and b/apps/web/src/assets/fonts/BeVietnamPro-Regular.ttf differ diff --git a/apps/web/src/assets/fonts/OFL.txt b/apps/web/src/assets/fonts/OFL.txt new file mode 100644 index 00000000..9e2c1177 --- /dev/null +++ b/apps/web/src/assets/fonts/OFL.txt @@ -0,0 +1,93 @@ +Copyright 2021 The Be Vietnam Pro Project Authors (https://github.com/bettergui/BeVietnamPro), + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/apps/web/src/components/DonationStatus.tsx b/apps/web/src/components/DonationStatus.tsx index b4b71c10..599a4ae8 100644 --- a/apps/web/src/components/DonationStatus.tsx +++ b/apps/web/src/components/DonationStatus.tsx @@ -2,10 +2,12 @@ import { useCallback, useEffect, useRef, useState, type ReactNode, type SVGProps } from "react" +import { ThankYouCardButton } from "@/components/ThankYouCardButton" import { buttonClass } from "@/components/ui/Button" import { ClockIcon } from "@/components/ui/icons" import { donationStatusLabel, POLL_INTERVAL_MS, POLL_WINDOW_MS, type ContributionStatus } from "@/lib/contributions" import { formatVnd } from "@/lib/format" +import type { ThankYouCardInput } from "@/lib/viral-sharing" function CheckIcon(props: SVGProps) { return ( @@ -42,6 +44,7 @@ export function DonationStatus({ qrExpired: qrExpiredAtRender, qrMsLeft, expiredNote, + thankYou, children, }: { code: string @@ -51,6 +54,8 @@ export function DonationStatus({ /** Milliseconds the QR had left when the server rendered the page. */ qrMsLeft: number expiredNote: ReactNode + /** Public campaign + non-PII card details shown once the donation is received (DOS/Give#313). */ + thankYou?: Omit | null children: ReactNode }) { const [status, setStatus] = useState(initial) @@ -115,6 +120,17 @@ export function DonationStatus({

Đã nhận {formatVnd(status.received_amount)}. Cảm ơn bạn!

Khoản ủng hộ đã vào tài khoản nhận của chiến dịch.

+ {thankYou && status.received_amount > 0 && ( +
+ +
+ )}
) } diff --git a/apps/web/src/components/QrPosterButton.test.ts b/apps/web/src/components/QrPosterButton.test.ts new file mode 100644 index 00000000..420803ed --- /dev/null +++ b/apps/web/src/components/QrPosterButton.test.ts @@ -0,0 +1,196 @@ +// @vitest-environment happy-dom +import { act, createElement } from "react" +import { createRoot, type Root } from "react-dom/client" +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" + +import { encodeQrMatrix, type CampaignPosterData } from "@/lib/viral-sharing" + +import { QrPosterButton } from "./QrPosterButton" + +declare global { + var IS_REACT_ACT_ENVIRONMENT: boolean | undefined +} + +let container: HTMLDivElement +let root: Root +let drawnText: string[] +let originalBeacon: PropertyDescriptor | undefined +let sendBeaconMock: ReturnType + +function createMockContext() { + return { + fillStyle: "", + strokeStyle: "", + lineWidth: 1, + font: "", + textAlign: "left", + textBaseline: "top", + fillRect: vi.fn(), + beginPath: vi.fn(), + moveTo: vi.fn(), + lineTo: vi.fn(), + quadraticCurveTo: vi.fn(), + closePath: vi.fn(), + fill: vi.fn(), + stroke: vi.fn(), + fillText: vi.fn((text: string) => { + drawnText.push(text) + }), + measureText: vi.fn((text: string) => ({ width: text.length * 14 })), + } +} + +function posterFixture(overrides: Partial = {}): CampaignPosterData { + return { + campaignId: "33333333-3333-4333-8333-333333333333", + slug: "xay-truong-ban-may", + path: "/campaigns/xay-truong-ban-may", + origin: "https://give.vn", + type: "give", + typeBadge: "Từ thiện", + title: "Xây trường Bản Mây", + organizerName: "Quỹ Bản Mây", + organizerVerified: true, + raisedLabel: "Đã nhận", + raisedText: "40.000.000 ₫", + goalText: "Mục tiêu 100.000.000 ₫", + percent: 40, + showProgressBar: true, + verifiedStatementBadge: "Sao kê đối chiếu ngân hàng", + vietQr: { + qr: encodeQrMatrix("00020101021138540010A00000072701240006970436011001234567890208QRIBFTTA53037045802VN6304ABCD"), + bankName: "Vietcombank", + maskedAccount: "•••• 6789", + }, + ...overrides, + } +} + +beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true + drawnText = [] + originalBeacon = Object.getOwnPropertyDescriptor(navigator, "sendBeacon") + sendBeaconMock = vi.fn(() => true) + Object.defineProperty(navigator, "sendBeacon", { value: sendBeaconMock, configurable: true, writable: true }) + container = document.createElement("div") + document.body.append(container) + root = createRoot(container) + vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation( + () => createMockContext() as unknown as CanvasRenderingContext2D + ) + vi.spyOn(HTMLCanvasElement.prototype, "toBlob").mockImplementation((cb) => { + cb(new Blob(["png"], { type: "image/png" })) + }) +}) + +afterEach(() => { + act(() => root.unmount()) + container.remove() + if (originalBeacon) { + Object.defineProperty(navigator, "sendBeacon", originalBeacon) + } else { + Reflect.deleteProperty(navigator, "sendBeacon") + } + vi.restoreAllMocks() +}) + +describe("QrPosterButton (DOS/Give#313)", () => { + it("opens modal, switches Story (9:16) and Square (1:1), shows masked VietQR hint, and downloads PNG", async () => { + const createUrl = vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:poster-url") + vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {}) + const clickedDownloads: string[] = [] + const origClick = HTMLAnchorElement.prototype.click + vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(function (this: HTMLAnchorElement) { + clickedDownloads.push(this.download) + }) + + try { + act(() => { + root.render(createElement(QrPosterButton, { data: posterFixture() })) + }) + + const trigger = container.querySelector("button")! + expect(trigger.textContent).toContain("Tải poster QR") + expect(trigger.className).toContain("btn-secondary") + expect(document.querySelector('[role="dialog"]')).toBeNull() + + act(() => { + trigger.click() + }) + + // Portaled into document.body (outside container) so sticky parents cannot trap z-index. + expect(container.querySelector('[role="dialog"]')).toBeNull() + const dialog = document.querySelector('[role="dialog"]')! + expect(dialog).not.toBeNull() + expect(dialog.parentElement?.parentElement).toBe(document.body) + expect(dialog.textContent).toContain("Vietcombank · •••• 6789") + expect(dialog.textContent).not.toContain("0123456789") + + const canvas = dialog.querySelector("canvas")! + expect(canvas.width).toBe(1080) + expect(canvas.height).toBe(1920) + expect(drawnText.some((t) => t.includes("Vietcombank · •••• 6789"))).toBe(true) + + // Tab / Shift+Tab focus trap cycles between first (Close) and last (Download) buttons. + const closeBtn = dialog.querySelector('button[aria-label="Đóng"]')! + const initialDownloadBtn = [...dialog.querySelectorAll("button")].find((b) => + b.textContent?.includes("Tải ảnh PNG") + )! + expect(document.activeElement).toBe(closeBtn) + act(() => { + document.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", shiftKey: true, cancelable: true })) + }) + expect(document.activeElement).toBe(initialDownloadBtn) + act(() => { + document.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", cancelable: true })) + }) + expect(document.activeElement).toBe(closeBtn) + + // Switch to Square (1:1) + const squareBtn = [...dialog.querySelectorAll("button")].find((b) => b.textContent?.includes("Vuông (1:1)"))! + drawnText = [] + act(() => { + squareBtn.click() + }) + expect(canvas.width).toBe(1080) + expect(canvas.height).toBe(1080) + expect(drawnText.some((t) => t.includes("VietQR chuyển khoản"))).toBe(true) + + // Download Square PNG + const downloadBtn = [...dialog.querySelectorAll("button")].find((b) => + b.textContent?.includes("Tải ảnh PNG (1:1)") + )! + await act(async () => { + downloadBtn.click() + }) + expect(createUrl).toHaveBeenCalledTimes(1) + expect(clickedDownloads).toEqual(["give-poster-xay-truong-ban-may-square.png"]) + + // Escape closes the dialog and returns focus to trigger + act(() => { + document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })) + }) + expect(document.querySelector('[role="dialog"]')).toBeNull() + expect(document.activeElement).toBe(trigger) + } finally { + HTMLAnchorElement.prototype.click = origClick + } + }) + + it("renders campaign-link QR only without VietQR payment text when vietQr is suppressed (#93)", () => { + act(() => { + root.render(createElement(QrPosterButton, { data: posterFixture({ vietQr: null }) })) + }) + + act(() => { + container.querySelector("button")!.click() + }) + + const dialog = document.querySelector('[role="dialog"]')! + expect(dialog.textContent).toContain("không gắn mã chuyển khoản") + expect(dialog.textContent).not.toContain("VietQR") + expect(dialog.textContent).not.toContain("Vietcombank") + expect(drawnText.some((t) => t.includes("VIETQR"))).toBe(false) + expect(drawnText.some((t) => t.includes("Quét mã QR để xem chiến dịch"))).toBe(true) + }) +}) diff --git a/apps/web/src/components/QrPosterButton.tsx b/apps/web/src/components/QrPosterButton.tsx new file mode 100644 index 00000000..e3545a90 --- /dev/null +++ b/apps/web/src/components/QrPosterButton.tsx @@ -0,0 +1,157 @@ +"use client" + +import clsx from "clsx" +import { useEffect, useId, useRef, useState, useSyncExternalStore } from "react" + +import { buttonClass } from "@/components/ui/Button" +import { DownloadIcon, QrCodeIcon } from "@/components/ui/icons" +import { ModalDialog } from "@/components/ui/ModalDialog" +import { trackShareClick } from "@/lib/analytics-client" +import { exportCanvasPng, renderPosterCanvas, waitForCanvasFonts } from "@/lib/canvas-cards" +import { POSTER_DIMENSIONS, type CampaignPosterData, type PosterFormat } from "@/lib/viral-sharing" + +const noSubscribe = () => () => {} + +/** + * "Tải poster QR" trigger and modal on public /campaigns/[slug] pages (DOS/Give#313). + * + * Lets supporters and organizers preview and download a Story (9:16) or Square (1:1) + * PNG poster generated entirely on a client-side canvas. VietQR payment data is + * strictly gated on the server (`data.vietQr === null` whenever payments are stopped + * or the campaign is not accepting donations). + */ +export function QrPosterButton({ data }: { data: CampaignPosterData }) { + const [open, setOpen] = useState(false) + const [format, setFormat] = useState("story") + const [status, setStatus] = useState(null) + const [busy, setBusy] = useState(false) + + const titleId = useId() + const triggerRef = useRef(null) + const canvasRef = useRef(null) + + const origin = useSyncExternalStore( + noSubscribe, + () => data.origin ?? window.location.origin, + () => data.origin ?? "" + ) + const campaignUrl = `${origin}${data.path}` + + useEffect(() => { + if (!open || !canvasRef.current) return + let cancelled = false + renderPosterCanvas(canvasRef.current, data, format, campaignUrl) + void waitForCanvasFonts().then(() => { + if (!cancelled && canvasRef.current) { + renderPosterCanvas(canvasRef.current, data, format, campaignUrl) + } + }) + return () => { + cancelled = true + } + }, [open, data, format, campaignUrl]) + + const handleDownload = async () => { + if (!canvasRef.current || busy) return + setBusy(true) + setStatus(null) + try { + await waitForCanvasFonts() + if (!canvasRef.current) return + renderPosterCanvas(canvasRef.current, data, format, campaignUrl) + const filename = `give-poster-${data.slug}-${format}.png` + const ok = await exportCanvasPng(canvasRef.current, filename) + if (ok) { + trackShareClick(data.campaignId) + setStatus("Đã tải poster PNG.") + } else { + setStatus("Không tạo được ảnh PNG. Hãy thử lại trên trình duyệt khác.") + } + } catch { + setStatus("Không tạo được ảnh PNG. Hãy thử lại trên trình duyệt khác.") + } finally { + setBusy(false) + } + } + + return ( + <> + + + setOpen(false)} + titleId={titleId} + title="Tải poster QR" + returnFocusRef={triggerRef} + > +

+ {data.vietQr + ? `Poster gồm mã QR trang chiến dịch và mã VietQR (${data.vietQr.bankName} · ${data.vietQr.maskedAccount}).` + : "Poster chỉ gắn mã QR dẫn tới trang chiến dịch (không gắn mã chuyển khoản)."} +

+ + {/* Format segmented control (DESIGN.md 6) */} +
+ {(["story", "square"] as const).map((option) => { + const active = format === option + return ( + + ) + })} +
+ +
+ +
+ +
+ +

+ {status} +

+
+
+ + ) +} diff --git a/apps/web/src/components/ThankYouCardButton.test.ts b/apps/web/src/components/ThankYouCardButton.test.ts new file mode 100644 index 00000000..a189de7c --- /dev/null +++ b/apps/web/src/components/ThankYouCardButton.test.ts @@ -0,0 +1,153 @@ +// @vitest-environment happy-dom +import { act, createElement } from "react" +import { createRoot, type Root } from "react-dom/client" +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" + +import { formatVnd } from "@/lib/format" +import { ANONYMOUS_DONOR_CARD_LABEL, type ThankYouCardInput } from "@/lib/viral-sharing" + +import { ThankYouCardButton } from "./ThankYouCardButton" + +declare global { + var IS_REACT_ACT_ENVIRONMENT: boolean | undefined +} + +let container: HTMLDivElement +let root: Root +let drawnText: string[] + +function createMockContext() { + return { + fillStyle: "", + strokeStyle: "", + lineWidth: 1, + font: "", + textAlign: "left", + textBaseline: "top", + fillRect: vi.fn(), + beginPath: vi.fn(), + moveTo: vi.fn(), + lineTo: vi.fn(), + quadraticCurveTo: vi.fn(), + closePath: vi.fn(), + fill: vi.fn(), + stroke: vi.fn(), + fillText: vi.fn((text: string) => { + drawnText.push(text) + }), + measureText: vi.fn((text: string) => ({ width: text.length * 14 })), + } +} + +function cardFixture(overrides: Partial = {}): ThankYouCardInput { + return { + kind: "donation", + referenceCode: "GVABCDEFG", + amount: 250_000, + campaignTitle: "Bữa trưa cho em", + campaignSlug: "bua-trua-cho-em", + campaignType: "give", + donorName: "Nguyễn Minh", + isAnonymous: false, + createdAt: "2026-11-20T03:00:00.000Z", + origin: "https://give.vn", + ...overrides, + } +} + +beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true + drawnText = [] + container = document.createElement("div") + document.body.append(container) + root = createRoot(container) + vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation( + () => createMockContext() as unknown as CanvasRenderingContext2D + ) + vi.spyOn(HTMLCanvasElement.prototype, "toBlob").mockImplementation((cb) => { + cb(new Blob(["png"], { type: "image/png" })) + }) +}) + +afterEach(() => { + act(() => root.unmount()) + container.remove() + vi.restoreAllMocks() +}) + +describe("ThankYouCardButton (DOS/Give#313)", () => { + it("shows VND amount clearly by default and completely omits it when the privacy toggle is enabled", async () => { + const createUrl = vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:thankyou-url") + vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {}) + const clickedDownloads: string[] = [] + vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(function (this: HTMLAnchorElement) { + clickedDownloads.push(this.download) + }) + + act(() => { + root.render(createElement(ThankYouCardButton, { card: cardFixture() })) + }) + + const trigger = container.querySelector("button")! + expect(trigger.textContent).toContain("Tôi đã chung tay") + + act(() => { + trigger.click() + }) + + // Portaled into document.body (outside container / role="status") + expect(container.querySelector('[role="dialog"]')).toBeNull() + const dialog = document.querySelector('[role="dialog"]')! + expect(dialog).not.toBeNull() + expect(dialog.textContent).toContain("Nguyễn Minh") + expect(dialog.textContent).toContain("GVABCDEFG") + expect(dialog.textContent).toContain(formatVnd(250_000)) + expect(drawnText).toContain(formatVnd(250_000)) + expect(drawnText).toContain("Tôi đã chung tay") + expect(drawnText).toContain("GVABCDEFG") + + // Toggle "Ẩn số tiền trên thẻ" + const checkbox = dialog.querySelector('input[type="checkbox"]')! + expect(checkbox.checked).toBe(false) + + drawnText = [] + act(() => { + checkbox.click() + }) + expect(checkbox.checked).toBe(true) + expect(dialog.textContent).toContain("Đã ẩn theo lựa chọn của bạn") + expect(dialog.textContent).not.toContain("250.000") + expect(drawnText.join(" ")).not.toContain("250.000") + expect(drawnText.join(" ")).not.toContain("250000") + + // Download PNG + const downloadBtn = [...dialog.querySelectorAll("button")].find((b) => b.textContent?.includes("Tải ảnh PNG"))! + await act(async () => { + downloadBtn.click() + }) + expect(createUrl).toHaveBeenCalledTimes(1) + expect(clickedDownloads).toEqual(["give-chung-tay-gvabcdefg.png"]) + }) + + it("renders anonymous donor label when isAnonymous is true without leaking donorName", () => { + act(() => { + root.render( + createElement(ThankYouCardButton, { + card: cardFixture({ donorName: "Tên riêng tư", isAnonymous: true }), + }) + ) + }) + + act(() => { + container.querySelector("button")!.click() + }) + + // Portaled into document.body (outside container / role="status") + expect(container.querySelector('[role="dialog"]')).toBeNull() + const dialog = document.querySelector('[role="dialog"]')! + expect(dialog.textContent).toContain(ANONYMOUS_DONOR_CARD_LABEL) + expect(dialog.textContent).not.toContain("Tên riêng tư") + expect(drawnText).toContain(ANONYMOUS_DONOR_CARD_LABEL) + expect(drawnText.join(" ")).not.toContain("Tên riêng tư") + }) +}) diff --git a/apps/web/src/components/ThankYouCardButton.tsx b/apps/web/src/components/ThankYouCardButton.tsx new file mode 100644 index 00000000..41b9b88b --- /dev/null +++ b/apps/web/src/components/ThankYouCardButton.tsx @@ -0,0 +1,161 @@ +"use client" + +import { useEffect, useId, useMemo, useRef, useState } from "react" + +import { buttonClass, type ButtonSize } from "@/components/ui/Button" +import { DownloadIcon, HeartIcon } from "@/components/ui/icons" +import { ModalDialog } from "@/components/ui/ModalDialog" +import { RefCode } from "@/components/ui/RefCode" +import { exportCanvasPng, renderThankYouCanvas, waitForCanvasFonts } from "@/lib/canvas-cards" +import { buildThankYouCardModel, type ThankYouCardInput } from "@/lib/viral-sharing" + +/** + * Shareable "Tôi đã chung tay" thank-you card button and modal (DOS/Give#313). + * + * Available only for matched/received contributions on /donations/[code] and + * /me/contributions. Exports a 1080x1080 PNG on a client-side canvas with a + * user-controlled toggle to hide/show the VND amount (shown clearly by default). + * Zero PII or bank details are accepted or rendered. + */ +export function ThankYouCardButton({ + card, + size = "md", + label = "Tải thẻ “Tôi đã chung tay”", + className, +}: { + card: ThankYouCardInput + size?: ButtonSize + label?: string + className?: string +}) { + const [open, setOpen] = useState(false) + const [hideAmount, setHideAmount] = useState(false) + const [status, setStatus] = useState(null) + const [busy, setBusy] = useState(false) + + const titleId = useId() + const toggleId = useId() + const triggerRef = useRef(null) + const canvasRef = useRef(null) + + const model = useMemo(() => buildThankYouCardModel(card, { hideAmount }), [card, hideAmount]) + + useEffect(() => { + if (!open || !canvasRef.current) return + let cancelled = false + renderThankYouCanvas(canvasRef.current, model) + void waitForCanvasFonts().then(() => { + if (!cancelled && canvasRef.current) { + renderThankYouCanvas(canvasRef.current, model) + } + }) + return () => { + cancelled = true + } + }, [open, model]) + + const handleDownload = async () => { + if (!canvasRef.current || busy) return + setBusy(true) + setStatus(null) + try { + await waitForCanvasFonts() + if (!canvasRef.current) return + renderThankYouCanvas(canvasRef.current, model) + const filename = `give-chung-tay-${model.referenceCode.toLowerCase()}.png` + const ok = await exportCanvasPng(canvasRef.current, filename) + setStatus(ok ? "Đã tải thẻ cảm ơn PNG." : "Không tạo được ảnh PNG. Hãy thử lại trên trình duyệt khác.") + } catch { + setStatus("Không tạo được ảnh PNG. Hãy thử lại trên trình duyệt khác.") + } finally { + setBusy(false) + } + } + + return ( + <> + + + setOpen(false)} + titleId={titleId} + title="Thẻ “Tôi đã chung tay”" + returnFocusRef={triggerRef} + > +

+ Tải ảnh cảm ơn để chia sẻ lên mạng xã hội. Thẻ chỉ hiển thị tên hiển thị, chiến dịch và mã đối chiếu sao kê — + không chứa thông tin cá nhân hay tài khoản ngân hàng. +

+ + + +
+ +
+ +
+
+
Tên hiển thị
+
{model.donorName}
+
+
+
Số tiền trên thẻ
+
{model.amountText ?? "Đã ẩn theo lựa chọn của bạn"}
+
+
+
Mã đối chiếu
+
+ {model.referenceCode} +
+
+
+ +
+ +

+ {status} +

+
+
+ + ) +} diff --git a/apps/web/src/components/ui/ModalDialog.tsx b/apps/web/src/components/ui/ModalDialog.tsx new file mode 100644 index 00000000..ac0e6b9f --- /dev/null +++ b/apps/web/src/components/ui/ModalDialog.tsx @@ -0,0 +1,121 @@ +"use client" + +import { useEffect, useRef, type ReactNode, type RefObject } from "react" +import { createPortal } from "react-dom" + +import { CloseIcon } from "@/components/ui/icons" + +const FOCUSABLE_SELECTOR = + 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])' + +/** + * Accessible modal dialog rendered via React Portal into `document.body` so it + * never gets trapped inside a sticky stacking context or an aria-live region. + * + * Implements Escape close, backdrop click close, Tab/Shift+Tab focus trapping, + * body scroll lock while open, and focus restoration to `returnFocusRef`. + */ +export function ModalDialog({ + open, + onClose, + titleId, + title, + returnFocusRef, + children, +}: { + open: boolean + onClose: () => void + titleId: string + title: string + returnFocusRef?: RefObject + children: ReactNode +}) { + const dialogRef = useRef(null) + const closeRef = useRef(null) + const wasOpenRef = useRef(false) + const onCloseRef = useRef(onClose) + + useEffect(() => { + onCloseRef.current = onClose + }, [onClose]) + + useEffect(() => { + if (!open) { + if (wasOpenRef.current) { + wasOpenRef.current = false + returnFocusRef?.current?.focus() + } + return + } + wasOpenRef.current = true + closeRef.current?.focus() + + const previousOverflow = document.body.style.overflow + document.body.style.overflow = "hidden" + + const onKeyDown = (event: KeyboardEvent) => { + if (event.key === "Escape") { + event.preventDefault() + onCloseRef.current() + return + } + if (event.key !== "Tab" || !dialogRef.current) return + const focusables = [...dialogRef.current.querySelectorAll(FOCUSABLE_SELECTOR)] + if (focusables.length === 0) return + const first = focusables[0]! + const last = focusables[focusables.length - 1]! + const active = document.activeElement + if (event.shiftKey) { + if (active === first || !dialogRef.current.contains(active)) { + event.preventDefault() + last.focus() + } + } else if (active === last || !dialogRef.current.contains(active)) { + event.preventDefault() + first.focus() + } + } + + document.addEventListener("keydown", onKeyDown) + return () => { + document.removeEventListener("keydown", onKeyDown) + document.body.style.overflow = previousOverflow + } + }, [open, returnFocusRef]) + + if (!open || typeof document === "undefined") return null + + return createPortal( +
{ + if (event.target === event.currentTarget) onClose() + }} + > +
+
+

+ {title} +

+ +
+ {children} +
+
, + document.body + ) +} diff --git a/apps/web/src/components/ui/icons.tsx b/apps/web/src/components/ui/icons.tsx index f95c17dc..c142cefa 100644 --- a/apps/web/src/components/ui/icons.tsx +++ b/apps/web/src/components/ui/icons.tsx @@ -161,3 +161,18 @@ export const MessageIcon = (p: SVGProps) => ( ) + +export const QrCodeIcon = (p: SVGProps) => ( + + + + + + +) + +export const DownloadIcon = (p: SVGProps) => ( + + + +) diff --git a/apps/web/src/lib/canvas-cards.ts b/apps/web/src/lib/canvas-cards.ts new file mode 100644 index 00000000..4f629634 --- /dev/null +++ b/apps/web/src/lib/canvas-cards.ts @@ -0,0 +1,678 @@ +import { + displayShortUrl, + encodeQrMatrix, + POSTER_DIMENSIONS, + type CampaignPosterData, + type PosterFormat, + type QrMatrix, + type ThankYouCardModel, +} from "./viral-sharing" + +/** + * Client-side HTML5 Canvas renderers for Give viral-sharing PNGs (DOS/Give#313): + * - Downloadable QR Poster (Story 9:16 = 1080x1920, Square 1:1 = 1080x1080) + * - Shareable "Tôi đã chung tay" Thank-You Card (1080x1080) + * + * Follows DESIGN.md colors, low corner radii, Be Vietnam Pro typography, and + * monospace reference codes. Pure client-side; zero external network requests. + */ + +const SANS_FONT = '"Be Vietnam Pro", system-ui, -apple-system, "Segoe UI", Roboto, sans-serif' +const MONO_FONT = "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace" + +const COLORS = { + bg: "#FFFFFF", + surface: "#F7F8FA", + border: "#E6E8EC", + text: "#111318", + muted: "#5B6270", + primary: "#047857", + primarySoft: "#ECFDF5", + accent: "#C2410C", + accentSoft: "#FFF7ED", +} as const + +function fillRoundedRect( + ctx: CanvasRenderingContext2D, + x: number, + y: number, + width: number, + height: number, + radius: number, + fill: string, + stroke?: string, + lineWidth = 2 +) { + const r = Math.max(0, Math.min(radius, width / 2, height / 2)) + ctx.beginPath() + ctx.moveTo(x + r, y) + ctx.lineTo(x + width - r, y) + ctx.quadraticCurveTo(x + width, y, x + width, y + r) + ctx.lineTo(x + width, y + height - r) + ctx.quadraticCurveTo(x + width, y + height, x + width - r, y + height) + ctx.lineTo(x + r, y + height) + ctx.quadraticCurveTo(x, y + height, x, y + height - r) + ctx.lineTo(x, y + r) + ctx.quadraticCurveTo(x, y, x + r, y) + ctx.closePath() + ctx.fillStyle = fill + ctx.fill() + if (stroke) { + ctx.strokeStyle = stroke + ctx.lineWidth = lineWidth + ctx.stroke() + } +} + +function truncateSingleLine(ctx: CanvasRenderingContext2D, text: string, maxWidth: number): string { + if (ctx.measureText(text).width <= maxWidth) return text + let chars = Array.from(text) + while (chars.length > 1 && ctx.measureText(`${chars.join("").trimEnd()}…`).width > maxWidth) { + chars = chars.slice(0, -1) + } + return `${chars.join("").trimEnd()}…` +} + +/** Splits text into at most `maxLines` lines that fit within `maxWidth`, adding an ellipsis if truncated. */ +export function wrapCanvasLines( + ctx: CanvasRenderingContext2D, + text: string, + maxWidth: number, + maxLines: number +): string[] { + const words = text.replace(/\s+/g, " ").trim().split(" ").filter(Boolean) + if (words.length === 0 || maxLines <= 0) return [] + + const lines: string[] = [] + let current = "" + + for (let i = 0; i < words.length; i++) { + const word = words[i]! + const candidate = current ? `${current} ${word}` : word + if (ctx.measureText(candidate).width <= maxWidth) { + current = candidate + continue + } + if (current) { + lines.push(truncateSingleLine(ctx, current, maxWidth)) + current = word + } else { + lines.push(truncateSingleLine(ctx, word, maxWidth)) + current = "" + } + if (lines.length === maxLines) { + return appendEllipsis(ctx, lines, maxWidth) + } + } + + if (current) { + if (lines.length < maxLines) { + lines.push(truncateSingleLine(ctx, current, maxWidth)) + } else { + return appendEllipsis(ctx, lines, maxWidth) + } + } + + return lines +} + +function appendEllipsis(ctx: CanvasRenderingContext2D, lines: string[], maxWidth: number): string[] { + const out = [...lines] + const lastIndex = out.length - 1 + if (lastIndex < 0) return out + const existing = out[lastIndex]! + if (existing.endsWith("…") && ctx.measureText(existing).width <= maxWidth) return out + let chars = Array.from(existing.replace(/…$/, "")) + while (chars.length > 1 && ctx.measureText(`${chars.join("").trimEnd()}…`).width > maxWidth) { + chars = chars.slice(0, -1) + } + out[lastIndex] = `${chars.join("").trimEnd()}…` + return out +} + +/** Draws a QR matrix sharply on a white background with exact integer pixel alignment. */ +export function drawQrMatrix(ctx: CanvasRenderingContext2D, matrix: QrMatrix, x: number, y: number, boxSize: number) { + ctx.fillStyle = "#FFFFFF" + ctx.fillRect(x, y, boxSize, boxSize) + + if (matrix.size <= 0 || matrix.bits.length < matrix.size * matrix.size) return + const cell = Math.floor(boxSize / matrix.size) + if (cell <= 0) return + const renderedSize = cell * matrix.size + const offsetX = Math.floor(x + (boxSize - renderedSize) / 2) + const offsetY = Math.floor(y + (boxSize - renderedSize) / 2) + + ctx.fillStyle = COLORS.text + for (let row = 0; row < matrix.size; row++) { + const rowStart = row * matrix.size + for (let col = 0; col < matrix.size; col++) { + if (matrix.bits[rowStart + col] === "1") { + ctx.fillRect(offsetX + col * cell, offsetY + row * cell, cell, cell) + } + } + } +} + +function drawBadge( + ctx: CanvasRenderingContext2D, + text: string, + x: number, + y: number, + options: { bg: string; fg: string; fontSize?: number; height?: number; padX?: number } +): number { + const fontSize = options.fontSize ?? 24 + const height = options.height ?? 48 + const padX = options.padX ?? 20 + ctx.font = `700 ${fontSize}px ${SANS_FONT}` + const textWidth = ctx.measureText(text).width + const width = Math.ceil(textWidth + padX * 2) + fillRoundedRect(ctx, x, y, width, height, 8, options.bg) + ctx.fillStyle = options.fg + ctx.textBaseline = "middle" + ctx.fillText(text, x + padX, y + height / 2 + 1) + return width +} + +function drawGiveBrand(ctx: CanvasRenderingContext2D, rightEdge: number, y: number) { + ctx.font = `700 34px ${SANS_FONT}` + const labelWidth = ctx.measureText("Give").width + const markSize = 44 + const gap = 12 + const startX = rightEdge - (markSize + gap + labelWidth) + + fillRoundedRect(ctx, startX, y, markSize, markSize, 8, COLORS.primary) + ctx.fillStyle = "#FFFFFF" + ctx.font = `700 28px ${SANS_FONT}` + ctx.textAlign = "center" + ctx.textBaseline = "middle" + ctx.fillText("G", startX + markSize / 2, y + markSize / 2 + 1) + + ctx.textAlign = "left" + ctx.fillStyle = COLORS.text + ctx.font = `700 34px ${SANS_FONT}` + ctx.fillText("Give", startX + markSize + gap, y + markSize / 2 + 1) +} + +/** + * Renders the campaign QR poster onto `canvas` at full export resolution + * (1080x1920 for Story 9:16, 1080x1080 for Square 1:1). + */ +export function renderPosterCanvas( + canvas: HTMLCanvasElement, + data: CampaignPosterData, + format: PosterFormat, + campaignUrl: string +) { + const { width, height } = POSTER_DIMENSIONS[format] + canvas.width = width + canvas.height = height + const ctx = canvas.getContext("2d") + if (!ctx) return + + const isStory = format === "story" + const isGive = data.type === "give" + const topBarColor = isGive ? COLORS.primary : COLORS.accent + const badgeBg = isGive ? COLORS.primarySoft : COLORS.accentSoft + const badgeFg = isGive ? COLORS.primary : COLORS.accent + const padX = 72 + const contentW = width - padX * 2 + const shortUrl = (() => { + try { + const parsed = new URL(campaignUrl) + return `${parsed.host}${parsed.pathname}` + } catch { + return displayShortUrl(data.origin, data.path) + } + })() + const linkQr = encodeQrMatrix(campaignUrl) + + // Background and top brand rule + ctx.fillStyle = COLORS.bg + ctx.fillRect(0, 0, width, height) + ctx.fillStyle = topBarColor + ctx.fillRect(0, 0, width, 16) + + // Header row: type badge (+ verified statement badge) and Give brand + const headerY = isStory ? 84 : 56 + ctx.textAlign = "left" + const typeW = drawBadge(ctx, data.typeBadge, padX, headerY, { bg: badgeBg, fg: badgeFg }) + if (data.verifiedStatementBadge) { + drawBadge(ctx, data.verifiedStatementBadge, padX + typeW + 14, headerY, { + bg: COLORS.primarySoft, + fg: COLORS.primary, + fontSize: 22, + }) + } + drawGiveBrand(ctx, width - padX, headerY + 2) + + // Campaign title + let cursorY = isStory ? 188 : 140 + const titleFontSize = isStory ? 54 : 42 + const titleLineHeight = isStory ? 70 : 54 + ctx.font = `700 ${titleFontSize}px ${SANS_FONT}` + ctx.fillStyle = COLORS.text + ctx.textBaseline = "top" + const titleLines = wrapCanvasLines(ctx, data.title, contentW, isStory ? 3 : 2) + for (const line of titleLines) { + ctx.fillText(line, padX, cursorY) + cursorY += titleLineHeight + } + + // Organizer line + if (data.organizerName) { + cursorY += isStory ? 16 : 10 + ctx.font = `500 ${isStory ? 28 : 24}px ${SANS_FONT}` + ctx.fillStyle = COLORS.muted + const verifiedSuffix = data.organizerVerified ? " · Đã xác minh" : "" + const orgLine = wrapCanvasLines(ctx, `${data.organizerName}${verifiedSuffix}`, contentW, 1)[0] ?? "" + ctx.fillText(orgLine, padX, cursorY) + cursorY += isStory ? 44 : 36 + } + + // Funding progress card + cursorY += isStory ? 28 : 20 + const fundingH = isStory ? (data.showProgressBar ? 196 : 156) : data.showProgressBar ? 154 : 124 + fillRoundedRect(ctx, padX, cursorY, contentW, fundingH, 12, COLORS.surface, COLORS.border, 2) + + const innerX = padX + 32 + const innerW = contentW - 64 + const figureY = cursorY + (isStory ? 32 : 24) + ctx.textBaseline = "top" + ctx.font = `700 ${isStory ? 46 : 38}px ${SANS_FONT}` + ctx.fillStyle = COLORS.text + ctx.fillText(data.raisedText, innerX, figureY) + + ctx.textAlign = "right" + ctx.font = `700 ${isStory ? 38 : 32}px ${SANS_FONT}` + ctx.fillStyle = COLORS.primary + ctx.fillText(`${data.percent}%`, innerX + innerW, figureY + 4) + + ctx.textAlign = "left" + const subY = figureY + (isStory ? 60 : 48) + ctx.font = `400 ${isStory ? 24 : 21}px ${SANS_FONT}` + ctx.fillStyle = COLORS.muted + ctx.fillText(`${data.raisedLabel} · ${data.goalText}`, innerX, subY) + + if (data.showProgressBar) { + const barY = subY + (isStory ? 46 : 38) + const barH = 16 + fillRoundedRect(ctx, innerX, barY, innerW, barH, 6, COLORS.border) + const fillW = Math.round((innerW * Math.max(0, Math.min(100, data.percent))) / 100) + if (fillW > 0) { + fillRoundedRect(ctx, innerX, barY, Math.max(12, fillW), barH, 6, COLORS.primary) + } + } + + cursorY += fundingH + (isStory ? 48 : 28) + + // QR section + const footerH = isStory ? 120 : 88 + const qrAreaH = height - footerH - cursorY - (isStory ? 24 : 18) + + if (data.vietQr) { + // Two QR boxes: VietQR direct transfer + Campaign link + if (isStory) { + const gap = 32 + const boxH = Math.floor((qrAreaH - gap) / 2) + drawHorizontalQrCard(ctx, { + x: padX, + y: cursorY, + width: contentW, + height: boxH, + qr: data.vietQr.qr, + eyebrow: "VIETQR CHUYỂN KHOẢN", + eyebrowColor: COLORS.primary, + title: "Quét bằng app ngân hàng", + detail: `${data.vietQr.bankName} · ${data.vietQr.maskedAccount}`, + caption: "Chuyển thẳng vào tài khoản nhận đã xác minh của chiến dịch.", + }) + drawHorizontalQrCard(ctx, { + x: padX, + y: cursorY + boxH + gap, + width: contentW, + height: boxH, + qr: linkQr, + eyebrow: "TRANG CHIẾN DỊCH", + eyebrowColor: COLORS.muted, + title: "Xem sao kê & nhận mã ủng hộ", + detail: shortUrl, + caption: "Quét camera để theo dõi sao kê công khai và nhận mã đối chiếu riêng.", + }) + } else { + const gap = 28 + const colW = Math.floor((contentW - gap) / 2) + drawCompactQrCard(ctx, { + x: padX, + y: cursorY, + width: colW, + height: qrAreaH, + qr: data.vietQr.qr, + title: "VietQR chuyển khoản", + subtitle: `${data.vietQr.bankName} · ${data.vietQr.maskedAccount}`, + highlight: true, + }) + drawCompactQrCard(ctx, { + x: padX + colW + gap, + y: cursorY, + width: colW, + height: qrAreaH, + qr: linkQr, + title: "Trang chiến dịch & sao kê", + subtitle: shortUrl, + highlight: false, + }) + } + } else { + // Campaign-link QR ONLY (payments_stopped_at set, closed/back campaign, or no usable account) + fillRoundedRect(ctx, padX, cursorY, contentW, qrAreaH, 12, COLORS.surface, COLORS.border, 2) + const qrSize = isStory ? Math.min(540, qrAreaH - 220) : Math.min(310, qrAreaH - 130) + const qrX = Math.floor(padX + (contentW - qrSize) / 2) + const qrY = Math.floor(cursorY + (isStory ? 64 : 28)) + fillRoundedRect(ctx, qrX - 16, qrY - 16, qrSize + 32, qrSize + 32, 10, "#FFFFFF", COLORS.border, 2) + drawQrMatrix(ctx, linkQr, qrX, qrY, qrSize) + + ctx.textAlign = "center" + ctx.textBaseline = "top" + ctx.font = `700 ${isStory ? 34 : 26}px ${SANS_FONT}` + ctx.fillStyle = COLORS.text + ctx.fillText("Quét mã QR để xem chiến dịch", width / 2, qrY + qrSize + (isStory ? 44 : 26)) + + ctx.font = `500 ${isStory ? 26 : 21}px ${SANS_FONT}` + ctx.fillStyle = COLORS.primary + const urlLine = wrapCanvasLines(ctx, shortUrl, contentW - 80, 1)[0] ?? shortUrl + ctx.fillText(urlLine, width / 2, qrY + qrSize + (isStory ? 96 : 64)) + ctx.textAlign = "left" + } + + // Footer transparency rule + const footerY = height - footerH + ctx.strokeStyle = COLORS.border + ctx.lineWidth = 2 + ctx.beginPath() + ctx.moveTo(padX, footerY) + ctx.lineTo(width - padX, footerY) + ctx.stroke() + + ctx.textAlign = "center" + ctx.textBaseline = "middle" + ctx.font = `600 ${isStory ? 24 : 21}px ${SANS_FONT}` + ctx.fillStyle = COLORS.primary + const footerCopy = isGive + ? "give.vn · Sao kê đối chiếu ngân hàng · Give không giữ tiền" + : "give.vn · Gây quỹ minh bạch · Sao kê công khai" + ctx.fillText(footerCopy, width / 2, footerY + footerH / 2) + ctx.textAlign = "left" +} + +function drawHorizontalQrCard( + ctx: CanvasRenderingContext2D, + opts: { + x: number + y: number + width: number + height: number + qr: QrMatrix + eyebrow: string + eyebrowColor: string + title: string + detail: string + caption: string + } +) { + fillRoundedRect(ctx, opts.x, opts.y, opts.width, opts.height, 12, COLORS.surface, COLORS.border, 2) + const pad = 36 + const qrBoxSize = Math.min(opts.height - pad * 2, 340) + const qrX = opts.x + pad + const qrY = Math.floor(opts.y + (opts.height - qrBoxSize) / 2) + + fillRoundedRect(ctx, qrX - 10, qrY - 10, qrBoxSize + 20, qrBoxSize + 20, 8, "#FFFFFF", COLORS.border, 2) + drawQrMatrix(ctx, opts.qr, qrX, qrY, qrBoxSize) + + const textX = qrX + qrBoxSize + 40 + const textW = opts.x + opts.width - pad - textX + let y = qrY + 12 + + ctx.textAlign = "left" + ctx.textBaseline = "top" + ctx.font = `700 22px ${SANS_FONT}` + ctx.fillStyle = opts.eyebrowColor + ctx.fillText(opts.eyebrow, textX, y) + y += 40 + + ctx.font = `700 32px ${SANS_FONT}` + ctx.fillStyle = COLORS.text + const titleLines = wrapCanvasLines(ctx, opts.title, textW, 2) + for (const line of titleLines) { + ctx.fillText(line, textX, y) + y += 42 + } + + y += 10 + ctx.font = `600 26px ${SANS_FONT}` + ctx.fillStyle = COLORS.primary + const detailLines = wrapCanvasLines(ctx, opts.detail, textW, 2) + for (const line of detailLines) { + ctx.fillText(line, textX, y) + y += 34 + } + + y += 12 + ctx.font = `400 22px ${SANS_FONT}` + ctx.fillStyle = COLORS.muted + const capLines = wrapCanvasLines(ctx, opts.caption, textW, 3) + for (const line of capLines) { + ctx.fillText(line, textX, y) + y += 30 + } +} + +function drawCompactQrCard( + ctx: CanvasRenderingContext2D, + opts: { + x: number + y: number + width: number + height: number + qr: QrMatrix + title: string + subtitle: string + highlight: boolean + } +) { + fillRoundedRect( + ctx, + opts.x, + opts.y, + opts.width, + opts.height, + 12, + opts.highlight ? COLORS.primarySoft : COLORS.surface, + opts.highlight ? COLORS.primary : COLORS.border, + 2 + ) + const qrSize = Math.min(opts.width - 96, opts.height - 150, 290) + const qrX = Math.floor(opts.x + (opts.width - qrSize) / 2) + const qrY = opts.y + 28 + + fillRoundedRect(ctx, qrX - 10, qrY - 10, qrSize + 20, qrSize + 20, 8, "#FFFFFF", COLORS.border, 2) + drawQrMatrix(ctx, opts.qr, qrX, qrY, qrSize) + + ctx.textAlign = "center" + ctx.textBaseline = "top" + const centerX = opts.x + opts.width / 2 + ctx.font = `700 24px ${SANS_FONT}` + ctx.fillStyle = COLORS.text + ctx.fillText(opts.title, centerX, qrY + qrSize + 24) + + ctx.font = `600 20px ${SANS_FONT}` + ctx.fillStyle = opts.highlight ? COLORS.primary : COLORS.muted + const sub = wrapCanvasLines(ctx, opts.subtitle, opts.width - 40, 1)[0] ?? opts.subtitle + ctx.fillText(sub, centerX, qrY + qrSize + 60) + ctx.textAlign = "left" +} + +/** + * Renders the 1080x1080 "Tôi đã chung tay" shareable thank-you card onto `canvas`. + * Strictly omits any VND figure when `model.amountText === null`. + */ +export function renderThankYouCanvas(canvas: HTMLCanvasElement, model: ThankYouCardModel) { + const size = 1080 + canvas.width = size + canvas.height = size + const ctx = canvas.getContext("2d") + if (!ctx) return + + const padX = 80 + const contentW = size - padX * 2 + + ctx.fillStyle = COLORS.bg + ctx.fillRect(0, 0, size, size) + ctx.fillStyle = COLORS.primary + ctx.fillRect(0, 0, size, 18) + + // Top bar: Give wordmark & badge + const headerY = 64 + ctx.textAlign = "left" + drawBadge(ctx, model.typeBadge, padX, headerY, { + bg: model.typeBadge === "Dự án" ? COLORS.accentSoft : COLORS.primarySoft, + fg: model.typeBadge === "Dự án" ? COLORS.accent : COLORS.primary, + }) + drawGiveBrand(ctx, size - padX, headerY + 2) + + // Headline banner + let y = 168 + fillRoundedRect(ctx, padX, y, contentW, 196, 12, COLORS.primarySoft) + ctx.textAlign = "left" + ctx.textBaseline = "top" + ctx.font = `700 58px ${SANS_FONT}` + ctx.fillStyle = COLORS.primary + ctx.fillText(model.headline, padX + 40, y + 36) + + ctx.font = `600 32px ${SANS_FONT}` + ctx.fillStyle = COLORS.text + const donorLine = wrapCanvasLines(ctx, model.donorName, contentW - 80, 1)[0] ?? model.donorName + ctx.fillText(donorLine, padX + 40, y + 118) + y += 236 + + // Campaign title block + ctx.font = `500 24px ${SANS_FONT}` + ctx.fillStyle = COLORS.muted + ctx.fillText("Chiến dịch", padX, y) + y += 38 + + ctx.font = `700 40px ${SANS_FONT}` + ctx.fillStyle = COLORS.text + const titleLines = wrapCanvasLines(ctx, model.campaignTitle, contentW, 3) + for (const line of titleLines) { + ctx.fillText(line, padX, y) + y += 52 + } + + // Amount & verification card + y = Math.max(y + 32, 620) + const cardH = 260 + fillRoundedRect(ctx, padX, y, contentW, cardH, 12, COLORS.surface, COLORS.border, 2) + + const innerX = padX + 40 + const innerW = contentW - 80 + + ctx.textAlign = "left" + ctx.textBaseline = "top" + ctx.font = `500 24px ${SANS_FONT}` + ctx.fillStyle = COLORS.muted + ctx.fillText(model.amountCaption, innerX, y + 32) + + if (model.amountText !== null) { + ctx.font = `700 52px ${SANS_FONT}` + ctx.fillStyle = COLORS.primary + ctx.fillText(model.amountText, innerX, y + 72, innerW) + } else { + ctx.font = `600 28px ${SANS_FONT}` + ctx.fillStyle = COLORS.text + const hiddenLines = wrapCanvasLines(ctx, "Số tiền được ẩn theo lựa chọn của người ủng hộ", innerW, 2) + hiddenLines.forEach((line, index) => { + ctx.fillText(line, innerX, y + 74 + index * 36) + }) + } + + // Divider inside summary card + const divY = y + 158 + ctx.strokeStyle = COLORS.border + ctx.lineWidth = 2 + ctx.beginPath() + ctx.moveTo(innerX, divY) + ctx.lineTo(innerX + innerW, divY) + ctx.stroke() + + // Verification code (monospace per DESIGN.md Reference codes) & date + ctx.font = `500 22px ${SANS_FONT}` + ctx.fillStyle = COLORS.muted + ctx.fillText("Mã đối chiếu sao kê", innerX, divY + 20) + + ctx.font = `700 34px ${MONO_FONT}` + ctx.fillStyle = COLORS.text + ctx.fillText(model.referenceCode, innerX, divY + 52) + + if (model.dateText) { + ctx.textAlign = "right" + ctx.font = `500 22px ${SANS_FONT}` + ctx.fillStyle = COLORS.muted + ctx.fillText("Ngày ghi nhận", innerX + innerW, divY + 20) + + ctx.font = `600 28px ${SANS_FONT}` + ctx.fillStyle = COLORS.text + ctx.fillText(model.dateText, innerX + innerW, divY + 54) + ctx.textAlign = "left" + } + + // Transparency footer + const footerTop = 948 + ctx.strokeStyle = COLORS.border + ctx.lineWidth = 2 + ctx.beginPath() + ctx.moveTo(padX, footerTop) + ctx.lineTo(size - padX, footerTop) + ctx.stroke() + + ctx.textAlign = "center" + ctx.textBaseline = "top" + ctx.font = `600 22px ${SANS_FONT}` + ctx.fillStyle = COLORS.primary + ctx.fillText(model.footerText, size / 2, footerTop + 26) + + ctx.font = `400 20px ${SANS_FONT}` + ctx.fillStyle = COLORS.muted + const urlLine = wrapCanvasLines(ctx, `Sao kê: ${model.statementUrlText}`, contentW, 1)[0] ?? model.statementUrlText + ctx.fillText(urlLine, size / 2, footerTop + 64) + ctx.textAlign = "left" +} + +/** Waits for web fonts (Be Vietnam Pro) to settle before drawing or exporting canvas text. */ +export async function waitForCanvasFonts(): Promise { + if (typeof document !== "undefined" && "fonts" in document && document.fonts?.ready) { + try { + await document.fonts.ready + } catch { + // Proceed with fallback system font if FontFaceSet rejects. + } + } +} + +/** Exports an HTMLCanvasElement as a PNG file download; returns false if the browser cannot encode a blob. */ +export async function exportCanvasPng(canvas: HTMLCanvasElement, filename: string): Promise { + return new Promise((resolve) => { + canvas.toBlob((blob) => { + if (!blob) { + resolve(false) + return + } + const url = URL.createObjectURL(blob) + const link = document.createElement("a") + link.href = url + link.download = filename + link.click() + setTimeout(() => URL.revokeObjectURL(url), 10_000) + resolve(true) + }, "image/png") + }) +} diff --git a/apps/web/src/lib/viral-sharing.test.ts b/apps/web/src/lib/viral-sharing.test.ts new file mode 100644 index 00000000..0b9bf69d --- /dev/null +++ b/apps/web/src/lib/viral-sharing.test.ts @@ -0,0 +1,370 @@ +import { describe, expect, it } from "vitest" + +import type { CampaignStatus } from "./campaigns" +import { formatVnd } from "./format" +import type { MoneyTotals } from "./statement" +import { + ANONYMOUS_DONOR_CARD_LABEL, + buildOgCampaignCardModel, + buildThankYouCardModel, + DEFAULT_DONOR_CARD_LABEL, + displayShortUrl, + encodeQrMatrix, + formatPosterBankHint, + isOgEligible, + isThankYouCardEligible, + resolveThankYouDonorName, + shouldIncludePosterVietQr, + truncateCodePoints, + verifiedStatementLabel, +} from "./viral-sharing" + +function totalsFixture(overrides: Partial = {}): MoneyTotals { + return { + campaign_id: "33333333-3333-4333-8333-333333333333", + type: "give", + asset: "VND", + goal_amount: 100_000_000, + pledged_amount: 0, + paid_amount: 45_000_000, + disbursable_amount: 45_000_000, + disbursed_amount: 10_000_000, + refunded_amount: 0, + unexplained_out_amount: 0, + unexplained_out_count: 0, + supporters_count: 18, + other_in_amount: 5_000_000, + refund_owed_amount: 0, + backers_count: 0, + payments_stopped_at: null, + payments_stopped_note: null, + own_transfer_amount: 0, + ...overrides, + } +} + +describe("OG card eligibility and formatting (DOS/Give#313)", () => { + it.each(["live", "settling", "succeeded", "failed", "closed"] as const)( + "allows public campaign status %s", + (status) => { + expect(isOgEligible({ status })).toBe(true) + } + ) + + it.each(["draft", "in_review", "changes_requested", "approved", "suspended", "cancelled"] as const)( + "rejects non-public campaign status %s", + (status) => { + expect(isOgEligible({ status })).toBe(false) + expect( + buildOgCampaignCardModel({ + campaign: { + slug: "test", + type: "give", + status, + title: "Chiến dịch thử nghiệm", + goal_amount: 50_000_000, + display_options: { progress_bar: true, backers_count: true, time_remaining: true }, + }, + totals: totalsFixture(), + organizer: null, + }) + ).toBeNull() + } + ) + + it("formats give campaign figures excluding other_in_amount and shows verified statement badge when clean", () => { + const model = buildOgCampaignCardModel({ + campaign: { + slug: "xay-truong-ban-may", + type: "give", + status: "live", + title: "Xây trường Bản Mây", + goal_amount: 100_000_000, + display_options: { progress_bar: true, backers_count: true, time_remaining: true }, + }, + totals: totalsFixture({ paid_amount: 45_000_000, other_in_amount: 5_000_000, supporters_count: 18 }), + organizer: { display_name: "Quỹ Bản Mây", verification_status: "verified" }, + })! + + expect(model).not.toBeNull() + expect(model.typeBadge).toBe("Từ thiện") + expect(model.statusBadge).toBeNull() + // Raised excludes other_in_amount: 45M - 5M = 40M (40%). + expect(model.raised).toBe(40_000_000) + expect(model.raisedText).toBe(formatVnd(40_000_000)) + expect(model.goalText).toBe(`Mục tiêu ${formatVnd(100_000_000)}`) + expect(model.percent).toBe(40) + expect(model.raisedLabel).toBe("Đã nhận") + expect(model.supportersText).toBe("18 người ủng hộ") + expect(model.organizerVerified).toBe(true) + expect(model.verifiedStatementBadge).toBe("Sao kê đối chiếu ngân hàng") + }) + + it("formats back campaigns with pledged amounts and hides verified statement badge when unexplained outflows exist", () => { + const model = buildOgCampaignCardModel({ + campaign: { + slug: "sach-anh-viet-nam", + type: "back", + status: "succeeded", + title: "Sách ảnh Việt Nam", + goal_amount: 50_000_000, + display_options: { progress_bar: true, backers_count: true, time_remaining: true }, + }, + totals: totalsFixture({ + type: "back", + pledged_amount: 60_000_000, + paid_amount: 40_000_000, + backers_count: 42, + unexplained_out_count: 2, + }), + organizer: { display_name: "Nhóm Sách Ảnh", verification_status: "verified" }, + })! + + expect(model.typeBadge).toBe("Dự án") + expect(model.statusBadge).toBe("Thành công") + expect(model.raised).toBe(60_000_000) + expect(model.percent).toBe(100) + expect(model.raisedLabel).toBe("Đã cam kết") + expect(model.supportersText).toBe("42 người đồng hành") + expect(model.verifiedStatementBadge).toBeNull() + expect(verifiedStatementLabel(null, null)).toBeNull() + // Zero-inflow campaign shows "Sao kê công khai" rather than claiming bank-reconciled inflows. + expect( + verifiedStatementLabel(totalsFixture({ paid_amount: 0, unexplained_out_count: 0 }), { + verification_status: "verified", + }) + ).toBe("Sao kê công khai") + }) + + it("truncates long titles safely by Unicode code points without splitting surrogate pairs", () => { + const emojiTitle = `🌱 ${"Chiến dịch hỗ trợ trẻ em vùng cao ".repeat(5)}` + const truncated = truncateCodePoints(emojiTitle, 40) + expect(Array.from(truncated).length).toBeLessThanOrEqual(40) + expect(truncated.endsWith("…")).toBe(true) + expect(truncated).not.toMatch(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? { + const NOW = new Date("2026-11-22T12:00:00.000Z") + const liveGive = { + type: "give" as const, + status: "live" as CampaignStatus, + starts_at: "2026-11-01T00:00:00.000Z", + ends_at: "2026-12-31T00:00:00.000Z", + payments_stopped_at: null as string | null, + } + + it("allows VietQR only for a live give campaign inside dates with no payments_stopped_at and a usable account", () => { + expect( + shouldIncludePosterVietQr({ + campaign: liveGive, + totals: { payments_stopped_at: null }, + hasUsableAccount: true, + now: NOW, + }) + ).toBe(true) + }) + + it("strictly suppresses VietQR whenever payments_stopped_at is set on campaign or totals (#93)", () => { + expect( + shouldIncludePosterVietQr({ + campaign: { ...liveGive, payments_stopped_at: "2026-11-20T00:00:00.000Z" }, + totals: { payments_stopped_at: null }, + hasUsableAccount: true, + now: NOW, + }) + ).toBe(false) + + expect( + shouldIncludePosterVietQr({ + campaign: liveGive, + totals: { payments_stopped_at: "2026-11-20T00:00:00.000Z" }, + hasUsableAccount: true, + now: NOW, + }) + ).toBe(false) + + // Defense-in-depth: fail closed when totals is null and campaign omits payments_stopped_at. + expect( + shouldIncludePosterVietQr({ + campaign: { + type: "give", + status: "live", + starts_at: liveGive.starts_at, + ends_at: liveGive.ends_at, + }, + totals: null, + hasUsableAccount: true, + now: NOW, + }) + ).toBe(false) + }) + + it("suppresses VietQR for non-live, back, out-of-window, or account-less campaigns", () => { + expect( + shouldIncludePosterVietQr({ + campaign: liveGive, + totals: { payments_stopped_at: null }, + hasUsableAccount: false, + now: NOW, + }) + ).toBe(false) + + expect( + shouldIncludePosterVietQr({ + campaign: { ...liveGive, type: "back" }, + totals: { payments_stopped_at: null }, + hasUsableAccount: true, + now: NOW, + }) + ).toBe(false) + + for (const status of [ + "draft", + "in_review", + "approved", + "settling", + "succeeded", + "failed", + "closed", + "suspended", + "cancelled", + ] as const) { + expect( + shouldIncludePosterVietQr({ + campaign: { ...liveGive, status }, + totals: { payments_stopped_at: null }, + hasUsableAccount: true, + now: NOW, + }) + ).toBe(false) + } + + expect( + shouldIncludePosterVietQr({ + campaign: { ...liveGive, starts_at: "2026-12-01T00:00:00.000Z" }, + totals: { payments_stopped_at: null }, + hasUsableAccount: true, + now: NOW, + }) + ).toBe(false) + + expect( + shouldIncludePosterVietQr({ + campaign: { ...liveGive, ends_at: "2026-11-21T00:00:00.000Z" }, + totals: { payments_stopped_at: null }, + hasUsableAccount: true, + now: NOW, + }) + ).toBe(false) + }) + + it("masks bank account numbers strictly via maskedAccountLast4 and never leaks raw digits", () => { + expect(formatPosterBankHint("970436", "0011012345678")).toEqual({ + bankName: "Vietcombank", + maskedAccount: "•••• 5678", + }) + expect(formatPosterBankHint("970407", "1234")).toEqual({ + bankName: "Techcombank", + maskedAccount: "••••", + }) + expect(formatPosterBankHint("970407", null)).toEqual({ + bankName: "Techcombank", + maskedAccount: "••••", + }) + expect(formatPosterBankHint("970407", "bad!@#acct")).toEqual({ + bankName: "Techcombank", + maskedAccount: "••••", + }) + }) + + it("encodes valid square QR matrices and formats short display URLs", () => { + const qr = encodeQrMatrix("https://give.vn/campaigns/xay-truong") + expect(qr.size).toBeGreaterThanOrEqual(21) + expect(qr.bits).toHaveLength(qr.size * qr.size) + expect(/^[01]+$/.test(qr.bits)).toBe(true) + + expect(displayShortUrl("https://give.vn", "/campaigns/xay-truong")).toBe("give.vn/campaigns/xay-truong") + expect(displayShortUrl(undefined, "/campaigns/xay-truong")).toBe("give.vn/campaigns/xay-truong") + }) +}) + +describe("Thank-You Card eligibility, anonymity, and amount-privacy toggle (DOS/Give#313)", () => { + it("allows only matched/received donations and paid pledges on public campaigns", () => { + expect( + isThankYouCardEligible({ kind: "donation", status: "received", receivedAmount: 250_000, hasPublicCampaign: true }) + ).toBe(true) + expect( + isThankYouCardEligible({ kind: "pledge", status: "paid", receivedAmount: 500_000, hasPublicCampaign: true }) + ).toBe(true) + + expect( + isThankYouCardEligible({ + kind: "donation", + status: "awaiting_transfer", + receivedAmount: 0, + hasPublicCampaign: true, + }) + ).toBe(false) + expect( + isThankYouCardEligible({ kind: "donation", status: "expired", receivedAmount: 0, hasPublicCampaign: true }) + ).toBe(false) + expect( + isThankYouCardEligible({ + kind: "donation", + status: "received", + receivedAmount: 250_000, + hasPublicCampaign: false, + }) + ).toBe(false) + expect( + isThankYouCardEligible({ kind: "pledge", status: "pledged", receivedAmount: 0, hasPublicCampaign: true }) + ).toBe(false) + expect( + isThankYouCardEligible({ kind: "pledge", status: "refunded", receivedAmount: 0, hasPublicCampaign: true }) + ).toBe(false) + expect(isThankYouCardEligible({ kind: "pledge", status: "paid", receivedAmount: 0, hasPublicCampaign: true })).toBe( + false + ) + }) + + it("respects anonymous donations even when publicName or fallbackName is provided", () => { + expect(resolveThankYouDonorName({ publicName: "Nguyễn Minh", isAnonymous: true, fallbackName: "Minh" })).toBe( + ANONYMOUS_DONOR_CARD_LABEL + ) + expect(resolveThankYouDonorName({ publicName: "Nguyễn Minh", isAnonymous: false })).toBe("Nguyễn Minh") + expect(resolveThankYouDonorName({ publicName: " ", isAnonymous: false, fallbackName: "Trần An" })).toBe("Trần An") + expect(resolveThankYouDonorName({ publicName: null, isAnonymous: false, fallbackName: null })).toBe( + DEFAULT_DONOR_CARD_LABEL + ) + }) + + it("shows VND amount clearly by default and completely strips VND digits when hideAmount is true", () => { + const base = { + kind: "donation" as const, + referenceCode: "gvabcdefg", + amount: 350_000, + campaignTitle: "Bữa trưa cho em", + campaignSlug: "bua-trua-cho-em", + campaignType: "give" as const, + donorName: "Nguyễn Minh", + isAnonymous: false, + createdAt: "2026-11-20T03:00:00.000Z", + origin: "https://give.vn", + } + + const visible = buildThankYouCardModel(base, { hideAmount: false }) + expect(visible.headline).toBe("Tôi đã chung tay") + expect(visible.donorName).toBe("Nguyễn Minh") + expect(visible.amountText).toBe(formatVnd(350_000)) + expect(visible.referenceCode).toBe("GVABCDEFG") + expect(visible.statementUrlText).toBe("give.vn/campaigns/bua-trua-cho-em/statement") + + const hidden = buildThankYouCardModel(base, { hideAmount: true }) + expect(hidden.amountText).toBeNull() + expect(hidden.amountCaption).toContain("ẩn số tiền") + expect(JSON.stringify(hidden)).not.toContain("350.000") + expect(JSON.stringify(hidden)).not.toContain("350000") + }) +}) diff --git a/apps/web/src/lib/viral-sharing.ts b/apps/web/src/lib/viral-sharing.ts new file mode 100644 index 00000000..08531396 --- /dev/null +++ b/apps/web/src/lib/viral-sharing.ts @@ -0,0 +1,364 @@ +import { encode } from "uqr" + +import { bankLabel } from "./banks" +import { + isPublicStatus, + STATUS_LABELS, + TYPE_LABELS, + type CampaignStatus, + type CampaignType, + type DisplayOptions, + type PublicOrganizer, +} from "./campaigns" +import { formatDate, formatVnd, progressPercent } from "./format" +import { maskedAccountLast4 } from "./notices" +import { raisedAmount, type MoneyTotals } from "./statement" + +/** + * Shared domain logic for Give viral sharing (DOS/Give#313): + * 1. Dynamic Open Graph card eligibility & display model for /campaigns/[slug] + * 2. Downloadable QR poster eligibility (#93 stopped-payment gating & account masking) + * 3. Shareable "Tôi đã chung tay" thank-you card eligibility & amount-privacy toggle + * + * Client-safe: never imports server-only modules or Supabase clients. + */ + +const OG_TITLE_MAX_CHARS = 92 +const POSTER_TITLE_MAX_CHARS = 120 +const THANK_YOU_TITLE_MAX_CHARS = 120 +const THANK_YOU_DONOR_MAX_CHARS = 60 + +export const ANONYMOUS_DONOR_CARD_LABEL = "Người ủng hộ ẩn danh" +export const DEFAULT_DONOR_CARD_LABEL = "Người ủng hộ" + +/** Truncates cleanly by Unicode code point so diacritics and surrogate pairs never split. */ +export function truncateCodePoints(text: string, maxChars: number): string { + const clean = text.replace(/\s+/g, " ").trim() + const chars = Array.from(clean) + if (chars.length <= maxChars) return clean + return `${chars + .slice(0, Math.max(1, maxChars - 1)) + .join("") + .trimEnd()}…` +} + +// --------------------------------------------------------------------------- +// 1. Dynamic Open Graph card (/campaigns/[slug]/opengraph-image) +// --------------------------------------------------------------------------- + +export interface OgCampaignInput { + slug: string + type: CampaignType + status: CampaignStatus + title: string + goal_amount: number + display_options: DisplayOptions +} + +export interface OgCampaignCardModel { + title: string + type: CampaignType + typeBadge: string + statusBadge: string | null + raised: number + goal: number + percent: number + raisedLabel: string + raisedText: string + goalText: string + showProgressBar: boolean + supportersText: string | null + organizerName: string | null + organizerVerified: boolean + verifiedStatementBadge: string | null + footerText: string +} + +/** Only publicly visible campaigns may render an Open Graph card; everything else is 404. */ +export function isOgEligible(campaign: Pick | null | undefined): boolean { + return campaign != null && isPublicStatus(campaign.status) +} + +/** + * Verified statement indicator for the OG card: shown only when public totals + * loaded cleanly and there are zero unexplained outgoing transactions. + * "Sao kê đối chiếu ngân hàng" is reserved for campaigns with recorded inflows + * (`paid_amount > 0`); zero-inflow campaigns show "Sao kê công khai". + */ +export function verifiedStatementLabel( + totals: Pick | null | undefined, + _organizer?: Pick | null | undefined +): string | null { + if (!totals || totals.unexplained_out_count > 0) return null + if (totals.paid_amount > 0) { + return "Sao kê đối chiếu ngân hàng" + } + return "Sao kê công khai" +} + +export function buildOgCampaignCardModel({ + campaign, + totals, + organizer, +}: { + campaign: OgCampaignInput + totals: MoneyTotals | null + organizer: Pick | null +}): OgCampaignCardModel | null { + if (!isOgEligible(campaign)) return null + + const isGive = campaign.type === "give" + const raised = raisedAmount(totals, campaign.type) + const percent = progressPercent(raised, campaign.goal_amount) + const people = totals ? (isGive ? totals.supporters_count : totals.backers_count) : null + const supportersText = + people !== null && campaign.display_options.backers_count !== false + ? `${people} ${isGive ? "người ủng hộ" : "người đồng hành"}` + : null + + return { + title: truncateCodePoints(campaign.title, OG_TITLE_MAX_CHARS), + type: campaign.type, + typeBadge: TYPE_LABELS[campaign.type], + statusBadge: campaign.status !== "live" ? STATUS_LABELS[campaign.status] : null, + raised, + goal: campaign.goal_amount, + percent, + raisedLabel: isGive ? "Đã nhận" : "Đã cam kết", + raisedText: formatVnd(raised), + goalText: `Mục tiêu ${formatVnd(campaign.goal_amount)}`, + showProgressBar: campaign.display_options.progress_bar !== false, + supportersText, + organizerName: organizer ? truncateCodePoints(organizer.display_name, 56) : null, + organizerVerified: organizer?.verification_status === "verified", + verifiedStatementBadge: verifiedStatementLabel(totals, organizer), + footerText: isGive + ? "give.vn · Tiền vào thẳng tài khoản chiến dịch · Sao kê công khai" + : "give.vn · Gây quỹ minh bạch", + } +} + +// --------------------------------------------------------------------------- +// 2. Downloadable QR Poster (/campaigns/[slug]) +// --------------------------------------------------------------------------- + +export type PosterFormat = "story" | "square" + +export const POSTER_DIMENSIONS: Record = { + story: { width: 1080, height: 1920, label: "Story (9:16)" }, + square: { width: 1080, height: 1080, label: "Vuông (1:1)" }, +} + +export interface QrMatrix { + size: number + /** Row-major bit string of length size * size ('1' = dark module, '0' = light module). */ + bits: string +} + +/** Encodes a string into a deterministic QR module matrix (error correction M, 4-module quiet zone). */ +export function encodeQrMatrix(value: string): QrMatrix { + const { size, data } = encode(value, { ecc: "M", border: 4 }) + let bits = "" + for (let y = 0; y < size; y++) { + const row = data[y] + for (let x = 0; x < size; x++) { + bits += row?.[x] ? "1" : "0" + } + } + return { size, bits } +} + +export interface PosterVietQrBox { + qr: QrMatrix + bankName: string + /** Strictly masked via maskedAccountLast4 ("•••• 5678") or "••••". Never raw digits. */ + maskedAccount: string +} + +export interface CampaignPosterData { + campaignId: string + slug: string + path: string + origin?: string + type: CampaignType + typeBadge: string + title: string + organizerName: string | null + organizerVerified: boolean + raisedLabel: string + raisedText: string + goalText: string + percent: number + showProgressBar: boolean + verifiedStatementBadge: string | null + /** Present only for a live give campaign accepting donations with no payments_stopped_at and a usable bank account. */ + vietQr: PosterVietQrBox | null +} + +export interface PosterVietQrEligibilityInput { + campaign: { + type: CampaignType + status: CampaignStatus + starts_at: string | null + ends_at: string | null + payments_stopped_at?: string | null + } + totals: Pick | null | undefined + hasUsableAccount: boolean + now?: Date +} + +/** + * #93 & money safety gate for poster VietQR boxes: + * Strictly suppresses VietQR / payment instructions whenever payments_stopped_at + * is set (on campaign or public_campaigns totals), when stopped-payment status + * cannot be verified (both `totals == null` and `campaign.payments_stopped_at === undefined`), + * or when the campaign is not a live give campaign inside its active dates with + * a verified usable bank account. + */ +export function shouldIncludePosterVietQr({ + campaign, + totals, + hasUsableAccount, + now = new Date(), +}: PosterVietQrEligibilityInput): boolean { + if (!isPublicStatus(campaign.status)) return false + if (campaign.type !== "give" || campaign.status !== "live") return false + if (totals == null && campaign.payments_stopped_at === undefined) return false + if (campaign.payments_stopped_at || totals?.payments_stopped_at) return false + if (campaign.starts_at && new Date(campaign.starts_at) > now) return false + if (campaign.ends_at && new Date(campaign.ends_at) <= now) return false + return hasUsableAccount +} + +/** + * Formats the bank summary shown next to a poster's VietQR box. + * Reuses maskedAccountLast4 so raw or malformed account numbers can never leak. + */ +export function formatPosterBankHint( + bankBin: string | null | undefined, + accountNumber: string | null | undefined +): { bankName: string; maskedAccount: string } { + const trimmed = accountNumber?.trim() ?? "" + const last4 = /^[0-9A-Za-z]{5,19}$/.test(trimmed) ? trimmed.slice(-4) : null + return { + bankName: bankLabel(bankBin), + maskedAccount: maskedAccountLast4(last4, null) ?? "••••", + } +} + +/** Strips protocol and trailing slashes for compact display on posters and cards. */ +export function displayShortUrl(origin: string | undefined, path: string): string { + const cleanPath = path.startsWith("/") ? path : `/${path}` + if (!origin) return `give.vn${cleanPath}` + try { + const parsed = new URL(cleanPath, origin) + return `${parsed.host}${parsed.pathname}` + } catch { + return `give.vn${cleanPath}` + } +} + +export function posterDisplayTitle(title: string): string { + return truncateCodePoints(title, POSTER_TITLE_MAX_CHARS) +} + +// --------------------------------------------------------------------------- +// 3. Shareable "Tôi đã chung tay" Thank-You Card +// --------------------------------------------------------------------------- + +export interface ThankYouEligibilityInput { + kind: "donation" | "pledge" + status: string + receivedAmount: number + hasPublicCampaign: boolean +} + +/** + * Thank-you cards are only available for matched/received donations or paid + * pledges with a positive net amount on a public campaign. + */ +export function isThankYouCardEligible({ + kind, + status, + receivedAmount, + hasPublicCampaign, +}: ThankYouEligibilityInput): boolean { + if (!hasPublicCampaign) return false + if (!Number.isFinite(receivedAmount) || receivedAmount <= 0) return false + return kind === "donation" ? status === "received" : status === "paid" +} + +/** + * Resolves the display name shown on a thank-you card. + * Anonymous contributions ALWAYS render as "Người ủng hộ ẩn danh", never + * leaking public_name or account display names. + */ +export function resolveThankYouDonorName({ + publicName, + isAnonymous, + fallbackName, +}: { + publicName?: string | null + isAnonymous?: boolean | null + fallbackName?: string | null +}): string { + if (isAnonymous) return ANONYMOUS_DONOR_CARD_LABEL + const chosen = publicName?.trim() || fallbackName?.trim() || "" + return chosen ? truncateCodePoints(chosen, THANK_YOU_DONOR_MAX_CHARS) : DEFAULT_DONOR_CARD_LABEL +} + +export interface ThankYouCardInput { + kind: "donation" | "pledge" + referenceCode: string + amount: number + campaignTitle: string + campaignSlug: string + campaignType: CampaignType + donorName?: string | null + isAnonymous?: boolean + createdAt?: string | null + origin?: string +} + +export interface ThankYouCardModel { + headline: string + donorName: string + campaignTitle: string + typeBadge: string + /** Formatted VND amount when visible, strictly null when hideAmount is enabled. */ + amountText: string | null + amountCaption: string + referenceCode: string + dateText: string | null + statementUrlText: string + footerText: string +} + +export function buildThankYouCardModel(input: ThankYouCardInput, options: { hideAmount: boolean }): ThankYouCardModel { + const donorName = resolveThankYouDonorName({ + publicName: input.donorName, + isAnonymous: input.isAnonymous, + }) + const cleanCode = input.referenceCode.trim().toUpperCase() + const hideAmount = options.hideAmount + const amountText = hideAmount ? null : formatVnd(input.amount) + const amountCaption = hideAmount + ? "Đã xác nhận chung tay (ẩn số tiền)" + : input.kind === "pledge" + ? "Đã xác nhận đồng hành" + : "Đã xác nhận ủng hộ" + + return { + headline: "Tôi đã chung tay", + donorName, + campaignTitle: truncateCodePoints(input.campaignTitle, THANK_YOU_TITLE_MAX_CHARS), + typeBadge: TYPE_LABELS[input.campaignType], + amountText, + amountCaption, + referenceCode: cleanCode, + dateText: input.createdAt ? formatDate(input.createdAt) : null, + statementUrlText: displayShortUrl(input.origin, `/campaigns/${input.campaignSlug}/statement`), + footerText: "give.vn · Minh bạch từng đồng · Đối chiếu sao kê ngân hàng", + } +} diff --git a/apps/web/src/server/contributions/index.ts b/apps/web/src/server/contributions/index.ts index 25348b53..d842867e 100644 --- a/apps/web/src/server/contributions/index.ts +++ b/apps/web/src/server/contributions/index.ts @@ -34,6 +34,13 @@ import { isDonationCode } from "@/server/vietqr" const PAYMENT_COLUMNS = "id, campaign_id, intended_amount, received_amount, reference_code, status, created_at, plan_id, plan_period" +/** + * Signed-in donors viewing their own contribution under RLS may also read + * their chosen public display name and anonymity flag for the thank-you card + * (DOS/Give#313). Guest tracking lookups never read these columns. + */ +const OWN_PAYMENT_COLUMNS = `${PAYMENT_COLUMNS}, public_name, is_anonymous` + export interface PaymentContribution { id: string campaign_id: string @@ -46,6 +53,10 @@ export interface PaymentContribution { plan_id: string | null /** The first day of the plan month this donation is for (YYYY-MM-DD), with plan_id. */ plan_period: string | null + /** Populated only for signed-in ownContribution reads (never guest tracking lookups). */ + public_name?: string | null + /** Populated only for signed-in ownContribution reads (never guest tracking lookups). */ + is_anonymous?: boolean } /** The hex form of sha256(token bytes), as give.create_donation stores it in status_token_hash. */ @@ -300,7 +311,7 @@ export async function guestContribution( export async function ownContribution(db: Db, userId: string, code: string): Promise { const { data, error } = await db .from("contributions") - .select(PAYMENT_COLUMNS) + .select(OWN_PAYMENT_COLUMNS) .eq("reference_code", code) .eq("kind", "donation") .eq("contributor_user_id", userId) diff --git a/apps/web/src/server/viral-sharing.test.ts b/apps/web/src/server/viral-sharing.test.ts new file mode 100644 index 00000000..29472bb3 --- /dev/null +++ b/apps/web/src/server/viral-sharing.test.ts @@ -0,0 +1,159 @@ +import { describe, expect, it } from "vitest" + +import type { CampaignStatus } from "@/lib/campaigns" +import type { MoneyTotals } from "@/lib/statement" + +import { buildServerPosterData } from "./viral-sharing" + +const NOW = new Date("2026-11-22T12:00:00.000Z") + +function campaignFixture(overrides: Record = {}) { + return { + id: "33333333-3333-4333-8333-333333333333", + slug: "xay-truong-ban-may", + type: "give" as const, + status: "live" as CampaignStatus, + title: "Xây trường Bản Mây", + goal_amount: 100_000_000, + starts_at: "2026-11-01T00:00:00.000Z", + ends_at: "2026-12-31T00:00:00.000Z", + display_options: { progress_bar: true, backers_count: true, time_remaining: true }, + payments_stopped_at: null as string | null, + ...overrides, + } +} + +function totalsFixture(overrides: Partial = {}): MoneyTotals { + return { + campaign_id: "33333333-3333-4333-8333-333333333333", + type: "give", + asset: "VND", + goal_amount: 100_000_000, + pledged_amount: 0, + paid_amount: 25_000_000, + disbursable_amount: 25_000_000, + disbursed_amount: 0, + refunded_amount: 0, + unexplained_out_amount: 0, + unexplained_out_count: 0, + supporters_count: 10, + other_in_amount: 0, + refund_owed_amount: 0, + backers_count: 0, + payments_stopped_at: null, + payments_stopped_note: null, + own_transfer_amount: 0, + ...overrides, + } +} + +const ACCOUNT = { + bank_bin: "970436", + account_number: "0011012345678", + account_name: "NGUYEN VAN SECRET", +} + +describe("buildServerPosterData (DOS/Give#313)", () => { + it("returns null for non-public campaign statuses", () => { + for (const status of ["draft", "in_review", "changes_requested", "approved", "suspended", "cancelled"] as const) { + expect( + buildServerPosterData({ + campaign: campaignFixture({ status }), + totals: totalsFixture(), + organizer: { display_name: "Quỹ Bản Mây", verification_status: "verified" }, + account: ACCOUNT, + origin: "https://give.vn", + now: NOW, + }) + ).toBeNull() + } + }) + + it("includes static VietQR matrix with masked bank hint for an eligible live give campaign without leaking raw account fields", () => { + const poster = buildServerPosterData({ + campaign: campaignFixture(), + totals: totalsFixture(), + organizer: { display_name: "Quỹ Bản Mây", verification_status: "verified" }, + account: ACCOUNT, + origin: "https://give.vn", + now: NOW, + })! + + expect(poster).not.toBeNull() + expect(poster.vietQr).not.toBeNull() + expect(poster.vietQr?.bankName).toBe("Vietcombank") + expect(poster.vietQr?.maskedAccount).toBe("•••• 5678") + expect(poster.vietQr?.qr.size).toBeGreaterThanOrEqual(21) + expect(poster.vietQr?.qr.bits).toHaveLength(poster.vietQr!.qr.size * poster.vietQr!.qr.size) + + // Anti-leak: neither the raw bank account number nor the account holder's legal name appears in serialized props. + const serialized = JSON.stringify(poster) + expect(serialized).not.toContain(ACCOUNT.account_number) + expect(serialized).not.toContain(ACCOUNT.account_name) + expect(serialized).not.toContain("001101234") + }) + + it("strictly suppresses VietQR when payments_stopped_at is set on campaign or totals (#93)", () => { + const stoppedOnCampaign = buildServerPosterData({ + campaign: campaignFixture({ payments_stopped_at: "2026-11-20T00:00:00.000Z" }), + totals: totalsFixture(), + organizer: { display_name: "Quỹ Bản Mây", verification_status: "verified" }, + account: ACCOUNT, + origin: "https://give.vn", + now: NOW, + })! + expect(stoppedOnCampaign.vietQr).toBeNull() + + const stoppedOnTotals = buildServerPosterData({ + campaign: campaignFixture(), + totals: totalsFixture({ payments_stopped_at: "2026-11-20T00:00:00.000Z" }), + organizer: { display_name: "Quỹ Bản Mây", verification_status: "verified" }, + account: ACCOUNT, + origin: "https://give.vn", + now: NOW, + })! + expect(stoppedOnTotals.vietQr).toBeNull() + }) + + it("suppresses VietQR for closed, back, expired, missing-account, or malformed-account campaigns", () => { + expect( + buildServerPosterData({ + campaign: campaignFixture({ status: "closed" }), + totals: totalsFixture(), + organizer: null, + account: ACCOUNT, + now: NOW, + })!.vietQr + ).toBeNull() + + expect( + buildServerPosterData({ + campaign: campaignFixture({ type: "back" }), + totals: totalsFixture({ type: "back" }), + organizer: null, + account: ACCOUNT, + now: NOW, + })!.vietQr + ).toBeNull() + + expect( + buildServerPosterData({ + campaign: campaignFixture(), + totals: totalsFixture(), + organizer: null, + account: null, + now: NOW, + })!.vietQr + ).toBeNull() + + expect( + buildServerPosterData({ + campaign: campaignFixture(), + totals: totalsFixture(), + organizer: null, + account: { bank_bin: "invalid", account_number: "0123456789", account_name: "TEST" }, + now: NOW, + })!.vietQr + ).toBeNull() + }) +}) diff --git a/apps/web/src/server/viral-sharing.ts b/apps/web/src/server/viral-sharing.ts new file mode 100644 index 00000000..d0f2eb3c --- /dev/null +++ b/apps/web/src/server/viral-sharing.ts @@ -0,0 +1,110 @@ +import "server-only" + +import { isPublicStatus, TYPE_LABELS, type PublicCampaign, type PublicOrganizer } from "@/lib/campaigns" +import { formatVnd, progressPercent } from "@/lib/format" +import { raisedAmount, type MoneyTotals } from "@/lib/statement" +import { + encodeQrMatrix, + formatPosterBankHint, + posterDisplayTitle, + shouldIncludePosterVietQr, + verifiedStatementLabel, + type CampaignPosterData, + type PosterVietQrBox, +} from "@/lib/viral-sharing" +import type { PaymentAccount } from "@/server/contributions" +import { encodeVietQr } from "@/server/vietqr" +import { hasValidCrc } from "@/server/vietqr/crc16" + +/** + * Server-side assembly of downloadable QR poster props for /campaigns/[slug]. + * + * Security & #93 invariants: + * - Returns null for non-public campaigns so drafts/private campaigns never build posters. + * - Encodes static VietQR strictly on the server only when `shouldIncludePosterVietQr` + * allows it (live give campaign, inside dates, no `payments_stopped_at`, usable account). + * - Never sends raw `account_number` or `account_name` to client components; the human-readable + * bank hint uses `formatPosterBankHint` (reusing `maskedAccountLast4`), and the VietQR + * payload is pre-encoded into a boolean module matrix. + */ +export function buildServerPosterData({ + campaign, + totals, + organizer, + account, + origin, + now = new Date(), +}: { + campaign: Pick< + PublicCampaign, + | "id" + | "slug" + | "type" + | "status" + | "title" + | "goal_amount" + | "starts_at" + | "ends_at" + | "display_options" + | "payments_stopped_at" + > + totals: MoneyTotals | null + organizer: Pick | null + account: PaymentAccount | null + origin?: string + now?: Date +}): CampaignPosterData | null { + if (!isPublicStatus(campaign.status)) return null + + const isGive = campaign.type === "give" + const raised = raisedAmount(totals, campaign.type) + const percent = progressPercent(raised, campaign.goal_amount) + + let vietQr: PosterVietQrBox | null = null + const allowVietQr = shouldIncludePosterVietQr({ + campaign, + totals, + hasUsableAccount: account !== null, + now, + }) + + if (allowVietQr && account) { + try { + const payload = encodeVietQr({ + bankBin: account.bank_bin, + consumerId: account.account_number, + service: "account", + }) + if (hasValidCrc(payload)) { + const hint = formatPosterBankHint(account.bank_bin, account.account_number) + vietQr = { + qr: encodeQrMatrix(payload), + bankName: hint.bankName, + maskedAccount: hint.maskedAccount, + } + } + } catch { + // Malformed bank BIN or account number falls back safely to campaign-link QR only. + vietQr = null + } + } + + return { + campaignId: campaign.id, + slug: campaign.slug, + path: `/campaigns/${campaign.slug}`, + origin, + type: campaign.type, + typeBadge: TYPE_LABELS[campaign.type], + title: posterDisplayTitle(campaign.title), + organizerName: organizer?.display_name ?? null, + organizerVerified: organizer?.verification_status === "verified", + raisedLabel: isGive ? "Đã nhận" : "Đã cam kết", + raisedText: formatVnd(raised), + goalText: `Mục tiêu ${formatVnd(campaign.goal_amount)}`, + percent, + showProgressBar: campaign.display_options.progress_bar !== false, + verifiedStatementBadge: verifiedStatementLabel(totals, organizer), + vietQr, + } +}