From a1d13fe8d784206d6e546a0778de6e89ef0f3d2a Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 20:14:48 +0800 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs --- local/seed/04-zh-cn-messages.sql | 30 ++++ .../sql/02-notification-labels.sql | 33 +++++ .../sql/99-rollback.sql | 1 + .../changes/add-lead-notifications/tasks.md | 6 +- .../app/api/notifications/[id]/read/route.ts | 14 ++ .../app/api/notifications/read-all/route.ts | 12 ++ .../app/api/notifications/route.ts | 19 +++ .../app/api/notifications/routes.test.ts | 68 +++++++++ .../api/notifications/unread-count/route.ts | 12 ++ .../app/components/app/Header.tsx | 2 + .../components/app/NotificationsBell.test.tsx | 84 +++++++++++ .../app/components/app/NotificationsBell.tsx | 134 ++++++++++++++++++ .../app/lib/i18n/defaultMessages.ts | 15 ++ .../app/lib/i18n/zh_CN.seed.json | 15 ++ .../app/lib/services/notifications.test.ts | 48 +++++++ .../app/lib/services/notifications.ts | 71 ++++++++++ .../app/notifications/page.test.tsx | 57 ++++++++ .../app/notifications/page.tsx | 85 +++++++++++ 18 files changed, 703 insertions(+), 3 deletions(-) create mode 100644 openspec/changes/add-lead-notifications/sql/02-notification-labels.sql create mode 100644 solvway-admin-portal/app/api/notifications/[id]/read/route.ts create mode 100644 solvway-admin-portal/app/api/notifications/read-all/route.ts create mode 100644 solvway-admin-portal/app/api/notifications/route.ts create mode 100644 solvway-admin-portal/app/api/notifications/routes.test.ts create mode 100644 solvway-admin-portal/app/api/notifications/unread-count/route.ts create mode 100644 solvway-admin-portal/app/components/app/NotificationsBell.test.tsx create mode 100644 solvway-admin-portal/app/components/app/NotificationsBell.tsx create mode 100644 solvway-admin-portal/app/lib/services/notifications.test.ts create mode 100644 solvway-admin-portal/app/lib/services/notifications.ts create mode 100644 solvway-admin-portal/app/notifications/page.test.tsx create mode 100644 solvway-admin-portal/app/notifications/page.tsx 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/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 index 1c01e8a..54092c6 100644 --- a/openspec/changes/add-lead-notifications/sql/99-rollback.sql +++ b/openspec/changes/add-lead-notifications/sql/99-rollback.sql @@ -13,3 +13,4 @@ ALTER TABLE `notification` 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 index e1e2939..40eb07f 100644 --- a/openspec/changes/add-lead-notifications/tasks.md +++ b/openspec/changes/add-lead-notifications/tasks.md @@ -22,9 +22,9 @@ Design: `design.md` and `docs/superpowers/specs/2026-12-02-lead-notifications-de ## 3. Portal -- [ ] 3.1 BFF routes `app/api/notifications/**` and `app/lib/services/notifications.ts`. -- [ ] 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". -- [ ] 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. +- [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 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/Header.tsx b/solvway-admin-portal/app/components/app/Header.tsx index fad4c57..4e9dc2c 100644 --- a/solvway-admin-portal/app/components/app/Header.tsx +++ b/solvway-admin-portal/app/components/app/Header.tsx @@ -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 @@ -78,6 +79,7 @@ export default function Header() {
+ + + +
+ {t("NotificationsTitle")} + +
+ + {failed ? ( +

{t("NotificationsLoadFailed")}

+ ) : items === null ? ( +

{t("Loading")}

+ ) : items.length === 0 ? ( +

{t("NotificationsEmpty")}

+ ) : ( +
+ {items.map((item) => { + const { title, body } = noticeText(item, t); + const inner = ( + + + {title} + {body && {body}} + {when(item.createDateTime)} + + {!item.seen && + ); + return isSitePath(item.link) ? ( + + {inner} + + ) : ( + {inner} + ); + })} +
+ )} + + + {t("NotificationsSeeAll")} + +
+ + ); +} diff --git a/solvway-admin-portal/app/lib/i18n/defaultMessages.ts b/solvway-admin-portal/app/lib/i18n/defaultMessages.ts index 2bf211e..4d5d9ed 100644 --- a/solvway-admin-portal/app/lib/i18n/defaultMessages.ts +++ b/solvway-admin-portal/app/lib/i18n/defaultMessages.ts @@ -760,6 +760,21 @@ export const DEFAULT_MESSAGES: Record = { 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", diff --git a/solvway-admin-portal/app/lib/i18n/zh_CN.seed.json b/solvway-admin-portal/app/lib/i18n/zh_CN.seed.json index d16002b..c18822a 100644 --- a/solvway-admin-portal/app/lib/i18n/zh_CN.seed.json +++ b/solvway-admin-portal/app/lib/i18n/zh_CN.seed.json @@ -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": "格式", diff --git a/solvway-admin-portal/app/lib/services/notifications.test.ts b/solvway-admin-portal/app/lib/services/notifications.test.ts new file mode 100644 index 0000000..05917e6 --- /dev/null +++ b/solvway-admin-portal/app/lib/services/notifications.test.ts @@ -0,0 +1,48 @@ +import { describe, it, expect } from "vitest"; +import { noticeText, type AdminNotification } from "./notifications"; + +const t = (code: string, params?: Record) => `${code}${params ? JSON.stringify(params) : ""}`; +const item = (over: Partial): 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"); + }); +}); diff --git a/solvway-admin-portal/app/lib/services/notifications.ts b/solvway-admin-portal/app/lib/services/notifications.ts new file mode 100644 index 0000000..fc0ccf2 --- /dev/null +++ b/solvway-admin-portal/app/lib/services/notifications.ts @@ -0,0 +1,71 @@ +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 { + const res = await apiGet>(`/api/notifications?page=${page}&size=${size}`); + return { items: res?.items ?? [], total: res?.total ?? 0 }; +} + +export async function getUnreadCount(): Promise { + return (await apiGet<{ count: number }>("/api/notifications/unread-count"))?.count ?? 0; +} + +export async function markRead(id: number): Promise { + await apiPost(`/api/notifications/${id}/read`); +} + +export async function markAllRead(): Promise { + await apiPost("/api/notifications/read-all"); +} + +type T = (code: string, params?: Record) => 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 }; + if (typeof m.code === "string") { + const params: Record = {}; + 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; + } +} diff --git a/solvway-admin-portal/app/notifications/page.test.tsx b/solvway-admin-portal/app/notifications/page.test.tsx new file mode 100644 index 0000000..8ed87a5 --- /dev/null +++ b/solvway-admin-portal/app/notifications/page.test.tsx @@ -0,0 +1,57 @@ +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()), + ...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(); + 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 () => { + render(); + 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()); + }); + + it("shows an empty state and a load error", async () => { + svc.listNotifications.mockResolvedValue({ items: [], total: 0 }); + const { unmount } = render(); + expect(await screen.findByText("No notifications yet.")).toBeInTheDocument(); + unmount(); + + svc.listNotifications.mockRejectedValue(new Error("down")); + render(); + expect(await screen.findByText("Couldn't load notifications.")).toBeInTheDocument(); + }); +}); diff --git a/solvway-admin-portal/app/notifications/page.tsx b/solvway-admin-portal/app/notifications/page.tsx new file mode 100644 index 0000000..e570bfb --- /dev/null +++ b/solvway-admin-portal/app/notifications/page.tsx @@ -0,0 +1,85 @@ +"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, + 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(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(() => {}); + load(); + } + + const when = (iso: string) => noticeTime(iso, locale); + + return ( + <> + {t("NotificationsMarkAllRead")}} + /> + {error && } + {data?.items.length === 0 && } + {!!data?.items.length && ( + <> +
    + {data.items.map((item) => { + const { title, body } = noticeText(item, t); + const inner = ( + + + {title} + {body && {body}} + {when(item.createDateTime)} + + {!item.seen && {t("NotificationsUnreadBadge")}} + + ); + return ( +
  • + {isSitePath(item.link) ? ( + {inner} + ) : inner} +
  • + ); + })} +
+ + + )} + + ); +}