The minimalistic document archiving platform.
feat(documents): added document search (#11)
Corentin THOMASSET74b5884e30c9
diff --git a/apps/papra-client/package.json b/apps/papra-client/package.jsonindex fd626261..a92a2469 100644--- a/apps/papra-client/package.json+++ b/apps/papra-client/package.json@@ -39,6 +39,7 @@"@unocss/reset": "^0.64.0","class-variance-authority": "^0.7.0","clsx": "^2.1.1",+ "cmdk-solid": "^1.1.0","date-fns": "^4.1.0","jszip": "^3.10.1","lodash-es": "^4.17.21",diff --git a/apps/papra-client/src/index.tsx b/apps/papra-client/src/index.tsxindex c44410bf..76700b78 100644--- a/apps/papra-client/src/index.tsx+++ b/apps/papra-client/src/index.tsx@@ -1,10 +1,12 @@/* @refresh reload */+import type { ConfigColorMode } from '@kobalte/core/color-mode';import { ColorModeProvider, ColorModeScript, createLocalStorageManager } from '@kobalte/core/color-mode';import { Router } from '@solidjs/router';import { QueryClientProvider } from '@tanstack/solid-query';import { render, Suspense } from 'solid-js/web';+import { CommandPaletteProvider } from './modules/command-palette/command-palette.provider';import { ConfirmModalProvider } from './modules/shared/confirm';import { queryClient } from './modules/shared/query/query-client';import { Toaster } from './modules/ui/components/sonner';@@ -15,7 +17,7 @@ import './app.css';render(() => {- const initialColorMode = 'system';+ const initialColorMode: ConfigColorMode = 'dark';const colorModeStorageKey = 'papra_color_mode';const localStorageManager = createLocalStorageManager(colorModeStorageKey);@@ -31,10 +33,13 @@ render(initialColorMode={initialColorMode}storageManager={localStorageManager}>- <div class="min-h-screen font-sans text-sm font-400">{props.children}</div>- <Toaster />+ <CommandPaletteProvider>+ <div class="min-h-screen font-sans text-sm font-400">{props.children}</div>+ <Toaster />+ </CommandPaletteProvider></ColorModeProvider>+</ConfirmModalProvider></Suspense></QueryClientProvider>diff --git a/apps/papra-client/src/modules/command-palette/command-palette.provider.tsx b/apps/papra-client/src/modules/command-palette/command-palette.provider.tsxnew file mode 100644index 00000000..4e7a1796--- /dev/null+++ b/apps/papra-client/src/modules/command-palette/command-palette.provider.tsx@@ -0,0 +1,151 @@+import type { Accessor, ParentComponent } from 'solid-js';+import type { Document } from '../documents/documents.types';+import { useNavigate, useParams } from '@solidjs/router';+import { debounce } from 'lodash-es';+import { createContext, createEffect, createSignal, For, on, onCleanup, onMount, Show, useContext } from 'solid-js';+import { getDocumentIcon } from '../documents/document.models';+import { searchDocuments } from '../documents/documents.services';+import { cn } from '../shared/style/cn';+import { useThemeStore } from '../theme/theme.store';+import { CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandLoading } from '../ui/components/command';++const CommandPaletteContext = createContext<{+ getIsCommandPaletteOpen: Accessor<boolean>;+ openCommandPalette: () => void;+ closeCommandPalette: () => void;+}>();++export function useCommandPalette() {+ const context = useContext(CommandPaletteContext);++ if (!context) {+ throw new Error('CommandPalette context not found');+ }++ return context;+}++export const CommandPaletteProvider: ParentComponent = (props) => {+ const [getIsCommandPaletteOpen, setIsCommandPaletteOpen] = createSignal(false);+ const [getMatchingDocuments, setMatchingDocuments] = createSignal<Document[]>([]);+ const [getSearchQuery, setSearchQuery] = createSignal('');+ const params = useParams();+ const [getIsLoading, setIsLoading] = createSignal(false);++ const handleKeyDown = (e: KeyboardEvent) => {+ if (e.key === 'k' && (e.metaKey || e.ctrlKey)) {+ e.preventDefault();+ setIsCommandPaletteOpen(true);+ }+ };++ onMount(() => {+ document.addEventListener('keydown', handleKeyDown);+ });++ onCleanup(() => {+ document.removeEventListener('keydown', handleKeyDown);+ });++ const navigate = useNavigate();+ const { setColorMode } = useThemeStore();++ const searchDocs = debounce(async ({ searchQuery }: { searchQuery: string }) => {+ const { documents } = await searchDocuments({ searchQuery, organizationId: params.organizationId, pageIndex: 0, pageSize: 5 });+ setMatchingDocuments(documents);+ setIsLoading(false);+ }, 300);++ createEffect(on(+ getSearchQuery,+ (searchQuery) => {+ setMatchingDocuments([]);+ if (searchQuery.length > 1) {+ setIsLoading(true);+ searchDocs({ searchQuery });+ }+ },+ ));++ const getCommandData = () => [+ {+ label: 'Documents',+ options: getMatchingDocuments().map(document => ({+ label: document.name,+ icon: getDocumentIcon({ document }),+ action: () => navigate(`/organizations/${params.organizationId}/documents/${document.id}`),+ })),+ },+ {+ label: `Theme`,+ options: [+ {+ label: 'Switch to light mode',+ icon: 'i-tabler-sun',+ action: () => setColorMode({ mode: 'light' }),+ },+ {+ label: 'Switch to dark mode',+ icon: 'i-tabler-moon',+ action: () => setColorMode({ mode: 'dark' }),+ },+ {+ label: 'Switch to system',+ icon: 'i-tabler-device-laptop',+ action: () => setColorMode({ mode: 'system' }),+ },+ ],+ },+ ];++ const onCommandSelect = ({ action }: { action: () => void }) => {+ action();+ setIsCommandPaletteOpen(false);+ };++ return (+ <CommandPaletteContext.Provider value={{+ getIsCommandPaletteOpen,+ openCommandPalette: () => setIsCommandPaletteOpen(true),+ closeCommandPalette: () => setIsCommandPaletteOpen(false),+ }}+ >+ <CommandDialog+ class="rounded-lg border shadow-md"+ open={getIsCommandPaletteOpen()}+ onOpenChange={setIsCommandPaletteOpen}+ >+ <CommandInput placeholder="Search commands" onValueChange={setSearchQuery} />+ <CommandList>+ <Show when={getIsLoading()}>+ <CommandLoading>+ <div class="i-tabler-loader-2 size-6 animate-spin text-muted-foreground mx-auto"></div>+ </CommandLoading>+ </Show>+ <Show when={!getIsLoading()}>+ <CommandEmpty>+ No results found.+ </CommandEmpty>++ <For each={getCommandData().filter(section => section.options.length > 0)}>+ {section => (+ <CommandGroup heading={section.label}>+ <For each={section.options}>+ {item => (+ <CommandItem onSelect={() => onCommandSelect(item)}>+ <span class={cn('mr-2 ml-2 size-4 text-primary', item.icon)} />+ <span>{item.label}</span>+ </CommandItem>+ )}+ </For>+ </CommandGroup>+ )}+ </For>+ </Show>+ </CommandList>+ </CommandDialog>++ {props.children}+ </CommandPaletteContext.Provider>+ );+};diff --git a/apps/papra-client/src/modules/documents/documents.services.ts b/apps/papra-client/src/modules/documents/documents.services.tsindex d6967c71..e88d91b3 100644--- a/apps/papra-client/src/modules/documents/documents.services.ts+++ b/apps/papra-client/src/modules/documents/documents.services.ts@@ -106,3 +106,35 @@ export async function fetchDocumentFile({return blob;}++export async function searchDocuments({+ organizationId,+ searchQuery,+ pageIndex,+ pageSize,+}: {+ organizationId: string;+ searchQuery: string;+ pageIndex: number;+ pageSize: number;+}) {+ const {+ documents,+ } = await apiClient<{ documents: Document[] }>({+ method: 'GET',+ path: `/api/organizations/${organizationId}/documents/search`,+ queryParams: {+ searchQuery,+ pageIndex,+ pageSize,+ },+ });++ return {+ documents: documents.map(document => ({+ ...document,+ createdAt: new Date(document.createdAt),+ updatedAt: document.updatedAt ? new Date(document.updatedAt) : undefined,+ })),+ };+}diff --git a/apps/papra-client/src/modules/ui/components/command.tsx b/apps/papra-client/src/modules/ui/components/command.tsxnew file mode 100644index 00000000..d118820a--- /dev/null+++ b/apps/papra-client/src/modules/ui/components/command.tsx@@ -0,0 +1,163 @@+import type {+ CommandDialogProps,+ CommandEmptyProps,+ CommandGroupProps,+ CommandInputProps,+ CommandItemProps,+ CommandListProps,+ CommandLoadingProps,+ CommandRootProps,+} from 'cmdk-solid';+import type { ComponentProps, VoidProps } from 'solid-js';+import { cn } from '@/modules/shared/style/cn';+import { Command as CommandPrimitive } from 'cmdk-solid';+import { splitProps } from 'solid-js';+import { Dialog, DialogContent } from './dialog';++export function Command(props: CommandRootProps) {+ const [local, rest] = splitProps(props, ['class']);++ return (+ <CommandPrimitive+ class={cn(+ 'flex size-full flex-col overflow-hidden bg-popover text-popover-foreground',+ local.class,+ )}+ {...rest}+ />+ );+}++export function CommandLoading(props: CommandLoadingProps) {+ const [local, rest] = splitProps(props, ['class']);++ return (+ <CommandPrimitive.Loading+ class={cn('py-6 text-center text-sm', local.class)}+ {...rest}+ />+ );+}++export function CommandList(props: CommandListProps) {+ const [local, rest] = splitProps(props, ['class']);++ return (+ <CommandPrimitive.List+ class={cn(+ 'max-h-[300px] overflow-y-auto overflow-x-hidden p-1',+ local.class,+ )}+ {...rest}+ />+ );+}++export function CommandInput(props: VoidProps<CommandInputProps>) {+ const [local, rest] = splitProps(props, ['class']);++ return (+ <div class="flex items-center border-b px-3" cmdk-input-wrapper="">+ <svg+ xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 24 24"+ class="mr-2 h-4 w-4 shrink-0 opacity-50"+ >+ <path+ fill="none"+ stroke="currentColor"+ stroke-linecap="round"+ stroke-linejoin="round"+ stroke-width="2"+ d="M3 10a7 7 0 1 0 14 0a7 7 0 1 0-14 0m18 11l-6-6"+ />+ <title>Search</title>+ </svg>+ <CommandPrimitive.Input+ class={cn(+ 'flex h-10! w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:(cursor-not-allowed opacity-50)',+ local.class,+ )}+ {...rest}+ />+ </div>+ );+}++export function CommandItem(props: CommandItemProps) {+ const [local, rest] = splitProps(props, ['class']);++ return (+ <CommandPrimitive.Item+ class={cn(+ 'relative flex cursor-default select-none items-center rounded-sm px-1! py-1.5! text-sm outline-none aria-selected:(bg-accent text-accent-foreground) aria-disabled:(pointer-events-none opacity-50)',+ local.class,+ )}+ {...rest}+ />+ );+}++export function CommandShortcut(props: ComponentProps<'span'>) {+ const [local, rest] = splitProps(props, ['class']);++ return (+ <span+ class={cn(+ 'ml-auto text-xs tracking-widest text-muted-foreground',+ local.class,+ )}+ {...rest}+ />+ );+}++export function CommandDialog(props: CommandDialogProps) {+ const [local, rest] = splitProps(props, ['children']);++ return (+ <Dialog {...rest}>+ <DialogContent class="overflow-hidden p-0">+ <Command class="[&_[cmdk-group-heading]]:(px-2 font-medium text-muted-foreground) [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:size-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:(px-2 py-3) [&_[cmdk-item]_svg]:size-5">+ {local.children}+ </Command>+ </DialogContent>+ </Dialog>+ );+}++export function CommandEmpty(props: CommandEmptyProps) {+ const [local, rest] = splitProps(props, ['class']);++ return (+ <CommandPrimitive.Empty+ class={cn('py-6 text-center text-sm', local.class)}+ {...rest}+ />+ );+}++export function CommandGroup(props: CommandGroupProps) {+ const [local, rest] = splitProps(props, ['class']);++ return (+ <CommandPrimitive.Group+ class={cn(+ 'overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:(px-2 py-1.5 text-xs font-medium text-muted-foreground)',+ local.class,+ )}+ {...rest}+ />+ );+}++export function CommandSeparator(props: CommandEmptyProps) {+ const [local, rest] = splitProps(props, ['class']);++ return (+ <CommandPrimitive.Separator+ class={cn('-mx-1 h-px bg-border', local.class)}+ {...rest}+ />+ );+}diff --git a/apps/papra-client/src/modules/ui/layouts/organization.layout.tsx b/apps/papra-client/src/modules/ui/layouts/organization.layout.tsxindex 4bb3d1cb..71ab8f06 100644--- a/apps/papra-client/src/modules/ui/layouts/organization.layout.tsx+++ b/apps/papra-client/src/modules/ui/layouts/organization.layout.tsx@@ -1,14 +1,15 @@import type { Organization } from '@/modules/organizations/organizations.types';import { authStore } from '@/modules/auth/auth.store';+import { useCommandPalette } from '@/modules/command-palette/command-palette.provider';import { uploadDocument } from '@/modules/documents/documents.services';import { fetchOrganizations } from '@/modules/organizations/organizations.services';import { promptUploadFiles } from '@/modules/shared/files/upload';import { queryClient } from '@/modules/shared/query/query-client';import { cn } from '@/modules/shared/style/cn';import { useThemeStore } from '@/modules/theme/theme.store';-import { Button } from '@/modules/ui/components/button';+import { Button } from '@/modules/ui/components/button';import { useCurrentUser } from '@/modules/users/composables/useCurrentUser';import { A, useNavigate, useParams } from '@solidjs/router';import { createQuery } from '@tanstack/solid-query';@@ -196,6 +197,7 @@ export const OrganizationLayout: ParentComponent = (props) => {const themeStore = useThemeStore();const params = useParams();const navigate = useNavigate();+ const { openCommandPalette } = useCommandPalette();const query = createQuery(() => ({queryKey: ['organizations'],@@ -210,7 +212,6 @@ export const OrganizationLayout: ParentComponent = (props) => {const promptImport = async () => {const { files } = await promptUploadFiles();-for (const file of files) {await uploadDocument({ file, organizationId: params.organizationId });}@@ -241,7 +242,7 @@ export const OrganizationLayout: ParentComponent = (props) => {</SheetContent></Sheet>- <Button variant="outline" class="lg:min-w-64 justify-start">+ <Button variant="outline" class="lg:min-w-64 justify-start" onClick={openCommandPalette}><div class="i-tabler-search size-4 mr-2"></div>Search...</Button>diff --git a/apps/papra-server/migrations/0000_colossal_talon.sql b/apps/papra-server/migrations/0000_lame_wendell_rand.sqlsimilarity index 93%rename from apps/papra-server/migrations/0000_colossal_talon.sqlrename to apps/papra-server/migrations/0000_lame_wendell_rand.sqlindex 44125900..3fdc4cd8 100644--- a/apps/papra-server/migrations/0000_colossal_talon.sql+++ b/apps/papra-server/migrations/0000_lame_wendell_rand.sql@@ -20,12 +20,13 @@ CREATE TABLE `documents` (`created_by` text,`deleted_by` text,`original_name` text NOT NULL,- `original_checksum` text NOT NULL,- `original_size` numeric DEFAULT '0' NOT NULL,+ `original_size` integer DEFAULT 0 NOT NULL,+ `storage_key` text NOT NULL,`name` text NOT NULL,- `mime_type` text NOT NULL,- `size` numeric DEFAULT '0' NOT NULL,+ `size` integer DEFAULT 0 NOT NULL,`status` text DEFAULT 'pending' NOT NULL,+ `mime_type` text NOT NULL,+ `content` text DEFAULT '' NOT NULL,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 nulldiff --git a/apps/papra-server/migrations/0001_fine_raza.sql b/apps/papra-server/migrations/0001_fine_raza.sqldeleted file mode 100644index a68ed3fc..00000000--- a/apps/papra-server/migrations/0001_fine_raza.sql+++ /dev/null@@ -1,20 +0,0 @@-DROP INDEX "token_index";--> statement-breakpoint-DROP INDEX "expires_at_index";--> statement-breakpoint-DROP INDEX "token_user_id_expires_at_index";--> statement-breakpoint-DROP INDEX "role_index";--> statement-breakpoint-DROP INDEX "user_roles_user_id_role_key";--> statement-breakpoint-DROP INDEX "users_email_unique";--> statement-breakpoint-DROP INDEX "email_index";--> statement-breakpoint-ALTER TABLE `documents` ALTER COLUMN "original_size" TO "original_size" integer NOT NULL;--> statement-breakpoint-CREATE INDEX `token_index` ON `auth_tokens` (`token`);--> statement-breakpoint-CREATE INDEX `expires_at_index` ON `auth_tokens` (`expires_at`);--> statement-breakpoint-CREATE INDEX `token_user_id_expires_at_index` ON `auth_tokens` (`token`,`user_id`,`expires_at`);--> statement-breakpoint-CREATE INDEX `role_index` ON `user_roles` (`role`);--> statement-breakpoint-CREATE UNIQUE INDEX `user_roles_user_id_role_key` ON `user_roles` (`user_id`,`role`);--> statement-breakpoint-CREATE UNIQUE INDEX `users_email_unique` ON `users` (`email`);--> statement-breakpoint-CREATE INDEX `email_index` ON `users` (`email`);--> statement-breakpoint-ALTER TABLE `documents` ALTER COLUMN "original_size" TO "original_size" integer NOT NULL DEFAULT 0;--> statement-breakpoint-ALTER TABLE `documents` ALTER COLUMN "size" TO "size" integer NOT NULL;--> statement-breakpoint-ALTER TABLE `documents` ALTER COLUMN "size" TO "size" integer NOT NULL DEFAULT 0;--> statement-breakpoint-ALTER TABLE `documents` ADD `storage_key` text NOT NULL;--> statement-breakpoint-ALTER TABLE `documents` DROP COLUMN `original_checksum`;\ No newline at end of filediff --git a/apps/papra-server/migrations/0001_supreme_odin.sql b/apps/papra-server/migrations/0001_supreme_odin.sqlnew file mode 100644index 00000000..c6d959b9--- /dev/null+++ b/apps/papra-server/migrations/0001_supreme_odin.sql@@ -0,0 +1,20 @@+-- Custom SQL migration file, put your code below! --++CREATE VIRTUAL TABLE documents_fts USING fts5(id UNINDEXED, name, original_name, content, content='documents', prefix='2 3 4');++-- Copy data from documents to documents_fts for existing records+INSERT INTO documents_fts(id, name, original_name, content)+SELECT id, name, original_name, content FROM documents;++CREATE TRIGGER trigger_documents_fts_insert AFTER INSERT ON documents BEGIN+ INSERT INTO documents_fts(id, name, original_name, content) VALUES (new.id, new.name, new.original_name, new.content);+END;++CREATE TRIGGER trigger_documents_fts_update AFTER UPDATE ON documents BEGIN+ INSERT INTO documents_fts(documents_fts, id) VALUES('delete', old.id);+ INSERT INTO documents_fts(id, name, original_name, content) VALUES (new.id, new.name, new.original_name, new.content);+END;++CREATE TRIGGER trigger_documents_fts_delete AFTER DELETE ON documents BEGIN+ INSERT INTO documents_fts(documents_fts, id) VALUES('delete', old.id);+END;\ No newline at end of filediff --git a/apps/papra-server/migrations/meta/0000_snapshot.json b/apps/papra-server/migrations/meta/0000_snapshot.jsonindex 6017c1cc..7fdd0fae 100644--- a/apps/papra-server/migrations/meta/0000_snapshot.json+++ b/apps/papra-server/migrations/meta/0000_snapshot.json@@ -1,7 +1,7 @@{"version": "6","dialect": "sqlite",- "id": "daf25e46-2a4b-462a-8488-04778b929104",+ "id": "74d7233a-2257-411c-b8cd-b5df0523bbff","prevId": "00000000-0000-0000-0000-000000000000","tables": {"auth_tokens": {@@ -154,30 +154,23 @@"notNull": true,"autoincrement": false},- "original_checksum": {- "name": "original_checksum",- "type": "text",- "primaryKey": false,- "notNull": true,- "autoincrement": false- },"original_size": {"name": "original_size",- "type": "numeric",+ "type": "integer","primaryKey": false,"notNull": true,"autoincrement": false,- "default": "'0'"+ "default": 0},- "name": {- "name": "name",+ "storage_key": {+ "name": "storage_key","type": "text","primaryKey": false,"notNull": true,"autoincrement": false},- "mime_type": {- "name": "mime_type",+ "name": {+ "name": "name","type": "text","primaryKey": false,"notNull": true,@@ -185,11 +178,11 @@},"size": {"name": "size",- "type": "numeric",+ "type": "integer","primaryKey": false,"notNull": true,"autoincrement": false,- "default": "'0'"+ "default": 0},"status": {"name": "status",@@ -198,6 +191,21 @@"notNull": true,"autoincrement": false,"default": "'pending'"+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"}},"indexes": {},diff --git a/apps/papra-server/migrations/meta/0001_snapshot.json b/apps/papra-server/migrations/meta/0001_snapshot.jsonindex 286a0689..07b06d8d 100644--- a/apps/papra-server/migrations/meta/0001_snapshot.json+++ b/apps/papra-server/migrations/meta/0001_snapshot.json@@ -1,8 +1,8 @@{+ "id": "b40309ae-eb2f-4eb4-9cce-a6ccb6ddc820",+ "prevId": "74d7233a-2257-411c-b8cd-b5df0523bbff","version": "6","dialect": "sqlite",- "id": "1c84dab4-216c-4dfb-bcc9-a73b6be8290d",- "prevId": "daf25e46-2a4b-462a-8488-04778b929104","tables": {"auth_tokens": {"name": "auth_tokens",@@ -72,15 +72,15 @@"auth_tokens_user_id_users_id_fk": {"name": "auth_tokens_user_id_users_id_fk","tableFrom": "auth_tokens",- "tableTo": "users","columnsFrom": ["user_id"],+ "tableTo": "users","columnsTo": ["id"],- "onDelete": "cascade",- "onUpdate": "cascade"+ "onUpdate": "cascade",+ "onDelete": "cascade"}},"compositePrimaryKeys": {},@@ -198,6 +198,14 @@"primaryKey": false,"notNull": true,"autoincrement": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"}},"indexes": {},@@ -205,41 +213,41 @@"documents_organization_id_organizations_id_fk": {"name": "documents_organization_id_organizations_id_fk","tableFrom": "documents",- "tableTo": "organizations","columnsFrom": ["organization_id"],+ "tableTo": "organizations","columnsTo": ["id"],- "onDelete": "cascade",- "onUpdate": "cascade"+ "onUpdate": "cascade",+ "onDelete": "cascade"},"documents_created_by_users_id_fk": {"name": "documents_created_by_users_id_fk","tableFrom": "documents",- "tableTo": "users","columnsFrom": ["created_by"],+ "tableTo": "users","columnsTo": ["id"],- "onDelete": "set null",- "onUpdate": "cascade"+ "onUpdate": "cascade",+ "onDelete": "set null"},"documents_deleted_by_users_id_fk": {"name": "documents_deleted_by_users_id_fk","tableFrom": "documents",- "tableTo": "users","columnsFrom": ["deleted_by"],+ "tableTo": "users","columnsTo": ["id"],- "onDelete": "set null",- "onUpdate": "cascade"+ "onUpdate": "cascade",+ "onDelete": "set null"}},"compositePrimaryKeys": {},@@ -298,28 +306,28 @@"organization_users_user_id_users_id_fk": {"name": "organization_users_user_id_users_id_fk","tableFrom": "organization_users",- "tableTo": "users","columnsFrom": ["user_id"],+ "tableTo": "users","columnsTo": ["id"],- "onDelete": "cascade",- "onUpdate": "cascade"+ "onUpdate": "cascade",+ "onDelete": "cascade"},"organization_users_organization_id_organizations_id_fk": {"name": "organization_users_organization_id_organizations_id_fk","tableFrom": "organization_users",- "tableTo": "organizations","columnsFrom": ["organization_id"],+ "tableTo": "organizations","columnsTo": ["id"],- "onDelete": "cascade",- "onUpdate": "cascade"+ "onUpdate": "cascade",+ "onDelete": "cascade"}},"compositePrimaryKeys": {},@@ -424,15 +432,15 @@"user_roles_user_id_users_id_fk": {"name": "user_roles_user_id_users_id_fk","tableFrom": "user_roles",- "tableTo": "users","columnsFrom": ["user_id"],+ "tableTo": "users","columnsTo": ["id"],- "onDelete": "cascade",- "onUpdate": "cascade"+ "onUpdate": "cascade",+ "onDelete": "cascade"}},"compositePrimaryKeys": {},@@ -503,9 +511,9 @@"views": {},"enums": {},"_meta": {+ "columns": {},"schemas": {},- "tables": {},- "columns": {}+ "tables": {}},"internal": {"indexes": {}diff --git a/apps/papra-server/migrations/meta/_journal.json b/apps/papra-server/migrations/meta/_journal.jsonindex 7226607d..3bcf3f1f 100644--- a/apps/papra-server/migrations/meta/_journal.json+++ b/apps/papra-server/migrations/meta/_journal.json@@ -5,15 +5,15 @@{"idx": 0,"version": "6",- "when": 1735830695548,- "tag": "0000_colossal_talon",+ "when": 1736080578539,+ "tag": "0000_lame_wendell_rand","breakpoints": true},{"idx": 1,"version": "6",- "when": 1735999064544,- "tag": "0001_fine_raza",+ "when": 1736080611791,+ "tag": "0001_supreme_odin","breakpoints": true}]diff --git a/apps/papra-server/src/modules/app/database/database.test-utils.ts b/apps/papra-server/src/modules/app/database/database.test-utils.tsindex 20b29412..feda1216 100644--- a/apps/papra-server/src/modules/app/database/database.test-utils.ts+++ b/apps/papra-server/src/modules/app/database/database.test-utils.ts@@ -1,5 +1,6 @@import type { Database } from './database.types';import { migrate } from 'drizzle-orm/libsql/migrator';+import { documentsTable } from '../../documents/documents.table';import { organizationsTable, organizationUsersTable } from '../../organizations/organizations.table';import { usersTable } from '../../users/users.table';import { setupDatabase } from './database';@@ -23,15 +24,18 @@ async function seedDatabase({users,organizations,organizationUsers,+ documents,}: {db: Database;users?: typeof usersTable.$inferInsert[];organizations?: typeof organizationsTable.$inferInsert[];organizationUsers?: typeof organizationUsersTable.$inferInsert[];+ documents?: typeof documentsTable.$inferInsert[];}) {await Promise.all([users && db.insert(usersTable).values(users).execute(),organizations && db.insert(organizationsTable).values(organizations).execute(),organizationUsers && db.insert(organizationUsersTable).values(organizationUsers).execute(),+ documents && db.insert(documentsTable).values(documents).execute(),]);}diff --git a/apps/papra-server/src/modules/documents/documents.repository.test.ts b/apps/papra-server/src/modules/documents/documents.repository.test.tsindex 957eec15..239846f3 100644--- a/apps/papra-server/src/modules/documents/documents.repository.test.ts+++ b/apps/papra-server/src/modules/documents/documents.repository.test.ts@@ -1,3 +1,4 @@+import { map } from 'lodash-es';import { describe, expect, test } from 'vitest';import { createInMemoryDatabase } from '../app/database/database.test-utils';import { createDocumentsRepository } from './documents.repository';@@ -63,4 +64,34 @@ describe('documents repository', () => {expect(documentsAfterDelete).to.have.length(0);});});++ describe('searchOrganizationDocuments', () => {+ test('provides full text search on document name, original name, and content', async () => {+ const { db } = await createInMemoryDatabase({+ users: [{ id: 'user-1', email: '[email protected]' }],+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],+ organizationUsers: [{ organizationId: 'organization-1', userId: 'user-1' }],+ documents: [+ { id: 'doc-1', organizationId: 'organization-1', createdBy: 'user-1', name: 'Document 1', originalName: 'document-1.pdf', content: 'lorem ipsum', storageKey: '', mimeType: 'application/pdf' },+ { id: 'doc-2', organizationId: 'organization-1', createdBy: 'user-1', name: 'File 2', originalName: 'document-2.pdf', content: 'lorem', storageKey: '', mimeType: 'application/pdf' },+ { id: 'doc-3', organizationId: 'organization-1', createdBy: 'user-1', name: 'File 3', originalName: 'document-3.pdf', content: 'ipsum', storageKey: '', mimeType: 'application/pdf' },+ ],+ });++ // Rebuild the FTS index since we are using an in-memory database+ await db.$client.execute(`INSERT INTO documents_fts(documents_fts) VALUES('rebuild');`);++ const documentsRepository = createDocumentsRepository({ db });++ const { documents } = await documentsRepository.searchOrganizationDocuments({+ organizationId: 'organization-1',+ searchQuery: 'lorem',+ pageIndex: 0,+ pageSize: 10,+ });++ expect(documents).to.have.length(2);+ expect(map(documents, 'id')).to.eql(['doc-2', 'doc-1']);+ });+ });});diff --git a/apps/papra-server/src/modules/documents/documents.repository.ts b/apps/papra-server/src/modules/documents/documents.repository.tsindex f446575c..950dab72 100644--- a/apps/papra-server/src/modules/documents/documents.repository.ts+++ b/apps/papra-server/src/modules/documents/documents.repository.ts@@ -1,7 +1,7 @@import type { Database } from '../app/database/database.types';import type { DbInsertableDocument } from './documents.types';import { injectArguments } from '@corentinth/chisels';-import { and, count, desc, eq } from 'drizzle-orm';+import { and, count, desc, eq, sql } from 'drizzle-orm';import { withPagination } from '../shared/db/pagination';import { documentsTable } from './documents.table';@@ -15,6 +15,7 @@ export function createDocumentsRepository({ db }: { db: Database }) {getDocumentById,softDeleteDocument,getOrganizationDocumentsCount,+ searchOrganizationDocuments,},{ db },);@@ -88,3 +89,25 @@ async function softDeleteDocument({ documentId, userId, db, now = new Date() }:}).where(eq(documentsTable.id, documentId));}++async function searchOrganizationDocuments({ organizationId, searchQuery, pageIndex, pageSize, db }: { organizationId: string; searchQuery: string; pageIndex: number; pageSize: number; db: Database }) {+ // const doubleQuotedSearchQuery = `"${searchQuery.replace(/"/g, '')}"`;+ // when searchquery is a single word, we append a wildcard to it to make it a prefix search+ const cleanedSearchQuery = searchQuery.replace(/"/g, '').replace(/\*/g, '').trim();+ const formatedSearchQuery = cleanedSearchQuery.includes(' ') ? cleanedSearchQuery : `${cleanedSearchQuery}*`;++ const result = await db.run(sql`+ SELECT * FROM ${documentsTable}+ JOIN documents_fts ON documents_fts.id = ${documentsTable.id}+ WHERE ${documentsTable.organizationId} = ${organizationId}+ AND ${documentsTable.isDeleted} = 0+ AND documents_fts MATCH ${formatedSearchQuery}+ ORDER BY rank+ LIMIT ${pageSize}+ OFFSET ${pageIndex * pageSize}+ `);++ return {+ documents: result.rows as unknown as (typeof documentsTable.$inferSelect)[],+ };+}diff --git a/apps/papra-server/src/modules/documents/documents.routes.ts b/apps/papra-server/src/modules/documents/documents.routes.tsindex 10a70fd6..0fc5aa71 100644--- a/apps/papra-server/src/modules/documents/documents.routes.ts+++ b/apps/papra-server/src/modules/documents/documents.routes.ts@@ -15,6 +15,7 @@ import { createDocumentStorageService } from './storage/documents.storage.servicexport function registerDocumentsPrivateRoutes({ app }: { app: ServerInstance }) {setupCreateDocumentRoute({ app });setupGetDocumentsRoute({ app });+ setupSearchDocumentsRoute({ app });setupGetDocumentRoute({ app });setupDeleteDocumentRoute({ app });setupGetDocumentFileRoute({ app });@@ -259,3 +260,45 @@ function setupGetDocumentFileRoute({ app }: { app: ServerInstance }) {},);}++function setupSearchDocumentsRoute({ app }: { app: ServerInstance }) {+ app.get(+ '/api/organizations/:organizationId/documents/search',+ validateParams(z.object({+ organizationId: z.string().regex(organizationIdRegex),+ })),+ validateQuery(+ z.object({+ searchQuery: z.string(),+ pageIndex: z.coerce.number().min(0).int().optional().default(0),+ pageSize: z.coerce.number().min(1).max(100).int().optional().default(100),+ }),+ ),+ async (context) => {+ const { userId } = getAuthUserId({ context });+ const { db } = getDb({ context });++ const { organizationId } = context.req.valid('param');+ const { searchQuery, pageIndex, pageSize } = context.req.valid('query');++ const documentsRepository = createDocumentsRepository({ db });+ const organizationsRepository = createOrganizationsRepository({ db });++ const { isInOrganization } = await organizationsRepository.isUserInOrganization({ userId, organizationId });++ if (!isInOrganization) {+ throw createError({+ message: 'You are not part of this organization.',+ code: 'user.not_in_organization',+ statusCode: 403,+ });+ }++ const { documents } = await documentsRepository.searchOrganizationDocuments({ organizationId, searchQuery, pageIndex, pageSize });++ return context.json({+ documents,+ });+ },+ );+}diff --git a/apps/papra-server/src/modules/documents/documents.table.ts b/apps/papra-server/src/modules/documents/documents.table.tsindex a8d6dfa6..84daaa30 100644--- a/apps/papra-server/src/modules/documents/documents.table.ts+++ b/apps/papra-server/src/modules/documents/documents.table.ts@@ -22,4 +22,5 @@ export const documentsTable = sqliteTable('documents', {size: integer('size').notNull().default(0),status: text('status').notNull().default('pending'),mimeType: text('mime_type').notNull(),+ content: text('content').notNull().default(''),});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 94c006b2..7c93b255 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -61,6 +61,9 @@ importers:clsx:specifier: ^2.1.1version: 2.1.1+ cmdk-solid:+ specifier: ^1.1.0+ version: 1.1.0([email protected])date-fns:specifier: ^4.1.0version: 4.1.0@@ -1370,6 +1373,11 @@ packages:'@jridgewell/[email protected]':resolution: {integrity: sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==}+ '@kobalte/[email protected]':+ resolution: {integrity: sha512-+Ta2o2wEqZ2fCqLMkvjT40VHNmcFKdGe8TNDVQbbMPk66qoU6g/DDRFR/Ib7eAjb+C95VoIyk6zaafos2VOo0w==}+ peerDependencies:+ solid-js: ^1.8.15+'@kobalte/[email protected]':resolution: {integrity: sha512-COhjWk1KnCkl3qMJDvdrOsvpTlJ9gMLdemkAn5SWfbPn/lxJYabejnNOk+b/ILGg7apzQycgbuo48qb8ppqsAg==}peerDependencies:@@ -1865,6 +1873,11 @@ packages:resolution: {integrity: sha512-PpjSboaDUE6yl+1qlg3Si57++e84oXdWGbuFUSAciXsVfEZJJJupR2Nb0QuXHiunt2vGR+1PTizOMvnUPaG2Qg==}engines: {node: '>=16.0.0'}+ '@solid-primitives/[email protected]':+ resolution: {integrity: sha512-uzhXr/cMABsGkTcV3yuviZjTDmj44wb2JetuJ5O8NCugz4Ug/6XlPjT8ISMPYV7eCbC/gFhgt7e60+TRpl2Upg==}+ peerDependencies:+ solid-js: ^1.6.12+'@solid-primitives/[email protected]':resolution: {integrity: sha512-DAJbl+F0wrFW2xmcV8dKMBhk9QLVLuBSW+TR4JmIfTaObxd13PuL7nqaXnaYKDWOYa6otB00qcCUIGbuIhSUgQ==}peerDependencies:@@ -1890,6 +1903,16 @@ packages:peerDependencies:solid-js: ^1.6.12+ '@solid-primitives/[email protected]':+ resolution: {integrity: sha512-S4cNjjKINVC4KiY3ovP1oagbTVQI77VvSRMNsInFIi7T4hM/N5InJk5k+W0zD4lt+SUYrWF04BMbZyMy17vfUw==}+ peerDependencies:+ solid-js: ^1.6.12++ '@solid-primitives/[email protected]':+ resolution: {integrity: sha512-01skkiHtNWl2PQ0ugFzZHBMsHk870+bZSNK8Gvjcj3mZwBzAJPaUPzFswfM/V8Io1Cko86vfXl73vl9ddRYb5A==}+ peerDependencies:+ solid-js: ^1.6.12+'@solid-primitives/[email protected]':resolution: {integrity: sha512-jZAKWwvDRHjiydIumDgMj68qviIbowQ1ci7nkEAgzgvanNkhKSQV8iPgR2jMk1uv7S2ZqXYHslVQTgJel/TEyg==}peerDependencies:@@ -1910,6 +1933,11 @@ packages:peerDependencies:solid-js: ^1.6.12+ '@solid-primitives/[email protected]':+ resolution: {integrity: sha512-BTGdFP7t+s7RSak+s1u0eTix4lHP23MrbGkgQTFlt1E+4fmnD/bEx3ZfNW7Grylz3GXgKyXrgDKA7jQ/wuWKgA==}+ peerDependencies:+ solid-js: ^1.6.12+'@solid-primitives/[email protected]':resolution: {integrity: sha512-ZecE4BqY0oBk0YG00nzaAWO5Mjcny8Fc06CdbXadH9T9lzq/9GefqcSe/5AtdXqjvY/DtJ5C6CkcjPZO0o/eqg==}peerDependencies:@@ -2401,6 +2429,11 @@ packages:resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==}engines: {node: '>=6'}+ resolution: {integrity: sha512-R8MRAWE2o8qnu0D8DOqGKoB1TMGI97mfSrH9CtgUQzcvZ+4jY2fvF6cxJS2N/iSwwl6LQeB/AYXh8GAGCPbkDQ==}+ peerDependencies:+ solid-js: ^1.8.0+resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==}engines: {node: '>=7.0.0'}@@ -5511,6 +5544,15 @@ snapshots:'@jridgewell/resolve-uri': 3.1.2'@jridgewell/sourcemap-codec': 1.5.0+ '@kobalte/[email protected]([email protected])':+ dependencies:+ '@floating-ui/dom': 1.6.12+ '@internationalized/date': 3.6.0+ '@internationalized/number': 3.6.0+ '@kobalte/utils': 0.9.1([email protected])+ solid-js: 1.9.3+ solid-prevent-scroll: 0.1.10([email protected])+'@kobalte/[email protected]([email protected])':dependencies:'@floating-ui/dom': 1.6.12@@ -6131,6 +6173,11 @@ snapshots:'@smithy/types': 3.7.2tslib: 2.8.1+ '@solid-primitives/[email protected]([email protected])':+ dependencies:+ '@solid-primitives/memo': 1.3.10([email protected])+ solid-js: 1.9.3+'@solid-primitives/[email protected]([email protected])':dependencies:'@solid-primitives/utils': 6.2.3([email protected])@@ -6157,6 +6204,17 @@ snapshots:'@solid-primitives/utils': 6.2.3([email protected])solid-js: 1.9.3+ '@solid-primitives/[email protected]([email protected])':+ dependencies:+ '@solid-primitives/scheduled': 1.4.4([email protected])+ '@solid-primitives/utils': 6.2.3([email protected])+ solid-js: 1.9.3++ '@solid-primitives/[email protected]([email protected])':+ dependencies:+ '@solid-primitives/utils': 6.2.3([email protected])+ solid-js: 1.9.3+'@solid-primitives/[email protected]([email protected])':dependencies:'@solid-primitives/utils': 6.2.3([email protected])@@ -6180,6 +6238,10 @@ snapshots:'@solid-primitives/utils': 6.2.3([email protected])solid-js: 1.9.3+ '@solid-primitives/[email protected]([email protected])':+ dependencies:+ solid-js: 1.9.3+'@solid-primitives/[email protected]([email protected])':dependencies:'@solid-primitives/utils': 6.2.3([email protected])@@ -6821,6 +6883,14 @@ snapshots:+ dependencies:+ '@kobalte/core': 0.12.6([email protected])+ '@kobalte/utils': 0.9.1([email protected])+ '@solid-primitives/deep': 0.2.10([email protected])+ '@solid-primitives/mutation-observer': 1.1.17([email protected])+ solid-js: 1.9.3+dependencies:color-name: 1.1.4