Compare commits

..
Author SHA1 Message Date
ngqileandClaude Opus 5.5 b7d771e2f4 docs: tick add-lead-notifications tasks
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 20:34:36 +08:00
ngqileandClaude Opus 5.5 51ef5b9611 fix(notifications): fit the header at 360 px and recount the bell after Mark all read
The bell pushed the user menu off a 360 px screen; the right-hand controls now
use smaller gaps and a capped company picker on phones. Mark all read on the
page now tells the bell to recount at once instead of on its next poll.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 20:34:02 +08:00
ngqileandClaude Opus 5.5 a99b18fbfd docs: deployment notes for lead notifications
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 20:15:13 +08:00
ngqileandClaude Opus 5.5 a1d13fe8d7 feat(notifications): header bell and notifications page
The bell polls the unread count every 30 s while the tab is visible. Opening it
loads the newest 10 and marks the unread ones read; items link only to paths on
this site. /notifications lists all with paging and Mark all read. Titles and
bodies render from message codes, in English and Chinese.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 20:14:48 +08:00
ngqileandClaude Opus 5.5 72394df1d7 fix(notifications): a WhatsApp notice without a contact name uses its own text
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 20:06:06 +08:00
ngqileandClaude Opus 5.5 56fb94ab81 feat(notifications): tell the chat owner about inbound WhatsApp messages
One unread notification per chat (collapse key WA:<conversation uuid>), linking to
/whatsapp?c=<uuid>. Parameters carry the contact name, never the phone number.
Best effort: a failing store never fails ingest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 20:02:37 +08:00
ngqileandClaude Opus 5.5 909c1754c0 feat(notifications): daily follow-up summary for each salesperson
Runs at 08:00 Malaysia time (leads.follow-up-notice.cron). One summary per
salesperson per company, collapsed per day so a rerun does not duplicate.
Message bodies now keep code before params.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 20:00:28 +08:00
ngqileandClaude Opus 5.5 e3f08bc6cf feat(notifications): bell alerts for assigned leads and web sign-ups
InvitationWiringTest registers StaffNotifier and asserts it is wired.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 19:54:57 +08:00
ngqileandClaude Opus 5.5 66e2e488d9 feat(notifications): admin bell API in mobile-api
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 19:46:06 +08:00
ngqileandClaude Opus 5.5 d5384c6ac0 feat(notifications): staff notification store in services-system
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 19:40:32 +08:00
ngqileandClaude Opus 5.5 26b285cc0a docs(openspec): add-lead-notifications change
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 19:24:33 +08:00
ngqileandClaude Opus 5.5 d195b6f91b docs: lead notifications design
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 19:21:16 +08:00
ngqile dd6cbfe71c Merge pull request 'feat(pages): Custom HTML block in a sealed frame, and Hide page header' (#55) from add-custom-html-block into main
CI / build-and-publish (push) Failing after 0s
2026-12-02 10:22:26 +00:00
ngqileandClaude Opus 5.5 4251d395ad docs: tick add-custom-html-block tasks
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 18:22:05 +08:00
ngqileandClaude Opus 5.5 36dbb4c949 fix(pages): keep the frame's sandbox policy past the config headers
next.config's baseline Content-Security-Policy replaced the frame route's
own header, so a frame address opened directly ran without the sandbox.
A later headers rule for the two frame paths restores it. Also drop the
gap above a header-less page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 18:18:51 +08:00
ngqileandClaude Opus 5.5 f13b2a592a docs: deployment notes for Custom HTML frames
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 18:05:10 +08:00
ngqileandClaude Opus 5.5 cfc817082d feat(pages): Custom HTML block and hide-header switch in the page editor
The iframe guard allow-lists HtmlFrame.tsx for the named FRAME_SANDBOX
only, and asserts it never grants same-origin, forms, top navigation
or modals.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 18:05:00 +08:00
ngqileandClaude Opus 5.5 6a0a6613c1 feat(pages): render Custom HTML blocks as sized sealed frames and honour hide header
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 17:58:15 +08:00
ngqileandClaude Opus 5.5 1ceefd7231 feat(pages): serve Custom HTML blocks from sealed frame routes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 17:56:52 +08:00
ngqileandClaude Opus 5.5 9a7b225827 feat(pages): HTML block type and hide-header option in the services
The counter accepts an HTML block (required, at most 200,000 characters, no
script check because it only runs sealed) and stores a hide-header flag on the
page. mobile-api passes the flag through on save and in the public page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 17:46:32 +08:00
ngqileandClaude Opus 5.5 dcad8cb650 docs(openspec): add-custom-html-block change
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 17:36:54 +08:00
ngqileandClaude Opus 5.5 34732ef2a5 docs: custom HTML block design
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 17:34:20 +08:00
ngqile 53f3298ded Merge pull request 'feat(pages): copy button for page addresses' (#54) from pages-copy-address into main
CI / build-and-publish (push) Failing after 0s
2026-12-02 09:30:03 +00:00
ngqileandClaude Opus 5.5 1e09b652dc feat(pages): copy button for page addresses
The Pages list and the page editor show a copy button next to the page
address. It copies the full URL (this site's origin plus the path) and
reuses the existing copy labels, so no new labels or SQL are needed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 17:29:51 +08:00
ngqile 26b39283e6 Merge pull request 'docs: archive whatsapp-inbox, zh-cn-messages, messages-colite-filter and landing-pages' (#53) from archive-2026-12-02 into main
CI / build-and-publish (push) Failing after 0s
2026-12-02 08:59:31 +00:00
102 changed files with 3640 additions and 84 deletions

No files matched your search

+10
View File
@@ -150,11 +150,17 @@ Run the three in order before the new services-system, gateway and mobile-api go
| `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.
+17
View File
@@ -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`);
+38
View File
@@ -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');
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-02
@@ -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.
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-12-02
@@ -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.
@@ -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);
});
});
+3 -2
View File
@@ -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;
+10 -3
View File
@@ -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);
});
});
+67
View File
@@ -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": "格式",
+5 -1
View File
@@ -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" }],
+2 -1
View File
@@ -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",
@@ -0,0 +1,30 @@
import { describe, it, expect } from "vitest";
import { NextRequest } from "next/server";
import { middleware } from "./middleware";
import { guardDecision, isPublicPath } from "@/app/lib/routeGuard";
// add-custom-html-block: frame responses carry their own sandbox policy, so the middleware adds no nonce policy.
const get = (path: string) => new NextRequest(new URL(path, "https://portal.test"), { method: "GET" });
describe("middleware: custom HTML frames", () => {
it("lets a signed-out visitor load a public frame, without the nonce policy", async () => {
const res = await middleware(get("/p/INS/hotel-technology/frame/0"));
expect(res.status).toBe(200);
expect(res.headers.get("content-security-policy")).toBeNull();
});
it("sends a signed-out preview frame request to sign in", async () => {
const res = await middleware(get("/pages/5/preview/frame/0"));
expect(res.status).toBeGreaterThanOrEqual(300);
expect(res.headers.get("location")).toContain("/login");
});
it("keeps the nonce policy on the landing page itself and on look-alike paths", async () => {
expect((await middleware(get("/p/INS/hotel-technology"))).headers.get("content-security-policy")).toMatch(/nonce-/);
expect(isPublicPath("/p/INS/hotel-technology/frame/0")).toBe(true);
for (const p of ["/p/INS/hotel/frame/x", "/p/INS/hotel/frame/0/x", "/p/INS/frame/0", "/p/INS/hotel/frame/"]) {
expect(isPublicPath(p), p).toBe(false);
expect(guardDecision(p, null), p).toBe("/login");
}
});
});
+3 -1
View File
@@ -2,7 +2,7 @@ import { NextResponse, type NextRequest } from "next/server";
import { sessionEnded, type SessionData } from "@/app/lib/sessionCodec";
import { openSession } from "@/app/lib/sessionSeal";
import { sessionCookieName } from "@/app/lib/sessionCookieName";
import { guardDecision } from "@/app/lib/routeGuard";
import { guardDecision, LANDING_FRAME_PATH, PREVIEW_FRAME_PATH } from "@/app/lib/routeGuard";
import { loginUrl } from "@/app/lib/returnTo";
import { isCrossSiteWrite } from "@/app/lib/sameOrigin";
import { bodyLimit } from "@/app/lib/bodyLimit";
@@ -44,6 +44,8 @@ function guard(req: NextRequest, session: SessionData | null): NextResponse {
}
return NextResponse.redirect(url);
}
// add-custom-html-block: a Custom HTML frame sends its own sandbox policy; the nonce policy would block its scripts.
if (LANDING_FRAME_PATH.test(pathname) || PREVIEW_FRAME_PATH.test(pathname)) return NextResponse.next();
return withScriptPolicy(req);
}
@@ -0,0 +1,21 @@
import { describe, it, expect } from "vitest";
import nextConfig from "./next.config";
import { FRAME_CSP } from "./app/lib/frameHtml";
// add-custom-html-block: config headers replace a route's own header of the same name, so the baseline
// Content-Security-Policy would strip the frame's sandbox. A later rule for the frame paths puts it back
// (Next.js: the last rule setting a key wins).
describe("Custom HTML frame headers", () => {
it("sends the sandbox policy on both frame paths, after the baseline rule", async () => {
const rules = await nextConfig.headers!();
const baseline = rules.findIndex((r) => r.source === "/:path*");
for (const source of ["/p/:company/:slug/frame/:block", "/pages/:id/preview/frame/:block"]) {
const at = rules.findIndex((r) => r.source === source);
expect(at, source).toBeGreaterThan(baseline);
const sent = Object.fromEntries(rules[at].headers.map((h) => [h.key, h.value]));
expect(sent["Content-Security-Policy"]).toBe(FRAME_CSP);
expect(sent["Referrer-Policy"]).toBe("no-referrer");
}
expect(FRAME_CSP).toMatch(/^sandbox allow-scripts allow-popups allow-popups-to-escape-sandbox; frame-ancestors 'self'/);
});
});
+10 -1
View File
@@ -1,5 +1,6 @@
import type { NextConfig } from "next";
import { SECURITY_HEADERS } from "./app/lib/securityHeaders";
import { FRAME_CSP } from "./app/lib/frameHtml";
// 2026-10-07: CI run 5545 (#731 CMS forms) failed in Docker build (a runner storage fault while run
// 5544 built at the same time), so nothing from #731 rolled out. Only a push that changes this
@@ -9,7 +10,15 @@ const nextConfig: NextConfig = {
// harden-portal-requests (F30): no X-Powered-By, baseline security headers everywhere.
poweredByHeader: false,
async headers() {
return [{ source: "/:path*", headers: [...SECURITY_HEADERS] }];
// add-custom-html-block: these headers replace a route's own, so the Custom HTML frame paths get their sandbox
// policy back from a later rule (the last rule setting a key wins). Without it, a frame address opened directly
// would run pasted scripts as this origin.
const frame = [{ key: "Content-Security-Policy", value: FRAME_CSP }, { key: "Referrer-Policy", value: "no-referrer" }];
return [
{ source: "/:path*", headers: [...SECURITY_HEADERS] },
{ source: "/p/:company/:slug/frame/:block", headers: frame },
{ source: "/pages/:id/preview/frame/:block", headers: frame },
];
},
reactStrictMode: true,
// Stop `next dev` writing AGENTS.md/CLAUDE.md into the repo; agent instructions live in the root CLAUDE.md.
@@ -7,6 +7,11 @@ public class RestApiSystemServiceConstants {
public static final String API_REST_SYSTEM_USER_FIND_BY_USERNAME = "/user/findByUsername/{username}";
public static final String API_REST_SYSTEM_USER_FIND_BY_ID = "/user/findById/{id}";
public static final String API_REST_SYSTEM_USER_ACTIVE_ADMIN_OF = "/user/{id}/activeAdminOf/{companyId}";
// add-lead-notifications: the staff bell (receiver = the caller's user id)
public static final String API_REST_SYSTEM_NOTIFICATION_INBOX = "/notification/inbox/";
public static final String API_REST_SYSTEM_NOTIFICATION_UNREAD_COUNT = "/notification/unreadCount/";
public static final String API_REST_SYSTEM_NOTIFICATION_MARK_READ = "/notification/markRead/";
public static final String API_REST_SYSTEM_NOTIFICATION_MARK_ALL_READ = "/notification/markAllRead/";
public static final String API_REST_SYSTEM_USER_ACTIVE_WITH_MODULE = "/user/activeWithModule?companyId={companyId}&module={module}";
public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL = "/user/findByEmail/{email}";
public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL_AND_ID_NOT = "/user/findByEmailAndIdNot/{email}/{id}";
@@ -0,0 +1,54 @@
package com.solvway.mobile.api.controller.admin;
import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.service.AdminNotificationService;
import com.solvway.mobile.api.useraccess.AdminModule;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/** add-lead-notifications: the signed-in user's own bell. Must stay under {@code controller..} for AppAccessAspect. */
@RestController
@RequestMapping("/api/admin")
public class AdminNotificationController {
private final AdminNotificationService service;
public AdminNotificationController(AdminNotificationService service) {
this.service = service;
}
@AppAuth
@AdminModule(AdminModule.ANY_ADMIN)
@GetMapping("/notifications")
public ResponseEntity<Map<String, Object>> list(@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "20") int size) {
return ResponseEntity.ok(service.list(page, size));
}
@AppAuth
@AdminModule(AdminModule.ANY_ADMIN)
@GetMapping("/notifications/unread-count")
public ResponseEntity<Map<String, Object>> unreadCount() {
return ResponseEntity.ok(service.unreadCount());
}
@AppAuth
@AdminModule(AdminModule.ANY_ADMIN)
@PostMapping("/notifications/{id}/read")
public ResponseEntity<Void> markRead(@PathVariable long id) {
service.markRead(id);
return ResponseEntity.noContent().build();
}
@AppAuth
@AdminModule(AdminModule.ANY_ADMIN)
@PostMapping("/notifications/read-all")
public ResponseEntity<Map<String, Object>> markAllRead() {
return ResponseEntity.ok(service.markAllRead());
}
}
@@ -5,4 +5,11 @@ import java.util.Map;
/** A landing page as the editor saves it. Blocks pass through to the counter, which validates them. companyId counts only on create. */
public record AdminPageRequest(Long companyId, String slug, String title, String metaDescription, String status,
List<Map<String, Object>> blocks) {}
boolean hideHeader, List<Map<String, Object>> blocks) {
/** A page that shows its header (the default). */
public AdminPageRequest(Long companyId, String slug, String title, String metaDescription, String status,
List<Map<String, Object>> blocks) {
this(companyId, slug, title, metaDescription, status, false, blocks);
}
}
@@ -163,6 +163,7 @@ public class AdminEventLeadService {
body.put("nextFollowUpDate", followUp == null ? null : followUp.toString());
body.put("notes", trimmed(r.notes()));
body.put("doneBy", caller.getUsername());
body.put("doneByUserId", caller.getId()); // add-lead-notifications: self-assignment is silent
try {
return view(restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_CAPTURE), MAP, body).getBody(),
known, new HashMap<>());
@@ -281,6 +282,7 @@ public class AdminEventLeadService {
body.put("notes", trimmed(r.notes()));
body.put("attended", r.attended());
body.put("doneBy", caller.getUsername());
body.put("doneByUserId", caller.getId()); // add-lead-notifications: self-assignment is silent
Map<String, Object> saved = restTemplateUtil.postForEntity(url(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LEAD_UPDATE), MAP, body).getBody();
// field names only: follow-up values are personal data
List<String> changed = new ArrayList<>();
@@ -0,0 +1,65 @@
package com.solvway.mobile.api.service;
import com.solvway.core.model.User;
import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import java.util.Map;
/**
* add-lead-notifications: the staff bell. Every call acts for the signed-in user, whose id comes from the token,
* never from the request; service-system only reads and marks that user's rows.
*/
@Service
public class AdminNotificationService {
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
private static final int MAX_PAGE = 50;
private final RestTemplateCustomUtil rest;
private final AdminAuthenticationService adminAuthenticationService;
public AdminNotificationService(RestTemplateCustomUtil rest, AdminAuthenticationService adminAuthenticationService) {
this.rest = rest;
this.adminAuthenticationService = adminAuthenticationService;
}
private long caller() {
User u = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
if (u == null || u.getId() == null) throw new CodedResponseStatusException(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED");
return u.getId();
}
private String url(String api, Object... parts) {
StringBuilder b = new StringBuilder(rest.getURLforApiService(api));
for (int i = 0; i < parts.length; i++) b.append(i == 0 ? "" : "/").append(parts[i]);
return b.toString();
}
public Map<String, Object> list(int page, int size) {
int p = Math.max(page, 0);
int s = Math.min(Math.max(size, 1), MAX_PAGE);
return rest.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_NOTIFICATION_INBOX, caller(), p, s), MAP).getBody();
}
public Map<String, Object> unreadCount() {
return rest.getForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_NOTIFICATION_UNREAD_COUNT, caller()), MAP).getBody();
}
public void markRead(long id) {
try {
rest.postForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_NOTIFICATION_MARK_READ, caller(), id), Void.class, Map.of());
} catch (HttpClientErrorException.NotFound e) {
throw new CodedResponseStatusException(HttpStatus.NOT_FOUND, "Notification not found", "NOTIFICATION_NOT_FOUND");
}
}
public Map<String, Object> markAllRead() {
return rest.postForEntity(url(RestApiSystemServiceConstants.API_REST_SYSTEM_NOTIFICATION_MARK_ALL_READ, caller()), MAP, Map.of()).getBody();
}
}
@@ -93,6 +93,7 @@ public class AdminPageService {
page.put("title", r.title());
page.put("metaDescription", r.metaDescription());
page.put("status", r.status());
page.put("hideHeader", r.hideHeader());
page.put("blocks", r.blocks() == null ? List.of() : r.blocks());
Map<String, Object> body = new LinkedHashMap<>();
body.put("page", page);
@@ -59,6 +59,7 @@ public class PublicPageService {
page.put("slug", f.page().get("slug"));
page.put("title", f.page().get("title"));
page.put("metaDescription", f.page().get("metaDescription"));
page.put("hideHeader", Boolean.TRUE.equals(f.page().get("hideHeader")));
page.put("blocks", blocks);
return Map.of("company", f.company(), "page", page);
}
@@ -0,0 +1,41 @@
package com.solvway.mobile.api.controller.admin;
import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.service.AdminNotificationService;
import com.solvway.mobile.api.useraccess.AdminModule;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Method;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
// add-lead-notifications: every signed-in staff user has the bell; no module, and no user id from the request.
class AdminNotificationControllerTest {
@Test
void everyEndpointNeedsASignedInStaffUserOnly() {
for (Method m : AdminNotificationController.class.getDeclaredMethods()) {
if (!java.lang.reflect.Modifier.isPublic(m.getModifiers())) continue;
assertThat(m.isAnnotationPresent(AppAuth.class)).as(m.getName()).isTrue();
assertThat(m.getAnnotation(AdminModule.class).value()).as(m.getName()).containsExactly(AdminModule.ANY_ADMIN);
}
}
@Test
void passesThrough() {
AdminNotificationService service = mock(AdminNotificationService.class);
AdminNotificationController c = new AdminNotificationController(service);
when(service.list(2, 20)).thenReturn(Map.of("total", 0));
when(service.unreadCount()).thenReturn(Map.of("count", 1));
assertThat(c.list(2, 20).getBody()).containsEntry("total", 0);
assertThat(c.unreadCount().getBody()).containsEntry("count", 1);
assertThat(c.markRead(5L).getStatusCode().value()).isEqualTo(204);
verify(service).markRead(5L);
c.markAllRead();
verify(service).markAllRead();
}
}
@@ -302,6 +302,16 @@ class AdminEventLeadServiceTest {
.containsEntry("eventUuid", String.valueOf(EV)).containsEntry("leadType", "NEW").containsEntry("mobile", "+60123456789");
}
@Test
void captureAndUpdateSendTheActingUsersIdSoSelfAssignmentIsSilent() {
// add-lead-notifications: the counter skips the bell when the actor is the new salesperson.
service.capture(String.valueOf(EV), capture(null, "Aisyah", "+60 12-345 6789", null));
assertThat(sent(CAPTURE)).containsEntry("doneByUserId", 21L);
stubStored(EV, 23L, List.of());
service.update(String.valueOf(EV), String.valueOf(EL), new AdminEventLeadUpdateRequest(23L, null, "CONTACTED", List.of(), null, null));
assertThat(sent(UPDATE)).containsEntry("doneByUserId", 21L);
}
@Test
void neitherMobileNorEmailIsRefusedNamingBoth() {
assertThatThrownBy(() -> service.capture(String.valueOf(EV), capture(null, "Aisyah", "", " ")))
@@ -0,0 +1,103 @@
package com.solvway.mobile.api.service;
import com.solvway.core.model.User;
import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
// add-lead-notifications: the bell's admin API always acts for the signed-in user, never one named in the request.
@SuppressWarnings({"unchecked", "rawtypes"})
class AdminNotificationServiceTest {
private RestTemplateCustomUtil rest;
private AdminAuthenticationService auth;
private AdminNotificationService service;
private MockedStatic<HttpReqRespUtils> http;
@BeforeEach
void setUp() {
rest = mock(RestTemplateCustomUtil.class);
auth = mock(AdminAuthenticationService.class);
service = new AdminNotificationService(rest, auth);
when(rest.getURLforApiService(any())).thenAnswer(i -> "http://gw" + i.getArgument(0));
http = mockStatic(HttpReqRespUtils.class);
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
User u = new User();
u.setId(11L);
u.setCompanyId(2L);
when(auth.loadUserByToken("tok")).thenReturn(u);
}
@AfterEach
void close() {
http.close();
}
@Test
void listsTheCallersOwnNotifications() {
Map<String, Object> page = Map.of("items", List.of(), "total", 0);
when(rest.getForEntity(eq("http://gw/notification/inbox/11/1/20"), any(ParameterizedTypeReference.class)))
.thenReturn(ResponseEntity.ok(page));
assertThat(service.list(1, 20)).isEqualTo(page);
}
@Test
void capsThePageSize() {
when(rest.getForEntity(eq("http://gw/notification/inbox/11/0/50"), any(ParameterizedTypeReference.class)))
.thenReturn(ResponseEntity.ok(Map.of("items", List.of(), "total", 0)));
service.list(-3, 500);
verify(rest).getForEntity(eq("http://gw/notification/inbox/11/0/50"), any(ParameterizedTypeReference.class));
}
@Test
void countsTheCallersUnread() {
when(rest.getForEntity(eq("http://gw/notification/unreadCount/11"), any(ParameterizedTypeReference.class)))
.thenReturn(ResponseEntity.ok(Map.of("count", 3)));
assertThat(service.unreadCount()).containsEntry("count", 3);
}
@Test
void marksReadForTheCaller() {
service.markRead(5L);
verify(rest).postForEntity(eq("http://gw/notification/markRead/11/5"), eq(Void.class), any());
when(rest.postForEntity(eq("http://gw/notification/markAllRead/11"), any(ParameterizedTypeReference.class), any()))
.thenReturn(ResponseEntity.ok(Map.of("count", 2)));
assertThat(service.markAllRead()).containsEntry("count", 2);
verify(rest).postForEntity(eq("http://gw/notification/markAllRead/11"), any(ParameterizedTypeReference.class), any());
}
@Test
void anotherUsersNotificationIsNotFound() {
when(rest.postForEntity(eq("http://gw/notification/markRead/11/6"), eq(Void.class), any()))
.thenThrow(HttpClientErrorException.create(HttpStatus.NOT_FOUND, "nf", null, null, null));
assertThatThrownBy(() -> service.markRead(6L))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(404));
}
@Test
void notSignedInIsRefused() {
when(auth.loadUserByToken("tok")).thenReturn(null);
assertThatThrownBy(() -> service.unreadCount())
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(401));
}
}
@@ -115,6 +115,17 @@ class AdminPageServiceTest {
assertThat((Map<String, Object>) sent.get("page")).containsEntry("companyId", 2L).containsEntry("slug", "hotel").containsEntry("id", null);
}
@Test
void theHideHeaderOptionIsSentToTheCounter() {
caller(2L, false);
service.create(new AdminPageRequest(null, "designed", "Designed", null, "DRAFT", true, List.of(Map.<String, Object>of("type", "HTML", "html", "<script>x()</script>"))));
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
verify(rest).postForEntity(eq(SAVE), any(ParameterizedTypeReference.class), body.capture());
Map<String, Object> page = (Map<String, Object>) ((Map<String, Object>) body.getValue()).get("page");
assertThat(page).containsEntry("hideHeader", true);
assertThat((List<Map<String, Object>>) page.get("blocks")).first().isEqualTo(Map.of("type", "HTML", "html", "<script>x()</script>"));
}
@Test
void updateKeepsTheIdAndStoredCompany() {
caller(2L, false);
@@ -123,6 +123,16 @@ class PublicPageServiceTest {
assertThat(blocks.get(1)).doesNotContainKey("closed");
}
@Test
void thePageCarriesItsHideHeaderOptionDefaultingToOff() {
assertThat((Map<String, Object>) service.page("INS", "hotel-technology").get("page")).containsEntry("hideHeader", false);
Map<String, Object> designed = page();
designed.put("hideHeader", true);
when(rest.getForEntity(eq(PUBLISHED), any(ParameterizedTypeReference.class), eq(COMPANY), eq("hotel-technology")))
.thenReturn(ResponseEntity.ok(designed));
assertThat((Map<String, Object>) service.page("INS", "hotel-technology").get("page")).containsEntry("hideHeader", true);
}
@Test
void aFormWhoseEventEndedIsClosedButThePageStillShows() {
stubEvent(LocalDateTime.of(2027, 1, 15, 23, 59));
@@ -1,6 +1,8 @@
package com.solvway.services.counter.constant;
public class RestApiSystemServiceConstant {
// add-lead-notifications: the staff bell
public static final String API_REST_SYSTEM_NOTIFICATION_SEND = "/notification/send";
//Message
public static final String API_REST_SYSTEM_MESSAGE_FIND_BY_CODE = "/message/getMessagesByCode/{code}";
public static final String API_REST_SYSTEM_MESSAGE_FIND_BY_CODE_AND_AREA = "/message/getMessagesByCodeAndArea/{code}/{Area}";
@@ -5,4 +5,11 @@ import java.util.List;
/** A landing page as the API sends and receives it; blocks are omitted (null) in list rows. */
public record CmsPageDto(Long id, Long companyId, String slug, String title, String metaDescription, String status,
List<CmsBlock> blocks, LocalDateTime updatedAt) {}
boolean hideHeader, List<CmsBlock> blocks, LocalDateTime updatedAt) {
/** A page that shows its header (the default). */
public CmsPageDto(Long id, Long companyId, String slug, String title, String metaDescription, String status,
List<CmsBlock> blocks, LocalDateTime updatedAt) {
this(id, companyId, slug, title, metaDescription, status, false, blocks, updatedAt);
}
}
@@ -19,5 +19,14 @@ public record EventLeadCaptureRequest(
List<Long> interestIds,
LocalDate nextFollowUpDate,
String notes,
String doneBy
) {}
String doneBy,
/* add-lead-notifications: the acting staff user's id, so assigning a lead to yourself is silent. */
Long doneByUserId
) {
public EventLeadCaptureRequest(Long companyId, long eventUuid, Long leadUuid, String name, String mobileE164, String email,
String companyName, String jobTitle, Long salespersonUserId, String temperature, String status,
List<Long> interestIds, LocalDate nextFollowUpDate, String notes, String doneBy) {
this(companyId, eventUuid, leadUuid, name, mobileE164, email, companyName, jobTitle, salespersonUserId, temperature, status,
interestIds, nextFollowUpDate, notes, doneBy, null);
}
}
@@ -6,9 +6,15 @@ import java.util.List;
/** Replaces an event lead's working fields and its interest set. Values arrive validated by mobile-api. attended: true stamps now if empty, false clears, null leaves it. */
public record EventLeadUpdateRequest(Long companyId, long eventLeadUuid, Long salespersonUserId, String temperature,
String status, List<Long> interestIds, LocalDate nextFollowUpDate, String notes,
String doneBy, Boolean attended) {
String doneBy, Boolean attended, Long doneByUserId) {
/** doneByUserId (add-lead-notifications): the acting staff user's id, so assigning a lead to yourself is silent. */
public EventLeadUpdateRequest(Long companyId, long eventLeadUuid, Long salespersonUserId, String temperature,
String status, List<Long> interestIds, LocalDate nextFollowUpDate, String notes,
String doneBy, Boolean attended) {
this(companyId, eventLeadUuid, salespersonUserId, temperature, status, interestIds, nextFollowUpDate, notes, doneBy, attended, null);
}
public EventLeadUpdateRequest(Long companyId, long eventLeadUuid, Long salespersonUserId, String temperature,
String status, List<Long> interestIds, LocalDate nextFollowUpDate, String notes, String doneBy) {
this(companyId, eventLeadUuid, salespersonUserId, temperature, status, interestIds, nextFollowUpDate, notes, doneBy, null);
this(companyId, eventLeadUuid, salespersonUserId, temperature, status, interestIds, nextFollowUpDate, notes, doneBy, null, null);
}
}
@@ -19,6 +19,7 @@ public class CmsPage {
private String title;
private String metaDescription;
private String status = "DRAFT";
private boolean hideHeader;
/** JSON array of blocks, replaced as a whole on every save. */
@Column(columnDefinition = "json")
private String blocks;
@@ -8,6 +8,7 @@ import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.time.LocalDate;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
@@ -63,4 +64,19 @@ public interface EventLeadRepository extends JpaRepository<EventLead, Long> {
@Query("SELECT e, l FROM EventLead e, Lead l WHERE l.uuid = e.leadUuid AND l.companyId = e.companyId"
+ " AND e.eventUuid = :eventUuid AND l.emailNormalised = :email")
List<Object[]> findByEventAndEmail(@Param("eventUuid") long eventUuid, @Param("email") String email);
/** add-lead-notifications: one salesperson's open leads due today and overdue. */
interface FollowUpRow {
Long getCompanyId();
Long getSalespersonUserId();
Long getDueToday();
Long getOverdue();
}
/** Open (not WON or LOST) event leads with a salesperson and a follow-up date today or earlier, per company and salesperson. */
@Query(nativeQuery = true, value = "SELECT company_id AS companyId, salesperson_user_id AS salespersonUserId,"
+ " CAST(SUM(next_follow_up_date = :today) AS SIGNED) AS dueToday, CAST(SUM(next_follow_up_date < :today) AS SIGNED) AS overdue"
+ " FROM event_lead WHERE salesperson_user_id IS NOT NULL AND status NOT IN ('WON', 'LOST')"
+ " AND next_follow_up_date <= :today GROUP BY company_id, salesperson_user_id ORDER BY company_id, salesperson_user_id")
List<FollowUpRow> followUpsDue(@Param("today") LocalDate today);
}
@@ -12,7 +12,8 @@ import java.util.regex.Pattern;
/**
* Landing-page block rules, ported from babyboo's CmsBlockValidator (specs/cms-pages) without the product blocks.
* Co-Lite changes: images are uploaded ids of the page's company, FORM points at an event of that company,
* buttons may also use mailto: and tel:, and HTML holding scripts is refused (the public page sanitises as well).
* buttons may also use mailto: and tel:, and rich-text HTML holding scripts is refused (the public page sanitises as well).
* The HTML block (custom HTML) is exempt from the script check: it is served only inside a sandboxed frame.
* Throws 422 on the first violation, with the reason "path|MessageCode".
*/
public final class CmsBlockValidator {
@@ -44,6 +45,11 @@ public final class CmsBlockValidator {
button(b, path);
}
case "RICH_TEXT" -> html(b.getHtml(), path + ".html");
case "HTML" -> {
// Custom HTML may hold scripts: it is only ever served in a sandboxed frame (add-custom-html-block).
required(b.getHtml(), path + ".html");
max(b.getHtml(), path + ".html", 200_000);
}
case "IMAGE_TEXT" -> {
image(b, path, ownImage);
max(b.getHeading(), path + ".heading", 120);
@@ -69,6 +69,7 @@ public class CmsPageService {
row.setTitle(dto.title().trim());
row.setMetaDescription(dto.metaDescription() == null || dto.metaDescription().isBlank() ? null : dto.metaDescription().trim());
row.setStatus(dto.status());
row.setHideHeader(dto.hideHeader());
row.setBlocks(write(dto.blocks() == null ? List.of() : dto.blocks()));
row.setUpdatedBy(user);
row.setUpdatedAt(LocalDateTime.now());
@@ -109,7 +110,7 @@ public class CmsPageService {
private CmsPageDto toDto(CmsPage p, boolean withBlocks) {
return new CmsPageDto(p.getId(), p.getCompanyId(), p.getSlug(), p.getTitle(), p.getMetaDescription(), p.getStatus(),
withBlocks ? read(p.getBlocks()) : null, p.getUpdatedAt());
p.isHideHeader(), withBlocks ? read(p.getBlocks()) : null, p.getUpdatedAt());
}
private String write(List<CmsBlock> blocks) {
@@ -54,6 +54,7 @@ public class EventLeadService {
private final EventRepository eventRepository;
private final GuestLinker guestLinker;
private final WhatsappNotifier whatsappNotifier;
private final StaffNotifier staffNotifier;
// ponytail: null event repository, linker and notifier keep older wiring working; drop once callers pass all.
public EventLeadService(LeadRepository leadRepository, EventLeadRepository eventLeadRepository,
@@ -70,6 +71,24 @@ public class EventLeadService {
eventRepository, guestLinker, null);
}
public EventLeadService(LeadRepository leadRepository, EventLeadRepository eventLeadRepository,
EventLeadInterestRepository eventLeadInterestRepository,
EventLeadStatusChangeRepository eventLeadStatusChangeRepository,
EventRepository eventRepository, GuestLinker guestLinker, WhatsappNotifier whatsappNotifier) {
this(leadRepository, eventLeadRepository, eventLeadInterestRepository, eventLeadStatusChangeRepository,
eventRepository, guestLinker, whatsappNotifier, null);
}
/**
* add-lead-notifications: the staff bell for a capture or a registration. A landing-page sign-up is a sign-up;
* anything else tells the salesperson the lead is theirs (silent when they assigned it to themselves).
*/
public void notifyStaff(EventLead e, Lead lead, String source, Long actorUserId) {
if (staffNotifier == null) return;
if ("WEB".equals(source)) staffNotifier.webSignup(e, lead);
else staffNotifier.leadAssigned(e, lead, actorUserId);
}
/** The one place every capture or salesperson change tells the WhatsApp service; skipped for a lead with no mobile. */
public void notifyLeadChanged(Lead lead) {
if (whatsappNotifier != null && lead.getMobileE164() != null) {
@@ -161,6 +180,7 @@ public class EventLeadService {
linkGuest(req.eventUuid(), eventLead, lead);
List<Long> interestIds = saveInterests(eventLead.getId(), req.companyId(), req.interestIds());
notifyLeadChanged(lead);
notifyStaff(eventLead, lead, null, req.doneByUserId());
return detail(eventLead, lead, interestIds);
}
@@ -219,7 +239,10 @@ public class EventLeadService {
List<Long> interestIds = saveInterests(eventLead.getId(), req.companyId(), req.interestIds());
Lead lead = leadRepository.findByUuidAndCompanyId(eventLead.getLeadUuid(), req.companyId())
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
if (salespersonChanged) notifyLeadChanged(lead);
if (salespersonChanged) {
notifyLeadChanged(lead);
notifyStaff(eventLead, lead, null, req.doneByUserId());
}
return detail(eventLead, lead, interestIds);
}
@@ -0,0 +1,46 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.EventLeadRepository.FollowUpRow;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* add-lead-notifications: every morning, each salesperson with open event leads due today or overdue gets one summary
* in the bell. A second run on the same day refreshes an unread summary instead of adding one (collapse key).
*/
@Component
@Slf4j
public class FollowUpNoticeJob {
private static final ZoneId MALAYSIA = ZoneId.of("Asia/Kuala_Lumpur");
private final EventLeadRepository eventLeads;
private final StaffNotifier notifier;
public FollowUpNoticeJob(EventLeadRepository eventLeads, StaffNotifier notifier) {
this.eventLeads = eventLeads;
this.notifier = notifier;
}
@Scheduled(cron = "${leads.follow-up-notice.cron:0 0 8 * * *}", zone = "Asia/Kuala_Lumpur")
public void daily() {
int sent = run(LocalDate.now(MALAYSIA));
log.info("Follow-up summaries sent to {} salespeople", sent);
}
int run(LocalDate today) {
List<FollowUpRow> rows = eventLeads.followUpsDue(today);
Map<Long, List<FollowUpRow>> byCompany = rows.stream()
.collect(Collectors.groupingBy(FollowUpRow::getCompanyId, LinkedHashMap::new, Collectors.toList()));
byCompany.forEach((company, list) -> notifier.followUpsDue(company, list, today));
return rows.size();
}
}
@@ -134,6 +134,7 @@ public class RegistrationService {
eventLeadService.saveInterests(e.getId(), req.companyId(), req.interestIds());
link(req, e, lead);
eventLeadService.notifyLeadChanged(lead);
eventLeadService.notifyStaff(e, lead, req.source(), null);
return new RegisterResult(match.isEmpty() ? "CREATED" : "LINKED", String.valueOf(e.getUuid()));
}
@@ -149,6 +150,8 @@ public class RegistrationService {
}
link(req, e, lead);
if (assign) eventLeadService.notifyLeadChanged(lead);
// add-lead-notifications: a repeat landing-page sign-up is news to the team; a QR scan only when it assigns.
if (WEB.equals(req.source()) || assign) eventLeadService.notifyStaff(e, lead, req.source(), null);
return new RegisterResult(assign ? "ASSIGNED" : "ALREADY_CAPTURED", String.valueOf(e.getUuid()));
}
@@ -0,0 +1,151 @@
package com.solvway.services.counter.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.solvway.core.constant.SystemConstants;
import com.solvway.services.counter.constant.RestApiSystemServiceConstant;
import com.solvway.services.counter.model.Event;
import com.solvway.services.counter.model.EventLead;
import com.solvway.services.counter.model.EventSalesperson;
import com.solvway.services.counter.model.Lead;
import com.solvway.services.counter.repo.EventLeadRepository.FollowUpRow;
import com.solvway.services.counter.repo.EventRepository;
import com.solvway.services.counter.repo.EventSalespersonRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.client.RestTemplate;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* add-lead-notifications: tells staff about their leads through the bell in service-system. Resolves who hears
* about it, then sends after the surrounding transaction commits. Best effort: never throws, no retry, and logs ids
* only. Parameters carry the lead's and event's names, never a phone number or email address.
*/
@Component
@Slf4j
public class StaffNotifier {
private static final int TIMEOUT_MS = 2000;
private static final String URL = "http://" + SystemConstants.SERVICE_ID_SYSTEM
+ RestApiSystemServiceConstant.API_REST_SYSTEM_NOTIFICATION_SEND;
private static final ObjectMapper JSON = new ObjectMapper();
private final RestTemplate restTemplate;
private final EventRepository events;
private final EventSalespersonRepository team;
@Autowired
public StaffNotifier(EventRepository events, EventSalespersonRepository team) {
// The shared RestTemplate bean has 5 s timeouts; this call must never hold a request thread that long.
SimpleClientHttpRequestFactory f = new SimpleClientHttpRequestFactory();
f.setConnectTimeout(TIMEOUT_MS);
f.setReadTimeout(TIMEOUT_MS);
this.restTemplate = new RestTemplate(f);
this.events = events;
this.team = team;
}
StaffNotifier(RestTemplate restTemplate, EventRepository events, EventSalespersonRepository team) {
this.restTemplate = restTemplate;
this.events = events;
this.team = team;
}
/** The event lead's salesperson hears about it, unless nobody is assigned or they assigned it to themselves. */
public void leadAssigned(EventLead e, Lead lead, Long actorUserId) {
Long to = e.getSalespersonUserId();
if (to == null || to.equals(actorUserId)) return;
send(List.of(row(to, e, lead, "LEAD_ASSIGNED", "NoticeLeadAssigned")));
}
/** A landing-page sign-up: its salesperson, else everyone on the event's sales team, else nobody. */
public void webSignup(EventLead e, Lead lead) {
Set<Long> to = new LinkedHashSet<>();
if (e.getSalespersonUserId() != null) {
to.add(e.getSalespersonUserId());
} else {
team.findByEventUuid(e.getEventUuid()).stream().map(EventSalesperson::getUserId).forEach(to::add);
}
if (to.isEmpty()) return;
List<Map<String, Object>> rows = new ArrayList<>();
for (Long userId : to) rows.add(row(userId, e, lead, "WEB_SIGNUP", "NoticeWebSignup"));
send(rows);
}
/** The morning summary for one company: one row per salesperson, collapsed for the day (a rerun refreshes it). */
public void followUpsDue(long companyId, List<FollowUpRow> rows, LocalDate today) {
List<Map<String, Object>> out = new ArrayList<>();
for (FollowUpRow r : rows) {
Map<String, Object> params = new LinkedHashMap<>();
params.put("due", r.getDueToday());
params.put("overdue", r.getOverdue());
out.add(row(r.getSalespersonUserId(), companyId, "FOLLOW_UP_DUE", "NoticeFollowUpDue",
body("NoticeFollowUpBody", params), "/leads", "FOLLOW_UP:" + today));
}
if (!out.isEmpty()) send(out);
}
private Map<String, Object> row(long userId, EventLead e, Lead lead, String type, String title) {
Map<String, Object> params = new LinkedHashMap<>();
params.put("lead", Objects.toString(lead.getName(), ""));
params.put("event", events.findByUuid(e.getEventUuid()).map(Event::getName).orElse(""));
return row(userId, e.getCompanyId(), type, title, body("NoticeLeadBody", params),
"/leads/" + lead.getUuid(), null);
}
/** A message body: code first, then its parameters (stable order, so the stored JSON is predictable). */
private static Map<String, Object> body(String code, Map<String, Object> params) {
Map<String, Object> m = new LinkedHashMap<>();
m.put("code", code);
m.put("params", params);
return m;
}
/** One bell row; {@code message} is a code and its parameters, rendered in the reader's language. */
static Map<String, Object> row(long userId, Long companyId, String type, String title, Map<String, Object> message,
String link, String collapseKey) {
Map<String, Object> r = new LinkedHashMap<>();
r.put("receiver", String.valueOf(userId));
r.put("companyId", companyId);
r.put("type", type);
r.put("title", title);
try {
r.put("message", JSON.writeValueAsString(message));
} catch (JsonProcessingException ex) {
throw new IllegalStateException(ex);
}
r.put("link", link);
r.put("collapseKey", collapseKey);
return r;
}
void send(List<Map<String, Object>> rows) {
if (!TransactionSynchronizationManager.isSynchronizationActive()) {
post(rows);
return;
}
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override public void afterCommit() { post(rows); }
});
}
private void post(List<Map<String, Object>> rows) {
try {
restTemplate.postForLocation(URL, rows);
} catch (Exception e) {
// ponytail: no retry; the lead, chat and follow-up date are still there. Pub/Sub if losses show up.
log.warn("Staff notification ({} rows, type {}) failed: {}", rows.size(), rows.get(0).get("type"), e.getClass().getSimpleName());
}
}
}
@@ -150,4 +150,20 @@ class CmsBlockValidatorTest {
refused(List.of(noImage), "blocks[0].imageId", "PagesBadImage");
refused(List.of(form(901)), "blocks[0].eventUuid", "PagesBadEvent");
}
private static CmsBlock custom(String html) {
CmsBlock b = new CmsBlock();
b.setType("HTML");
b.setHtml(html);
return b;
}
@Test
void anHtmlBlockMayHoldScriptsButHasALimit() {
assertThatCode(() -> validate(List.of(custom("<style>h1{color:gold}</style><script>document.title = 'x'</script><h1 onclick=\"go()\">Hi</h1>"))))
.doesNotThrowAnyException();
assertThatCode(() -> validate(List.of(custom("x".repeat(200_000))))).doesNotThrowAnyException();
refused(List.of(custom("x".repeat(200_001))), "blocks[0].html", "PagesTooLong");
refused(List.of(custom(" ")), "blocks[0].html", "PagesRequired");
}
}
@@ -130,6 +130,22 @@ class CmsPageServiceTest {
refused(page(null, INS, "launch", List.of(hero)), HttpStatus.UNPROCESSABLE_ENTITY, "blocks[0].imageId|PagesBadImage");
}
@Test
void theHideHeaderOptionAndAnHtmlBlockReadBack() {
CmsBlock custom = new CmsBlock();
custom.setType("HTML");
custom.setHtml("<section><script>x()</script></section>");
CmsPageDto dto = new CmsPageDto(null, INS, "designed", "Designed", null, "DRAFT", true, List.of(custom), null);
service.save(dto, "staff1");
ArgumentCaptor<CmsPage> row = ArgumentCaptor.forClass(CmsPage.class);
verify(pages).saveAndFlush(row.capture());
when(pages.findById(77L)).thenReturn(Optional.of(row.getValue()));
CmsPageDto read = service.findById(77L);
assertThat(read.hideHeader()).isTrue();
assertThat(read.blocks().get(0).getHtml()).isEqualTo("<section><script>x()</script></section>");
}
@Test
void blocksReadBackInTheirSavedOrder() {
CmsBlock faq = new CmsBlock();
@@ -0,0 +1,60 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.EventLeadRepository.FollowUpRow;
import org.junit.jupiter.api.Test;
import org.springframework.scheduling.annotation.Scheduled;
import java.time.LocalDate;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
// add-lead-notifications: one morning summary per salesperson with open leads due today or overdue.
class FollowUpNoticeJobTest {
private static final LocalDate TODAY = LocalDate.of(2026, 12, 3);
private final EventLeadRepository eventLeads = mock(EventLeadRepository.class);
private final StaffNotifier notifier = mock(StaffNotifier.class);
private final FollowUpNoticeJob job = new FollowUpNoticeJob(eventLeads, notifier);
static FollowUpRow row(long company, long user, long due, long overdue) {
return new FollowUpRow() {
public Long getCompanyId() { return company; }
public Long getSalespersonUserId() { return user; }
public Long getDueToday() { return due; }
public Long getOverdue() { return overdue; }
};
}
@Test
void sendsOneSummaryPerSalespersonOnePostPerCompany() {
FollowUpRow a = row(2, 7, 2, 1), b = row(2, 8, 0, 3), c = row(3, 9, 1, 0);
when(eventLeads.followUpsDue(TODAY)).thenReturn(List.of(a, b, c));
assertThat(job.run(TODAY)).isEqualTo(3);
verify(notifier).followUpsDue(2L, List.of(a, b), TODAY);
verify(notifier).followUpsDue(3L, List.of(c), TODAY);
}
@Test
void nothingDueSendsNothing() {
when(eventLeads.followUpsDue(TODAY)).thenReturn(List.of());
assertThat(job.run(TODAY)).isZero();
verify(notifier, never()).followUpsDue(anyLong(), any(), any());
}
@Test
void runsAtEightMalaysiaTimeWithAnOverridableCron() throws Exception {
Scheduled s = FollowUpNoticeJob.class.getMethod("daily").getAnnotation(Scheduled.class);
assertThat(s.cron()).isEqualTo("${leads.follow-up-notice.cron:0 0 8 * * *}");
assertThat(s.zone()).isEqualTo("Asia/Kuala_Lumpur");
}
}
@@ -5,6 +5,7 @@ import com.solvway.services.counter.repo.EventLeadInterestRepository;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.EventLeadStatusChangeRepository;
import com.solvway.services.counter.repo.EventRepository;
import com.solvway.services.counter.repo.EventSalespersonRepository;
import com.solvway.services.counter.repo.LeadRepository;
import com.solvway.services.counter.util.redis.RedisUtil;
import org.junit.jupiter.api.Test;
@@ -26,15 +27,16 @@ class InvitationWiringTest {
try (var ctx = new AnnotationConfigApplicationContext()) {
for (Class<?> c : new Class<?>[]{LeadRepository.class, EventLeadRepository.class, EventLeadInterestRepository.class,
EventLeadStatusChangeRepository.class, EventRepository.class, EventGuestRepository.class,
RedisUtil.class, TransactionTemplate.class}) {
RedisUtil.class, TransactionTemplate.class, EventSalespersonRepository.class}) {
mockBean(ctx, c);
}
ctx.register(GuestLinker.class, WhatsappNotifier.class, EventLeadService.class, RegistrationService.class, EventService.class,
ctx.register(GuestLinker.class, WhatsappNotifier.class, StaffNotifier.class, EventLeadService.class, RegistrationService.class, EventService.class,
EventHeadcountService.class);
ctx.refresh();
assertThat(ReflectionTestUtils.getField(ctx.getBean(EventLeadService.class), "guestLinker")).isNotNull();
assertThat(ReflectionTestUtils.getField(ctx.getBean(EventLeadService.class), "eventRepository")).isNotNull();
assertThat(ReflectionTestUtils.getField(ctx.getBean(EventLeadService.class), "staffNotifier")).isNotNull();
assertThat(ReflectionTestUtils.getField(ctx.getBean(RegistrationService.class), "guestLinker")).isNotNull();
assertThat(ReflectionTestUtils.getField(ctx.getBean(EventService.class), "guestRepository")).isNotNull();
assertThat(ctx.getBean(EventHeadcountService.class)).isNotNull();
@@ -0,0 +1,173 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.model.Event;
import com.solvway.services.counter.model.EventLead;
import com.solvway.services.counter.model.EventSalesperson;
import com.solvway.services.counter.model.Lead;
import com.solvway.services.counter.repo.EventRepository;
import com.solvway.services.counter.repo.EventSalespersonRepository;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.client.RestTemplate;
import java.util.List;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
// add-lead-notifications: who hears about a lead, sent best effort to service-system after commit.
class StaffNotifierTest {
private static final String URL = "http://service-system/notification/send";
private static final long COMPANY = 2L;
private static final long EVENT = 1000L;
private final RestTemplate rest = new RestTemplate();
private final MockRestServiceServer server = MockRestServiceServer.bindTo(rest).build();
private final EventRepository events = mock(EventRepository.class);
private final EventSalespersonRepository team = mock(EventSalespersonRepository.class);
private final StaffNotifier notifier = new StaffNotifier(rest, events, team);
private Lead lead;
@BeforeEach
void setUp() {
Event e = new Event();
e.setName("Hotel Expo");
when(events.findByUuid(EVENT)).thenReturn(Optional.of(e));
lead = new Lead();
lead.setCompanyId(COMPANY);
lead.setName("Tan Mei Ling");
lead.setMobileE164("+60123456789");
lead.setEmailNormalised("tan@example.com");
}
@AfterEach
void clear() {
if (TransactionSynchronizationManager.isSynchronizationActive()) TransactionSynchronizationManager.clearSynchronization();
}
private EventLead eventLead(Long salesperson) {
EventLead e = new EventLead();
e.setCompanyId(COMPANY);
e.setEventUuid(EVENT);
e.setLeadUuid(lead.getUuid());
e.setSalespersonUserId(salesperson);
return e;
}
private static EventSalesperson member(long userId) {
EventSalesperson s = new EventSalesperson();
s.setUserId(userId);
return s;
}
@Test
void anAssignedLeadNotifiesTheSalespersonWithNamesOnly() {
server.expect(requestTo(URL)).andExpect(method(HttpMethod.POST))
.andExpect(content().json("[{\"receiver\":\"7\",\"companyId\":2,\"type\":\"LEAD_ASSIGNED\",\"title\":\"NoticeLeadAssigned\","
+ "\"link\":\"/leads/" + lead.getUuid() + "\",\"collapseKey\":null}]"))
.andExpect(r -> {
String body = r.getBody().toString();
assertThat(body).contains("Tan Mei Ling").contains("Hotel Expo").contains("NoticeLeadBody");
assertThat(body).doesNotContain("+60123456789").doesNotContain("tan@example.com");
})
.andRespond(withSuccess());
notifier.leadAssigned(eventLead(7L), lead, 3L);
server.verify();
}
@Test
void selfAssignmentAndClearingNotifyNobody() {
notifier.leadAssigned(eventLead(7L), lead, 7L);
notifier.leadAssigned(eventLead(null), lead, 3L);
server.verify(); // no expectation set: any call would have failed
}
@Test
void aWebSignUpGoesToItsSalesperson() {
server.expect(requestTo(URL))
.andExpect(content().json("[{\"receiver\":\"7\",\"type\":\"WEB_SIGNUP\",\"title\":\"NoticeWebSignup\"}]"))
.andRespond(withSuccess());
notifier.webSignup(eventLead(7L), lead);
server.verify();
}
@Test
void anUnassignedWebSignUpGoesToTheEventsSalesTeamOnceEach() {
when(team.findByEventUuid(EVENT)).thenReturn(List.of(member(7L), member(8L), member(7L)));
server.expect(requestTo(URL))
.andExpect(content().json("[{\"receiver\":\"7\",\"type\":\"WEB_SIGNUP\"},{\"receiver\":\"8\",\"type\":\"WEB_SIGNUP\"}]"))
.andRespond(withSuccess());
notifier.webSignup(eventLead(null), lead);
server.verify();
}
@Test
void anUnassignedWebSignUpWithNoTeamNotifiesNobody() {
when(team.findByEventUuid(EVENT)).thenReturn(List.of());
notifier.webSignup(eventLead(null), lead);
server.verify();
}
@Test
void theFollowUpSummaryGoesToEachSalespersonCollapsedForTheDay() {
server.expect(requestTo(URL))
.andExpect(content().json("[{\"receiver\":\"7\",\"companyId\":2,\"type\":\"FOLLOW_UP_DUE\",\"title\":\"NoticeFollowUpDue\","
+ "\"link\":\"/leads\",\"collapseKey\":\"FOLLOW_UP:2026-12-03\","
+ "\"message\":\"{\\\"code\\\":\\\"NoticeFollowUpBody\\\",\\\"params\\\":{\\\"due\\\":2,\\\"overdue\\\":1}}\"},"
+ "{\"receiver\":\"8\",\"type\":\"FOLLOW_UP_DUE\"}]"))
.andRespond(withSuccess());
notifier.followUpsDue(2L, List.of(FollowUpNoticeJobTest.row(2, 7, 2, 1), FollowUpNoticeJobTest.row(2, 8, 0, 3)),
java.time.LocalDate.of(2026, 12, 3));
server.verify();
}
@Test
void failuresAreSwallowed() {
server.expect(requestTo(URL)).andRespond(withStatus(HttpStatus.INTERNAL_SERVER_ERROR));
server.expect(requestTo(URL)).andRespond(r -> { throw new java.net.ConnectException("refused"); });
assertThatCode(() -> notifier.leadAssigned(eventLead(7L), lead, null)).doesNotThrowAnyException();
assertThatCode(() -> notifier.leadAssigned(eventLead(7L), lead, null)).doesNotThrowAnyException();
}
@Test
void insideATransactionTheCallWaitsForCommitAndARollbackSendsNothing() {
TransactionSynchronizationManager.initSynchronization();
notifier.leadAssigned(eventLead(7L), lead, null);
TransactionSynchronizationManager.getSynchronizations()
.forEach(s -> s.afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK));
server.verify();
TransactionSynchronizationManager.clearSynchronization();
server.expect(requestTo(URL)).andRespond(withSuccess());
TransactionSynchronizationManager.initSynchronization();
notifier.leadAssigned(eventLead(7L), lead, null);
TransactionSynchronizationManager.getSynchronizations().forEach(TransactionSynchronization::afterCommit);
server.verify();
}
}
@@ -0,0 +1,144 @@
package com.solvway.services.counter.service;
import com.solvway.services.counter.dto.EventLeadCaptureRequest;
import com.solvway.services.counter.dto.EventLeadUpdateRequest;
import com.solvway.services.counter.model.EventLead;
import com.solvway.services.counter.model.Lead;
import com.solvway.services.counter.repo.EventLeadInterestRepository;
import com.solvway.services.counter.repo.EventLeadRepository;
import com.solvway.services.counter.repo.EventLeadStatusChangeRepository;
import com.solvway.services.counter.repo.LeadRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import java.util.Optional;
import static org.mockito.AdditionalAnswers.returnsFirstArg;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
// add-lead-notifications: every path that assigns an event lead, and every landing-page sign-up, tells the bell.
class StaffNotifyOnSaveTest {
private static final long COMPANY = 42L;
private static final long EVENT = 1000L;
private static final String MOBILE = "+60123456789";
private final LeadRepository leads = mock(LeadRepository.class);
private final EventLeadRepository eventLeads = mock(EventLeadRepository.class);
private final StaffNotifier staff = mock(StaffNotifier.class);
private EventLeadService service;
private RegistrationService registration;
@BeforeEach
void setUp() {
service = new EventLeadService(leads, eventLeads, mock(EventLeadInterestRepository.class),
mock(EventLeadStatusChangeRepository.class), null, null, null, staff);
registration = new RegistrationService(new TransactionTemplate(mock(PlatformTransactionManager.class)),
leads, eventLeads, service);
when(leads.saveAndFlush(any(Lead.class))).then(returnsFirstArg());
when(eventLeads.saveAndFlush(any(EventLead.class))).then(i -> {
EventLead e = i.getArgument(0);
if (e.getId() == null) e.setId(1L);
return e;
});
}
private static Lead lead() {
Lead l = new Lead();
l.setCompanyId(COMPANY);
l.setMobileE164(MOBILE);
return l;
}
@Test
void staffCaptureTellsTheSalespersonWithTheActingUser() {
service.capture(new EventLeadCaptureRequest(COMPANY, EVENT, null, "Aisyah", MOBILE, null, null, null, 7L,
null, null, null, null, null, "staff", 3L));
verify(staff).leadAssigned(any(EventLead.class), any(Lead.class), eq(3L));
verify(staff, never()).webSignup(any(), any());
}
@Test
void qrRegistrationWithAPersonalCodeIsAnAssignment() {
registration.register(new RegistrationService.RegisterRequest(COMPANY, EVENT, 7L, "A", MOBILE, null, null, null,
null, null, null));
verify(staff).leadAssigned(any(EventLead.class), any(Lead.class), eq(null));
}
@Test
void aWebSignUpIsASignUpNotAnAssignment() {
registration.register(new RegistrationService.RegisterRequest(COMPANY, EVENT, 7L, "A", MOBILE, null, null, null,
null, null, null, false, "WEB", null));
verify(staff).webSignup(any(EventLead.class), any(Lead.class));
verify(staff, never()).leadAssigned(any(), any(), any());
}
@Test
void aRepeatWebSignUpOfACapturedPersonIsASignUpAgain() {
Lead l = lead();
EventLead existing = new EventLead();
existing.setLeadUuid(l.getUuid());
existing.setSalespersonUserId(5L);
when(leads.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(l));
when(eventLeads.findByEventUuidAndLeadUuid(EVENT, l.getUuid())).thenReturn(Optional.of(existing));
registration.register(new RegistrationService.RegisterRequest(COMPANY, EVENT, null, "A", MOBILE, null, null, null,
null, null, null, false, "WEB", null));
verify(staff).webSignup(existing, l);
}
@Test
void qrAssigningAnUnownedCaptureIsAnAssignmentAndAnOwnedOneIsSilent() {
Lead l = lead();
EventLead existing = new EventLead();
existing.setLeadUuid(l.getUuid());
when(leads.findFirstByCompanyIdAndMobileE164OrderByIdDesc(COMPANY, MOBILE)).thenReturn(Optional.of(l));
when(eventLeads.findByEventUuidAndLeadUuid(EVENT, l.getUuid())).thenReturn(Optional.of(existing));
registration.register(new RegistrationService.RegisterRequest(COMPANY, EVENT, 7L, "A", MOBILE, null, null, null, null, null, null));
verify(staff).leadAssigned(existing, l, null);
registration.register(new RegistrationService.RegisterRequest(COMPANY, EVENT, 9L, "A", MOBILE, null, null, null, null, null, null));
verify(staff, org.mockito.Mockito.times(1)).leadAssigned(any(), any(), any());
}
private void stubUpdate(Long currentSalesperson) {
Lead l = lead();
EventLead e = new EventLead();
e.setCompanyId(COMPANY);
e.setLeadUuid(l.getUuid());
e.setId(1L);
e.setSalespersonUserId(currentSalesperson);
when(eventLeads.findByUuidAndCompanyId(555L, COMPANY)).thenReturn(Optional.of(e));
when(leads.findByUuidAndCompanyId(l.getUuid(), COMPANY)).thenReturn(Optional.of(l));
}
private static EventLeadUpdateRequest update(Long salesperson) {
return new EventLeadUpdateRequest(COMPANY, 555L, salesperson, null, null, null, null, null, "bo", null, 3L);
}
@Test
void reassignmentTellsTheNewSalespersonWithTheActingUser() {
stubUpdate(5L);
service.update(update(7L));
verify(staff).leadAssigned(any(EventLead.class), any(Lead.class), eq(3L));
}
@Test
void anUpdateKeepingTheSalespersonIsSilent() {
stubUpdate(5L);
service.update(update(5L));
verifyNoInteractions(staff);
}
}
@@ -1,45 +1,52 @@
package com.solvway.services.system.controller;
import com.solvway.services.system.model.Notification;
import com.solvway.services.system.service.NotificationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
* add-lead-notifications: internal endpoints of the staff bell. The receiver in a read or mark path is set by
* mobile-api from the caller's session, never from a client.
*/
@RequestMapping("/notification")
@RestController
public class NotificationController {
private static final Logger log = LoggerFactory.getLogger(MessageController.class);
@Autowired
private NotificationService notificationService;
@RequestMapping("/save")
public Notification save(@RequestBody Notification notification) {
try {
return notificationService.save(notification);
} catch (Exception e) {
log.error(e.getLocalizedMessage(),e);
}
return null;
}
@RequestMapping("/findAllByReceiver/{receiver}/{page}/{count}")
public List<Notification> findAllByReceiver(@PathVariable("receiver") String receiver, @PathVariable("page") int page, @PathVariable("count") int count) {
try {
return notificationService.findAllByReceiver(receiver, PageRequest.of(page,count));
}catch(Exception e){
log.error(e.getLocalizedMessage(),e);
}
return null;
private final NotificationService service;
public NotificationController(NotificationService service) {
this.service = service;
}
@PostMapping("/send")
public Map<String, Object> send(@RequestBody List<NotificationService.Send> rows) {
return Map.of("count", service.send(rows));
}
@GetMapping("/inbox/{receiver}/{page}/{count}")
public Map<String, Object> inbox(@PathVariable String receiver, @PathVariable int page, @PathVariable int count) {
return service.inbox(receiver, page, count);
}
@GetMapping("/unreadCount/{receiver}")
public Map<String, Object> unreadCount(@PathVariable String receiver) {
return Map.of("count", service.unreadCount(receiver));
}
@PostMapping("/markRead/{receiver}/{id}")
public void markRead(@PathVariable String receiver, @PathVariable long id) {
service.markRead(receiver, id);
}
@PostMapping("/markAllRead/{receiver}")
public Map<String, Object> markAllRead(@PathVariable String receiver) {
return Map.of("count", service.markAllRead(receiver));
}
}
@@ -9,15 +9,30 @@ import lombok.Setter;
import java.time.LocalDateTime;
/**
* add-lead-notifications: one bell row per recipient. {@code receiver} is the staff user id; {@code title} and
* {@code message} are a message code and its JSON parameters, rendered in the reader's language by the portal.
*/
@Setter
@Getter
@Entity
public class Notification {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private long id;
private String receiver;
/** 'A' = staff user (the only recipient type today). */
private String recipientType;
private Long companyId;
private String title;
private String message;
/** LEAD_ASSIGNED, WEB_SIGNUP, WHATSAPP_MESSAGE or FOLLOW_UP_DUE. */
private String type;
/** Portal path opened on click. */
private String link;
/** An unread row of the same receiver with this key is updated instead of duplicated. */
private String collapseKey;
private boolean seen;
private LocalDateTime readAt;
private LocalDateTime createDateTime;
}
@@ -1,14 +1,32 @@
package com.solvway.services.system.repo;
import com.solvway.services.system.model.Notification;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.time.LocalDateTime;
import java.util.Optional;
@Repository
public interface NotificationRepository extends JpaRepository<Notification, Long>{
public interface NotificationRepository extends JpaRepository<Notification, Long> {
List<Notification> findAllByReceiverOrderByCreateDateTimeDesc(String receiver, Pageable pageable);
Page<Notification> findAllByRecipientTypeAndReceiverOrderByCreateDateTimeDescIdDesc(String recipientType, String receiver, Pageable pageable);
long countByRecipientTypeAndReceiverAndSeenFalse(String recipientType, String receiver);
Optional<Notification> findFirstByRecipientTypeAndReceiverAndCollapseKeyAndSeenFalse(String recipientType, String receiver, String collapseKey);
/** Marks one row read only when it belongs to the caller: a foreign id updates nothing. */
@Modifying
@Query("update Notification n set n.seen = true, n.readAt = :at where n.id = :id and n.recipientType = :type and n.receiver = :receiver")
int markSeen(@Param("id") long id, @Param("type") String recipientType, @Param("receiver") String receiver, @Param("at") LocalDateTime at);
@Modifying
@Query("update Notification n set n.seen = true, n.readAt = :at where n.recipientType = :type and n.receiver = :receiver and n.seen = false")
int markAllSeen(@Param("type") String recipientType, @Param("receiver") String receiver, @Param("at") LocalDateTime at);
}
@@ -2,25 +2,94 @@ package com.solvway.services.system.service;
import com.solvway.services.system.model.Notification;
import com.solvway.services.system.repo.NotificationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* add-lead-notifications: the staff bell's store. Other services send rows (recipients resolved by the sender);
* the admin API reads and marks the caller's own rows, identified by the session's user id.
*/
@Service
public class NotificationService {
@Autowired
private NotificationRepository notificationRepository;
@Transactional
public Notification save(Notification nofication) {
return notificationRepository.save(nofication);
static final String STAFF = "A";
private static final Set<String> TYPES = Set.of("LEAD_ASSIGNED", "WEB_SIGNUP", "WHATSAPP_MESSAGE", "FOLLOW_UP_DUE");
private static final int MAX_PAGE = 50;
/** One notification to store. {@code collapseKey} is optional. */
public record Send(String receiver, Long companyId, String title, String message, String type, String link, String collapseKey) {}
private final NotificationRepository repo;
public NotificationService(NotificationRepository repo) {
this.repo = repo;
}
public List<Notification> findAllByReceiver(String receiver, Pageable pageable){
return notificationRepository.findAllByReceiverOrderByCreateDateTimeDesc(receiver, pageable);
/**
* Stores each row unread. With a collapse key, the receiver's unread row with that key is refreshed instead.
* ponytail: check-then-insert, so two concurrent sends for one key can both insert (two rows at worst).
*/
@Transactional
public int send(List<Send> rows) {
rows.forEach(NotificationService::check);
LocalDateTime now = LocalDateTime.now();
for (Send s : rows) {
Notification n = s.collapseKey() == null ? null
: repo.findFirstByRecipientTypeAndReceiverAndCollapseKeyAndSeenFalse(STAFF, s.receiver(), s.collapseKey()).orElse(null);
if (n == null) {
n = new Notification();
n.setRecipientType(STAFF);
n.setReceiver(s.receiver());
n.setCollapseKey(s.collapseKey());
}
n.setCompanyId(s.companyId());
n.setTitle(s.title());
n.setMessage(s.message());
n.setType(s.type());
n.setLink(s.link());
n.setCreateDateTime(now);
repo.save(n);
}
return rows.size();
}
private static void check(Send s) {
boolean ok = s.receiver() != null && !s.receiver().isBlank() && s.receiver().length() <= 45
&& s.companyId() != null && s.title() != null && !s.title().isBlank()
&& TYPES.contains(s.type())
&& s.link() != null && s.link().startsWith("/") && !s.link().startsWith("//") && s.link().length() <= 512
&& (s.collapseKey() == null || s.collapseKey().length() <= 100);
if (!ok) throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY, "notification: invalid row");
}
public Map<String, Object> inbox(String receiver, int page, int count) {
Page<Notification> p = repo.findAllByRecipientTypeAndReceiverOrderByCreateDateTimeDescIdDesc(
STAFF, receiver, PageRequest.of(Math.max(page, 0), Math.min(Math.max(count, 1), MAX_PAGE)));
return Map.of("items", p.getContent(), "total", p.getTotalElements());
}
public long unreadCount(String receiver) {
return repo.countByRecipientTypeAndReceiverAndSeenFalse(STAFF, receiver);
}
@Transactional
public void markRead(String receiver, long id) {
if (repo.markSeen(id, STAFF, receiver, LocalDateTime.now()) == 0) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "notification: not found");
}
}
@Transactional
public int markAllRead(String receiver) {
return repo.markAllSeen(STAFF, receiver, LocalDateTime.now());
}
}
@@ -0,0 +1,73 @@
package com.solvway.services.system.controller;
import com.solvway.services.system.service.NotificationService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
import java.util.Map;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
// add-lead-notifications: the store's internal endpoints, with explicit methods and real error statuses.
@ExtendWith(MockitoExtension.class)
class NotificationControllerTest {
@Mock private NotificationService service;
@InjectMocks private NotificationController controller;
private MockMvc mvc;
@BeforeEach
void setUp() {
mvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@Test
void sendStoresTheRows() throws Exception {
when(service.send(anyList())).thenReturn(1);
mvc.perform(post("/notification/send").contentType(MediaType.APPLICATION_JSON)
.content("[{\"receiver\":\"11\",\"companyId\":2,\"title\":\"T\",\"message\":\"{}\",\"type\":\"LEAD_ASSIGNED\",\"link\":\"/event-leads/9\"}]"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.count").value(1));
verify(service).send(List.of(new NotificationService.Send("11", 2L, "T", "{}", "LEAD_ASSIGNED", "/event-leads/9", null)));
}
@Test
void inboxCountAndMarks() throws Exception {
when(service.inbox("11", 0, 20)).thenReturn(Map.of("items", List.of(), "total", 0L));
when(service.unreadCount("11")).thenReturn(3L);
when(service.markAllRead("11")).thenReturn(2);
mvc.perform(get("/notification/inbox/11/0/20")).andExpect(status().isOk()).andExpect(jsonPath("$.total").value(0));
mvc.perform(get("/notification/unreadCount/11")).andExpect(status().isOk()).andExpect(jsonPath("$.count").value(3));
mvc.perform(post("/notification/markRead/11/5")).andExpect(status().isOk());
verify(service).markRead("11", 5L);
mvc.perform(post("/notification/markAllRead/11")).andExpect(status().isOk()).andExpect(jsonPath("$.count").value(2));
}
@Test
void aForeignRowIs404() throws Exception {
doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND)).when(service).markRead("12", 5L);
mvc.perform(post("/notification/markRead/12/5")).andExpect(status().isNotFound());
}
@Test
void theOldUncheckedEndpointsAreGone() throws Exception {
mvc.perform(post("/notification/save").contentType(MediaType.APPLICATION_JSON).content("{}")).andExpect(status().isNotFound());
}
}
@@ -0,0 +1,134 @@
package com.solvway.services.system.service;
import com.solvway.services.system.model.Notification;
import com.solvway.services.system.repo.NotificationRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.server.ResponseStatusException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
// add-lead-notifications: the staff bell's store. Rows come from other services; reads and marks are the caller's own.
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class NotificationServiceTest {
@Mock private NotificationRepository repo;
private NotificationService service;
@BeforeEach
void setUp() {
service = new NotificationService(repo);
when(repo.save(any(Notification.class))).thenAnswer(i -> i.getArgument(0));
}
private static NotificationService.Send send(String receiver, String collapseKey) {
return new NotificationService.Send(receiver, 2L, "NoticeLeadAssignedTitle", "{\"lead\":\"Tan\"}", "LEAD_ASSIGNED", "/event-leads/9", collapseKey);
}
@Test
void storesOneUnreadStaffRowPerRecipient() {
assertThat(service.send(List.of(send("11", null), send("12", null)))).isEqualTo(2);
ArgumentCaptor<Notification> saved = ArgumentCaptor.forClass(Notification.class);
verify(repo, org.mockito.Mockito.times(2)).save(saved.capture());
Notification n = saved.getAllValues().get(0);
assertThat(n.getRecipientType()).isEqualTo("A");
assertThat(n.getReceiver()).isEqualTo("11");
assertThat(n.getCompanyId()).isEqualTo(2L);
assertThat(n.getTitle()).isEqualTo("NoticeLeadAssignedTitle");
assertThat(n.getMessage()).isEqualTo("{\"lead\":\"Tan\"}");
assertThat(n.getType()).isEqualTo("LEAD_ASSIGNED");
assertThat(n.getLink()).isEqualTo("/event-leads/9");
assertThat(n.isSeen()).isFalse();
assertThat(n.getCreateDateTime()).isNotNull();
}
@Test
void anUnreadRowWithTheSameCollapseKeyIsUpdatedNotDuplicated() {
Notification unread = new Notification();
unread.setReceiver("11");
unread.setMessage("old");
unread.setCreateDateTime(LocalDateTime.of(2026, 12, 1, 9, 0));
when(repo.findFirstByRecipientTypeAndReceiverAndCollapseKeyAndSeenFalse("A", "11", "WA:5")).thenReturn(Optional.of(unread));
service.send(List.of(send("11", "WA:5")));
verify(repo).save(unread);
assertThat(unread.getMessage()).isEqualTo("{\"lead\":\"Tan\"}");
assertThat(unread.getCreateDateTime()).isAfter(LocalDateTime.of(2026, 12, 1, 9, 0));
}
@Test
void aCollapseKeyWithNoUnreadRowInsertsOne() {
when(repo.findFirstByRecipientTypeAndReceiverAndCollapseKeyAndSeenFalse("A", "11", "WA:5")).thenReturn(Optional.empty());
service.send(List.of(send("11", "WA:5")));
ArgumentCaptor<Notification> saved = ArgumentCaptor.forClass(Notification.class);
verify(repo).save(saved.capture());
assertThat(saved.getValue().getCollapseKey()).isEqualTo("WA:5");
}
@Test
void refusesRowsWithoutARecipientTypeCodeOrCompany() {
for (NotificationService.Send bad : List.of(
new NotificationService.Send(" ", 2L, "T", "{}", "LEAD_ASSIGNED", "/x", null),
new NotificationService.Send("11", null, "T", "{}", "LEAD_ASSIGNED", "/x", null),
new NotificationService.Send("11", 2L, null, "{}", "LEAD_ASSIGNED", "/x", null),
new NotificationService.Send("11", 2L, "T", "{}", "OTHER", "/x", null),
new NotificationService.Send("11", 2L, "T", "{}", "LEAD_ASSIGNED", "https://evil.example/x", null))) {
assertThatThrownBy(() -> service.send(List.of(bad))).isInstanceOf(ResponseStatusException.class);
}
verify(repo, never()).save(any());
}
@Test
void readsAndCountsOnlyTheCallersStaffRows() {
when(repo.findAllByRecipientTypeAndReceiverOrderByCreateDateTimeDescIdDesc(eq("A"), eq("11"), any()))
.thenReturn(new PageImpl<>(List.of(new Notification()), PageRequest.of(0, 20), 21));
when(repo.countByRecipientTypeAndReceiverAndSeenFalse("A", "11")).thenReturn(3L);
Map<String, Object> page = service.inbox("11", 0, 20);
assertThat(page.get("total")).isEqualTo(21L);
assertThat((List<?>) page.get("items")).hasSize(1);
assertThat(service.unreadCount("11")).isEqualTo(3L);
}
@Test
void markingAnotherUsersRowIsNotFound() {
when(repo.markSeen(eq(5L), eq("A"), eq("12"), any())).thenReturn(0);
when(repo.markSeen(eq(5L), eq("A"), eq("11"), any())).thenReturn(1);
service.markRead("11", 5L);
assertThatThrownBy(() -> service.markRead("12", 5L))
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(404));
}
@Test
void markAllReadTouchesOnlyTheCallersRows() {
when(repo.markAllSeen(eq("A"), eq("11"), any())).thenReturn(4);
assertThat(service.markAllRead("11")).isEqualTo(4);
verify(repo, never()).markSeen(anyLong(), any(), any(), any());
}
}
@@ -0,0 +1,66 @@
package com.solvway.services.whatsapp.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.solvway.services.whatsapp.model.WaConversation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* add-lead-notifications: tells a chat's owner about an inbound message through service-system's bell. One unread row
* per chat (collapse key), so a busy chat does not flood the bell. Best effort: never throws, logs ids only, and the
* parameters carry the contact name but never the phone number.
*/
@Component
public class StaffNotifier {
private static final Logger log = LoggerFactory.getLogger(StaffNotifier.class);
private static final String URL = "http://service-system/notification/send";
private static final ObjectMapper JSON = new ObjectMapper();
private final RestTemplate rest;
@Autowired
public StaffNotifier(RestTemplateBuilder builder) {
this(builder.setConnectTimeout(Duration.ofSeconds(2)).setReadTimeout(Duration.ofSeconds(2)).build());
}
StaffNotifier(RestTemplate rest) {
this.rest = rest;
}
public void whatsappMessage(WaConversation c, String contactName) {
if (c.ownerUserId == null) {
return;
}
try {
boolean named = contactName != null && !contactName.isBlank();
Map<String, Object> params = new LinkedHashMap<>();
if (named) {
params.put("name", contactName);
}
Map<String, Object> message = new LinkedHashMap<>();
message.put("code", named ? "NoticeWhatsappBody" : "NoticeWhatsappBodyNoName");
message.put("params", params);
Map<String, Object> row = new LinkedHashMap<>();
row.put("receiver", String.valueOf(c.ownerUserId));
row.put("companyId", c.companyId);
row.put("type", "WHATSAPP_MESSAGE");
row.put("title", "NoticeWhatsappMessage");
row.put("message", JSON.writeValueAsString(message));
row.put("link", "/whatsapp?c=" + c.uuid);
row.put("collapseKey", "WA:" + c.uuid);
rest.postForEntity(URL, List.of(row), Void.class);
} catch (JsonProcessingException | RuntimeException e) {
log.warn("WhatsApp notification: not sent for conversation {} ({})", c.uuid, e.getClass().getSimpleName());
}
}
}
@@ -57,10 +57,12 @@ public class WebhookIngestService {
private final WaMessageRepository messages;
private final OwnershipService ownership;
private final WhatsAppSettings settings;
private final StaffNotifier notifier;
public WebhookIngestService(CompanyDirectory companies, WaConversationRepository conversations, WaMessageRepository messages,
OwnershipService ownership, WhatsAppSettings settings) {
OwnershipService ownership, WhatsAppSettings settings, StaffNotifier notifier) {
this.settings = settings;
this.notifier = notifier;
this.companies = companies;
this.conversations = conversations;
this.messages = messages;
@@ -164,7 +166,10 @@ public class WebhookIngestService {
c.duplicates++;
return;
}
conversations.recordInbound(conv.id, cut(contactName(value, from), 255), phoneNumberId, at, preview(msg));
String name = cut(contactName(value, from), 255);
String shownName = name == null || name.isBlank() ? conv.contactName : name; // read before recordInbound moves it
conversations.recordInbound(conv.id, name, phoneNumberId, at, preview(msg));
notifier.whatsappMessage(conv, shownName);
c.accepted++;
}
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more