From 2ed9c6ddcc88046d2d00748bbab8e6544c745772 Mon Sep 17 00:00:00 2001 From: Apoorv Mishra Date: Tue, 21 Nov 2023 22:07:43 +0530 Subject: [PATCH] feat: functionally working first pass --- app/components/Input.tsx | 2 +- app/components/InputSelect.tsx | 3 +- .../Sidebar/components/SharedWithMe.tsx | 8 +- app/menus/MemberMenu.tsx | 2 +- app/models/Document.ts | 25 +++ app/models/User.ts | 12 ++ app/models/UserMembership.ts | 12 ++ .../InputMemberPermissionSelect.tsx | 41 ++-- .../components/MemberListItem.tsx | 6 +- app/scenes/Document/components/Combobox.tsx | 179 +++++++++++++++++ .../Document/components/InviteTeamMembers.tsx | 186 ++++++++++++++++++ .../Document/components/SharePopover.tsx | 5 + app/stores/UserMembershipsStore.ts | 58 +++++- server/models/Document.ts | 5 +- server/models/UserPermission.ts | 9 - server/presenters/documentMembership.ts | 2 +- server/routes/api/documents/documents.test.ts | 88 ++++++++- server/routes/api/documents/documents.ts | 61 ++++++ server/routes/api/documents/schema.ts | 12 ++ server/routes/api/userMemberships/schema.ts | 17 +- .../userMemberships/userMemberships.test.ts | 9 +- .../api/userMemberships/userMemberships.ts | 14 +- server/utils/indexing.ts | 2 +- server/validation.ts | 5 - shared/i18n/locales/en_US/translation.json | 3 + 25 files changed, 704 insertions(+), 62 deletions(-) create mode 100644 app/scenes/Document/components/Combobox.tsx create mode 100644 app/scenes/Document/components/InviteTeamMembers.tsx diff --git a/app/components/Input.tsx b/app/components/Input.tsx index 2cd3264f7e..63d2f9eb1d 100644 --- a/app/components/Input.tsx +++ b/app/components/Input.tsx @@ -56,7 +56,7 @@ const RealInput = styled.input<{ hasIcon?: boolean }>` `}; `; -const Wrapper = styled.div<{ +export const Wrapper = styled.div<{ flex?: boolean; short?: boolean; minHeight?: number; diff --git a/app/components/InputSelect.tsx b/app/components/InputSelect.tsx index 5e73300c87..b6c98cb1ed 100644 --- a/app/components/InputSelect.tsx +++ b/app/components/InputSelect.tsx @@ -44,6 +44,7 @@ export type Props = { options: Option[]; note?: React.ReactNode; onChange?: (value: string | null) => void; + isAdminPermissionSupported?: boolean; }; interface InnerProps extends React.HTMLAttributes { @@ -267,7 +268,7 @@ const Wrapper = styled.label<{ short?: boolean }>` max-width: ${(props) => (props.short ? "350px" : "100%")}; `; -const Positioner = styled(Position)` +export const Positioner = styled(Position)` &.focus-visible { ${StyledSelectOption} { &[aria-selected="true"] { diff --git a/app/components/Sidebar/components/SharedWithMe.tsx b/app/components/Sidebar/components/SharedWithMe.tsx index 60fe4a29e1..b06a513c8e 100644 --- a/app/components/Sidebar/components/SharedWithMe.tsx +++ b/app/components/Sidebar/components/SharedWithMe.tsx @@ -7,6 +7,7 @@ import { toast } from "sonner"; import UserMembership from "~/models/UserMembership"; import DelayedMount from "~/components/DelayedMount"; import Flex from "~/components/Flex"; +import useCurrentUser from "~/hooks/useCurrentUser"; import usePaginatedRequest from "~/hooks/usePaginatedRequest"; import useStores from "~/hooks/useStores"; import DropCursor from "./DropCursor"; @@ -22,6 +23,7 @@ const STARRED_PAGINATION_LIMIT = 10; function SharedWithMe() { const { userMemberships } = useStores(); const { t } = useTranslation(); + const user = useCurrentUser(); const { loading, next, end, error, page } = usePaginatedRequest(userMemberships.fetchPage, { @@ -33,7 +35,7 @@ function SharedWithMe() { accept: "userMembership", drop: async (item: { userMembership: UserMembership }) => { void item.userMembership.save({ - index: fractionalIndex(null, userMemberships.orderedData[0].index), + index: fractionalIndex(null, user.memberships[0].index), }); }, collect: (monitor) => ({ @@ -46,7 +48,7 @@ function SharedWithMe() { toast.error(t("Could not load shared documents")); } - if (!userMemberships.orderedData.length) { + if (!user.memberships.length) { return null; } @@ -62,7 +64,7 @@ function SharedWithMe() { position="top" /> )} - {userMemberships.orderedData + {user.memberships .slice(0, page * STARRED_PAGINATION_LIMIT) .map((membership) => ( m.documentId === this.id) + .map((m) => m.user); + + const uninvitedUsers = teamMembers.filter( + (teamMember) => + !documentUsers.map((u) => u?.id).includes(teamMember.id) && + teamMember.id !== this.store.rootStore.auth.user?.id + ); + + return uninvitedUsers; + } + + @computed + get users(): User[] { + const documentUsers = this.store.rootStore.userMemberships.orderedData + .filter((m) => m.documentId === this.id) + .map((m) => m.user); + + return documentUsers; + } + @computed get isArchived(): boolean { return !!this.archivedAt; diff --git a/app/models/User.ts b/app/models/User.ts index 2344d9ea6c..b5b0f1125f 100644 --- a/app/models/User.ts +++ b/app/models/User.ts @@ -12,6 +12,8 @@ import { } from "@shared/types"; import type { NotificationSettings } from "@shared/types"; import { client } from "~/utils/ApiClient"; +import Document from "./Document"; +import UserMembership from "./UserMembership"; import ParanoidModel from "./base/ParanoidModel"; import Field from "./decorators/Field"; @@ -109,6 +111,12 @@ class User extends ParanoidModel { ); } + @computed + get memberships(): UserMembership[] { + const memberships = this.store.rootStore.userMemberships.orderedData; + return memberships.filter((m) => m.userId === this.id); + } + /** * Returns the current preference for the given notification event type taking * into account the default system value. @@ -172,6 +180,10 @@ class User extends ParanoidModel { [key]: value, }; } + + getMembership(document: Document) { + return this.memberships.find((m) => m.documentId === document.id); + } } export default User; diff --git a/app/models/UserMembership.ts b/app/models/UserMembership.ts index 2c4e157c23..a85ba3f386 100644 --- a/app/models/UserMembership.ts +++ b/app/models/UserMembership.ts @@ -1,6 +1,8 @@ import { observable } from "mobx"; +import { DocumentPermission } from "@shared/types"; import type UserMembershipsStore from "~/stores/UserMembershipsStore"; import Document from "./Document"; +import User from "./User"; import Model from "./base/Model"; import Field from "./decorators/Field"; import Relation from "./decorators/Relation"; @@ -13,6 +15,9 @@ class UserMembership extends Model { @observable index: string; + @observable + permission: DocumentPermission; + /** The document ID comprising of membership. */ documentId?: string; @@ -20,6 +25,13 @@ class UserMembership extends Model { @Relation(() => Document, { onDelete: "cascade" }) document?: Document; + /** The user ID of user who is a member */ + userId: string; + + /** The user who is a member */ + @Relation(() => User, { onDelete: "cascade" }) + user: User; + store: UserMembershipsStore; /** diff --git a/app/scenes/CollectionPermissions/components/InputMemberPermissionSelect.tsx b/app/scenes/CollectionPermissions/components/InputMemberPermissionSelect.tsx index 25c82d60b3..679627a759 100644 --- a/app/scenes/CollectionPermissions/components/InputMemberPermissionSelect.tsx +++ b/app/scenes/CollectionPermissions/components/InputMemberPermissionSelect.tsx @@ -13,20 +13,33 @@ export default function InputMemberPermissionSelect( return ( { + actions = [ + RPCAction.List, + RPCAction.Create, + RPCAction.Delete, + RPCAction.Update, + ]; + constructor(rootStore: RootStore) { super(rootStore, UserMembership); } @@ -34,6 +41,55 @@ export default class UserMembershipsStore extends Store { } }; + @action + fetchDocumentMemberships = async ( + params: (PaginationParams & { id: string }) | undefined + ): Promise => { + this.isFetching = true; + + try { + const res = await client.post(`/documents.memberships`, params); + invariant(res?.data, "Data not available"); + + let response: UserMembership[] = []; + runInAction(`MembershipsStore#fetchDocmentMemberships`, () => { + res.data.users.forEach(this.rootStore.users.add); + response = res.data.memberships.map(this.add); + this.isLoaded = true; + }); + response[PAGINATION_SYMBOL] = res.pagination; + return response; + } finally { + this.isFetching = false; + } + }; + + @action + async create({ documentId, userId, permission }: Partial) { + const res = await client.post("/documents.add_user", { + id: documentId, + userId, + permission, + }); + invariant(res?.data, "Membership data should be available"); + res.data.users.forEach(this.rootStore.users.add); + + const memberships = res.data.memberships.map(this.add); + return memberships[0]; + } + + @action + async delete({ documentId, userId }: UserMembership) { + await client.post("/documents.remove_user", { + id: documentId, + userId, + }); + const membership = this.orderedData.find( + (v) => v.documentId === documentId && v.userId === userId + ); + this.remove(membership?.id as string); + } + @computed get orderedData(): UserMembership[] { const memberships = Array.from(this.data.values()); diff --git a/server/models/Document.ts b/server/models/Document.ts index 8866076bc5..c661db894f 100644 --- a/server/models/Document.ts +++ b/server/models/Document.ts @@ -206,8 +206,7 @@ type AdditionalFindOptions = { return { include: [ { - model: UserPermission, - as: "memberships", + association: "memberships", where: { userId, documentId: { @@ -536,7 +535,7 @@ class Document extends ParanoidModel { @Column(DataType.UUID) collectionId?: string | null; - @HasMany(() => UserPermission, "documentId") + @HasMany(() => UserPermission) memberships: UserPermission[]; @HasMany(() => Revision) diff --git a/server/models/UserPermission.ts b/server/models/UserPermission.ts index 0d90d7316b..6c231b1c1c 100644 --- a/server/models/UserPermission.ts +++ b/server/models/UserPermission.ts @@ -9,7 +9,6 @@ import { DataType, Scopes, AllowNull, - PrimaryKey, } from "sequelize-typescript"; import { CollectionPermission, DocumentPermission } from "@shared/types"; import Collection from "./Collection"; @@ -56,7 +55,6 @@ class UserPermission extends IdModel { @BelongsTo(() => Collection, "collectionId") collection?: Collection | null; - @PrimaryKey @ForeignKey(() => Collection) @Column(DataType.UUID) collectionId?: string | null; @@ -64,7 +62,6 @@ class UserPermission extends IdModel { @BelongsTo(() => Document, "documentId") document?: Document | null; - @PrimaryKey @ForeignKey(() => Document) @Column(DataType.UUID) documentId?: string | null; @@ -72,7 +69,6 @@ class UserPermission extends IdModel { @BelongsTo(() => User, "userId") user: User; - @PrimaryKey @ForeignKey(() => User) @Column(DataType.UUID) userId: string; @@ -83,11 +79,6 @@ class UserPermission extends IdModel { @ForeignKey(() => User) @Column(DataType.UUID) createdById: string; - - // methods - getId() { - return `${this.userId}-${this.documentId}`; - } } export default UserPermission; diff --git a/server/presenters/documentMembership.ts b/server/presenters/documentMembership.ts index 86b62d73b4..0454acdbd4 100644 --- a/server/presenters/documentMembership.ts +++ b/server/presenters/documentMembership.ts @@ -13,7 +13,7 @@ export default function presentDocumentMembership( membership: UserPermission ): DocumentMembership { return { - id: membership.getId(), + id: membership.id, userId: membership.userId, documentId: membership.documentId, permission: membership.permission, diff --git a/server/routes/api/documents/documents.test.ts b/server/routes/api/documents/documents.test.ts index 9e472108e1..a768180054 100644 --- a/server/routes/api/documents/documents.test.ts +++ b/server/routes/api/documents/documents.test.ts @@ -1,5 +1,5 @@ import { addMinutes, subDays } from "date-fns"; -import { CollectionPermission } from "@shared/types"; +import { CollectionPermission, DocumentPermission } from "@shared/types"; import { Document, View, @@ -4102,3 +4102,89 @@ describe("#documents.remove_user", () => { expect(users.length).toEqual(0); }); }); + +describe("#documents.memberships", () => { + it("should return members in document", async () => { + const user = await buildUser(); + const document = await buildDocument({ + teamId: user.teamId, + userId: user.id, + }); + const members = await Promise.all([ + buildUser({ teamId: user.teamId }), + buildUser({ teamId: user.teamId }), + ]); + await Promise.all([ + server.post("/api/documents.add_user", { + body: { + token: user.getJwtToken(), + id: document.id, + userId: members[0].id, + }, + }), + server.post("/api/documents.add_user", { + body: { + token: user.getJwtToken(), + id: document.id, + userId: members[1].id, + }, + }), + ]); + const res = await server.post("/api/documents.memberships", { + body: { + token: user.getJwtToken(), + id: document.id, + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.data.users.length).toEqual(2); + expect(body.data.users.map((u: User) => u.id).includes(members[0].id)).toBe( + true + ); + expect(body.data.users.map((u: User) => u.id).includes(members[1].id)).toBe( + true + ); + }); + + it("should allow filtering members in document by permission", async () => { + const user = await buildUser(); + const document = await buildDocument({ + teamId: user.teamId, + userId: user.id, + }); + const members = await Promise.all([ + buildUser({ teamId: user.teamId }), + buildUser({ teamId: user.teamId }), + ]); + await Promise.all([ + server.post("/api/documents.add_user", { + body: { + token: user.getJwtToken(), + id: document.id, + userId: members[0].id, + permission: DocumentPermission.ReadWrite, + }, + }), + server.post("/api/documents.add_user", { + body: { + token: user.getJwtToken(), + id: document.id, + userId: members[1].id, + permission: DocumentPermission.Read, + }, + }), + ]); + const res = await server.post("/api/documents.memberships", { + body: { + token: user.getJwtToken(), + id: document.id, + permission: DocumentPermission.Read, + }, + }); + const body = await res.json(); + expect(res.status).toEqual(200); + expect(body.data.users.length).toEqual(1); + expect(body.data.users[0].id).toEqual(members[1].id); + }); +}); diff --git a/server/routes/api/documents/documents.ts b/server/routes/api/documents/documents.ts index d508aff2b5..2953cd76ef 100644 --- a/server/routes/api/documents/documents.ts +++ b/server/routes/api/documents/documents.ts @@ -1556,4 +1556,65 @@ router.post( } ); +router.post( + "documents.memberships", + auth(), + pagination(), + validate(T.DocumentsMembershipsSchema), + async (ctx: APIContext) => { + const { id, query, permission } = ctx.input.body; + const { user: actor } = ctx.state.auth; + + const document = await Document.findByPk(id, { userId: actor.id }); + authorize(actor, "update", document); + + let where: WhereOptions = { + documentId: id, + }; + let userWhere; + + if (query) { + userWhere = { + name: { + [Op.iLike]: `%${query}%`, + }, + }; + } + + if (permission) { + where = { ...where, permission }; + } + + const options = { + where, + include: [ + { + model: User, + as: "user", + where: userWhere, + required: true, + }, + ], + }; + + const [total, memberships] = await Promise.all([ + UserPermission.count(options), + UserPermission.findAll({ + ...options, + order: [["createdAt", "DESC"]], + offset: ctx.state.pagination.offset, + limit: ctx.state.pagination.limit, + }), + ]); + + ctx.body = { + pagination: { ...ctx.state.pagination, total }, + data: { + memberships: memberships.map(presentDocumentMembership), + users: memberships.map((membership) => presentUser(membership.user)), + }, + }; + } +); + export default router; diff --git a/server/routes/api/documents/schema.ts b/server/routes/api/documents/schema.ts index 996b0881de..9cebdf6b38 100644 --- a/server/routes/api/documents/schema.ts +++ b/server/routes/api/documents/schema.ts @@ -388,3 +388,15 @@ export const DocumentsSharedWithUserSchema = BaseSchema.extend({ export type DocumentsSharedWithUserReq = z.infer< typeof DocumentsSharedWithUserSchema >; + +export const DocumentsMembershipsSchema = BaseSchema.extend({ + body: z.object({ + id: z.string().uuid(), + query: z.string().optional(), + permission: z.nativeEnum(DocumentPermission).optional(), + }), +}); + +export type DocumentsMembershipsReq = z.infer< + typeof DocumentsMembershipsSchema +>; diff --git a/server/routes/api/userMemberships/schema.ts b/server/routes/api/userMemberships/schema.ts index 45a5a71c6d..9eba472cbf 100644 --- a/server/routes/api/userMemberships/schema.ts +++ b/server/routes/api/userMemberships/schema.ts @@ -1,5 +1,5 @@ import { z } from "zod"; -import { ValidateIndex, ValidateMembershipId } from "@server/validation"; +import { ValidateIndex } from "@server/validation"; import BaseSchema from "../BaseSchema"; export const UserMembershipsListSchema = BaseSchema; @@ -7,17 +7,12 @@ export const UserMembershipsListSchema = BaseSchema; export type UserMembershipsListReq = z.infer; export const UserMembershipsUpdateSchema = BaseSchema.extend({ - body: z - .object({ - id: z.string().regex(ValidateMembershipId.regex), - index: z.string().regex(ValidateIndex.regex, { - message: ValidateIndex.message, - }), - }) - .transform((val) => { - const match = val.id.match(ValidateMembershipId.regex)!; - return { ...val, userId: match[1], documentId: match[2] }; + body: z.object({ + id: z.string().uuid(), + index: z.string().regex(ValidateIndex.regex, { + message: ValidateIndex.message, }), + }), }); export type UserMembershipsUpdateReq = z.infer< diff --git a/server/routes/api/userMemberships/userMemberships.test.ts b/server/routes/api/userMemberships/userMemberships.test.ts index 398dbe568d..9c9afa37cf 100644 --- a/server/routes/api/userMemberships/userMemberships.test.ts +++ b/server/routes/api/userMemberships/userMemberships.test.ts @@ -63,19 +63,24 @@ describe("#userMemberships.update", () => { const member = await buildUser({ teamId: user.teamId, }); - await server.post("/api/documents.add_user", { + const resp = await server.post("/api/documents.add_user", { body: { token: user.getJwtToken(), id: document.id, userId: member.id, }, }); + const respBody = await resp.json(); + expect(respBody.data).not.toBeFalsy(); + expect(respBody.data.memberships).not.toBeFalsy(); + expect(respBody.data.memberships).toHaveLength(1); + const users = await document.$get("users"); expect(users.length).toEqual(1); const res = await server.post("/api/userMemberships.update", { body: { token: member.getJwtToken(), - id: `${member.id}-${document.id}`, + id: respBody.data.memberships[0].id, index: "V", }, }); diff --git a/server/routes/api/userMemberships/userMemberships.ts b/server/routes/api/userMemberships/userMemberships.ts index 02c47cfb10..30750c58f5 100644 --- a/server/routes/api/userMemberships/userMemberships.ts +++ b/server/routes/api/userMemberships/userMemberships.ts @@ -48,12 +48,15 @@ router.post( if (nullIndex !== -1) { const indexedPermissions = await userPermissionIndexing(user.id); permissions.forEach((permission) => { - permission.index = indexedPermissions[permission.getId()]; + permission.index = indexedPermissions[permission.id]; }); } const documentIds = permissions.map((p) => p.documentId); - const documents = await Document.defaultScopeWithUser(user.id).findAll({ + const documents = await Document.scope([ + "withDrafts", + { method: ["withMembership", user.id] }, + ]).findAll({ where: { id: documentIds, }, @@ -80,14 +83,11 @@ router.post( validate(T.UserMembershipsUpdateSchema), transaction(), async (ctx: APIContext) => { - const { userId, documentId, index } = ctx.input.body; + const { id, index } = ctx.input.body; const { transaction } = ctx.state; const { user } = ctx.state.auth; - const membership = await UserPermission.findOne({ - where: { userId, documentId }, - transaction, - }); + const membership = await UserPermission.findByPk(id, { transaction }); authorize(user, "update", membership); membership.index = index; diff --git a/server/utils/indexing.ts b/server/utils/indexing.ts index d02c215a20..ae2d119b8f 100644 --- a/server/utils/indexing.ts +++ b/server/utils/indexing.ts @@ -121,7 +121,7 @@ export async function userPermissionIndexing( const indexedPermissions = {}; sortable.forEach((permission) => { - indexedPermissions[permission.getId()] = permission.index; + indexedPermissions[permission.id] = permission.index; }); return indexedPermissions; } diff --git a/server/validation.ts b/server/validation.ts index c2f12372f3..097bf1281d 100644 --- a/server/validation.ts +++ b/server/validation.ts @@ -250,8 +250,3 @@ export class ValidateColor { export class ValidateIcon { public static maxLength = 50; } - -export class ValidateMembershipId { - public static regex = - /^([0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12})\b-([0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12})$/; -} diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json index 5c0f4cd68a..1b5993b261 100644 --- a/shared/i18n/locales/en_US/translation.json +++ b/shared/i18n/locales/en_US/translation.json @@ -552,6 +552,9 @@ "Viewed {{ count }} times by {{ teamMembers }} people_plural": "Viewed {{ count }} times by {{ teamMembers }} people", "Viewer insights": "Viewer insights", "As an admin you can manage if team members can see who has viewed this document": "As an admin you can manage if team members can see who has viewed this document", + "{{ userName }} was removed from the document": "{{ userName }} was removed from the document", + "Invite team members": "Invite team members", + "In this project": "In this project", "Sorry, the last change could not be persisted – please reload the page": "Sorry, the last change could not be persisted – please reload the page", "This template will be permanently deleted in <2> unless restored.": "This template will be permanently deleted in <2> unless restored.", "This document will be permanently deleted in <2> unless restored.": "This document will be permanently deleted in <2> unless restored.",