diff --git a/docs/deployment.md b/docs/deployment.md index 12c61ab..6446ef2 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -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 | diff --git a/docs/superpowers/specs/2026-12-02-lead-notifications-design.md b/docs/superpowers/specs/2026-12-02-lead-notifications-design.md new file mode 100644 index 0000000..403880f --- /dev/null +++ b/docs/superpowers/specs/2026-12-02-lead-notifications-design.md @@ -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. diff --git a/local/seed/03-colite.sql b/local/seed/03-colite.sql index e43ef3c..ddd26ab 100644 --- a/local/seed/03-colite.sql +++ b/local/seed/03-colite.sql @@ -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`); diff --git a/local/seed/04-zh-cn-messages.sql b/local/seed/04-zh-cn-messages.sql index ba7d6b6..e736308 100644 --- a/local/seed/04-zh-cn-messages.sql +++ b/local/seed/04-zh-cn-messages.sql @@ -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'); diff --git a/openspec/changes/add-lead-notifications/.openspec.yaml b/openspec/changes/add-lead-notifications/.openspec.yaml new file mode 100644 index 0000000..eb2b21e --- /dev/null +++ b/openspec/changes/add-lead-notifications/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-12-02 diff --git a/openspec/changes/add-lead-notifications/design.md b/openspec/changes/add-lead-notifications/design.md new file mode 100644 index 0000000..1e0dfe2 --- /dev/null +++ b/openspec/changes/add-lead-notifications/design.md @@ -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:`; the follow-up summary uses `FOLLOW_UP:`, 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. diff --git a/openspec/changes/add-lead-notifications/proposal.md b/openspec/changes/add-lead-notifications/proposal.md new file mode 100644 index 0000000..6ea8964 --- /dev/null +++ b/openspec/changes/add-lead-notifications/proposal.md @@ -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. diff --git a/openspec/changes/add-lead-notifications/specs/lead-notifications/spec.md b/openspec/changes/add-lead-notifications/specs/lead-notifications/spec.md new file mode 100644 index 0000000..0ad7445 --- /dev/null +++ b/openspec/changes/add-lead-notifications/specs/lead-notifications/spec.md @@ -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 diff --git a/openspec/changes/add-lead-notifications/sql/01-notification-columns.sql b/openspec/changes/add-lead-notifications/sql/01-notification-columns.sql new file mode 100644 index 0000000..80a15d4 --- /dev/null +++ b/openspec/changes/add-lead-notifications/sql/01-notification-columns.sql @@ -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`); diff --git a/openspec/changes/add-lead-notifications/sql/02-notification-labels.sql b/openspec/changes/add-lead-notifications/sql/02-notification-labels.sql new file mode 100644 index 0000000..1490332 --- /dev/null +++ b/openspec/changes/add-lead-notifications/sql/02-notification-labels.sql @@ -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'; diff --git a/openspec/changes/add-lead-notifications/sql/99-rollback.sql b/openspec/changes/add-lead-notifications/sql/99-rollback.sql new file mode 100644 index 0000000..54092c6 --- /dev/null +++ b/openspec/changes/add-lead-notifications/sql/99-rollback.sql @@ -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'; diff --git a/openspec/changes/add-lead-notifications/tasks.md b/openspec/changes/add-lead-notifications/tasks.md new file mode 100644 index 0000000..6be58d9 --- /dev/null +++ b/openspec/changes/add-lead-notifications/tasks.md @@ -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:`; 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. diff --git a/solvway-admin-portal/app/api/notifications/[id]/read/route.ts b/solvway-admin-portal/app/api/notifications/[id]/read/route.ts new file mode 100644 index 0000000..f499fd8 --- /dev/null +++ b/solvway-admin-portal/app/api/notifications/[id]/read/route.ts @@ -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(`/api/admin/notifications/${encodeURIComponent(id)}/read`, { method: "POST", token }); + if (!result.ok) return errorResponse(result); + return new NextResponse(null, { status: 204 }); +} diff --git a/solvway-admin-portal/app/api/notifications/read-all/route.ts b/solvway-admin-portal/app/api/notifications/read-all/route.ts new file mode 100644 index 0000000..e2f06a6 --- /dev/null +++ b/solvway-admin-portal/app/api/notifications/read-all/route.ts @@ -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); +} diff --git a/solvway-admin-portal/app/api/notifications/route.ts b/solvway-admin-portal/app/api/notifications/route.ts new file mode 100644 index 0000000..b4e2e6e --- /dev/null +++ b/solvway-admin-portal/app/api/notifications/route.ts @@ -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>(`/api/admin/notifications?${qs.toString()}`, { token }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} diff --git a/solvway-admin-portal/app/api/notifications/routes.test.ts b/solvway-admin-portal/app/api/notifications/routes.test.ts new file mode 100644 index 0000000..89c8561 --- /dev/null +++ b/solvway-admin-portal/app/api/notifications/routes.test.ts @@ -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[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); + }); +}); diff --git a/solvway-admin-portal/app/api/notifications/unread-count/route.ts b/solvway-admin-portal/app/api/notifications/unread-count/route.ts new file mode 100644 index 0000000..34345be --- /dev/null +++ b/solvway-admin-portal/app/api/notifications/unread-count/route.ts @@ -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); +} diff --git a/solvway-admin-portal/app/components/app/CompanyPicker.tsx b/solvway-admin-portal/app/components/app/CompanyPicker.tsx index 23290e7..60754a3 100644 --- a/solvway-admin-portal/app/components/app/CompanyPicker.tsx +++ b/solvway-admin-portal/app/components/app/CompanyPicker.tsx @@ -16,7 +16,7 @@ export default function CompanyPicker() { if (!isSuper) return null; return (