mirror of
https://github.com/Shadowfita/docmost.git
synced 2025-11-09 20:12:00 +10:00
Compare commits
4 Commits
9e8a3681d6
...
8eb5eb3161
| Author | SHA1 | Date | |
|---|---|---|---|
| 8eb5eb3161 | |||
| fb27282886 | |||
| dea9f4c063 | |||
| 0b6730c06f |
@ -5,14 +5,15 @@ import {
|
||||
Badge,
|
||||
Table,
|
||||
ScrollArea,
|
||||
} from "@mantine/core";
|
||||
import { Link } from "react-router-dom";
|
||||
import PageListSkeleton from "@/components/ui/page-list-skeleton.tsx";
|
||||
import { buildPageUrl } from "@/features/page/page.utils.ts";
|
||||
import { formattedDate } from "@/lib/time.ts";
|
||||
import { useRecentChangesQuery } from "@/features/page/queries/page-query.ts";
|
||||
import { IconFileDescription } from "@tabler/icons-react";
|
||||
import { getSpaceUrl } from "@/lib/config.ts";
|
||||
ActionIcon,
|
||||
} from '@mantine/core';
|
||||
import { Link } from 'react-router-dom';
|
||||
import PageListSkeleton from '@/components/ui/page-list-skeleton.tsx';
|
||||
import { buildPageUrl } from '@/features/page/page.utils.ts';
|
||||
import { formattedDate } from '@/lib/time.ts';
|
||||
import { useRecentChangesQuery } from '@/features/page/queries/page-query.ts';
|
||||
import { IconFileDescription } from '@tabler/icons-react';
|
||||
import { getSpaceUrl } from '@/lib/config.ts';
|
||||
|
||||
interface Props {
|
||||
spaceId?: string;
|
||||
@ -40,10 +41,14 @@ export default function RecentChanges({ spaceId }: Props) {
|
||||
to={buildPageUrl(page?.space.slug, page.slugId, page.title)}
|
||||
>
|
||||
<Group wrap="nowrap">
|
||||
{page.icon || <IconFileDescription size={18} />}
|
||||
{page.icon || (
|
||||
<ActionIcon variant='transparent' color='gray' size={18}>
|
||||
<IconFileDescription size={18} />
|
||||
</ActionIcon>
|
||||
)}
|
||||
|
||||
<Text fw={500} size="md" lineClamp={1}>
|
||||
{page.title || "Untitled"}
|
||||
{page.title || 'Untitled'}
|
||||
</Text>
|
||||
</Group>
|
||||
</UnstyledButton>
|
||||
@ -55,7 +60,7 @@ export default function RecentChanges({ spaceId }: Props) {
|
||||
variant="light"
|
||||
component={Link}
|
||||
to={getSpaceUrl(page?.space.slug)}
|
||||
style={{ cursor: "pointer" }}
|
||||
style={{ cursor: 'pointer' }}
|
||||
>
|
||||
{page?.space.name}
|
||||
</Badge>
|
||||
|
||||
@ -3,8 +3,8 @@ import {
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
UseQueryResult,
|
||||
} from "@tanstack/react-query";
|
||||
import { IGroup } from "@/features/group/types/group.types";
|
||||
} from '@tanstack/react-query';
|
||||
import { IGroup } from '@/features/group/types/group.types';
|
||||
import {
|
||||
addGroupMember,
|
||||
createGroup,
|
||||
@ -14,22 +14,22 @@ import {
|
||||
getGroups,
|
||||
removeGroupMember,
|
||||
updateGroup,
|
||||
} from "@/features/group/services/group-service";
|
||||
import { notifications } from "@mantine/notifications";
|
||||
import { QueryParams } from "@/lib/types.ts";
|
||||
} from '@/features/group/services/group-service';
|
||||
import { notifications } from '@mantine/notifications';
|
||||
import { QueryParams } from '@/lib/types.ts';
|
||||
|
||||
export function useGetGroupsQuery(
|
||||
params?: QueryParams,
|
||||
params?: QueryParams
|
||||
): UseQueryResult<any, Error> {
|
||||
return useQuery({
|
||||
queryKey: ["groups", params],
|
||||
queryKey: ['groups', params],
|
||||
queryFn: () => getGroups(params),
|
||||
});
|
||||
}
|
||||
|
||||
export function useGroupQuery(groupId: string): UseQueryResult<IGroup, Error> {
|
||||
return useQuery({
|
||||
queryKey: ["groups", groupId],
|
||||
queryKey: ['groups', groupId],
|
||||
queryFn: () => getGroupById(groupId),
|
||||
enabled: !!groupId,
|
||||
});
|
||||
@ -37,7 +37,7 @@ export function useGroupQuery(groupId: string): UseQueryResult<IGroup, Error> {
|
||||
|
||||
export function useGroupMembersQuery(groupId: string) {
|
||||
return useQuery({
|
||||
queryKey: ["groupMembers", groupId],
|
||||
queryKey: ['groupMembers', groupId],
|
||||
queryFn: () => getGroupMembers(groupId),
|
||||
enabled: !!groupId,
|
||||
});
|
||||
@ -47,10 +47,10 @@ export function useCreateGroupMutation() {
|
||||
return useMutation<IGroup, Error, Partial<IGroup>>({
|
||||
mutationFn: (data) => createGroup(data),
|
||||
onSuccess: () => {
|
||||
notifications.show({ message: "Group created successfully" });
|
||||
notifications.show({ message: 'Group created successfully' });
|
||||
},
|
||||
onError: () => {
|
||||
notifications.show({ message: "Failed to create group", color: "red" });
|
||||
notifications.show({ message: 'Failed to create group', color: 'red' });
|
||||
},
|
||||
});
|
||||
}
|
||||
@ -61,14 +61,14 @@ export function useUpdateGroupMutation() {
|
||||
return useMutation<IGroup, Error, Partial<IGroup>>({
|
||||
mutationFn: (data) => updateGroup(data),
|
||||
onSuccess: (data, variables) => {
|
||||
notifications.show({ message: "Group updated successfully" });
|
||||
notifications.show({ message: 'Group updated successfully' });
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["group", variables.groupId],
|
||||
queryKey: ['group', variables.groupId],
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
const errorMessage = error["response"]?.data?.message;
|
||||
notifications.show({ message: errorMessage, color: "red" });
|
||||
const errorMessage = error['response']?.data?.message;
|
||||
notifications.show({ message: errorMessage, color: 'red' });
|
||||
},
|
||||
});
|
||||
}
|
||||
@ -79,17 +79,19 @@ export function useDeleteGroupMutation() {
|
||||
return useMutation({
|
||||
mutationFn: (groupId: string) => deleteGroup({ groupId }),
|
||||
onSuccess: (data, variables) => {
|
||||
notifications.show({ message: "Group deleted successfully" });
|
||||
notifications.show({ message: 'Group deleted successfully' });
|
||||
|
||||
const groups = queryClient.getQueryData(["groups"]) as any;
|
||||
const groups = queryClient.getQueryData(['groups']) as any;
|
||||
if (groups) {
|
||||
groups.items?.filter((group: IGroup) => group.id !== variables);
|
||||
queryClient.setQueryData(["groups"], groups);
|
||||
groups.items = groups.items?.filter(
|
||||
(group: IGroup) => group.id !== variables
|
||||
);
|
||||
queryClient.setQueryData(['groups'], groups);
|
||||
}
|
||||
},
|
||||
onError: (error) => {
|
||||
const errorMessage = error["response"]?.data?.message;
|
||||
notifications.show({ message: errorMessage, color: "red" });
|
||||
const errorMessage = error['response']?.data?.message;
|
||||
notifications.show({ message: errorMessage, color: 'red' });
|
||||
},
|
||||
});
|
||||
}
|
||||
@ -100,15 +102,15 @@ export function useAddGroupMemberMutation() {
|
||||
return useMutation<void, Error, { groupId: string; userIds: string[] }>({
|
||||
mutationFn: (data) => addGroupMember(data),
|
||||
onSuccess: (data, variables) => {
|
||||
notifications.show({ message: "Added successfully" });
|
||||
notifications.show({ message: 'Added successfully' });
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["groupMembers", variables.groupId],
|
||||
queryKey: ['groupMembers', variables.groupId],
|
||||
});
|
||||
},
|
||||
onError: () => {
|
||||
notifications.show({
|
||||
message: "Failed to add group members",
|
||||
color: "red",
|
||||
message: 'Failed to add group members',
|
||||
color: 'red',
|
||||
});
|
||||
},
|
||||
});
|
||||
@ -127,14 +129,14 @@ export function useRemoveGroupMemberMutation() {
|
||||
>({
|
||||
mutationFn: (data) => removeGroupMember(data),
|
||||
onSuccess: (data, variables) => {
|
||||
notifications.show({ message: "Removed successfully" });
|
||||
notifications.show({ message: 'Removed successfully' });
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["groupMembers", variables.groupId],
|
||||
queryKey: ['groupMembers', variables.groupId],
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
const errorMessage = error["response"]?.data?.message;
|
||||
notifications.show({ message: errorMessage, color: "red" });
|
||||
const errorMessage = error['response']?.data?.message;
|
||||
notifications.show({ message: errorMessage, color: 'red' });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@ -64,7 +64,7 @@ export async function exportPage(data: IExportPageParams): Promise<void> {
|
||||
.split("filename=")[1]
|
||||
.replace(/"/g, "");
|
||||
|
||||
saveAs(req.data, fileName);
|
||||
saveAs(req.data, decodeURIComponent(fileName));
|
||||
}
|
||||
|
||||
export async function importPage(file: File, spaceId: string) {
|
||||
@ -81,14 +81,17 @@ export async function importPage(file: File, spaceId: string) {
|
||||
return req.data;
|
||||
}
|
||||
|
||||
export async function uploadFile(file: File, pageId: string, attachmentId?: string): Promise<IAttachment> {
|
||||
export async function uploadFile(
|
||||
file: File,
|
||||
pageId: string,
|
||||
attachmentId?: string,
|
||||
): Promise<IAttachment> {
|
||||
const formData = new FormData();
|
||||
if(attachmentId){
|
||||
if (attachmentId) {
|
||||
formData.append("attachmentId", attachmentId);
|
||||
}
|
||||
formData.append("pageId", pageId);
|
||||
formData.append("file", file);
|
||||
|
||||
|
||||
const req = await api.post<IAttachment>("/files/upload", formData, {
|
||||
headers: {
|
||||
|
||||
@ -0,0 +1,86 @@
|
||||
import { Button, Divider, Group, Modal, Text, TextInput } from '@mantine/core';
|
||||
import { useDisclosure } from '@mantine/hooks';
|
||||
import { useDeleteSpaceMutation } from '../queries/space-query';
|
||||
import { useField } from '@mantine/form';
|
||||
import { ISpace } from '../types/space.types';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import APP_ROUTE from '@/lib/app-route';
|
||||
|
||||
interface DeleteSpaceModalProps {
|
||||
space: ISpace;
|
||||
}
|
||||
|
||||
export default function DeleteSpaceModal({ space }: DeleteSpaceModalProps) {
|
||||
const [opened, { open, close }] = useDisclosure(false);
|
||||
const deleteSpaceMutation = useDeleteSpaceMutation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const confirmNameField = useField({
|
||||
initialValue: '',
|
||||
validateOnChange: true,
|
||||
validate: (value) =>
|
||||
value.trim().toLowerCase() === space.name.trim().toLocaleLowerCase()
|
||||
? null
|
||||
: 'Names do not match',
|
||||
});
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (
|
||||
confirmNameField.getValue().trim().toLowerCase() !==
|
||||
space.name.trim().toLowerCase()
|
||||
) {
|
||||
confirmNameField.validate();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// pass slug too so we can clear the local cache
|
||||
await deleteSpaceMutation.mutateAsync({ id: space.id, slug: space.slug });
|
||||
navigate(APP_ROUTE.HOME);
|
||||
} catch (error) {
|
||||
console.error('Failed to delete space', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button onClick={open} variant="light" color="red">
|
||||
Delete
|
||||
</Button>
|
||||
|
||||
<Modal
|
||||
opened={opened}
|
||||
onClose={close}
|
||||
title="Are you sure you want to delete this space?"
|
||||
>
|
||||
<Divider size="xs" mb="xs" />
|
||||
<Text>
|
||||
All pages, comments, attachments and permissions in this space will be
|
||||
deleted irreversibly.
|
||||
</Text>
|
||||
<Text mt="sm">
|
||||
Type the space name{' '}
|
||||
<Text span fw={500}>
|
||||
'{space.name}'
|
||||
</Text>{' '}
|
||||
to confirm your action.
|
||||
</Text>
|
||||
<TextInput
|
||||
{...confirmNameField.getInputProps()}
|
||||
variant="filled"
|
||||
placeholder="Confirm space name"
|
||||
py="sm"
|
||||
data-autofocus
|
||||
/>
|
||||
<Group justify="flex-end" mt="md">
|
||||
<Button onClick={close} variant="default">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleDelete} color="red">
|
||||
Confirm
|
||||
</Button>
|
||||
</Group>
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@ -8,6 +8,14 @@ import { ISpace } from "@/features/space/types/space.types.ts";
|
||||
const formSchema = z.object({
|
||||
name: z.string().min(2).max(50),
|
||||
description: z.string().max(250),
|
||||
slug: z
|
||||
.string()
|
||||
.min(2)
|
||||
.max(50)
|
||||
.regex(
|
||||
/^[a-zA-Z0-9]+$/,
|
||||
"Space slug must be alphanumeric. No special characters",
|
||||
),
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof formSchema>;
|
||||
@ -23,12 +31,14 @@ export function EditSpaceForm({ space, readOnly }: EditSpaceFormProps) {
|
||||
initialValues: {
|
||||
name: space?.name,
|
||||
description: space?.description || "",
|
||||
slug: space.slug,
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = async (values: {
|
||||
name?: string;
|
||||
description?: string;
|
||||
slug?: string;
|
||||
}) => {
|
||||
const spaceData: Partial<ISpace> = {
|
||||
spaceId: space.id,
|
||||
@ -40,6 +50,10 @@ export function EditSpaceForm({ space, readOnly }: EditSpaceFormProps) {
|
||||
spaceData.description = values.description;
|
||||
}
|
||||
|
||||
if (form.isDirty("slug")) {
|
||||
spaceData.slug = values.slug;
|
||||
}
|
||||
|
||||
await updateSpaceMutation.mutateAsync(spaceData);
|
||||
form.resetDirty();
|
||||
};
|
||||
@ -62,8 +76,8 @@ export function EditSpaceForm({ space, readOnly }: EditSpaceFormProps) {
|
||||
id="slug"
|
||||
label="Slug"
|
||||
variant="filled"
|
||||
readOnly
|
||||
value={space.slug}
|
||||
readOnly={readOnly}
|
||||
{...form.getInputProps("slug")}
|
||||
/>
|
||||
|
||||
<Textarea
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
import React from "react";
|
||||
import { useSpaceQuery } from "@/features/space/queries/space-query.ts";
|
||||
import { EditSpaceForm } from "@/features/space/components/edit-space-form.tsx";
|
||||
import { Text } from "@mantine/core";
|
||||
import React from 'react';
|
||||
import { useSpaceQuery } from '@/features/space/queries/space-query.ts';
|
||||
import { EditSpaceForm } from '@/features/space/components/edit-space-form.tsx';
|
||||
import { Divider, Group, Text } from '@mantine/core';
|
||||
import DeleteSpaceModal from './delete-space-modal';
|
||||
|
||||
interface SpaceDetailsProps {
|
||||
spaceId: string;
|
||||
@ -18,6 +19,23 @@ export default function SpaceDetails({ spaceId, readOnly }: SpaceDetailsProps) {
|
||||
Details
|
||||
</Text>
|
||||
<EditSpaceForm space={space} readOnly={readOnly} />
|
||||
|
||||
{!readOnly && (
|
||||
<>
|
||||
<Divider my="lg" />
|
||||
|
||||
<Group justify="space-between" wrap="nowrap" gap="xl">
|
||||
<div>
|
||||
<Text size="md">Delete space</Text>
|
||||
<Text size="sm" c="dimmed">
|
||||
Delete this space with all its pages and data.
|
||||
</Text>
|
||||
</div>
|
||||
|
||||
<DeleteSpaceModal space={space} />
|
||||
</Group>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
|
||||
@ -3,14 +3,14 @@ import {
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
UseQueryResult,
|
||||
} from "@tanstack/react-query";
|
||||
} from '@tanstack/react-query';
|
||||
import {
|
||||
IAddSpaceMember,
|
||||
IChangeSpaceMemberRole,
|
||||
IRemoveSpaceMember,
|
||||
ISpace,
|
||||
ISpaceMember,
|
||||
} from "@/features/space/types/space.types";
|
||||
} from '@/features/space/types/space.types';
|
||||
import {
|
||||
addSpaceMember,
|
||||
changeMemberRole,
|
||||
@ -20,23 +20,24 @@ import {
|
||||
removeSpaceMember,
|
||||
createSpace,
|
||||
updateSpace,
|
||||
} from "@/features/space/services/space-service.ts";
|
||||
import { notifications } from "@mantine/notifications";
|
||||
import { IPagination } from "@/lib/types.ts";
|
||||
deleteSpace,
|
||||
} from '@/features/space/services/space-service.ts';
|
||||
import { notifications } from '@mantine/notifications';
|
||||
import { IPagination } from '@/lib/types.ts';
|
||||
|
||||
export function useGetSpacesQuery(): UseQueryResult<
|
||||
IPagination<ISpace>,
|
||||
Error
|
||||
> {
|
||||
return useQuery({
|
||||
queryKey: ["spaces"],
|
||||
queryKey: ['spaces'],
|
||||
queryFn: () => getSpaces(),
|
||||
});
|
||||
}
|
||||
|
||||
export function useSpaceQuery(spaceId: string): UseQueryResult<ISpace, Error> {
|
||||
return useQuery({
|
||||
queryKey: ["spaces", spaceId],
|
||||
queryKey: ['spaces', spaceId],
|
||||
queryFn: () => getSpaceById(spaceId),
|
||||
enabled: !!spaceId,
|
||||
staleTime: 5 * 60 * 1000,
|
||||
@ -50,22 +51,22 @@ export function useCreateSpaceMutation() {
|
||||
mutationFn: (data) => createSpace(data),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["spaces"],
|
||||
queryKey: ['spaces'],
|
||||
});
|
||||
notifications.show({ message: "Space created successfully" });
|
||||
notifications.show({ message: 'Space created successfully' });
|
||||
},
|
||||
onError: (error) => {
|
||||
const errorMessage = error["response"]?.data?.message;
|
||||
notifications.show({ message: errorMessage, color: "red" });
|
||||
const errorMessage = error['response']?.data?.message;
|
||||
notifications.show({ message: errorMessage, color: 'red' });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useGetSpaceBySlugQuery(
|
||||
spaceId: string,
|
||||
spaceId: string
|
||||
): UseQueryResult<ISpace, Error> {
|
||||
return useQuery({
|
||||
queryKey: ["spaces", spaceId],
|
||||
queryKey: ['spaces', spaceId],
|
||||
queryFn: () => getSpaceById(spaceId),
|
||||
enabled: !!spaceId,
|
||||
staleTime: 5 * 60 * 1000,
|
||||
@ -78,34 +79,64 @@ export function useUpdateSpaceMutation() {
|
||||
return useMutation<ISpace, Error, Partial<ISpace>>({
|
||||
mutationFn: (data) => updateSpace(data),
|
||||
onSuccess: (data, variables) => {
|
||||
notifications.show({ message: "Space updated successfully" });
|
||||
notifications.show({ message: 'Space updated successfully' });
|
||||
|
||||
const space = queryClient.getQueryData([
|
||||
"space",
|
||||
'space',
|
||||
variables.spaceId,
|
||||
]) as ISpace;
|
||||
if (space) {
|
||||
const updatedSpace = { ...space, ...data };
|
||||
queryClient.setQueryData(["space", variables.spaceId], updatedSpace);
|
||||
queryClient.setQueryData(["space", data.slug], updatedSpace);
|
||||
queryClient.setQueryData(['space', variables.spaceId], updatedSpace);
|
||||
queryClient.setQueryData(['space', data.slug], updatedSpace);
|
||||
}
|
||||
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["spaces"],
|
||||
queryKey: ['spaces'],
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
const errorMessage = error["response"]?.data?.message;
|
||||
notifications.show({ message: errorMessage, color: "red" });
|
||||
const errorMessage = error['response']?.data?.message;
|
||||
notifications.show({ message: errorMessage, color: 'red' });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteSpaceMutation() {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (data: Partial<ISpace>) => deleteSpace(data.id),
|
||||
onSuccess: (data, variables) => {
|
||||
notifications.show({ message: 'Space deleted successfully' });
|
||||
|
||||
if (variables.slug) {
|
||||
queryClient.removeQueries({
|
||||
queryKey: ['spaces', variables.slug],
|
||||
exact: true,
|
||||
});
|
||||
}
|
||||
|
||||
const spaces = queryClient.getQueryData(['spaces']) as any;
|
||||
if (spaces) {
|
||||
spaces.items = spaces.items?.filter(
|
||||
(space: ISpace) => space.id !== variables.id
|
||||
);
|
||||
queryClient.setQueryData(['spaces'], spaces);
|
||||
}
|
||||
},
|
||||
onError: (error) => {
|
||||
const errorMessage = error['response']?.data?.message;
|
||||
notifications.show({ message: errorMessage, color: 'red' });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useSpaceMembersQuery(
|
||||
spaceId: string,
|
||||
spaceId: string
|
||||
): UseQueryResult<IPagination<ISpaceMember>, Error> {
|
||||
return useQuery({
|
||||
queryKey: ["spaceMembers", spaceId],
|
||||
queryKey: ['spaceMembers', spaceId],
|
||||
queryFn: () => getSpaceMembers(spaceId),
|
||||
enabled: !!spaceId,
|
||||
});
|
||||
@ -117,14 +148,14 @@ export function useAddSpaceMemberMutation() {
|
||||
return useMutation<void, Error, IAddSpaceMember>({
|
||||
mutationFn: (data) => addSpaceMember(data),
|
||||
onSuccess: (data, variables) => {
|
||||
notifications.show({ message: "Members added successfully" });
|
||||
notifications.show({ message: 'Members added successfully' });
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["spaceMembers", variables.spaceId],
|
||||
queryKey: ['spaceMembers', variables.spaceId],
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
const errorMessage = error["response"]?.data?.message;
|
||||
notifications.show({ message: errorMessage, color: "red" });
|
||||
const errorMessage = error['response']?.data?.message;
|
||||
notifications.show({ message: errorMessage, color: 'red' });
|
||||
},
|
||||
});
|
||||
}
|
||||
@ -135,14 +166,14 @@ export function useRemoveSpaceMemberMutation() {
|
||||
return useMutation<void, Error, IRemoveSpaceMember>({
|
||||
mutationFn: (data) => removeSpaceMember(data),
|
||||
onSuccess: (data, variables) => {
|
||||
notifications.show({ message: "Removed successfully" });
|
||||
notifications.show({ message: 'Removed successfully' });
|
||||
queryClient.refetchQueries({
|
||||
queryKey: ["spaceMembers", variables.spaceId],
|
||||
queryKey: ['spaceMembers', variables.spaceId],
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
const errorMessage = error["response"]?.data?.message;
|
||||
notifications.show({ message: errorMessage, color: "red" });
|
||||
const errorMessage = error['response']?.data?.message;
|
||||
notifications.show({ message: errorMessage, color: 'red' });
|
||||
},
|
||||
});
|
||||
}
|
||||
@ -153,15 +184,15 @@ export function useChangeSpaceMemberRoleMutation() {
|
||||
return useMutation<void, Error, IChangeSpaceMemberRole>({
|
||||
mutationFn: (data) => changeMemberRole(data),
|
||||
onSuccess: (data, variables) => {
|
||||
notifications.show({ message: "Member role updated successfully" });
|
||||
notifications.show({ message: 'Member role updated successfully' });
|
||||
// due to pagination levels, change in cache instead
|
||||
queryClient.refetchQueries({
|
||||
queryKey: ["spaceMembers", variables.spaceId],
|
||||
queryKey: ['spaceMembers', variables.spaceId],
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
const errorMessage = error["response"]?.data?.message;
|
||||
notifications.show({ message: errorMessage, color: "red" });
|
||||
const errorMessage = error['response']?.data?.message;
|
||||
notifications.show({ message: errorMessage, color: 'red' });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@ -1,52 +1,56 @@
|
||||
import api from "@/lib/api-client";
|
||||
import api from '@/lib/api-client';
|
||||
import {
|
||||
IAddSpaceMember,
|
||||
IChangeSpaceMemberRole,
|
||||
IRemoveSpaceMember,
|
||||
ISpace,
|
||||
} from "@/features/space/types/space.types";
|
||||
import { IPagination } from "@/lib/types.ts";
|
||||
import { IUser } from "@/features/user/types/user.types.ts";
|
||||
} from '@/features/space/types/space.types';
|
||||
import { IPagination } from '@/lib/types.ts';
|
||||
import { IUser } from '@/features/user/types/user.types.ts';
|
||||
|
||||
export async function getSpaces(): Promise<IPagination<ISpace>> {
|
||||
const req = await api.post("/spaces");
|
||||
const req = await api.post('/spaces');
|
||||
return req.data;
|
||||
}
|
||||
|
||||
export async function getSpaceById(spaceId: string): Promise<ISpace> {
|
||||
const req = await api.post<ISpace>("/spaces/info", { spaceId });
|
||||
const req = await api.post<ISpace>('/spaces/info', { spaceId });
|
||||
return req.data;
|
||||
}
|
||||
|
||||
export async function createSpace(data: Partial<ISpace>): Promise<ISpace> {
|
||||
const req = await api.post<ISpace>("/spaces/create", data);
|
||||
const req = await api.post<ISpace>('/spaces/create', data);
|
||||
return req.data;
|
||||
}
|
||||
|
||||
export async function updateSpace(data: Partial<ISpace>): Promise<ISpace> {
|
||||
const req = await api.post<ISpace>("/spaces/update", data);
|
||||
const req = await api.post<ISpace>('/spaces/update', data);
|
||||
return req.data;
|
||||
}
|
||||
|
||||
export async function deleteSpace(spaceId: string): Promise<void> {
|
||||
await api.post<void>('/spaces/delete', { spaceId });
|
||||
}
|
||||
|
||||
export async function getSpaceMembers(
|
||||
spaceId: string,
|
||||
spaceId: string
|
||||
): Promise<IPagination<IUser>> {
|
||||
const req = await api.post<any>("/spaces/members", { spaceId });
|
||||
const req = await api.post<any>('/spaces/members', { spaceId });
|
||||
return req.data;
|
||||
}
|
||||
|
||||
export async function addSpaceMember(data: IAddSpaceMember): Promise<void> {
|
||||
await api.post("/spaces/members/add", data);
|
||||
await api.post('/spaces/members/add', data);
|
||||
}
|
||||
|
||||
export async function removeSpaceMember(
|
||||
data: IRemoveSpaceMember,
|
||||
data: IRemoveSpaceMember
|
||||
): Promise<void> {
|
||||
await api.post("/spaces/members/remove", data);
|
||||
await api.post('/spaces/members/remove', data);
|
||||
}
|
||||
|
||||
export async function changeMemberRole(
|
||||
data: IChangeSpaceMemberRole,
|
||||
data: IChangeSpaceMemberRole
|
||||
): Promise<void> {
|
||||
await api.post("/spaces/members/change-role", data);
|
||||
await api.post('/spaces/members/change-role', data);
|
||||
}
|
||||
|
||||
@ -1,20 +1,34 @@
|
||||
import { createTheme, MantineColorsTuple } from "@mantine/core";
|
||||
import { createTheme, MantineColorsTuple } from '@mantine/core';
|
||||
|
||||
const blue: MantineColorsTuple = [
|
||||
"#e7f3ff",
|
||||
"#d0e4ff",
|
||||
"#a1c6fa",
|
||||
"#6ea6f6",
|
||||
"#458bf2",
|
||||
"#2b7af1",
|
||||
"#0b60d8", //
|
||||
"#1b72f2",
|
||||
"#0056c1",
|
||||
"#004aac",
|
||||
'#e7f3ff',
|
||||
'#d0e4ff',
|
||||
'#a1c6fa',
|
||||
'#6ea6f6',
|
||||
'#458bf2',
|
||||
'#2b7af1',
|
||||
'#0b60d8',
|
||||
'#1b72f2',
|
||||
'#0056c1',
|
||||
'#004aac',
|
||||
];
|
||||
|
||||
const red: MantineColorsTuple = [
|
||||
'#ffebeb',
|
||||
'#fad7d7',
|
||||
'#eeadad',
|
||||
'#e3807f',
|
||||
'#da5a59',
|
||||
'#d54241',
|
||||
'#d43535',
|
||||
'#bc2727',
|
||||
'#a82022',
|
||||
'#93151b',
|
||||
];
|
||||
|
||||
export const theme = createTheme({
|
||||
colors: {
|
||||
blue,
|
||||
red,
|
||||
},
|
||||
});
|
||||
|
||||
3
apps/server/src/common/events/event.contants.ts
Normal file
3
apps/server/src/common/events/event.contants.ts
Normal file
@ -0,0 +1,3 @@
|
||||
export enum EventName {
|
||||
COLLAB_PAGE_UPDATED = 'collab.page.updated',
|
||||
}
|
||||
@ -182,7 +182,7 @@ export class AttachmentController {
|
||||
if (!inlineFileExtensions.includes(attachment.fileExt)) {
|
||||
res.header(
|
||||
'Content-Disposition',
|
||||
`attachment; filename="${attachment.fileName}"`,
|
||||
`attachment; filename="${encodeURIComponent(attachment.fileName)}"`,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@ -4,10 +4,11 @@ import { AttachmentController } from './attachment.controller';
|
||||
import { StorageModule } from '../../integrations/storage/storage.module';
|
||||
import { UserModule } from '../user/user.module';
|
||||
import { WorkspaceModule } from '../workspace/workspace.module';
|
||||
import { AttachmentProcessor } from './processors/attachment.processor';
|
||||
|
||||
@Module({
|
||||
imports: [StorageModule, UserModule, WorkspaceModule],
|
||||
controllers: [AttachmentController],
|
||||
providers: [AttachmentService],
|
||||
providers: [AttachmentService, AttachmentProcessor],
|
||||
})
|
||||
export class AttachmentModule {}
|
||||
|
||||
@ -0,0 +1,47 @@
|
||||
import { Logger, OnModuleDestroy } from '@nestjs/common';
|
||||
import { OnWorkerEvent, Processor, WorkerHost } from '@nestjs/bullmq';
|
||||
import { Job } from 'bullmq';
|
||||
import { AttachmentService } from '../services/attachment.service';
|
||||
import { QueueJob, QueueName } from 'src/integrations/queue/constants';
|
||||
import { Space } from '@docmost/db/types/entity.types';
|
||||
|
||||
@Processor(QueueName.ATTACHEMENT_QUEUE)
|
||||
export class AttachmentProcessor extends WorkerHost implements OnModuleDestroy {
|
||||
private readonly logger = new Logger(AttachmentProcessor.name);
|
||||
constructor(private readonly attachmentService: AttachmentService) {
|
||||
super();
|
||||
}
|
||||
|
||||
async process(job: Job<Space, void>): Promise<void> {
|
||||
try {
|
||||
if (job.name === QueueJob.DELETE_SPACE_ATTACHMENTS) {
|
||||
await this.attachmentService.handleDeleteSpaceAttachments(job.data.id);
|
||||
}
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
@OnWorkerEvent('active')
|
||||
onActive(job: Job) {
|
||||
this.logger.debug(`Processing ${job.name} job`);
|
||||
}
|
||||
|
||||
@OnWorkerEvent('failed')
|
||||
onError(job: Job) {
|
||||
this.logger.error(
|
||||
`Error processing ${job.name} job. Reason: ${job.failedReason}`,
|
||||
);
|
||||
}
|
||||
|
||||
@OnWorkerEvent('completed')
|
||||
onCompleted(job: Job) {
|
||||
this.logger.debug(`Completed ${job.name} job`);
|
||||
}
|
||||
|
||||
async onModuleDestroy(): Promise<void> {
|
||||
if (this.worker) {
|
||||
await this.worker.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -256,4 +256,37 @@ export class AttachmentService {
|
||||
trx,
|
||||
);
|
||||
}
|
||||
|
||||
async handleDeleteSpaceAttachments(spaceId: string) {
|
||||
try {
|
||||
const attachments = await this.attachmentRepo.findBySpaceId(spaceId);
|
||||
if (!attachments || attachments.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const failedDeletions = [];
|
||||
|
||||
await Promise.all(
|
||||
attachments.map(async (attachment) => {
|
||||
try {
|
||||
await this.storageService.delete(attachment.filePath);
|
||||
await this.attachmentRepo.deleteAttachmentById(attachment.id);
|
||||
} catch (err) {
|
||||
failedDeletions.push(attachment.id);
|
||||
this.logger.log(
|
||||
`DeleteSpaceAttachments: failed to delete attachment ${attachment.id}:`,
|
||||
err,
|
||||
);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
if(failedDeletions.length === attachments.length){
|
||||
throw new Error(`Failed to delete any attachments for spaceId: ${spaceId}`);
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -14,6 +14,9 @@ import { executeTx } from '@docmost/db/utils';
|
||||
import { InjectKysely } from 'nestjs-kysely';
|
||||
import { SpaceMemberService } from './space-member.service';
|
||||
import { SpaceRole } from '../../../common/helpers/types/permission';
|
||||
import { QueueJob, QueueName } from 'src/integrations/queue/constants';
|
||||
import { Queue } from 'bullmq';
|
||||
import { InjectQueue } from '@nestjs/bullmq';
|
||||
|
||||
@Injectable()
|
||||
export class SpaceService {
|
||||
@ -21,6 +24,7 @@ export class SpaceService {
|
||||
private spaceRepo: SpaceRepo,
|
||||
private spaceMemberService: SpaceMemberService,
|
||||
@InjectKysely() private readonly db: KyselyDB,
|
||||
@InjectQueue(QueueName.ATTACHEMENT_QUEUE) private attachmentQueue: Queue,
|
||||
) {}
|
||||
|
||||
async createSpace(
|
||||
@ -88,10 +92,24 @@ export class SpaceService {
|
||||
updateSpaceDto: UpdateSpaceDto,
|
||||
workspaceId: string,
|
||||
): Promise<Space> {
|
||||
if (updateSpaceDto?.slug) {
|
||||
const slugExists = await this.spaceRepo.slugExists(
|
||||
updateSpaceDto.slug,
|
||||
workspaceId,
|
||||
);
|
||||
|
||||
if (slugExists) {
|
||||
throw new BadRequestException(
|
||||
'Space slug exists. Please use a unique space slug',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return await this.spaceRepo.updateSpace(
|
||||
{
|
||||
name: updateSpaceDto.name,
|
||||
description: updateSpaceDto.description,
|
||||
slug: updateSpaceDto.slug,
|
||||
},
|
||||
updateSpaceDto.spaceId,
|
||||
workspaceId,
|
||||
@ -120,4 +138,14 @@ export class SpaceService {
|
||||
|
||||
return spaces;
|
||||
}
|
||||
|
||||
async deleteSpace(spaceId: string, workspaceId: string): Promise<void> {
|
||||
const space = await this.spaceRepo.findById(spaceId, workspaceId);
|
||||
if (!space) {
|
||||
throw new NotFoundException('Space not found');
|
||||
}
|
||||
|
||||
await this.spaceRepo.deleteSpace(spaceId, workspaceId);
|
||||
await this.attachmentQueue.add(QueueJob.DELETE_SPACE_ATTACHMENTS, space);
|
||||
}
|
||||
}
|
||||
|
||||
@ -95,7 +95,7 @@ export class SpaceController {
|
||||
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('create')
|
||||
createGroup(
|
||||
createSpace(
|
||||
@Body() createSpaceDto: CreateSpaceDto,
|
||||
@AuthUser() user: User,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
@ -111,7 +111,7 @@ export class SpaceController {
|
||||
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('update')
|
||||
async updateGroup(
|
||||
async updateSpace(
|
||||
@Body() updateSpaceDto: UpdateSpaceDto,
|
||||
@AuthUser() user: User,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
@ -126,6 +126,23 @@ export class SpaceController {
|
||||
return this.spaceService.updateSpace(updateSpaceDto, workspace.id);
|
||||
}
|
||||
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('delete')
|
||||
async deleteSpace(
|
||||
@Body() spaceIdDto: SpaceIdDto,
|
||||
@AuthUser() user: User,
|
||||
@AuthWorkspace() workspace: Workspace,
|
||||
) {
|
||||
const ability = await this.spaceAbility.createForUser(
|
||||
user,
|
||||
spaceIdDto.spaceId,
|
||||
);
|
||||
if (ability.cannot(SpaceCaslAction.Manage, SpaceCaslSubject.Settings)) {
|
||||
throw new ForbiddenException();
|
||||
}
|
||||
return this.spaceService.deleteSpace(spaceIdDto.spaceId, workspace.id);
|
||||
}
|
||||
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@Post('members')
|
||||
async getSpaceMembers(
|
||||
|
||||
@ -40,6 +40,21 @@ export class AttachmentRepo {
|
||||
.executeTakeFirst();
|
||||
}
|
||||
|
||||
async findBySpaceId(
|
||||
spaceId: string,
|
||||
opts?: {
|
||||
trx?: KyselyTransaction;
|
||||
},
|
||||
): Promise<Attachment[]> {
|
||||
const db = dbOrTx(this.db, opts?.trx);
|
||||
|
||||
return db
|
||||
.selectFrom('attachments')
|
||||
.selectAll()
|
||||
.where('spaceId', '=', spaceId)
|
||||
.execute();
|
||||
}
|
||||
|
||||
async updateAttachment(
|
||||
updatableAttachment: UpdatableAttachment,
|
||||
attachmentId: string,
|
||||
@ -52,7 +67,7 @@ export class AttachmentRepo {
|
||||
.executeTakeFirst();
|
||||
}
|
||||
|
||||
async deleteAttachment(attachmentId: string): Promise<void> {
|
||||
async deleteAttachmentById(attachmentId: string): Promise<void> {
|
||||
await this.db
|
||||
.deleteFrom('attachments')
|
||||
.where('id', '=', attachmentId)
|
||||
|
||||
@ -64,7 +64,7 @@ export class SpaceMemberRepo {
|
||||
} else if (opts.groupId) {
|
||||
query = query.where('groupId', '=', opts.groupId);
|
||||
} else {
|
||||
throw new BadRequestException('Please provider a userId or groupId');
|
||||
throw new BadRequestException('Please provide a userId or groupId');
|
||||
}
|
||||
return query.executeTakeFirst();
|
||||
}
|
||||
|
||||
@ -61,7 +61,8 @@ export class ImportController {
|
||||
|
||||
res.headers({
|
||||
'Content-Type': getMimeType(fileExt),
|
||||
'Content-Disposition': 'attachment; filename="' + fileName + '"',
|
||||
'Content-Disposition':
|
||||
'attachment; filename="' + encodeURIComponent(fileName) + '"',
|
||||
});
|
||||
|
||||
res.send(rawContent);
|
||||
|
||||
@ -1,7 +1,10 @@
|
||||
export enum QueueName {
|
||||
EMAIL_QUEUE = '{email-queue}',
|
||||
ATTACHEMENT_QUEUE = '{attachment-queue}',
|
||||
}
|
||||
|
||||
export enum QueueJob {
|
||||
SEND_EMAIL = 'send-email',
|
||||
DELETE_SPACE_ATTACHMENTS = 'delete-space-attachments',
|
||||
DELETE_PAGE_ATTACHMENTS = 'delete-page-attachments',
|
||||
}
|
||||
|
||||
@ -31,6 +31,9 @@ import { QueueName } from './constants';
|
||||
BullModule.registerQueue({
|
||||
name: QueueName.EMAIL_QUEUE,
|
||||
}),
|
||||
BullModule.registerQueue({
|
||||
name: QueueName.ATTACHEMENT_QUEUE,
|
||||
}),
|
||||
],
|
||||
exports: [BullModule],
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user