Merge pull request 'feat(pages): drafts for published pages, starter templates and duplicate' (#62) from add-page-drafts-and-templates into main
CI / build-and-publish (push) Failing after 0s
CI / build-and-publish (push) Failing after 0s
This commit was merged in pull request #62.
This commit is contained in:
commit
3b977fc277
40 files changed
+1247
-58
No files matched your search
+5
-1
@@ -463,8 +463,12 @@ Marketing builds public pages under **Events → Pages**. Each page has blocks (
|
||||
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.
|
||||
- **Rebuild it as sections.** The INS page is pasted HTML today, which only a developer can maintain. Rebuild it from sections (hero, trust strip, feature cards, steps, FAQ, sign-up form, call to action) so marketing can edit it, then delete the Custom HTML block.
|
||||
- **Jump to the form.** To make a button jump to the sign-up form, give the form block a link name, for example `signup`, and link the button to `#signup`. Links inside a Custom HTML block work the same way: on the INS page, change the HTML's `#consult` links to `#signup`. A `#name` link inside the HTML that matches an `id` in that same HTML (such as `#top`) scrolls to that spot instead.
|
||||
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.
|
||||
5. **Drafts of published pages.** Once a page is published, Save keeps the changes as a draft: visitors still see the published version, and the editor shows **Publish changes** and **Discard changes**. Preview shows the draft. The pages list marks such pages "Unpublished changes". Publish changes checks the page again (an ended event, for example, is refused at its field). Switching the status back to Draft and saving takes the page offline and drops the separate draft. Two people saving the same page overwrite each other's draft, last save wins.
|
||||
6. **Templates and Duplicate.** New page offers a blank page, **Event sign-up** and **Service showcase**. A template fills the editor with sections and placeholder text; staff replace the text and choose the form's event before saving. **Duplicate** (on the list and in the editor) opens a copy titled "… (copy)" with slug "…-copy" as a new draft; nothing is stored until Save.
|
||||
7. **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.
|
||||
|
||||
**Release add-page-drafts-and-templates (SQL, in its OpenSpec change folder):** run `sql/01-page-draft.sql` (adds `cms_page.draft`) before the new services-counter starts, then deploy services-counter, mobile-api and the portal, then run `sql/02-draft-template-labels.sql`. Rollback: previous images, then `sql/99-rollback.sql`, which drops every unpublished draft, so publish or note them first.
|
||||
|
||||
**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.
|
||||
@@ -520,3 +520,6 @@ ALTER TABLE `notification`
|
||||
ADD COLUMN `read_at` datetime NULL AFTER `seen`,
|
||||
ADD INDEX `idx_notification_inbox` (`recipient_type`, `receiver`, `seen`, `create_date_time`),
|
||||
ADD INDEX `idx_notification_collapse` (`receiver`, `collapse_key`, `seen`);
|
||||
-- add-page-drafts-and-templates: a published page's unpublished draft
|
||||
USE `service-counter`;
|
||||
ALTER TABLE `cms_page` ADD COLUMN `draft` json NULL COMMENT 'Unpublished changes of a published page: slug, title, metaDescription, hideHeader, blocks' AFTER `blocks`;
|
||||
@@ -1461,6 +1461,42 @@ INSERT INTO message (code, content, area) SELECT 'PagesPreviewBanner', JSON_OBJE
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '预览。网页发布后访客才能看到。') WHERE LOWER(code) = LOWER('PagesPreviewBanner') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesViewPage', JSON_OBJECT('en_US', 'View page', 'zh_CN', '查看网页'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesViewPage') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '查看网页') WHERE LOWER(code) = LOWER('PagesViewPage') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesDuplicate', JSON_OBJECT('en_US', 'Duplicate', 'zh_CN', '复制'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDuplicate') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '复制') WHERE LOWER(code) = LOWER('PagesDuplicate') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesDuplicateNamed', JSON_OBJECT('en_US', 'Duplicate {title}', 'zh_CN', '复制 {title}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDuplicateNamed') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '复制 {title}') WHERE LOWER(code) = LOWER('PagesDuplicateNamed') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesChooseStart', JSON_OBJECT('en_US', 'How do you want to start?', 'zh_CN', '您想如何开始?'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesChooseStart') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '您想如何开始?') WHERE LOWER(code) = LOWER('PagesChooseStart') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesStartBlank', JSON_OBJECT('en_US', 'Blank page', 'zh_CN', '空白网页'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesStartBlank') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '空白网页') WHERE LOWER(code) = LOWER('PagesStartBlank') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesStartBlankHint', JSON_OBJECT('en_US', 'Start empty and add sections yourself.', 'zh_CN', '从空白开始,自行添加区块。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesStartBlankHint') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '从空白开始,自行添加区块。') WHERE LOWER(code) = LOWER('PagesStartBlankHint') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesTemplateEvent', JSON_OBJECT('en_US', 'Event sign-up', 'zh_CN', '活动报名'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTemplateEvent') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '活动报名') WHERE LOWER(code) = LOWER('PagesTemplateEvent') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesTemplateEventHint', JSON_OBJECT('en_US', 'A page for one event: headline, benefits, steps, questions and the sign-up form.', 'zh_CN', '为单个活动准备的网页:标题、优势、步骤、常见问题和报名表。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTemplateEventHint') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '为单个活动准备的网页:标题、优势、步骤、常见问题和报名表。') WHERE LOWER(code) = LOWER('PagesTemplateEventHint') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesTemplateShowcase', JSON_OBJECT('en_US', 'Service showcase', 'zh_CN', '服务展示'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTemplateShowcase') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '服务展示') WHERE LOWER(code) = LOWER('PagesTemplateShowcase') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesTemplateShowcaseHint', JSON_OBJECT('en_US', 'Present a service with benefits, steps and a call to action, ending with the sign-up form.', 'zh_CN', '介绍一项服务:优势、步骤和行动号召,最后是报名表。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTemplateShowcaseHint') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '介绍一项服务:优势、步骤和行动号召,最后是报名表。') WHERE LOWER(code) = LOWER('PagesTemplateShowcaseHint') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesHasDraft', JSON_OBJECT('en_US', 'Unpublished changes', 'zh_CN', '有未发布的修改'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHasDraft') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '有未发布的修改') WHERE LOWER(code) = LOWER('PagesHasDraft') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesDraftBanner', JSON_OBJECT('en_US', 'You have unpublished changes. Visitors still see the published version until you publish them.', 'zh_CN', '您有未发布的修改。发布之前,访客看到的仍是已发布的版本。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDraftBanner') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '您有未发布的修改。发布之前,访客看到的仍是已发布的版本。') WHERE LOWER(code) = LOWER('PagesDraftBanner') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesPublishChanges', JSON_OBJECT('en_US', 'Publish changes', 'zh_CN', '发布修改'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesPublishChanges') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '发布修改') WHERE LOWER(code) = LOWER('PagesPublishChanges') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesDiscardChanges', JSON_OBJECT('en_US', 'Discard changes', 'zh_CN', '放弃修改'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDiscardChanges') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '放弃修改') WHERE LOWER(code) = LOWER('PagesDiscardChanges') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesDiscardTitle', JSON_OBJECT('en_US', 'Discard unpublished changes?', 'zh_CN', '放弃未发布的修改?'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDiscardTitle') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '放弃未发布的修改?') WHERE LOWER(code) = LOWER('PagesDiscardTitle') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesDiscardMessage', JSON_OBJECT('en_US', 'Your unpublished changes to "{title}" will be lost. Visitors keep seeing the published version.', 'zh_CN', '“{title}”未发布的修改将会丢失。访客仍看到已发布的版本。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDiscardMessage') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '“{title}”未发布的修改将会丢失。访客仍看到已发布的版本。') WHERE LOWER(code) = LOWER('PagesDiscardMessage') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesChangesPublished', JSON_OBJECT('en_US', 'Changes published.', 'zh_CN', '修改已发布。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesChangesPublished') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '修改已发布。') WHERE LOWER(code) = LOWER('PagesChangesPublished') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesChangesDiscarded', JSON_OBJECT('en_US', 'Changes discarded.', 'zh_CN', '修改已放弃。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesChangesDiscarded') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '修改已放弃。') WHERE LOWER(code) = LOWER('PagesChangesDiscarded') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesPreviewDraftBanner', JSON_OBJECT('en_US', 'Preview of unpublished changes. Visitors still see the published version.', 'zh_CN', '未发布修改的预览。访客看到的仍是已发布的版本。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesPreviewDraftBanner') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '未发布修改的预览。访客看到的仍是已发布的版本。') WHERE LOWER(code) = LOWER('PagesPreviewDraftBanner') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesSaved', JSON_OBJECT('en_US', 'Page saved.', 'zh_CN', '网页已保存。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesSaved') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '网页已保存。') WHERE LOWER(code) = LOWER('PagesSaved') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesSaveFailed', JSON_OBJECT('en_US', 'Could not save the page. Try again.', 'zh_CN', '无法保存网页,请重试。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesSaveFailed') AND area = 'A');
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-12-03
|
||||
@@ -0,0 +1,45 @@
|
||||
## Context
|
||||
|
||||
Design: `docs/superpowers/specs/2026-12-03-page-builder-design.md`, change 2. A page is one `cms_page` row (slug, title, meta description, status, hide header, blocks JSON), saved whole by `CmsPageService.save` after `CmsBlockValidator`; mobile-api scopes every call to the caller's company; the portal editor saves through `/api/pages`.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:** draft and live separation for published pages; Publish changes and Discard changes; starter templates; Duplicate.
|
||||
|
||||
**Non-Goals:** version history; scheduled publishing; templates saved by staff; drafts for pages that were never published (they have no visitors, so they save directly as today).
|
||||
|
||||
## Decisions
|
||||
|
||||
1. **One nullable JSON column `draft`** on `cms_page`, holding `{slug, title, metaDescription, hideHeader, blocks}`. Status and company stay on the row.
|
||||
2. **Save rules** (`/counter/cmsPage/save`, unchanged request):
|
||||
- New page, or a stored page whose status is DRAFT: writes the row as today (including going straight to PUBLISHED).
|
||||
- Stored page PUBLISHED, request status PUBLISHED: validates exactly as today and writes the content into `draft`. The live columns do not change.
|
||||
- Stored page PUBLISHED, request status DRAFT (unpublish): writes the row from the request and clears `draft`; with no visitors the split no longer matters.
|
||||
- Slug uniqueness is checked against the other pages' live slugs, as today.
|
||||
3. **Publish** (`/counter/cmsPage/publish`, body: id and user): when a draft exists, validates it again (an event may have ended, an image may be gone) and checks its slug again, copies it into the live columns, clears it. With no draft it returns the page unchanged. A refusal comes back like a save refusal, so the editor shows it at its field.
|
||||
4. **Discard** (`/counter/cmsPage/discard`, body: id): clears `draft`.
|
||||
5. **Reads.** `findById` returns the live fields plus `draft` (or null). `search` rows carry `hasDraft`. `findPublished` reads only the live columns, so visitors never see a draft.
|
||||
6. **mobile-api** adds `POST /api/admin/pages/{id}/publish` and `/discard`, each loading the page through the caller's scope first (another company's page is "not found"), relaying refusals like save.
|
||||
7. **Portal editor.** It edits the draft when there is one, else the live content. On a published page:
|
||||
- **Save** stores the draft; a banner then says visitors still see the published version, with **Publish changes** and **Discard changes** (Discard asks first);
|
||||
- **Publish changes** saves the current edits, then publishes.
|
||||
- Status radio Draft plus Save unpublishes, as today.
|
||||
- "View page" opens the live page; Preview shows the draft.
|
||||
8. **Pages list** shows an "Unpublished changes" badge next to the status for rows with `hasDraft`.
|
||||
9. **Templates** are block lists in portal code (`app/lib/pageTemplates.ts`), English placeholder text, no images, the FORM block with no event and link name `signup`, buttons linking to `#signup`.
|
||||
- **Event sign-up:** HERO (Dark), TRUST, FEATURES, STEPS (Muted), FAQ, FORM (Muted).
|
||||
- **Service showcase:** HERO (Dark), TRUST, FEATURES, STEPS, FAQ, CTA (Accent), FORM (Muted).
|
||||
- `/pages/new` first shows a picker (Blank and the two templates, each with a one-line description); choosing one opens the editor filled with its blocks. A test runs every template through the same rules the server applies, apart from the event and images that staff fill in.
|
||||
10. **Duplicate** (list row action and editor button) opens `/pages/new?from=<id>`. The editor loads that page (its draft if any), clears the id, sets status Draft, title "<title> (copy)" and slug "<slug>-copy", same company. Nothing is stored until Save. No new API.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- Two staff editing one published page overwrite each other's draft (last save wins), as today for live pages. Accepted.
|
||||
- A draft's slug can collide with a page published after the draft was saved → Publish checks again and refuses on `slug`.
|
||||
- Rollback drops unpublished drafts → noted in `99-rollback.sql`; publish or note drafts first.
|
||||
|
||||
## Migration Plan
|
||||
|
||||
1. Run `sql/01-page-draft.sql` (DDL) before the new services-counter starts.
|
||||
2. Deploy services-counter, mobile-api, the portal; run `sql/02-draft-template-labels.sql`.
|
||||
Rollback: previous images, then `sql/99-rollback.sql`.
|
||||
@@ -0,0 +1,29 @@
|
||||
## Why
|
||||
|
||||
Marketing staff will edit pages that are already live and that printed QR codes point to. Today every Save on a published page changes it for visitors at once, so half-finished edits go live. Staff also start each event page from a blank form, though most event pages share one shape. This is change 2 of the page builder: `docs/superpowers/specs/2026-12-03-page-builder-design.md`.
|
||||
|
||||
## What Changes
|
||||
|
||||
- Published pages keep a separate draft. Saving a published page stores the draft; visitors keep seeing the published version until staff press **Publish changes**. **Discard changes** drops the draft. Unpublishing and pages never published work as today.
|
||||
- The staff preview and the editor show the draft when there is one. The pages list marks pages with unpublished changes.
|
||||
- **New page** first offers a starting point: Blank, **Event sign-up** or **Service showcase** (starter templates built from the section types).
|
||||
- **Duplicate** copies a page into a new draft of the same company.
|
||||
- New labels in English and Chinese.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
None.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- `landing-pages`: draft and live content, starter templates, duplicate.
|
||||
|
||||
## Impact
|
||||
|
||||
- DDL: `cms_page.draft` (nullable JSON) in `sql/01-page-draft.sql`; mirror in `local/seed/`.
|
||||
- services-counter: save writes the draft for a published page; new publish and discard endpoints; `findById` returns the draft; list rows carry `hasDraft`; `findPublished` unchanged.
|
||||
- mobile-api: publish and discard admin endpoints, scoped like save.
|
||||
- Portal: BFF routes, editor buttons and banner, list badge, preview, template picker, duplicate, labels.
|
||||
- Rollback: `sql/99-rollback.sql` drops the column, which loses unpublished drafts; the previous release saves published pages directly again.
|
||||
@@ -0,0 +1,83 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: The Pages List
|
||||
|
||||
`/pages` SHALL list the pages in scope with their title, public address, status, an "Unpublished changes" mark when a published page has a draft, and last update, with a search by title or slug and an Add page action. Each row SHALL open its editor and offer Duplicate. Pages SHALL appear in the sidebar for users with `BO_PAGES`.
|
||||
|
||||
#### Scenario: Draft in the list
|
||||
|
||||
- **GIVEN** INS page `launch` is a draft
|
||||
- **WHEN** INS staff open `/pages`
|
||||
- **THEN** its row shows status Draft and address `/p/INS/launch`
|
||||
|
||||
#### Scenario: Unpublished changes in the list
|
||||
|
||||
- **GIVEN** INS page `hotel` is published and has a saved draft
|
||||
- **WHEN** INS staff open `/pages`
|
||||
- **THEN** its row shows status Published and "Unpublished changes"
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Published Pages Keep A Separate Draft
|
||||
|
||||
Saving a published page with status Published SHALL store the content as the page's draft, checked by the same rules as any save, and SHALL NOT change what visitors see. Saving a published page with status Draft SHALL unpublish it, write the content to the page and drop any draft. A page that is not published SHALL save directly, as before. The staff preview and the editor SHALL show the draft when there is one.
|
||||
|
||||
#### Scenario: Editing a live page does not change it for visitors
|
||||
|
||||
- **GIVEN** INS page `hotel` is published with heading "Hotel day"
|
||||
- **WHEN** staff change the heading to "Hotel week" and save
|
||||
- **THEN** visitors still see "Hotel day"
|
||||
- **AND** the editor and the staff preview show "Hotel week"
|
||||
|
||||
#### Scenario: Unpublishing drops the draft
|
||||
|
||||
- **GIVEN** a published page with a draft
|
||||
- **WHEN** staff choose status Draft and save
|
||||
- **THEN** the page is a draft with the saved content and no separate draft
|
||||
|
||||
### Requirement: Publish And Discard Changes
|
||||
|
||||
Publishing a page's changes SHALL check its draft again by the same rules, including a unique slug, then make it the page's content and drop the draft. A refusal SHALL show at its field and change nothing. Discarding changes SHALL ask first, then drop the draft so the editor shows the published content again. Both SHALL be limited to pages in the caller's company scope.
|
||||
|
||||
#### Scenario: Publish changes
|
||||
|
||||
- **GIVEN** published page `hotel` has a draft with heading "Hotel week"
|
||||
- **WHEN** staff press Publish changes
|
||||
- **THEN** visitors see "Hotel week" and the page has no draft
|
||||
|
||||
#### Scenario: Publish refused for a taken slug
|
||||
|
||||
- **GIVEN** a draft with slug `launch` and another page published with slug `launch` since
|
||||
- **WHEN** staff press Publish changes
|
||||
- **THEN** the publish is refused on field `slug` and visitors still see the old content
|
||||
|
||||
#### Scenario: Discard changes
|
||||
|
||||
- **GIVEN** published page `hotel` has a draft
|
||||
- **WHEN** staff press Discard changes and confirm
|
||||
- **THEN** the draft is gone and the editor shows the published content
|
||||
|
||||
#### Scenario: Another company's page
|
||||
|
||||
- **WHEN** CV staff ask to publish INS page `hotel`
|
||||
- **THEN** the request is answered "not found" and nothing changes
|
||||
|
||||
### Requirement: Starter Templates
|
||||
|
||||
New page SHALL first offer Blank, Event sign-up and Service showcase. A template SHALL fill the editor with its sections, placeholder text, a sign-up form with link name `signup` and no event, and buttons linking to `#signup`; nothing is stored until staff save. Every template's sections SHALL pass the server's block rules once an event is chosen.
|
||||
|
||||
#### Scenario: Start from the event template
|
||||
|
||||
- **WHEN** staff choose New page, then Event sign-up
|
||||
- **THEN** the editor shows a hero, trust strip, feature cards, steps, FAQ and a sign-up form, filled with placeholder text
|
||||
- **AND** saving it without choosing the form's event is refused on that event field
|
||||
|
||||
### Requirement: Duplicate A Page
|
||||
|
||||
Duplicate SHALL open the editor with a copy of the page's current content (its draft when there is one), as a new unsaved draft page of the same company titled "<title> (copy)" with slug "<slug>-copy". Nothing SHALL be stored until staff save.
|
||||
|
||||
#### Scenario: Duplicate last event's page
|
||||
|
||||
- **GIVEN** INS page `hotel` titled "Hotel day"
|
||||
- **WHEN** staff press Duplicate on it and save
|
||||
- **THEN** a new draft INS page `hotel-copy` titled "Hotel day (copy)" exists with the same sections
|
||||
@@ -0,0 +1,5 @@
|
||||
-- Co-Lite change add-page-drafts-and-templates: a published page's unpublished draft.
|
||||
-- Run before the new services-counter starts. DDL: needs a user that may alter tables.
|
||||
USE `service-counter`;
|
||||
ALTER TABLE `cms_page`
|
||||
ADD COLUMN `draft` json NULL COMMENT 'Unpublished changes of a published page: slug, title, metaDescription, hideHeader, blocks' AFTER `blocks`;
|
||||
@@ -0,0 +1,39 @@
|
||||
-- The labels added by add-page-drafts-and-templates, 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 'PagesHasDraft', JSON_OBJECT('en_US', 'Unpublished changes', 'zh_CN', '有未发布的修改'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHasDraft') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '有未发布的修改') WHERE LOWER(code) = LOWER('PagesHasDraft') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesDraftBanner', JSON_OBJECT('en_US', 'You have unpublished changes. Visitors still see the published version until you publish them.', 'zh_CN', '您有未发布的修改。发布之前,访客看到的仍是已发布的版本。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDraftBanner') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '您有未发布的修改。发布之前,访客看到的仍是已发布的版本。') WHERE LOWER(code) = LOWER('PagesDraftBanner') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesPublishChanges', JSON_OBJECT('en_US', 'Publish changes', 'zh_CN', '发布修改'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesPublishChanges') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '发布修改') WHERE LOWER(code) = LOWER('PagesPublishChanges') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesDiscardChanges', JSON_OBJECT('en_US', 'Discard changes', 'zh_CN', '放弃修改'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDiscardChanges') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '放弃修改') WHERE LOWER(code) = LOWER('PagesDiscardChanges') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesDiscardTitle', JSON_OBJECT('en_US', 'Discard unpublished changes?', 'zh_CN', '放弃未发布的修改?'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDiscardTitle') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '放弃未发布的修改?') WHERE LOWER(code) = LOWER('PagesDiscardTitle') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesDiscardMessage', JSON_OBJECT('en_US', 'Your unpublished changes to "{title}" will be lost. Visitors keep seeing the published version.', 'zh_CN', '“{title}”未发布的修改将会丢失。访客仍看到已发布的版本。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDiscardMessage') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '“{title}”未发布的修改将会丢失。访客仍看到已发布的版本。') WHERE LOWER(code) = LOWER('PagesDiscardMessage') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesChangesPublished', JSON_OBJECT('en_US', 'Changes published.', 'zh_CN', '修改已发布。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesChangesPublished') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '修改已发布。') WHERE LOWER(code) = LOWER('PagesChangesPublished') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesChangesDiscarded', JSON_OBJECT('en_US', 'Changes discarded.', 'zh_CN', '修改已放弃。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesChangesDiscarded') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '修改已放弃。') WHERE LOWER(code) = LOWER('PagesChangesDiscarded') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesPreviewDraftBanner', JSON_OBJECT('en_US', 'Preview of unpublished changes. Visitors still see the published version.', 'zh_CN', '未发布修改的预览。访客看到的仍是已发布的版本。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesPreviewDraftBanner') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '未发布修改的预览。访客看到的仍是已发布的版本。') WHERE LOWER(code) = LOWER('PagesPreviewDraftBanner') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesDuplicate', JSON_OBJECT('en_US', 'Duplicate', 'zh_CN', '复制'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDuplicate') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '复制') WHERE LOWER(code) = LOWER('PagesDuplicate') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesDuplicateNamed', JSON_OBJECT('en_US', 'Duplicate {title}', 'zh_CN', '复制 {title}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesDuplicateNamed') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '复制 {title}') WHERE LOWER(code) = LOWER('PagesDuplicateNamed') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesChooseStart', JSON_OBJECT('en_US', 'How do you want to start?', 'zh_CN', '您想如何开始?'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesChooseStart') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '您想如何开始?') WHERE LOWER(code) = LOWER('PagesChooseStart') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesStartBlank', JSON_OBJECT('en_US', 'Blank page', 'zh_CN', '空白网页'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesStartBlank') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '空白网页') WHERE LOWER(code) = LOWER('PagesStartBlank') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesStartBlankHint', JSON_OBJECT('en_US', 'Start empty and add sections yourself.', 'zh_CN', '从空白开始,自行添加区块。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesStartBlankHint') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '从空白开始,自行添加区块。') WHERE LOWER(code) = LOWER('PagesStartBlankHint') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesTemplateEvent', JSON_OBJECT('en_US', 'Event sign-up', 'zh_CN', '活动报名'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTemplateEvent') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '活动报名') WHERE LOWER(code) = LOWER('PagesTemplateEvent') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesTemplateEventHint', JSON_OBJECT('en_US', 'A page for one event: headline, benefits, steps, questions and the sign-up form.', 'zh_CN', '为单个活动准备的网页:标题、优势、步骤、常见问题和报名表。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTemplateEventHint') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '为单个活动准备的网页:标题、优势、步骤、常见问题和报名表。') WHERE LOWER(code) = LOWER('PagesTemplateEventHint') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesTemplateShowcase', JSON_OBJECT('en_US', 'Service showcase', 'zh_CN', '服务展示'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTemplateShowcase') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '服务展示') WHERE LOWER(code) = LOWER('PagesTemplateShowcase') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesTemplateShowcaseHint', JSON_OBJECT('en_US', 'Present a service with benefits, steps and a call to action, ending with the sign-up form.', 'zh_CN', '介绍一项服务:优势、步骤和行动号召,最后是报名表。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesTemplateShowcaseHint') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '介绍一项服务:优势、步骤和行动号召,最后是报名表。') WHERE LOWER(code) = LOWER('PagesTemplateShowcaseHint') AND area = 'A';
|
||||
@@ -0,0 +1,8 @@
|
||||
-- Co-Lite change add-page-drafts-and-templates: rollback. Dropping the column loses every unpublished draft:
|
||||
-- publish or note them first. Then deploy the previous services-counter, which saves published pages directly.
|
||||
USE `service-counter`;
|
||||
ALTER TABLE `cms_page` DROP COLUMN `draft`;
|
||||
|
||||
-- Labels (02-draft-template-labels.sql).
|
||||
USE `service-system`;
|
||||
DELETE FROM message WHERE code IN ('PagesHasDraft', 'PagesDraftBanner', 'PagesPublishChanges', 'PagesDiscardChanges', 'PagesDiscardTitle', 'PagesDiscardMessage', 'PagesChangesPublished', 'PagesChangesDiscarded', 'PagesPreviewDraftBanner', 'PagesDuplicate', 'PagesDuplicateNamed', 'PagesChooseStart', 'PagesStartBlank', 'PagesStartBlankHint', 'PagesTemplateEvent', 'PagesTemplateEventHint', 'PagesTemplateShowcase', 'PagesTemplateShowcaseHint') AND area = 'A';
|
||||
@@ -0,0 +1,23 @@
|
||||
# Tasks: add-page-drafts-and-templates
|
||||
|
||||
Design: `design.md` and `docs/superpowers/specs/2026-12-03-page-builder-design.md` (change 2). Every task is TDD. Work is serial in the main session, with a self-review per task.
|
||||
|
||||
## 1. Data and services
|
||||
|
||||
- [x] 1.1 SQL: `sql/01-page-draft.sql`, `sql/99-rollback.sql`; mirror 01 into `local/seed/`; apply locally.
|
||||
- [x] 1.2 services-counter: `draft` on the entity and DTO, `hasDraft` on list rows; save rules for published pages; publish (re-validate, slug check) and discard endpoints; `findPublished` unchanged.
|
||||
- Verify: `mvn -T 1C -B -pl solvway-services-counter -am verify`
|
||||
- [x] 1.3 mobile-api: `POST /api/admin/pages/{id}/publish` and `/discard`, scoped, refusals relayed like save.
|
||||
- Verify: `mvn -T 1C -B -pl solvway-mobile-api -am verify`
|
||||
|
||||
## 2. Portal
|
||||
|
||||
- [x] 2.1 BFF routes for publish and discard; services; the editor loads the draft, the published-page banner with Publish changes and Discard changes (confirm); preview shows the draft; list badge.
|
||||
- [x] 2.2 Templates (`pageTemplates.ts`, with a rules test) and the start picker on New page; Duplicate in the list and editor.
|
||||
- [x] 2.3 Labels in `defaultMessages.ts` and `zh_CN.seed.json`, `npm run i18n:sql`, `sql/02-draft-template-labels.sql`; rollback lines.
|
||||
- Verify (2.1 to 2.3): `cd solvway-admin-portal && npx vitest run; echo VITEST=$? && npx tsc --noEmit && npm run lint`
|
||||
|
||||
## 3. Release
|
||||
|
||||
- [x] 3.1 `docs/deployment.md`: SQL rows (01 before services-counter starts), the draft behaviour for staff.
|
||||
- [x] 3.2 Live check (Playwright), on disposable pages: edit a published page and save (the visitor still sees the old version, preview shows the new); Publish changes; Discard changes; New page from each template (refused without an event, then saved); Duplicate; 1280 and 360 px.
|
||||
@@ -0,0 +1,15 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
|
||||
type Ctx = { params: Promise<{ id: string }> };
|
||||
|
||||
export async function POST(_req: NextRequest, { params }: Ctx) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { id } = await params;
|
||||
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/pages/${encodeURIComponent(id)}/discard`, { method: "POST", token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
|
||||
type Ctx = { params: Promise<{ id: string }> };
|
||||
|
||||
export async function POST(_req: NextRequest, { params }: Ctx) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { id } = await params;
|
||||
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/pages/${encodeURIComponent(id)}/publish`, { method: "POST", token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -8,6 +8,8 @@ vi.mock("@/app/lib/server/clientContext", () => ({ clientIp: () => "203.0.113.9"
|
||||
import * as list from "./route";
|
||||
import * as one from "./[id]/route";
|
||||
import * as images from "./images/route";
|
||||
import * as publish from "./[id]/publish/route";
|
||||
import * as discard from "./[id]/discard/route";
|
||||
import * as form from "../public/pages/[company]/[slug]/form/[block]/route";
|
||||
import * as image from "../public/page-images/[id]/route";
|
||||
import * as branding from "../companies/[id]/branding/route";
|
||||
@@ -42,6 +44,10 @@ describe("admin page routes", () => {
|
||||
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/pages/1", { method: "PUT", body: { title: "T" }, token: "jwt" });
|
||||
await one.DELETE(req("/api/pages/1", { method: "DELETE" }), ctx({ id: "1" }));
|
||||
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/pages/1", { method: "DELETE", token: "jwt" });
|
||||
await publish.POST(req("/api/pages/1/publish", { method: "POST" }), ctx({ id: "1/x" }));
|
||||
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/pages/1%2Fx/publish", { method: "POST", token: "jwt" });
|
||||
await discard.POST(req("/api/pages/1/discard", { method: "POST" }), ctx({ id: "1" }));
|
||||
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/pages/1/discard", { method: "POST", token: "jwt" });
|
||||
await list.POST(req("/api/pages", { method: "POST", body: JSON.stringify({ title: "T" }) }));
|
||||
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/pages", { method: "POST", body: { title: "T" }, token: "jwt" });
|
||||
});
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { render, screen, waitFor, within } 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(), publishPage: vi.fn(), discardPage: 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,
|
||||
publishPage: mocks.publishPage, discardPage: mocks.discardPage,
|
||||
}));
|
||||
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";
|
||||
|
||||
// add-page-drafts-and-templates: a published page's edits stay a draft until Publish changes.
|
||||
const live = {
|
||||
id: 5, companyId: 2, slug: "hotel", title: "Hotel day", metaDescription: null, status: "PUBLISHED" as const, hideHeader: false,
|
||||
blocks: [{ type: "CTA" as const, heading: "Live heading", buttonLabel: "Go", buttonUrl: "#signup" }], draft: null, hasDraft: false,
|
||||
};
|
||||
const draft = { slug: "hotel-week", title: "Hotel week", metaDescription: null, hideHeader: false, blocks: [{ type: "CTA" as const, heading: "Draft heading", buttonLabel: "Go", buttonUrl: "#signup" }] };
|
||||
const withDraft = { ...live, draft, hasDraft: true };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
memoryRouter.reset("/pages/5");
|
||||
mocks.useAdminAuth.mockReturnValue({ isSuper: false, companyCode: "INS" });
|
||||
mocks.useCompanyScope.mockReturnValue({ companyId: undefined, companies: [], codeOf: (id?: number) => (id === 2 ? "INS" : "") });
|
||||
mocks.listAdminEvents.mockResolvedValue({ items: [], total: 0 });
|
||||
mocks.getPage.mockResolvedValue(live);
|
||||
mocks.savePage.mockResolvedValue(withDraft);
|
||||
mocks.publishPage.mockResolvedValue({ ...live, slug: "hotel-week", title: "Hotel week", blocks: draft.blocks });
|
||||
mocks.discardPage.mockResolvedValue(live);
|
||||
});
|
||||
|
||||
describe("PageEditor drafts", () => {
|
||||
it("edits the draft when there is one, while View page stays on the live address", async () => {
|
||||
mocks.getPage.mockResolvedValue(withDraft);
|
||||
render(<PageEditor pageId={5} />);
|
||||
expect(await screen.findByLabelText("Title")).toHaveValue("Hotel week");
|
||||
expect(screen.getByLabelText("Heading")).toHaveValue("Draft heading");
|
||||
expect(screen.getByRole("link", { name: "View page" })).toHaveAttribute("href", "/p/INS/hotel");
|
||||
expect(screen.getByText(/Visitors still see the published version/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("saving a published page shows the banner, and Publish changes saves then publishes", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<PageEditor pageId={5} />);
|
||||
expect(await screen.findByLabelText("Title")).toHaveValue("Hotel day");
|
||||
expect(screen.queryByText(/Visitors still see the published version/)).not.toBeInTheDocument();
|
||||
await user.clear(screen.getByLabelText("Title"));
|
||||
await user.type(screen.getByLabelText("Title"), "Hotel week");
|
||||
const scroll = vi.fn();
|
||||
Element.prototype.scrollIntoView = scroll;
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByText(/Visitors still see the published version/)).toBeInTheDocument();
|
||||
// Save sits at the bottom of a long form: the banner is brought into view.
|
||||
await waitFor(() => expect(scroll).toHaveBeenCalled());
|
||||
expect(scroll.mock.contexts[0]).toHaveTextContent(/Visitors still see the published version/);
|
||||
expect(screen.getByLabelText("Title")).toHaveValue("Hotel week");
|
||||
|
||||
await user.click(screen.getByRole("button", { name: "Publish changes" }));
|
||||
await waitFor(() => expect(mocks.publishPage).toHaveBeenCalledWith(5));
|
||||
expect(mocks.savePage).toHaveBeenCalledTimes(2);
|
||||
expect(mocks.savePage.mock.invocationCallOrder[1]).toBeLessThan(mocks.publishPage.mock.invocationCallOrder[0]);
|
||||
await waitFor(() => expect(screen.queryByText(/Visitors still see the published version/)).not.toBeInTheDocument());
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Changes published");
|
||||
expect(screen.getByRole("link", { name: "View page" })).toHaveAttribute("href", "/p/INS/hotel-week");
|
||||
});
|
||||
|
||||
it("offers Duplicate for a saved page", async () => {
|
||||
render(<PageEditor pageId={5} />);
|
||||
expect(await screen.findByRole("link", { name: "Duplicate" })).toHaveAttribute("href", "/pages/new?from=5");
|
||||
});
|
||||
|
||||
it("a publish refusal shows at its field and keeps the banner", async () => {
|
||||
mocks.getPage.mockResolvedValue(withDraft);
|
||||
mocks.publishPage.mockRejectedValue(new ApiError("x", 409, { code: "PagesSlugTaken", details: { field: "slug" } }));
|
||||
const user = userEvent.setup();
|
||||
render(<PageEditor pageId={5} />);
|
||||
await user.click(await screen.findByRole("button", { name: "Publish changes" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Another page already uses this slug.");
|
||||
expect(screen.getByText(/Visitors still see the published version/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("Discard changes asks first, then shows the live page again", async () => {
|
||||
mocks.getPage.mockResolvedValue(withDraft);
|
||||
const user = userEvent.setup();
|
||||
render(<PageEditor pageId={5} />);
|
||||
await user.click(await screen.findByRole("button", { name: "Discard changes" }));
|
||||
expect(mocks.discardPage).not.toHaveBeenCalled();
|
||||
await user.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Discard changes" }));
|
||||
await waitFor(() => expect(mocks.discardPage).toHaveBeenCalledWith(5));
|
||||
expect(await screen.findByLabelText("Title")).toHaveValue("Hotel day");
|
||||
expect(screen.getByLabelText("Heading")).toHaveValue("Live heading");
|
||||
expect(screen.queryByText(/Visitors still see the published version/)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -16,8 +16,8 @@ import { ApiError } from "@/app/lib/clientApi";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { CopyAddress } from "./CopyAddress";
|
||||
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 { BLOCK_LABELS, BLOCK_TYPES, emptyBlock, emptyPage, pageAddress, pageBody, withTitle, type CmsBlock, type CmsPage, type CmsPageDraft, type PageStatus } from "@/app/lib/cmsPages";
|
||||
import { deletePage, discardPage, getPage, publishPage, 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";
|
||||
@@ -46,45 +46,73 @@ function FieldError({ message }: { message?: string }) {
|
||||
return message ? <p role="alert" className="text-sm text-destructive">{message}</p> : null;
|
||||
}
|
||||
|
||||
export function PageEditor({ pageId }: { pageId?: number }) {
|
||||
/** pageId edits a page; fromId opens an unsaved copy of one (Duplicate); initialBlocks start a new page (templates). */
|
||||
export function PageEditor({ pageId, fromId, initialBlocks }: { pageId?: number; fromId?: number; initialBlocks?: CmsBlock[] }) {
|
||||
const t = useT();
|
||||
const router = useRouter();
|
||||
const { isSuper, companyCode } = useAdminAuth();
|
||||
const scope = useCompanyScope();
|
||||
const justSaved = useSearchParams()?.get("saved") === "1";
|
||||
const [draft, setDraft] = useState<CmsPageDraft>(() => ({ ...emptyPage(), companyId: scope.companyId }));
|
||||
const [rows, setRows] = useState<Row[]>([]);
|
||||
const [rows, setRows] = useState<Row[]>(() => (initialBlocks ?? []).map((block, i) => ({ key: -1 - i, block })));
|
||||
const [pending, setPending] = useState<Record<number, { file: File; preview?: string }>>({});
|
||||
// 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 loadId = pageId ?? fromId;
|
||||
const [loading, setLoading] = useState(loadId != null);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [summary, setSummary] = useState<string | null>(null);
|
||||
const [notice, setNotice] = useState<string | null>(justSaved ? "PagesSaved" : null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [confirmDelete, setConfirmDelete] = useState(false);
|
||||
const [confirmDiscard, setConfirmDiscard] = useState(false);
|
||||
// A published page's edits are saved as a draft; visitors see the live version until Publish changes.
|
||||
const [hasDraft, setHasDraft] = useState(false);
|
||||
// Bumped when a save leaves a draft: Save sits below a long form, so the banner is scrolled into view.
|
||||
const [revealDraft, setRevealDraft] = useState(0);
|
||||
const draftBanner = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
if (revealDraft) draftBanner.current?.scrollIntoView?.({ behavior: "smooth", block: "nearest" });
|
||||
}, [revealDraft]);
|
||||
const [events, setEvents] = useState<EventOption[]>([]);
|
||||
const nextKey = useRef(0);
|
||||
const toRows = (blocks: CmsBlock[]) => blocks.map((block) => ({ key: ++nextKey.current, block }));
|
||||
const isNew = draft.id == null;
|
||||
|
||||
/** Shows a loaded page: its draft when there is one, else the live content. */
|
||||
function show(p: CmsPage) {
|
||||
const c = p.draft ?? p;
|
||||
setDraft({ id: p.id, companyId: p.companyId, slug: c.slug, slugTouched: true, title: c.title, metaDescription: c.metaDescription ?? "", status: p.status, hideHeader: !!c.hideHeader, blocks: [] });
|
||||
setRows(toRows(c.blocks ?? []));
|
||||
setPending({});
|
||||
setSaved({ slug: p.slug, status: p.status });
|
||||
setHasDraft(!!p.draft);
|
||||
setDirty(false);
|
||||
}
|
||||
const code = (isSuper ? scope.codeOf(draft.companyId) : companyCode) || "";
|
||||
|
||||
useEffect(() => {
|
||||
if (pageId == null) return;
|
||||
if (loadId == null) return;
|
||||
let cancelled = false;
|
||||
getPage(pageId)
|
||||
getPage(loadId)
|
||||
.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, hideHeader: !!p.hideHeader, blocks: [] });
|
||||
setRows(toRows(p.blocks ?? []));
|
||||
setSaved({ slug: p.slug, status: p.status });
|
||||
show(p);
|
||||
if (pageId == null) {
|
||||
// Duplicate: the same company's content as a new, unsaved draft page.
|
||||
setDraft((d) => ({ ...d, id: undefined, status: "DRAFT", title: `${d.title} (copy)`, slug: `${d.slug}-copy` }));
|
||||
setSaved(null);
|
||||
setHasDraft(false);
|
||||
setDirty(true);
|
||||
}
|
||||
})
|
||||
.catch((err: unknown) => { if (!cancelled) setLoadError(err instanceof ApiError && err.status === 404 ? "PagesNotFound" : "PagesLoadFailed"); })
|
||||
.finally(() => { if (!cancelled) setLoading(false); });
|
||||
return () => { cancelled = true; };
|
||||
}, [pageId]);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- show only sets state; load again only for another page.
|
||||
}, [loadId]);
|
||||
|
||||
// The FORM picker: the page company's enabled events that have not ended (Malaysia dates).
|
||||
const eventsCompany = isSuper ? draft.companyId : undefined;
|
||||
@@ -141,13 +169,13 @@ export function PageEditor({ pageId }: { pageId?: number }) {
|
||||
else setSummary(message);
|
||||
}
|
||||
|
||||
async function save() {
|
||||
async function save(): Promise<boolean> {
|
||||
setSummary(null);
|
||||
setNotice(null);
|
||||
setErrors({});
|
||||
if (isNew && isSuper && !draft.companyId) {
|
||||
setErrors({ companyId: t("ChooseCompany") });
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
setSaving(true);
|
||||
const next = rows.map((r) => ({ ...r }));
|
||||
@@ -162,11 +190,15 @@ export function PageEditor({ pageId }: { pageId?: number }) {
|
||||
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 });
|
||||
setHasDraft(!!page.draft);
|
||||
if (page.draft) setRevealDraft((n) => n + 1);
|
||||
setDirty(false);
|
||||
setNotice("PagesSaved");
|
||||
if (isNew) router.replace(`/pages/${page.id}?saved=1`);
|
||||
return true;
|
||||
} catch (err) {
|
||||
showError(err);
|
||||
return false;
|
||||
} finally {
|
||||
// Uploaded images stay on their blocks and leave the pending set, success or not.
|
||||
setRows(next);
|
||||
@@ -175,6 +207,37 @@ export function PageEditor({ pageId }: { pageId?: number }) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Saves the current edits, then makes the draft live. */
|
||||
async function publishChanges() {
|
||||
if (draft.id == null || !(await save())) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
show(await publishPage(draft.id));
|
||||
setNotice("PagesChangesPublished");
|
||||
} catch (err) {
|
||||
setNotice(null);
|
||||
showError(err);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function discardChanges() {
|
||||
if (draft.id == null) return;
|
||||
setSaving(true);
|
||||
setSummary(null);
|
||||
setErrors({});
|
||||
try {
|
||||
show(await discardPage(draft.id));
|
||||
setNotice("PagesChangesDiscarded");
|
||||
} catch (err) {
|
||||
showError(err);
|
||||
} finally {
|
||||
setConfirmDiscard(false);
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function remove() {
|
||||
if (draft.id == null) return;
|
||||
setSaving(true);
|
||||
@@ -203,9 +266,14 @@ export function PageEditor({ pageId }: { pageId?: number }) {
|
||||
<div className="flex flex-wrap items-center justify-end gap-2">
|
||||
{saved && code ? <span className="mr-auto"><CopyAddress address={pageAddress(code, saved.slug)} /></span> : null}
|
||||
{draft.id != null ? (
|
||||
<Button variant="outline" asChild>
|
||||
<Link href={`/pages/${draft.id}/preview`}>{t("PagesPreview")}</Link>
|
||||
</Button>
|
||||
<>
|
||||
<Button variant="outline" asChild>
|
||||
<Link href={`/pages/new?from=${draft.id}`}>{t("PagesDuplicate")}</Link>
|
||||
</Button>
|
||||
<Button variant="outline" asChild>
|
||||
<Link href={`/pages/${draft.id}/preview`}>{t("PagesPreview")}</Link>
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
{saved?.status === "PUBLISHED" && code ? (
|
||||
<Button variant="outline" asChild>
|
||||
@@ -215,6 +283,13 @@ export function PageEditor({ pageId }: { pageId?: number }) {
|
||||
</div>
|
||||
{summary && <p role="alert" className="text-sm text-destructive">{summary}</p>}
|
||||
{notice && <p role="status" className="text-sm text-positive">{t(notice)}</p>}
|
||||
{hasDraft && draft.status === "PUBLISHED" ? (
|
||||
<div ref={draftBanner} className="flex scroll-mt-20 flex-wrap items-center gap-2 rounded-md border border-warning/30 bg-warning/10 px-3 py-2 text-sm">
|
||||
<p className="mr-auto">{t("PagesDraftBanner")}</p>
|
||||
<Button type="button" size="sm" variant="outline" disabled={saving} onClick={() => setConfirmDiscard(true)}>{t("PagesDiscardChanges")}</Button>
|
||||
<Button type="button" size="sm" disabled={saving} onClick={() => void publishChanges()}>{t("PagesPublishChanges")}</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
|
||||
<div className="space-y-4">
|
||||
@@ -313,6 +388,17 @@ export function PageEditor({ pageId }: { pageId?: number }) {
|
||||
<Button type="button" disabled={saving} onClick={() => void save()}>{t("Save")}</Button>
|
||||
</div>
|
||||
|
||||
{confirmDiscard ? (
|
||||
<ConfirmDialog
|
||||
title={t("PagesDiscardTitle")}
|
||||
message={t("PagesDiscardMessage", { title: draft.title })}
|
||||
confirmLabel={t("PagesDiscardChanges")}
|
||||
destructive
|
||||
busy={saving}
|
||||
onConfirm={() => void discardChanges()}
|
||||
onCancel={() => setConfirmDiscard(false)}
|
||||
/>
|
||||
) : null}
|
||||
{confirmDelete ? (
|
||||
<ConfirmDialog
|
||||
title={t("PagesDeleteTitle")}
|
||||
|
||||
@@ -72,6 +72,19 @@ export interface CmsPage {
|
||||
hideHeader?: boolean;
|
||||
blocks: CmsBlock[];
|
||||
updatedAt?: string | null;
|
||||
/** Unpublished changes of a published page (editor reads only). */
|
||||
draft?: PageContent | null;
|
||||
/** List rows: the page has unpublished changes. */
|
||||
hasDraft?: boolean;
|
||||
}
|
||||
|
||||
/** What a draft holds; status and company stay on the page. */
|
||||
export interface PageContent {
|
||||
slug: string;
|
||||
title: string;
|
||||
metaDescription: string | null;
|
||||
hideHeader?: boolean;
|
||||
blocks: CmsBlock[];
|
||||
}
|
||||
|
||||
export interface CmsPageDraft {
|
||||
|
||||
@@ -63,6 +63,14 @@ describe("preview frame", () => {
|
||||
expect(res.headers.get("content-security-policy")).toMatch(/^sandbox allow-scripts/);
|
||||
});
|
||||
|
||||
it("serves the unpublished changes' HTML block when the page has a draft", async () => {
|
||||
const draft = { slug: "hotel", title: "Hotel", blocks: [{ type: "HTML", html: "<p>draft only</p>" }] };
|
||||
mocks.callMobileApi.mockResolvedValueOnce({ ok: true, data: { slug: "hotel", title: "Hotel", blocks: [{ type: "FAQ" }], draft } });
|
||||
const res = await preview.GET(req, ctx({ id: "5", block: "0" }));
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.text()).toContain("draft only");
|
||||
});
|
||||
|
||||
it("is not found without a session, for a bad id, a refused page or a non-HTML block", async () => {
|
||||
mocks.getToken.mockResolvedValueOnce(null);
|
||||
expect((await preview.GET(req, ctx({ id: "5", block: "0" }))).status).toBe(404);
|
||||
|
||||
@@ -742,6 +742,24 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
PagesPreview: "Preview",
|
||||
PagesPreviewBanner: "Preview. Visitors see this page only once it is published.",
|
||||
PagesViewPage: "View page",
|
||||
PagesDuplicate: "Duplicate",
|
||||
PagesDuplicateNamed: "Duplicate {title}",
|
||||
PagesChooseStart: "How do you want to start?",
|
||||
PagesStartBlank: "Blank page",
|
||||
PagesStartBlankHint: "Start empty and add sections yourself.",
|
||||
PagesTemplateEvent: "Event sign-up",
|
||||
PagesTemplateEventHint: "A page for one event: headline, benefits, steps, questions and the sign-up form.",
|
||||
PagesTemplateShowcase: "Service showcase",
|
||||
PagesTemplateShowcaseHint: "Present a service with benefits, steps and a call to action, ending with the sign-up form.",
|
||||
PagesHasDraft: "Unpublished changes",
|
||||
PagesDraftBanner: "You have unpublished changes. Visitors still see the published version until you publish them.",
|
||||
PagesPublishChanges: "Publish changes",
|
||||
PagesDiscardChanges: "Discard changes",
|
||||
PagesDiscardTitle: "Discard unpublished changes?",
|
||||
PagesDiscardMessage: "Your unpublished changes to \"{title}\" will be lost. Visitors keep seeing the published version.",
|
||||
PagesChangesPublished: "Changes published.",
|
||||
PagesChangesDiscarded: "Changes discarded.",
|
||||
PagesPreviewDraftBanner: "Preview of unpublished changes. Visitors still see the published version.",
|
||||
PagesSaved: "Page saved.",
|
||||
PagesSaveFailed: "Could not save the page. Try again.",
|
||||
PagesNotFound: "Page not found.",
|
||||
|
||||
@@ -726,6 +726,24 @@
|
||||
"PagesMetaDescription": "搜索引擎描述",
|
||||
"PagesPreview": "预览",
|
||||
"PagesPreviewBanner": "预览。网页发布后访客才能看到。",
|
||||
"PagesDuplicate": "复制",
|
||||
"PagesDuplicateNamed": "复制 {title}",
|
||||
"PagesChooseStart": "您想如何开始?",
|
||||
"PagesStartBlank": "空白网页",
|
||||
"PagesStartBlankHint": "从空白开始,自行添加区块。",
|
||||
"PagesTemplateEvent": "活动报名",
|
||||
"PagesTemplateEventHint": "为单个活动准备的网页:标题、优势、步骤、常见问题和报名表。",
|
||||
"PagesTemplateShowcase": "服务展示",
|
||||
"PagesTemplateShowcaseHint": "介绍一项服务:优势、步骤和行动号召,最后是报名表。",
|
||||
"PagesHasDraft": "有未发布的修改",
|
||||
"PagesDraftBanner": "您有未发布的修改。发布之前,访客看到的仍是已发布的版本。",
|
||||
"PagesPublishChanges": "发布修改",
|
||||
"PagesDiscardChanges": "放弃修改",
|
||||
"PagesDiscardTitle": "放弃未发布的修改?",
|
||||
"PagesDiscardMessage": "“{title}”未发布的修改将会丢失。访客仍看到已发布的版本。",
|
||||
"PagesChangesPublished": "修改已发布。",
|
||||
"PagesChangesDiscarded": "修改已放弃。",
|
||||
"PagesPreviewDraftBanner": "未发布修改的预览。访客看到的仍是已发布的版本。",
|
||||
"PagesViewPage": "查看网页",
|
||||
"PagesSaved": "网页已保存。",
|
||||
"PagesSaveFailed": "无法保存网页,请重试。",
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { ANCHOR, ICONS, isSafeLink, pageBody, emptyPage, type CmsBlock } from "@/app/lib/cmsPages";
|
||||
import { PAGE_TEMPLATES } from "@/app/lib/pageTemplates";
|
||||
|
||||
// The server's block rules (CmsBlockValidator) that a template can break, so a starter page never saves with an
|
||||
// error staff did not make. The event and images are left for staff to choose.
|
||||
function problems(blocks: CmsBlock[]): string[] {
|
||||
const out: string[] = [];
|
||||
const anchors = new Set<string>();
|
||||
const len = (v: string | undefined, max: number, path: string, required = false) => {
|
||||
if (required && !v?.trim()) out.push(`${path} required`);
|
||||
if (v && v.length > max) out.push(`${path} too long`);
|
||||
};
|
||||
blocks.forEach((b, i) => {
|
||||
const p = `blocks[${i}]`;
|
||||
if (b.anchor) {
|
||||
if (!ANCHOR.test(b.anchor) || anchors.has(b.anchor)) out.push(`${p}.anchor`);
|
||||
anchors.add(b.anchor);
|
||||
}
|
||||
const label = !!b.buttonLabel?.trim();
|
||||
if (label !== !!b.buttonUrl?.trim()) out.push(`${p} button pair`);
|
||||
if (b.buttonUrl && !isSafeLink(b.buttonUrl)) out.push(`${p}.buttonUrl`);
|
||||
if (b.buttonUrl?.startsWith("#") && !blocks.some((x) => x.anchor === b.buttonUrl!.slice(1))) out.push(`${p}.buttonUrl target`);
|
||||
len(b.buttonLabel, 40, `${p}.buttonLabel`, b.type === "CTA");
|
||||
len(b.heading, 120, `${p}.heading`, ["HERO", "FEATURES", "STEPS", "CTA"].includes(b.type));
|
||||
len(b.text, 300, `${p}.text`);
|
||||
if (b.type === "TRUST" && b.heading != null) out.push(`${p}.heading unused`);
|
||||
if (["FEATURES", "STEPS", "TRUST"].includes(b.type)) {
|
||||
const cards = b.cards ?? [];
|
||||
if (cards.length < 2 || cards.length > 6) out.push(`${p}.cards count`);
|
||||
cards.forEach((c, j) => {
|
||||
const cp = `${p}.cards[${j}]`;
|
||||
if (b.type === "FEATURES" ? !(c.icon && c.icon in ICONS) : c.icon != null) out.push(`${cp}.icon`);
|
||||
len(c.title, 80, `${cp}.title`, true);
|
||||
if (b.type === "TRUST" ? c.text != null : !c.text?.trim()) out.push(`${cp}.text`);
|
||||
len(c.text, 300, `${cp}.text`);
|
||||
});
|
||||
} else if (b.cards) out.push(`${p}.cards unused`);
|
||||
if (b.type === "FAQ") {
|
||||
if (!b.items?.length) out.push(`${p}.items count`);
|
||||
b.items?.forEach((it, j) => { len(it.question, 300, `${p}.items[${j}].question`, true); len(it.answer, 2000, `${p}.items[${j}].answer`, true); });
|
||||
}
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
describe("page templates", () => {
|
||||
it.each(PAGE_TEMPLATES)("$id passes the server's block rules", (tpl) => {
|
||||
expect(problems(pageBody({ ...emptyPage(), blocks: tpl.blocks() }).blocks)).toEqual([]);
|
||||
});
|
||||
|
||||
it("the rules catch a broken block", () => {
|
||||
expect(problems([{ type: "CTA", heading: "x", buttonLabel: "Go", buttonUrl: "#nowhere" }])).toEqual(["blocks[0].buttonUrl target"]);
|
||||
});
|
||||
|
||||
it.each(PAGE_TEMPLATES)("$id ends with a sign-up form named signup and no event", (tpl) => {
|
||||
const blocks = tpl.blocks();
|
||||
expect(blocks.at(-1)).toMatchObject({ type: "FORM", anchor: "signup", eventUuid: null });
|
||||
});
|
||||
|
||||
it("the sections are as designed", () => {
|
||||
expect(PAGE_TEMPLATES.map((t) => t.blocks().map((b) => b.type + (b.look ? `:${b.look}` : "")))).toEqual([
|
||||
["HERO:DARK", "TRUST", "FEATURES", "STEPS:MUTED", "FAQ", "FORM:MUTED"],
|
||||
["HERO:DARK", "TRUST", "FEATURES", "STEPS", "FAQ", "CTA:ACCENT", "FORM:MUTED"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("each use gets fresh blocks", () => {
|
||||
const [a, b] = [PAGE_TEMPLATES[0].blocks(), PAGE_TEMPLATES[0].blocks()];
|
||||
expect(a[0]).not.toBe(b[0]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { CmsBlock } from "@/app/lib/cmsPages";
|
||||
|
||||
// add-page-drafts-and-templates: starter pages for marketing staff. Placeholder text in English, no images, the
|
||||
// sign-up form without an event (staff choose it) and named "signup" so every button can link to it.
|
||||
|
||||
export interface PageTemplate {
|
||||
id: "EVENT" | "SHOWCASE";
|
||||
label: string;
|
||||
description: string;
|
||||
blocks: () => CmsBlock[];
|
||||
}
|
||||
|
||||
const hero = (): CmsBlock => ({
|
||||
type: "HERO", look: "DARK", heading: "Your event headline",
|
||||
text: "One or two sentences on what visitors get and why they should come.",
|
||||
buttonLabel: "Sign up now", buttonUrl: "#signup",
|
||||
});
|
||||
|
||||
const trust = (): CmsBlock => ({
|
||||
type: "TRUST", cards: [{ title: "Trusted by 500+ customers" }, { title: "Local support team" }, { title: "Free consultation" }],
|
||||
});
|
||||
|
||||
const features = (): CmsBlock => ({
|
||||
type: "FEATURES", heading: "What you get", text: "A short line introducing the benefits.",
|
||||
cards: [
|
||||
{ icon: "star", title: "First benefit", text: "Describe the first benefit in a sentence." },
|
||||
{ icon: "shield-check", title: "Second benefit", text: "Describe the second benefit in a sentence." },
|
||||
{ icon: "headset", title: "Third benefit", text: "Describe the third benefit in a sentence." },
|
||||
],
|
||||
});
|
||||
|
||||
const steps = (look?: CmsBlock["look"]): CmsBlock => ({
|
||||
type: "STEPS", ...(look ? { look } : {}), heading: "How it works",
|
||||
cards: [
|
||||
{ title: "Sign up", text: "Fill in the form below." },
|
||||
{ title: "We contact you", text: "Our team calls you to confirm the details." },
|
||||
{ title: "Enjoy", text: "Say what happens next." },
|
||||
],
|
||||
});
|
||||
|
||||
const faq = (): CmsBlock => ({
|
||||
type: "FAQ", heading: "Questions",
|
||||
items: [
|
||||
{ question: "A question visitors often ask?", answer: "The answer to it." },
|
||||
{ question: "Another common question?", answer: "The answer to it." },
|
||||
],
|
||||
});
|
||||
|
||||
const form = (): CmsBlock => ({ type: "FORM", look: "MUTED", anchor: "signup", heading: "Sign up", eventUuid: null });
|
||||
|
||||
export const PAGE_TEMPLATES: PageTemplate[] = [
|
||||
{
|
||||
id: "EVENT", label: "PagesTemplateEvent", description: "PagesTemplateEventHint",
|
||||
blocks: () => [hero(), trust(), features(), steps("MUTED"), faq(), form()],
|
||||
},
|
||||
{
|
||||
id: "SHOWCASE", label: "PagesTemplateShowcase", description: "PagesTemplateShowcaseHint",
|
||||
blocks: () => [hero(), trust(), features(), steps(), faq(),
|
||||
{ type: "CTA", look: "ACCENT", heading: "Ready to start?", text: "One line that asks visitors to act.", buttonLabel: "Sign up", buttonUrl: "#signup" },
|
||||
form()],
|
||||
},
|
||||
];
|
||||
@@ -24,6 +24,11 @@ export const getPage = (id: number) => apiGet<CmsPage>(`/api/pages/${id}`);
|
||||
export const savePage = (id: number | undefined, body: ReturnType<typeof pageBody>) =>
|
||||
id == null ? apiPost<CmsPage>("/api/pages", body) : apiPut<CmsPage>(`/api/pages/${id}`, body);
|
||||
|
||||
/** Makes a published page's saved draft live; refusals carry a field like a save. */
|
||||
export const publishPage = (id: number) => apiPost<CmsPage>(`/api/pages/${id}/publish`, {});
|
||||
|
||||
export const discardPage = (id: number) => apiPost<CmsPage>(`/api/pages/${id}/discard`, {});
|
||||
|
||||
export const deletePage = (id: number) => apiDelete<unknown>(`/api/pages/${id}`);
|
||||
|
||||
/** Base64 without the data-URL prefix; the counter checks type (PNG, JPEG, WebP) and size (2 MB). */
|
||||
|
||||
@@ -2,7 +2,7 @@ import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { frameNotFound, frameResponse, htmlBlock } from "@/app/lib/frameHtml";
|
||||
|
||||
// add-custom-html-block: a draft page's Custom HTML block for the staff preview, sealed like the public frame.
|
||||
// add-custom-html-block: a draft page's (or a published page's unpublished changes') Custom HTML block for the staff preview, sealed like the public frame.
|
||||
// The admin API checks BO_PAGES and the caller's company; anything it refuses is not found here.
|
||||
type Ctx = { params: Promise<{ id: string; block: string }> };
|
||||
|
||||
@@ -10,8 +10,8 @@ export async function GET(_req: Request, { params }: Ctx): Promise<Response> {
|
||||
const { id, block } = await params;
|
||||
const token = await getToken();
|
||||
if (!token || !/^\d{1,19}$/.test(id) || !/^\d{1,2}$/.test(block)) return frameNotFound();
|
||||
const result = await callMobileApi<{ blocks?: unknown }>(`/api/admin/pages/${encodeURIComponent(id)}`, { token });
|
||||
const result = await callMobileApi<{ blocks?: unknown; draft?: { blocks?: unknown } | null }>(`/api/admin/pages/${encodeURIComponent(id)}`, { token });
|
||||
if (!result.ok) return frameNotFound();
|
||||
const html = htmlBlock(result.data.blocks, block);
|
||||
const html = htmlBlock((result.data.draft ?? result.data).blocks, block);
|
||||
return html === null ? frameNotFound() : frameResponse(html, { preview: true });
|
||||
}
|
||||
@@ -15,6 +15,8 @@ interface AdminPage {
|
||||
hideHeader?: boolean;
|
||||
blocks: PublicBlock[];
|
||||
company?: Branding;
|
||||
/** Unpublished changes of a published page: the preview shows them. */
|
||||
draft?: { title: string; hideHeader?: boolean; blocks: PublicBlock[] } | null;
|
||||
}
|
||||
|
||||
export default async function PagePreview({ params }: Props) {
|
||||
@@ -24,8 +26,8 @@ export default async function PagePreview({ params }: Props) {
|
||||
const result = await callMobileApi<AdminPage>(`/api/admin/pages/${encodeURIComponent(id)}`, { token });
|
||||
if (!result.ok) notFound();
|
||||
const t = await getServerT();
|
||||
const page = result.data;
|
||||
const banner = <p role="status" className="bg-warning/15 px-4 py-2 text-center text-sm font-medium">{t("PagesPreviewBanner")}</p>;
|
||||
const page = result.data.draft ? { ...result.data, ...result.data.draft } : result.data;
|
||||
const banner = <p role="status" className="bg-warning/15 px-4 py-2 text-center text-sm font-medium">{t(result.data.draft ? "PagesPreviewDraftBanner" : "PagesPreviewBanner")}</p>;
|
||||
return (
|
||||
<RequireModule pathname="/pages">
|
||||
<LandingPage company={page.company ?? { code: "", name: "" }} page={page} banner={banner} preview frameBase={`/pages/${encodeURIComponent(id)}/preview/frame`} />
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getPage: vi.fn(), savePage: vi.fn(), deletePage: vi.fn(), uploadPageImage: vi.fn(), publishPage: vi.fn(), discardPage: 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,
|
||||
publishPage: mocks.publishPage, discardPage: mocks.discardPage,
|
||||
}));
|
||||
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 NewLandingPage from "./page";
|
||||
|
||||
// add-page-drafts-and-templates: New page starts from Blank or a template; Duplicate starts from a copy.
|
||||
const published = {
|
||||
id: 5, companyId: 2, slug: "hotel", title: "Hotel day", metaDescription: null, status: "PUBLISHED" as const, hideHeader: false,
|
||||
blocks: [{ type: "CTA" as const, heading: "Live", buttonLabel: "Go", buttonUrl: "/x" }],
|
||||
draft: { slug: "hotel", title: "Hotel day", metaDescription: null, hideHeader: true, blocks: [{ type: "CTA" as const, heading: "Draft", buttonLabel: "Go", buttonUrl: "/x" }] },
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
memoryRouter.reset("/pages/new");
|
||||
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: (m: string) => m === "BO_PAGES", isSuper: false, companyCode: "INS" });
|
||||
mocks.useCompanyScope.mockReturnValue({ companyId: undefined, companies: [], codeOf: (id?: number) => (id === 2 ? "INS" : "") });
|
||||
mocks.listAdminEvents.mockResolvedValue({ items: [], total: 0 });
|
||||
mocks.getPage.mockResolvedValue(published);
|
||||
mocks.savePage.mockImplementation(async (_id: unknown, body: object) => ({ ...published, ...body, id: 8, draft: null }));
|
||||
});
|
||||
|
||||
describe("New page", () => {
|
||||
it("offers Blank and the two templates first", async () => {
|
||||
render(<NewLandingPage />);
|
||||
expect(await screen.findByRole("link", { name: /Blank page/ })).toHaveAttribute("href", "/pages/new?template=BLANK");
|
||||
expect(screen.getByRole("link", { name: /Event sign-up/ })).toHaveAttribute("href", "/pages/new?template=EVENT");
|
||||
expect(screen.getByRole("link", { name: /Service showcase/ })).toHaveAttribute("href", "/pages/new?template=SHOWCASE");
|
||||
expect(screen.queryByLabelText("Title")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("a template fills the editor with its sections", async () => {
|
||||
memoryRouter.reset("/pages/new", "template=EVENT");
|
||||
render(<NewLandingPage />);
|
||||
expect(await screen.findByDisplayValue("Your event headline")).toBeInTheDocument();
|
||||
for (const legend of ["Block 1: Hero", "Block 2: Trust strip", "Block 3: Feature cards", "Block 4: Steps", "Block 5: FAQ", "Block 6: Sign-up form"]) {
|
||||
expect(screen.getByText(legend)).toBeInTheDocument();
|
||||
}
|
||||
expect(screen.getByLabelText("Event")).toBeInTheDocument();
|
||||
expect(mocks.savePage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("Blank opens an empty editor", async () => {
|
||||
memoryRouter.reset("/pages/new", "template=BLANK");
|
||||
render(<NewLandingPage />);
|
||||
expect(await screen.findByLabelText("Title")).toHaveValue("");
|
||||
expect(screen.queryByLabelText("Heading")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("Duplicate copies the current content as a new draft page of the same company", async () => {
|
||||
memoryRouter.reset("/pages/new", "from=5");
|
||||
const user = userEvent.setup();
|
||||
render(<NewLandingPage />);
|
||||
expect(await screen.findByLabelText("Title")).toHaveValue("Hotel day (copy)");
|
||||
expect(screen.getByLabelText("Slug")).toHaveValue("hotel-copy");
|
||||
expect(screen.getByLabelText("Heading")).toHaveValue("Draft");
|
||||
expect(screen.getByLabelText("Draft")).toBeChecked();
|
||||
expect(screen.queryByRole("link", { name: "View page" })).not.toBeInTheDocument();
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mocks.savePage).toHaveBeenCalled());
|
||||
const [id, body] = mocks.savePage.mock.calls[0];
|
||||
expect(id).toBeUndefined();
|
||||
expect(body).toMatchObject({ companyId: 2, slug: "hotel-copy", title: "Hotel day (copy)", status: "DRAFT", hideHeader: true });
|
||||
expect(body.blocks).toEqual([{ type: "CTA", heading: "Draft", buttonLabel: "Go", buttonUrl: "/x" }]);
|
||||
});
|
||||
});
|
||||
@@ -1,19 +1,46 @@
|
||||
"use client";
|
||||
|
||||
import { Suspense } from "react";
|
||||
import Link from "next/link";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { PageEditor } from "@/app/components/pages/PageEditor";
|
||||
import { PAGE_TEMPLATES } from "@/app/lib/pageTemplates";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
// New page: staff first pick Blank or a starter template; ?from=<id> (Duplicate) opens a copy of that page.
|
||||
const CHOICES = [{ id: "BLANK", label: "PagesStartBlank", description: "PagesStartBlankHint" }, ...PAGE_TEMPLATES];
|
||||
|
||||
function NewPageContent() {
|
||||
const t = useT();
|
||||
const params = useSearchParams();
|
||||
const from = params?.get("from");
|
||||
const fromId = from && /^\d+$/.test(from) ? Number(from) : undefined;
|
||||
const choice = params?.get("template");
|
||||
const template = PAGE_TEMPLATES.find((tpl) => tpl.id === choice);
|
||||
const picked = fromId != null || choice === "BLANK" || template != null;
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("PagesNew")} />
|
||||
<Suspense>
|
||||
<PageEditor />
|
||||
</Suspense>
|
||||
{picked ? (
|
||||
<PageEditor key={`${from}-${choice}`} fromId={fromId} initialBlocks={template?.blocks()} />
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">{t("PagesChooseStart")}</p>
|
||||
<ul className="grid gap-3 sm:grid-cols-3">
|
||||
{CHOICES.map((c) => (
|
||||
<li key={c.id}>
|
||||
<Link href={`/pages/new?template=${c.id}`}
|
||||
className="block h-full rounded-lg border bg-card p-4 hover:border-primary focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">
|
||||
<span className="block font-medium">{t(c.label)}</span>
|
||||
<span className="mt-1 block text-sm text-muted-foreground">{t(c.description)}</span>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -21,7 +48,9 @@ function NewPageContent() {
|
||||
export default function NewLandingPage() {
|
||||
return (
|
||||
<RequireModule pathname="/pages">
|
||||
<NewPageContent />
|
||||
<Suspense>
|
||||
<NewPageContent />
|
||||
</Suspense>
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -47,6 +47,24 @@ describe("PagesPage", () => {
|
||||
expect(screen.getByRole("link", { name: /new page/i })).toHaveAttribute("href", "/pages/new");
|
||||
});
|
||||
|
||||
it("marks a published page with unpublished changes", async () => {
|
||||
mocks.listPages.mockResolvedValue({
|
||||
items: [{ id: 5, companyId: 2, slug: "hotel-tech", title: "Hotel tech", status: "PUBLISHED", metaDescription: null, blocks: [], hasDraft: true }],
|
||||
total: 1,
|
||||
});
|
||||
render(<PagesPage />);
|
||||
expect(await screen.findByText("Unpublished changes")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("offers Duplicate on each row", async () => {
|
||||
mocks.listPages.mockResolvedValue({
|
||||
items: [{ id: 5, companyId: 2, slug: "hotel-tech", title: "Hotel tech", status: "PUBLISHED", metaDescription: null, blocks: [] }],
|
||||
total: 1,
|
||||
});
|
||||
render(<PagesPage />);
|
||||
expect(await screen.findByRole("link", { name: "Duplicate Hotel tech" })).toHaveAttribute("href", "/pages/new?from=5");
|
||||
});
|
||||
|
||||
it("searches by title", async () => {
|
||||
mocks.listPages.mockResolvedValue({ items: [], total: 0 });
|
||||
const user = userEvent.setup();
|
||||
|
||||
@@ -70,9 +70,12 @@ function PagesPageContent() {
|
||||
accessorKey: "status",
|
||||
header: t("Status"),
|
||||
cell: ({ row }) => (
|
||||
<Badge variant={row.original.status === "PUBLISHED" ? "positive" : "neutral"}>
|
||||
{t(row.original.status === "PUBLISHED" ? "PagesPublished" : "PagesDraft")}
|
||||
</Badge>
|
||||
<span className="flex flex-wrap gap-1">
|
||||
<Badge variant={row.original.status === "PUBLISHED" ? "positive" : "neutral"}>
|
||||
{t(row.original.status === "PUBLISHED" ? "PagesPublished" : "PagesDraft")}
|
||||
</Badge>
|
||||
{row.original.hasDraft ? <Badge variant="warning">{t("PagesHasDraft")}</Badge> : null}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -80,6 +83,16 @@ function PagesPageContent() {
|
||||
header: t("PagesUpdated"),
|
||||
cell: ({ row }) => <span className="tabular">{row.original.updatedAt ? formatEmailDate(row.original.updatedAt) : ""}</span>,
|
||||
},
|
||||
{
|
||||
id: "actions",
|
||||
header: () => <span className="sr-only">{t("CatActions")}</span>,
|
||||
cell: ({ row }) => (
|
||||
<Link href={`/pages/new?from=${row.original.id}`} aria-label={t("PagesDuplicateNamed", { title: row.original.title })}
|
||||
className="text-sm text-primary underline-offset-4 hover:underline focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">
|
||||
{t("PagesDuplicate")}
|
||||
</Link>
|
||||
),
|
||||
},
|
||||
], [t, showCompanyColumn, codeOf, companyCode]);
|
||||
|
||||
return (
|
||||
|
||||
+2
@@ -79,6 +79,8 @@ public class RestApiCounterServiceConstants {
|
||||
public static final String API_REST_COUNTER_CMS_PAGE_FIND_BY_ID = "/counter/cmsPage/findById/{id}";
|
||||
public static final String API_REST_COUNTER_CMS_PAGE_SEARCH = "/counter/cmsPage/search";
|
||||
public static final String API_REST_COUNTER_CMS_PAGE_DELETE = "/counter/cmsPage/delete";
|
||||
public static final String API_REST_COUNTER_CMS_PAGE_PUBLISH = "/counter/cmsPage/publish";
|
||||
public static final String API_REST_COUNTER_CMS_PAGE_DISCARD = "/counter/cmsPage/discard";
|
||||
public static final String API_REST_COUNTER_CMS_PAGE_FIND_PUBLISHED = "/counter/cmsPage/findPublished/{companyId}/{slug}";
|
||||
public static final String API_REST_COUNTER_PAGE_IMAGE_UPLOAD = "/counter/pageImage/upload";
|
||||
public static final String API_REST_COUNTER_PAGE_IMAGE = "/counter/pageImage/{id}";
|
||||
|
||||
+14
@@ -58,6 +58,20 @@ public class AdminPageController {
|
||||
return ResponseEntity.ok(pages.update(id, request));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_PAGES")
|
||||
@PostMapping("/pages/{id}/publish")
|
||||
public ResponseEntity<Map<String, Object>> publish(@PathVariable long id) {
|
||||
return ResponseEntity.ok(pages.publish(id));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_PAGES")
|
||||
@PostMapping("/pages/{id}/discard")
|
||||
public ResponseEntity<Map<String, Object>> discard(@PathVariable long id) {
|
||||
return ResponseEntity.ok(pages.discard(id));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule("BO_PAGES")
|
||||
@DeleteMapping("/pages/{id}")
|
||||
|
||||
@@ -75,6 +75,21 @@ public class AdminPageService {
|
||||
rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_CMS_PAGE_DELETE), Void.class, id);
|
||||
}
|
||||
|
||||
/** Makes a published page's draft live; the counter checks the draft again. */
|
||||
public Map<String, Object> publish(long id) {
|
||||
User caller = caller();
|
||||
load(caller, id);
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("id", id);
|
||||
body.put("user", caller.getUsername());
|
||||
return relay(() -> rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_CMS_PAGE_PUBLISH), MAP, body).getBody());
|
||||
}
|
||||
|
||||
public Map<String, Object> discard(long id) {
|
||||
load(caller(), id);
|
||||
return relay(() -> rest.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_CMS_PAGE_DISCARD), MAP, id).getBody());
|
||||
}
|
||||
|
||||
/** base64 bytes; the counter checks type and size. */
|
||||
public Map<String, Object> uploadImage(Long companyId, String data) {
|
||||
User caller = caller();
|
||||
|
||||
+39
@@ -41,6 +41,8 @@ class AdminPageServiceTest {
|
||||
private static final String SEARCH = "/counter/cmsPage/search";
|
||||
private static final String DELETE = "/counter/cmsPage/delete";
|
||||
private static final String UPLOAD = "/counter/pageImage/upload";
|
||||
private static final String PUBLISH = "/counter/cmsPage/publish";
|
||||
private static final String DISCARD = "/counter/cmsPage/discard";
|
||||
|
||||
private RestTemplateCustomUtil rest;
|
||||
private AdminAuthenticationService auth;
|
||||
@@ -173,4 +175,41 @@ class AdminPageServiceTest {
|
||||
assertThatThrownBy(() -> service.create(request(null))).isInstanceOf(CodedResponseStatusException.class);
|
||||
verify(rest, never()).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishAndDiscardAreScopedAndSentForTheStoredPage() {
|
||||
caller(2L, false);
|
||||
when(rest.postForEntity(eq(PUBLISH), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of("id", 5)));
|
||||
when(rest.postForEntity(eq(DISCARD), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of("id", 5)));
|
||||
assertThat(service.publish(5L)).containsEntry("id", 5);
|
||||
assertThat(service.discard(5L)).containsEntry("id", 5);
|
||||
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
|
||||
verify(rest).postForEntity(eq(PUBLISH), any(ParameterizedTypeReference.class), body.capture());
|
||||
assertThat((Map<String, Object>) body.getValue()).containsEntry("id", 5L).containsEntry("user", "boss");
|
||||
verify(rest).postForEntity(eq(DISCARD), any(ParameterizedTypeReference.class), eq(5L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void staffCannotPublishOrDiscardAnotherCompanysPage() {
|
||||
caller(3L, false);
|
||||
for (Runnable r : List.<Runnable>of(() -> service.publish(5L), () -> service.discard(5L))) {
|
||||
assertThatThrownBy(r::run).isInstanceOfSatisfying(CodedResponseStatusException.class,
|
||||
e -> assertThat(e.getCode()).isEqualTo("PAGE_NOT_FOUND"));
|
||||
}
|
||||
verify(rest, never()).postForEntity(eq(PUBLISH), any(ParameterizedTypeReference.class), any());
|
||||
verify(rest, never()).postForEntity(eq(DISCARD), any(ParameterizedTypeReference.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPublishRefusalBecomesCodeAndField() {
|
||||
caller(2L, false);
|
||||
byte[] problem = "{\"status\":409,\"detail\":\"slug|PagesSlugTaken\"}".getBytes(StandardCharsets.UTF_8);
|
||||
when(rest.postForEntity(eq(PUBLISH), any(ParameterizedTypeReference.class), any())).thenThrow(
|
||||
HttpClientErrorException.create(HttpStatus.CONFLICT, "x", HttpHeaders.EMPTY, problem, StandardCharsets.UTF_8));
|
||||
assertThatThrownBy(() -> service.publish(5L)).isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT);
|
||||
assertThat(e.getCode()).isEqualTo("PagesSlugTaken");
|
||||
assertThat(e.getBody().getProperties()).containsEntry("details", Map.of("field", "slug"));
|
||||
});
|
||||
}
|
||||
}
|
||||
+10
@@ -30,6 +30,16 @@ public class CmsPageController {
|
||||
return pages.save(req.page(), req.user());
|
||||
}
|
||||
|
||||
@PostMapping("/cmsPage/publish")
|
||||
public CmsPageDto publish(@RequestBody CmsPageRequests.Publish req) {
|
||||
return pages.publish(req.id(), req.user());
|
||||
}
|
||||
|
||||
@PostMapping("/cmsPage/discard")
|
||||
public CmsPageDto discard(@RequestBody Long id) {
|
||||
return pages.discard(id);
|
||||
}
|
||||
|
||||
@GetMapping("/cmsPage/findById/{id}")
|
||||
public CmsPageDto findById(@PathVariable("id") long id) {
|
||||
return pages.findById(id);
|
||||
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package com.solvway.services.counter.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** Unpublished changes of a published page; visitors keep seeing the live columns until Publish. */
|
||||
public record CmsPageDraft(String slug, String title, String metaDescription, boolean hideHeader, List<CmsBlock> blocks) {}
|
||||
+10
-2
@@ -3,9 +3,17 @@ package com.solvway.services.counter.dto;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/** A landing page as the API sends and receives it; blocks are omitted (null) in list rows. */
|
||||
/**
|
||||
* A landing page as the API sends and receives it; blocks are omitted (null) in list rows.
|
||||
* draft is the unpublished change set of a published page (admin reads only); hasDraft flags it in list rows.
|
||||
*/
|
||||
public record CmsPageDto(Long id, Long companyId, String slug, String title, String metaDescription, String status,
|
||||
boolean hideHeader, List<CmsBlock> blocks, LocalDateTime updatedAt) {
|
||||
boolean hideHeader, List<CmsBlock> blocks, LocalDateTime updatedAt, CmsPageDraft draft, boolean hasDraft) {
|
||||
|
||||
public CmsPageDto(Long id, Long companyId, String slug, String title, String metaDescription, String status,
|
||||
boolean hideHeader, List<CmsBlock> blocks, LocalDateTime updatedAt) {
|
||||
this(id, companyId, slug, title, metaDescription, status, hideHeader, blocks, updatedAt, null, false);
|
||||
}
|
||||
|
||||
/** A page that shows its header (the default). */
|
||||
public CmsPageDto(Long id, Long companyId, String slug, String title, String metaDescription, String status,
|
||||
|
||||
+2
@@ -7,6 +7,8 @@ public final class CmsPageRequests {
|
||||
|
||||
public record Save(CmsPageDto page, String user) {}
|
||||
|
||||
public record Publish(long id, String user) {}
|
||||
|
||||
/** companyId null searches every company (super admin). */
|
||||
public record Search(Long companyId, String searchKey, int page, int size) {}
|
||||
|
||||
|
||||
@@ -23,6 +23,10 @@ public class CmsPage {
|
||||
/** JSON array of blocks, replaced as a whole on every save. */
|
||||
@Column(columnDefinition = "json")
|
||||
private String blocks;
|
||||
|
||||
/** JSON CmsPageDraft: unpublished changes of a published page, null when there are none. */
|
||||
@Column(columnDefinition = "json")
|
||||
private String draft;
|
||||
private String createdBy;
|
||||
private LocalDateTime createdAt = LocalDateTime.now();
|
||||
private String updatedBy;
|
||||
|
||||
+80
-27
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.solvway.services.counter.dto.CmsBlock;
|
||||
import com.solvway.services.counter.dto.CmsPageDraft;
|
||||
import com.solvway.services.counter.dto.CmsPageDto;
|
||||
import com.solvway.services.counter.model.CmsPage;
|
||||
import com.solvway.services.counter.repo.CmsPageRepository;
|
||||
@@ -46,43 +47,84 @@ public class CmsPageService {
|
||||
row.setCompanyId(dto.companyId());
|
||||
row.setCreatedBy(user);
|
||||
} else {
|
||||
row = pages.findById(dto.id()).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "PagesNotFound"));
|
||||
row = load(dto.id());
|
||||
}
|
||||
long companyId = row.getCompanyId();
|
||||
String slug = dto.slug() == null ? "" : dto.slug();
|
||||
if (slug.length() > 80 || !SLUG.matcher(slug).matches()) {
|
||||
throw CmsBlockValidator.refuse("slug", "PagesBadSlug");
|
||||
}
|
||||
CmsBlockValidator.required(dto.title(), "title");
|
||||
CmsBlockValidator.max(dto.title(), "title", 120);
|
||||
CmsBlockValidator.max(dto.metaDescription(), "metaDescription", 160);
|
||||
if (!"DRAFT".equals(dto.status()) && !"PUBLISHED".equals(dto.status())) {
|
||||
throw CmsBlockValidator.refuse("status", "PagesBadStatus");
|
||||
}
|
||||
CmsBlockValidator.validate(dto.blocks(),
|
||||
id -> images.findCompanyIdById(id).map(c -> c == companyId).orElse(false),
|
||||
CmsPageDraft content = check(row, new CmsPageDraft(dto.slug(), dto.title(), dto.metaDescription(), dto.hideHeader(), dto.blocks()));
|
||||
if ("PUBLISHED".equals(row.getStatus()) && "PUBLISHED".equals(dto.status())) {
|
||||
// Visitors keep the live page; the edit waits for Publish.
|
||||
row.setDraft(writeJson(content));
|
||||
} else {
|
||||
goLive(row, content);
|
||||
row.setStatus(dto.status());
|
||||
}
|
||||
return store(row, user);
|
||||
}
|
||||
|
||||
/** Makes the draft live after checking it again (an event or image may have gone, or the slug been taken). */
|
||||
public CmsPageDto publish(long id, String user) {
|
||||
CmsPage row = load(id);
|
||||
if (row.getDraft() == null) {
|
||||
return toDto(row, true, true);
|
||||
}
|
||||
goLive(row, check(row, readDraft(row.getDraft())));
|
||||
return store(row, user);
|
||||
}
|
||||
|
||||
public CmsPageDto discard(long id) {
|
||||
CmsPage row = load(id);
|
||||
row.setDraft(null);
|
||||
return toDto(pages.saveAndFlush(row), true, true);
|
||||
}
|
||||
|
||||
/** Validates page content against the page's company and returns it trimmed. */
|
||||
private CmsPageDraft check(CmsPage row, CmsPageDraft c) {
|
||||
long companyId = row.getCompanyId();
|
||||
String slug = c.slug() == null ? "" : c.slug();
|
||||
if (slug.length() > 80 || !SLUG.matcher(slug).matches()) {
|
||||
throw CmsBlockValidator.refuse("slug", "PagesBadSlug");
|
||||
}
|
||||
CmsBlockValidator.required(c.title(), "title");
|
||||
CmsBlockValidator.max(c.title(), "title", 120);
|
||||
CmsBlockValidator.max(c.metaDescription(), "metaDescription", 160);
|
||||
CmsBlockValidator.validate(c.blocks(),
|
||||
id -> images.findCompanyIdById(id).map(co -> co == companyId).orElse(false),
|
||||
uuid -> events.findByUuid(uuid).map(e -> e.getCompanyId() != null && e.getCompanyId() == companyId).orElse(false));
|
||||
if (pages.existsByCompanyIdAndSlugAndIdNot(companyId, slug, dto.id() == null ? -1L : dto.id())) {
|
||||
if (pages.existsByCompanyIdAndSlugAndIdNot(companyId, slug, row.getId() == null ? -1L : row.getId())) {
|
||||
throw slugTaken();
|
||||
}
|
||||
row.setSlug(slug);
|
||||
row.setTitle(dto.title().trim());
|
||||
row.setMetaDescription(dto.metaDescription() == null || dto.metaDescription().isBlank() ? null : dto.metaDescription().trim());
|
||||
row.setStatus(dto.status());
|
||||
row.setHideHeader(dto.hideHeader());
|
||||
row.setBlocks(write(dto.blocks() == null ? List.of() : dto.blocks()));
|
||||
return new CmsPageDraft(slug, c.title().trim(),
|
||||
c.metaDescription() == null || c.metaDescription().isBlank() ? null : c.metaDescription().trim(),
|
||||
c.hideHeader(), c.blocks() == null ? List.of() : c.blocks());
|
||||
}
|
||||
|
||||
private void goLive(CmsPage row, CmsPageDraft c) {
|
||||
row.setSlug(c.slug());
|
||||
row.setTitle(c.title());
|
||||
row.setMetaDescription(c.metaDescription());
|
||||
row.setHideHeader(c.hideHeader());
|
||||
row.setBlocks(writeJson(c.blocks()));
|
||||
row.setDraft(null);
|
||||
}
|
||||
|
||||
private CmsPageDto store(CmsPage row, String user) {
|
||||
row.setUpdatedBy(user);
|
||||
row.setUpdatedAt(LocalDateTime.now());
|
||||
try {
|
||||
return toDto(pages.saveAndFlush(row), true);
|
||||
return toDto(pages.saveAndFlush(row), true, true);
|
||||
} catch (DataIntegrityViolationException e) {
|
||||
throw slugTaken();
|
||||
}
|
||||
}
|
||||
|
||||
private CmsPage load(long id) {
|
||||
return pages.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "PagesNotFound"));
|
||||
}
|
||||
|
||||
public CmsPageDto findById(long id) {
|
||||
return pages.findById(id).map(p -> toDto(p, true))
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "PagesNotFound"));
|
||||
return toDto(load(id), true, true);
|
||||
}
|
||||
|
||||
/** Newest update first; rows carry no blocks. */
|
||||
@@ -90,7 +132,7 @@ public class CmsPageService {
|
||||
String key = searchKey == null || searchKey.isBlank() ? null : "%" + searchKey.trim().toLowerCase(Locale.ROOT) + "%";
|
||||
PageRequest request = PageRequest.of(Math.max(page, 0), size >= 1 ? Math.min(size, 100) : 20,
|
||||
Sort.by(Sort.Order.desc("updatedAt"), Sort.Order.desc("id")));
|
||||
return pages.search(companyId, key, request).map(p -> toDto(p, false));
|
||||
return pages.search(companyId, key, request).map(p -> toDto(p, false, true));
|
||||
}
|
||||
|
||||
public void delete(long id) {
|
||||
@@ -101,21 +143,32 @@ public class CmsPageService {
|
||||
public Optional<CmsPageDto> findPublished(long companyId, String slug) {
|
||||
return pages.findByCompanyIdAndSlug(companyId, slug.toLowerCase(Locale.ROOT))
|
||||
.filter(p -> "PUBLISHED".equals(p.getStatus()))
|
||||
.map(p -> toDto(p, true));
|
||||
.map(p -> toDto(p, true, false));
|
||||
}
|
||||
|
||||
private static ResponseStatusException slugTaken() {
|
||||
return new ResponseStatusException(HttpStatus.CONFLICT, "slug|PagesSlugTaken");
|
||||
}
|
||||
|
||||
private CmsPageDto toDto(CmsPage p, boolean withBlocks) {
|
||||
/** admin: the caller may see the draft (full read) or whether one exists (list row); visitors see neither. */
|
||||
private CmsPageDto toDto(CmsPage p, boolean withBlocks, boolean admin) {
|
||||
boolean hasDraft = admin && p.getDraft() != null;
|
||||
return new CmsPageDto(p.getId(), p.getCompanyId(), p.getSlug(), p.getTitle(), p.getMetaDescription(), p.getStatus(),
|
||||
p.isHideHeader(), withBlocks ? read(p.getBlocks()) : null, p.getUpdatedAt());
|
||||
p.isHideHeader(), withBlocks ? read(p.getBlocks()) : null, p.getUpdatedAt(),
|
||||
hasDraft && withBlocks ? readDraft(p.getDraft()) : null, hasDraft);
|
||||
}
|
||||
|
||||
private String write(List<CmsBlock> blocks) {
|
||||
private CmsPageDraft readDraft(String draft) {
|
||||
try {
|
||||
return json.writeValueAsString(blocks);
|
||||
return json.readValue(draft, CmsPageDraft.class);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException("Unreadable page draft", e);
|
||||
}
|
||||
}
|
||||
|
||||
private String writeJson(Object value) {
|
||||
try {
|
||||
return json.writeValueAsString(value);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
package com.solvway.services.counter.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.solvway.services.counter.dto.CmsBlock;
|
||||
import com.solvway.services.counter.dto.CmsPageDto;
|
||||
import com.solvway.services.counter.model.CmsPage;
|
||||
import com.solvway.services.counter.repo.CmsPageRepository;
|
||||
import com.solvway.services.counter.repo.EventRepository;
|
||||
import com.solvway.services.counter.repo.PageImageRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** add-page-drafts-and-templates: a published page's edits stay a draft until Publish; Discard drops them. */
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class CmsPageDraftTest {
|
||||
|
||||
private static final long INS = 1L;
|
||||
|
||||
@Mock private CmsPageRepository pages;
|
||||
@Mock private PageImageRepository images;
|
||||
@Mock private EventRepository events;
|
||||
|
||||
private CmsPageService service;
|
||||
private CmsPage stored;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new CmsPageService(pages, images, events, new ObjectMapper());
|
||||
lenient().when(pages.saveAndFlush(any())).thenAnswer(i -> i.getArgument(0));
|
||||
stored = new CmsPage();
|
||||
stored.setId(12L);
|
||||
stored.setCompanyId(INS);
|
||||
stored.setSlug("hotel");
|
||||
stored.setTitle("Hotel day");
|
||||
stored.setStatus("PUBLISHED");
|
||||
stored.setBlocks("[{\"type\":\"CTA\",\"heading\":\"Hotel day\",\"buttonLabel\":\"Go\",\"buttonUrl\":\"#signup\"}]");
|
||||
lenient().when(pages.findById(12L)).thenReturn(Optional.of(stored));
|
||||
}
|
||||
|
||||
private static CmsBlock cta(String heading) {
|
||||
CmsBlock b = new CmsBlock();
|
||||
b.setType("CTA");
|
||||
b.setHeading(heading);
|
||||
b.setButtonLabel("Go");
|
||||
b.setButtonUrl("#signup");
|
||||
return b;
|
||||
}
|
||||
|
||||
private static CmsPageDto edit(String status, String slug, String heading) {
|
||||
return new CmsPageDto(12L, INS, slug, "Hotel week", "New description", status, true, List.of(cta(heading)), null);
|
||||
}
|
||||
|
||||
private CmsPage saved() {
|
||||
ArgumentCaptor<CmsPage> row = ArgumentCaptor.forClass(CmsPage.class);
|
||||
verify(pages).saveAndFlush(row.capture());
|
||||
return row.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void savingAPublishedPageStoresADraftAndLeavesWhatVisitorsSee() {
|
||||
CmsPageDto dto = service.save(edit("PUBLISHED", "hotel-week", "Hotel week"), "staff1");
|
||||
|
||||
CmsPage row = saved();
|
||||
assertThat(row.getTitle()).isEqualTo("Hotel day");
|
||||
assertThat(row.getSlug()).isEqualTo("hotel");
|
||||
assertThat(row.getBlocks()).contains("Hotel day").doesNotContain("Hotel week");
|
||||
assertThat(row.getDraft()).contains("Hotel week").contains("hotel-week").contains("New description");
|
||||
assertThat(row.getUpdatedBy()).isEqualTo("staff1");
|
||||
assertThat(dto.title()).isEqualTo("Hotel day");
|
||||
assertThat(dto.draft().title()).isEqualTo("Hotel week");
|
||||
assertThat(dto.draft().slug()).isEqualTo("hotel-week");
|
||||
assertThat(dto.draft().hideHeader()).isTrue();
|
||||
assertThat(dto.draft().blocks()).extracting(CmsBlock::getHeading).containsExactly("Hotel week");
|
||||
assertThat(dto.hasDraft()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDraftIsCheckedLikeAnySave() {
|
||||
CmsBlock bad = cta("x");
|
||||
bad.setButtonUrl("javascript:alert(1)");
|
||||
assertThatThrownBy(() -> service.save(new CmsPageDto(12L, INS, "hotel", "T", null, "PUBLISHED", false, List.of(bad), null), "staff1"))
|
||||
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getReason()).isEqualTo("blocks[0].buttonUrl|PagesBadLink"));
|
||||
when(pages.existsByCompanyIdAndSlugAndIdNot(INS, "launch", 12L)).thenReturn(true);
|
||||
assertThatThrownBy(() -> service.save(edit("PUBLISHED", "launch", "x"), "staff1"))
|
||||
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getReason()).isEqualTo("slug|PagesSlugTaken"));
|
||||
verify(pages, never()).saveAndFlush(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unpublishingWritesThePageAndDropsTheDraft() {
|
||||
stored.setDraft("{\"slug\":\"x\",\"title\":\"Old draft\",\"hideHeader\":false,\"blocks\":[]}");
|
||||
service.save(edit("DRAFT", "hotel", "Hotel week"), "staff1");
|
||||
CmsPage row = saved();
|
||||
assertThat(row.getStatus()).isEqualTo("DRAFT");
|
||||
assertThat(row.getTitle()).isEqualTo("Hotel week");
|
||||
assertThat(row.getDraft()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPageNeverPublishedSavesDirectly() {
|
||||
stored.setStatus("DRAFT");
|
||||
service.save(edit("DRAFT", "hotel", "Hotel week"), "staff1");
|
||||
CmsPage row = saved();
|
||||
assertThat(row.getTitle()).isEqualTo("Hotel week");
|
||||
assertThat(row.getDraft()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishMakesTheDraftLiveAfterCheckingItAgain() {
|
||||
service.save(edit("PUBLISHED", "hotel-week", "Hotel week"), "staff1");
|
||||
CmsPageDto live = service.publish(12L, "staff2");
|
||||
ArgumentCaptor<CmsPage> rows = ArgumentCaptor.forClass(CmsPage.class);
|
||||
verify(pages, org.mockito.Mockito.times(2)).saveAndFlush(rows.capture());
|
||||
CmsPage row = rows.getAllValues().get(1);
|
||||
assertThat(row.getTitle()).isEqualTo("Hotel week");
|
||||
assertThat(row.getSlug()).isEqualTo("hotel-week");
|
||||
assertThat(row.getMetaDescription()).isEqualTo("New description");
|
||||
assertThat(row.isHideHeader()).isTrue();
|
||||
assertThat(row.getBlocks()).contains("Hotel week");
|
||||
assertThat(row.getDraft()).isNull();
|
||||
assertThat(row.getStatus()).isEqualTo("PUBLISHED");
|
||||
assertThat(row.getUpdatedBy()).isEqualTo("staff2");
|
||||
assertThat(live.hasDraft()).isFalse();
|
||||
assertThat(live.draft()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishRefusesADraftThatNoLongerPassesAndChangesNothing() {
|
||||
stored.setDraft("{\"slug\":\"launch\",\"title\":\"T\",\"hideHeader\":false,\"blocks\":[]}");
|
||||
when(pages.existsByCompanyIdAndSlugAndIdNot(INS, "launch", 12L)).thenReturn(true);
|
||||
assertThatThrownBy(() -> service.publish(12L, "staff1"))
|
||||
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getReason()).isEqualTo("slug|PagesSlugTaken"));
|
||||
stored.setDraft("{\"slug\":\"hotel\",\"title\":\"T\",\"hideHeader\":false,\"blocks\":[{\"type\":\"FORM\",\"eventUuid\":\"55\"}]}");
|
||||
assertThatThrownBy(() -> service.publish(12L, "staff1"))
|
||||
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getReason()).isEqualTo("blocks[0].eventUuid|PagesBadEvent"));
|
||||
verify(pages, never()).saveAndFlush(any());
|
||||
assertThat(stored.getTitle()).isEqualTo("Hotel day");
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishWithoutADraftChangesNothing() {
|
||||
CmsPageDto dto = service.publish(12L, "staff1");
|
||||
assertThat(dto.title()).isEqualTo("Hotel day");
|
||||
verify(pages, never()).saveAndFlush(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void discardDropsTheDraft() {
|
||||
stored.setDraft("{\"slug\":\"hotel\",\"title\":\"T\",\"hideHeader\":false,\"blocks\":[]}");
|
||||
CmsPageDto dto = service.discard(12L);
|
||||
assertThat(saved().getDraft()).isNull();
|
||||
assertThat(dto.title()).isEqualTo("Hotel day");
|
||||
assertThat(dto.hasDraft()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void listRowsSayWhetherAPageHasADraftAndVisitorsNeverSeeIt() {
|
||||
stored.setDraft("{\"slug\":\"hotel\",\"title\":\"Secret\",\"hideHeader\":false,\"blocks\":[]}");
|
||||
when(pages.search(eq(INS), any(), any())).thenReturn(new PageImpl<>(List.of(stored)));
|
||||
CmsPageDto row = service.search(INS, null, 0, 20).getContent().get(0);
|
||||
assertThat(row.hasDraft()).isTrue();
|
||||
assertThat(row.draft()).isNull();
|
||||
when(pages.findByCompanyIdAndSlug(INS, "hotel")).thenReturn(Optional.of(stored));
|
||||
CmsPageDto visitor = service.findPublished(INS, "hotel").orElseThrow();
|
||||
assertThat(visitor.title()).isEqualTo("Hotel day");
|
||||
assertThat(visitor.draft()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishAndDiscardOfAMissingPageAreNotFound() {
|
||||
when(pages.findById(anyLong())).thenReturn(Optional.empty());
|
||||
assertThatThrownBy(() -> service.publish(99L, "staff1")).isInstanceOf(ResponseStatusException.class).hasMessageContaining("404");
|
||||
assertThatThrownBy(() -> service.discard(99L)).isInstanceOf(ResponseStatusException.class).hasMessageContaining("404");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user