From 3ba107bfa4b73794f2a7a2ac660c3b2a395f48d1 Mon Sep 17 00:00:00 2001 From: yiling Date: Fri, 29 May 2026 23:30:15 +0800 Subject: [PATCH] feat(notification): add unread sidebar count badge and fix project scope upload authorization check --- src/api/upload.test.ts | 4 +- src/api/upload.ts | 4 +- src/dtos/team.ts | 1 + .../notification/notification.test.ts | 46 ++++++++++++ src/services/notification/notification.ts | 74 +++++++++++++------ src/services/team/team.ts | 7 ++ src/ui/components/dual-sidebar.tsx | 4 +- src/ui/components/notification-list.tsx | 8 ++ src/ui/routes/__root.tsx | 26 ++++++- 9 files changed, 147 insertions(+), 27 deletions(-) diff --git a/src/api/upload.test.ts b/src/api/upload.test.ts index 730c44ca..7a749753 100644 --- a/src/api/upload.test.ts +++ b/src/api/upload.test.ts @@ -110,8 +110,8 @@ describe('Upload API', () => { expect(res.status).toBe(200) expect(authzService.hasPermission).toHaveBeenCalledWith( expect.objectContaining({ - type: ResourceType.Team, - id: 'team1', + type: ResourceType.Asset, + id: 'file1', permission: Permission.Edit, }), ) diff --git a/src/api/upload.ts b/src/api/upload.ts index f7698b2d..74f25ec6 100644 --- a/src/api/upload.ts +++ b/src/api/upload.ts @@ -92,8 +92,8 @@ const route = new Hono<{ Variables: { user: User } }>() await authzService.hasPermission({ user, permission: Permission.Edit, - type: ResourceType.Team, - id: teamId, + type: ResourceType.Asset, + id: req.fileId, }) await uploadService.confirmFileUpload(user.id, taskId, req) diff --git a/src/dtos/team.ts b/src/dtos/team.ts index 9eefca99..4cc0b2cb 100644 --- a/src/dtos/team.ts +++ b/src/dtos/team.ts @@ -35,6 +35,7 @@ export const getMeResponseSchema = z.object({ name: z.string(), email: z.string().optional(), role: z.string(), + unreadNotificationCount: z.number().optional(), }) export type GetMeResponse = z.infer diff --git a/src/services/notification/notification.test.ts b/src/services/notification/notification.test.ts index af7d7ed2..a4a58154 100644 --- a/src/services/notification/notification.test.ts +++ b/src/services/notification/notification.test.ts @@ -310,4 +310,50 @@ describe('NotificationService', () => { expect(resCustom.data.some((n) => n.id === uploadNotifOther.id)).toBe(false) // otherUploads is now false expect(resCustom.data.some((n) => n.id === uploadNotifSelf.id)).toBe(true) // yourUploads is now true }) + + it('getUnreadCount retrieves correct count of unread notifications', async () => { + const tm = await prisma.team.create({ data: { name: 'Team 2' } }) + const u1 = await prisma.user.create({ + data: { name: 'u3', email: `u3-${Date.now()}@example.com`, password: 'p' }, + }) + const u2 = await prisma.user.create({ + data: { name: 'u4', email: `u4-${Date.now()}@example.com`, password: 'p' }, + }) + const member = await prisma.teamMember.create({ + data: { teamId: tm.id, userId: u1.id, role: 'owner' }, + }) + + // No notifications initially + let count = await notificationService.getUnreadCount(tm.id, u1.id) + expect(count).toBe(0) + + // Create unread notifications from other user + const n1 = await prisma.notification.create({ + data: { id: '101', teamId: tm.id, type: NotificationType.comment_created, creatorId: u2.id }, + }) + const n2 = await prisma.notification.create({ + data: { id: '102', teamId: tm.id, type: NotificationType.reply_created, userId: u1.id, creatorId: u2.id }, + }) + + count = await notificationService.getUnreadCount(tm.id, u1.id) + expect(count).toBe(2) + + // Mark up to n1 as read + await prisma.teamMember.update({ + where: { id: member.id }, + data: { lastReadNotificationId: n1.id }, + }) + + count = await notificationService.getUnreadCount(tm.id, u1.id) + expect(count).toBe(1) // n2 is still unread + + // Mark all as read (up to n2) + await prisma.teamMember.update({ + where: { id: member.id }, + data: { lastReadNotificationId: n2.id }, + }) + + count = await notificationService.getUnreadCount(tm.id, u1.id) + expect(count).toBe(0) + }) }) diff --git a/src/services/notification/notification.ts b/src/services/notification/notification.ts index 64878454..4a78afb4 100644 --- a/src/services/notification/notification.ts +++ b/src/services/notification/notification.ts @@ -97,28 +97,12 @@ export class NotificationService { } } - async list( + private async getListWhere( teamId: string, userId: string, - params: ListNotificationParams, - ): Promise> { - // Get user's last read notification - const teamMember = await prisma.teamMember.findUnique({ - where: { - teamIdUserId: { - teamId, - userId, - }, - }, - include: { - lastReadNotification: true, - }, - }) - - if (!teamMember) { - throw new Error('failed to get team member') - } - + teamMember: Prisma.TeamMemberGetPayload<{ include: { lastReadNotification: true } }>, + unreadOnly: boolean, + ): Promise { // Permission Filtering based on Scope let projectFilter: string[] = [] if (teamMember.scope === 'project') { @@ -215,7 +199,7 @@ export class NotificationService { ] as Prisma.NotificationWhereInput[] } - if (params.unreadOnly && teamMember.lastReadNotification) { + if (unreadOnly && teamMember.lastReadNotification) { // We want notifications NEWER than the last read one. // String comparison works for ULID/KSUID. const currentAnd = Array.isArray(where.AND) ? where.AND : where.AND ? [where.AND] : [] @@ -225,6 +209,54 @@ export class NotificationService { ] as Prisma.NotificationWhereInput[] } + return where + } + + async getUnreadCount(teamId: string, userId: string): Promise { + const teamMember = await prisma.teamMember.findUnique({ + where: { + teamIdUserId: { + teamId, + userId, + }, + }, + include: { + lastReadNotification: true, + }, + }) + + if (!teamMember) { + return 0 + } + + const where = await this.getListWhere(teamId, userId, teamMember, true) + return prisma.notification.count({ where }) + } + + async list( + teamId: string, + userId: string, + params: ListNotificationParams, + ): Promise> { + // Get user's last read notification + const teamMember = await prisma.teamMember.findUnique({ + where: { + teamIdUserId: { + teamId, + userId, + }, + }, + include: { + lastReadNotification: true, + }, + }) + + if (!teamMember) { + throw new Error('failed to get team member') + } + + const where = await this.getListWhere(teamId, userId, teamMember, !!params.unreadOnly) + return paginateQuery( async (skip, take) => { const notifications = await prisma.notification.findMany({ diff --git a/src/services/team/team.ts b/src/services/team/team.ts index d28f32d7..9d481ccc 100644 --- a/src/services/team/team.ts +++ b/src/services/team/team.ts @@ -2,6 +2,7 @@ import { prisma } from '@/db' import { Prisma } from '@/generated/prisma/client' import { PaginatedData, paginateQuery } from '@/services/pagination' import { ProviderService, providerService } from '@/services/provider/provider' +import { notificationService } from '@/services/notification/notification' import { ServiceCreateTeamRequest, ServiceGetUserTeamsRequest, @@ -138,11 +139,17 @@ export class TeamService { if (!member) throw new Error('user is not a team member') + const unreadNotificationCount = await notificationService.getUnreadCount( + req.teamId, + req.user.id, + ) + return { id: req.user.id, name: req.user.name, email: undefined, role: member.role, + unreadNotificationCount, } } diff --git a/src/ui/components/dual-sidebar.tsx b/src/ui/components/dual-sidebar.tsx index dd5fd9d0..3869859c 100644 --- a/src/ui/components/dual-sidebar.tsx +++ b/src/ui/components/dual-sidebar.tsx @@ -7,6 +7,7 @@ import { UserMenu } from './user-menu' interface DualSidebarItemProps { icon: React.ReactNode label: string + badge?: React.ReactNode children?: React.ReactNode onItemClick?: () => void } @@ -113,13 +114,14 @@ export const DualSidebar: React.FC = ({ children }) => { onClick={() => handleItemClick(index)} aria-label={item.props.label} aria-expanded={activeItem === index} - className={`w-12 h-12 [&_svg:not([class*='size-'])]:size-6 transition-all duration-200 ${ + className={`relative w-12 h-12 [&_svg:not([class*='size-'])]:size-6 transition-all duration-200 ${ activeItem === index ? 'bg-blue-600 text-white shadow-lg hover:bg-blue-600 hover:text-white' : 'text-slate-400 hover:text-slate-500 dark:hover:text-slate-400 dark:text-slate-500 hover:bg-slate-200 dark:hover:bg-slate-800' }`} > {item.props.icon} + {item.props.badge} { [data], ) + useEffect(() => { + if (teamId) { + queryClient.invalidateQueries({ + queryKey: ['teams', teamId, 'me'], + }) + } + }, [teamId, notifications.length, queryClient]) + const $post = client.api.teams[':teamId'].notifications.read.$post const markReadMutation = useMutation< InferResponseType, diff --git a/src/ui/routes/__root.tsx b/src/ui/routes/__root.tsx index 02f148ad..1ae0f804 100644 --- a/src/ui/routes/__root.tsx +++ b/src/ui/routes/__root.tsx @@ -13,6 +13,8 @@ import { useNavigate, useRouterState, } from '@tanstack/react-router' +import { useQuery } from '@tanstack/react-query' +import { client } from '@/ui/api/client' import { useEffect } from 'react' function RootComponent() { @@ -45,6 +47,28 @@ function RootComponent() { } }, [teamId, projectId, setTeamId, ensureTeamIdForProject]) + const { data: me } = useQuery({ + queryKey: ['teams', storedTeamId, 'me'], + queryFn: async () => { + if (!storedTeamId) return null + const res = await client.api.teams[':teamId'].me.$get({ + param: { teamId: storedTeamId }, + }) + if (!res.ok) throw new Error('Failed to fetch me') + return await res.json() + }, + enabled: !!storedTeamId, + }) + + const unreadCount = me?.unreadNotificationCount ?? 0 + const displayCount = unreadCount > 99 ? '99+' : unreadCount + const badge = + unreadCount > 0 ? ( +
+ {displayCount} +
+ ) : null + return (
@@ -61,7 +85,7 @@ function RootComponent() { } }} /> - } label="Notifications"> + } label="Notifications" badge={badge}>