Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(documents): added document restoration and deletion hooks (#96)

Corentin THOMASSETb15bc2a087cd
diff --git a/apps/papra-client/src/modules/documents/components/document-management-dropdown.component.tsx b/apps/papra-client/src/modules/documents/components/document-management-dropdown.component.tsx
index 4e039504..088bd89f 100644
--- a/apps/papra-client/src/modules/documents/components/document-management-dropdown.component.tsx
+++ b/apps/papra-client/src/modules/documents/components/document-management-dropdown.component.tsx
@@ -1,49 +1,19 @@
import type { DropdownMenuSubTriggerProps } from '@kobalte/core/dropdown-menu';
import type { Component } from 'solid-js';
import type { Document } from '../documents.types';
-import { useConfirmModal } from '@/modules/shared/confirm';
-import { queryClient } from '@/modules/shared/query/query-client';
import { Button } from '@/modules/ui/components/button';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/modules/ui/components/dropdown-menu';
-import { createToast } from '@/modules/ui/components/sonner';
import { A } from '@solidjs/router';
-import { deleteDocument } from '../documents.services';
+import { useDeleteDocument } from '../documents.composables';
export const DocumentManagementDropdown: Component<{ document: Document }> = (props) => {
- const { confirm } = useConfirmModal();
+ const { deleteDocument } = useDeleteDocument();
- const deleteDoc = async () => {
- const isConfirmed = await confirm({
- title: 'Delete document',
- message: (
- <>
- Are you sure you want to delete
- {' '}
- <span class="font-bold">{props.document.name}</span>
- ?
- </>
- ),
- confirmButton: {
- text: 'Delete document',
- variant: 'destructive',
- },
- cancelButton: {
- text: 'Cancel',
- },
- });
-
- if (!isConfirmed) {
- return;
- }
-
- await deleteDocument({
- documentId: props.document.id,
- organizationId: props.document.organizationId,
- });
-
- await queryClient.invalidateQueries({ queryKey: ['organizations', props.document.organizationId, 'documents'] });
- createToast({ type: 'success', message: 'Document deleted' });
- };
+ const deleteDoc = () => deleteDocument({
+ documentId: props.document.id,
+ organizationId: props.document.organizationId,
+ documentName: props.document.name,
+ });
return (
<DropdownMenu>
diff --git a/apps/papra-client/src/modules/documents/document.models.test.ts b/apps/papra-client/src/modules/documents/document.models.test.ts
index 141e731a..adee9c7e 100644
--- a/apps/papra-client/src/modules/documents/document.models.test.ts
+++ b/apps/papra-client/src/modules/documents/document.models.test.ts
@@ -1,7 +1,7 @@
import { icons as tablerIconSet } from '@iconify-json/tabler';
import { values } from 'lodash-es';
import { describe, expect, test } from 'vitest';
-import { getDocumentIcon, iconByFileType } from './document.models';
+import { getDaysBeforePermanentDeletion, getDocumentIcon, iconByFileType } from './document.models';
describe('files models', () => {
describe('iconByFileType', () => {
@@ -79,4 +79,26 @@ describe('files models', () => {
expect(icon).to.eql('i-tabler-file-type-html');
});
});
+
+ describe('getDaysBeforePermanentDeletion', () => {
+ test('get the amount of days before a document is permanently deleted, basically the difference between the deletion date and now', () => {
+ const document = { deletedAt: new Date('2021-01-01') };
+ const deletedDocumentsRetentionDays = 30;
+ const now = new Date('2021-01-10');
+
+ const daysBeforeDeletion = getDaysBeforePermanentDeletion({ document, deletedDocumentsRetentionDays, now });
+
+ expect(daysBeforeDeletion).to.eql(21);
+ });
+
+ test('if the document has not been deleted, the days before permanent deletion is undefined', () => {
+ const document = { deletedAt: undefined };
+ const deletedDocumentsRetentionDays = 30;
+ const now = new Date('2021-01-10');
+
+ const daysBeforeDeletion = getDaysBeforePermanentDeletion({ document, deletedDocumentsRetentionDays, now });
+
+ expect(daysBeforeDeletion).to.eql(undefined);
+ });
+ });
});
diff --git a/apps/papra-client/src/modules/documents/document.models.ts b/apps/papra-client/src/modules/documents/document.models.ts
index cc394559..9bdbf278 100644
--- a/apps/papra-client/src/modules/documents/document.models.ts
+++ b/apps/papra-client/src/modules/documents/document.models.ts
@@ -1,3 +1,5 @@
+import { addDays, differenceInDays } from 'date-fns';
+
export const iconByFileType = {
'*': 'i-tabler-file',
'image': 'i-tabler-photo',
@@ -35,3 +37,15 @@ export function getDocumentIcon({ document, iconsMap = iconByFileType }: { docum
return icon;
}
+
+export function getDaysBeforePermanentDeletion({ document, deletedDocumentsRetentionDays, now = new Date() }: { document: { deletedAt?: Date }; deletedDocumentsRetentionDays: number; now?: Date }) {
+ if (!document.deletedAt) {
+ return undefined;
+ }
+
+ const deletionDate = addDays(document.deletedAt, deletedDocumentsRetentionDays);
+
+ const daysBeforeDeletion = differenceInDays(deletionDate, now);
+
+ return daysBeforeDeletion;
+}
diff --git a/apps/papra-client/src/modules/documents/documents.composables.tsx b/apps/papra-client/src/modules/documents/documents.composables.tsx
new file mode 100644
index 00000000..7eb7c83c
--- /dev/null
+++ b/apps/papra-client/src/modules/documents/documents.composables.tsx
@@ -0,0 +1,68 @@
+import type { Document } from './documents.types';
+import { createSignal } from 'solid-js';
+import { useConfirmModal } from '../shared/confirm';
+import { queryClient } from '../shared/query/query-client';
+import { createToast } from '../ui/components/sonner';
+import { deleteDocument, restoreDocument } from './documents.services';
+
+export function useDeleteDocument() {
+ const { confirm } = useConfirmModal();
+
+ return {
+ async deleteDocument({ documentId, organizationId, documentName }: { documentId: string; organizationId: string; documentName: string }) {
+ const isConfirmed = await confirm({
+ title: 'Delete document',
+ message: (
+ <>
+ Are you sure you want to delete
+ {' '}
+ <span class="font-bold">{documentName}</span>
+ ?
+ </>
+ ),
+ confirmButton: {
+ text: 'Delete document',
+ variant: 'destructive',
+ },
+ cancelButton: {
+ text: 'Cancel',
+ },
+ });
+
+ if (!isConfirmed) {
+ return { hasDeleted: false };
+ }
+
+ await deleteDocument({
+ documentId,
+ organizationId,
+ });
+
+ await queryClient.invalidateQueries({ queryKey: ['organizations', organizationId, 'documents'] });
+ createToast({ type: 'success', message: 'Document deleted' });
+
+ return { hasDeleted: true };
+ },
+ };
+}
+
+export function useRestoreDocument() {
+ const [getIsRestoring, setIsRestoring] = createSignal(false);
+
+ return {
+ getIsRestoring,
+ async restore({ document }: { document: Document }) {
+ setIsRestoring(true);
+
+ await restoreDocument({
+ documentId: document.id,
+ organizationId: document.organizationId,
+ });
+
+ await queryClient.invalidateQueries({ queryKey: ['organizations', document.organizationId, 'documents'] });
+
+ createToast({ type: 'success', message: 'Document restored' });
+ setIsRestoring(false);
+ },
+ };
+}
diff --git a/apps/papra-client/src/modules/documents/documents.types.ts b/apps/papra-client/src/modules/documents/documents.types.ts
index 9ff0fa20..01ab6b58 100644
--- a/apps/papra-client/src/modules/documents/documents.types.ts
+++ b/apps/papra-client/src/modules/documents/documents.types.ts
@@ -6,6 +6,7 @@ export type Document = {
originalSize: number;
createdAt: Date;
updatedAt?: Date;
+ isDeleted?: boolean;
deletedAt?: Date;
deletedBy?: string;
};
diff --git a/apps/papra-client/src/modules/documents/pages/deleted-documents.page.tsx b/apps/papra-client/src/modules/documents/pages/deleted-documents.page.tsx
index 66bb7a6f..170769ce 100644
--- a/apps/papra-client/src/modules/documents/pages/deleted-documents.page.tsx
+++ b/apps/papra-client/src/modules/documents/pages/deleted-documents.page.tsx
@@ -1,36 +1,26 @@
import type { Document } from '../documents.types';
import { useConfig } from '@/modules/config/config.provider';
import { timeAgo } from '@/modules/shared/date/time-ago';
-import { queryClient } from '@/modules/shared/query/query-client';
import { Alert, AlertDescription } from '@/modules/ui/components/alert';
import { Button } from '@/modules/ui/components/button';
-import { createToast } from '@/modules/ui/components/sonner';
import { useParams } from '@solidjs/router';
import { createQuery, keepPreviousData } from '@tanstack/solid-query';
import { type Component, createSignal, Show, Suspense } from 'solid-js';
import { DocumentsPaginatedList } from '../components/documents-list.component';
-import { fetchOrganizationDeletedDocuments, restoreDocument } from '../documents.services';
+import { useRestoreDocument } from '../documents.composables';
+import { fetchOrganizationDeletedDocuments } from '../documents.services';
const RestoreDocumentButton: Component<{ document: Document }> = (props) => {
- const [getIsLoading, setIsLoading] = createSignal(false);
-
- const restore = async ({ document }: { document: Document }) => {
- setIsLoading(true);
-
- await restoreDocument({
- documentId: document.id,
- organizationId: document.organizationId,
- });
-
- await queryClient.invalidateQueries({ queryKey: ['organizations', document.organizationId, 'documents'] });
-
- createToast({ type: 'success', message: 'Document restored' });
- setIsLoading(false);
- };
+ const { getIsRestoring, restore } = useRestoreDocument();
return (
- <Button variant="outline" size="sm" onClick={() => restore({ document: props.document })} isLoading={getIsLoading()}>
- { getIsLoading()
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => restore({ document: props.document })}
+ isLoading={getIsRestoring()}
+ >
+ { getIsRestoring()
? (<>Restoring...</>)
: (
<>
diff --git a/apps/papra-client/src/modules/documents/pages/document.page.tsx b/apps/papra-client/src/modules/documents/pages/document.page.tsx
index 1fd6d686..da94ebbc 100644
--- a/apps/papra-client/src/modules/documents/pages/document.page.tsx
+++ b/apps/papra-client/src/modules/documents/pages/document.page.tsx
@@ -1,10 +1,16 @@
+import { useConfig } from '@/modules/config/config.provider';
import { timeAgo } from '@/modules/shared/date/time-ago';
import { downloadFile } from '@/modules/shared/files/download';
+import { Alert } from '@/modules/ui/components/alert';
import { Button } from '@/modules/ui/components/button';
-import { useParams } from '@solidjs/router';
+import { Separator } from '@/modules/ui/components/separator';
+import { formatBytes } from '@corentinth/chisels';
+import { useNavigate, useParams } from '@solidjs/router';
import { createQueries } from '@tanstack/solid-query';
import { type Component, type JSX, Show, Suspense } from 'solid-js';
import { DocumentPreview } from '../components/document-preview.component';
+import { getDaysBeforePermanentDeletion } from '../document.models';
+import { useDeleteDocument, useRestoreDocument } from '../documents.composables';
import { fetchDocument, fetchDocumentFile } from '../documents.services';
import '@pdfslick/solid/dist/pdf_viewer.css';
@@ -34,6 +40,10 @@ const KeyValues: Component<{ data?: KeyValueItem[] }> = (props) => {
export const DocumentPage: Component = () => {
const params = useParams();
+ const { deleteDocument } = useDeleteDocument();
+ const { restore, getIsRestoring } = useRestoreDocument();
+ const navigate = useNavigate();
+ const { config } = useConfig();
const queries = createQueries(() => ({
queries: [
@@ -48,29 +58,94 @@ export const DocumentPage: Component = () => {
],
}));
+ const deleteDoc = async () => {
+ if (!queries[0].data) {
+ return;
+ }
+
+ const { hasDeleted } = await deleteDocument({
+ documentId: params.documentId,
+ organizationId: params.organizationId,
+ documentName: queries[0].data.document.name,
+ });
+
+ if (!hasDeleted) {
+ return;
+ }
+
+ navigate(`/organizations/${params.organizationId}/documents`);
+ };
+
const getDataUrl = () => queries[1].data ? URL.createObjectURL(queries[1].data) : undefined;
return (
<div class="p-6 flex gap-6 h-full flex-col md:flex-row max-w-7xl mx-auto">
<Suspense>
- <div class="md:flex-1">
+ <div class="md:flex-1 md:border-r">
<Show when={queries[0].data?.document}>
{getDocument => (
- <div class="flex gap-4">
+ <div class="flex gap-4 md:pr-6">
<div class="flex-1">
<h1 class="text-xl font-semibold">{getDocument().name}</h1>
<p class="text-sm text-muted-foreground mb-6">{getDocument().id}</p>
- <Button
- onClick={() => downloadFile({
- fileName: getDocument().name,
- url: getDataUrl()!,
- })}
- variant="default"
- class="mb-4"
- >
- <div class="i-tabler-download mr-2"></div>
- Download
- </Button>
+
+ <div class="flex gap-2">
+ <Button
+ onClick={() => downloadFile({ fileName: getDocument().name, url: getDataUrl()! })}
+ variant="outline"
+ size="sm"
+ >
+ <div class="i-tabler-download size-4 mr-2"></div>
+ Download
+ </Button>
+
+ <Button
+ variant="outline"
+ onClick={() => window.open(getDataUrl()!, '_blank')}
+ size="sm"
+ >
+ <div class="i-tabler-eye size-4 mr-2"></div>
+ Open in new tab
+ </Button>
+
+ {getDocument().isDeleted
+ ? (
+ <Button
+ variant="destructive"
+ size="sm"
+ onClick={() => restore({ document: getDocument() })}
+ isLoading={getIsRestoring()}
+ >
+ <div class="i-tabler-refresh size-4 mr-2"></div>
+ Restore
+ </Button>
+ )
+ : (
+ <Button
+ variant="destructive"
+ size="sm"
+ onClick={deleteDoc}
+ >
+ <div class="i-tabler-trash size-4 mr-2"></div>
+ Delete
+ </Button>
+ )}
+ </div>
+
+ {getDocument().isDeleted && (
+ <Alert variant="destructive" class="mt-6">
+ This document has been deleted and will be permanently removed in
+ {' '}
+ {getDaysBeforePermanentDeletion({
+ document: getDocument(),
+ deletedDocumentsRetentionDays: config.documents.deletedDocumentsRetentionDays,
+ })}
+ {' '}
+ days.
+ </Alert>
+ )}
+
+ <Separator class="my-6" />
<KeyValues data={[
{
@@ -81,7 +156,17 @@ export const DocumentPage: Component = () => {
{
label: 'Name',
value: getDocument().name,
- icon: 'i-tabler-file',
+ icon: 'i-tabler-file-text',
+ },
+ {
+ label: 'Type',
+ value: getDocument().mimeType,
+ icon: 'i-tabler-file-unknown',
+ },
+ {
+ label: 'Size',
+ value: formatBytes({ bytes: getDocument().originalSize, base: 1000 }),
+ icon: 'i-tabler-weight',
},
{
label: 'Created At',