feat: functionally working first pass

This commit is contained in:
Apoorv Mishra committed 2023-12-27 22:47:15 +05:30
1 parent 3cc4bc8217
commit 2ed9c6ddcc
25 files changed
+704 -62

No files matched your search

+1 -1
View File
@@ -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;
+2 -1
View File
@@ -44,6 +44,7 @@ export type Props = {
options: Option[];
note?: React.ReactNode;
onChange?: (value: string | null) => void;
isAdminPermissionSupported?: boolean;
};
interface InnerProps extends React.HTMLAttributes<HTMLDivElement> {
@@ -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"] {
@@ -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<UserMembership>(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) => (
<SharedWithMeLink
+1 -1
View File
@@ -16,7 +16,7 @@ function MemberMenu({ user, onRemove }: Props) {
const { t } = useTranslation();
const currentUser = useCurrentUser();
const menu = useMenuState({
modal: true,
modal: false,
});
return (
+25
View File
@@ -226,6 +226,31 @@ export default class Document extends ParanoidModel {
);
}
@computed
get uninvitedUsers(): User[] {
const teamMembers = this.store.rootStore.users.orderedData;
const documentUsers = this.store.rootStore.userMemberships.orderedData
.filter((m) => 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;
+12
View File
@@ -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;
+12
View File
@@ -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;
/**
@@ -13,20 +13,33 @@ export default function InputMemberPermissionSelect(
return (
<Select
label={t("Permissions")}
options={[
{
label: t("View only"),
value: CollectionPermission.Read,
},
{
label: t("View and edit"),
value: CollectionPermission.ReadWrite,
},
{
label: t("Admin"),
value: CollectionPermission.Admin,
},
]}
options={
props.isAdminPermissionSupported
? [
{
label: t("View only"),
value: CollectionPermission.Read,
},
{
label: t("View and edit"),
value: CollectionPermission.ReadWrite,
},
{
label: t("Admin"),
value: CollectionPermission.Admin,
},
]
: [
{
label: t("View only"),
value: CollectionPermission.Read,
},
{
label: t("View and edit"),
value: CollectionPermission.ReadWrite,
},
]
}
ariaLabel={t("Permissions")}
labelHidden
nude
@@ -4,6 +4,7 @@ import { Trans, useTranslation } from "react-i18next";
import { CollectionPermission } from "@shared/types";
import Membership from "~/models/Membership";
import User from "~/models/User";
import UserMembership from "~/models/UserMembership";
import Avatar from "~/components/Avatar";
import Badge from "~/components/Badge";
import Button from "~/components/Button";
@@ -15,11 +16,12 @@ import InputMemberPermissionSelect from "./InputMemberPermissionSelect";
type Props = {
user: User;
membership?: Membership | undefined;
membership?: Membership | UserMembership | undefined;
canEdit: boolean;
onAdd?: () => void;
onRemove?: () => void;
onUpdate?: (permission: CollectionPermission) => void;
isAdminPermissionSupported?: boolean;
};
const MemberListItem = ({
@@ -29,6 +31,7 @@ const MemberListItem = ({
onUpdate,
onAdd,
canEdit,
isAdminPermissionSupported = true,
}: Props) => {
const { t } = useTranslation();
@@ -53,6 +56,7 @@ const MemberListItem = ({
<Flex align="center" gap={8}>
{onUpdate && (
<InputMemberPermissionSelect
isAdminPermissionSupported={isAdminPermissionSupported}
value={membership ? membership.permission : undefined}
onChange={onUpdate}
disabled={!canEdit}
+179
View File
@@ -0,0 +1,179 @@
import { observer } from "mobx-react";
import * as React from "react";
import { VisuallyHidden } from "reakit";
import {
unstable_useComboboxState as useComboboxState,
unstable_Combobox as ComboboxInput,
unstable_ComboboxPopover as ComboboxPopover,
unstable_ComboboxOption as ComboboxOption,
} from "reakit/Combobox";
import styled from "styled-components";
import breakpoint from "styled-components-breakpoint";
import { s, ellipsis } from "@shared/styles";
import { Background, Placement } from "~/components/ContextMenu";
import { MenuAnchorCSS } from "~/components/ContextMenu/MenuItem";
import { LabelText, Outline, Wrapper } from "~/components/Input";
import { Positioner } from "~/components/InputSelect";
import { undraggableOnDesktop } from "~/styles";
type Props = {
onChangeInput: (value: string) => void;
onSelectOption: (option: Record<string, any>) => void;
} & Record<any, any>;
function Combobox({
suggestions = [],
value,
label,
listLabel,
// new props
className,
short,
flex,
labelHidden,
onRequestSubmit,
onChangeInput,
onSelectOption,
margin,
children,
...rest
}: Props) {
const [focused, setFocused] = React.useState(false);
const [items, setItems] = React.useState(suggestions);
const handleBlur = () => {
setFocused(false);
};
const handleFocus = () => {
setFocused(true);
};
const handleChange = (ev: React.ChangeEvent<HTMLInputElement>) => {
onChangeInput(ev.target.value);
};
const state = useComboboxState({
gutter: 8,
values: suggestions.map((s: any) => s.value),
});
React.useEffect(() => {
setItems(suggestions.filter((s: any) => state.matches.includes(s.value)));
}, [state.matches, suggestions]);
const wrappedLabel = <LabelText>{label}</LabelText>;
return (
<>
<Wrapper className={className} short={short} flex={flex}>
<label>
{label &&
(labelHidden ? (
<VisuallyHidden>{wrappedLabel}</VisuallyHidden>
) : (
wrappedLabel
))}
<Outline focused={focused} margin={margin}>
<StyledComboboxInput
{...state}
onBlur={handleBlur}
onFocus={handleFocus}
onChange={handleChange}
type="search"
{...rest}
/>
{children}
</Outline>
</label>
</Wrapper>
<ComboboxPopover {...state} aria-label={listLabel}>
{(
props: React.HTMLAttributes<HTMLDivElement> & {
placement: Placement;
}
) => {
const topAnchor = props.style?.top === "0";
const rightAnchor = props.placement === "bottom-end";
if (!items.length) {
return null;
}
return (
<StyledPositioner {...props}>
<Background
dir="auto"
topAnchor={topAnchor}
rightAnchor={rightAnchor}
hiddenScrollbars
style={{ maxWidth: "100%" }}
>
{state.visible
? items.map((match: any) => (
<StyledComboboxOption
{...state}
value={match.value}
key={match.value}
onClick={() => onSelectOption(match)}
>
{match.value}
</StyledComboboxOption>
))
: null}
</Background>
</StyledPositioner>
);
}}
</ComboboxPopover>
</>
);
}
const StyledComboboxInput = styled(ComboboxInput)`
border: 0;
flex: 1;
padding: 8px 12px 8px;
outline: none;
background: none;
color: ${s("text")};
height: 30px;
min-width: 0;
font-size: 15px;
${ellipsis()}
${undraggableOnDesktop()}
&:disabled,
&::placeholder {
color: ${s("placeholder")};
}
&:-webkit-autofill,
&:-webkit-autofill:hover,
&:-webkit-autofill:focus {
-webkit-box-shadow: 0 0 0px 1000px ${s("background")} inset;
}
&::-webkit-search-cancel-button {
-webkit-appearance: none;
}
${breakpoint("mobile", "tablet")`
font-size: 16px;
`};
`;
const StyledComboboxOption = styled(ComboboxOption)`
${MenuAnchorCSS}
/* overriding the styles from MenuAnchorCSS because we use &nbsp; here */
svg:not(:last-child) {
margin-right: 0px;
}
`;
const StyledPositioner = styled(Positioner)`
width: 100%;
`;
export default observer(Combobox);
@@ -0,0 +1,186 @@
import { t } from "i18next";
import { observer } from "mobx-react";
import * as React from "react";
import { toast } from "sonner";
import styled from "styled-components";
import { DocumentPermission } from "@shared/types";
import Document from "~/models/Document";
import User from "~/models/User";
import UserMembership from "~/models/UserMembership";
import MemberListItem from "~/scenes/CollectionPermissions/components/MemberListItem";
import Flex from "~/components/Flex";
import LoadingIndicator from "~/components/LoadingIndicator";
import PaginatedList from "~/components/PaginatedList";
import Text from "~/components/Text";
import useCurrentUser from "~/hooks/useCurrentUser";
import useRequest from "~/hooks/useRequest";
import useStores from "~/hooks/useStores";
import useThrottledCallback from "~/hooks/useThrottledCallback";
import Combobox from "./Combobox";
type Props = {
document: Document;
};
function InviteTeamMembers({ document }: Props) {
const { users, userMemberships } = useStores();
const [query, setQuery] = React.useState("");
const [selectedUser, setSelectedUser] = React.useState<User | null>(null);
const user = useCurrentUser();
const {
data: teamMembers,
loading: loadingTeamMembers,
request: loadTeamMembers,
} = useRequest(
React.useCallback(() => users.fetchPage({ limit: 10 }), [users])
);
const {
data: documentMembers,
loading: loadingDocumentMembers,
request: loadDocumentMembers,
} = useRequest(
React.useCallback(
() =>
userMemberships.fetchDocumentMemberships({
id: document.id,
limit: 10,
}),
[userMemberships, document.id]
)
);
const inviteUser = React.useCallback(
(user: User) =>
userMemberships.create({
documentId: document.id,
userId: user.id,
permission: DocumentPermission.ReadWrite,
}),
[userMemberships, document.id]
);
React.useEffect(() => {
void loadTeamMembers();
void loadDocumentMembers();
}, [loadTeamMembers, loadDocumentMembers]);
const fetchUsersByQuery = useThrottledCallback(
(query) =>
users.fetchPage({
query,
}),
250
);
React.useEffect(() => {
if (query) {
void fetchUsersByQuery(query);
}
}, [query, fetchUsersByQuery]);
React.useEffect(() => {
if (selectedUser) {
void inviteUser(selectedUser);
}
}, [selectedUser, inviteUser]);
const handleQuery = (value: string) => {
setQuery(value);
};
const handleSelect = (user: User) => {
setSelectedUser(user);
};
const handleRemoveUser = React.useCallback(
async (user) => {
try {
await userMemberships.delete({
documentId: document.id,
userId: user.id,
} as UserMembership);
toast.success(
t(`{{ userName }} was removed from the document`, {
userName: user.name,
})
);
} catch (err) {
toast.error(t("Could not remove user"));
}
},
[userMemberships, document]
);
const handleUpdateUser = React.useCallback(
async (user, permission) => {
try {
await userMemberships.create({
documentId: document.id,
userId: user.id,
permission,
});
toast.success(
t(`{{ userName }} permissions were updated`, {
userName: user.name,
})
);
} catch (err) {
toast.error(t("Could not update user"));
}
},
[userMemberships, document]
);
if (!teamMembers || !documentMembers) {
return null;
}
if (loadingTeamMembers || loadingDocumentMembers) {
return <LoadingIndicator />;
}
return (
<RelativeFlex column>
<Combobox
suggestions={document.uninvitedUsers.map((user) => ({
...user,
value: user.name,
}))}
value={query}
onChangeInput={handleQuery}
onSelectOption={handleSelect}
placeholder={`${t("Search by name")}…`}
label={t("Invite team members")}
listLabel="Team members"
flex
autoFocus
/>
{document.users.length > 0 ? (
<Text weight="bold">{t("In this project")}</Text>
) : null}
<PaginatedList
items={document.users}
options={{ id: document.id }}
renderItem={(item: User) => (
<MemberListItem
key={item.id}
user={item}
membership={item.getMembership(document)}
canEdit={item.id !== user.id || user.isAdmin}
onRemove={() => handleRemoveUser(item)}
onUpdate={(permission) => handleUpdateUser(item, permission)}
isAdminPermissionSupported={false}
/>
)}
/>
</RelativeFlex>
);
}
const RelativeFlex = styled(Flex)`
position: relative;
`;
export default observer(InviteTeamMembers);
@@ -25,6 +25,7 @@ import useKeyDown from "~/hooks/useKeyDown";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
import useUserLocale from "~/hooks/useUserLocale";
import InviteTeamMembers from "./InviteTeamMembers";
type Props = {
/** The document to share. */
@@ -301,6 +302,10 @@ function SharePopover({
</SwitchLabel>
</SwitchWrapper>
<Separator />
<SwitchWrapper>
<InviteTeamMembers document={document} />
</SwitchWrapper>
<Separator />
<SwitchWrapper>
<Input
type="text"
+57 -1
View File
@@ -4,9 +4,16 @@ import UserMembership from "~/models/UserMembership";
import { PaginationParams } from "~/types";
import { client } from "~/utils/ApiClient";
import RootStore from "./RootStore";
import Store from "./base/Store";
import Store, { PAGINATION_SYMBOL, RPCAction } from "./base/Store";
export default class UserMembershipsStore extends Store<UserMembership> {
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<UserMembership> {
}
};
@action
fetchDocumentMemberships = async (
params: (PaginationParams & { id: string }) | undefined
): Promise<UserMembership[]> => {
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<UserMembership>) {
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());
+2 -3
View File
@@ -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)
-9
View File
@@ -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;
+1 -1
View File
@@ -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,
+87 -1
View File
@@ -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);
});
});
+61
View File
@@ -1556,4 +1556,65 @@ router.post(
}
);
router.post(
"documents.memberships",
auth(),
pagination(),
validate(T.DocumentsMembershipsSchema),
async (ctx: APIContext<T.DocumentsMembershipsReq>) => {
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<UserPermission> = {
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;
+12
View File
@@ -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
>;
+6 -11
View File
@@ -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<typeof UserMembershipsListSchema>;
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<
@@ -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",
},
});
@@ -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<T.UserMembershipsUpdateReq>) => {
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;
+1 -1
View File
@@ -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;
}
-5
View File
@@ -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})$/;
}
@@ -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></2> unless restored.": "This template will be permanently deleted in <2></2> unless restored.",
"This document will be permanently deleted in <2></2> unless restored.": "This document will be permanently deleted in <2></2> unless restored.",