Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(tagging-rules): added documents auto tagging rules (#200)

Corentin Thomasset2bbb68aa17b8
diff --git a/apps/papra-client/src/locales/en.yml b/apps/papra-client/src/locales/en.yml
index 78f2a93d..7471424c 100644
--- a/apps/papra-client/src/locales/en.yml
+++ b/apps/papra-client/src/locales/en.yml
@@ -24,10 +24,80 @@ layout:
home: Home
documents: Documents
tags: Tags
+ tagging-rules: Tagging rules
integrations: Integrations
deleted-documents: Deleted documents
organization-settings: Organization settings
+tagging-rules:
+ field:
+ name: document name
+ content: document content
+ operator:
+ equals: equals
+ not-equals: not equals
+ contains: contains
+ not-contains: not contains
+ starts-with: starts with
+ ends-with: ends with
+ list:
+ title: Tagging rules
+ description: Manage your organization's tagging rules, to automatically tag documents based on conditions you define.
+ demo-warning: 'Note: As this is a demo environment (with no server), tagging rules will not be applied to newly added documents.'
+ no-tagging-rules:
+ title: No tagging rules
+ description: Create a tagging rule to automatically tag your added documents based on conditions you define.
+ create-tagging-rule: Create tagging rule
+ card:
+ no-conditions: No conditions
+ one-condition: 1 condition
+ conditions: '{{ count }} conditions'
+ delete: Delete rule
+ edit: Edit rule
+ create:
+ title: Create tagging rule
+ success: Tagging rule created successfully
+ error: Failed to create tagging rule
+ submit: Create rule
+ form:
+ name:
+ label: Name
+ placeholder: 'Example: Tag invoices'
+ min-length: Please enter a name for the rule
+ max-length: The name must be less than 64 characters
+ description:
+ label: Description
+ placeholder: 'Example: Tag documents with "invoice" in the name'
+ max-length: The description must be less than 256 characters
+ conditions:
+ label: Conditions
+ description: Define the conditions that must be met for the rule to apply. All conditions must be met for the rule to apply.
+ add-condition: Add condition
+ no-conditions:
+ title: No conditions
+ description: You didn't add any conditions to this rule. This rule will apply its tags to all documents.
+ confirm: Apply rule without conditions
+ cancel: Cancel
+ field:
+ label: Field
+ operator:
+ label: Operator
+ value:
+ label: Value
+ placeholder: 'Example: invoice'
+ min-length: Please enter a value for the condition
+ tags:
+ label: Tags
+ description: Select the tags to apply to the added documents that match the conditions
+ min-length: At least one tag to apply is required
+ add-tag: Create tag
+ submit: Create rule
+ update:
+ title: Update tagging rule
+ success: Tagging rule updated successfully
+ error: Failed to update tagging rule
+ submit: Update rule
+ cancel: Cancel
demo:
popup:
description: This is a demo environment, all data is save to your browser local storage.
diff --git a/apps/papra-client/src/modules/demo/demo-api-mock.ts b/apps/papra-client/src/modules/demo/demo-api-mock.ts
index 2833b30b..68a47222 100644
--- a/apps/papra-client/src/modules/demo/demo-api-mock.ts
+++ b/apps/papra-client/src/modules/demo/demo-api-mock.ts
@@ -2,7 +2,7 @@ import { get } from 'lodash-es';
import { FetchError } from 'ofetch';
import { createRouter } from 'radix3';
import { defineHandler } from './demo-api-mock.models';
-import { documentFileStorage, documentStorage, organizationStorage, tagDocumentStorage, tagStorage } from './demo.storage';
+import { documentFileStorage, documentStorage, organizationStorage, tagDocumentStorage, taggingRuleStorage, tagStorage } from './demo.storage';
import { findMany, getValues } from './demo.storage.models';
function assert(condition: unknown, { message = 'Error', status }: { message?: string; status?: number } = {}): asserts condition {
@@ -457,6 +457,70 @@ const inMemoryApiMock: Record<string, { handler: any }> = {
},
}),
+ ...defineHandler({
+ path: '/api/organizations/:organizationId/tagging-rules',
+ method: 'GET',
+ handler: async ({ params: { organizationId } }) => {
+ const taggingRules = await findMany(taggingRuleStorage, taggingRule => taggingRule.organizationId === organizationId);
+
+ return { taggingRules };
+ },
+ }),
+
+ ...defineHandler({
+ path: '/api/organizations/:organizationId/tagging-rules',
+ method: 'POST',
+ handler: async ({ params: { organizationId }, body }) => {
+ const taggingRule = {
+ id: `tr_${Math.random().toString(36).slice(2)}`,
+ organizationId,
+ name: get(body, 'name'),
+ description: get(body, 'description'),
+ conditions: get(body, 'conditions'),
+ actions: get(body, 'tagIds').map((tagId: string) => ({ tagId })),
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ };
+
+ await taggingRuleStorage.setItem(taggingRule.id, taggingRule);
+
+ return { taggingRule };
+ },
+ }),
+
+ ...defineHandler({
+ path: '/api/organizations/:organizationId/tagging-rules/:taggingRuleId',
+ method: 'GET',
+ handler: async ({ params: { taggingRuleId } }) => {
+ const taggingRule = await taggingRuleStorage.getItem(taggingRuleId);
+
+ assert(taggingRule, { status: 404 });
+
+ return { taggingRule };
+ },
+ }),
+
+ ...defineHandler({
+ path: '/api/organizations/:organizationId/tagging-rules/:taggingRuleId',
+ method: 'DELETE',
+ handler: async ({ params: { taggingRuleId } }) => {
+ await taggingRuleStorage.removeItem(taggingRuleId);
+ },
+ }),
+
+ ...defineHandler({
+ path: '/api/organizations/:organizationId/tagging-rules/:taggingRuleId',
+ method: 'PUT',
+ handler: async ({ params: { taggingRuleId }, body }) => {
+ const taggingRule = await taggingRuleStorage.getItem(taggingRuleId);
+
+ assert(taggingRule, { status: 404 });
+
+ await taggingRuleStorage.setItem(taggingRuleId, Object.assign(taggingRule, body, { updatedAt: new Date() }));
+
+ return { taggingRule };
+ },
+ }),
};
export const router = createRouter({ routes: inMemoryApiMock, strictTrailingSlash: false });
diff --git a/apps/papra-client/src/modules/demo/demo.storage.ts b/apps/papra-client/src/modules/demo/demo.storage.ts
index fae92201..fd361b27 100644
--- a/apps/papra-client/src/modules/demo/demo.storage.ts
+++ b/apps/papra-client/src/modules/demo/demo.storage.ts
@@ -1,5 +1,6 @@
import type { Document } from '../documents/documents.types';
import type { Organization } from '../organizations/organizations.types';
+import type { TaggingRule } from '../tagging-rules/tagging-rules.types';
import type { Tag } from '../tags/tags.types';
import { createStorage, prefixStorage } from 'unstorage';
import localStorageDriver from 'unstorage/drivers/localstorage';
@@ -14,6 +15,7 @@ export const documentStorage = prefixStorage<Document>(storage, 'documents');
export const documentFileStorage = prefixStorage(storage, 'documentFiles');
export const tagStorage = prefixStorage<Omit<Tag, 'documentsCount'>>(storage, 'tags');
export const tagDocumentStorage = prefixStorage<{ documentId: string; tagId: string; id: string }>(storage, 'tagDocuments');
+export const taggingRuleStorage = prefixStorage<TaggingRule>(storage, 'taggingRules');
export async function clearDemoStorage() {
await storage.clear();
diff --git a/apps/papra-client/src/modules/documents/pages/document.page.tsx b/apps/papra-client/src/modules/documents/pages/document.page.tsx
index f5bc4b9b..cb725765 100644
--- a/apps/papra-client/src/modules/documents/pages/document.page.tsx
+++ b/apps/papra-client/src/modules/documents/pages/document.page.tsx
@@ -138,8 +138,7 @@ export const DocumentPage: Component = () => {
<DocumentTagPicker
organizationId={params.organizationId}
- documentId={params.documentId}
- tags={getDocument().tags}
+ tagIds={getDocument().tags.map(tag => tag.id)}
onTagAdded={async ({ tag }) => {
await addTagToDocument({
documentId: params.documentId,
diff --git a/apps/papra-client/src/modules/i18n/locales.types.ts b/apps/papra-client/src/modules/i18n/locales.types.ts
index 521b0d78..bd2eef13 100644
--- a/apps/papra-client/src/modules/i18n/locales.types.ts
+++ b/apps/papra-client/src/modules/i18n/locales.types.ts
@@ -1,2 +1,2 @@
// Dynamically generated file. Use "pnpm script:generate-i18n-types" to update.
-export type LocaleKeys = 'auth.login.title' | 'auth.login.description' | 'auth.login.login-with-provider' | 'auth.login.no-account' | 'auth.login.register' | 'auth.email-validation-required.title' | 'auth.email-validation-required.description' | 'auth.legal-links.description' | 'auth.legal-links.terms' | 'auth.legal-links.privacy' | 'tags.no-tags.title' | 'tags.no-tags.description' | 'tags.no-tags.create-tag' | 'layout.menu.home' | 'layout.menu.documents' | 'layout.menu.tags' | 'layout.menu.integrations' | 'layout.menu.deleted-documents' | 'layout.menu.organization-settings' | 'demo.popup.description' | 'demo.popup.discord' | 'demo.popup.discord-link-label' | 'demo.popup.reset' | 'demo.popup.hide';
+export type LocaleKeys = 'auth.login.title' | 'auth.login.description' | 'auth.login.login-with-provider' | 'auth.login.no-account' | 'auth.login.register' | 'auth.email-validation-required.title' | 'auth.email-validation-required.description' | 'auth.legal-links.description' | 'auth.legal-links.terms' | 'auth.legal-links.privacy' | 'tags.no-tags.title' | 'tags.no-tags.description' | 'tags.no-tags.create-tag' | 'layout.menu.home' | 'layout.menu.documents' | 'layout.menu.tags' | 'layout.menu.tagging-rules' | 'layout.menu.integrations' | 'layout.menu.deleted-documents' | 'layout.menu.organization-settings' | 'tagging-rules.field.name' | 'tagging-rules.field.content' | 'tagging-rules.operator.equals' | 'tagging-rules.operator.not-equals' | 'tagging-rules.operator.contains' | 'tagging-rules.operator.not-contains' | 'tagging-rules.operator.starts-with' | 'tagging-rules.operator.ends-with' | 'tagging-rules.list.title' | 'tagging-rules.list.description' | 'tagging-rules.list.demo-warning' | 'tagging-rules.list.no-tagging-rules.title' | 'tagging-rules.list.no-tagging-rules.description' | 'tagging-rules.list.no-tagging-rules.create-tagging-rule' | 'tagging-rules.list.card.no-conditions' | 'tagging-rules.list.card.one-condition' | 'tagging-rules.list.card.conditions' | 'tagging-rules.list.card.delete' | 'tagging-rules.list.card.edit' | 'tagging-rules.create.title' | 'tagging-rules.create.success' | 'tagging-rules.create.error' | 'tagging-rules.create.submit' | 'tagging-rules.form.name.label' | 'tagging-rules.form.name.placeholder' | 'tagging-rules.form.name.min-length' | 'tagging-rules.form.name.max-length' | 'tagging-rules.form.description.label' | 'tagging-rules.form.description.placeholder' | 'tagging-rules.form.description.max-length' | 'tagging-rules.form.conditions.label' | 'tagging-rules.form.conditions.description' | 'tagging-rules.form.conditions.add-condition' | 'tagging-rules.form.conditions.no-conditions.title' | 'tagging-rules.form.conditions.no-conditions.description' | 'tagging-rules.form.conditions.no-conditions.confirm' | 'tagging-rules.form.conditions.no-conditions.cancel' | 'tagging-rules.form.conditions.field.label' | 'tagging-rules.form.conditions.operator.label' | 'tagging-rules.form.conditions.value.label' | 'tagging-rules.form.conditions.value.placeholder' | 'tagging-rules.form.conditions.value.min-length' | 'tagging-rules.form.tags.label' | 'tagging-rules.form.tags.description' | 'tagging-rules.form.tags.min-length' | 'tagging-rules.form.tags.add-tag' | 'tagging-rules.form.submit' | 'tagging-rules.update.title' | 'tagging-rules.update.success' | 'tagging-rules.update.error' | 'tagging-rules.update.submit' | 'tagging-rules.update.cancel' | 'demo.popup.description' | 'demo.popup.discord' | 'demo.popup.discord-link-label' | 'demo.popup.reset' | 'demo.popup.hide';
diff --git a/apps/papra-client/src/modules/shared/form/form.ts b/apps/papra-client/src/modules/shared/form/form.ts
index 0dcf2e04..34e6b3d1 100644
--- a/apps/papra-client/src/modules/shared/form/form.ts
+++ b/apps/papra-client/src/modules/shared/form/form.ts
@@ -1,6 +1,6 @@
-import type { FormProps, PartialValues } from '@modular-forms/solid';
+import type { FormErrors, FormProps, PartialValues } from '@modular-forms/solid';
import type * as v from 'valibot';
-import { createForm as createModularForm, valiForm } from '@modular-forms/solid';
+import { createForm as createModularForm, FormError, valiForm } from '@modular-forms/solid';
import { createHook } from '../hooks/hooks';
export function createForm<Schema extends v.ObjectSchema<any, any>>({
@@ -18,7 +18,7 @@ export function createForm<Schema extends v.ObjectSchema<any, any>>({
submitHook.on(onSubmit);
}
- const [form, { Form, Field }] = createModularForm<v.InferInput<Schema>>({
+ const [form, { Form, Field, FieldArray }] = createModularForm<v.InferInput<Schema>>({
validate: valiForm(schema),
initialValues,
});
@@ -27,7 +27,9 @@ export function createForm<Schema extends v.ObjectSchema<any, any>>({
form,
Form: (props: Omit<FormProps<v.InferInput<Schema>, undefined>, 'of'>) => Form({ ...props, onSubmit: submitHook.trigger }),
Field,
+ FieldArray,
onSubmit: submitHook.on,
submit: submitHook.trigger,
+ createFormError: ({ message, fields }: { message: string; fields?: FormErrors<v.InferInput<Schema>> }) => new FormError<v.InferInput<Schema>>(message, fields),
};
}
diff --git a/apps/papra-client/src/modules/tagging-rules/components/tagging-rule-form.component.tsx b/apps/papra-client/src/modules/tagging-rules/components/tagging-rule-form.component.tsx
new file mode 100644
index 00000000..e44612a8
--- /dev/null
+++ b/apps/papra-client/src/modules/tagging-rules/components/tagging-rule-form.component.tsx
@@ -0,0 +1,253 @@
+import type { TaggingRule, TaggingRuleForCreation } from '../tagging-rules.types';
+import { useI18n } from '@/modules/i18n/i18n.provider';
+import { useConfirmModal } from '@/modules/shared/confirm';
+import { createForm } from '@/modules/shared/form/form';
+import { DocumentTagPicker } from '@/modules/tags/components/tag-picker.component';
+import { CreateTagModal } from '@/modules/tags/pages/tags.page';
+import { Button } from '@/modules/ui/components/button';
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/modules/ui/components/select';
+import { Separator } from '@/modules/ui/components/separator';
+import { TextArea } from '@/modules/ui/components/textarea';
+import { TextField, TextFieldLabel, TextFieldRoot } from '@/modules/ui/components/textfield';
+import { insert, remove, setValue } from '@modular-forms/solid';
+import { A } from '@solidjs/router';
+import { type Component, For, Show } from 'solid-js';
+import * as v from 'valibot';
+import { TAGGING_RULE_FIELDS, TAGGING_RULE_FIELDS_LOCALIZATION_KEYS, TAGGING_RULE_OPERATORS, TAGGING_RULE_OPERATORS_LOCALIZATION_KEYS } from '../tagging-rules.constants';
+
+export const TaggingRuleForm: Component<{
+ onSubmit: (args: { taggingRule: TaggingRuleForCreation }) => Promise<void> | void;
+ organizationId: string;
+ taggingRule?: TaggingRule;
+ submitButtonText?: string;
+}> = (props) => {
+ const { t } = useI18n();
+ const { confirm } = useConfirmModal();
+
+ const { form, Form, Field, FieldArray } = createForm({
+ onSubmit: async ({ name, conditions = [], tagIds, description }) => {
+ if (conditions.length === 0) {
+ const confirmed = await confirm({
+ title: t('tagging-rules.form.conditions.no-conditions.title'),
+ message: t('tagging-rules.form.conditions.no-conditions.description'),
+ confirmButton: {
+ variant: 'default',
+ text: t('tagging-rules.form.conditions.no-conditions.confirm'),
+ },
+ cancelButton: {
+ text: t('tagging-rules.form.conditions.no-conditions.cancel'),
+ },
+ });
+
+ if (!confirmed) {
+ return;
+ }
+ }
+
+ props.onSubmit({ taggingRule: { name, conditions, tagIds, description } });
+ },
+ schema: v.object({
+ name: v.pipe(
+ v.string(),
+ v.minLength(1, t('tagging-rules.form.name.min-length')),
+ v.maxLength(64, t('tagging-rules.form.name.max-length')),
+ ),
+ description: v.pipe(
+ v.string(),
+ v.maxLength(256, t('tagging-rules.form.description.max-length')),
+ ),
+ conditions: v.optional(
+ v.array(v.object({
+ field: v.picklist(Object.values(TAGGING_RULE_FIELDS)),
+ operator: v.picklist(Object.values(TAGGING_RULE_OPERATORS)),
+ value: v.pipe(
+ v.string(),
+ v.minLength(1, t('tagging-rules.form.conditions.value.min-length')),
+ ),
+ })),
+ ),
+ tagIds: v.pipe(
+ v.array(v.string()),
+ v.minLength(1, t('tagging-rules.form.tags.min-length')),
+ ),
+ }),
+ initialValues: {
+ conditions: props.taggingRule?.conditions ?? [],
+ tagIds: props.taggingRule?.actions.map(action => action.tagId) ?? [],
+ name: props.taggingRule?.name,
+ description: props.taggingRule?.description,
+ },
+ });
+
+ const getOperatorLabel = (operator: string) => {
+ return t(TAGGING_RULE_OPERATORS_LOCALIZATION_KEYS[operator as keyof typeof TAGGING_RULE_OPERATORS_LOCALIZATION_KEYS]);
+ };
+
+ const getFieldLabel = (field: string) => {
+ return t(TAGGING_RULE_FIELDS_LOCALIZATION_KEYS[field as keyof typeof TAGGING_RULE_FIELDS_LOCALIZATION_KEYS]);
+ };
+
+ return (
+ <Form>
+ <Field name="name">
+ {(field, inputProps) => (
+ <TextFieldRoot class="flex flex-col gap-1">
+ <TextFieldLabel for="name">{t('tagging-rules.form.name.label')}</TextFieldLabel>
+ <TextField
+ type="text"
+ id="name"
+ placeholder={t('tagging-rules.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('tagging-rules.form.description.label')}</TextFieldLabel>
+ <TextArea
+ id="description"
+ placeholder={t('tagging-rules.form.description.placeholder')}
+ {...inputProps}
+ value={field.value}
+ />
+ {field.error && <div class="text-red-500 text-sm">{field.error}</div>}
+ </TextFieldRoot>
+ )}
+ </Field>
+
+ <Separator class="my-6" />
+
+ <p class="mb-1 font-medium">{t('tagging-rules.form.conditions.label')}</p>
+ <p class="mb-2 text-sm text-muted-foreground">{t('tagging-rules.form.conditions.description')}</p>
+
+ <FieldArray name="conditions">
+ {fieldArray => (
+ <div>
+ <For each={fieldArray.items}>
+ {(_, index) => (
+ <div class="px-4 py-4 mb-1 flex gap-2 items-center bg-card border rounded-md">
+ <div>When</div>
+
+ <Field name={`conditions.${index()}.field`}>
+ {field => (
+ <Select
+ id="field"
+ defaultValue={field.value}
+ onChange={value => value && setValue(form, `conditions.${index()}.field`, value)}
+ options={Object.values(TAGGING_RULE_FIELDS)}
+ itemComponent={props => (
+ <SelectItem item={props.item}>{getFieldLabel(props.item.rawValue)}</SelectItem>
+ )}
+ >
+ <SelectTrigger class="w-[180px]">
+ <SelectValue<string>>{state => getFieldLabel(state.selectedOption())}</SelectValue>
+ </SelectTrigger>
+ <SelectContent />
+ </Select>
+ )}
+ </Field>
+
+ <Field name={`conditions.${index()}.operator`}>
+ {field => (
+ <Select
+ id="operator"
+ defaultValue={field.value}
+ onChange={value => value && setValue(form, `conditions.${index()}.operator`, value)}
+ options={Object.values(TAGGING_RULE_OPERATORS)}
+ itemComponent={props => (
+ <SelectItem item={props.item}>{getOperatorLabel(props.item.rawValue)}</SelectItem>
+ )}
+ >
+ <SelectTrigger class="w-[140px]">
+ <SelectValue<string>>{state => getOperatorLabel(state.selectedOption())}</SelectValue>
+ </SelectTrigger>
+ <SelectContent />
+ </Select>
+ )}
+ </Field>
+
+ <Field name={`conditions.${index()}.value`}>
+ {(field, inputProps) => (
+ <TextFieldRoot class="flex flex-col gap-1 flex-1">
+ <TextField
+ id="value"
+ {...inputProps}
+ value={field.value}
+ placeholder={t('tagging-rules.form.conditions.value.placeholder')}
+
+ />
+ {field.error && <div class="text-red-500 text-sm">{field.error}</div>}
+
+ </TextFieldRoot>
+ )}
+ </Field>
+
+ <Button variant="outline" size="icon" onClick={() => remove(form, 'conditions', { at: index() })}>
+ <div class="i-tabler-x size-4"></div>
+ </Button>
+ </div>
+ )}
+ </For>
+ {fieldArray.error && <div class="text-red-500 text-sm">{fieldArray.error}</div>}
+ </div>
+ )}
+ </FieldArray>
+
+ <Button
+ variant="outline"
+ onClick={() => insert(form, 'conditions', { value: { field: 'name', operator: 'contains', value: '' } })}
+ class="gap-2 mt-2"
+ >
+ <div class="i-tabler-plus size-4"></div>
+ {t('tagging-rules.form.conditions.add-condition')}
+ </Button>
+
+ <Separator class="my-6" />
+
+ <p class="mb-1 font-medium">{t('tagging-rules.form.tags.label')}</p>
+ <p class="mb-2 text-sm text-muted-foreground">{t('tagging-rules.form.tags.description')}</p>
+
+ <Field name="tagIds" type="string[]">
+ {field => (
+ <>
+ <div class="flex gap-2 sm:items-center sm:flex-row flex-col">
+ <div class="flex-1">
+
+ <DocumentTagPicker
+ organizationId={props.organizationId}
+ tagIds={field.value ?? []}
+ onTagsChange={({ tags }) => setValue(form, 'tagIds', tags.map(tag => tag.id))}
+ />
+ </div>
+
+ <CreateTagModal organizationId={props.organizationId}>
+ {props => (
+ <Button variant="outline" {...props}>
+ <div class="i-tabler-plus size-4 mr-2"></div>
+ {t('tagging-rules.form.tags.add-tag')}
+ </Button>
+ )}
+ </CreateTagModal>
+ </div>
+ {field.error && <div class="text-red-500 text-sm">{field.error}</div>}
+ </>
+ )}
+ </Field>
+
+ <div class="flex justify-end mt-6 gap-2">
+ <Show when={props.taggingRule}>
+ <Button variant="outline" as={A} href={`/organizations/${props.organizationId}/tagging-rules`}>
+ {t('tagging-rules.update.cancel')}
+ </Button>
+ </Show>
+
+ <Button type="submit">{props.submitButtonText ?? t('tagging-rules.form.submit')}</Button>
+ </div>
+ </Form>
+ );
+};
diff --git a/apps/papra-client/src/modules/tagging-rules/pages/create-tagging-rule.page.tsx b/apps/papra-client/src/modules/tagging-rules/pages/create-tagging-rule.page.tsx
new file mode 100644
index 00000000..98a0308e
--- /dev/null
+++ b/apps/papra-client/src/modules/tagging-rules/pages/create-tagging-rule.page.tsx
@@ -0,0 +1,49 @@
+import type { Component } from 'solid-js';
+import type { TaggingRuleForCreation } from '../tagging-rules.types';
+import { useI18n } from '@/modules/i18n/i18n.provider';
+import { createToast } from '@/modules/ui/components/sonner';
+import { useNavigate, useParams } from '@solidjs/router';
+import { createMutation } from '@tanstack/solid-query';
+import { TaggingRuleForm } from '../components/tagging-rule-form.component';
+import { createTaggingRule } from '../tagging-rules.services';
+
+export const CreateTaggingRulePage: Component = () => {
+ const { t } = useI18n();
+ const params = useParams();
+ const navigate = useNavigate();
+
+ const createTaggingRuleMutation = createMutation(() => ({
+ mutationFn: async ({ taggingRule }: { taggingRule: TaggingRuleForCreation }) => {
+ await createTaggingRule({ taggingRule, organizationId: params.organizationId });
+ },
+ onSuccess: () => {
+ createToast({
+ message: t('tagging-rules.create.success'),
+ type: 'success',
+ });
+ navigate(`/organizations/${params.organizationId}/tagging-rules`);
+ },
+ onError: () => {
+ createToast({
+ message: t('tagging-rules.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('tagging-rules.create.title')}
+ </h1>
+ </div>
+
+ <TaggingRuleForm
+ onSubmit={({ taggingRule }) => createTaggingRuleMutation.mutate({ taggingRule })}
+ organizationId={params.organizationId}
+ submitButtonText={t('tagging-rules.create.submit')}
+ />
+ </div>
+ );
+};
diff --git a/apps/papra-client/src/modules/tagging-rules/pages/tagging-rules.page.tsx b/apps/papra-client/src/modules/tagging-rules/pages/tagging-rules.page.tsx
new file mode 100644
index 00000000..7f64b7a2
--- /dev/null
+++ b/apps/papra-client/src/modules/tagging-rules/pages/tagging-rules.page.tsx
@@ -0,0 +1,146 @@
+import type { TaggingRule } from '../tagging-rules.types';
+import { useConfig } from '@/modules/config/config.provider';
+import { useI18n } from '@/modules/i18n/i18n.provider';
+import { queryClient } from '@/modules/shared/query/query-client';
+import { Alert } from '@/modules/ui/components/alert';
+import { Button } from '@/modules/ui/components/button';
+import { EmptyState } from '@/modules/ui/components/empty';
+import { A, useParams } from '@solidjs/router';
+import { createMutation, createQuery } from '@tanstack/solid-query';
+import { type Component, For, Match, Show, Switch } from 'solid-js';
+import { deleteTaggingRule, fetchTaggingRules } from '../tagging-rules.services';
+
+const TaggingRuleCard: Component<{ taggingRule: TaggingRule }> = (props) => {
+ const { t } = useI18n();
+
+ const getConditionsLabel = () => {
+ const count = props.taggingRule.conditions.length;
+
+ if (count === 0) {
+ return t('tagging-rules.list.card.no-conditions');
+ }
+
+ if (count === 1) {
+ return t('tagging-rules.list.card.one-condition');
+ }
+
+ return t('tagging-rules.list.card.conditions', { count });
+ };
+
+ const deleteTaggingRuleMutation = createMutation(() => ({
+ mutationFn: async () => {
+ await deleteTaggingRule({ organizationId: props.taggingRule.organizationId, taggingRuleId: props.taggingRule.id });
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['organizations', props.taggingRule.organizationId, 'tagging-rules'] });
+ },
+ }));
+
+ return (
+ <div class="flex items-center gap-2 bg-card py-4 px-6 rounded-md border">
+ <A href={`/organizations/${props.taggingRule.organizationId}/tagging-rules/${props.taggingRule.id}`}>
+ <div class="i-tabler-list-check size-8 opacity-30 mr-2" />
+ </A>
+
+ <div class="flex-1">
+ <A href={`/organizations/${props.taggingRule.organizationId}/tagging-rules/${props.taggingRule.id}`} class="text-base font-bold">{props.taggingRule.name}</A>
+
+ <p class="text-xs text-muted-foreground">
+ {[getConditionsLabel(), props.taggingRule.description].filter(Boolean).join(' - ')}
+ </p>
+ </div>
+
+ <div class="flex items-center gap-2">
+ <Button
+ as={A}
+ href={`/organizations/${props.taggingRule.organizationId}/tagging-rules/${props.taggingRule.id}`}
+ variant="outline"
+ size="icon"
+ aria-label={t('tagging-rules.list.card.edit')}
+ >
+ <div class="i-tabler-edit size-4" />
+ </Button>
+
+ <Button
+ variant="outline"
+ size="icon"
+ onClick={() => deleteTaggingRuleMutation.mutate()}
+ disabled={deleteTaggingRuleMutation.isPending}
+ aria-label={t('tagging-rules.list.card.delete')}
+ >
+ <div class="i-tabler-trash size-4" />
+ </Button>
+ </div>
+
+ </div>
+ );
+};
+
+export const TaggingRulesPage: Component = () => {
+ const { t } = useI18n();
+ const { config } = useConfig();
+ const params = useParams();
+
+ const query = createQuery(() => ({
+ queryKey: ['organizations', params.organizationId, 'tagging-rules'],
+ queryFn: () => fetchTaggingRules({ organizationId: params.organizationId }),
+ }));
+
+ return (
+ <div class="p-6 max-w-screen-lg mx-auto mt-4">
+ <div class="border-b mb-6 pb-4 flex items-center justify-between gap-4 sm:flex-row flex-col">
+ <div>
+ <h1 class="text-xl font-bold">
+ {t('tagging-rules.list.title')}
+ </h1>
+
+ <p class="text-muted-foreground mt-1">
+ {t('tagging-rules.list.description')}
+ </p>
+ </div>
+
+ <Show when={query.data?.taggingRules.length}>
+ <Button as={A} href={`/organizations/${params.organizationId}/tagging-rules/create`} class="flex items-center gap-2 flex-shrink-0 sm:w-auto w-full">
+ <div class="i-tabler-plus size-4" />
+ {t('tagging-rules.list.no-tagging-rules.create-tagging-rule')}
+ </Button>
+ </Show>
+ </div>
+
+ <Show when={config.isDemoMode}>
+ <Alert class="bg-primary text-primary-foreground mb-4">
+ {t('tagging-rules.list.demo-warning')}
+ </Alert>
+ </Show>
+
+ <Switch>
+ <Match when={query.data?.taggingRules.length === 0}>
+ <div class="mt-16">
+ <EmptyState
+ title={t('tagging-rules.list.no-tagging-rules.title')}
+ description={t('tagging-rules.list.no-tagging-rules.description')}
+ class="pt-0"
+ icon="i-tabler-list-check"
+ cta={(
+ <Button as={A} href={`/organizations/${params.organizationId}/tagging-rules/create`}>
+ <div class="i-tabler-plus size-4 mr-2" />
+ {t('tagging-rules.list.no-tagging-rules.create-tagging-rule')}
+ </Button>
+ )}
+ />
+ </div>
+ </Match>
+
+ <Match when={query.data?.taggingRules.length}>
+ <div class="flex flex-col gap-2">
+ <For each={query.data?.taggingRules}>
+ {taggingRule => <TaggingRuleCard taggingRule={taggingRule} />}
+ </For>
+ </div>
+ </Match>
+
+ </Switch>
+
+ </div>
+ );
+};
diff --git a/apps/papra-client/src/modules/tagging-rules/pages/update-tagging-rule.page.tsx b/apps/papra-client/src/modules/tagging-rules/pages/update-tagging-rule.page.tsx
new file mode 100644
index 00000000..efd90273
--- /dev/null
+++ b/apps/papra-client/src/modules/tagging-rules/pages/update-tagging-rule.page.tsx
@@ -0,0 +1,63 @@
+import type { TaggingRuleForCreation } from '../tagging-rules.types';
+import { useI18n } from '@/modules/i18n/i18n.provider';
+import { queryClient } from '@/modules/shared/query/query-client';
+import { createToast } from '@/modules/ui/components/sonner';
+import { useNavigate, useParams } from '@solidjs/router';
+import { createMutation, createQuery } from '@tanstack/solid-query';
+import { type Component, Show } from 'solid-js';
+import { TaggingRuleForm } from '../components/tagging-rule-form.component';
+import { getTaggingRule, updateTaggingRule } from '../tagging-rules.services';
+
+export const UpdateTaggingRulePage: Component = () => {
+ const { t } = useI18n();
+ const params = useParams();
+ const navigate = useNavigate();
+
+ const query = createQuery(() => ({
+ queryKey: ['organizations', params.organizationId, 'tagging-rules', params.taggingRuleId],
+ queryFn: () => getTaggingRule({ organizationId: params.organizationId, taggingRuleId: params.taggingRuleId }),
+ }));
+
+ const updateTaggingRuleMutation = createMutation(() => ({
+ mutationFn: async ({ taggingRule }: { taggingRule: TaggingRuleForCreation }) => {
+ await updateTaggingRule({ organizationId: params.organizationId, taggingRuleId: params.taggingRuleId, taggingRule });
+ },
+ onSuccess: async () => {
+ await queryClient.invalidateQueries({ queryKey: ['organizations', params.organizationId, 'tagging-rules'] });
+
+ createToast({
+ message: t('tagging-rules.create.success'),
+ type: 'success',
+ });
+ navigate(`/organizations/${params.organizationId}/tagging-rules`);
+ },
+ onError: () => {
+ createToast({
+ message: t('tagging-rules.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('tagging-rules.update.title')}
+ </h1>
+ </div>
+
+ <Show when={query.data?.taggingRule}>
+ {getTaggingRule => (
+ <TaggingRuleForm
+ onSubmit={({ taggingRule }) => updateTaggingRuleMutation.mutate({ taggingRule })}
+ organizationId={params.organizationId}
+ taggingRule={getTaggingRule()}
+ submitButtonText={t('tagging-rules.update.submit')}
+ />
+ )}
+ </Show>
+
+ </div>
+ );
+};
diff --git a/apps/papra-client/src/modules/tagging-rules/tagging-rules.constants.ts b/apps/papra-client/src/modules/tagging-rules/tagging-rules.constants.ts
new file mode 100644
index 00000000..7480c21d
--- /dev/null
+++ b/apps/papra-client/src/modules/tagging-rules/tagging-rules.constants.ts
@@ -0,0 +1,29 @@
+import type { LocaleKeys } from '../i18n/locales.types';
+
+export const TAGGING_RULE_OPERATORS = {
+ EQUAL: 'equal',
+ NOT_EQUAL: 'not_equal',
+ CONTAINS: 'contains',
+ NOT_CONTAINS: 'not_contains',
+ STARTS_WITH: 'starts_with',
+ ENDS_WITH: 'ends_with',
+} as const;
+
+export const TAGGING_RULE_FIELDS = {
+ DOCUMENT_NAME: 'name',
+ DOCUMENT_CONTENT: 'content',
+} as const;
+
+export const TAGGING_RULE_OPERATORS_LOCALIZATION_KEYS: Record<(typeof TAGGING_RULE_OPERATORS)[keyof typeof TAGGING_RULE_OPERATORS], LocaleKeys> = {
+ [TAGGING_RULE_OPERATORS.EQUAL]: 'tagging-rules.operator.equals',
+ [TAGGING_RULE_OPERATORS.NOT_EQUAL]: 'tagging-rules.operator.not-equals',
+ [TAGGING_RULE_OPERATORS.CONTAINS]: 'tagging-rules.operator.contains',
+ [TAGGING_RULE_OPERATORS.NOT_CONTAINS]: 'tagging-rules.operator.not-contains',
+ [TAGGING_RULE_OPERATORS.STARTS_WITH]: 'tagging-rules.operator.starts-with',
+ [TAGGING_RULE_OPERATORS.ENDS_WITH]: 'tagging-rules.operator.ends-with',
+} as const;
+
+export const TAGGING_RULE_FIELDS_LOCALIZATION_KEYS: Record<(typeof TAGGING_RULE_FIELDS)[keyof typeof TAGGING_RULE_FIELDS], LocaleKeys> = {
+ [TAGGING_RULE_FIELDS.DOCUMENT_NAME]: 'tagging-rules.field.name',
+ [TAGGING_RULE_FIELDS.DOCUMENT_CONTENT]: 'tagging-rules.field.content',
+} as const;
diff --git a/apps/papra-client/src/modules/tagging-rules/tagging-rules.models.ts b/apps/papra-client/src/modules/tagging-rules/tagging-rules.models.ts
new file mode 100644
index 00000000..e69de29b
diff --git a/apps/papra-client/src/modules/tagging-rules/tagging-rules.services.ts b/apps/papra-client/src/modules/tagging-rules/tagging-rules.services.ts
new file mode 100644
index 00000000..9b56b06c
--- /dev/null
+++ b/apps/papra-client/src/modules/tagging-rules/tagging-rules.services.ts
@@ -0,0 +1,43 @@
+import type { TaggingRule, TaggingRuleForCreation } from './tagging-rules.types';
+import { apiClient } from '../shared/http/api-client';
+
+export async function fetchTaggingRules({ organizationId }: { organizationId: string }) {
+ const { taggingRules } = await apiClient<{ taggingRules: TaggingRule[] }>({
+ path: `/api/organizations/${organizationId}/tagging-rules`,
+ method: 'GET',
+ });
+
+ return { taggingRules };
+}
+
+export async function createTaggingRule({ taggingRule, organizationId }: { taggingRule: TaggingRuleForCreation; organizationId: string }) {
+ await apiClient({
+ path: `/api/organizations/${organizationId}/tagging-rules`,
+ method: 'POST',
+ body: taggingRule,
+ });
+}
+
+export async function deleteTaggingRule({ organizationId, taggingRuleId }: { organizationId: string; taggingRuleId: string }) {
+ await apiClient({
+ path: `/api/organizations/${organizationId}/tagging-rules/${taggingRuleId}`,
+ method: 'DELETE',
+ });
+}
+
+export async function getTaggingRule({ organizationId, taggingRuleId }: { organizationId: string; taggingRuleId: string }) {
+ const { taggingRule } = await apiClient<{ taggingRule: TaggingRule }>({
+ path: `/api/organizations/${organizationId}/tagging-rules/${taggingRuleId}`,
+ method: 'GET',
+ });
+
+ return { taggingRule };
+}
+
+export async function updateTaggingRule({ organizationId, taggingRuleId, taggingRule }: { organizationId: string; taggingRuleId: string; taggingRule: TaggingRuleForCreation }) {
+ await apiClient({
+ path: `/api/organizations/${organizationId}/tagging-rules/${taggingRuleId}`,
+ method: 'PUT',
+ body: taggingRule,
+ });
+}
diff --git a/apps/papra-client/src/modules/tagging-rules/tagging-rules.types.ts b/apps/papra-client/src/modules/tagging-rules/tagging-rules.types.ts
new file mode 100644
index 00000000..5a329b53
--- /dev/null
+++ b/apps/papra-client/src/modules/tagging-rules/tagging-rules.types.ts
@@ -0,0 +1,25 @@
+import type { TAGGING_RULE_FIELDS, TAGGING_RULE_OPERATORS } from './tagging-rules.constants';
+
+export type TaggingRuleForCreation = {
+ name: string;
+ description: string;
+ conditions: TaggingRuleCondition[];
+ tagIds: string[];
+};
+
+export type TaggingRuleCondition = {
+ field: (typeof TAGGING_RULE_FIELDS)[keyof typeof TAGGING_RULE_FIELDS];
+ operator: (typeof TAGGING_RULE_OPERATORS)[keyof typeof TAGGING_RULE_OPERATORS];
+ value: string;
+};
+
+export type TaggingRule = {
+ id: string;
+ name: string;
+ description: string;
+ conditions: TaggingRuleCondition[];
+ actions: { tagId: string }[];
+ organizationId: string;
+ createdAt: Date;
+ updatedAt: Date;
+};
diff --git a/apps/papra-client/src/modules/tags/components/tag-picker.component.tsx b/apps/papra-client/src/modules/tags/components/tag-picker.component.tsx
index c2a6a3ea..2ed51860 100644
--- a/apps/papra-client/src/modules/tags/components/tag-picker.component.tsx
+++ b/apps/papra-client/src/modules/tags/components/tag-picker.component.tsx
@@ -7,13 +7,12 @@ import { Tag as TagComponent } from './tag.component';
export const DocumentTagPicker: Component<{
organizationId: string;
- tags: Tag[];
- documentId: string;
+ tagIds: string[];
onTagsChange?: (args: { tags: Tag[] }) => void;
onTagAdded?: (args: { tag: Tag }) => void;
onTagRemoved?: (args: { tag: Tag }) => void;
}> = (props) => {
- const [getSelectedTags, setSelectedTags] = createSignal<Tag[]>(props.tags);
+ const [getSelectedTagIds, setSelectedTagIds] = createSignal<string[]>(props.tagIds);
const query = createQuery(() => ({
queryKey: ['organizations', props.organizationId, 'tags'],
@@ -22,6 +21,9 @@ export const DocumentTagPicker: Component<{
const options = () => query.data?.tags || [];
+ const getSelectedTags = () => query.data?.tags.filter(tag => getSelectedTagIds().includes(tag.id)) ?? [];
+ const setSelectedTags = (tags: Tag[]) => setSelectedTagIds(tags.map(tag => tag.id));
+
return (
<Combobox<Tag>
options={options()}
diff --git a/apps/papra-client/src/modules/tags/pages/tags.page.tsx b/apps/papra-client/src/modules/tags/pages/tags.page.tsx
index a3a8d569..54d51360 100644
--- a/apps/papra-client/src/modules/tags/pages/tags.page.tsx
+++ b/apps/papra-client/src/modules/tags/pages/tags.page.tsx
@@ -104,7 +104,7 @@ const TagForm: Component<{
);
};
-const CreateTagModal: Component<{
+export const CreateTagModal: Component<{
children: (props: DialogTriggerProps) => JSX.Element;
organizationId: string;
}> = (props) => {
diff --git a/apps/papra-client/src/modules/ui/layouts/integrations.layout.tsx b/apps/papra-client/src/modules/ui/layouts/integrations.layout.tsx
index bb60907e..b5db2a04 100644
--- a/apps/papra-client/src/modules/ui/layouts/integrations.layout.tsx
+++ b/apps/papra-client/src/modules/ui/layouts/integrations.layout.tsx
@@ -8,7 +8,7 @@ export const IntegrationsLayout: ParentComponent = (props) => {
return (
<div class="p-6 mt-4 pb-32 mx-auto max-w-5xl">
<div class="border-b mb-6">
- <h1 class="text-xl font-bold ">
+ <h1 class="text-xl font-bold">
Integrations
</h1>
diff --git a/apps/papra-client/src/modules/ui/layouts/organization.layout.tsx b/apps/papra-client/src/modules/ui/layouts/organization.layout.tsx
index 785b891f..2cb5538a 100644
--- a/apps/papra-client/src/modules/ui/layouts/organization.layout.tsx
+++ b/apps/papra-client/src/modules/ui/layouts/organization.layout.tsx
@@ -38,6 +38,11 @@ const OrganizationLayoutSideNav: Component = () => {
icon: 'i-tabler-tag',
href: `/organizations/${params.organizationId}/tags`,
},
+ {
+ label: t('layout.menu.tagging-rules'),
+ icon: 'i-tabler-list-check',
+ href: `/organizations/${params.organizationId}/tagging-rules`,
+ },
{
label: t('layout.menu.integrations'),
icon: 'i-tabler-link',
diff --git a/apps/papra-client/src/routes.tsx b/apps/papra-client/src/routes.tsx
index bd0cc51c..7f696131 100644
--- a/apps/papra-client/src/routes.tsx
+++ b/apps/papra-client/src/routes.tsx
@@ -19,6 +19,9 @@ import { OrganizationsSettingsPage } from './modules/organizations/pages/organiz
import { OrganizationsPage } from './modules/organizations/pages/organizations.page';
import { ComingSoonPage } from './modules/shared/pages/coming-soon.page';
import { NotFoundPage } from './modules/shared/pages/not-found.page';
+import { CreateTaggingRulePage } from './modules/tagging-rules/pages/create-tagging-rule.page';
+import { TaggingRulesPage } from './modules/tagging-rules/pages/tagging-rules.page';
+import { UpdateTaggingRulePage } from './modules/tagging-rules/pages/update-tagging-rule.page';
import { TagsPage } from './modules/tags/pages/tags.page';
import { IntegrationsLayout } from './modules/ui/layouts/integrations.layout';
import { OrganizationLayout } from './modules/ui/layouts/organization.layout';
@@ -111,6 +114,18 @@ export const routes: RouteDefinition[] = [
path: '/tags',
component: TagsPage,
},
+ {
+ path: '/tagging-rules',
+ component: TaggingRulesPage,
+ },
+ {
+ path: '/tagging-rules/create',
+ component: CreateTaggingRulePage,
+ },
+ {
+ path: '/tagging-rules/:taggingRuleId',
+ component: UpdateTaggingRulePage,
+ },
{
path: '/',
component: IntegrationsLayout,
diff --git a/apps/papra-server/migrations/0002_tagging_rules.sql b/apps/papra-server/migrations/0002_tagging_rules.sql
new file mode 100644
index 00000000..38828e9e
--- /dev/null
+++ b/apps/papra-server/migrations/0002_tagging_rules.sql
@@ -0,0 +1,32 @@
+CREATE TABLE `tagging_rule_actions` (
+ `id` text PRIMARY KEY NOT NULL,
+ `created_at` integer NOT NULL,
+ `updated_at` integer NOT NULL,
+ `tagging_rule_id` text NOT NULL,
+ `tag_id` text NOT NULL,
+ FOREIGN KEY (`tagging_rule_id`) REFERENCES `tagging_rules`(`id`) ON UPDATE cascade ON DELETE cascade,
+ FOREIGN KEY (`tag_id`) REFERENCES `tags`(`id`) ON UPDATE cascade ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE TABLE `tagging_rule_conditions` (
+ `id` text PRIMARY KEY NOT NULL,
+ `created_at` integer NOT NULL,
+ `updated_at` integer NOT NULL,
+ `tagging_rule_id` text NOT NULL,
+ `field` text NOT NULL,
+ `operator` text NOT NULL,
+ `value` text NOT NULL,
+ `is_case_sensitive` integer DEFAULT false NOT NULL,
+ FOREIGN KEY (`tagging_rule_id`) REFERENCES `tagging_rules`(`id`) ON UPDATE cascade ON DELETE cascade
+);
+--> statement-breakpoint
+CREATE TABLE `tagging_rules` (
+ `id` text PRIMARY KEY NOT NULL,
+ `created_at` integer NOT NULL,
+ `updated_at` integer NOT NULL,
+ `organization_id` text NOT NULL,
+ `name` text NOT NULL,
+ `description` text,
+ `enabled` integer DEFAULT true NOT NULL,
+ FOREIGN KEY (`organization_id`) REFERENCES `organizations`(`id`) ON UPDATE cascade ON DELETE cascade
+);
diff --git a/apps/papra-server/migrations/meta/0002_snapshot.json b/apps/papra-server/migrations/meta/0002_snapshot.json
new file mode 100644
index 00000000..4c9d0fd0
--- /dev/null
+++ b/apps/papra-server/migrations/meta/0002_snapshot.json
@@ -0,0 +1,1443 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "6d328e8d-0cb2-440d-beb4-ebb9b92370e6",
+ "prevId": "4d99e358-8e33-4991-80c4-d7595c094310",
+ "tables": {
+ "documents": {
+ "name": "documents",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_deleted": {
+ "name": "is_deleted",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "deleted_by": {
+ "name": "deleted_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "original_name": {
+ "name": "original_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "original_size": {
+ "name": "original_size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "original_storage_key": {
+ "name": "original_storage_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "original_sha256_hash": {
+ "name": "original_sha256_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "mime_type": {
+ "name": "mime_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ }
+ },
+ "indexes": {
+ "documents_organization_id_is_deleted_created_at_index": {
+ "name": "documents_organization_id_is_deleted_created_at_index",
+ "columns": [
+ "organization_id",
+ "is_deleted",
+ "created_at"
+ ],
+ "isUnique": false
+ },
+ "documents_organization_id_is_deleted_index": {
+ "name": "documents_organization_id_is_deleted_index",
+ "columns": [
+ "organization_id",
+ "is_deleted"
+ ],
+ "isUnique": false
+ },
+ "documents_organization_id_original_sha256_hash_unique": {
+ "name": "documents_organization_id_original_sha256_hash_unique",
+ "columns": [
+ "organization_id",
+ "original_sha256_hash"
+ ],
+ "isUnique": true
+ },
+ "documents_original_sha256_hash_index": {
+ "name": "documents_original_sha256_hash_index",
+ "columns": [
+ "original_sha256_hash"
+ ],
+ "isUnique": false
+ },
+ "documents_organization_id_size_index": {
+ "name": "documents_organization_id_size_index",
+ "columns": [
+ "organization_id",
+ "original_size"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "documents_organization_id_organizations_id_fk": {
+ "name": "documents_organization_id_organizations_id_fk",
+ "tableFrom": "documents",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ },
+ "documents_created_by_users_id_fk": {
+ "name": "documents_created_by_users_id_fk",
+ "tableFrom": "documents",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "cascade"
+ },
+ "documents_deleted_by_users_id_fk": {
+ "name": "documents_deleted_by_users_id_fk",
+ "tableFrom": "documents",
+ "tableTo": "users",
+ "columnsFrom": [
+ "deleted_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "organization_invitations": {
+ "name": "organization_invitations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "inviter_id": {
+ "name": "inviter_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "organization_invitations_organization_id_organizations_id_fk": {
+ "name": "organization_invitations_organization_id_organizations_id_fk",
+ "tableFrom": "organization_invitations",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ },
+ "organization_invitations_inviter_id_users_id_fk": {
+ "name": "organization_invitations_inviter_id_users_id_fk",
+ "tableFrom": "organization_invitations",
+ "tableTo": "users",
+ "columnsFrom": [
+ "inviter_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "organization_members": {
+ "name": "organization_members",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "organization_members_user_organization_unique": {
+ "name": "organization_members_user_organization_unique",
+ "columns": [
+ "organization_id",
+ "user_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "organization_members_organization_id_organizations_id_fk": {
+ "name": "organization_members_organization_id_organizations_id_fk",
+ "tableFrom": "organization_members",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ },
+ "organization_members_user_id_users_id_fk": {
+ "name": "organization_members_user_id_users_id_fk",
+ "tableFrom": "organization_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "organizations": {
+ "name": "organizations",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "customer_id": {
+ "name": "customer_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "user_roles": {
+ "name": "user_roles",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "user_roles_role_index": {
+ "name": "user_roles_role_index",
+ "columns": [
+ "role"
+ ],
+ "isUnique": false
+ },
+ "user_roles_user_id_role_unique_index": {
+ "name": "user_roles_user_id_role_unique_index",
+ "columns": [
+ "user_id",
+ "role"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "user_roles_user_id_users_id_fk": {
+ "name": "user_roles_user_id_users_id_fk",
+ "tableFrom": "user_roles",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "documents_tags": {
+ "name": "documents_tags",
+ "columns": {
+ "document_id": {
+ "name": "document_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tag_id": {
+ "name": "tag_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "documents_tags_document_id_documents_id_fk": {
+ "name": "documents_tags_document_id_documents_id_fk",
+ "tableFrom": "documents_tags",
+ "tableTo": "documents",
+ "columnsFrom": [
+ "document_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ },
+ "documents_tags_tag_id_tags_id_fk": {
+ "name": "documents_tags_tag_id_tags_id_fk",
+ "tableFrom": "documents_tags",
+ "tableTo": "tags",
+ "columnsFrom": [
+ "tag_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {
+ "documents_tags_pkey": {
+ "columns": [
+ "document_id",
+ "tag_id"
+ ],
+ "name": "documents_tags_pkey"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "tags": {
+ "name": "tags",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "tags_organization_id_name_unique": {
+ "name": "tags_organization_id_name_unique",
+ "columns": [
+ "organization_id",
+ "name"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "tags_organization_id_organizations_id_fk": {
+ "name": "tags_organization_id_organizations_id_fk",
+ "tableFrom": "tags",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "users": {
+ "name": "users",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email_verified": {
+ "name": "email_verified",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "max_organization_count": {
+ "name": "max_organization_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "users_email_unique": {
+ "name": "users_email_unique",
+ "columns": [
+ "email"
+ ],
+ "isUnique": true
+ },
+ "users_email_index": {
+ "name": "users_email_index",
+ "columns": [
+ "email"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "auth_accounts": {
+ "name": "auth_accounts",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "account_id": {
+ "name": "account_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "access_token_expires_at": {
+ "name": "access_token_expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token_expires_at": {
+ "name": "refresh_token_expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "auth_accounts_user_id_users_id_fk": {
+ "name": "auth_accounts_user_id_users_id_fk",
+ "tableFrom": "auth_accounts",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "auth_sessions": {
+ "name": "auth_sessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "active_organization_id": {
+ "name": "active_organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "auth_sessions_token_index": {
+ "name": "auth_sessions_token_index",
+ "columns": [
+ "token"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "auth_sessions_user_id_users_id_fk": {
+ "name": "auth_sessions_user_id_users_id_fk",
+ "tableFrom": "auth_sessions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ },
+ "auth_sessions_active_organization_id_organizations_id_fk": {
+ "name": "auth_sessions_active_organization_id_organizations_id_fk",
+ "tableFrom": "auth_sessions",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "active_organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "auth_verifications": {
+ "name": "auth_verifications",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "auth_verifications_identifier_index": {
+ "name": "auth_verifications_identifier_index",
+ "columns": [
+ "identifier"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "intake_emails": {
+ "name": "intake_emails",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email_address": {
+ "name": "email_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "allowed_origins": {
+ "name": "allowed_origins",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "is_enabled": {
+ "name": "is_enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ }
+ },
+ "indexes": {
+ "intake_emails_email_address_unique": {
+ "name": "intake_emails_email_address_unique",
+ "columns": [
+ "email_address"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "intake_emails_organization_id_organizations_id_fk": {
+ "name": "intake_emails_organization_id_organizations_id_fk",
+ "tableFrom": "intake_emails",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "organization_subscriptions": {
+ "name": "organization_subscriptions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "customer_id": {
+ "name": "customer_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "plan_id": {
+ "name": "plan_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "seats_count": {
+ "name": "seats_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "current_period_end": {
+ "name": "current_period_end",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "current_period_start": {
+ "name": "current_period_start",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cancel_at_period_end": {
+ "name": "cancel_at_period_end",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "organization_subscriptions_organization_id_organizations_id_fk": {
+ "name": "organization_subscriptions_organization_id_organizations_id_fk",
+ "tableFrom": "organization_subscriptions",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "tagging_rule_actions": {
+ "name": "tagging_rule_actions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tagging_rule_id": {
+ "name": "tagging_rule_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tag_id": {
+ "name": "tag_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "tagging_rule_actions_tagging_rule_id_tagging_rules_id_fk": {
+ "name": "tagging_rule_actions_tagging_rule_id_tagging_rules_id_fk",
+ "tableFrom": "tagging_rule_actions",
+ "tableTo": "tagging_rules",
+ "columnsFrom": [
+ "tagging_rule_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ },
+ "tagging_rule_actions_tag_id_tags_id_fk": {
+ "name": "tagging_rule_actions_tag_id_tags_id_fk",
+ "tableFrom": "tagging_rule_actions",
+ "tableTo": "tags",
+ "columnsFrom": [
+ "tag_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "tagging_rule_conditions": {
+ "name": "tagging_rule_conditions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tagging_rule_id": {
+ "name": "tagging_rule_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "field": {
+ "name": "field",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "operator": {
+ "name": "operator",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "is_case_sensitive": {
+ "name": "is_case_sensitive",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "tagging_rule_conditions_tagging_rule_id_tagging_rules_id_fk": {
+ "name": "tagging_rule_conditions_tagging_rule_id_tagging_rules_id_fk",
+ "tableFrom": "tagging_rule_conditions",
+ "tableTo": "tagging_rules",
+ "columnsFrom": [
+ "tagging_rule_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "tagging_rules": {
+ "name": "tagging_rules",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "tagging_rules_organization_id_organizations_id_fk": {
+ "name": "tagging_rules_organization_id_organizations_id_fk",
+ "tableFrom": "tagging_rules",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "cascade"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
diff --git a/apps/papra-server/migrations/meta/_journal.json b/apps/papra-server/migrations/meta/_journal.json
index f93b839b..49a9d8c4 100644
--- a/apps/papra-server/migrations/meta/_journal.json
+++ b/apps/papra-server/migrations/meta/_journal.json
@@ -15,6 +15,13 @@
"when": 1743508401881,
"tag": "0001_documents_fts",
"breakpoints": true
+ },
+ {
+ "idx": 2,
+ "version": "6",
+ "when": 1743938048080,
+ "tag": "0002_tagging_rules",
+ "breakpoints": true
}
]
}
diff --git a/apps/papra-server/src/modules/app/database/database.test-utils.ts b/apps/papra-server/src/modules/app/database/database.test-utils.ts
index 790d3eb0..f457d624 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,7 @@ import { documentsTable } from '../../documents/documents.table';
import { intakeEmailsTable } from '../../intake-emails/intake-emails.tables';
import { organizationMembersTable, organizationsTable } from '../../organizations/organizations.table';
import { organizationSubscriptionsTable } from '../../subscriptions/subscriptions.tables';
+import { taggingRuleActionsTable, taggingRuleConditionsTable, taggingRulesTable } from '../../tagging-rules/tagging-rules.tables';
import { documentsTagsTable, tagsTable } from '../../tags/tags.table';
import { usersTable } from '../../users/users.table';
import { setupDatabase } from './database';
@@ -31,6 +32,9 @@ const seedTables = {
documentsTags: documentsTagsTable,
intakeEmails: intakeEmailsTable,
organizationSubscriptions: organizationSubscriptionsTable,
+ taggingRules: taggingRulesTable,
+ taggingRuleConditions: taggingRuleConditionsTable,
+ taggingRuleActions: taggingRuleActionsTable,
} as const;
type SeedTablesRows = {
diff --git a/apps/papra-server/src/modules/app/server.routes.ts b/apps/papra-server/src/modules/app/server.routes.ts
index eb8e6b95..fac6d2c7 100644
--- a/apps/papra-server/src/modules/app/server.routes.ts
+++ b/apps/papra-server/src/modules/app/server.routes.ts
@@ -4,6 +4,7 @@ import { registerDocumentsPrivateRoutes } from '../documents/documents.routes';
import { registerIntakeEmailsPrivateRoutes, registerIntakeEmailsPublicRoutes } from '../intake-emails/intake-emails.routes';
import { registerOrganizationsPrivateRoutes } from '../organizations/organizations.routes';
import { registerSubscriptionsPrivateRoutes, registerSubscriptionsPublicRoutes } from '../subscriptions/subscriptions.routes';
+import { registerTaggingRulesRoutes } from '../tagging-rules/tagging-rules.routes';
import { registerTagsRoutes } from '../tags/tags.routes';
import { registerUsersPrivateRoutes } from '../users/users.routes';
import { createUnauthorizedError } from './auth/auth.errors';
@@ -42,4 +43,5 @@ function registerPrivateRoutes(context: RouteDefinitionContext) {
registerTagsRoutes(context);
registerIntakeEmailsPrivateRoutes(context);
registerSubscriptionsPrivateRoutes(context);
+ registerTaggingRulesRoutes(context);
}
diff --git a/apps/papra-server/src/modules/documents/documents.routes.ts b/apps/papra-server/src/modules/documents/documents.routes.ts
index 1e8f01df..a782dd0f 100644
--- a/apps/papra-server/src/modules/documents/documents.routes.ts
+++ b/apps/papra-server/src/modules/documents/documents.routes.ts
@@ -9,6 +9,8 @@ import { createPlansRepository } from '../plans/plans.repository';
import { createError } from '../shared/errors/errors';
import { validateFormData, validateParams, validateQuery } from '../shared/validation/validation';
import { createSubscriptionsRepository } from '../subscriptions/subscriptions.repository';
+import { createTaggingRulesRepository } from '../tagging-rules/tagging-rules.repository';
+import { createTagsRepository } from '../tags/tags.repository';
import { createDocumentIsNotDeletedError } from './documents.errors';
import { createDocumentsRepository } from './documents.repository';
import { createDocument, ensureDocumentExists, getDocumentOrThrow } from './documents.usecases';
@@ -78,6 +80,8 @@ function setupCreateDocumentRoute({ app, config, db, trackingServices }: RouteDe
const documentsStorageService = await createDocumentStorageService({ config });
const plansRepository = createPlansRepository({ config });
const subscriptionsRepository = createSubscriptionsRepository({ db });
+ const taggingRulesRepository = createTaggingRulesRepository({ db });
+ const tagsRepository = createTagsRepository({ db });
const { document } = await createDocument({
file,
@@ -88,6 +92,8 @@ function setupCreateDocumentRoute({ app, config, db, trackingServices }: RouteDe
plansRepository,
subscriptionsRepository,
trackingServices,
+ taggingRulesRepository,
+ tagsRepository,
});
return context.json({
diff --git a/apps/papra-server/src/modules/documents/documents.types.ts b/apps/papra-server/src/modules/documents/documents.types.ts
index 5134c726..f12500af 100644
--- a/apps/papra-server/src/modules/documents/documents.types.ts
+++ b/apps/papra-server/src/modules/documents/documents.types.ts
@@ -2,3 +2,6 @@ import type { Expand } from '@corentinth/chisels';
import type { documentsTable } from './documents.table';
export type DbInsertableDocument = Expand<typeof documentsTable.$inferInsert>;
+export type DbSelectableDocument = Expand<typeof documentsTable.$inferSelect>;
+
+export type Document = DbSelectableDocument;
diff --git a/apps/papra-server/src/modules/documents/documents.usecases.test.ts b/apps/papra-server/src/modules/documents/documents.usecases.test.ts
index e14c2bb6..90e27df3 100644
--- a/apps/papra-server/src/modules/documents/documents.usecases.test.ts
+++ b/apps/papra-server/src/modules/documents/documents.usecases.test.ts
@@ -5,6 +5,8 @@ import { ORGANIZATION_ROLES } from '../organizations/organizations.constants';
import { createPlansRepository } from '../plans/plans.repository';
import { collectReadableStreamToString } from '../shared/streams/readable-stream';
import { createSubscriptionsRepository } from '../subscriptions/subscriptions.repository';
+import { createTaggingRulesRepository } from '../tagging-rules/tagging-rules.repository';
+import { createTagsRepository } from '../tags/tags.repository';
import { createDummyTrackingServices } from '../tracking/tracking.services';
import { createDocumentAlreadyExistsError } from './documents.errors';
import { createDocumentsRepository } from './documents.repository';
@@ -26,6 +28,8 @@ describe('documents usecases', () => {
const plansRepository = createPlansRepository({ config: { organizationPlans: { isFreePlanUnlimited: true } } as Config });
const subscriptionsRepository = createSubscriptionsRepository({ db });
const trackingServices = createDummyTrackingServices();
+ const taggingRulesRepository = createTaggingRulesRepository({ db });
+ const tagsRepository = createTagsRepository({ db });
const generateDocumentId = () => 'doc_1';
const file = new File(['content'], 'file.txt', { type: 'text/plain' });
@@ -42,6 +46,8 @@ describe('documents usecases', () => {
plansRepository,
subscriptionsRepository,
trackingServices,
+ taggingRulesRepository,
+ tagsRepository,
});
expect(document).to.include({
@@ -81,6 +87,9 @@ describe('documents usecases', () => {
const plansRepository = createPlansRepository({ config: { organizationPlans: { isFreePlanUnlimited: true } } as Config });
const subscriptionsRepository = createSubscriptionsRepository({ db });
const trackingServices = createDummyTrackingServices();
+ const taggingRulesRepository = createTaggingRulesRepository({ db });
+ const tagsRepository = createTagsRepository({ db });
+
let documentIdIndex = 1;
const generateDocumentId = () => `doc_${documentIdIndex++}`;
@@ -98,6 +107,8 @@ describe('documents usecases', () => {
subscriptionsRepository,
generateDocumentId,
trackingServices,
+ taggingRulesRepository,
+ tagsRepository,
});
expect(document1).to.include({
@@ -124,6 +135,8 @@ describe('documents usecases', () => {
subscriptionsRepository,
generateDocumentId,
trackingServices,
+ taggingRulesRepository,
+ tagsRepository,
}),
).rejects.toThrow(
createDocumentAlreadyExistsError(),
@@ -150,6 +163,8 @@ describe('documents usecases', () => {
const plansRepository = createPlansRepository({ config: { organizationPlans: { isFreePlanUnlimited: true } } as Config });
const subscriptionsRepository = createSubscriptionsRepository({ db });
const trackingServices = createDummyTrackingServices();
+ const taggingRulesRepository = createTaggingRulesRepository({ db });
+ const tagsRepository = createTagsRepository({ db });
const generateDocumentId = () => 'doc_1';
const file = new File(['content'], 'file.txt', { type: 'text/plain' });
@@ -172,6 +187,8 @@ describe('documents usecases', () => {
subscriptionsRepository,
generateDocumentId,
trackingServices,
+ taggingRulesRepository,
+ tagsRepository,
}),
).rejects.toThrow(new Error('Macron, explosion!'));
diff --git a/apps/papra-server/src/modules/documents/documents.usecases.ts b/apps/papra-server/src/modules/documents/documents.usecases.ts
index 87355be2..d8f27d7d 100644
--- a/apps/papra-server/src/modules/documents/documents.usecases.ts
+++ b/apps/papra-server/src/modules/documents/documents.usecases.ts
@@ -2,6 +2,8 @@ import type { Config } from '../config/config.types';
import type { PlansRepository } from '../plans/plans.repository';
import type { Logger } from '../shared/logger/logger';
import type { SubscriptionsRepository } from '../subscriptions/subscriptions.repository';
+import type { TaggingRulesRepository } from '../tagging-rules/tagging-rules.repository';
+import type { TagsRepository } from '../tags/tags.repository';
import type { TrackingServices } from '../tracking/tracking.services';
import type { DocumentsRepository } from './documents.repository';
import type { DocumentStorageService } from './storage/documents.storage.services';
@@ -9,6 +11,7 @@ import { safely } from '@corentinth/chisels';
import { extractTextFromFile } from '@papra/lecture';
import { checkIfOrganizationCanCreateNewDocument } from '../organizations/organizations.usecases';
import { createLogger } from '../shared/logger/logger';
+import { applyTaggingRules } from '../tagging-rules/tagging-rules.usecases';
import { createDocumentAlreadyExistsError, createDocumentNotFoundError } from './documents.errors';
import { buildOriginalDocumentKey, generateDocumentId as generateDocumentIdImpl } from './documents.models';
import { getFileSha256Hash } from './documents.services';
@@ -37,6 +40,8 @@ export async function createDocument({
plansRepository,
subscriptionsRepository,
trackingServices,
+ taggingRulesRepository,
+ tagsRepository,
logger = createLogger({ namespace: 'documents:usecases' }),
}: {
file: File;
@@ -48,6 +53,8 @@ export async function createDocument({
plansRepository: PlansRepository;
subscriptionsRepository: SubscriptionsRepository;
trackingServices: TrackingServices;
+ taggingRulesRepository: TaggingRulesRepository;
+ tagsRepository: TagsRepository;
logger?: Logger;
}) {
const {
@@ -119,6 +126,8 @@ export async function createDocument({
logger.info({ documentId, userId, organizationId }, 'Document created');
+ await applyTaggingRules({ document: result.document, taggingRulesRepository, tagsRepository });
+
const { document } = result;
return { document };
diff --git a/apps/papra-server/src/modules/intake-emails/intake-emails.routes.ts b/apps/papra-server/src/modules/intake-emails/intake-emails.routes.ts
index 6f9bc8b1..91774f9f 100644
--- a/apps/papra-server/src/modules/intake-emails/intake-emails.routes.ts
+++ b/apps/papra-server/src/modules/intake-emails/intake-emails.routes.ts
@@ -14,6 +14,8 @@ import { getHeader } from '../shared/headers/headers.models';
import { createLogger } from '../shared/logger/logger';
import { validateFormData, validateJsonBody, validateParams } from '../shared/validation/validation';
import { createSubscriptionsRepository } from '../subscriptions/subscriptions.repository';
+import { createTaggingRulesRepository } from '../tagging-rules/tagging-rules.repository';
+import { createTagsRepository } from '../tags/tags.repository';
import { INTAKE_EMAILS_INGEST_ROUTE } from './intake-emails.constants';
import { createIntakeEmailsRepository } from './intake-emails.repository';
import { intakeEmailsIngestionMetaSchema, parseJson } from './intake-emails.schemas';
@@ -190,6 +192,8 @@ function setupIngestIntakeEmailRoute({ app, db, config, trackingServices }: Rout
const documentsStorageService = await createDocumentStorageService({ config });
const plansRepository = createPlansRepository({ config });
const subscriptionsRepository = createSubscriptionsRepository({ db });
+ const taggingRulesRepository = createTaggingRulesRepository({ db });
+ const tagsRepository = createTagsRepository({ db });
await processIntakeEmailIngestion({
fromAddress: email.from.address,
@@ -201,6 +205,8 @@ function setupIngestIntakeEmailRoute({ app, db, config, trackingServices }: Rout
plansRepository,
subscriptionsRepository,
trackingServices,
+ taggingRulesRepository,
+ tagsRepository,
});
return context.body(null, 202);
diff --git a/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.test.ts b/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.test.ts
index 530375d6..5d2ff05d 100644
--- a/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.test.ts
+++ b/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.test.ts
@@ -12,6 +12,8 @@ import { PLUS_PLAN_ID } from '../plans/plans.constants';
import { createPlansRepository } from '../plans/plans.repository';
import { createLogger } from '../shared/logger/logger';
import { createSubscriptionsRepository } from '../subscriptions/subscriptions.repository';
+import { createTaggingRulesRepository } from '../tagging-rules/tagging-rules.repository';
+import { createTagsRepository } from '../tags/tags.repository';
import { createDummyTrackingServices } from '../tracking/tracking.services';
import { createIntakeEmailLimitReachedError } from './intake-emails.errors';
import { createIntakeEmailsRepository } from './intake-emails.repository';
@@ -33,6 +35,8 @@ describe('intake-emails usecases', () => {
const plansRepository = createPlansRepository({ config: { organizationPlans: { isFreePlanUnlimited: true } } as Config });
const subscriptionsRepository = createSubscriptionsRepository({ db });
const trackingServices = createDummyTrackingServices();
+ const taggingRulesRepository = createTaggingRulesRepository({ db });
+ const tagsRepository = createTagsRepository({ db });
await ingestEmailForRecipient({
fromAddress: '[email protected]',
@@ -47,6 +51,8 @@ describe('intake-emails usecases', () => {
plansRepository,
subscriptionsRepository,
trackingServices,
+ taggingRulesRepository,
+ tagsRepository,
});
const documents = await db.select().from(documentsTable).orderBy(asc(documentsTable.name));
@@ -74,6 +80,8 @@ describe('intake-emails usecases', () => {
const plansRepository = createPlansRepository({ config: { organizationPlans: { isFreePlanUnlimited: true } } as Config });
const subscriptionsRepository = createSubscriptionsRepository({ db });
const trackingServices = createDummyTrackingServices();
+ const taggingRulesRepository = createTaggingRulesRepository({ db });
+ const tagsRepository = createTagsRepository({ db });
await ingestEmailForRecipient({
fromAddress: '[email protected]',
@@ -86,6 +94,8 @@ describe('intake-emails usecases', () => {
subscriptionsRepository,
trackingServices,
logger,
+ taggingRulesRepository,
+ tagsRepository,
});
expect(loggerTransport.getLogs({ excludeTimestampMs: true })).to.eql([
@@ -106,6 +116,8 @@ describe('intake-emails usecases', () => {
const plansRepository = createPlansRepository({ config: { organizationPlans: { isFreePlanUnlimited: true } } as Config });
const subscriptionsRepository = createSubscriptionsRepository({ db });
const trackingServices = createDummyTrackingServices();
+ const taggingRulesRepository = createTaggingRulesRepository({ db });
+ const tagsRepository = createTagsRepository({ db });
await ingestEmailForRecipient({
fromAddress: '[email protected]',
@@ -117,6 +129,8 @@ describe('intake-emails usecases', () => {
plansRepository,
subscriptionsRepository,
trackingServices,
+ taggingRulesRepository,
+ tagsRepository,
logger,
});
@@ -143,6 +157,8 @@ describe('intake-emails usecases', () => {
const plansRepository = createPlansRepository({ config: { organizationPlans: { isFreePlanUnlimited: true } } as Config });
const subscriptionsRepository = createSubscriptionsRepository({ db });
const trackingServices = createDummyTrackingServices();
+ const taggingRulesRepository = createTaggingRulesRepository({ db });
+ const tagsRepository = createTagsRepository({ db });
await ingestEmailForRecipient({
fromAddress: '[email protected]',
@@ -154,6 +170,8 @@ describe('intake-emails usecases', () => {
plansRepository,
subscriptionsRepository,
trackingServices,
+ taggingRulesRepository,
+ tagsRepository,
logger,
});
@@ -191,6 +209,8 @@ describe('intake-emails usecases', () => {
const plansRepository = createPlansRepository({ config: { organizationPlans: { isFreePlanUnlimited: true } } as Config });
const subscriptionsRepository = createSubscriptionsRepository({ db });
const trackingServices = createDummyTrackingServices();
+ const taggingRulesRepository = createTaggingRulesRepository({ db });
+ const tagsRepository = createTagsRepository({ db });
await processIntakeEmailIngestion({
fromAddress: '[email protected]',
@@ -204,6 +224,8 @@ describe('intake-emails usecases', () => {
plansRepository,
subscriptionsRepository,
trackingServices,
+ taggingRulesRepository,
+ tagsRepository,
});
const documents = await db.select().from(documentsTable).orderBy(asc(documentsTable.organizationId));
diff --git a/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.ts b/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.ts
index 68bdfdc4..26482217 100644
--- a/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.ts
+++ b/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.ts
@@ -3,6 +3,8 @@ import type { DocumentStorageService } from '../documents/storage/documents.stor
import type { PlansRepository } from '../plans/plans.repository';
import type { Logger } from '../shared/logger/logger';
import type { SubscriptionsRepository } from '../subscriptions/subscriptions.repository';
+import type { TaggingRulesRepository } from '../tagging-rules/tagging-rules.repository';
+import type { TagsRepository } from '../tags/tags.repository';
import type { TrackingServices } from '../tracking/tracking.services';
import type { IntakeEmailsServices } from './drivers/intake-emails.drivers.models';
import type { IntakeEmailsRepository } from './intake-emails.repository';
@@ -50,6 +52,8 @@ export function processIntakeEmailIngestion({
plansRepository,
subscriptionsRepository,
trackingServices,
+ taggingRulesRepository,
+ tagsRepository,
}: {
fromAddress: string;
recipientsAddresses: string[];
@@ -60,6 +64,8 @@ export function processIntakeEmailIngestion({
plansRepository: PlansRepository;
subscriptionsRepository: SubscriptionsRepository;
trackingServices: TrackingServices;
+ taggingRulesRepository: TaggingRulesRepository;
+ tagsRepository: TagsRepository;
}) {
return Promise.all(
recipientsAddresses.map(recipientAddress => safely(
@@ -73,6 +79,8 @@ export function processIntakeEmailIngestion({
plansRepository,
subscriptionsRepository,
trackingServices,
+ taggingRulesRepository,
+ tagsRepository,
}),
)),
);
@@ -89,6 +97,8 @@ export async function ingestEmailForRecipient({
plansRepository,
trackingServices,
subscriptionsRepository,
+ taggingRulesRepository,
+ tagsRepository,
}: {
fromAddress: string;
recipientAddress: string;
@@ -99,6 +109,8 @@ export async function ingestEmailForRecipient({
plansRepository: PlansRepository;
subscriptionsRepository: SubscriptionsRepository;
trackingServices: TrackingServices;
+ taggingRulesRepository: TaggingRulesRepository;
+ tagsRepository: TagsRepository;
logger?: Logger;
}) {
const { intakeEmail } = await intakeEmailsRepository.getIntakeEmailByEmailAddress({ emailAddress: recipientAddress });
@@ -137,6 +149,8 @@ export async function ingestEmailForRecipient({
plansRepository,
subscriptionsRepository,
trackingServices,
+ taggingRulesRepository,
+ tagsRepository,
}));
if (error) {
diff --git a/apps/papra-server/src/modules/shared/logger/logger.test-utils.ts b/apps/papra-server/src/modules/shared/logger/logger.test-utils.ts
new file mode 100644
index 00000000..98fe550f
--- /dev/null
+++ b/apps/papra-server/src/modules/shared/logger/logger.test-utils.ts
@@ -0,0 +1,11 @@
+import { createInMemoryLoggerTransport, createLogger } from '@crowlog/logger';
+
+export function createTestLogger({ namespace = 'test' }: { namespace?: string } = {}) {
+ const transport = createInMemoryLoggerTransport();
+ const logger = createLogger({ namespace, transports: [transport] });
+
+ return {
+ logger,
+ getLogs: transport.getLogs,
+ };
+}
diff --git a/apps/papra-server/src/modules/tagging-rules/conditions/tagging-rule-conditions.models.test.ts b/apps/papra-server/src/modules/tagging-rules/conditions/tagging-rule-conditions.models.test.ts
new file mode 100644
index 00000000..5d089c25
--- /dev/null
+++ b/apps/papra-server/src/modules/tagging-rules/conditions/tagging-rule-conditions.models.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, test } from 'vitest';
+import { equalTaggingRuleCondition } from './tagging-rule-conditions.models';
+
+describe('equal tagging-rule-condition', () => {
+ describe('equalTaggingRuleCondition', () => {
+ const { validate, operator } = equalTaggingRuleCondition;
+
+ test('the operator is equal', () => {
+ expect(operator).to.equal('equal');
+ });
+
+ test('the condition is valid is the field value is strictly equal to the condition value', () => {
+ expect(validate({ conditionValue: 'test', fieldValue: 'test', isCaseSensitive: true })).to.equal(true);
+ expect(validate({ conditionValue: 'test', fieldValue: 'testa', isCaseSensitive: true })).to.equal(false);
+ expect(validate({ conditionValue: 'test', fieldValue: 'testa', isCaseSensitive: false })).to.equal(false);
+ expect(validate({ conditionValue: 'test', fieldValue: 'test', isCaseSensitive: false })).to.equal(true);
+ expect(validate({ conditionValue: 'test', fieldValue: 'TEST', isCaseSensitive: false })).to.equal(true);
+ expect(validate({ conditionValue: 'test', fieldValue: 'TEST', isCaseSensitive: true })).to.equal(false);
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/tagging-rules/conditions/tagging-rule-conditions.models.ts b/apps/papra-server/src/modules/tagging-rules/conditions/tagging-rule-conditions.models.ts
new file mode 100644
index 00000000..2e3960bd
--- /dev/null
+++ b/apps/papra-server/src/modules/tagging-rules/conditions/tagging-rule-conditions.models.ts
@@ -0,0 +1,61 @@
+import type { TaggingRuleConditionDefinition, TaggingRuleConditionDefinitionValidator, TaggingRuleConditionDefinitionValidatorArguments } from './tagging-rule-conditions.types';
+import { TAGGING_RULE_OPERATORS } from '../tagging-rules.constants';
+import { defineTaggingRuleCondition } from './tagging-rule-conditions.registry.models';
+
+function negateValidator({ validate }: TaggingRuleConditionDefinition): TaggingRuleConditionDefinitionValidator {
+ return (args: TaggingRuleConditionDefinitionValidatorArguments) => !validate(args);
+}
+
+export const equalTaggingRuleCondition = defineTaggingRuleCondition({
+ operator: TAGGING_RULE_OPERATORS.EQUAL,
+ validate: ({ conditionValue, fieldValue, isCaseSensitive }) => {
+ if (isCaseSensitive) {
+ return conditionValue === fieldValue;
+ }
+
+ return conditionValue.toLowerCase() === fieldValue.toLowerCase();
+ },
+});
+
+export const notEqualTaggingRuleCondition = defineTaggingRuleCondition({
+ operator: TAGGING_RULE_OPERATORS.NOT_EQUAL,
+ validate: negateValidator(equalTaggingRuleCondition),
+});
+
+export const containsTaggingRuleCondition = defineTaggingRuleCondition({
+ operator: TAGGING_RULE_OPERATORS.CONTAINS,
+ validate: ({ conditionValue, fieldValue, isCaseSensitive }) => {
+ if (isCaseSensitive) {
+ return fieldValue.includes(conditionValue);
+ }
+
+ return fieldValue.toLowerCase().includes(conditionValue.toLowerCase());
+ },
+});
+
+export const notContainsTaggingRuleCondition = defineTaggingRuleCondition({
+ operator: TAGGING_RULE_OPERATORS.NOT_CONTAINS,
+ validate: negateValidator(containsTaggingRuleCondition),
+});
+
+export const startsWithTaggingRuleCondition = defineTaggingRuleCondition({
+ operator: TAGGING_RULE_OPERATORS.STARTS_WITH,
+ validate: ({ conditionValue, fieldValue, isCaseSensitive }) => {
+ if (isCaseSensitive) {
+ return fieldValue.startsWith(conditionValue);
+ }
+
+ return fieldValue.toLowerCase().startsWith(conditionValue.toLowerCase());
+ },
+});
+
+export const endsWithTaggingRuleCondition = defineTaggingRuleCondition({
+ operator: TAGGING_RULE_OPERATORS.ENDS_WITH,
+ validate: ({ conditionValue, fieldValue, isCaseSensitive }) => {
+ if (isCaseSensitive) {
+ return fieldValue.endsWith(conditionValue);
+ }
+
+ return fieldValue.toLowerCase().endsWith(conditionValue.toLowerCase());
+ },
+});
diff --git a/apps/papra-server/src/modules/tagging-rules/conditions/tagging-rule-conditions.registry.models.ts b/apps/papra-server/src/modules/tagging-rules/conditions/tagging-rule-conditions.registry.models.ts
new file mode 100644
index 00000000..579633b5
--- /dev/null
+++ b/apps/papra-server/src/modules/tagging-rules/conditions/tagging-rule-conditions.registry.models.ts
@@ -0,0 +1,5 @@
+import type { TaggingRuleConditionDefinition } from './tagging-rule-conditions.types';
+
+export function defineTaggingRuleCondition(args: TaggingRuleConditionDefinition) {
+ return args;
+}
diff --git a/apps/papra-server/src/modules/tagging-rules/conditions/tagging-rule-conditions.registry.test.ts b/apps/papra-server/src/modules/tagging-rules/conditions/tagging-rule-conditions.registry.test.ts
new file mode 100644
index 00000000..235780f4
--- /dev/null
+++ b/apps/papra-server/src/modules/tagging-rules/conditions/tagging-rule-conditions.registry.test.ts
@@ -0,0 +1,15 @@
+import { describe, expect, test } from 'vitest';
+import { TAGGING_RULE_OPERATORS } from '../tagging-rules.constants';
+import { taggingRuleOperatorDefinitions } from './tagging-rule-conditions.registry';
+
+describe('tagging-rule-conditions registry', () => {
+ describe('taggingRuleOperatorDefinitions', () => {
+ test('all defined allowed operators must have a corresponding tagging rule condition definition', () => {
+ const allowedOperators = Object.values(TAGGING_RULE_OPERATORS);
+
+ const missingOperators = allowedOperators.filter(operator => !taggingRuleOperatorDefinitions.some(taggingRuleOperatorDefinition => taggingRuleOperatorDefinition.operator === operator));
+
+ expect(missingOperators).to.deep.equal([], `Missing tagging rule operator definitions for operators: ${missingOperators.map(operator => `"${operator}"`).join(', ')}`);
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/tagging-rules/conditions/tagging-rule-conditions.registry.ts b/apps/papra-server/src/modules/tagging-rules/conditions/tagging-rule-conditions.registry.ts
new file mode 100644
index 00000000..3e520eb1
--- /dev/null
+++ b/apps/papra-server/src/modules/tagging-rules/conditions/tagging-rule-conditions.registry.ts
@@ -0,0 +1,43 @@
+import { createError } from '../../shared/errors/errors';
+import {
+ containsTaggingRuleCondition,
+ endsWithTaggingRuleCondition,
+ equalTaggingRuleCondition,
+ notContainsTaggingRuleCondition,
+ notEqualTaggingRuleCondition,
+ startsWithTaggingRuleCondition,
+} from './tagging-rule-conditions.models';
+
+export const taggingRuleOperatorDefinitions = [
+ equalTaggingRuleCondition,
+ notEqualTaggingRuleCondition,
+ containsTaggingRuleCondition,
+ notContainsTaggingRuleCondition,
+ startsWithTaggingRuleCondition,
+ endsWithTaggingRuleCondition,
+];
+
+const taggingRuleOperatorDefinitionsByOperator = Object.fromEntries(taggingRuleOperatorDefinitions.map(taggingRuleOperatorDefinition => [taggingRuleOperatorDefinition.operator, taggingRuleOperatorDefinition]));
+
+export type TaggingRuleOperatorValidatorRegistry = ReturnType<typeof createTaggingRuleOperatorValidatorRegistry>;
+
+export function createTaggingRuleOperatorValidatorRegistry() {
+ return {
+ getTaggingRuleOperatorValidator,
+ };
+}
+
+function getTaggingRuleOperatorValidator({ operator }: { operator: string }) {
+ const taggingRuleOperatorDefinition = taggingRuleOperatorDefinitionsByOperator[operator];
+
+ if (!taggingRuleOperatorDefinition) {
+ throw createError({
+ message: `Tagging rule condition for operator ${operator} not found`,
+ code: 'tagging_rules.condition_not_found',
+ statusCode: 400,
+ isInternal: true,
+ });
+ }
+
+ return taggingRuleOperatorDefinition;
+}
diff --git a/apps/papra-server/src/modules/tagging-rules/conditions/tagging-rule-conditions.types.ts b/apps/papra-server/src/modules/tagging-rules/conditions/tagging-rule-conditions.types.ts
new file mode 100644
index 00000000..64a4a73f
--- /dev/null
+++ b/apps/papra-server/src/modules/tagging-rules/conditions/tagging-rule-conditions.types.ts
@@ -0,0 +1,14 @@
+import type { TaggingRuleOperator } from '../tagging-rules.types';
+
+export type TaggingRuleConditionDefinitionValidatorArguments = {
+ conditionValue: string;
+ fieldValue: string;
+ isCaseSensitive: boolean;
+};
+
+export type TaggingRuleConditionDefinitionValidator = (args: TaggingRuleConditionDefinitionValidatorArguments) => boolean;
+
+export type TaggingRuleConditionDefinition = {
+ operator: TaggingRuleOperator;
+ validate: TaggingRuleConditionDefinitionValidator;
+};
diff --git a/apps/papra-server/src/modules/tagging-rules/tagging-rules.constants.ts b/apps/papra-server/src/modules/tagging-rules/tagging-rules.constants.ts
new file mode 100644
index 00000000..f31abf23
--- /dev/null
+++ b/apps/papra-server/src/modules/tagging-rules/tagging-rules.constants.ts
@@ -0,0 +1,18 @@
+import type { DbSelectableDocument } from '../documents/documents.types';
+
+export const taggingRuleIdPrefix = 'tr';
+export const taggingRuleIdRegex = new RegExp(`^${taggingRuleIdPrefix}_[a-z0-9]{24}$`);
+
+export const TAGGING_RULE_OPERATORS = {
+ EQUAL: 'equal',
+ NOT_EQUAL: 'not_equal',
+ CONTAINS: 'contains',
+ NOT_CONTAINS: 'not_contains',
+ STARTS_WITH: 'starts_with',
+ ENDS_WITH: 'ends_with',
+} as const;
+
+export const TAGGING_RULE_FIELDS = {
+ DOCUMENT_NAME: 'name',
+ DOCUMENT_CONTENT: 'content',
+} as const satisfies Record<string, keyof DbSelectableDocument>;
diff --git a/apps/papra-server/src/modules/tagging-rules/tagging-rules.models.ts b/apps/papra-server/src/modules/tagging-rules/tagging-rules.models.ts
new file mode 100644
index 00000000..fa147e97
--- /dev/null
+++ b/apps/papra-server/src/modules/tagging-rules/tagging-rules.models.ts
@@ -0,0 +1,8 @@
+import type { Document } from '../documents/documents.types';
+import { get } from 'lodash-es';
+
+export function getDocumentFieldValue({ document, field }: { document: Document; field: string }) {
+ const fieldValue = get(document, field);
+
+ return { fieldValue };
+}
diff --git a/apps/papra-server/src/modules/tagging-rules/tagging-rules.repository.models.ts b/apps/papra-server/src/modules/tagging-rules/tagging-rules.repository.models.ts
new file mode 100644
index 00000000..e93cf674
--- /dev/null
+++ b/apps/papra-server/src/modules/tagging-rules/tagging-rules.repository.models.ts
@@ -0,0 +1,43 @@
+import type { TaggingRule, TaggingRuleAction, TaggingRuleCondition } from './tagging-rules.types';
+
+export function aggregateTaggingRules({
+ rawTaggingRules,
+}: {
+ rawTaggingRules: {
+ tagging_rules: TaggingRule;
+ tagging_rule_conditions: TaggingRuleCondition | null;
+ tagging_rule_actions: TaggingRuleAction | null;
+ }[];
+}) {
+ const taggingRulesRecord = rawTaggingRules.reduce((acc, rawTaggingRule) => {
+ const { id: taggingRuleId } = rawTaggingRule.tagging_rules;
+
+ if (!acc[taggingRuleId]) {
+ acc[taggingRuleId] = {
+ ...rawTaggingRule.tagging_rules,
+ conditions: {},
+ actions: {},
+ };
+ }
+
+ if (rawTaggingRule.tagging_rule_conditions) {
+ acc[taggingRuleId].conditions[rawTaggingRule.tagging_rule_conditions.id] = rawTaggingRule.tagging_rule_conditions;
+ }
+
+ if (rawTaggingRule.tagging_rule_actions) {
+ acc[taggingRuleId].actions[rawTaggingRule.tagging_rule_actions.id] = rawTaggingRule.tagging_rule_actions;
+ }
+
+ return acc;
+ }, {} as Record<string, TaggingRule & { conditions: Record<string, TaggingRuleCondition>; actions: Record<string, TaggingRuleAction> }>);
+
+ return {
+ taggingRules: Object
+ .values(taggingRulesRecord)
+ .map(taggingRule => ({
+ ...taggingRule,
+ conditions: Object.values(taggingRule.conditions),
+ actions: Object.values(taggingRule.actions),
+ })),
+ };
+}
diff --git a/apps/papra-server/src/modules/tagging-rules/tagging-rules.repository.ts b/apps/papra-server/src/modules/tagging-rules/tagging-rules.repository.ts
new file mode 100644
index 00000000..d8fb1b42
--- /dev/null
+++ b/apps/papra-server/src/modules/tagging-rules/tagging-rules.repository.ts
@@ -0,0 +1,143 @@
+import type { Database } from '../app/database/database.types';
+import type { DbInsertableTaggingRule, TaggingRuleField, TaggingRuleOperator } from './tagging-rules.types';
+import { injectArguments } from '@corentinth/chisels';
+import { and, eq } from 'drizzle-orm';
+import { createError } from '../shared/errors/errors';
+import { omitUndefined } from '../shared/utils';
+import { aggregateTaggingRules } from './tagging-rules.repository.models';
+import { taggingRuleActionsTable, taggingRuleConditionsTable, taggingRulesTable } from './tagging-rules.tables';
+
+export type TaggingRulesRepository = ReturnType<typeof createTaggingRulesRepository>;
+
+export function createTaggingRulesRepository({ db }: { db: Database }) {
+ return injectArguments(
+ {
+ getOrganizationTaggingRules,
+ getOrganizationEnabledTaggingRules,
+ getOrganizationTaggingRule,
+ createTaggingRule,
+ deleteOrganizationTaggingRule,
+ updateOrganizationTaggingRule,
+ createTaggingRuleConditions,
+ createTaggingRuleActions,
+ },
+ { db },
+ );
+}
+
+async function getOrganizationTaggingRules({ organizationId, db }: { organizationId: string; db: Database }) {
+ const rawTaggingRules = await db
+ .select()
+ .from(taggingRulesTable)
+ .where(eq(taggingRulesTable.organizationId, organizationId))
+ .leftJoin(taggingRuleConditionsTable, eq(taggingRulesTable.id, taggingRuleConditionsTable.taggingRuleId))
+ .leftJoin(taggingRuleActionsTable, eq(taggingRulesTable.id, taggingRuleActionsTable.taggingRuleId));
+
+ return aggregateTaggingRules({ rawTaggingRules });
+}
+
+async function getOrganizationTaggingRule({ organizationId, taggingRuleId, db }: { organizationId: string; taggingRuleId: string; db: Database }) {
+ const rawTaggingRules = await db
+ .select()
+ .from(taggingRulesTable)
+ .where(and(eq(taggingRulesTable.id, taggingRuleId), eq(taggingRulesTable.organizationId, organizationId)))
+ .leftJoin(taggingRuleConditionsTable, eq(taggingRulesTable.id, taggingRuleConditionsTable.taggingRuleId))
+ .leftJoin(taggingRuleActionsTable, eq(taggingRulesTable.id, taggingRuleActionsTable.taggingRuleId));
+
+ const { taggingRules = [] } = aggregateTaggingRules({ rawTaggingRules });
+ const [taggingRule] = taggingRules;
+
+ return {
+ taggingRule,
+ };
+}
+
+async function getOrganizationEnabledTaggingRules({ organizationId, db }: { organizationId: string; db: Database }) {
+ const rawTaggingRules = await db
+ .select()
+ .from(taggingRulesTable)
+ .where(and(
+ eq(taggingRulesTable.organizationId, organizationId),
+ eq(taggingRulesTable.enabled, true),
+ ))
+ .leftJoin(taggingRuleConditionsTable, eq(taggingRulesTable.id, taggingRuleConditionsTable.taggingRuleId))
+ .leftJoin(taggingRuleActionsTable, eq(taggingRulesTable.id, taggingRuleActionsTable.taggingRuleId));
+
+ return aggregateTaggingRules({ rawTaggingRules });
+}
+
+async function createTaggingRule({ taggingRule, db }: { taggingRule: DbInsertableTaggingRule; db: Database }) {
+ const [createdTaggingRule] = await db.insert(taggingRulesTable).values(taggingRule).returning();
+
+ return { taggingRule: createdTaggingRule };
+}
+
+async function deleteOrganizationTaggingRule({ organizationId, taggingRuleId, db }: { organizationId: string; taggingRuleId: string; db: Database }) {
+ await db
+ .delete(taggingRulesTable)
+ .where(and(
+ eq(taggingRulesTable.id, taggingRuleId),
+ eq(taggingRulesTable.organizationId, organizationId),
+ ));
+}
+
+async function updateOrganizationTaggingRule({
+ organizationId,
+ taggingRuleId,
+ taggingRule,
+ db,
+}: {
+ organizationId: string;
+ taggingRuleId: string;
+ taggingRule: {
+ name: string;
+ description: string | undefined;
+ enabled: boolean | undefined;
+ conditions: { field: TaggingRuleField; operator: TaggingRuleOperator; value: string }[];
+ tagIds: string[];
+ };
+ db: Database;
+}) {
+ const { name, description, enabled, conditions, tagIds } = taggingRule;
+
+ await db.transaction(async (tx) => {
+ const [updatedTaggingRule] = await tx
+ .update(taggingRulesTable)
+ .set(omitUndefined({ name, description, enabled }))
+ .where(and(
+ eq(taggingRulesTable.id, taggingRuleId),
+ eq(taggingRulesTable.organizationId, organizationId),
+ ))
+ .returning();
+
+ if (!updatedTaggingRule) {
+ throw createError({ statusCode: 404, message: 'Tagging rule not found', code: 'tagging-rules.not-found' });
+ }
+
+ // Recreate conditions
+ await tx.delete(taggingRuleConditionsTable).where(eq(taggingRuleConditionsTable.taggingRuleId, taggingRuleId));
+ if (conditions.length > 0) {
+ await tx.insert(taggingRuleConditionsTable).values(conditions.map(condition => ({ ...condition, taggingRuleId })));
+ }
+
+ // Recreate actions
+ await tx.delete(taggingRuleActionsTable).where(eq(taggingRuleActionsTable.taggingRuleId, taggingRuleId));
+ await tx.insert(taggingRuleActionsTable).values(tagIds.map(tagId => ({ taggingRuleId, tagId })));
+ });
+}
+
+async function createTaggingRuleConditions({ taggingRuleId, conditions, db }: { taggingRuleId: string; conditions: {
+ field: TaggingRuleField;
+ operator: TaggingRuleOperator;
+ value: string;
+}[]; db: Database ; }) {
+ await db
+ .insert(taggingRuleConditionsTable)
+ .values(conditions.map(condition => ({ ...condition, taggingRuleId })));
+}
+
+async function createTaggingRuleActions({ taggingRuleId, tagIds, db }: { taggingRuleId: string; tagIds: string[]; db: Database }) {
+ await db
+ .insert(taggingRuleActionsTable)
+ .values(tagIds.map(tagId => ({ taggingRuleId, tagId })));
+}
diff --git a/apps/papra-server/src/modules/tagging-rules/tagging-rules.routes.ts b/apps/papra-server/src/modules/tagging-rules/tagging-rules.routes.ts
new file mode 100644
index 00000000..108b74d7
--- /dev/null
+++ b/apps/papra-server/src/modules/tagging-rules/tagging-rules.routes.ts
@@ -0,0 +1,170 @@
+import type { RouteDefinitionContext } from '../app/server.types';
+import type { TaggingRuleField, TaggingRuleOperator } from './tagging-rules.types';
+import { z } from 'zod';
+import { getUser } from '../app/auth/auth.models';
+import { organizationIdRegex } from '../organizations/organizations.constants';
+import { createOrganizationsRepository } from '../organizations/organizations.repository';
+import { ensureUserIsInOrganization } from '../organizations/organizations.usecases';
+import { validateJsonBody, validateParams } from '../shared/validation/validation';
+import { tagIdRegex } from '../tags/tags.constants';
+import { TAGGING_RULE_FIELDS, TAGGING_RULE_OPERATORS, taggingRuleIdRegex } from './tagging-rules.constants';
+import { createTaggingRulesRepository } from './tagging-rules.repository';
+import { createTaggingRule } from './tagging-rules.usecases';
+
+export function registerTaggingRulesRoutes(context: RouteDefinitionContext) {
+ setupGetOrganizationTaggingRulesRoute(context);
+ setupCreateTaggingRuleRoute(context);
+ setupDeleteTaggingRuleRoute(context);
+ setupGetTaggingRuleRoute(context);
+ setupUpdateTaggingRuleRoute(context);
+}
+
+function setupGetOrganizationTaggingRulesRoute({ app, db }: RouteDefinitionContext) {
+ app.get(
+ '/api/organizations/:organizationId/tagging-rules',
+ validateParams(z.object({
+ organizationId: z.string().regex(organizationIdRegex),
+ })),
+ async (context) => {
+ const { userId } = getUser({ context });
+
+ const { organizationId } = context.req.valid('param');
+
+ const taggingRulesRepository = createTaggingRulesRepository({ db });
+ const organizationsRepository = createOrganizationsRepository({ db });
+
+ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });
+
+ const { taggingRules } = await taggingRulesRepository.getOrganizationTaggingRules({ organizationId });
+
+ return context.json({
+ taggingRules,
+ });
+ },
+ );
+}
+
+function setupCreateTaggingRuleRoute({ app, db }: RouteDefinitionContext) {
+ app.post(
+ '/api/organizations/:organizationId/tagging-rules',
+ validateParams(z.object({
+ organizationId: z.string().regex(organizationIdRegex),
+ })),
+ validateJsonBody(z.object({
+ name: z.string().min(1).max(64),
+ description: z.string().max(256).optional(),
+ enabled: z.boolean().optional(),
+ conditions: z.array(z.object({
+ field: z.enum(Object.values(TAGGING_RULE_FIELDS) as [TaggingRuleField, ...TaggingRuleField[]]), // casting since zod require non-empty array
+ operator: z.enum(Object.values(TAGGING_RULE_OPERATORS) as [TaggingRuleOperator, ...TaggingRuleOperator[]]), // casting since zod require non-empty array
+ value: z.string().min(1).max(256),
+ })),
+ tagIds: z.array(z.string().regex(tagIdRegex)).min(1),
+ })),
+ async (context) => {
+ const { userId } = getUser({ context });
+
+ const { organizationId } = context.req.valid('param');
+ const { name, description, enabled, conditions, tagIds } = context.req.valid('json');
+
+ const taggingRulesRepository = createTaggingRulesRepository({ db });
+ const organizationsRepository = createOrganizationsRepository({ db });
+
+ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });
+
+ await createTaggingRule({ name, description, enabled, conditions, tagIds, organizationId, taggingRulesRepository });
+
+ return context.body(null, 204);
+ },
+ );
+}
+
+function setupDeleteTaggingRuleRoute({ app, db }: RouteDefinitionContext) {
+ app.delete(
+ '/api/organizations/:organizationId/tagging-rules/:taggingRuleId',
+ validateParams(z.object({
+ organizationId: z.string().regex(organizationIdRegex),
+ taggingRuleId: z.string().regex(taggingRuleIdRegex),
+ })),
+ async (context) => {
+ const { userId } = getUser({ context });
+
+ const { organizationId, taggingRuleId } = context.req.valid('param');
+
+ const taggingRulesRepository = createTaggingRulesRepository({ db });
+ const organizationsRepository = createOrganizationsRepository({ db });
+
+ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });
+
+ await taggingRulesRepository.deleteOrganizationTaggingRule({ organizationId, taggingRuleId });
+
+ return context.body(null, 204);
+ },
+ );
+}
+
+function setupGetTaggingRuleRoute({ app, db }: RouteDefinitionContext) {
+ app.get(
+ '/api/organizations/:organizationId/tagging-rules/:taggingRuleId',
+ validateParams(z.object({
+ organizationId: z.string().regex(organizationIdRegex),
+ taggingRuleId: z.string().regex(taggingRuleIdRegex),
+ })),
+ async (context) => {
+ const { userId } = getUser({ context });
+
+ const { organizationId, taggingRuleId } = context.req.valid('param');
+
+ const taggingRulesRepository = createTaggingRulesRepository({ db });
+ const organizationsRepository = createOrganizationsRepository({ db });
+
+ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });
+
+ const { taggingRule } = await taggingRulesRepository.getOrganizationTaggingRule({ organizationId, taggingRuleId });
+
+ return context.json({
+ taggingRule,
+ });
+ },
+ );
+}
+
+function setupUpdateTaggingRuleRoute({ app, db }: RouteDefinitionContext) {
+ app.put(
+ '/api/organizations/:organizationId/tagging-rules/:taggingRuleId',
+ validateParams(z.object({
+ organizationId: z.string().regex(organizationIdRegex),
+ taggingRuleId: z.string().regex(taggingRuleIdRegex),
+ })),
+ validateJsonBody(z.object({
+ name: z.string().min(1).max(64),
+ description: z.string().max(256).optional(),
+ enabled: z.boolean().optional(),
+ conditions: z.array(z.object({
+ field: z.enum(Object.values(TAGGING_RULE_FIELDS) as [TaggingRuleField, ...TaggingRuleField[]]), // casting since zod require non-empty array
+ operator: z.enum(Object.values(TAGGING_RULE_OPERATORS) as [TaggingRuleOperator, ...TaggingRuleOperator[]]), // casting since zod require non-empty array
+ value: z.string().min(1).max(256),
+ })).max(10),
+ tagIds: z.array(z.string().regex(tagIdRegex)).min(1),
+ })),
+ async (context) => {
+ const { userId } = getUser({ context });
+
+ const { organizationId, taggingRuleId } = context.req.valid('param');
+ const { name, description, enabled, conditions, tagIds } = context.req.valid('json');
+
+ const taggingRulesRepository = createTaggingRulesRepository({ db });
+ const organizationsRepository = createOrganizationsRepository({ db });
+
+ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });
+
+ await taggingRulesRepository.updateOrganizationTaggingRule({
+ organizationId,
+ taggingRuleId,
+ taggingRule: { name, description, enabled, conditions, tagIds },
+ });
+
+ return context.body(null, 204);
+ },
+ );
+}
diff --git a/apps/papra-server/src/modules/tagging-rules/tagging-rules.tables.ts b/apps/papra-server/src/modules/tagging-rules/tagging-rules.tables.ts
new file mode 100644
index 00000000..762ca0be
--- /dev/null
+++ b/apps/papra-server/src/modules/tagging-rules/tagging-rules.tables.ts
@@ -0,0 +1,44 @@
+import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';
+
+import { organizationsTable } from '../organizations/organizations.table';
+import { createPrimaryKeyField, createTimestampColumns } from '../shared/db/columns.helpers';
+import { tagsTable } from '../tags/tags.table';
+import { taggingRuleIdPrefix } from './tagging-rules.constants';
+
+export const taggingRulesTable = sqliteTable(
+ 'tagging_rules',
+ {
+ ...createPrimaryKeyField({ prefix: taggingRuleIdPrefix }),
+ ...createTimestampColumns(),
+
+ organizationId: text('organization_id').notNull().references(() => organizationsTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),
+ name: text('name').notNull(),
+ description: text('description'),
+ enabled: integer('enabled', { mode: 'boolean' }).notNull().default(true),
+ },
+);
+
+export const taggingRuleConditionsTable = sqliteTable(
+ 'tagging_rule_conditions',
+ {
+ ...createPrimaryKeyField({ prefix: 'trc' }),
+ ...createTimestampColumns(),
+
+ taggingRuleId: text('tagging_rule_id').notNull().references(() => taggingRulesTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),
+ field: text('field').notNull(),
+ operator: text('operator').notNull(),
+ value: text('value').notNull(),
+ isCaseSensitive: integer('is_case_sensitive', { mode: 'boolean' }).notNull().default(false),
+ },
+);
+
+export const taggingRuleActionsTable = sqliteTable(
+ 'tagging_rule_actions',
+ {
+ ...createPrimaryKeyField({ prefix: 'tra' }),
+ ...createTimestampColumns(),
+
+ taggingRuleId: text('tagging_rule_id').notNull().references(() => taggingRulesTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),
+ tagId: text('tag_id').notNull().references(() => tagsTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),
+ },
+);
diff --git a/apps/papra-server/src/modules/tagging-rules/tagging-rules.types.ts b/apps/papra-server/src/modules/tagging-rules/tagging-rules.types.ts
new file mode 100644
index 00000000..1d267e21
--- /dev/null
+++ b/apps/papra-server/src/modules/tagging-rules/tagging-rules.types.ts
@@ -0,0 +1,14 @@
+import type { Expand } from '@corentinth/chisels';
+import type { TAGGING_RULE_FIELDS, TAGGING_RULE_OPERATORS } from './tagging-rules.constants';
+import type { taggingRuleActionsTable, taggingRuleConditionsTable, taggingRulesTable } from './tagging-rules.tables';
+
+export type DbInsertableTaggingRule = typeof taggingRulesTable.$inferInsert;
+export type DbInsertableTaggingRuleCondition = typeof taggingRuleConditionsTable.$inferInsert;
+export type DbInsertableTaggingRuleAction = typeof taggingRuleActionsTable.$inferInsert;
+
+export type TaggingRuleField = (typeof TAGGING_RULE_FIELDS)[keyof typeof TAGGING_RULE_FIELDS];
+export type TaggingRuleOperator = (typeof TAGGING_RULE_OPERATORS)[keyof typeof TAGGING_RULE_OPERATORS];
+
+export type TaggingRule = Expand<typeof taggingRulesTable.$inferSelect>;
+export type TaggingRuleCondition = Expand<typeof taggingRuleConditionsTable.$inferSelect>;
+export type TaggingRuleAction = Expand<typeof taggingRuleActionsTable.$inferSelect>;
diff --git a/apps/papra-server/src/modules/tagging-rules/tagging-rules.usecases.test.ts b/apps/papra-server/src/modules/tagging-rules/tagging-rules.usecases.test.ts
new file mode 100644
index 00000000..dbf24cbd
--- /dev/null
+++ b/apps/papra-server/src/modules/tagging-rules/tagging-rules.usecases.test.ts
@@ -0,0 +1,91 @@
+import { eq } from 'drizzle-orm';
+import { describe, expect, test } from 'vitest';
+import { createInMemoryDatabase } from '../app/database/database.test-utils';
+import { documentsTable } from '../documents/documents.table';
+import { createTestLogger } from '../shared/logger/logger.test-utils';
+import { createTagsRepository } from '../tags/tags.repository';
+import { documentsTagsTable } from '../tags/tags.table';
+import { createTaggingRulesRepository } from './tagging-rules.repository';
+import { applyTaggingRules } from './tagging-rules.usecases';
+
+describe('tagging-rules usecases', () => {
+ describe('applyTaggingRules', () => {
+ test('when a document matches a tagging rule, the tag is applied to the document', async () => {
+ const { logger, getLogs } = createTestLogger();
+
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org_1', name: 'Org 1' }],
+ tags: [{ id: 'tag_1', name: 'Tag 1', color: '#000000', organizationId: 'org_1' }],
+ documents: [{ id: 'doc_1', organizationId: 'org_1', name: 'Doc 1', originalName: 'Doc 1', originalStorageKey: 'doc_1', originalSha256Hash: 'doc_1', mimeType: 'text/plain' }],
+
+ taggingRules: [{ id: 'tr_1', organizationId: 'org_1', name: 'Tagging Rule 1' }],
+ taggingRuleConditions: [{ id: 'trc_1', taggingRuleId: 'tr_1', field: 'name', operator: 'equal', value: 'Doc 1' }],
+ taggingRuleActions: [{ id: 'tra_1', taggingRuleId: 'tr_1', tagId: 'tag_1' }],
+ });
+
+ const [document] = await db.select().from(documentsTable).where(eq(documentsTable.id, 'doc_1'));
+
+ const taggingRulesRepository = createTaggingRulesRepository({ db });
+ const tagsRepository = createTagsRepository({ db });
+
+ await applyTaggingRules({ document, taggingRulesRepository, tagsRepository, logger });
+
+ const documentTags = await db.select().from(documentsTagsTable);
+
+ expect(documentTags).to.eql([{ documentId: 'doc_1', tagId: 'tag_1' }]);
+
+ expect(getLogs({ excludeTimestampMs: true })).to.eql([
+ {
+ data: {
+ tagIdsToApply: ['tag_1'],
+ appliedTagIds: ['tag_1'],
+ taggingRulesIdsToApply: ['tr_1'],
+ hasAllTagBeenApplied: true,
+ },
+ level: 'info',
+ message: 'Tagging rules applied',
+ namespace: 'test',
+ },
+ ]);
+ });
+
+ test('a rule without conditions will apply its tags to all imported documents', async () => {
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org_1', name: 'Org 1' }],
+ documents: [{ id: 'doc_1', organizationId: 'org_1', name: 'Doc 1', originalName: 'Doc 1', originalStorageKey: 'doc_1', originalSha256Hash: 'doc_1', mimeType: 'text/plain' }],
+ tags: [{ id: 'tag_1', name: 'Tag 1', color: '#000000', organizationId: 'org_1' }],
+ taggingRules: [{ id: 'tr_1', organizationId: 'org_1', name: 'Tagging Rule 1' }],
+ taggingRuleActions: [{ id: 'tra_1', taggingRuleId: 'tr_1', tagId: 'tag_1' }],
+ });
+
+ const [document] = await db.select().from(documentsTable).where(eq(documentsTable.id, 'doc_1'));
+
+ const taggingRulesRepository = createTaggingRulesRepository({ db });
+ const tagsRepository = createTagsRepository({ db });
+
+ await applyTaggingRules({ document, taggingRulesRepository, tagsRepository });
+
+ const documentTags = await db.select().from(documentsTagsTable);
+
+ expect(documentTags).to.eql([{ documentId: 'doc_1', tagId: 'tag_1' }]);
+ });
+
+ test('an organization with no tagging rules will not apply any tag to a document', async () => {
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org_1', name: 'Org 1' }],
+ documents: [{ id: 'doc_1', organizationId: 'org_1', name: 'Doc 1', originalName: 'Doc 1', originalStorageKey: 'doc_1', originalSha256Hash: 'doc_1', mimeType: 'text/plain' }],
+ });
+
+ const [document] = await db.select().from(documentsTable).where(eq(documentsTable.id, 'doc_1'));
+
+ const taggingRulesRepository = createTaggingRulesRepository({ db });
+ const tagsRepository = createTagsRepository({ db });
+
+ await applyTaggingRules({ document, taggingRulesRepository, tagsRepository });
+
+ const documentTags = await db.select().from(documentsTagsTable);
+
+ expect(documentTags).to.eql([]);
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/tagging-rules/tagging-rules.usecases.ts b/apps/papra-server/src/modules/tagging-rules/tagging-rules.usecases.ts
new file mode 100644
index 00000000..d65bf3c5
--- /dev/null
+++ b/apps/papra-server/src/modules/tagging-rules/tagging-rules.usecases.ts
@@ -0,0 +1,105 @@
+import type { Document } from '../documents/documents.types';
+import type { Logger } from '../shared/logger/logger';
+import type { TagsRepository } from '../tags/tags.repository';
+import type { TaggingRuleOperatorValidatorRegistry } from './conditions/tagging-rule-conditions.registry';
+import type { TaggingRulesRepository } from './tagging-rules.repository';
+import type { TaggingRuleField, TaggingRuleOperator } from './tagging-rules.types';
+import { safely, safelySync } from '@corentinth/chisels';
+import { uniq } from 'lodash-es';
+import { createLogger } from '../shared/logger/logger';
+import { createTaggingRuleOperatorValidatorRegistry } from './conditions/tagging-rule-conditions.registry';
+import { getDocumentFieldValue } from './tagging-rules.models';
+
+export async function createTaggingRule({
+ name,
+ description,
+ enabled,
+ conditions,
+ tagIds,
+ organizationId,
+
+ taggingRulesRepository,
+}: {
+ name: string;
+ description: string | undefined;
+ enabled: boolean | undefined;
+ conditions: {
+ field: TaggingRuleField;
+ operator: TaggingRuleOperator;
+ value: string;
+ }[];
+ tagIds: string[];
+ organizationId: string;
+
+ taggingRulesRepository: TaggingRulesRepository;
+}) {
+ const { taggingRule } = await taggingRulesRepository.createTaggingRule({
+ taggingRule: {
+ name,
+ description,
+ enabled,
+ organizationId,
+ },
+ });
+
+ const { id: taggingRuleId } = taggingRule;
+
+ await Promise.all([
+ conditions.length > 0 && taggingRulesRepository.createTaggingRuleConditions({ taggingRuleId, conditions }),
+ taggingRulesRepository.createTaggingRuleActions({ taggingRuleId, tagIds }),
+ ]);
+}
+
+export async function applyTaggingRules({
+ document,
+
+ taggingRulesRepository,
+ tagsRepository,
+ taggingRuleOperatorValidatorRegistry = createTaggingRuleOperatorValidatorRegistry(),
+ logger = createLogger({ namespace: 'tagging-rules' }),
+}: {
+ document: Document;
+
+ taggingRulesRepository: TaggingRulesRepository;
+ taggingRuleOperatorValidatorRegistry?: TaggingRuleOperatorValidatorRegistry;
+ tagsRepository: TagsRepository;
+ logger?: Logger;
+}) {
+ const { taggingRules } = await taggingRulesRepository.getOrganizationEnabledTaggingRules({ organizationId: document.organizationId });
+
+ const taggingRulesToApplyActions = taggingRules.filter(taggingRule => taggingRule.conditions.every(({ operator, field, value: conditionValue, isCaseSensitive }) => {
+ const { validate } = taggingRuleOperatorValidatorRegistry.getTaggingRuleOperatorValidator({ operator });
+ const { fieldValue } = getDocumentFieldValue({ document, field });
+
+ const [isValid, error] = safelySync(() => validate({ conditionValue, fieldValue, isCaseSensitive }));
+
+ if (error) {
+ logger.error({ error, conditionValue, fieldValue, isCaseSensitive }, 'Failed to validate tagging rule condition');
+
+ return false;
+ }
+
+ return isValid;
+ }));
+
+ const tagIdsToApply: string[] = uniq(taggingRulesToApplyActions.flatMap(taggingRule => taggingRule.actions.map(action => action.tagId)));
+
+ const appliedTagIds = await Promise.all(tagIdsToApply.map(async (tagId) => {
+ const [, error] = await safely(() => tagsRepository.addTagToDocument({ tagId, documentId: document.id }));
+
+ if (error) {
+ logger.error({ error, tagId, documentId: document.id }, 'Failed to add tag to document');
+
+ return;
+ }
+
+ return tagId;
+ }));
+
+ logger.info({
+ taggingRulesIdsToApply: taggingRulesToApplyActions.map(taggingRule => taggingRule.id),
+ appliedTagIds,
+ tagIdsToApply,
+ hasAllTagBeenApplied: appliedTagIds.length === tagIdsToApply.length,
+ }, 'Tagging rules applied');
+}
diff --git a/apps/papra-server/src/modules/tags/tags.constants.ts b/apps/papra-server/src/modules/tags/tags.constants.ts
index e7d43893..199a1222 100644
--- a/apps/papra-server/src/modules/tags/tags.constants.ts
+++ b/apps/papra-server/src/modules/tags/tags.constants.ts
@@ -1 +1,4 @@
export const TagColorRegex = /^#[0-9a-f]{6}$/;
+
+export const tagIdPrefix = 'tag';
+export const tagIdRegex = new RegExp(`^${tagIdPrefix}_[a-z0-9]{24}$`);
diff --git a/apps/papra-server/src/modules/tags/tags.repository.ts b/apps/papra-server/src/modules/tags/tags.repository.ts
index 4573a246..afdef72a 100644
--- a/apps/papra-server/src/modules/tags/tags.repository.ts
+++ b/apps/papra-server/src/modules/tags/tags.repository.ts
@@ -17,6 +17,7 @@ export function createTagsRepository({ db }: { db: Database }) {
deleteTag,
updateTag,
addTagToDocument,
+ addTagsToDocument,
removeTagFromDocument,
},
{ db },
@@ -79,6 +80,10 @@ async function addTagToDocument({ tagId, documentId, db }: { tagId: string; docu
}
}
+async function addTagsToDocument({ tagIds, documentId, db }: { tagIds: string[]; documentId: string; db: Database }) {
+ await db.insert(documentsTagsTable).values(tagIds.map(tagId => ({ tagId, documentId })));
+}
+
async function removeTagFromDocument({ tagId, documentId, db }: { tagId: string; documentId: string; db: Database }) {
await db.delete(documentsTagsTable).where(
and(
diff --git a/apps/papra-server/src/modules/tags/tags.table.ts b/apps/papra-server/src/modules/tags/tags.table.ts
index 17934a21..836c75bd 100644
--- a/apps/papra-server/src/modules/tags/tags.table.ts
+++ b/apps/papra-server/src/modules/tags/tags.table.ts
@@ -2,11 +2,12 @@ import { primaryKey, sqliteTable, text, unique } 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 { tagIdPrefix } from './tags.constants';
export const tagsTable = sqliteTable(
'tags',
{
- ...createPrimaryKeyField({ prefix: 'tag' }),
+ ...createPrimaryKeyField({ prefix: tagIdPrefix }),
...createTimestampColumns(),
organizationId: text('organization_id').notNull().references(() => organizationsTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),