⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
fix: respect inbox filters in bulk notification actions (#487)
I'm Groot 🌳169bf240292e
diff --git a/apps/api/src/modules/notifications/__tests__/integration/notifications.test.ts b/apps/api/src/modules/notifications/__tests__/integration/notifications.test.tsindex 647d44eb..a9bf38e1 100644--- a/apps/api/src/modules/notifications/__tests__/integration/notifications.test.ts+++ b/apps/api/src/modules/notifications/__tests__/integration/notifications.test.ts@@ -43,6 +43,85 @@ function createIssue(client: Api, columnId: number, patch: Record<string, unknow}describe('notifications', () => {+ it('bulk read and delete keep notifications outside the active type filter', async () => {+ const { owner, columnId, doneColumnId } = await setup();+ const member = await addMember(owner);+ const issue = (await createIssue(owner.api, columnId, { assigneeUserId: member.userId })).data!;+ const client = owner.api.issues({ issueId: issue.id });+ await client.comments.post({ body: 'Please review' } as never);+ await client.patch({ description: `@${member.username} review this` });+ await client.patch({ columnId: doneColumnId });++ const before = (await member.api.notifications.get({ query: {} })).data!.items;+ expect(before.map((item) => item.type).sort()).toEqual([+ 'assigned',+ 'commented',+ 'mentioned',+ 'state_changed',+ ]);+ const read = await member.api.notifications['read-all'].post({+ types: ['state_changed'],+ includeSnoozed: false,+ });+ expect(read.status).toBe(200);+ expect(read.data!.count).toBe(1);+ const afterRead = (await member.api.notifications.get({ query: {} })).data!.items;+ expect(afterRead.filter((item) => item.readAt != null).map((item) => item.type)).toEqual([+ 'state_changed',+ ]);+ expect((await member.api.notifications['read-all'].post()).data!.count).toBe(3);+ const deleted = await member.api.notifications.delete(undefined, {+ query: { scope: 'read-completed', types: 'state_changed', includeSnoozed: 'false' },+ });+ expect(deleted.data!.count).toBe(1);+ const remaining = (await member.api.notifications.get({ query: {} })).data!.items;+ expect(remaining.map((item) => item.type).sort()).toEqual([+ 'assigned',+ 'commented',+ 'mentioned',+ ]);+ expect(remaining.every((item) => item.readAt != null)).toBe(true);+ });++ it('bulk actions respect actor and snooze filters', async () => {+ const { owner, columnId } = await setup();+ const member = await addMember(owner);+ const other = await addMember(owner);+ const issue = (await createIssue(owner.api, columnId, { assigneeUserId: member.userId })).data!;+ await other.api.issues({ issueId: issue.id }).comments.post({ body: 'Other actor' } as never);+ await owner.api.issues({ issueId: issue.id }).comments.post({ body: 'Owner actor' } as never);+ const items = (await member.api.notifications.get({ query: {} })).data!.items;+ const snoozed = items.find((item) => item.type === 'assigned')!;+ await member.api.notifications({ id: snoozed.id }).snooze.post({+ until: new Date(Date.now() + 86_400_000).toISOString(),+ });+ const read = await member.api.notifications['read-all'].post({+ from: owner.userId,+ includeSnoozed: false,+ });+ expect(read.data!.count).toBe(1);+ const deleted = await member.api.notifications.delete(undefined, {+ query: { scope: 'all', from: owner.userId, includeSnoozed: 'false' },+ });+ expect(deleted.data!.count).toBe(1);+ const remaining = (await member.api.notifications.get({ query: { includeSnoozed: 'true' } }))+ .data!.items;+ expect(remaining).toHaveLength(2);+ expect(remaining.every((item) => item.readAt == null)).toBe(true);+ expect(remaining.some((item) => item.id === snoozed.id)).toBe(true);+ });++ it('rejects an unknown bulk delete type without deleting notifications', async () => {+ const { owner, columnId } = await setup();+ const member = await addMember(owner);+ await createIssue(owner.api, columnId, { assigneeUserId: member.userId });+ const deleted = await member.api.notifications.delete(undefined, {+ query: { scope: 'all', types: 'unknown' },+ });+ expect(deleted.status).toBe(400);+ expect((await member.api.notifications.get({ query: {} })).data!.items).toHaveLength(1);+ });+beforeEach(async () => {await resetDb();});diff --git a/apps/api/src/modules/notifications/index.ts b/apps/api/src/modules/notifications/index.tsindex 1e54cecd..c5689012 100644--- a/apps/api/src/modules/notifications/index.ts+++ b/apps/api/src/modules/notifications/index.ts@@ -94,7 +94,12 @@ export const notificationRoutes = new Elysia({'/notifications/read-all',async ({ user, body }) => {const userId = requireUser(user).id;- const count = await markAllRead(userId, body?.projectId ?? undefined);+ const count = await markAllRead(userId, body?.projectId, {+ types: body?.types,+ fromUserId: body?.from,+ includeRead: body?.includeRead,+ includeSnoozed: body?.includeSnoozed ?? true,+ });return { count };},{@@ -110,12 +115,24 @@ export const notificationRoutes = new Elysia({const userId = requireUser(user).id;const scope = (query.scope ?? 'read') as DeleteScope;const projectId = query.projectId ? Number(query.projectId) : undefined;- const count = await deleteNotifications(userId, scope, projectId);+ let types: NotificationType[] | undefined;+ if (query.types != null) {+ const supplied = query.types.split(',');+ if (supplied.some((value) => !(NOTIFICATION_TYPES as readonly string[]).includes(value)))+ throw new HttpError(400, 'Invalid notification type');+ types = supplied as NotificationType[];+ }+ const count = await deleteNotifications(userId, scope, projectId, {+ types,+ fromUserId: query.from,+ includeRead: query.includeRead !== 'false',+ includeSnoozed: query.includeSnoozed !== 'false',+ });return { count };},{query: deleteNotificationsQuery,- response: { 200: AffectedCountResponse, ...errors(401) },+ response: { 200: AffectedCountResponse, ...errors(400, 401) },detail: { summary: 'Delete inbox notifications' },},)diff --git a/apps/api/src/modules/notifications/model.ts b/apps/api/src/modules/notifications/model.tsindex ec3b6f5f..fc2b0118 100644--- a/apps/api/src/modules/notifications/model.ts+++ b/apps/api/src/modules/notifications/model.ts@@ -45,7 +45,25 @@ export const unreadCountQuery = t.Object({projectId: t.Optional(t.String({ description: 'Scope the count to one project.' })),});-export const markAllReadBody = t.Optional(t.Object({ projectId: t.Optional(t.Number()) }));+export const markAllReadBody = t.Optional(+ t.Object({+ projectId: t.Optional(t.Number()),+ types: t.Optional(+ t.Array(+ t.Union([+ t.Literal('assigned'),+ t.Literal('mentioned'),+ t.Literal('commented'),+ t.Literal('state_changed'),+ ]),+ { minItems: 1 },+ ),+ ),+ from: t.Optional(t.String()),+ includeRead: t.Optional(t.Boolean()),+ includeSnoozed: t.Optional(t.Boolean()),+ }),+);export const deleteNotificationsQuery = t.Object({scope: t.Optional(@@ -54,6 +72,10 @@ export const deleteNotificationsQuery = t.Object({}),),projectId: t.Optional(t.String({ description: 'Scope the delete to one project.' })),+ types: t.Optional(t.String()),+ from: t.Optional(t.String()),+ includeRead: t.Optional(t.String()),+ includeSnoozed: t.Optional(t.String()),});export const setNotificationReadBody = t.Optional(t.Object({ read: t.Optional(t.Boolean()) }));diff --git a/apps/api/src/modules/notifications/service.ts b/apps/api/src/modules/notifications/service.tsindex 60f655e4..28d3b2f8 100644--- a/apps/api/src/modules/notifications/service.ts+++ b/apps/api/src/modules/notifications/service.ts@@ -262,6 +262,17 @@ export interface NotificationFilters {includeSnoozed?: boolean;}+function notificationConditions(userId: string, f: NotificationFilters) {+ const conds = [eq(notification.userId, userId)];+ if (f.types && f.types.length) conds.push(inArray(notification.type, f.types));+ if (f.fromUserId) conds.push(eq(notification.actorUserId, f.fromUserId));+ if (f.projectId != null) conds.push(eq(notification.projectId, f.projectId));+ if (f.includeRead === false) conds.push(isNull(notification.readAt));+ if (!f.includeSnoozed)+ conds.push(or(isNull(notification.snoozedUntil), lt(notification.snoozedUntil, sql`now()`))!);+ return conds;+}+function mapRow(r: {id: number;type: string;@@ -313,13 +324,7 @@ export async function listNotifications(const limit = Math.min(Math.max(opts.limit ?? 30, 1), 100);const before = opts.before ?? null;const f = opts.filters ?? {};- const conds = [eq(notification.userId, userId)];- if (f.types && f.types.length) conds.push(inArray(notification.type, f.types));- if (f.fromUserId) conds.push(eq(notification.actorUserId, f.fromUserId));- if (f.projectId != null) conds.push(eq(notification.projectId, f.projectId));- if (f.includeRead === false) conds.push(isNull(notification.readAt));- if (!f.includeSnoozed)- conds.push(or(isNull(notification.snoozedUntil), lt(notification.snoozedUntil, sql`now()`))!);+ const conds = notificationConditions(userId, f);if (before)conds.push(sql`(${notification.createdAt}, ${notification.id}) < (${before.ts}::timestamptz, ${before.id}::integer)`,@@ -401,11 +406,15 @@ export async function setNotificationRead(return rows.length > 0;}-// Marks every unread notification of the user read, optionally scoped to a project.+// Marks the user's matching unread notifications read.// Returns how many were updated.-export async function markAllRead(userId: string, projectId?: number): Promise<number> {- const conds = [eq(notification.userId, userId), isNull(notification.readAt)];- if (projectId != null) conds.push(eq(notification.projectId, projectId));+export async function markAllRead(+ userId: string,+ projectId?: number,+ filters: NotificationFilters = { includeSnoozed: true },+): Promise<number> {+ const conds = notificationConditions(userId, { ...filters, projectId });+ conds.push(isNull(notification.readAt));const rows = await db.update(notification).set({ readAt: sql`now()` })@@ -441,16 +450,15 @@ export async function deleteNotification(userId: string, id: number): Promise<boexport type DeleteScope = 'all' | 'read' | 'read-completed';-// Bulk-deletes the user's notifications by scope: all, all read, or all read whose-// issue is in a completed or canceled column. Scoped to one project when projectId-// is given (the per-project inbox). Returns how many were deleted.+// Bulk-deletes matching notifications: all, read, or read on completed/canceled issues.+// Returns how many were deleted.export async function deleteNotifications(userId: string,scope: DeleteScope,projectId?: number,+ filters: NotificationFilters = { includeSnoozed: true },): Promise<number> {- const conds = [eq(notification.userId, userId)];- if (projectId != null) conds.push(eq(notification.projectId, projectId));+ const conds = notificationConditions(userId, { ...filters, projectId });if (scope === 'read' || scope === 'read-completed')conds.push(sql`${notification.readAt} is not null`);if (scope === 'read-completed') {diff --git a/apps/web/src/features/inbox/components/InboxView.tsx b/apps/web/src/features/inbox/components/InboxView.tsxindex 26c17c4c..f2cf25de 100644--- a/apps/web/src/features/inbox/components/InboxView.tsx+++ b/apps/web/src/features/inbox/components/InboxView.tsx@@ -69,9 +69,11 @@ export default function InboxView({ project }: { project: ProjectDetail }) {unread={unreadQuery.data ?? 0}filters={filters}onFiltersChange={changeFilters}- onMarkAllRead={() => markAllRead.mutate()}- onDeleteRead={() => deleteNotifications.mutate('read')}- onDeleteReadCompleted={() => deleteNotifications.mutate('read-completed')}+ onMarkAllRead={() => markAllRead.mutate(filters)}+ onDeleteRead={() => deleteNotifications.mutate({ scope: 'read', filters })}+ onDeleteReadCompleted={() =>+ deleteNotifications.mutate({ scope: 'read-completed', filters })+ }/><InboxListitems={items}diff --git a/apps/web/src/features/inbox/services/notifications.service.ts b/apps/web/src/features/inbox/services/notifications.service.tsindex 6b59af3e..20c65429 100644--- a/apps/web/src/features/inbox/services/notifications.service.ts+++ b/apps/web/src/features/inbox/services/notifications.service.ts@@ -47,7 +47,7 @@ export function useSetNotificationRead(projectKey: string) {export function useMarkAllRead(projectKey: string, projectId: number) {const invalidate = useInvalidateInbox(projectKey);return useMutation({- mutationFn: () => markAllNotificationsRead(projectId),+ mutationFn: (filters: NotificationFilters) => markAllNotificationsRead(projectId, filters),onSuccess: invalidate,});}@@ -72,7 +72,13 @@ export function useDeleteNotification(projectKey: string) {export function useDeleteNotifications(projectKey: string, projectId: number) {const invalidate = useInvalidateInbox(projectKey);return useMutation({- mutationFn: (scope: NotificationDeleteScope) => deleteNotifications(scope, projectId),+ mutationFn: ({+ scope,+ filters,+ }: {+ scope: NotificationDeleteScope;+ filters: NotificationFilters;+ }) => deleteNotifications(scope, projectId, filters),onSuccess: invalidate,});}diff --git a/apps/web/src/lib/api/endpoints/notifications.ts b/apps/web/src/lib/api/endpoints/notifications.tsindex e73a679e..8614eec3 100644--- a/apps/web/src/lib/api/endpoints/notifications.ts+++ b/apps/web/src/lib/api/endpoints/notifications.ts@@ -80,16 +80,28 @@ export const snoozeNotification = (id: number, until: string | null) =>body: JSON.stringify({ until }),});-export const markAllNotificationsRead = (projectId: number) =>+export const markAllNotificationsRead = (projectId: number, filters: NotificationFilters) =>request<{ count: number }>(`/notifications/read-all`, {method: 'POST',- body: JSON.stringify({ projectId }),+ body: JSON.stringify({+ projectId,+ ...filters,+ includeSnoozed: filters.includeSnoozed ?? false,+ }),});export const deleteNotification = (id: number) =>request<void>(`/notifications/${id}`, { method: 'DELETE' });-export const deleteNotifications = (scope: NotificationDeleteScope, projectId: number) =>- request<{ count: number }>(`/notifications?scope=${scope}&projectId=${projectId}`, {- method: 'DELETE',- });+export const deleteNotifications = (+ scope: NotificationDeleteScope,+ projectId: number,+ filters: NotificationFilters,+) => {+ const q = new URLSearchParams({ scope, projectId: String(projectId) });+ if (filters.types?.length) q.set('types', filters.types.join(','));+ if (filters.from) q.set('from', filters.from);+ if (filters.includeRead === false) q.set('includeRead', 'false');+ q.set('includeSnoozed', String(filters.includeSnoozed ?? false));+ return request<{ count: number }>(`/notifications?${q.toString()}`, { method: 'DELETE' });+};