Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(documents): added document soft-deletion (#7)

Corentin THOMASSET09051187c4a4
diff --git a/apps/papra-client/src/app.css b/apps/papra-client/src/app.css
index ca101c77..535420f6 100644
--- a/apps/papra-client/src/app.css
+++ b/apps/papra-client/src/app.css
@@ -40,7 +40,7 @@
--card: 240 4% 8%;
--card-foreground: 0 0% 98%;
- --popover: 0 0% 3.9%;
+ --popover: 240 4% 8%;
--popover-foreground: 0 0% 98%;
--primary: 256 100% 73%;
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
new file mode 100644
index 00000000..0ace249c
--- /dev/null
+++ b/apps/papra-client/src/modules/documents/components/document-management-dropdown.component.tsx
@@ -0,0 +1,50 @@
+import type { DropdownMenuSubTriggerProps } from '@kobalte/core/dropdown-menu';
+import type { Component } from 'solid-js';
+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 { toast } from '@/modules/ui/components/sonner';
+import { A } from '@solidjs/router';
+import { deleteDocument } from '../documents.services';
+
+export const DocumentManagementDropdown: Component<{ documentId: string; organizationId: string }> = (props) => {
+ const deleteDoc = async () => {
+ await deleteDocument({
+ documentId: props.documentId,
+ organizationId: props.organizationId,
+ });
+
+ await queryClient.invalidateQueries({ queryKey: ['organizations', props.organizationId, 'documents'] });
+ toast.success('Document deleted');
+ };
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ as={(props: DropdownMenuSubTriggerProps) => (
+ <Button variant="ghost" size="icon" {...props}>
+ <div class="i-tabler-dots-vertical size-4"></div>
+ </Button>
+ )}
+ />
+ <DropdownMenuContent class="w-48">
+ <DropdownMenuItem
+ class="cursor-pointer "
+ as={A}
+ href={`/organizations/${props.organizationId}/documents/${props.documentId}`}
+ >
+ <div class="i-tabler-info-circle size-4 mr-2"></div>
+ <span>Document details</span>
+ </DropdownMenuItem>
+
+ <DropdownMenuItem
+ class="cursor-pointer text-red"
+ onClick={() => deleteDoc()}
+ >
+ <div class="i-tabler-trash size-4 mr-2"></div>
+ <span>Delete document</span>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+};
diff --git a/apps/papra-client/src/modules/documents/components/documents-paginated-list.component.tsx b/apps/papra-client/src/modules/documents/components/documents-paginated-list.component.tsx
new file mode 100644
index 00000000..cad53ce8
--- /dev/null
+++ b/apps/papra-client/src/modules/documents/components/documents-paginated-list.component.tsx
@@ -0,0 +1,234 @@
+import type { TooltipTriggerProps } from '@kobalte/core/tooltip';
+import { timeAgo } from '@/modules/shared/date/time-ago';
+import { cn } from '@/modules/shared/style/cn';
+import { Button } from '@/modules/ui/components/button';
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/modules/ui/components/select';
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/modules/ui/components/table';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@/modules/ui/components/tooltip';
+import { formatBytes } from '@corentinth/chisels';
+import { A } from '@solidjs/router';
+import { createQuery, keepPreviousData } from '@tanstack/solid-query';
+import { createSolidTable, flexRender, getCoreRowModel, getPaginationRowModel } from '@tanstack/solid-table';
+import { type Component, createSignal, For, Match, Show, Switch } from 'solid-js';
+import { getDocumentIcon } from '../document.models';
+import { fetchOrganizationDocuments } from '../documents.services';
+import { DocumentManagementDropdown } from './document-management-dropdown.component';
+
+export const DocumentsPaginatedList: Component<{ organizationId: string }> = (props) => {
+ const [getPagination, setPagination] = createSignal({ pageIndex: 0, pageSize: 100 });
+
+ const query = createQuery(() => ({
+ queryKey: ['organizations', props.organizationId, 'documents', getPagination()],
+ queryFn: () => fetchOrganizationDocuments({
+ organizationId: props.organizationId,
+ ...getPagination(),
+ }),
+ placeholderData: keepPreviousData,
+ }));
+
+ const table = createSolidTable({
+ get data() {
+ return query.data?.documents ?? [];
+ },
+ columns: [
+ {
+ header: 'File name',
+ cell: data => (
+ <div class="overflow-hidden flex gap-4 items-center">
+ <div class="bg-muted flex items-center justify-center p-2 rounded-lg">
+ <div class={cn(getDocumentIcon({ document: data.row.original }), 'size-6 text-muted-foreground')}></div>
+ </div>
+
+ <div class="flex-1 flex flex-col gap-1 truncate">
+ <A
+ href={`/organizations/${props.organizationId}/documents/${data.row.original.id}`}
+ class="font-bold truncate block hover:underline"
+ >
+ {data.row.original.name.split('.').shift()}
+ </A>
+
+ <div class="text-xs text-muted-foreground lh-tight">
+ {formatBytes({ bytes: data.row.original.size, base: 1000 })}
+ {' '}
+ -
+ {' '}
+ {data.row.original.name.split('.').pop()?.toUpperCase()}
+ {' '}
+ -
+ {' '}
+ <Tooltip>
+ <TooltipTrigger as={(tooltipProps: TooltipTriggerProps) => (
+ <span {...tooltipProps}>
+ {timeAgo({ date: data.row.original.createdAt })}
+ </span>
+ )}
+ />
+ <TooltipContent>
+ {data.row.original.createdAt.toLocaleString()}
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ </div>
+ </div>
+
+ ),
+ },
+ {
+ header: 'Created at',
+ accessorKey: 'createdAt',
+ cell: data => <div class="text-muted-foreground" title={data.getValue<Date>().toLocaleString()}>{timeAgo({ date: data.getValue<Date>() })}</div>,
+ },
+ {
+ header: 'Actions',
+ cell: data => (
+ <div class="flex items-center justify-end">
+ <DocumentManagementDropdown documentId={data.row.original.id} organizationId={props.organizationId} />
+ </div>
+ ),
+ },
+ ],
+ get rowCount() {
+ return query.data?.documentsCount;
+ },
+ getCoreRowModel: getCoreRowModel(),
+ getPaginationRowModel: getPaginationRowModel(),
+ onPaginationChange: setPagination,
+ state: {
+ get pagination() {
+ return getPagination();
+ },
+ },
+ manualPagination: true,
+
+ });
+
+ return (
+ <div>
+ <Switch>
+ <Match when={query.data?.documentsCount === 0}>
+ <p>No documents found</p>
+ </Match>
+ <Match when={query.isError}>
+ <p>
+ Error:
+ {query.error?.message}
+ </p>
+ </Match>
+ <Match when={query.isSuccess}>
+ <Table>
+
+ <TableHeader>
+ <For each={table.getHeaderGroups()}>
+ {headerGroup => (
+ <TableRow>
+ <For each={headerGroup.headers}>
+ {(header) => {
+ return (
+ <TableHead>
+ {header.isPlaceholder
+ ? null
+ : flexRender(header.column.columnDef.header, header.getContext())}
+ </TableHead>
+ );
+ }}
+ </For>
+ </TableRow>
+ )}
+ </For>
+ </TableHeader>
+
+ <TableBody>
+ <Show when={table.getRowModel().rows?.length}>
+ <For each={table.getRowModel().rows}>
+ {row => (
+ <TableRow data-state={row.getIsSelected() && 'selected'}>
+ <For each={row.getVisibleCells()}>
+ {cell => (
+ <TableCell>
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
+ </TableCell>
+ )}
+ </For>
+ </TableRow>
+ )}
+ </For>
+ </Show>
+ </TableBody>
+
+ </Table>
+
+ <div class="flex flex-col-reverse items-center gap-4 sm:flex-row sm:justify-end mt-4">
+ <div class="flex items-center space-x-2">
+ <p class="whitespace-nowrap text-sm font-medium">Rows per page</p>
+ <Select
+ value={table.getState().pagination.pageSize}
+ onChange={value => value && table.setPageSize(value)}
+ options={[15, 50, 100]}
+ itemComponent={props => (
+ <SelectItem item={props.item}>{props.item.rawValue}</SelectItem>
+ )}
+ >
+ <SelectTrigger class="h-8 w-[4.5rem]">
+ <SelectValue<string>>
+ {state => state.selectedOption()}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent />
+ </Select>
+ </div>
+ <div class="flex items-center justify-center whitespace-nowrap text-sm font-medium">
+ Page
+ {' '}
+ {table.getState().pagination.pageIndex + 1}
+ {' '}
+ of
+ {' '}
+ {table.getPageCount()}
+ </div>
+ <div class="flex items-center space-x-2">
+ <Button
+ aria-label="Go to first page"
+ variant="outline"
+ class="flex size-8 p-0"
+ onClick={() => table.setPageIndex(0)}
+ disabled={!table.getCanPreviousPage()}
+ >
+ <div class="size-4 i-tabler-chevrons-left" />
+ </Button>
+ <Button
+ aria-label="Go to previous page"
+ variant="outline"
+ size="icon"
+ class="size-8"
+ onClick={() => table.previousPage()}
+ disabled={!table.getCanPreviousPage()}
+ >
+ <div class="size-4 i-tabler-chevron-left" />
+ </Button>
+ <Button
+ aria-label="Go to next page"
+ variant="outline"
+ size="icon"
+ class="size-8"
+ onClick={() => table.nextPage()}
+ disabled={!table.getCanNextPage()}
+ >
+ <div class="size-4 i-tabler-chevron-right" />
+ </Button>
+ <Button
+ aria-label="Go to last page"
+ variant="outline"
+ size="icon"
+ class="flex size-8"
+ onClick={() => table.setPageIndex(table.getPageCount() - 1)}
+ disabled={!table.getCanNextPage()}
+ >
+ <div class="size-4 i-tabler-chevrons-right" />
+ </Button>
+ </div>
+ </div>
+ </Match>
+ </Switch>
+ </div>
+ );
+};
diff --git a/apps/papra-client/src/modules/documents/documents.services.ts b/apps/papra-client/src/modules/documents/documents.services.ts
index e4d90f31..bb9059b2 100644
--- a/apps/papra-client/src/modules/documents/documents.services.ts
+++ b/apps/papra-client/src/modules/documents/documents.services.ts
@@ -35,7 +35,10 @@ export async function fetchOrganizationDocuments({
pageIndex: number;
pageSize: number;
}) {
- const { documents } = await apiClient<{ documents: Document[] }>({
+ const {
+ documents,
+ documentsCount,
+ } = await apiClient<{ documents: Document[]; documentsCount: number }>({
method: 'GET',
path: `/api/organizations/${organizationId}/documents`,
queryParams: {
@@ -45,6 +48,7 @@ export async function fetchOrganizationDocuments({
});
return {
+ documentsCount,
documents: documents.map(document => ({
...document,
createdAt: new Date(document.createdAt),
@@ -52,3 +56,37 @@ export async function fetchOrganizationDocuments({
})),
};
}
+
+export async function deleteDocument({
+ documentId,
+ organizationId,
+}: {
+ documentId: string;
+ organizationId: string;
+}) {
+ await apiClient({
+ method: 'DELETE',
+ path: `/api/organizations/${organizationId}/documents/${documentId}`,
+ });
+}
+
+export async function getDocument({
+ documentId,
+ organizationId,
+}: {
+ documentId: string;
+ organizationId: string;
+}) {
+ const { document } = await apiClient<{ document: Document }>({
+ method: 'GET',
+ path: `/api/organizations/${organizationId}/documents/${documentId}`,
+ });
+
+ return {
+ document: {
+ ...document,
+ createdAt: new Date(document.createdAt),
+ updatedAt: document.updatedAt ? new Date(document.updatedAt) : undefined,
+ },
+ };
+}
diff --git a/apps/papra-client/src/modules/documents/pages/documents.page.tsx b/apps/papra-client/src/modules/documents/pages/documents.page.tsx
index 8370333c..60bde380 100644
--- a/apps/papra-client/src/modules/documents/pages/documents.page.tsx
+++ b/apps/papra-client/src/modules/documents/pages/documents.page.tsx
@@ -1,17 +1,68 @@
import type { TooltipTriggerProps } from '@kobalte/core/tooltip';
+import type { Component } from 'solid-js';
+import type { Document } from '../documents.types';
import { timeAgo } from '@/modules/shared/date/time-ago';
import { cn } from '@/modules/shared/style/cn';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/modules/ui/components/tooltip';
import { formatBytes } from '@corentinth/chisels';
import { A, useParams } from '@solidjs/router';
-import { createQueries, keepPreviousData } from '@tanstack/solid-query';
-import { type Component, createSignal } from 'solid-js';
+import { createQueries } from '@tanstack/solid-query';
+import { DocumentManagementDropdown } from '../components/document-management-dropdown.component';
import { DocumentUploadArea } from '../components/document-upload-area.component';
+import { DocumentsPaginatedList } from '../components/documents-paginated-list.component';
import { getDocumentIcon } from '../document.models';
import { fetchOrganizationDocuments } from '../documents.services';
+const DocumentCard: Component<{ document: Document; organizationId?: string }> = (props) => {
+ const params = useParams();
+
+ const getOrganizationId = () => props.organizationId ?? params.organizationId;
+
+ return (
+ <div class="border rounded-lg overflow-hidden flex gap-4 p-3 pr-2 items-center">
+ <div class="bg-muted flex items-center justify-center p-2 rounded-lg">
+ <div class={cn(getDocumentIcon({ document: props.document }), 'size-6 text-muted-foreground')}></div>
+ </div>
+
+ <div class="flex-1 flex flex-col gap-1 truncate">
+ <A
+ href={`/organizations/${getOrganizationId()}/documents/${props.document.id}`}
+ class="font-bold truncate block hover:underline"
+ >
+ {props.document.name.split('.').shift()}
+ </A>
+
+ <div class="text-xs text-muted-foreground lh-tight">
+ {formatBytes({ bytes: props.document.size, base: 1000 })}
+ {' '}
+ -
+ {' '}
+ {props.document.name.split('.').pop()?.toUpperCase()}
+ {' '}
+ -
+ {' '}
+ <Tooltip>
+ <TooltipTrigger as={(tooltipProps: TooltipTriggerProps) => (
+ <span {...tooltipProps}>
+ {timeAgo({ date: props.document.createdAt })}
+ </span>
+ )}
+ />
+ <TooltipContent>
+ {props.document.createdAt.toLocaleString()}
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ </div>
+
+ <div>
+ <DocumentManagementDropdown documentId={props.document.id} organizationId={getOrganizationId()} />
+ </div>
+ </div>
+ );
+};
+
export const DocumentsPage: Component = () => {
- const [getPagination] = createSignal({ pageIndex: 0, pageSize: 100 });
const params = useParams();
const query = createQueries(() => ({
@@ -20,16 +71,9 @@ export const DocumentsPage: Component = () => {
queryKey: ['organizations', params.organizationId, 'documents', { pageIndex: 0, pageSize: 100 }],
queryFn: () => fetchOrganizationDocuments({
organizationId: params.organizationId,
- ...getPagination(),
- }),
- },
- {
- queryKey: ['organizations', params.organizationId, 'documents', getPagination()],
- queryFn: () => fetchOrganizationDocuments({
- organizationId: params.organizationId,
- ...getPagination(),
+ pageIndex: 0,
+ pageSize: 5,
}),
- placeholderData: keepPreviousData,
},
],
}));
@@ -59,45 +103,15 @@ export const DocumentsPage: Component = () => {
</h2>
<div class="grid gap-4 grid-cols-1 lg:grid-cols-3 xl:grid-cols-4">
{query[0].data?.documents.map(document => (
- <div class="border rounded-lg overflow-hidden flex gap-4 p-3 items-center">
- <div class="bg-muted flex items-center justify-center p-2 rounded-lg">
- <div class={cn(getDocumentIcon({ document }), 'size-6 text-muted-foreground')}></div>
- </div>
-
- <div class="flex-1 flex flex-col gap-1 truncate">
- <A
- href={`/organizations/${params.organizationId}/documents/${document.id}`}
- class="text-xs font-bold truncate block hover:underline"
- >
- {document.name.split('.').shift()}
- </A>
-
- <div class="text-xs text-muted-foreground lh-none">
- {formatBytes({ bytes: document.size, base: 1000 })}
- {' '}
- -
- {' '}
- {document.name.split('.').pop()?.toUpperCase()}
- {' '}
- -
- {' '}
- <Tooltip>
- <TooltipTrigger as={(props: TooltipTriggerProps) => (
- <span {...props}>
- {timeAgo({ date: document.createdAt })}
- </span>
- )}
- />
- <TooltipContent>
- {document.createdAt.toLocaleString()}
- </TooltipContent>
- </Tooltip>
- </div>
- </div>
- </div>
+ <DocumentCard document={document} />
))}
-
</div>
+
+ <h2 class="text-lg font-semibold mt-8 mb-2">
+ All documents
+ </h2>
+
+ <DocumentsPaginatedList organizationId={params.organizationId} />
</>
)}
diff --git a/apps/papra-server/migrations/0001_fine_raza.sql b/apps/papra-server/migrations/0001_fine_raza.sql
new file mode 100644
index 00000000..a68ed3fc
--- /dev/null
+++ b/apps/papra-server/migrations/0001_fine_raza.sql
@@ -0,0 +1,20 @@
+DROP INDEX "token_index";--> statement-breakpoint
+DROP INDEX "expires_at_index";--> statement-breakpoint
+DROP INDEX "token_user_id_expires_at_index";--> statement-breakpoint
+DROP INDEX "role_index";--> statement-breakpoint
+DROP INDEX "user_roles_user_id_role_key";--> statement-breakpoint
+DROP INDEX "users_email_unique";--> statement-breakpoint
+DROP INDEX "email_index";--> statement-breakpoint
+ALTER TABLE `documents` ALTER COLUMN "original_size" TO "original_size" integer NOT NULL;--> statement-breakpoint
+CREATE INDEX `token_index` ON `auth_tokens` (`token`);--> statement-breakpoint
+CREATE INDEX `expires_at_index` ON `auth_tokens` (`expires_at`);--> statement-breakpoint
+CREATE INDEX `token_user_id_expires_at_index` ON `auth_tokens` (`token`,`user_id`,`expires_at`);--> statement-breakpoint
+CREATE INDEX `role_index` ON `user_roles` (`role`);--> statement-breakpoint
+CREATE UNIQUE INDEX `user_roles_user_id_role_key` ON `user_roles` (`user_id`,`role`);--> statement-breakpoint
+CREATE UNIQUE INDEX `users_email_unique` ON `users` (`email`);--> statement-breakpoint
+CREATE INDEX `email_index` ON `users` (`email`);--> statement-breakpoint
+ALTER TABLE `documents` ALTER COLUMN "original_size" TO "original_size" integer NOT NULL DEFAULT 0;--> statement-breakpoint
+ALTER TABLE `documents` ALTER COLUMN "size" TO "size" integer NOT NULL;--> statement-breakpoint
+ALTER TABLE `documents` ALTER COLUMN "size" TO "size" integer NOT NULL DEFAULT 0;--> statement-breakpoint
+ALTER TABLE `documents` ADD `storage_key` text NOT NULL;--> statement-breakpoint
+ALTER TABLE `documents` DROP COLUMN `original_checksum`;
\ No newline at end of file
diff --git a/apps/papra-server/migrations/meta/0001_snapshot.json b/apps/papra-server/migrations/meta/0001_snapshot.json
new file mode 100644
index 00000000..286a0689
--- /dev/null
+++ b/apps/papra-server/migrations/meta/0001_snapshot.json
@@ -0,0 +1,513 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "1c84dab4-216c-4dfb-bcc9-a73b6be8290d",
+ "prevId": "daf25e46-2a4b-462a-8488-04778b929104",
+ "tables": {
+ "auth_tokens": {
+ "name": "auth_tokens",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "token_index": {
+ "name": "token_index",
+ "columns": [
+ "token"
+ ],
+ "isUnique": false
+ },
+ "expires_at_index": {
+ "name": "expires_at_index",
+ "columns": [
+ "expires_at"
+ ],
+ "isUnique": false
+ },
+ "token_user_id_expires_at_index": {
+ "name": "token_user_id_expires_at_index",
+ "columns": [
+ "token",
+ "user_id",
+ "expires_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "auth_tokens_user_id_users_id_fk": {
+ "name": "auth_tokens_user_id_users_id_fk",
+ "tableFrom": "auth_tokens",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "documents": {
+ "name": "documents",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_deleted": {
+ "name": "is_deleted",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "deleted_by": {
+ "name": "deleted_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "original_name": {
+ "name": "original_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "original_size": {
+ "name": "original_size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "storage_key": {
+ "name": "storage_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "size": {
+ "name": "size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "mime_type": {
+ "name": "mime_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "documents_organization_id_organizations_id_fk": {
+ "name": "documents_organization_id_organizations_id_fk",
+ "tableFrom": "documents",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ },
+ "documents_created_by_users_id_fk": {
+ "name": "documents_created_by_users_id_fk",
+ "tableFrom": "documents",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "cascade"
+ },
+ "documents_deleted_by_users_id_fk": {
+ "name": "documents_deleted_by_users_id_fk",
+ "tableFrom": "documents",
+ "tableTo": "users",
+ "columnsFrom": [
+ "deleted_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "organization_users": {
+ "name": "organization_users",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'member'"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "organization_users_user_id_users_id_fk": {
+ "name": "organization_users_user_id_users_id_fk",
+ "tableFrom": "organization_users",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ },
+ "organization_users_organization_id_organizations_id_fk": {
+ "name": "organization_users_organization_id_organizations_id_fk",
+ "tableFrom": "organization_users",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "organizations": {
+ "name": "organizations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "user_roles": {
+ "name": "user_roles",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "role_index": {
+ "name": "role_index",
+ "columns": [
+ "role"
+ ],
+ "isUnique": false
+ },
+ "user_roles_user_id_role_key": {
+ "name": "user_roles_user_id_role_key",
+ "columns": [
+ "user_id",
+ "role"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "user_roles_user_id_users_id_fk": {
+ "name": "user_roles_user_id_users_id_fk",
+ "tableFrom": "user_roles",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "users": {
+ "name": "users",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "full_name": {
+ "name": "full_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "users_email_unique": {
+ "name": "users_email_unique",
+ "columns": [
+ "email"
+ ],
+ "isUnique": true
+ },
+ "email_index": {
+ "name": "email_index",
+ "columns": [
+ "email"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
diff --git a/apps/papra-server/migrations/meta/_journal.json b/apps/papra-server/migrations/meta/_journal.json
index 98ed71be..7226607d 100644
--- a/apps/papra-server/migrations/meta/_journal.json
+++ b/apps/papra-server/migrations/meta/_journal.json
@@ -8,6 +8,13 @@
"when": 1735830695548,
"tag": "0000_colossal_talon",
"breakpoints": true
+ },
+ {
+ "idx": 1,
+ "version": "6",
+ "when": 1735999064544,
+ "tag": "0001_fine_raza",
+ "breakpoints": true
}
]
}
diff --git a/apps/papra-server/src/modules/app/database/database.test-utils.ts b/apps/papra-server/src/modules/app/database/database.test-utils.ts
index 378ffb1e..20b29412 100644
--- a/apps/papra-server/src/modules/app/database/database.test-utils.ts
+++ b/apps/papra-server/src/modules/app/database/database.test-utils.ts
@@ -1,5 +1,6 @@
import type { Database } from './database.types';
import { migrate } from 'drizzle-orm/libsql/migrator';
+import { organizationsTable, organizationUsersTable } from '../../organizations/organizations.table';
import { usersTable } from '../../users/users.table';
import { setupDatabase } from './database';
@@ -20,11 +21,17 @@ async function createInMemoryDatabase(seedOptions: Omit<Parameters<typeof seedDa
async function seedDatabase({
db,
users,
+ organizations,
+ organizationUsers,
}: {
db: Database;
users?: typeof usersTable.$inferInsert[];
+ organizations?: typeof organizationsTable.$inferInsert[];
+ organizationUsers?: typeof organizationUsersTable.$inferInsert[];
}) {
await Promise.all([
users && db.insert(usersTable).values(users).execute(),
+ organizations && db.insert(organizationsTable).values(organizations).execute(),
+ organizationUsers && db.insert(organizationUsersTable).values(organizationUsers).execute(),
]);
}
diff --git a/apps/papra-server/src/modules/documents/documents.repository.test.ts b/apps/papra-server/src/modules/documents/documents.repository.test.ts
new file mode 100644
index 00000000..957eec15
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/documents.repository.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, test } from 'vitest';
+import { createInMemoryDatabase } from '../app/database/database.test-utils';
+import { createDocumentsRepository } from './documents.repository';
+
+describe('documents repository', () => {
+ describe('crud operations on document collection', () => {
+ test('a document can be created, retrieved, and soft deleted', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'user-1', email: '[email protected]' }],
+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],
+ organizationUsers: [{ organizationId: 'organization-1', userId: 'user-1' }],
+ });
+
+ const documentsRepository = createDocumentsRepository({ db });
+
+ const { document } = await documentsRepository.saveOrganizationDocument({
+ organizationId: 'organization-1',
+ createdBy: 'user-1',
+ mimeType: 'application/pdf',
+ name: 'Document 1',
+ originalName: 'document-1.pdf',
+ storageKey: 'document-1.pdf',
+ });
+
+ expect(document).to.include({
+ organizationId: 'organization-1',
+ createdBy: 'user-1',
+ mimeType: 'application/pdf',
+ name: 'Document 1',
+ originalName: 'document-1.pdf',
+ storageKey: 'document-1.pdf',
+ isDeleted: false,
+ });
+
+ const { documents } = await documentsRepository.getOrganizationDocuments({
+ organizationId: 'organization-1',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(documents).to.have.length(1);
+ expect(documents[0]).to.include({
+ organizationId: 'organization-1',
+ createdBy: 'user-1',
+ mimeType: 'application/pdf',
+ name: 'Document 1',
+ originalName: 'document-1.pdf',
+ storageKey: 'document-1.pdf',
+ isDeleted: false,
+ });
+
+ await documentsRepository.softDeleteDocument({
+ documentId: document.id,
+ userId: 'user-1',
+ });
+
+ const { documents: documentsAfterDelete } = await documentsRepository.getOrganizationDocuments({
+ organizationId: 'organization-1',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(documentsAfterDelete).to.have.length(0);
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/documents/documents.repository.ts b/apps/papra-server/src/modules/documents/documents.repository.ts
index 392e1c3f..dcc69de8 100644
--- a/apps/papra-server/src/modules/documents/documents.repository.ts
+++ b/apps/papra-server/src/modules/documents/documents.repository.ts
@@ -1,7 +1,7 @@
import type { Database } from '../app/database/database.types';
import type { DbInsertableDocument } from './documents.types';
import { injectArguments } from '@corentinth/chisels';
-import { desc, eq } from 'drizzle-orm';
+import { and, count, desc, eq } from 'drizzle-orm';
import { withPagination } from '../shared/db/pagination';
import { documentsTable } from './documents.table';
@@ -12,6 +12,9 @@ export function createDocumentsRepository({ db }: { db: Database }) {
{
saveOrganizationDocument,
getOrganizationDocuments,
+ getDocumentById,
+ softDeleteDocument,
+ getOrganizationDocumentsCount,
},
{ db },
);
@@ -23,11 +26,29 @@ async function saveOrganizationDocument({ db, ...documentToInsert }: { db: Datab
return { document };
}
+async function getOrganizationDocumentsCount({ organizationId, db }: { organizationId: string; db: Database }) {
+ const [{ documentsCount }] = await db
+ .select({
+ documentsCount: count(),
+ })
+ .from(documentsTable)
+ .where(
+ eq(documentsTable.organizationId, organizationId),
+ );
+
+ return { documentsCount };
+}
+
async function getOrganizationDocuments({ organizationId, pageIndex, pageSize, db }: { organizationId: string; pageIndex: number; pageSize: number; db: Database }) {
const query = db
.select()
.from(documentsTable)
- .where(eq(documentsTable.organizationId, organizationId));
+ .where(
+ and(
+ eq(documentsTable.organizationId, organizationId),
+ eq(documentsTable.isDeleted, false),
+ ),
+ );
const documents = await withPagination(
query.$dynamic(),
@@ -42,3 +63,25 @@ async function getOrganizationDocuments({ organizationId, pageIndex, pageSize, d
documents,
};
}
+
+async function getDocumentById({ documentId, db }: { documentId: string; db: Database }) {
+ const [document] = await db
+ .select()
+ .from(documentsTable)
+ .where(eq(documentsTable.id, documentId));
+
+ return {
+ document,
+ };
+}
+
+async function softDeleteDocument({ documentId, userId, db, now = new Date() }: { documentId: string; userId: string; db: Database; now?: Date }) {
+ await db
+ .update(documentsTable)
+ .set({
+ isDeleted: true,
+ deletedBy: userId,
+ deletedAt: now,
+ })
+ .where(eq(documentsTable.id, documentId));
+}
diff --git a/apps/papra-server/src/modules/documents/documents.routes.ts b/apps/papra-server/src/modules/documents/documents.routes.ts
index 96f59cae..ba03287e 100644
--- a/apps/papra-server/src/modules/documents/documents.routes.ts
+++ b/apps/papra-server/src/modules/documents/documents.routes.ts
@@ -15,6 +15,8 @@ import { createDocumentStorageService } from './storage/documents.storage.servic
export function registerDocumentsPrivateRoutes({ app }: { app: ServerInstance }) {
setupCreateDocumentRoute({ app });
setupGetDocumentsRoute({ app });
+ setupGetDocumentRoute({ app });
+ setupDeleteDocumentRoute({ app });
}
function setupCreateDocumentRoute({ app }: { app: ServerInstance }) {
@@ -118,10 +120,87 @@ function setupGetDocumentsRoute({ app }: { app: ServerInstance }) {
});
}
- const { documents } = await documentsRepository.getOrganizationDocuments({ organizationId, pageIndex, pageSize });
+ const [
+ { documents },
+ { documentsCount },
+ ] = await Promise.all([
+ documentsRepository.getOrganizationDocuments({ organizationId, pageIndex, pageSize }),
+ documentsRepository.getOrganizationDocumentsCount({ organizationId }),
+ ]);
return context.json({
documents,
+ documentsCount,
+ });
+ },
+ );
+}
+
+function setupGetDocumentRoute({ app }: { app: ServerInstance }) {
+ app.get(
+ '/api/organizations/:organizationId/documents/:documentId',
+ validateParams(z.object({
+ organizationId: z.string().regex(organizationIdRegex),
+ documentId: z.string(),
+ })),
+ async (context) => {
+ const { userId } = getAuthUserId({ context });
+ const { db } = getDb({ context });
+
+ const { organizationId, documentId } = context.req.valid('param');
+
+ const documentsRepository = createDocumentsRepository({ db });
+ const organizationsRepository = createOrganizationsRepository({ db });
+
+ const { isInOrganization } = await organizationsRepository.isUserInOrganization({ userId, organizationId });
+
+ if (!isInOrganization) {
+ throw createError({
+ message: 'You are not part of this organization.',
+ code: 'user.not_in_organization',
+ statusCode: 403,
+ });
+ }
+
+ const { document } = await documentsRepository.getDocumentById({ documentId });
+
+ return context.json({
+ document,
+ });
+ },
+ );
+}
+
+function setupDeleteDocumentRoute({ app }: { app: ServerInstance }) {
+ app.delete(
+ '/api/organizations/:organizationId/documents/:documentId',
+ validateParams(z.object({
+ organizationId: z.string().regex(organizationIdRegex),
+ documentId: z.string(),
+ })),
+ async (context) => {
+ const { userId } = getAuthUserId({ context });
+ const { db } = getDb({ context });
+
+ const { organizationId, documentId } = context.req.valid('param');
+
+ const documentsRepository = createDocumentsRepository({ db });
+ const organizationsRepository = createOrganizationsRepository({ db });
+
+ const { isInOrganization } = await organizationsRepository.isUserInOrganization({ userId, organizationId });
+
+ if (!isInOrganization) {
+ throw createError({
+ message: 'You are not part of this organization.',
+ code: 'user.not_in_organization',
+ statusCode: 403,
+ });
+ }
+
+ await documentsRepository.softDeleteDocument({ documentId, userId });
+
+ return context.json({
+ success: true,
});
},
);