feat(notifications): header bell and notifications page
The bell polls the unread count every 30 s while the tab is visible. Opening it loads the newest 10 and marks the unread ones read; items link only to paths on this site. /notifications lists all with paging and Mark all read. Titles and bodies render from message codes, in English and Chinese. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
This commit is contained in:
1 parent
72394df1d7
commit
a1d13fe8d7
18 files changed
+703
-3
No files matched your search
@@ -1497,6 +1497,36 @@ INSERT INTO message (code, content, area) SELECT 'PagesHtmlHint', JSON_OBJECT('e
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '粘贴的 HTML 中的表单不会发送。请添加报名表单区块来收集线索。') WHERE LOWER(code) = LOWER('PagesHtmlHint') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesHideHeader', JSON_OBJECT('en_US', 'Hide page header', 'zh_CN', '隐藏页面顶栏'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesHideHeader') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '隐藏页面顶栏') WHERE LOWER(code) = LOWER('PagesHideHeader') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NotificationsTitle', JSON_OBJECT('en_US', 'Notifications', 'zh_CN', '通知'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsTitle') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '通知') WHERE LOWER(code) = LOWER('NotificationsTitle') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NotificationsUnread', JSON_OBJECT('en_US', 'Notifications, {count} unread', 'zh_CN', '通知,{count} 条未读'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsUnread') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '通知,{count} 条未读') WHERE LOWER(code) = LOWER('NotificationsUnread') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NotificationsEmpty', JSON_OBJECT('en_US', 'No notifications yet.', 'zh_CN', '暂无通知。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsEmpty') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '暂无通知。') WHERE LOWER(code) = LOWER('NotificationsEmpty') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NotificationsLoadFailed', JSON_OBJECT('en_US', 'Couldn''t load notifications.', 'zh_CN', '无法加载通知。'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsLoadFailed') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '无法加载通知。') WHERE LOWER(code) = LOWER('NotificationsLoadFailed') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NotificationsMarkAllRead', JSON_OBJECT('en_US', 'Mark all read', 'zh_CN', '全部标为已读'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsMarkAllRead') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '全部标为已读') WHERE LOWER(code) = LOWER('NotificationsMarkAllRead') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NotificationsSeeAll', JSON_OBJECT('en_US', 'See all', 'zh_CN', '查看全部'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsSeeAll') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '查看全部') WHERE LOWER(code) = LOWER('NotificationsSeeAll') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NotificationsUnreadBadge', JSON_OBJECT('en_US', 'Unread', 'zh_CN', '未读'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NotificationsUnreadBadge') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '未读') WHERE LOWER(code) = LOWER('NotificationsUnreadBadge') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NoticeLeadAssigned', JSON_OBJECT('en_US', 'Lead assigned to you', 'zh_CN', '有新线索分配给你'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeLeadAssigned') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '有新线索分配给你') WHERE LOWER(code) = LOWER('NoticeLeadAssigned') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NoticeWebSignup', JSON_OBJECT('en_US', 'New sign-up', 'zh_CN', '新的报名'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeWebSignup') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '新的报名') WHERE LOWER(code) = LOWER('NoticeWebSignup') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NoticeLeadBody', JSON_OBJECT('en_US', '{lead} · {event}', 'zh_CN', '{lead} · {event}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeLeadBody') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '{lead} · {event}') WHERE LOWER(code) = LOWER('NoticeLeadBody') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NoticeFollowUpDue', JSON_OBJECT('en_US', 'Follow-ups due', 'zh_CN', '待跟进'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeFollowUpDue') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '待跟进') WHERE LOWER(code) = LOWER('NoticeFollowUpDue') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NoticeFollowUpBody', JSON_OBJECT('en_US', '{due} due today, {overdue} overdue', 'zh_CN', '今天到期 {due} 条,已逾期 {overdue} 条'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeFollowUpBody') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '今天到期 {due} 条,已逾期 {overdue} 条') WHERE LOWER(code) = LOWER('NoticeFollowUpBody') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NoticeWhatsappMessage', JSON_OBJECT('en_US', 'New WhatsApp message', 'zh_CN', '新的 WhatsApp 消息'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeWhatsappMessage') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '新的 WhatsApp 消息') WHERE LOWER(code) = LOWER('NoticeWhatsappMessage') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NoticeWhatsappBody', JSON_OBJECT('en_US', 'From {name}', 'zh_CN', '来自 {name}'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeWhatsappBody') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '来自 {name}') WHERE LOWER(code) = LOWER('NoticeWhatsappBody') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'NoticeWhatsappBodyNoName', JSON_OBJECT('en_US', 'From a new contact', 'zh_CN', '来自新联系人'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('NoticeWhatsappBodyNoName') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '来自新联系人') WHERE LOWER(code) = LOWER('NoticeWhatsappBodyNoName') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesMoveUp', JSON_OBJECT('en_US', 'Move up', 'zh_CN', '上移'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesMoveUp') AND area = 'A');
|
||||
UPDATE message SET content = JSON_SET(COALESCE(content, JSON_OBJECT()), '$.zh_CN', '上移') WHERE LOWER(code) = LOWER('PagesMoveUp') AND area = 'A';
|
||||
INSERT INTO message (code, content, area) SELECT 'PagesMoveDown', JSON_OBJECT('en_US', 'Move down', 'zh_CN', '下移'), 'A' FROM DUAL WHERE NOT EXISTS (SELECT 1 FROM message WHERE LOWER(code) = LOWER('PagesMoveDown') AND area = 'A');
|
||||
|
||||
@@ -0,0 +1,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';
|
||||
@@ -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';
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
|
||||
export async function POST(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const { id } = await params;
|
||||
if (!/^\d+$/.test(id)) return badRequest("A numeric notification id is required.");
|
||||
const result = await callMobileApi<unknown>(`/api/admin/notifications/${encodeURIComponent(id)}/read`, { method: "POST", token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
|
||||
export async function POST() {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const result = await callMobileApi<{ count: number }>("/api/admin/notifications/read-all", { method: "POST", token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
|
||||
// GET -> /api/admin/notifications: the signed-in user's own inbox, newest first. Side-effect free.
|
||||
export async function GET(req: NextRequest) {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const params = new URL(req.url).searchParams;
|
||||
const qs = new URLSearchParams();
|
||||
for (const k of ["page", "size"]) {
|
||||
const v = params.get(k);
|
||||
if (v && /^\d+$/.test(v)) qs.set(k, v);
|
||||
}
|
||||
const result = await callMobileApi<Record<string, unknown>>(`/api/admin/notifications?${qs.toString()}`, { token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
|
||||
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
||||
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
|
||||
|
||||
import * as list from "./route";
|
||||
import * as count from "./unread-count/route";
|
||||
import * as readAll from "./read-all/route";
|
||||
import * as readOne from "./[id]/read/route";
|
||||
|
||||
type Req = Parameters<typeof list.GET>[0];
|
||||
const req = (url: string, init: RequestInit = {}) => new Request(`http://localhost${url}`, init) as unknown as Req;
|
||||
const ctx = (id: string) => ({ params: Promise.resolve({ id }) });
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.getToken.mockResolvedValue("jwt");
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { items: [], total: 0 } });
|
||||
});
|
||||
|
||||
// add-lead-notifications: the bell's routes only ever act on the signed-in user's own notifications.
|
||||
describe("notification routes", () => {
|
||||
it("refuse without a session", async () => {
|
||||
mocks.getToken.mockResolvedValue(null);
|
||||
expect((await list.GET(req("/api/notifications"))).status).toBe(401);
|
||||
expect((await count.GET()).status).toBe(401);
|
||||
expect((await readAll.POST()).status).toBe(401);
|
||||
expect((await readOne.POST(req("/api/notifications/1/read", { method: "POST" }), ctx("1"))).status).toBe(401);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("list forwards only numeric page and size", async () => {
|
||||
const res = await list.GET(req("/api/notifications?page=2&size=10&receiver=9&x=1"));
|
||||
expect(res.status).toBe(200);
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/notifications?page=2&size=10", { token: "jwt" });
|
||||
|
||||
await list.GET(req("/api/notifications?page=-1&size=abc"));
|
||||
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/notifications?", { token: "jwt" });
|
||||
});
|
||||
|
||||
it("unread count and read-all call mobile-api", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { count: 3 } });
|
||||
expect(await (await count.GET()).json()).toEqual({ count: 3 });
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/notifications/unread-count", { token: "jwt" });
|
||||
|
||||
await readAll.POST();
|
||||
expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/notifications/read-all", { method: "POST", token: "jwt" });
|
||||
});
|
||||
|
||||
it("mark read takes a numeric id only and answers 204", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: true, data: undefined });
|
||||
const ok = await readOne.POST(req("/api/notifications/42/read", { method: "POST" }), ctx("42"));
|
||||
expect(ok.status).toBe(204);
|
||||
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/notifications/42/read", { method: "POST", token: "jwt" });
|
||||
|
||||
mocks.callMobileApi.mockClear();
|
||||
const bad = await readOne.POST(req("/api/notifications/..%2Fx/read", { method: "POST" }), ctx("../x"));
|
||||
expect(bad.status).toBe(400);
|
||||
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("pass an upstream failure through", async () => {
|
||||
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Not found", status: 404 });
|
||||
const res = await readOne.POST(req("/api/notifications/7/read", { method: "POST" }), ctx("7"));
|
||||
expect(res.status).toBe(404);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { callMobileApi } from "@/app/lib/server/mobileApi";
|
||||
import { getToken } from "@/app/lib/server/session";
|
||||
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
|
||||
|
||||
export async function GET() {
|
||||
const token = await getToken();
|
||||
if (!token) return unauthorized();
|
||||
const result = await callMobileApi<{ count: number }>("/api/admin/notifications/unread-count", { token });
|
||||
if (!result.ok) return errorResponse(result);
|
||||
return NextResponse.json(result.data);
|
||||
}
|
||||
@@ -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() {
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<CompanyPicker />
|
||||
<LocaleSwitcher />
|
||||
<NotificationsBell />
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const svc = vi.hoisted(() => ({
|
||||
getUnreadCount: vi.fn(),
|
||||
listNotifications: vi.fn(),
|
||||
markRead: vi.fn(),
|
||||
markAllRead: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/notifications", async (orig) => ({
|
||||
...(await orig<typeof import("@/app/lib/services/notifications")>()),
|
||||
...svc,
|
||||
}));
|
||||
|
||||
import NotificationsBell from "./NotificationsBell";
|
||||
|
||||
const row = (id: number, seen: boolean, link: string | null = `/leads/${id}`) => ({
|
||||
id, title: "NoticeLeadAssigned", type: "LEAD_ASSIGNED", link, seen, createDateTime: "2026-12-02T09:00:00",
|
||||
message: '{"code":"NoticeLeadBody","params":{"lead":"Ali","event":"Expo"}}',
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
svc.getUnreadCount.mockResolvedValue(2);
|
||||
svc.listNotifications.mockResolvedValue({ items: [row(1, false), row(2, false), row(3, true)], total: 3 });
|
||||
svc.markRead.mockResolvedValue(undefined);
|
||||
svc.markAllRead.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
// add-lead-notifications: the header bell.
|
||||
describe("NotificationsBell", () => {
|
||||
it("shows the unread count from the server", async () => {
|
||||
render(<NotificationsBell />);
|
||||
expect(await screen.findByText("2")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: /2 unread/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("opening it lists the newest 10 in the reader's language and marks the unread ones read", async () => {
|
||||
render(<NotificationsBell />);
|
||||
await screen.findByText("2");
|
||||
svc.getUnreadCount.mockResolvedValue(0);
|
||||
await userEvent.click(screen.getByRole("button", { name: /notifications/i }));
|
||||
|
||||
expect(svc.listNotifications).toHaveBeenCalledWith(0, 10);
|
||||
expect(await screen.findAllByText("Lead assigned to you")).toHaveLength(3);
|
||||
expect(screen.getAllByText("Ali · Expo")).toHaveLength(3);
|
||||
await waitFor(() => expect(svc.markRead).toHaveBeenCalledTimes(2));
|
||||
expect(svc.markRead).toHaveBeenCalledWith(1);
|
||||
expect(svc.markRead).toHaveBeenCalledWith(2);
|
||||
await waitFor(() => expect(screen.queryByText("2")).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it("each item links to its target, and only to a path on this site", async () => {
|
||||
svc.listNotifications.mockResolvedValue({ items: [row(1, true), row(2, true, "//evil.example")], total: 2 });
|
||||
render(<NotificationsBell />);
|
||||
await userEvent.click(await screen.findByRole("button", { name: /notifications/i }));
|
||||
|
||||
const items = await screen.findAllByRole("menuitem", { name: /Lead assigned to you/ });
|
||||
expect(items[0]).toHaveAttribute("href", "/leads/1");
|
||||
expect(items[1]).not.toHaveAttribute("href");
|
||||
expect(screen.getByRole("menuitem", { name: /see all/i })).toHaveAttribute("href", "/notifications");
|
||||
});
|
||||
|
||||
it("says so when there are none, or when loading fails", async () => {
|
||||
svc.listNotifications.mockResolvedValue({ items: [], total: 0 });
|
||||
const { unmount } = render(<NotificationsBell />);
|
||||
await userEvent.click(await screen.findByRole("button", { name: /notifications/i }));
|
||||
expect(await screen.findByText("No notifications yet.")).toBeInTheDocument();
|
||||
unmount();
|
||||
|
||||
svc.listNotifications.mockRejectedValue(new Error("down"));
|
||||
render(<NotificationsBell />);
|
||||
await userEvent.click(await screen.findByRole("button", { name: /notifications/i }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Couldn't load notifications.");
|
||||
});
|
||||
|
||||
it("a failing unread count leaves the bell quiet instead of breaking the header", async () => {
|
||||
svc.getUnreadCount.mockRejectedValue(new Error("down"));
|
||||
render(<NotificationsBell />);
|
||||
expect(await screen.findByRole("button", { name: /notifications/i })).toBeInTheDocument();
|
||||
expect(screen.queryByText("0")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Bell } from "lucide-react";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/app/components/ui/dropdown-menu";
|
||||
import { useLocale, useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { usePolling } from "@/app/lib/hooks/usePolling";
|
||||
import {
|
||||
getUnreadCount,
|
||||
isSitePath,
|
||||
listNotifications,
|
||||
markAllRead,
|
||||
markRead,
|
||||
noticeText,
|
||||
noticeTime,
|
||||
type AdminNotification,
|
||||
} from "@/app/lib/services/notifications";
|
||||
|
||||
const POLL_MS = 30_000;
|
||||
|
||||
// add-lead-notifications: the header bell. The unread count polls while the tab is visible; opening the menu loads
|
||||
// the newest 10 and marks the unread ones read (read state lives on the server, so it follows the user).
|
||||
export default function NotificationsBell() {
|
||||
const t = useT();
|
||||
const locale = useLocale();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [unread, setUnread] = useState(0);
|
||||
const [items, setItems] = useState<AdminNotification[] | null>(null);
|
||||
const [failed, setFailed] = useState(false);
|
||||
|
||||
const refreshCount = () => getUnreadCount().then(setUnread).catch(() => {});
|
||||
usePolling(refreshCount, POLL_MS, undefined, !open);
|
||||
|
||||
async function onOpenChange(next: boolean) {
|
||||
setOpen(next);
|
||||
if (!next) return;
|
||||
setItems(null);
|
||||
setFailed(false);
|
||||
try {
|
||||
const page = await listNotifications(0, 10);
|
||||
setItems(page.items);
|
||||
const unseen = page.items.filter((i) => !i.seen).map((i) => i.id);
|
||||
if (unseen.length) {
|
||||
await Promise.allSettled(unseen.map((id) => markRead(id)));
|
||||
await refreshCount();
|
||||
}
|
||||
} catch {
|
||||
setFailed(true);
|
||||
}
|
||||
}
|
||||
|
||||
async function onMarkAll() {
|
||||
await markAllRead().catch(() => {});
|
||||
setItems((list) => list?.map((i) => ({ ...i, seen: true })) ?? list);
|
||||
await refreshCount();
|
||||
}
|
||||
|
||||
const when = (iso: string) => noticeTime(iso, locale);
|
||||
|
||||
return (
|
||||
<DropdownMenu open={open} onOpenChange={onOpenChange}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="relative size-9"
|
||||
aria-label={unread > 0 ? t("NotificationsUnread", { count: unread }) : t("NotificationsTitle")}
|
||||
>
|
||||
<Bell aria-hidden="true" className="size-4" />
|
||||
{unread > 0 && (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="absolute -top-0.5 -right-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-destructive px-1 text-[10px] leading-none font-semibold text-destructive-foreground"
|
||||
>
|
||||
{unread > 99 ? "99+" : unread}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-80 max-w-[calc(100vw-2rem)]">
|
||||
<div className="flex items-center justify-between gap-2 pr-1">
|
||||
<DropdownMenuLabel>{t("NotificationsTitle")}</DropdownMenuLabel>
|
||||
<Button variant="link" size="sm" className="h-auto p-0 text-xs" onClick={onMarkAll}>
|
||||
{t("NotificationsMarkAllRead")}
|
||||
</Button>
|
||||
</div>
|
||||
<DropdownMenuSeparator />
|
||||
{failed ? (
|
||||
<p role="alert" className="px-2 py-3 text-sm text-destructive">{t("NotificationsLoadFailed")}</p>
|
||||
) : items === null ? (
|
||||
<p className="px-2 py-3 text-sm text-muted-foreground">{t("Loading")}</p>
|
||||
) : items.length === 0 ? (
|
||||
<p className="px-2 py-3 text-sm text-muted-foreground">{t("NotificationsEmpty")}</p>
|
||||
) : (
|
||||
<div className="max-h-96 overflow-y-auto">
|
||||
{items.map((item) => {
|
||||
const { title, body } = noticeText(item, t);
|
||||
const inner = (
|
||||
<span className="flex w-full min-w-0 items-start gap-2">
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-sm font-medium">{title}</span>
|
||||
{body && <span className="block truncate text-xs text-muted-foreground">{body}</span>}
|
||||
<span className="block text-xs text-muted-foreground">{when(item.createDateTime)}</span>
|
||||
</span>
|
||||
{!item.seen && <span aria-hidden="true" className="mt-1.5 size-2 shrink-0 rounded-full bg-primary" />}
|
||||
</span>
|
||||
);
|
||||
return isSitePath(item.link) ? (
|
||||
<DropdownMenuItem key={item.id} asChild>
|
||||
<Link href={item.link}>{inner}</Link>
|
||||
</DropdownMenuItem>
|
||||
) : (
|
||||
<DropdownMenuItem key={item.id}>{inner}</DropdownMenuItem>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href="/notifications" className="justify-center text-sm">{t("NotificationsSeeAll")}</Link>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
@@ -760,6 +760,21 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
PagesHtml: "HTML",
|
||||
PagesHtmlHint: "Forms inside the pasted HTML don't send. Add a Sign-up form block to collect leads.",
|
||||
PagesHideHeader: "Hide page header",
|
||||
NotificationsTitle: "Notifications",
|
||||
NotificationsUnread: "Notifications, {count} unread",
|
||||
NotificationsEmpty: "No notifications yet.",
|
||||
NotificationsLoadFailed: "Couldn't load notifications.",
|
||||
NotificationsMarkAllRead: "Mark all read",
|
||||
NotificationsSeeAll: "See all",
|
||||
NotificationsUnreadBadge: "Unread",
|
||||
NoticeLeadAssigned: "Lead assigned to you",
|
||||
NoticeWebSignup: "New sign-up",
|
||||
NoticeLeadBody: "{lead} · {event}",
|
||||
NoticeFollowUpDue: "Follow-ups due",
|
||||
NoticeFollowUpBody: "{due} due today, {overdue} overdue",
|
||||
NoticeWhatsappMessage: "New WhatsApp message",
|
||||
NoticeWhatsappBody: "From {name}",
|
||||
NoticeWhatsappBodyNoName: "From a new contact",
|
||||
PagesMoveUp: "Move up",
|
||||
PagesMoveDown: "Move down",
|
||||
PagesRemoveBlock: "Remove block",
|
||||
|
||||
@@ -767,6 +767,21 @@
|
||||
"PagesHtml": "HTML",
|
||||
"PagesHtmlHint": "粘贴的 HTML 中的表单不会发送。请添加报名表单区块来收集线索。",
|
||||
"PagesHideHeader": "隐藏页面顶栏",
|
||||
"NotificationsTitle": "通知",
|
||||
"NotificationsUnread": "通知,{count} 条未读",
|
||||
"NotificationsEmpty": "暂无通知。",
|
||||
"NotificationsLoadFailed": "无法加载通知。",
|
||||
"NotificationsMarkAllRead": "全部标为已读",
|
||||
"NotificationsSeeAll": "查看全部",
|
||||
"NotificationsUnreadBadge": "未读",
|
||||
"NoticeLeadAssigned": "有新线索分配给你",
|
||||
"NoticeWebSignup": "新的报名",
|
||||
"NoticeLeadBody": "{lead} · {event}",
|
||||
"NoticeFollowUpDue": "待跟进",
|
||||
"NoticeFollowUpBody": "今天到期 {due} 条,已逾期 {overdue} 条",
|
||||
"NoticeWhatsappMessage": "新的 WhatsApp 消息",
|
||||
"NoticeWhatsappBody": "来自 {name}",
|
||||
"NoticeWhatsappBodyNoName": "来自新联系人",
|
||||
"PagesFormClosed": "报名已截止。",
|
||||
"PagesFormPreview": "发布后的网页会在此显示报名表。",
|
||||
"PagesToolbar": "格式",
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { noticeText, type AdminNotification } from "./notifications";
|
||||
|
||||
const t = (code: string, params?: Record<string, string | number>) => `${code}${params ? JSON.stringify(params) : ""}`;
|
||||
const item = (over: Partial<AdminNotification>): AdminNotification => ({
|
||||
id: 1, title: "NoticeLeadAssigned", message: null, type: "LEAD_ASSIGNED", link: "/leads/9", seen: false,
|
||||
createDateTime: "2026-12-02T09:00:00", ...over,
|
||||
});
|
||||
|
||||
// add-lead-notifications: rows store codes, so the reader's language decides the text.
|
||||
describe("noticeText", () => {
|
||||
it("renders the title code and the body code with its parameters", () => {
|
||||
expect(noticeText(item({ message: '{"code":"NoticeLeadBody","params":{"lead":"Ali","event":"Expo"}}' }), t)).toEqual({
|
||||
title: "NoticeLeadAssigned",
|
||||
body: 'NoticeLeadBody{"lead":"Ali","event":"Expo"}',
|
||||
});
|
||||
});
|
||||
|
||||
it("shows no body for a missing or unreadable message, never the raw JSON", () => {
|
||||
expect(noticeText(item({ message: null }), t).body).toBe("");
|
||||
expect(noticeText(item({ message: "{not json" }), t).body).toBe("");
|
||||
expect(noticeText(item({ message: '{"params":{}}' }), t).body).toBe("");
|
||||
});
|
||||
|
||||
it("keeps only string and number parameters", () => {
|
||||
expect(noticeText(item({ message: '{"code":"B","params":{"a":1,"b":null,"c":{"x":1}}}' }), t).body).toBe('B{"a":1}');
|
||||
});
|
||||
});
|
||||
|
||||
describe("isSitePath", () => {
|
||||
it("accepts a path on this site only", async () => {
|
||||
const { isSitePath } = await import("./notifications");
|
||||
expect(isSitePath("/leads/1")).toBe(true);
|
||||
expect(isSitePath("/whatsapp?c=x")).toBe(true);
|
||||
for (const bad of [null, "", "//evil.example", "/\\evil.example", "https://evil.example", "javascript:alert(1)"]) {
|
||||
expect(isSitePath(bad)).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("noticeTime", () => {
|
||||
it("formats in the stored locale and falls back to the raw value", async () => {
|
||||
const { noticeTime } = await import("./notifications");
|
||||
expect(noticeTime("2026-12-02T09:00:00", "en_US")).toMatch(/2026/);
|
||||
expect(noticeTime("2026-12-02T09:00:00", "zh_CN")).toMatch(/2026/);
|
||||
expect(noticeTime("2026-12-02T09:00:00", "not a locale!")).toBe("2026-12-02T09:00:00");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,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<NotificationPage> {
|
||||
const res = await apiGet<Partial<NotificationPage>>(`/api/notifications?page=${page}&size=${size}`);
|
||||
return { items: res?.items ?? [], total: res?.total ?? 0 };
|
||||
}
|
||||
|
||||
export async function getUnreadCount(): Promise<number> {
|
||||
return (await apiGet<{ count: number }>("/api/notifications/unread-count"))?.count ?? 0;
|
||||
}
|
||||
|
||||
export async function markRead(id: number): Promise<void> {
|
||||
await apiPost<void>(`/api/notifications/${id}/read`);
|
||||
}
|
||||
|
||||
export async function markAllRead(): Promise<void> {
|
||||
await apiPost<void>("/api/notifications/read-all");
|
||||
}
|
||||
|
||||
type T = (code: string, params?: Record<string, string | number>) => string;
|
||||
|
||||
/** The title and body in the reader's language. The row stores codes; anything unreadable shows no body. */
|
||||
export function noticeText(item: AdminNotification, t: T): { title: string; body: string } {
|
||||
let body = "";
|
||||
try {
|
||||
const m = JSON.parse(item.message ?? "") as { code?: unknown; params?: Record<string, unknown> };
|
||||
if (typeof m.code === "string") {
|
||||
const params: Record<string, string | number> = {};
|
||||
for (const [k, v] of Object.entries(m.params ?? {})) {
|
||||
if (typeof v === "string" || typeof v === "number") params[k] = v;
|
||||
}
|
||||
body = t(m.code, params);
|
||||
}
|
||||
} catch {
|
||||
/* not JSON: no body */
|
||||
}
|
||||
return { title: t(item.title), body };
|
||||
}
|
||||
|
||||
/** A link opens only when it is a path on this site (a single leading slash, no backslash tricks). */
|
||||
export function isSitePath(link: string | null | undefined): link is string {
|
||||
return !!link && link.startsWith("/") && !link.startsWith("//") && !link.includes("\\");
|
||||
}
|
||||
|
||||
/** Date and time in the reader's locale (stored as en_US, Intl wants en-US). */
|
||||
export function noticeTime(iso: string, locale: string): string {
|
||||
try {
|
||||
return new Intl.DateTimeFormat(locale.replace("_", "-"), { dateStyle: "medium", timeStyle: "short" }).format(new Date(iso));
|
||||
} catch {
|
||||
return iso;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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<typeof import("@/app/lib/services/notifications")>()),
|
||||
...svc,
|
||||
}));
|
||||
|
||||
import NotificationsPage from "./page";
|
||||
|
||||
const row = (id: number, seen: boolean) => ({
|
||||
id, title: "NoticeFollowUpDue", type: "FOLLOW_UP_DUE", link: "/leads", seen, createDateTime: "2026-12-02T08:00:00",
|
||||
message: '{"code":"NoticeFollowUpBody","params":{"due":2,"overdue":1}}',
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
svc.listNotifications.mockResolvedValue({ items: [row(1, false), row(2, true)], total: 2 });
|
||||
svc.markAllRead.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
// add-lead-notifications: the full list of the signed-in user's notifications.
|
||||
describe("/notifications", () => {
|
||||
it("lists the user's notifications with links and marks unread ones", async () => {
|
||||
render(<NotificationsPage />);
|
||||
const links = await screen.findAllByRole("link", { name: /Follow-ups due/ });
|
||||
expect(links).toHaveLength(2);
|
||||
expect(links[0]).toHaveAttribute("href", "/leads");
|
||||
expect(screen.getAllByText("2 due today, 1 overdue")).toHaveLength(2);
|
||||
expect(screen.getAllByText("Unread")).toHaveLength(1);
|
||||
expect(svc.listNotifications).toHaveBeenCalledWith(0, 20);
|
||||
});
|
||||
|
||||
it("Mark all read marks them and reloads", async () => {
|
||||
render(<NotificationsPage />);
|
||||
await screen.findAllByRole("link", { name: /Follow-ups due/ });
|
||||
svc.listNotifications.mockResolvedValue({ items: [row(1, true), row(2, true)], total: 2 });
|
||||
|
||||
await userEvent.click(screen.getByRole("button", { name: "Mark all read" }));
|
||||
|
||||
expect(svc.markAllRead).toHaveBeenCalled();
|
||||
await waitFor(() => expect(screen.queryByText("Unread")).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it("shows an empty state and a load error", async () => {
|
||||
svc.listNotifications.mockResolvedValue({ items: [], total: 0 });
|
||||
const { unmount } = render(<NotificationsPage />);
|
||||
expect(await screen.findByText("No notifications yet.")).toBeInTheDocument();
|
||||
unmount();
|
||||
|
||||
svc.listNotifications.mockRejectedValue(new Error("down"));
|
||||
render(<NotificationsPage />);
|
||||
expect(await screen.findByText("Couldn't load notifications.")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,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<NotificationPage | null>(null);
|
||||
const [error, setError] = useState(false);
|
||||
|
||||
const load = useCallback(() => {
|
||||
listNotifications(page - 1, PAGE_SIZE)
|
||||
.then((d) => {
|
||||
setError(false);
|
||||
setData(d);
|
||||
})
|
||||
.catch(() => setError(true));
|
||||
}, [page]);
|
||||
|
||||
useEffect(load, [load]);
|
||||
|
||||
async function onMarkAll() {
|
||||
await markAllRead().catch(() => {});
|
||||
load();
|
||||
}
|
||||
|
||||
const when = (iso: string) => noticeTime(iso, locale);
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title={t("NotificationsTitle")}
|
||||
actions={<Button variant="outline" onClick={onMarkAll}>{t("NotificationsMarkAllRead")}</Button>}
|
||||
/>
|
||||
{error && <ErrorState message={t("NotificationsLoadFailed")} onRetry={load} />}
|
||||
{data?.items.length === 0 && <EmptyState title={t("NotificationsEmpty")} />}
|
||||
{!!data?.items.length && (
|
||||
<>
|
||||
<ul className="divide-y rounded-md border bg-card">
|
||||
{data.items.map((item) => {
|
||||
const { title, body } = noticeText(item, t);
|
||||
const inner = (
|
||||
<span className="flex items-start gap-3 px-4 py-3">
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block font-medium">{title}</span>
|
||||
{body && <span className="block text-sm text-muted-foreground">{body}</span>}
|
||||
<span className="block text-xs text-muted-foreground">{when(item.createDateTime)}</span>
|
||||
</span>
|
||||
{!item.seen && <Badge>{t("NotificationsUnreadBadge")}</Badge>}
|
||||
</span>
|
||||
);
|
||||
return (
|
||||
<li key={item.id}>
|
||||
{isSitePath(item.link) ? (
|
||||
<Link href={item.link} className="block hover:bg-accent">{inner}</Link>
|
||||
) : inner}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
<TablePager page={page} pageSize={PAGE_SIZE} total={data.total} onPageChange={setPage} />
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user