Compare commits
28
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b7d771e2f4 | ||
|
|
51ef5b9611 | ||
|
|
a99b18fbfd | ||
|
|
a1d13fe8d7 | ||
|
|
72394df1d7 | ||
|
|
56fb94ab81 | ||
|
|
909c1754c0 | ||
|
|
e3f08bc6cf | ||
|
|
66e2e488d9 | ||
|
|
d5384c6ac0 | ||
|
|
26b285cc0a | ||
|
|
d195b6f91b | ||
|
|
dd6cbfe71c | ||
|
|
4251d395ad | ||
|
|
36dbb4c949 | ||
|
|
f13b2a592a | ||
|
|
cfc817082d | ||
|
|
6a0a6613c1 | ||
|
|
1ceefd7231 | ||
|
|
9a7b225827 | ||
|
|
dcad8cb650 | ||
|
|
34732ef2a5 | ||
|
|
53f3298ded | ||
|
|
1e09b652dc | ||
|
|
26b39283e6 | ||
|
|
4d291c6150 | ||
|
|
2c6a4dc8ce | ||
|
|
e70e1084d9 |
No files matched your search
+21
-11
@@ -129,32 +129,38 @@ Run both, in order, before the new images go live: the new services-counter read
|
||||
|
||||
| File | What it does |
|
||||
|---|---|
|
||||
| `openspec/changes/archive/<date>-add-whatsapp-inbox/sql/01-whatsapp-schema.sql` | Creates the schema `service-whatsapp` with the conversation, message, read-marker and template tables. DDL: run it with a user that may create databases and tables. |
|
||||
| `openspec/changes/archive/<date>-add-whatsapp-inbox/sql/02-whatsapp-modules.sql` | Adds the WhatsApp modules `BO_WHATSAPP` (the inbox) and `BO_WHATSAPP_ADMIN` (every chat of the company, assigning owners, template sync). No role gets them; super admins grant them under Roles. |
|
||||
| `openspec/changes/archive/2026-12-02-add-whatsapp-inbox/sql/01-whatsapp-schema.sql` | Creates the schema `service-whatsapp` with the conversation, message, read-marker and template tables. DDL: run it with a user that may create databases and tables. |
|
||||
| `openspec/changes/archive/2026-12-02-add-whatsapp-inbox/sql/02-whatsapp-modules.sql` | Adds the WhatsApp modules `BO_WHATSAPP` (the inbox) and `BO_WHATSAPP_ADMIN` (every chat of the company, assigning owners, template sync). No role gets them; super admins grant them under Roles. |
|
||||
|
||||
Run both before `service-whatsapp` starts. Give the services' database user the same rights on `service-whatsapp` as on the other schemas. `99-rollback.sql` in the same folder removes the modules and drops the schema with every stored chat.
|
||||
|
||||
| File | What it does |
|
||||
|---|---|
|
||||
| `openspec/changes/archive/<date>-add-zh-cn-messages/sql/01-locales.sql` | Creates `service-system`.`supported_locale` (the languages staff can pick: English and 简体中文 on; Malay, Traditional Chinese and Indonesian off) and `catalog_meta` (the label catalog version). DDL. |
|
||||
| `openspec/changes/archive/<date>-add-zh-cn-messages/sql/02-modules.sql` | Adds the back-office modules `BO_MESSAGES` (Translations) and `BO_LOCALES` (Languages) under System. No role gets them; super admins grant them under Roles. |
|
||||
| `openspec/changes/archive/<date>-add-zh-cn-messages/sql/03-zh-cn-messages.sql` | Loads the first-pass Chinese for every back-office label into `service-system`.`message`: inserts the labels that are missing, sets their Chinese, gives four rows (`LogIn`, `Member`, `Tree`, `Wallet`) the back office's English, and bumps the catalog version. Generated; run it once. |
|
||||
| `openspec/changes/archive/<date>-add-messages-colite-filter/sql/01-colite-filter-labels.sql` | Adds the "Co-Lite labels only" label. Run it only where the 03 file above already ran before this change; the regenerated 03 already includes it. |
|
||||
| `openspec/changes/archive/2026-12-02-add-zh-cn-messages/sql/01-locales.sql` | Creates `service-system`.`supported_locale` (the languages staff can pick: English and 简体中文 on; Malay, Traditional Chinese and Indonesian off) and `catalog_meta` (the label catalog version). DDL. |
|
||||
| `openspec/changes/archive/2026-12-02-add-zh-cn-messages/sql/02-modules.sql` | Adds the back-office modules `BO_MESSAGES` (Translations) and `BO_LOCALES` (Languages) under System. No role gets them; super admins grant them under Roles. |
|
||||
| `openspec/changes/archive/2026-12-02-add-zh-cn-messages/sql/03-zh-cn-messages.sql` | Loads the first-pass Chinese for every back-office label into `service-system`.`message`: inserts the labels that are missing, sets their Chinese, gives four rows (`LogIn`, `Member`, `Tree`, `Wallet`) the back office's English, and bumps the catalog version. Generated; run it once. |
|
||||
| `openspec/changes/archive/2026-12-02-add-messages-colite-filter/sql/01-colite-filter-labels.sql` | Adds the "Co-Lite labels only" label. Run it only where the 03 file above already ran before this change; the regenerated 03 already includes it. |
|
||||
|
||||
Run the three in order before the new services-system, gateway and mobile-api go live. `01` needs a user that may create tables. Run `03` once only: it overwrites the Chinese of every back-office label, so running it again after staff have edited translations undoes their edits. `99-rollback.sql` in the same folder drops the two tables and removes the modules; the Chinese stays in `message`, which the previous images never read.
|
||||
|
||||
| File | What it does |
|
||||
|---|---|
|
||||
| `openspec/changes/archive/<date>-add-landing-pages/sql/01-pages.sql` | Creates `service-counter`.`cms_page` (landing pages, blocks as JSON, slug unique per company) and `page_image` (uploaded images, at most 2 MB each). DDL. |
|
||||
| `openspec/changes/archive/<date>-add-landing-pages/sql/02-event-lead-web.sql` | Adds `page_path`, `utm_source`, `utm_medium` and `utm_campaign` to `event_lead`, for sign-ups from a landing page (source `WEB`). DDL. |
|
||||
| `openspec/changes/archive/<date>-add-landing-pages/sql/03-company-branding.sql` | Adds `logo_image_id` and `accent_color` to `service-system`.`company`. DDL. |
|
||||
| `openspec/changes/archive/<date>-add-landing-pages/sql/04-module.sql` | Adds the Pages back-office module (`BO_PAGES`) under Events. No role gets it; super admins grant it under Roles. |
|
||||
| `openspec/changes/archive/<date>-add-landing-pages/sql/05-page-labels.sql` | Adds the landing-page labels in English and Chinese. Run it only where `add-zh-cn-messages/sql/03` already ran before this change; the regenerated 03 already includes them. |
|
||||
| `openspec/changes/archive/2026-12-02-add-landing-pages/sql/01-pages.sql` | Creates `service-counter`.`cms_page` (landing pages, blocks as JSON, slug unique per company) and `page_image` (uploaded images, at most 2 MB each). DDL. |
|
||||
| `openspec/changes/archive/2026-12-02-add-landing-pages/sql/02-event-lead-web.sql` | Adds `page_path`, `utm_source`, `utm_medium` and `utm_campaign` to `event_lead`, for sign-ups from a landing page (source `WEB`). DDL. |
|
||||
| `openspec/changes/archive/2026-12-02-add-landing-pages/sql/03-company-branding.sql` | Adds `logo_image_id` and `accent_color` to `service-system`.`company`. DDL. |
|
||||
| `openspec/changes/archive/2026-12-02-add-landing-pages/sql/04-module.sql` | Adds the Pages back-office module (`BO_PAGES`) under Events. No role gets it; super admins grant it under Roles. |
|
||||
| `openspec/changes/archive/2026-12-02-add-landing-pages/sql/05-page-labels.sql` | Adds the landing-page labels in English and Chinese. Run it only where `add-zh-cn-messages/sql/03` already ran before this change; the regenerated 03 already includes them. |
|
||||
| `openspec/changes/add-custom-html-block/sql/01-hide-header.sql` | Adds `hide_header` to `service-counter`.`cms_page`, the "Hide page header" option. DDL. |
|
||||
| `openspec/changes/add-custom-html-block/sql/02-html-block-labels.sql` | Adds the Custom HTML block labels in English and Chinese. Same rule as `05-page-labels.sql`: only where `add-zh-cn-messages/sql/03` already ran. |
|
||||
| `openspec/changes/add-lead-notifications/sql/01-notification-columns.sql` | Turns the unused `service-system`.`notification` table into the staff bell: converts it to utf8mb4 and adds the recipient, company, type, link, collapse and read columns and two indexes. DDL. |
|
||||
| `openspec/changes/add-lead-notifications/sql/02-notification-labels.sql` | Adds the bell's labels in English and Chinese. Same rule as `05-page-labels.sql`: only where `add-zh-cn-messages/sql/03` already ran. |
|
||||
|
||||
Run them in order before the new services-counter, services-system and mobile-api go live: the new services read the new columns on every event lead and company query. `01` to `03` need a user that may alter tables. `99-rollback.sql` in the same folder removes the module and drops the two tables and the columns, which deletes every page, image, page address and campaign tag.
|
||||
|
||||
**Review the privacy notice before go-live.** The seeded text is a starting template written for the PDPA, not legal advice. INS and CV should each have theirs checked; a super admin changes it under **Companies → Privacy notice**. A company with no notice has no working QR codes.
|
||||
|
||||
**Lead notifications (`add-lead-notifications`).** Run `01` before the new services-system goes live; it reads the new columns on every inbox query. Check first that the table is empty (`SELECT COUNT(*) FROM `service-system`.`notification`` returns 0). `01` needs a user that may alter tables. `99-rollback.sql` in the same folder drops the columns, the indexes and the labels, which deletes every notification's read state.
|
||||
|
||||
**Database user:**
|
||||
- Create one user with `SELECT, INSERT, UPDATE, DELETE, EXECUTE` on the five schemas, and on `service-whatsapp` once that exists. EXECUTE is needed: service-member calls a stored function.
|
||||
- Every Java service reads the same variables (section 6): `MYSQLHOST`, `MYSQLPORT`, `MYSQLUSER`, `MYSQLPWD`.
|
||||
@@ -249,6 +255,8 @@ The keys:
|
||||
|
||||
`service-whatsapp` also reads `MYSQLHOST`, `MYSQLPORT`, `MYSQLUSER` and `MYSQLPWD`. It uses no Pub/Sub, Redis or `key.json`. mobile-api reads the secrets on each request, so a rotated secret needs no restart there; `service-whatsapp` reads them at startup.
|
||||
|
||||
**`service-counter`, optional:** `LEADS_FOLLOWUPNOTICE_CRON` overrides when the daily follow-up summary runs (Spring cron, six fields, Malaysia time). Default `0 0 8 * * *`, 08:00. Run one service-counter replica, or the summary is sent once per replica; a second send on the same day only refreshes an unread summary.
|
||||
|
||||
**`service-log`:**
|
||||
|
||||
| Variable | Kind | Value |
|
||||
@@ -309,6 +317,8 @@ QR registration pages (`/r/<code>`) are served by the admin portal on the same h
|
||||
|
||||
**Landing pages.** Published pages live at `/p/<company-code>/<slug>` on the admin portal, with their images at `/api/public/page-images/<id>` and their form at `/api/public/pages/...`. They need no new route: serve them on the public-pages hostname above, so printed and shared page links survive a later move to the customer portal.
|
||||
|
||||
**Custom HTML frames.** A Custom HTML block loads in a sealed frame from `/p/<company-code>/<slug>/frame/<n>`, and staff preview a draft one at `/pages/<id>/preview/frame/<n>`. Both are portal routes on the same hostname as the page. Their responses carry their own `Content-Security-Policy: sandbox allow-scripts allow-popups allow-popups-to-escape-sandbox; frame-ancestors 'self'`. The proxy (Traefik or any other layer) must not replace or strip that header, and must not add `X-Frame-Options: DENY` to these paths. Without the sandbox header, pasted scripts would run as the portal's own origin when the address is opened directly. After deploy, open a frame address and check the response header.
|
||||
|
||||
## 9. Secret templates
|
||||
|
||||
There is no template yet for `service-email` (its keys wait for the email provider) or `service-system` (its Jumio keys stay unset). Kubernetes Secrets hold base64 values. Encode each one with `printf '%s' 'value' | base64 -w0`. These are templates: replace every `<…>` and never commit the filled-in files.
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
# Custom HTML block for landing pages — design
|
||||
|
||||
Date: 2026-12-02. Status: draft for owner approval.
|
||||
|
||||
## Intent
|
||||
|
||||
Marketing staff want to generate page sections with an AI tool and paste the HTML into a landing page, so a page can look like a designed site rather than only the built-in blocks. The owner chose option 1 on 2026-12-02: a "Custom HTML" block shown in a sealed frame.
|
||||
|
||||
## Goals
|
||||
|
||||
- A new block type, **Custom HTML**, holding HTML pasted by staff with `BO_PAGES`.
|
||||
- The pasted HTML renders as the AI designed it: its own styles, fonts, CDN libraries and scripts.
|
||||
- The pasted HTML can never act as the visitor or as a staff member on the Co-Lite site: no access to cookies, the back-office APIs, the page around it, or top-level navigation.
|
||||
- Leads still come only from the built-in Sign-up form block, with consent, interests and UTM tags.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Forms inside the pasted HTML do not submit. A pasted "contact us" form is decoration; staff add the Sign-up form block for real leads.
|
||||
- No HTML editor, syntax highlighting or AI generation inside Co-Lite. Staff paste text.
|
||||
- No search-engine indexing of the framed content. The page title, description and the other blocks still carry the page's search text.
|
||||
|
||||
## Anti-goals
|
||||
|
||||
- Any path where pasted HTML runs with the Co-Lite origin. This includes someone opening the frame's address directly in a browser tab.
|
||||
|
||||
## Approaches
|
||||
|
||||
1. **Sealed frame (chosen).** The HTML is served from its own address with a `sandbox` Content-Security-Policy and shown in an `<iframe sandbox>`. It looks exactly as pasted, and it is isolated by the browser. Costs: weaker SEO for the framed part, and forms inside it don't work.
|
||||
2. **Sanitise into the page.** It is safe and searchable, but it strips scripts, `<style>` and most classes, so AI output usually looks broken. The owner rejected it.
|
||||
|
||||
## Design
|
||||
|
||||
### Storage and validation (services-counter)
|
||||
|
||||
- New block type `HTML` with one field, `html` (the pasted document or fragment).
|
||||
- Limit: 200,000 characters per block, refused at the field (`blocks[i].html`) when exceeded or blank.
|
||||
- The script check that RICH_TEXT uses does **not** apply to `HTML`. Scripts are expected and contained by the frame.
|
||||
- The existing limit of 30 blocks per page still applies. Pages keep storing blocks as JSON.
|
||||
|
||||
### Serving the frame (portal)
|
||||
|
||||
- **Public:** `GET /p/{company}/{slug}/frame/{block}` returns the block's HTML as `text/html; charset=utf-8`. It reads the published page through the existing public page API; anything else is 404 with an empty body.
|
||||
- **Staff preview:** `GET /pages/{id}/preview/frame/{block}` returns a draft block's HTML for a signed-in user with `BO_PAGES`, through the admin page API.
|
||||
- Both responses carry:
|
||||
- `Content-Security-Policy: sandbox allow-scripts allow-popups allow-popups-to-escape-sandbox; frame-ancestors 'self'`. The `sandbox` directive gives the document an opaque origin even when opened directly. `frame-ancestors 'self'` stops other sites from embedding it.
|
||||
- `X-Content-Type-Options: nosniff`, `Referrer-Policy: no-referrer`, and `Cache-Control: no-store` on the preview.
|
||||
- They do not carry the portal's per-page nonce policy. The middleware leaves these two routes alone.
|
||||
- **Not granted:** `allow-same-origin`, `allow-forms`, `allow-top-navigation` and `allow-modals`.
|
||||
|
||||
### Height
|
||||
|
||||
- On serve, the portal appends a small script to the HTML. The script posts the document height to the parent when the page loads and when the height changes (`{ type: "colite-frame-height", height }`).
|
||||
- The page around it sets the frame's height from messages whose `source` is that frame's window, clamped to 100–20,000 px. Before any message arrives, the frame is 600 px tall.
|
||||
|
||||
### Rendering
|
||||
|
||||
- The public page and the staff preview render the HTML block as `<iframe sandbox="allow-scripts allow-popups allow-popups-to-escape-sandbox" src="…/frame/{index}" title="{page title}" loading="lazy">`, full width, with no border.
|
||||
|
||||
### Editor
|
||||
|
||||
- An "Add Custom HTML" button and a monospace textarea with a character counter (/200,000).
|
||||
- A one-line hint that forms inside the pasted HTML don't send, and that staff should add a Sign-up form block for leads.
|
||||
- New labels in English and Chinese, shipped as SQL in the change folder.
|
||||
|
||||
### Security review points
|
||||
|
||||
- The gateway is unchanged. The frame routes are portal routes that call the existing public and admin page APIs.
|
||||
- A staff account with `BO_PAGES` can still publish misleading content on the company's page, for example a fake login form. That risk already exists with text blocks. The frame stops the content from reaching any Co-Lite session or data. Page saves are audited.
|
||||
|
||||
## Left to the builder
|
||||
|
||||
- How the middleware skips the two frame routes: the matcher or an early return. A test must prove that the frame response carries the sandbox policy and not the nonce policy.
|
||||
- Whether the height script is injected before `</body>` or appended at the end when the paste is a fragment.
|
||||
@@ -0,0 +1,90 @@
|
||||
# Lead notifications (bell) — design
|
||||
|
||||
Date: 2026-12-02. Status: draft for owner approval.
|
||||
|
||||
## Intent
|
||||
|
||||
Sales staff need to know about new work without refreshing lists: a lead assigned to them, a new sign-up from a landing page, an incoming WhatsApp message, and follow-ups due. This is feature-list item 12, needed before go-live on 2027-01-15. On 2026-12-02 the owner chose the in-app bell only (no email, no WhatsApp alerts) and approved the recommended approach and recipient rules.
|
||||
|
||||
## Goals
|
||||
|
||||
- A bell in the portal header with an unread badge, a drop-down of recent notifications and a full notifications page.
|
||||
- Each notification links straight to the lead, or to the WhatsApp chat.
|
||||
- Read state is stored on the server, so it survives a reload and follows the user to another device.
|
||||
- Four triggers:
|
||||
- lead assigned to me;
|
||||
- new landing-page sign-up;
|
||||
- incoming WhatsApp message on a chat I own;
|
||||
- follow-ups due today.
|
||||
- English and Chinese text, following the user's language.
|
||||
- Company scoping: a user only ever receives notifications about their own company's leads.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Email, WhatsApp or browser push alerts.
|
||||
- Per-user notification settings (mute a type). Add when staff ask for it.
|
||||
- Admin broadcast messages (babyboo has them; Co-Lite has no need yet).
|
||||
- Purging old notifications. Rows are small; add a purge when the table grows.
|
||||
|
||||
## Anti-goals
|
||||
|
||||
- A notification that reveals another company's lead, or a lead to someone who may not see it.
|
||||
- A noisy bell: one alert per WhatsApp message during a busy chat would train staff to ignore it.
|
||||
- A notification failure that breaks the action behind it. A sign-up, an assignment or an inbound message must succeed even when the notification cannot be written.
|
||||
|
||||
## Approaches
|
||||
|
||||
1. **Port babyboo's bell (chosen).** Each trigger writes one notification row per recipient in `service-system`.`notification`. Babyboo extended that table and built the admin inbox API and the header bell (`add-admin-internal-notifications`, 2026-10-07); the flow is proven.
|
||||
2. **Counts only.** The bell shows numbers computed from existing data (new leads, unread chats, follow-ups due). Cheaper, but no list, no link to the item, and no record of the moment a lead was assigned. Not chosen.
|
||||
|
||||
## Design
|
||||
|
||||
### Storage (service-system)
|
||||
|
||||
Extend the existing, unused `notification` table the way babyboo did, plus a company id:
|
||||
|
||||
- `recipient_type` (`A` for staff; only `A` is used now), `title`, `type`, `link`, `seen`, `read_at`, `company_id`.
|
||||
- Index `(recipient_type, receiver, seen, create_date_time)`.
|
||||
- `receiver` holds the staff user id.
|
||||
- `title` and `message` hold message codes and parameters (JSON), not text, so the bell renders in the reader's language (babyboo's `renderNotice` pattern). Parameters hold only what the bell shows: the lead's name and the event name. No phone numbers or email addresses.
|
||||
|
||||
Endpoints in service-system: create (one or many rows), list mine (newest first, paged), unread count, mark one read, mark all read. The mark-read endpoints only touch rows whose receiver is the caller.
|
||||
|
||||
### Admin API and portal
|
||||
|
||||
- mobile-api: `GET /api/admin/notifications`, `GET /api/admin/notifications/unread-count`, `POST /api/admin/notifications/{id}/read`, `POST /api/admin/notifications/read-all`. The caller is always the signed-in user; no user id is taken from the request.
|
||||
- Portal: babyboo's `NotificationsBell` in the header (polls the unread count every 30 seconds while the tab is visible) and a `/notifications` page. Opening the drop-down marks the shown items read; clicking an item opens its link.
|
||||
- Every signed-in staff user has the bell. No new module permission: a user only ever sees their own notifications.
|
||||
|
||||
### Triggers and recipients
|
||||
|
||||
| Trigger | Where | Who gets it |
|
||||
|---|---|---|
|
||||
| Lead assigned | services-counter, wherever the salesperson of an event lead changes to someone (manual assignment, assignment at capture, re-assignment) | The new salesperson. Not the person who made the change, when they assigned it to themselves. |
|
||||
| New landing-page sign-up | services-counter, registration with source `WEB` | The assigned salesperson when there is one. Otherwise everyone on the event's sales team (`event_salesperson`). Nobody when the event has no sales team. |
|
||||
| Incoming WhatsApp message | services-whatsapp, inbound message on a conversation | The chat owner. Nobody when the chat has no owner (the shared inbox already shows it). One unread notification per chat: while the owner has an unread notification for that chat, a new message updates its time instead of adding another. |
|
||||
| Follow-ups due | services-counter, a daily job at 08:00 Malaysia time | Each salesperson with event leads whose `next_follow_up_date` is today or earlier and whose status is still open. One summary notification per salesperson per day ("3 follow-ups due, 1 overdue"), linking to their event leads list. |
|
||||
|
||||
A new sign-up that is also assigned at capture sends one notification to the salesperson (the sign-up), not two.
|
||||
|
||||
### Delivery
|
||||
|
||||
- Senders call service-system's create endpoint over REST, after their transaction commits, with a 2-second timeout. A failure is logged with ids only and never fails the action. This copies `WhatsappNotifier`.
|
||||
- ponytail: no retry or queue. A lost notification is an inconvenience, not lost data: the lead, the chat and the follow-up date are all still there. Add a Pub/Sub topic if losses show up.
|
||||
- The daily job must not send twice when the service runs more than one copy, or restarts: it records the day it last ran for each company (or uses the existing scheduler lock pattern, if the codebase has one).
|
||||
|
||||
### Labels
|
||||
|
||||
New labels in English and Chinese, shipped as SQL in the change folder, the same way as earlier changes.
|
||||
|
||||
## Constraints
|
||||
|
||||
- New and changed tables carry a company id.
|
||||
- Logs never contain lead names, phone numbers or email addresses.
|
||||
- The notification store is written only through service-system; other services never write its table directly.
|
||||
|
||||
## Left to the builder
|
||||
|
||||
- The exact link targets (lead detail page, chat page, event leads list with a follow-up filter if one exists).
|
||||
- Whether the daily job lives in services-counter or service-system, as long as it runs once per day per company.
|
||||
- Page size of the notifications list and how many items the drop-down shows.
|
||||
@@ -503,3 +503,20 @@ ALTER TABLE `company`
|
||||
USE `service-system`;
|
||||
INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `icon_name`) VALUES
|
||||
(40250000, 'BO_PAGES', 'Pages', 'BO', 'M', 40000000, '/pages', 'PanelsTopLeft');
|
||||
-- add-custom-html-block: the hide-header page option
|
||||
USE `service-counter`;
|
||||
ALTER TABLE `cms_page` ADD COLUMN `hide_header` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Hide the company header and the page title on the public page' AFTER `status`;
|
||||
-- add-lead-notifications: the staff notification bell
|
||||
USE `service-system`;
|
||||
ALTER TABLE `notification`
|
||||
CONVERT TO CHARACTER SET utf8mb4,
|
||||
ADD COLUMN `recipient_type` char(1) NULL COMMENT 'A = staff user' AFTER `receiver`,
|
||||
ADD COLUMN `company_id` bigint NULL AFTER `recipient_type`,
|
||||
ADD COLUMN `title` varchar(255) NULL COMMENT 'Message code' AFTER `company_id`,
|
||||
ADD COLUMN `type` varchar(45) NULL COMMENT 'LEAD_ASSIGNED, WEB_SIGNUP, WHATSAPP_MESSAGE, FOLLOW_UP_DUE' AFTER `message`,
|
||||
ADD COLUMN `link` varchar(512) NULL COMMENT 'Portal path opened on click' AFTER `type`,
|
||||
ADD COLUMN `collapse_key` varchar(100) NULL COMMENT 'An unread row with the same receiver and key is updated, not duplicated' AFTER `link`,
|
||||
ADD COLUMN `seen` tinyint(1) NOT NULL DEFAULT 0 AFTER `collapse_key`,
|
||||
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`);
|
||||
@@ -1489,6 +1489,44 @@ INSERT INTO message (code, content, area) SELECT 'PagesBlockFaq', JSON_OBJECT('e
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '常见问题') WHERE LOWER(code) = LOWER('PagesBlockFaq') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesBlockForm', JSON_OBJECT('en_US', 'Sign-up form', 'zh_CN', '报名表'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockForm') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '报名表') WHERE LOWER(code) = LOWER('PagesBlockForm') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesBlockHtml', JSON_OBJECT('en_US', 'Custom HTML', 'zh_CN', '自定义 HTML'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockHtml') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '自定义 HTML') WHERE LOWER(code) = LOWER('PagesBlockHtml') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesHtml', JSON_OBJECT('en_US', 'HTML', 'zh_CN', 'HTML'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHtml') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', 'HTML') WHERE LOWER(code) = LOWER('PagesHtml') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesHtmlHint', JSON_OBJECT('en_US', 'Forms inside the pasted HTML don''t send. Add a Sign-up form block to collect leads.', 'zh_CN', '粘贴的 HTML 中的表单不会发送。请添加报名表单区块来收集线索。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHtmlHint') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '粘贴的 HTML 中的表单不会发送。请添加报名表单区块来收集线索。') WHERE LOWER(code) = LOWER('PagesHtmlHint') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesHideHeader', JSON_OBJECT('en_US', 'Hide page header', 'zh_CN', '隐藏页面顶栏'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHideHeader') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '隐藏页面顶栏') WHERE LOWER(code) = LOWER('PagesHideHeader') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NotificationsTitle', JSON_OBJECT('en_US', 'Notifications', 'zh_CN', '通知'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsTitle') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '通知') WHERE LOWER(code) = LOWER('NotificationsTitle') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NotificationsUnread', JSON_OBJECT('en_US', 'Notifications, {count} unread', 'zh_CN', '通知,{count} 条未读'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsUnread') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '通知,{count} 条未读') WHERE LOWER(code) = LOWER('NotificationsUnread') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NotificationsEmpty', JSON_OBJECT('en_US', 'No notifications yet.', 'zh_CN', '暂无通知。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsEmpty') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '暂无通知。') WHERE LOWER(code) = LOWER('NotificationsEmpty') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NotificationsLoadFailed', JSON_OBJECT('en_US', 'Couldn''t load notifications.', 'zh_CN', '无法加载通知。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsLoadFailed') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '无法加载通知。') WHERE LOWER(code) = LOWER('NotificationsLoadFailed') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NotificationsMarkAllRead', JSON_OBJECT('en_US', 'Mark all read', 'zh_CN', '全部标为已读'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsMarkAllRead') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '全部标为已读') WHERE LOWER(code) = LOWER('NotificationsMarkAllRead') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NotificationsSeeAll', JSON_OBJECT('en_US', 'See all', 'zh_CN', '查看全部'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsSeeAll') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '查看全部') WHERE LOWER(code) = LOWER('NotificationsSeeAll') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NotificationsUnreadBadge', JSON_OBJECT('en_US', 'Unread', 'zh_CN', '未读'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsUnreadBadge') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '未读') WHERE LOWER(code) = LOWER('NotificationsUnreadBadge') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NoticeLeadAssigned', JSON_OBJECT('en_US', 'Lead assigned to you', 'zh_CN', '有新线索分配给你'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeLeadAssigned') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '有新线索分配给你') WHERE LOWER(code) = LOWER('NoticeLeadAssigned') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NoticeWebSignup', JSON_OBJECT('en_US', 'New sign-up', 'zh_CN', '新的报名'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeWebSignup') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '新的报名') WHERE LOWER(code) = LOWER('NoticeWebSignup') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NoticeLeadBody', JSON_OBJECT('en_US', '{lead} · {event}', 'zh_CN', '{lead} · {event}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeLeadBody') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '{lead} · {event}') WHERE LOWER(code) = LOWER('NoticeLeadBody') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NoticeFollowUpDue', JSON_OBJECT('en_US', 'Follow-ups due', 'zh_CN', '待跟进'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeFollowUpDue') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '待跟进') WHERE LOWER(code) = LOWER('NoticeFollowUpDue') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NoticeFollowUpBody', JSON_OBJECT('en_US', '{due} due today, {overdue} overdue', 'zh_CN', '今天到期 {due} 条,已逾期 {overdue} 条'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeFollowUpBody') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '今天到期 {due} 条,已逾期 {overdue} 条') WHERE LOWER(code) = LOWER('NoticeFollowUpBody') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NoticeWhatsappMessage', JSON_OBJECT('en_US', 'New WhatsApp message', 'zh_CN', '新的 WhatsApp 消息'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeWhatsappMessage') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '新的 WhatsApp 消息') WHERE LOWER(code) = LOWER('NoticeWhatsappMessage') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NoticeWhatsappBody', JSON_OBJECT('en_US', 'From {name}', 'zh_CN', '来自 {name}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeWhatsappBody') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '来自 {name}') WHERE LOWER(code) = LOWER('NoticeWhatsappBody') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NoticeWhatsappBodyNoName', JSON_OBJECT('en_US', 'From a new contact', 'zh_CN', '来自新联系人'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeWhatsappBodyNoName') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '来自新联系人') WHERE LOWER(code) = LOWER('NoticeWhatsappBodyNoName') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesMoveUp', JSON_OBJECT('en_US', 'Move up', 'zh_CN', '上移'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesMoveUp') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '上移') WHERE LOWER(code) = LOWER('PagesMoveUp') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesMoveDown', JSON_OBJECT('en_US', 'Move down', 'zh_CN', '下移'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesMoveDown') AND area = 'A');
|
||||
|
||||
File renamed without changes.
@@ -0,0 +1,41 @@
|
||||
# Design
|
||||
|
||||
The full design is `docs/superpowers/specs/2026-12-02-custom-html-block-design.md` (approved 2026-12-02). This file records the technical decisions.
|
||||
|
||||
## Context
|
||||
|
||||
- Pages store their blocks as JSON in `cms_page.blocks`. `CmsBlockValidator` in services-counter checks the blocks, and mobile-api passes them to the portal unchanged.
|
||||
- The portal's `middleware.ts` gives every page and API response a per-request nonce Content-Security-Policy. An `srcdoc` frame would inherit that policy and block the pasted scripts, inline styles and CDN links. So the pasted HTML needs its own response with its own policy.
|
||||
- The public page `/p/[company]/[slug]` renders on the server. `routeGuard.isPublicPath` admits only `^/p/[^/]+/[^/]+$` today.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
- Pasted HTML renders as designed.
|
||||
- It runs with an opaque origin on every path, including a direct visit to the frame address.
|
||||
|
||||
**Non-Goals:**
|
||||
- SEO for the framed content.
|
||||
- Working forms inside it.
|
||||
- An HTML editor.
|
||||
|
||||
## Decisions
|
||||
|
||||
1. **Route handlers, not pages.** `app/p/[company]/[slug]/frame/[block]/route.ts` and `app/pages/[id]/preview/frame/[block]/route.ts` return `text/html` directly. They reuse the server helpers that the public page (published read) and the preview (admin read with the session token) already use.
|
||||
2. **Sandbox in two places.**
|
||||
- The response header: `Content-Security-Policy: sandbox allow-scripts allow-popups allow-popups-to-escape-sandbox; frame-ancestors 'self'`. This covers a direct visit.
|
||||
- The `<iframe sandbox="allow-scripts allow-popups allow-popups-to-escape-sandbox">` attribute. This covers embedding.
|
||||
- There is no `default-src` restriction, so the AI's CDN scripts, fonts and images load.
|
||||
3. **Middleware skips the frame routes.** It returns early, with no nonce policy, for paths ending `/frame/<n>` under `/p/` and `/pages/<id>/preview/`. The preview route still checks the session itself; the middleware's route guard still runs before the early return, so an unsigned preview request is redirected to sign in.
|
||||
4. **Height script.**
|
||||
- The handler inserts a fixed script before `</body>`, or appends it when there is no `</body>`. The script posts `{type: "colite-frame-height", height}` to `parent` on load, on resize and through a `ResizeObserver` on `document.documentElement`.
|
||||
- The parent accepts a message only when `event.source` is that iframe's `contentWindow`. It clamps the height to 100–20,000 px, starting at 600.
|
||||
5. **Not-found.** The public handler answers 404 with an empty body for every miss: unknown company or slug, a draft page, a bad index or a non-HTML block. The same rule holds on the public page.
|
||||
6. **`hideHeader`.** A `cms_page.hide_header TINYINT(1) NOT NULL DEFAULT 0` column carried through the counter DTO, the mobile-api admin request and the public page response. `LandingPage` omits the header and the `<h1>` when it is on.
|
||||
7. **Limits.** `HTML` blocks allow 200,000 characters, about 200 KB for a large AI page. The existing 30-block cap stands. The portal body limit for page saves is checked and raised if it is below the largest page: 30 × 200,000 characters.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- **Misleading content:** staff with `BO_PAGES` can publish misleading content, such as a fake form. The frame contains it, saves are audited, and the role is granted by super admins only.
|
||||
- **Cost of each frame:** each HTML block is one more request per visit. Pages have at most 30 blocks.
|
||||
- **Relative addresses:** a relative asset path in pasted HTML (such as `/logo.png`) resolves against the Co-Lite site and breaks. The editor note tells staff to use full `https://` addresses for images.
|
||||
@@ -0,0 +1,54 @@
|
||||
# Proposal
|
||||
|
||||
## Why
|
||||
|
||||
Marketing staff want to design a landing page with an AI tool and paste the result in, so a page can look like a designed site instead of only the built-in blocks. The INS page is the first case: rebuilt from blocks, it does not match the design of the INS proof of concept (`~/Projects/ins-landing-page`). On 2026-12-02 the owner chose to show pasted HTML in a sealed frame (option 1). Design approved 2026-12-02: `docs/superpowers/specs/2026-12-02-custom-html-block-design.md`.
|
||||
|
||||
## What Changes
|
||||
|
||||
- **New block type `HTML` (Custom HTML).**
|
||||
- Staff with `BO_PAGES` paste HTML, at most 200,000 characters per block.
|
||||
- Scripts are allowed in this block only. Every other block keeps refusing scripts.
|
||||
- **Sealed frame.**
|
||||
- The public page shows each HTML block in an `<iframe sandbox>` loaded from its own address: `/p/<company>/<slug>/frame/<block>`.
|
||||
- That response carries a `sandbox` Content-Security-Policy, so the pasted HTML runs with an opaque origin even when the address is opened directly. It cannot reach cookies, Co-Lite APIs, the page around it or top-level navigation, and its forms do not submit.
|
||||
- Only Co-Lite pages may frame it (`frame-ancestors 'self'`).
|
||||
- Staff preview a draft through a signed-in twin: `/pages/<id>/preview/frame/<block>`.
|
||||
- **Frame height:** a small script is added to the served HTML. It reports the document height, so the frame grows to fit.
|
||||
- **Hide page header:** a page option that hides the company header and the page title, so a page made of pasted HTML looks exactly as designed.
|
||||
- **Editor:**
|
||||
- "Add Custom HTML" with a monospace text box and a character counter;
|
||||
- a note that forms in the pasted HTML don't send;
|
||||
- the "Hide page header" switch.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
None.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- `landing-pages`:
|
||||
- the block types gain `HTML`, with its limit;
|
||||
- the scripts rule exempts it;
|
||||
- a new requirement covers how it is served sealed and sized;
|
||||
- the page gains the "hide header" option;
|
||||
- the editor gains the Custom HTML block and the switch.
|
||||
|
||||
## Impact
|
||||
|
||||
- **services-counter:**
|
||||
- `CmsBlockValidator` accepts `HTML` (200,000 characters, no script check);
|
||||
- `cms_page` gets a `hide_header` column and the page DTO carries it.
|
||||
- **SQL:** `sql/01-hide-header.sql` (DDL), `sql/02-html-block-labels.sql` (labels) and `sql/99-rollback.sql`. Mirror 01 into `local/seed/`.
|
||||
- **mobile-api:** the admin page request and the public page response carry `hideHeader`. Blocks already pass through unchanged.
|
||||
- **Portal:**
|
||||
- two frame route handlers;
|
||||
- `middleware.ts` leaves the frame routes without the nonce policy;
|
||||
- `routeGuard` admits the public frame path;
|
||||
- `CmsBlocks` renders the frame and honours `hideHeader`;
|
||||
- the editor;
|
||||
- labels, with Chinese.
|
||||
- **Gateway:** unchanged.
|
||||
- **Dependencies:** none.
|
||||
@@ -0,0 +1,129 @@
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: A Page Is An Ordered List Of Typed Blocks
|
||||
|
||||
A page SHALL belong to one company and have a slug, a title, an optional meta description, a status (Draft or Published), a "hide header" flag that defaults to off, and an ordered list of zero to 30 blocks. The block types SHALL be HERO, RICH_TEXT, IMAGE_TEXT, FAQ, FORM and HTML. Blocks SHALL be returned in the order they were saved, and a valid save SHALL replace all of a page's blocks.
|
||||
|
||||
#### Scenario: Blocks read back in order
|
||||
|
||||
- **WHEN** staff save page `hotel-technology` with blocks HERO, RICH_TEXT, FORM
|
||||
- **THEN** reading the page returns those three blocks in that order with their fields
|
||||
|
||||
#### Scenario: A save replaces the blocks
|
||||
|
||||
- **GIVEN** a page whose blocks are HERO and FAQ
|
||||
- **WHEN** it is saved with only a RICH_TEXT block
|
||||
- **THEN** the page has only that RICH_TEXT block
|
||||
|
||||
#### Scenario: An HTML block and the header flag read back
|
||||
|
||||
- **WHEN** staff save a page with "hide header" on and blocks HTML, FORM
|
||||
- **THEN** reading the page returns "hide header" on and the HTML block with its HTML unchanged
|
||||
|
||||
### Requirement: Block Fields Are Validated Server-Side
|
||||
|
||||
A page save SHALL be refused with the offending field path, writing nothing, when a block has an unknown type, a required field is blank, or a text exceeds its limit: heading 120, text and FAQ question 300, button label 40, FAQ answer 2000, rich-text HTML 100000 characters, and an HTML block's HTML 200000 characters. An HTML block's HTML SHALL NOT be blank. A FAQ SHALL have 1 to 30 items. `imagePosition` SHALL be LEFT or RIGHT.
|
||||
|
||||
#### Scenario: Too many blocks
|
||||
|
||||
- **WHEN** a page is saved with 31 blocks
|
||||
- **THEN** the save is refused and nothing is written
|
||||
|
||||
#### Scenario: HTML block too long
|
||||
|
||||
- **WHEN** a page is saved with an HTML block of 200001 characters
|
||||
- **THEN** the save is refused on field `blocks[0].html` and nothing is written
|
||||
|
||||
### Requirement: Page Content Cannot Run Scripts
|
||||
|
||||
A button SHALL have both a label and a link or neither. The link SHALL be a same-site path starting with a single `/`, an `https://` URL, a `mailto:` link or a `tel:` link. A save SHALL be refused when the HTML of a RICH_TEXT or IMAGE_TEXT block holds a `script` element, an `on*` attribute or a `javascript:` URL. The public page SHALL also sanitise that HTML against an allow-list before rendering it. HTML blocks are exempt, because they only ever run sealed.
|
||||
|
||||
#### Scenario: Script link on a button
|
||||
|
||||
- **WHEN** a page is saved with a HERO button link `javascript:alert(1)`
|
||||
- **THEN** the save is refused on field `blocks[0].buttonUrl`
|
||||
|
||||
#### Scenario: Script in rich text
|
||||
|
||||
- **WHEN** a page is saved with rich text holding `<img src=x onerror=alert(1)>`
|
||||
- **THEN** the save is refused on that block's HTML field
|
||||
|
||||
#### Scenario: Script in an HTML block
|
||||
|
||||
- **WHEN** a page is saved with an HTML block holding `<script>document.title = "x"</script>`
|
||||
- **THEN** the save succeeds
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Custom HTML Runs Sealed
|
||||
|
||||
The public page and the staff preview SHALL show each HTML block in a sandboxed frame loaded from its own address. Each frame response SHALL carry a Content-Security-Policy whose `sandbox` directive allows scripts and pop-ups only, so the HTML runs with an opaque origin even when the address is opened directly, and whose `frame-ancestors` directive allows only the Co-Lite site. The frame element SHALL NOT grant same-origin, form submission, top-level navigation or modal dialogs.
|
||||
|
||||
#### Scenario: Public frame is sealed
|
||||
|
||||
- **GIVEN** INS page `hotel-technology` is published with an HTML block at index 0
|
||||
- **WHEN** a visitor's browser loads `/p/INS/hotel-technology/frame/0`
|
||||
- **THEN** the response is the block's HTML with a `sandbox` policy that allows scripts and pop-ups and not same-origin
|
||||
- **AND** its `frame-ancestors` allows only the Co-Lite site
|
||||
|
||||
#### Scenario: Pasted HTML cannot reach the visitor's session
|
||||
|
||||
- **GIVEN** a published HTML block whose script reads `document.cookie` and calls `/api/auth/session`
|
||||
- **WHEN** the page is shown
|
||||
- **THEN** the script sees no Co-Lite cookies and its call carries no Co-Lite session
|
||||
|
||||
### Requirement: Custom HTML Frame Addresses
|
||||
|
||||
The public frame address SHALL be `/p/<company>/<slug>/frame/<block index>` and SHALL answer only for an HTML block of a published page; every other request SHALL get the same not-found response. The preview frame address SHALL be `/pages/<id>/preview/frame/<block index>` and SHALL require a signed-in user with `BO_PAGES` who may see that page.
|
||||
|
||||
#### Scenario: No frame for a draft, a missing block or a non-HTML block
|
||||
|
||||
- **WHEN** a visitor loads the frame address of a draft page, of block 7 of a page with 3 blocks, or of a FORM block
|
||||
- **THEN** each answers with the same not-found response
|
||||
|
||||
#### Scenario: Staff preview of a draft frame
|
||||
|
||||
- **GIVEN** a draft page with an HTML block
|
||||
- **WHEN** a signed-in user with `BO_PAGES` of that page's company opens the preview
|
||||
- **THEN** the frame shows the draft HTML, sealed as on the public page
|
||||
- **AND** the same address without a session sends the browser to sign in
|
||||
|
||||
### Requirement: Custom HTML Frame Height
|
||||
|
||||
The frame SHALL grow to fit its content, between 100 and 20000 pixels, using height reports sent by that frame only. Before the first report it SHALL be 600 pixels tall.
|
||||
|
||||
#### Scenario: A tall paste grows the frame
|
||||
|
||||
- **GIVEN** a published HTML block whose content is 3000 pixels tall
|
||||
- **WHEN** a visitor opens the page
|
||||
- **THEN** the frame is 3000 pixels tall and shows no inner scroll bar
|
||||
|
||||
#### Scenario: Another frame cannot resize it
|
||||
|
||||
- **WHEN** a different window posts a height report to the page
|
||||
- **THEN** the frame's height does not change
|
||||
|
||||
### Requirement: The Custom HTML Block In The Editor
|
||||
|
||||
The editor SHALL offer "Add Custom HTML", which adds an HTML block with a monospace text box, a 200000-character counter and a note that forms inside the pasted HTML do not send and the sign-up form block collects leads. The editor SHALL also offer a "hide page header" switch for the page.
|
||||
|
||||
#### Scenario: Adding a Custom HTML block
|
||||
|
||||
- **WHEN** staff add a Custom HTML block and paste HTML into it
|
||||
- **THEN** the block shows the pasted HTML, the character count and the note about forms
|
||||
|
||||
#### Scenario: Hiding the header
|
||||
|
||||
- **WHEN** staff turn on "hide page header" and save
|
||||
- **THEN** reading the page returns "hide header" on
|
||||
|
||||
### Requirement: Hide Page Header
|
||||
|
||||
When a page's "hide header" flag is on, its public page and its preview SHALL NOT show the company header or the page title, and SHALL still use the page title in the browser title and the page metadata.
|
||||
|
||||
#### Scenario: Header hidden
|
||||
|
||||
- **GIVEN** INS page `hotel-technology` has "hide header" on
|
||||
- **WHEN** a visitor opens it
|
||||
- **THEN** no company logo bar or page title heading shows above the first block
|
||||
- **AND** the browser title is still the page title
|
||||
@@ -0,0 +1,5 @@
|
||||
-- Co-Lite change add-custom-html-block: a page option that hides the company header and the page title.
|
||||
-- Target: `service-counter`. Additive only. Run once, after add-landing-pages 01.
|
||||
SET NAMES utf8mb4;
|
||||
USE `service-counter`;
|
||||
ALTER TABLE `cms_page` ADD COLUMN `hide_header` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Hide the company header and the page title on the public page' AFTER `status`;
|
||||
@@ -0,0 +1,11 @@
|
||||
-- The labels added by add-custom-html-block, 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 'PagesBlockHtml', JSON_OBJECT('en_US', 'Custom HTML', 'zh_CN', '自定义 HTML'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesBlockHtml') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '自定义 HTML') WHERE LOWER(code) = LOWER('PagesBlockHtml') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesHtml', JSON_OBJECT('en_US', 'HTML', 'zh_CN', 'HTML'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHtml') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', 'HTML') WHERE LOWER(code) = LOWER('PagesHtml') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesHtmlHint', JSON_OBJECT('en_US', 'Forms inside the pasted HTML don''t send. Add a Sign-up form block to collect leads.', 'zh_CN', '粘贴的 HTML 中的表单不会发送。请添加报名表单区块来收集线索。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHtmlHint') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '粘贴的 HTML 中的表单不会发送。请添加报名表单区块来收集线索。') WHERE LOWER(code) = LOWER('PagesHtmlHint') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesHideHeader', JSON_OBJECT('en_US', 'Hide page header', 'zh_CN', '隐藏页面顶栏'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHideHeader') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '隐藏页面顶栏') WHERE LOWER(code) = LOWER('PagesHideHeader') AND area = 'A';
|
||||
@@ -0,0 +1,6 @@
|
||||
-- Co-Lite change add-custom-html-block: rollback. Pages with HTML blocks must be edited or deleted first,
|
||||
-- because the previous release refuses the HTML block type when such a page is saved.
|
||||
USE `service-counter`;
|
||||
ALTER TABLE `cms_page` DROP COLUMN `hide_header`;
|
||||
USE `service-system`;
|
||||
DELETE FROM message WHERE code IN ('PagesBlockHtml', 'PagesHtml', 'PagesHtmlHint', 'PagesHideHeader') AND area = 'A';
|
||||
@@ -0,0 +1,39 @@
|
||||
# Tasks: add-custom-html-block
|
||||
|
||||
Design: `design.md` and `docs/superpowers/specs/2026-12-02-custom-html-block-design.md`. 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-hide-header.sql` (`cms_page.hide_header`), `sql/99-rollback.sql`; mirror 01 into `local/seed/`.
|
||||
- [x] 1.2 services-counter:
|
||||
- the `HTML` block type: required, at most 200,000 characters, no script check;
|
||||
- `hideHeader` on the page model and DTO.
|
||||
- Verify: `mvn -T 1C -B -pl solvway-services-counter -am verify`
|
||||
- [x] 1.3 mobile-api: `hideHeader` on `AdminPageRequest` and in the public page response.
|
||||
- Verify: `mvn -T 1C -B -pl solvway-mobile-api -am verify`
|
||||
|
||||
## 2. Portal
|
||||
|
||||
- [x] 2.1 Frame routes (public and preview) with the sandbox headers, the 404 rules and the height script.
|
||||
- The middleware skips them; `routeGuard` admits the public frame path.
|
||||
- Security code: read the whole diff.
|
||||
- [x] 2.2 `CmsBlocks`:
|
||||
- the sandboxed iframe with height messages from its own frame only;
|
||||
- `hideHeader` hides the header and the title.
|
||||
- [x] 2.3 Editor:
|
||||
- "Add Custom HTML", with a monospace text box, a counter and the forms note;
|
||||
- the "Hide page header" switch;
|
||||
- field errors at the HTML field.
|
||||
- [x] 2.4 Labels in `defaultMessages.ts` with Chinese in `zh_CN.seed.json`, then `npm run i18n:sql`. `sql/02-html-block-labels.sql` holds only the new labels.
|
||||
- Verify (2.1 to 2.4): `cd solvway-admin-portal && npx vitest run; echo VITEST=$? && npx tsc --noEmit && npm run lint`
|
||||
|
||||
## 3. Release
|
||||
|
||||
- [x] 3.1 `docs/deployment.md`: the SQL rows and the frame routes. A Traefik or proxy layer must not add a CSP that overrides the frame's own policy.
|
||||
- [x] 3.2 Live Playwright check on the local stack, at 1280 and 360 px:
|
||||
- paste the INS proof-of-concept HTML into the INS page, with "hide page header" on and the sign-up form below it;
|
||||
- it looks like the PoC signed out;
|
||||
- opening the frame address directly shows no Co-Lite cookies to the frame's script;
|
||||
- a draft frame is not found for visitors and previews for staff;
|
||||
- an over-limit paste is refused at its field.
|
||||
- [x] 3.3 Whole-branch self-review (security: the sandbox headers, the middleware skip and the message handler), then the PR to main and the merge.
|
||||
File renamed without changes.
@@ -0,0 +1,50 @@
|
||||
# Design
|
||||
|
||||
The full design is `docs/superpowers/specs/2026-12-02-lead-notifications-design.md` (approved 2026-12-02). This file records the technical decisions.
|
||||
|
||||
## Context
|
||||
|
||||
- `service-system`.`notification` exists from Tastefully (`id, receiver, message, create_date_time`, `utf8mb3`) and is empty. services-system has a thin `NotificationController` (save, find by receiver).
|
||||
- Babyboo extended the same table and built the admin inbox API and bell (`add-admin-internal-notifications`, 2026-10-07). Its files are the porting source: services-system `Notification`/`NotificationService`/`NotificationController`, mobile-api `AdminNotificationController`/`AdminNotificationService`, portal `NotificationsBell.tsx`, `app/notifications/page.tsx`, `app/api/notifications/**`, `app/lib/services/notifications.ts`.
|
||||
- services-counter already calls another service best-effort after commit: `WhatsappNotifier` (2-second timeout, never throws, `TransactionSynchronization.afterCommit`).
|
||||
- Assignment points in services-counter: `EventLeadService` capture and update (`salespersonChanged`), `RegistrationService` new capture and `alreadyCaptured` (`assign`). The event's sales team is `event_salesperson`.
|
||||
- Inbound WhatsApp: `WebhookIngestService` calls `WaConversationRepository.recordInbound`. The chat owner is `wa_conversation.owner_user_id`.
|
||||
- Leads due: `event_lead.next_follow_up_date`, `status`, `salesperson_user_id`. The lead dashboard already counts overdue follow-ups.
|
||||
- The portal has `usePolling` (babyboo used `useVisiblePolling`).
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:** the bell, the four triggers, server read state, both languages, company scoping.
|
||||
|
||||
**Non-Goals:** email, WhatsApp or push alerts; per-user settings; broadcasts; purging.
|
||||
|
||||
## Decisions
|
||||
|
||||
1. **One row per recipient** in `notification`, `recipient_type = 'A'`, `receiver` = user id as text (the column is `varchar(45)`), `company_id` set. Babyboo's model; read state is a column.
|
||||
2. **Codes, not text.** `type` is `LEAD_ASSIGNED`, `WEB_SIGNUP`, `WHATSAPP_MESSAGE` or `FOLLOW_UP_DUE`. `title` and `message` hold a label code and a JSON parameter object (lead name, event name, counts). The bell renders them with `t()`. No phone numbers or emails in parameters.
|
||||
3. **Collapse key.** An optional `collapse_key` on create: when the receiver already has an unread row with that key, the create updates that row's message and time and marks nothing else; otherwise it inserts. WhatsApp uses `WA:<conversation uuid>`; the follow-up summary uses `FOLLOW_UP:<date>`, so a second run of the job on the same day before the user reads it does not duplicate.
|
||||
- ponytail: a job rerun after the user read the summary adds a second one that day. Add a run record if that happens in practice.
|
||||
4. **Delivery is a REST call after commit**, copying `WhatsappNotifier`: 2-second timeout, no retry, failures logged with ids only. Counter and WhatsApp each get one small `StaffNotifier` posting to services-system's create endpoint.
|
||||
- ponytail: no queue; a lost notification leaves the lead, chat and follow-up date in place. Move to Pub/Sub if losses show up.
|
||||
5. **Recipients are resolved by the sender**, which already has the data: counter knows the salesperson and the event's sales team; WhatsApp knows the chat owner. services-system only stores and serves rows.
|
||||
6. **Self-assignment is silent.** When the staff user making the change is the new salesperson, no "lead assigned" notification is sent. The counter compares the request's acting user with the new salesperson.
|
||||
7. **A web sign-up assigned at capture sends one notification**, of type `WEB_SIGNUP`, to the salesperson. A web sign-up without a salesperson goes to every user in `event_salesperson` for that event; none when the team is empty.
|
||||
8. **Follow-up job** in services-counter, `@Scheduled(cron = "${leads.follow-up-notice.cron:0 0 8 * * *}", zone = "Asia/Kuala_Lumpur")`. It groups open event leads with `next_follow_up_date <= today` by company and salesperson, and sends one summary each (due today count, overdue count) linking to the event leads list. Leads without a salesperson are skipped.
|
||||
9. **Admin API** in mobile-api reads the user id and company from the session, never from the request. Mark-read endpoints change only the caller's rows; another user's id returns 404.
|
||||
10. **Bell** ported from babyboo: polls the unread count every 30 seconds while visible, the drop-down shows the newest 10, opening it marks the shown items read, clicking navigates to `link`. `/notifications` lists 20 per page with "Mark all read". Every signed-in user gets it; no module permission.
|
||||
11. **Charset.** The DDL converts the table to `utf8mb4` (it is empty), so names with any characters are stored.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- [Lost notifications on a services-system outage] → the underlying data is unaffected; logs show the failures.
|
||||
- [Noisy bell for busy salespeople] → the WhatsApp collapse and the daily summary limit it; per-user settings come later if asked.
|
||||
- [Leaking another company's lead] → recipients come from the same company's data; the API filters by the session user; tests cover a second company.
|
||||
- [Links that the reader may not open] → links point to pages that still check access; a notification only names a lead its recipient is assigned to or on the team for.
|
||||
|
||||
## Migration Plan
|
||||
|
||||
Run `sql/01` (additive columns on an empty table) before deploying the services, then `sql/02` labels. Rollback: `sql/99-rollback.sql` drops the columns and labels; the old services ignore them.
|
||||
|
||||
## Open Questions
|
||||
|
||||
None.
|
||||
@@ -0,0 +1,41 @@
|
||||
# Proposal
|
||||
|
||||
## Why
|
||||
|
||||
Sales staff learn about new work only by refreshing lists. A lead assigned to them, a sign-up from a landing page, a customer's WhatsApp reply and a follow-up falling due all go unnoticed until someone looks. This is feature-list item 12, needed before go-live on 2027-01-15. On 2026-12-02 the owner chose an in-app bell only and approved the design: `docs/superpowers/specs/2026-12-02-lead-notifications-design.md`.
|
||||
|
||||
## What Changes
|
||||
|
||||
- **Bell in the portal header** for every signed-in staff user:
|
||||
- an unread badge, refreshed every 30 seconds while the tab is visible;
|
||||
- a drop-down of recent notifications, each linking to its lead or chat;
|
||||
- a full notifications page;
|
||||
- read state kept on the server.
|
||||
- **Four triggers:**
|
||||
- a lead assigned to someone notifies that salesperson;
|
||||
- a landing-page sign-up notifies the assigned salesperson, else the event's sales team;
|
||||
- an inbound WhatsApp message notifies the chat owner, at most one unread notification per chat;
|
||||
- a daily 08:00 (Malaysia) summary of follow-ups due or overdue, per salesperson.
|
||||
- **Text follows the reader's language**: notifications store message codes and parameters, not text.
|
||||
- **Best effort:** a notification that cannot be written never fails the sign-up, assignment or message behind it.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
- `lead-notifications`: the staff bell, its read state, and the four triggers with their recipients.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
None. The triggers add a side effect to lead capture, lead assignment and WhatsApp intake without changing their specified behaviour.
|
||||
|
||||
## Impact
|
||||
|
||||
- **services-system:** the unused `notification` table gains `recipient_type`, `company_id`, `title`, `type`, `link`, `collapse_key`, `seen`, `read_at` and an index, and moves to `utf8mb4`. New endpoints: create, list mine, unread count, mark read, mark all read.
|
||||
- **SQL:** `sql/01-notification-columns.sql` (DDL), `sql/02-notification-labels.sql` (labels), `sql/99-rollback.sql`. Mirror 01 into `local/seed/`.
|
||||
- **services-counter:** a notifier called after commit on assignment and on web sign-up; a daily follow-up job.
|
||||
- **services-whatsapp:** a notifier called after an inbound message is recorded.
|
||||
- **mobile-api:** `/api/admin/notifications` (list, unread count, read, read all), always for the signed-in user.
|
||||
- **Portal:** `NotificationsBell` in the header, `/notifications` page, BFF routes, labels with Chinese. Ported from babyboo.
|
||||
- **Gateway:** unchanged; `/api/admin/**` is already routed.
|
||||
- **Dependencies:** none.
|
||||
@@ -0,0 +1,132 @@
|
||||
## Purpose
|
||||
|
||||
In-app notifications for staff: a bell with unread state, and alerts when a lead is assigned, a landing-page sign-up arrives, a customer sends a WhatsApp message, or follow-ups fall due.
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Staff Notification Bell
|
||||
|
||||
The portal SHALL show every signed-in staff user a bell in the header with the count of their unread notifications, refreshed at least every 30 seconds while the page is visible. Opening the bell SHALL list their newest notifications, newest first, and mark the listed ones read. Choosing a notification SHALL open the page it links to.
|
||||
|
||||
#### Scenario: Unread count and opening the bell
|
||||
|
||||
- **GIVEN** a salesperson has 3 unread notifications
|
||||
- **WHEN** they open any portal page
|
||||
- **THEN** the bell shows 3
|
||||
- **WHEN** they open the bell
|
||||
- **THEN** the 3 notifications are listed newest first
|
||||
- **AND** after a reload the bell shows no unread count
|
||||
|
||||
#### Scenario: A notification opens its lead
|
||||
|
||||
- **GIVEN** a "lead assigned" notification for lead L
|
||||
- **WHEN** the salesperson chooses it
|
||||
- **THEN** the portal opens lead L
|
||||
|
||||
### Requirement: Notifications Page
|
||||
|
||||
The portal SHALL provide a notifications page listing the signed-in user's notifications, newest first and paged, showing which are unread, with an action to mark all of them read.
|
||||
|
||||
#### Scenario: Mark all read
|
||||
|
||||
- **GIVEN** a user with 25 notifications, 5 of them unread
|
||||
- **WHEN** they open the notifications page and choose "Mark all read"
|
||||
- **THEN** none of their notifications is unread
|
||||
- **AND** the bell shows no unread count
|
||||
|
||||
### Requirement: Notifications Are Private To Their Recipient
|
||||
|
||||
The system SHALL show and change a user's notifications only for that user, identified from their session. A request naming another user's notification SHALL be refused as not found. A notification SHALL only name a lead of the recipient's own company.
|
||||
|
||||
#### Scenario: Another user's notification
|
||||
|
||||
- **GIVEN** notification N belongs to user A
|
||||
- **WHEN** user B asks to mark N read
|
||||
- **THEN** the request is refused as not found
|
||||
- **AND** N stays unread for user A
|
||||
|
||||
#### Scenario: Two companies
|
||||
|
||||
- **GIVEN** an INS salesperson and a CV salesperson
|
||||
- **WHEN** a CV lead is assigned to the CV salesperson
|
||||
- **THEN** only the CV salesperson is notified
|
||||
|
||||
### Requirement: Notifications Follow The Reader's Language
|
||||
|
||||
A notification SHALL be stored as message codes with parameters and shown in the reader's current portal language. Its parameters SHALL NOT include phone numbers or email addresses.
|
||||
|
||||
#### Scenario: Chinese reader
|
||||
|
||||
- **GIVEN** a "lead assigned" notification
|
||||
- **WHEN** a user with the portal in Chinese opens the bell
|
||||
- **THEN** the notification text is in Chinese, with the lead's name
|
||||
|
||||
### Requirement: Lead Assigned Notification
|
||||
|
||||
When an event lead's salesperson is set or changed to a user, the system SHALL notify that user, linking to the lead. It SHALL NOT notify a user who assigned the lead to themselves, and SHALL NOT notify anyone when the salesperson is cleared.
|
||||
|
||||
#### Scenario: Manager assigns a lead
|
||||
|
||||
- **WHEN** a manager assigns event lead L to salesperson S
|
||||
- **THEN** S gets one "lead assigned" notification naming L and its event
|
||||
|
||||
#### Scenario: Self-assignment
|
||||
|
||||
- **WHEN** salesperson S assigns lead L to themselves
|
||||
- **THEN** no notification is created
|
||||
|
||||
### Requirement: Landing Page Sign-up Notification
|
||||
|
||||
When a landing-page sign-up creates or updates an event lead, the system SHALL notify the lead's salesperson if it has one, otherwise every member of the event's sales team, once each. With no salesperson and no sales team, nobody SHALL be notified.
|
||||
|
||||
#### Scenario: Unassigned sign-up
|
||||
|
||||
- **GIVEN** event E has sales team members S1 and S2
|
||||
- **WHEN** a visitor signs up on a page whose form belongs to E, and no salesperson is assigned
|
||||
- **THEN** S1 and S2 each get one "new sign-up" notification
|
||||
|
||||
#### Scenario: Assigned at capture
|
||||
|
||||
- **WHEN** a web sign-up is captured already assigned to S
|
||||
- **THEN** S gets exactly one notification, the "new sign-up" one
|
||||
|
||||
### Requirement: WhatsApp Message Notification
|
||||
|
||||
When an inbound WhatsApp message is recorded on a chat with an owner, the system SHALL notify the owner, linking to the chat. While the owner has an unread notification for that chat, a further message SHALL update it rather than add another. A chat without an owner SHALL notify nobody.
|
||||
|
||||
#### Scenario: Busy chat
|
||||
|
||||
- **GIVEN** salesperson S owns a chat
|
||||
- **WHEN** the customer sends 4 messages before S opens the bell
|
||||
- **THEN** S has one unread notification for that chat, timed at the last message
|
||||
|
||||
#### Scenario: Unowned chat
|
||||
|
||||
- **WHEN** a message arrives on a chat without an owner
|
||||
- **THEN** no notification is created
|
||||
|
||||
### Requirement: Follow-ups Due Notification
|
||||
|
||||
Every day at 08:00 Malaysia time, the system SHALL send each salesperson with open event leads whose next follow-up date is today or earlier one summary notification giving the count due today and the count overdue, linking to their event leads.
|
||||
|
||||
#### Scenario: Morning summary
|
||||
|
||||
- **GIVEN** salesperson S has 2 open leads due today and 1 open lead due yesterday
|
||||
- **WHEN** the daily run happens
|
||||
- **THEN** S gets one notification saying 2 due today and 1 overdue
|
||||
|
||||
#### Scenario: Nothing due
|
||||
|
||||
- **GIVEN** salesperson S has no open lead due today or earlier
|
||||
- **WHEN** the daily run happens
|
||||
- **THEN** S gets no notification
|
||||
|
||||
### Requirement: Notifications Never Block The Action
|
||||
|
||||
A failure to create a notification SHALL NOT fail or roll back the sign-up, assignment or inbound message that caused it. The failure SHALL be logged without names, phone numbers or email addresses.
|
||||
|
||||
#### Scenario: Notification store down
|
||||
|
||||
- **GIVEN** the notification store cannot be reached
|
||||
- **WHEN** a visitor signs up on a landing page
|
||||
- **THEN** the sign-up succeeds and the lead is saved
|
||||
@@ -0,0 +1,19 @@
|
||||
-- Co-Lite change add-lead-notifications: the staff notification bell.
|
||||
-- Target: `service-system`.`notification`, the unused table from Tastefully. Pre-check (read-only):
|
||||
-- SELECT COUNT(*) FROM `service-system`.`notification`; -- expect 0
|
||||
-- The table is converted to utf8mb4 (names in any script) and gains babyboo's bell columns plus company_id
|
||||
-- and collapse_key. Existing columns keep their meaning. Run once.
|
||||
SET NAMES utf8mb4;
|
||||
USE `service-system`;
|
||||
ALTER TABLE `notification`
|
||||
CONVERT TO CHARACTER SET utf8mb4,
|
||||
ADD COLUMN `recipient_type` char(1) NULL COMMENT 'A = staff user' AFTER `receiver`,
|
||||
ADD COLUMN `company_id` bigint NULL AFTER `recipient_type`,
|
||||
ADD COLUMN `title` varchar(255) NULL COMMENT 'Message code' AFTER `company_id`,
|
||||
ADD COLUMN `type` varchar(45) NULL COMMENT 'LEAD_ASSIGNED, WEB_SIGNUP, WHATSAPP_MESSAGE, FOLLOW_UP_DUE' AFTER `message`,
|
||||
ADD COLUMN `link` varchar(512) NULL COMMENT 'Portal path opened on click' AFTER `type`,
|
||||
ADD COLUMN `collapse_key` varchar(100) NULL COMMENT 'An unread row with the same receiver and key is updated, not duplicated' AFTER `link`,
|
||||
ADD COLUMN `seen` tinyint(1) NOT NULL DEFAULT 0 AFTER `collapse_key`,
|
||||
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`);
|
||||
@@ -0,0 +1,33 @@
|
||||
-- The labels added by add-lead-notifications, 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 'NotificationsTitle', JSON_OBJECT('en_US', 'Notifications', 'zh_CN', '通知'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsTitle') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '通知') WHERE LOWER(code) = LOWER('NotificationsTitle') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NotificationsUnread', JSON_OBJECT('en_US', 'Notifications, {count} unread', 'zh_CN', '通知,{count} 条未读'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsUnread') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '通知,{count} 条未读') WHERE LOWER(code) = LOWER('NotificationsUnread') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NotificationsEmpty', JSON_OBJECT('en_US', 'No notifications yet.', 'zh_CN', '暂无通知。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsEmpty') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '暂无通知。') WHERE LOWER(code) = LOWER('NotificationsEmpty') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NotificationsLoadFailed', JSON_OBJECT('en_US', 'Couldn''t load notifications.', 'zh_CN', '无法加载通知。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsLoadFailed') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '无法加载通知。') WHERE LOWER(code) = LOWER('NotificationsLoadFailed') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NotificationsMarkAllRead', JSON_OBJECT('en_US', 'Mark all read', 'zh_CN', '全部标为已读'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsMarkAllRead') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '全部标为已读') WHERE LOWER(code) = LOWER('NotificationsMarkAllRead') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NotificationsSeeAll', JSON_OBJECT('en_US', 'See all', 'zh_CN', '查看全部'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsSeeAll') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '查看全部') WHERE LOWER(code) = LOWER('NotificationsSeeAll') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NotificationsUnreadBadge', JSON_OBJECT('en_US', 'Unread', 'zh_CN', '未读'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsUnreadBadge') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '未读') WHERE LOWER(code) = LOWER('NotificationsUnreadBadge') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NoticeLeadAssigned', JSON_OBJECT('en_US', 'Lead assigned to you', 'zh_CN', '有新线索分配给你'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeLeadAssigned') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '有新线索分配给你') WHERE LOWER(code) = LOWER('NoticeLeadAssigned') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NoticeWebSignup', JSON_OBJECT('en_US', 'New sign-up', 'zh_CN', '新的报名'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeWebSignup') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '新的报名') WHERE LOWER(code) = LOWER('NoticeWebSignup') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NoticeLeadBody', JSON_OBJECT('en_US', '{lead} · {event}', 'zh_CN', '{lead} · {event}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeLeadBody') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '{lead} · {event}') WHERE LOWER(code) = LOWER('NoticeLeadBody') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NoticeFollowUpDue', JSON_OBJECT('en_US', 'Follow-ups due', 'zh_CN', '待跟进'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeFollowUpDue') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '待跟进') WHERE LOWER(code) = LOWER('NoticeFollowUpDue') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NoticeFollowUpBody', JSON_OBJECT('en_US', '{due} due today, {overdue} overdue', 'zh_CN', '今天到期 {due} 条,已逾期 {overdue} 条'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeFollowUpBody') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '今天到期 {due} 条,已逾期 {overdue} 条') WHERE LOWER(code) = LOWER('NoticeFollowUpBody') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NoticeWhatsappMessage', JSON_OBJECT('en_US', 'New WhatsApp message', 'zh_CN', '新的 WhatsApp 消息'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeWhatsappMessage') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '新的 WhatsApp 消息') WHERE LOWER(code) = LOWER('NoticeWhatsappMessage') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NoticeWhatsappBody', JSON_OBJECT('en_US', 'From {name}', 'zh_CN', '来自 {name}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeWhatsappBody') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '来自 {name}') WHERE LOWER(code) = LOWER('NoticeWhatsappBody') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NoticeWhatsappBodyNoName', JSON_OBJECT('en_US', 'From a new contact', 'zh_CN', '来自新联系人'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeWhatsappBodyNoName') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '来自新联系人') WHERE LOWER(code) = LOWER('NoticeWhatsappBodyNoName') AND area = 'A';
|
||||
@@ -0,0 +1,16 @@
|
||||
-- Co-Lite change add-lead-notifications: rollback. Drops the bell columns and labels; the previous release never
|
||||
-- reads them. The charset change is left in place (utf8mb4 holds everything utf8mb3 did).
|
||||
SET NAMES utf8mb4;
|
||||
USE `service-system`;
|
||||
ALTER TABLE `notification`
|
||||
DROP INDEX `idx_notification_inbox`,
|
||||
DROP INDEX `idx_notification_collapse`,
|
||||
DROP COLUMN `recipient_type`,
|
||||
DROP COLUMN `company_id`,
|
||||
DROP COLUMN `title`,
|
||||
DROP COLUMN `type`,
|
||||
DROP COLUMN `link`,
|
||||
DROP COLUMN `collapse_key`,
|
||||
DROP COLUMN `seen`,
|
||||
DROP COLUMN `read_at`;
|
||||
DELETE FROM message WHERE code IN ('NotificationsTitle', 'NotificationsUnread', 'NotificationsEmpty', 'NotificationsLoadFailed', 'NotificationsMarkAllRead', 'NotificationsSeeAll', 'NotificationsUnreadBadge', 'NoticeLeadAssigned', 'NoticeWebSignup', 'NoticeLeadBody', 'NoticeFollowUpDue', 'NoticeFollowUpBody', 'NoticeWhatsappMessage', 'NoticeWhatsappBody', 'NoticeWhatsappBodyNoName') AND area = 'A';
|
||||
@@ -0,0 +1,39 @@
|
||||
# Tasks: add-lead-notifications
|
||||
|
||||
Design: `design.md` and `docs/superpowers/specs/2026-12-02-lead-notifications-design.md`. Every task is TDD. Work is serial in the main session, with a self-review per task. Porting source: babyboo's `add-admin-internal-notifications`.
|
||||
|
||||
## 1. Store and API
|
||||
|
||||
- [x] 1.1 SQL: `sql/01-notification-columns.sql` (columns, index, `utf8mb4`), `sql/99-rollback.sql`; mirror 01 into `local/seed/`.
|
||||
- [x] 1.2 services-system: the extended `Notification`; create (with `collapse_key`), list mine (paged), unread count, mark one read (own rows only), mark all read.
|
||||
- Verify: `mvn -T 1C -B -pl solvway-services-system -am verify`
|
||||
- [x] 1.3 mobile-api: `/api/admin/notifications`, `/unread-count`, `/{id}/read`, `/read-all`, user and company from the session.
|
||||
- Verify: `mvn -T 1C -B -pl solvway-mobile-api -am verify`
|
||||
|
||||
## 2. Triggers
|
||||
|
||||
- [x] 2.1 services-counter `StaffNotifier` (after commit, 2 s timeout, never throws, ids-only logs).
|
||||
- Lead assigned at capture and on update, not on self-assignment or clearing.
|
||||
- Web sign-up to the salesperson, else the event's sales team; one notification when assigned at capture.
|
||||
- [x] 2.2 services-counter daily follow-up summary job (08:00 Asia/Kuala_Lumpur, cron property), one per salesperson with open leads due today or overdue.
|
||||
- Verify (2.1, 2.2): `mvn -T 1C -B -pl solvway-services-counter -am verify`
|
||||
- [x] 2.3 services-whatsapp: notify the chat owner after an inbound message is recorded, collapse key `WA:<conversation uuid>`; no owner, no notification.
|
||||
- Verify: `mvn -T 1C -B -pl solvway-services-whatsapp -am verify`
|
||||
|
||||
## 3. Portal
|
||||
|
||||
- [x] 3.1 BFF routes `app/api/notifications/**` and `app/lib/services/notifications.ts`.
|
||||
- [x] 3.2 `NotificationsBell` in the header (30 s polling while visible, newest 10, opening marks read, click opens the link) and the `/notifications` page with "Mark all read".
|
||||
- [x] 3.3 Labels in `defaultMessages.ts` with Chinese in `zh_CN.seed.json`, then `npm run i18n:sql`. `sql/02-notification-labels.sql` holds only the new labels.
|
||||
- Verify (3.1 to 3.3): `cd solvway-admin-portal && npx vitest run; echo VITEST=$? && npx tsc --noEmit && npm run lint`
|
||||
|
||||
## 4. Release
|
||||
|
||||
- [x] 4.1 `docs/deployment.md`: the SQL rows and the follow-up job's cron property.
|
||||
- [x] 4.2 Live Playwright check on the local stack, signed in as two users of different companies:
|
||||
- assigning a lead notifies the salesperson and not the other company;
|
||||
- a landing-page sign-up notifies the event's sales team;
|
||||
- a WhatsApp message (mock) on an owned chat shows one notification per chat;
|
||||
- the follow-up job (run by setting its cron for the test) gives the summary;
|
||||
- the bell, the page and "Mark all read" work in English and Chinese, at 1280 and 360 px.
|
||||
- [x] 4.3 Whole-branch self-review (security: recipient scoping, own-rows-only read endpoints, no personal data in logs or parameters), then the PR to main and the merge.
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-12-02
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+1
@@ -108,3 +108,4 @@ Verify commands:
|
||||
- the unread badge.
|
||||
- Earlier in 5.1: media, ticks and the 360 px layout. The staff-only view (Mine only, no owner select) is covered by tests only: no staff password was available, and staff passwords were not reset for it. The test rows were removed.
|
||||
- [ ] 6.3 The owner's manual click-every-button e2e on a production build covers the inbox too (record the result here).
|
||||
- Deferred by the owner on 2026-12-02: the WhatsApp business account cannot be linked yet, so the change is archived with this check open. Run it once the account is linked; any fix goes in a new change.
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-12-02
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -129,10 +129,15 @@ A table wider than its container SHALL show a fade on each edge where more colum
|
||||
|
||||
The sidebar SHALL show Dashboard first, then the labelled sections Events, Leads, Access and System, each with a fixed set and order of pages. A page not in any section SHALL appear in a final section without a label. A section SHALL be marked by a divider and a small muted label, with only the divider in the collapsed rail, and SHALL NOT show when it has no page the user may open. Every page SHALL have a distinct icon.
|
||||
|
||||
#### Scenario: WhatsApp inbox in the Leads section
|
||||
|
||||
- **WHEN** a user with `BO_WHATSAPP` and two unread conversations opens the portal
|
||||
- **THEN** the Leads section lists Leads, WhatsApp and Interests, with a badge showing 2
|
||||
|
||||
#### Scenario: Super admin sidebar
|
||||
|
||||
- **WHEN** a super admin opens the portal
|
||||
- **THEN** the sidebar shows Dashboard, then "Events" with Events and Event leads, "Leads" with Leads and Interests, "Access" with Users, Roles and Login security, and "System" with Companies, Emails and Audit log
|
||||
- **THEN** the sidebar shows Dashboard, then "Events" with Events, Event leads and Pages, "Leads" with Leads, WhatsApp and Interests, "Access" with Users, Roles and Login security, and "System" with Companies, Emails, Audit log, Translations and Languages
|
||||
|
||||
#### Scenario: Staff without admin pages
|
||||
|
||||
|
||||
@@ -70,7 +70,7 @@ On the event days, a registered guest's invite link SHALL show a "Check in" butt
|
||||
|
||||
### Requirement: Attendance at capture
|
||||
|
||||
Each event lead SHALL have an attended time. A staff capture, a walk-in code registration or a check-in-page capture made during the event days SHALL set it. A registration made before the event days SHALL NOT set it. Event leads that exist before this change SHALL count as not attended.
|
||||
Each event lead SHALL have an attended time. A staff capture, a walk-in code registration or a check-in-page capture made during the event days SHALL set it. A registration made before the event days SHALL NOT set it. A web page sign-up SHALL NOT set it, whenever it is made. Event leads that exist before this change SHALL count as not attended.
|
||||
|
||||
#### Scenario: Walk-in on the day
|
||||
|
||||
@@ -84,15 +84,27 @@ Each event lead SHALL have an attended time. A staff capture, a walk-in code reg
|
||||
- **WHEN** a visitor registers through the event's walk-in code
|
||||
- **THEN** the event lead is registered but not attended
|
||||
|
||||
#### Scenario: Web enquiry during a standing event
|
||||
|
||||
- **GIVEN** the running event `INS website enquiries`
|
||||
- **WHEN** a visitor submits the form on a landing page that points at it
|
||||
- **THEN** the event lead is registered but not attended
|
||||
|
||||
### Requirement: Attendance in staff screens
|
||||
|
||||
Users who can edit event leads SHALL tick or untick Attended. The event leads listing SHALL show an Attended column and filter, and each event lead's source (Staff, QR, Invite).
|
||||
Users who can edit event leads SHALL tick or untick Attended. The event leads listing SHALL show an Attended column and filter, and each event lead's source (Staff, QR, Invite, Web page).
|
||||
|
||||
#### Scenario: Staff untick
|
||||
|
||||
- **WHEN** staff untick Attended on an event lead linked to a guest
|
||||
- **THEN** the guest list shows that guest as Registered
|
||||
|
||||
#### Scenario: Web page source
|
||||
|
||||
- **GIVEN** an event lead created by a landing-page form
|
||||
- **WHEN** staff open the event leads listing
|
||||
- **THEN** its source shows "Web page"
|
||||
|
||||
### Requirement: Guest linking across routes
|
||||
|
||||
A guest's status SHALL be derived from the event lead it is linked to: Registered when linked, Attended when that event lead is attended. Whenever a capture for an event creates or finds an event lead, by staff, walk-in code, invite or check-in, an unlinked guest of the same event SHALL be linked to it. The guest is matched by mobile first, else by email. The guest then SHALL count as a guest, not as a walk-in.
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
# landing-pages Specification
|
||||
|
||||
## Purpose
|
||||
|
||||
Public landing pages per company, built by staff from blocks in the back office without a developer. A page's sign-up form registers visitors into an event as web sign-ups, with the page address and campaign tags, so they enter the lead pipeline. Each page shows its company's logo and accent colour.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: A Page Is An Ordered List Of Typed Blocks
|
||||
|
||||
A page SHALL belong to one company and have a slug, a title, an optional meta description, a status (Draft or Published) and an ordered list of zero to 30 blocks. The block types SHALL be HERO, RICH_TEXT, IMAGE_TEXT, FAQ and FORM. Blocks SHALL be returned in the order they were saved, and a valid save SHALL replace all of a page's blocks.
|
||||
|
||||
#### Scenario: Blocks read back in order
|
||||
|
||||
- **WHEN** staff save page `hotel-technology` with blocks HERO, RICH_TEXT, FORM
|
||||
- **THEN** reading the page returns those three blocks in that order with their fields
|
||||
|
||||
#### Scenario: A save replaces the blocks
|
||||
|
||||
- **GIVEN** a page whose blocks are HERO and FAQ
|
||||
- **WHEN** it is saved with only a RICH_TEXT block
|
||||
- **THEN** the page has only that RICH_TEXT block
|
||||
|
||||
### Requirement: Page Fields Are Validated Server-Side
|
||||
|
||||
A page save SHALL be refused with the offending field path, writing nothing, when the slug does not match `^[a-z0-9]+(-[a-z0-9]+)*$`, is longer than 80 characters or is used by another page of the same company, ignoring case; or when the title is blank or longer than 120 characters; or when the meta description is longer than 160 characters.
|
||||
|
||||
#### Scenario: Duplicate slug in one company
|
||||
|
||||
- **GIVEN** INS has a page `hotel-technology`
|
||||
- **WHEN** INS staff save another page with slug `hotel-technology`
|
||||
- **THEN** the save is refused on field `slug`
|
||||
|
||||
#### Scenario: Same slug in two companies
|
||||
|
||||
- **GIVEN** INS has a page `about`
|
||||
- **WHEN** CV staff save a page with slug `about`
|
||||
- **THEN** the save succeeds
|
||||
|
||||
### Requirement: Block Fields Are Validated Server-Side
|
||||
|
||||
A page save SHALL be refused with the offending field path, writing nothing, when a block has an unknown type, a required field is blank, or a text exceeds its limit: heading 120, text and FAQ question 300, button label 40, FAQ answer 2000, HTML 100000 characters. A FAQ SHALL have 1 to 30 items. `imagePosition` SHALL be LEFT or RIGHT.
|
||||
|
||||
#### Scenario: Too many blocks
|
||||
|
||||
- **WHEN** a page is saved with 31 blocks
|
||||
- **THEN** the save is refused and nothing is written
|
||||
|
||||
### Requirement: Block References Stay Inside The Company
|
||||
|
||||
A block's image SHALL be an image of the page's company, and a FORM block's event SHALL be an event of the page's company. Otherwise the save SHALL be refused on that field.
|
||||
|
||||
#### Scenario: Another company's event
|
||||
|
||||
- **GIVEN** event `CV Roadshow` belongs to CV
|
||||
- **WHEN** INS staff save a FORM block pointing at `CV Roadshow`
|
||||
- **THEN** the save is refused on that block's event field
|
||||
|
||||
### Requirement: Page Content Cannot Run Scripts
|
||||
|
||||
A button SHALL have both a label and a link or neither. The link SHALL be a same-site path starting with a single `/`, an `https://` URL, a `mailto:` link or a `tel:` link. A save SHALL be refused when any HTML holds a `script` element, an `on*` attribute or a `javascript:` URL. The public page SHALL also sanitise all HTML against an allow-list before rendering it.
|
||||
|
||||
#### Scenario: Script link on a button
|
||||
|
||||
- **WHEN** a page is saved with a HERO button link `javascript:alert(1)`
|
||||
- **THEN** the save is refused on field `blocks[0].buttonUrl`
|
||||
|
||||
#### Scenario: Script in rich text
|
||||
|
||||
- **WHEN** a page is saved with rich text holding `<img src=x onerror=alert(1)>`
|
||||
- **THEN** the save is refused on that block's HTML field
|
||||
|
||||
### Requirement: Page Images
|
||||
|
||||
Staff with `BO_PAGES` SHALL upload images for their company in PNG, JPEG or WebP, each at most 2 MB, checked by the file's content and not by its name. Anyone SHALL be able to read an image by its id, so that public pages can show it.
|
||||
|
||||
#### Scenario: Wrong file type
|
||||
|
||||
- **WHEN** staff upload a PDF renamed to `banner.png`
|
||||
- **THEN** the upload is refused and nothing is stored
|
||||
|
||||
#### Scenario: Too large
|
||||
|
||||
- **WHEN** staff upload a 3 MB JPEG
|
||||
- **THEN** the upload is refused and nothing is stored
|
||||
|
||||
### Requirement: Company Branding
|
||||
|
||||
Each company SHALL have an optional logo, an image of that company, and an optional accent colour in `#RRGGBB` form. These SHALL be edited on the Companies screen. Its public pages SHALL show the logo in the header and use the accent colour on buttons, with black or white button text, whichever contrasts more. Without these, the pages SHALL use the neutral Co-Lite look.
|
||||
|
||||
#### Scenario: Accent colour
|
||||
|
||||
- **GIVEN** INS has accent colour `#0B5FFF`
|
||||
- **WHEN** a visitor opens an INS page
|
||||
- **THEN** its buttons are `#0B5FFF` with white text
|
||||
|
||||
#### Scenario: Invalid colour
|
||||
|
||||
- **WHEN** a super admin saves the accent colour `blue`
|
||||
- **THEN** the save is refused on that field
|
||||
|
||||
### Requirement: Public Page Address
|
||||
|
||||
A published page SHALL be public at `/p/<company-code>/<slug>`, matching the company code and the slug ignoring case. It SHALL be rendered on the server with the page title, the meta description and Open Graph tags. An unknown company, an unknown slug or a draft SHALL show the same not-found page to a visitor.
|
||||
|
||||
#### Scenario: Draft hidden from visitors
|
||||
|
||||
- **GIVEN** INS page `launch` is a draft
|
||||
- **WHEN** a signed-out visitor opens `/p/INS/launch`
|
||||
- **THEN** they see the not-found page
|
||||
|
||||
#### Scenario: Staff preview a draft
|
||||
|
||||
- **GIVEN** INS page `launch` is a draft
|
||||
- **WHEN** INS staff with `BO_PAGES` open its preview from the editor
|
||||
- **THEN** they see the page as it would be published, marked as a preview
|
||||
|
||||
### Requirement: The Form Block Registers For An Event
|
||||
|
||||
A FORM block SHALL show Co-Lite's sign-up form for its event, with that event's interests and the company's privacy notice. A submit SHALL follow the QR registration rules for matching, the existing-lead notes, consent and abuse limits. It SHALL create the event lead with source Web page and no salesperson, and SHALL record the page address and the `utm_source`, `utm_medium` and `utm_campaign` values from the page URL, each cut to 100 characters.
|
||||
|
||||
#### Scenario: New enquiry
|
||||
|
||||
- **GIVEN** page `/p/INS/hotel-technology` has a FORM block for `INS website enquiries`
|
||||
- **WHEN** a new visitor submits it from a URL with `utm_source=facebook`
|
||||
- **THEN** a new lead and an event lead with source Web page, no salesperson and UTM source `facebook` are created
|
||||
|
||||
#### Scenario: Known visitor
|
||||
|
||||
- **GIVEN** a lead with the same mobile exists in INS
|
||||
- **WHEN** they submit the form with a different email
|
||||
- **THEN** the lead is not edited, and the new email is written into the event lead's notes
|
||||
|
||||
### Requirement: The Form Block Closes With Its Event
|
||||
|
||||
A FORM block SHALL accept a submit only while its event is enabled, the event's end date in Malaysia time has not passed and the company has a privacy notice. Otherwise the page SHALL still show its other blocks, and the form area SHALL say that sign-up is closed.
|
||||
|
||||
#### Scenario: Ended event
|
||||
|
||||
- **GIVEN** the FORM block's event ended yesterday
|
||||
- **WHEN** a visitor opens the page
|
||||
- **THEN** the other blocks show and the form area says sign-up is closed
|
||||
|
||||
### Requirement: Web Sign-Up Details For Staff
|
||||
|
||||
The event lead detail SHALL show the page address and the UTM values of a Web page sign-up.
|
||||
|
||||
#### Scenario: Campaign shown
|
||||
|
||||
- **GIVEN** an event lead from a page opened with `utm_campaign=jan-launch`
|
||||
- **WHEN** staff open the event lead
|
||||
- **THEN** its detail shows the page address and campaign `jan-launch`
|
||||
|
||||
### Requirement: Pages Are Company-Scoped
|
||||
|
||||
Pages and page images SHALL follow the company scoping rules: staff see, edit and delete only their own company's pages, and a super admin sees every company's pages with their company. The Pages screens SHALL need `BO_PAGES`, which no role has at first. Page saves and deletes SHALL be audited.
|
||||
|
||||
#### Scenario: Another company's page
|
||||
|
||||
- **GIVEN** page 12 belongs to CV
|
||||
- **WHEN** INS staff ask for page 12
|
||||
- **THEN** they get not found
|
||||
|
||||
### Requirement: The Pages List
|
||||
|
||||
`/pages` SHALL list the pages in scope with their title, public address, status and last update, with a search by title or slug and an Add page action. Each row SHALL open its editor. 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`
|
||||
|
||||
### Requirement: The Page Editor
|
||||
|
||||
The editor SHALL offer the title, a slug filled from the title until edited, a meta description with a 160-character counter, the status and the block list. Blocks SHALL be added, moved up or down and removed. A chosen image SHALL be uploaded only when the page is saved. A FORM block SHALL pick from the company's enabled events that have not ended.
|
||||
|
||||
#### Scenario: Slug follows the title until edited
|
||||
|
||||
- **GIVEN** a new page
|
||||
- **WHEN** staff type the title "Hotel Technology"
|
||||
- **THEN** the slug becomes `hotel-technology`
|
||||
|
||||
### Requirement: Saving And Deleting In The Editor
|
||||
|
||||
Server field errors SHALL show next to their fields, keeping all entered values. After a save the editor SHALL offer a link to view the page. Deleting a page SHALL ask first, and unsaved edits SHALL be guarded.
|
||||
|
||||
#### Scenario: Server error at its field
|
||||
|
||||
- **WHEN** staff save a HERO button link `javascript:alert(1)`
|
||||
- **THEN** the error shows next to that button link and every entered value stays
|
||||
@@ -0,0 +1,286 @@
|
||||
# ui-translations Specification
|
||||
|
||||
## Purpose
|
||||
|
||||
Back-office labels load from a database message catalog per language, with English built in as the fallback. Staff can correct wording and add Chinese (zh_CN) translations on the Translations and Languages screens without a release.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: The Portal Shows Labels In The Chosen Language
|
||||
|
||||
The admin portal SHALL show every label in the language the user picked, read from the back-office message catalog. A label with no text in that language SHALL fall back to its English text, then to the portal's built-in English, and never show blank. The catalog read SHALL need no session, because the sign-in page shows labels too, and it SHALL return label text only.
|
||||
|
||||
#### Scenario: Chinese picked
|
||||
|
||||
- **GIVEN** the catalog has Chinese text for the label `Leads`
|
||||
- **WHEN** a signed-in user picks 简体中文
|
||||
- **THEN** the sidebar shows the Chinese text instead of "Leads"
|
||||
|
||||
#### Scenario: A label without Chinese
|
||||
|
||||
- **GIVEN** a label has English text in the catalog and no Chinese text
|
||||
- **WHEN** a user who picked 简体中文 opens a page with that label
|
||||
- **THEN** the label shows its English text
|
||||
|
||||
#### Scenario: Catalog unavailable
|
||||
|
||||
- **WHEN** the catalog cannot be read
|
||||
- **THEN** the portal shows the last catalog it loaded, or its built-in English if it has none
|
||||
- **AND** no label is blank
|
||||
|
||||
### Requirement: A Wording Change Shows On The Next Page Load
|
||||
|
||||
The system SHALL keep a catalog version that increases with every saved or imported label and every language change, within the same write. The portal SHALL check the version on each page load and reload the catalog when it has changed, on every portal instance, with no fixed waiting time.
|
||||
|
||||
#### Scenario: A label is edited
|
||||
|
||||
- **GIVEN** a user sees a label's Chinese text
|
||||
- **WHEN** a translator saves new Chinese text for that label
|
||||
- **THEN** the next page load shows the new text
|
||||
|
||||
#### Scenario: A refused save
|
||||
|
||||
- **WHEN** a label save or language change is refused
|
||||
- **THEN** the catalog version does not change
|
||||
|
||||
### Requirement: Supported Languages Are Kept In A Registry
|
||||
|
||||
The system SHALL keep the supported languages in a registry, each with a code that matches the catalog's language keys, a label, an enabled flag and an order. It SHALL start with English (`en_US`) and 简体中文 (`zh_CN`) enabled, and Bahasa Melayu (`ms_MY`), 繁體中文 (`zh_TW`) and Bahasa Indonesia (`in_ID`) disabled. The language picker SHALL list only enabled languages in their order, before and after sign-in. If the registry cannot be read, the picker SHALL offer English and 简体中文.
|
||||
|
||||
#### Scenario: Picker after rollout
|
||||
|
||||
- **WHEN** a user opens the language picker
|
||||
- **THEN** it lists English and 简体中文 only
|
||||
|
||||
#### Scenario: A language is enabled
|
||||
|
||||
- **WHEN** an admin enables Bahasa Melayu on the Languages page
|
||||
- **THEN** the picker lists it on the next page load, with no redeploy
|
||||
|
||||
#### Scenario: Registry unavailable
|
||||
|
||||
- **WHEN** the language list cannot be read
|
||||
- **THEN** the picker lists English and 简体中文
|
||||
|
||||
### Requirement: A Language Change Cannot Break The Registry
|
||||
|
||||
The system SHALL refuse:
|
||||
- a new language whose code already exists;
|
||||
- a change of a language's code;
|
||||
- switching English off;
|
||||
- switching off the last enabled language.
|
||||
|
||||
Each refusal SHALL leave the registry unchanged and SHALL reach the user as a named reason, not a generic error.
|
||||
|
||||
#### Scenario: Duplicate code
|
||||
|
||||
- **WHEN** an admin adds a language with the code `zh_CN`
|
||||
- **THEN** it is refused and the page says the code already exists
|
||||
|
||||
#### Scenario: English cannot be switched off
|
||||
|
||||
- **WHEN** the Languages page lists English
|
||||
- **THEN** its switch is disabled and the page says why
|
||||
- **AND** a direct request to disable English is refused
|
||||
|
||||
#### Scenario: Last enabled language
|
||||
|
||||
- **GIVEN** only one language is enabled
|
||||
- **WHEN** a request disables it
|
||||
- **THEN** it is refused
|
||||
|
||||
### Requirement: The Languages Page
|
||||
|
||||
The portal SHALL provide a Languages page at `/locales` that lists every language with its code, label, order and an enabled switch. It SHALL let the user add a language and edit a label and order. The code SHALL be editable only when adding. Switching a language off SHALL ask for confirmation first. Refusals SHALL show on the page.
|
||||
|
||||
#### Scenario: Switching a language off asks first
|
||||
|
||||
- **WHEN** a user switches 简体中文 off
|
||||
- **THEN** a confirmation is shown
|
||||
- **AND** nothing changes unless the user confirms
|
||||
|
||||
#### Scenario: Code read-only when editing
|
||||
|
||||
- **WHEN** a user edits an existing language
|
||||
- **THEN** its code is shown read-only
|
||||
|
||||
### Requirement: The Translations Page Lists And Finds Back-Office Labels
|
||||
|
||||
The portal SHALL provide a Translations page at `/messages` listing the back-office labels in pages, each with its code, English text and Chinese text. The search SHALL match the code, the English text or the Chinese text, ignoring case. A "Missing Chinese" filter SHALL list labels whose Chinese text is absent, blank or the same as the English text. Each such label SHALL be marked with a text badge, not colour alone. The page SHALL offer no way to add or delete a label.
|
||||
|
||||
#### Scenario: Search by Chinese wording
|
||||
|
||||
- **GIVEN** a label whose Chinese text contains "线索"
|
||||
- **WHEN** the user searches "线索"
|
||||
- **THEN** that label is listed
|
||||
|
||||
#### Scenario: Copied English counts as missing
|
||||
|
||||
- **GIVEN** a label whose English and Chinese text are both "WhatsApp"
|
||||
- **WHEN** the user turns on "Missing Chinese"
|
||||
- **THEN** that label is listed with a badge that says why
|
||||
|
||||
#### Scenario: No add or delete
|
||||
|
||||
- **WHEN** the Translations page and its row actions are inspected
|
||||
- **THEN** there is no add and no delete action
|
||||
|
||||
### Requirement: Editing A Translation
|
||||
|
||||
Opening a label SHALL show an edit panel with one multi-line field per enabled language and the code read-only. Closing it with unsaved changes SHALL ask before discarding them. The server SHALL refuse a save that changes a label's code, or that creates a label whose code already exists ignoring case. Label text SHALL always be shown as text, never as markup.
|
||||
|
||||
#### Scenario: Unsaved edits
|
||||
|
||||
- **WHEN** the user changes a field and closes the panel
|
||||
- **THEN** the panel asks before discarding the change
|
||||
|
||||
#### Scenario: Code change refused
|
||||
|
||||
- **WHEN** a save request changes an existing label's code
|
||||
- **THEN** it is refused and the label is unchanged
|
||||
|
||||
#### Scenario: Markup is shown as text
|
||||
|
||||
- **GIVEN** a translator saves `<b>Leads</b>` as a label's Chinese text
|
||||
- **WHEN** a page shows that label
|
||||
- **THEN** the angle brackets show as text and nothing is bold
|
||||
|
||||
### Requirement: Placeholders Are Kept In Translations
|
||||
|
||||
Each non-English text SHALL keep the same placeholders as the English text, in the `{name}` and `{0}` forms. When an edit creates a mismatch, the edit panel SHALL name the missing or extra placeholders and block Save. When the label was mismatched before the edit, it SHALL warn without blocking.
|
||||
|
||||
#### Scenario: A new placeholder mismatch blocks Save
|
||||
|
||||
- **GIVEN** a label whose English is "{n} unread" and Chinese is "{n} 条未读"
|
||||
- **WHEN** the user changes the Chinese to "条未读"
|
||||
- **THEN** the panel names `{n}` as missing
|
||||
- **AND** Save is disabled
|
||||
|
||||
#### Scenario: An old mismatch only warns
|
||||
|
||||
- **GIVEN** a label whose English is "{n} unread" and Chinese is "未读"
|
||||
- **WHEN** the user edits the English
|
||||
- **THEN** the panel warns that `{n}` is missing in Chinese
|
||||
- **AND** Save stays enabled
|
||||
|
||||
### Requirement: Translations Export
|
||||
|
||||
The Translations page SHALL export every back-office label, with the text in every language, as a JSON file download, without leaving the page.
|
||||
|
||||
#### Scenario: Export downloads
|
||||
|
||||
- **WHEN** the user clicks Export
|
||||
- **THEN** the browser offers a JSON file with every back-office label
|
||||
- **AND** the page stays on `/messages`
|
||||
|
||||
### Requirement: Translations Import With A Preview
|
||||
|
||||
The Translations page SHALL import a file in the export shape. It SHALL first show a preview that marks each row as an update, matched by code ignoring case and never by an id in the file, or as a new label. It SHALL apply nothing until the user confirms. A file that is not a JSON list SHALL be rejected on the page without sending anything. Each row SHALL be saved on its own, and a summary SHALL show the counts created and updated and name the failed rows.
|
||||
|
||||
#### Scenario: Preview before import
|
||||
|
||||
- **WHEN** the user picks an export file
|
||||
- **THEN** the page lists every row as an update or a new label
|
||||
- **AND** nothing is saved until the user confirms
|
||||
|
||||
#### Scenario: Matched by code
|
||||
|
||||
- **GIVEN** a file row with code `leads` and the id of another label
|
||||
- **AND** the catalog holds the label `Leads`
|
||||
- **WHEN** the file is imported
|
||||
- **THEN** the `Leads` label is updated
|
||||
|
||||
#### Scenario: Not a list
|
||||
|
||||
- **WHEN** the user picks a file that is not a JSON list
|
||||
- **THEN** the page shows an error and sends nothing
|
||||
|
||||
#### Scenario: One bad row
|
||||
|
||||
- **WHEN** an import has one row that fails and others that succeed
|
||||
- **THEN** the other rows are saved
|
||||
- **AND** the summary names the failed row
|
||||
|
||||
### Requirement: Access To Translations And Languages
|
||||
|
||||
The Translations page SHALL require `BO_MESSAGES` and the Languages page `BO_LOCALES`, checked on the server for every list, detail, export and write, with a signed-in admin. Both modules SHALL be granted to no role, so only super admins have them until a super admin grants them. Saves, imports, exports and language changes SHALL be audited.
|
||||
|
||||
#### Scenario: Without the module
|
||||
|
||||
- **WHEN** a staff user without `BO_MESSAGES` opens `/messages`
|
||||
- **THEN** the not-authorised page is shown
|
||||
- **AND** a direct save request is refused
|
||||
|
||||
#### Scenario: A save is audited
|
||||
|
||||
- **WHEN** a super admin saves a translation
|
||||
- **THEN** the audit log records who saved which label
|
||||
|
||||
### Requirement: Internal Catalog Writes Need A Token
|
||||
|
||||
Inside the system, message and language writes and full listings SHALL need a user token. Only the catalog, its version and the enabled-language list SHALL be readable without one.
|
||||
|
||||
#### Scenario: Internal write without a token
|
||||
|
||||
- **WHEN** a request without a user token tries to save a message or language inside the system
|
||||
- **THEN** it is refused
|
||||
|
||||
#### Scenario: Catalog read without a token
|
||||
|
||||
- **WHEN** the sign-in page loads the catalog without a session
|
||||
- **THEN** the catalog is returned
|
||||
|
||||
### Requirement: Every Back-Office Label Has Chinese
|
||||
|
||||
Every back-office label SHALL have Simplified Chinese text with the same placeholders as its English, using one consistent glossary, as a first pass for a native speaker to review. Every new back-office label SHALL ship with its Chinese text.
|
||||
|
||||
#### Scenario: Back office in Chinese
|
||||
|
||||
- **WHEN** a user picks 简体中文 and opens any back-office page
|
||||
- **THEN** every label on it shows Chinese text
|
||||
|
||||
#### Scenario: A new label without Chinese
|
||||
|
||||
- **WHEN** a developer adds a back-office label with no Chinese text
|
||||
- **THEN** the portal's tests fail and name the label
|
||||
|
||||
### Requirement: Loading The Chinese Keeps English Unchanged
|
||||
|
||||
Loading the Chinese SHALL replace earlier Chinese for the back-office labels, leave other languages unchanged, and add missing labels with their English. It SHALL reset the English of any label whose old database text differs from the portal's English, so nobody who keeps English sees a change.
|
||||
|
||||
#### Scenario: English unchanged
|
||||
|
||||
- **GIVEN** the old database English for the sign-in button is "Login"
|
||||
- **WHEN** the Chinese is loaded and a user who keeps English opens the sign-in page
|
||||
- **THEN** the button reads "Log in"
|
||||
|
||||
### Requirement: Translations Can Be Limited To Co-Lite Labels
|
||||
|
||||
The Translations page SHALL offer a "Co-Lite labels only" checkbox, on by default, that limits the list, the search and the "Missing Chinese" filter to the labels in the portal's built-in English list. Codes SHALL match ignoring case. Turning the checkbox off SHALL list every back-office label.
|
||||
|
||||
#### Scenario: Inherited labels hidden by default
|
||||
|
||||
- **GIVEN** a back-office label "OrderPayment" that is not in the portal's built-in list, and a label "Leads" that is
|
||||
- **WHEN** the user opens the Translations page
|
||||
- **THEN** "Leads" is listed and "OrderPayment" is not
|
||||
- **AND** "Co-Lite labels only" is checked
|
||||
|
||||
#### Scenario: Missing Chinese counts only Co-Lite labels
|
||||
|
||||
- **GIVEN** every label in the built-in list has Chinese and some inherited labels have none
|
||||
- **WHEN** the user turns on "Missing Chinese" with "Co-Lite labels only" checked
|
||||
- **THEN** no label is listed
|
||||
|
||||
#### Scenario: Every label on request
|
||||
|
||||
- **WHEN** the user unchecks "Co-Lite labels only"
|
||||
- **THEN** "OrderPayment" is listed too
|
||||
|
||||
### Requirement: The Co-Lite Code List Comes From The Portal Server
|
||||
|
||||
The portal's server SHALL build the Co-Lite code list from its built-in list and SHALL NOT take codes from the browser. mobile-api SHALL refuse with 400 a code list that is not a list of strings or holds more than 5,000 entries. Export and import SHALL keep covering every back-office label.
|
||||
|
||||
#### Scenario: Code list too long
|
||||
|
||||
- **WHEN** mobile-api receives a search with 5,001 codes
|
||||
- **THEN** it answers 400 and does not call services-system
|
||||
@@ -0,0 +1,211 @@
|
||||
# whatsapp-inbox Specification
|
||||
|
||||
## Purpose
|
||||
|
||||
A two-way WhatsApp inbox inside Co-Lite on each company's business number. Sales staff follow up leads from the back office, every message is recorded, and any colleague with access can pick up a chat.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Company WhatsApp settings
|
||||
|
||||
The system SHALL read each company's WhatsApp number id, business account id, access token and app secret from the environment, and SHALL never store or log them. A company without complete settings SHALL have WhatsApp switched off. Its inbox SHALL say "WhatsApp is not configured", and the rest of the system SHALL keep working.
|
||||
|
||||
#### Scenario: Company not configured
|
||||
|
||||
- **GIVEN** CV has no WhatsApp settings
|
||||
- **WHEN** a CV admin with `BO_WHATSAPP` opens the inbox
|
||||
- **THEN** the page says "WhatsApp is not configured" and offers no composer
|
||||
|
||||
### Requirement: Webhook handshake
|
||||
|
||||
The public webhook SHALL answer Meta's subscription check with the given challenge only when the verify token matches the configured one. Otherwise it SHALL answer 403.
|
||||
|
||||
#### Scenario: Wrong verify token
|
||||
|
||||
- **WHEN** a subscription check arrives with a verify token that does not match
|
||||
- **THEN** the webhook answers 403 and does not echo the challenge
|
||||
|
||||
### Requirement: Webhook signature
|
||||
|
||||
The webhook SHALL accept an event only when its `X-Hub-Signature-256` header is a valid HMAC-SHA256 of the raw body under the app secret of the company the event's number belongs to. A missing or invalid signature SHALL get 401, and nothing SHALL be stored.
|
||||
|
||||
#### Scenario: Forged event
|
||||
|
||||
- **WHEN** an event for INS's number arrives without a valid signature
|
||||
- **THEN** the webhook answers 401 and no message is stored
|
||||
|
||||
#### Scenario: Signed with the other company's secret
|
||||
|
||||
- **GIVEN** INS and CV have different app secrets
|
||||
- **WHEN** an event for INS's number is signed with CV's app secret
|
||||
- **THEN** the event is rejected and no message is stored
|
||||
|
||||
### Requirement: Inbound messages
|
||||
|
||||
An accepted inbound message SHALL be stored once, in the conversation of the company that owns the receiving number, for the sender's WhatsApp number. Meta redelivering the same message id SHALL NOT create a second message. An event for a number no company owns SHALL be dropped. An event the inbox cannot take yet (the service is down, or the company of a configured number is not known yet) SHALL be refused, so that Meta redelivers it. Receiving a message SHALL open the 24-hour reply window.
|
||||
|
||||
#### Scenario: Lead writes to INS
|
||||
|
||||
- **GIVEN** INS lead Aisyah has mobile `+60123456701`
|
||||
- **WHEN** she sends "Hi, about the expo" to INS's number
|
||||
- **THEN** an INS conversation for `60123456701` holds the message, linked to Aisyah's lead
|
||||
- **AND** no CV user can see it
|
||||
|
||||
#### Scenario: Redelivery
|
||||
|
||||
- **WHEN** Meta delivers the same message id twice
|
||||
- **THEN** the conversation holds the message once
|
||||
|
||||
#### Scenario: Inbox not ready
|
||||
|
||||
- **GIVEN** the WhatsApp service has just started and cannot reach the system service yet
|
||||
- **WHEN** Meta delivers a message to INS's number
|
||||
- **THEN** the webhook answers 503 and stores nothing
|
||||
- **AND** when Meta redelivers after the service has resolved INS, the message is stored once
|
||||
|
||||
### Requirement: Delivery status
|
||||
|
||||
The status of a sent message SHALL move only forward, from pending to sent to delivered to read, except that failed SHALL be recorded at any point, together with Meta's error code and title. The thread SHALL show the status as ticks, or as a failure with its reason.
|
||||
|
||||
#### Scenario: Late delivered after read
|
||||
|
||||
- **WHEN** a "read" status arrives and then a "delivered" status arrives for the same message
|
||||
- **THEN** the message stays "read"
|
||||
|
||||
#### Scenario: Send failed
|
||||
|
||||
- **WHEN** Meta rejects a sent message
|
||||
- **THEN** the thread shows the message as failed with Meta's error title
|
||||
|
||||
### Requirement: Automatic ownership
|
||||
|
||||
A conversation without a manual owner SHALL be owned by the lead's latest salesperson (the salesperson of its most recently captured event lead that has one) when that user is active and holds `BO_WHATSAPP`. Otherwise the current owner SHALL be kept while still active with `BO_WHATSAPP`, and the conversation SHALL be unassigned when not. Ownership SHALL be recomputed when the conversation is created and when an event lead of that lead is captured or changes salesperson.
|
||||
|
||||
#### Scenario: Chat follows the latest salesperson
|
||||
|
||||
- **GIVEN** Aisyah's latest event lead has salesperson `sales1`, who holds `BO_WHATSAPP`
|
||||
- **WHEN** Aisyah writes for the first time
|
||||
- **THEN** the conversation is owned by `sales1`
|
||||
|
||||
#### Scenario: Latest event has no salesperson
|
||||
|
||||
- **GIVEN** a conversation owned by `sales1`
|
||||
- **WHEN** Aisyah is captured at a new event without a salesperson
|
||||
- **THEN** the conversation stays with `sales1`
|
||||
|
||||
#### Scenario: Salesperson without WhatsApp access
|
||||
|
||||
- **GIVEN** Aisyah's latest salesperson `sales2` does not hold `BO_WHATSAPP` and the conversation has no owner
|
||||
- **WHEN** ownership is recomputed
|
||||
- **THEN** the conversation is unassigned
|
||||
|
||||
#### Scenario: Unknown sender
|
||||
|
||||
- **WHEN** a number with no lead in INS writes to INS
|
||||
- **THEN** an unassigned conversation without a lead link is created
|
||||
|
||||
### Requirement: Manual assignment
|
||||
|
||||
A WhatsApp Admin SHALL be able to assign a conversation of their company to any active user of that company who holds `BO_WHATSAPP`, including themselves. A manual owner SHALL NOT change when event leads change. "Return to automatic" SHALL clear the manual owner and recompute it.
|
||||
|
||||
#### Scenario: Manual owner sticks
|
||||
|
||||
- **GIVEN** a WhatsApp Admin assigned Aisyah's conversation to `sales3`
|
||||
- **WHEN** Aisyah is captured at a new event with salesperson `sales1`
|
||||
- **THEN** the conversation stays with `sales3`
|
||||
|
||||
#### Scenario: Owner outside WhatsApp
|
||||
|
||||
- **WHEN** a WhatsApp Admin tries to assign a conversation to a user without `BO_WHATSAPP`
|
||||
- **THEN** the request is refused and the owner does not change
|
||||
|
||||
### Requirement: Owner loses access
|
||||
|
||||
When a user is disabled, or their roles no longer grant `BO_WHATSAPP`, the system SHALL make their conversations unassigned and clear any manual assignment. A user locked out by failed logins SHALL keep their conversations.
|
||||
|
||||
#### Scenario: Owner disabled
|
||||
|
||||
- **GIVEN** `sales1` owns three conversations
|
||||
- **WHEN** an admin disables `sales1`
|
||||
- **THEN** the three conversations are unassigned
|
||||
|
||||
### Requirement: Inbox access
|
||||
|
||||
A user with `BO_WHATSAPP` SHALL see, read and reply only in conversations they own. A user with `BO_WHATSAPP_ADMIN` SHALL see every conversation of their company, including unassigned ones, and SHALL be able to read and reply in any of them. A super admin SHALL see the conversations of every company. Every request SHALL be limited to the caller's company, and SHALL fail closed when the caller's company cannot be determined.
|
||||
|
||||
#### Scenario: Staff opens someone else's chat
|
||||
|
||||
- **WHEN** `sales1` requests a conversation owned by `sales3`
|
||||
- **THEN** the request answers 404
|
||||
|
||||
#### Scenario: WhatsApp Admin sees the queue
|
||||
|
||||
- **WHEN** an INS WhatsApp Admin opens the Unassigned tab
|
||||
- **THEN** it lists INS's unassigned conversations and none of CV's
|
||||
|
||||
### Requirement: Replies inside the 24-hour window
|
||||
|
||||
A user SHALL be able to send a text message only while less than 24 hours have passed since the contact's last inbound message. Outside the window a text send SHALL be refused with "The 24-hour window has closed. Send a template." The composer SHALL show the window's state and offer only templates when the window is closed.
|
||||
|
||||
#### Scenario: Window closed
|
||||
|
||||
- **GIVEN** Aisyah last wrote 25 hours ago
|
||||
- **WHEN** `sales1` sends a text reply
|
||||
- **THEN** it is refused and nothing is sent to Meta
|
||||
|
||||
### Requirement: Templates
|
||||
|
||||
A WhatsApp Admin SHALL be able to sync a company's approved templates from that company's business account, and the system SHALL also sync them nightly. Staff SHALL be able to send a synced template with every body parameter filled, inside or outside the window. Templates whose header or buttons need parameters SHALL be listed as not supported and SHALL NOT be sendable.
|
||||
|
||||
#### Scenario: Missing parameter
|
||||
|
||||
- **WHEN** a user sends template `expo_followup` with one of its two parameters empty
|
||||
- **THEN** it is refused and nothing is sent to Meta
|
||||
|
||||
### Requirement: Starting a chat from a lead
|
||||
|
||||
A user with `BO_WHATSAPP` SHALL be able to start a chat from a lead or event lead that has a mobile number, in that lead's company. If the conversation has no owner it SHALL become the starter's as a manual assignment. If another user owns it, the starter SHALL be told who owns it. Until the contact replies, only templates SHALL be offered.
|
||||
|
||||
#### Scenario: Start an unowned chat
|
||||
|
||||
- **GIVEN** Aisyah has no conversation yet and no salesperson with WhatsApp
|
||||
- **WHEN** `sales1` presses WhatsApp on her event lead
|
||||
- **THEN** a conversation owned by `sales1` opens with the template composer
|
||||
|
||||
### Requirement: Incoming media
|
||||
|
||||
Incoming images, documents, audio, video, stickers and locations SHALL be shown in the thread. Media SHALL be fetched from Meta only when a user with access opens it. Media that Meta no longer holds SHALL show "Media expired".
|
||||
|
||||
#### Scenario: Image opened by someone without access
|
||||
|
||||
- **WHEN** a user who cannot see the conversation requests one of its images
|
||||
- **THEN** the request answers 404
|
||||
|
||||
### Requirement: Unread counts
|
||||
|
||||
The system SHALL track, per user, the last message they read in each conversation they can see. It SHALL show unread conversations in the list and the number of unread conversations as a badge on the sidebar's inbox item.
|
||||
|
||||
#### Scenario: Reading clears the badge
|
||||
|
||||
- **GIVEN** `sales1` has one unread conversation
|
||||
- **WHEN** `sales1` opens it
|
||||
- **THEN** the sidebar badge clears
|
||||
|
||||
### Requirement: WhatsApp audit and privacy
|
||||
|
||||
Sending a message, reassigning a conversation and syncing templates SHALL be recorded in the audit log with the conversation and template names but not the message text. Message text, phone numbers, media, tokens and signatures SHALL NOT be written to application logs.
|
||||
|
||||
#### Scenario: Template send audited
|
||||
|
||||
- **WHEN** `sales1` sends template `expo_followup`
|
||||
- **THEN** the audit log records the send by `sales1` with the conversation and template name
|
||||
- **AND** not the filled-in text
|
||||
|
||||
### Requirement: Local Meta stand-in
|
||||
|
||||
The local stack SHALL include a test-only stand-in for Meta's API. It SHALL accept sends, serve templates and media, and post signed inbound events to the webhook on request, so the inbox can be developed and tested without a Meta account. The stand-in SHALL NOT be part of any release.
|
||||
|
||||
#### Scenario: Simulated inbound message
|
||||
|
||||
- **WHEN** a developer asks the stand-in to deliver "Hello" from `+60123456701` to INS's number
|
||||
- **THEN** the INS inbox shows the message within one polling interval
|
||||
@@ -0,0 +1,14 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
|
||||
export async function POST(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { id } = await params;
|
||||
if (!/^\d+$/.test(id)) return badRequest("A numeric notification id is required.");
|
||||
const result = await callMobileApi<unknown>(`/api/admin/notifications/${encodeURIComponent(id)}/read`, { method: "POST", token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { NextResponse } 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";
|
||||
|
||||
export async function POST() {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const result = await callMobileApi<{ count: number }>("/api/admin/notifications/read-all", { method: "POST", token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
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";
|
||||
|
||||
// GET -> /api/admin/notifications: the signed-in user's own inbox, newest first. Side-effect free.
|
||||
export async function GET(req: NextRequest) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const params = new URL(req.url).searchParams;
|
||||
const qs = new URLSearchParams();
|
||||
for (const k of ["page", "size"]) {
|
||||
const v = params.get(k);
|
||||
if (v && /^\d+$/.test(v)) qs.set(k, v);
|
||||
}
|
||||
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/notifications?${qs.toString()}`, { token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
|
||||
|
||||
import * as list from "./route";
|
||||
import * as count from "./unread-count/route";
|
||||
import * as readAll from "./read-all/route";
|
||||
import * as readOne from "./[id]/read/route";
|
||||
|
||||
type Req = Parameters<typeof list.GET>[0];
|
||||
const req = (url: string, init: RequestInit = {}) => new Request(`http://localhost${url}`, init) as unknown as Req;
|
||||
const ctx = (id: string) => ({ params: Promise.resolve({ id }) });
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.getToken.mockResolvedValue("jwt");
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { items: [], total: 0 } });
|
||||
});
|
||||
|
||||
// add-lead-notifications: the bell's routes only ever act on the signed-in user's own notifications.
|
||||
describe("notification routes", () => {
|
||||
it("refuse without a session", async () => {
|
||||
mocks.getToken.mockResolvedValue(null);
|
||||
expect((await list.GET(req("/api/notifications"))).status).toBe(401);
|
||||
expect((await count.GET()).status).toBe(401);
|
||||
expect((await readAll.POST()).status).toBe(401);
|
||||
expect((await readOne.POST(req("/api/notifications/1/read", { method: "POST" }), ctx("1"))).status).toBe(401);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("list forwards only numeric page and size", async () => {
|
||||
const res = await list.GET(req("/api/notifications?page=2&size=10&receiver=9&x=1"));
|
||||
expect(res.status).toBe(200);
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/notifications?page=2&size=10", { token: "jwt" });
|
||||
|
||||
await list.GET(req("/api/notifications?page=-1&size=abc"));
|
||||
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/notifications?", { token: "jwt" });
|
||||
});
|
||||
|
||||
it("unread count and read-all call mobile-api", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { count: 3 } });
|
||||
expect(await (await count.GET()).json()).toEqual({ count: 3 });
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/notifications/unread-count", { token: "jwt" });
|
||||
|
||||
await readAll.POST();
|
||||
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/notifications/read-all", { method: "POST", token: "jwt" });
|
||||
});
|
||||
|
||||
it("mark read takes a numeric id only and answers 204", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: undefined });
|
||||
const ok = await readOne.POST(req("/api/notifications/42/read", { method: "POST" }), ctx("42"));
|
||||
expect(ok.status).toBe(204);
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/notifications/42/read", { method: "POST", token: "jwt" });
|
||||
|
||||
mocks.callMobileApi.mockClear();
|
||||
const bad = await readOne.POST(req("/api/notifications/..%2Fx/read", { method: "POST" }), ctx("../x"));
|
||||
expect(bad.status).toBe(400);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("pass an upstream failure through", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Not found", status: 404 });
|
||||
const res = await readOne.POST(req("/api/notifications/7/read", { method: "POST" }), ctx("7"));
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import { NextResponse } 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";
|
||||
|
||||
export async function GET() {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const result = await callMobileApi<{ count: number }>("/api/admin/notifications/unread-count", { token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -16,7 +16,7 @@ export default function CompanyPicker() {
|
||||
if (!isSuper) return null;
|
||||
return (
|
||||
<Select value={companyId === undefined ? ALL : String(companyId)} onValueChange={(v) => setCompanyId(v === ALL ? undefined : Number(v))}>
|
||||
<SelectTrigger aria-label={t("Company")} className="min-w-36">
|
||||
<SelectTrigger aria-label={t("Company")} className="max-w-28 sm:max-w-none sm:min-w-36">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
|
||||
@@ -23,6 +23,7 @@ import CompanyPicker from "./CompanyPicker";
|
||||
import { clearStoredCompany } from "@/app/lib/CompanyScope";
|
||||
import LocaleSwitcher from "./LocaleSwitcher";
|
||||
import ChangePasswordDialog from "./ChangePasswordDialog";
|
||||
import NotificationsBell from "./NotificationsBell";
|
||||
|
||||
// The authenticated shell's header: user menu reads the signed-in name from
|
||||
// AdminAuthContext (session hydration, Task 5), and logout calls the
|
||||
@@ -75,9 +76,10 @@ export default function Header() {
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
<Breadcrumbs />
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<div className="ml-auto flex items-center gap-1 sm:gap-2">
|
||||
<CompanyPicker />
|
||||
<LocaleSwitcher />
|
||||
<NotificationsBell />
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const svc = vi.hoisted(() => ({
|
||||
getUnreadCount: vi.fn(),
|
||||
listNotifications: vi.fn(),
|
||||
markRead: vi.fn(),
|
||||
markAllRead: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/notifications", async (orig) => ({
|
||||
...(await orig<typeof import("@/app/lib/services/notifications")>()),
|
||||
...svc,
|
||||
}));
|
||||
|
||||
import NotificationsBell from "./NotificationsBell";
|
||||
|
||||
const row = (id: number, seen: boolean, link: string | null = `/leads/${id}`) => ({
|
||||
id, title: "NoticeLeadAssigned", type: "LEAD_ASSIGNED", link, seen, createDateTime: "2026-12-02T09:00:00",
|
||||
message: '{"code":"NoticeLeadBody","params":{"lead":"Ali","event":"Expo"}}',
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
svc.getUnreadCount.mockResolvedValue(2);
|
||||
svc.listNotifications.mockResolvedValue({ items: [row(1, false), row(2, false), row(3, true)], total: 3 });
|
||||
svc.markRead.mockResolvedValue(undefined);
|
||||
svc.markAllRead.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
// add-lead-notifications: the header bell.
|
||||
describe("NotificationsBell", () => {
|
||||
it("shows the unread count from the server", async () => {
|
||||
render(<NotificationsBell />);
|
||||
expect(await screen.findByText("2")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: /2 unread/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("opening it lists the newest 10 in the reader's language and marks the unread ones read", async () => {
|
||||
render(<NotificationsBell />);
|
||||
await screen.findByText("2");
|
||||
svc.getUnreadCount.mockResolvedValue(0);
|
||||
await userEvent.click(screen.getByRole("button", { name: /notifications/i }));
|
||||
|
||||
expect(svc.listNotifications).toHaveBeenCalledWith(0, 10);
|
||||
expect(await screen.findAllByText("Lead assigned to you")).toHaveLength(3);
|
||||
expect(screen.getAllByText("Ali · Expo")).toHaveLength(3);
|
||||
await waitFor(() => expect(svc.markRead).toHaveBeenCalledTimes(2));
|
||||
expect(svc.markRead).toHaveBeenCalledWith(1);
|
||||
expect(svc.markRead).toHaveBeenCalledWith(2);
|
||||
await waitFor(() => expect(screen.queryByText("2")).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it("each item links to its target, and only to a path on this site", async () => {
|
||||
svc.listNotifications.mockResolvedValue({ items: [row(1, true), row(2, true, "//evil.example")], total: 2 });
|
||||
render(<NotificationsBell />);
|
||||
await userEvent.click(await screen.findByRole("button", { name: /notifications/i }));
|
||||
|
||||
const items = await screen.findAllByRole("menuitem", { name: /Lead assigned to you/ });
|
||||
expect(items[0]).toHaveAttribute("href", "/leads/1");
|
||||
expect(items[1]).not.toHaveAttribute("href");
|
||||
expect(screen.getByRole("menuitem", { name: /see all/i })).toHaveAttribute("href", "/notifications");
|
||||
});
|
||||
|
||||
it("says so when there are none, or when loading fails", async () => {
|
||||
svc.listNotifications.mockResolvedValue({ items: [], total: 0 });
|
||||
const { unmount } = render(<NotificationsBell />);
|
||||
await userEvent.click(await screen.findByRole("button", { name: /notifications/i }));
|
||||
expect(await screen.findByText("No notifications yet.")).toBeInTheDocument();
|
||||
unmount();
|
||||
|
||||
svc.listNotifications.mockRejectedValue(new Error("down"));
|
||||
render(<NotificationsBell />);
|
||||
await userEvent.click(await screen.findByRole("button", { name: /notifications/i }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Couldn't load notifications.");
|
||||
});
|
||||
|
||||
it("recounts at once when another screen changes read state", async () => {
|
||||
render(<NotificationsBell />);
|
||||
await screen.findByText("2");
|
||||
svc.getUnreadCount.mockResolvedValue(0);
|
||||
|
||||
window.dispatchEvent(new Event("notifications:changed"));
|
||||
|
||||
await waitFor(() => expect(screen.queryByText("2")).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it("a failing unread count leaves the bell quiet instead of breaking the header", async () => {
|
||||
svc.getUnreadCount.mockRejectedValue(new Error("down"));
|
||||
render(<NotificationsBell />);
|
||||
expect(await screen.findByRole("button", { name: /notifications/i })).toBeInTheDocument();
|
||||
expect(screen.queryByText("0")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Bell } from "lucide-react";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/app/components/ui/dropdown-menu";
|
||||
import { useLocale, useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { usePolling } from "@/app/lib/hooks/usePolling";
|
||||
import {
|
||||
getUnreadCount,
|
||||
isSitePath,
|
||||
listNotifications,
|
||||
markAllRead,
|
||||
markRead,
|
||||
NOTIFICATIONS_CHANGED,
|
||||
noticeText,
|
||||
noticeTime,
|
||||
type AdminNotification,
|
||||
} from "@/app/lib/services/notifications";
|
||||
|
||||
const POLL_MS = 30_000;
|
||||
|
||||
// add-lead-notifications: the header bell. The unread count polls while the tab is visible; opening the menu loads
|
||||
// the newest 10 and marks the unread ones read (read state lives on the server, so it follows the user).
|
||||
export default function NotificationsBell() {
|
||||
const t = useT();
|
||||
const locale = useLocale();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [unread, setUnread] = useState(0);
|
||||
const [items, setItems] = useState<AdminNotification[] | null>(null);
|
||||
const [failed, setFailed] = useState(false);
|
||||
|
||||
const refreshCount = () => getUnreadCount().then(setUnread).catch(() => {});
|
||||
usePolling(refreshCount, POLL_MS, NOTIFICATIONS_CHANGED, !open);
|
||||
|
||||
async function onOpenChange(next: boolean) {
|
||||
setOpen(next);
|
||||
if (!next) return;
|
||||
setItems(null);
|
||||
setFailed(false);
|
||||
try {
|
||||
const page = await listNotifications(0, 10);
|
||||
setItems(page.items);
|
||||
const unseen = page.items.filter((i) => !i.seen).map((i) => i.id);
|
||||
if (unseen.length) {
|
||||
await Promise.allSettled(unseen.map((id) => markRead(id)));
|
||||
await refreshCount();
|
||||
}
|
||||
} catch {
|
||||
setFailed(true);
|
||||
}
|
||||
}
|
||||
|
||||
async function onMarkAll() {
|
||||
await markAllRead().catch(() => {});
|
||||
setItems((list) => list?.map((i) => ({ ...i, seen: true })) ?? list);
|
||||
await refreshCount();
|
||||
}
|
||||
|
||||
const when = (iso: string) => noticeTime(iso, locale);
|
||||
|
||||
return (
|
||||
<DropdownMenu open={open} onOpenChange={onOpenChange}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="relative size-9"
|
||||
aria-label={unread > 0 ? t("NotificationsUnread", { count: unread }) : t("NotificationsTitle")}
|
||||
>
|
||||
<Bell aria-hidden="true" className="size-4" />
|
||||
{unread > 0 && (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="absolute -top-0.5 -right-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-destructive px-1 text-[10px] leading-none font-semibold text-destructive-foreground"
|
||||
>
|
||||
{unread > 99 ? "99+" : unread}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-80 max-w-[calc(100vw-2rem)]">
|
||||
<div className="flex items-center justify-between gap-2 pr-1">
|
||||
<DropdownMenuLabel>{t("NotificationsTitle")}</DropdownMenuLabel>
|
||||
<Button variant="link" size="sm" className="h-auto p-0 text-xs" onClick={onMarkAll}>
|
||||
{t("NotificationsMarkAllRead")}
|
||||
</Button>
|
||||
</div>
|
||||
<DropdownMenuSeparator />
|
||||
{failed ? (
|
||||
<p role="alert" className="px-2 py-3 text-sm text-destructive">{t("NotificationsLoadFailed")}</p>
|
||||
) : items === null ? (
|
||||
<p className="px-2 py-3 text-sm text-muted-foreground">{t("Loading")}</p>
|
||||
) : items.length === 0 ? (
|
||||
<p className="px-2 py-3 text-sm text-muted-foreground">{t("NotificationsEmpty")}</p>
|
||||
) : (
|
||||
<div className="max-h-96 overflow-y-auto">
|
||||
{items.map((item) => {
|
||||
const { title, body } = noticeText(item, t);
|
||||
const inner = (
|
||||
<span className="flex w-full min-w-0 items-start gap-2">
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-sm font-medium">{title}</span>
|
||||
{body && <span className="block truncate text-xs text-muted-foreground">{body}</span>}
|
||||
<span className="block text-xs text-muted-foreground">{when(item.createDateTime)}</span>
|
||||
</span>
|
||||
{!item.seen && <span aria-hidden="true" className="mt-1.5 size-2 shrink-0 rounded-full bg-primary" />}
|
||||
</span>
|
||||
);
|
||||
return isSitePath(item.link) ? (
|
||||
<DropdownMenuItem key={item.id} asChild>
|
||||
<Link href={item.link}>{inner}</Link>
|
||||
</DropdownMenuItem>
|
||||
) : (
|
||||
<DropdownMenuItem key={item.id}>{inner}</DropdownMenuItem>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href="/notifications" className="justify-center text-sm">{t("NotificationsSeeAll")}</Link>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
@@ -19,6 +19,7 @@ const INLINE: Record<string, string[]> = {
|
||||
IMAGE_TEXT: ["imageId", "imagePosition", "heading", "html", "buttonLabel", "buttonUrl"],
|
||||
FAQ: ["heading", "items"],
|
||||
FORM: ["heading", "eventUuid"],
|
||||
HTML: ["html"],
|
||||
};
|
||||
const LISTED = /^items\[\d+\]\.(question|answer)$/;
|
||||
const SELECT = "flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm disabled:cursor-not-allowed disabled:opacity-50";
|
||||
@@ -169,6 +170,15 @@ export function BlockFields(props: {
|
||||
</>
|
||||
)}
|
||||
|
||||
{block.type === "HTML" && (
|
||||
<Field id={fid("html")} label={t("PagesHtml")} error={errors.html}>
|
||||
<Textarea id={fid("html")} rows={12} spellCheck={false} className="font-mono text-xs" value={block.html ?? ""} disabled={saving}
|
||||
aria-invalid={!!errors.html} onChange={(e) => set({ html: e.target.value })} />
|
||||
<p className="tabular text-xs text-muted-foreground">{`${(block.html ?? "").length}/200000`}</p>
|
||||
<p className="text-xs text-muted-foreground">{t("PagesHtmlHint")}</p>
|
||||
</Field>
|
||||
)}
|
||||
|
||||
{block.type === "FORM" && (
|
||||
<>
|
||||
{text("heading", "PagesHeading")}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { act, render, screen } from "@testing-library/react";
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { LandingPage, type PublicBlock } from "./CmsBlocks";
|
||||
import { FRAME_SANDBOX } from "@/app/lib/frameHtml";
|
||||
|
||||
// add-custom-html-block: an HTML block is a sealed frame sized by its own reports; "hide header" drops the header.
|
||||
const company = { code: "INS", name: "INS Sdn Bhd", logoImageId: 4, accentColor: null };
|
||||
const page = (blocks: PublicBlock[], hideHeader = false) => ({ slug: "hotel", title: "Hotel day", hideHeader, blocks });
|
||||
const HTML: PublicBlock = { type: "HTML", html: "<h1>Designed</h1><script>x()</script>" };
|
||||
|
||||
const frame = () => document.querySelector("iframe") as HTMLIFrameElement;
|
||||
|
||||
describe("LandingPage: Custom HTML", () => {
|
||||
it("shows an HTML block as a sealed frame from its own address, never inline", () => {
|
||||
render(<LandingPage company={company} page={page([{ type: "FAQ", items: [{ question: "Q", answer: "A" }] }, HTML])} />);
|
||||
expect(frame()).toHaveAttribute("src", "/p/INS/hotel/frame/1");
|
||||
expect(frame()).toHaveAttribute("sandbox", FRAME_SANDBOX);
|
||||
expect(frame()).toHaveAttribute("title", "Hotel day");
|
||||
expect(frame().style.height).toBe("600px");
|
||||
expect(screen.queryByText("Designed")).not.toBeInTheDocument();
|
||||
expect(document.querySelector("script")).toBeNull();
|
||||
});
|
||||
|
||||
it("uses the preview's frame address when given", () => {
|
||||
render(<LandingPage company={company} page={page([HTML])} frameBase="/pages/5/preview/frame" preview />);
|
||||
expect(frame()).toHaveAttribute("src", "/pages/5/preview/frame/0");
|
||||
});
|
||||
|
||||
it("grows to its frame's reported height and ignores other windows", () => {
|
||||
render(<LandingPage company={company} page={page([HTML])} />);
|
||||
act(() => { window.dispatchEvent(new MessageEvent("message", { data: { type: "colite-frame-height", height: 2400 }, source: window })); });
|
||||
expect(frame().style.height).toBe("600px");
|
||||
act(() => { window.dispatchEvent(new MessageEvent("message", { data: { type: "colite-frame-height", height: 2400 }, source: frame().contentWindow })); });
|
||||
expect(frame().style.height).toBe("2400px");
|
||||
});
|
||||
|
||||
it("hides the company header and shows the title to screen readers only when the page says so", () => {
|
||||
render(<LandingPage company={company} page={page([HTML], true)} />);
|
||||
expect(screen.queryByRole("img", { name: "INS Sdn Bhd" })).not.toBeInTheDocument();
|
||||
expect(document.querySelector("header")).toBeNull();
|
||||
expect(screen.getByRole("heading", { level: 1, name: "Hotel day" })).toHaveClass("sr-only");
|
||||
});
|
||||
|
||||
it("starts a header-less page flush at the top: the hidden title takes no part in block spacing", () => {
|
||||
render(<LandingPage company={company} page={page([HTML], true)} />);
|
||||
const title = screen.getByRole("heading", { level: 1, name: "Hotel day" });
|
||||
expect(title.parentElement!.className).not.toMatch(/space-y/);
|
||||
expect(frame().parentElement!.className).toMatch(/space-y/);
|
||||
});
|
||||
});
|
||||
@@ -3,9 +3,11 @@ import { contrastText, imageSrc, isSafeLink, type CmsBlock } from "@/app/lib/cms
|
||||
import type { RegistrationInfo } from "@/app/lib/services/publicRegistration";
|
||||
import { SafeHtml } from "./SafeHtml";
|
||||
import { LandingForm } from "./LandingForm";
|
||||
import { HtmlFrame } from "./HtmlFrame";
|
||||
|
||||
// Landing-page blocks, ported from babyboo's CmsBlocks minus the product blocks. HTML only goes through SafeHtml;
|
||||
// images are this company's uploads; buttons render only for a safe link, checked again here.
|
||||
// images are this company's uploads; buttons render only for a safe link, checked again here. A Custom HTML block is
|
||||
// never rendered here: it is a sealed frame loaded from its own address (add-custom-html-block).
|
||||
|
||||
export type PublicBlock = CmsBlock & { form?: RegistrationInfo; closed?: boolean };
|
||||
|
||||
@@ -86,20 +88,28 @@ function Block({ block, index, company, slug, preview }: { block: PublicBlock; i
|
||||
}
|
||||
}
|
||||
|
||||
/** A whole landing page: the company header (logo, accent), the title as the only h1, then the blocks. */
|
||||
export function LandingPage({ company, page, banner, preview }: {
|
||||
const WIDTH = "mx-auto w-full max-w-5xl px-4";
|
||||
|
||||
/**
|
||||
* A whole landing page: the company header (logo, accent), the title as the only h1, then the blocks. Custom HTML
|
||||
* blocks run full width; with hideHeader the header goes and the title is for screen readers only.
|
||||
*/
|
||||
export function LandingPage({ company, page, banner, preview, frameBase }: {
|
||||
company: Branding;
|
||||
page: { slug: string; title: string; blocks: PublicBlock[] };
|
||||
page: { slug: string; title: string; hideHeader?: boolean; blocks: PublicBlock[] };
|
||||
banner?: ReactNode;
|
||||
/** The editor's draft preview: forms show a note instead of taking sign-ups. */
|
||||
preview?: boolean;
|
||||
/** Where block frames load from; the public page's frame address by default. */
|
||||
frameBase?: string;
|
||||
}) {
|
||||
const frames = frameBase ?? `/p/${encodeURIComponent(company.code)}/${encodeURIComponent(page.slug)}/frame`;
|
||||
const accent = company.accentColor && /^#[0-9A-Fa-f]{6}$/.test(company.accentColor) ? company.accentColor : null;
|
||||
const style = accent ? ({ "--primary": accent, "--primary-foreground": contrastText(accent), "--ring": accent } as CSSProperties) : undefined;
|
||||
return (
|
||||
<div style={style} className="min-h-svh bg-background">
|
||||
{banner}
|
||||
<header className="border-b bg-card">
|
||||
{page.hideHeader ? null : <header className="border-b bg-card">
|
||||
<div className="mx-auto flex max-w-5xl items-center gap-3 px-4 py-3">
|
||||
{company.logoImageId ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element -- the company's uploaded logo
|
||||
@@ -108,10 +118,14 @@ export function LandingPage({ company, page, banner, preview }: {
|
||||
<span className="text-lg font-semibold">{company.name}</span>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
<main className="mx-auto max-w-5xl space-y-10 px-4 py-8">
|
||||
<h1 className="text-3xl font-semibold sm:text-4xl">{page.title}</h1>
|
||||
{page.blocks.map((block, i) => <Block key={i} block={block} index={i} company={company.code} slug={page.slug} preview={preview} />)}
|
||||
</header>}
|
||||
<main className={page.hideHeader ? "pb-8" : "py-8"}>
|
||||
<h1 className={page.hideHeader ? "sr-only" : `${WIDTH} mb-10 text-3xl font-semibold sm:text-4xl`}>{page.title}</h1>
|
||||
<div className="space-y-10">
|
||||
{page.blocks.map((block, i) => block.type === "HTML"
|
||||
? <HtmlFrame key={i} src={`${frames}/${i}`} title={page.title} />
|
||||
: <div key={i} className={WIDTH}><Block block={block} index={i} company={company.code} slug={page.slug} preview={preview} /></div>)}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Check, Copy } from "lucide-react";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
/** A page address with a button that copies its full URL (this site's origin plus the path). */
|
||||
export function CopyAddress({ address }: { address: string }) {
|
||||
const t = useT();
|
||||
const [state, setState] = useState<"idle" | "copied" | "failed">("idle");
|
||||
|
||||
async function copy() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(`${window.location.origin}${address}`);
|
||||
setState("copied");
|
||||
setTimeout(() => setState("idle"), 2000);
|
||||
} catch {
|
||||
setState("failed");
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<span className="font-mono text-xs">{address}</span>
|
||||
<Button type="button" variant="ghost" size="icon" className="size-7" aria-label={`${t("QrCopy")} ${address}`} title={t("QrCopy")} onClick={copy}>
|
||||
{state === "copied" ? <Check className="size-3.5" aria-hidden /> : <Copy className="size-3.5" aria-hidden />}
|
||||
</Button>
|
||||
{state !== "idle" ? (
|
||||
<span role="status" className={state === "failed" ? "text-xs text-destructive" : "text-xs text-muted-foreground"}>
|
||||
{t(state === "copied" ? "QrCopied" : "CopyFailed")}
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { FRAME_SANDBOX, nextFrameHeight, START_HEIGHT, type FrameHeight } from "@/app/lib/frameHtml";
|
||||
|
||||
/** A Custom HTML block: the sealed frame, sized by height reports from that frame's own window only. */
|
||||
export function HtmlFrame({ src, title }: { src: string; title: string }) {
|
||||
const ref = useRef<HTMLIFrameElement>(null);
|
||||
const [size, setSize] = useState<FrameHeight>({ height: START_HEIGHT, steps: [] });
|
||||
useEffect(() => {
|
||||
const onMessage = (e: MessageEvent) => {
|
||||
if (!ref.current || e.source !== ref.current.contentWindow) return;
|
||||
setSize((s) => nextFrameHeight(s, e.data));
|
||||
};
|
||||
window.addEventListener("message", onMessage);
|
||||
return () => window.removeEventListener("message", onMessage);
|
||||
}, []);
|
||||
return <iframe ref={ref} src={src} title={title} sandbox={FRAME_SANDBOX} loading="lazy" className="block w-full border-0" style={{ height: `${size.height}px` }} />;
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
// add-custom-html-block: the editor's Custom HTML block and "Hide page header" switch.
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getPage: vi.fn(), savePage: vi.fn(), deletePage: vi.fn(), uploadPageImage: vi.fn(),
|
||||
listAdminEvents: vi.fn(), useAdminAuth: vi.fn(), useCompanyScope: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminPages", () => ({ getPage: mocks.getPage, savePage: mocks.savePage, deletePage: mocks.deletePage, uploadPageImage: mocks.uploadPageImage }));
|
||||
vi.mock("@/app/lib/services/adminEvents", () => ({ listAdminEvents: mocks.listAdminEvents }));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: mocks.useCompanyScope }));
|
||||
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
||||
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import { PageEditor } from "./PageEditor";
|
||||
|
||||
const stored = {
|
||||
id: 5, companyId: 2, slug: "hotel", title: "Hotel", metaDescription: null, status: "PUBLISHED" as const, hideHeader: true,
|
||||
blocks: [{ type: "HTML" as const, html: "<h1>Designed</h1>" }],
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
memoryRouter.reset("/pages/5");
|
||||
mocks.useAdminAuth.mockReturnValue({ isSuper: false, companyCode: "INS" });
|
||||
mocks.useCompanyScope.mockReturnValue({ companyId: undefined, companies: [{ id: 2, code: "INS", name: "INS", status: "A" }], codeOf: (id?: number) => (id === 2 ? "INS" : "") });
|
||||
mocks.listAdminEvents.mockResolvedValue({ items: [], total: 0 });
|
||||
mocks.getPage.mockResolvedValue(stored);
|
||||
mocks.savePage.mockImplementation(async (id: number | undefined, body: object) => ({ ...stored, ...body, id: id ?? 7 }));
|
||||
});
|
||||
|
||||
describe("PageEditor: Custom HTML", () => {
|
||||
it("loads the HTML and the hide-header option, and saves both", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<PageEditor pageId={5} />);
|
||||
const box = await screen.findByLabelText("HTML");
|
||||
expect(box).toHaveValue("<h1>Designed</h1>");
|
||||
expect(box).toHaveClass("font-mono");
|
||||
expect(screen.getByText("17/200000")).toBeInTheDocument();
|
||||
expect(screen.getByText(/Forms inside the pasted HTML don't send/)).toBeInTheDocument();
|
||||
const toggle = screen.getByRole("switch", { name: "Hide page header" });
|
||||
expect(toggle).toBeChecked();
|
||||
|
||||
await user.click(toggle);
|
||||
await user.click(screen.getByRole("button", { name: "Add Custom HTML" }));
|
||||
await user.type(screen.getAllByLabelText("HTML")[1], "<p>x</p>");
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
await waitFor(() => expect(mocks.savePage).toHaveBeenCalled());
|
||||
const body = mocks.savePage.mock.calls[0][1];
|
||||
expect(body.hideHeader).toBe(false);
|
||||
expect(body.blocks).toEqual([{ type: "HTML", html: "<h1>Designed</h1>" }, { type: "HTML", html: "<p>x</p>" }]);
|
||||
});
|
||||
|
||||
it("shows a refusal of the HTML at its field", async () => {
|
||||
mocks.savePage.mockRejectedValue(new ApiError("x", 422, { code: "PagesTooLong", details: { field: "blocks[0].html" } }));
|
||||
const user = userEvent.setup();
|
||||
render(<PageEditor pageId={5} />);
|
||||
const box = await screen.findByLabelText("HTML");
|
||||
await user.click(screen.getByRole("button", { name: "Save" }));
|
||||
expect(await screen.findByText("Too long.")).toBeInTheDocument();
|
||||
expect(box.closest("div")).toHaveTextContent("Too long.");
|
||||
expect(box).toHaveAttribute("aria-invalid", "true");
|
||||
});
|
||||
});
|
||||
@@ -35,6 +35,15 @@ beforeEach(() => {
|
||||
});
|
||||
|
||||
describe("PageEditor", () => {
|
||||
it("copies the saved page's full address", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<PageEditor pageId={5} />);
|
||||
await screen.findByLabelText("Event");
|
||||
const write = vi.spyOn(navigator.clipboard, "writeText");
|
||||
await user.click(screen.getByRole("button", { name: "Copy link /p/INS/hotel" }));
|
||||
expect(write).toHaveBeenCalledWith(`${window.location.origin}/p/INS/hotel`);
|
||||
});
|
||||
|
||||
it("names the rich text box after its field label", async () => {
|
||||
const user = userEvent.setup();
|
||||
render(<PageEditor pageId={5} />);
|
||||
|
||||
@@ -8,12 +8,14 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/ca
|
||||
import { ConfirmDialog } from "@/app/components/ui/confirm-dialog";
|
||||
import { Input } from "@/app/components/ui/input";
|
||||
import { Label } from "@/app/components/ui/label";
|
||||
import { Switch } from "@/app/components/ui/switch";
|
||||
import { Textarea } from "@/app/components/ui/textarea";
|
||||
import { ErrorState } from "@/app/components/ui/states";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/app/components/ui/select";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { 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 { listAdminEvents } from "@/app/lib/services/adminEvents";
|
||||
@@ -75,7 +77,7 @@ export function PageEditor({ pageId }: { pageId?: number }) {
|
||||
getPage(pageId)
|
||||
.then((p) => {
|
||||
if (cancelled) return;
|
||||
setDraft({ id: p.id, companyId: p.companyId, slug: p.slug, slugTouched: true, title: p.title, metaDescription: p.metaDescription ?? "", status: p.status, blocks: [] });
|
||||
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 });
|
||||
})
|
||||
@@ -198,7 +200,8 @@ export function PageEditor({ pageId }: { pageId?: number }) {
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap justify-end gap-2">
|
||||
<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>
|
||||
@@ -292,6 +295,10 @@ export function PageEditor({ pageId }: { pageId?: number }) {
|
||||
</label>
|
||||
))}
|
||||
<FieldError message={errors.status} />
|
||||
<div className="flex items-center gap-2 pt-2 text-sm">
|
||||
<Switch id="page-hide-header" checked={draft.hideHeader} disabled={saving} onCheckedChange={(on) => patch({ hideHeader: on })} />
|
||||
<Label htmlFor="page-hide-header">{t("PagesHideHeader")}</Label>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { bodyLimit, DEFAULT_BODY_LIMIT, UPLOAD_BODY_LIMIT } from "./bodyLimit";
|
||||
|
||||
// add-custom-html-block: a page save may carry several Custom HTML blocks of up to 200,000 characters each.
|
||||
describe("bodyLimit: page saves", () => {
|
||||
it("gives page creates and updates the large limit", () => {
|
||||
expect(bodyLimit("/api/pages")).toBe(UPLOAD_BODY_LIMIT);
|
||||
expect(bodyLimit("/api/pages/12")).toBe(UPLOAD_BODY_LIMIT);
|
||||
});
|
||||
|
||||
it("leaves other page-like paths on the default", () => {
|
||||
for (const p of ["/api/pagesx", "/api/pages/12/other", "/api/companies/1/branding"]) expect(bodyLimit(p), p).toBe(DEFAULT_BODY_LIMIT);
|
||||
});
|
||||
});
|
||||
@@ -2,12 +2,13 @@
|
||||
// front of the portal caps it (a 2 MB POST reached the login route live). The middleware refuses an API write whose
|
||||
// declared Content-Length exceeds its route's limit. Uploads (images, photos, documents, attachments, imports) get
|
||||
// room for a 5 MB file sent as base64 JSON, as do email-template saves (free HTML, which may carry inline images);
|
||||
// everything else 1 MB.
|
||||
// everything else 1 MB. Landing-page saves get the large limit too (add-custom-html-block): a Custom HTML block holds
|
||||
// up to 200,000 characters.
|
||||
|
||||
export const DEFAULT_BODY_LIMIT = 1024 * 1024;
|
||||
export const UPLOAD_BODY_LIMIT = 10 * 1024 * 1024;
|
||||
|
||||
const UPLOAD_PATH = /\/(?:image|images|photos|upload|attachments|doc|invoice-header|import)(?:\/|$)|^\/api\/(?:fulfilment|email-templates)(?:\/|$)/;
|
||||
const UPLOAD_PATH = /\/(?:image|images|photos|upload|attachments|doc|invoice-header|import)(?:\/|$)|^\/api\/(?:fulfilment|email-templates)(?:\/|$)|^\/api\/pages(?:\/\d+)?$/;
|
||||
|
||||
export function bodyLimit(pathname: string): number {
|
||||
return UPLOAD_PATH.test(pathname) ? UPLOAD_BODY_LIMIT : DEFAULT_BODY_LIMIT;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
// Landing-page blocks and the editor's pure helpers (add-landing-pages), ported from babyboo's cmsPages.ts
|
||||
// minus the product blocks. Images are page_image ids, served at /api/public/page-images/<id>.
|
||||
|
||||
export type BlockType = "HERO" | "RICH_TEXT" | "IMAGE_TEXT" | "FAQ" | "FORM";
|
||||
export type BlockType = "HERO" | "RICH_TEXT" | "IMAGE_TEXT" | "FAQ" | "FORM" | "HTML";
|
||||
|
||||
export const BLOCK_TYPES: BlockType[] = ["HERO", "RICH_TEXT", "IMAGE_TEXT", "FAQ", "FORM"];
|
||||
export const BLOCK_TYPES: BlockType[] = ["HERO", "RICH_TEXT", "IMAGE_TEXT", "FAQ", "FORM", "HTML"];
|
||||
|
||||
export const BLOCK_LABELS: Record<BlockType, string> = {
|
||||
HERO: "PagesBlockHero",
|
||||
@@ -11,6 +11,7 @@ export const BLOCK_LABELS: Record<BlockType, string> = {
|
||||
IMAGE_TEXT: "PagesBlockImageText",
|
||||
FAQ: "PagesBlockFaq",
|
||||
FORM: "PagesBlockForm",
|
||||
HTML: "PagesBlockHtml",
|
||||
};
|
||||
|
||||
export interface CmsFaqItem {
|
||||
@@ -41,6 +42,7 @@ export interface CmsPage {
|
||||
title: string;
|
||||
metaDescription: string | null;
|
||||
status: PageStatus;
|
||||
hideHeader?: boolean;
|
||||
blocks: CmsBlock[];
|
||||
updatedAt?: string | null;
|
||||
}
|
||||
@@ -53,6 +55,8 @@ export interface CmsPageDraft {
|
||||
title: string;
|
||||
metaDescription: string;
|
||||
status: PageStatus;
|
||||
/** Hide the company header and the page title (add-custom-html-block). */
|
||||
hideHeader: boolean;
|
||||
blocks: CmsBlock[];
|
||||
}
|
||||
|
||||
@@ -61,7 +65,7 @@ export const imageSrc = (id: number) => `/api/public/page-images/${id}`;
|
||||
export const pageAddress = (companyCode: string, slug: string) => `/p/${companyCode}/${slug}`;
|
||||
|
||||
export function emptyPage(): CmsPageDraft {
|
||||
return { slug: "", slugTouched: false, title: "", metaDescription: "", status: "DRAFT", blocks: [] };
|
||||
return { slug: "", slugTouched: false, title: "", metaDescription: "", status: "DRAFT", hideHeader: false, blocks: [] };
|
||||
}
|
||||
|
||||
export function emptyBlock(type: BlockType): CmsBlock {
|
||||
@@ -72,6 +76,8 @@ export function emptyBlock(type: BlockType): CmsBlock {
|
||||
return { type, imageId: null, heading: "", html: "", imagePosition: "LEFT", buttonLabel: "", buttonUrl: "" };
|
||||
case "FORM":
|
||||
return { type, heading: "", eventUuid: null };
|
||||
case "HTML":
|
||||
return { type, html: "" };
|
||||
default:
|
||||
return { type };
|
||||
}
|
||||
@@ -96,6 +102,7 @@ export function pageBody(draft: CmsPageDraft) {
|
||||
title: draft.title.trim(),
|
||||
metaDescription: draft.metaDescription.trim() || null,
|
||||
status: draft.status,
|
||||
hideHeader: draft.hideHeader,
|
||||
blocks: draft.blocks.map((b) => {
|
||||
const out: Record<string, unknown> = { type: b.type };
|
||||
for (const [key, val] of Object.entries(b)) {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { FRAME_SANDBOX, frameDocument, frameResponse, nextFrameHeight, START_HEIGHT } from "./frameHtml";
|
||||
|
||||
// add-custom-html-block: pasted HTML runs sealed, in its own document with a sandbox policy, and reports its height.
|
||||
describe("frameHtml", () => {
|
||||
it("grants scripts and pop-ups only", () => {
|
||||
expect(FRAME_SANDBOX.split(" ").sort()).toEqual(["allow-popups", "allow-popups-to-escape-sandbox", "allow-scripts"]);
|
||||
});
|
||||
|
||||
it("adds the height script before </body>, or at the end of a fragment", () => {
|
||||
const doc = frameDocument("<html><body><h1>Hi</h1></body></html>");
|
||||
expect(doc).toMatch(/<h1>Hi<\/h1><script>[\s\S]*colite-frame-height[\s\S]*<\/script><\/body><\/html>$/);
|
||||
expect(frameDocument("<section>x</section>")).toMatch(/^<section>x<\/section><script>[\s\S]*colite-frame-height/);
|
||||
expect(frameDocument("<BODY>x</BODY>")).toMatch(/x<script>[\s\S]*<\/script><\/BODY>$/);
|
||||
});
|
||||
|
||||
it("serves the HTML sealed: sandbox policy, own framing only, no sniffing", async () => {
|
||||
const res = frameResponse("<p>x</p>", { preview: false });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("content-type")).toBe("text/html; charset=utf-8");
|
||||
const csp = res.headers.get("content-security-policy") ?? "";
|
||||
expect(csp).toBe(`sandbox ${FRAME_SANDBOX}; frame-ancestors 'self'`);
|
||||
expect(csp).not.toContain("allow-same-origin");
|
||||
expect(csp).not.toContain("allow-forms");
|
||||
expect(csp).not.toContain("allow-top-navigation");
|
||||
expect(res.headers.get("x-content-type-options")).toBe("nosniff");
|
||||
expect(res.headers.get("referrer-policy")).toBe("no-referrer");
|
||||
expect(await res.text()).toContain("<p>x</p>");
|
||||
});
|
||||
|
||||
it("does not let a browser cache a draft", () => {
|
||||
expect(frameResponse("<p>x</p>", { preview: true }).headers.get("cache-control")).toBe("no-store");
|
||||
expect(frameResponse("<p>x</p>", { preview: false }).headers.get("cache-control")).not.toBe("no-store");
|
||||
});
|
||||
|
||||
it("clamps a reported height between 100 and 20000 pixels and ignores junk", () => {
|
||||
const start = { height: START_HEIGHT, steps: [] };
|
||||
expect(START_HEIGHT).toBe(600);
|
||||
expect(nextFrameHeight(start, { type: "colite-frame-height", height: 3000 }).height).toBe(3000);
|
||||
expect(nextFrameHeight(start, { type: "colite-frame-height", height: 10 }).height).toBe(100);
|
||||
expect(nextFrameHeight(start, { type: "colite-frame-height", height: 99999 }).height).toBe(20000);
|
||||
for (const junk of [null, "600", { type: "other", height: 900 }, { type: "colite-frame-height", height: "900" }, { type: "colite-frame-height", height: NaN }]) {
|
||||
expect(nextFrameHeight(start, junk)).toBe(start);
|
||||
}
|
||||
});
|
||||
|
||||
it("stops growing when the content grows with the frame (100vh sections)", () => {
|
||||
let s = { height: START_HEIGHT, steps: [] as number[] };
|
||||
// Each report is the frame height plus the same 400 px below a full-height section: a loop.
|
||||
for (let i = 0; i < 10; i++) s = nextFrameHeight(s, { type: "colite-frame-height", height: s.height + 400 });
|
||||
expect(s.height).toBeLessThan(START_HEIGHT + 400 * 4);
|
||||
// Ordinary growth with varying steps (images loading) keeps following the content.
|
||||
let t = { height: START_HEIGHT, steps: [] as number[] };
|
||||
for (const h of [900, 1250, 1900, 2000, 2600]) t = nextFrameHeight(t, { type: "colite-frame-height", height: h });
|
||||
expect(t.height).toBe(2600);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
// add-custom-html-block: a Custom HTML block runs sealed. It is served as its own document whose
|
||||
// Content-Security-Policy `sandbox` gives it an opaque origin, even when its address is opened directly, and it is
|
||||
// shown in an <iframe sandbox> with the same grants. No same-origin, forms, top navigation or modals.
|
||||
|
||||
export const FRAME_SANDBOX = "allow-scripts allow-popups allow-popups-to-escape-sandbox";
|
||||
/** The frame document's own policy. next.config sends it too: config headers replace a route's header of the same name. */
|
||||
export const FRAME_CSP = `sandbox ${FRAME_SANDBOX}; frame-ancestors 'self'`;
|
||||
export const FRAME_MESSAGE = "colite-frame-height";
|
||||
export const START_HEIGHT = 600;
|
||||
const MIN_HEIGHT = 100;
|
||||
const MAX_HEIGHT = 20000;
|
||||
|
||||
// Posts the document height to the parent page on load and whenever it changes.
|
||||
const HEIGHT_SCRIPT =
|
||||
`<script>(function(){function s(){parent.postMessage({type:"${FRAME_MESSAGE}",height:Math.ceil(document.documentElement.scrollHeight)},"*")}` +
|
||||
`addEventListener("load",s);if(window.ResizeObserver)new ResizeObserver(s).observe(document.documentElement);s()})();</script>`;
|
||||
|
||||
/** The pasted HTML with the height script before its last </body>, or appended when it is a fragment. */
|
||||
export function frameDocument(html: string): string {
|
||||
const at = html.toLowerCase().lastIndexOf("</body>");
|
||||
return at < 0 ? html + HEIGHT_SCRIPT : html.slice(0, at) + HEIGHT_SCRIPT + html.slice(at);
|
||||
}
|
||||
|
||||
export function frameResponse(html: string, { preview }: { preview: boolean }): Response {
|
||||
return new Response(frameDocument(html), {
|
||||
headers: {
|
||||
"Content-Type": "text/html; charset=utf-8",
|
||||
"Content-Security-Policy": FRAME_CSP,
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Referrer-Policy": "no-referrer",
|
||||
"Cache-Control": preview ? "no-store" : "public, max-age=60",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** The same empty answer for every frame miss. */
|
||||
export const frameNotFound = () => new Response(null, { status: 404, headers: { "Cache-Control": "no-store" } });
|
||||
|
||||
/** The HTML of block `index` when it is an HTML block, else null. */
|
||||
export function htmlBlock(blocks: unknown, index: string): string | null {
|
||||
if (!/^\d{1,2}$/.test(index) || !Array.isArray(blocks)) return null;
|
||||
const block = blocks[Number(index)] as { type?: unknown; html?: unknown } | undefined;
|
||||
return block?.type === "HTML" && typeof block.html === "string" ? block.html : null;
|
||||
}
|
||||
|
||||
export interface FrameHeight {
|
||||
height: number;
|
||||
/** The last growth steps, to spot content that grows with the frame. */
|
||||
steps: number[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The frame's next height after a message from it. Junk leaves the state as it is. A section sized by the viewport
|
||||
* (100vh) grows with the frame, so each report is the frame plus the same remainder: after two equal steps the
|
||||
* frame stops growing.
|
||||
* ponytail: equal-step heuristic; a page that grows by the same step three times for another reason stops early.
|
||||
*/
|
||||
export function nextFrameHeight(state: FrameHeight, data: unknown): FrameHeight {
|
||||
const d = data as { type?: unknown; height?: unknown } | null;
|
||||
if (!d || typeof d !== "object" || d.type !== FRAME_MESSAGE || typeof d.height !== "number" || !Number.isFinite(d.height)) return state;
|
||||
const height = Math.min(MAX_HEIGHT, Math.max(MIN_HEIGHT, Math.ceil(d.height)));
|
||||
if (height <= state.height) return { height, steps: [] };
|
||||
const step = height - state.height;
|
||||
const [a, b] = state.steps.slice(-2);
|
||||
if (a !== undefined && b !== undefined && Math.abs(a - step) <= 2 && Math.abs(b - step) <= 2) return state;
|
||||
return { height, steps: [...state.steps, step].slice(-2) };
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
|
||||
|
||||
import * as pub from "@/app/p/[company]/[slug]/frame/[block]/route";
|
||||
import * as preview from "@/app/pages/[id]/preview/frame/[block]/route";
|
||||
|
||||
// add-custom-html-block: the frame addresses serve only an HTML block, sealed; every public miss looks the same.
|
||||
const req = new Request("http://localhost/x");
|
||||
const ctx = <T,>(p: T) => ({ params: Promise.resolve(p) });
|
||||
const page = (blocks: object[]) => ({ ok: true, data: { company: { code: "INS", name: "INS" }, page: { slug: "hotel", title: "Hotel", blocks } } });
|
||||
const BLOCKS = [{ type: "HTML", html: "<h1>Designed</h1>" }, { type: "FORM", heading: "Join" }];
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.callMobileApi.mockReset();
|
||||
mocks.getToken.mockReset();
|
||||
mocks.getToken.mockResolvedValue("jwt");
|
||||
mocks.callMobileApi.mockResolvedValue(page(BLOCKS));
|
||||
});
|
||||
|
||||
describe("public frame", () => {
|
||||
it("serves a published page's HTML block sealed", async () => {
|
||||
const res = await pub.GET(req, ctx({ company: "INS", slug: "hotel", block: "0" }));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/public/pages/INS/hotel");
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("content-security-policy")).toMatch(/^sandbox allow-scripts/);
|
||||
expect(await res.text()).toContain("<h1>Designed</h1>");
|
||||
});
|
||||
|
||||
it("answers every miss with the same empty not-found", async () => {
|
||||
// The API answers the published page; a bad index never reaches it.
|
||||
for (const block of ["1", "7", "x", "-1", "100"]) {
|
||||
const res = await pub.GET(req, ctx({ company: "INS", slug: "hotel", block }));
|
||||
expect(res.status, block).toBe(404);
|
||||
expect(await res.text()).toBe("");
|
||||
}
|
||||
mocks.callMobileApi.mockResolvedValueOnce({ ok: false, status: 404 });
|
||||
const draft = await pub.GET(req, ctx({ company: "INS", slug: "draft", block: "0" }));
|
||||
expect(draft.status).toBe(404);
|
||||
expect(await draft.text()).toBe("");
|
||||
});
|
||||
|
||||
it("encodes the address parts", async () => {
|
||||
await pub.GET(req, ctx({ company: "I/S", slug: "a b", block: "0" }));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/public/pages/I%2FS/a%20b");
|
||||
});
|
||||
|
||||
it("reports an upstream failure as 502", async () => {
|
||||
mocks.callMobileApi.mockResolvedValueOnce({ ok: false, status: 500 });
|
||||
expect((await pub.GET(req, ctx({ company: "INS", slug: "hotel", block: "0" }))).status).toBe(502);
|
||||
});
|
||||
});
|
||||
|
||||
describe("preview frame", () => {
|
||||
it("serves a draft HTML block to staff through the admin API, uncached", async () => {
|
||||
mocks.callMobileApi.mockResolvedValueOnce({ ok: true, data: { slug: "hotel", title: "Hotel", blocks: BLOCKS } });
|
||||
const res = await preview.GET(req, ctx({ id: "5", block: "0" }));
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/pages/5", { token: "jwt" });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers.get("cache-control")).toBe("no-store");
|
||||
expect(res.headers.get("content-security-policy")).toMatch(/^sandbox allow-scripts/);
|
||||
});
|
||||
|
||||
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);
|
||||
expect((await preview.GET(req, ctx({ id: "5x", block: "0" }))).status).toBe(404);
|
||||
mocks.callMobileApi.mockResolvedValueOnce({ ok: false, status: 403 });
|
||||
expect((await preview.GET(req, ctx({ id: "5", block: "0" }))).status).toBe(404);
|
||||
mocks.callMobileApi.mockResolvedValueOnce({ ok: true, data: { slug: "hotel", title: "Hotel", blocks: BLOCKS } });
|
||||
expect((await preview.GET(req, ctx({ id: "5", block: "1" }))).status).toBe(404);
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -756,6 +756,25 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
PagesBlockImageText: "Image with text",
|
||||
PagesBlockFaq: "FAQ",
|
||||
PagesBlockForm: "Sign-up form",
|
||||
PagesBlockHtml: "Custom HTML",
|
||||
PagesHtml: "HTML",
|
||||
PagesHtmlHint: "Forms inside the pasted HTML don't send. Add a Sign-up form block to collect leads.",
|
||||
PagesHideHeader: "Hide page header",
|
||||
NotificationsTitle: "Notifications",
|
||||
NotificationsUnread: "Notifications, {count} unread",
|
||||
NotificationsEmpty: "No notifications yet.",
|
||||
NotificationsLoadFailed: "Couldn't load notifications.",
|
||||
NotificationsMarkAllRead: "Mark all read",
|
||||
NotificationsSeeAll: "See all",
|
||||
NotificationsUnreadBadge: "Unread",
|
||||
NoticeLeadAssigned: "Lead assigned to you",
|
||||
NoticeWebSignup: "New sign-up",
|
||||
NoticeLeadBody: "{lead} · {event}",
|
||||
NoticeFollowUpDue: "Follow-ups due",
|
||||
NoticeFollowUpBody: "{due} due today, {overdue} overdue",
|
||||
NoticeWhatsappMessage: "New WhatsApp message",
|
||||
NoticeWhatsappBody: "From {name}",
|
||||
NoticeWhatsappBodyNoName: "From a new contact",
|
||||
PagesMoveUp: "Move up",
|
||||
PagesMoveDown: "Move down",
|
||||
PagesRemoveBlock: "Remove block",
|
||||
|
||||
@@ -763,6 +763,25 @@
|
||||
"PagesChooseEvent": "选择活动",
|
||||
"PagesUnavailableEvent": "活动已不可用",
|
||||
"PagesFormEventHint": "报名会成为此活动的线索。一般咨询请选择长期的咨询活动。",
|
||||
"PagesBlockHtml": "自定义 HTML",
|
||||
"PagesHtml": "HTML",
|
||||
"PagesHtmlHint": "粘贴的 HTML 中的表单不会发送。请添加报名表单区块来收集线索。",
|
||||
"PagesHideHeader": "隐藏页面顶栏",
|
||||
"NotificationsTitle": "通知",
|
||||
"NotificationsUnread": "通知,{count} 条未读",
|
||||
"NotificationsEmpty": "暂无通知。",
|
||||
"NotificationsLoadFailed": "无法加载通知。",
|
||||
"NotificationsMarkAllRead": "全部标为已读",
|
||||
"NotificationsSeeAll": "查看全部",
|
||||
"NotificationsUnreadBadge": "未读",
|
||||
"NoticeLeadAssigned": "有新线索分配给你",
|
||||
"NoticeWebSignup": "新的报名",
|
||||
"NoticeLeadBody": "{lead} · {event}",
|
||||
"NoticeFollowUpDue": "待跟进",
|
||||
"NoticeFollowUpBody": "今天到期 {due} 条,已逾期 {overdue} 条",
|
||||
"NoticeWhatsappMessage": "新的 WhatsApp 消息",
|
||||
"NoticeWhatsappBody": "来自 {name}",
|
||||
"NoticeWhatsappBodyNoName": "来自新联系人",
|
||||
"PagesFormClosed": "报名已截止。",
|
||||
"PagesFormPreview": "发布后的网页会在此显示报名表。",
|
||||
"PagesToolbar": "格式",
|
||||
|
||||
@@ -13,9 +13,13 @@ export const PUBLIC_PATHS = new Set<string>(["/login", "/reset-password", "/forg
|
||||
const VISITOR_PATH = /^\/[ric]\/[^/]+$/;
|
||||
// Published landing pages: /p/<company-code>/<slug>.
|
||||
const LANDING_PATH = /^\/p\/[^/]+\/[^/]+$/;
|
||||
// add-custom-html-block: a published page's Custom HTML frame, /p/<company-code>/<slug>/frame/<block>.
|
||||
export const LANDING_FRAME_PATH = /^\/p\/[^/]+\/[^/]+\/frame\/\d{1,2}$/;
|
||||
// The staff preview of a draft's Custom HTML frame (signed in).
|
||||
export const PREVIEW_FRAME_PATH = /^\/pages\/\d+\/preview\/frame\/\d{1,2}$/;
|
||||
|
||||
export function isPublicPath(pathname: string): boolean {
|
||||
return PUBLIC_PATHS.has(pathname) || VISITOR_PATH.test(pathname) || LANDING_PATH.test(pathname);
|
||||
return PUBLIC_PATHS.has(pathname) || VISITOR_PATH.test(pathname) || LANDING_PATH.test(pathname) || LANDING_FRAME_PATH.test(pathname);
|
||||
}
|
||||
|
||||
export interface SessionState {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, it, expect } from "vitest";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import ts from "typescript";
|
||||
import { FRAME_SANDBOX } from "@/app/lib/frameHtml";
|
||||
|
||||
// Spec (admin-portal-markup-safety), security finding F09: the admin portal never injects HTML into its own origin.
|
||||
// Data HTML goes into <iframe sandbox="" srcDoc>. Allow-listing a file here is a security
|
||||
@@ -26,6 +27,13 @@ const SINK_ALLOWED: Record<string, Sink[]> = {
|
||||
"components/pages/SafeHtml.tsx": ["dangerouslySetInnerHTML"],
|
||||
};
|
||||
|
||||
// add-custom-html-block: a Custom HTML block's frame loads its own address, whose response carries a `sandbox` CSP
|
||||
// (opaque origin), and may run scripts but never as this origin: FRAME_SANDBOX holds no allow-same-origin.
|
||||
// Only this file may give an iframe that one non-empty sandbox, and only as the named constant.
|
||||
const SANDBOX_ALLOWED: Record<string, string> = {
|
||||
"components/pages/HtmlFrame.tsx": "FRAME_SANDBOX",
|
||||
};
|
||||
|
||||
function sourceFiles(dir: string, out: string[] = []): string[] {
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
if (entry.name === "node_modules" || entry.name === ".next") continue;
|
||||
@@ -58,7 +66,9 @@ function iframeProblems(fileName: string, src: string): string[] {
|
||||
(p): p is ts.JsxAttribute => ts.isJsxAttribute(p) && p.name.getText(sf) === "sandbox",
|
||||
);
|
||||
const value = sandbox?.initializer;
|
||||
if (!value || !ts.isStringLiteral(value) || value.text !== "") {
|
||||
const allowed = SANDBOX_ALLOWED[fileName];
|
||||
const named = !!allowed && !!value && ts.isJsxExpression(value) && value.expression?.getText(sf) === allowed;
|
||||
if (!named && (!value || !ts.isStringLiteral(value) || value.text !== "")) {
|
||||
problems.push(`${fileName}:${line} iframe without sandbox=""`);
|
||||
}
|
||||
}
|
||||
@@ -106,6 +116,13 @@ describe("admin portal never injects HTML into its own origin", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("lets the Custom HTML frame run scripts, never as this origin, submit forms or navigate the page", () => {
|
||||
const grants = FRAME_SANDBOX.split(/\s+/);
|
||||
for (const g of ["allow-same-origin", "allow-forms", "allow-top-navigation", "allow-top-navigation-by-user-activation", "allow-modals"]) {
|
||||
expect(grants).not.toContain(g);
|
||||
}
|
||||
});
|
||||
|
||||
it("gives every iframe a literal empty sandbox", () => {
|
||||
const problems = files.flatMap((f) => iframeProblems(f.rel, f.src));
|
||||
expect(problems).toEqual([]);
|
||||
@@ -127,6 +144,13 @@ describe("iframe checker", () => {
|
||||
expect(check(`<iframe sandbox="" {...props} srcDoc={html} />`)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("accepts the named Custom HTML sandbox only in its allow-listed file", () => {
|
||||
const src = `export const X = () => <iframe title="t" sandbox={FRAME_SANDBOX} src={u} />;`;
|
||||
expect(iframeProblems("components/pages/HtmlFrame.tsx", src)).toEqual([]);
|
||||
expect(iframeProblems("fixture.tsx", src)).toHaveLength(1);
|
||||
expect(iframeProblems("components/pages/HtmlFrame.tsx", src.replace("FRAME_SANDBOX", "mode"))).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("rejects a non-empty or computed sandbox", () => {
|
||||
expect(check(`<iframe sandbox="allow-scripts" srcDoc={html} />`)).toHaveLength(1);
|
||||
expect(check(`<iframe sandbox={mode} srcDoc={html} />`)).toHaveLength(1);
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { noticeText, type AdminNotification } from "./notifications";
|
||||
|
||||
const t = (code: string, params?: Record<string, string | number>) => `${code}${params ? JSON.stringify(params) : ""}`;
|
||||
const item = (over: Partial<AdminNotification>): AdminNotification => ({
|
||||
id: 1, title: "NoticeLeadAssigned", message: null, type: "LEAD_ASSIGNED", link: "/leads/9", seen: false,
|
||||
createDateTime: "2026-12-02T09:00:00", ...over,
|
||||
});
|
||||
|
||||
// add-lead-notifications: rows store codes, so the reader's language decides the text.
|
||||
describe("noticeText", () => {
|
||||
it("renders the title code and the body code with its parameters", () => {
|
||||
expect(noticeText(item({ message: '{"code":"NoticeLeadBody","params":{"lead":"Ali","event":"Expo"}}' }), t)).toEqual({
|
||||
title: "NoticeLeadAssigned",
|
||||
body: 'NoticeLeadBody{"lead":"Ali","event":"Expo"}',
|
||||
});
|
||||
});
|
||||
|
||||
it("shows no body for a missing or unreadable message, never the raw JSON", () => {
|
||||
expect(noticeText(item({ message: null }), t).body).toBe("");
|
||||
expect(noticeText(item({ message: "{not json" }), t).body).toBe("");
|
||||
expect(noticeText(item({ message: '{"params":{}}' }), t).body).toBe("");
|
||||
});
|
||||
|
||||
it("keeps only string and number parameters", () => {
|
||||
expect(noticeText(item({ message: '{"code":"B","params":{"a":1,"b":null,"c":{"x":1}}}' }), t).body).toBe('B{"a":1}');
|
||||
});
|
||||
});
|
||||
|
||||
describe("isSitePath", () => {
|
||||
it("accepts a path on this site only", async () => {
|
||||
const { isSitePath } = await import("./notifications");
|
||||
expect(isSitePath("/leads/1")).toBe(true);
|
||||
expect(isSitePath("/whatsapp?c=x")).toBe(true);
|
||||
for (const bad of [null, "", "//evil.example", "/\\evil.example", "https://evil.example", "javascript:alert(1)"]) {
|
||||
expect(isSitePath(bad)).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("noticeTime", () => {
|
||||
it("formats in the stored locale and falls back to the raw value", async () => {
|
||||
const { noticeTime } = await import("./notifications");
|
||||
expect(noticeTime("2026-12-02T09:00:00", "en_US")).toMatch(/2026/);
|
||||
expect(noticeTime("2026-12-02T09:00:00", "zh_CN")).toMatch(/2026/);
|
||||
expect(noticeTime("2026-12-02T09:00:00", "not a locale!")).toBe("2026-12-02T09:00:00");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { apiGet, apiPost } from "@/app/lib/clientApi";
|
||||
|
||||
// add-lead-notifications: client wrapper for the bell and /notifications. Calls only this portal's /api/notifications/**.
|
||||
|
||||
export interface AdminNotification {
|
||||
id: number;
|
||||
title: string;
|
||||
/** JSON {"code","params"}: rendered in the reader's language. */
|
||||
message: string | null;
|
||||
type: string;
|
||||
link: string | null;
|
||||
seen: boolean;
|
||||
createDateTime: string;
|
||||
}
|
||||
|
||||
export interface NotificationPage {
|
||||
items: AdminNotification[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
/** `page` is 0-based, as mobile-api is. */
|
||||
export async function listNotifications(page: number, size: number): Promise<NotificationPage> {
|
||||
const res = await apiGet<Partial<NotificationPage>>(`/api/notifications?page=${page}&size=${size}`);
|
||||
return { items: res?.items ?? [], total: res?.total ?? 0 };
|
||||
}
|
||||
|
||||
export async function getUnreadCount(): Promise<number> {
|
||||
return (await apiGet<{ count: number }>("/api/notifications/unread-count"))?.count ?? 0;
|
||||
}
|
||||
|
||||
export async function markRead(id: number): Promise<void> {
|
||||
await apiPost<void>(`/api/notifications/${id}/read`);
|
||||
}
|
||||
|
||||
export async function markAllRead(): Promise<void> {
|
||||
await apiPost<void>("/api/notifications/read-all");
|
||||
}
|
||||
|
||||
/** Fired after read state changes outside the bell, so the bell recounts at once instead of on its next poll. */
|
||||
export const NOTIFICATIONS_CHANGED = "notifications:changed";
|
||||
|
||||
type T = (code: string, params?: Record<string, string | number>) => string;
|
||||
|
||||
/** The title and body in the reader's language. The row stores codes; anything unreadable shows no body. */
|
||||
export function noticeText(item: AdminNotification, t: T): { title: string; body: string } {
|
||||
let body = "";
|
||||
try {
|
||||
const m = JSON.parse(item.message ?? "") as { code?: unknown; params?: Record<string, unknown> };
|
||||
if (typeof m.code === "string") {
|
||||
const params: Record<string, string | number> = {};
|
||||
for (const [k, v] of Object.entries(m.params ?? {})) {
|
||||
if (typeof v === "string" || typeof v === "number") params[k] = v;
|
||||
}
|
||||
body = t(m.code, params);
|
||||
}
|
||||
} catch {
|
||||
/* not JSON: no body */
|
||||
}
|
||||
return { title: t(item.title), body };
|
||||
}
|
||||
|
||||
/** A link opens only when it is a path on this site (a single leading slash, no backslash tricks). */
|
||||
export function isSitePath(link: string | null | undefined): link is string {
|
||||
return !!link && link.startsWith("/") && !link.startsWith("//") && !link.includes("\\");
|
||||
}
|
||||
|
||||
/** Date and time in the reader's locale (stored as en_US, Intl wants en-US). */
|
||||
export function noticeTime(iso: string, locale: string): string {
|
||||
try {
|
||||
return new Intl.DateTimeFormat(locale.replace("_", "-"), { dateStyle: "medium", timeStyle: "short" }).format(new Date(iso));
|
||||
} catch {
|
||||
return iso;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const svc = vi.hoisted(() => ({ listNotifications: vi.fn(), markAllRead: vi.fn() }));
|
||||
vi.mock("@/app/lib/services/notifications", async (orig) => ({
|
||||
...(await orig<typeof import("@/app/lib/services/notifications")>()),
|
||||
...svc,
|
||||
}));
|
||||
|
||||
import NotificationsPage from "./page";
|
||||
|
||||
const row = (id: number, seen: boolean) => ({
|
||||
id, title: "NoticeFollowUpDue", type: "FOLLOW_UP_DUE", link: "/leads", seen, createDateTime: "2026-12-02T08:00:00",
|
||||
message: '{"code":"NoticeFollowUpBody","params":{"due":2,"overdue":1}}',
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
svc.listNotifications.mockResolvedValue({ items: [row(1, false), row(2, true)], total: 2 });
|
||||
svc.markAllRead.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
// add-lead-notifications: the full list of the signed-in user's notifications.
|
||||
describe("/notifications", () => {
|
||||
it("lists the user's notifications with links and marks unread ones", async () => {
|
||||
render(<NotificationsPage />);
|
||||
const links = await screen.findAllByRole("link", { name: /Follow-ups due/ });
|
||||
expect(links).toHaveLength(2);
|
||||
expect(links[0]).toHaveAttribute("href", "/leads");
|
||||
expect(screen.getAllByText("2 due today, 1 overdue")).toHaveLength(2);
|
||||
expect(screen.getAllByText("Unread")).toHaveLength(1);
|
||||
expect(svc.listNotifications).toHaveBeenCalledWith(0, 20);
|
||||
});
|
||||
|
||||
it("Mark all read marks them and reloads", async () => {
|
||||
const changed = vi.fn();
|
||||
window.addEventListener("notifications:changed", changed);
|
||||
render(<NotificationsPage />);
|
||||
await screen.findAllByRole("link", { name: /Follow-ups due/ });
|
||||
svc.listNotifications.mockResolvedValue({ items: [row(1, true), row(2, true)], total: 2 });
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: "Mark all read" }));
|
||||
|
||||
expect(svc.markAllRead).toHaveBeenCalled();
|
||||
await waitFor(() => expect(screen.queryByText("Unread")).not.toBeInTheDocument());
|
||||
expect(changed).toHaveBeenCalled(); // the header bell recounts at once
|
||||
window.removeEventListener("notifications:changed", changed);
|
||||
});
|
||||
|
||||
it("shows an empty state and a load error", async () => {
|
||||
svc.listNotifications.mockResolvedValue({ items: [], total: 0 });
|
||||
const { unmount } = render(<NotificationsPage />);
|
||||
expect(await screen.findByText("No notifications yet.")).toBeInTheDocument();
|
||||
unmount();
|
||||
|
||||
svc.listNotifications.mockRejectedValue(new Error("down"));
|
||||
render(<NotificationsPage />);
|
||||
expect(await screen.findByText("Couldn't load notifications.")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Badge } from "@/app/components/ui/badge";
|
||||
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
||||
import { TablePager } from "@/app/components/ui/table-pager";
|
||||
import { useLocale, useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import {
|
||||
isSitePath,
|
||||
listNotifications,
|
||||
markAllRead,
|
||||
NOTIFICATIONS_CHANGED,
|
||||
noticeText,
|
||||
noticeTime,
|
||||
type NotificationPage,
|
||||
} from "@/app/lib/services/notifications";
|
||||
|
||||
const PAGE_SIZE = 20;
|
||||
|
||||
// add-lead-notifications: every signed-in staff user's own notifications; deliberately not in ROUTE_MODULES.
|
||||
export default function NotificationsPage() {
|
||||
const t = useT();
|
||||
const locale = useLocale();
|
||||
const [page, setPage] = useState(1);
|
||||
const [data, setData] = useState<NotificationPage | null>(null);
|
||||
const [error, setError] = useState(false);
|
||||
|
||||
const load = useCallback(() => {
|
||||
listNotifications(page - 1, PAGE_SIZE)
|
||||
.then((d) => {
|
||||
setError(false);
|
||||
setData(d);
|
||||
})
|
||||
.catch(() => setError(true));
|
||||
}, [page]);
|
||||
|
||||
useEffect(load, [load]);
|
||||
|
||||
async function onMarkAll() {
|
||||
await markAllRead().catch(() => {});
|
||||
window.dispatchEvent(new Event(NOTIFICATIONS_CHANGED));
|
||||
load();
|
||||
}
|
||||
|
||||
const when = (iso: string) => noticeTime(iso, locale);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title={t("NotificationsTitle")}
|
||||
actions={<Button variant="outline" onClick={onMarkAll}>{t("NotificationsMarkAllRead")}</Button>}
|
||||
/>
|
||||
{error && <ErrorState message={t("NotificationsLoadFailed")} onRetry={load} />}
|
||||
{data?.items.length === 0 && <EmptyState title={t("NotificationsEmpty")} />}
|
||||
{!!data?.items.length && (
|
||||
<>
|
||||
<ul className="divide-y rounded-md border bg-card">
|
||||
{data.items.map((item) => {
|
||||
const { title, body } = noticeText(item, t);
|
||||
const inner = (
|
||||
<span className="flex items-start gap-3 px-4 py-3">
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block font-medium">{title}</span>
|
||||
{body && <span className="block text-sm text-muted-foreground">{body}</span>}
|
||||
<span className="block text-xs text-muted-foreground">{when(item.createDateTime)}</span>
|
||||
</span>
|
||||
{!item.seen && <Badge>{t("NotificationsUnreadBadge")}</Badge>}
|
||||
</span>
|
||||
);
|
||||
return (
|
||||
<li key={item.id}>
|
||||
{isSitePath(item.link) ? (
|
||||
<Link href={item.link} className="block hover:bg-accent">{inner}</Link>
|
||||
) : inner}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
<TablePager page={page} pageSize={PAGE_SIZE} total={data.total} onPageChange={setPage} />
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { frameNotFound, frameResponse, htmlBlock } from "@/app/lib/frameHtml";
|
||||
|
||||
// add-custom-html-block: a published page's Custom HTML block as its own sealed document (see frameHtml.ts).
|
||||
// Every miss (unknown company or page, draft, bad index, a block that is not HTML) is the same empty 404.
|
||||
type Ctx = { params: Promise<{ company: string; slug: string; block: string }> };
|
||||
|
||||
export async function GET(_req: Request, { params }: Ctx): Promise<Response> {
|
||||
const { company, slug, block } = await params;
|
||||
if (!/^\d{1,2}$/.test(block)) return frameNotFound();
|
||||
const result = await callMobileApi<{ page?: { blocks?: unknown } }>(`/api/public/pages/${encodeURIComponent(company)}/${encodeURIComponent(slug)}`);
|
||||
if (!result.ok) return result.status === 404 ? frameNotFound() : new Response(null, { status: 502 });
|
||||
const html = htmlBlock(result.data.page?.blocks, block);
|
||||
return html === null ? frameNotFound() : frameResponse(html, { preview: false });
|
||||
}
|
||||
@@ -10,7 +10,7 @@ type Props = { params: Promise<{ company: string; slug: string }> };
|
||||
|
||||
interface PublicPage {
|
||||
company: Branding;
|
||||
page: { slug: string; title: string; metaDescription?: string | null; blocks: PublicBlock[] };
|
||||
page: { slug: string; title: string; metaDescription?: string | null; hideHeader?: boolean; blocks: PublicBlock[] };
|
||||
}
|
||||
|
||||
const load = cache(async (company: string, slug: string): Promise<PublicPage> => {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
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.
|
||||
// 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 }> };
|
||||
|
||||
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 });
|
||||
if (!result.ok) return frameNotFound();
|
||||
const html = htmlBlock(result.data.blocks, block);
|
||||
return html === null ? frameNotFound() : frameResponse(html, { preview: true });
|
||||
}
|
||||
@@ -12,6 +12,7 @@ type Props = { params: Promise<{ id: string }> };
|
||||
interface AdminPage {
|
||||
slug: string;
|
||||
title: string;
|
||||
hideHeader?: boolean;
|
||||
blocks: PublicBlock[];
|
||||
company?: Branding;
|
||||
}
|
||||
@@ -27,7 +28,7 @@ export default async function PagePreview({ params }: Props) {
|
||||
const banner = <p role="status" className="bg-warning/15 px-4 py-2 text-center text-sm font-medium">{t("PagesPreviewBanner")}</p>;
|
||||
return (
|
||||
<RequireModule pathname="/pages">
|
||||
<LandingPage company={page.company ?? { code: "", name: "" }} page={page} banner={banner} preview />
|
||||
<LandingPage company={page.company ?? { code: "", name: "" }} page={page} banner={banner} preview frameBase={`/pages/${encodeURIComponent(id)}/preview/frame`} />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -17,6 +17,23 @@ beforeEach(() => {
|
||||
});
|
||||
|
||||
describe("PagesPage", () => {
|
||||
it("copies a page's full address and reports a clipboard failure", async () => {
|
||||
const user = userEvent.setup();
|
||||
mocks.listPages.mockResolvedValue({
|
||||
items: [{ id: 5, companyId: 2, slug: "hotel-tech", title: "Hotel tech", status: "PUBLISHED", metaDescription: null, blocks: [], updatedAt: "2026-12-02T10:15:00" }],
|
||||
total: 1,
|
||||
});
|
||||
render(<PagesPage />);
|
||||
const write = vi.spyOn(navigator.clipboard, "writeText");
|
||||
await user.click(await screen.findByRole("button", { name: "Copy link /p/INS/hotel-tech" }));
|
||||
expect(write).toHaveBeenCalledWith(`${window.location.origin}/p/INS/hotel-tech`);
|
||||
expect(await screen.findByText("Link copied")).toBeInTheDocument();
|
||||
|
||||
write.mockRejectedValueOnce(new Error("denied"));
|
||||
await user.click(screen.getByRole("button", { name: "Copy link /p/INS/hotel-tech" }));
|
||||
expect(await screen.findByText("Could not copy.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("lists title, address, status and update time", async () => {
|
||||
mocks.listPages.mockResolvedValue({
|
||||
items: [{ id: 5, companyId: 2, slug: "hotel-tech", title: "Hotel tech", status: "PUBLISHED", metaDescription: null, blocks: [], updatedAt: "2026-12-02T10:15:00" }],
|
||||
|
||||
@@ -18,6 +18,7 @@ import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize";
|
||||
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { listPages } from "@/app/lib/services/adminPages";
|
||||
import { formatEmailDate } from "@/app/lib/services/adminEmails";
|
||||
import { CopyAddress } from "@/app/components/pages/CopyAddress";
|
||||
import { pageAddress, type CmsPage } from "@/app/lib/cmsPages";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
@@ -63,7 +64,7 @@ function PagesPageContent() {
|
||||
{
|
||||
id: "address",
|
||||
header: t("PagesAddress"),
|
||||
cell: ({ row }) => <span className="font-mono text-xs">{pageAddress(codeOf(row.original.companyId) || companyCode || "", row.original.slug)}</span>,
|
||||
cell: ({ row }) => <CopyAddress address={pageAddress(codeOf(row.original.companyId) || companyCode || "", row.original.slug)} />,
|
||||
},
|
||||
{
|
||||
accessorKey: "status",
|
||||
|
||||
Loaded 100 of 144 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user