diff --git a/docs/deployment.md b/docs/deployment.md index 45db32c..a313bc5 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -143,6 +143,16 @@ Run both before `service-whatsapp` starts. Give the services' database user the Run the three in order before the new services-system, gateway and mobile-api go live. `01` needs a user that may create tables. Run `03` once only: it overwrites the Chinese of every back-office label, so running it again after staff have edited translations undoes their edits. `99-rollback.sql` in the same folder drops the two tables and removes the modules; the Chinese stays in `message`, which the previous images never read. +| File | What it does | +|---|---| +| `openspec/changes/archive/-add-landing-pages/sql/01-pages.sql` | Creates `service-counter`.`cms_page` (landing pages, blocks as JSON, slug unique per company) and `page_image` (uploaded images, at most 2 MB each). DDL. | +| `openspec/changes/archive/-add-landing-pages/sql/02-event-lead-web.sql` | Adds `page_path`, `utm_source`, `utm_medium` and `utm_campaign` to `event_lead`, for sign-ups from a landing page (source `WEB`). DDL. | +| `openspec/changes/archive/-add-landing-pages/sql/03-company-branding.sql` | Adds `logo_image_id` and `accent_color` to `service-system`.`company`. DDL. | +| `openspec/changes/archive/-add-landing-pages/sql/04-module.sql` | Adds the Pages back-office module (`BO_PAGES`) under Events. No role gets it; super admins grant it under Roles. | +| `openspec/changes/archive/-add-landing-pages/sql/05-page-labels.sql` | Adds the landing-page labels in English and Chinese. Run it only where `add-zh-cn-messages/sql/03` already ran before this change; the regenerated 03 already includes them. | + +Run them in order before the new services-counter, services-system and mobile-api go live: the new services read the new columns on every event lead and company query. `01` to `03` need a user that may alter tables. `99-rollback.sql` in the same folder removes the module and drops the two tables and the columns, which deletes every page, image, page address and campaign tag. + **Review the privacy notice before go-live.** The seeded text is a starting template written for the PDPA, not legal advice. INS and CV should each have theirs checked; a super admin changes it under **Companies → Privacy notice**. A company with no notice has no working QR codes. **Database user:** @@ -297,6 +307,8 @@ QR registration pages (`/r/`) are served by the admin portal on the same h **Public pages on their own hostname.** The owner wants the public pages (`/r`, `/i`, `/c`) served on their own hostname, for example `go.`, so that printed QR links survive a later move to the customer portal. Route that hostname to the same `admin-portal` Service with TLS, and set `ADMIN_PORTAL_BASE_URL` to the address the invitation links should carry. +**Landing pages.** Published pages live at `/p//` on the admin portal, with their images at `/api/public/page-images/` and their form at `/api/public/pages/...`. They need no new route: serve them on the public-pages hostname above, so printed and shared page links survive a later move to the customer portal. + ## 9. Secret templates There is no template yet for `service-email` (its keys wait for the email provider) or `service-system` (its Jumio keys stay unset). Kubernetes Secrets hold base64 values. Encode each one with `printf '%s' 'value' | base64 -w0`. These are templates: replace every `<…>` and never commit the filled-in files. @@ -401,6 +413,14 @@ data: - **WhatsApp webhook and outages.** If `service-whatsapp` is down or answers with an error, the webhook answers 503 and Meta sends the event again, for up to 7 days; a message is never stored twice. The same happens right after `service-whatsapp` starts while `service-system` is unreachable. Keep `service-system` up before `service-whatsapp` (section 2). - **Client addresses for rate limits.** mobile-api takes a caller's address for its rate limits from the first entry of `X-Forwarded-For` when the header is present (`HttpReqRespUtils` in core-libs). On the webhook route, a caller can set that header itself and so pick its own limit bucket. The webhook still rejects anything Meta did not sign, so this only weakens the flood limit (6000 calls per 10 minutes per address). Check that Traefik replaces an `X-Forwarded-For` sent by an untrusted caller instead of passing it on (`forwardedHeaders.insecure` off, `trustedIPs` limited to real proxies). +- **Landing pages.** + - Images live in MySQL (`page_image`), at most 2 MB each. That suits a few hundred images; past that, move them to object storage. + - Image ids are sequential and every image is public by id, so an image uploaded for a draft page can be read before the page is published. Do not upload anything confidential as a page image. + - An image removed from a page stays stored; nothing deletes unused images. + - The editor warns about unsaved edits only on reload or close, not when staff click another link in the back office. + - A standing enquiries event (section 12) appears in event lists and dashboards like any event. + - Links accept only `https://`, `mailto:`, `tel:` or a path starting with `/`. A same-page `#anchor` link (for example a hero button that jumps to the form) is refused; use the page's own path instead. + ## 11. Connecting WhatsApp (Meta) Do this per company, after the services run with the variables of section 6. A Meta admin of the company's WhatsApp Business Account does it in Meta's developer console. @@ -420,3 +440,17 @@ Do this per company, after the services run with the variables of section 6. A M 7. **First real message.** From a personal phone, send a WhatsApp message to the company's number. It must appear under WhatsApp within 30 seconds, in the right company only. Reply from Co-Lite and check that it arrives. Outside 24 hours after the customer's last message, Meta allows only templates; Co-Lite then offers only the template picker. If nothing arrives: the mobile-api log says `WhatsApp webhook forward failed: ` when it could not hand an event on, and Meta's webhook page shows failed deliveries. A 401 there means the app secret does not match the app that sends. + +## 12. Landing pages + +Marketing builds public pages under **Events → Pages**. Each page has blocks (hero, text, image with text, FAQ and a sign-up form) and is a draft until published. Its address is `/p//`. + +1. **Module.** Grant `BO_PAGES` to the roles that build pages. +2. **Branding.** A super admin sets each company's logo and accent colour under **Companies → Branding**. Buttons on the company's pages use the accent colour, with black or white text, whichever is easier to read. Without them the page shows the company name and the default blue. +3. **Standing enquiries event.** A sign-up form always belongs to an event. For general enquiries, each company creates one event, for example "INS website enquiries", with a far-off end date and its sales team, and picks it in the form block. Sign-ups from a landing page are never marked as attended, so this event does not inflate attendance. Name it clearly: it shows in event lists and dashboards. +4. **The INS page.** The INS proof of concept (`ins-landing-page`, never deployed) is content, not code: rebuild it by hand in the editor after deploy. Its test leads are not imported. +5. **Check.** Publish a page, open its address signed out, sign up through its form with `?utm_source=test` on the address, and check that the event lead shows source **Web page**, the page address and the campaign. Delete that test lead afterwards. + +A form stops taking sign-ups when its event is disabled, its end date has passed (Malaysia time), or the company has no privacy notice; the page then says sign-up is closed and still shows its other blocks. Sign-ups share the QR pages' rate limits. + +**New portal dependencies:** `@tiptap/react`, `@tiptap/pm`, `@tiptap/starter-kit` and `@tiptap/extension-text-align` (the editor, loaded only on the editor screens), and `sanitize-html` (cleans page text on the server before it reaches a visitor). The image build installs them from `package-lock.json`; nothing to do by hand. diff --git a/docs/superpowers/specs/2026-12-02-landing-pages-design.md b/docs/superpowers/specs/2026-12-02-landing-pages-design.md new file mode 100644 index 0000000..af73b95 --- /dev/null +++ b/docs/superpowers/specs/2026-12-02-landing-pages-design.md @@ -0,0 +1,129 @@ +# Landing Pages + +Status: draft for the owner's approval, 2026-12-02. + +## Intent + +Marketing wants public pages, per company, that feed the lead pipeline. Each page is either an event sign-up page or a general enquiry page. We port babyboo's CMS page builder instead of hand-building each page. The INS landing-page proof of concept (`~/Projects/ins-landing-page`, never deployed) is rebuilt as the first page. Its leads were never real, so none are imported. + +Timing: after the WhatsApp inbox and before go-live on 2027-01-15. + +## Goals + +- Staff with `BO_PAGES` build pages for their own company from blocks: hero, rich text, image with text, FAQ and form. They save a page as a draft or publish it. +- A published page is public at `/p//`, rendered on the server so search engines and link previews read it. +- The form block creates real Co-Lite leads through the existing sign-up rules: consent, matching by mobile then email, a new or existing lead, and interests. The lead source is a new value, "Web page", and the capture records the page and the visitor's UTM tags. +- Each company has a logo and one accent colour, used on all its landing pages. + +## Non-Goals + +- No leads without an event (decided 2026-12-02: approach 1 below). General enquiries go to a standing "enquiries" event that the company creates. +- No custom form builder (babyboo's `cms-forms`). The form block always uses Co-Lite's sign-up form. +- No custom domain per company. There is one public hostname with a path per company. +- The QR sign-up and invitation pages (`/r`, `/i`, `/c`) keep their neutral look. Company branding there is a later choice. +- No babyboo product blocks: featured products and collection list. + +## Anti-Goals + +- A landing page must never write leads outside the sign-up rules: no second lead-creation path with weaker matching or no consent. +- A company must never see, edit or show another company's pages, images or events. +- Page HTML must not run scripts on the public page. + +## Constraints + +- **Hosting:** public pages stay in the admin portal for go-live, on their own hostname (for example `go.`). This keeps printed QR links working after a later move to the customer portal. No host-splitting middleware: the existing public-route logic (`isPublicPath`) is extended to `/p`. +- **APIs:** admin screens call `/api/admin/**` in mobile-api. Public reads and submits use `/api/public/**` with the API key and no session. +- **Data:** new tables carry `company_id`. DDL for real environments goes in the OpenSpec change folder, and the local seed in `local/seed/`. +- **Porting rule:** when porting, list babyboo's business rules first and turn them into tests before building the screen. +- **Infrastructure:** Co-Lite has no file service (babyboo's `services-drive`), and adding one is out of scope. + +## Approaches + +### Where a general enquiry goes (decided by the owner) + +1. **A standing "enquiries" event per company (chosen).** The company creates an event such as "INS website enquiries", with a far-off end date and a team. Every form block points at an event, so status, follow-ups, salesperson, the dashboard and the WhatsApp owner all work unchanged. The cost is that enquiries appear as an event in event lists and dashboards. +2. **Leads with no event.** This would move status, salesperson and follow-ups onto the lead, and teach the lead list, dashboard, WhatsApp owner and exports about leads without an event. It is the cleaner model, but it reworks the pipeline weeks before go-live. It can follow after go-live by moving the standing event's captures. + +### The look (decided by the owner) + +1. **Company logo and accent colour (chosen).** These are set once per company and used on all its pages. +2. **The neutral Co-Lite look.** Less work, but every company's pages look the same. + +### Image storage (my call; the owner can override) + +1. **Images in MySQL (chosen).** + - A `page_image` table holds the bytes, at most 2 MB each, in PNG, JPEG or WebP only. + - Images are served publicly by id with long cache headers. + - There is no new infrastructure, and backups already cover the database. + - Its ceiling is a few hundred images. Past that, move to object storage. +2. **Object storage (S3-compatible or MinIO on the cluster).** It scales, but it is new infrastructure, credentials and backups for a few dozen images. +3. **External image URLs only.** No upload: marketing hosts images elsewhere. It is fragile, and staff would need somewhere to host them. + +## Design + +### Model (services-counter, beside events and event leads) + +- **`cms_page`:** + - columns: `id`, `company_id`, `slug`, `title`, `meta_description`, `status` (DRAFT or PUBLISHED), the blocks as JSON, and the audit columns; + - `slug` is unique per company, ignoring case; + - at most 30 blocks per page, stored and returned in order; + - a save replaces the blocks as a whole (babyboo rule). +- **Blocks** (ported from babyboo, minus the product blocks): + - HERO: `imageId`, `heading`, optional `text`, optional `buttonLabel` and `buttonUrl`. + - RICH_TEXT: `html`. + - IMAGE_TEXT: `imageId`, `imagePosition` (LEFT or RIGHT), optional `heading`, `html`, optional button. + - FAQ: optional `heading`, 1 to 30 `question` and `answer` pairs, in plain text. + - FORM: optional `heading`, `eventUuid`. The event must belong to the page's company. + - Field limits and link rules are ported from babyboo's validation. Buttons allow only `https:`, `mailto:`, `tel:` and same-site paths. +- **`page_image`:** `id`, `company_id`, `content_type`, `bytes`, `created`. Images are company-scoped for staff and public by id. +- **Company:** `logo_image_id` and `accent_color` (`#RRGGBB`), edited on the existing Companies screen. +- **Event lead:** a new source value `WEB`, plus a nullable `page_id`, `utm_source`, `utm_medium` and `utm_campaign`. These show on the event lead detail and in the lead export. + +### The form block's submit + +- The public submit takes the company code, the slug and the block position. +- The server finds the published page and its FORM block's event. It then runs the same registration service the QR flow uses, with source `WEB`, no salesperson, the page id and the UTM tags. +- The form works under the same conditions as an event code: the event is enabled, its end date in Malaysia time has not passed, and the company has a privacy notice. When the form cannot work, the page still shows its other blocks, and the form area says sign-up is closed. +- The QR flow's registration abuse limits apply to this submit too. +- **Builder check:** + - The submit reuses `PublicRegistrationService` in mobile-api for validation and normalisation. It also reuses `RegistrationService.register` in services-counter, which already takes a `source`. + - That service marks a registration as attended when it is not an INVITE and arrives during the event. A WEB registration MUST NOT be marked attended. Otherwise every enquiry to a standing event, which is always running, would count as an attendance. + - The notes text "Registered by QR with: …" must say "web page" for WEB registrations. + +### Admin portal + +- A **Pages** entry is added to the sidebar under a new "Website" group, or under Events if the group would hold only one item. This is the builder's call; the sidebar spec decides. +- **List:** title, slug, status and updated time. Plus a page editor ported from babyboo's `PageEditor` and `BlockFields`: + - Tiptap for rich text, with babyboo's extension set minus YouTube and tables, unless the INS page needs them; + - image upload on HERO and IMAGE_TEXT; + - an event picker for FORM, limited to the company's enabled events that have not ended; + - a "View page" link after saving; + - drafts can be previewed by signed-in staff. +- **Tiptap:** a new dependency for the portal (`@tiptap/*`), the same versions as babyboo. +- **Sanitising:** `sanitize-html` sanitises the HTML at render time with an allow-list. This is a second new dependency. Saves also reject `' }, + { type: "HERO", heading: "Hi", buttonLabel: "Go", buttonUrl: "javascript:alert(1)" }, + { type: "IMAGE_TEXT", heading: "Side", buttonLabel: "Mail", buttonUrl: "mailto:a@b.c" }, + ])} />); + expect(screen.getByText("Hello")).toBeInTheDocument(); + expect(document.querySelector("script, [onerror]")).toBeNull(); + expect(screen.queryByRole("link", { name: "Go" })).not.toBeInTheDocument(); + expect(screen.getByRole("link", { name: "Mail" })).toHaveAttribute("href", "mailto:a@b.c"); + }); + + it("a closed form says so; the preview shows a note instead of a form", () => { + const { unmount } = render(); + expect(screen.getByText("Sign-up is closed.")).toBeInTheDocument(); + unmount(); + render(); + expect(screen.getByText("The sign-up form shows here on the published page.")).toBeInTheDocument(); + expect(screen.queryByLabelText(/name/i)).not.toBeInTheDocument(); + }); + + it("an open form posts to its block with the page's UTM tags, and a closed answer closes it", async () => { + window.history.replaceState(null, "", "/p/INS/hotel?utm_source=fb&utm_medium=cpc&utm_campaign=jan"); + const fetchMock = vi.spyOn(globalThis, "fetch") + .mockResolvedValueOnce(new Response(JSON.stringify({ code: "FORM_CLOSED" }), { status: 409 })); + const user = userEvent.setup(); + render(x

" }, { type: "FORM", form: info }])} />); + await user.type(screen.getByLabelText("Your name"), "Tan"); + await user.type(screen.getByLabelText("Mobile number"), "0125550101"); + await user.click(screen.getByRole("checkbox")); + await user.click(screen.getByRole("button", { name: "Register" })); + const [url, init] = fetchMock.mock.calls[0]; + expect(url).toBe("/api/public/pages/INS/hotel/form/1"); + expect(JSON.parse(String((init as RequestInit).body))).toMatchObject({ name: "Tan", utmSource: "fb", utmMedium: "cpc", utmCampaign: "jan" }); + expect(await screen.findByText("Sign-up is closed.")).toBeInTheDocument(); + }); +}); + +describe("utmTags", () => { + it("reads the three tags, capped at 100 characters", () => { + expect(utmTags("?utm_source=" + "x".repeat(150))).toEqual({ utmSource: "x".repeat(100), utmMedium: undefined, utmCampaign: undefined }); + }); +}); diff --git a/solvway-admin-portal/app/components/pages/CmsBlocks.tsx b/solvway-admin-portal/app/components/pages/CmsBlocks.tsx new file mode 100644 index 0000000..66e4cf1 --- /dev/null +++ b/solvway-admin-portal/app/components/pages/CmsBlocks.tsx @@ -0,0 +1,118 @@ +import type { CSSProperties, ReactNode } from "react"; +import { contrastText, imageSrc, isSafeLink, type CmsBlock } from "@/app/lib/cmsPages"; +import type { RegistrationInfo } from "@/app/lib/services/publicRegistration"; +import { SafeHtml } from "./SafeHtml"; +import { LandingForm } from "./LandingForm"; + +// Landing-page blocks, ported from babyboo's CmsBlocks minus the product blocks. HTML only goes through SafeHtml; +// images are this company's uploads; buttons render only for a safe link, checked again here. + +export type PublicBlock = CmsBlock & { form?: RegistrationInfo; closed?: boolean }; + +export interface Branding { + code: string; + name: string; + logoImageId?: number | null; + accentColor?: string | null; +} + +const PROSE = "space-y-3 text-base leading-relaxed [&_a]:text-primary [&_a]:underline [&_blockquote]:border-l-2 [&_blockquote]:pl-3 [&_h2]:text-2xl [&_h2]:font-semibold [&_h3]:text-xl [&_h3]:font-semibold [&_ol]:list-decimal [&_ol]:pl-5 [&_ul]:list-disc [&_ul]:pl-5"; + +function ButtonLink({ block }: { block: CmsBlock }) { + if (!block.buttonLabel || !isSafeLink(block.buttonUrl)) return null; + const external = /^https:/i.test(block.buttonUrl!); + return ( + + {block.buttonLabel} + + ); +} + +function BlockImage({ id, className }: { id?: number | null; className: string }) { + // eslint-disable-next-line @next/next/no-img-element -- an uploaded image of unknown size + return id ? : null; +} + +function Block({ block, index, company, slug, preview }: { block: PublicBlock; index: number; company: string; slug: string; preview?: boolean }) { + switch (block.type) { + case "HERO": + return ( +
+ +
+ {block.heading ?

{block.heading}

: null} + {block.text ?

{block.text}

: null} +
+
+
+ ); + case "RICH_TEXT": + return block.html ?
: null; + case "IMAGE_TEXT": + return ( +
+ +
+ {block.heading ?

{block.heading}

: null} + {block.html ? : null} + +
+
+ ); + case "FAQ": + return block.items?.length ? ( +
+ {block.heading ?

{block.heading}

: null} +
+ {block.items.map((item, i) => ( +
+ {item.question} +

{item.answer}

+
+ ))} +
+
+ ) : null; + case "FORM": + return ( +
+ {block.heading ?

{block.heading}

: null} + +
+ ); + default: + return null; + } +} + +/** A whole landing page: the company header (logo, accent), the title as the only h1, then the blocks. */ +export function LandingPage({ company, page, banner, preview }: { + company: Branding; + page: { slug: string; title: string; blocks: PublicBlock[] }; + banner?: ReactNode; + /** The editor's draft preview: forms show a note instead of taking sign-ups. */ + preview?: boolean; +}) { + const accent = company.accentColor && /^#[0-9A-Fa-f]{6}$/.test(company.accentColor) ? company.accentColor : null; + const style = accent ? ({ "--primary": accent, "--primary-foreground": contrastText(accent), "--ring": accent } as CSSProperties) : undefined; + return ( +
+ {banner} +
+
+ {company.logoImageId ? ( + // eslint-disable-next-line @next/next/no-img-element -- the company's uploaded logo + {company.name} + ) : ( + {company.name} + )} +
+
+
+

{page.title}

+ {page.blocks.map((block, i) => )} +
+
+ ); +} diff --git a/solvway-admin-portal/app/components/pages/LandingForm.tsx b/solvway-admin-portal/app/components/pages/LandingForm.tsx new file mode 100644 index 0000000..cfc2224 --- /dev/null +++ b/solvway-admin-portal/app/components/pages/LandingForm.tsx @@ -0,0 +1,37 @@ +"use client"; + +import { useState } from "react"; +import { AlertCircle, CheckCircle2 } from "lucide-react"; +import { Button } from "@/app/components/ui/button"; +import { VisitorState } from "@/app/components/registration/VisitorCard"; +import { RegistrationForm } from "@/app/components/registration/RegistrationForm"; +import { publicCall, type RegistrationBody, type RegistrationInfo } from "@/app/lib/services/publicRegistration"; +import { useT } from "@/app/lib/i18n/MessagesProvider"; + +const UTM = ["utm_source", "utm_medium", "utm_campaign"] as const; + +/** The page address's UTM tags, as the submit body names them. */ +export function utmTags(search: string): { utmSource?: string; utmMedium?: string; utmCampaign?: string } { + const q = new URLSearchParams(search); + const [utmSource, utmMedium, utmCampaign] = UTM.map((k) => q.get(k)?.slice(0, 100) || undefined); + return { utmSource, utmMedium, utmCampaign }; +} + +// A landing page's FORM block: the QR sign-up form, posting to the page's block, with the visitor's UTM tags. +export function LandingForm({ companyCode, slug, index, info, preview }: { companyCode: string; slug: string; index: number; info?: RegistrationInfo; preview?: boolean }) { + const t = useT(); + const [phase, setPhase] = useState<"form" | "done" | "closed">(info ? "form" : "closed"); + + if (preview) return ; + if (phase === "closed" || !info) return ; + if (phase === "done") { + return setPhase("form")}>{t("RegAnother")}} />; + } + const submit = (body: RegistrationBody) => + publicCall(`/api/public/pages/${encodeURIComponent(companyCode)}/${encodeURIComponent(slug)}/form/${index}`, { + method: "POST", + body: JSON.stringify({ ...body, ...utmTags(window.location.search) }), + }); + return setPhase("done")} onInactive={() => setPhase("closed")} />; +} diff --git a/solvway-admin-portal/app/components/pages/PageEditor.test.tsx b/solvway-admin-portal/app/components/pages/PageEditor.test.tsx new file mode 100644 index 0000000..b8da06a --- /dev/null +++ b/solvway-admin-portal/app/components/pages/PageEditor.test.tsx @@ -0,0 +1,112 @@ +import { render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { ApiError } from "@/app/lib/clientApi"; + +const mocks = vi.hoisted(() => ({ + getPage: vi.fn(), savePage: vi.fn(), deletePage: vi.fn(), uploadPageImage: vi.fn(), + listAdminEvents: vi.fn(), useAdminAuth: vi.fn(), useCompanyScope: vi.fn(), +})); +vi.mock("@/app/lib/services/adminPages", () => ({ getPage: mocks.getPage, savePage: mocks.savePage, deletePage: mocks.deletePage, uploadPageImage: mocks.uploadPageImage })); +vi.mock("@/app/lib/services/adminEvents", () => ({ listAdminEvents: mocks.listAdminEvents })); +vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth })); +vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope })); +vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock); + +import { memoryRouter } from "@/test/memoryRouter"; +import { PageEditor } from "./PageEditor"; + +const stored = { + id: 5, companyId: 2, slug: "hotel", title: "Hotel", metaDescription: null, status: "PUBLISHED" as const, + blocks: [{ type: "HERO" as const, heading: "Hi", imageId: 9 }, { type: "FORM" as const, heading: "Join", eventUuid: "3312726793093644288" }], +}; + +beforeEach(() => { + vi.clearAllMocks(); + memoryRouter.reset("/pages/5"); + mocks.useAdminAuth.mockReturnValue({ isSuper: false, companyCode: "INS" }); + mocks.useCompanyScope.mockReturnValue({ companyId: undefined, companies: [{ id: 2, code: "INS", name: "INS", status: "A" }], codeOf: (id?: number) => (id === 2 ? "INS" : "") }); + mocks.listAdminEvents.mockResolvedValue({ items: [ + { uuid: "3312726793093644288", name: "Website enquiries", endDate: "2099-12-31", enabled: true, location: "", startDate: "" }, + { uuid: "1", name: "Old fair", endDate: "2020-01-01", enabled: true, location: "", startDate: "" }, + ], total: 2 }); + mocks.getPage.mockResolvedValue(stored); + mocks.savePage.mockImplementation(async (id: number | undefined, body: object) => ({ ...stored, ...body, id: id ?? 7 })); +}); + +describe("PageEditor", () => { + it("names the rich text box after its field label", async () => { + const user = userEvent.setup(); + render(); + await screen.findByLabelText("Event"); + await user.click(screen.getByRole("button", { name: "Add Text" })); + expect(await screen.findByRole("textbox", { name: "Content" })).toHaveAttribute("contenteditable", "true"); + }); + + it("loads a page, offers only events that have not ended, and saves the blocks in order", async () => { + const user = userEvent.setup(); + render(); + const picker = await screen.findByLabelText("Event"); + await waitFor(() => expect(screen.getByRole("option", { name: "Website enquiries" })).toBeInTheDocument()); + expect(screen.queryByRole("option", { name: "Old fair" })).not.toBeInTheDocument(); + expect(picker).toHaveValue("3312726793093644288"); + expect(screen.getByRole("link", { name: "View page" })).toHaveAttribute("href", "/p/INS/hotel"); + expect(screen.getByRole("link", { name: "Preview" })).toHaveAttribute("href", "/pages/5/preview"); + + await user.click(screen.getAllByRole("button", { name: "Move down" })[0]); + await user.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => expect(mocks.savePage).toHaveBeenCalled()); + const [id, body] = mocks.savePage.mock.calls[0]; + expect(id).toBe(5); + expect(body.blocks.map((b: { type: string }) => b.type)).toEqual(["FORM", "HERO"]); + expect(body.blocks[0].eventUuid).toBe("3312726793093644288"); + expect(await screen.findByRole("status")).toHaveTextContent("Page saved"); + }); + + it("shows a server refusal at its field", async () => { + mocks.savePage.mockRejectedValue(new ApiError("x", 422, { code: "PagesBadLink", details: { field: "blocks[0].buttonUrl" } })); + const user = userEvent.setup(); + render(); + await screen.findByLabelText("Event"); + await user.click(screen.getByRole("button", { name: "Save" })); + const link = screen.getAllByLabelText("Button link")[0]; + expect(await screen.findByText("Use a link that starts with https://, mailto:, tel: or /.")).toBeInTheDocument(); + expect(link.closest("div")).toHaveTextContent("Use a link that starts with https://, mailto:, tel: or /."); + }); + + it("uploads a chosen image on save and puts its id on the block", async () => { + mocks.uploadPageImage.mockResolvedValue({ id: 44 }); + const user = userEvent.setup(); + render(); + await screen.findByLabelText("Event"); + await user.upload(screen.getByLabelText("Image"), new File(["png"], "hero.png", { type: "image/png" })); + await user.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => expect(mocks.savePage).toHaveBeenCalled()); + expect(mocks.uploadPageImage).toHaveBeenCalledWith(2, expect.any(String)); + expect(mocks.savePage.mock.calls[0][1].blocks[0].imageId).toBe(44); + }); + + it("asks before deleting", async () => { + mocks.deletePage.mockResolvedValue(undefined); + const user = userEvent.setup(); + render(); + await user.click(await screen.findByRole("button", { name: "Delete page" })); + expect(mocks.deletePage).not.toHaveBeenCalled(); + await user.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Delete page" })); + await waitFor(() => expect(mocks.deletePage).toHaveBeenCalledWith(5)); + expect(memoryRouter.push).toHaveBeenCalledWith("/pages"); + }); + + it("a super admin must choose a company for a new page", async () => { + mocks.useAdminAuth.mockReturnValue({ isSuper: true, companyCode: null }); + const user = userEvent.setup(); + render(); + await user.type(screen.getByLabelText("Title"), "Hotel Day"); + expect(screen.getByLabelText("Slug")).toHaveValue("hotel-day"); + await user.click(screen.getByRole("button", { name: "Save" })); + expect(await screen.findByText("Choose a company.")).toBeInTheDocument(); + expect(mocks.savePage).not.toHaveBeenCalled(); + }); +}); + +import { within } from "@testing-library/react"; diff --git a/solvway-admin-portal/app/components/pages/PageEditor.tsx b/solvway-admin-portal/app/components/pages/PageEditor.tsx new file mode 100644 index 0000000..0be7fa8 --- /dev/null +++ b/solvway-admin-portal/app/components/pages/PageEditor.tsx @@ -0,0 +1,322 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import Link from "next/link"; +import { useRouter, useSearchParams } from "next/navigation"; +import { Button } from "@/app/components/ui/button"; +import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card"; +import { ConfirmDialog } from "@/app/components/ui/confirm-dialog"; +import { Input } from "@/app/components/ui/input"; +import { Label } from "@/app/components/ui/label"; +import { Textarea } from "@/app/components/ui/textarea"; +import { ErrorState } from "@/app/components/ui/states"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select"; +import { ApiError } from "@/app/lib/clientApi"; +import { useAdminAuth } from "@/app/lib/AdminAuthContext"; +import { useCompanyScope } from "@/app/lib/CompanyScope"; +import { BLOCK_LABELS, BLOCK_TYPES, emptyBlock, emptyPage, pageAddress, pageBody, withTitle, type CmsBlock, type CmsPageDraft, type PageStatus } from "@/app/lib/cmsPages"; +import { deletePage, getPage, savePage, uploadPageImage } from "@/app/lib/services/adminPages"; +import { listAdminEvents } from "@/app/lib/services/adminEvents"; +import { useT } from "@/app/lib/i18n/MessagesProvider"; +import { BlockFields, type EventOption } from "./BlockFields"; + +// The landing-page editor, ported from babyboo's PageEditor. Every block carries a stable key, so a chosen image +// follows its block through moves and removals. Block images upload on Save, just before the page is saved, +// each at most once even when a later step fails. + +interface Row { + key: number; + block: CmsBlock; +} + +function readDataUrl(file: File): Promise { + return new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.onload = () => resolve(reader.result as string); + reader.onerror = () => reject(reader.error); + reader.readAsDataURL(file); + }); +} + +const malaysiaToday = () => new Intl.DateTimeFormat("en-CA", { timeZone: "Asia/Kuala_Lumpur" }).format(new Date()); + +function FieldError({ message }: { message?: string }) { + return message ?

{message}

: null; +} + +export function PageEditor({ pageId }: { pageId?: number }) { + const t = useT(); + const router = useRouter(); + const { isSuper, companyCode } = useAdminAuth(); + const scope = useCompanyScope(); + const justSaved = useSearchParams()?.get("saved") === "1"; + const [draft, setDraft] = useState(() => ({ ...emptyPage(), companyId: scope.companyId })); + const [rows, setRows] = useState([]); + const [pending, setPending] = useState>({}); + // The page as last loaded or saved: what "View page" points at. + const [saved, setSaved] = useState<{ slug: string; status: PageStatus } | null>(null); + const [dirty, setDirty] = useState(false); + const [loading, setLoading] = useState(pageId != null); + const [loadError, setLoadError] = useState(null); + const [errors, setErrors] = useState>({}); + const [summary, setSummary] = useState(null); + const [notice, setNotice] = useState(justSaved ? "PagesSaved" : null); + const [saving, setSaving] = useState(false); + const [confirmDelete, setConfirmDelete] = useState(false); + const [events, setEvents] = useState([]); + const nextKey = useRef(0); + const toRows = (blocks: CmsBlock[]) => blocks.map((block) => ({ key: ++nextKey.current, block })); + const isNew = draft.id == null; + const code = (isSuper ? scope.codeOf(draft.companyId) : companyCode) || ""; + + useEffect(() => { + if (pageId == null) return; + let cancelled = false; + getPage(pageId) + .then((p) => { + if (cancelled) return; + setDraft({ id: p.id, companyId: p.companyId, slug: p.slug, slugTouched: true, title: p.title, metaDescription: p.metaDescription ?? "", status: p.status, blocks: [] }); + setRows(toRows(p.blocks ?? [])); + setSaved({ slug: p.slug, status: p.status }); + }) + .catch((err: unknown) => { if (!cancelled) setLoadError(err instanceof ApiError && err.status === 404 ? "PagesNotFound" : "PagesLoadFailed"); }) + .finally(() => { if (!cancelled) setLoading(false); }); + return () => { cancelled = true; }; + }, [pageId]); + + // The FORM picker: the page company's enabled events that have not ended (Malaysia dates). + const eventsCompany = isSuper ? draft.companyId : undefined; + useEffect(() => { + if (isSuper && !eventsCompany) return; + let live = true; + const today = malaysiaToday(); + listAdminEvents({ enabled: "Y", page: 1, pageSize: 100, sortBy: "name", sortDir: "asc", companyId: eventsCompany }) + .then((r) => { if (live) setEvents(r.items.filter((e) => !e.endDate || e.endDate >= today).map((e) => ({ uuid: e.uuid, name: e.name }))); }) + .catch(() => {}); // the picker stays empty; a saved event still shows as unavailable + return () => { live = false; }; + }, [isSuper, eventsCompany]); + + // Unsaved edits: the browser asks before a reload or close. ponytail: in-app links are not guarded; add a router guard if staff lose work that way. + useEffect(() => { + if (!dirty) return; + const warn = (e: BeforeUnloadEvent) => e.preventDefault(); + window.addEventListener("beforeunload", warn); + return () => window.removeEventListener("beforeunload", warn); + }, [dirty]); + + const edit = (fn: (v: T) => void) => (v: T) => { setDirty(true); fn(v); }; + const patch = edit((next: Partial) => setDraft((d) => ({ ...d, ...next }))); + const updateBlock = (key: number, update: (block: CmsBlock) => CmsBlock) => { + setDirty(true); + setRows((rs) => rs.map((r) => (r.key === key ? { ...r, block: update(r.block) } : r))); + }; + const moveBlock = (index: number, delta: -1 | 1) => { + setDirty(true); + setRows((rs) => { + const next = [...rs]; + [next[index], next[index + delta]] = [next[index + delta], next[index]]; + return next; + }); + }; + const removeBlock = (key: number) => { + setDirty(true); + setRows((rs) => rs.filter((r) => r.key !== key)); + setPending(({ [key]: _dropped, ...rest }) => rest); + }; + const chooseImage = (key: number, file: File) => { + setDirty(true); + setPending((p) => ({ ...p, [key]: { file } })); + readDataUrl(file) + .then((preview) => setPending((p) => (p[key]?.file === file ? { ...p, [key]: { file, preview } } : p))) + .catch(() => {}); + }; + + function showError(err: unknown) { + const data = err instanceof ApiError ? (err.data as { code?: string; details?: { field?: string } } | undefined) : undefined; + const field = data?.details?.field; + const message = data?.code ? t(data.code) : t("PagesSaveFailed"); + if (field) setErrors({ [field === "file" ? "blocks" : field]: message }); + else setSummary(message); + } + + async function save() { + setSummary(null); + setNotice(null); + setErrors({}); + if (isNew && isSuper && !draft.companyId) { + setErrors({ companyId: t("ChooseCompany") }); + return; + } + setSaving(true); + const next = rows.map((r) => ({ ...r })); + const left = { ...pending }; + try { + for (const row of next) { + if (!left[row.key]) continue; + const data = (await readDataUrl(left[row.key].file)).split(",")[1]; + row.block = { ...row.block, imageId: (await uploadPageImage(draft.companyId, data)).id }; + delete left[row.key]; + } + const page = await savePage(draft.id, pageBody({ ...draft, blocks: next.map((r) => r.block) })); + setDraft((d) => ({ ...d, id: page.id, companyId: page.companyId })); + setSaved({ slug: page.slug, status: page.status }); + setDirty(false); + setNotice("PagesSaved"); + if (isNew) router.replace(`/pages/${page.id}?saved=1`); + } catch (err) { + showError(err); + } finally { + // Uploaded images stay on their blocks and leave the pending set, success or not. + setRows(next); + setPending(left); + setSaving(false); + } + } + + async function remove() { + if (draft.id == null) return; + setSaving(true); + try { + await deletePage(draft.id); + setDirty(false); + router.push("/pages"); + } catch (err) { + setConfirmDelete(false); + showError(err); + } finally { + setSaving(false); + } + } + + if (loadError) return ; + if (loading) return null; + + const blockErrors = (index: number) => { + const prefix = `blocks[${index}].`; + return Object.fromEntries(Object.entries(errors).flatMap(([path, m]) => (path.startsWith(prefix) ? [[path.slice(prefix.length), m]] : []))); + }; + + return ( +
+
+ {draft.id != null ? ( + + ) : null} + {saved?.status === "PUBLISHED" && code ? ( + + ) : null} +
+ {summary &&

{summary}

} + {notice &&

{t(notice)}

} + +
+
+ + {t("PagesPageCard")} + + {isSuper && isNew ? ( +
+ + + +
+ ) : null} +
+ + { const v = e.target.value; setDirty(true); setDraft((d) => withTitle(d, v)); }} /> + +
+
+ + patch({ slug: e.target.value, slugTouched: true })} /> +

{t("PagesAddressHint", { address: pageAddress(code || "…", draft.slug || "…") })}

+ +
+
+ +