Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(documents): add stored queries views (#960)

Anbratenf4b361ed79e5
diff --git a/.changeset/breezy-seas-beg.md b/.changeset/breezy-seas-beg.md
new file mode 100644
index 00000000..4f70bbab
--- /dev/null
+++ b/.changeset/breezy-seas-beg.md
@@ -0,0 +1,5 @@
+---
+"@papra/app": minor
+---
+
+Added the ability to save search queries as views, allowing quick access to frequently used searches. Saved views can be accessed from the sidebar.
diff --git a/apps/papra-client/src/locales/en.dictionary.ts b/apps/papra-client/src/locales/en.dictionary.ts
index 9b987d42..71d3e699 100644
--- a/apps/papra-client/src/locales/en.dictionary.ts
+++ b/apps/papra-client/src/locales/en.dictionary.ts
@@ -675,6 +675,38 @@ export const translations = {
'tags.picker.create-new-with-name': 'Create new tag "{{ name }}"',
'tags.picker.create-new': 'Create new tag',
+ // Document views
+
+ 'document-views.create': 'Create view',
+ 'document-views.save-as-view': 'Save query as view',
+ 'document-views.update': 'Update view',
+ 'document-views.delete': 'Delete view',
+ 'document-views.delete.confirm.title': 'Delete view',
+ 'document-views.delete.confirm.message': 'Are you sure you want to delete this view?',
+ 'document-views.delete.confirm.confirm-button': 'Delete',
+ 'document-views.delete.confirm.cancel-button': 'Cancel',
+ 'document-views.delete.success': 'View deleted successfully',
+ 'document-views.create.success': 'View "{{ name }}" created successfully.',
+ 'document-views.update.success': 'View "{{ name }}" updated successfully.',
+ 'document-views.form.name.label': 'Name',
+ 'document-views.form.name.placeholder': 'Eg. Inbox',
+ 'document-views.form.name.required': 'Please enter a view name',
+ 'document-views.form.name.max-length': 'View name must be less than 100 characters',
+ 'document-views.form.query.label': 'Query',
+ 'document-views.form.query.placeholder': 'Eg. tag:inbox AND -tag:archived',
+ 'document-views.form.query.required': 'Please enter a query',
+ 'document-views.form.query.max-length': 'Query must be less than 500 characters',
+ 'document-views.form.query.hint': 'Use the same syntax as the document search bar. Eg. tag:inbox, has:tags, before:2024-01-01',
+ 'document-views.form.description.label': 'Description',
+ 'document-views.form.description.optional': '(optional)',
+ 'document-views.form.description.placeholder': 'Eg. Documents waiting to be processed',
+ 'document-views.form.description.max-length': 'Description must be less than 256 characters',
+ 'document-views.actions.menu': 'View actions',
+ 'document-views.view.no-documents': 'No documents match this view\'s query.',
+ 'document-views.view.not-found': 'View not found.',
+ 'api-errors.document_views.already_exists': 'A view with this name already exists for this organization',
+ 'api-errors.document_views.not_found': 'View not found',
+
// Tagging rules
'tagging-rules.field.name': 'document name',
@@ -881,6 +913,7 @@ export const translations = {
'layout.menu.intake-emails': 'Intake emails',
'layout.menu.webhooks': 'Webhooks',
'layout.menu.members': 'Members',
+ 'layout.menu.document-views': 'Views',
'layout.menu.invitations': 'Invitations',
'layout.menu.admin': 'Admin',
diff --git a/apps/papra-client/src/modules/admin/layouts/admin.layout.tsx b/apps/papra-client/src/modules/admin/layouts/admin.layout.tsx
index 9e28e85e..552e091c 100644
--- a/apps/papra-client/src/modules/admin/layouts/admin.layout.tsx
+++ b/apps/papra-client/src/modules/admin/layouts/admin.layout.tsx
@@ -10,23 +10,25 @@ import { useCurrentUser } from '@/modules/users/composables/useCurrentUser';
const AdminLayout: ParentComponent = (props) => {
const { t } = useI18n();
- const getNavigationMenu = () => [
- {
- label: t('admin.layout.menu.analytics'),
- href: '/admin/analytics',
- icon: 'i-tabler-chart-bar',
- },
- {
- label: t('admin.layout.menu.users'),
- href: '/admin/users',
- icon: 'i-tabler-users',
- },
- {
- label: t('admin.layout.menu.organizations'),
- href: '/admin/organizations',
- icon: 'i-tabler-building-community',
- },
- ];
+ const getNavigationMenu = () => [{
+ items: [
+ {
+ label: t('admin.layout.menu.analytics'),
+ href: '/admin/analytics',
+ icon: 'i-tabler-chart-bar',
+ },
+ {
+ label: t('admin.layout.menu.users'),
+ href: '/admin/users',
+ icon: 'i-tabler-users',
+ },
+ {
+ label: t('admin.layout.menu.organizations'),
+ href: '/admin/organizations',
+ icon: 'i-tabler-building-community',
+ },
+ ],
+ }];
const sidenav = () => (
<SideNav
diff --git a/apps/papra-client/src/modules/document-views/components/document-view-modals.tsx b/apps/papra-client/src/modules/document-views/components/document-view-modals.tsx
new file mode 100644
index 00000000..953c0309
--- /dev/null
+++ b/apps/papra-client/src/modules/document-views/components/document-view-modals.tsx
@@ -0,0 +1,198 @@
+import type { DialogTriggerProps } from '@kobalte/core/dialog';
+import type { Component, JSX, ValidComponent } from 'solid-js';
+import type { DocumentView } from '../document-views.types';
+import { useNavigate } from '@solidjs/router';
+import { useMutation } from '@tanstack/solid-query';
+import { createSignal } from 'solid-js';
+import * as v from 'valibot';
+import { useI18n } from '@/modules/i18n/i18n.provider';
+import { createForm } from '@/modules/shared/form/form';
+import { makeReturnVoidAsync } from '@/modules/shared/functions/void';
+import { useI18nApiErrors } from '@/modules/shared/http/composables/i18n-api-errors';
+import { queryClient } from '@/modules/shared/query/query-client';
+import { Button } from '@/modules/ui/components/button';
+import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/modules/ui/components/dialog';
+import { createToast } from '@/modules/ui/components/sonner';
+import { TextArea } from '@/modules/ui/components/textarea';
+import { TextField, TextFieldLabel, TextFieldRoot } from '@/modules/ui/components/textfield';
+import { createDocumentView, updateDocumentView } from '../document-views.services';
+
+const DocumentViewForm: Component<{
+ onSubmit: (values: { name: string; query: string; description?: string }) => Promise<unknown> | unknown;
+ initialValues?: { name?: string; query?: string; description?: string | null };
+ submitButton: JSX.Element;
+}> = (props) => {
+ const { t } = useI18n();
+ const { Form, Field } = createForm({
+ onSubmit: makeReturnVoidAsync(props.onSubmit),
+ schema: v.object({
+ name: v.pipe(
+ v.string(),
+ v.trim(),
+ v.nonEmpty(t('document-views.form.name.required')),
+ v.maxLength(100, t('document-views.form.name.max-length')),
+ ),
+ query: v.pipe(
+ v.string(),
+ v.trim(),
+ v.nonEmpty(t('document-views.form.query.required')),
+ v.maxLength(500, t('document-views.form.query.max-length')),
+ ),
+ description: v.optional(v.pipe(
+ v.string(),
+ v.trim(),
+ v.maxLength(256, t('document-views.form.description.max-length')),
+ )),
+ }),
+ initialValues: {
+ ...props.initialValues,
+ description: props.initialValues?.description ?? undefined,
+ },
+ });
+
+ return (
+ <Form>
+ <Field name="name">
+ {(field, inputProps) => (
+ <TextFieldRoot class="flex flex-col gap-1 mb-4">
+ <TextFieldLabel for="name">{t('document-views.form.name.label')}</TextFieldLabel>
+ <TextField type="text" id="name" {...inputProps} autoFocus value={field.value} aria-invalid={Boolean(field.error)} placeholder={t('document-views.form.name.placeholder')} />
+ {field.error && <div class="text-red-500 text-sm">{field.error}</div>}
+ </TextFieldRoot>
+ )}
+ </Field>
+
+ <Field name="query">
+ {(field, inputProps) => (
+ <TextFieldRoot class="flex flex-col gap-1 mb-4">
+ <TextFieldLabel for="query">{t('document-views.form.query.label')}</TextFieldLabel>
+ <TextField type="text" id="query" {...inputProps} value={field.value} aria-invalid={Boolean(field.error)} placeholder={t('document-views.form.query.placeholder')} />
+ {field.error && <div class="text-red-500 text-sm">{field.error}</div>}
+ <div class="text-xs text-muted-foreground">{t('document-views.form.query.hint')}</div>
+ </TextFieldRoot>
+ )}
+ </Field>
+
+ <Field name="description">
+ {(field, inputProps) => (
+ <TextFieldRoot class="flex flex-col gap-1 mb-4">
+ <TextFieldLabel for="description">
+ {t('document-views.form.description.label')}
+ <span class="font-normal ml-1 text-muted-foreground">{t('document-views.form.description.optional')}</span>
+ </TextFieldLabel>
+ <TextArea id="description" {...inputProps} value={field.value} aria-invalid={Boolean(field.error)} placeholder={t('document-views.form.description.placeholder')} />
+ {field.error && <div class="text-red-500 text-sm">{field.error}</div>}
+ </TextFieldRoot>
+ )}
+ </Field>
+
+ <div class="flex justify-end mt-6">
+ {props.submitButton}
+ </div>
+ </Form>
+ );
+};
+
+export const CreateDocumentViewModal: Component<{
+ children?: <T extends ValidComponent | HTMLElement>(props: DialogTriggerProps<T>) => JSX.Element;
+ organizationId: string;
+ initialValues?: { name?: string; query?: string };
+}> = (props) => {
+ const [getIsOpen, setIsOpen] = createSignal(false);
+ const { t } = useI18n();
+ const navigate = useNavigate();
+ const { getErrorMessage } = useI18nApiErrors({ t });
+
+ const mutation = useMutation(() => ({
+ mutationFn: (data: { name: string; query: string; description?: string }) => createDocumentView({
+ organizationId: props.organizationId,
+ name: data.name,
+ query: data.query,
+ description: data.description,
+ }),
+ onSuccess: async ({ documentView }, variables) => {
+ await queryClient.invalidateQueries({ queryKey: ['organizations', props.organizationId, 'document-views'], refetchType: 'all' });
+ createToast({ message: t('document-views.create.success', { name: variables.name }), type: 'success' });
+ setIsOpen(false);
+ navigate(`/organizations/${props.organizationId}/views/${documentView.id}`);
+ },
+ onError: (error) => {
+ createToast({ message: getErrorMessage({ error }), type: 'error' });
+ },
+ }));
+
+ return (
+ <Dialog open={getIsOpen()} onOpenChange={setIsOpen}>
+ {props.children && <DialogTrigger as={props.children} />}
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t('document-views.create')}</DialogTitle>
+ </DialogHeader>
+ <DocumentViewForm
+ onSubmit={mutation.mutateAsync}
+ initialValues={props.initialValues}
+ submitButton={(
+ <Button type="submit" isLoading={mutation.isPending} disabled={!getIsOpen()}>
+ {t('document-views.create')}
+ </Button>
+ )}
+ />
+ </DialogContent>
+ </Dialog>
+ );
+};
+
+export const UpdateDocumentViewModal: Component<{
+ children?: (props: DialogTriggerProps) => JSX.Element;
+ organizationId: string;
+ documentView: DocumentView;
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
+}> = (props) => {
+ const [getInternalIsOpen, setInternalIsOpen] = createSignal(false);
+ const getIsOpen = () => props.open ?? getInternalIsOpen();
+ const setIsOpen = (open: boolean) => {
+ props.onOpenChange?.(open);
+ setInternalIsOpen(open);
+ };
+ const { t } = useI18n();
+ const { getErrorMessage } = useI18nApiErrors({ t });
+
+ const mutation = useMutation(() => ({
+ mutationFn: (data: { name: string; query: string; description?: string }) => updateDocumentView({
+ organizationId: props.organizationId,
+ documentViewId: props.documentView.id,
+ name: data.name,
+ query: data.query,
+ description: data.description ?? null,
+ }),
+ onSuccess: async (_, variables) => {
+ await queryClient.invalidateQueries({ queryKey: ['organizations', props.organizationId, 'document-views'], refetchType: 'all' });
+ createToast({ message: t('document-views.update.success', { name: variables.name }), type: 'success' });
+ setIsOpen(false);
+ },
+ onError: (error) => {
+ createToast({ message: getErrorMessage({ error }), type: 'error' });
+ },
+ }));
+
+ return (
+ <Dialog open={getIsOpen()} onOpenChange={setIsOpen}>
+ {props.children && <DialogTrigger as={props.children} />}
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t('document-views.update')}</DialogTitle>
+ </DialogHeader>
+ <DocumentViewForm
+ onSubmit={mutation.mutate}
+ initialValues={props.documentView}
+ submitButton={(
+ <Button type="submit" isLoading={mutation.isPending} disabled={!getIsOpen()}>
+ {t('document-views.update')}
+ </Button>
+ )}
+ />
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/apps/papra-client/src/modules/document-views/document-views.services.ts b/apps/papra-client/src/modules/document-views/document-views.services.ts
new file mode 100644
index 00000000..8a95bd24
--- /dev/null
+++ b/apps/papra-client/src/modules/document-views/document-views.services.ts
@@ -0,0 +1,46 @@
+import type { AsDto } from '../shared/http/http-client.types';
+import type { DocumentView } from './document-views.types';
+import { apiClient } from '../shared/http/api-client';
+import { coerceDates } from '../shared/http/http-client.models';
+
+export async function fetchDocumentViews({ organizationId }: { organizationId: string }) {
+ const { documentViews } = await apiClient<{ documentViews: AsDto<DocumentView>[] }>({
+ path: `/api/organizations/${organizationId}/document-views`,
+ method: 'GET',
+ });
+
+ return { documentViews: documentViews.map(coerceDates) };
+}
+
+export async function fetchDocumentView({ organizationId, documentViewId }: { organizationId: string; documentViewId: string }) {
+ const { documentViews } = await fetchDocumentViews({ organizationId });
+ const documentView = documentViews.find(d => d.id === documentViewId);
+ return { documentView };
+}
+
+export async function createDocumentView({ organizationId, name, query, description }: { organizationId: string; name: string; query: string; description?: string | null }) {
+ const { documentView } = await apiClient<{ documentView: AsDto<DocumentView> }>({
+ path: `/api/organizations/${organizationId}/document-views`,
+ method: 'POST',
+ body: { name, query, description },
+ });
+
+ return { documentView: coerceDates(documentView) };
+}
+
+export async function updateDocumentView({ organizationId, documentViewId, name, query, description }: { organizationId: string; documentViewId: string; name?: string; query?: string; description?: string | null }) {
+ const { documentView } = await apiClient<{ documentView: AsDto<DocumentView> }>({
+ path: `/api/organizations/${organizationId}/document-views/${documentViewId}`,
+ method: 'PUT',
+ body: { name, query, description },
+ });
+
+ return { documentView: coerceDates(documentView) };
+}
+
+export async function deleteDocumentView({ organizationId, documentViewId }: { organizationId: string; documentViewId: string }) {
+ await apiClient({
+ path: `/api/organizations/${organizationId}/document-views/${documentViewId}`,
+ method: 'DELETE',
+ });
+}
diff --git a/apps/papra-client/src/modules/document-views/document-views.types.ts b/apps/papra-client/src/modules/document-views/document-views.types.ts
new file mode 100644
index 00000000..7ec36764
--- /dev/null
+++ b/apps/papra-client/src/modules/document-views/document-views.types.ts
@@ -0,0 +1,9 @@
+export type DocumentView = {
+ id: string;
+ name: string;
+ query: string;
+ description?: string | null;
+ organizationId: string;
+ createdAt: Date;
+ updatedAt: Date;
+};
diff --git a/apps/papra-client/src/modules/document-views/pages/document-view.page.tsx b/apps/papra-client/src/modules/document-views/pages/document-view.page.tsx
new file mode 100644
index 00000000..11f8c5e6
--- /dev/null
+++ b/apps/papra-client/src/modules/document-views/pages/document-view.page.tsx
@@ -0,0 +1,148 @@
+import type { DropdownMenuSubTriggerProps } from '@kobalte/core/dropdown-menu';
+import type { Component } from 'solid-js';
+import { safely } from '@corentinth/chisels';
+import { useNavigate, useParams } from '@solidjs/router';
+import { keepPreviousData, useQuery } from '@tanstack/solid-query';
+import { createSignal, Show, Suspense } from 'solid-js';
+import { createdAtColumn, DocumentsPaginatedList, standardActionsColumn, tagsColumn } from '@/modules/documents/components/documents-list.component';
+import { fetchOrganizationDocuments } from '@/modules/documents/documents.services';
+import { useI18n } from '@/modules/i18n/i18n.provider';
+import { useConfirmModal } from '@/modules/shared/confirm';
+import { useI18nApiErrors } from '@/modules/shared/http/composables/i18n-api-errors';
+import { createParamSynchronizedPagination } from '@/modules/shared/pagination/query-synchronized-pagination';
+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 { UpdateDocumentViewModal } from '../components/document-view-modals';
+import { deleteDocumentView, fetchDocumentView } from '../document-views.services';
+
+export const DocumentViewPage: Component = () => {
+ const params = useParams();
+ const navigate = useNavigate();
+ const { t } = useI18n();
+ const { confirm } = useConfirmModal();
+ const { getErrorMessage } = useI18nApiErrors({ t });
+ const [getPagination, setPagination] = createParamSynchronizedPagination();
+ const [getIsUpdateOpen, setIsUpdateOpen] = createSignal(false);
+
+ const deleteDocumentViewConfirm = async () => {
+ const confirmed = await confirm({
+ title: t('document-views.delete.confirm.title'),
+ message: t('document-views.delete.confirm.message'),
+ cancelButton: { text: t('document-views.delete.confirm.cancel-button'), variant: 'secondary' },
+ confirmButton: { text: t('document-views.delete.confirm.confirm-button'), variant: 'destructive' },
+ });
+
+ if (!confirmed) {
+ return;
+ }
+
+ const [, error] = await safely(deleteDocumentView({ organizationId: params.organizationId, documentViewId: params.documentViewId }));
+
+ if (error) {
+ createToast({ message: getErrorMessage({ error }), type: 'error' });
+ return;
+ }
+
+ await queryClient.invalidateQueries({ queryKey: ['organizations', params.organizationId, 'document-views'], refetchType: 'all' });
+ createToast({ message: t('document-views.delete.success'), type: 'success' });
+ navigate(`/organizations/${params.organizationId}`);
+ };
+
+ const documentViewQuery = useQuery(() => ({
+ queryKey: ['organizations', params.organizationId, 'document-views', params.documentViewId],
+ queryFn: () => fetchDocumentView({ organizationId: params.organizationId, documentViewId: params.documentViewId }),
+ }));
+
+ const documentsQuery = useQuery(() => ({
+ queryKey: ['organizations', params.organizationId, 'documents', 'document-view', params.documentViewId, getPagination()],
+ queryFn: () => fetchOrganizationDocuments({
+ organizationId: params.organizationId,
+ searchQuery: documentViewQuery.data?.documentView?.query ?? '',
+ ...getPagination(),
+ }),
+ enabled: Boolean(documentViewQuery.data?.documentView),
+ placeholderData: keepPreviousData,
+ }));
+
+ return (
+ <div class="p-6 mt-4 pb-32 max-w-5xl mx-auto">
+ <Suspense>
+ <Show when={documentViewQuery.data?.documentView}>
+ {getDocumentView => (
+ <>
+ <div class="mb-6">
+ <div class="flex items-center justify-between gap-2 mb-1">
+ <div class="flex items-center gap-2">
+ <div class="i-tabler-layout-list size-5 text-muted-foreground" />
+ <h2 class="text-xl font-bold">{getDocumentView().name}</h2>
+ </div>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ as={(triggerProps: DropdownMenuSubTriggerProps) => (
+ <Button variant="ghost" size="icon" aria-label={t('document-views.actions.menu')} {...triggerProps}>
+ <div class="i-tabler-dots-vertical size-4" />
+ </Button>
+ )}
+ />
+ <DropdownMenuContent class="w-48">
+ <DropdownMenuItem class="cursor-pointer" onClick={() => setIsUpdateOpen(true)}>
+ <div class="i-tabler-edit size-4 mr-2" />
+ <span>{t('document-views.update')}</span>
+ </DropdownMenuItem>
+
+ <DropdownMenuItem class="cursor-pointer text-red" onClick={deleteDocumentViewConfirm}>
+ <div class="i-tabler-trash size-4 mr-2" />
+ <span>{t('document-views.delete')}</span>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ <code class="text-xs bg-muted px-2 py-1 rounded text-muted-foreground">{getDocumentView().query}</code>
+ <Show when={getDocumentView().description}>
+ {getDescription => (
+ <p class="text-sm text-muted-foreground mt-2">{getDescription()}</p>
+ )}
+ </Show>
+ </div>
+
+ <UpdateDocumentViewModal
+ organizationId={params.organizationId}
+ documentView={getDocumentView()}
+ open={getIsUpdateOpen()}
+ onOpenChange={setIsUpdateOpen}
+ />
+
+ <Show when={documentsQuery.data}>
+ {getData => (
+ <DocumentsPaginatedList
+ documents={getData().documents}
+ documentsCount={getData().documentsCount}
+ getPagination={getPagination}
+ setPagination={setPagination}
+ extraColumns={[tagsColumn, createdAtColumn, standardActionsColumn]}
+ />
+ )}
+ </Show>
+
+ <Show when={documentsQuery.data?.documentsCount === 0}>
+ <div class="text-center py-16 text-muted-foreground">
+ <div class="i-tabler-file-off size-10 mx-auto mb-3 opacity-40" />
+ <p>{t('document-views.view.no-documents')}</p>
+ </div>
+ </Show>
+ </>
+ )}
+ </Show>
+
+ <Show when={!documentViewQuery.isLoading && !documentViewQuery.data?.documentView}>
+ <div class="text-center py-16 text-muted-foreground">
+ <div class="i-tabler-layout-list size-10 mx-auto mb-3 opacity-40" />
+ <p>{t('document-views.view.not-found')}</p>
+ </div>
+ </Show>
+ </Suspense>
+ </div>
+ );
+};
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 006830c5..1b873949 100644
--- a/apps/papra-client/src/modules/documents/pages/documents.page.tsx
+++ b/apps/papra-client/src/modules/documents/pages/documents.page.tsx
@@ -5,6 +5,7 @@ import type { DocumentSearchSortField, DocumentSearchSortOrder } from '../docume
import { useParams } from '@solidjs/router';
import { keepPreviousData, useMutation, useQuery } from '@tanstack/solid-query';
import { createEffect, createMemo, createSignal, on, Show, Suspense } from 'solid-js';
+import { CreateDocumentViewModal } from '@/modules/document-views/components/document-view-modals';
import { useI18n } from '@/modules/i18n/i18n.provider';
import { useConfirmModal } from '@/modules/shared/confirm';
import { createParamSynchronizedPagination } from '@/modules/shared/pagination/query-synchronized-pagination';
@@ -233,34 +234,46 @@ export const DocumentsPage: Component = () => {
{t('documents.list.title')}
</h2>
- <div class="flex items-center">
- <TextFieldRoot class="max-w-md flex-1">
- <TextField
- type="search"
- name="search"
- placeholder={t('documents.list.search.placeholder')}
- value={getSearchQuery()}
- onInput={e => setSearchQuery(e.currentTarget.value)}
- class="pr-9"
- autofocus
- />
- </TextFieldRoot>
+ <div class="flex items-center gap-4">
+ <div class="flex items-center max-w-md flex-1">
+ <TextFieldRoot class="flex-1">
+ <TextField
+ type="search"
+ name="search"
+ placeholder={t('documents.list.search.placeholder')}
+ value={getSearchQuery()}
+ onInput={e => setSearchQuery(e.currentTarget.value)}
+ class="pr-9"
+ autofocus
+ />
+ </TextFieldRoot>
+
+ <Show when={getSearchQuery().length > 0}>
+ <Button
+ variant="ghost"
+ size="icon"
+ class="size-6 ml--8"
+ disabled={documentsQuery.isFetching}
+ onClick={() => setSearchQuery('')}
+ aria-label={documentsQuery.isFetching ? 'Loading' : 'Clear search'}
+ >
+ <div
+ class={cn('text-muted-foreground', documentsQuery.isFetching ? 'i-tabler-loader-2 animate-spin' : 'i-tabler-x')}
+ />
+ </Button>
+ </Show>
+ </div>
<Show when={getSearchQuery().length > 0}>
- <Button
- variant="ghost"
- size="icon"
- class="size-6 ml--8"
- disabled={documentsQuery.isFetching}
- onClick={() => setSearchQuery('')}
- aria-label={documentsQuery.isFetching ? 'Loading' : 'Clear search'}
- >
- <div
- class={cn('text-muted-foreground', documentsQuery.isFetching ? 'i-tabler-loader-2 animate-spin' : 'i-tabler-x')}
- />
- </Button>
+ <CreateDocumentViewModal organizationId={params.organizationId} initialValues={{ query: debouncedSearchQuery() }}>
+ {triggerProps => (
+ <Button variant="outline" title={t('document-views.save-as-view')} {...triggerProps}>
+ <div class="i-tabler-layout-list size-4 mr-1.5" />
+ {t('document-views.save-as-view')}
+ </Button>
+ )}
+ </CreateDocumentViewModal>
</Show>
-
</div>
<div class="mb-4 mt-2 ml-2 min-h-8 flex items-center">
diff --git a/apps/papra-client/src/modules/ui/components/sidenav.tsx b/apps/papra-client/src/modules/ui/components/sidenav.tsx
index 451ac840..e53aebcf 100644
--- a/apps/papra-client/src/modules/ui/components/sidenav.tsx
+++ b/apps/papra-client/src/modules/ui/components/sidenav.tsx
@@ -12,6 +12,12 @@ export type SideNavMenuItem = {
badge?: JSX.Element;
};
+export type SideNavSection = {
+ label?: string;
+ action?: JSX.Element;
+ items: SideNavMenuItem[];
+};
+
const MenuItemButton: Component<SideNavMenuItem> = (props) => {
return (
<Button
@@ -22,15 +28,15 @@ const MenuItemButton: Component<SideNavMenuItem> = (props) => {
: { as: A, href: props.href, activeClass: 'bg-accent/50! text-accent-foreground! truncate', end: true } as ComponentProps<typeof Button>)
}
>
- <div class={cn(props.icon, 'size-5 text-muted-foreground opacity-50')} />
- <div>{props.label}</div>
+ <div class={cn(props.icon, 'size-5 text-muted-foreground opacity-50 flex-shrink-0')} />
+ <div class="truncate">{props.label}</div>
{props.badge && <div class="ml-auto">{props.badge}</div>}
</Button>
);
};
export const SideNav: Component<{
- mainMenu?: SideNavMenuItem[];
+ mainMenu: SideNavSection[];
footerMenu?: SideNavMenuItem[];
header?: Component;
footer?: Component;
@@ -42,11 +48,21 @@ export const SideNav: Component<{
<div class="h-full flex flex-col pb-6 flex-1 min-w-0">
{props.header && <props.header />}
- {props.mainMenu && (
- <nav class="flex flex-col gap-0.5 mt-4 px-4">
- <For each={props.mainMenu}>{menuItem => <MenuItemButton {...menuItem} />}</For>
- </nav>
- )}
+ <For each={props.mainMenu}>
+ {section => (
+ <div class="mt-4 px-4">
+ {section.label && (
+ <div class="flex items-center justify-between pl-3 mb-2">
+ <div class="text-xs font-medium text-muted-foreground/70 uppercase tracking-wider">{section.label}</div>
+ {section.action}
+ </div>
+ )}
+ <nav class="flex flex-col gap-0.5">
+ <For each={section.items}>{menuItem => <MenuItemButton {...menuItem} />}</For>
+ </nav>
+ </div>
+ )}
+ </For>
<div class="flex-1" />
diff --git a/apps/papra-client/src/modules/ui/layouts/organization-settings.layout.tsx b/apps/papra-client/src/modules/ui/layouts/organization-settings.layout.tsx
index e2832399..1ede68de 100644
--- a/apps/papra-client/src/modules/ui/layouts/organization-settings.layout.tsx
+++ b/apps/papra-client/src/modules/ui/layouts/organization-settings.layout.tsx
@@ -10,24 +10,29 @@ export const OrganizationSettingsLayout: ParentComponent = (props) => {
const getNavigationItems = () => [
{
- label: t('layout.menu.general-settings'),
- href: `/organizations/${params.organizationId}/settings`,
- icon: 'i-tabler-settings',
- },
- {
- label: t('layout.menu.usage'),
- href: `/organizations/${params.organizationId}/settings/usage`,
- icon: 'i-tabler-chart-bar',
- },
- {
- label: t('layout.menu.intake-emails'),
- href: `/organizations/${params.organizationId}/settings/intake-emails`,
- icon: 'i-tabler-mail',
- },
- {
- label: t('layout.menu.webhooks'),
- href: `/organizations/${params.organizationId}/settings/webhooks`,
- icon: 'i-tabler-webhook',
+ items: [
+
+ {
+ label: t('layout.menu.general-settings'),
+ href: `/organizations/${params.organizationId}/settings`,
+ icon: 'i-tabler-settings',
+ },
+ {
+ label: t('layout.menu.usage'),
+ href: `/organizations/${params.organizationId}/settings/usage`,
+ icon: 'i-tabler-chart-bar',
+ },
+ {
+ label: t('layout.menu.intake-emails'),
+ href: `/organizations/${params.organizationId}/settings/intake-emails`,
+ icon: 'i-tabler-mail',
+ },
+ {
+ label: t('layout.menu.webhooks'),
+ href: `/organizations/${params.organizationId}/settings/webhooks`,
+ icon: 'i-tabler-webhook',
+ },
+ ],
},
];
diff --git a/apps/papra-client/src/modules/ui/layouts/organization.layout.tsx b/apps/papra-client/src/modules/ui/layouts/organization.layout.tsx
index 753e791e..10afdf1b 100644
--- a/apps/papra-client/src/modules/ui/layouts/organization.layout.tsx
+++ b/apps/papra-client/src/modules/ui/layouts/organization.layout.tsx
@@ -6,6 +6,7 @@ import { useNavigate, useParams } from '@solidjs/router';
import { useQuery } from '@tanstack/solid-query';
import { createEffect, on, Show } from 'solid-js';
import { useConfig } from '@/modules/config/config.provider';
+import { fetchDocumentViews } from '@/modules/document-views/document-views.services';
import { DocumentUploadProvider } from '@/modules/documents/components/document-import-status.component';
import { useI18n } from '@/modules/i18n/i18n.provider';
import { fetchOrganization, fetchOrganizations } from '@/modules/organizations/organizations.services';
@@ -72,43 +73,71 @@ const OrganizationLayoutSideNav: Component = () => {
const params = useParams();
const { t } = useI18n();
- const getMainMenuItems = () => [
- {
- label: t('layout.menu.home'),
- icon: 'i-tabler-home',
- href: `/organizations/${params.organizationId}`,
- },
- {
- label: t('layout.menu.documents'),
- icon: 'i-tabler-file-text',
- href: `/organizations/${params.organizationId}/documents`,
- },
+ const documentViewsQuery = useQuery(() => ({
+ queryKey: ['organizations', params.organizationId, 'document-views'],
+ queryFn: () => fetchDocumentViews({ organizationId: params.organizationId }),
+ }));
+ const getDocumentViewsSections = () => {
+ const documentViews = documentViewsQuery.data?.documentViews ?? [];
+
+ if (documentViews.length === 0) {
+ return [];
+ }
+
+ return [
+ {
+ label: t('layout.menu.document-views'),
+ items: documentViews.map(documentView => ({
+ label: documentView.name,
+ icon: 'i-tabler-layout-list',
+ href: `/organizations/${params.organizationId}/views/${documentView.id}`,
+ })),
+ },
+ ];
+ };
+
+ const getMainMenuItems = () => [
{
- label: t('layout.menu.tags'),
- icon: 'i-tabler-tag',
- href: `/organizations/${params.organizationId}/tags`,
- },
- {
- label: t('layout.menu.custom-properties'),
- icon: 'i-tabler-forms',
- href: `/organizations/${params.organizationId}/custom-properties`,
- },
- {
- label: t('layout.menu.tagging-rules'),
- icon: 'i-tabler-list-check',
- href: `/organizations/${params.organizationId}/tagging-rules`,
- },
- {
- label: t('layout.menu.share-links'),
- icon: 'i-tabler-share',
- href: `/organizations/${params.organizationId}/share-links`,
- },
- {
- label: t('layout.menu.members'),
- icon: 'i-tabler-users',
- href: `/organizations/${params.organizationId}/members`,
+ items: [
+ {
+ label: t('layout.menu.home'),
+ icon: 'i-tabler-home',
+ href: `/organizations/${params.organizationId}`,
+ },
+ {
+ label: t('layout.menu.documents'),
+ icon: 'i-tabler-file-text',
+ href: `/organizations/${params.organizationId}/documents`,
+ },
+ {
+ label: t('layout.menu.tags'),
+ icon: 'i-tabler-tag',
+ href: `/organizations/${params.organizationId}/tags`,
+ },
+ {
+ label: t('layout.menu.custom-properties'),
+ icon: 'i-tabler-forms',
+ href: `/organizations/${params.organizationId}/custom-properties`,
+ },
+ {
+ label: t('layout.menu.tagging-rules'),
+ icon: 'i-tabler-list-check',
+ href: `/organizations/${params.organizationId}/tagging-rules`,
+ },
+ {
+ label: t('layout.menu.share-links'),
+ icon: 'i-tabler-share',
+ href: `/organizations/${params.organizationId}/share-links`,
+ },
+ {
+ label: t('layout.menu.members'),
+ icon: 'i-tabler-users',
+ href: `/organizations/${params.organizationId}/members`,
+ },
+ ],
},
+ ...getDocumentViewsSections(),
];
const getFooterMenuItems = () => [
diff --git a/apps/papra-client/src/modules/ui/layouts/settings.layout.tsx b/apps/papra-client/src/modules/ui/layouts/settings.layout.tsx
index 3037d2e5..1c7510a2 100644
--- a/apps/papra-client/src/modules/ui/layouts/settings.layout.tsx
+++ b/apps/papra-client/src/modules/ui/layouts/settings.layout.tsx
@@ -7,23 +7,25 @@ import { Button } from '../components/button';
export const SettingsLayout: ParentComponent = (props) => {
const { t } = useI18n();
- const getMainMenuItems = () => [
- {
- label: t('layout.menu.account'),
- icon: 'i-tabler-user',
- href: '/settings',
- },
- {
- label: t('layout.menu.api-keys'),
- icon: 'i-tabler-key',
- href: '/api-keys',
- },
- {
- label: t('layout.menu.invitations'),
- icon: 'i-tabler-mail',
- href: '/invitations',
- },
- ];
+ const getMainMenuItems = () => [{
+ items: [
+ {
+ label: t('layout.menu.account'),
+ icon: 'i-tabler-user',
+ href: '/settings',
+ },
+ {
+ label: t('layout.menu.api-keys'),
+ icon: 'i-tabler-key',
+ href: '/api-keys',
+ },
+ {
+ label: t('layout.menu.invitations'),
+ icon: 'i-tabler-mail',
+ href: '/invitations',
+ },
+ ],
+ }];
return (
<div class="flex flex-row h-screen min-h-0">
diff --git a/apps/papra-client/src/routes.tsx b/apps/papra-client/src/routes.tsx
index 66fa839f..7e86577a 100644
--- a/apps/papra-client/src/routes.tsx
+++ b/apps/papra-client/src/routes.tsx
@@ -18,6 +18,7 @@ import { CustomPropertiesPage } from './modules/custom-properties/pages/custom-p
import { UpdateCustomPropertyPage } from './modules/custom-properties/pages/update-custom-property.page';
import { OrganizationShareLinksPage } from './modules/document-share-links/pages/organization-share-links.page';
import { SharedDocumentPage } from './modules/document-share-links/pages/shared-document.page';
+import { DocumentViewPage } from './modules/document-views/pages/document-view.page';
import { DeletedDocumentsPage } from './modules/documents/pages/deleted-documents.page';
import { DocumentPdfViewerPage } from './modules/documents/pages/document-pdf-viewer.page';
import { DocumentPage } from './modules/documents/pages/document.page';
@@ -148,6 +149,10 @@ export const routes: RouteDefinition[] = [
path: '/tags',
component: TagsPage,
},
+ {
+ path: '/views/:documentViewId',
+ component: DocumentViewPage,
+ },
{
path: '/custom-properties',
component: CustomPropertiesPage,
diff --git a/apps/papra-server/src/migrations/list/0023-document-views.migration.ts b/apps/papra-server/src/migrations/list/0023-document-views.migration.ts
new file mode 100644
index 00000000..eb8a6a8f
--- /dev/null
+++ b/apps/papra-server/src/migrations/list/0023-document-views.migration.ts
@@ -0,0 +1,26 @@
+import type { Migration } from '../migrations.types';
+import { sql } from 'drizzle-orm';
+
+export const documentViewsMigration = {
+ name: 'document-views',
+
+ up: async ({ db }) => {
+ await db.run(sql`
+ CREATE TABLE IF NOT EXISTS "document_views" (
+ "id" text PRIMARY KEY NOT NULL,
+ "created_at" integer NOT NULL,
+ "updated_at" integer NOT NULL,
+ "organization_id" text NOT NULL,
+ "name" text NOT NULL,
+ "query" text NOT NULL,
+ "description" text,
+ FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade,
+ UNIQUE("organization_id", "name")
+ );
+ `);
+ },
+
+ down: async ({ db }) => {
+ await db.run(sql`DROP TABLE IF EXISTS "document_views"`);
+ },
+} satisfies Migration;
diff --git a/apps/papra-server/src/migrations/migrations.registry.test.ts b/apps/papra-server/src/migrations/migrations.registry.test.ts
index dfb58606..efb3db5d 100644
--- a/apps/papra-server/src/migrations/migrations.registry.test.ts
+++ b/apps/papra-server/src/migrations/migrations.registry.test.ts
@@ -117,6 +117,7 @@ describe('migrations registry', () => {
CREATE TABLE "document_activity_log" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "document_id" text NOT NULL, "event" text NOT NULL, "event_data" text, "user_id" text, "tag_id" text, FOREIGN KEY ("document_id") REFERENCES "documents"("id") ON UPDATE cascade ON DELETE cascade, FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE set null, FOREIGN KEY ("tag_id") REFERENCES "tags"("id") ON UPDATE cascade ON DELETE set null );
CREATE TABLE "document_custom_property_values" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "document_id" text NOT NULL REFERENCES "documents"("id") ON DELETE CASCADE ON UPDATE CASCADE, "property_definition_id" text NOT NULL REFERENCES "custom_property_definitions"("id") ON DELETE CASCADE ON UPDATE CASCADE, "text_value" text, "number_value" real, "date_value" integer, "boolean_value" integer, "select_option_id" text REFERENCES "custom_property_select_options"("id") ON DELETE CASCADE ON UPDATE CASCADE, "user_id" text REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE, "related_document_id" text REFERENCES "documents"("id") ON DELETE CASCADE ON UPDATE CASCADE );
CREATE TABLE "document_share_links" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "organization_id" text NOT NULL, "document_id" text NOT NULL, "created_by" text, "token" text NOT NULL, "expires_at" integer, "password_hash" text, "is_enabled" integer DEFAULT true NOT NULL, "last_accessed_at" integer, FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade, FOREIGN KEY ("document_id") REFERENCES "documents"("id") ON UPDATE cascade ON DELETE cascade, FOREIGN KEY ("created_by") REFERENCES "users"("id") ON UPDATE cascade ON DELETE set null );
+ CREATE TABLE "document_views" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "organization_id" text NOT NULL, "name" text NOT NULL, "query" text NOT NULL, "description" text, FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade, UNIQUE("organization_id", "name") );
CREATE TABLE "documents" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "is_deleted" integer DEFAULT false NOT NULL, "deleted_at" integer, "organization_id" text NOT NULL, "created_by" text, "deleted_by" text, "original_name" text NOT NULL, "original_size" integer DEFAULT 0 NOT NULL, "original_storage_key" text NOT NULL, "original_sha256_hash" text NOT NULL, "name" text NOT NULL, "mime_type" text NOT NULL, "content" text DEFAULT '' NOT NULL, file_encryption_key_wrapped TEXT, file_encryption_kek_version TEXT, file_encryption_algorithm TEXT, document_date INTEGER, notes TEXT, FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE cascade, FOREIGN KEY ("created_by") REFERENCES "users"("id") ON UPDATE cascade ON DELETE set null, FOREIGN KEY ("deleted_by") REFERENCES "users"("id") ON UPDATE cascade ON DELETE set null );
CREATE VIRTUAL TABLE documents_fts USING fts5( document_id, organization_id, name, content, prefix='2 3 4' );
CREATE TABLE 'documents_fts_config'(k PRIMARY KEY, v) WITHOUT ROWID;
diff --git a/apps/papra-server/src/migrations/migrations.registry.ts b/apps/papra-server/src/migrations/migrations.registry.ts
index 09ce8ccd..76f56eb8 100644
--- a/apps/papra-server/src/migrations/migrations.registry.ts
+++ b/apps/papra-server/src/migrations/migrations.registry.ts
@@ -22,6 +22,7 @@ import { twoFactorVerifiedMigration } from './list/0019-two-factor-verified.migr
import { kvStoreMigration } from './list/0020-kv-store.migration';
import { documentShareLinksMigration } from './list/0021-document-share-links.migration';
import { documentsNotesMigration } from './list/0022-documents-notes.migration';
+import { documentViewsMigration } from './list/0023-document-views.migration';
export const migrations: Migration[] = [
initialSchemaSetupMigration,
@@ -46,4 +47,5 @@ export const migrations: Migration[] = [
kvStoreMigration,
documentShareLinksMigration,
documentsNotesMigration,
+ documentViewsMigration,
];
diff --git a/apps/papra-server/src/modules/app/server.routes.test.ts b/apps/papra-server/src/modules/app/server.routes.test.ts
index 42e32391..45ca7f79 100644
--- a/apps/papra-server/src/modules/app/server.routes.test.ts
+++ b/apps/papra-server/src/modules/app/server.routes.test.ts
@@ -21,7 +21,8 @@ function setValidParams(path: string) {
.replaceAll(':propertyDefinitionId', 'cpd_111111111111111111111111')
.replaceAll(':optionId', 'cpso_222222222222222222222222')
.replaceAll(':shareLinkId', 'dsl_333333333333333333333333')
- .replaceAll(':shareLinkToken', 't'.repeat(SHARE_LINK_TOKEN_LENGTH));
+ .replaceAll(':shareLinkToken', 't'.repeat(SHARE_LINK_TOKEN_LENGTH))
+ .replaceAll(':documentViewId', 'dv_444444444444444444444444');
// throw if there are any remaining params
if (newPath.match(/:\w+/g)) {
diff --git a/apps/papra-server/src/modules/app/server.routes.ts b/apps/papra-server/src/modules/app/server.routes.ts
index e10f45ed..0e631bca 100644
--- a/apps/papra-server/src/modules/app/server.routes.ts
+++ b/apps/papra-server/src/modules/app/server.routes.ts
@@ -4,6 +4,7 @@ import { registerApiKeysRoutes } from '../api-keys/api-keys.routes';
import { registerConfigRoutes } from '../config/config.routes';
import { registerCustomPropertiesRoutes } from '../custom-properties/custom-properties.routes';
import { registerDocumentShareLinksRoutes } from '../document-share-links/document-share-links.routes';
+import { registerDocumentViewsRoutes } from '../document-views/document-views.routes';
import { registerDocumentActivityRoutes } from '../documents/document-activity/document-activity.routes';
import { registerDocumentsBatchRoutes } from '../documents/documents-batch/documents-batch.routes';
import { registerDocumentsRoutes } from '../documents/documents.routes';
@@ -29,6 +30,7 @@ export function registerRoutes(context: RouteDefinitionContext) {
registerDocumentsRoutes(context);
registerDocumentsBatchRoutes(context);
registerTagsRoutes(context);
+ registerDocumentViewsRoutes(context);
registerTaggingRulesRoutes(context);
registerApiKeysRoutes(context);
registerWebhooksRoutes(context);
diff --git a/apps/papra-server/src/modules/document-views/document-views.constants.ts b/apps/papra-server/src/modules/document-views/document-views.constants.ts
new file mode 100644
index 00000000..168bcecd
--- /dev/null
+++ b/apps/papra-server/src/modules/document-views/document-views.constants.ts
@@ -0,0 +1,4 @@
+import { createPrefixedIdRegex } from '../shared/random/ids';
+
+export const DOCUMENT_VIEW_ID_PREFIX = 'dv';
+export const DOCUMENT_VIEW_ID_REGEX = createPrefixedIdRegex({ prefix: DOCUMENT_VIEW_ID_PREFIX });
diff --git a/apps/papra-server/src/modules/document-views/document-views.errors.ts b/apps/papra-server/src/modules/document-views/document-views.errors.ts
new file mode 100644
index 00000000..2e032c06
--- /dev/null
+++ b/apps/papra-server/src/modules/document-views/document-views.errors.ts
@@ -0,0 +1,13 @@
+import { createErrorFactory } from '../shared/errors/errors';
+
+export const createDocumentViewNotFoundError = createErrorFactory({
+ message: 'Document view not found',
+ code: 'document_views.not_found',
+ statusCode: 404,
+});
+
+export const createDocumentViewAlreadyExistsError = createErrorFactory({
+ message: 'A document view with this name already exists',
+ code: 'document_views.already_exists',
+ statusCode: 400,
+});
diff --git a/apps/papra-server/src/modules/document-views/document-views.repository.ts b/apps/papra-server/src/modules/document-views/document-views.repository.ts
new file mode 100644
index 00000000..5e64b38d
--- /dev/null
+++ b/apps/papra-server/src/modules/document-views/document-views.repository.ts
@@ -0,0 +1,88 @@
+import type { Database } from '../app/database/database.types';
+import { injectArguments, safely } from '@corentinth/chisels';
+import { and, desc, eq } from 'drizzle-orm';
+import { isUniqueConstraintError } from '../shared/db/constraints.models';
+import { omitUndefined } from '../shared/objects';
+import { createDocumentViewAlreadyExistsError } from './document-views.errors';
+import { documentViewsTable } from './document-views.table';
+
+export type DocumentViewsRepository = ReturnType<typeof createDocumentViewsRepository>;
+
+export function createDocumentViewsRepository({ db }: { db: Database }) {
+ return injectArguments(
+ {
+ getOrganizationDocumentViews,
+ getDocumentViewById,
+ createDocumentView,
+ updateDocumentView,
+ deleteDocumentView,
+ },
+ { db },
+ );
+}
+
+async function getOrganizationDocumentViews({ organizationId, db }: { organizationId: string; db: Database }) {
+ const documentViews = await db
+ .select()
+ .from(documentViewsTable)
+ .where(eq(documentViewsTable.organizationId, organizationId))
+ .orderBy(desc(documentViewsTable.createdAt));
+
+ return { documentViews };
+}
+
+async function getDocumentViewById({ documentViewId, organizationId, db }: { documentViewId: string; organizationId: string; db: Database }) {
+ const [documentView] = await db
+ .select()
+ .from(documentViewsTable)
+ .where(
+ and(
+ eq(documentViewsTable.id, documentViewId),
+ eq(documentViewsTable.organizationId, organizationId),
+ ),
+ );
+
+ return { documentView };
+}
+
+async function createDocumentView({ documentView, db }: { documentView: { name: string; query: string; description?: string | null; organizationId: string }; db: Database }) {
+ const [result, error] = await safely(
+ db.insert(documentViewsTable).values(documentView).returning(),
+ );
+
+ if (isUniqueConstraintError({ error })) {
+ throw createDocumentViewAlreadyExistsError();
+ }
+
+ if (error) {
+ throw error;
+ }
+
+ const [createdDocumentView] = result;
+ return { documentView: createdDocumentView };
+}
+
+async function updateDocumentView({ documentViewId, name, query, description, db }: { documentViewId: string; name?: string; query?: string; description?: string | null; db: Database }) {
+ const [result, error] = await safely(
+ db
+ .update(documentViewsTable)
+ .set(omitUndefined({ name, query, description }))
+ .where(eq(documentViewsTable.id, documentViewId))
+ .returning(),
+ );
+
+ if (isUniqueConstraintError({ error })) {
+ throw createDocumentViewAlreadyExistsError();
+ }
+
+ if (error) {
+ throw error;
+ }
+
+ const [documentView] = result;
+ return { documentView };
+}
+
+async function deleteDocumentView({ documentViewId, db }: { documentViewId: string; db: Database }) {
+ await db.delete(documentViewsTable).where(eq(documentViewsTable.id, documentViewId));
+}
diff --git a/apps/papra-server/src/modules/document-views/document-views.routes.ts b/apps/papra-server/src/modules/document-views/document-views.routes.ts
new file mode 100644
index 00000000..530b0db1
--- /dev/null
+++ b/apps/papra-server/src/modules/document-views/document-views.routes.ts
@@ -0,0 +1,133 @@
+import type { RouteDefinitionContext } from '../app/server.types';
+import * as v from 'valibot';
+import { requireAuthentication } from '../app/auth/auth.middleware';
+import { getUser } from '../app/auth/auth.models';
+import { searchDocumentsQuerySchema } from '../documents/documents.schemas';
+import { organizationIdSchema } from '../organizations/organization.schemas';
+import { createOrganizationsRepository } from '../organizations/organizations.repository';
+import { ensureUserIsInOrganization } from '../organizations/organizations.usecases';
+import { validateJsonBody, validateParams } from '../shared/validation/validation';
+import { createDocumentViewNotFoundError } from './document-views.errors';
+import { createDocumentViewsRepository } from './document-views.repository';
+import { documentViewDescriptionSchema, documentViewIdSchema, documentViewNameSchema } from './document-views.schemas';
+
+export function registerDocumentViewsRoutes(context: RouteDefinitionContext) {
+ setupCreateDocumentViewRoute(context);
+ setupGetOrganizationDocumentViewsRoute(context);
+ setupUpdateDocumentViewRoute(context);
+ setupDeleteDocumentViewRoute(context);
+}
+
+function setupCreateDocumentViewRoute({ app, db }: RouteDefinitionContext) {
+ app.post(
+ '/api/organizations/:organizationId/document-views',
+ requireAuthentication(),
+ validateParams(v.strictObject({ organizationId: organizationIdSchema })),
+ validateJsonBody(v.strictObject({
+ name: documentViewNameSchema,
+ query: searchDocumentsQuerySchema,
+ description: v.optional(documentViewDescriptionSchema),
+ })),
+ async (context) => {
+ const { userId } = getUser({ context });
+ const { organizationId } = context.req.valid('param');
+ const { name, query, description } = context.req.valid('json');
+
+ const documentViewsRepository = createDocumentViewsRepository({ db });
+ const organizationsRepository = createOrganizationsRepository({ db });
+
+ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });
+
+ const { documentView } = await documentViewsRepository.createDocumentView({ documentView: { organizationId, name, query, description } });
+
+ return context.json({ documentView });
+ },
+ );
+}
+
+function setupGetOrganizationDocumentViewsRoute({ app, db }: RouteDefinitionContext) {
+ app.get(
+ '/api/organizations/:organizationId/document-views',
+ requireAuthentication(),
+ validateParams(v.strictObject({ organizationId: organizationIdSchema })),
+ async (context) => {
+ const { userId } = getUser({ context });
+ const { organizationId } = context.req.valid('param');
+
+ const documentViewsRepository = createDocumentViewsRepository({ db });
+ const organizationsRepository = createOrganizationsRepository({ db });
+
+ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });
+
+ const { documentViews } = await documentViewsRepository.getOrganizationDocumentViews({ organizationId });
+
+ return context.json({ documentViews });
+ },
+ );
+}
+
+function setupUpdateDocumentViewRoute({ app, db }: RouteDefinitionContext) {
+ app.put(
+ '/api/organizations/:organizationId/document-views/:documentViewId',
+ requireAuthentication(),
+ validateParams(v.strictObject({
+ organizationId: organizationIdSchema,
+ documentViewId: documentViewIdSchema,
+ })),
+ validateJsonBody(v.strictObject({
+ name: documentViewNameSchema,
+ query: searchDocumentsQuerySchema,
+ description: v.optional(documentViewDescriptionSchema),
+ })),
+ async (context) => {
+ const { userId } = getUser({ context });
+ const { organizationId, documentViewId } = context.req.valid('param');
+ const { name, query, description } = context.req.valid('json');
+
+ const documentViewsRepository = createDocumentViewsRepository({ db });
+ const organizationsRepository = createOrganizationsRepository({ db });
+
+ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });
+
+ const { documentView: existingDocumentView } = await documentViewsRepository.getDocumentViewById({ documentViewId, organizationId });
+
+ if (!existingDocumentView) {
+ throw createDocumentViewNotFoundError();
+ }
+
+ const { documentView } = await documentViewsRepository.updateDocumentView({ documentViewId, name, query, description });
+
+ return context.json({ documentView });
+ },
+ );
+}
+
+function setupDeleteDocumentViewRoute({ app, db }: RouteDefinitionContext) {
+ app.delete(
+ '/api/organizations/:organizationId/document-views/:documentViewId',
+ requireAuthentication(),
+ validateParams(v.strictObject({
+ organizationId: organizationIdSchema,
+ documentViewId: documentViewIdSchema,
+ })),
+ async (context) => {
+ const { userId } = getUser({ context });
+ const { organizationId, documentViewId } = context.req.valid('param');
+
+ const documentViewsRepository = createDocumentViewsRepository({ db });
+ const organizationsRepository = createOrganizationsRepository({ db });
+
+ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });
+
+ const { documentView: existingDocumentView } = await documentViewsRepository.getDocumentViewById({ documentViewId, organizationId });
+
+ if (!existingDocumentView) {
+ throw createDocumentViewNotFoundError();
+ }
+
+ await documentViewsRepository.deleteDocumentView({ documentViewId });
+
+ return context.body(null, 204);
+ },
+ );
+}
diff --git a/apps/papra-server/src/modules/document-views/document-views.schemas.ts b/apps/papra-server/src/modules/document-views/document-views.schemas.ts
new file mode 100644
index 00000000..23111609
--- /dev/null
+++ b/apps/papra-server/src/modules/document-views/document-views.schemas.ts
@@ -0,0 +1,7 @@
+import * as v from 'valibot';
+import { createRegexSchema } from '../shared/schemas/string.schemas';
+import { DOCUMENT_VIEW_ID_REGEX } from './document-views.constants';
+
+export const documentViewIdSchema = createRegexSchema(DOCUMENT_VIEW_ID_REGEX);
+export const documentViewNameSchema = v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(255));
+export const documentViewDescriptionSchema = v.pipe(v.string(), v.trim(), v.maxLength(256));
diff --git a/apps/papra-server/src/modules/document-views/document-views.table.ts b/apps/papra-server/src/modules/document-views/document-views.table.ts
new file mode 100644
index 00000000..c9801831
--- /dev/null
+++ b/apps/papra-server/src/modules/document-views/document-views.table.ts
@@ -0,0 +1,20 @@
+import { sqliteTable, text, unique } from 'drizzle-orm/sqlite-core';
+import { organizationsTable } from '../organizations/organizations.table';
+import { createPrimaryKeyField, createTimestampColumns } from '../shared/db/columns.helpers';
+import { DOCUMENT_VIEW_ID_PREFIX } from './document-views.constants';
+
+export const documentViewsTable = sqliteTable(
+ 'document_views',
+ {
+ ...createPrimaryKeyField({ prefix: DOCUMENT_VIEW_ID_PREFIX }),
+ ...createTimestampColumns(),
+
+ organizationId: text('organization_id').notNull().references(() => organizationsTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),
+ name: text('name').notNull(),
+ query: text('query').notNull(),
+ description: text('description'),
+ },
+ table => [
+ unique('document_views_organization_id_name_unique').on(table.organizationId, table.name),
+ ],
+);