Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(documents): advanced document search page (#758)

Corentin Thomasseta2a2061a63bd
diff --git a/.changeset/fast-candles-look.md b/.changeset/fast-candles-look.md
new file mode 100644
index 00000000..f73043bd
--- /dev/null
+++ b/.changeset/fast-candles-look.md
@@ -0,0 +1,5 @@
+---
+"@papra/docker": patch
+---
+
+The documents page can now be used with advanced search queries
diff --git a/.changeset/metal-laws-chew.md b/.changeset/metal-laws-chew.md
new file mode 100644
index 00000000..b7ec45f0
--- /dev/null
+++ b/.changeset/metal-laws-chew.md
@@ -0,0 +1,5 @@
+---
+"@papra/docker": patch
+---
+
+Document search endpoint now returns complete documents along with total count matching the search query
diff --git a/.changeset/sour-meals-find.md b/.changeset/sour-meals-find.md
new file mode 100644
index 00000000..beea0c49
--- /dev/null
+++ b/.changeset/sour-meals-find.md
@@ -0,0 +1,5 @@
+---
+"@papra/docker": patch
+---
+
+Added query params sync for the search query in the documents search page for deep linking and browser state navigation
diff --git a/.changeset/sweet-yaks-kiss.md b/.changeset/sweet-yaks-kiss.md
new file mode 100644
index 00000000..08fef81a
--- /dev/null
+++ b/.changeset/sweet-yaks-kiss.md
@@ -0,0 +1,13 @@
+---
+"@papra/docker": patch
+---
+
+Removed the possibility to filter by tag in the `/api/organizations/:organizationId/documents` route, use the `/api/organizations/:organizationId/documents/search` route instead.
+
+```bash
+# Before:
+GET /api/organizations/:organizationId/documents?tags=yourTagId
+
+# After:
+GET /api/organizations/:organizationId/documents/search?query=tag:yourTagNameOrId
+```
diff --git a/apps/papra-client/src/locales/de.dictionary.ts b/apps/papra-client/src/locales/de.dictionary.ts
index d05efddd..bb0529df 100644
--- a/apps/papra-client/src/locales/de.dictionary.ts
+++ b/apps/papra-client/src/locales/de.dictionary.ts
@@ -328,6 +328,10 @@ export const translations: Partial<TranslationsDictionary> = {
'documents.list.table.headers.deleted': 'Gelöscht am',
'documents.list.table.headers.actions': 'Aktionen',
'documents.list.table.headers.tags': 'Tags',
+ 'documents.list.search.placeholder': 'Dokumente durchsuchen...',
+ 'documents.list.search.no-results': 'Keine Dokumente für diese Suche gefunden',
+ 'documents.list.search.total-count-with-query': '{{ count }} {{ count, =1:Dokument, Dokumente }} entsprechen dieser Suche',
+ 'documents.list.search.total-count-no-query': '{{ count }} {{ count, =1:Dokument, Dokumente }} insgesamt',
'documents.tabs.info': 'Info',
'documents.tabs.content': 'Inhalt',
@@ -657,7 +661,7 @@ export const translations: Partial<TranslationsDictionary> = {
'layout.theme.dark': 'Dunkler Modus',
'layout.theme.system': 'Systemmodus',
- 'layout.search.placeholder': 'Suchen...',
+ 'layout.search.placeholder': 'Schnellsuche',
'layout.menu.import-document': 'Dokument importieren',
'user-menu.account-settings': 'Kontoeinstellungen',
diff --git a/apps/papra-client/src/locales/en.dictionary.ts b/apps/papra-client/src/locales/en.dictionary.ts
index ee548f40..c6c08694 100644
--- a/apps/papra-client/src/locales/en.dictionary.ts
+++ b/apps/papra-client/src/locales/en.dictionary.ts
@@ -326,6 +326,10 @@ export const translations = {
'documents.list.table.headers.deleted': 'Deleted at',
'documents.list.table.headers.actions': 'Actions',
'documents.list.table.headers.tags': 'Tags',
+ 'documents.list.search.placeholder': 'Search documents...',
+ 'documents.list.search.no-results': 'No documents found matching this query',
+ 'documents.list.search.total-count-with-query': '{{ count }} {{ count, =1:document, documents }} matching this query',
+ 'documents.list.search.total-count-no-query': '{{ count }} {{ count, =1:document, documents }} in total',
'documents.tabs.info': 'Info',
'documents.tabs.content': 'Content',
@@ -655,7 +659,7 @@ export const translations = {
'layout.theme.dark': 'Dark mode',
'layout.theme.system': 'System mode',
- 'layout.search.placeholder': 'Search...',
+ 'layout.search.placeholder': 'Quick search',
'layout.menu.import-document': 'Import a document',
'user-menu.account-settings': 'Account settings',
diff --git a/apps/papra-client/src/locales/es.dictionary.ts b/apps/papra-client/src/locales/es.dictionary.ts
index 617beaac..94764bac 100644
--- a/apps/papra-client/src/locales/es.dictionary.ts
+++ b/apps/papra-client/src/locales/es.dictionary.ts
@@ -328,6 +328,10 @@ export const translations: Partial<TranslationsDictionary> = {
'documents.list.table.headers.deleted': 'Eliminado el',
'documents.list.table.headers.actions': 'Acciones',
'documents.list.table.headers.tags': 'Etiquetas',
+ 'documents.list.search.placeholder': 'Buscar documentos...',
+ 'documents.list.search.no-results': 'No se encontraron documentos para esta búsqueda',
+ 'documents.list.search.total-count-with-query': '{{ count }} {{ count, =1:documento, documentos }} coinciden con esta búsqueda',
+ 'documents.list.search.total-count-no-query': '{{ count }} {{ count, =1:documento, documentos }} en total',
'documents.tabs.info': 'Información',
'documents.tabs.content': 'Contenido',
@@ -657,7 +661,7 @@ export const translations: Partial<TranslationsDictionary> = {
'layout.theme.dark': 'Modo oscuro',
'layout.theme.system': 'Modo del sistema',
- 'layout.search.placeholder': 'Buscar...',
+ 'layout.search.placeholder': 'Búsqueda rápida',
'layout.menu.import-document': 'Importar un documento',
'user-menu.account-settings': 'Ajustes de cuenta',
diff --git a/apps/papra-client/src/locales/fr.dictionary.ts b/apps/papra-client/src/locales/fr.dictionary.ts
index 625ae4c1..85f330c8 100644
--- a/apps/papra-client/src/locales/fr.dictionary.ts
+++ b/apps/papra-client/src/locales/fr.dictionary.ts
@@ -328,6 +328,10 @@ export const translations: Partial<TranslationsDictionary> = {
'documents.list.table.headers.deleted': 'Supprimé le',
'documents.list.table.headers.actions': 'Actions',
'documents.list.table.headers.tags': 'Étiquettes',
+ 'documents.list.search.placeholder': 'Rechercher des documents...',
+ 'documents.list.search.no-results': 'Aucun document ne correspond à cette recherche',
+ 'documents.list.search.total-count-with-query': '{{ count }} {{ count, =1:document, documents }} correspondant à cette recherche',
+ 'documents.list.search.total-count-no-query': '{{ count }} {{ count, =1:document, documents }} au total',
'documents.tabs.info': 'Info',
'documents.tabs.content': 'Contenu',
@@ -657,7 +661,7 @@ export const translations: Partial<TranslationsDictionary> = {
'layout.theme.dark': 'Mode sombre',
'layout.theme.system': 'Mode système',
- 'layout.search.placeholder': 'Rechercher...',
+ 'layout.search.placeholder': 'Recherche rapide',
'layout.menu.import-document': 'Importer un document',
'user-menu.account-settings': 'Paramètres du compte',
diff --git a/apps/papra-client/src/locales/it.dictionary.ts b/apps/papra-client/src/locales/it.dictionary.ts
index 0a4dc6d2..7080d208 100644
--- a/apps/papra-client/src/locales/it.dictionary.ts
+++ b/apps/papra-client/src/locales/it.dictionary.ts
@@ -328,6 +328,10 @@ export const translations: Partial<TranslationsDictionary> = {
'documents.list.table.headers.deleted': 'Eliminato il',
'documents.list.table.headers.actions': 'Azioni',
'documents.list.table.headers.tags': 'Tag',
+ 'documents.list.search.placeholder': 'Cerca documenti...',
+ 'documents.list.search.no-results': 'Nessun documento trovato per questa ricerca',
+ 'documents.list.search.total-count-with-query': '{{ count }} {{ count, =1:documento, documenti }} corrispondente a questa ricerca',
+ 'documents.list.search.total-count-no-query': '{{ count }} {{ count, =1:documento, documenti }} in totale',
'documents.tabs.info': 'Info',
'documents.tabs.content': 'Contenuto',
@@ -657,7 +661,7 @@ export const translations: Partial<TranslationsDictionary> = {
'layout.theme.dark': 'Modalità scura',
'layout.theme.system': 'Modalità sistema',
- 'layout.search.placeholder': 'Cerca...',
+ 'layout.search.placeholder': 'Ricerca rapida',
'layout.menu.import-document': 'Importa un documento',
'user-menu.account-settings': 'Impostazioni account',
diff --git a/apps/papra-client/src/locales/nl.dictionary.ts b/apps/papra-client/src/locales/nl.dictionary.ts
index e40e3b07..6907b3fe 100644
--- a/apps/papra-client/src/locales/nl.dictionary.ts
+++ b/apps/papra-client/src/locales/nl.dictionary.ts
@@ -328,6 +328,10 @@ export const translations: Partial<TranslationsDictionary> = {
'documents.list.table.headers.deleted': 'Verwijderd op',
'documents.list.table.headers.actions': 'Acties',
'documents.list.table.headers.tags': 'Tags',
+ 'documents.list.search.placeholder': 'Zoek documenten...',
+ 'documents.list.search.no-results': 'Geen documenten gevonden voor deze zoekopdracht',
+ 'documents.list.search.total-count-with-query': '{{ count }} {{ count, =1:document, documenten }} komen overeen met deze zoekopdracht',
+ 'documents.list.search.total-count-no-query': '{{ count }} {{ count, =1:document, documenten }} in totaal',
'documents.tabs.info': 'Info',
'documents.tabs.content': 'Inhoud',
@@ -657,7 +661,7 @@ export const translations: Partial<TranslationsDictionary> = {
'layout.theme.dark': 'Donker thema',
'layout.theme.system': 'Systeemstandaard',
- 'layout.search.placeholder': 'Zoeken...',
+ 'layout.search.placeholder': 'Snel zoeken',
'layout.menu.import-document': 'Een document importeren',
'user-menu.account-settings': 'Accountinstellingen',
diff --git a/apps/papra-client/src/locales/pl.dictionary.ts b/apps/papra-client/src/locales/pl.dictionary.ts
index 8e4a8211..a93ebc40 100644
--- a/apps/papra-client/src/locales/pl.dictionary.ts
+++ b/apps/papra-client/src/locales/pl.dictionary.ts
@@ -328,6 +328,10 @@ export const translations: Partial<TranslationsDictionary> = {
'documents.list.table.headers.deleted': 'Usunięto',
'documents.list.table.headers.actions': 'Akcje',
'documents.list.table.headers.tags': 'Tagi',
+ 'documents.list.search.placeholder': 'Szukaj dokumentów...',
+ 'documents.list.search.no-results': 'Nie znaleziono dokumentów dla tego wyszukiwania',
+ 'documents.list.search.total-count-with-query': '{{ count }} {{ count, =1:dokument, dokumentów }} pasujących do tego wyszukiwania',
+ 'documents.list.search.total-count-no-query': '{{ count }} {{ count, =1:dokument, dokumentów }} łącznie',
'documents.tabs.info': 'Informacje',
'documents.tabs.content': 'Treść',
@@ -657,7 +661,7 @@ export const translations: Partial<TranslationsDictionary> = {
'layout.theme.dark': 'Tryb ciemny',
'layout.theme.system': 'Tryb systemowy',
- 'layout.search.placeholder': 'Szukaj...',
+ 'layout.search.placeholder': 'Szybkie wyszukiwanie',
'layout.menu.import-document': 'Importuj dokument',
'user-menu.account-settings': 'Ustawienia konta',
diff --git a/apps/papra-client/src/locales/pt-BR.dictionary.ts b/apps/papra-client/src/locales/pt-BR.dictionary.ts
index ec725bfc..4beb9fce 100644
--- a/apps/papra-client/src/locales/pt-BR.dictionary.ts
+++ b/apps/papra-client/src/locales/pt-BR.dictionary.ts
@@ -328,6 +328,10 @@ export const translations: Partial<TranslationsDictionary> = {
'documents.list.table.headers.deleted': 'Excluído em',
'documents.list.table.headers.actions': 'Ações',
'documents.list.table.headers.tags': 'Tags',
+ 'documents.list.search.placeholder': 'Buscar documentos...',
+ 'documents.list.search.no-results': 'Nenhum documento encontrado para esta busca',
+ 'documents.list.search.total-count-with-query': '{{ count }} {{ count, =1:documento, documentos }} correspondente a esta busca',
+ 'documents.list.search.total-count-no-query': '{{ count }} {{ count, =1:documento, documentos }} no total',
'documents.tabs.info': 'Informações',
'documents.tabs.content': 'Conteúdo',
@@ -657,7 +661,7 @@ export const translations: Partial<TranslationsDictionary> = {
'layout.theme.dark': 'Tema escuro',
'layout.theme.system': 'Tema do sistema',
- 'layout.search.placeholder': 'Buscar...',
+ 'layout.search.placeholder': 'Busca rápida',
'layout.menu.import-document': 'Importar um documento',
'user-menu.account-settings': 'Configurações da conta',
diff --git a/apps/papra-client/src/locales/pt.dictionary.ts b/apps/papra-client/src/locales/pt.dictionary.ts
index 9d873103..626f54cb 100644
--- a/apps/papra-client/src/locales/pt.dictionary.ts
+++ b/apps/papra-client/src/locales/pt.dictionary.ts
@@ -328,6 +328,10 @@ export const translations: Partial<TranslationsDictionary> = {
'documents.list.table.headers.deleted': 'Eliminado em',
'documents.list.table.headers.actions': 'Ações',
'documents.list.table.headers.tags': 'Etiquetas',
+ 'documents.list.search.placeholder': 'Procurar documentos...',
+ 'documents.list.search.no-results': 'Nenhum documento encontrado para esta pesquisa',
+ 'documents.list.search.total-count-with-query': '{{ count }} {{ count, =1:documento, documentos }} correspondente a esta pesquisa',
+ 'documents.list.search.total-count-no-query': '{{ count }} {{ count, =1:documento, documentos }} no total',
'documents.tabs.info': 'Informação',
'documents.tabs.content': 'Conteúdo',
@@ -657,7 +661,7 @@ export const translations: Partial<TranslationsDictionary> = {
'layout.theme.dark': 'Tema escuro',
'layout.theme.system': 'Tema do sistema',
- 'layout.search.placeholder': 'Procurar...',
+ 'layout.search.placeholder': 'Pesquisa rápida',
'layout.menu.import-document': 'Importar um documento',
'user-menu.account-settings': 'Definições da conta',
diff --git a/apps/papra-client/src/locales/ro.dictionary.ts b/apps/papra-client/src/locales/ro.dictionary.ts
index 5b1a1c94..a42af7d6 100644
--- a/apps/papra-client/src/locales/ro.dictionary.ts
+++ b/apps/papra-client/src/locales/ro.dictionary.ts
@@ -328,6 +328,10 @@ export const translations: Partial<TranslationsDictionary> = {
'documents.list.table.headers.deleted': 'Șters la',
'documents.list.table.headers.actions': 'Acțiuni',
'documents.list.table.headers.tags': 'Etichete',
+ 'documents.list.search.placeholder': 'Caută documente...',
+ 'documents.list.search.no-results': 'Niciun document găsit pentru această căutare',
+ 'documents.list.search.total-count-with-query': '{{ count }} {{ count, =1:document, documente }} corespunzător acestei căutări',
+ 'documents.list.search.total-count-no-query': '{{ count }} {{ count, =1:document, documente }} în total',
'documents.tabs.info': 'Info',
'documents.tabs.content': 'Conținut',
@@ -657,7 +661,7 @@ export const translations: Partial<TranslationsDictionary> = {
'layout.theme.dark': 'Mod intunecat',
'layout.theme.system': 'Modul sistemului',
- 'layout.search.placeholder': 'Căutare...',
+ 'layout.search.placeholder': 'Căutare rapidă',
'layout.menu.import-document': 'Importă un document',
'user-menu.account-settings': 'Setări cont',
diff --git a/apps/papra-client/src/locales/zh.dictionary.ts b/apps/papra-client/src/locales/zh.dictionary.ts
index 756e9e82..1cf880eb 100644
--- a/apps/papra-client/src/locales/zh.dictionary.ts
+++ b/apps/papra-client/src/locales/zh.dictionary.ts
@@ -328,6 +328,10 @@ export const translations: Partial<TranslationsDictionary> = {
'documents.list.table.headers.deleted': '删除时间',
'documents.list.table.headers.actions': '操作',
'documents.list.table.headers.tags': '标签',
+ 'documents.list.search.placeholder': '搜索文档...',
+ 'documents.list.search.no-results': '未找到与此搜索匹配的文档',
+ 'documents.list.search.total-count-with-query': '{{ count }} 个文档与此搜索匹配',
+ 'documents.list.search.total-count-no-query': '共 {{ count }} 个文档',
'documents.tabs.info': '信息',
'documents.tabs.content': '内容',
@@ -657,7 +661,7 @@ export const translations: Partial<TranslationsDictionary> = {
'layout.theme.dark': '深色模式',
'layout.theme.system': '跟随系统',
- 'layout.search.placeholder': '搜索...',
+ 'layout.search.placeholder': '快速搜索',
'layout.menu.import-document': '导入文档',
'user-menu.account-settings': '账户设置',
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 28ed64f1..6c7894e9 100644
--- a/apps/papra-client/src/modules/documents/document.models.test.ts
+++ b/apps/papra-client/src/modules/documents/document.models.test.ts
@@ -1,6 +1,6 @@
import { icons as tablerIconSet } from '@iconify-json/tabler';
import { describe, expect, test } from 'vitest';
-import { fileIcons, getDaysBeforePermanentDeletion, getDocumentIcon, getDocumentNameExtension, getDocumentNameWithoutExtension } from './document.models';
+import { fileIcons, getDaysBeforePermanentDeletion, getDocumentIcon, getDocumentNameExtension, getDocumentNameWithoutExtension, makeDocumentSearchPermalink, makeDocumentSearchQuery } from './document.models';
describe('files models', () => {
describe('iconByFileType', () => {
@@ -255,4 +255,74 @@ describe('files models', () => {
expect(getDocumentNameExtension({ name: 'document.test.txt' })).to.eql('txt');
});
});
+
+ describe('makeDocumentSearchQuery', () => {
+ test('with no search criteria, the search query is an empty string', () => {
+ expect(makeDocumentSearchQuery()).to.eql('');
+ expect(makeDocumentSearchQuery({})).to.eql('');
+ expect(makeDocumentSearchQuery({ tags: [] })).to.eql('');
+ expect(makeDocumentSearchQuery({ query: '' })).to.eql('');
+ expect(makeDocumentSearchQuery({ query: undefined })).to.eql('');
+ expect(makeDocumentSearchQuery({ tags: [], query: '' })).to.eql('');
+ expect(makeDocumentSearchQuery({ tags: [], query: undefined })).to.eql('');
+ });
+
+ test('the tags are prefixed with "tag:" and use preferably the name over the id', () => {
+ expect(
+ makeDocumentSearchQuery({
+ tags: [
+ { name: 'invoices', id: 'tag_1111' },
+ { name: 'receipts' },
+ { id: 'tag_2222' },
+ ],
+ }),
+ ).to.eql('tag:invoices tag:receipts tag:tag_2222');
+ });
+
+ test('the tags are sorted alphabetically in the search query for deterministic results', () => {
+ expect(
+ makeDocumentSearchQuery({
+ tags: [
+ { name: 'bbb' },
+ { name: 'ccc' },
+ { name: 'aaa' },
+ ],
+ }),
+ ).to.eql('tag:aaa tag:bbb tag:ccc');
+ });
+
+ test('the text query is included in the search query', () => {
+ expect(makeDocumentSearchQuery({ query: 'my search' })).to.eql('my search');
+ });
+
+ test('both tags and text query are included in the search query', () => {
+ expect(
+ makeDocumentSearchQuery({
+ tags: [
+ { name: 'invoices' },
+ { id: 'tag_2222' },
+ ],
+ query: 'my search',
+ }),
+ ).to.eql('tag:invoices tag:tag_2222 my search');
+ });
+ });
+
+ describe('makeDocumentSearchPermalink', () => {
+ test('constructs a url-safe permalink for document search with search query', () => {
+ const permalink = makeDocumentSearchPermalink({
+ organizationId: 'org-123',
+ search: {
+ tags: [
+ { name: 'invoices', id: 'tag_1111' },
+ { name: 'receipts' },
+ { id: 'tag_2222' },
+ ],
+ query: 'financial report',
+ },
+ });
+
+ expect(permalink).to.eql('/organizations/org-123/documents?query=tag%3Ainvoices%20tag%3Areceipts%20tag%3Atag_2222%20financial%20report');
+ });
+ });
});
diff --git a/apps/papra-client/src/modules/documents/document.models.ts b/apps/papra-client/src/modules/documents/document.models.ts
index 6d4b16d4..ab204ca4 100644
--- a/apps/papra-client/src/modules/documents/document.models.ts
+++ b/apps/papra-client/src/modules/documents/document.models.ts
@@ -177,3 +177,21 @@ export const documentActivityIcon: Record<DocumentActivityEvent, string> = {
export function getDocumentActivityIcon({ event }: { event: DocumentActivityEvent }) {
return documentActivityIcon[event] ?? 'i-tabler-file';
}
+
+type DocumentSearchCriteria = {
+ tags?: ({ name: string; id?: string } | { id: string; name?: string })[];
+ query?: string;
+};
+
+export function makeDocumentSearchQuery({ tags = [], query }: DocumentSearchCriteria = {}) {
+ return [
+ ...tags.map(t => `tag:${t.name ?? t.id}`).toSorted(),
+ query,
+ ].filter(Boolean).join(' ');
+}
+
+export function makeDocumentSearchPermalink({ organizationId, search }: { organizationId: string; search: DocumentSearchCriteria }) {
+ const queryString = makeDocumentSearchQuery(search);
+
+ return `/organizations/${organizationId}/documents?query=${encodeURIComponent(queryString)}`;
+}
diff --git a/apps/papra-client/src/modules/documents/documents.services.ts b/apps/papra-client/src/modules/documents/documents.services.ts
index 62124c98..bf225f3d 100644
--- a/apps/papra-client/src/modules/documents/documents.services.ts
+++ b/apps/papra-client/src/modules/documents/documents.services.ts
@@ -152,7 +152,12 @@ export async function searchDocuments({
}) {
const {
searchResults,
- } = await apiClient<{ searchResults: { documents: { id: string; name: string }[] } }>({
+ } = await apiClient<{
+ searchResults: {
+ documents: Document[];
+ totalCount: number;
+ };
+ }>({
method: 'GET',
path: `/api/organizations/${organizationId}/documents/search`,
query: {
@@ -163,7 +168,10 @@ export async function searchDocuments({
});
return {
- searchResults,
+ searchResults: {
+ documents: searchResults.documents.map(coerceDates),
+ totalCount: searchResults.totalCount,
+ },
};
}
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 485d31eb..fdaf42bd 100644
--- a/apps/papra-client/src/modules/documents/pages/documents.page.tsx
+++ b/apps/papra-client/src/modules/documents/pages/documents.page.tsx
@@ -1,47 +1,48 @@
import type { Component } from 'solid-js';
import { useParams, useSearchParams } from '@solidjs/router';
import { keepPreviousData, useQuery } from '@tanstack/solid-query';
-import { createSignal, For, Show, Suspense } from 'solid-js';
+import { createEffect, createSignal, Show, Suspense } from 'solid-js';
import { useI18n } from '@/modules/i18n/i18n.provider';
-import { castArray } from '@/modules/shared/utils/array';
-import { Tag } from '@/modules/tags/components/tag.component';
-import { fetchTags } from '@/modules/tags/tags.services';
+import { cn } from '@/modules/shared/style/cn';
+import { asSingleParam } from '@/modules/shared/utils/query-params';
+import { useDebounce } from '@/modules/shared/utils/timing';
+import { Button } from '@/modules/ui/components/button';
+import { TextField, TextFieldRoot } from '@/modules/ui/components/textfield';
import { DocumentUploadArea } from '../components/document-upload-area.component';
import { createdAtColumn, DocumentsPaginatedList, standardActionsColumn, tagsColumn } from '../components/documents-list.component';
-import { fetchOrganizationDocuments } from '../documents.services';
+import { searchDocuments } from '../documents.services';
export const DocumentsPage: Component = () => {
const params = useParams();
const { t } = useI18n();
const [searchParams, setSearchParams] = useSearchParams();
- const [getPagination, setPagination] = createSignal({ pageIndex: 0, pageSize: 100 });
+ const [getSearchQuery, setSearchQuery] = createSignal<string>(asSingleParam(searchParams.query) ?? '');
+ const debouncedSearchQuery = useDebounce(getSearchQuery, 300);
+ const [getPagination, setPagination] = createSignal({ pageIndex: 0, pageSize: 15 });
- const getFiltererTagIds = () => searchParams.tags ? castArray(searchParams.tags) : [];
+ const onSearchInput = (query: string) => {
+ setSearchQuery(query);
+ setSearchParams({ query });
+ };
+
+ createEffect(() => {
+ setSearchQuery(asSingleParam(searchParams.query) ?? '');
+ });
const documentsQuery = useQuery(() => ({
- queryKey: ['organizations', params.organizationId, 'documents', getPagination(), getFiltererTagIds()],
- queryFn: () => fetchOrganizationDocuments({
+ queryKey: ['organizations', params.organizationId, 'documents', getPagination(), debouncedSearchQuery()],
+ queryFn: () => searchDocuments({
organizationId: params.organizationId,
+ searchQuery: debouncedSearchQuery(),
...getPagination(),
- filters: {
- tags: getFiltererTagIds(),
- },
}),
placeholderData: keepPreviousData,
}));
- const tagsQuery = useQuery(() => ({
- queryKey: ['organizations', params.organizationId, 'tags'],
- queryFn: () => fetchTags({ organizationId: params.organizationId }),
- }));
-
- const getFilteredTags = () => tagsQuery.data?.tags.filter(tag => getFiltererTagIds().includes(tag.id)) ?? [];
- const hasFilters = () => getFiltererTagIds().length > 0;
-
return (
<div class="p-6 mt-4 pb-32 max-w-5xl mx-auto">
<Suspense>
- {documentsQuery.data?.documents?.length === 0 && !hasFilters()
+ {documentsQuery.data?.searchResults.documents?.length === 0 && debouncedSearchQuery().length === 0
? (
<>
<h2 class="text-xl font-bold ">
@@ -61,29 +62,54 @@ export const DocumentsPage: Component = () => {
<h2 class="text-lg font-semibold mb-4">
{t('documents.list.title')}
</h2>
- <Show when={hasFilters()}>
- <div class="flex flex-wrap gap-2 mb-4">
- <For each={getFilteredTags()}>
- {tag => (
- <Tag
- {...tag}
- closable
- onClose={() => setSearchParams({ tags: getFiltererTagIds().filter(id => id !== tag.id) })}
- />
- )}
- </For>
- </div>
- </Show>
- <Show when={hasFilters() && documentsQuery.data?.documentsCount === 0}>
+ <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 => onSearchInput(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={() => onSearchInput('')}
+ 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>
+ <div class="mb-4 text-sm text-muted-foreground mt-2 ml-2">
+ <Show
+ when={debouncedSearchQuery().length > 0}
+ fallback={t('documents.list.search.total-count-no-query', { count: documentsQuery.data?.searchResults.totalCount ?? 0 })}
+ >
+ {t('documents.list.search.total-count-with-query', { count: documentsQuery.data?.searchResults.totalCount ?? 0 })}
+ </Show>
+ </div>
+
+ <Show when={debouncedSearchQuery().length > 0 && documentsQuery.data?.searchResults.documents.length === 0}>
<p class="text-muted-foreground mt-1 mb-6">
{t('documents.list.no-results')}
</p>
</Show>
<DocumentsPaginatedList
- documents={documentsQuery.data?.documents ?? []}
- documentsCount={documentsQuery.data?.documentsCount ?? 0}
+ documents={documentsQuery.data?.searchResults.documents ?? []}
+ documentsCount={documentsQuery.data?.searchResults.totalCount ?? 0}
getPagination={getPagination}
setPagination={setPagination}
extraColumns={[
diff --git a/apps/papra-client/src/modules/shared/utils/query-params.test.ts b/apps/papra-client/src/modules/shared/utils/query-params.test.ts
new file mode 100644
index 00000000..eefb0f32
--- /dev/null
+++ b/apps/papra-client/src/modules/shared/utils/query-params.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, test } from 'vitest';
+import { asSingleParam } from './query-params';
+
+describe('query-params', () => {
+ describe('asSingleParam', () => {
+ test('simple helper to help cast query params to a single string as they can be string or string[], taking only the first element if array', () => {
+ expect(asSingleParam('test')).to.eql('test');
+ expect(asSingleParam(['test1', 'test2'])).to.eql('test1');
+ expect(asSingleParam(undefined)).to.eql(undefined);
+ expect(asSingleParam([])).to.eql(undefined);
+ });
+ });
+});
diff --git a/apps/papra-client/src/modules/shared/utils/query-params.ts b/apps/papra-client/src/modules/shared/utils/query-params.ts
new file mode 100644
index 00000000..dbc37789
--- /dev/null
+++ b/apps/papra-client/src/modules/shared/utils/query-params.ts
@@ -0,0 +1,6 @@
+export function asSingleParam(param: string | string[] | undefined): string | undefined {
+ if (Array.isArray(param)) {
+ return param[0];
+ }
+ return param;
+}
diff --git a/apps/papra-client/src/modules/shared/utils/timing.ts b/apps/papra-client/src/modules/shared/utils/timing.ts
index 782933b1..6df1e487 100644
--- a/apps/papra-client/src/modules/shared/utils/timing.ts
+++ b/apps/papra-client/src/modules/shared/utils/timing.ts
@@ -1,3 +1,6 @@
+import type { Accessor } from 'solid-js';
+import { createEffect, createSignal } from 'solid-js';
+
/**
* Creates a debounced function that delays invoking func until after wait milliseconds
* have elapsed since the last time the debounced function was invoked.
@@ -85,3 +88,15 @@ export function throttle<Args extends unknown[], Return>(
}, waitMs - timeSinceLastCall);
};
}
+
+export function useDebounce<T>(signal: Accessor<T>, waitMs: number = 500): Accessor<T> {
+ const [debouncedValue, setDebouncedValue] = createSignal<T>(signal());
+
+ const debouncedSetter = debounce((value: T) => setDebouncedValue(() => value), waitMs);
+
+ createEffect(() => {
+ debouncedSetter(signal());
+ });
+
+ return debouncedValue;
+}
diff --git a/apps/papra-client/src/modules/tags/components/tag.component.tsx b/apps/papra-client/src/modules/tags/components/tag.component.tsx
index 3e6c148f..15269cbc 100644
--- a/apps/papra-client/src/modules/tags/components/tag.component.tsx
+++ b/apps/papra-client/src/modules/tags/components/tag.component.tsx
@@ -1,9 +1,11 @@
import type { Component, ComponentProps } from 'solid-js';
import { A } from '@solidjs/router';
import { splitProps } from 'solid-js';
+import { makeDocumentSearchPermalink } from '@/modules/documents/document.models';
import { cn } from '@/modules/shared/style/cn';
type TagProps = {
+ id?: string;
name?: string;
description?: string | null;
color?: string;
@@ -12,7 +14,7 @@ type TagProps = {
};
export const Tag: Component<TagProps & ComponentProps<'span'>> = (props) => {
- const [local, rest] = splitProps(props, ['name', 'description', 'color', 'class']);
+ const [local, rest] = splitProps(props, ['id', 'name', 'description', 'color', 'class']);
return (
<span
@@ -37,18 +39,19 @@ export const Tag: Component<TagProps & ComponentProps<'span'>> = (props) => {
};
type TagLinkProps = {
- name?: string;
+ id?: string;
+ name: string;
description?: string | null;
color?: string;
organizationId: string;
};
export const TagLink: Component<TagLinkProps & Omit<ComponentProps<typeof A>, 'href'> & { href?: string }> = (props) => {
- const [local, rest] = splitProps(props, ['name', 'description', 'color', 'class', 'href']);
+ const [local, rest] = splitProps(props, ['id', 'name', 'description', 'color', 'class', 'href']);
return (
<A
- href={props.href ?? `/organizations/${props.organizationId}/documents?tags=${props.id}`}
+ href={props.href ?? makeDocumentSearchPermalink({ organizationId: props.organizationId, search: { tags: [props] } })}
class={cn(
'inline-flex gap-2 px-2.5 py-1 leading-none rounded-lg text-sm items-center bg-muted group hover:underline',
local.class,
diff --git a/apps/papra-client/src/modules/tags/pages/tags.page.tsx b/apps/papra-client/src/modules/tags/pages/tags.page.tsx
index ff460e20..dafeebf9 100644
--- a/apps/papra-client/src/modules/tags/pages/tags.page.tsx
+++ b/apps/papra-client/src/modules/tags/pages/tags.page.tsx
@@ -7,6 +7,7 @@ import { A, useParams } from '@solidjs/router';
import { useQuery } from '@tanstack/solid-query';
import { createSignal, For, Show, Suspense } from 'solid-js';
import * as v from 'valibot';
+import { makeDocumentSearchPermalink } from '@/modules/documents/document.models';
import { RelativeTime } from '@/modules/i18n/components/RelativeTime';
import { useI18n } from '@/modules/i18n/i18n.provider';
import { useConfirmModal } from '@/modules/shared/confirm';
@@ -349,7 +350,7 @@ export const TagsPage: Component = () => {
</TableCell>
<TableCell class="text-wrap">{tag.description || <span class="text-muted-foreground">{t('tags.form.no-description')}</span>}</TableCell>
<TableCell>
- <A href={`/organizations/${params.organizationId}/documents?tags=${tag.id}`} class="inline-flex items-center gap-1 hover:underline">
+ <A href={makeDocumentSearchPermalink({ organizationId: params.organizationId, search: { tags: [tag] } })} class="inline-flex items-center gap-1 hover:underline">
<div class="i-tabler-file-text size-5 text-muted-foreground" />
{tag.documentsCount}
</A>
diff --git a/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.test.ts b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.test.ts
index 506e1b3b..522a0220 100644
--- a/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.test.ts
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.test.ts
@@ -73,104 +73,188 @@ describe('database-fts5 repository', () => {
expect(searchResults2.map(doc => doc.id)).to.eql(['doc_1']);
});
- test('the total count of search results is returned for pagination', async () => {
- const documents = Array.from({ length: 15 }).map((_, index) => ({
- id: `doc_${index + 1}`,
- organizationId: 'org_1',
- name: `Document ${index + 1}`,
- originalName: `document-${index + 1}.pdf`,
- content: 'lorem ipsum dolor sit amet',
- originalStorageKey: '',
- mimeType: 'application/pdf',
- originalSha256Hash: `hash${index + 1}`,
- isDeleted: false,
- }));
+ describe('total count', () => {
+ test('the total count of search results is returned for pagination', async () => {
+ const documents = Array.from({ length: 15 }).map((_, index) => ({
+ id: `doc_${index + 1}`,
+ organizationId: 'org_1',
+ name: `Document ${index + 1}`,
+ originalName: `document-${index + 1}.pdf`,
+ content: 'lorem ipsum dolor sit amet',
+ originalStorageKey: '',
+ mimeType: 'application/pdf',
+ originalSha256Hash: `hash${index + 1}`,
+ isDeleted: false,
+ }));
- const { db } = await createInMemoryDatabase({
- organizations: [{ id: 'org_1', name: 'Organization 1' }],
- documents,
- });
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org_1', name: 'Organization 1' }],
+ documents,
+ });
- const documentsSearchRepository = createDocumentSearchRepository({ db });
+ const documentsSearchRepository = createDocumentSearchRepository({ db });
- await Promise.all(
- documents.map(async document => documentsSearchRepository.indexDocument({ document })),
- );
+ await Promise.all(
+ documents.map(async document => documentsSearchRepository.indexDocument({ document })),
+ );
- const { totalCount, documents: searchDocuments } = await documentsSearchRepository.searchOrganizationDocuments({
- organizationId: 'org_1',
- searchQuery: 'lorem',
- pageIndex: 0,
- pageSize: 10,
+ const { totalCount, documents: searchDocuments } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'lorem',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(totalCount).to.equal(15);
+ expect(searchDocuments).to.have.length(10);
});
- expect(totalCount).to.equal(15);
- expect(searchDocuments).to.have.length(10);
- });
+ test('no results means total count is zero', async () => {
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org_1', name: 'Organization 1' }],
+ });
- test('no results means total count is zero', async () => {
- const { db } = await createInMemoryDatabase({
- organizations: [{ id: 'org_1', name: 'Organization 1' }],
- });
+ const documentsSearchRepository = createDocumentSearchRepository({ db });
- const documentsSearchRepository = createDocumentSearchRepository({ db });
+ const { totalCount, documents: searchDocuments } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'nonexistent',
+ pageIndex: 0,
+ pageSize: 10,
+ });
- const { totalCount, documents: searchDocuments } = await documentsSearchRepository.searchOrganizationDocuments({
- organizationId: 'org_1',
- searchQuery: 'nonexistent',
- pageIndex: 0,
- pageSize: 10,
+ expect(totalCount).to.equal(0);
+ expect(searchDocuments).to.have.length(0);
});
- expect(totalCount).to.equal(0);
- expect(searchDocuments).to.have.length(0);
- });
+ test('document with multiple matching tags are not double-counted', async () => {
+ const documents = [
+ { id: 'doc_1', organizationId: 'org_1', name: 'Document 1', originalName: 'document-1.pdf', content: 'lorem ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash1', isDeleted: false },
+ { id: 'doc_2', organizationId: 'org_1', name: 'Document 2', originalName: 'document-2.pdf', content: 'lorem ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash2', isDeleted: false },
+ ];
+
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org_1', name: 'Organization 1' }],
+ documents,
+ tags: [
+ { id: 'tag_1', organizationId: 'org_1', name: 'tag1', color: '#ff0000' },
+ { id: 'tag_2', organizationId: 'org_1', name: 'tag2', color: '#00ff00' },
+ ],
+ documentsTags: [
+ { documentId: 'doc_1', tagId: 'tag_1' },
+ { documentId: 'doc_1', tagId: 'tag_2' },
+ { documentId: 'doc_2', tagId: 'tag_1' },
+ ],
+ });
- test('pagination permits retrieving subsequent pages of results', async () => {
- const documents = Array.from({ length: 25 }).map((_, index) => ({
- id: `doc_${index + 1}`,
- organizationId: 'org_1',
- name: `Document ${index + 1}`,
- originalName: `document-${index + 1}.pdf`,
- content: 'lorem ipsum dolor sit amet',
- originalStorageKey: '',
- mimeType: 'application/pdf',
- originalSha256Hash: `hash${index + 1}`,
- isDeleted: false,
- }));
+ const documentsSearchRepository = createDocumentSearchRepository({ db });
- const { db } = await createInMemoryDatabase({
- organizations: [{ id: 'org_1', name: 'Organization 1' }],
- documents,
+ await Promise.all(
+ documents.map(async document => documentsSearchRepository.indexDocument({ document })),
+ );
+
+ const { totalCount, documents: searchDocuments } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'lorem',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(totalCount).to.equal(2);
+ expect(searchDocuments).to.have.length(2);
});
+ });
- const documentsSearchRepository = createDocumentSearchRepository({ db });
+ describe('pagination', () => {
+ test('pagination permits retrieving subsequent pages of results', async () => {
+ const documents = Array.from({ length: 25 }).map((_, index) => ({
+ id: `doc_${index + 1}`,
+ organizationId: 'org_1',
+ name: `Document ${index + 1}`,
+ originalName: `document-${index + 1}.pdf`,
+ content: 'lorem ipsum dolor sit amet',
+ originalStorageKey: '',
+ mimeType: 'application/pdf',
+ originalSha256Hash: `hash${index + 1}`,
+ isDeleted: false,
+ createdAt: new Date(`2026-01-${String(index + 1).padStart(2, '0')}`),
+ }));
- await Promise.all(
- documents.map(async document => documentsSearchRepository.indexDocument({ document })),
- );
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org_1', name: 'Organization 1' }],
+ documents,
+ });
- const { documents: firstPageDocuments, totalCount: firstTotalCount } = await documentsSearchRepository.searchOrganizationDocuments({
- organizationId: 'org_1',
- searchQuery: 'lorem',
- pageIndex: 0,
- pageSize: 10,
- });
+ const documentsSearchRepository = createDocumentSearchRepository({ db });
- expect(firstPageDocuments).to.have.length(10);
- expect(firstTotalCount).to.equal(25);
- expect(firstPageDocuments.map(doc => doc.id)).to.eql(['doc_1', 'doc_2', 'doc_3', 'doc_4', 'doc_5', 'doc_6', 'doc_7', 'doc_8', 'doc_9', 'doc_10']);
+ await Promise.all(
+ documents.map(async document => documentsSearchRepository.indexDocument({ document })),
+ );
- const { documents: secondPageDocuments, totalCount: secondTotalCount } = await documentsSearchRepository.searchOrganizationDocuments({
- organizationId: 'org_1',
- searchQuery: 'lorem',
- pageIndex: 1,
- pageSize: 5,
+ const { documents: firstPageDocuments, totalCount: firstTotalCount } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'lorem',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(firstPageDocuments).to.have.length(10);
+ expect(firstTotalCount).to.equal(25);
+ expect(firstPageDocuments.map(doc => doc.id)).to.eql(['doc_25', 'doc_24', 'doc_23', 'doc_22', 'doc_21', 'doc_20', 'doc_19', 'doc_18', 'doc_17', 'doc_16']);
+
+ const { documents: secondPageDocuments, totalCount: secondTotalCount } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'lorem',
+ pageIndex: 1,
+ pageSize: 5,
+ });
+
+ expect(secondPageDocuments).to.have.length(5);
+ expect(secondTotalCount).to.equal(25);
+ expect(secondPageDocuments.map(doc => doc.id)).to.eql(['doc_20', 'doc_19', 'doc_18', 'doc_17', 'doc_16']);
});
- expect(secondPageDocuments).to.have.length(5);
- expect(secondTotalCount).to.equal(25);
- expect(secondPageDocuments.map(doc => doc.id)).to.eql(['doc_6', 'doc_7', 'doc_8', 'doc_9', 'doc_10']);
+ test('with multiple tags per documents, the page size is respected', async () => {
+ const documents = Array.from({ length: 20 }).map((_, index) => ({
+ id: `doc_${index + 1}`,
+ organizationId: 'org_1',
+ name: `Document ${index + 1}`,
+ originalName: `document-${index + 1}.pdf`,
+ content: 'lorem ipsum dolor sit amet',
+ originalStorageKey: '',
+ mimeType: 'application/pdf',
+ originalSha256Hash: `hash${index + 1}`,
+ isDeleted: false,
+ }));
+
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org_1', name: 'Organization 1' }],
+ documents,
+ tags: [
+ { id: 'tag_1', organizationId: 'org_1', name: 'tag1', color: '#ff0000' },
+ { id: 'tag_2', organizationId: 'org_1', name: 'tag2', color: '#00ff00' },
+ ],
+ documentsTags: [
+ { documentId: 'doc_1', tagId: 'tag_1' },
+ { documentId: 'doc_1', tagId: 'tag_2' },
+ ],
+ });
+
+ const documentsSearchRepository = createDocumentSearchRepository({ db });
+ await Promise.all(
+ documents.map(async document => documentsSearchRepository.indexDocument({ document })),
+ );
+
+ const { documents: firstPageDocuments, totalCount } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'lorem',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(firstPageDocuments).to.have.length(10);
+ expect(totalCount).to.equal(20);
+ });
});
describe('search query can have filters', async () => {
@@ -307,6 +391,83 @@ describe('database-fts5 repository', () => {
// Even though "Organization 2" appears in org_2's documents, org_1 search should return nothing
expect(org1SpecificSearch).to.have.length(0);
});
+
+ test('documents are ordered by creation date descending', async () => {
+ const documents = [
+ { id: 'doc_1', organizationId: 'org_1', name: 'Document 1', originalName: 'document-1.pdf', content: 'lorem ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash1', isDeleted: false, createdAt: new Date('2023-01-02T10:00:00Z') },
+ { id: 'doc_2', organizationId: 'org_1', name: 'Document 2', originalName: 'document-2.pdf', content: 'lorem ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash2', isDeleted: false, createdAt: new Date('2023-01-01T10:00:00Z') },
+ { id: 'doc_3', organizationId: 'org_1', name: 'Document 3', originalName: 'document-3.pdf', content: 'lorem ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash3', isDeleted: false, createdAt: new Date('2023-01-03T10:00:00Z') },
+ ];
+
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org_1', name: 'Organization 1' }],
+ documents,
+ });
+
+ const documentsSearchRepository = createDocumentSearchRepository({ db });
+
+ await Promise.all(
+ documents.map(async document => documentsSearchRepository.indexDocument({ document })),
+ );
+
+ const { documents: searchResults } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'lorem',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(searchResults).to.have.length(3);
+ expect(searchResults.map(doc => doc.id)).to.eql(['doc_3', 'doc_1', 'doc_2']);
+ });
+
+ test('documents are retrieved with their tags', async () => {
+ const documents = [
+ { id: 'doc_1', organizationId: 'org_1', name: 'Document 1', originalName: 'document-1.pdf', content: 'lorem ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash1', isDeleted: false },
+ { id: 'doc_2', organizationId: 'org_1', name: 'Document 2', originalName: 'document-2.pdf', content: 'lorem ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash2', isDeleted: false },
+ ];
+
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org_1', name: 'Organization 1' }],
+ documents,
+ tags: [
+ { id: 'tag_1', organizationId: 'org_1', name: 'tag1', color: '#ff0000' },
+ { id: 'tag_2', organizationId: 'org_1', name: 'tag2', color: '#00ff00' },
+ ],
+ documentsTags: [
+ { documentId: 'doc_1', tagId: 'tag_1' },
+ { documentId: 'doc_1', tagId: 'tag_2' },
+ ],
+ });
+
+ const documentsSearchRepository = createDocumentSearchRepository({ db });
+
+ await Promise.all(
+ documents.map(async document => documentsSearchRepository.indexDocument({ document })),
+ );
+
+ const { documents: searchResults, totalCount } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'lorem',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(searchResults).to.have.length(2);
+ expect(totalCount).to.equal(2);
+ expect(
+ searchResults.map(doc => ({
+ id: doc.id,
+ tags: doc.tags.map(({ id, organizationId, name, color }) => ({ id, organizationId, name, color })),
+ })).toSorted((a, b) => a.id.localeCompare(b.id)),
+ ).to.eql([
+ { id: 'doc_1', tags: [
+ { id: 'tag_1', organizationId: 'org_1', name: 'tag1', color: '#ff0000' },
+ { id: 'tag_2', organizationId: 'org_1', name: 'tag2', color: '#00ff00' },
+ ] },
+ { id: 'doc_2', tags: [] },
+ ]);
+ });
});
describe('indexDocument', () => {
diff --git a/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.ts b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.ts
index 5cdd7fa7..c1e363c4 100644
--- a/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.ts
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.ts
@@ -1,8 +1,12 @@
import type { Database } from '../../../app/database/database.types';
+import type { Tag } from '../../../tags/tags.types';
+import type { Document } from '../../documents.types';
import type { DocumentSearchableData } from '../document-search.types';
import { injectArguments } from '@corentinth/chisels';
-import { asc, eq, sql } from 'drizzle-orm';
+import { desc, eq, getTableColumns, sql } from 'drizzle-orm';
+import { omit } from 'lodash-es';
import { omitUndefined } from '../../../shared/utils';
+import { documentsTagsTable, tagsTable } from '../../../tags/tags.table';
import { documentsTable } from '../../documents.table';
import { makeSearchWhereClause } from './database-fts5.repository.models';
import { documentsFtsTable } from './database-fts5.tables';
@@ -21,20 +25,56 @@ export function createDocumentSearchRepository({ db }: { db: Database }) {
async function searchOrganizationDocuments({ organizationId, searchQuery, pageIndex, pageSize, db }: { organizationId: string; searchQuery: string; pageIndex: number; pageSize: number; db: Database }) {
const { searchWhereClause } = makeSearchWhereClause({ organizationId, query: searchQuery, db });
- const documentsWithTotalCount = await db.selectDistinct({
- id: documentsTable.id,
- organizationId: documentsTable.organizationId,
- name: documentsTable.name,
- totalCount: sql<number>`COUNT(*) OVER()`,
- })
+ const paginatedIdsSubquery = db
+ .selectDistinct({ id: documentsTable.id, createdAt: documentsTable.createdAt })
.from(documentsTable)
.where(searchWhereClause)
- .orderBy(asc(documentsTable.createdAt))
+ .orderBy(desc(documentsTable.createdAt))
.limit(pageSize)
- .offset(pageIndex * pageSize);
+ .offset(pageIndex * pageSize)
+ .as('paginated_docs');
- const documents = documentsWithTotalCount.map(({ id, name }) => ({ id, name }));
- const totalCount = documentsWithTotalCount[0]?.totalCount ?? 0;
+ const [totalCountResult, documentsWithTags] = await Promise.all([
+ db
+ .select({ count: sql<number>`COUNT(DISTINCT ${documentsTable.id})` })
+ .from(documentsTable)
+ .where(searchWhereClause),
+
+ db
+ .selectDistinct({
+ document: omit(getTableColumns(documentsTable), ['content']),
+ tag: getTableColumns(tagsTable),
+ _createdAt: paginatedIdsSubquery.createdAt,
+ })
+ .from(paginatedIdsSubquery)
+ .innerJoin(documentsTable, eq(documentsTable.id, paginatedIdsSubquery.id))
+ .leftJoin(documentsTagsTable, eq(documentsTable.id, documentsTagsTable.documentId))
+ .leftJoin(tagsTable, eq(tagsTable.id, documentsTagsTable.tagId))
+ .orderBy(desc(paginatedIdsSubquery.createdAt)),
+ ]);
+
+ const totalCount = totalCountResult[0]?.count ?? 0;
+
+ if (documentsWithTags.length === 0) {
+ return { documents: [], totalCount };
+ }
+
+ const documentsMap = documentsWithTags.reduce(
+ (acc, { document, tag }) => {
+ if (!acc[document.id]) {
+ acc[document.id] = { ...document, tags: [] };
+ }
+
+ if (tag) {
+ acc[document.id]!.tags.push(tag);
+ }
+
+ return acc;
+ },
+ {} as Record<string, Omit<Document, 'content'> & { tags: Tag[] }>,
+ );
+
+ const documents = Object.values(documentsMap);
return { documents, totalCount };
}
diff --git a/apps/papra-server/src/modules/documents/document-search/document-search.types.ts b/apps/papra-server/src/modules/documents/document-search/document-search.types.ts
index 692dcf87..a70ea48f 100644
--- a/apps/papra-server/src/modules/documents/document-search/document-search.types.ts
+++ b/apps/papra-server/src/modules/documents/document-search/document-search.types.ts
@@ -1,3 +1,5 @@
+import type { Document } from '../documents.types';
+
export type DocumentSearchableData = {
id: string;
name: string;
@@ -14,7 +16,7 @@ export type DocumentSearchServices = {
organizationId: string;
pageIndex: number;
pageSize: number;
- }) => Promise<{ searchResults: { documents: { id: string; name: string }[]; totalCount: number } }>;
+ }) => Promise<{ searchResults: { documents: Omit<Document, 'content'>[]; totalCount: number } }>;
indexDocument: (args: { document: DocumentSearchableData }) => Promise<void>;
updateDocument: (args: { documentId: string; document: Partial<Omit<DocumentSearchableData, 'id'>> }) => Promise<void>;
diff --git a/apps/papra-server/src/modules/documents/documents.repository.ts b/apps/papra-server/src/modules/documents/documents.repository.ts
index c1de5e56..02e8d5b0 100644
--- a/apps/papra-server/src/modules/documents/documents.repository.ts
+++ b/apps/papra-server/src/modules/documents/documents.repository.ts
@@ -82,7 +82,7 @@ async function saveOrganizationDocument({ db, ...documentToInsert }: { db: Datab
return { document };
}
-async function getOrganizationDocumentsCount({ organizationId, filters, db }: { organizationId: string; filters?: { tags?: string[] }; db: Database }) {
+async function getOrganizationDocumentsCount({ organizationId, db }: { organizationId: string; db: Database }) {
const [record] = await db
.select({
documentsCount: count(documentsTable.id),
@@ -93,7 +93,6 @@ async function getOrganizationDocumentsCount({ organizationId, filters, db }: {
and(
eq(documentsTable.organizationId, organizationId),
eq(documentsTable.isDeleted, false),
- ...(filters?.tags ? filters.tags.map(tag => eq(documentsTagsTable.tagId, tag)) : []),
),
);
@@ -132,13 +131,11 @@ async function getOrganizationDocuments({
organizationId,
pageIndex,
pageSize,
- filters,
db,
}: {
organizationId: string;
pageIndex: number;
pageSize: number;
- filters?: { tags?: string[] };
db: Database;
}) {
const query = db
@@ -153,7 +150,6 @@ async function getOrganizationDocuments({
and(
eq(documentsTable.organizationId, organizationId),
eq(documentsTable.isDeleted, false),
- ...(filters?.tags ? filters.tags.map(tag => eq(documentsTagsTable.tagId, tag)) : []),
),
);
diff --git a/apps/papra-server/src/modules/documents/documents.routes.ts b/apps/papra-server/src/modules/documents/documents.routes.ts
index faea098d..01cbd68f 100644
--- a/apps/papra-server/src/modules/documents/documents.routes.ts
+++ b/apps/papra-server/src/modules/documents/documents.routes.ts
@@ -82,17 +82,13 @@ function setupGetDocumentsRoute({ app, db }: RouteDefinitionContext) {
z.object({
pageIndex: z.coerce.number().min(0).int().optional().default(0),
pageSize: z.coerce.number().min(1).max(100).int().optional().default(100),
- tags: z.union([
- z.array(z.string()),
- z.string().transform(value => [value]),
- ]).optional(),
}),
),
async (context) => {
const { userId } = getUser({ context });
const { organizationId } = context.req.valid('param');
- const { pageIndex, pageSize, tags } = context.req.valid('query');
+ const { pageIndex, pageSize } = context.req.valid('query');
const documentsRepository = createDocumentsRepository({ db });
const organizationsRepository = createOrganizationsRepository({ db });
@@ -103,8 +99,8 @@ function setupGetDocumentsRoute({ app, db }: RouteDefinitionContext) {
{ documents },
{ documentsCount },
] = await Promise.all([
- documentsRepository.getOrganizationDocuments({ organizationId, pageIndex, pageSize, filters: { tags } }),
- documentsRepository.getOrganizationDocumentsCount({ organizationId, filters: { tags } }),
+ documentsRepository.getOrganizationDocuments({ organizationId, pageIndex, pageSize }),
+ documentsRepository.getOrganizationDocumentsCount({ organizationId }),
]);
return context.json({