diff --git a/app/components/Notifications/NotificationListItem.tsx b/app/components/Notifications/NotificationListItem.tsx
index 657a224843..7e6b09d534 100644
--- a/app/components/Notifications/NotificationListItem.tsx
+++ b/app/components/Notifications/NotificationListItem.tsx
@@ -80,7 +80,7 @@ function NotificationListItem({ notification, onNavigate }: Props) {
{notification.actor?.name ?? t("Unknown")}
{" "}
{notification.eventText(t)}{" "}
- {notification.subject}
+ {notification.subject(t)}
{" "}
diff --git a/app/models/Notification.ts b/app/models/Notification.ts
index c7524934e8..6fd4c29f49 100644
--- a/app/models/Notification.ts
+++ b/app/models/Notification.ts
@@ -11,6 +11,7 @@ import {
import Collection from "./Collection";
import Comment from "./Comment";
import Document from "./Document";
+import Group from "./Group";
import User from "./User";
import Model from "./base/Model";
import Field from "./decorators/Field";
@@ -64,6 +65,8 @@ class Notification extends Model {
NotificationEventType.Onboarding,
NotificationEventType.Features,
NotificationEventType.ExportCompleted,
+ NotificationEventType.AddUserToGroup,
+ NotificationEventType.RemoveUserFromGroup,
],
};
@@ -121,6 +124,17 @@ class Notification extends Model {
@Relation(() => Collection, { onDelete: "cascade" })
collection?: Collection;
+ /**
+ * The group ID that the notification is associated with.
+ */
+ groupId?: string;
+
+ /**
+ * The group that the notification is associated with.
+ */
+ @Relation(() => Group, { onDelete: "cascade" })
+ group?: Group;
+
commentId?: string;
/**
@@ -213,6 +227,10 @@ class Notification extends Model {
return t("shared");
case NotificationEventType.AddUserToCollection:
return t("invited you to");
+ case NotificationEventType.AddUserToGroup:
+ return t("added you to the group");
+ case NotificationEventType.RemoveUserFromGroup:
+ return t("removed you from the group");
case NotificationEventType.RequestDocumentAccess:
if (this.accessRequestStatus === "approved") {
return t("was granted access to");
@@ -227,19 +245,23 @@ class Notification extends Model {
}
/**
- * Returns the subject of the notification. This is the title of the associated
- * document.
+ * Returns translated text for the subject of the notification. This is the
+ * name of the associated document, collection, or group.
*
- * @returns The subject
+ * @param t - The translation function.
+ * @returns The subject.
*/
- get subject() {
+ subject(t: TFunction): string {
if (this.documentId) {
- return this.document?.title ?? "a document";
+ return this.document?.title ?? t("a document");
}
if (this.collectionId) {
- return this.collection?.name ?? "a collection";
+ return this.collection?.name ?? t("a collection");
}
- return "Unknown";
+ if (this.groupId) {
+ return this.group?.name ?? t("a group");
+ }
+ return t("Unknown");
}
/**
@@ -288,6 +310,12 @@ class Notification extends Model {
case NotificationEventType.ExportCompleted: {
return settingsPath("export");
}
+ case NotificationEventType.AddUserToGroup:
+ case NotificationEventType.RemoveUserFromGroup: {
+ return this.groupId
+ ? settingsPath("groups", this.groupId, "members")
+ : "";
+ }
default:
this.event satisfies never;
return;
diff --git a/app/scenes/Settings/Notifications.tsx b/app/scenes/Settings/Notifications.tsx
index 65ed71a83b..0ffabbe29f 100644
--- a/app/scenes/Settings/Notifications.tsx
+++ b/app/scenes/Settings/Notifications.tsx
@@ -123,6 +123,14 @@ function Notifications() {
"Receive a notification when you are given access to a collection"
),
},
+ {
+ event: NotificationEventType.AddUserToGroup,
+ icon: ,
+ title: t("Group membership"),
+ description: t(
+ "Receive a notification when you are added to or removed from a group"
+ ),
+ },
{
event: NotificationEventType.ExportCompleted,
icon: ,
diff --git a/server/commands/groupsSyncer.test.ts b/server/commands/groupsSyncer.test.ts
index 92ee361602..cf74c8b229 100644
--- a/server/commands/groupsSyncer.test.ts
+++ b/server/commands/groupsSyncer.test.ts
@@ -1,6 +1,7 @@
import { createContext } from "@server/context";
import {
AuthenticationProvider,
+ Event,
ExternalGroup,
Group,
GroupUser,
@@ -267,6 +268,16 @@ describe("groupsSyncer", () => {
where: { groupId: designGroup!.id, userId: user.id },
});
expect(membership).toBeNull();
+
+ const events = await Event.findAll({
+ where: { teamId: user.teamId, modelId: designGroup!.id },
+ order: [["createdAt", "ASC"]],
+ });
+ expect(
+ events
+ .filter((event) => event.name !== "groups.create")
+ .map((event) => event.name)
+ ).toEqual(["groups.add_user", "groups.remove_user"]);
});
it("should not create duplicate memberships on re-sync", async () => {
diff --git a/server/commands/groupsSyncer.ts b/server/commands/groupsSyncer.ts
index 69c60f6fe6..1c249406f7 100644
--- a/server/commands/groupsSyncer.ts
+++ b/server/commands/groupsSyncer.ts
@@ -124,10 +124,14 @@ async function groupsSyncer(
}
// Add user to group if not already a member
- const [, membershipCreated] = await GroupUser.findOrCreateWithCtx(ctx, {
- where: { groupId: externalGroup.groupId!, userId: user.id },
- defaults: { createdById: user.id },
- });
+ const [, membershipCreated] = await GroupUser.findOrCreateWithCtx(
+ ctx,
+ {
+ where: { groupId: externalGroup.groupId!, userId: user.id },
+ defaults: { createdById: user.id },
+ },
+ { name: "add_user" }
+ );
if (membershipCreated) {
result.membershipsAdded++;
@@ -170,7 +174,7 @@ async function groupsSyncer(
for (const stale of staleExternalGroups) {
const membership = stale.group?.groupUsers?.[0];
if (membership) {
- await membership.destroyWithCtx(ctx);
+ await membership.destroyWithCtx(ctx, { name: "remove_user" });
result.membershipsRemoved++;
}
}
diff --git a/server/models/Notification.ts b/server/models/Notification.ts
index 513125a2b9..ce07248493 100644
--- a/server/models/Notification.ts
+++ b/server/models/Notification.ts
@@ -94,6 +94,10 @@ let baseDomain;
association: "accessRequest",
required: false,
},
+ {
+ association: "group",
+ required: false,
+ },
],
}))
@Table({
diff --git a/server/presenters/notification.ts b/server/presenters/notification.ts
index 69d6e4e2d8..8de78b8152 100644
--- a/server/presenters/notification.ts
+++ b/server/presenters/notification.ts
@@ -1,5 +1,6 @@
import type { Notification } from "@server/models";
import type { APIContext } from "@server/types";
+import presentGroup from "./group";
import presentUser from "./user";
import { presentComment, presentDocument } from ".";
@@ -28,6 +29,10 @@ export default async function presentNotification(
: undefined,
revisionId: notification.revisionId,
collectionId: notification.collectionId,
+ groupId: notification.groupId,
+ group: notification.group
+ ? await presentGroup(notification.group)
+ : undefined,
data: notification.data,
};
}
diff --git a/server/queues/processors/NotificationsProcessor.test.ts b/server/queues/processors/NotificationsProcessor.test.ts
new file mode 100644
index 0000000000..bc06ceee0c
--- /dev/null
+++ b/server/queues/processors/NotificationsProcessor.test.ts
@@ -0,0 +1,52 @@
+import { buildGroup, buildUser } from "@server/test/factories";
+import GroupUserNotificationsTask from "../tasks/GroupUserNotificationsTask";
+import NotificationsProcessor from "./NotificationsProcessor";
+
+const ip = "127.0.0.1";
+
+describe("NotificationsProcessor", () => {
+ describe("group membership", () => {
+ let schedule: ReturnType;
+
+ beforeEach(() => {
+ schedule = vi.spyOn(GroupUserNotificationsTask.prototype, "schedule");
+ });
+
+ afterEach(() => {
+ schedule.mockRestore();
+ });
+
+ it("should schedule a notification when another user changes membership", async () => {
+ const actor = await buildUser();
+ const user = await buildUser({ teamId: actor.teamId });
+ const group = await buildGroup({ teamId: actor.teamId });
+
+ await new NotificationsProcessor().perform({
+ name: "groups.add_user",
+ userId: user.id,
+ modelId: group.id,
+ teamId: actor.teamId,
+ actorId: actor.id,
+ ip,
+ });
+
+ expect(schedule).toHaveBeenCalledTimes(1);
+ });
+
+ it("should not schedule a notification when the user changes their own membership", async () => {
+ const user = await buildUser();
+ const group = await buildGroup({ teamId: user.teamId });
+
+ await new NotificationsProcessor().perform({
+ name: "groups.add_user",
+ userId: user.id,
+ modelId: group.id,
+ teamId: user.teamId,
+ actorId: user.id,
+ ip,
+ });
+
+ expect(schedule).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/server/queues/processors/NotificationsProcessor.ts b/server/queues/processors/NotificationsProcessor.ts
index ed2af6c05b..e6f881f8ea 100644
--- a/server/queues/processors/NotificationsProcessor.ts
+++ b/server/queues/processors/NotificationsProcessor.ts
@@ -9,6 +9,7 @@ import type {
DocumentUserEvent,
DocumentGroupEvent,
CommentReactionEvent,
+ GroupUserEvent,
} from "@server/types";
import CollectionAddUserNotificationsTask from "../tasks/CollectionAddUserNotificationsTask";
import CollectionCreatedNotificationsTask from "../tasks/CollectionCreatedNotificationsTask";
@@ -20,6 +21,7 @@ import DocumentAccessRequestNotificationsTask from "../tasks/DocumentAccessReque
import DocumentAddGroupNotificationsTask from "../tasks/DocumentAddGroupNotificationsTask";
import DocumentAddUserNotificationsTask from "../tasks/DocumentAddUserNotificationsTask";
import DocumentPublishedNotificationsTask from "../tasks/DocumentPublishedNotificationsTask";
+import GroupUserNotificationsTask from "../tasks/GroupUserNotificationsTask";
import RevisionCreatedNotificationsTask from "../tasks/RevisionCreatedNotificationsTask";
import ShareSubscriptionNotificationsTask from "../tasks/ShareSubscriptionNotificationsTask";
import BaseProcessor from "./BaseProcessor";
@@ -33,6 +35,8 @@ export default class NotificationsProcessor extends BaseProcessor {
"revisions.create",
"collections.create",
"collections.add_user",
+ "groups.add_user",
+ "groups.remove_user",
"comments.create",
"comments.update",
"comments.add_reaction",
@@ -55,6 +59,9 @@ export default class NotificationsProcessor extends BaseProcessor {
return this.collectionCreated(event);
case "collections.add_user":
return this.collectionAddUser(event);
+ case "groups.add_user":
+ case "groups.remove_user":
+ return this.groupUserChanged(event);
case "comments.create":
return this.commentCreated(event);
case "comments.update":
@@ -119,6 +126,14 @@ export default class NotificationsProcessor extends BaseProcessor {
await new CollectionAddUserNotificationsTask().schedule(event);
}
+ async groupUserChanged(event: GroupUserEvent) {
+ if (event.userId === event.actorId) {
+ return;
+ }
+
+ await new GroupUserNotificationsTask().schedule(event);
+ }
+
async commentCreated(event: CommentEvent) {
await new CommentCreatedNotificationsTask().schedule(event);
}
diff --git a/server/queues/tasks/GroupUserNotificationsTask.test.ts b/server/queues/tasks/GroupUserNotificationsTask.test.ts
new file mode 100644
index 0000000000..4c854f4513
--- /dev/null
+++ b/server/queues/tasks/GroupUserNotificationsTask.test.ts
@@ -0,0 +1,234 @@
+import { NotificationEventType } from "@shared/types";
+import { Event, Notification } from "@server/models";
+import { buildGroup, buildUser } from "@server/test/factories";
+import GroupUserNotificationsTask from "./GroupUserNotificationsTask";
+
+const ip = "127.0.0.1";
+
+describe("GroupUserNotificationsTask", () => {
+ it("should notify a user added to a group", async () => {
+ const actor = await buildUser();
+ const user = await buildUser({ teamId: actor.teamId });
+ const group = await buildGroup({ teamId: actor.teamId });
+
+ await new GroupUserNotificationsTask().perform({
+ name: "groups.add_user",
+ userId: user.id,
+ modelId: group.id,
+ teamId: actor.teamId,
+ actorId: actor.id,
+ ip,
+ });
+
+ const notifications = await Notification.findAll({
+ where: { userId: user.id },
+ });
+ expect(notifications).toHaveLength(1);
+ expect(notifications[0].event).toEqual(
+ NotificationEventType.AddUserToGroup
+ );
+ expect(notifications[0].groupId).toEqual(group.id);
+ expect(notifications[0].actorId).toEqual(actor.id);
+ });
+
+ it("should notify a user removed from a group", async () => {
+ const actor = await buildUser();
+ const user = await buildUser({ teamId: actor.teamId });
+ const group = await buildGroup({ teamId: actor.teamId });
+
+ await new GroupUserNotificationsTask().perform({
+ name: "groups.remove_user",
+ userId: user.id,
+ modelId: group.id,
+ teamId: actor.teamId,
+ actorId: actor.id,
+ ip,
+ });
+
+ const notifications = await Notification.findAll({
+ where: { userId: user.id },
+ });
+ expect(notifications).toHaveLength(1);
+ expect(notifications[0].event).toEqual(
+ NotificationEventType.RemoveUserFromGroup
+ );
+ expect(notifications[0].groupId).toEqual(group.id);
+ });
+
+ it("should delete an unread removal notification when the user is added back", async () => {
+ const actor = await buildUser();
+ const user = await buildUser({ teamId: actor.teamId });
+ const group = await buildGroup({ teamId: actor.teamId });
+ const props = {
+ userId: user.id,
+ modelId: group.id,
+ teamId: actor.teamId,
+ actorId: actor.id,
+ ip,
+ };
+
+ await new GroupUserNotificationsTask().perform({
+ ...props,
+ name: "groups.remove_user",
+ });
+ const removal = await Notification.findOne({
+ where: { userId: user.id },
+ });
+ await new GroupUserNotificationsTask().perform({
+ ...props,
+ name: "groups.add_user",
+ });
+
+ const notifications = await Notification.findAll({
+ where: { userId: user.id },
+ });
+ expect(notifications.map((n) => n.event)).toEqual([
+ NotificationEventType.AddUserToGroup,
+ ]);
+
+ const deleteEvent = await Event.findOne({
+ where: { name: "notifications.delete", modelId: removal!.id },
+ });
+ expect(deleteEvent?.userId).toEqual(user.id);
+ });
+
+ it("should delete an unread addition notification when the user is removed", async () => {
+ const actor = await buildUser();
+ const user = await buildUser({ teamId: actor.teamId });
+ const group = await buildGroup({ teamId: actor.teamId });
+ const props = {
+ userId: user.id,
+ modelId: group.id,
+ teamId: actor.teamId,
+ actorId: actor.id,
+ ip,
+ };
+
+ await new GroupUserNotificationsTask().perform({
+ ...props,
+ name: "groups.add_user",
+ });
+ await new GroupUserNotificationsTask().perform({
+ ...props,
+ name: "groups.remove_user",
+ });
+
+ const notifications = await Notification.findAll({
+ where: { userId: user.id },
+ });
+ expect(notifications.map((n) => n.event)).toEqual([
+ NotificationEventType.RemoveUserFromGroup,
+ ]);
+ });
+
+ it("should keep a read notification when the membership changes again", async () => {
+ const actor = await buildUser();
+ const user = await buildUser({ teamId: actor.teamId });
+ const group = await buildGroup({ teamId: actor.teamId });
+ const props = {
+ userId: user.id,
+ modelId: group.id,
+ teamId: actor.teamId,
+ actorId: actor.id,
+ ip,
+ };
+
+ await new GroupUserNotificationsTask().perform({
+ ...props,
+ name: "groups.add_user",
+ });
+ await Notification.update(
+ { viewedAt: new Date() },
+ { where: { userId: user.id } }
+ );
+ await new GroupUserNotificationsTask().perform({
+ ...props,
+ name: "groups.remove_user",
+ });
+
+ const count = await Notification.count({ where: { userId: user.id } });
+ expect(count).toEqual(2);
+ });
+
+ it("should not notify a user when the group is externally managed", async () => {
+ const actor = await buildUser();
+ const user = await buildUser({ teamId: actor.teamId });
+ const group = await buildGroup({
+ teamId: actor.teamId,
+ externalId: "ext-1",
+ });
+
+ await new GroupUserNotificationsTask().perform({
+ name: "groups.add_user",
+ userId: user.id,
+ modelId: group.id,
+ teamId: actor.teamId,
+ actorId: actor.id,
+ ip,
+ });
+
+ const count = await Notification.count({ where: { userId: user.id } });
+ expect(count).toEqual(0);
+ });
+
+ it("should not notify a removed user that is unsubscribed", async () => {
+ const actor = await buildUser();
+ const user = await buildUser({ teamId: actor.teamId });
+ user.setNotificationEventType(NotificationEventType.AddUserToGroup, false);
+ await user.save();
+ const group = await buildGroup({ teamId: actor.teamId });
+
+ await new GroupUserNotificationsTask().perform({
+ name: "groups.remove_user",
+ userId: user.id,
+ modelId: group.id,
+ teamId: actor.teamId,
+ actorId: actor.id,
+ ip,
+ });
+
+ const count = await Notification.count({ where: { userId: user.id } });
+ expect(count).toEqual(0);
+ });
+
+ it("should not notify a user that is unsubscribed", async () => {
+ const actor = await buildUser();
+ const user = await buildUser({ teamId: actor.teamId });
+ user.setNotificationEventType(NotificationEventType.AddUserToGroup, false);
+ await user.save();
+ const group = await buildGroup({ teamId: actor.teamId });
+
+ await new GroupUserNotificationsTask().perform({
+ name: "groups.add_user",
+ userId: user.id,
+ modelId: group.id,
+ teamId: actor.teamId,
+ actorId: actor.id,
+ ip,
+ });
+
+ const count = await Notification.count({ where: { userId: user.id } });
+ expect(count).toEqual(0);
+ });
+
+ it("should not notify a suspended user", async () => {
+ const actor = await buildUser();
+ const user = await buildUser({
+ teamId: actor.teamId,
+ suspendedAt: new Date(),
+ });
+ const group = await buildGroup({ teamId: actor.teamId });
+
+ await new GroupUserNotificationsTask().perform({
+ name: "groups.remove_user",
+ userId: user.id,
+ modelId: group.id,
+ teamId: actor.teamId,
+ actorId: actor.id,
+ ip,
+ });
+
+ const count = await Notification.count({ where: { userId: user.id } });
+ expect(count).toEqual(0);
+ });
+});
diff --git a/server/queues/tasks/GroupUserNotificationsTask.ts b/server/queues/tasks/GroupUserNotificationsTask.ts
new file mode 100644
index 0000000000..474ebc2a7e
--- /dev/null
+++ b/server/queues/tasks/GroupUserNotificationsTask.ts
@@ -0,0 +1,90 @@
+import { NotificationEventType } from "@shared/types";
+import { createContext } from "@server/context";
+import { Group, Notification, User } from "@server/models";
+import { sequelize } from "@server/storage/database";
+import type { GroupUserEvent } from "@server/types";
+import { BaseTask, TaskPriority } from "./base/BaseTask";
+
+/**
+ * Notifies a user when another user adds them to or removes them from a group
+ * that is not managed by an external provider.
+ */
+export default class GroupUserNotificationsTask extends BaseTask {
+ public async perform(event: GroupUserEvent) {
+ const notificationEvent =
+ GroupUserNotificationsTask.notificationEvents[event.name];
+ if (!notificationEvent) {
+ return;
+ }
+
+ await this.deleteUnreadNotifications(event);
+
+ // Additions and removals share a single preference.
+ const recipient = await User.findByPk(event.userId);
+ if (
+ !recipient ||
+ recipient.isSuspended ||
+ !recipient.subscribedToEventType(NotificationEventType.AddUserToGroup)
+ ) {
+ return;
+ }
+
+ // Memberships of externally managed groups only change through sync.
+ const group = await Group.findByPk(event.modelId);
+ if (!group || group.externalId) {
+ return;
+ }
+
+ await Notification.create({
+ event: notificationEvent,
+ userId: event.userId,
+ actorId: event.actorId,
+ teamId: event.teamId,
+ groupId: group.id,
+ });
+ }
+
+ public get options() {
+ return {
+ priority: TaskPriority.Background,
+ };
+ }
+
+ /** The notification type for each group membership event. */
+ private static notificationEvents: Record<
+ GroupUserEvent["name"],
+ NotificationEventType
+ > = {
+ "groups.add_user": NotificationEventType.AddUserToGroup,
+ "groups.remove_user": NotificationEventType.RemoveUserFromGroup,
+ };
+
+ /**
+ * Deletes the user's unread membership notifications for the group, so that
+ * only the latest change is shown.
+ *
+ * @param event The group membership event.
+ */
+ private async deleteUnreadNotifications(event: GroupUserEvent) {
+ const actor = await User.findByPk(event.actorId);
+
+ await sequelize.transaction((transaction) =>
+ Notification.destroyWithCtx(
+ createContext({
+ user: actor ?? undefined,
+ authType: event.authType,
+ ip: event.ip,
+ transaction,
+ }),
+ {
+ where: {
+ event: Object.values(GroupUserNotificationsTask.notificationEvents),
+ userId: event.userId,
+ groupId: event.modelId,
+ viewedAt: null,
+ },
+ }
+ )
+ );
+ }
+}
diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json
index fbb0ef31cf..a2f8860392 100644
--- a/shared/i18n/locales/en_US/translation.json
+++ b/shared/i18n/locales/en_US/translation.json
@@ -851,9 +851,14 @@
"reacted {{ emoji }} to your comment on": "reacted {{ emoji }} to your comment on",
"shared": "shared",
"invited you to": "invited you to",
+ "added you to the group": "added you to the group",
+ "removed you from the group": "removed you from the group",
"was granted access to": "was granted access to",
"requested access to": "requested access to",
"is requesting access to": "is requesting access to",
+ "a document": "a document",
+ "a collection": "a collection",
+ "a group": "a group",
"Choose a date": "Choose a date",
"API key created. Please copy the value now as it will not be shown again.": "API key created. Please copy the value now as it will not be shown again.",
"Scopes": "Scopes",
@@ -1460,6 +1465,8 @@
"Receive a notification when a document is shared with you": "Receive a notification when a document is shared with you",
"Invited to collection": "Invited to collection",
"Receive a notification when you are given access to a collection": "Receive a notification when you are given access to a collection",
+ "Group membership": "Group membership",
+ "Receive a notification when you are added to or removed from a group": "Receive a notification when you are added to or removed from a group",
"Export completed": "Export completed",
"Receive a notification when an export you requested has been completed": "Receive a notification when an export you requested has been completed",
"Document access requested": "Document access requested",
@@ -1618,7 +1625,6 @@
"Event": "Event",
"Timestamp": "Timestamp",
"IP": "IP",
- "a group": "a group",
"All users": "All users",
"View and edit": "View and edit",
"Sharing enabled": "Sharing enabled",
diff --git a/shared/types.ts b/shared/types.ts
index 0215fcfcb4..c531b24a7d 100644
--- a/shared/types.ts
+++ b/shared/types.ts
@@ -561,6 +561,8 @@ export enum NotificationEventType {
UpdateDocument = "documents.update",
AddUserToDocument = "documents.add_user",
AddUserToCollection = "collections.add_user",
+ AddUserToGroup = "groups.add_user",
+ RemoveUserFromGroup = "groups.remove_user",
CreateRevision = "revisions.create",
CreateCollection = "collections.create",
CreateComment = "comments.create",
@@ -614,6 +616,8 @@ export const NotificationEventDefaults: Record =
[NotificationEventType.ExportCompleted]: true,
[NotificationEventType.AddUserToDocument]: true,
[NotificationEventType.AddUserToCollection]: true,
+ [NotificationEventType.AddUserToGroup]: true,
+ [NotificationEventType.RemoveUserFromGroup]: true,
[NotificationEventType.RequestDocumentAccess]: true,
};