mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-06 08:04:37 +00:00
feat(notification): add unread sidebar count badge and fix project scope upload authorization check
This commit is contained in:
@@ -110,8 +110,8 @@ describe('Upload API', () => {
|
|||||||
expect(res.status).toBe(200)
|
expect(res.status).toBe(200)
|
||||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
type: ResourceType.Team,
|
type: ResourceType.Asset,
|
||||||
id: 'team1',
|
id: 'file1',
|
||||||
permission: Permission.Edit,
|
permission: Permission.Edit,
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|||||||
+2
-2
@@ -92,8 +92,8 @@ const route = new Hono<{ Variables: { user: User } }>()
|
|||||||
await authzService.hasPermission({
|
await authzService.hasPermission({
|
||||||
user,
|
user,
|
||||||
permission: Permission.Edit,
|
permission: Permission.Edit,
|
||||||
type: ResourceType.Team,
|
type: ResourceType.Asset,
|
||||||
id: teamId,
|
id: req.fileId,
|
||||||
})
|
})
|
||||||
|
|
||||||
await uploadService.confirmFileUpload(user.id, taskId, req)
|
await uploadService.confirmFileUpload(user.id, taskId, req)
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ export const getMeResponseSchema = z.object({
|
|||||||
name: z.string(),
|
name: z.string(),
|
||||||
email: z.string().optional(),
|
email: z.string().optional(),
|
||||||
role: z.string(),
|
role: z.string(),
|
||||||
|
unreadNotificationCount: z.number().optional(),
|
||||||
})
|
})
|
||||||
export type GetMeResponse = z.infer<typeof getMeResponseSchema>
|
export type GetMeResponse = z.infer<typeof getMeResponseSchema>
|
||||||
|
|
||||||
|
|||||||
@@ -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 === uploadNotifOther.id)).toBe(false) // otherUploads is now false
|
||||||
expect(resCustom.data.some((n) => n.id === uploadNotifSelf.id)).toBe(true) // yourUploads is now true
|
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)
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -97,28 +97,12 @@ export class NotificationService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async list(
|
private async getListWhere(
|
||||||
teamId: string,
|
teamId: string,
|
||||||
userId: string,
|
userId: string,
|
||||||
params: ListNotificationParams,
|
teamMember: Prisma.TeamMemberGetPayload<{ include: { lastReadNotification: true } }>,
|
||||||
): Promise<PaginatedData<NotificationInfo[]>> {
|
unreadOnly: boolean,
|
||||||
// Get user's last read notification
|
): Promise<Prisma.NotificationWhereInput> {
|
||||||
const teamMember = await prisma.teamMember.findUnique({
|
|
||||||
where: {
|
|
||||||
teamIdUserId: {
|
|
||||||
teamId,
|
|
||||||
userId,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
include: {
|
|
||||||
lastReadNotification: true,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!teamMember) {
|
|
||||||
throw new Error('failed to get team member')
|
|
||||||
}
|
|
||||||
|
|
||||||
// Permission Filtering based on Scope
|
// Permission Filtering based on Scope
|
||||||
let projectFilter: string[] = []
|
let projectFilter: string[] = []
|
||||||
if (teamMember.scope === 'project') {
|
if (teamMember.scope === 'project') {
|
||||||
@@ -215,7 +199,7 @@ export class NotificationService {
|
|||||||
] as Prisma.NotificationWhereInput[]
|
] as Prisma.NotificationWhereInput[]
|
||||||
}
|
}
|
||||||
|
|
||||||
if (params.unreadOnly && teamMember.lastReadNotification) {
|
if (unreadOnly && teamMember.lastReadNotification) {
|
||||||
// We want notifications NEWER than the last read one.
|
// We want notifications NEWER than the last read one.
|
||||||
// String comparison works for ULID/KSUID.
|
// String comparison works for ULID/KSUID.
|
||||||
const currentAnd = Array.isArray(where.AND) ? where.AND : where.AND ? [where.AND] : []
|
const currentAnd = Array.isArray(where.AND) ? where.AND : where.AND ? [where.AND] : []
|
||||||
@@ -225,6 +209,54 @@ export class NotificationService {
|
|||||||
] as Prisma.NotificationWhereInput[]
|
] as Prisma.NotificationWhereInput[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return where
|
||||||
|
}
|
||||||
|
|
||||||
|
async getUnreadCount(teamId: string, userId: string): Promise<number> {
|
||||||
|
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<PaginatedData<NotificationInfo[]>> {
|
||||||
|
// 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<NotificationInfo>(
|
return paginateQuery<NotificationInfo>(
|
||||||
async (skip, take) => {
|
async (skip, take) => {
|
||||||
const notifications = await prisma.notification.findMany({
|
const notifications = await prisma.notification.findMany({
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { prisma } from '@/db'
|
|||||||
import { Prisma } from '@/generated/prisma/client'
|
import { Prisma } from '@/generated/prisma/client'
|
||||||
import { PaginatedData, paginateQuery } from '@/services/pagination'
|
import { PaginatedData, paginateQuery } from '@/services/pagination'
|
||||||
import { ProviderService, providerService } from '@/services/provider/provider'
|
import { ProviderService, providerService } from '@/services/provider/provider'
|
||||||
|
import { notificationService } from '@/services/notification/notification'
|
||||||
import {
|
import {
|
||||||
ServiceCreateTeamRequest,
|
ServiceCreateTeamRequest,
|
||||||
ServiceGetUserTeamsRequest,
|
ServiceGetUserTeamsRequest,
|
||||||
@@ -138,11 +139,17 @@ export class TeamService {
|
|||||||
|
|
||||||
if (!member) throw new Error('user is not a team member')
|
if (!member) throw new Error('user is not a team member')
|
||||||
|
|
||||||
|
const unreadNotificationCount = await notificationService.getUnreadCount(
|
||||||
|
req.teamId,
|
||||||
|
req.user.id,
|
||||||
|
)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: req.user.id,
|
id: req.user.id,
|
||||||
name: req.user.name,
|
name: req.user.name,
|
||||||
email: undefined,
|
email: undefined,
|
||||||
role: member.role,
|
role: member.role,
|
||||||
|
unreadNotificationCount,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { UserMenu } from './user-menu'
|
|||||||
interface DualSidebarItemProps {
|
interface DualSidebarItemProps {
|
||||||
icon: React.ReactNode
|
icon: React.ReactNode
|
||||||
label: string
|
label: string
|
||||||
|
badge?: React.ReactNode
|
||||||
children?: React.ReactNode
|
children?: React.ReactNode
|
||||||
onItemClick?: () => void
|
onItemClick?: () => void
|
||||||
}
|
}
|
||||||
@@ -113,13 +114,14 @@ export const DualSidebar: React.FC<DualSidebarProps> = ({ children }) => {
|
|||||||
onClick={() => handleItemClick(index)}
|
onClick={() => handleItemClick(index)}
|
||||||
aria-label={item.props.label}
|
aria-label={item.props.label}
|
||||||
aria-expanded={activeItem === index}
|
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
|
activeItem === index
|
||||||
? 'bg-blue-600 text-white shadow-lg hover:bg-blue-600 hover:text-white'
|
? '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'
|
: '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.icon}
|
||||||
|
{item.props.badge}
|
||||||
</Button>
|
</Button>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
<TooltipContent
|
<TooltipContent
|
||||||
|
|||||||
@@ -55,6 +55,14 @@ export const NotificationList = () => {
|
|||||||
[data],
|
[data],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (teamId) {
|
||||||
|
queryClient.invalidateQueries({
|
||||||
|
queryKey: ['teams', teamId, 'me'],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}, [teamId, notifications.length, queryClient])
|
||||||
|
|
||||||
const $post = client.api.teams[':teamId'].notifications.read.$post
|
const $post = client.api.teams[':teamId'].notifications.read.$post
|
||||||
const markReadMutation = useMutation<
|
const markReadMutation = useMutation<
|
||||||
InferResponseType<typeof $post>,
|
InferResponseType<typeof $post>,
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ import {
|
|||||||
useNavigate,
|
useNavigate,
|
||||||
useRouterState,
|
useRouterState,
|
||||||
} from '@tanstack/react-router'
|
} from '@tanstack/react-router'
|
||||||
|
import { useQuery } from '@tanstack/react-query'
|
||||||
|
import { client } from '@/ui/api/client'
|
||||||
import { useEffect } from 'react'
|
import { useEffect } from 'react'
|
||||||
|
|
||||||
function RootComponent() {
|
function RootComponent() {
|
||||||
@@ -45,6 +47,28 @@ function RootComponent() {
|
|||||||
}
|
}
|
||||||
}, [teamId, projectId, setTeamId, ensureTeamIdForProject])
|
}, [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 ? (
|
||||||
|
<div className="absolute -top-1 -right-1 min-w-[18px] h-[18px] px-1 bg-red-500 text-white rounded-full flex items-center justify-center text-[10px] font-bold border-2 border-slate-100 dark:border-slate-900 animate-pulse">
|
||||||
|
{displayCount}
|
||||||
|
</div>
|
||||||
|
) : null
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex h-screen w-full bg-background overflow-hidden">
|
<div className="flex h-screen w-full bg-background overflow-hidden">
|
||||||
<Toaster />
|
<Toaster />
|
||||||
@@ -61,7 +85,7 @@ function RootComponent() {
|
|||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<DualSidebarItem icon={<NotificationFillIcon />} label="Notifications">
|
<DualSidebarItem icon={<NotificationFillIcon />} label="Notifications" badge={badge}>
|
||||||
<NotificationList />
|
<NotificationList />
|
||||||
</DualSidebarItem>
|
</DualSidebarItem>
|
||||||
<DualSidebarItem
|
<DualSidebarItem
|
||||||
|
|||||||
Reference in New Issue
Block a user