The minimalistic document archiving platform.
feat(documents): add custom properties (#956)
Corentin Thomasset7c2b2d27cd43
diff --git a/.changeset/strong-cooks-dress.md b/.changeset/strong-cooks-dress.mdnew file mode 100644index 00000000..47487c33--- /dev/null+++ b/.changeset/strong-cooks-dress.md@@ -0,0 +1,5 @@+---+"@papra/app": minor+---++Introduced custom properties! Define custom properties on your organization and set them on documents. Custom properties can be of different types, including text, number, select, multi-select and document or organization members relations.diff --git a/apps/papra-client/src/locales/en.dictionary.ts b/apps/papra-client/src/locales/en.dictionary.tsindex c89b6e1f..41d71e0c 100644--- a/apps/papra-client/src/locales/en.dictionary.ts+++ b/apps/papra-client/src/locales/en.dictionary.ts@@ -356,6 +356,72 @@ export const translations = {'documents.info.no-date': 'No date','documents.info.today': 'Today',+ 'custom-properties.types.text': 'Text',+ 'custom-properties.types.number': 'Number',+ 'custom-properties.types.date': 'Date',+ 'custom-properties.types.boolean': 'Boolean',+ 'custom-properties.types.select': 'Select',+ 'custom-properties.types.multi_select': 'Multi-select',+ 'custom-properties.types.user_relation': 'User',+ 'custom-properties.types.document_relation': 'Document',++ 'custom-properties.list.title': 'Custom Properties',+ 'custom-properties.list.description': 'Define custom metadata fields for your documents. Properties can be text, numbers, dates, booleans, or selection lists.',+ 'custom-properties.list.create-button': 'Create property',+ 'custom-properties.list.empty.title': 'Custom Properties',+ 'custom-properties.list.empty.description': 'Custom properties let you add structured metadata to your documents, such as expiration dates, company names, or amounts.',+ 'custom-properties.list.table.name': 'Name',+ 'custom-properties.list.table.type': 'Type',+ 'custom-properties.list.table.description': 'Description',+ 'custom-properties.list.table.created': 'Created',+ 'custom-properties.list.table.actions': 'Actions',+ 'custom-properties.list.table.no-description': 'No description',+ 'custom-properties.list.delete.confirm-title': 'Delete custom property',+ 'custom-properties.list.delete.confirm-message': 'Are you sure you want to delete the custom property "{{ name }}"? This action cannot be undone.',+ 'custom-properties.list.delete.confirm-button': 'Delete',+ 'custom-properties.list.delete.success': 'Custom property deleted successfully',+ 'custom-properties.list.delete.error': 'Failed to delete custom property',++ 'custom-properties.create.title': 'Create Custom Property',+ 'custom-properties.create.submit': 'Create property',+ 'custom-properties.create.success': 'Custom property created successfully',+ 'custom-properties.create.error': 'Failed to create custom property',++ 'custom-properties.update.title': 'Update Custom Property',+ 'custom-properties.update.submit': 'Save changes',+ 'custom-properties.update.success': 'Custom property updated successfully',+ 'custom-properties.update.error': 'Failed to update custom property',++ 'custom-properties.form.name.label': 'Name',+ 'custom-properties.form.name.placeholder': 'e.g. Invoice Amount',+ 'custom-properties.form.name.required': 'Name is required',+ 'custom-properties.form.name.max-length': 'Name must be at most 255 characters',+ 'custom-properties.form.description.label': 'Description',+ 'custom-properties.form.description.optional': '(optional)',+ 'custom-properties.form.description.placeholder': 'Describe what this property is used for',+ 'custom-properties.form.description.max-length': 'Description must be at most 1000 characters',+ 'custom-properties.form.type.label': 'Type',+ 'custom-properties.form.type.immutable': 'Property type cannot be changed after creation.',+ 'custom-properties.form.options.title': 'Options',+ 'custom-properties.form.options.description': 'Define the choices available for this property.',+ 'custom-properties.form.options.name.placeholder': 'Option name',+ 'custom-properties.form.options.name.required': 'Option name is required',+ 'custom-properties.form.options.name.max-length': 'Option name must be at most 255 characters',+ 'custom-properties.form.options.validation.required': 'Please add at least one option',+ 'custom-properties.form.options.add': 'Add option',+ 'custom-properties.form.cancel': 'Cancel',+ 'custom-properties.form.save-error': 'An error occurred while saving the property definition. Please try again.',++ 'documents.custom-properties.section-title': 'Properties',+ 'documents.custom-properties.no-value': 'Not set',+ 'documents.custom-properties.text-placeholder': 'Enter a value...',+ 'documents.custom-properties.save': 'Save',+ 'documents.custom-properties.clear': 'Clear',+ 'documents.custom-properties.document-relation-search-placeholder': 'Search documents...',+ 'documents.custom-properties.user-relation-manage': 'Manage users',+ 'documents.custom-properties.document-relation-manage': 'Manage documents',+ 'documents.custom-properties.no-results': 'No results',+'documents.rename.title': 'Rename document','documents.rename.form.name.label': 'Name','documents.rename.form.name.placeholder': 'Example: Invoice 2024',@@ -709,6 +775,7 @@ export const translations = {'layout.menu.home': 'Home','layout.menu.documents': 'Documents','layout.menu.tags': 'Tags',+ 'layout.menu.custom-properties': 'Custom Properties','layout.menu.tagging-rules': 'Tagging rules','layout.menu.deleted-documents': 'Deleted documents','layout.menu.organization-settings': 'Settings',diff --git a/apps/papra-client/src/modules/custom-properties/components/custom-property-definition-form.component.tsx b/apps/papra-client/src/modules/custom-properties/components/custom-property-definition-form.component.tsxnew file mode 100644index 00000000..62c14593--- /dev/null+++ b/apps/papra-client/src/modules/custom-properties/components/custom-property-definition-form.component.tsx@@ -0,0 +1,222 @@+import type { Component, JSX } from 'solid-js';+import type { CustomPropertyDefinition, CustomPropertyType } from '../custom-properties.types';+import { getValue, insert, remove, setValue } from '@modular-forms/solid';+import { A } from '@solidjs/router';+import { For, Show } from 'solid-js';+import * as v from 'valibot';+import { useI18n } from '@/modules/i18n/i18n.provider';+import { createForm } from '@/modules/shared/form/form';+import { useI18nApiErrors } from '@/modules/shared/http/composables/i18n-api-errors';+import { Button } from '@/modules/ui/components/button';+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/modules/ui/components/select';+import { TextArea } from '@/modules/ui/components/textarea';+import { TextField, TextFieldLabel, TextFieldRoot } from '@/modules/ui/components/textfield';+import { PROPERTY_TYPE_LABEL_I18N_KEYS } from '../custom-properties.constants';++const PROPERTY_TYPES: CustomPropertyType[] = ['text', 'number', 'date', 'boolean', 'select', 'multi_select', 'user_relation', 'document_relation'];+const SELECT_LIKE_TYPES: CustomPropertyType[] = ['select', 'multi_select'];++type OptionDraft = { id?: string; name: string };+export type PropertyDefinitionDraft = { name: string; description?: string; type: CustomPropertyType; options?: OptionDraft[] };++export const CustomPropertyDefinitionForm: Component<{+ onSubmit: (args: { propertyDefinition: PropertyDefinitionDraft }) => Promise<void> | void;+ organizationId: string;+ propertyDefinition?: CustomPropertyDefinition;+ submitButton: JSX.Element;+}> = (props) => {+ const hasExistingType = () => Boolean(props.propertyDefinition?.type);+ const { getErrorMessage } = useI18nApiErrors();+ const { t } = useI18n();++ const { form, Form, Field, FieldArray, createFormError } = createForm({+ onSubmit: async ({ name, description, type, options }) => {+ // TODO: make a discriminated union of the form values based on the type to avoid having to do this kind of validation+ if ((!options || options.length === 0) && SELECT_LIKE_TYPES.includes(type)) {+ throw createFormError({ message: t('custom-properties.form.options.validation.required') });+ }++ try {+ await props.onSubmit({+ propertyDefinition: {+ name,+ description,+ type,+ options,+ },+ });+ } catch (error) {+ const message = getErrorMessage({ error, defaultMessage: t('custom-properties.form.save-error') });+ throw createFormError({ message });+ }+ },+ schema: v.object({+ name: v.pipe(+ v.string(),+ v.trim(),+ v.minLength(1, t('custom-properties.form.name.required')),+ v.maxLength(255, t('custom-properties.form.name.max-length')),+ ),+ description: v.pipe(+ v.string(),+ v.trim(),+ v.maxLength(1000, t('custom-properties.form.description.max-length')),+ ),+ type: v.picklist(PROPERTY_TYPES),+ options: v.optional(+ v.array(v.object({+ id: v.optional(v.string()),+ name: v.pipe(+ v.string(),+ v.trim(),+ v.minLength(1, t('custom-properties.form.options.name.required')),+ v.maxLength(255, t('custom-properties.form.options.name.max-length')),+ ),+ })),+ [],+ ),+ }),+ initialValues: {+ name: props.propertyDefinition?.name ?? '',+ description: props.propertyDefinition?.description ?? '',+ type: props.propertyDefinition?.type ?? 'text',+ options: props.propertyDefinition?.options?.map(o => ({ id: o.id, name: o.name })) ?? [{ name: '' }],+ },+ });++ const currentType = () => getValue(form, 'type');+ const isSelectLike = () => SELECT_LIKE_TYPES.includes(currentType() as CustomPropertyType);++ return (+ <Form>+ <Field name="name">+ {(field, inputProps) => (+ <TextFieldRoot class="flex flex-col gap-1">+ <TextFieldLabel for="name">{t('custom-properties.form.name.label')}</TextFieldLabel>+ <TextField+ type="text"+ id="name"+ placeholder={t('custom-properties.form.name.placeholder')}+ {...inputProps}+ value={field.value}+ aria-invalid={Boolean(field.error)}+ />+ {field.error && <div class="text-red-500 text-sm">{field.error}</div>}+ </TextFieldRoot>+ )}+ </Field>++ <Field name="description">+ {(field, inputProps) => (+ <TextFieldRoot class="flex flex-col gap-1 mt-6">+ <TextFieldLabel for="description">+ {t('custom-properties.form.description.label')}+ <span class="text-muted-foreground font-normal ml-1">{t('custom-properties.form.description.optional')}</span>+ </TextFieldLabel>+ <TextArea+ id="description"+ placeholder={t('custom-properties.form.description.placeholder')}+ {...inputProps}+ value={field.value}+ />+ {field.error && <div class="text-red-500 text-sm">{field.error}</div>}+ </TextFieldRoot>+ )}+ </Field>++ <Field name="type">+ {field => (+ <div class="flex flex-col gap-1 mt-6">+ <label class="text-sm font-medium" for="type">{t('custom-properties.form.type.label')}</label>+ <Select+ id="type"+ defaultValue={field.value ?? 'text'}+ onChange={value => value && setValue(form, 'type', value as CustomPropertyType)}+ options={PROPERTY_TYPES}+ itemComponent={itemProps => (+ <SelectItem item={itemProps.item}>{t(PROPERTY_TYPE_LABEL_I18N_KEYS[itemProps.item.rawValue as CustomPropertyType])}</SelectItem>+ )}+ disabled={hasExistingType()}+ >+ <SelectTrigger class="w-full">+ <SelectValue<CustomPropertyType>>{state => t(PROPERTY_TYPE_LABEL_I18N_KEYS[state.selectedOption()])}</SelectValue>+ </SelectTrigger>+ <SelectContent />+ </Select>+ {field.error && <div class="text-red-500 text-sm">{field.error}</div>}+ </div>+ )}+ </Field>++ <Show when={hasExistingType()}>+ <p class="text-xs text-muted-foreground">{t('custom-properties.form.type.immutable')}</p>+ </Show>++ <Show when={isSelectLike()}>+ <p class="mb-1 font-medium mt-6">{t('custom-properties.form.options.title')}</p>+ <p class="mb-3 text-sm text-muted-foreground">{t('custom-properties.form.options.description')}</p>++ <FieldArray name="options">+ {fieldArray => (+ <div class="flex flex-col gap-3">+ <For each={fieldArray.items}>+ {(_, index) => (+ <Field name={`options.${index()}.id`}>+ {() => (+ <div class="flex gap-2 items-start">+ <div class="flex-1">+ <Field name={`options.${index()}.name`}>+ {(field, inputProps) => (+ <TextFieldRoot>+ <TextField+ placeholder={t('custom-properties.form.options.name.placeholder')}+ {...inputProps}+ value={field.value}+ aria-invalid={Boolean(field.error)}+ />+ {field.error && <div class="text-red-500 text-xs mt-1">{field.error}</div>}+ </TextFieldRoot>+ )}+ </Field>+ </div>+ <Button+ variant="outline"+ size="icon"+ class="shrink-0"+ onClick={() => remove(form, 'options', { at: index() })}+ >+ <div class="i-tabler-x size-4" />+ </Button>+ </div>+ )}+ </Field>+ )}+ </For>++ <Button+ variant="outline"+ class="gap-2 mt-1 self-start"+ onClick={() => insert(form, 'options', { value: { name: '' } })}+ >+ <div class="i-tabler-plus size-4" />+ {t('custom-properties.form.options.add')}+ </Button>++ {fieldArray.error && <div class="text-red-500 text-sm">{fieldArray.error}</div>}+ </div>+ )}+ </FieldArray>+ </Show>++ <div class="flex justify-end mt-8 gap-2">+ <Button variant="outline" as={A} href={`/organizations/${props.organizationId}/custom-properties`}>+ {t('custom-properties.form.cancel')}+ </Button>+ {props.submitButton}+ </div>++ <div class="text-red-500 text-sm mt-4">{form.response.message}</div>++ </Form>+ );+};diff --git a/apps/papra-client/src/modules/custom-properties/components/document-custom-properties-panel.component.tsx b/apps/papra-client/src/modules/custom-properties/components/document-custom-properties-panel.component.tsxnew file mode 100644index 00000000..429cf1ca--- /dev/null+++ b/apps/papra-client/src/modules/custom-properties/components/document-custom-properties-panel.component.tsx@@ -0,0 +1,809 @@+import type { Component } from 'solid-js';+import type { CustomPropertyDefinition } from '../custom-properties.types';+import type { Document } from '@/modules/documents/documents.types';+import Calendar from '@corvu/calendar';+import { A } from '@solidjs/router';++import { useMutation, useQuery } from '@tanstack/solid-query';+import { createMemo, createSignal, For, Match, Show, Switch as SolidSwitch, Suspense } from 'solid-js';+import { fetchOrganizationDocuments } from '@/modules/documents/documents.services';+import { useI18n } from '@/modules/i18n/i18n.provider';+import { fetchOrganizationMembers } from '@/modules/organizations/organizations.services';+import { useI18nApiErrors } from '@/modules/shared/http/composables/i18n-api-errors';+import { queryClient } from '@/modules/shared/query/query-client';+import { useDebounce } from '@/modules/shared/utils/timing';+import { Button } from '@/modules/ui/components/button';+import { CalendarGrid } from '@/modules/ui/components/calendar';+import { CalendarMonthYearHeader } from '@/modules/ui/components/calendar-month-year-header';+import { NumberField, NumberFieldDecrementTrigger, NumberFieldGroup, NumberFieldIncrementTrigger, NumberFieldInput } from '@/modules/ui/components/number-field';+import { Popover, PopoverContent, PopoverTrigger } from '@/modules/ui/components/popover';+import { Separator } from '@/modules/ui/components/separator';+import { createToast } from '@/modules/ui/components/sonner';+import { Switch, SwitchControl, SwitchThumb } from '@/modules/ui/components/switch';+import { TextField, TextFieldRoot } from '@/modules/ui/components/textfield';+import { rawPropertyValueAsOption, rawPropertyValueAsOptionArray, rawPropertyValueAsRelatedDocumentArray, rawPropertyValueAsUserArray } from '../custom-properties.models';+import { deleteDocumentCustomPropertyValue, setDocumentCustomPropertyValue } from '../custom-properties.services';++type SelectOption = { optionId: string; name: string };++function getDateValue(value: unknown): Date | null {+ if (value === null || value === undefined) {+ return null;+ }+ if (typeof value === 'string') {+ const d = new Date(value);+ return Number.isNaN(d.getTime()) ? null : d;+ }+ return null;+}++const TextPropertyEditor: Component<{+ value: string | null;+ onSave: (value: string | null) => void;+ isPending: boolean;+}> = (props) => {+ const { t } = useI18n();+ const [open, setOpen] = createSignal(false);+ const [draft, setDraft] = createSignal('');++ const handleOpen = (isOpen: boolean) => {+ if (isOpen) {+ setDraft(props.value ?? '');+ }+ setOpen(isOpen);+ };++ const handleSave = () => {+ const val = draft().trim();+ props.onSave(val === '' ? null : val);+ setOpen(false);+ };++ const handleClear = () => {+ props.onSave(null);+ setOpen(false);+ };++ return (+ <Popover open={open()} onOpenChange={handleOpen} placement="bottom-start">+ <PopoverTrigger+ as={Button}+ variant="ghost"+ class="flex items-center gap-2 group bg-transparent! p-0 h-auto text-left"+ disabled={props.isPending}+ >+ <Show+ when={props.value}+ keyed+ fallback={<span class="text-muted-foreground">{t('documents.custom-properties.no-value')}</span>}+ >+ {v => <span>{v}</span>}+ </Show>+ <div class="i-tabler-pencil size-4 text-muted-foreground group-hover:text-foreground transition-colors flex-shrink-0" />+ </PopoverTrigger>+ <PopoverContent class="w-72 p-3">+ <div class="flex flex-col gap-2">+ <TextFieldRoot>+ <TextField+ value={draft()}+ onInput={e => setDraft(e.currentTarget.value)}+ onKeyDown={e => e.key === 'Enter' && handleSave()}+ placeholder={t('documents.custom-properties.text-placeholder')}+ />+ </TextFieldRoot>+ <div class="flex gap-2 justify-end">+ <Button variant="ghost" size="sm" onClick={handleClear}>+ {t('documents.custom-properties.clear')}+ </Button>+ <Button size="sm" onClick={handleSave}>+ {t('documents.custom-properties.save')}+ </Button>+ </div>+ </div>+ </PopoverContent>+ </Popover>+ );+};++const NumberPropertyEditor: Component<{+ value: number | null;+ onSave: (value: number | null) => void;+ isPending: boolean;+}> = (props) => {+ const { t } = useI18n();+ const [open, setOpen] = createSignal(false);+ const [draft, setDraft] = createSignal<number | undefined>(undefined);++ const handleOpen = (isOpen: boolean) => {+ if (isOpen) {+ setDraft(props.value ?? undefined);+ }+ setOpen(isOpen);+ };++ const handleSave = () => {+ const val = draft();+ props.onSave(val != null && Number.isFinite(val) ? val : null);+ setOpen(false);+ };++ const handleClear = () => {+ props.onSave(null);+ setOpen(false);+ };++ const onChange = (value: number) => {+ setDraft(value);+ };++ return (+ <Popover open={open()} onOpenChange={handleOpen} placement="bottom-start">+ <PopoverTrigger+ as={Button}+ variant="ghost"+ class="flex items-center gap-2 group bg-transparent! p-0 h-auto text-left"+ disabled={props.isPending}+ >+ <Show when={props.value != null} fallback={<span class="text-muted-foreground">{t('documents.custom-properties.no-value')}</span>}>+ <span>{props.value}</span>+ </Show>+ <div class="i-tabler-pencil size-4 text-muted-foreground group-hover:text-foreground transition-colors flex-shrink-0" />+ </PopoverTrigger>+ <PopoverContent class="w-56 p-3">+ <div class="flex flex-col gap-2">+ <NumberField rawValue={draft()} onRawValueChange={onChange}>+ <NumberFieldGroup>+ <NumberFieldInput onKeyDown={e => e.key === 'Enter' && handleSave()} />+ <NumberFieldDecrementTrigger />+ <NumberFieldIncrementTrigger />+ </NumberFieldGroup>+ </NumberField>+ <div class="flex gap-2 justify-end">+ <Button variant="ghost" size="sm" onClick={handleClear}>+ {t('documents.custom-properties.clear')}+ </Button>+ <Button size="sm" onClick={handleSave}>+ {t('documents.custom-properties.save')}+ </Button>+ </div>+ </div>+ </PopoverContent>+ </Popover>+ );+};++const DatePropertyEditor: Component<{+ value: Date | null;+ onSave: (value: Date | null) => void;+ isPending: boolean;+}> = (props) => {+ const { t, formatDate } = useI18n();+ const [open, setOpen] = createSignal(false);++ const handleSave = (date: Date | null) => {+ props.onSave(date);+ setOpen(false);+ };++ return (+ <Popover open={open()} onOpenChange={setOpen} placement="bottom-start">+ <PopoverTrigger+ as={Button}+ variant="ghost"+ class="flex items-center gap-2 group bg-transparent! p-0 h-auto text-left"+ disabled={props.isPending}+ >+ <Show when={props.value} keyed fallback={<span class="text-muted-foreground">{t('documents.custom-properties.no-value')}</span>}>+ {d => formatDate(d, { dateStyle: 'medium' })}+ </Show>+ <div class="i-tabler-pencil size-4 text-muted-foreground group-hover:text-foreground transition-colors flex-shrink-0" />+ </PopoverTrigger>+ <PopoverContent class="w-auto p-3">+ <Calendar+ mode="single"+ value={props.value ?? null}+ onValueChange={handleSave}+ fixedWeeks+ >+ {() => (+ <div class="flex">+ <div class="flex flex-col gap-2">+ <CalendarMonthYearHeader />+ <CalendarGrid />+ </div>+ <div class="flex flex-col gap-1 min-w-28 ml-2 border-l pl-2">+ <Button+ variant="ghost"+ size="sm"+ class="justify-start text-sm"+ onClick={() => handleSave(new Date())}+ disabled={props.isPending}+ >+ <div class="i-tabler-calendar-event size-4 mr-2 text-muted-foreground" />+ {t('documents.info.today')}+ </Button>+ <Button+ variant="ghost"+ size="sm"+ class="justify-start text-sm"+ onClick={() => handleSave(null)}+ disabled={props.isPending}+ >+ <div class="i-tabler-x size-4 mr-2 text-muted-foreground" />+ {t('documents.custom-properties.clear')}+ </Button>+ </div>+ </div>+ )}+ </Calendar>+ </PopoverContent>+ </Popover>+ );+};++const BooleanPropertyEditor: Component<{+ value: boolean | null;+ onSave: (value: boolean) => void;+ isPending: boolean;+}> = (props) => {+ return (+ <Switch+ checked={props.value ?? false}+ onChange={checked => props.onSave(checked)}+ disabled={props.isPending}+ >+ <SwitchControl>+ <SwitchThumb />+ </SwitchControl>+ </Switch>+ );+};++const SelectPropertyEditor: Component<{+ value: SelectOption | null;+ options: { id: string; name: string }[];+ onSave: (value: string | null) => void;+ isPending: boolean;+}> = (props) => {+ const { t } = useI18n();+ const [open, setOpen] = createSignal(false);++ const handleSelect = (optionId: string) => {+ props.onSave(optionId);+ setOpen(false);+ };++ const handleClear = () => {+ props.onSave(null);+ setOpen(false);+ };++ return (+ <Popover open={open()} onOpenChange={setOpen} placement="bottom-start">+ <PopoverTrigger+ as={Button}+ variant="ghost"+ class="flex items-center gap-2 group bg-transparent! p-0 h-auto text-left"+ disabled={props.isPending}+ >+ <Show when={props.value?.name} keyed fallback={<span class="text-muted-foreground">{t('documents.custom-properties.no-value')}</span>}>+ {name => <span>{name}</span>}+ </Show>+ <div class="i-tabler-pencil size-4 text-muted-foreground group-hover:text-foreground transition-colors flex-shrink-0" />+ </PopoverTrigger>+ <PopoverContent class="w-48 p-2">+ <div class="flex flex-col gap-1">+ <For each={props.options}>+ {option => (+ <button+ type="button"+ class={`flex items-center gap-2 px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors text-left w-full${props.value?.optionId === option.id ? ' bg-accent' : ''}`}+ onClick={() => handleSelect(option.id)}+ >+ {option.name}+ </button>+ )}+ </For>+ <Show when={props.value !== null}>+ <Separator class="my-1" />+ <button+ type="button"+ class="flex items-center gap-2 px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors text-left w-full text-muted-foreground"+ onClick={handleClear}+ >+ <div class="i-tabler-x size-4" />+ {t('documents.custom-properties.clear')}+ </button>+ </Show>+ </div>+ </PopoverContent>+ </Popover>+ );+};++const MultiSelectPropertyEditor: Component<{+ value: SelectOption[];+ options: { id: string; name: string }[];+ onSave: (value: string[]) => void;+ isPending: boolean;+}> = (props) => {+ const { t } = useI18n();+ const [open, setOpen] = createSignal(false);++ const selectedIds = createMemo(() => (props.value ?? []).map(v => v.optionId));+ const displayText = createMemo(() => {+ const selected = props.value ?? [];+ return selected.length === 0 ? null : selected.map(v => v.name ?? v.optionId).join(', ');+ });++ const toggleOption = (optionId: string) => {+ const current = selectedIds();+ const next = current.includes(optionId)+ ? current.filter(id => id !== optionId)+ : [...current, optionId];+ props.onSave(next);+ };++ const handleClear = () => {+ props.onSave([]);+ setOpen(false);+ };++ return (+ <Popover open={open()} onOpenChange={setOpen} placement="bottom-start">+ <PopoverTrigger+ as={Button}+ variant="ghost"+ class="flex items-center gap-2 group bg-transparent! p-0 h-auto text-left"+ disabled={props.isPending}+ >+ <Show when={displayText()} keyed fallback={<span class="text-muted-foreground">{t('documents.custom-properties.no-value')}</span>}>+ {text => <span class="max-w-40 truncate">{text}</span>}+ </Show>+ <div class="i-tabler-pencil size-4 text-muted-foreground group-hover:text-foreground transition-colors flex-shrink-0" />+ </PopoverTrigger>+ <PopoverContent class="w-52 p-2">+ <div class="flex flex-col gap-1">+ <For each={props.options}>+ {(option) => {+ const isSelected = () => selectedIds().includes(option.id);+ return (+ <button+ type="button"+ class="flex items-center gap-2 px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors text-left w-full"+ onClick={() => toggleOption(option.id)}+ >+ <div class={`size-4 rounded border flex-shrink-0 flex items-center justify-center ${isSelected() ? 'bg-primary border-primary' : 'border-input'}`}>+ <Show when={isSelected()}>+ <div class="i-tabler-check size-3 text-primary-foreground" />+ </Show>+ </div>+ {option.name}+ </button>+ );+ }}+ </For>+ <Show when={selectedIds().length > 0}>+ <Separator class="my-1" />+ <button+ type="button"+ class="flex items-center gap-2 px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors text-left w-full text-muted-foreground"+ onClick={handleClear}+ >+ <div class="i-tabler-x size-4" />+ {t('documents.custom-properties.clear')}+ </button>+ </Show>+ </div>+ </PopoverContent>+ </Popover>+ );+};++type UserRelationValue = { userId: string; name: string | null; email: string };++const UserRelationPropertyEditor: Component<{+ value: UserRelationValue[];+ organizationId: string;+ onSave: (value: string[]) => void;+ isPending: boolean;+}> = (props) => {+ const { t } = useI18n();+ const [open, setOpen] = createSignal(false);++ const membersQuery = useQuery(() => ({+ queryKey: ['organizations', props.organizationId, 'members'],+ queryFn: () => fetchOrganizationMembers({ organizationId: props.organizationId }),+ enabled: open(),+ }));++ const members = () => membersQuery.data?.members ?? [];+ const selectedUserIds = createMemo(() => props.value.map(u => u.userId));++ const toggleUser = (userId: string) => {+ const current = selectedUserIds();+ const next = current.includes(userId)+ ? current.filter(id => id !== userId)+ : [...current, userId];+ props.onSave(next);+ };++ const handleClear = () => {+ props.onSave([]);+ setOpen(false);+ };++ return (+ <Popover open={open()} onOpenChange={setOpen} placement="bottom-start">+ <div class="flex flex-col gap-0.5 min-w-0">+ <Show when={props.value.length > 0}>+ <For each={props.value}>+ {user => (+ <span class="text-sm truncate">+ {user.name ?? user.email}+ </span>+ )}+ </For>+ </Show>+ <PopoverTrigger+ as={Button}+ variant="ghost"+ class="flex items-center gap-1 group bg-transparent! p-0 h-auto text-left w-fit"+ disabled={props.isPending}+ >+ <Show+ when={props.value.length === 0}+ fallback={<span class="text-xs text-muted-foreground group-hover:text-foreground transition-colors">{t('documents.custom-properties.user-relation-manage')}</span>}+ >+ <span class="text-muted-foreground">{t('documents.custom-properties.no-value')}</span>+ </Show>+ <div class="i-tabler-pencil size-3.5 text-muted-foreground group-hover:text-foreground transition-colors flex-shrink-0" />+ </PopoverTrigger>+ </div>+ <PopoverContent class="w-64 p-2">+ <Suspense>+ <div class="flex flex-col gap-1">+ <For each={members()}>+ {(member) => {+ const userId = member.user?.id ?? '';+ const isSelected = () => selectedUserIds().includes(userId);+ const displayName = member.user?.name ?? member.user?.email ?? userId;+ return (+ <button+ type="button"+ class="flex items-center gap-2 px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors text-left w-full"+ onClick={() => toggleUser(userId)}+ >+ <div class={`size-4 rounded border flex-shrink-0 flex items-center justify-center ${isSelected() ? 'bg-primary border-primary' : 'border-input'}`}>+ <Show when={isSelected()}>+ <div class="i-tabler-check size-3 text-primary-foreground" />+ </Show>+ </div>+ <div class="flex flex-col min-w-0">+ <span class="truncate">{displayName}</span>+ <Show when={member.user?.name}>+ <span class="text-xs text-muted-foreground truncate">{member.user?.email}</span>+ </Show>+ </div>+ </button>+ );+ }}+ </For>+ <Show when={selectedUserIds().length > 0}>+ <Separator class="my-1" />+ <button+ type="button"+ class="flex items-center gap-2 px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors text-left w-full text-muted-foreground"+ onClick={handleClear}+ >+ <div class="i-tabler-x size-4" />+ {t('documents.custom-properties.clear')}+ </button>+ </Show>+ </div>+ </Suspense>+ </PopoverContent>+ </Popover>+ );+};++type RelatedDocumentValue = { documentId: string; name: string };++const DocumentRelationPropertyEditor: Component<{+ value: RelatedDocumentValue[];+ organizationId: string;+ onSave: (value: string[]) => void;+ isPending: boolean;+}> = (props) => {+ const { t } = useI18n();+ const [open, setOpen] = createSignal(false);+ const [search, setSearch] = createSignal('');+ const debouncedSearch = useDebounce(search, 300);++ const isSearchActive = () => debouncedSearch().length > 0;++ const documentsQuery = useQuery(() => ({+ queryKey: ['organizations', props.organizationId, 'documents', { searchQuery: debouncedSearch() }],+ queryFn: () => fetchOrganizationDocuments({ organizationId: props.organizationId, searchQuery: debouncedSearch(), pageIndex: 0, pageSize: 10 }),+ enabled: open() && isSearchActive(),+ }));++ const searchResults = () => documentsQuery.data?.documents ?? [];+ const selectedDocumentIds = createMemo(() => props.value.map(d => d.documentId));++ const toggleDocument = (documentId: string) => {+ const current = selectedDocumentIds();+ const next = current.includes(documentId)+ ? current.filter(id => id !== documentId)+ : [...current, documentId];+ props.onSave(next);+ };++ const handleClear = () => {+ props.onSave([]);+ setOpen(false);+ };++ return (+ <Popover+ open={open()}+ onOpenChange={(isOpen) => {+ setOpen(isOpen);+ if (!isOpen) {+ setSearch('');+ }+ }}+ placement="bottom-start"+ >+ <div class="flex flex-col gap-0.5 min-w-0">+ <Show when={props.value.length > 0}>+ <For each={props.value}>+ {doc => (+ <A+ href={`/organizations/${props.organizationId}/documents/${doc.documentId}`}+ class="text-sm hover:underline truncate"+ >+ {doc.name}+ </A>+ )}+ </For>+ </Show>+ <PopoverTrigger+ as={Button}+ variant="ghost"+ class="flex items-center gap-1 group bg-transparent! p-0 h-auto text-left w-fit"+ disabled={props.isPending}+ >+ <Show+ when={props.value.length === 0}+ fallback={<span class="text-xs text-muted-foreground group-hover:text-foreground transition-colors">{t('documents.custom-properties.document-relation-manage')}</span>}+ >+ <span class="text-muted-foreground">{t('documents.custom-properties.no-value')}</span>+ </Show>+ <div class="i-tabler-pencil size-3.5 text-muted-foreground group-hover:text-foreground transition-colors flex-shrink-0" />+ </PopoverTrigger>+ </div>+ <PopoverContent class="w-72 p-2">+ <div class="flex flex-col gap-1">+ <TextFieldRoot class="mb-1">+ <TextField+ value={search()}+ onInput={e => setSearch(e.currentTarget.value)}+ placeholder={t('documents.custom-properties.document-relation-search-placeholder')}+ />+ </TextFieldRoot>+ <Suspense>+ <Show+ when={isSearchActive()}+ fallback={(+ <Show+ when={props.value.length > 0}+ fallback={<span class="text-sm text-muted-foreground px-2 py-1.5">{t('documents.custom-properties.no-results')}</span>}+ >+ <For each={props.value}>+ {doc => (+ <button+ type="button"+ class="flex items-center gap-2 px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors text-left w-full"+ onClick={() => toggleDocument(doc.documentId)}+ >+ <div class="size-4 rounded border flex-shrink-0 flex items-center justify-center bg-primary border-primary">+ <div class="i-tabler-check size-3 text-primary-foreground" />+ </div>+ <span class="truncate">{doc.name}</span>+ </button>+ )}+ </For>+ </Show>+ )}+ >+ <Show+ when={searchResults().length > 0}+ fallback={<span class="text-sm text-muted-foreground px-2 py-1.5">{t('documents.custom-properties.no-results')}</span>}+ >+ <For each={searchResults()}>+ {(doc) => {+ const isSelected = () => selectedDocumentIds().includes(doc.id);+ return (+ <button+ type="button"+ class="flex items-center gap-2 px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors text-left w-full"+ onClick={() => toggleDocument(doc.id)}+ >+ <div class={`size-4 rounded border flex-shrink-0 flex items-center justify-center ${isSelected() ? 'bg-primary border-primary' : 'border-input'}`}>+ <Show when={isSelected()}>+ <div class="i-tabler-check size-3 text-primary-foreground" />+ </Show>+ </div>+ <span class="truncate">{doc.name}</span>+ </button>+ );+ }}+ </For>+ </Show>+ </Show>+ <Show when={selectedDocumentIds().length > 0}>+ <Separator class="my-1" />+ <button+ type="button"+ class="flex items-center gap-2 px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors text-left w-full text-muted-foreground"+ onClick={handleClear}+ >+ <div class="i-tabler-x size-4" />+ {t('documents.custom-properties.clear')}+ </button>+ </Show>+ </Suspense>+ </div>+ </PopoverContent>+ </Popover>+ );+};++const PropertyValueEditor: Component<{+ definition: CustomPropertyDefinition;+ rawValue: unknown;+ documentId: string;+ organizationId: string;+}> = (props) => {+ const { getErrorMessage } = useI18nApiErrors();++ const mutation = useMutation(() => ({+ mutationFn: (value: string | number | boolean | string[] | null) => {+ if (value === null) {+ return deleteDocumentCustomPropertyValue({+ organizationId: props.organizationId,+ documentId: props.documentId,+ propertyDefinitionId: props.definition.id,+ });+ }+ return setDocumentCustomPropertyValue({+ organizationId: props.organizationId,+ documentId: props.documentId,+ propertyDefinitionId: props.definition.id,+ value,+ });+ },+ onSuccess: () => queryClient.invalidateQueries({+ queryKey: ['organizations', props.organizationId, 'documents', props.documentId],+ }),+ onError: (error: unknown) => {+ createToast({ message: getErrorMessage({ error }), type: 'error' });+ },+ }));++ const save = (value: string | number | boolean | string[] | null) => {+ mutation.mutate(value);+ };++ return (+ <SolidSwitch>+ <Match when={props.definition.type === 'text'}>+ <TextPropertyEditor+ value={typeof props.rawValue === 'string' ? props.rawValue : null}+ onSave={save}+ isPending={mutation.isPending}+ />+ </Match>+ <Match when={props.definition.type === 'number'}>+ <NumberPropertyEditor+ value={typeof props.rawValue === 'number' ? props.rawValue : null}+ onSave={save}+ isPending={mutation.isPending}+ />+ </Match>+ <Match when={props.definition.type === 'date'}>+ <DatePropertyEditor+ value={getDateValue(props.rawValue)}+ onSave={date => save(date ? date.toISOString() : null)}+ isPending={mutation.isPending}+ />+ </Match>+ <Match when={props.definition.type === 'boolean'}>+ <BooleanPropertyEditor+ value={typeof props.rawValue === 'boolean' ? props.rawValue : null}+ onSave={save}+ isPending={mutation.isPending}+ />+ </Match>+ <Match when={props.definition.type === 'select'}>+ <SelectPropertyEditor+ value={rawPropertyValueAsOption(props.rawValue)}+ options={props.definition.options}+ onSave={optionId => save(optionId)}+ isPending={mutation.isPending}+ />+ </Match>+ <Match when={props.definition.type === 'multi_select'}>+ <MultiSelectPropertyEditor+ value={rawPropertyValueAsOptionArray(props.rawValue)}+ options={props.definition.options}+ onSave={ids => save(ids)}+ isPending={mutation.isPending}+ />+ </Match>+ <Match when={props.definition.type === 'user_relation'}>+ <UserRelationPropertyEditor+ value={rawPropertyValueAsUserArray(props.rawValue)}+ organizationId={props.organizationId}+ onSave={ids => save(ids)}+ isPending={mutation.isPending}+ />+ </Match>+ <Match when={props.definition.type === 'document_relation'}>+ <DocumentRelationPropertyEditor+ value={rawPropertyValueAsRelatedDocumentArray(props.rawValue)}+ organizationId={props.organizationId}+ onSave={ids => save(ids)}+ isPending={mutation.isPending}+ />+ </Match>+ </SolidSwitch>+ );+};++export const DocumentCustomPropertiesPanel: Component<{+ document: Document;+ organizationId: string;+ propertyDefinitions: CustomPropertyDefinition[];+}> = (props) => {+ const { t } = useI18n();++ const definitions = createMemo(() => props.propertyDefinitions.toSorted((a, b) => a.displayOrder - b.displayOrder));+ const getPropertyValueByKey = createMemo(() => Object.fromEntries(props.document.customProperties?.map(p => [p.key, p.value]) ?? []));+ const getPropertyValue = (key: string) => getPropertyValueByKey()[key] ?? null;++ return (+ <Show when={definitions().length > 0}>+ <>+ <div class="col-span-2 mt-4">+ <Separator class="mb-3" />+ <p class="text-xs font-medium text-muted-foreground mb-2 uppercase tracking-wide">+ {t('documents.custom-properties.section-title')}+ </p>+ </div>+ <For each={definitions()}>+ {definition => (+ <>+ <div class="py-1 pr-2 text-sm text-muted-foreground flex items-start">+ <div class="flex items-center gap-2 whitespace-nowrap">+ <div class="i-tabler-tag size-4" />+ {definition.name}+ </div>++ </div>+ <div class="py-1 pl-2 text-sm">+ <PropertyValueEditor+ definition={definition}+ rawValue={getPropertyValue(definition.key)}+ documentId={props.document.id}+ organizationId={props.organizationId}+ />+ </div>+ </>+ )}+ </For>+ </>+ </Show>+ );+};diff --git a/apps/papra-client/src/modules/custom-properties/custom-properties.constants.ts b/apps/papra-client/src/modules/custom-properties/custom-properties.constants.tsnew file mode 100644index 00000000..7f61217a--- /dev/null+++ b/apps/papra-client/src/modules/custom-properties/custom-properties.constants.ts@@ -0,0 +1,13 @@+import type { TranslationsDictionary } from '../i18n/locales.types';+import type { CustomPropertyType } from './custom-properties.types';++export const PROPERTY_TYPE_LABEL_I18N_KEYS: Record<CustomPropertyType, keyof TranslationsDictionary> = {+ text: 'custom-properties.types.text',+ number: 'custom-properties.types.number',+ date: 'custom-properties.types.date',+ boolean: 'custom-properties.types.boolean',+ select: 'custom-properties.types.select',+ multi_select: 'custom-properties.types.multi_select',+ user_relation: 'custom-properties.types.user_relation',+ document_relation: 'custom-properties.types.document_relation',+} as const;diff --git a/apps/papra-client/src/modules/custom-properties/custom-properties.models.ts b/apps/papra-client/src/modules/custom-properties/custom-properties.models.tsnew file mode 100644index 00000000..680912d2--- /dev/null+++ b/apps/papra-client/src/modules/custom-properties/custom-properties.models.ts@@ -0,0 +1,50 @@+export function rawPropertyValueAsOption(value: unknown): { optionId: string; name: string } | null {+ if (+ typeof value === 'object'+ && value !== null+ && 'optionId' in value+ && typeof value.optionId === 'string'+ && 'name' in value+ && typeof value.name === 'string'+ ) {+ return { optionId: value.optionId, name: value.name };+ }+ return null;+}++export function rawPropertyValueAsOptionArray(value: unknown): { optionId: string; name: string }[] {+ if (Array.isArray(value)) {+ return value.map(rawPropertyValueAsOption).filter(v => v !== null);+ }+ return [];+}++export function rawPropertyValueAsUserArray(value: unknown): { userId: string; name: string | null; email: string }[] {+ if (!Array.isArray(value)) {+ return [];+ }+ return value.filter(+ (v): v is { userId: string; name: string | null; email: string } =>+ typeof v === 'object'+ && v !== null+ && 'userId' in v+ && typeof v.userId === 'string'+ && 'email' in v+ && typeof v.email === 'string',+ );+}++export function rawPropertyValueAsRelatedDocumentArray(value: unknown): { documentId: string; name: string }[] {+ if (!Array.isArray(value)) {+ return [];+ }+ return value.filter(+ (v): v is { documentId: string; name: string } =>+ typeof v === 'object'+ && v !== null+ && 'documentId' in v+ && typeof v.documentId === 'string'+ && 'name' in v+ && typeof v.name === 'string',+ );+}diff --git a/apps/papra-client/src/modules/custom-properties/custom-properties.services.ts b/apps/papra-client/src/modules/custom-properties/custom-properties.services.tsnew file mode 100644index 00000000..85815467--- /dev/null+++ b/apps/papra-client/src/modules/custom-properties/custom-properties.services.ts@@ -0,0 +1,119 @@+import type { AsDto } from '../shared/http/http-client.types';+import type { CustomPropertyDefinition, CustomPropertyType } from './custom-properties.types';+import { apiClient } from '../shared/http/api-client';+import { coerceDates } from '../shared/http/http-client.models';++export async function fetchCustomPropertyDefinitions({ organizationId }: { organizationId: string }) {+ const { propertyDefinitions } = await apiClient<{ propertyDefinitions: AsDto<CustomPropertyDefinition>[] }>({+ path: `/api/organizations/${organizationId}/custom-properties`,+ method: 'GET',+ });++ return {+ propertyDefinitions: propertyDefinitions.map(coerceDates),+ };+}++export async function fetchCustomPropertyDefinition({ organizationId, propertyDefinitionId }: { organizationId: string; propertyDefinitionId: string }) {+ const { definition } = await apiClient<{ definition: AsDto<CustomPropertyDefinition> }>({+ path: `/api/organizations/${organizationId}/custom-properties/${propertyDefinitionId}`,+ method: 'GET',+ });++ return {+ definition: coerceDates(definition),+ };+}++export async function createCustomPropertyDefinition({+ organizationId,+ propertyDefinition,+}: {+ organizationId: string;+ propertyDefinition: {+ name: string;+ description?: string;+ type: CustomPropertyType;+ options?: { name: string }[];+ };+}) {+ const { propertyDefinition: created } = await apiClient<{ propertyDefinition: AsDto<CustomPropertyDefinition> }>({+ path: `/api/organizations/${organizationId}/custom-properties`,+ method: 'POST',+ body: propertyDefinition,+ });++ return {+ propertyDefinition: coerceDates(created),+ };+}++export async function updateCustomPropertyDefinition({+ organizationId,+ propertyDefinitionId,+ propertyDefinition,+}: {+ organizationId: string;+ propertyDefinitionId: string;+ propertyDefinition: {+ name?: string;+ description?: string;+ options?: { id?: string; name: string }[];+ };+}) {+ const { propertyDefinition: updated } = await apiClient<{ propertyDefinition: AsDto<CustomPropertyDefinition> }>({+ path: `/api/organizations/${organizationId}/custom-properties/${propertyDefinitionId}`,+ method: 'PUT',+ body: propertyDefinition,+ });++ return {+ propertyDefinition: coerceDates(updated),+ };+}++export async function deleteCustomPropertyDefinition({+ organizationId,+ propertyDefinitionId,+}: {+ organizationId: string;+ propertyDefinitionId: string;+}) {+ await apiClient({+ path: `/api/organizations/${organizationId}/custom-properties/${propertyDefinitionId}`,+ method: 'DELETE',+ });+}++export async function setDocumentCustomPropertyValue({+ organizationId,+ documentId,+ propertyDefinitionId,+ value,+}: {+ organizationId: string;+ documentId: string;+ propertyDefinitionId: string;+ value: string | number | boolean | string[];+}) {+ await apiClient({+ path: `/api/organizations/${organizationId}/documents/${documentId}/custom-properties/${propertyDefinitionId}`,+ method: 'PUT',+ body: { value },+ });+}++export async function deleteDocumentCustomPropertyValue({+ organizationId,+ documentId,+ propertyDefinitionId,+}: {+ organizationId: string;+ documentId: string;+ propertyDefinitionId: string;+}) {+ await apiClient({+ path: `/api/organizations/${organizationId}/documents/${documentId}/custom-properties/${propertyDefinitionId}`,+ method: 'DELETE',+ });+}diff --git a/apps/papra-client/src/modules/custom-properties/custom-properties.types.ts b/apps/papra-client/src/modules/custom-properties/custom-properties.types.tsnew file mode 100644index 00000000..cad4ce13--- /dev/null+++ b/apps/papra-client/src/modules/custom-properties/custom-properties.types.ts@@ -0,0 +1,29 @@+export type CustomPropertyType = 'text' | 'number' | 'date' | 'boolean' | 'select' | 'multi_select' | 'user_relation' | 'document_relation';++export type DocumentCustomProperty = {+ key: string;+ name: string;+ type: CustomPropertyType;+ displayOrder: number;+ value: unknown;+};++export type CustomPropertySelectOption = {+ id: string;+ name: string;+ key: string;+ displayOrder: number;+};++export type CustomPropertyDefinition = {+ id: string;+ organizationId: string;+ name: string;+ key: string;+ description?: string | null;+ type: CustomPropertyType;+ displayOrder: number;+ options: CustomPropertySelectOption[];+ createdAt: Date;+ updatedAt: Date;+};diff --git a/apps/papra-client/src/modules/custom-properties/pages/create-custom-property.page.tsx b/apps/papra-client/src/modules/custom-properties/pages/create-custom-property.page.tsxnew file mode 100644index 00000000..7072ed7e--- /dev/null+++ b/apps/papra-client/src/modules/custom-properties/pages/create-custom-property.page.tsx@@ -0,0 +1,57 @@+import type { Component } from 'solid-js';+import type { PropertyDefinitionDraft } from '../components/custom-property-definition-form.component';+import { useNavigate, useParams } from '@solidjs/router';+import { useMutation } from '@tanstack/solid-query';+import { useI18n } from '@/modules/i18n/i18n.provider';+import { queryClient } from '@/modules/shared/query/query-client';+import { Button } from '@/modules/ui/components/button';+import { createToast } from '@/modules/ui/components/sonner';+import { CustomPropertyDefinitionForm } from '../components/custom-property-definition-form.component';+import { createCustomPropertyDefinition } from '../custom-properties.services';++export const CreateCustomPropertyPage: Component = () => {+ const params = useParams();+ const navigate = useNavigate();+ const { t } = useI18n();++ const createMutation = useMutation(() => ({+ mutationFn: async ({ propertyDefinition }: { propertyDefinition: PropertyDefinitionDraft }) => {+ await createCustomPropertyDefinition({ organizationId: params.organizationId, propertyDefinition });+ },+ onSuccess: async () => {+ await queryClient.invalidateQueries({ queryKey: ['organizations', params.organizationId, 'custom-properties'] });++ createToast({+ message: t('custom-properties.create.success'),+ type: 'success',+ });+ navigate(`/organizations/${params.organizationId}/custom-properties`);+ },+ onError: () => {+ createToast({+ message: t('custom-properties.create.error'),+ type: 'error',+ });+ },+ }));++ return (+ <div class="p-6 max-w-screen-md mx-auto mt-4">+ <div class="border-b mb-6 pb-4">+ <h1 class="text-xl font-bold">+ {t('custom-properties.create.title')}+ </h1>+ </div>++ <CustomPropertyDefinitionForm+ organizationId={params.organizationId}+ onSubmit={({ propertyDefinition }) => createMutation.mutateAsync({ propertyDefinition })}+ submitButton={(+ <Button type="submit" isLoading={createMutation.isPending}>+ {t('custom-properties.create.submit')}+ </Button>+ )}+ />+ </div>+ );+};diff --git a/apps/papra-client/src/modules/custom-properties/pages/custom-properties-list.page.tsx b/apps/papra-client/src/modules/custom-properties/pages/custom-properties-list.page.tsxnew file mode 100644index 00000000..415763e6--- /dev/null+++ b/apps/papra-client/src/modules/custom-properties/pages/custom-properties-list.page.tsx@@ -0,0 +1,260 @@+import type { Component } from 'solid-js';+import type { CustomPropertyType } from '../custom-properties.types';+import { A, useParams } from '@solidjs/router';+import { useMutation, useQuery } from '@tanstack/solid-query';+import { createSolidTable, flexRender, getCoreRowModel, getSortedRowModel } from '@tanstack/solid-table';+import { For, Show, Suspense } from 'solid-js';+import { RelativeTime } from '@/modules/i18n/components/RelativeTime';+import { useI18n } from '@/modules/i18n/i18n.provider';+import { useConfirmModal } from '@/modules/shared/confirm';+import { queryClient } from '@/modules/shared/query/query-client';+import { Button } from '@/modules/ui/components/button';+import { EmptyState } from '@/modules/ui/components/empty';+import { createToast } from '@/modules/ui/components/sonner';+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/modules/ui/components/table';+import { PROPERTY_TYPE_LABEL_I18N_KEYS } from '../custom-properties.constants';+import {+ deleteCustomPropertyDefinition,+ fetchCustomPropertyDefinitions,+} from '../custom-properties.services';++const TYPE_ICON: Record<CustomPropertyType, string> = {+ text: 'i-tabler-text-size',+ number: 'i-tabler-123',+ date: 'i-tabler-calendar',+ boolean: 'i-tabler-toggle-left',+ select: 'i-tabler-list',+ multi_select: 'i-tabler-list-check',+ user_relation: 'i-tabler-user',+ document_relation: 'i-tabler-file-symlink',+};++export const DeleteCustomPropertyButton: Component<{ organizationId: string; propertyDefinitionId: string; propertyDefinitionName: string }> = (props) => {+ const { confirm } = useConfirmModal();+ const { t } = useI18n();++ const deleteMutation = useMutation(() => ({+ mutationFn: async () => {+ await deleteCustomPropertyDefinition({ organizationId: props.organizationId, propertyDefinitionId: props.propertyDefinitionId });+ },+ onSuccess: async () => {+ await queryClient.invalidateQueries({ queryKey: ['organizations', props.organizationId, 'custom-properties'] });++ createToast({+ message: t('custom-properties.list.delete.success'),+ type: 'success',+ });+ },+ onError: () => {+ createToast({+ message: t('custom-properties.list.delete.error'),+ type: 'error',+ });+ },+ }));++ const handleDelete = async () => {+ const isConfirmed = await confirm({+ title: t('custom-properties.list.delete.confirm-title'),+ message: t('custom-properties.list.delete.confirm-message', { name: props.propertyDefinitionName }),+ confirmButton: {+ text: t('custom-properties.list.delete.confirm-button'),+ variant: 'destructive',+ },+ });++ if (isConfirmed) {+ deleteMutation.mutate();+ }+ };++ return (+ <Button size="icon" variant="outline" class="size-7 text-red" onClick={handleDelete} disabled={deleteMutation.isPending} aria-label={`Delete custom property ${props.propertyDefinitionName}`}>+ <div class="i-tabler-trash size-4" />+ </Button>+ );+};++export const CustomPropertiesPage: Component = () => {+ const params = useParams();+ const { t } = useI18n();++ const query = useQuery(() => ({+ queryKey: ['organizations', params.organizationId, 'custom-properties'],+ queryFn: () => fetchCustomPropertyDefinitions({ organizationId: params.organizationId }),+ }));++ const table = createSolidTable({+ get data() {+ return query.data?.propertyDefinitions ?? [];+ },+ columns: [+ {+ header: () => t('custom-properties.list.table.name'),+ accessorKey: 'name',+ sortingFn: 'alphanumeric',+ cell: data => (+ <A href={`/organizations/${params.organizationId}/custom-properties/${data.row.original.id}`} class="font-medium hover:underline">{data.getValue<string>()}</A>+ ),+ },+ {+ header: () => t('custom-properties.list.table.type'),+ accessorKey: 'type',+ sortingFn: 'alphanumeric',+ cell: (data) => {+ const type = data.getValue<CustomPropertyType>();+ return (+ <div class="flex items-center gap-1.5 w-fit px-2 py-0.5 rounded bg-muted text-xs font-medium">+ <div class={`${TYPE_ICON[type]} size-3.5 text-muted-foreground`} />+ {t(PROPERTY_TYPE_LABEL_I18N_KEYS[type])}+ </div>+ );+ },+ },+ {+ header: () => t('custom-properties.list.table.description'),+ accessorKey: 'description',+ sortingFn: 'alphanumeric',+ cell: data => (+ <span class="text-wrap">+ {data.getValue<string | null>() || <span class="text-muted-foreground">{t('custom-properties.list.table.no-description')}</span>}+ </span>+ ),+ },+ {+ header: () => t('custom-properties.list.table.created'),+ accessorKey: 'createdAt',+ sortingFn: 'datetime',+ cell: data => (+ <RelativeTime class="text-muted-foreground" date={data.getValue<Date>()} />+ ),+ },+ {+ id: 'actions',+ header: () => <span class="text-right">{t('custom-properties.list.table.actions')}</span>,+ cell: data => (+ <div class="flex gap-2 justify-end">+ <Button+ as={A}+ href={`/organizations/${params.organizationId}/custom-properties/${data.row.original.id}`}+ size="icon"+ variant="outline"+ class="size-7"+ aria-label={`Edit custom property ${data.row.original.name}`}+ >+ <div class="i-tabler-pencil size-4" />+ </Button>+ <DeleteCustomPropertyButton+ organizationId={params.organizationId}+ propertyDefinitionId={data.row.original.id}+ propertyDefinitionName={data.row.original.name}+ />+ </div>+ ),+ },+ ],+ initialState: {+ sorting: [{ id: 'name', desc: false }],+ },+ getCoreRowModel: getCoreRowModel(),+ getSortedRowModel: getSortedRowModel(),+ });++ return (+ <div class="p-6 mt-4 pb-32 mx-auto max-w-5xl">+ <Suspense>+ <Show when={query.data?.propertyDefinitions}>+ {getPropertyDefinitions => (+ <Show+ when={getPropertyDefinitions().length > 0}+ fallback={(+ <EmptyState+ title={t('custom-properties.list.empty.title')}+ icon="i-tabler-forms"+ description={t('custom-properties.list.empty.description')}+ cta={(+ <Button as={A} href={`/organizations/${params.organizationId}/custom-properties/create`}>+ <div class="i-tabler-plus size-4 mr-2" />+ {t('custom-properties.list.create-button')}+ </Button>+ )}+ />+ )}+ >+ <div class="flex justify-between sm:items-center pb-6 gap-4 flex-col sm:flex-row">+ <div>+ <h2 class="text-xl font-bold">+ {t('custom-properties.list.title')}+ </h2>++ <p class="text-muted-foreground mt-1">+ {t('custom-properties.list.description')}+ </p>+ </div>++ <div class="flex-shrink-0">+ <Button as={A} href={`/organizations/${params.organizationId}/custom-properties/create`} class="w-full">+ <div class="i-tabler-plus size-4 mr-2" />+ {t('custom-properties.list.create-button')}+ </Button>+ </div>+ </div>++ <Table>+ <TableHeader>+ <For each={table.getHeaderGroups()}>+ {headerGroup => (+ <TableRow>+ <For each={headerGroup.headers}>+ {header => (+ <TableHead>+ <Show+ when={header.column.getCanSort()}+ fallback={flexRender(header.column.columnDef.header, header.getContext())}+ >+ <button+ class="flex items-center gap-1 cursor-pointer select-none"+ onClick={header.column.getToggleSortingHandler()}+ >+ {flexRender(header.column.columnDef.header, header.getContext())}+ <Show when={header.column.getIsSorted() === 'asc'}>+ <div class="i-tabler-arrow-down size-3.5" />+ </Show>+ <Show when={header.column.getIsSorted() === 'desc'}>+ <div class="i-tabler-arrow-up size-3.5" />+ </Show>+ <Show when={!header.column.getIsSorted()}>+ <div class="i-tabler-arrows-sort size-3.5 opacity-40" />+ </Show>+ </button>+ </Show>+ </TableHead>+ )}+ </For>+ </TableRow>+ )}+ </For>+ </TableHeader>+ <TableBody>+ <For each={table.getRowModel().rows}>+ {row => (+ <TableRow>+ <For each={row.getVisibleCells()}>+ {cell => (+ <TableCell>+ {flexRender(cell.column.columnDef.cell, cell.getContext())}+ </TableCell>+ )}+ </For>+ </TableRow>+ )}+ </For>+ </TableBody>+ </Table>+ </Show>+ )}+ </Show>+ </Suspense>+ </div>+ );+};diff --git a/apps/papra-client/src/modules/custom-properties/pages/update-custom-property.page.tsx b/apps/papra-client/src/modules/custom-properties/pages/update-custom-property.page.tsxnew file mode 100644index 00000000..0dd39722--- /dev/null+++ b/apps/papra-client/src/modules/custom-properties/pages/update-custom-property.page.tsx@@ -0,0 +1,75 @@+import type { Component } from 'solid-js';+import type { PropertyDefinitionDraft } from '../components/custom-property-definition-form.component';+import { useNavigate, useParams } from '@solidjs/router';+import { useMutation, useQuery } from '@tanstack/solid-query';+import { Show } from 'solid-js';+import { useI18n } from '@/modules/i18n/i18n.provider';+import { queryClient } from '@/modules/shared/query/query-client';+import { Button } from '@/modules/ui/components/button';+import { createToast } from '@/modules/ui/components/sonner';+import { CustomPropertyDefinitionForm } from '../components/custom-property-definition-form.component';+import { fetchCustomPropertyDefinition, updateCustomPropertyDefinition } from '../custom-properties.services';++export const UpdateCustomPropertyPage: Component = () => {+ const params = useParams();+ const navigate = useNavigate();+ const { t } = useI18n();++ const query = useQuery(() => ({+ queryKey: ['organizations', params.organizationId, 'custom-properties', params.propertyDefinitionId],+ queryFn: () => fetchCustomPropertyDefinition({ organizationId: params.organizationId, propertyDefinitionId: params.propertyDefinitionId }),+ }));++ const updateMutation = useMutation(() => ({+ mutationFn: async ({ propertyDefinition }: { propertyDefinition: PropertyDefinitionDraft }) => {+ // Cannot update the type+ const { type: _, ...definition } = propertyDefinition;++ await updateCustomPropertyDefinition({+ organizationId: params.organizationId,+ propertyDefinitionId: params.propertyDefinitionId,+ propertyDefinition: definition,+ });+ },+ onSuccess: async () => {+ await queryClient.invalidateQueries({ queryKey: ['organizations', params.organizationId, 'custom-properties'] });++ createToast({+ message: t('custom-properties.update.success'),+ type: 'success',+ });+ navigate(`/organizations/${params.organizationId}/custom-properties`);+ },+ onError: () => {+ createToast({+ message: t('custom-properties.update.error'),+ type: 'error',+ });+ },+ }));++ return (+ <div class="p-6 max-w-screen-md mx-auto mt-4">+ <div class="border-b mb-6 pb-4">+ <h1 class="text-xl font-bold">+ {t('custom-properties.update.title')}+ </h1>+ </div>++ <Show when={query.data?.definition}>+ {getDefinition => (+ <CustomPropertyDefinitionForm+ organizationId={params.organizationId}+ propertyDefinition={getDefinition()}+ onSubmit={({ propertyDefinition }) => updateMutation.mutateAsync({ propertyDefinition })}+ submitButton={(+ <Button type="submit" isLoading={updateMutation.isPending}>+ {t('custom-properties.update.submit')}+ </Button>+ )}+ />+ )}+ </Show>+ </div>+ );+};diff --git a/apps/papra-client/src/modules/documents/components/document-date-picker.component.tsx b/apps/papra-client/src/modules/documents/components/document-date-picker.component.tsxindex 711dab88..30f08dae 100644--- a/apps/papra-client/src/modules/documents/components/document-date-picker.component.tsx+++ b/apps/papra-client/src/modules/documents/components/document-date-picker.component.tsx@@ -5,81 +5,13 @@ import { Show } from 'solid-js';import { useI18n } from '@/modules/i18n/i18n.provider';import { useI18nApiErrors } from '@/modules/shared/http/composables/i18n-api-errors';import { Button } from '@/modules/ui/components/button';-import { CalendarGrid, CalendarNav } from '@/modules/ui/components/calendar';+import { CalendarGrid } from '@/modules/ui/components/calendar';+import { CalendarMonthYearHeader } from '@/modules/ui/components/calendar-month-year-header';import { Popover, PopoverContent, PopoverTrigger } from '@/modules/ui/components/popover';-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/modules/ui/components/select';import { createToast } from '@/modules/ui/components/sonner';import { invalidateOrganizationDocumentsQuery } from '../documents.composables';import { updateDocument } from '../documents.services';-const YEAR_RANGE_OFFSET = 50;--function getMonthOptions() {- return Array.from({ length: 12 }, (_, i) => String(i));-}--function getYearOptions() {- const currentYear = new Date().getFullYear();- return Array.from({ length: YEAR_RANGE_OFFSET * 2 + 1 }, (_, i) => String(currentYear - YEAR_RANGE_OFFSET + i));-}--function formatMonthLabel(monthIndex: string) {- return new Date(2024, Number(monthIndex), 1).toLocaleDateString(undefined, { month: 'long' });-}--function CalendarMonthYearHeader() {- const context = Calendar.useContext<'single'>();-- const monthOptions = getMonthOptions();- const yearOptions = getYearOptions();-- return (- <div class="flex items-center justify-between">- <CalendarNav action="prev-month">- <div class="i-tabler-chevron-left size-4" />- </CalendarNav>-- <div class="flex items-center">- <Select- value={String(context.month().getMonth())}- onChange={value => value != null && context.setMonth(new Date(context.month().getFullYear(), Number(value), 1))}- options={monthOptions}- itemComponent={itemProps => (- <SelectItem item={itemProps.item}>- {formatMonthLabel(itemProps.item.rawValue)}- </SelectItem>- )}- >- <SelectTrigger class="border-none hover:bg-accent shadow-none text-sm font-medium gap-0" caretIcon={null}>- <SelectValue<string>>{state => formatMonthLabel(state.selectedOption())}</SelectValue>- </SelectTrigger>- <SelectContent />- </Select>-- <Select- value={String(context.month().getFullYear())}- onChange={value => value != null && context.setMonth(new Date(Number(value), context.month().getMonth(), 1))}- options={yearOptions}- itemComponent={itemProps => (- <SelectItem item={itemProps.item}>- {itemProps.item.rawValue}- </SelectItem>- )}- >- <SelectTrigger class="border-none hover:bg-accent shadow-none text-sm font-medium gap-0" caretIcon={null}>- <SelectValue<string>>{state => state.selectedOption()}</SelectValue>- </SelectTrigger>- <SelectContent />- </Select>- </div>-- <CalendarNav action="next-month">- <div class="i-tabler-chevron-right size-4" />- </CalendarNav>- </div>- );-}-export function DocumentDatePicker(props: { document: Document; organizationId: string }) {const { t, formatDate } = useI18n();const { getErrorMessage } = useI18nApiErrors();diff --git a/apps/papra-client/src/modules/documents/documents.types.ts b/apps/papra-client/src/modules/documents/documents.types.tsindex 06866b79..fddae0f3 100644--- a/apps/papra-client/src/modules/documents/documents.types.ts+++ b/apps/papra-client/src/modules/documents/documents.types.ts@@ -1,3 +1,4 @@+import type { DocumentCustomProperty } from '../custom-properties/custom-properties.types';import type { Tag } from '../tags/tags.types';import type { User } from '../users/users.types';import type { DOCUMENT_ACTIVITY_EVENTS } from './documents.constants';@@ -16,6 +17,7 @@ export type Document = {deletedBy?: string;content: string;tags: Tag[];+ customProperties?: DocumentCustomProperty[];};export type DocumentActivityEvent = (typeof DOCUMENT_ACTIVITY_EVENTS)[keyof typeof DOCUMENT_ACTIVITY_EVENTS];diff --git a/apps/papra-client/src/modules/documents/pages/document.page.tsx b/apps/papra-client/src/modules/documents/pages/document.page.tsxindex 4bdb0e1b..8b073910 100644--- a/apps/papra-client/src/modules/documents/pages/document.page.tsx+++ b/apps/papra-client/src/modules/documents/pages/document.page.tsx@@ -6,6 +6,8 @@ import { A, useNavigate, useParams, useSearchParams } from '@solidjs/router';import { useInfiniteQuery, useQuery } from '@tanstack/solid-query';import { createEffect, createSignal, For, Match, Show, Suspense, Switch } from 'solid-js';import { useConfig } from '@/modules/config/config.provider';+import { DocumentCustomPropertiesPanel } from '@/modules/custom-properties/components/document-custom-properties-panel.component';+import { fetchCustomPropertyDefinitions } from '@/modules/custom-properties/custom-properties.services';import { RelativeTime } from '@/modules/i18n/components/RelativeTime';import { useI18n } from '@/modules/i18n/i18n.provider';import { downloadFile } from '@/modules/shared/files/download';@@ -33,21 +35,17 @@ type KeyValueItem = {const KeyValues: Component<{ data?: KeyValueItem[] }> = (props) => {return (- <div class="flex flex-col gap-2">- <table>- <For each={props.data}>- {item => (- <tr>- <td class="py-1 pr-2 text-sm text-muted-foreground flex items-center gap-2 whitespace-nowrap">- {item.icon && <div class={item.icon} />}- {item.label}- </td>- <td class="py-1 pl-2 text-sm">{item.value}</td>- </tr>- )}- </For>- </table>- </div>+ <For each={props.data}>+ {item => (+ <>+ <div class="py-1 pr-2 text-sm text-muted-foreground flex items-center gap-2 whitespace-nowrap">+ {item.icon && <div class={item.icon} />}+ {item.label}+ </div>+ <div class="py-1 pl-2 text-sm">{item.value}</div>+ </>+ )}+ </For>);};@@ -158,6 +156,11 @@ export const DocumentPage: Component = () => {queryFn: () => fetchDocumentFile({ documentId: params.documentId, organizationId: params.organizationId }),}));+ const customPropertyDefinitionsQuery = useQuery(() => ({+ queryKey: ['organizations', params.organizationId, 'custom-properties'],+ queryFn: () => fetchCustomPropertyDefinitions({ organizationId: params.organizationId }),+ }));+const activityPageSize = 20;const activityQuery = useInfiniteQuery(() => ({enabled: getTab() === 'activity',@@ -291,58 +294,70 @@ export const DocumentPage: Component = () => {</TabsList><TabsContent value="info">- <KeyValues data={[- {- label: t('documents.info.id'),- value: getDocument().id,- icon: 'i-tabler-id',- },- {- label: t('documents.info.name'),- value: (- <Button- variant="ghost"- class="flex items-center gap-2 group bg-transparent! p-0 h-auto text-left"- onClick={() => openRenameDialog({- documentId: getDocument().id,- organizationId: params.organizationId,- documentName: getDocument().name,- })}- >- {getDocument().name}-- <div class="i-tabler-pencil size-4 text-muted-foreground group-hover:text-foreground transition-colors flex-shrink-0" />- </Button>- ),- icon: 'i-tabler-file-text',- },- {- label: t('documents.info.type'),- value: getDocument().mimeType,- icon: 'i-tabler-file-unknown',- },- {- label: t('documents.info.size'),- value: formatBytes({ bytes: getDocument().originalSize, base: 1000 }),- icon: 'i-tabler-weight',- },- {- label: t('documents.info.document-date'),- value: <DocumentDatePicker document={getDocument()} organizationId={params.organizationId} />,- icon: 'i-tabler-calendar-event',- },- {- label: t('documents.info.created-at'),- value: formatRelativeTime(getDocument().createdAt),- icon: 'i-tabler-calendar',- },- {- label: t('documents.info.updated-at'),- value: getDocument().updatedAt ? formatRelativeTime(getDocument().updatedAt!) : <span class="text-muted-foreground">{t('documents.info.never')}</span>,- icon: 'i-tabler-calendar',- },- ]}- />+ <div class="grid grid-cols-[max-content_1fr]">+ <KeyValues data={[+ {+ label: t('documents.info.id'),+ value: getDocument().id,+ icon: 'i-tabler-id',+ },+ {+ label: t('documents.info.name'),+ value: (+ <Button+ variant="ghost"+ class="flex items-center gap-2 group bg-transparent! p-0 h-auto text-left"+ onClick={() => openRenameDialog({+ documentId: getDocument().id,+ organizationId: params.organizationId,+ documentName: getDocument().name,+ })}+ >+ {getDocument().name}++ <div class="i-tabler-pencil size-4 text-muted-foreground group-hover:text-foreground transition-colors flex-shrink-0" />+ </Button>+ ),+ icon: 'i-tabler-file-text',+ },+ {+ label: t('documents.info.type'),+ value: getDocument().mimeType,+ icon: 'i-tabler-file-unknown',+ },+ {+ label: t('documents.info.size'),+ value: formatBytes({ bytes: getDocument().originalSize, base: 1000 }),+ icon: 'i-tabler-weight',+ },+ {+ label: t('documents.info.document-date'),+ value: <DocumentDatePicker document={getDocument()} organizationId={params.organizationId} />,+ icon: 'i-tabler-calendar-event',+ },+ {+ label: t('documents.info.created-at'),+ value: formatRelativeTime(getDocument().createdAt),+ icon: 'i-tabler-calendar',+ },+ {+ label: t('documents.info.updated-at'),+ value: getDocument().updatedAt ? formatRelativeTime(getDocument().updatedAt!) : <span class="text-muted-foreground">{t('documents.info.never')}</span>,+ icon: 'i-tabler-calendar',+ },+ ]}+ />++ <Show when={customPropertyDefinitionsQuery.data?.propertyDefinitions}>+ {getDefinitions => (+ <DocumentCustomPropertiesPanel+ document={getDocument()}+ organizationId={params.organizationId}+ propertyDefinitions={getDefinitions()}+ />+ )}+ </Show>+ </div></TabsContent><TabsContent value="content">diff --git a/apps/papra-client/src/modules/shared/http/composables/i18n-api-errors.ts b/apps/papra-client/src/modules/shared/http/composables/i18n-api-errors.tsindex 1dfdf35d..21ffea62 100644--- a/apps/papra-client/src/modules/shared/http/composables/i18n-api-errors.ts+++ b/apps/papra-client/src/modules/shared/http/composables/i18n-api-errors.ts@@ -31,6 +31,16 @@ export function useI18nApiErrors({ t = useI18n().t }: { t?: ReturnType<typeof us}}+ const responseMessage = get(+ error,+ ['data', 'error', 'message'], // From fetch errors+ ['details', 'message'], // From custom errors throw in better auth hooks, must be before ['message'] as they have both+ );++ if (responseMessage && typeof responseMessage === 'string') {+ return responseMessage;+ }+// Fetch error messages without codes are not helpfulif (error instanceof FetchError) {return defaultMessage;@@ -38,8 +48,6 @@ export function useI18nApiErrors({ t = useI18n().t }: { t?: ReturnType<typeof usconst message = get(error,- ['data', 'error', 'message'], // From fetch errors- ['details', 'message'], // From custom errors throw in better auth hooks, must be before ['message'] as they have both['message'], // From generic errors);diff --git a/apps/papra-client/src/modules/ui/components/calendar-month-year-header.tsx b/apps/papra-client/src/modules/ui/components/calendar-month-year-header.tsxnew file mode 100644index 00000000..f563704f--- /dev/null+++ b/apps/papra-client/src/modules/ui/components/calendar-month-year-header.tsx@@ -0,0 +1,65 @@+import Calendar from '@corvu/calendar';+import { CalendarNav } from './calendar';+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './select';++const YEAR_RANGE_OFFSET = 50;++const monthOptions = Array.from({ length: 12 }, (_, i) => String(i));+const yearOptions = (() => {+ const currentYear = new Date().getFullYear();+ return Array.from({ length: YEAR_RANGE_OFFSET * 2 + 1 }, (_, i) => String(currentYear - YEAR_RANGE_OFFSET + i));+})();++function formatMonthLabel(monthIndex: string) {+ return new Date(2024, Number(monthIndex), 1).toLocaleDateString(undefined, { month: 'long' });+}++export function CalendarMonthYearHeader() {+ const context = Calendar.useContext<'single'>();++ return (+ <div class="flex items-center justify-between">+ <CalendarNav action="prev-month">+ <div class="i-tabler-chevron-left size-4" />+ </CalendarNav>++ <div class="flex items-center">+ <Select+ value={String(context.month().getMonth())}+ onChange={value => value != null && context.setMonth(new Date(context.month().getFullYear(), Number(value), 1))}+ options={monthOptions}+ itemComponent={itemProps => (+ <SelectItem item={itemProps.item}>+ {formatMonthLabel(itemProps.item.rawValue)}+ </SelectItem>+ )}+ >+ <SelectTrigger class="border-none hover:bg-accent shadow-none text-sm font-medium gap-0" caretIcon={null}>+ <SelectValue<string>>{state => formatMonthLabel(state.selectedOption())}</SelectValue>+ </SelectTrigger>+ <SelectContent />+ </Select>++ <Select+ value={String(context.month().getFullYear())}+ onChange={value => value != null && context.setMonth(new Date(Number(value), context.month().getMonth(), 1))}+ options={yearOptions}+ itemComponent={itemProps => (+ <SelectItem item={itemProps.item}>+ {itemProps.item.rawValue}+ </SelectItem>+ )}+ >+ <SelectTrigger class="border-none hover:bg-accent shadow-none text-sm font-medium gap-0" caretIcon={null}>+ <SelectValue<string>>{state => state.selectedOption()}</SelectValue>+ </SelectTrigger>+ <SelectContent />+ </Select>+ </div>++ <CalendarNav action="next-month">+ <div class="i-tabler-chevron-right size-4" />+ </CalendarNav>+ </div>+ );+}diff --git a/apps/papra-client/src/modules/ui/components/number-field.tsx b/apps/papra-client/src/modules/ui/components/number-field.tsxindex c0abd57c..54ed6e01 100644--- a/apps/papra-client/src/modules/ui/components/number-field.tsx+++ b/apps/papra-client/src/modules/ui/components/number-field.tsx@@ -98,7 +98,7 @@ export function NumberFieldInput<T extends ValidComponent = 'input'>(props: Polyreturn (<NumberFieldPrimitive.Inputclass={cn(- 'flex h-9 w-full rounded-md border border-input bg-transparent px-10 py-1 text-sm text-center shadow-sm placeholder:text-muted-foreground disabled:(cursor-not-allowed opacity-50) focus-visible:outline-none',+ 'flex h-9 w-full rounded-md border border-input bg-transparent pl-3 pr-16 py-1 text-sm shadow-sm placeholder:text-muted-foreground disabled:(cursor-not-allowed opacity-50) focus-visible:outline-none',local.class,)}{...rest}@@ -114,7 +114,7 @@ export function NumberFieldDecrementTrigger<T extends ValidComponent = 'button',return (<NumberFieldPrimitive.DecrementTriggerclass={cn(- 'absolute top-1/2 -translate-y-1/2 left-0 p-3 disabled:(cursor-not-allowed opacity-20)',+ 'absolute top-1/2 -translate-y-1/2 right-8 p-3 pr-1.5 disabled:(cursor-not-allowed opacity-20) hover:color-primary',local.class,)}{...rest}@@ -146,7 +146,7 @@ export function NumberFieldIncrementTrigger<T extends ValidComponent = 'button',return (<NumberFieldPrimitive.IncrementTriggerclass={cn(- 'absolute top-1/2 -translate-y-1/2 right-0 disabled:(cursor-not-allowed opacity-20) p-3',+ 'absolute top-1/2 -translate-y-1/2 right-0 disabled:(cursor-not-allowed opacity-20) p-3 pl-1.5 hover:color-primary',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 710e7c0a..ba234838 100644--- a/apps/papra-client/src/modules/ui/layouts/organization.layout.tsx+++ b/apps/papra-client/src/modules/ui/layouts/organization.layout.tsx@@ -89,6 +89,11 @@ const OrganizationLayoutSideNav: Component = () => {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',diff --git a/apps/papra-client/src/routes.tsx b/apps/papra-client/src/routes.tsxindex 66fcba3e..acd8444d 100644--- a/apps/papra-client/src/routes.tsx+++ b/apps/papra-client/src/routes.tsx@@ -13,6 +13,9 @@ import { LoginPage } from './modules/auth/pages/login.page';import { RegisterPage } from './modules/auth/pages/register.page';import { RequestPasswordResetPage } from './modules/auth/pages/request-password-reset.page';import { ResetPasswordPage } from './modules/auth/pages/reset-password.page';+import { CreateCustomPropertyPage } from './modules/custom-properties/pages/create-custom-property.page';+import { CustomPropertiesPage } from './modules/custom-properties/pages/custom-properties-list.page';+import { UpdateCustomPropertyPage } from './modules/custom-properties/pages/update-custom-property.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';@@ -143,6 +146,18 @@ export const routes: RouteDefinition[] = [path: '/tags',component: TagsPage,},+ {+ path: '/custom-properties',+ component: CustomPropertiesPage,+ },+ {+ path: '/custom-properties/create',+ component: CreateCustomPropertyPage,+ },+ {+ path: '/custom-properties/:propertyDefinitionId',+ component: UpdateCustomPropertyPage,+ },{path: '/tagging-rules',component: TaggingRulesPage,diff --git a/apps/papra-server/src/migrations/list/0018-custom-properties.migration.ts b/apps/papra-server/src/migrations/list/0018-custom-properties.migration.tsnew file mode 100644index 00000000..92f75444--- /dev/null+++ b/apps/papra-server/src/migrations/list/0018-custom-properties.migration.ts@@ -0,0 +1,117 @@+import type { Migration } from '../migrations.types';+import { sql } from 'drizzle-orm';++export const customPropertiesMigration = {+ name: 'custom-properties',++ up: async ({ db }) => {+ await db.batch([+ db.run(sql`+ CREATE TABLE IF NOT EXISTS "custom_property_definitions" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "organization_id" text NOT NULL REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ "name" text NOT NULL,+ "key" text NOT NULL,+ "description" text,+ "type" text NOT NULL,+ "config" text,+ "display_order" integer NOT NULL DEFAULT 0+ )+ `),++ db.run(sql`+ CREATE UNIQUE INDEX IF NOT EXISTS "custom_property_definitions_organization_id_key_unique"+ ON "custom_property_definitions" ("organization_id", "key")+ `),++ db.run(sql`+ CREATE UNIQUE INDEX IF NOT EXISTS "custom_property_definitions_organization_id_name_unique"+ ON "custom_property_definitions" ("organization_id", "name")+ `),++ db.run(sql`+ CREATE TABLE IF NOT EXISTS "custom_property_select_options" (+ "id" text PRIMARY KEY NOT NULL,+ "created_at" integer NOT NULL,+ "updated_at" integer NOT NULL,+ "property_definition_id" text NOT NULL REFERENCES "custom_property_definitions"("id") ON DELETE CASCADE ON UPDATE CASCADE,+ "name" text NOT NULL,+ "key" text NOT NULL,+ "display_order" integer NOT NULL DEFAULT 0+ )+ `),++ db.run(sql`+ CREATE UNIQUE INDEX IF NOT EXISTS "custom_property_select_options_definition_id_key_unique"+ ON "custom_property_select_options" ("property_definition_id", "key")+ `),++ db.run(sql`+ CREATE UNIQUE INDEX IF NOT EXISTS "custom_property_select_options_definition_id_name_unique"+ ON "custom_property_select_options" ("property_definition_id", "name")+ `),++ db.run(sql`+ CREATE TABLE IF NOT EXISTS "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+ )+ `),++ db.run(sql`+ CREATE INDEX IF NOT EXISTS "document_custom_property_values_document_id_index"+ ON "document_custom_property_values" ("document_id", "property_definition_id")+ `),++ db.run(sql`+ CREATE INDEX IF NOT EXISTS "document_custom_property_values_definition_text_index"+ ON "document_custom_property_values" ("property_definition_id", "text_value")+ `),++ db.run(sql`+ CREATE INDEX IF NOT EXISTS "document_custom_property_values_definition_number_index"+ ON "document_custom_property_values" ("property_definition_id", "number_value")+ `),++ db.run(sql`+ CREATE INDEX IF NOT EXISTS "document_custom_property_values_definition_date_index"+ ON "document_custom_property_values" ("property_definition_id", "date_value")+ `),++ db.run(sql`+ CREATE INDEX IF NOT EXISTS "document_custom_property_values_definition_boolean_index"+ ON "document_custom_property_values" ("property_definition_id", "boolean_value")+ `),++ db.run(sql`+ CREATE INDEX IF NOT EXISTS "document_custom_property_values_definition_user_id_index"+ ON "document_custom_property_values" ("property_definition_id", "user_id")+ `),++ db.run(sql`+ CREATE INDEX IF NOT EXISTS "document_custom_property_values_definition_related_document_id_index"+ ON "document_custom_property_values" ("property_definition_id", "related_document_id")+ `),+ ]);+ },++ down: async ({ db }) => {+ await db.batch([+ db.run(sql`DROP TABLE IF EXISTS "document_custom_property_values"`),+ db.run(sql`DROP TABLE IF EXISTS "custom_property_select_options"`),+ db.run(sql`DROP TABLE IF EXISTS "custom_property_definitions"`),+ ]);+ },+} satisfies Migration;diff --git a/apps/papra-server/src/migrations/migrations.registry.test.ts b/apps/papra-server/src/migrations/migrations.registry.test.tsindex 797296a8..6744ad0c 100644--- a/apps/papra-server/src/migrations/migrations.registry.test.ts+++ b/apps/papra-server/src/migrations/migrations.registry.test.ts@@ -72,6 +72,17 @@ describe('migrations registry', () => {"CREATE UNIQUE INDEX "api_keys_key_hash_unique" ON "api_keys" ("key_hash");CREATE INDEX "auth_sessions_token_index" ON "auth_sessions" ("token");CREATE INDEX "auth_verifications_identifier_index" ON "auth_verifications" ("identifier");+ CREATE UNIQUE INDEX "custom_property_definitions_organization_id_key_unique" ON "custom_property_definitions" ("organization_id", "key");+ CREATE UNIQUE INDEX "custom_property_definitions_organization_id_name_unique" ON "custom_property_definitions" ("organization_id", "name");+ CREATE UNIQUE INDEX "custom_property_select_options_definition_id_key_unique" ON "custom_property_select_options" ("property_definition_id", "key");+ CREATE UNIQUE INDEX "custom_property_select_options_definition_id_name_unique" ON "custom_property_select_options" ("property_definition_id", "name");+ CREATE INDEX "document_custom_property_values_definition_boolean_index" ON "document_custom_property_values" ("property_definition_id", "boolean_value");+ CREATE INDEX "document_custom_property_values_definition_date_index" ON "document_custom_property_values" ("property_definition_id", "date_value");+ CREATE INDEX "document_custom_property_values_definition_number_index" ON "document_custom_property_values" ("property_definition_id", "number_value");+ CREATE INDEX "document_custom_property_values_definition_related_document_id_index" ON "document_custom_property_values" ("property_definition_id", "related_document_id");+ CREATE INDEX "document_custom_property_values_definition_text_index" ON "document_custom_property_values" ("property_definition_id", "text_value");+ CREATE INDEX "document_custom_property_values_definition_user_id_index" ON "document_custom_property_values" ("property_definition_id", "user_id");+ CREATE INDEX "document_custom_property_values_document_id_index" ON "document_custom_property_values" ("document_id", "property_definition_id");CREATE INDEX documents_file_encryption_kek_version_index ON documents (file_encryption_kek_version);CREATE INDEX documents_organization_id_document_date_index ON documents(organization_id, document_date);CREATE INDEX "documents_organization_id_is_deleted_created_at_index" ON "documents" ("organization_id","is_deleted","created_at");@@ -99,7 +110,10 @@ describe('migrations registry', () => {CREATE TABLE "auth_sessions" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "token" text NOT NULL, "user_id" text, "expires_at" integer NOT NULL, "ip_address" text, "user_agent" text, "active_organization_id" text, FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE cascade, FOREIGN KEY ("active_organization_id") REFERENCES "organizations"("id") ON UPDATE cascade ON DELETE set null );CREATE TABLE "auth_two_factor" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "user_id" text, "secret" text, "backup_codes" text, FOREIGN KEY ("user_id") REFERENCES "users"("id") ON UPDATE cascade ON DELETE cascade );CREATE TABLE "auth_verifications" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "identifier" text NOT NULL, "value" text NOT NULL, "expires_at" integer NOT NULL );+ CREATE TABLE "custom_property_definitions" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "organization_id" text NOT NULL REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE, "name" text NOT NULL, "key" text NOT NULL, "description" text, "type" text NOT NULL, "config" text, "display_order" integer NOT NULL DEFAULT 0 );+ CREATE TABLE "custom_property_select_options" ( "id" text PRIMARY KEY NOT NULL, "created_at" integer NOT NULL, "updated_at" integer NOT NULL, "property_definition_id" text NOT NULL REFERENCES "custom_property_definitions"("id") ON DELETE CASCADE ON UPDATE CASCADE, "name" text NOT NULL, "key" text NOT NULL, "display_order" integer NOT NULL DEFAULT 0 );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 "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, 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.tsindex 700c5209..8368a150 100644--- a/apps/papra-server/src/migrations/migrations.registry.ts+++ b/apps/papra-server/src/migrations/migrations.registry.ts@@ -17,6 +17,7 @@ import { twoFactorAuthenticationMigration } from './list/0014-two-factor-authentimport { indexDocumentsFtsIdsMigration } from './list/0015-index-documents-fts-ids.migration';import { caseInsensitiveTagNameUniqConstraintMigration } from './list/0016-case-insensitive-tag-name-uniq-constraint.migration';import { documentsDateMigration } from './list/0017-documents-date.migration';+import { customPropertiesMigration } from './list/0018-custom-properties.migration';export const migrations: Migration[] = [initialSchemaSetupMigration,@@ -36,4 +37,5 @@ export const migrations: Migration[] = [indexDocumentsFtsIdsMigration,caseInsensitiveTagNameUniqConstraintMigration,documentsDateMigration,+ customPropertiesMigration,];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 d51a5ccd..7998a490 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@@ -3,6 +3,8 @@ import { createNoopLogger } from '@crowlog/logger';import { sql } from 'drizzle-orm';import { runMigrations } from '../../../migrations/migrations.usecases';import { apiKeyOrganizationsTable, apiKeysTable } from '../../api-keys/api-keys.tables';+import { customPropertyDefinitionsTable, documentCustomPropertyValuesTable } from '../../custom-properties/custom-properties.table';+import { customPropertySelectOptionsTable } from '../../custom-properties/options/custom-properties-options.table';import { documentsTable } from '../../documents/documents.table';import { intakeEmailsTable } from '../../intake-emails/intake-emails.tables';import { organizationInvitationsTable, organizationMembersTable, organizationsTable } from '../../organizations/organizations.table';@@ -51,6 +53,9 @@ const seedTables = {webhookDeliveries: webhookDeliveriesTable,organizationInvitations: organizationInvitationsTable,userRoles: userRolesTable,+ customPropertyDefinitions: customPropertyDefinitionsTable,+ customPropertySelectOptions: customPropertySelectOptionsTable,+ documentCustomPropertyValues: documentCustomPropertyValuesTable,} as const;type SeedTablesRows = {diff --git a/apps/papra-server/src/modules/app/server.routes.test.ts b/apps/papra-server/src/modules/app/server.routes.test.tsindex 34098bae..99c7b8e7 100644--- a/apps/papra-server/src/modules/app/server.routes.test.ts+++ b/apps/papra-server/src/modules/app/server.routes.test.ts@@ -16,7 +16,9 @@ function setValidParams(path: string) {.replaceAll(':apiKeyId', 'api_key_777777777777777777777777').replaceAll(':webhookId', 'wbh_888888888888888888888888').replaceAll(':memberId', 'org_mem_999999999999999999999999')- .replaceAll(':invitationId', 'inv_101010101010101010101010');+ .replaceAll(':invitationId', 'inv_101010101010101010101010')+ .replaceAll(':propertyDefinitionId', 'cpd_111111111111111111111111')+ .replaceAll(':optionId', 'cpso_222222222222222222222222');// throw if there are any remaining paramsif (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.tsindex 81d21ce7..e831cc13 100644--- a/apps/papra-server/src/modules/app/server.routes.ts+++ b/apps/papra-server/src/modules/app/server.routes.ts@@ -2,6 +2,7 @@ import type { RouteDefinitionContext } from './server.types';import { registerAdminRoutes } from '../admin/admin.routes';import { registerApiKeysRoutes } from '../api-keys/api-keys.routes';import { registerConfigRoutes } from '../config/config.routes';+import { registerCustomPropertiesRoutes } from '../custom-properties/custom-properties.routes';import { registerDocumentActivityRoutes } from '../documents/document-activity/document-activity.routes';import { registerDocumentsRoutes } from '../documents/documents.routes';import { registerIntakeEmailsRoutes } from '../intake-emails/intake-emails.routes';@@ -30,5 +31,6 @@ export function registerRoutes(context: RouteDefinitionContext) {registerWebhooksRoutes(context);registerInvitationsRoutes(context);registerDocumentActivityRoutes(context);+ registerCustomPropertiesRoutes(context);registerAdminRoutes(context);}diff --git a/apps/papra-server/src/modules/config/config.ts b/apps/papra-server/src/modules/config/config.tsindex 0045787c..d066ceda 100644--- a/apps/papra-server/src/modules/config/config.ts+++ b/apps/papra-server/src/modules/config/config.ts@@ -7,6 +7,7 @@ import { z } from 'zod';import { authConfig } from '../app/auth/auth.config';import { ensureAuthSecretIsNotDefaultInProduction } from '../app/auth/auth.config.models';import { databaseConfig } from '../app/database/database.config';+import { customPropertiesConfig } from '../custom-properties/custom-properties.config';import { documentSearchConfig } from '../documents/document-search/document-search.config';import { documentsConfig } from '../documents/documents.config';import { documentStorageConfig } from '../documents/storage/document-storage.config';@@ -159,6 +160,7 @@ export const configDefinition = {organizationPlans: organizationPlansConfig,subscriptions: subscriptionsConfig,tags: tagsConfig,+ customProperties: customPropertiesConfig,tracking: trackingConfig,} as const satisfies AppConfigDefinition;diff --git a/apps/papra-server/src/modules/custom-properties/custom-properties.config.ts b/apps/papra-server/src/modules/custom-properties/custom-properties.config.tsnew file mode 100644index 00000000..51955412--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/custom-properties.config.ts@@ -0,0 +1,11 @@+import type { ConfigDefinition } from 'figue';+import { z } from 'zod';++export const customPropertiesConfig = {+ maxCustomPropertiesPerOrganization: {+ doc: 'The maximum number of custom property definitions an organization can have',+ schema: z.coerce.number().int().positive(),+ default: 100,+ env: 'MAX_CUSTOM_PROPERTIES_PER_ORGANIZATION',+ },+} as const satisfies ConfigDefinition;diff --git a/apps/papra-server/src/modules/custom-properties/custom-properties.constants.ts b/apps/papra-server/src/modules/custom-properties/custom-properties.constants.tsnew file mode 100644index 00000000..5a1bf18e--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/custom-properties.constants.ts@@ -0,0 +1,22 @@+import { createPrefixedIdRegex } from '../shared/random/ids';++export const CUSTOM_PROPERTY_DEFINITION_ID_PREFIX = 'cpd';+export const CUSTOM_PROPERTY_DEFINITION_ID_REGEX = createPrefixedIdRegex({ prefix: CUSTOM_PROPERTY_DEFINITION_ID_PREFIX });++export const DOCUMENT_CUSTOM_PROPERTY_VALUE_ID_PREFIX = 'dcpv';+export const DOCUMENT_CUSTOM_PROPERTY_VALUE_ID_REGEX = createPrefixedIdRegex({ prefix: DOCUMENT_CUSTOM_PROPERTY_VALUE_ID_PREFIX });++export const CUSTOM_PROPERTY_TYPES = {+ TEXT: 'text',+ NUMBER: 'number',+ DATE: 'date',+ BOOLEAN: 'boolean',+ SELECT: 'select',+ MULTI_SELECT: 'multi_select',+ USER_RELATION: 'user_relation',+ DOCUMENT_RELATION: 'document_relation',+} as const;++export const CUSTOM_PROPERTY_TYPES_LIST = Object.values(CUSTOM_PROPERTY_TYPES);++export type CustomPropertyType = typeof CUSTOM_PROPERTY_TYPES[keyof typeof CUSTOM_PROPERTY_TYPES];diff --git a/apps/papra-server/src/modules/custom-properties/custom-properties.errors.ts b/apps/papra-server/src/modules/custom-properties/custom-properties.errors.tsnew file mode 100644index 00000000..814c0696--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/custom-properties.errors.ts@@ -0,0 +1,49 @@+import { createErrorFactory } from '../shared/errors/errors';++export const createCustomPropertyDefinitionNotFoundError = createErrorFactory({+ message: 'Custom property definition not found.',+ code: 'custom_property_definition.not_found',+ statusCode: 404,+});++export const createCustomPropertyDefinitionAlreadyExistsError = createErrorFactory({+ message: 'A custom property definition with this name or key already exists in this organization.',+ code: 'custom_property_definition.already_exists',+ statusCode: 409,+});++export const createCustomPropertyValueInvalidError = createErrorFactory({+ message: 'The provided value is invalid for this property type.',+ code: 'custom_property_value.invalid',+ statusCode: 400,+});++export const createCustomPropertyTypeChangeNotAllowedError = createErrorFactory({+ message: 'Changing the type of a custom property definition is not allowed.',+ code: 'custom_property_definition.type_change_not_allowed',+ statusCode: 400,+});++export const createCustomPropertyDefinitionInvalidUpdateError = createErrorFactory({+ message: 'The provided update data is invalid for this property type.',+ code: 'custom_property_definition.invalid_update',+ statusCode: 400,+});++export const createOrganizationCustomPropertyLimitReachedError = createErrorFactory({+ message: 'The maximum number of custom properties for this organization has been reached.',+ code: 'custom_property_definition.organization_limit_reached',+ statusCode: 403,+});++export const createCustomPropertyUserNotFoundError = createErrorFactory({+ message: 'One or more provided user IDs are not members of this organization.',+ code: 'custom_property_value.user_not_found',+ statusCode: 400,+});++export const createCustomPropertyRelatedDocumentNotFoundError = createErrorFactory({+ message: 'One or more provided document IDs do not belong to this organization.',+ code: 'custom_property_value.related_document_not_found',+ statusCode: 400,+});diff --git a/apps/papra-server/src/modules/custom-properties/custom-properties.models.test.ts b/apps/papra-server/src/modules/custom-properties/custom-properties.models.test.tsnew file mode 100644index 00000000..024f86ea--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/custom-properties.models.test.ts@@ -0,0 +1,148 @@+import { describe, expect, test } from 'vitest';+import { aggregateDocumentCustomPropertyValues, buildCustomPropertiesArray } from './custom-properties.models';++const baseValue = { userId: null, relatedDocumentId: null } as const;+const baseRow = { relatedUser: null, relatedDocument: null } as const;++describe('custom-properties models', () => {+ describe('aggregateDocumentCustomPropertyValues', () => {+ test('aggregates scalar property values', () => {+ const result = aggregateDocumentCustomPropertyValues({+ rawValues: [+ {+ value: { id: 'v1', propertyDefinitionId: 'cpd_a', textValue: 'hello', numberValue: null, dateValue: null, booleanValue: null, selectOptionId: null, ...baseValue },+ definition: { id: 'cpd_a', name: 'Name', key: 'name', type: 'text' },+ option: null,+ ...baseRow,+ },+ {+ value: { id: 'v2', propertyDefinitionId: 'cpd_b', textValue: null, numberValue: 42, dateValue: null, booleanValue: null, selectOptionId: null, ...baseValue },+ definition: { id: 'cpd_b', name: 'Amount', key: 'amount', type: 'number' },+ option: null,+ ...baseRow,+ },+ ],+ });++ expect(result).to.eql([+ { propertyDefinitionId: 'cpd_a', key: 'name', name: 'Name', type: 'text', value: 'hello' },+ { propertyDefinitionId: 'cpd_b', key: 'amount', name: 'Amount', type: 'number', value: 42 },+ ]);+ });++ test('aggregates select property values', () => {+ const result = aggregateDocumentCustomPropertyValues({+ rawValues: [+ {+ value: { id: 'v1', propertyDefinitionId: 'cpd_a', textValue: null, numberValue: null, dateValue: null, booleanValue: null, selectOptionId: 'cpso_x', ...baseValue },+ definition: { id: 'cpd_a', name: 'Category', key: 'category', type: 'select' },+ option: { id: 'cpso_x', name: 'Finance' },+ ...baseRow,+ },+ ],+ });++ expect(result).to.eql([+ { propertyDefinitionId: 'cpd_a', key: 'category', name: 'Category', type: 'select', value: { optionId: 'cpso_x', name: 'Finance' } },+ ]);+ });++ test('aggregates multi-select property values into arrays', () => {+ const result = aggregateDocumentCustomPropertyValues({+ rawValues: [+ {+ value: { id: 'v1', propertyDefinitionId: 'cpd_a', textValue: null, numberValue: null, dateValue: null, booleanValue: null, selectOptionId: 'cpso_1', ...baseValue },+ definition: { id: 'cpd_a', name: 'Labels', key: 'labels', type: 'multi_select' },+ option: { id: 'cpso_1', name: 'Urgent' },+ ...baseRow,+ },+ {+ value: { id: 'v2', propertyDefinitionId: 'cpd_a', textValue: null, numberValue: null, dateValue: null, booleanValue: null, selectOptionId: 'cpso_2', ...baseValue },+ definition: { id: 'cpd_a', name: 'Labels', key: 'labels', type: 'multi_select' },+ option: { id: 'cpso_2', name: 'Review' },+ ...baseRow,+ },+ ],+ });++ expect(result).to.eql([+ {+ propertyDefinitionId: 'cpd_a',+ key: 'labels',+ name: 'Labels',+ type: 'multi_select',+ value: [+ { optionId: 'cpso_1', name: 'Urgent' },+ { optionId: 'cpso_2', name: 'Review' },+ ],+ },+ ]);+ });++ test('returns an empty array for no values', () => {+ expect(aggregateDocumentCustomPropertyValues({ rawValues: [] })).to.eql([]);+ });+ });++ describe('buildCustomPropertiesArray', () => {+ const def = (key: string, name: string, type: string, displayOrder: number) => ({ key, name, type, displayOrder });++ test('returns an array with definition info and values', () => {+ const result = buildCustomPropertiesArray({+ propertyDefinitions: [def('name', 'Name', 'text', 0), def('amount', 'Amount', 'number', 1)],+ rawValues: [+ {+ value: { id: 'v1', propertyDefinitionId: 'cpd_a', textValue: 'hello', numberValue: null, dateValue: null, booleanValue: null, selectOptionId: null, ...baseValue },+ definition: { id: 'cpd_a', name: 'Name', key: 'name', type: 'text' },+ option: null,+ ...baseRow,+ },+ {+ value: { id: 'v2', propertyDefinitionId: 'cpd_b', textValue: null, numberValue: 42, dateValue: null, booleanValue: null, selectOptionId: null, ...baseValue },+ definition: { id: 'cpd_b', name: 'Amount', key: 'amount', type: 'number' },+ option: null,+ ...baseRow,+ },+ ],+ });++ expect(result).to.eql([+ { key: 'name', name: 'Name', type: 'text', displayOrder: 0, value: 'hello' },+ { key: 'amount', name: 'Amount', type: 'number', displayOrder: 1, value: 42 },+ ]);+ });++ test('includes null value for definitions with no value set', () => {+ const result = buildCustomPropertiesArray({+ propertyDefinitions: [def('name', 'Name', 'text', 0), def('amount', 'Amount', 'number', 1)],+ rawValues: [+ {+ value: { id: 'v1', propertyDefinitionId: 'cpd_a', textValue: 'hello', numberValue: null, dateValue: null, booleanValue: null, selectOptionId: null, ...baseValue },+ definition: { id: 'cpd_a', name: 'Name', key: 'name', type: 'text' },+ option: null,+ ...baseRow,+ },+ ],+ });++ expect(result).to.eql([+ { key: 'name', name: 'Name', type: 'text', displayOrder: 0, value: 'hello' },+ { key: 'amount', name: 'Amount', type: 'number', displayOrder: 1, value: null },+ ]);+ });++ test('returns all nulls when no values are set', () => {+ expect(buildCustomPropertiesArray({+ propertyDefinitions: [def('name', 'Name', 'text', 0), def('amount', 'Amount', 'number', 1)],+ rawValues: [],+ })).to.eql([+ { key: 'name', name: 'Name', type: 'text', displayOrder: 0, value: null },+ { key: 'amount', name: 'Amount', type: 'number', displayOrder: 1, value: null },+ ]);+ });++ test('returns an empty array when there are no definitions', () => {+ expect(buildCustomPropertiesArray({ propertyDefinitions: [], rawValues: [] })).to.eql([]);+ });+ });+});diff --git a/apps/papra-server/src/modules/custom-properties/custom-properties.models.ts b/apps/papra-server/src/modules/custom-properties/custom-properties.models.tsnew file mode 100644index 00000000..adc628c8--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/custom-properties.models.ts@@ -0,0 +1,51 @@+import type { DocumentCustomPropertyValueWithRelatedInfo } from './definitions/custom-property-definition.models';+import { getCustomPropertyTypeDefinition } from './definitions/custom-property-definition.registry';++export function aggregateDocumentCustomPropertyValues({ rawValues }: { rawValues: DocumentCustomPropertyValueWithRelatedInfo[] }) {+ const groupedRows = new Map<string, { definition: DocumentCustomPropertyValueWithRelatedInfo['definition']; rows: DocumentCustomPropertyValueWithRelatedInfo[] }>();++ for (const row of rawValues) {+ const existing = groupedRows.get(row.definition.id);++ if (existing) {+ existing.rows.push(row);+ } else {+ groupedRows.set(row.definition.id, { definition: row.definition, rows: [row] });+ }+ }++ return [...groupedRows.values()].map(({ definition, rows }) => {+ const customPropertyTypeDefinition = getCustomPropertyTypeDefinition({ type: definition.type });++ const value = customPropertyTypeDefinition.value.fromDb({ rows });++ return {+ propertyDefinitionId: definition.id,+ key: definition.key,+ name: definition.name,+ type: definition.type,+ value,+ };+ });+}++export type DocumentCustomPropertyForApi = {+ key: string;+ name: string;+ type: string;+ displayOrder: number;+ value: unknown;+};++export function buildCustomPropertiesArray({ rawValues, propertyDefinitions }: { rawValues: DocumentCustomPropertyValueWithRelatedInfo[]; propertyDefinitions: { key: string; name: string; type: string; displayOrder: number }[] }): DocumentCustomPropertyForApi[] {+ const aggregated = aggregateDocumentCustomPropertyValues({ rawValues });+ const valuesByKey = Object.fromEntries(aggregated.map(({ key, value }) => [key, value]));++ return propertyDefinitions.map(def => ({+ key: def.key,+ name: def.name,+ type: def.type,+ displayOrder: def.displayOrder,+ value: valuesByKey[def.key] ?? null,+ }));+}diff --git a/apps/papra-server/src/modules/custom-properties/custom-properties.repository.models.test.ts b/apps/papra-server/src/modules/custom-properties/custom-properties.repository.models.test.tsnew file mode 100644index 00000000..002f5cb7--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/custom-properties.repository.models.test.ts@@ -0,0 +1,38 @@+import { describe, expect, test } from 'vitest';+import { generatePropertyKey } from './custom-properties.repository.models';++describe('custom-properties repository models', () => {+ describe('generatePropertyKey', () => {+ test('a key is generated from the name', () => {+ expect(generatePropertyKey({ name: 'Invoice Number' })).toBe('invoicenumber');+ });++ test('diacritics are preserved', () => {+ expect(generatePropertyKey({ name: 'Catégorie du Document' })).toBe('catégoriedudocument');+ expect(generatePropertyKey({ name: 'Führerschein' })).toBe('führerschein');+ });++ test('cjk characters are preserved', () => {+ expect(generatePropertyKey({ name: '发票编号' })).toBe('发票编号');+ expect(generatePropertyKey({ name: '請求書番号' })).toBe('請求書番号');+ expect(generatePropertyKey({ name: '인보이스 번호' })).toBe('인보이스번호');+ });++ test('mixed scripts are preserved', () => {+ expect(generatePropertyKey({ name: 'Invoice 发票' })).toBe('invoice发票');+ });++ test('special characters are stripped', () => {+ expect(generatePropertyKey({ name: 'Invoice #123 (test)' })).toBe('invoice123test');+ });++ test('uppercase letters are converted to lowercase', () => {+ expect(generatePropertyKey({ name: 'InvoiceNumber' })).toBe('invoicenumber');+ });++ test('whitespace is stripped', () => {+ expect(generatePropertyKey({ name: ' Hello World ' })).toBe('helloworld');+ expect(generatePropertyKey({ name: 'Hello \t\nWorld' })).toBe('helloworld');+ });+ });+});diff --git a/apps/papra-server/src/modules/custom-properties/custom-properties.repository.models.ts b/apps/papra-server/src/modules/custom-properties/custom-properties.repository.models.tsnew file mode 100644index 00000000..8be43bf7--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/custom-properties.repository.models.ts@@ -0,0 +1,5 @@+export function generatePropertyKey({ name }: { name: string }): string {+ return name+ .replace(/[^\p{L}\p{N}]/gu, '')+ .toLowerCase();+}diff --git a/apps/papra-server/src/modules/custom-properties/custom-properties.repository.test.ts b/apps/papra-server/src/modules/custom-properties/custom-properties.repository.test.tsnew file mode 100644index 00000000..575c117a--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/custom-properties.repository.test.ts@@ -0,0 +1,147 @@+import { describe, expect, test } from 'vitest';+import { createInMemoryDatabase } from '../app/database/database.test-utils';+import { CUSTOM_PROPERTY_TYPES } from './custom-properties.constants';+import { createCustomPropertyDefinitionAlreadyExistsError } from './custom-properties.errors';+import { createCustomPropertiesRepository } from './custom-properties.repository';++describe('custom-properties repository', () => {+ describe('property definitions', () => {+ test('can create and retrieve a property definition', async () => {+ const orgId = 'org_111111111111111111111111';+ const docId = 'doc_111111111111111111111111';++ const { db } = await createInMemoryDatabase({+ organizations: [{ id: orgId, name: 'Test Org' }],+ documents: [{ id: docId, organizationId: orgId, name: 'test.pdf', originalName: 'test.pdf', mimeType: 'application/pdf', originalSha256Hash: 'abc', originalSize: 100, originalStorageKey: 'key' }],+ });++ const repository = createCustomPropertiesRepository({ db });++ const { propertyDefinition: created } = await repository.createPropertyDefinition({+ definition: { organizationId: orgId, name: 'Invoice Number', type: CUSTOM_PROPERTY_TYPES.TEXT },+ });++ expect(created).to.include({ name: 'Invoice Number', type: 'text', organizationId: orgId });++ const { propertyDefinitions } = await repository.getOrganizationPropertyDefinitions({ organizationId: orgId });+ expect(propertyDefinitions).to.have.length(1);+ expect(propertyDefinitions[0]).to.include({ name: 'Invoice Number' });+ expect(propertyDefinitions[0]?.options).to.eql([]);+ });++ test('can get a single property definition by ID', async () => {+ const orgId = 'org_111111111111111111111111';+ const docId = 'doc_111111111111111111111111';++ const { db } = await createInMemoryDatabase({+ organizations: [{ id: orgId, name: 'Test Org' }],+ documents: [{ id: docId, organizationId: orgId, name: 'test.pdf', originalName: 'test.pdf', mimeType: 'application/pdf', originalSha256Hash: 'abc', originalSize: 100, originalStorageKey: 'key' }],+ });++ const repository = createCustomPropertiesRepository({ db });++ const { propertyDefinition: created } = await repository.createPropertyDefinition({+ definition: { organizationId: orgId, name: 'Amount', type: CUSTOM_PROPERTY_TYPES.NUMBER },+ });++ const { definition } = await repository.getPropertyDefinitionById({ propertyDefinitionId: created.id, organizationId: orgId });+ expect(definition).to.include({ name: 'Amount', type: 'number' });+ });++ test('returns undefined for non-existent definition', async () => {+ const orgId = 'org_111111111111111111111111';+ const docId = 'doc_111111111111111111111111';++ const { db } = await createInMemoryDatabase({+ organizations: [{ id: orgId, name: 'Test Org' }],+ documents: [{ id: docId, organizationId: orgId, name: 'test.pdf', originalName: 'test.pdf', mimeType: 'application/pdf', originalSha256Hash: 'abc', originalSize: 100, originalStorageKey: 'key' }],+ });++ const repository = createCustomPropertiesRepository({ db });++ const { definition } = await repository.getPropertyDefinitionById({ propertyDefinitionId: 'cpd_nonexistent000000000000', organizationId: orgId });+ expect(definition).to.eql(undefined);+ });++ test('can count property definitions', async () => {+ const orgId = 'org_111111111111111111111111';+ const docId = 'doc_111111111111111111111111';++ const { db } = await createInMemoryDatabase({+ organizations: [{ id: orgId, name: 'Test Org' }],+ documents: [{ id: docId, organizationId: orgId, name: 'test.pdf', originalName: 'test.pdf', mimeType: 'application/pdf', originalSha256Hash: 'abc', originalSize: 100, originalStorageKey: 'key' }],+ });++ const repository = createCustomPropertiesRepository({ db });++ await repository.createPropertyDefinition({ definition: { organizationId: orgId, name: 'A', type: CUSTOM_PROPERTY_TYPES.TEXT } });+ await repository.createPropertyDefinition({ definition: { organizationId: orgId, name: 'B', type: CUSTOM_PROPERTY_TYPES.NUMBER } });++ const { count } = await repository.getOrganizationPropertyDefinitionsCount({ organizationId: orgId });+ expect(count).to.eql(2);+ });++ test('can update a property definition', async () => {+ const orgId = 'org_111111111111111111111111';+ const docId = 'doc_111111111111111111111111';++ const { db } = await createInMemoryDatabase({+ organizations: [{ id: orgId, name: 'Test Org' }],+ documents: [{ id: docId, organizationId: orgId, name: 'test.pdf', originalName: 'test.pdf', mimeType: 'application/pdf', originalSha256Hash: 'abc', originalSize: 100, originalStorageKey: 'key' }],+ });++ const repository = createCustomPropertiesRepository({ db });++ const { propertyDefinition: created } = await repository.createPropertyDefinition({+ definition: { organizationId: orgId, name: 'Old Name', type: CUSTOM_PROPERTY_TYPES.TEXT },+ });++ const { propertyDefinition: updated } = await repository.updatePropertyDefinition({+ propertyDefinitionId: created.id,+ organizationId: orgId,+ name: 'New Name',+ });++ expect(updated).to.include({ name: 'New Name' });+ });++ test('can delete a property definition', async () => {+ const orgId = 'org_111111111111111111111111';+ const docId = 'doc_111111111111111111111111';++ const { db } = await createInMemoryDatabase({+ organizations: [{ id: orgId, name: 'Test Org' }],+ documents: [{ id: docId, organizationId: orgId, name: 'test.pdf', originalName: 'test.pdf', mimeType: 'application/pdf', originalSha256Hash: 'abc', originalSize: 100, originalStorageKey: 'key' }],+ });++ const repository = createCustomPropertiesRepository({ db });++ const { propertyDefinition: created } = await repository.createPropertyDefinition({+ definition: { organizationId: orgId, name: 'To Delete', type: CUSTOM_PROPERTY_TYPES.TEXT },+ });++ await repository.deletePropertyDefinition({ propertyDefinitionId: created.id, organizationId: orgId });++ const { propertyDefinitions } = await repository.getOrganizationPropertyDefinitions({ organizationId: orgId });+ expect(propertyDefinitions).to.have.length(0);+ });++ test('throws on duplicate name within organization', async () => {+ const orgId = 'org_111111111111111111111111';+ const docId = 'doc_111111111111111111111111';++ const { db } = await createInMemoryDatabase({+ organizations: [{ id: orgId, name: 'Test Org' }],+ documents: [{ id: docId, organizationId: orgId, name: 'test.pdf', originalName: 'test.pdf', mimeType: 'application/pdf', originalSha256Hash: 'abc', originalSize: 100, originalStorageKey: 'key' }],+ });++ const repository = createCustomPropertiesRepository({ db });++ await repository.createPropertyDefinition({ definition: { organizationId: orgId, name: 'Unique', type: CUSTOM_PROPERTY_TYPES.TEXT } });++ await expect(+ repository.createPropertyDefinition({ definition: { organizationId: orgId, name: 'Unique', type: CUSTOM_PROPERTY_TYPES.NUMBER } }),+ ).rejects.toThrow(createCustomPropertyDefinitionAlreadyExistsError());+ });+ });+});diff --git a/apps/papra-server/src/modules/custom-properties/custom-properties.repository.ts b/apps/papra-server/src/modules/custom-properties/custom-properties.repository.tsnew file mode 100644index 00000000..438cbee7--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/custom-properties.repository.ts@@ -0,0 +1,366 @@+import type { Database } from '../app/database/database.types';+import type { CustomPropertyType } from './custom-properties.constants';+import { injectArguments, safely } from '@corentinth/chisels';+import { and, asc, count, eq, inArray } from 'drizzle-orm';+import { alias } from 'drizzle-orm/sqlite-core';+import { documentsTable } from '../documents/documents.table';+import { isUniqueConstraintError } from '../shared/db/constraints.models';+import { createError } from '../shared/errors/errors';+import { isDefined, isNil, omitUndefined } from '../shared/utils';+import { usersTable } from '../users/users.table';+import { createCustomPropertyDefinitionAlreadyExistsError } from './custom-properties.errors';+import { generatePropertyKey } from './custom-properties.repository.models';+import { customPropertyDefinitionsTable, documentCustomPropertyValuesTable } from './custom-properties.table';+import { customPropertySelectOptionsTable } from './options/custom-properties-options.table';++export type CustomPropertiesRepository = ReturnType<typeof createCustomPropertiesRepository>;++export function createCustomPropertiesRepository({ db }: { db: Database }) {+ return injectArguments(+ {+ getOrganizationPropertyDefinitions,+ getOrganizationPropertyDefinitionsCount,+ getPropertyDefinitionById,+ createPropertyDefinition,+ updatePropertyDefinition,+ deletePropertyDefinition,++ getDocumentCustomPropertyValues,+ getCustomPropertyValuesByDocumentIds,+ setDocumentCustomPropertyValue,+ deleteDocumentCustomPropertyValue,+ },+ { db },+ );+}++async function getOrganizationPropertyDefinitions({ organizationId, db }: { organizationId: string; db: Database }) {+ const definitions = await db+ .select()+ .from(customPropertyDefinitionsTable)+ .where(eq(customPropertyDefinitionsTable.organizationId, organizationId))+ .orderBy(asc(customPropertyDefinitionsTable.displayOrder), asc(customPropertyDefinitionsTable.createdAt));++ const definitionIds = definitions.map(d => d.id);++ const options = definitionIds.length > 0+ ? await db+ .select()+ .from(customPropertySelectOptionsTable)+ .where(inArray(customPropertySelectOptionsTable.propertyDefinitionId, definitionIds))+ .orderBy(asc(customPropertySelectOptionsTable.displayOrder))+ : [];++ const optionsByDefinition = new Map<string, typeof options>();++ for (const option of options) {+ const existing = optionsByDefinition.get(option.propertyDefinitionId) ?? [];+ existing.push(option);+ optionsByDefinition.set(option.propertyDefinitionId, existing);+ }++ return {+ propertyDefinitions: definitions.map(definition => ({+ ...definition,+ options: optionsByDefinition.get(definition.id) ?? [],+ })),+ };+}++async function getOrganizationPropertyDefinitionsCount({ organizationId, db }: { organizationId: string; db: Database }) {+ const [result] = await db+ .select({ count: count() })+ .from(customPropertyDefinitionsTable)+ .where(eq(customPropertyDefinitionsTable.organizationId, organizationId));++ return { count: result?.count ?? 0 };+}++async function getPropertyDefinitionById({ propertyDefinitionId, organizationId, db }: { propertyDefinitionId: string; organizationId: string; db: Database }) {+ const [definition] = await db+ .select()+ .from(customPropertyDefinitionsTable)+ .where(+ and(+ eq(customPropertyDefinitionsTable.id, propertyDefinitionId),+ eq(customPropertyDefinitionsTable.organizationId, organizationId),+ ),+ );++ if (!definition) {+ return { definition: undefined };+ }++ const options = await db+ .select()+ .from(customPropertySelectOptionsTable)+ .where(eq(customPropertySelectOptionsTable.propertyDefinitionId, propertyDefinitionId))+ .orderBy(asc(customPropertySelectOptionsTable.displayOrder));++ return {+ definition: {+ ...definition,+ options,+ },+ };+}++async function createPropertyDefinition({ definition, db }: {+ definition: {+ organizationId: string;+ name: string;+ description?: string | null;+ type: CustomPropertyType;+ displayOrder?: number;+ };+ db: Database;+}) {+ const [result, error] = await safely(+ db+ .insert(customPropertyDefinitionsTable)+ .values({+ organizationId: definition.organizationId,+ name: definition.name,+ key: generatePropertyKey({ name: definition.name }),+ description: definition.description,+ type: definition.type,+ displayOrder: definition.displayOrder,+ })+ .returning(),+ );++ if (isUniqueConstraintError({ error })) {+ throw createCustomPropertyDefinitionAlreadyExistsError();+ }++ if (error) {+ throw error;+ }++ const [created] = result;++ if (isNil(created)) {+ throw createError({+ message: 'Failed to create custom property definition',+ code: 'create_custom_property_definition_failed',+ statusCode: 500,+ isInternal: true,+ });+ }++ return { propertyDefinition: created };+}++async function updatePropertyDefinition({+ propertyDefinitionId,+ organizationId,+ name,+ description,+ displayOrder,+ db,+}: {+ propertyDefinitionId: string;+ organizationId: string;+ name?: string;+ description?: string | null;+ displayOrder?: number;+ db: Database;+}) {+ const [result, error] = await safely(+ db+ .update(customPropertyDefinitionsTable)+ .set(omitUndefined({+ name,+ key: isDefined(name) ? generatePropertyKey({ name }) : undefined,+ description,+ displayOrder,+ }))+ .where(+ and(+ eq(customPropertyDefinitionsTable.id, propertyDefinitionId),+ eq(customPropertyDefinitionsTable.organizationId, organizationId),+ ),+ )+ .returning(),+ );++ if (isUniqueConstraintError({ error })) {+ throw createCustomPropertyDefinitionAlreadyExistsError();+ }++ if (error) {+ throw error;+ }++ const [propertyDefinition] = result;++ if (isNil(propertyDefinition)) {+ throw createError({+ message: 'Failed to update custom property definition',+ code: 'update_custom_property_definition_failed',+ statusCode: 500,+ isInternal: true,+ });+ }++ return { propertyDefinition };+}++async function deletePropertyDefinition({ propertyDefinitionId, organizationId, db }: { propertyDefinitionId: string; organizationId: string; db: Database }) {+ await db+ .delete(customPropertyDefinitionsTable)+ .where(+ and(+ eq(customPropertyDefinitionsTable.id, propertyDefinitionId),+ eq(customPropertyDefinitionsTable.organizationId, organizationId),+ ),+ );+}++async function getDocumentCustomPropertyValues({ documentId, db }: { documentId: string; db: Database }) {+ const relatedDocAlias = alias(documentsTable, 'related_doc');++ const values = await db+ .select({+ value: {+ id: documentCustomPropertyValuesTable.id,+ propertyDefinitionId: documentCustomPropertyValuesTable.propertyDefinitionId,+ textValue: documentCustomPropertyValuesTable.textValue,+ numberValue: documentCustomPropertyValuesTable.numberValue,+ dateValue: documentCustomPropertyValuesTable.dateValue,+ booleanValue: documentCustomPropertyValuesTable.booleanValue,+ selectOptionId: documentCustomPropertyValuesTable.selectOptionId,+ userId: documentCustomPropertyValuesTable.userId,+ relatedDocumentId: documentCustomPropertyValuesTable.relatedDocumentId,+ },+ definition: {+ id: customPropertyDefinitionsTable.id,+ name: customPropertyDefinitionsTable.name,+ key: customPropertyDefinitionsTable.key,+ type: customPropertyDefinitionsTable.type,+ },+ option: {+ id: customPropertySelectOptionsTable.id,+ name: customPropertySelectOptionsTable.name,+ },+ relatedUser: {+ id: usersTable.id,+ name: usersTable.name,+ email: usersTable.email,+ },+ relatedDocument: {+ id: relatedDocAlias.id,+ name: relatedDocAlias.name,+ },+ })+ .from(documentCustomPropertyValuesTable)+ .innerJoin(customPropertyDefinitionsTable, eq(documentCustomPropertyValuesTable.propertyDefinitionId, customPropertyDefinitionsTable.id))+ .leftJoin(customPropertySelectOptionsTable, eq(documentCustomPropertyValuesTable.selectOptionId, customPropertySelectOptionsTable.id))+ .leftJoin(usersTable, eq(documentCustomPropertyValuesTable.userId, usersTable.id))+ .leftJoin(relatedDocAlias, eq(documentCustomPropertyValuesTable.relatedDocumentId, relatedDocAlias.id))+ .where(eq(documentCustomPropertyValuesTable.documentId, documentId));++ return { values };+}++async function getCustomPropertyValuesByDocumentIds({ documentIds, db }: { documentIds: string[]; db: Database }) {+ if (documentIds.length === 0) {+ return { valuesByDocumentId: {} as Record<string, { value: { id: string; propertyDefinitionId: string; textValue: string | null; numberValue: number | null; dateValue: Date | null; booleanValue: boolean | null; selectOptionId: string | null; userId: string | null; relatedDocumentId: string | null }; definition: { id: string; name: string; key: string; type: string }; option: { id: string; name: string } | null; relatedUser: { id: string; name: string | null; email: string } | null; relatedDocument: { id: string; name: string } | null }[]> };+ }++ const relatedDocAlias = alias(documentsTable, 'related_doc');++ const rows = await db+ .select({+ documentId: documentCustomPropertyValuesTable.documentId,+ value: {+ id: documentCustomPropertyValuesTable.id,+ propertyDefinitionId: documentCustomPropertyValuesTable.propertyDefinitionId,+ textValue: documentCustomPropertyValuesTable.textValue,+ numberValue: documentCustomPropertyValuesTable.numberValue,+ dateValue: documentCustomPropertyValuesTable.dateValue,+ booleanValue: documentCustomPropertyValuesTable.booleanValue,+ selectOptionId: documentCustomPropertyValuesTable.selectOptionId,+ userId: documentCustomPropertyValuesTable.userId,+ relatedDocumentId: documentCustomPropertyValuesTable.relatedDocumentId,+ },+ definition: {+ id: customPropertyDefinitionsTable.id,+ name: customPropertyDefinitionsTable.name,+ key: customPropertyDefinitionsTable.key,+ type: customPropertyDefinitionsTable.type,+ },+ option: {+ id: customPropertySelectOptionsTable.id,+ name: customPropertySelectOptionsTable.name,+ },+ relatedUser: {+ id: usersTable.id,+ name: usersTable.name,+ email: usersTable.email,+ },+ relatedDocument: {+ id: relatedDocAlias.id,+ name: relatedDocAlias.name,+ },+ })+ .from(documentCustomPropertyValuesTable)+ .innerJoin(customPropertyDefinitionsTable, eq(documentCustomPropertyValuesTable.propertyDefinitionId, customPropertyDefinitionsTable.id))+ .leftJoin(customPropertySelectOptionsTable, eq(documentCustomPropertyValuesTable.selectOptionId, customPropertySelectOptionsTable.id))+ .leftJoin(usersTable, eq(documentCustomPropertyValuesTable.userId, usersTable.id))+ .leftJoin(relatedDocAlias, eq(documentCustomPropertyValuesTable.relatedDocumentId, relatedDocAlias.id))+ .where(inArray(documentCustomPropertyValuesTable.documentId, documentIds));++ const valuesByDocumentId: Record<string, { value: typeof rows[0]['value']; definition: typeof rows[0]['definition']; option: typeof rows[0]['option']; relatedUser: typeof rows[0]['relatedUser']; relatedDocument: typeof rows[0]['relatedDocument'] }[]> = {};++ for (const { documentId, ...rest } of rows) {+ (valuesByDocumentId[documentId] ??= []).push(rest);+ }++ return { valuesByDocumentId };+}++async function setDocumentCustomPropertyValue({ documentId, propertyDefinitionId, values, db }: {+ documentId: string;+ propertyDefinitionId: string;+ values: {+ textValue?: string | null;+ numberValue?: number | null;+ dateValue?: Date | null;+ booleanValue?: boolean | null;+ selectOptionId?: string | null;+ userId?: string | null;+ relatedDocumentId?: string | null;+ }[];+ db: Database;+}) {+ await db+ .delete(documentCustomPropertyValuesTable)+ .where(+ and(+ eq(documentCustomPropertyValuesTable.documentId, documentId),+ eq(documentCustomPropertyValuesTable.propertyDefinitionId, propertyDefinitionId),+ ),+ );++ if (values.length > 0) {+ await db+ .insert(documentCustomPropertyValuesTable)+ .values(values.map(v => ({+ documentId,+ propertyDefinitionId,+ ...v,+ })));+ }+}++async function deleteDocumentCustomPropertyValue({ documentId, propertyDefinitionId, db }: { documentId: string; propertyDefinitionId: string; db: Database }) {+ await db+ .delete(documentCustomPropertyValuesTable)+ .where(+ and(+ eq(documentCustomPropertyValuesTable.documentId, documentId),+ eq(documentCustomPropertyValuesTable.propertyDefinitionId, propertyDefinitionId),+ ),+ );+}diff --git a/apps/papra-server/src/modules/custom-properties/custom-properties.routes.ts b/apps/papra-server/src/modules/custom-properties/custom-properties.routes.tsnew file mode 100644index 00000000..9b6a4947--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/custom-properties.routes.ts@@ -0,0 +1,289 @@+import type { RouteDefinitionContext } from '../app/server.types';+import { z } from 'zod';+import { API_KEY_PERMISSIONS } from '../api-keys/api-keys.constants';+import { requireAuthentication } from '../app/auth/auth.middleware';+import { getUser } from '../app/auth/auth.models';+import { createDocumentNotFoundError } from '../documents/documents.errors';+import { createDocumentsRepository } from '../documents/documents.repository';+import { documentIdSchema } 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 { aggregateDocumentCustomPropertyValues } from './custom-properties.models';+import { createCustomPropertiesRepository } from './custom-properties.repository';+import { customPropertyDefinitionIdSchema } from './custom-properties.schemas';+import { createPropertyDefinition, deleteDocumentCustomPropertyValue, deletePropertyDefinition, ensurePropertyDefinitionExists, setDocumentCustomPropertyValue, updatePropertyDefinition } from './custom-properties.usecases';+import { createPropertyDefinitionBodySchema } from './definitions/custom-property-definition.registry';+import { createCustomPropertiesOptionsRepository } from './options/custom-properties-options.repository';++export function registerCustomPropertiesRoutes(context: RouteDefinitionContext) {+ setupCreatePropertyDefinitionRoute(context);+ setupGetOrganizationPropertyDefinitionsRoute(context);+ setupGetPropertyDefinitionRoute(context);+ setupUpdatePropertyDefinitionRoute(context);+ setupDeletePropertyDefinitionRoute(context);++ setupSetDocumentCustomPropertyValueRoute(context);+ setupDeleteDocumentCustomPropertyValueRoute(context);+ setupGetDocumentCustomPropertyValuesRoute(context);+}++function setupCreatePropertyDefinitionRoute({ app, db, config }: RouteDefinitionContext) {+ app.post(+ '/api/organizations/:organizationId/custom-properties',+ requireAuthentication(),+ validateParams(z.object({+ organizationId: organizationIdSchema,+ })),+ validateJsonBody(createPropertyDefinitionBodySchema),+ async (context) => {+ const { userId } = getUser({ context });+ const { organizationId } = context.req.valid('param');+ const definition = context.req.valid('json');++ const customPropertiesRepository = createCustomPropertiesRepository({ db });+ const organizationsRepository = createOrganizationsRepository({ db });+ const customPropertiesOptionsRepository = createCustomPropertiesOptionsRepository({ db });++ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });++ const { propertyDefinition } = await createPropertyDefinition({+ organizationId,+ definition,+ config,+ customPropertiesRepository,+ customPropertiesOptionsRepository,+ });++ return context.json({ propertyDefinition });+ },+ );+}++function setupGetOrganizationPropertyDefinitionsRoute({ app, db }: RouteDefinitionContext) {+ app.get(+ '/api/organizations/:organizationId/custom-properties',+ requireAuthentication(),+ validateParams(z.object({+ organizationId: organizationIdSchema,+ })),+ async (context) => {+ const { userId } = getUser({ context });+ const { organizationId } = context.req.valid('param');++ const customPropertiesRepository = createCustomPropertiesRepository({ db });+ const organizationsRepository = createOrganizationsRepository({ db });++ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });++ const { propertyDefinitions } = await customPropertiesRepository.getOrganizationPropertyDefinitions({ organizationId });++ return context.json({ propertyDefinitions });+ },+ );+}++function setupGetPropertyDefinitionRoute({ app, db }: RouteDefinitionContext) {+ app.get(+ '/api/organizations/:organizationId/custom-properties/:propertyDefinitionId',+ requireAuthentication(),+ validateParams(z.object({+ organizationId: organizationIdSchema,+ propertyDefinitionId: customPropertyDefinitionIdSchema,+ })),+ async (context) => {+ const { userId } = getUser({ context });+ const { organizationId, propertyDefinitionId } = context.req.valid('param');++ const customPropertiesRepository = createCustomPropertiesRepository({ db });+ const organizationsRepository = createOrganizationsRepository({ db });++ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });++ const { definition } = await ensurePropertyDefinitionExists({+ propertyDefinitionId,+ organizationId,+ customPropertiesRepository,+ });++ return context.json({ definition });+ },+ );+}++function setupUpdatePropertyDefinitionRoute({ app, db }: RouteDefinitionContext) {+ app.put(+ '/api/organizations/:organizationId/custom-properties/:propertyDefinitionId',+ requireAuthentication(),+ validateParams(z.object({+ organizationId: organizationIdSchema,+ propertyDefinitionId: customPropertyDefinitionIdSchema,+ })),+ async (context) => {+ const { userId } = getUser({ context });+ const { organizationId, propertyDefinitionId } = context.req.valid('param');+ const rawBody: unknown = await context.req.json();++ const customPropertiesRepository = createCustomPropertiesRepository({ db });+ const organizationsRepository = createOrganizationsRepository({ db });+ const customPropertiesOptionsRepository = createCustomPropertiesOptionsRepository({ db });++ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });++ const { propertyDefinition } = await updatePropertyDefinition({+ propertyDefinitionId,+ organizationId,+ rawDefinition: rawBody,+ customPropertiesRepository,+ customPropertiesOptionsRepository,+ });++ return context.json({ propertyDefinition });+ },+ );+}++function setupDeletePropertyDefinitionRoute({ app, db }: RouteDefinitionContext) {+ app.delete(+ '/api/organizations/:organizationId/custom-properties/:propertyDefinitionId',+ requireAuthentication(),+ validateParams(z.object({+ organizationId: organizationIdSchema,+ propertyDefinitionId: customPropertyDefinitionIdSchema,+ })),+ async (context) => {+ const { userId } = getUser({ context });+ const { organizationId, propertyDefinitionId } = context.req.valid('param');++ const customPropertiesRepository = createCustomPropertiesRepository({ db });+ const organizationsRepository = createOrganizationsRepository({ db });++ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });++ await deletePropertyDefinition({+ propertyDefinitionId,+ organizationId,+ customPropertiesRepository,+ });++ return context.json({});+ },+ );+}++function setupSetDocumentCustomPropertyValueRoute({ app, db }: RouteDefinitionContext) {+ app.put(+ '/api/organizations/:organizationId/documents/:documentId/custom-properties/:propertyDefinitionId',+ requireAuthentication({ apiKeyPermissions: [API_KEY_PERMISSIONS.DOCUMENTS.UPDATE] }),+ validateParams(z.object({+ organizationId: organizationIdSchema,+ documentId: documentIdSchema,+ propertyDefinitionId: customPropertyDefinitionIdSchema,+ })),+ validateJsonBody(z.object({+ value: z.unknown(), // validation happens per-type in the use case+ })),+ async (context) => {+ const { userId } = getUser({ context });+ const { organizationId, documentId, propertyDefinitionId } = context.req.valid('param');+ const { value } = context.req.valid('json');++ const customPropertiesRepository = createCustomPropertiesRepository({ db });+ const organizationsRepository = createOrganizationsRepository({ db });+ const documentsRepository = createDocumentsRepository({ db });+ const customPropertiesOptionsRepository = createCustomPropertiesOptionsRepository({ db });++ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });++ const { document } = await documentsRepository.getDocumentById({ documentId, organizationId });++ if (!document) {+ throw createDocumentNotFoundError();+ }++ await setDocumentCustomPropertyValue({+ documentId,+ propertyDefinitionId,+ organizationId,+ value,+ customPropertiesRepository,+ customPropertiesOptionsRepository,+ organizationsRepository,+ documentsRepository,+ });++ return context.body(null, 204);+ },+ );+}++function setupDeleteDocumentCustomPropertyValueRoute({ app, db }: RouteDefinitionContext) {+ app.delete(+ '/api/organizations/:organizationId/documents/:documentId/custom-properties/:propertyDefinitionId',+ requireAuthentication({ apiKeyPermissions: [API_KEY_PERMISSIONS.DOCUMENTS.UPDATE] }),+ validateParams(z.object({+ organizationId: organizationIdSchema,+ documentId: documentIdSchema,+ propertyDefinitionId: customPropertyDefinitionIdSchema,+ })),+ async (context) => {+ const { userId } = getUser({ context });+ const { organizationId, documentId, propertyDefinitionId } = context.req.valid('param');++ const customPropertiesRepository = createCustomPropertiesRepository({ db });+ const organizationsRepository = createOrganizationsRepository({ db });+ const documentsRepository = createDocumentsRepository({ db });++ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });++ const { document } = await documentsRepository.getDocumentById({ documentId, organizationId });++ if (!document) {+ throw createDocumentNotFoundError();+ }++ await deleteDocumentCustomPropertyValue({+ documentId,+ propertyDefinitionId,+ organizationId,+ customPropertiesRepository,+ });++ return context.body(null, 204);+ },+ );+}++function setupGetDocumentCustomPropertyValuesRoute({ app, db }: RouteDefinitionContext) {+ app.get(+ '/api/organizations/:organizationId/documents/:documentId/custom-properties',+ requireAuthentication({ apiKeyPermissions: [API_KEY_PERMISSIONS.DOCUMENTS.READ] }),+ validateParams(z.object({+ organizationId: organizationIdSchema,+ documentId: documentIdSchema,+ })),+ async (context) => {+ const { userId } = getUser({ context });+ const { organizationId, documentId } = context.req.valid('param');++ const customPropertiesRepository = createCustomPropertiesRepository({ db });+ const organizationsRepository = createOrganizationsRepository({ db });+ const documentsRepository = createDocumentsRepository({ db });++ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });++ const { document } = await documentsRepository.getDocumentById({ documentId, organizationId });++ if (!document) {+ throw createDocumentNotFoundError();+ }++ const { values } = await customPropertiesRepository.getDocumentCustomPropertyValues({ documentId });++ const customProperties = aggregateDocumentCustomPropertyValues({ rawValues: values });++ return context.json({ customProperties });+ },+ );+}diff --git a/apps/papra-server/src/modules/custom-properties/custom-properties.schemas.ts b/apps/papra-server/src/modules/custom-properties/custom-properties.schemas.tsnew file mode 100644index 00000000..4f3ecf12--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/custom-properties.schemas.ts@@ -0,0 +1,5 @@+import { z } from 'zod';+import { CUSTOM_PROPERTY_DEFINITION_ID_REGEX, CUSTOM_PROPERTY_TYPES_LIST } from './custom-properties.constants';++export const customPropertyDefinitionIdSchema = z.string().regex(CUSTOM_PROPERTY_DEFINITION_ID_REGEX);+export const customPropertyTypeSchema = z.enum(CUSTOM_PROPERTY_TYPES_LIST as [string, ...string[]]);diff --git a/apps/papra-server/src/modules/custom-properties/custom-properties.table.test.ts b/apps/papra-server/src/modules/custom-properties/custom-properties.table.test.tsnew file mode 100644index 00000000..be98e166--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/custom-properties.table.test.ts@@ -0,0 +1,77 @@+import { safely } from '@corentinth/chisels';+import { describe, expect, test } from 'vitest';+import { createInMemoryDatabase } from '../app/database/database.test-utils';+import { isUniqueConstraintError } from '../shared/db/constraints.models';+import { customPropertyDefinitionsTable } from './custom-properties.table';++describe('custom properties table', () => {+ describe('custom property definitions table', () => {+ test('in a same organization, two definitions cannot have the same name', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [+ { id: 'org_111111111111111111111111', name: 'Test Org' },+ { id: 'org_222222222222222222222222', name: 'Other Org' },+ ],+ });++ await db.insert(customPropertyDefinitionsTable).values({+ organizationId: 'org_111111111111111111111111',+ name: 'Definition 1',+ key: 'definition-1',+ type: 'text',+ });++ const [value, error] = await safely(db.insert(customPropertyDefinitionsTable).values({+ organizationId: 'org_111111111111111111111111',+ name: 'Definition 1',+ key: 'other-key',+ type: 'text',+ }));++ expect(value).to.eql(null);+ expect(isUniqueConstraintError({ error })).to.eql(true);++ // But we can have the same definition name in another organization+ await db.insert(customPropertyDefinitionsTable).values({+ organizationId: 'org_222222222222222222222222',+ name: 'Definition 1',+ key: 'definition-1',+ type: 'text',+ });+ });++ test('in a same organization, two definitions cannot have the same key', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [+ { id: 'org_111111111111111111111111', name: 'Test Org' },+ { id: 'org_222222222222222222222222', name: 'Other Org' },+ ],+ });++ await db.insert(customPropertyDefinitionsTable).values({+ organizationId: 'org_111111111111111111111111',+ name: 'Definition 1',+ key: 'definition-1',+ type: 'text',+ });++ const [value, error] = await safely(db.insert(customPropertyDefinitionsTable).values({+ organizationId: 'org_111111111111111111111111',+ name: 'Other Name',+ key: 'definition-1',+ type: 'text',+ }));++ expect(value).to.eql(null);+ expect(isUniqueConstraintError({ error })).to.eql(true);++ // But we can have the same definition key in another organization+ await db.insert(customPropertyDefinitionsTable).values({+ organizationId: 'org_222222222222222222222222',+ name: 'Definition 1',+ key: 'definition-1',+ type: 'text',+ });+ });+ });+});diff --git a/apps/papra-server/src/modules/custom-properties/custom-properties.table.ts b/apps/papra-server/src/modules/custom-properties/custom-properties.table.tsnew file mode 100644index 00000000..a9dc4ef5--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/custom-properties.table.ts@@ -0,0 +1,48 @@+import type { NonEmptyArray } from '../shared/types';+import type { CustomPropertyType } from './custom-properties.constants';+import { integer, real, sqliteTable, text } from 'drizzle-orm/sqlite-core';+import { documentsTable } from '../documents/documents.table';+import { organizationsTable } from '../organizations/organizations.table';+import { createPrimaryKeyField, createTimestampColumns } from '../shared/db/columns.helpers';+import { usersTable } from '../users/users.table';+import {+ CUSTOM_PROPERTY_DEFINITION_ID_PREFIX,+ CUSTOM_PROPERTY_TYPES_LIST,+ DOCUMENT_CUSTOM_PROPERTY_VALUE_ID_PREFIX,+} from './custom-properties.constants';+import { customPropertySelectOptionsTable } from './options/custom-properties-options.table';++export const customPropertyDefinitionsTable = sqliteTable(+ 'custom_property_definitions',+ {+ ...createPrimaryKeyField({ prefix: CUSTOM_PROPERTY_DEFINITION_ID_PREFIX }),+ ...createTimestampColumns(),++ organizationId: text('organization_id').notNull().references(() => organizationsTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),+ name: text('name').notNull(),+ key: text('key').notNull(),+ description: text('description'),+ type: text('type', { enum: CUSTOM_PROPERTY_TYPES_LIST as NonEmptyArray<CustomPropertyType> }).notNull(),+ config: text('config', { mode: 'json' }).$type<Record<string, unknown>>(),+ displayOrder: integer('display_order').notNull().default(0),+ },+);++export const documentCustomPropertyValuesTable = sqliteTable(+ 'document_custom_property_values',+ {+ ...createPrimaryKeyField({ prefix: DOCUMENT_CUSTOM_PROPERTY_VALUE_ID_PREFIX }),+ ...createTimestampColumns(),++ documentId: text('document_id').notNull().references(() => documentsTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),+ propertyDefinitionId: text('property_definition_id').notNull().references(() => customPropertyDefinitionsTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),++ textValue: text('text_value'),+ numberValue: real('number_value'),+ dateValue: integer('date_value', { mode: 'timestamp_ms' }),+ booleanValue: integer('boolean_value', { mode: 'boolean' }),+ selectOptionId: text('select_option_id').references(() => customPropertySelectOptionsTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),+ userId: text('user_id').references(() => usersTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),+ relatedDocumentId: text('related_document_id').references(() => documentsTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),+ },+);diff --git a/apps/papra-server/src/modules/custom-properties/custom-properties.types.ts b/apps/papra-server/src/modules/custom-properties/custom-properties.types.tsnew file mode 100644index 00000000..5e37f504--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/custom-properties.types.ts@@ -0,0 +1,12 @@+import type { Expand } from '@corentinth/chisels';+import type { customPropertyDefinitionsTable, documentCustomPropertyValuesTable } from './custom-properties.table';+import type { customPropertySelectOptionsTable } from './options/custom-properties-options.table';++export type CustomPropertyDefinition = Expand<typeof customPropertyDefinitionsTable.$inferSelect>;+export type DbInsertableCustomPropertyDefinition = Expand<typeof customPropertyDefinitionsTable.$inferInsert>;++export type CustomPropertySelectOption = Expand<typeof customPropertySelectOptionsTable.$inferSelect>;+export type DbInsertableCustomPropertySelectOption = Expand<typeof customPropertySelectOptionsTable.$inferInsert>;++export type DocumentCustomPropertyValue = Expand<typeof documentCustomPropertyValuesTable.$inferSelect>;+export type DbInsertableDocumentCustomPropertyValue = Expand<typeof documentCustomPropertyValuesTable.$inferInsert>;diff --git a/apps/papra-server/src/modules/custom-properties/custom-properties.usecases.test.ts b/apps/papra-server/src/modules/custom-properties/custom-properties.usecases.test.tsnew file mode 100644index 00000000..160350a8--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/custom-properties.usecases.test.ts@@ -0,0 +1,331 @@+import { describe, expect, test } from 'vitest';+import { createInMemoryDatabase } from '../app/database/database.test-utils';+import { overrideConfig } from '../config/config.test-utils';+import { createDocumentsRepository } from '../documents/documents.repository';+import { createOrganizationsRepository } from '../organizations/organizations.repository';+import { CUSTOM_PROPERTY_TYPES } from './custom-properties.constants';+import { createCustomPropertiesRepository } from './custom-properties.repository';+import { createPropertyDefinition, deleteDocumentCustomPropertyValue, deletePropertyDefinition, ensurePropertyDefinitionExists, setDocumentCustomPropertyValue, updatePropertyDefinition } from './custom-properties.usecases';+import { createCustomPropertiesOptionsRepository } from './options/custom-properties-options.repository';++describe('custom-properties usecases', () => {+ describe('createPropertyDefinition', () => {+ test('creates a property definition successfully', async () => {+ const orgId = 'org_111111111111111111111111';+ const docId = 'doc_111111111111111111111111';++ const { db } = await createInMemoryDatabase({+ organizations: [{ id: orgId, name: 'Test Org' }],+ documents: [{ id: docId, organizationId: orgId, name: 'test.pdf', originalName: 'test.pdf', mimeType: 'application/pdf', originalSha256Hash: 'abc', originalSize: 100, originalStorageKey: 'key' }],+ });++ const customPropertiesRepository = createCustomPropertiesRepository({ db });+ const customPropertiesOptionsRepository = createCustomPropertiesOptionsRepository({ db });++ const { propertyDefinition: definition } = await createPropertyDefinition({+ organizationId: orgId,+ definition: { name: 'Invoice Number', type: CUSTOM_PROPERTY_TYPES.TEXT },+ config: overrideConfig(),+ customPropertiesRepository,+ customPropertiesOptionsRepository,+ });++ expect(definition).to.include({ name: 'Invoice Number', type: 'text' });+ });++ test('enforces organization limit', async () => {+ const orgId = 'org_111111111111111111111111';+ const docId = 'doc_111111111111111111111111';++ const { db } = await createInMemoryDatabase({+ organizations: [{ id: orgId, name: 'Test Org' }],+ documents: [{ id: docId, organizationId: orgId, name: 'test.pdf', originalName: 'test.pdf', mimeType: 'application/pdf', originalSha256Hash: 'abc', originalSize: 100, originalStorageKey: 'key' }],+ });++ const customPropertiesRepository = createCustomPropertiesRepository({ db });+ const customPropertiesOptionsRepository = createCustomPropertiesOptionsRepository({ db });++ const config = overrideConfig({+ customProperties: {+ maxCustomPropertiesPerOrganization: 2,+ },+ });++ await createPropertyDefinition({+ organizationId: orgId,+ definition: { name: 'A', type: CUSTOM_PROPERTY_TYPES.TEXT },+ config,+ customPropertiesRepository,+ customPropertiesOptionsRepository,+ });+ await createPropertyDefinition({+ organizationId: orgId,+ definition: { name: 'B', type: CUSTOM_PROPERTY_TYPES.TEXT },+ config,+ customPropertiesRepository,+ customPropertiesOptionsRepository,+ });++ await expect(+ createPropertyDefinition({+ organizationId: orgId,+ definition: { name: 'C', type: CUSTOM_PROPERTY_TYPES.TEXT },+ config,+ customPropertiesRepository,+ customPropertiesOptionsRepository,+ }),+ ).rejects.toThrow('The maximum number of custom properties for this organization has been reached.');+ });+ });++ describe('updatePropertyDefinition', () => {+ test('updates a property definition', async () => {+ const orgId = 'org_111111111111111111111111';+ const docId = 'doc_111111111111111111111111';++ const { db } = await createInMemoryDatabase({+ organizations: [{ id: orgId, name: 'Test Org' }],+ documents: [{ id: docId, organizationId: orgId, name: 'test.pdf', originalName: 'test.pdf', mimeType: 'application/pdf', originalSha256Hash: 'abc', originalSize: 100, originalStorageKey: 'key' }],+ });++ const customPropertiesRepository = createCustomPropertiesRepository({ db });+ const customPropertiesOptionsRepository = createCustomPropertiesOptionsRepository({ db });++ const { propertyDefinition: created } = await createPropertyDefinition({+ organizationId: orgId,+ definition: { name: 'Old', type: CUSTOM_PROPERTY_TYPES.TEXT },+ config: overrideConfig(),+ customPropertiesRepository,+ customPropertiesOptionsRepository,+ });++ const { propertyDefinition: updated } = await updatePropertyDefinition({+ propertyDefinitionId: created.id,+ organizationId: orgId,+ rawDefinition: { name: 'New' },+ customPropertiesRepository,+ customPropertiesOptionsRepository,+ });++ expect(updated).to.include({ name: 'New' });+ });++ test('throws when definition does not exist', async () => {+ const orgId = 'org_111111111111111111111111';+ const docId = 'doc_111111111111111111111111';++ const { db } = await createInMemoryDatabase({+ organizations: [{ id: orgId, name: 'Test Org' }],+ documents: [{ id: docId, organizationId: orgId, name: 'test.pdf', originalName: 'test.pdf', mimeType: 'application/pdf', originalSha256Hash: 'abc', originalSize: 100, originalStorageKey: 'key' }],+ });++ const customPropertiesRepository = createCustomPropertiesRepository({ db });+ const customPropertiesOptionsRepository = createCustomPropertiesOptionsRepository({ db });++ await expect(+ updatePropertyDefinition({+ propertyDefinitionId: 'cpd_nonexistent000000000000',+ organizationId: orgId,+ rawDefinition: { name: 'New' },+ customPropertiesRepository,+ customPropertiesOptionsRepository,+ }),+ ).rejects.toThrow('Custom property definition not found.');+ });+ });++ describe('deletePropertyDefinition', () => {+ test('deletes a property definition', async () => {+ const orgId = 'org_111111111111111111111111';+ const docId = 'doc_111111111111111111111111';++ const { db } = await createInMemoryDatabase({+ organizations: [{ id: orgId, name: 'Test Org' }],+ documents: [{ id: docId, organizationId: orgId, name: 'test.pdf', originalName: 'test.pdf', mimeType: 'application/pdf', originalSha256Hash: 'abc', originalSize: 100, originalStorageKey: 'key' }],+ });++ const customPropertiesRepository = createCustomPropertiesRepository({ db });+ const customPropertiesOptionsRepository = createCustomPropertiesOptionsRepository({ db });++ const { propertyDefinition: created } = await createPropertyDefinition({+ organizationId: orgId,+ definition: { name: 'To Delete', type: CUSTOM_PROPERTY_TYPES.TEXT },+ config: overrideConfig(),+ customPropertiesRepository,+ customPropertiesOptionsRepository,+ });++ await deletePropertyDefinition({+ propertyDefinitionId: created.id,+ organizationId: orgId,+ customPropertiesRepository,+ });++ await expect(+ ensurePropertyDefinitionExists({+ propertyDefinitionId: created.id,+ organizationId: orgId,+ customPropertiesRepository,+ }),+ ).rejects.toThrow('Custom property definition not found.');+ });+ });++ describe('setDocumentCustomPropertyValue', () => {+ test('sets a text value on a document', async () => {+ const orgId = 'org_111111111111111111111111';+ const docId = 'doc_111111111111111111111111';++ const { db } = await createInMemoryDatabase({+ organizations: [{ id: orgId, name: 'Test Org' }],+ documents: [{ id: docId, organizationId: orgId, name: 'test.pdf', originalName: 'test.pdf', mimeType: 'application/pdf', originalSha256Hash: 'abc', originalSize: 100, originalStorageKey: 'key' }],+ });++ const customPropertiesRepository = createCustomPropertiesRepository({ db });+ const customPropertiesOptionsRepository = createCustomPropertiesOptionsRepository({ db });+ const organizationsRepository = createOrganizationsRepository({ db });+ const documentsRepository = createDocumentsRepository({ db });++ const { propertyDefinition: definition } = await createPropertyDefinition({+ organizationId: orgId,+ definition: { name: 'Note', type: CUSTOM_PROPERTY_TYPES.TEXT },+ config: overrideConfig(),+ customPropertiesRepository,+ customPropertiesOptionsRepository,+ });++ await setDocumentCustomPropertyValue({+ documentId: docId,+ propertyDefinitionId: definition.id,+ organizationId: orgId,+ value: 'Hello',+ customPropertiesRepository,+ customPropertiesOptionsRepository,+ organizationsRepository,+ documentsRepository,+ });++ const { values } = await customPropertiesRepository.getDocumentCustomPropertyValues({ documentId: docId });+ expect(values).to.have.length(1);+ expect(values[0]!.value.textValue).to.eql('Hello');+ });++ test('rejects invalid select option ID', async () => {+ const orgId = 'org_111111111111111111111111';+ const docId = 'doc_111111111111111111111111';++ const { db } = await createInMemoryDatabase({+ organizations: [{ id: orgId, name: 'Test Org' }],+ documents: [{ id: docId, organizationId: orgId, name: 'test.pdf', originalName: 'test.pdf', mimeType: 'application/pdf', originalSha256Hash: 'abc', originalSize: 100, originalStorageKey: 'key' }],+ });++ const customPropertiesRepository = createCustomPropertiesRepository({ db });+ const customPropertiesOptionsRepository = createCustomPropertiesOptionsRepository({ db });+ const organizationsRepository = createOrganizationsRepository({ db });+ const documentsRepository = createDocumentsRepository({ db });++ const { propertyDefinition: definition } = await createPropertyDefinition({+ organizationId: orgId,+ definition: { name: 'Category', type: CUSTOM_PROPERTY_TYPES.SELECT, options: [] },+ config: overrideConfig(),+ customPropertiesRepository,+ customPropertiesOptionsRepository,+ });++ await expect(+ setDocumentCustomPropertyValue({+ documentId: docId,+ propertyDefinitionId: definition.id,+ organizationId: orgId,+ value: 'cpso_aaaaaaaaaaaaaaaaaaaaaaaa',+ customPropertiesRepository,+ customPropertiesOptionsRepository,+ organizationsRepository,+ documentsRepository,+ }),+ ).rejects.toThrow('The provided value is not a valid option for this select property.');+ });++ test('rejects invalid value type', async () => {+ const orgId = 'org_111111111111111111111111';+ const docId = 'doc_111111111111111111111111';++ const { db } = await createInMemoryDatabase({+ organizations: [{ id: orgId, name: 'Test Org' }],+ documents: [{ id: docId, organizationId: orgId, name: 'test.pdf', originalName: 'test.pdf', mimeType: 'application/pdf', originalSha256Hash: 'abc', originalSize: 100, originalStorageKey: 'key' }],+ });++ const customPropertiesRepository = createCustomPropertiesRepository({ db });+ const customPropertiesOptionsRepository = createCustomPropertiesOptionsRepository({ db });+ const organizationsRepository = createOrganizationsRepository({ db });+ const documentsRepository = createDocumentsRepository({ db });++ const { propertyDefinition: definition } = await createPropertyDefinition({+ organizationId: orgId,+ definition: { name: 'Amount', type: CUSTOM_PROPERTY_TYPES.NUMBER },+ config: overrideConfig(),+ customPropertiesRepository,+ customPropertiesOptionsRepository,+ });++ await expect(+ setDocumentCustomPropertyValue({+ documentId: docId,+ propertyDefinitionId: definition.id,+ organizationId: orgId,+ value: 'not-a-number',+ customPropertiesRepository,+ customPropertiesOptionsRepository,+ organizationsRepository,+ documentsRepository,+ }),+ ).rejects.toThrow('The provided value is invalid for this property type.');+ });+ });++ describe('deleteDocumentCustomPropertyValue', () => {+ test('removes a value from a document', async () => {+ const orgId = 'org_111111111111111111111111';+ const docId = 'doc_111111111111111111111111';++ const { db } = await createInMemoryDatabase({+ organizations: [{ id: orgId, name: 'Test Org' }],+ documents: [{ id: docId, organizationId: orgId, name: 'test.pdf', originalName: 'test.pdf', mimeType: 'application/pdf', originalSha256Hash: 'abc', originalSize: 100, originalStorageKey: 'key' }],+ });++ const customPropertiesRepository = createCustomPropertiesRepository({ db });+ const customPropertiesOptionsRepository = createCustomPropertiesOptionsRepository({ db });+ const organizationsRepository = createOrganizationsRepository({ db });+ const documentsRepository = createDocumentsRepository({ db });++ const { propertyDefinition: definition } = await createPropertyDefinition({+ organizationId: orgId,+ definition: { name: 'Note', type: CUSTOM_PROPERTY_TYPES.TEXT },+ config: overrideConfig(),+ customPropertiesRepository,+ customPropertiesOptionsRepository,+ });++ await setDocumentCustomPropertyValue({+ documentId: docId,+ propertyDefinitionId: definition.id,+ organizationId: orgId,+ value: 'Hello',+ customPropertiesRepository,+ customPropertiesOptionsRepository,+ organizationsRepository,+ documentsRepository,+ });++ await deleteDocumentCustomPropertyValue({+ documentId: docId,+ propertyDefinitionId: definition.id,+ organizationId: orgId,+ customPropertiesRepository,+ });++ const { values } = await customPropertiesRepository.getDocumentCustomPropertyValues({ documentId: docId });+ expect(values).to.have.length(0);+ });+ });+});diff --git a/apps/papra-server/src/modules/custom-properties/custom-properties.usecases.ts b/apps/papra-server/src/modules/custom-properties/custom-properties.usecases.tsnew file mode 100644index 00000000..60e5f64b--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/custom-properties.usecases.ts@@ -0,0 +1,194 @@+import type { Config } from '../config/config.types';+import type { DocumentsRepository } from '../documents/documents.repository';+import type { OrganizationsRepository } from '../organizations/organizations.repository';+import type { CustomPropertiesRepository } from './custom-properties.repository';+import type { CreatePropertyDefinition } from './definitions/custom-property-definition.registry';+import type { CustomPropertiesOptionsRepository } from './options/custom-properties-options.repository';+import {+ createCustomPropertyDefinitionInvalidUpdateError,+ createCustomPropertyDefinitionNotFoundError,+ createCustomPropertyValueInvalidError,+ createOrganizationCustomPropertyLimitReachedError,+} from './custom-properties.errors';+import { getCustomPropertyTypeDefinition } from './definitions/custom-property-definition.registry';++export async function createPropertyDefinition({+ organizationId,+ definition,+ config,+ customPropertiesRepository,+ customPropertiesOptionsRepository,+}: {+ organizationId: string;+ definition: CreatePropertyDefinition;+ config: Config;+ customPropertiesRepository: CustomPropertiesRepository;+ customPropertiesOptionsRepository: CustomPropertiesOptionsRepository;+}) {+ const { count } = await customPropertiesRepository.getOrganizationPropertyDefinitionsCount({ organizationId });++ if (count >= config.customProperties.maxCustomPropertiesPerOrganization) {+ throw createOrganizationCustomPropertyLimitReachedError();+ }++ const { propertyDefinition } = await customPropertiesRepository.createPropertyDefinition({+ definition: {+ organizationId,+ name: definition.name,+ description: definition.description,+ displayOrder: definition.displayOrder,+ type: definition.type,+ },+ });++ const customPropertyTypeDefinition = getCustomPropertyTypeDefinition({ type: propertyDefinition.type });++ await customPropertyTypeDefinition.definition.onCreate?.({+ apiInput: definition,+ propertyDefinition,+ customPropertiesRepository,+ customPropertiesOptionsRepository,+ });++ return { propertyDefinition };+}++export async function updatePropertyDefinition({+ propertyDefinitionId,+ organizationId,+ rawDefinition,+ customPropertiesRepository,+ customPropertiesOptionsRepository,+}: {+ propertyDefinitionId: string;+ organizationId: string;+ rawDefinition: unknown;+ customPropertiesRepository: CustomPropertiesRepository;+ customPropertiesOptionsRepository: CustomPropertiesOptionsRepository;+}) {+ const { definition: existingDefinition } = await ensurePropertyDefinitionExists({ propertyDefinitionId, organizationId, customPropertiesRepository });++ const customPropertyTypeDefinition = getCustomPropertyTypeDefinition({ type: existingDefinition.type });++ const parseResult = customPropertyTypeDefinition.definition.updatePropertySchema.safeParse(rawDefinition);++ if (!parseResult.success) {+ throw createCustomPropertyDefinitionInvalidUpdateError();+ }++ const definition = parseResult.data;++ const { propertyDefinition } = await customPropertiesRepository.updatePropertyDefinition({+ propertyDefinitionId,+ organizationId,+ name: definition.name,+ description: definition.description,+ displayOrder: definition.displayOrder,+ });++ await customPropertyTypeDefinition.definition.onUpdate?.({+ apiInput: definition,+ propertyDefinition,+ customPropertiesRepository,+ customPropertiesOptionsRepository,+ });++ return { propertyDefinition };+}++export async function deletePropertyDefinition({+ propertyDefinitionId,+ organizationId,+ customPropertiesRepository,+}: {+ propertyDefinitionId: string;+ organizationId: string;+ customPropertiesRepository: CustomPropertiesRepository;+}) {+ await ensurePropertyDefinitionExists({ propertyDefinitionId, organizationId, customPropertiesRepository });++ await customPropertiesRepository.deletePropertyDefinition({ propertyDefinitionId, organizationId });+}++export async function setDocumentCustomPropertyValue({+ documentId,+ propertyDefinitionId,+ organizationId,+ value,+ customPropertiesRepository,+ customPropertiesOptionsRepository,+ organizationsRepository,+ documentsRepository,+}: {+ documentId: string;+ propertyDefinitionId: string;+ organizationId: string;+ value: unknown;+ customPropertiesRepository: CustomPropertiesRepository;+ customPropertiesOptionsRepository: CustomPropertiesOptionsRepository;+ organizationsRepository: OrganizationsRepository;+ documentsRepository: DocumentsRepository;+}) {+ const { definition: customProperty } = await ensurePropertyDefinitionExists({ propertyDefinitionId, organizationId, customPropertiesRepository });++ const customPropertyTypeDefinition = getCustomPropertyTypeDefinition({ type: customProperty.type });++ const parseResult = customPropertyTypeDefinition.value.inputSchema.safeParse(value);++ if (!parseResult.success) {+ throw createCustomPropertyValueInvalidError();+ }++ const parsedValue = parseResult.data;++ await customPropertyTypeDefinition.value.extendInputValidation?.({+ value: parsedValue,+ customProperty,+ customPropertiesRepository,+ customPropertiesOptionsRepository,+ organizationsRepository,+ documentsRepository,+ });++ const dbValue = customPropertyTypeDefinition.value.toDb({ value: parsedValue });++ await customPropertiesRepository.setDocumentCustomPropertyValue({+ documentId,+ propertyDefinitionId,+ values: Array.isArray(dbValue) ? dbValue : [dbValue],+ });+}++export async function deleteDocumentCustomPropertyValue({+ documentId,+ propertyDefinitionId,+ organizationId,+ customPropertiesRepository,+}: {+ documentId: string;+ propertyDefinitionId: string;+ organizationId: string;+ customPropertiesRepository: CustomPropertiesRepository;+}) {+ await ensurePropertyDefinitionExists({ propertyDefinitionId, organizationId, customPropertiesRepository });++ await customPropertiesRepository.deleteDocumentCustomPropertyValue({ documentId, propertyDefinitionId });+}++export async function ensurePropertyDefinitionExists({+ propertyDefinitionId,+ organizationId,+ customPropertiesRepository,+}: {+ propertyDefinitionId: string;+ organizationId: string;+ customPropertiesRepository: CustomPropertiesRepository;+}) {+ const { definition } = await customPropertiesRepository.getPropertyDefinitionById({ propertyDefinitionId, organizationId });++ if (!definition) {+ throw createCustomPropertyDefinitionNotFoundError();+ }++ return { definition };+}diff --git a/apps/papra-server/src/modules/custom-properties/definitions/boolean/boolean.custom-property-definition.ts b/apps/papra-server/src/modules/custom-properties/definitions/boolean/boolean.custom-property-definition.tsnew file mode 100644index 00000000..045ea49b--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/definitions/boolean/boolean.custom-property-definition.ts@@ -0,0 +1,15 @@+import z from 'zod';+import { defineCustomPropertyType, ensureRow } from '../custom-property-definition.models';++export const booleanCustomPropertyDefinition = defineCustomPropertyType({+ typeName: 'boolean',++ value: {++ inputSchema: z.boolean(),++ toDb: ({ value }) => ({ booleanValue: value }),++ fromDb: ensureRow(({ row }) => row.value.booleanValue),+ },+});diff --git a/apps/papra-server/src/modules/custom-properties/definitions/custom-property-definition.models.ts b/apps/papra-server/src/modules/custom-properties/definitions/custom-property-definition.models.tsnew file mode 100644index 00000000..3234b9e6--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/definitions/custom-property-definition.models.ts@@ -0,0 +1,212 @@+import type { Expand } from '@corentinth/chisels';+import type { DocumentsRepository } from '../../documents/documents.repository';+import type { OrganizationsRepository } from '../../organizations/organizations.repository';+import type { CustomPropertiesRepository } from '../custom-properties.repository';+import type { CustomPropertyDefinition, DbInsertableDocumentCustomPropertyValue } from '../custom-properties.types';+import type { CustomPropertiesOptionsRepository } from '../options/custom-properties-options.repository';+import z from 'zod';+import { isNil } from '../../shared/utils';+import { customPropertyDefinitionDescriptionSchema, customPropertyDefinitionDisplayOrderSchema, customPropertyDefinitionNameSchema } from './custom-property-definition.schema';++// Type from ../custom-properties.repository.ts getDocumentCustomPropertyValues query+export type DocumentCustomPropertyValueWithRelatedInfo = {+ value: {+ id: string;+ propertyDefinitionId: string;+ textValue: string | null;+ numberValue: number | null;+ dateValue: Date | null;+ booleanValue: boolean | null;+ selectOptionId: string | null;+ userId: string | null;+ relatedDocumentId: string | null;+ };+ definition: {+ id: string;+ name: string;+ key: string;+ type: string;+ };+ option: {+ id: string;+ name: string;+ } | null;+ relatedUser: {+ id: string;+ name: string | null;+ email: string;+ } | null;+ relatedDocument: {+ id: string;+ name: string;+ } | null;+};++type InsertableCustomPropertyValue = Expand<Omit<DbInsertableDocumentCustomPropertyValue, 'id' | 'createdAt' | 'updatedAt' | 'documentId' | 'propertyDefinitionId'>>;++type BaseCreateFields<TypeName extends string> = {+ type: TypeName;+ name: string;+ description?: string;+ displayOrder?: number;+};++type BaseUpdateFields = {+ name?: string;+ description?: string | null;+ displayOrder?: number;+};++type InferExtraFields<T> = T extends z.ZodType<infer U> ? U : Record<string, never>;++export type CustomPropertyTypeDefinitionInput<+ TypeName extends string = string,+ ValueInput = unknown,+ CreateExtraSchema extends z.ZodObject<Record<string, z.ZodTypeAny>> | undefined = undefined,+ UpdateExtraSchema extends z.ZodObject<Record<string, z.ZodTypeAny>> | undefined = undefined,+> = {+ typeName: TypeName;++ definition?: {+ createExtraSchema?: CreateExtraSchema;+ updateExtraSchema?: UpdateExtraSchema;++ onCreate?: (args: {+ apiInput: BaseCreateFields<TypeName> & InferExtraFields<CreateExtraSchema>;+ propertyDefinition: CustomPropertyDefinition;++ customPropertiesRepository: CustomPropertiesRepository;+ customPropertiesOptionsRepository: CustomPropertiesOptionsRepository;+ }) => Promise<void>;++ onUpdate?: (args: {+ apiInput: BaseUpdateFields & InferExtraFields<UpdateExtraSchema>;+ propertyDefinition: CustomPropertyDefinition;+ customPropertiesRepository: CustomPropertiesRepository;+ customPropertiesOptionsRepository: CustomPropertiesOptionsRepository;+ }) => Promise<void>;+ };++ value: {+ inputSchema: z.ZodType<ValueInput, z.ZodTypeDef, unknown>;++ extendInputValidation?: (args: {+ value: ValueInput;+ customProperty: CustomPropertyDefinition;+ customPropertiesRepository: CustomPropertiesRepository;+ customPropertiesOptionsRepository: CustomPropertiesOptionsRepository;+ organizationsRepository: OrganizationsRepository;+ documentsRepository: DocumentsRepository;+ }) => Promise<void>;++ toDb: (args: {+ value: ValueInput;+ }) => InsertableCustomPropertyValue | InsertableCustomPropertyValue[];++ fromDb: (args: {+ rows: DocumentCustomPropertyValueWithRelatedInfo[];+ }) => unknown;+ };+};++export type CustomPropertyTypeDefinition = {+ typeName: string;+ definition: {+ createExtraSchema?: z.ZodObject<Record<string, z.ZodTypeAny>>;+ updateExtraSchema?: z.ZodObject<Record<string, z.ZodTypeAny>>;+ createPropertySchema: z.ZodType<BaseCreateFields<string>>;+ updatePropertySchema: z.ZodType<BaseUpdateFields>;+ onCreate?: (args: {+ apiInput: BaseCreateFields<string> & Record<string, unknown>;+ propertyDefinition: CustomPropertyDefinition;+ customPropertiesRepository: CustomPropertiesRepository;+ customPropertiesOptionsRepository: CustomPropertiesOptionsRepository;+ }) => Promise<void>;+ onUpdate?: (args: {+ apiInput: BaseUpdateFields & Record<string, unknown>;+ propertyDefinition: CustomPropertyDefinition;+ customPropertiesRepository: CustomPropertiesRepository;+ customPropertiesOptionsRepository: CustomPropertiesOptionsRepository;+ }) => Promise<void>;+ };+ value: {+ inputSchema: z.ZodType<unknown, z.ZodTypeDef, unknown>;+ extendInputValidation?: (args: {+ value: unknown;+ customProperty: CustomPropertyDefinition;+ customPropertiesRepository: CustomPropertiesRepository;+ customPropertiesOptionsRepository: CustomPropertiesOptionsRepository;+ organizationsRepository: OrganizationsRepository;+ documentsRepository: DocumentsRepository;+ }) => Promise<void>;+ toDb: (args: { value: unknown }) => InsertableCustomPropertyValue | InsertableCustomPropertyValue[];+ fromDb: (args: { rows: DocumentCustomPropertyValueWithRelatedInfo[] }) => unknown;+ };+};++// Conditional types that properly resolve the schema shape based on whether extra schemas are provided.+// This concentrates type assertions in defineCustomPropertyType so all consumer code is cast-free.+const baseCreatePropertySchema = z.object({+ name: customPropertyDefinitionNameSchema,+ description: customPropertyDefinitionDescriptionSchema.optional(),+ displayOrder: customPropertyDefinitionDisplayOrderSchema.optional(),+});++const baseUpdatePropertySchema = z.object({+ name: customPropertyDefinitionNameSchema.optional(),+ description: customPropertyDefinitionDescriptionSchema.nullable().optional(),+ displayOrder: customPropertyDefinitionDisplayOrderSchema.optional(),+});++type BaseCreateSchemaShape = typeof baseCreatePropertySchema.shape;+type BaseUpdateSchemaShape = typeof baseUpdatePropertySchema.shape;++type CreatePropertySchemaFor<T extends string, Extra extends z.ZodObject<Record<string, z.ZodTypeAny>> | undefined>+ = Extra extends z.ZodObject<infer E extends z.ZodRawShape>+ ? z.ZodObject<{ type: z.ZodLiteral<T> } & BaseCreateSchemaShape & E>+ : z.ZodObject<{ type: z.ZodLiteral<T> } & BaseCreateSchemaShape>;++type UpdatePropertySchemaFor<Extra extends z.ZodObject<Record<string, z.ZodTypeAny>> | undefined>+ = Extra extends z.ZodObject<infer E extends z.ZodRawShape>+ ? z.ZodObject<BaseUpdateSchemaShape & E>+ : z.ZodObject<BaseUpdateSchemaShape>;++function buildCreatePropertySchema(typeName: string, extraSchema?: z.ZodObject<z.ZodRawShape>) {+ const schema = baseCreatePropertySchema.extend({ type: z.literal(typeName) });++ return extraSchema ? schema.merge(extraSchema) : schema;+}++function buildUpdatePropertySchema(extraSchema?: z.ZodObject<z.ZodRawShape>) {+ return extraSchema ? baseUpdatePropertySchema.merge(extraSchema) : baseUpdatePropertySchema;+}++export function defineCustomPropertyType<+ TypeName extends string,+ ValueInput,+ CreateExtraSchema extends z.ZodObject<Record<string, z.ZodTypeAny>> | undefined = undefined,+ UpdateExtraSchema extends z.ZodObject<Record<string, z.ZodTypeAny>> | undefined = undefined,+>(config: CustomPropertyTypeDefinitionInput<TypeName, ValueInput, CreateExtraSchema, UpdateExtraSchema>) {+ return {+ ...config,+ definition: {+ ...config.definition,+ createPropertySchema: buildCreatePropertySchema(config.typeName, config.definition?.createExtraSchema) as CreatePropertySchemaFor<TypeName, CreateExtraSchema>,+ updatePropertySchema: buildUpdatePropertySchema(config.definition?.updateExtraSchema) as UpdatePropertySchemaFor<UpdateExtraSchema>,+ },+ };+}++export function ensureRow<T>(fn: (args: { row: T }) => unknown) {+ return (args: { rows: T[] }) => {+ const { rows } = args;++ const [row] = rows;++ if (isNil(row)) {+ return null;+ }++ return fn({ row });+ };+}diff --git a/apps/papra-server/src/modules/custom-properties/definitions/custom-property-definition.registry.ts b/apps/papra-server/src/modules/custom-properties/definitions/custom-property-definition.registry.tsnew file mode 100644index 00000000..f8d0bc23--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/definitions/custom-property-definition.registry.ts@@ -0,0 +1,54 @@+import type { CustomPropertyTypeDefinition } from './custom-property-definition.models';+import { z } from 'zod';+import { createError } from '../../shared/errors/errors';+import { booleanCustomPropertyDefinition } from './boolean/boolean.custom-property-definition';+import { dateCustomPropertyDefinition } from './date/date.custom-property-definition';+import { documentRelationCustomPropertyDefinition } from './document-relation/document-relation.custom-property-definition';+import { multiSelectCustomPropertyDefinition } from './multi-select/multi-select.custom-property-definition';+import { numberCustomPropertyDefinition } from './number/number.custom-property-definition';+import { selectCustomPropertyDefinition } from './select/select.custom-property-definition';+import { textCustomPropertyDefinition } from './text/text.custom-property-definition';+import { userRelationCustomPropertyDefinition } from './user-relation/user-relation.custom-property-definition';++export const customPropertyDefinitionRegistry = {+ [textCustomPropertyDefinition.typeName]: textCustomPropertyDefinition,+ [numberCustomPropertyDefinition.typeName]: numberCustomPropertyDefinition,+ [dateCustomPropertyDefinition.typeName]: dateCustomPropertyDefinition,+ [booleanCustomPropertyDefinition.typeName]: booleanCustomPropertyDefinition,+ [selectCustomPropertyDefinition.typeName]: selectCustomPropertyDefinition,+ [multiSelectCustomPropertyDefinition.typeName]: multiSelectCustomPropertyDefinition,+ [userRelationCustomPropertyDefinition.typeName]: userRelationCustomPropertyDefinition,+ [documentRelationCustomPropertyDefinition.typeName]: documentRelationCustomPropertyDefinition,+};++export const customPropertyDefinitions = Object.values(customPropertyDefinitionRegistry);++export type CustomPropertyType = keyof typeof customPropertyDefinitionRegistry;++export function getCustomPropertyTypeDefinition({ type }: { type: string }) {+ const definition = customPropertyDefinitionRegistry[type as CustomPropertyType] as CustomPropertyTypeDefinition | undefined;++ if (!definition) {+ throw createError({+ message: `Custom property type "${type}" is not supported`,+ code: 'unsupported_custom_property_type',+ statusCode: 400,+ });+ }++ return definition;+}++// Build schemas as explicit tuples so TypeScript preserves individual types for the discriminated union+export const createPropertyDefinitionBodySchema = z.discriminatedUnion('type', [+ textCustomPropertyDefinition.definition.createPropertySchema,+ numberCustomPropertyDefinition.definition.createPropertySchema,+ dateCustomPropertyDefinition.definition.createPropertySchema,+ booleanCustomPropertyDefinition.definition.createPropertySchema,+ selectCustomPropertyDefinition.definition.createPropertySchema,+ multiSelectCustomPropertyDefinition.definition.createPropertySchema,+ userRelationCustomPropertyDefinition.definition.createPropertySchema,+ documentRelationCustomPropertyDefinition.definition.createPropertySchema,+]);++export type CreatePropertyDefinition = z.infer<typeof createPropertyDefinitionBodySchema>;diff --git a/apps/papra-server/src/modules/custom-properties/definitions/custom-property-definition.schema.ts b/apps/papra-server/src/modules/custom-properties/definitions/custom-property-definition.schema.tsnew file mode 100644index 00000000..b04660fc--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/definitions/custom-property-definition.schema.ts@@ -0,0 +1,5 @@+import { z } from 'zod';++export const customPropertyDefinitionNameSchema = z.string().trim().min(1).max(255);+export const customPropertyDefinitionDescriptionSchema = z.string().trim().max(1000);+export const customPropertyDefinitionDisplayOrderSchema = z.number().int().min(0);diff --git a/apps/papra-server/src/modules/custom-properties/definitions/date/date.custom-property-definition.ts b/apps/papra-server/src/modules/custom-properties/definitions/date/date.custom-property-definition.tsnew file mode 100644index 00000000..36b28ecf--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/definitions/date/date.custom-property-definition.ts@@ -0,0 +1,26 @@+import z from 'zod';+import { isValidDate } from '../../../shared/date';+import { defineCustomPropertyType, ensureRow } from '../custom-property-definition.models';++const dateInputSchema = z.union([z.string(), z.number()]).transform((value) => {+ const date = new Date(value);++ if (!isValidDate(date)) {+ throw new Error('Invalid date value');+ }++ return date;+});++export const dateCustomPropertyDefinition = defineCustomPropertyType({+ typeName: 'date',++ value: {++ inputSchema: dateInputSchema,++ toDb: ({ value }) => ({ dateValue: value }),++ fromDb: ensureRow(({ row }) => row.value.dateValue),+ },+});diff --git a/apps/papra-server/src/modules/custom-properties/definitions/document-relation/document-relation.custom-property-definition.ts b/apps/papra-server/src/modules/custom-properties/definitions/document-relation/document-relation.custom-property-definition.tsnew file mode 100644index 00000000..042fc080--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/definitions/document-relation/document-relation.custom-property-definition.ts@@ -0,0 +1,32 @@+import z from 'zod';+import { createCustomPropertyRelatedDocumentNotFoundError } from '../../custom-properties.errors';+import { defineCustomPropertyType } from '../custom-property-definition.models';++export const documentRelationCustomPropertyDefinition = defineCustomPropertyType({+ typeName: 'document_relation',++ value: {++ inputSchema: z.array(z.string()),++ extendInputValidation: async ({ value: documentIds, customProperty, documentsRepository }) => {+ const { documents } = await documentsRepository.getDocumentsByIds({ documentIds, organizationId: customProperty.organizationId });+ const foundIds = new Set(documents.map(d => d.id));++ for (const documentId of documentIds) {+ if (!foundIds.has(documentId)) {+ throw createCustomPropertyRelatedDocumentNotFoundError();+ }+ }+ },++ toDb: ({ value }) => value.map(relatedDocumentId => ({ relatedDocumentId })),++ fromDb: ({ rows }) => rows+ .filter(r => r.relatedDocument !== null)+ .map(r => ({+ documentId: r.relatedDocument!.id,+ name: r.relatedDocument!.name,+ })),+ },+});diff --git a/apps/papra-server/src/modules/custom-properties/definitions/multi-select/multi-select.custom-property-definition.ts b/apps/papra-server/src/modules/custom-properties/definitions/multi-select/multi-select.custom-property-definition.tsnew file mode 100644index 00000000..2e5a4918--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/definitions/multi-select/multi-select.custom-property-definition.ts@@ -0,0 +1,72 @@+import z from 'zod';+import { customPropertySelectOptionIdSchema } from '../../options/custom-properties-options.schemas';+import { ensureOptionsExist } from '../../options/custom-properties-options.usecases';+import { defineCustomPropertyType } from '../custom-property-definition.models';+import { selectCustomPropertyOptionNameSchema } from '../select/select.custom-property-definition.schemas';++export const multiSelectCustomPropertyDefinition = defineCustomPropertyType({+ typeName: 'multi_select',++ definition: {+ createExtraSchema: z.object({+ options: z+ .array(z.object({+ name: selectCustomPropertyOptionNameSchema,+ }))+ .min(1, 'At least one option must be provided'),+ }),++ onCreate: async ({+ apiInput: { options },+ propertyDefinition,+ customPropertiesOptionsRepository,+ }) => {+ await customPropertiesOptionsRepository.syncSelectOptions({+ propertyDefinitionId: propertyDefinition.id,+ options,+ });+ },++ updateExtraSchema: z.object({+ options: z.array(z.object({+ id: customPropertySelectOptionIdSchema.optional(),+ name: selectCustomPropertyOptionNameSchema,+ })).min(1, 'At least one option must be provided').optional(),+ }),++ onUpdate: async ({+ apiInput: { options },+ propertyDefinition,+ customPropertiesOptionsRepository,+ }) => {+ if (options) {+ await customPropertiesOptionsRepository.syncSelectOptions({+ propertyDefinitionId: propertyDefinition.id,+ options,+ });+ }+ },+ },++ value: {++ inputSchema: z.array(customPropertySelectOptionIdSchema),++ extendInputValidation: async ({ value, customProperty, customPropertiesOptionsRepository }) => {+ await ensureOptionsExist({+ propertyDefinitionId: customProperty.id,+ optionIds: value,+ customPropertiesOptionsRepository,+ });+ },++ toDb: ({ value }) => value.map(selectOptionId => ({ selectOptionId })),++ fromDb: ({ rows }) => rows+ .filter(r => r.option !== null)+ .map(r => ({+ optionId: r.option!.id,+ name: r.option!.name,+ })),+ },+});diff --git a/apps/papra-server/src/modules/custom-properties/definitions/number/number.custom-property-definition.ts b/apps/papra-server/src/modules/custom-properties/definitions/number/number.custom-property-definition.tsnew file mode 100644index 00000000..f6e58bd2--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/definitions/number/number.custom-property-definition.ts@@ -0,0 +1,14 @@+import z from 'zod';+import { defineCustomPropertyType, ensureRow } from '../custom-property-definition.models';++export const numberCustomPropertyDefinition = defineCustomPropertyType({+ typeName: 'number',++ value: {+ inputSchema: z.number().finite(),++ toDb: ({ value }) => ({ numberValue: value }),++ fromDb: ensureRow(({ row }) => row.value.numberValue),+ },+});diff --git a/apps/papra-server/src/modules/custom-properties/definitions/select/select.custom-property-definition.schemas.ts b/apps/papra-server/src/modules/custom-properties/definitions/select/select.custom-property-definition.schemas.tsnew file mode 100644index 00000000..e5af26c3--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/definitions/select/select.custom-property-definition.schemas.ts@@ -0,0 +1,3 @@+import z from 'zod';++export const selectCustomPropertyOptionNameSchema = z.string().trim().min(1).max(255);diff --git a/apps/papra-server/src/modules/custom-properties/definitions/select/select.custom-property-definition.ts b/apps/papra-server/src/modules/custom-properties/definitions/select/select.custom-property-definition.tsnew file mode 100644index 00000000..116ca35c--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/definitions/select/select.custom-property-definition.ts@@ -0,0 +1,78 @@+import z from 'zod';+import { customPropertySelectOptionIdSchema } from '../../options/custom-properties-options.schemas';+import { ensureOptionExists } from '../../options/custom-properties-options.usecases';+import { defineCustomPropertyType } from '../custom-property-definition.models';+import { selectCustomPropertyOptionNameSchema } from './select.custom-property-definition.schemas';++export const selectCustomPropertyDefinition = defineCustomPropertyType({+ typeName: 'select',++ definition: {+ createExtraSchema: z.object({+ options: z+ .array(z.object({+ name: selectCustomPropertyOptionNameSchema,+ }))+ .min(1, 'At least one option must be provided'),+ }),++ onCreate: async ({+ apiInput: { options },+ propertyDefinition,+ customPropertiesOptionsRepository,+ }) => {+ await customPropertiesOptionsRepository.syncSelectOptions({+ propertyDefinitionId: propertyDefinition.id,+ options,+ });+ },++ updateExtraSchema: z.object({+ options: z.array(z.object({+ id: customPropertySelectOptionIdSchema.optional(),+ name: selectCustomPropertyOptionNameSchema,+ })).min(1, 'At least one option must be provided').optional(),+ }),++ onUpdate: async ({+ apiInput: { options },+ propertyDefinition,+ customPropertiesOptionsRepository,+ }) => {+ if (options) {+ await customPropertiesOptionsRepository.syncSelectOptions({+ propertyDefinitionId: propertyDefinition.id,+ options,+ });+ }+ },+ },++ value: {++ inputSchema: customPropertySelectOptionIdSchema,++ extendInputValidation: async ({ value, customProperty, customPropertiesOptionsRepository }) => {+ await ensureOptionExists({+ optionId: value,+ propertyDefinitionId: customProperty.id,+ customPropertiesOptionsRepository,+ });+ },++ toDb: ({ value }) => ({ selectOptionId: value }),++ fromDb: ({ rows }) => {+ const row = rows[0];++ if (!row?.option) {+ return null;+ }++ return ({+ optionId: row.option.id,+ name: row.option.name,+ });+ },+ },+});diff --git a/apps/papra-server/src/modules/custom-properties/definitions/text/text.custom-property-definition.ts b/apps/papra-server/src/modules/custom-properties/definitions/text/text.custom-property-definition.tsnew file mode 100644index 00000000..995d7c6e--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/definitions/text/text.custom-property-definition.ts@@ -0,0 +1,15 @@+import z from 'zod';+import { defineCustomPropertyType, ensureRow } from '../custom-property-definition.models';++export const textCustomPropertyDefinition = defineCustomPropertyType({+ typeName: 'text',++ value: {++ inputSchema: z.string().max(10_000, 'Text custom property value must be at most 10,000 characters long'),++ toDb: ({ value }) => ({ textValue: value }),++ fromDb: ensureRow(({ row }) => row.value.textValue),+ },+});diff --git a/apps/papra-server/src/modules/custom-properties/definitions/user-relation/user-relation.custom-property-definition.ts b/apps/papra-server/src/modules/custom-properties/definitions/user-relation/user-relation.custom-property-definition.tsnew file mode 100644index 00000000..e416a298--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/definitions/user-relation/user-relation.custom-property-definition.ts@@ -0,0 +1,32 @@+import z from 'zod';+import { createCustomPropertyUserNotFoundError } from '../../custom-properties.errors';+import { defineCustomPropertyType } from '../custom-property-definition.models';++export const userRelationCustomPropertyDefinition = defineCustomPropertyType({+ typeName: 'user_relation',++ value: {+ inputSchema: z.array(z.string()),++ extendInputValidation: async ({ value: userIds, customProperty, organizationsRepository }) => {+ const { members } = await organizationsRepository.getOrganizationMembers({ organizationId: customProperty.organizationId });+ const memberUserIds = new Set(members.map(m => m.userId));++ for (const userId of userIds) {+ if (!memberUserIds.has(userId)) {+ throw createCustomPropertyUserNotFoundError();+ }+ }+ },++ toDb: ({ value }) => value.map(userId => ({ userId })),++ fromDb: ({ rows }) => rows+ .filter(r => r.relatedUser !== null)+ .map(r => ({+ userId: r.relatedUser!.id,+ name: r.relatedUser!.name,+ email: r.relatedUser!.email,+ })),+ },+});diff --git a/apps/papra-server/src/modules/custom-properties/e2e/custom-properties-definitions.e2e.test.ts b/apps/papra-server/src/modules/custom-properties/e2e/custom-properties-definitions.e2e.test.tsnew file mode 100644index 00000000..5cf0a772--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/e2e/custom-properties-definitions.e2e.test.ts@@ -0,0 +1,190 @@+import type { CustomPropertyDefinition } from '../custom-properties.types';+import { describe, expect, test } from 'vitest';+import { createInMemoryDatabase } from '../../app/database/database.test-utils';+import { createServer } from '../../app/server';+import { createTestServerDependencies } from '../../app/server.test-utils';+import { overrideConfig } from '../../config/config.test-utils';+import { ORGANIZATION_ROLES } from '../../organizations/organizations.constants';++const USER_ID = 'usr_111111111111111111111111';+const ORG_ID = 'org_222222222222222222222222';++async function setupApp() {+ const { db } = await createInMemoryDatabase({+ users: [{ id: USER_ID, email: '[email protected]' }],+ organizations: [{ id: ORG_ID, name: 'Org 1' }],+ organizationMembers: [{ organizationId: ORG_ID, userId: USER_ID, role: ORGANIZATION_ROLES.OWNER }],+ });++ const { app } = createServer(createTestServerDependencies({ db, config: overrideConfig({ env: 'test' }) }));++ return { db, app };+}++describe('custom properties e2e', () => {+ describe('property definitions', () => {+ test('can create a property definition', async () => {+ const { app } = await setupApp();++ const response = await app.request(+ `/api/organizations/${ORG_ID}/custom-properties`,+ {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name: 'Invoice Number', type: 'text' }),+ },+ { loggedInUserId: USER_ID },+ );++ expect(response.status).to.eql(200);++ const { propertyDefinition } = await response.json() as { propertyDefinition: CustomPropertyDefinition };++ expect(propertyDefinition).to.include({+ organizationId: ORG_ID,+ name: 'Invoice Number',+ key: 'invoicenumber',+ type: 'text',+ });+ });++ test('can list property definitions for an organization', async () => {+ const { app } = await setupApp();++ await app.request(+ `/api/organizations/${ORG_ID}/custom-properties`,+ {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name: 'Invoice Number', type: 'text' }),+ },+ { loggedInUserId: USER_ID },+ );++ const response = await app.request(+ `/api/organizations/${ORG_ID}/custom-properties`,+ { method: 'GET' },+ { loggedInUserId: USER_ID },+ );++ expect(response.status).to.eql(200);++ const { propertyDefinitions } = await response.json() as { propertyDefinitions: CustomPropertyDefinition[] };++ expect(propertyDefinitions).to.have.length(1);+ expect(propertyDefinitions[0]).to.include({ key: 'invoicenumber', name: 'Invoice Number' });+ });++ test('can get a single property definition', async () => {+ const { app } = await setupApp();++ const createResponse = await app.request(+ `/api/organizations/${ORG_ID}/custom-properties`,+ {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name: 'Invoice Number', type: 'text' }),+ },+ { loggedInUserId: USER_ID },+ );+ const { propertyDefinition } = await createResponse.json() as { propertyDefinition: CustomPropertyDefinition };++ const response = await app.request(+ `/api/organizations/${ORG_ID}/custom-properties/${propertyDefinition.id}`,+ { method: 'GET' },+ { loggedInUserId: USER_ID },+ );++ expect(response.status).to.eql(200);++ const { definition } = await response.json() as { definition: CustomPropertyDefinition };++ expect(definition).to.include({ id: propertyDefinition.id, key: 'invoicenumber' });+ });++ test('can update a property definition', async () => {+ const { app } = await setupApp();++ const createResponse = await app.request(+ `/api/organizations/${ORG_ID}/custom-properties`,+ {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name: 'Invoice Number', type: 'text' }),+ },+ { loggedInUserId: USER_ID },+ );+ const { propertyDefinition } = await createResponse.json() as { propertyDefinition: CustomPropertyDefinition };++ const updateResponse = await app.request(+ `/api/organizations/${ORG_ID}/custom-properties/${propertyDefinition.id}`,+ { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Invoice No.' }) },+ { loggedInUserId: USER_ID },+ );++ expect(updateResponse.status).to.eql(200);++ const { propertyDefinition: updated } = await updateResponse.json() as { propertyDefinition: CustomPropertyDefinition };++ expect(updated).to.include({ name: 'Invoice No.', key: 'invoiceno' });+ });++ test('can delete a property definition', async () => {+ const { app } = await setupApp();++ const createResponse = await app.request(+ `/api/organizations/${ORG_ID}/custom-properties`,+ {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name: 'Invoice Number', type: 'text' }),+ },+ { loggedInUserId: USER_ID },+ );+ const { propertyDefinition } = await createResponse.json() as { propertyDefinition: CustomPropertyDefinition };++ const deleteResponse = await app.request(+ `/api/organizations/${ORG_ID}/custom-properties/${propertyDefinition.id}`,+ { method: 'DELETE' },+ { loggedInUserId: USER_ID },+ );++ expect(deleteResponse.status).to.eql(200);++ const listResponse = await app.request(+ `/api/organizations/${ORG_ID}/custom-properties`,+ { method: 'GET' },+ { loggedInUserId: USER_ID },+ );+ const { propertyDefinitions } = await listResponse.json() as { propertyDefinitions: CustomPropertyDefinition[] };++ expect(propertyDefinitions).to.have.length(0);+ });++ test('two property definitions with the same key in the same organization are rejected', async () => {+ const { app } = await setupApp();++ await app.request(+ `/api/organizations/${ORG_ID}/custom-properties`,+ {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name: 'Invoice Number', type: 'text' }),+ },+ { loggedInUserId: USER_ID },+ );++ const response = await app.request(+ `/api/organizations/${ORG_ID}/custom-properties`,+ {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name: 'Invoice Number', type: 'number' }),+ },+ { loggedInUserId: USER_ID },+ );++ expect(response.status).to.eql(409);+ });+ });+});diff --git a/apps/papra-server/src/modules/custom-properties/e2e/documents-custom-properties.e2e.test.ts b/apps/papra-server/src/modules/custom-properties/e2e/documents-custom-properties.e2e.test.tsnew file mode 100644index 00000000..9da022fd--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/e2e/documents-custom-properties.e2e.test.ts@@ -0,0 +1,190 @@+import type { DocumentCustomPropertyForApi } from '../custom-properties.models';+import type { CustomPropertyDefinition } from '../custom-properties.types';+import { describe, expect, test } from 'vitest';+import { createInMemoryDatabase } from '../../app/database/database.test-utils';+import { createServer } from '../../app/server';+import { createTestServerDependencies } from '../../app/server.test-utils';+import { overrideConfig } from '../../config/config.test-utils';+import { ORGANIZATION_ROLES } from '../../organizations/organizations.constants';++const USER_ID = 'usr_111111111111111111111111';+const ORG_ID = 'org_222222222222222222222222';+const DOC_ID = 'doc_333333333333333333333333';++const BASE_DOCUMENT = {+ id: DOC_ID,+ organizationId: ORG_ID,+ name: 'invoice.txt',+ originalName: 'invoice.txt',+ mimeType: 'text/plain',+ originalStorageKey: 'org/originals/invoice.txt',+ originalSha256Hash: 'hash',+};++async function setupApp() {+ const { db } = await createInMemoryDatabase({+ users: [{ id: USER_ID, email: '[email protected]' }],+ organizations: [{ id: ORG_ID, name: 'Org 1' }],+ organizationMembers: [{ organizationId: ORG_ID, userId: USER_ID, role: ORGANIZATION_ROLES.OWNER }],+ documents: [BASE_DOCUMENT],+ });++ const { app } = createServer(createTestServerDependencies({ db, config: overrideConfig({ env: 'test' }) }));++ return { db, app };+}++describe('custom properties e2e', () => {+ describe('document custom property values', () => {+ test('can set a custom property value on a document', async () => {+ const { app } = await setupApp();++ const createResponse = await app.request(+ `/api/organizations/${ORG_ID}/custom-properties`,+ {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name: 'Invoice Number', type: 'text' }),+ },+ { loggedInUserId: USER_ID },+ );+ const { propertyDefinition } = await createResponse.json() as { propertyDefinition: CustomPropertyDefinition };++ const setResponse = await app.request(+ `/api/organizations/${ORG_ID}/documents/${DOC_ID}/custom-properties/${propertyDefinition.id}`,+ {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ value: 'INV-001' }),+ },+ { loggedInUserId: USER_ID },+ );++ expect(setResponse.status).to.eql(204);++ const getResponse = await app.request(+ `/api/organizations/${ORG_ID}/documents/${DOC_ID}`,+ { method: 'GET' },+ { loggedInUserId: USER_ID },+ );+ const { document } = await getResponse.json() as { document: { customProperties: DocumentCustomPropertyForApi[] } };++ expect(document.customProperties).to.eql([+ { key: 'invoicenumber', name: 'Invoice Number', type: 'text', displayOrder: 0, value: 'INV-001' },+ ]);+ });++ test('setting a value twice overwrites it', async () => {+ const { app } = await setupApp();++ const createResponse = await app.request(+ `/api/organizations/${ORG_ID}/custom-properties`,+ {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name: 'Invoice Number', type: 'text' }),+ },+ { loggedInUserId: USER_ID },+ );+ const { propertyDefinition } = await createResponse.json() as { propertyDefinition: CustomPropertyDefinition };++ await app.request(+ `/api/organizations/${ORG_ID}/documents/${DOC_ID}/custom-properties/${propertyDefinition.id}`,+ {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ value: 'INV-001' }),+ },+ { loggedInUserId: USER_ID },+ );++ await app.request(+ `/api/organizations/${ORG_ID}/documents/${DOC_ID}/custom-properties/${propertyDefinition.id}`,+ {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ value: 'INV-002' }),+ },+ { loggedInUserId: USER_ID },+ );++ const getResponse = await app.request(+ `/api/organizations/${ORG_ID}/documents/${DOC_ID}`,+ { method: 'GET' },+ { loggedInUserId: USER_ID },+ );+ const { document } = await getResponse.json() as { document: { customProperties: DocumentCustomPropertyForApi[] } };++ expect(document.customProperties[0]?.value).to.eql('INV-002');+ });++ test('can delete a custom property value from a document, it shows as null in the document', async () => {+ const { app } = await setupApp();++ const createResponse = await app.request(+ `/api/organizations/${ORG_ID}/custom-properties`,+ {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name: 'Invoice Number', type: 'text' }),+ },+ { loggedInUserId: USER_ID },+ );+ const { propertyDefinition } = await createResponse.json() as { propertyDefinition: CustomPropertyDefinition };++ await app.request(+ `/api/organizations/${ORG_ID}/documents/${DOC_ID}/custom-properties/${propertyDefinition.id}`,+ {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ value: 'INV-001' }),+ },+ { loggedInUserId: USER_ID },+ );++ const deleteResponse = await app.request(+ `/api/organizations/${ORG_ID}/documents/${DOC_ID}/custom-properties/${propertyDefinition.id}`,+ { method: 'DELETE' },+ { loggedInUserId: USER_ID },+ );++ expect(deleteResponse.status).to.eql(204);++ const getResponse = await app.request(+ `/api/organizations/${ORG_ID}/documents/${DOC_ID}`,+ { method: 'GET' },+ { loggedInUserId: USER_ID },+ );+ const { document } = await getResponse.json() as { document: { customProperties: DocumentCustomPropertyForApi[] } };++ expect(document.customProperties).to.eql([+ { key: 'invoicenumber', name: 'Invoice Number', type: 'text', displayOrder: 0, value: null },+ ]);+ });++ test('a defined property with no value set shows as null in the document', async () => {+ const { app } = await setupApp();++ await app.request(+ `/api/organizations/${ORG_ID}/custom-properties`,+ {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name: 'Invoice Number', type: 'text' }),+ },+ { loggedInUserId: USER_ID },+ );++ const getResponse = await app.request(+ `/api/organizations/${ORG_ID}/documents/${DOC_ID}`,+ { method: 'GET' },+ { loggedInUserId: USER_ID },+ );+ const { document } = await getResponse.json() as { document: { customProperties: DocumentCustomPropertyForApi[] } };++ expect(document.customProperties).to.eql([+ { key: 'invoicenumber', name: 'Invoice Number', type: 'text', displayOrder: 0, value: null },+ ]);+ });+ });+});diff --git a/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.constants.ts b/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.constants.tsnew file mode 100644index 00000000..48cc1bd0--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.constants.ts@@ -0,0 +1,4 @@+import { createPrefixedIdRegex } from '../../shared/random/ids';++export const CUSTOM_PROPERTY_SELECT_OPTION_ID_PREFIX = 'cpso';+export const CUSTOM_PROPERTY_SELECT_OPTION_ID_REGEX = createPrefixedIdRegex({ prefix: CUSTOM_PROPERTY_SELECT_OPTION_ID_PREFIX });diff --git a/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.errors.ts b/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.errors.tsnew file mode 100644index 00000000..054527f9--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.errors.ts@@ -0,0 +1,13 @@+import { createErrorFactory } from '../../shared/errors/errors';++export const createCustomPropertySelectOptionNotFoundError = createErrorFactory({+ message: 'The provided value is not a valid option for this select property.',+ code: 'custom_property_select_option.not_found',+ statusCode: 400,+});++export const createCustomPropertySelectOptionUnknownIdError = createErrorFactory({+ message: 'One or more provided select option IDs do not belong to this property definition.',+ code: 'custom_property_select_option.unknown_id',+ statusCode: 400,+});diff --git a/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.repository.test.ts b/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.repository.test.tsnew file mode 100644index 00000000..4547a54b--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.repository.test.ts@@ -0,0 +1,267 @@+import type { Database } from '../../app/database/database.types';+import { getTableColumns } from 'drizzle-orm';+import { pick } from 'lodash-es';+import { describe, expect, test } from 'vitest';+import { createInMemoryDatabase } from '../../app/database/database.test-utils';+import { CUSTOM_PROPERTY_TYPES } from '../custom-properties.constants';+import { createCustomPropertySelectOptionUnknownIdError } from './custom-properties-options.errors';+import { createCustomPropertiesOptionsRepository } from './custom-properties-options.repository';+import { customPropertySelectOptionsTable } from './custom-properties-options.table';++async function getOptions({ db, withId = true }: { db: Database; withId?: boolean }) {+ return db+ .select({+ ...pick(+ getTableColumns(customPropertySelectOptionsTable),+ [...(withId ? ['id'] : []), 'propertyDefinitionId', 'name', 'key', 'displayOrder'],+ ),+ })+ .from(customPropertySelectOptionsTable);+}++describe('custom-properties-options repository', () => {+ describe('syncSelectOptions', () => {+ test('creates new options when none exist', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_111111111111111111111111', name: 'Test Org' }],+ customPropertyDefinitions: [{+ id: 'cpd_111111111111111111111111',+ organizationId: 'org_111111111111111111111111',+ name: 'Status',+ type: CUSTOM_PROPERTY_TYPES.SELECT,+ key: 'status',+ }],+ });+ const customPropertiesOptionsRepository = createCustomPropertiesOptionsRepository({ db });++ expect(await getOptions({ db })).to.eql([]);++ await customPropertiesOptionsRepository.syncSelectOptions({+ propertyDefinitionId: 'cpd_111111111111111111111111',+ options: [{ name: 'Open' }, { name: 'Closed' }],+ });++ expect(+ await getOptions({ db, withId: false }),+ ).to.eql([+ { propertyDefinitionId: 'cpd_111111111111111111111111', name: 'Open', key: 'open', displayOrder: 0 },+ { propertyDefinitionId: 'cpd_111111111111111111111111', name: 'Closed', key: 'closed', displayOrder: 1 },+ ]);+ });++ test('assigns displayOrder based on array position', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_111111111111111111111111', name: 'Test Org' }],+ customPropertyDefinitions: [{+ id: 'cpd_111111111111111111111111',+ organizationId: 'org_111111111111111111111111',+ name: 'Status',+ type: CUSTOM_PROPERTY_TYPES.SELECT,+ key: 'status',+ }],+ });+ const customPropertiesOptionsRepository = createCustomPropertiesOptionsRepository({ db });++ await customPropertiesOptionsRepository.syncSelectOptions({+ propertyDefinitionId: 'cpd_111111111111111111111111',+ options: [{ name: 'A' }, { name: 'B' }, { name: 'C' }],+ });++ expect(+ await getOptions({ db, withId: false }),+ ).to.eql([+ { propertyDefinitionId: 'cpd_111111111111111111111111', name: 'A', key: 'a', displayOrder: 0 },+ { propertyDefinitionId: 'cpd_111111111111111111111111', name: 'B', key: 'b', displayOrder: 1 },+ { propertyDefinitionId: 'cpd_111111111111111111111111', name: 'C', key: 'c', displayOrder: 2 },+ ]);+ });++ test('updates existing options by ID', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_111111111111111111111111', name: 'Test Org' }],+ customPropertyDefinitions: [{+ id: 'cpd_111111111111111111111111',+ organizationId: 'org_111111111111111111111111',+ name: 'Status',+ type: CUSTOM_PROPERTY_TYPES.SELECT,+ key: 'status',+ }],+ customPropertySelectOptions: [{+ id: 'cso_111111111111111111111111',+ propertyDefinitionId: 'cpd_111111111111111111111111',+ name: 'Draft',+ key: 'draft',+ displayOrder: 0,+ }],+ });+ const customPropertiesOptionsRepository = createCustomPropertiesOptionsRepository({ db });++ await customPropertiesOptionsRepository.syncSelectOptions({+ propertyDefinitionId: 'cpd_111111111111111111111111',+ options: [{ id: 'cso_111111111111111111111111', name: 'Published' }],+ });++ expect(+ await getOptions({ db }),+ ).to.eql([+ { id: 'cso_111111111111111111111111', propertyDefinitionId: 'cpd_111111111111111111111111', name: 'Published', key: 'published', displayOrder: 0 },+ ]);+ });++ test('deletes options omitted from the incoming list', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_111111111111111111111111', name: 'Test Org' }],+ customPropertyDefinitions: [{+ id: 'cpd_111111111111111111111111',+ organizationId: 'org_111111111111111111111111',+ name: 'Status',+ type: CUSTOM_PROPERTY_TYPES.SELECT,+ key: 'status',+ }],+ customPropertySelectOptions: [+ { id: 'cso_111111111111111111111111', propertyDefinitionId: 'cpd_111111111111111111111111', name: 'Keep', key: 'keep', displayOrder: 0 },+ { id: 'cso_222222222222222222222222', propertyDefinitionId: 'cpd_111111111111111111111111', name: 'Remove', key: 'remove', displayOrder: 1 },+ ],+ });+ const customPropertiesOptionsRepository = createCustomPropertiesOptionsRepository({ db });++ await customPropertiesOptionsRepository.syncSelectOptions({+ propertyDefinitionId: 'cpd_111111111111111111111111',+ options: [{ id: 'cso_111111111111111111111111', name: 'Keep' }],+ });++ expect(+ await getOptions({ db, withId: false }),+ ).to.eql([+ { propertyDefinitionId: 'cpd_111111111111111111111111', name: 'Keep', key: 'keep', displayOrder: 0 },+ ]);+ });++ test('handles mixed create, update, and delete in one call', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_111111111111111111111111', name: 'Test Org' }],+ customPropertyDefinitions: [{+ id: 'cpd_111111111111111111111111',+ organizationId: 'org_111111111111111111111111',+ name: 'Status',+ type: CUSTOM_PROPERTY_TYPES.SELECT,+ key: 'status',+ }],+ customPropertySelectOptions: [+ { id: 'cso_111111111111111111111111', propertyDefinitionId: 'cpd_111111111111111111111111', name: 'Old', key: 'old', displayOrder: 0 },+ { id: 'cso_222222222222222222222222', propertyDefinitionId: 'cpd_111111111111111111111111', name: 'ToDelete', key: 'todelete', displayOrder: 1 },+ ],+ });+ const customPropertiesOptionsRepository = createCustomPropertiesOptionsRepository({ db });++ await customPropertiesOptionsRepository.syncSelectOptions({+ propertyDefinitionId: 'cpd_111111111111111111111111',+ options: [{ id: 'cso_111111111111111111111111', name: 'Updated' }, { name: 'New' }],+ });++ expect(+ await getOptions({ db, withId: false }),+ ).to.eql([+ { propertyDefinitionId: 'cpd_111111111111111111111111', name: 'Updated', key: 'updated', displayOrder: 0 },+ { propertyDefinitionId: 'cpd_111111111111111111111111', name: 'New', key: 'new', displayOrder: 1 },+ ]);+ });++ test('is a no-op when the incoming list is empty and there are no existing options', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_111111111111111111111111', name: 'Test Org' }],+ customPropertyDefinitions: [{+ id: 'cpd_111111111111111111111111',+ organizationId: 'org_111111111111111111111111',+ name: 'Status',+ type: CUSTOM_PROPERTY_TYPES.SELECT,+ key: 'status',+ }],+ });+ const customPropertiesOptionsRepository = createCustomPropertiesOptionsRepository({ db });++ await customPropertiesOptionsRepository.syncSelectOptions({+ propertyDefinitionId: 'cpd_111111111111111111111111',+ options: [],+ });++ expect(await getOptions({ db })).to.eql([]);+ });++ test('deletes all options when an empty list is provided', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_111111111111111111111111', name: 'Test Org' }],+ customPropertyDefinitions: [{+ id: 'cpd_111111111111111111111111',+ organizationId: 'org_111111111111111111111111',+ name: 'Status',+ type: CUSTOM_PROPERTY_TYPES.SELECT,+ key: 'status',+ }],+ customPropertySelectOptions: [+ { id: 'cso_111111111111111111111111', propertyDefinitionId: 'cpd_111111111111111111111111', name: 'A', key: 'a', displayOrder: 0 },+ { id: 'cso_222222222222222222222222', propertyDefinitionId: 'cpd_111111111111111111111111', name: 'B', key: 'b', displayOrder: 1 },+ ],+ });+ const customPropertiesOptionsRepository = createCustomPropertiesOptionsRepository({ db });++ await customPropertiesOptionsRepository.syncSelectOptions({+ propertyDefinitionId: 'cpd_111111111111111111111111',+ options: [],+ });++ expect(await getOptions({ db })).to.eql([]);+ });++ test('throws when an unknown option ID is provided', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_111111111111111111111111', name: 'Test Org' }],+ customPropertyDefinitions: [{+ id: 'cpd_111111111111111111111111',+ organizationId: 'org_111111111111111111111111',+ name: 'Status',+ type: CUSTOM_PROPERTY_TYPES.SELECT,+ key: 'status',+ }],+ });+ const customPropertiesOptionsRepository = createCustomPropertiesOptionsRepository({ db });++ await expect(+ customPropertiesOptionsRepository.syncSelectOptions({+ propertyDefinitionId: 'cpd_111111111111111111111111',+ options: [{ id: 'cso_nonexistent000000000000000', name: 'Ghost' }],+ }),+ ).rejects.toThrow(createCustomPropertySelectOptionUnknownIdError());+ });++ test('does not wipe existing options when a foreign ID is provided', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_111111111111111111111111', name: 'Test Org' }],+ customPropertyDefinitions: [{+ id: 'cpd_111111111111111111111111',+ organizationId: 'org_111111111111111111111111',+ name: 'Status',+ type: CUSTOM_PROPERTY_TYPES.SELECT,+ key: 'status',+ }],+ customPropertySelectOptions: [+ { id: 'cso_111111111111111111111111', propertyDefinitionId: 'cpd_111111111111111111111111', name: 'Safe', key: 'safe', displayOrder: 0 },+ ],+ });+ const customPropertiesOptionsRepository = createCustomPropertiesOptionsRepository({ db });++ await expect(+ customPropertiesOptionsRepository.syncSelectOptions({+ propertyDefinitionId: 'cpd_111111111111111111111111',+ options: [{ id: 'cso_nonexistent000000000000000', name: 'Attacker' }],+ }),+ ).rejects.toThrow(createCustomPropertySelectOptionUnknownIdError());++ expect(+ await getOptions({ db, withId: false }),+ ).to.eql([+ { propertyDefinitionId: 'cpd_111111111111111111111111', name: 'Safe', key: 'safe', displayOrder: 0 },+ ]);+ });+ });+});diff --git a/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.repository.ts b/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.repository.tsnew file mode 100644index 00000000..406b4b2b--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.repository.ts@@ -0,0 +1,129 @@+import type { BatchItem } from 'drizzle-orm/batch';+import type { Database } from '../../app/database/database.types';+import { injectArguments } from '@corentinth/chisels';+import { and, eq, inArray } from 'drizzle-orm';+import { generatePropertyKey } from '../custom-properties.repository.models';+import { createCustomPropertySelectOptionUnknownIdError } from './custom-properties-options.errors';+import { customPropertySelectOptionsTable } from './custom-properties-options.table';++export type CustomPropertiesOptionsRepository = ReturnType<typeof createCustomPropertiesOptionsRepository>;++export function createCustomPropertiesOptionsRepository({ db }: { db: Database }) {+ return injectArguments(+ {+ getSelectOption,+ getSelectOptions,+ syncSelectOptions,+ },+ { db },+ );+}++async function getSelectOption({ optionId, propertyDefinitionId, db}: { optionId: string; propertyDefinitionId: string; db: Database }) {+ const [option] = await db+ .select()+ .from(customPropertySelectOptionsTable)+ .where(+ and(+ eq(customPropertySelectOptionsTable.id, optionId),+ eq(customPropertySelectOptionsTable.propertyDefinitionId, propertyDefinitionId),+ ),+ );++ return {+ option,+ };+}++async function getSelectOptions({ optionsIds, propertyDefinitionId, db}: { optionsIds: string[]; propertyDefinitionId: string; db: Database }) {+ const options = await db+ .select()+ .from(customPropertySelectOptionsTable)+ .where(+ and(+ inArray(customPropertySelectOptionsTable.id, optionsIds),+ eq(customPropertySelectOptionsTable.propertyDefinitionId, propertyDefinitionId),+ ),+ );++ return {+ options,+ };+}++async function syncSelectOptions({ propertyDefinitionId, options, db }: {+ propertyDefinitionId: string;+ options: { id?: string; name: string }[];+ db: Database;+}) {+ const existingOptions = await db+ .select({ id: customPropertySelectOptionsTable.id })+ .from(customPropertySelectOptionsTable)+ .where(eq(customPropertySelectOptionsTable.propertyDefinitionId, propertyDefinitionId));++ const existingOptionIds = new Set(existingOptions.map(o => o.id));++ const optionsWithPositions = options.map((option, index) => ({ ...option, displayOrder: index }));++ const optionsToUpdate = optionsWithPositions.filter((option): option is { id: string; name: string; displayOrder: number } => option.id !== undefined);+ const optionsToCreate = optionsWithPositions.filter(option => option.id === undefined);++ const hasUnknownIds = optionsToUpdate.some(option => !existingOptionIds.has(option.id));++ if (hasUnknownIds) {+ throw createCustomPropertySelectOptionUnknownIdError();+ }++ const providedIds = new Set(optionsToUpdate.map(option => option.id));+ const optionsIdsToDelete = existingOptions.filter(existing => !providedIds.has(existing.id)).map(o => o.id);++ const hasUpdates = optionsToUpdate.length > 0;+ const hasCreates = optionsToCreate.length > 0;+ const hasDeletes = optionsIdsToDelete.length > 0;++ if (!hasUpdates && !hasCreates && !hasDeletes) {+ return;+ }++ await db.batch([+ ...optionsToUpdate.map(option =>+ db+ .update(customPropertySelectOptionsTable)+ .set({+ name: option.name,+ key: generatePropertyKey({ name: option.name }),+ displayOrder: option.displayOrder,+ })+ .where(+ and(+ eq(customPropertySelectOptionsTable.id, option.id),+ eq(customPropertySelectOptionsTable.propertyDefinitionId, propertyDefinitionId),+ ),+ ) as BatchItem<'sqlite'>,+ ),+ ...(hasCreates+ ? [+ db+ .insert(customPropertySelectOptionsTable)+ .values(optionsToCreate.map(option => ({+ propertyDefinitionId,+ name: option.name,+ key: generatePropertyKey({ name: option.name }),+ displayOrder: option.displayOrder,+ }))),+ ]+ : []),+ ...(hasDeletes+ ? [+ db+ .delete(customPropertySelectOptionsTable)+ .where(+ and(+ inArray(customPropertySelectOptionsTable.id, optionsIdsToDelete),+ eq(customPropertySelectOptionsTable.propertyDefinitionId, propertyDefinitionId),+ ),+ ),+ ]+ : []),+ ] as [BatchItem<'sqlite'>, ...BatchItem<'sqlite'>[]]);+}diff --git a/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.schemas.ts b/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.schemas.tsnew file mode 100644index 00000000..1f082957--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.schemas.ts@@ -0,0 +1,4 @@+import z from 'zod';+import { CUSTOM_PROPERTY_SELECT_OPTION_ID_REGEX } from './custom-properties-options.constants';++export const customPropertySelectOptionIdSchema = z.string().regex(CUSTOM_PROPERTY_SELECT_OPTION_ID_REGEX);diff --git a/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.table.ts b/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.table.tsnew file mode 100644index 00000000..a1db8384--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.table.ts@@ -0,0 +1,17 @@+import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';+import { createPrimaryKeyField, createTimestampColumns } from '../../shared/db/columns.helpers';+import { customPropertyDefinitionsTable } from '../custom-properties.table';+import { CUSTOM_PROPERTY_SELECT_OPTION_ID_PREFIX } from './custom-properties-options.constants';++export const customPropertySelectOptionsTable = sqliteTable(+ 'custom_property_select_options',+ {+ ...createPrimaryKeyField({ prefix: CUSTOM_PROPERTY_SELECT_OPTION_ID_PREFIX }),+ ...createTimestampColumns(),++ propertyDefinitionId: text('property_definition_id').notNull().references(() => customPropertyDefinitionsTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),+ name: text('name').notNull(),+ key: text('key').notNull(),+ displayOrder: integer('display_order').notNull().default(0),+ },+);diff --git a/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.usecases.ts b/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.usecases.tsnew file mode 100644index 00000000..5190fe02--- /dev/null+++ b/apps/papra-server/src/modules/custom-properties/options/custom-properties-options.usecases.ts@@ -0,0 +1,38 @@+import type { CustomPropertiesOptionsRepository } from './custom-properties-options.repository';+import { createCustomPropertySelectOptionNotFoundError } from './custom-properties-options.errors';++export async function ensureOptionExists({+ propertyDefinitionId,+ optionId,+ customPropertiesOptionsRepository,+}: {+ propertyDefinitionId: string;+ optionId: string;+ customPropertiesOptionsRepository: CustomPropertiesOptionsRepository;+}) {+ const { option } = await customPropertiesOptionsRepository.getSelectOption({ optionId, propertyDefinitionId });++ if (!option) {+ throw createCustomPropertySelectOptionNotFoundError();+ }+}++export async function ensureOptionsExist({+ propertyDefinitionId,+ optionIds,+ customPropertiesOptionsRepository,+}: {+ propertyDefinitionId: string;+ optionIds: string[];+ customPropertiesOptionsRepository: CustomPropertiesOptionsRepository;+}) {+ const { options } = await customPropertiesOptionsRepository.getSelectOptions({ optionsIds: optionIds, propertyDefinitionId });++ const existingOptionIds = new Set(options.map(option => option.id));++ for (const optionId of optionIds) {+ if (!existingOptionIds.has(optionId)) {+ throw createCustomPropertySelectOptionNotFoundError();+ }+ }+}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.tsindex cbd123e1..ff6b52fc 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@@ -456,54 +456,6 @@ describe('database-fts5 repository', () => {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', normalizedName: 'tag1', color: '#ff0000' },- { id: 'tag_2', organizationId: 'org_1', name: 'tag2', normalizedName: '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, documentsCount } = await documentsSearchRepository.searchOrganizationDocuments({- organizationId: 'org_1',- searchQuery: 'lorem',- pageIndex: 0,- pageSize: 10,- });-- expect(searchResults).to.have.length(2);- expect(documentsCount).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.tsindex 828b5654..2a2e6bc9 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,12 +1,9 @@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 { 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';@@ -34,48 +31,23 @@ async function searchOrganizationDocuments({ organizationId, searchQuery, pageIn.offset(pageIndex * pageSize).as('paginated_docs');- const [totalCountResult, documentsWithTags] = await Promise.all([+ const [totalCountResult, documents] = 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,+ .select({+ ...omit(getTableColumns(documentsTable), ['content']),}).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 documentsCount = totalCountResult[0]?.count ?? 0;- if (documentsWithTags.length === 0) {- return { documents: [], documentsCount };- }-- 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, documentsCount };}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.tsindex 491ce5d2..8f8a74b2 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@@ -9,6 +9,11 @@ export type DocumentSearchableData = {organizationId: string;};+export type DocumentSearchResult = {+ documents: Omit<Document, 'content'>[];+ documentsCount: number;+};+export type DocumentSearchServices = {name: string;searchDocuments: (args: {@@ -16,7 +21,7 @@ export type DocumentSearchServices = {organizationId: string;pageIndex: number;pageSize: number;- }) => Promise<{ documents: Omit<Document, 'content'>[]; documentsCount: number }>;+ }) => Promise<DocumentSearchResult>;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.models.ts b/apps/papra-server/src/modules/documents/documents.models.tsindex 3f6a998a..a6459e38 100644--- a/apps/papra-server/src/modules/documents/documents.models.ts+++ b/apps/papra-server/src/modules/documents/documents.models.ts@@ -30,17 +30,15 @@ export function isDocumentSizeLimitEnabled({ maxUploadSize }: { maxUploadSize: n}export function formatDocumentForApi<T extends PartialBy<DbSelectableDocument, 'content'>>({ document }: { document: T }) {- return {- ...omit(- document,- [- 'fileEncryptionAlgorithm',- 'fileEncryptionKeyWrapped',- 'fileEncryptionKekVersion',- 'originalStorageKey',- ],- ),- };+ return omit(+ document,+ [+ 'fileEncryptionAlgorithm',+ 'fileEncryptionKeyWrapped',+ 'fileEncryptionKekVersion',+ 'originalStorageKey',+ ],+ );}export function formatDocumentsForApi<T extends PartialBy<DbSelectableDocument, 'content'>>({ documents }: { documents: T[] }) {diff --git a/apps/papra-server/src/modules/documents/documents.repository.ts b/apps/papra-server/src/modules/documents/documents.repository.tsindex 365ab5b1..617ee19c 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, safely } from '@corentinth/chisels';-import { and, count, desc, eq, getTableColumns, lt, sql } from 'drizzle-orm';+import { and, count, desc, eq, inArray, lt, sql } from 'drizzle-orm';import { createIterator } from '../app/database/database.usecases';import { createOrganizationNotFoundError } from '../organizations/organizations.errors';import { subDays } from '../shared/date';@@ -9,7 +9,6 @@ import { isUniqueConstraintError } from '../shared/db/constraints.models';import { withPagination } from '../shared/db/pagination';import { createError } from '../shared/errors/errors';import { isDefined, isNil, omitUndefined } from '../shared/utils';-import { documentsTagsTable, tagsTable } from '../tags/tags.table';import { createDocumentAlreadyExistsError, createDocumentNotFoundError } from './documents.errors';import { documentsTable } from './documents.table';@@ -34,6 +33,7 @@ export function createDocumentsRepository({ db }: { db: Database }) {getAllOrganizationUndeletedDocumentsIterator,updateDocument,getGlobalDocumentsStats,+ getDocumentsByIds,},{ db },);@@ -126,6 +126,24 @@ async function getOrganizationDeletedDocuments({ organizationId, pageIndex, page};}+async function getDocumentsByIds({ documentIds, organizationId, db }: { documentIds: string[]; organizationId: string; db: Database }) {+ if (documentIds.length === 0) {+ return { documents: [] };+ }++ const documents = await db+ .select({ id: documentsTable.id })+ .from(documentsTable)+ .where(+ and(+ inArray(documentsTable.id, documentIds),+ eq(documentsTable.organizationId, organizationId),+ ),+ );++ return { documents };+}+async function getDocumentById({ documentId, organizationId, db }: { documentId: string; organizationId: string; db: Database }) {const [document] = await db.select()@@ -137,24 +155,7 @@ async function getDocumentById({ documentId, organizationId, db }: { documentId:),);- if (!document) {- return { document: undefined };- }-- const tags = await db- .select({- ...getTableColumns(tagsTable),- })- .from(documentsTagsTable)- .leftJoin(tagsTable, eq(tagsTable.id, documentsTagsTable.tagId))- .where(eq(documentsTagsTable.documentId, documentId));-- return {- document: {- ...document,- tags,- },- };+ return { document };}async function softDeleteDocument({ documentId, organizationId, userId, db, now = new Date() }: { documentId: string; organizationId: string; userId: string; db: Database; now?: Date }) {diff --git a/apps/papra-server/src/modules/documents/documents.routes.ts b/apps/papra-server/src/modules/documents/documents.routes.tsindex d94a89ce..653a5e34 100644--- a/apps/papra-server/src/modules/documents/documents.routes.ts+++ b/apps/papra-server/src/modules/documents/documents.routes.ts@@ -3,6 +3,7 @@ import { Readable } from 'node:stream';import { z } from 'zod';import { requireAuthentication } from '../app/auth/auth.middleware';import { getUser } from '../app/auth/auth.models';+import { createCustomPropertiesRepository } from '../custom-properties/custom-properties.repository';import { organizationIdSchema } from '../organizations/organization.schemas';import { createOrganizationsRepository } from '../organizations/organizations.repository';import { ensureUserIsInOrganization } from '../organizations/organizations.usecases';@@ -11,12 +12,13 @@ import { getOrganizationPlan } from '../plans/plans.usecases';import { getFileStreamFromMultipartForm } from '../shared/streams/file-upload';import { validateJsonBody, validateParams, validateQuery } from '../shared/validation/validation';import { createSubscriptionsRepository } from '../subscriptions/subscriptions.repository';+import { createTagsRepository } from '../tags/tags.repository';import { searchOrganizationDocuments } from './document-search/document-search.usecase';import { createDocumentIsNotDeletedError } from './documents.errors';import { formatDocumentForApi, formatDocumentsForApi, isDocumentSizeLimitEnabled } from './documents.models';import { createDocumentsRepository } from './documents.repository';import { documentIdSchema } from './documents.schemas';-import { createDocumentCreationUsecase, deleteAllTrashDocuments, deleteTrashDocument, ensureDocumentExists, getDocumentOrThrow, restoreDocument, trashDocument, updateDocument } from './documents.usecases';+import { createDocumentCreationUsecase, deleteAllTrashDocuments, deleteTrashDocument, enrichAndFormatDocumentForApi, enrichAndFormatDocumentsForApi, ensureDocumentExists, getDocumentOrThrow, restoreDocument, trashDocument, updateDocument } from './documents.usecases';export function registerDocumentsRoutes(context: RouteDefinitionContext) {setupCreateDocumentRoute(context);@@ -125,14 +127,15 @@ function setupGetDocumentRoute({ app, db }: RouteDefinitionContext) {const documentsRepository = createDocumentsRepository({ db });const organizationsRepository = createOrganizationsRepository({ db });+ const customPropertiesRepository = createCustomPropertiesRepository({ db });+ const tagsRepository = createTagsRepository({ db });await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });const { document } = await getDocumentOrThrow({ documentId, organizationId, documentsRepository });+ const { enrichedDocument } = await enrichAndFormatDocumentForApi({ document, tagsRepository, customPropertiesRepository });- return context.json({- document: formatDocumentForApi({ document }),- });+ return context.json({ document: enrichedDocument });},);}@@ -273,21 +276,15 @@ function setupGetDocumentsRoute({ app, db, documentSearchServices }: RouteDefiniconst { searchQuery, pageIndex, pageSize } = context.req.valid('query');const organizationsRepository = createOrganizationsRepository({ db });+ const customPropertiesRepository = createCustomPropertiesRepository({ db });+ const tagsRepository = createTagsRepository({ db });await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });- const { documents, documentsCount } = await searchOrganizationDocuments({- organizationId,- searchQuery,- pageIndex,- pageSize,- documentSearchServices,- });+ const { documents, documentsCount } = await searchOrganizationDocuments({ organizationId, searchQuery, pageIndex, pageSize, documentSearchServices });+ const { enrichedDocuments } = await enrichAndFormatDocumentsForApi({ documents, tagsRepository, customPropertiesRepository });- return context.json({- documents: formatDocumentsForApi({ documents }),- documentsCount,- });+ return context.json({ documents: enrichedDocuments, documentsCount });},);}diff --git a/apps/papra-server/src/modules/documents/documents.usecases.test.ts b/apps/papra-server/src/modules/documents/documents.usecases.test.tsindex e80cb99d..aef90c01 100644--- a/apps/papra-server/src/modules/documents/documents.usecases.test.ts+++ b/apps/papra-server/src/modules/documents/documents.usecases.test.ts@@ -4,6 +4,7 @@ import { describe, expect, test } from 'vitest';import { createInMemoryDatabase } from '../app/database/database.test-utils';import { createTestEventServices } from '../app/events/events.test-utils';import { overrideConfig } from '../config/config.test-utils';+import { createCustomPropertiesRepository } from '../custom-properties/custom-properties.repository';import { ORGANIZATION_ROLES } from '../organizations/organizations.constants';import { createOrganizationDocumentStorageLimitReachedError } from '../organizations/organizations.errors';import { createDeterministicIdGenerator } from '../shared/random/ids';@@ -17,7 +18,14 @@ import { createDocumentActivityRepository } from './document-activity/document-aimport { createDocumentAlreadyExistsError, createDocumentSizeTooLargeError } from './documents.errors';import { createDocumentsRepository } from './documents.repository';import { documentsTable } from './documents.table';-import { createDocumentCreationUsecase, extractAndSaveDocumentFileContent, restoreDocument, trashDocument, updateDocument } from './documents.usecases';+import {+ createDocumentCreationUsecase,+ enrichAndFormatDocumentsForApi,+ extractAndSaveDocumentFileContent,+ restoreDocument,+ trashDocument,+ updateDocument,+} from './documents.usecases';import { createDocumentStorageService } from './storage/documents.storage.services';import { createInMemoryDocumentStorageServices } from './storage/documents.storage.services.test-utils';@@ -876,6 +884,154 @@ describe('documents usecases', () => {});});+ describe('enrichDocumentsForApi', () => {+ const baseDocument = {+ organizationId: 'org-1',+ mimeType: 'text/plain',+ originalStorageKey: 'org-1/originals/doc-1.txt',+ name: 'file.txt',+ originalName: 'file.txt',+ originalSha256Hash: 'hash',+ };++ test('returns an empty array when given no documents', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org-1', name: 'Organization 1' }],+ });++ const { enrichedDocuments } = await enrichAndFormatDocumentsForApi({+ documents: [],+ tagsRepository: createTagsRepository({ db }),+ customPropertiesRepository: createCustomPropertiesRepository({ db }),+ });++ expect(enrichedDocuments).to.eql([]);+ });++ test('strips sensitive storage and encryption fields', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org-1', name: 'Organization 1' }],+ documents: [{ id: 'doc-1', ...baseDocument, fileEncryptionAlgorithm: 'aes-256-gcm', fileEncryptionKeyWrapped: 'wrapped-key', fileEncryptionKekVersion: 'v1' }],+ });++ const { document } = await createDocumentsRepository({ db }).getDocumentById({ documentId: 'doc-1', organizationId: 'org-1' });++ const { enrichedDocuments: [enrichedDocument] } = await enrichAndFormatDocumentsForApi({+ documents: [document!],+ tagsRepository: createTagsRepository({ db }),+ customPropertiesRepository: createCustomPropertiesRepository({ db }),+ });++ expect(enrichedDocument).not.to.have.property('originalStorageKey');+ expect(enrichedDocument).not.to.have.property('fileEncryptionAlgorithm');+ expect(enrichedDocument).not.to.have.property('fileEncryptionKeyWrapped');+ expect(enrichedDocument).not.to.have.property('fileEncryptionKekVersion');+ });++ test('a document with no tags gets an empty tags array', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org-1', name: 'Organization 1' }],+ documents: [{ id: 'doc-1', ...baseDocument }],+ });++ const { document } = await createDocumentsRepository({ db }).getDocumentById({ documentId: 'doc-1', organizationId: 'org-1' });+ const { enrichedDocuments: [enrichedDocument] } = await enrichAndFormatDocumentsForApi({+ documents: [document!],+ tagsRepository: createTagsRepository({ db }),+ customPropertiesRepository: createCustomPropertiesRepository({ db }),+ });++ expect(enrichedDocument!.tags).to.eql([]);+ });++ test('tags are attached to the correct document', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org-1', name: 'Organization 1' }],+ documents: [+ { id: 'doc-1', ...baseDocument },+ { id: 'doc-2', ...baseDocument, originalSha256Hash: 'hash2' },+ ],+ tags: [+ { id: 'tag-1', organizationId: 'org-1', name: 'Urgent', normalizedName: 'urgent', color: '#ff0000' },+ { id: 'tag-2', organizationId: 'org-1', name: 'Finance', normalizedName: 'finance', color: '#00ff00' },+ ],+ documentsTags: [+ { documentId: 'doc-1', tagId: 'tag-1' },+ { documentId: 'doc-1', tagId: 'tag-2' },+ // doc-2 has no tags+ ],+ });++ const documentsRepository = createDocumentsRepository({ db });+ const { document: doc1 } = await documentsRepository.getDocumentById({ documentId: 'doc-1', organizationId: 'org-1' });+ const { document: doc2 } = await documentsRepository.getDocumentById({ documentId: 'doc-2', organizationId: 'org-1' });++ const { enrichedDocuments } = await enrichAndFormatDocumentsForApi({+ documents: [doc1!, doc2!],+ tagsRepository: createTagsRepository({ db }),+ customPropertiesRepository: createCustomPropertiesRepository({ db }),+ });++ expect(enrichedDocuments[0]!.tags.map(t => t.id).toSorted()).to.eql(['tag-1', 'tag-2']);+ expect(enrichedDocuments[1]!.tags).to.eql([]);+ });++ test('a defined custom property with no value set appears as null', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org-1', name: 'Organization 1' }],+ documents: [{ id: 'doc-1', ...baseDocument }],+ customPropertyDefinitions: [+ { id: 'cpd-1', organizationId: 'org-1', name: 'Note', key: 'note', type: 'text' },+ ],+ });++ const { document } = await createDocumentsRepository({ db }).getDocumentById({ documentId: 'doc-1', organizationId: 'org-1' });+ const { enrichedDocuments: [enrichedDocument] } = await enrichAndFormatDocumentsForApi({+ documents: [document!],+ tagsRepository: createTagsRepository({ db }),+ customPropertiesRepository: createCustomPropertiesRepository({ db }),+ });++ expect(enrichedDocument!.customProperties).to.eql([+ { key: 'note', name: 'Note', type: 'text', displayOrder: 0, value: null },+ ]);+ });++ test('custom property values are attached to the correct document', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org-1', name: 'Organization 1' }],+ documents: [+ { id: 'doc-1', ...baseDocument },+ { id: 'doc-2', ...baseDocument, originalSha256Hash: 'hash2' },+ ],+ customPropertyDefinitions: [+ { id: 'cpd-1', organizationId: 'org-1', name: 'Note', key: 'note', type: 'text' },+ ],+ documentCustomPropertyValues: [+ { id: 'dcpv-1', documentId: 'doc-1', propertyDefinitionId: 'cpd-1', textValue: 'important' },+ // doc-2 has no value for this property+ ],+ });++ const documentsRepository = createDocumentsRepository({ db });+ const { document: doc1 } = await documentsRepository.getDocumentById({ documentId: 'doc-1', organizationId: 'org-1' });+ const { document: doc2 } = await documentsRepository.getDocumentById({ documentId: 'doc-2', organizationId: 'org-1' });++ const { enrichedDocuments } = await enrichAndFormatDocumentsForApi({+ documents: [doc1!, doc2!],+ tagsRepository: createTagsRepository({ db }),+ customPropertiesRepository: createCustomPropertiesRepository({ db }),+ });++ expect(enrichedDocuments[0]!.customProperties).to.eql([+ { key: 'note', name: 'Note', type: 'text', displayOrder: 0, value: 'important' },+ ]);+ expect(enrichedDocuments[1]!.customProperties).to.eql([+ { key: 'note', name: 'Note', type: 'text', displayOrder: 0, value: null },+ ]);+ });+ });+describe('updateDocument', () => {test('when a document is updated, a "document.updated" event is triggered', async () => {const { db } = await createInMemoryDatabase({diff --git a/apps/papra-server/src/modules/documents/documents.usecases.ts b/apps/papra-server/src/modules/documents/documents.usecases.tsindex 48806d0a..8fa8e7b3 100644--- a/apps/papra-server/src/modules/documents/documents.usecases.ts+++ b/apps/papra-server/src/modules/documents/documents.usecases.ts@@ -1,7 +1,9 @@+import type { PartialBy } from '@corentinth/chisels';import type { Readable } from 'node:stream';import type { Database } from '../app/database/database.types';import type { EventServices } from '../app/events/events.services';import type { Config } from '../config/config.types';+import type { CustomPropertiesRepository } from '../custom-properties/custom-properties.repository';import type { PlansRepository } from '../plans/plans.repository';import type { Logger } from '../shared/logger/logger';import type { SubscriptionsRepository } from '../subscriptions/subscriptions.repository';@@ -19,9 +21,11 @@ import { PassThrough } from 'node:stream';import { pipeline } from 'node:stream/promises';import { safely } from '@corentinth/chisels';import pLimit from 'p-limit';+import { buildCustomPropertiesArray } from '../custom-properties/custom-properties.models';import { createOrganizationDocumentStorageLimitReachedError } from '../organizations/organizations.errors';import { getOrganizationStorageLimits } from '../organizations/organizations.usecases';import { createPlansRepository } from '../plans/plans.repository';+import { createError } from '../shared/errors/errors';import { createLogger } from '../shared/logger/logger';import { createByteCounter } from '../shared/streams/byte-counter';import { createSha256HashTransformer } from '../shared/streams/stream-hash';@@ -34,7 +38,7 @@ import { createTagsRepository } from '../tags/tags.repository';import { createWebhookRepository } from '../webhooks/webhook.repository';import { createDocumentActivityRepository } from './document-activity/document-activity.repository';import { createDocumentAlreadyExistsError, createDocumentNotDeletedError, createDocumentNotFoundError, createDocumentSizeTooLargeError } from './documents.errors';-import { generateDocumentId as generateDocumentIdImpl } from './documents.models';+import { formatDocumentForApi, generateDocumentId as generateDocumentIdImpl } from './documents.models';import { createDocumentsRepository } from './documents.repository';import { extractDocumentText } from './documents.services';import { createStorageKey } from './storage/document-storage.usecases';@@ -589,6 +593,84 @@ export async function restoreDocument({});}+export async function enrichAndFormatDocumentsForApi({+ documents,+ tagsRepository,+ customPropertiesRepository,+}: {+ documents: Array<PartialBy<Document, 'content'>>;+ tagsRepository: TagsRepository;+ customPropertiesRepository: CustomPropertiesRepository;+}) {+ if (documents.length === 0) {+ return { enrichedDocuments: [] };+ }++ const { organizationId } = documents[0] ?? {};++ if (isNil(organizationId)) {+ throw createError({+ message: 'Organization ID is required to enrich documents',+ code: 'organization_id_required',+ statusCode: 500,+ });+ }++ const uniqueOrganizationIds = new Set(documents.map(d => d.organizationId));++ if (uniqueOrganizationIds.size > 1) {+ throw createError({+ message: 'All documents must belong to the same organization to be enriched',+ code: 'multiple_organization_ids',+ statusCode: 500,+ });+ }++ const documentIds = documents.map(d => d.id);++ const [{ tagsByDocumentId }, { valuesByDocumentId }, { propertyDefinitions }] = await Promise.all([+ tagsRepository.getTagsByDocumentIds({ documentIds }),+ customPropertiesRepository.getCustomPropertyValuesByDocumentIds({ documentIds }),+ customPropertiesRepository.getOrganizationPropertyDefinitions({ organizationId }),+ ]);++ return {+ enrichedDocuments: documents.map(document => ({+ ...formatDocumentForApi({ document }),+ tags: tagsByDocumentId[document.id] ?? [],+ customProperties: buildCustomPropertiesArray({+ rawValues: valuesByDocumentId[document.id] ?? [],+ propertyDefinitions,+ }),+ })),+ };+}++export async function enrichAndFormatDocumentForApi({+ document,+ tagsRepository,+ customPropertiesRepository,+}: {+ document: PartialBy<Document, 'content'>;+ tagsRepository: TagsRepository;+ customPropertiesRepository: CustomPropertiesRepository;+}) {+ const { enrichedDocuments } = await enrichAndFormatDocumentsForApi({ documents: [document], tagsRepository, customPropertiesRepository });++ const [enrichedDocument] = enrichedDocuments;++ if (!enrichedDocument) {+ // This should never happen, but for type safety+ throw createError({+ message: 'Document enrichment failed',+ code: 'document_enrichment_failed',+ statusCode: 500,+ });+ }++ return { enrichedDocument };+}+export async function updateDocument({documentId,organizationId,diff --git a/apps/papra-server/src/modules/documents/e2e/upload-documents.e2e.test.ts b/apps/papra-server/src/modules/documents/e2e/upload-documents.e2e.test.tsindex 9f0eda9c..91b5e3b5 100644--- a/apps/papra-server/src/modules/documents/e2e/upload-documents.e2e.test.ts+++ b/apps/papra-server/src/modules/documents/e2e/upload-documents.e2e.test.ts@@ -64,7 +64,7 @@ describe('documents e2e', () => {expect(getDocumentResponse.status).to.eql(200);const { document: retrievedDocument } = (await getDocumentResponse.json()) as { document: Document };- expect(retrievedDocument).to.eql({ ...document, tags: [] });+ expect(retrievedDocument).to.eql({ ...document, tags: [], customProperties: [] });// Retrieve the document fileconst getDocumentFileResponse = await app.request(@@ -245,7 +245,7 @@ describe('documents e2e', () => {expect(getDocumentResponse.status).to.eql(200);const { document: retrievedDocument } = (await getDocumentResponse.json()) as { document: Document };- expect(retrievedDocument).to.eql({ ...document, tags: [] });+ expect(retrievedDocument).to.eql({ ...document, tags: [], customProperties: [] });}});diff --git a/apps/papra-server/src/modules/tags/tags.repository.ts b/apps/papra-server/src/modules/tags/tags.repository.tsindex e6035204..20ae8772 100644--- a/apps/papra-server/src/modules/tags/tags.repository.ts+++ b/apps/papra-server/src/modules/tags/tags.repository.ts@@ -1,6 +1,7 @@import type { Database } from '../app/database/database.types';+import type { Tag } from './tags.types';import { injectArguments, safely } from '@corentinth/chisels';-import { and, count, desc, eq, getTableColumns, sql } from 'drizzle-orm';+import { and, count, desc, eq, getTableColumns, inArray, sql } from 'drizzle-orm';import { get } from 'lodash-es';import { documentsTable } from '../documents/documents.table';import { isUniqueConstraintError } from '../shared/db/constraints.models';@@ -17,6 +18,7 @@ export function createTagsRepository({ db }: { db: Database }) {getOrganizationTags,getOrganizationTagsCount,getTagById,+ getTagsByDocumentIds,createTag,deleteTag,updateTag,@@ -54,6 +56,29 @@ async function getOrganizationTagsCount({ organizationId, db }: { organizationIdreturn { tagsCount: result?.tagsCount ?? 0 };}+async function getTagsByDocumentIds({ documentIds, db }: { documentIds: string[]; db: Database }): Promise<{ tagsByDocumentId: Record<string, Tag[]> }> {+ if (documentIds.length === 0) {+ return { tagsByDocumentId: {} };+ }++ const rows = await db+ .select({+ documentId: documentsTagsTable.documentId,+ ...getTableColumns(tagsTable),+ })+ .from(documentsTagsTable)+ .innerJoin(tagsTable, eq(tagsTable.id, documentsTagsTable.tagId))+ .where(inArray(documentsTagsTable.documentId, documentIds));++ const tagsByDocumentId: Record<string, Tag[]> = {};++ for (const { documentId, ...tag } of rows) {+ (tagsByDocumentId[documentId] ??= []).push(tag);+ }++ return { tagsByDocumentId };+}+async function getTagById({ tagId, organizationId, db }: { tagId: string; organizationId: string; db: Database }) {const [tag] = await db.select()