diff --git a/src/api/file.test.ts b/src/api/file.test.ts index 4fba4117..88c231c8 100644 --- a/src/api/file.test.ts +++ b/src/api/file.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' import { Hono, type Context, type Next } from 'hono' +import { prisma } from '@/db' import fileRoute from './file' import { assetService } from '@/services/asset/asset' import { metadataService } from '@/services/metadata/metadata' @@ -202,6 +203,60 @@ describe('file api', () => { }) }) + it('POST /files/:fileId/comments - reply_created targets parent comment creator', async () => { + vi.mocked(assetService.createComment).mockResolvedValue({ + id: 'comment-id', + assetId: 'file-id', + message: 'hello reply', + annotations: null, + second: null, + creator: { id: 'user-id', name: 'Test User' }, + replies: [], + attachments: [], + mentions: [], + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + sessionId: null, + }) + + // Mock assetService.getAsset to return teamId for notification + vi.mocked(assetService.getAsset).mockResolvedValue({ + id: 'test-id', + project: { teamId: 'test-team' }, + } as any) // eslint-disable-line @typescript-eslint/no-explicit-any + + const mockFindUnique = vi.spyOn(prisma.assetComment, 'findUnique').mockResolvedValue({ + id: 'parent-comment-id', + creatorId: 'parent-comment-creator-id', + } as any) // eslint-disable-line @typescript-eslint/no-explicit-any + + const app = new Hono().use('*', authMiddleware).route('/', fileRoute) + const res = await app.request('/files/test-id/comments', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + message: 'hello reply', + replyToId: 'parent-comment-id', + attachmentIds: [], + }), + }) + + expect(res.status).toBe(201) + const json = await res.json() + expect(json.message).toBe('hello reply') + + expect(notificationService.create).toHaveBeenCalledWith({ + type: 'reply_created', + teamId: 'test-team', + creatorId: 'user1', + assetId: 'test-id', + userId: 'parent-comment-creator-id', + commentMessage: 'hello reply', + }) + + mockFindUnique.mockRestore() + }) + it('GET /files/:fileId/comments', async () => { vi.mocked(assetService.listComments).mockResolvedValue({ data: [ diff --git a/src/api/file.ts b/src/api/file.ts index a72d4eeb..0cae2f2c 100644 --- a/src/api/file.ts +++ b/src/api/file.ts @@ -1,5 +1,6 @@ import { Hono } from 'hono' import { zValidator } from '@hono/zod-validator' +import { prisma } from '@/db' import { authzService, Permission, ResourceType } from '@/services/authz/authz' import { assetService } from '@/services/asset/asset' import { metadataService } from '@/services/metadata/metadata' @@ -156,11 +157,22 @@ const route = new Hono<{ Variables: { user: User } }>() const context = await assetService.getAssetContext(fileId) if (context?.teamId) { + let targetUserId: string | undefined + if (req.replyToId) { + const parentComment = await prisma.assetComment.findUnique({ + where: { id: req.replyToId }, + }) + if (parentComment?.creatorId) { + targetUserId = parentComment.creatorId + } + } + notificationService.create({ type: notifType, teamId: context.teamId, creatorId: user.id, assetId: fileId, + userId: targetUserId, commentMessage: req.message, }) } diff --git a/src/api/notification.test.ts b/src/api/notification.test.ts index a5ed730d..0611a7b3 100644 --- a/src/api/notification.test.ts +++ b/src/api/notification.test.ts @@ -3,6 +3,7 @@ import { Hono, type Context, type Next } from 'hono' import notificationRoute from './notification' import { notificationService } from '@/services/notification/notification' import { authzService, Permission, ResourceType } from '@/services/authz/authz' +import { userMetadataService } from '@/services/user-metadata/user-metadata' vi.mock('@/api/middleware/auth', () => ({ authMiddleware: async ( @@ -16,6 +17,7 @@ vi.mock('@/api/middleware/auth', () => ({ vi.mock('@/services/authz/authz') vi.mock('@/services/notification/notification') +vi.mock('@/services/user-metadata/user-metadata') describe('notification api', () => { const app = new Hono<{ Variables: { user: { id: string; name: string } } }>() @@ -77,4 +79,78 @@ describe('notification api', () => { id: 't1', }) }) + + it('GET /teams/:teamId/notifications/settings - returns default settings', async () => { + vi.mocked(userMetadataService.getMetadata).mockResolvedValue(null) + + const res = await app.request('/teams/t1/notifications/settings') + + expect(res.status).toBe(200) + const json = await res.json() + expect(json.comments).toBe(true) + expect(json.yourUploads).toBe(false) + + expect(userMetadataService.getMetadata).toHaveBeenCalledWith( + 'user1', + 't1', + 'notification_settings', + ) + }) + + it('GET /teams/:teamId/notifications/settings - returns saved settings', async () => { + vi.mocked(userMetadataService.getMetadata).mockResolvedValue({ + key: 'notification_settings', + value: { + comments: false, + replies: false, + mentions: true, + yourUploads: true, + otherUploads: false, + statusUpdates: true, + }, + }) + + const res = await app.request('/teams/t1/notifications/settings') + + expect(res.status).toBe(200) + const json = await res.json() + expect(json.comments).toBe(false) + expect(json.yourUploads).toBe(true) + }) + + it('POST /teams/:teamId/notifications/settings - saves settings', async () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + vi.mocked(userMetadataService.upsertMetadata).mockResolvedValue(undefined as any) + + const res = await app.request('/teams/t1/notifications/settings', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + comments: false, + replies: false, + mentions: true, + yourUploads: true, + otherUploads: false, + statusUpdates: true, + }), + }) + + expect(res.status).toBe(200) + const json = await res.json() + expect(json.success).toBe(true) + + expect(userMetadataService.upsertMetadata).toHaveBeenCalledWith( + 'user1', + 't1', + 'notification_settings', + { + comments: false, + replies: false, + mentions: true, + yourUploads: true, + otherUploads: false, + statusUpdates: true, + }, + ) + }) }) diff --git a/src/api/notification.ts b/src/api/notification.ts index 24763575..795f5bb6 100644 --- a/src/api/notification.ts +++ b/src/api/notification.ts @@ -5,7 +5,9 @@ import { authzService, Permission, ResourceType } from '@/services/authz/authz' import { listNotificationsRequestSchema, markNotificationReadRequestSchema, + notificationSettingsSchema, } from '@/dtos/notification' +import { userMetadataService } from '@/services/user-metadata/user-metadata' import type { Prisma } from '@/generated/prisma/client' type User = Prisma.UserGetPayload> @@ -62,5 +64,50 @@ const route = new Hono<{ Variables: { user: User } }>() return new Response(null, { status: 204 }) }, ) + .get('/teams/:teamId/notifications/settings', async (c) => { + const teamId = c.req.param('teamId') + const user = c.get('user') + + await authzService.hasPermission({ + user, + permission: Permission.Read, + type: ResourceType.Team, + id: teamId, + }) + + const metadata = await userMetadataService.getMetadata(user.id, teamId, 'notification_settings') + const settings = metadata + ? metadata.value + : { + comments: true, + replies: true, + mentions: true, + yourUploads: false, + otherUploads: true, + statusUpdates: true, + } + + return c.json(settings) + }) + .post( + '/teams/:teamId/notifications/settings', + zValidator('json', notificationSettingsSchema), + async (c) => { + const teamId = c.req.param('teamId') + const user = c.get('user') + const req = c.req.valid('json') + + await authzService.hasPermission({ + user, + permission: Permission.Read, + type: ResourceType.Team, + id: teamId, + }) + + await userMetadataService.upsertMetadata(user.id, teamId, 'notification_settings', req) + + return c.json({ success: true }) + }, + ) export default route 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/notification.ts b/src/dtos/notification.ts index bf116b17..0dde3bd9 100644 --- a/src/dtos/notification.ts +++ b/src/dtos/notification.ts @@ -73,3 +73,14 @@ export interface ListNotificationParams { after?: string pageSize?: number } + +export const notificationSettingsSchema = z.object({ + comments: z.boolean().default(true), + replies: z.boolean().default(true), + mentions: z.boolean().default(true), + yourUploads: z.boolean().default(false), + otherUploads: z.boolean().default(true), + statusUpdates: z.boolean().default(true), +}) + +export type NotificationSettings = z.infer diff --git a/src/dtos/project.ts b/src/dtos/project.ts index 5ae98fbd..8f434cc9 100644 --- a/src/dtos/project.ts +++ b/src/dtos/project.ts @@ -4,7 +4,7 @@ import { paginationPageInfoSchema, paginationParamsSchema } from './pagination' export const createProjectRequestSchema = z.object({ name: z.string(), coverImageKey: z.string().optional(), - enableNotification: z.boolean().default(false), + enableNotification: z.boolean().default(true), }) export type CreateProjectRequest = z.infer 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 308b2f6e..3cffd566 100644 --- a/src/services/notification/notification.test.ts +++ b/src/services/notification/notification.test.ts @@ -3,6 +3,7 @@ import { prisma } from '@/db' import { setupTestDbHooks } from '@/db-test-hooks' import { NotificationType } from '@/generated/prisma/client' import { notificationService } from './notification' +import { userMetadataService } from '@/services/user-metadata/user-metadata' describe('NotificationService', () => { setupTestDbHooks() @@ -247,4 +248,118 @@ describe('NotificationService', () => { const p2Notification = res.data.find((n) => n.id === '002') expect(p2Notification).toBeUndefined() }) + + it('Respects user metadata notification settings', async () => { + const tm = await prisma.team.create({ data: { name: 'Team 1' } }) + const u1 = await prisma.user.create({ + data: { name: 'u1', email: `u1-${Date.now()}@example.com`, password: 'p' }, + }) + const u2 = await prisma.user.create({ + data: { name: 'u2', email: `u2-${Date.now()}@example.com`, password: 'p' }, + }) + await prisma.teamMember.create({ + data: { teamId: tm.id, userId: u1.id, role: 'owner' }, + }) + + // Create comments, replies, mentions, uploads, etc. + const commentNotif = await prisma.notification.create({ + data: { id: '001', teamId: tm.id, type: NotificationType.comment_created }, + }) + const replyNotif = await prisma.notification.create({ + data: { id: '002', teamId: tm.id, type: NotificationType.reply_created, userId: u1.id }, + }) + const uploadNotifOther = await prisma.notification.create({ + data: { + id: '003', + teamId: tm.id, + type: NotificationType.successful_file_uploaded, + creatorId: u2.id, + }, + }) + const uploadNotifSelf = await prisma.notification.create({ + data: { + id: '004', + teamId: tm.id, + type: NotificationType.successful_file_uploaded, + creatorId: u1.id, + }, + }) + + const svc = notificationService + + // Default settings: comments=true, replies=true, mentions=true, yourUploads=false, otherUploads=true + const resDefault = await svc.list(tm.id, u1.id, {}) + expect(resDefault.data.some((n) => n.id === commentNotif.id)).toBe(true) + expect(resDefault.data.some((n) => n.id === replyNotif.id)).toBe(true) + expect(resDefault.data.some((n) => n.id === uploadNotifOther.id)).toBe(true) + expect(resDefault.data.some((n) => n.id === uploadNotifSelf.id)).toBe(false) // yourUploads is false by default + + // Disable comments and replies, but enable yourUploads + await userMetadataService.upsertMetadata(u1.id, tm.id, 'notification_settings', { + comments: false, + replies: false, + mentions: true, + yourUploads: true, + otherUploads: false, + statusUpdates: true, + }) + + const resCustom = await svc.list(tm.id, u1.id, {}) + expect(resCustom.data.some((n) => n.id === commentNotif.id)).toBe(false) + expect(resCustom.data.some((n) => n.id === replyNotif.id)).toBe(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 + }) + + 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 e96e0bec..4a78afb4 100644 --- a/src/services/notification/notification.ts +++ b/src/services/notification/notification.ts @@ -5,10 +5,12 @@ import { NotificationInfo, CreateNotificationRequest, ListNotificationParams, + NotificationSettings, } from '@/dtos/notification' import { paginateQuery, PaginatedData } from '@/services/pagination' import '@/prisma-json-types' import { s3Service } from '@/services/s3/s3' +import { userMetadataService } from '@/services/user-metadata/user-metadata' const mentionRegex = /<@([^>]+)>/g @@ -95,6 +97,142 @@ export class NotificationService { } } + private async getListWhere( + teamId: string, + userId: string, + teamMember: Prisma.TeamMemberGetPayload<{ include: { lastReadNotification: true } }>, + unreadOnly: boolean, + ): Promise { + // Permission Filtering based on Scope + let projectFilter: string[] = [] + if (teamMember.scope === 'project') { + const pms = await prisma.projectMember.findMany({ + where: { teamMemberId: teamMember.id }, + include: { project: true }, + }) + projectFilter = pms.filter((pm) => pm.project).map((pm) => pm.projectId) + } + + // Load notification settings + const settingsMeta = await userMetadataService.getMetadata( + userId, + teamId, + 'notification_settings', + ) + const settings: NotificationSettings = settingsMeta + ? (settingsMeta.value as NotificationSettings) + : { + comments: true, + replies: true, + mentions: true, + yourUploads: false, + otherUploads: true, + statusUpdates: true, + } + + const typeConditions: Prisma.NotificationWhereInput[] = [] + + // 1. Comments + if (settings.comments) { + typeConditions.push({ type: NotificationType.comment_created, userId: null }) + } + + // 2. Replies + if (settings.replies) { + typeConditions.push({ type: NotificationType.reply_created, userId: userId }) + typeConditions.push({ type: NotificationType.reply_created, userId: null }) + } + + // 3. Mentions + if (settings.mentions) { + typeConditions.push({ type: NotificationType.mention, userId: userId }) + } + + // 4. Uploads + if (settings.yourUploads && settings.otherUploads) { + typeConditions.push({ type: NotificationType.successful_file_uploaded }) + } else if (settings.yourUploads) { + typeConditions.push({ type: NotificationType.successful_file_uploaded, creatorId: userId }) + } else if (settings.otherUploads) { + typeConditions.push({ + type: NotificationType.successful_file_uploaded, + creatorId: { not: userId }, + }) + } + + // 5. Status Updates + if (settings.statusUpdates) { + typeConditions.push({ type: NotificationType.metadata_field_updated_status }) + } + + // 6. Always include team/project join notifications + typeConditions.push({ type: NotificationType.new_user_join_team }) + typeConditions.push({ type: NotificationType.new_user_join_project }) + + const where: Prisma.NotificationWhereInput = { + teamId, + OR: typeConditions, + AND: [ + { + OR: [ + ...(settings.yourUploads + ? [{ type: NotificationType.successful_file_uploaded, creatorId: userId }] + : []), + { creatorId: null }, + { creatorId: { not: userId } }, + ], + }, + ], + } + + if (teamMember.scope === 'project') { + // Must be AND applied after the general rules + const currentAnd = Array.isArray(where.AND) ? where.AND : where.AND ? [where.AND] : [] + where.AND = [ + ...currentAnd, + { + OR: [ + { type: NotificationType.mention }, // Always allow mentions (targeted) + { projectId: { in: projectFilter } }, // Only show notifications for projects user is member of + ], + }, + ] as Prisma.NotificationWhereInput[] + } + + 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] : [] + where.AND = [ + ...currentAnd, + { id: { gt: teamMember.lastReadNotification.id } }, + ] 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, @@ -117,48 +255,7 @@ export class NotificationService { throw new Error('failed to get team member') } - // Permission Filtering based on Scope - let projectFilter: string[] = [] - if (teamMember.scope === 'project') { - const pms = await prisma.projectMember.findMany({ - where: { teamMemberId: teamMember.id }, - include: { project: true }, - }) - projectFilter = pms.filter((pm) => pm.project).map((pm) => pm.projectId) - } - - const where: Prisma.NotificationWhereInput = { - teamId, - OR: [ - { type: { not: NotificationType.mention } }, - { type: NotificationType.mention, userId: userId }, - ], - AND: [{ OR: [{ creatorId: null }, { creatorId: { not: userId } }] }], - } - - if (teamMember.scope === 'project') { - // Must be AND applied after the general rules - const currentAnd = Array.isArray(where.AND) ? where.AND : where.AND ? [where.AND] : [] - where.AND = [ - ...currentAnd, - { - OR: [ - { type: NotificationType.mention }, // Always allow mentions (targeted) - { projectId: { in: projectFilter } }, // Only show notifications for projects user is member of - ], - }, - ] as Prisma.NotificationWhereInput[] - } - - if (params.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] : [] - where.AND = [ - ...currentAnd, - { id: { gt: teamMember.lastReadNotification.id } }, - ] as Prisma.NotificationWhereInput[] - } + const where = await this.getListWhere(teamId, userId, teamMember, !!params.unreadOnly) return paginateQuery( async (skip, take) => { diff --git a/src/services/project/project.ts b/src/services/project/project.ts index 00be962f..1ce9128a 100644 --- a/src/services/project/project.ts +++ b/src/services/project/project.ts @@ -32,7 +32,7 @@ export class ProjectService { data: { name: req.name, teamId: req.teamId, - enableNotification: req.enableNotification || false, + enableNotification: req.enableNotification ?? true, coverImageKey: req.coverImageKey, }, }) @@ -304,7 +304,7 @@ export class ProjectService { const pi: ProjectInfo = { id: p.id, name: p.name, - enableNotification: p.enableNotification || false, + enableNotification: p.enableNotification ?? true, coverImageKey: p.coverImageKey || undefined, updatedAt: p.updatedAt, } 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} { const { teamId } = useTeamContextStore() @@ -55,6 +56,14 @@ export const NotificationList = () => { [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, @@ -75,14 +84,31 @@ export const NotificationList = () => { if (notifications.length > 0 && teamId) { const topId = notifications[0].id if (topId) { - await markReadMutation.mutateAsync({ - teamId, - notificationId: topId, + // Optimistically clear the unread count in React Query cache instantly + queryClient.setQueryData(['teams', teamId, 'me'], (oldData: GetMeResponse | undefined) => { + if (!oldData) return oldData + return { + ...oldData, + unreadNotificationCount: 0, + } }) - // Invalidate queries + + try { + await markReadMutation.mutateAsync({ + teamId, + notificationId: topId, + }) + } catch (err) { + console.error('Failed to mark all as read:', err) + } + + // Invalidate queries to trigger sync refetches queryClient.invalidateQueries({ queryKey: ['notifications', teamId], }) + queryClient.invalidateQueries({ + queryKey: ['teams', teamId, 'me'], + }) // Refetch to update UI state immediately refetch() } diff --git a/src/ui/components/settings/NotificationSettings.tsx b/src/ui/components/settings/NotificationSettings.tsx new file mode 100644 index 00000000..c1af0148 --- /dev/null +++ b/src/ui/components/settings/NotificationSettings.tsx @@ -0,0 +1,227 @@ +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' +import { client } from '@/ui/api/client' +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card' +import { Switch } from '@/ui/components/ui/switch' +import { + Loader2, + MessageSquare, + MessageCircle, + AtSign, + UploadCloud, + Activity, + Bell, +} from 'lucide-react' +import { toast } from 'sonner' +import type { NotificationSettings as Settings } from '@/dtos/notification' + +export function NotificationSettings({ teamId }: { teamId: string }) { + const queryClient = useQueryClient() + + const { data: settings, isLoading } = useQuery({ + queryKey: ['teams', teamId, 'notification-settings'], + queryFn: async () => { + const res = await client.api.teams[':teamId'].notifications.settings.$get({ + param: { teamId }, + }) + if (!res.ok) throw new Error('Failed to fetch notification settings') + return (await res.json()) as Settings + }, + }) + + const { mutate: updateSettings, isPending: isUpdating } = useMutation({ + mutationFn: async (updated: Settings) => { + const res = await client.api.teams[':teamId'].notifications.settings.$post({ + param: { teamId }, + json: updated, + }) + if (!res.ok) throw new Error('Failed to update notification settings') + return await res.json() + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'notification-settings'] }) + queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'notifications'] }) + toast.success('Notification settings updated') + }, + onError: (err) => { + toast.error(err instanceof Error ? err.message : 'Failed to update notification settings') + }, + }) + + const handleToggle = (key: keyof Settings) => { + if (!settings) return + const updated = { + ...settings, + [key]: !settings[key], + } + updateSettings(updated) + } + + if (isLoading) { + return ( +
+ +
+ ) + } + + return ( +
+ {/* Comments Settings */} + + +
+ + Comments & Replies +
+ + Control notification preferences when other users comment on assets you collaborate on + or mention you. + +
+ + {/* General Comments */} +
+
+
+ +
+
+

+ General Comments +

+

+ When someone comments on an asset +

+
+
+ handleToggle('comments')} + disabled={isUpdating} + /> +
+ + {/* Comment Replies */} +
+
+
+ +
+
+

+ Comment Replies +

+

+ When someone replies to your comment +

+
+
+ handleToggle('replies')} + disabled={isUpdating} + /> +
+ + {/* Mentions */} +
+
+
+ +
+
+

@Mentions

+

+ When someone @mentions you in a comment +

+
+
+ handleToggle('mentions')} + disabled={isUpdating} + /> +
+
+
+ + {/* Assets Settings */} + + +
+ + Assets & Statuses +
+ + Manage notifications related to file uploads and metadata field status updates. + +
+ + {/* Your Uploads */} +
+
+
+ +
+
+

+ Your Uploads +

+

When you upload assets

+
+
+ handleToggle('yourUploads')} + disabled={isUpdating} + /> +
+ + {/* Other Uploads */} +
+
+
+ +
+
+

+ Other Uploads +

+

+ When other users upload assets +

+
+
+ handleToggle('otherUploads')} + disabled={isUpdating} + /> +
+ + {/* Status Updates */} +
+
+
+ +
+
+

+ Status Updates +

+

+ When someone changes an asset’s status +

+
+
+ handleToggle('statusUpdates')} + disabled={isUpdating} + /> +
+
+
+
+ ) +} 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}> { + const res = await client.api.projects[':projectId'].$put({ + param: { projectId: project.id! }, + json: { + enableNotification: !project.enableNotification, + }, + }) + if (!res.ok) throw new Error('Failed to update project notification settings') + return await res.json() + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'projects'] }) + toast.success('Project notification settings updated') + }, + onError: (err) => { + toast.error( + err instanceof Error ? err.message : 'Failed to update project notification settings', + ) + }, + }) + const handleCreateProjectClick = () => { setProjectDialogMode('create') setSelectedProject(undefined) @@ -284,6 +308,19 @@ function TeamPage() { > Project Settings + { + e.preventDefault() + toggleProjectNotificationsMutation.mutate(project) + }} + > + Notification + + handleDeleteProjectClick(project)} diff --git a/src/ui/routes/teams/$teamId/settings.tsx b/src/ui/routes/teams/$teamId/settings.tsx index 26837ea2..7609c707 100644 --- a/src/ui/routes/teams/$teamId/settings.tsx +++ b/src/ui/routes/teams/$teamId/settings.tsx @@ -4,15 +4,23 @@ import { AgentsSettings } from '@/ui/components/settings/AgentsSettings' import { ProvidersSettings } from '@/ui/components/settings/ProvidersSettings' import { SandboxSettings } from '@/ui/components/settings/SandboxSettings' import { SkillsConfigCard } from '@/ui/components/settings/SkillsConfigCard' +import { NotificationSettings } from '@/ui/components/settings/NotificationSettings' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card' import { Switch } from '@/ui/components/ui/switch' import { cn } from '@/ui/lib/utils' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { createFileRoute } from '@tanstack/react-router' -import { Bot, Cpu, Film, Loader2, Puzzle, Shield, User } from 'lucide-react' +import { Bot, Cpu, Film, Loader2, Puzzle, Shield, User, Bell } from 'lucide-react' import { useState } from 'react' -type SettingsTab = 'general' | 'transcode' | 'skills' | 'providers' | 'agents' | 'sandbox' +type SettingsTab = + | 'general' + | 'transcode' + | 'skills' + | 'providers' + | 'agents' + | 'sandbox' + | 'notifications' function TeamSettingsPage() { const { teamId } = Route.useParams() @@ -145,6 +153,22 @@ function TeamSettingsPage() { )} + +
AI
@@ -227,6 +251,7 @@ function TeamSettingsPage() { {activeTab === 'providers' && 'AI Providers'} {activeTab === 'agents' && 'AI Agents'} {activeTab === 'sandbox' && 'Agent Sandbox Settings'} + {activeTab === 'notifications' && 'Notification Settings'}

{activeTab === 'general' && 'View your personal information and team role.'} @@ -238,6 +263,8 @@ function TeamSettingsPage() { {activeTab === 'agents' && 'Manage AI agents and their personalities.'} {activeTab === 'sandbox' && 'Configure security and network restrictions for the AI agent.'} + {activeTab === 'notifications' && + 'Configure your personal notification preferences for this team.'}

@@ -422,6 +449,8 @@ function TeamSettingsPage() { )} + + {activeTab === 'notifications' && }