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
56 changed files with 2578 additions and 57 deletions

No files matched your search

+6
View File
@@ -152,11 +152,15 @@ 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/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`.
@@ -251,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 |
@@ -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.
+14
View File
@@ -506,3 +506,17 @@ INSERT INTO `module` (`id`, `name`, `desc`, `area`, `type`, `parent`, `url`, `ic
-- 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`);
+30
View File
@@ -1497,6 +1497,36 @@ INSERT INTO message (code, content, area) SELECT 'PagesHtmlHint', JSON_OBJECT('e
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,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>
);
}
@@ -760,6 +760,21 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
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",
@@ -767,6 +767,21 @@
"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": "格式",
@@ -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} />
</>
)}
</>
);
}
@@ -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());
}
}
@@ -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();
}
}
@@ -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));
}
}
@@ -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}";
@@ -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);
}
}
@@ -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);
}
@@ -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());
}
}
}
@@ -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++;
}
@@ -0,0 +1,71 @@
package com.solvway.services.whatsapp.service;
import com.solvway.services.whatsapp.model.WaConversation;
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.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThatCode;
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: an inbound message tells the chat owner, one unread row per chat.
class StaffNotifierTest {
private static final String URL = "http://service-system/notification/send";
private final RestTemplate rest = new RestTemplate();
private final MockRestServiceServer server = MockRestServiceServer.bindTo(rest).build();
private final StaffNotifier notifier = new StaffNotifier(rest);
private static WaConversation chat(Long owner) {
WaConversation c = new WaConversation();
c.id = 5L;
c.uuid = "c-uuid";
c.companyId = 2L;
c.contactWaId = "60111222333";
c.ownerUserId = owner;
return c;
}
@Test
void theOwnerGetsOneCollapsedRowLinkingToTheChatWithTheNameButNeverThePhone() {
server.expect(requestTo(URL)).andExpect(method(HttpMethod.POST))
.andExpect(content().json("[{\"receiver\":\"7\",\"companyId\":2,\"type\":\"WHATSAPP_MESSAGE\","
+ "\"title\":\"NoticeWhatsappMessage\",\"link\":\"/whatsapp?c=c-uuid\",\"collapseKey\":\"WA:c-uuid\","
+ "\"message\":\"{\\\"code\\\":\\\"NoticeWhatsappBody\\\",\\\"params\\\":{\\\"name\\\":\\\"Aisyah\\\"}}\"}]", true))
.andRespond(withSuccess());
notifier.whatsappMessage(chat(7L), "Aisyah");
server.verify();
}
@Test
void withoutAContactNameTheBodySaysSoInsteadOfShowingThePhone() {
server.expect(requestTo(URL)).andExpect(content().json("[{\"message\":\"{\\\"code\\\":\\\"NoticeWhatsappBodyNoName\\\",\\\"params\\\":{}}\"}]"))
.andRespond(withSuccess());
notifier.whatsappMessage(chat(7L), " ");
server.verify();
}
@Test
void aChatWithoutAnOwnerNotifiesNobody() {
notifier.whatsappMessage(chat(null), "Aisyah");
server.verify(); // no request expected
}
@Test
void aFailingStoreNeverFailsTheCaller() {
server.expect(requestTo(URL)).andRespond(withStatus(HttpStatus.SERVICE_UNAVAILABLE));
assertThatCode(() -> notifier.whatsappMessage(chat(7L), null)).doesNotThrowAnyException();
}
}
@@ -47,6 +47,7 @@ class WebhookIngestServiceTest {
private long seq;
private WaConversationRepository convRepo;
private OwnershipService ownership;
private StaffNotifier notifier;
private WebhookIngestService service;
private CompanyDirectory companies;
@@ -105,7 +106,8 @@ class WebhookIngestServiceTest {
when(settings.companies()).thenReturn(List.of(
new WhatsAppSettings.CompanyConfig("INS", INS_PHONE, "w1", "t1", SECRETS.get("INS")),
new WhatsAppSettings.CompanyConfig("CV", CV_PHONE, "w2", "t2", SECRETS.get("CV"))));
service = new WebhookIngestService(companies, convRepo, msgRepo, ownership, settings);
notifier = mock(StaffNotifier.class);
service = new WebhookIngestService(companies, convRepo, msgRepo, ownership, settings, notifier);
}
private Optional<WaMessage> byWamid(String wamid) {
@@ -182,6 +184,24 @@ class WebhookIngestServiceTest {
assertThat(conversations).containsKey("1/60111222333");
}
@Test
void eachNewInboundMessageTellsTheChatOwnerButARedeliveryDoesNot() throws Exception {
ingest(payload("text.json", "WAMID", "wamid.a"), "INS");
ingest(payload("text.json", "WAMID", "wamid.b", "TS", "1764662500"), "INS");
ingest(payload("text.json", "WAMID", "wamid.b", "TS", "1764662500"), "INS"); // Meta redelivers
WaConversation chat = conversations.get("1/60111222333");
verify(notifier, times(2)).whatsappMessage(chat, "Aisyah");
}
@Test
void withoutANameInThePayloadTheStoredContactNameIsUsed() throws Exception {
ingest(payload("text.json", "WAMID", "wamid.a"), "INS");
ingest(payload("text.json", "WAMID", "wamid.b", "NAME", ""), "INS");
verify(notifier, times(2)).whatsappMessage(conversations.get("1/60111222333"), "Aisyah");
}
@Test
void truncatesAContactNameTo255() throws Exception {
ingest(payload("text.json", "NAME", "N".repeat(300)), "INS");