diff --git a/apps/web/src/app/start/StartCampaignForm.test.ts b/apps/web/src/app/start/StartCampaignForm.test.ts new file mode 100644 index 00000000..7fe7f772 --- /dev/null +++ b/apps/web/src/app/start/StartCampaignForm.test.ts @@ -0,0 +1,235 @@ +// @vitest-environment happy-dom +/** StartCampaignForm template selection, keyboard navigation, and field preservation (DOS/Give#338). */ +import { act, createElement } from "react" +import { createRoot, hydrateRoot, type Root } from "react-dom/client" +import { renderToString } from "react-dom/server" +import { afterEach, beforeEach, describe, expect, it } from "vitest" + +import { CAMPAIGN_TEMPLATES, getCampaignTemplate } from "@/lib/campaign-templates" +import { newCampaignSchema } from "@/lib/validation" + +import { StartCampaignForm } from "./StartCampaignForm" + +declare global { + var IS_REACT_ACT_ENVIRONMENT: boolean | undefined +} + +let container: HTMLDivElement +let root: Root + +function renderForm() { + act(() => { + root.render(createElement(StartCampaignForm, { action: async () => null })) + }) +} + +function templateRadio(id: string) { + const el = container.querySelector(`button[role="radio"][data-template-id="${id}"]`) + expect(el, `missing template radio ${id}`).toBeTruthy() + return el! +} + +function typeRadio(value: "give" | "back") { + const el = container.querySelector(`input[type="radio"][name="type"][value="${value}"]`) + expect(el, `missing type radio ${value}`).toBeTruthy() + return el! +} + +function titleInput() { + return container.querySelector("#title")! +} + +function goalInput() { + return container.querySelector("#goal_amount")! +} + +function templateHiddenInput() { + return container.querySelector('input[type="hidden"][name="template_id"]')! +} + +function setInputValue(input: HTMLInputElement, value: string) { + act(() => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value) + input.dispatchEvent(new Event("input", { bubbles: true })) + }) +} + +beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true + container = document.createElement("div") + document.body.append(container) + root = createRoot(container) +}) + +afterEach(() => { + act(() => root.unmount()) + container.remove() +}) + +describe("StartCampaignForm (DOS/Give#338)", () => { + it("defaults to the blank template with give checked, empty goal, and hidden template_id=blank", () => { + renderForm() + + const radiogroup = container.querySelector('[role="radiogroup"]') + expect(radiogroup).toBeTruthy() + expect(radiogroup?.getAttribute("aria-labelledby")).toBe("template_picker_label") + expect(radiogroup?.getAttribute("aria-describedby")).toBe("template_hint") + + const buttons = container.querySelectorAll('button[role="radio"]') + expect(buttons).toHaveLength(CAMPAIGN_TEMPLATES.length) + expect(templateRadio("blank").getAttribute("aria-checked")).toBe("true") + expect(templateRadio("blank").tabIndex).toBe(0) + expect(templateRadio("medical_emergency").getAttribute("aria-checked")).toBe("false") + expect(templateRadio("medical_emergency").tabIndex).toBe(-1) + + expect(templateHiddenInput().value).toBe("blank") + expect(typeRadio("give").checked).toBe(true) + expect(typeRadio("back").checked).toBe(false) + expect(goalInput().value).toBe("") + expect(goalInput().placeholder).toBe("50.000.000") + expect(titleInput().getAttribute("placeholder")).toBeNull() + expect(container.querySelector("#title_hint")).toBeNull() + expect(container.querySelector("#goal_amount_hint")).toBeNull() + }) + + it("pre-fills type, parseable goal_amount, title placeholder/hint, and template_id when selecting templates while preserving user title", () => { + renderForm() + + setInputValue(titleInput(), "Dự án thư viện cho em") + + act(() => templateRadio("creative_product").click()) + expect(templateHiddenInput().value).toBe("creative_product") + expect(templateRadio("creative_product").getAttribute("aria-checked")).toBe("true") + expect(templateRadio("blank").getAttribute("aria-checked")).toBe("false") + expect(typeRadio("back").checked).toBe(true) + expect(typeRadio("give").checked).toBe(false) + expect(goalInput().value).toBe("80.000.000") + expect(titleInput().value).toBe("Dự án thư viện cho em") + expect(titleInput().placeholder).toBe(getCampaignTemplate("creative_product")!.titlePlaceholder) + expect(titleInput().getAttribute("aria-describedby")).toBe("title_hint") + expect(container.querySelector("#title_hint")?.textContent).toContain("Sản phẩm & Dự án sáng tạo") + expect(goalInput().getAttribute("aria-describedby")).toBe("goal_amount_hint") + + const parsed = newCampaignSchema.safeParse({ + type: typeRadio("back").checked ? "back" : "give", + title: titleInput().value, + goal_amount: goalInput().value, + }) + expect(parsed.success).toBe(true) + if (parsed.success) { + expect(parsed.data).toEqual({ + type: "back", + title: "Dự án thư viện cho em", + goal_amount: 80_000_000, + }) + } + + act(() => templateRadio("medical_emergency").click()) + expect(templateHiddenInput().value).toBe("medical_emergency") + expect(typeRadio("give").checked).toBe(true) + expect(goalInput().value).toBe("100.000.000") + expect(titleInput().value).toBe("Dự án thư viện cho em") + expect(titleInput().placeholder).toBe(getCampaignTemplate("medical_emergency")!.titlePlaceholder) + + // Returning to blank clears the untouched template goal while keeping the user's title. + act(() => templateRadio("blank").click()) + expect(templateHiddenInput().value).toBe("blank") + expect(typeRadio("give").checked).toBe(true) + expect(goalInput().value).toBe("") + expect(titleInput().value).toBe("Dự án thư viện cho em") + expect(titleInput().getAttribute("placeholder")).toBeNull() + expect(container.querySelector("#title_hint")).toBeNull() + }) + + it("preserves a custom goal amount when returning to blank and lets user override campaign type manually", () => { + renderForm() + + act(() => templateRadio("medical_emergency").click()) + expect(goalInput().value).toBe("100.000.000") + + setInputValue(goalInput(), "125.000.000") + act(() => templateRadio("blank").click()) + expect(goalInput().value).toBe("125.000.000") + + act(() => templateRadio("education_community").click()) + expect(typeRadio("give").checked).toBe(true) + expect(goalInput().value).toBe("50.000.000") + + // User manually switches campaign type after choosing a template. + act(() => typeRadio("back").click()) + expect(typeRadio("back").checked).toBe(true) + expect(templateHiddenInput().value).toBe("education_community") + + // Re-clicking the already-selected template does not clobber manual type or goal overrides. + setInputValue(goalInput(), "75.000.000") + act(() => templateRadio("education_community").click()) + expect(typeRadio("back").checked).toBe(true) + expect(goalInput().value).toBe("75.000.000") + }) + + it("preserves pre-hydration edits to type, title, and goal_amount across React hydration", () => { + act(() => root.unmount()) + const ssrContainer = document.createElement("div") + ssrContainer.innerHTML = renderToString(createElement(StartCampaignForm, { action: async () => null })) + document.body.append(ssrContainer) + + try { + const preBack = ssrContainer.querySelector('input[type="radio"][name="type"][value="back"]')! + const preTitle = ssrContainer.querySelector("#title")! + const preGoal = ssrContainer.querySelector("#goal_amount")! + preBack.checked = true + preTitle.value = "Dự án gõ trước khi hydrate" + preGoal.value = "90.000.000" + + let hydratedRoot: Root + act(() => { + hydratedRoot = hydrateRoot(ssrContainer, createElement(StartCampaignForm, { action: async () => null })) + }) + + expect( + ssrContainer.querySelector('input[type="radio"][name="type"][value="back"]')!.checked + ).toBe(true) + expect(ssrContainer.querySelector("#title")!.value).toBe("Dự án gõ trước khi hydrate") + expect(ssrContainer.querySelector("#goal_amount")!.value).toBe("90.000.000") + + act(() => hydratedRoot.unmount()) + } finally { + ssrContainer.remove() + root = createRoot(container) + } + }) + + it("supports keyboard arrow, Home, and End navigation with roving tabindex across template cards", () => { + renderForm() + + const blankBtn = templateRadio("blank") + act(() => { + blankBtn.focus() + blankBtn.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true })) + }) + expect(templateHiddenInput().value).toBe("medical_emergency") + expect(document.activeElement).toBe(templateRadio("medical_emergency")) + expect(templateRadio("medical_emergency").tabIndex).toBe(0) + expect(blankBtn.tabIndex).toBe(-1) + + act(() => { + templateRadio("medical_emergency").dispatchEvent(new KeyboardEvent("keydown", { key: "End", bubbles: true })) + }) + expect(templateHiddenInput().value).toBe("creative_product") + expect(document.activeElement).toBe(templateRadio("creative_product")) + expect(typeRadio("back").checked).toBe(true) + + act(() => { + templateRadio("creative_product").dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowLeft", bubbles: true })) + }) + expect(templateHiddenInput().value).toBe("relief_environment") + expect(document.activeElement).toBe(templateRadio("relief_environment")) + expect(typeRadio("give").checked).toBe(true) + + act(() => { + templateRadio("relief_environment").dispatchEvent(new KeyboardEvent("keydown", { key: "Home", bubbles: true })) + }) + expect(templateHiddenInput().value).toBe("blank") + expect(document.activeElement).toBe(templateRadio("blank")) + }) +}) diff --git a/apps/web/src/app/start/StartCampaignForm.tsx b/apps/web/src/app/start/StartCampaignForm.tsx new file mode 100644 index 00000000..023fdc07 --- /dev/null +++ b/apps/web/src/app/start/StartCampaignForm.tsx @@ -0,0 +1,251 @@ +"use client" + +import clsx from "clsx" +import { useRef, useState, type KeyboardEvent } from "react" + +import { ActionForm, SubmitButton } from "@/components/forms" +import { HeartIcon, LedgerIcon, SparkIcon } from "@/components/ui/icons" +import { + CAMPAIGN_TEMPLATES, + formatTemplateGoal, + type CampaignTemplate, + type CampaignTemplateId, +} from "@/lib/campaign-templates" +import type { ActionResult } from "@/lib/errors" +import { formatVnd } from "@/lib/format" + +/** A campaign type choice: a bordered option; the checked one takes the selected fill (DESIGN.md 6). */ +const TYPE_CHOICE = + "flex cursor-pointer gap-3 rounded-md border border-border bg-raised p-4 transition-colors duration-150 hover:bg-surface has-[:checked]:border-primary has-[:checked]:bg-primary-soft has-[:checked]:ring-1 has-[:checked]:ring-primary" + +/** + * Campaign creation form on /start with optional quick-start Vietnamese + * templates (DOS/Give#338). Defaults to "blank" and keeps type/title/goal + * uncontrolled so pre-hydration edits and zero-JS submissions remain intact. + */ +export function StartCampaignForm({ + action, +}: { + action: (state: ActionResult, formData: FormData) => Promise +}) { + const [selectedId, setSelectedId] = useState("blank") + const optionRefs = useRef<(HTMLButtonElement | null)[]>([]) + const giveRadioRef = useRef(null) + const backRadioRef = useRef(null) + const goalInputRef = useRef(null) + + const selectedTemplate = CAMPAIGN_TEMPLATES.find((t) => t.id === selectedId) ?? CAMPAIGN_TEMPLATES[0] + const activeTemplate = selectedTemplate.id === "blank" ? null : selectedTemplate + const suggestedGoal = activeTemplate?.suggestedGoal ?? null + + function selectTemplate(template: CampaignTemplate) { + if (template.id === selectedId) return + const previous = CAMPAIGN_TEMPLATES.find((t) => t.id === selectedId) + setSelectedId(template.id) + + if (giveRadioRef.current) giveRadioRef.current.checked = template.type === "give" + if (backRadioRef.current) backRadioRef.current.checked = template.type === "back" + + const goalInput = goalInputRef.current + if (!goalInput) return + if (template.suggestedGoal !== null) { + goalInput.value = formatTemplateGoal(template.suggestedGoal) + } else if ( + previous?.suggestedGoal !== null && + previous?.suggestedGoal !== undefined && + goalInput.value === formatTemplateGoal(previous.suggestedGoal) + ) { + goalInput.value = "" + } + } + + function handleTemplateKeyDown(event: KeyboardEvent, index: number) { + const count = CAMPAIGN_TEMPLATES.length + let nextIndex: number | null = null + if (event.key === "ArrowRight" || event.key === "ArrowDown") { + nextIndex = (index + 1) % count + } else if (event.key === "ArrowLeft" || event.key === "ArrowUp") { + nextIndex = (index - 1 + count) % count + } else if (event.key === "Home") { + nextIndex = 0 + } else if (event.key === "End") { + nextIndex = count - 1 + } + if (nextIndex === null) return + event.preventDefault() + const next = CAMPAIGN_TEMPLATES[nextIndex] + selectTemplate(next) + optionRefs.current[nextIndex]?.focus() + } + + return ( + + + +
+
+ Mẫu khởi tạo +
+
+ {CAMPAIGN_TEMPLATES.map((template, index) => { + const selected = selectedId === template.id + const isBlank = template.id === "blank" + const nameId = `template_name_${template.id}` + const metaId = `template_meta_${template.id}` + const descId = `template_desc_${template.id}` + return ( + + ) + })} +
+

+ {activeTemplate + ? "Bản nháp sẽ được điền sẵn danh mục gợi ý, tóm tắt, khung câu chuyện và 3 câu hỏi thường gặp để bạn chỉnh sửa." + : "Chọn một mẫu để gợi ý nhanh loại chiến dịch, mục tiêu và khung nội dung, hoặc tự tạo từ đầu."} +

+
+ +
+ Loại chiến dịch +
+ + +
+

+ Không đổi được loại sau khi gửi duyệt. +

+
+ +
+ + + {activeTemplate && ( +

+ Gợi ý theo mẫu {activeTemplate.name}. Bạn có thể tự đặt tiêu đề riêng (5–120 ký tự). +

+ )} +
+ +
+ + + {suggestedGoal !== null && ( +

+ Mục tiêu gợi ý cho mẫu này ({formatVnd(suggestedGoal)}). Bạn có thể sửa lại bất kỳ mức nào từ 10.000 ₫. +

+ )} +
+ + Tạo bản nháp +
+ ) +} diff --git a/apps/web/src/app/start/actions.test.ts b/apps/web/src/app/start/actions.test.ts index 9ec9e3f3..2bd15b4c 100644 --- a/apps/web/src/app/start/actions.test.ts +++ b/apps/web/src/app/start/actions.test.ts @@ -3,7 +3,8 @@ import { redirect } from "next/navigation" import { beforeEach, describe, expect, it, vi } from "vitest" import { getSession } from "@/lib/auth/session" -import type { Organizer } from "@/lib/campaigns" +import { getCampaignTemplate } from "@/lib/campaign-templates" +import type { Category, Organizer } from "@/lib/campaigns" import { dbErrorMessage } from "@/lib/errors" import { uniqueSlug } from "@/lib/slug" import { dbAs } from "@/lib/supabase" @@ -408,3 +409,232 @@ describe("createCampaign (DOS/Give#208)", () => { } ) }) + +const HEALTHCARE_CAT: Category = { + id: "33333333-3333-4333-8333-333333333333", + slug: "healthcare", + name: "Y tế", + description: null, + icon: null, + color: null, + applies_to: "give", + sort_order: 3, +} + +const TECH_CAT: Category = { + id: "44444444-4444-4444-8444-444444444444", + slug: "technology", + name: "Công nghệ", + description: null, + icon: null, + color: null, + applies_to: "back", + sort_order: 101, +} + +describe("createCampaign templates (DOS/Give#338)", () => { + it.each(["blank", "unknown-template", ""])( + "behaves identically to omitted template_id when template_id = %j", + async (template_id) => { + state.handler = () => ({ data: { id: CAMPAIGN } }) + await expect(createCampaign(null, campaignForm({ template_id }))).rejects.toThrow( + `NEXT_REDIRECT /me/campaigns/${CAMPAIGN}` + ) + expect(state.calls).toEqual([ + { + target: "campaigns", + ops: [ + [ + "insert", + { + slug: "quy-hoc-bong-first", + type: "give", + funding_model: "flexible", + organizer_id: USER, + title: "Quỹ học bổng", + goal_amount: 10_000, + }, + ], + ["select", "id"], + ["single"], + ], + }, + ]) + expect(revalidatePath).toHaveBeenCalledExactlyOnceWith("/me/campaigns") + expect(redirect).toHaveBeenCalledExactlyOnceWith(`/me/campaigns/${CAMPAIGN}`) + } + ) + + it("populates category_id, summary, story, and starter FAQs sequentially for a matching non-blank template", async () => { + const template = getCampaignTemplate("creative_product")! + state.handler = (call) => { + if (call.target === "categories") return { data: [HEALTHCARE_CAT, TECH_CAT] } + if (call.target === "campaigns") return { data: { id: CAMPAIGN } } + if (call.target === "rpc:upsert_campaign_faq") return { data: [{ id: "faq-id" }] } + return undefined + } + + await expect( + createCampaign( + null, + campaignForm({ + type: "back", + title: "Bàn phím cơ tiếng Việt", + goal_amount: "80.000.000", + template_id: "creative_product", + }) + ) + ).rejects.toThrow(`NEXT_REDIRECT /me/campaigns/${CAMPAIGN}`) + + expect(state.calls[0].target).toBe("categories") + expect(state.calls[1].target).toBe("campaigns") + expect(op(state.calls[1], "insert")?.[0]).toEqual({ + slug: "quy-hoc-bong-first", + type: "back", + funding_model: "all_or_nothing", + organizer_id: USER, + title: "Bàn phím cơ tiếng Việt", + goal_amount: 80_000_000, + category_id: TECH_CAT.id, + summary: template.summary, + story: template.story, + }) + + const faqCalls = state.calls.slice(2) + expect(faqCalls).toHaveLength(3) + expect(faqCalls.map((c) => c.target)).toEqual([ + "rpc:upsert_campaign_faq", + "rpc:upsert_campaign_faq", + "rpc:upsert_campaign_faq", + ]) + expect(faqCalls.map((c) => op(c, "args")?.[0])).toEqual( + template.starterFaqs.map((faq) => ({ + p_campaign_id: CAMPAIGN, + p_question: faq.question, + p_answer: faq.answer, + p_faq_id: null, + p_position: null, + })) + ) + expect(revalidatePath).toHaveBeenCalledExactlyOnceWith("/me/campaigns") + expect(redirect).toHaveBeenCalledExactlyOnceWith(`/me/campaigns/${CAMPAIGN}`) + }) + + it("omits category_id when the user manually overrides type to one incompatible with the template category", async () => { + const template = getCampaignTemplate("medical_emergency")! + state.handler = (call) => { + if (call.target === "categories") return { data: [HEALTHCARE_CAT, TECH_CAT] } + if (call.target === "campaigns") return { data: { id: CAMPAIGN } } + return undefined + } + + await expect( + createCampaign( + null, + campaignForm({ + type: "back", + title: "Dự án thiết bị y tế", + goal_amount: "100.000.000", + template_id: "medical_emergency", + }) + ) + ).rejects.toThrow(`NEXT_REDIRECT /me/campaigns/${CAMPAIGN}`) + + const inserted = op(state.calls[1], "insert")?.[0] as Record + expect(inserted).not.toHaveProperty("category_id") + expect(inserted).toMatchObject({ + type: "back", + funding_model: "all_or_nothing", + summary: template.summary, + story: template.story, + }) + expect(state.calls.filter((c) => c.target === "rpc:upsert_campaign_faq")).toHaveLength(3) + }) + + it("never blocks draft creation or redirect when category lookup or starter FAQ insertion fails", async () => { + const spy = vi.spyOn(console, "error").mockImplementation(() => {}) + try { + let faqCount = 0 + state.handler = (call) => { + if (call.target === "categories") return { error: { code: "42501", message: "cat read error" } } + if (call.target === "campaigns") return { data: { id: CAMPAIGN } } + if (call.target === "rpc:upsert_campaign_faq") { + faqCount++ + if (faqCount === 1) return { error: { code: "42501", message: "faq denied" } } + if (faqCount === 2) throw new Error("network blip") + return { data: [{ id: "faq-3" }] } + } + return undefined + } + + await expect( + createCampaign( + null, + campaignForm({ + type: "give", + title: "Hỗ trợ chi phí phẫu thuật", + goal_amount: "100.000.000", + template_id: "medical_emergency", + }) + ) + ).rejects.toThrow(`NEXT_REDIRECT /me/campaigns/${CAMPAIGN}`) + + const insertCall = state.calls.find((c) => c.target === "campaigns") + expect(op(insertCall, "insert")?.[0]).not.toHaveProperty("category_id") + expect(state.calls.filter((c) => c.target === "rpc:upsert_campaign_faq")).toHaveLength(3) + expect(revalidatePath).toHaveBeenCalledExactlyOnceWith("/me/campaigns") + expect(redirect).toHaveBeenCalledExactlyOnceWith(`/me/campaigns/${CAMPAIGN}`) + expect(spy).toHaveBeenCalled() + } finally { + spy.mockRestore() + } + }) + + it("looks up categories once and preserves template fields across a 23505 slug collision retry", async () => { + const template = getCampaignTemplate("medical_emergency")! + vi.mocked(uniqueSlug).mockReturnValueOnce("ho-tro-y-te-first").mockReturnValueOnce("ho-tro-y-te-second") + + let campaignAttempt = 0 + state.handler = (call) => { + if (call.target === "categories") return { data: [HEALTHCARE_CAT] } + if (call.target === "campaigns") { + campaignAttempt++ + return campaignAttempt === 1 ? { error: { code: "23505" } } : { data: { id: CAMPAIGN } } + } + if (call.target === "rpc:upsert_campaign_faq") return { data: [{ id: "faq-id" }] } + return undefined + } + + await expect( + createCampaign( + null, + campaignForm({ + type: "give", + title: "Hỗ trợ phẫu thuật", + goal_amount: "100.000.000", + template_id: "medical_emergency", + }) + ) + ).rejects.toThrow(`NEXT_REDIRECT /me/campaigns/${CAMPAIGN}`) + + expect(state.calls.filter((c) => c.target === "categories")).toHaveLength(1) + const campaignInserts = state.calls.filter((c) => c.target === "campaigns").map((c) => op(c, "insert")?.[0]) + expect(campaignInserts).toEqual([ + expect.objectContaining({ + slug: "ho-tro-y-te-first", + category_id: HEALTHCARE_CAT.id, + summary: template.summary, + story: template.story, + }), + expect.objectContaining({ + slug: "ho-tro-y-te-second", + category_id: HEALTHCARE_CAT.id, + summary: template.summary, + story: template.story, + }), + ]) + expect(state.calls.filter((c) => c.target === "rpc:upsert_campaign_faq")).toHaveLength(3) + expect(revalidatePath).toHaveBeenCalledExactlyOnceWith("/me/campaigns") + expect(redirect).toHaveBeenCalledExactlyOnceWith(`/me/campaigns/${CAMPAIGN}`) + }) +}) diff --git a/apps/web/src/app/start/actions.ts b/apps/web/src/app/start/actions.ts index a408bbd5..b5d68e4c 100644 --- a/apps/web/src/app/start/actions.ts +++ b/apps/web/src/app/start/actions.ts @@ -4,7 +4,8 @@ import { revalidatePath } from "next/cache" import { redirect } from "next/navigation" import { getSession } from "@/lib/auth/session" -import { fundingModelFor, getOrganizer } from "@/lib/campaigns" +import { getCampaignTemplate } from "@/lib/campaign-templates" +import { categoriesFor, fundingModelFor, getOrganizer, listCategories } from "@/lib/campaigns" import { dbErrorMessage, done, fail, type ActionResult } from "@/lib/errors" import { uniqueSlug } from "@/lib/slug" import { dbAs } from "@/lib/supabase" @@ -64,22 +65,46 @@ export async function createCampaign(_state: ActionResult, form: FormData): Prom if (!parsed.success) return fail(firstError(parsed.error)) const { type, title, goal_amount } = parsed.data + const template = getCampaignTemplate(form.get("template_id")) + const activeTemplate = template && template.id !== "blank" ? template : null + const db = dbAs(session.accessToken) + let categoryId: string | null = null + if (activeTemplate?.categorySlug) { + try { + const categories = await listCategories(db) + const matched = categoriesFor(categories, type).find((c) => c.slug === activeTemplate.categorySlug) + categoryId = matched?.id ?? null + } catch (error) { + console.error("createCampaign category lookup failed", error) + categoryId = null + } + } + let id: string | null = null // A random suffix makes a slug clash unlikely; retry once if it happens. for (let attempt = 0; attempt < 2 && !id; attempt++) { - const { data, error } = await db - .from("campaigns") - .insert({ - slug: uniqueSlug(title), - type, - funding_model: fundingModelFor(type), - organizer_id: session.user.id, - title, - goal_amount, - }) - .select("id") - .single() + const draft = activeTemplate + ? { + slug: uniqueSlug(title), + type, + funding_model: fundingModelFor(type), + organizer_id: session.user.id, + title, + goal_amount, + ...(categoryId ? { category_id: categoryId } : {}), + ...(activeTemplate.summary ? { summary: activeTemplate.summary } : {}), + ...(activeTemplate.story ? { story: activeTemplate.story } : {}), + } + : { + slug: uniqueSlug(title), + type, + funding_model: fundingModelFor(type), + organizer_id: session.user.id, + title, + goal_amount, + } + const { data, error } = await db.from("campaigns").insert(draft).select("id").single() if (!error) id = (data as { id: string }).id else if (error.code !== "23505") { return fail(error.code === "23503" ? "Hãy tạo hồ sơ người tổ chức trước." : dbErrorMessage(error)) @@ -87,6 +112,23 @@ export async function createCampaign(_state: ActionResult, form: FormData): Prom } if (!id) return fail(dbErrorMessage({ code: "23505" })) + if (activeTemplate) { + for (const faq of activeTemplate.starterFaqs) { + try { + const { error } = await db.rpc("upsert_campaign_faq", { + p_campaign_id: id, + p_question: faq.question, + p_answer: faq.answer, + p_faq_id: null, + p_position: null, + }) + if (error) console.error("createCampaign starter FAQ failed", error) + } catch (error) { + console.error("createCampaign starter FAQ threw", error) + } + } + } + revalidatePath("/me/campaigns") redirect(`/me/campaigns/${id}`) } diff --git a/apps/web/src/app/start/page.test.ts b/apps/web/src/app/start/page.test.ts index e3a7b586..c37a896f 100644 --- a/apps/web/src/app/start/page.test.ts +++ b/apps/web/src/app/start/page.test.ts @@ -164,6 +164,11 @@ describe("StartPage (DOS/Give#208)", () => { expect(doc.querySelector("#phone")?.getAttribute("maxlength")).toBe("20") expect(doc.querySelector("#phone")?.getAttribute("aria-describedby")).toBe("phone_hint") expect(Boolean(doc.querySelector("#organizer_reverify_hint"))).toBe(warns) + + const templateGroup = doc.querySelector('[role="radiogroup"]') + expect(templateGroup).not.toBeNull() + expect(doc.querySelectorAll('button[role="radio"]')).toHaveLength(5) + expect(doc.querySelector('input[type="hidden"][name="template_id"]')?.getAttribute("value")).toBe("blank") } ) }) diff --git a/apps/web/src/app/start/page.tsx b/apps/web/src/app/start/page.tsx index bed04e1d..4372ef8d 100644 --- a/apps/web/src/app/start/page.tsx +++ b/apps/web/src/app/start/page.tsx @@ -2,19 +2,15 @@ import type { Metadata } from "next" import { VerificationBadge } from "@/components/badges" import { ActionForm, SubmitButton } from "@/components/forms" -import { HeartIcon, SparkIcon } from "@/components/ui/icons" import { requireSession } from "@/lib/auth/session" import { getOrganizer, type Organizer } from "@/lib/campaigns" import { dbAs } from "@/lib/supabase" import { createCampaign, saveOrganizer } from "./actions" +import { StartCampaignForm } from "./StartCampaignForm" export const metadata: Metadata = { title: "Tạo chiến dịch", robots: { index: false } } -/** A campaign type choice: a bordered option; the checked one takes the selected fill (DESIGN.md 6). */ -const TYPE_CHOICE = - "flex cursor-pointer gap-3 rounded-md border border-border bg-raised p-4 transition-colors duration-150 hover:bg-surface has-[:checked]:border-primary has-[:checked]:bg-primary-soft has-[:checked]:ring-1 has-[:checked]:ring-primary" - export default async function StartPage() { const session = await requireSession("/start") const organizer = await getOrganizer(dbAs(session.accessToken), session.user.id) @@ -26,7 +22,7 @@ export default async function StartPage() {

Tạo chiến dịch

{organizer - ? "Bắt đầu bằng loại chiến dịch, tiêu đề và mục tiêu. Bạn sẽ viết tiếp câu chuyện, chọn danh mục và ảnh bìa ở bước sau." + ? "Chọn mẫu gợi ý hoặc bắt đầu bằng loại chiến dịch, tiêu đề và mục tiêu. Bạn có thể chỉnh sửa câu chuyện, danh mục và ảnh bìa ở bước sau." : "Trước tiên, cho chúng tôi biết ai đứng ra gây quỹ. Tên pháp lý cần khớp với tên chủ tài khoản nhận tiền."}

@@ -37,66 +33,7 @@ export default async function StartPage() {

Chiến dịch mới

- -
- Loại chiến dịch -
- - -
-

- Không đổi được loại sau khi gửi duyệt. -

-
-
- - -
-
- - -
- Tạo bản nháp -
+
diff --git a/apps/web/src/lib/campaign-templates.test.ts b/apps/web/src/lib/campaign-templates.test.ts new file mode 100644 index 00000000..d0201e19 --- /dev/null +++ b/apps/web/src/lib/campaign-templates.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from "vitest" + +import { FAQ_ANSWER_MAX, FAQ_QUESTION_MAX } from "./campaign-faqs" +import { CAMPAIGN_TEMPLATES, formatTemplateGoal, getCampaignTemplate } from "./campaign-templates" +import { parseVnd } from "./format" +import { campaignFaqSchema, MIN_GOAL } from "./validation" + +describe("campaign-templates (DOS/Give#338)", () => { + it("exposes the 5 curated Vietnamese templates with expected defaults", () => { + expect(CAMPAIGN_TEMPLATES.map((t) => t.id)).toEqual([ + "blank", + "medical_emergency", + "education_community", + "relief_environment", + "creative_product", + ]) + + const blank = getCampaignTemplate("blank") + expect(blank).toMatchObject({ + id: "blank", + type: "give", + categorySlug: null, + suggestedGoal: null, + summary: "", + story: "", + starterFaqs: [], + }) + + expect(getCampaignTemplate("medical_emergency")).toMatchObject({ + type: "give", + categorySlug: "healthcare", + suggestedGoal: 100_000_000, + }) + expect(getCampaignTemplate("education_community")).toMatchObject({ + type: "give", + categorySlug: "education-charity", + suggestedGoal: 50_000_000, + }) + expect(getCampaignTemplate("relief_environment")).toMatchObject({ + type: "give", + categorySlug: "disaster-relief", + suggestedGoal: 150_000_000, + }) + expect(getCampaignTemplate("creative_product")).toMatchObject({ + type: "back", + categorySlug: "technology", + suggestedGoal: 80_000_000, + }) + }) + + it("allows only known template ids and rejects unknown, non-string, or prototype keys", () => { + for (const template of CAMPAIGN_TEMPLATES) { + expect(getCampaignTemplate(template.id)).toBe(template) + } + for (const invalid of [ + null, + undefined, + "", + "unknown", + "medical", + 123, + {}, + "__proto__", + "constructor", + "toString", + ]) { + expect(getCampaignTemplate(invalid)).toBeNull() + } + }) + + it("keeps every non-blank template within DB summary/story/FAQ schema limits and parseable VND goal", () => { + const nonBlank = CAMPAIGN_TEMPLATES.filter((t) => t.id !== "blank") + expect(nonBlank).toHaveLength(4) + + for (const template of nonBlank) { + expect(template.name.trim().length).toBeGreaterThan(0) + expect(template.tagline.trim().length).toBeGreaterThan(0) + expect(template.titlePlaceholder.trim().length).toBeGreaterThan(0) + expect(template.categorySlug).toBeTruthy() + expect(template.suggestedGoal).not.toBeNull() + expect(template.suggestedGoal!).toBeGreaterThanOrEqual(MIN_GOAL) + expect(parseVnd(formatTemplateGoal(template.suggestedGoal!))).toBe(template.suggestedGoal) + + expect(template.summary.length).toBeGreaterThan(20) + expect(template.summary.length).toBeLessThanOrEqual(200) + expect(template.story.length).toBeGreaterThanOrEqual(100) + expect(template.story.length).toBeLessThanOrEqual(50_000) + expect(template.story).toContain("## ") + + expect(template.starterFaqs).toHaveLength(3) + for (const faq of template.starterFaqs) { + expect(faq.question.length).toBeLessThanOrEqual(FAQ_QUESTION_MAX) + expect(faq.answer.length).toBeLessThanOrEqual(FAQ_ANSWER_MAX) + expect(campaignFaqSchema.safeParse(faq).success).toBe(true) + } + } + }) +}) diff --git a/apps/web/src/lib/campaign-templates.ts b/apps/web/src/lib/campaign-templates.ts new file mode 100644 index 00000000..86c10aef --- /dev/null +++ b/apps/web/src/lib/campaign-templates.ts @@ -0,0 +1,230 @@ +import type { CampaignType } from "./campaigns" + +export type CampaignTemplateId = + "blank" | "medical_emergency" | "education_community" | "relief_environment" | "creative_product" + +export interface CampaignTemplateFaq { + question: string + answer: string +} + +export interface CampaignTemplate { + id: CampaignTemplateId + name: string + tagline: string + type: CampaignType + categorySlug: string | null + suggestedGoal: number | null + titlePlaceholder: string + summary: string + story: string + starterFaqs: readonly CampaignTemplateFaq[] +} + +const goalFormatter = new Intl.NumberFormat("vi-VN", { maximumFractionDigits: 0 }) + +/** Formats a template's suggested VND goal without currency symbol for numeric inputs. */ +export function formatTemplateGoal(goal: number): string { + return goalFormatter.format(goal) +} + +export const CAMPAIGN_TEMPLATES: readonly CampaignTemplate[] = [ + { + id: "blank", + name: "Tự tạo từ đầu", + tagline: "Bắt đầu với bản nháp trống, tự chọn danh mục và viết toàn bộ nội dung.", + type: "give", + categorySlug: null, + suggestedGoal: null, + titlePlaceholder: "", + summary: "", + story: "", + starterFaqs: [], + }, + { + id: "medical_emergency", + name: "Hỗ trợ y tế khẩn cấp", + tagline: "Viện phí, phẫu thuật, điều trị bệnh hiểm nghèo cho cá nhân hoặc gia đình.", + type: "give", + categorySlug: "healthcare", + suggestedGoal: 100_000_000, + titlePlaceholder: "Ví dụ: Chung tay hỗ trợ chi phí phẫu thuật cho bé Minh Anh", + summary: + "Kêu gọi chung tay hỗ trợ chi phí điều trị, phẫu thuật và hồi phục sức khỏe cho [tên người bệnh], giúp gia đình vượt qua giai đoạn khó khăn trước mắt.", + story: [ + "## Hoàn cảnh hiện tại", + "", + "[Giới thiệu ngắn gọn về người bệnh: họ tên, độ tuổi, nơi sinh sống, gia cảnh hiện tại và chẩn đoán từ bác sĩ.]", + "", + "## Tình trạng điều trị và chi phí dự kiến", + "", + "[Nêu rõ bệnh viện đang điều trị, phác đồ hoặc ca phẫu thuật sắp tới, cùng lý do gia đình không đủ khả năng tự chi trả.]", + "", + "- Chi phí phẫu thuật / điều trị chính: [Điền số tiền ước tính] ₫", + "- Thuốc men, vật tư y tế ngoài bảo hiểm: [Điền số tiền ước tính] ₫", + "- Chi phí chăm sóc và đi lại dự kiến: [Điền số tiền ước tính] ₫", + "", + "## Cam kết minh bạch và cập nhật", + "", + "Toàn bộ số tiền quyên góp được chuyển trực tiếp qua tài khoản đã xác minh của chiến dịch. Chúng tôi sẽ đăng tải hóa đơn viện phí, giấy xác nhận điều trị và cập nhật tình hình sức khỏe định kỳ để cộng đồng cùng theo dõi.", + ].join("\n"), + starterFaqs: [ + { + question: "Số tiền ủng hộ sẽ được sử dụng vào những khoản nào?", + answer: + "Toàn bộ kinh phí được ưu tiên thanh toán trực tiếp cho viện phí, thuốc men và vật tư điều trị của [tên người bệnh] theo bảng kê của bệnh viện. Mọi khoản chi đều có hóa đơn, chứng từ kèm theo trên trang sao kê.", + }, + { + question: "Tôi có thể xem giấy tờ bệnh án và cập nhật tiến triển ở đâu?", + answer: + "Chúng tôi sẽ cập nhật định kỳ tình trạng sức khỏe và các biên lai thanh toán viện phí tại mục Cập nhật của chiến dịch (các thông tin cá nhân nhạy cảm được che mờ theo quy định).", + }, + { + question: "Nếu số tiền nhận được vượt mức viện phí thực tế thì sao?", + answer: + "Phần kinh phí dư sau khi hoàn tất điều trị sẽ được dùng cho quá trình phục hồi chức năng hoặc chuyển tiếp minh bạch cho [phương án xử lý cụ thể, ví dụ: quỹ hỗ trợ bệnh nhân cùng khoa] và thông báo công khai.", + }, + ], + }, + { + id: "education_community", + name: "Giáo dục & Cộng đồng", + tagline: "Học bổng, sách vở, sửa chữa lớp học hoặc dự án nâng đỡ cộng đồng.", + type: "give", + categorySlug: "education-charity", + suggestedGoal: 50_000_000, + titlePlaceholder: "Ví dụ: Góp sách và tủ đọc cho điểm trường tiểu học vùng cao", + summary: + "Gây quỹ trao [học bổng / sách vở / thiết bị học tập] cho [số lượng] học sinh tại [địa phương], giúp các em có điều kiện học tập an toàn và bền vững.", + story: [ + "## Bối cảnh và nhu cầu thực tế", + "", + "[Mô tả địa điểm triển khai, thực trạng trường lớp hoặc hoàn cảnh của các em học sinh, người thụ hưởng hiện nay.]", + "", + "## Kế hoạch triển khai và dự toán ngân sách", + "", + "[Liệt kê từng hạng mục cụ thể dự kiến thực hiện cùng thời gian hoàn thành.]", + "", + "- Hạng mục 1 ([Ví dụ: 50 suất học bổng / 500 đầu sách]): [Điền số tiền] ₫", + "- Hạng mục 2 ([Ví dụ: Sửa chữa bàn ghế / chi phí vận chuyển]): [Điền số tiền] ₫", + "- Dự phòng phát sinh: [Điền số tiền hoặc ghi 0] ₫", + "", + "## Cách chúng tôi báo cáo kết quả", + "", + "Sau khi hoàn thành trao tặng hoặc nghiệm thu công trình, chúng tôi sẽ đăng tải danh sách bàn giao, biên bản xác nhận của nhà trường/địa phương và hình ảnh thực tế tại mục Cập nhật.", + ].join("\n"), + starterFaqs: [ + { + question: "Đối tượng thụ hưởng của chiến dịch được lựa chọn như thế nào?", + answer: + "Chúng tôi phối hợp với [tên trường / chính quyền địa phương / đối tác cộng đồng] để rà soát danh sách thực tế, ưu tiên các trường hợp có hoàn cảnh khó khăn nhất và công bố tiêu chí rõ ràng.", + }, + { + question: "Dự kiến khi nào chương trình sẽ được triển khai?", + answer: + "Chiến dịch dự kiến triển khai vào [tháng/năm] ngay sau khi kết thúc đợt gây quỹ hoặc đạt đủ kinh phí cho từng hạng mục. Lịch trình cụ thể sẽ được thông báo trước qua mục Cập nhật.", + }, + { + question: "Nếu chưa đạt đủ 100% mục tiêu, chiến dịch có thực hiện không?", + answer: + "Chiến dịch sử dụng mô hình gây quỹ linh hoạt. Nếu chưa đạt đủ mục tiêu ban đầu, chúng tôi sẽ điều chỉnh quy mô tương ứng với số tiền thực nhận và thông báo công khai phương án điều chỉnh.", + }, + ], + }, + { + id: "relief_environment", + name: "Cứu trợ & Môi trường", + tagline: "Cứu trợ khẩn cấp sau thiên tai, nhu yếu phẩm hoặc phục hồi môi trường.", + type: "give", + categorySlug: "disaster-relief", + suggestedGoal: 150_000_000, + titlePlaceholder: "Ví dụ: Gửi nhu yếu phẩm khẩn cấp tới bà con vùng ngập lụt miền Trung", + summary: + "Huy động nguồn lực khẩn cấp hỗ trợ [nhu yếu phẩm / trồng cây / khắc phục hậu quả thiên tai] cho cộng đồng tại [khu vực chịu ảnh hưởng].", + story: [ + "## Tình hình khẩn cấp tại địa phương", + "", + "[Mô tả khu vực bị ảnh hưởng bởi thiên tai hoặc vấn đề môi trường, mức độ thiệt hại và nhu cầu cấp thiết trong những ngày tới.]", + "", + "## Phương án cứu trợ và phân bổ nguồn lực", + "", + "[Nêu rõ đơn vị phối hợp tại địa phương, tuyến vận chuyển và danh mục hàng hóa/hoạt động cụ thể.]", + "", + "- Nhu yếu phẩm / vật tư thiết yếu ([gạo, nước sạch, thuốc, cây giống...]): [Điền số tiền] ₫", + "- Chi phí vận chuyển và hậu cần tại hiện trường: [Điền số tiền] ₫", + "- Hỗ trợ khắc phục sau sự cố: [Điền số tiền] ₫", + "", + "## Minh bạch tài chính và nghiệm thu", + "", + "Mọi giao dịch thu chi đều đối soát trên sao kê ngân hàng công khai. Chúng tôi sẽ cập nhật biên nhận mua hàng, xác nhận tiếp nhận từ địa phương và hình ảnh phân phối thực tế.", + ].join("\n"), + starterFaqs: [ + { + question: "Hàng cứu trợ hoặc kinh phí được chuyển đến địa phương bằng cách nào?", + answer: + "Nhóm thực hiện phối hợp trực tiếp với [tổ chức / địa phương / đội tình nguyện] tại [địa bàn] để mua sắm tập trung và trao tận tay hộ dân theo danh sách xác nhận.", + }, + { + question: "Tần suất cập nhật tiến độ thực hiện của chiến dịch ra sao?", + answer: + "Trong giai đoạn khẩn cấp, chúng tôi cập nhật [hằng ngày / 2–3 ngày một lần] về lượng hàng đã xuất kho, tiến độ trao tặng và bảng kê chi phí phát sinh.", + }, + { + question: "Tôi muốn đóng góp bằng hiện vật thay vì chuyển khoản có được không?", + answer: + "Hiện nền tảng Give ghi nhận và đối soát các khoản đóng góp tài chính qua sao kê minh bạch. Nếu muốn gửi hiện vật, bạn có thể liên hệ qua thông tin do người tổ chức chia sẻ trong phần Câu chuyện hoặc trang hồ sơ công khai (nếu có).", + }, + ], + }, + { + id: "creative_product", + name: "Sản phẩm & Dự án sáng tạo", + tagline: "Ra mắt sản phẩm công nghệ, ấn phẩm, trò chơi hoặc thiết kế có phần quà.", + type: "back", + categorySlug: "technology", + suggestedGoal: 80_000_000, + titlePlaceholder: "Ví dụ: Bàn phím cơ tiếng Việt — Phiên bản đầu tiên cho cộng đồng", + summary: + "Dự án phát triển [tên sản phẩm/tác phẩm] dành cho [nhóm người dùng], cam kết giao phần quà cho người ủng hộ khi đạt đủ mục tiêu sản xuất.", + story: [ + "## Ý tưởng và điểm khác biệt của dự án", + "", + "[Giới thiệu sản phẩm hoặc tác phẩm bạn đang xây dựng, vấn đề mà nó giải quyết và lý do dự án cần sự đồng hành từ cộng đồng.]", + "", + "## Tiến độ hiện tại và lộ trình sản xuất", + "", + "[Chia sẻ trạng thái nguyên mẫu (prototype), các mốc hoàn thiện và thời gian dự kiến giao quà cho người ủng hộ.]", + "", + "- Giai đoạn 1 — Hoàn thiện thiết kế & nguyên mẫu: [Điền thời gian dự kiến]", + "- Giai đoạn 2 — Sản xuất hàng loạt & kiểm tra chất lượng: [Điền thời gian dự kiến]", + "- Giai đoạn 3 — Đóng gói và giao quà cho người ủng hộ: [Điền tháng/năm dự kiến]", + "", + "## Rủi ro và cam kết với người ủng hộ", + "", + "Dự án hoạt động theo hình thức đạt mục tiêu mới thu tiền (all-or-nothing). [Liệt kê 1–2 rủi ro chính về chuỗi cung ứng hoặc sản xuất và cách đội ngũ dự phòng xử lý.]", + ].join("\n"), + starterFaqs: [ + { + question: "Nếu dự án không đạt đủ 100% mục tiêu thì cam kết của tôi thế nào?", + answer: + "Dự án áp dụng mô hình đạt mục tiêu mới thu tiền. Bạn chưa phải chuyển khoản khi cam kết; nếu dự án không đạt mục tiêu khi hết hạn, mọi cam kết sẽ tự động hủy.", + }, + { + question: "Thời gian giao phần quà dự kiến và phí vận chuyển tính như thế nào?", + answer: + "Thời gian giao dự kiến được ghi rõ trên từng gói phần quà. Phí vận chuyển (nếu có) và phạm vi giao hàng sẽ được nêu cụ thể ở ghi chú giao quà của từng mức ủng hộ.", + }, + { + question: "Tôi có thể thay đổi gói phần quà hoặc thông tin nhận hàng sau khi cam kết không?", + answer: + "Trong thời gian dự án đang mở gây quỹ và trước khi chốt đơn sản xuất, bạn có thể vào mục quản lý cam kết cá nhân trên Give để điều chỉnh gói quà hoặc địa chỉ nhận hàng.", + }, + ], + }, +] + +/** Allowlist lookup returning a curated template by id, or null when missing/unknown. */ +export function getCampaignTemplate(id: unknown): CampaignTemplate | null { + if (typeof id !== "string") return null + return CAMPAIGN_TEMPLATES.find((template) => template.id === id) ?? null +}