feat(pages): a hero section can carry the sign-up form beside its text
A HERO block may name an event. services-counter checks it belongs to the page's company; mobile-api serves and accepts the form for it like a FORM block; the portal shows the form in a card beside the hero text (below it on phones), with the hero's own event picker, "No form" by default. OpenSpec change: add-hero-signup-form. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
This commit is contained in:
1 parent
55ae666f01
commit
417af36227
20 files changed
+294
-22
No files matched your search
@@ -464,4 +464,6 @@ A form stops taking sign-ups when its event is disabled, its end date has passed
|
||||
|
||||
**Release add-page-visual-editor (SQL, in its OpenSpec change folder):** portal only. Deploy the portal, then run `sql/01-visual-editor-labels.sql`. Rollback: the previous portal image, then `sql/99-rollback.sql` (labels only). No data changes.
|
||||
|
||||
**Release add-hero-signup-form (SQL, in its OpenSpec change folder):** deploy services-counter, mobile-api and the portal (any order), then run `sql/01-hero-form-labels.sql` (labels only). A hero section can now carry the sign-up form for an event, beside its text. Rollback: the previous images. A hero saved with an event keeps it in its JSON. The old code ignores it and shows the hero without a form, so add a Sign-up form section to those pages if you roll back.
|
||||
|
||||
**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.
|
||||
@@ -1713,6 +1713,10 @@ INSERT INTO message (code, content, area) SELECT 'PagesFormClosed', JSON_OBJECT(
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '报名已截止。') WHERE LOWER(code) = LOWER('PagesFormClosed') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesFormPreview', JSON_OBJECT('en_US', 'The sign-up form shows here on the published page.', 'zh_CN', '发布后的网页会在此显示报名表。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesFormPreview') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '发布后的网页会在此显示报名表。') WHERE LOWER(code) = LOWER('PagesFormPreview') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesHeroForm', JSON_OBJECT('en_US', 'Sign-up form', 'zh_CN', '报名表单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHeroForm') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '报名表单') WHERE LOWER(code) = LOWER('PagesHeroForm') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesNoForm', JSON_OBJECT('en_US', 'No form', 'zh_CN', '不显示表单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesNoForm') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '不显示表单') WHERE LOWER(code) = LOWER('PagesNoForm') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesToolbar', JSON_OBJECT('en_US', 'Formatting', 'zh_CN', '格式'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesToolbar') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '格式') WHERE LOWER(code) = LOWER('PagesToolbar') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesTextStyle', JSON_OBJECT('en_US', 'Text style', 'zh_CN', '文字样式'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTextStyle') AND area = 'A');
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-12-03
|
||||
@@ -0,0 +1,43 @@
|
||||
# Proposal
|
||||
|
||||
## Why
|
||||
|
||||
Event pages convert best when the sign-up form is visible as soon as the page opens. INS's standalone landing page (`~/Projects/ins-landing-page`) puts the form in a card beside the hero text. In Co-Lite the form is always its own section, so on a page built from Custom HTML it lands below the hero, and the hero tells visitors to "scroll down to the form". Custom HTML cannot hold the real form: it runs in a sealed frame that cannot send leads into Co-Lite.
|
||||
|
||||
## What Changes
|
||||
|
||||
- A HERO block gains an optional event (`eventUuid`). When it is set, the hero shows Co-Lite's sign-up form for that event in a card beside the heading, text and button on wide screens, and below them on phones.
|
||||
- The hero form behaves exactly like the FORM block:
|
||||
- the same fields, interests and privacy notice;
|
||||
- the same submit rules and limits;
|
||||
- the same lead source, UTM values and closing rules.
|
||||
- The server checks a hero's event like a FORM block's: it must be an event of the page's company.
|
||||
- In the editor, the Hero's settings gain the same event picker as the Sign-up form, with "No form" as the default. The canvas shows the form card in place.
|
||||
- Switching company in the editor clears a hero's event, as it already clears a FORM block's.
|
||||
|
||||
Not changing:
|
||||
- The FORM block stays as it is.
|
||||
- A page may have a hero form and a FORM block together, and each registers for its own event.
|
||||
- The form card has no heading of its own; the hero's heading and text introduce it.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
None.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- `landing-pages`: hero blocks may carry the sign-up form, and the event-reference rule covers them.
|
||||
|
||||
## Impact
|
||||
|
||||
- **services-counter:** `CmsBlockValidator`, which now checks a HERO's optional `eventUuid`.
|
||||
- **mobile-api:** `PublicPageService`, which attaches form info to, and accepts submits for, any block with an event (FORM or a HERO that has one).
|
||||
- **admin-portal:**
|
||||
- the `HERO` rendering in `CmsBlocks.tsx`;
|
||||
- the Hero fields in `BlockFields.tsx`;
|
||||
- the company-switch reset in `usePageDraft.ts`;
|
||||
- two labels, in English and Chinese.
|
||||
- **No schema change:** blocks are JSON.
|
||||
- **No new dependency.**
|
||||
@@ -0,0 +1,48 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Hero With A Sign-Up Form
|
||||
|
||||
A HERO block MAY name an event. When it does, the hero SHALL show Co-Lite's sign-up form for that event in a card beside its heading, text and button on wide screens, and below them on narrow screens. The hero's form SHALL follow every rule of the FORM block (see "The Form Block Registers For An Event" and "The Form Block Closes With Its Event"). A HERO block without an event SHALL show no form.
|
||||
|
||||
#### Scenario: Sign up from the hero
|
||||
|
||||
- **GIVEN** page `/p/INS/hotel-technology` has a HERO block whose event is `INS website enquiries`
|
||||
- **WHEN** a new visitor submits the form in the hero from a URL with `utm_source=facebook`
|
||||
- **THEN** a new lead and an event lead with source Web page, no salesperson and UTM source `facebook` are created
|
||||
|
||||
#### Scenario: Hero form closes with its event
|
||||
|
||||
- **GIVEN** the HERO block's event ended yesterday
|
||||
- **WHEN** a visitor opens the page
|
||||
- **THEN** the hero still shows its heading and text, and its form area says sign-up is closed
|
||||
|
||||
#### Scenario: Hero without an event
|
||||
|
||||
- **WHEN** a visitor opens a page whose HERO block names no event
|
||||
- **THEN** the hero shows no form
|
||||
- **AND** a submit addressed to that block is refused as not found
|
||||
|
||||
#### Scenario: Pick the hero's event in the editor
|
||||
|
||||
- **GIVEN** staff editing a page with a HERO block
|
||||
- **WHEN** they pick `INS website enquiries` under the hero's sign-up form setting
|
||||
- **THEN** the canvas shows the form card beside the hero text
|
||||
- **AND** choosing "No form" removes it
|
||||
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Block References Stay Inside The Company
|
||||
|
||||
A block's image SHALL be an image of the page's company, and the event of a FORM block or of a HERO block that names one SHALL be an event of the page's company. Otherwise the save SHALL be refused on that field.
|
||||
|
||||
#### Scenario: Another company's event
|
||||
|
||||
- **GIVEN** event `CV Roadshow` belongs to CV
|
||||
- **WHEN** INS staff save a FORM block pointing at `CV Roadshow`
|
||||
- **THEN** the save is refused on that block's event field
|
||||
|
||||
#### Scenario: Another company's event in a hero
|
||||
|
||||
- **GIVEN** event `CV Roadshow` belongs to CV
|
||||
- **WHEN** INS staff save a HERO block whose event is `CV Roadshow`
|
||||
- **THEN** the save is refused on that block's event field
|
||||
@@ -0,0 +1,7 @@
|
||||
-- The labels added by add-hero-signup-form, cut from the output of `npm run i18n:sql`. Run it only in an environment that already ran add-zh-cn-messages/sql/03-zh-cn-messages.sql; otherwise run that 03 file, which includes these labels.
|
||||
SET NAMES utf8mb4;
|
||||
USE `service-system`;
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesHeroForm', JSON_OBJECT('en_US', 'Sign-up form', 'zh_CN', '报名表单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHeroForm') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '报名表单') WHERE LOWER(code) = LOWER('PagesHeroForm') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesNoForm', JSON_OBJECT('en_US', 'No form', 'zh_CN', '不显示表单'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesNoForm') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '不显示表单') WHERE LOWER(code) = LOWER('PagesNoForm') AND area = 'A';
|
||||
@@ -0,0 +1,20 @@
|
||||
# Tasks
|
||||
|
||||
## 1. Server
|
||||
|
||||
- [ ] 1.1 services-counter `CmsBlockValidator`: a HERO's optional `eventUuid` must be an event of the page's company, refused at `blocks[n].eventUuid` with `PagesBadEvent`. Verify: new validator tests (own event saves, other company's event refused, no event saves) fail first, then pass; `mvn -T 1C -pl solvway-services-counter verify`.
|
||||
- [ ] 1.2 mobile-api `PublicPageService`: `page()` attaches `form`/`closed` to every block with an event that is FORM or HERO; `submit()` accepts a HERO with an event and refuses a HERO without one as not found. Verify: new service tests fail first, then pass; `mvn -T 1C -pl solvway-mobile-api verify`.
|
||||
|
||||
## 2. Portal
|
||||
|
||||
- [ ] 2.1 `CmsBlocks.tsx` HERO: with `form` or `closed`, two columns from `md` (text left, form card right; stacked on phones), image and shade kept; the card is `LandingForm` with the hero's block index. Verify: render tests for with/without event, closed, and the edit canvas; vitest exit 0.
|
||||
- [ ] 2.2 `BlockFields.tsx`: the Hero gets the event picker ("No form" default, same hint and unavailable-event option as FORM; `eventUuid` shown inline); `usePageDraft` clears a HERO's event on company switch like a FORM's; labels `PagesHeroForm` and `PagesNoForm` in `defaultMessages.ts`, `zh_CN.seed.json` and an SQL label file in this change folder. Verify: editor tests fail first, then pass; tsc and lint clean.
|
||||
|
||||
## 3. Verification
|
||||
|
||||
- [ ] 3.1 Rebuild services-counter and mobile-api locally; Playwright on port 3001: give a page's hero an event, see the card beside the text at 1280 px and below it at 390 px, submit as a visitor on the published page and see the lead under Event leads with source Web page; pick another company's event is impossible in the picker, and an ended event shows "closed". Use a disposable test page and the existing "LP Enquiries" test event; delete the test page after.
|
||||
- [ ] 3.2 Full portal vitest (exit 0), tsc, lint, both Maven modules, `openspec validate add-hero-signup-form --strict`.
|
||||
|
||||
## Workflow follow-up
|
||||
|
||||
- PR to `main` and merge; archive on its own branch with its own PR.
|
||||
@@ -14,7 +14,7 @@ import { RichTextEditor } from "./RichTextEditor";
|
||||
|
||||
/** Field paths (relative to the block) each type shows inline; any other error shows at the block's top. Every type also shows "anchor". */
|
||||
const INLINE: Record<string, string[]> = {
|
||||
HERO: ["imageId", "heading", "text", "buttonLabel", "buttonUrl"],
|
||||
HERO: ["imageId", "heading", "text", "buttonLabel", "buttonUrl", "eventUuid"],
|
||||
RICH_TEXT: ["html"],
|
||||
IMAGE_TEXT: ["imageId", "imagePosition", "heading", "html", "buttonLabel", "buttonUrl"],
|
||||
FAQ: ["heading", "items"],
|
||||
@@ -96,6 +96,20 @@ export function BlockFields(props: {
|
||||
);
|
||||
|
||||
const preview = pendingImage?.preview ?? (block.imageId ? imageSrc(block.imageId) : undefined);
|
||||
// The FORM block's event, and the hero's optional sign-up form (add-hero-signup-form): the same picker and hint.
|
||||
const eventPicker = (labelCode: string, emptyCode: string) => (
|
||||
<Field id={fid("event")} label={t(labelCode)} error={errors.eventUuid}>
|
||||
<select id={fid("event")} className={SELECT} value={block.eventUuid ?? ""} disabled={saving} aria-invalid={!!errors.eventUuid}
|
||||
onChange={(e) => set({ eventUuid: e.target.value || null })}>
|
||||
<option value="">{t(emptyCode)}</option>
|
||||
{events.map((ev) => <option key={ev.uuid} value={ev.uuid}>{ev.name}</option>)}
|
||||
{block.eventUuid && !events.some((ev) => ev.uuid === block.eventUuid) ? (
|
||||
<option value={block.eventUuid}>{t("PagesUnavailableEvent")}</option>
|
||||
) : null}
|
||||
</select>
|
||||
<p className="text-xs text-muted-foreground">{t("PagesFormEventHint")}</p>
|
||||
</Field>
|
||||
);
|
||||
const image = (
|
||||
<Field id={fid("image")} label={t("PagesImage")} error={errors.imageId}>
|
||||
<Input
|
||||
@@ -190,6 +204,7 @@ export function BlockFields(props: {
|
||||
{text("text", "PagesText")}
|
||||
{text("buttonLabel", "PagesButtonLabel")}
|
||||
{text("buttonUrl", "PagesButtonLink")}
|
||||
{eventPicker("PagesHeroForm", "PagesNoForm")}
|
||||
</>
|
||||
)}
|
||||
|
||||
@@ -249,17 +264,7 @@ export function BlockFields(props: {
|
||||
{block.type === "FORM" && (
|
||||
<>
|
||||
{text("heading", "PagesHeading")}
|
||||
<Field id={fid("event")} label={t("PagesFormEvent")} error={errors.eventUuid}>
|
||||
<select id={fid("event")} className={SELECT} value={block.eventUuid ?? ""} disabled={saving} aria-invalid={!!errors.eventUuid}
|
||||
onChange={(e) => set({ eventUuid: e.target.value || null })}>
|
||||
<option value="">{t("PagesChooseEvent")}</option>
|
||||
{events.map((ev) => <option key={ev.uuid} value={ev.uuid}>{ev.name}</option>)}
|
||||
{block.eventUuid && !events.some((ev) => ev.uuid === block.eventUuid) ? (
|
||||
<option value={block.eventUuid}>{t("PagesUnavailableEvent")}</option>
|
||||
) : null}
|
||||
</select>
|
||||
<p className="text-xs text-muted-foreground">{t("PagesFormEventHint")}</p>
|
||||
</Field>
|
||||
{eventPicker("PagesFormEvent", "PagesChooseEvent")}
|
||||
</>
|
||||
)}
|
||||
|
||||
|
||||
@@ -70,6 +70,37 @@ describe("LandingPage", () => {
|
||||
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();
|
||||
});
|
||||
|
||||
// add-hero-signup-form: a hero with an event carries the sign-up form beside its text.
|
||||
it("a hero with an event shows the sign-up form inside the hero and posts to the hero's block", async () => {
|
||||
window.history.replaceState(null, "", "/p/INS/hotel?utm_source=fb");
|
||||
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValueOnce(new Response(JSON.stringify({ code: "FORM_CLOSED" }), { status: 409 }));
|
||||
const user = userEvent.setup();
|
||||
render(<LandingPage company={company} page={page([{ type: "HERO", heading: "One partner", eventUuid: "77", form: info }])} />);
|
||||
const hero = screen.getByRole("heading", { name: "One partner" }).closest("section")!;
|
||||
expect(hero).toContainElement(screen.getByLabelText("Your name"));
|
||||
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" }));
|
||||
expect(fetchMock.mock.calls[0][0]).toBe("/api/public/pages/INS/hotel/form/0");
|
||||
});
|
||||
|
||||
it("a hero whose form closed keeps its text and says so; a hero without an event has no form", () => {
|
||||
const { unmount } = render(<LandingPage company={company} page={page([{ type: "HERO", heading: "One partner", eventUuid: "77", closed: true }])} />);
|
||||
const hero = screen.getByRole("heading", { name: "One partner" }).closest("section")!;
|
||||
expect(hero).toHaveTextContent("Sign-up is closed.");
|
||||
unmount();
|
||||
render(<LandingPage company={company} page={page([{ type: "HERO", heading: "Plain" }])} />);
|
||||
expect(screen.queryByText("Sign-up is closed.")).not.toBeInTheDocument();
|
||||
expect(screen.queryByLabelText("Your name")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("the preview of a hero with an event shows the form's note in the hero", () => {
|
||||
render(<LandingPage company={company} page={page([{ type: "HERO", heading: "One partner", eventUuid: "77" }])} preview />);
|
||||
expect(screen.getByRole("heading", { name: "One partner" }).closest("section"))
|
||||
.toHaveTextContent("The sign-up form shows here on the published page.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("utmTags", () => {
|
||||
|
||||
@@ -46,19 +46,40 @@ function Block({ block, index, company, slug, preview, edit }: { block: PublicBl
|
||||
const image = block.imageId ? imageSrc(block.imageId) : undefined;
|
||||
const button = <ButtonLink block={block} index={index} edit={edit} />;
|
||||
switch (block.type) {
|
||||
case "HERO":
|
||||
case "HERO": {
|
||||
const words = (
|
||||
<>
|
||||
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-3xl font-semibold sm:text-4xl" />
|
||||
<Text as="p" index={index} path="text" value={block.text} max={300} code="PagesText" className="max-w-2xl text-lg" />
|
||||
<div>{button}</div>
|
||||
</>
|
||||
);
|
||||
// add-hero-signup-form: with an event, the sign-up form sits in a card beside the text (below it on phones).
|
||||
if (block.eventUuid) {
|
||||
const grid = "grid items-center gap-6 p-6 md:grid-cols-[minmax(0,1fr)_minmax(0,26rem)] md:p-10";
|
||||
return (
|
||||
<section className={`relative overflow-hidden rounded-lg ${bandOf(block.look) ? "" : "bg-muted"}`}>
|
||||
<ImageSpot index={index} src={image} className="absolute inset-0 h-full w-full object-cover" corner />
|
||||
<HeroShade index={index} image={!!image} shaded={`relative ${grid} bg-gradient-to-r from-black/80 via-black/60 to-black/40 text-white sm:min-h-96`} plain={grid}>
|
||||
<div className="flex flex-col gap-3">{words}</div>
|
||||
<div className="rounded-lg border bg-card p-6 text-card-foreground shadow-card">
|
||||
<LandingForm companyCode={company} slug={slug} index={index} info={block.closed ? undefined : block.form} preview={preview} />
|
||||
</div>
|
||||
</HeroShade>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<section className={`relative overflow-hidden rounded-lg ${bandOf(block.look) ? "" : "bg-muted"}`}>
|
||||
<ImageSpot index={index} src={image} className="absolute inset-0 h-full w-full object-cover" corner />
|
||||
<HeroShade index={index} image={!!image}
|
||||
shaded="relative flex min-h-72 flex-col justify-end gap-3 bg-gradient-to-t from-black/80 via-black/50 to-transparent p-6 text-white sm:min-h-96"
|
||||
plain="flex flex-col gap-3 p-6">
|
||||
<Text as="h2" index={index} path="heading" value={block.heading} max={120} code="PagesHeading" className="text-3xl font-semibold sm:text-4xl" />
|
||||
<Text as="p" index={index} path="text" value={block.text} max={300} code="PagesText" className="max-w-2xl text-lg" />
|
||||
<div>{button}</div>
|
||||
{words}
|
||||
</HeroShade>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
case "RICH_TEXT":
|
||||
return block.html || edit ? (
|
||||
<section><RichSpot index={index} html={block.html} className={PROSE}>{block.html ? <SafeHtml html={block.html} className={PROSE} /> : null}</RichSpot></section>
|
||||
|
||||
@@ -56,7 +56,8 @@ describe("PageEditor", () => {
|
||||
const user = userEvent.setup();
|
||||
render(<PageEditor pageId={5} />);
|
||||
const picker = await screen.findByLabelText("Event");
|
||||
await waitFor(() => expect(screen.getByRole("option", { name: "Website enquiries" })).toBeInTheDocument());
|
||||
// Scoped to the FORM block's picker: since add-hero-signup-form the hero offers the same events in its own picker.
|
||||
await waitFor(() => expect(within(picker).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");
|
||||
@@ -106,6 +107,24 @@ describe("PageEditor", () => {
|
||||
expect(memoryRouter.push).toHaveBeenCalledWith("/pages");
|
||||
});
|
||||
|
||||
// add-hero-signup-form: the hero's own event picker, "No form" by default; its event is saved with the hero.
|
||||
it("gives a hero a sign-up form for a chosen event, and No form takes it away", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<PageEditor pageId={5} />);
|
||||
const picker = await screen.findByLabelText("Sign-up form");
|
||||
expect(picker).toHaveValue("");
|
||||
expect(within(picker).getByRole("option", { name: "No form" })).toBeInTheDocument();
|
||||
await waitFor(() => expect(within(picker).getByRole("option", { name: "Website enquiries" })).toBeInTheDocument());
|
||||
await user.selectOptions(picker, "3312726793093644288");
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mocks.savePage).toHaveBeenCalledTimes(1));
|
||||
expect(mocks.savePage.mock.calls[0][1].blocks[0]).toMatchObject({ type: "HERO", eventUuid: "3312726793093644288" });
|
||||
await user.selectOptions(screen.getByLabelText("Sign-up form"), "");
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mocks.savePage).toHaveBeenCalledTimes(2));
|
||||
expect(mocks.savePage.mock.calls[1][1].blocks[0].eventUuid ?? null).toBeNull();
|
||||
});
|
||||
|
||||
it("a super admin must choose a company for a new page", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue({ isSuper: true, companyCode: null });
|
||||
const user = userEvent.setup();
|
||||
|
||||
@@ -49,6 +49,15 @@ describe("moveItem", () => {
|
||||
});
|
||||
|
||||
describe("usePageDraft for the on-page editor", () => {
|
||||
it("a company switch clears the event of every FORM block and of a hero's sign-up form", async () => {
|
||||
mocks.getPage.mockResolvedValueOnce({ ...stored, blocks: [
|
||||
{ type: "HERO" as const, heading: "Hi", eventUuid: "77" }, { type: "FORM" as const, eventUuid: "77" }, { type: "HERO" as const, heading: "Plain" },
|
||||
] });
|
||||
const { result } = await loaded();
|
||||
act(() => result.current.changeCompany(3));
|
||||
expect(result.current.rows.map((r) => r.block.eventUuid ?? null)).toEqual([null, null, null]);
|
||||
});
|
||||
|
||||
it("keeps the company's branding from the loaded page", async () => {
|
||||
const { result } = await loaded();
|
||||
expect(result.current.branding).toEqual(stored.company);
|
||||
|
||||
@@ -191,11 +191,11 @@ export function usePageDraft({ pageId, fromId, initialBlocks }: { pageId?: numbe
|
||||
step("page:title");
|
||||
setDraft((d) => withTitle(d, title));
|
||||
};
|
||||
/** A super admin's new page changes company: FORM blocks lose their event, which belongs to the old one. */
|
||||
/** A super admin's new page changes company: FORM blocks and hero sign-up forms lose their event, which belongs to the old one. */
|
||||
const changeCompany = (companyId: number) => {
|
||||
step(null);
|
||||
setDraft((d) => ({ ...d, companyId }));
|
||||
setRows((rs) => rs.map((r) => (r.block.type === "FORM" ? { ...r, block: { ...r.block, eventUuid: null } } : r)));
|
||||
setRows((rs) => rs.map((r) => (r.block.eventUuid ? { ...r, block: { ...r.block, eventUuid: null } } : r)));
|
||||
};
|
||||
const setBlock = (key: number, update: (block: CmsBlock) => CmsBlock) =>
|
||||
setRows((rs) => rs.map((r) => (r.key === key ? { ...r, block: update(r.block) } : r)));
|
||||
|
||||
@@ -868,6 +868,8 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
PagesFormEventHint: "Sign-ups become leads of this event. For general enquiries, pick your standing enquiries event.",
|
||||
PagesFormClosed: "Sign-up is closed.",
|
||||
PagesFormPreview: "The sign-up form shows here on the published page.",
|
||||
PagesHeroForm: "Sign-up form",
|
||||
PagesNoForm: "No form",
|
||||
PagesToolbar: "Formatting",
|
||||
PagesTextStyle: "Text style",
|
||||
PagesParagraph: "Paragraph",
|
||||
|
||||
@@ -853,6 +853,8 @@
|
||||
"NoticeWhatsappBodyNoName": "来自新联系人",
|
||||
"PagesFormClosed": "报名已截止。",
|
||||
"PagesFormPreview": "发布后的网页会在此显示报名表。",
|
||||
"PagesHeroForm": "报名表单",
|
||||
"PagesNoForm": "不显示表单",
|
||||
"PagesToolbar": "格式",
|
||||
"PagesTextStyle": "文字样式",
|
||||
"PagesParagraph": "段落",
|
||||
|
||||
+7
-2
@@ -48,7 +48,7 @@ public class PublicPageService {
|
||||
List<Map<String, Object>> blocks = new ArrayList<>();
|
||||
for (Object b : blocks(f.page())) {
|
||||
Map<String, Object> block = new LinkedHashMap<>((Map<String, Object>) b);
|
||||
if ("FORM".equals(block.get("type"))) {
|
||||
if (hasForm(block)) {
|
||||
PublicRegistrationService.Open o = open(f.companyId(), block);
|
||||
if (o == null) block.put("closed", true);
|
||||
else block.put("form", registration.eventView(o));
|
||||
@@ -64,11 +64,16 @@ public class PublicPageService {
|
||||
return Map.of("company", f.company(), "page", page);
|
||||
}
|
||||
|
||||
/** A FORM block, or a HERO with an event: its sign-up form sits beside the hero text (add-hero-signup-form). */
|
||||
private static boolean hasForm(Map<?, ?> block) {
|
||||
return "FORM".equals(block.get("type")) || ("HERO".equals(block.get("type")) && block.get("eventUuid") != null);
|
||||
}
|
||||
|
||||
public Map<String, Object> submit(String companyCode, String slug, int blockIndex, PublicPageFormRequest r) {
|
||||
registration.limit("page:load:" + PublicRegistrationService.ip(), LOAD_LIMIT, "Too many requests from this device. Try again later.");
|
||||
Found f = find(companyCode, slug);
|
||||
List<?> blocks = blocks(f.page());
|
||||
if (blockIndex < 0 || blockIndex >= blocks.size() || !"FORM".equals(((Map<?, ?>) blocks.get(blockIndex)).get("type"))) {
|
||||
if (blockIndex < 0 || blockIndex >= blocks.size() || !hasForm((Map<?, ?>) blocks.get(blockIndex))) {
|
||||
throw notFound();
|
||||
}
|
||||
PublicRegistrationService.Open o = open(f.companyId(), (Map<String, Object>) blocks.get(blockIndex));
|
||||
|
||||
+36
@@ -180,6 +180,42 @@ class PublicPageServiceTest {
|
||||
verify(rest, never()).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHeroWithAnEventCarriesTheSignUpFormAndTakesSubmits() {
|
||||
// add-hero-signup-form: block 0 is a hero with the form beside its text, block 1 a hero without one.
|
||||
Map<String, Object> heroes = page();
|
||||
heroes.put("blocks", List.of(
|
||||
new HashMap<>(Map.of("type", "HERO", "heading", "One partner", "eventUuid", String.valueOf(EV))),
|
||||
Map.of("type", "HERO", "heading", "No form here")));
|
||||
when(rest.getForEntity(eq(PUBLISHED), any(ParameterizedTypeReference.class), eq(COMPANY), eq("hotel-technology")))
|
||||
.thenReturn(ResponseEntity.ok(heroes));
|
||||
|
||||
List<Map<String, Object>> blocks = (List<Map<String, Object>>) ((Map<String, Object>) service.page("INS", "hotel-technology").get("page")).get("blocks");
|
||||
assertThat((Map<String, Object>) blocks.get(0).get("form")).containsEntry("eventName", "INS website enquiries");
|
||||
assertThat(blocks.get(1)).doesNotContainKeys("form", "closed");
|
||||
|
||||
service.submit("INS", "hotel-technology", 0, visitor(null));
|
||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(REGISTER), any(ParameterizedTypeReference.class), body.capture());
|
||||
assertThat((Map<String, Object>) body.getValue()).containsEntry("eventUuid", EV).containsEntry("source", "WEB");
|
||||
|
||||
assertThatThrownBy(() -> service.submit("INS", "hotel-technology", 1, visitor(null)))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getCode()).isEqualTo("PAGE_NOT_FOUND"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHeroFormWhoseEventEndedIsClosed() {
|
||||
Map<String, Object> hero = page();
|
||||
hero.put("blocks", List.of(new HashMap<>(Map.of("type", "HERO", "heading", "One partner", "eventUuid", String.valueOf(EV)))));
|
||||
when(rest.getForEntity(eq(PUBLISHED), any(ParameterizedTypeReference.class), eq(COMPANY), eq("hotel-technology")))
|
||||
.thenReturn(ResponseEntity.ok(hero));
|
||||
stubEvent(LocalDateTime.of(2027, 1, 15, 23, 59));
|
||||
List<Map<String, Object>> blocks = (List<Map<String, Object>>) ((Map<String, Object>) service.page("INS", "hotel-technology").get("page")).get("blocks");
|
||||
assertThat(blocks.get(0)).containsEntry("closed", true).containsEntry("heading", "One partner").doesNotContainKey("form");
|
||||
assertThatThrownBy(() -> service.submit("INS", "hotel-technology", 0, visitor(null)))
|
||||
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getCode()).isEqualTo("FORM_CLOSED"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theHoneypotLooksLikeSuccessAndStoresNothing() {
|
||||
assertThat(service.submit("INS", "hotel-technology", 1, visitor("http://spam"))).containsKey("eventName");
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@ import java.util.List;
|
||||
|
||||
/**
|
||||
* One landing-page block. Which fields apply depends on {@code type}:
|
||||
* HERO (imageId, heading, text, button), RICH_TEXT (html), IMAGE_TEXT (imageId, imagePosition, heading, html, button),
|
||||
* HERO (imageId, heading, text, button, optional eventUuid for a sign-up form beside the text), RICH_TEXT (html), IMAGE_TEXT (imageId, imagePosition, heading, html, button),
|
||||
* FAQ (heading, items), FORM (heading, eventUuid), HTML (html), FEATURES (heading, text, cards), STEPS (heading, cards),
|
||||
* TRUST (cards), CTA (heading, text, button). Any block may carry anchor and look.
|
||||
*/
|
||||
|
||||
+4
@@ -71,6 +71,10 @@ public final class CmsBlockValidator {
|
||||
max(b.getHeading(), path + ".heading", 120);
|
||||
max(b.getText(), path + ".text", 300);
|
||||
button(b, path);
|
||||
// add-hero-signup-form: an optional sign-up form beside the hero text, for an event of the page's company.
|
||||
if (b.getEventUuid() != null && !ownEvent.test(b.getEventUuid())) {
|
||||
throw refuse(path + ".eventUuid", "PagesBadEvent");
|
||||
}
|
||||
}
|
||||
case "RICH_TEXT" -> html(b.getHtml(), path + ".html");
|
||||
case "HTML" -> {
|
||||
|
||||
+12
@@ -154,6 +154,18 @@ class CmsBlockValidatorTest {
|
||||
refused(List.of(form(901)), "blocks[0].eventUuid", "PagesBadEvent");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHeroMayCarryTheSignUpFormForAnEventOfThePagesCompany() {
|
||||
// add-hero-signup-form: the event is optional; when set it must be the company's own, as on a FORM block.
|
||||
validate(List.of(hero()));
|
||||
CmsBlock own = hero();
|
||||
own.setEventUuid(OWN_EVENT);
|
||||
validate(List.of(own));
|
||||
CmsBlock foreign = hero();
|
||||
foreign.setEventUuid(901L);
|
||||
refused(List.of(foreign), "blocks[0].eventUuid", "PagesBadEvent");
|
||||
}
|
||||
|
||||
private static CmsBlock custom(String html) {
|
||||
CmsBlock b = new CmsBlock();
|
||||
b.setType("HTML");
|
||||
|
||||
Reference in new issue
Block a user