import { Op } from "sequelize"; import { uniq } from "es-toolkit/compat"; import { NotificationEventType, DocumentPermission, CollectionPermission, UserRole, } from "@shared/types"; import Logger from "@server/logging/Logger"; import { Document, Notification, User, Collection, AccessRequest, } from "@server/models"; import { AccessRequestStatus } from "@server/models/AccessRequest"; import { can } from "@server/policies"; import type { AccessRequestEvent } from "@server/types"; import { BaseTask, TaskPriority } from "./base/BaseTask"; /** * Notification task that sends notifications to users who can manage a document * when someone requests access to it. */ export default class DocumentAccessRequestNotificationsTask extends BaseTask { public async perform(event: AccessRequestEvent) { const document = await Document.findByPk(event.documentId); if (!document) { Logger.debug( "task", `Document not found for access request notification`, { documentId: event.documentId, } ); return; } const accessRequest = await AccessRequest.findByPk(event.modelId); if ( !accessRequest || accessRequest.status !== AccessRequestStatus.Pending ) { Logger.debug("task", `Access request not pending for notification`, { documentId: event.documentId, accessRequestId: event.modelId, }); return; } const recipients = await this.findDocumentAdmins(document); Logger.debug("task", "Access request notification recipients", { documentId: event.documentId, accessRequestId: event.modelId, recipientIds: recipients.map((r) => r.id), }); for (const recipient of recipients) { if (recipient.id === event.actorId) { Logger.debug("task", "Skipping recipient: is the actor", { documentId: event.documentId, recipientId: recipient.id, }); continue; } if ( !recipient.subscribedToEventType( NotificationEventType.RequestDocumentAccess ) ) { Logger.debug("task", "Skipping recipient: not subscribed", { documentId: event.documentId, recipientId: recipient.id, }); continue; } await Notification.create({ event: NotificationEventType.RequestDocumentAccess, userId: recipient.id, actorId: event.actorId, teamId: event.teamId, documentId: event.documentId, accessRequestId: accessRequest.id, }); } } /** * Find users who can manage the document, with tiered fallback: * document owners → document admins → collection admins → workspace admins. * The first tier with any users is used. * * @param document - the document to find managers for. * @returns list of users who can manage the document. */ private async findDocumentAdmins(document: Document): Promise { const owners = await this.findDocumentOwners(document); if (owners.length > 0) { return owners; } const documentManagerIds = await Document.membershipUserIds( document.id, DocumentPermission.Admin ); if (documentManagerIds.length > 0) { return this.loadUsers(documentManagerIds, document.teamId); } if (document.collectionId) { const collection = await Collection.findOne({ attributes: ["id", "ownerId"], where: { id: document.collectionId }, }); // Only the owner manages a personal collection, never the workspace admins. if (collection?.ownerId) { return this.loadUsers([collection.ownerId], document.teamId); } const collectionManagerIds = await Collection.membershipUserIds( document.collectionId, CollectionPermission.Admin ); if (collectionManagerIds.length > 0) { return this.loadUsers(collectionManagerIds, document.teamId); } } Logger.debug("task", "Falling back to workspace admins", { documentId: document.id, collectionId: document.collectionId, }); return User.findAll({ where: { teamId: document.teamId, role: UserRole.Admin, suspendedAt: null, }, }); } /** * Find the owners of the document, and of its collection, that are able to * approve access requests. * * @param document the document to find owners for. * @returns the owners that can manage access to the document. */ private async findDocumentOwners(document: Document): Promise { const collection = document.collectionId ? await Collection.unscoped().findByPk(document.collectionId, { attributes: ["id", "ownerIds"], }) : null; const ownerIds = uniq([ ...(collection?.ownerIds ?? []), ...(document.ownerIds ?? []), ]); if (!ownerIds.length) { return []; } const owners = await User.scope("withTeam").findAll({ where: { id: { [Op.in]: ownerIds }, teamId: document.teamId, suspendedAt: null, }, }); const managers = await Promise.all( owners.map(async (owner) => { const ownerDocument = await Document.findByPk(document.id, { userId: owner.id, }); return can(owner, "manageUsers", ownerDocument) ? owner : undefined; }) ); return managers.filter((owner): owner is User => !!owner); } private async loadUsers(ids: string[], teamId: string): Promise { return User.findAll({ where: { id: { [Op.in]: uniq(ids) }, teamId, suspendedAt: null, }, }); } public get options() { return { priority: TaskPriority.Background, }; } }