The minimalistic document archiving platform.
feat(tagging-rules): added a "run now" button for tagging rules (#540)
Jan-Olaf Becker75340f0ce7b1
diff --git a/.changeset/smooth-adults-occur.md b/.changeset/smooth-adults-occur.mdnew file mode 100644index 00000000..0fa503ac--- /dev/null+++ b/.changeset/smooth-adults-occur.md@@ -0,0 +1,5 @@+---+"@papra/docker": patch+---++Added button to reapply a tagging rulediff --git a/apps/docs/src/content/docs/03-guides/06-tagging-rules.mdx b/apps/docs/src/content/docs/03-guides/06-tagging-rules.mdxnew file mode 100644index 00000000..38ff9c6d--- /dev/null+++ b/apps/docs/src/content/docs/03-guides/06-tagging-rules.mdx@@ -0,0 +1,102 @@+---+title: Using Tagging Rules+description: Learn how to automate document organization with tagging rules.+slug: guides/tagging-rules+---++## What are Tagging Rules?++Tagging rules allow you to automatically apply tags to documents based on specific conditions. This helps maintain consistent organization without manual effort, especially when dealing with large numbers of documents.++## How Tagging Rules Work++When a tagging rule is enabled, it automatically checks new documents as they're uploaded. If a document matches the rule's conditions, the specified tags are automatically applied.++### Rule Components++Each tagging rule consists of:++1. **Conditions**: Rules that determine which documents should be tagged+ - Field: The document property to check (e.g., name, content)+ - Operator: How to compare the field (e.g., contains, equals)+ - Value: The text to match against++2. **Actions**: The tags to apply when conditions are met++## Applying Rules to Existing Documents++### The "Run Now" Feature++When you create a new tagging rule, it only applies to documents uploaded *after* the rule is created. To apply the rule to documents that already exist in your organization, use the **"Apply to existing documents"** button.++This feature is particularly useful when:+- You create a new rule and want to organize your existing documents+- You modify a rule and want to reprocess documents+- You're setting up your organization and want to retroactively organize imported documents++### How to Apply a Rule to Existing Documents++1. Navigate to your organization's Tagging Rules page+2. Find the rule you want to apply+3. Click the **"Apply to existing documents"** button+4. Confirm the action in the dialog+5. The task is queued and will be processed in the background++The system will:+- Queue a background task to process all documents+- Process documents in batches to avoid overloading the system+- Check all existing documents in your organization+- Apply tags where the rule's conditions match+- Show you a success message once the task is queued++:::tip+Applying a rule to existing documents runs as a background task, so you don't need to wait for it to complete. The processing happens asynchronously and efficiently handles large document collections by processing them in batches.+:::++## Best Practices++### Creating Effective Rules++1. **Be specific**: Use precise conditions to avoid over-tagging+2. **Test first**: Create a rule and test it on a few documents before applying to all existing documents+3. **Use multiple conditions**: Combine conditions for more accurate matching+4. **Review regularly**: Periodically review your rules to ensure they're still relevant++### Example Rules++**Invoice Classification**+- Condition: Document name contains "invoice"+- Action: Apply "Invoice" tag++**Quarterly Reports**+- Condition: Document name contains "Q1" or "Q2" or "Q3" or "Q4"+- Action: Apply "Report" tag++## Using the API++You can also apply tagging rules programmatically using the API. The endpoint enqueues a background task and returns immediately:++```bash+curl -X POST \+ -H "Authorization: Bearer YOUR_API_TOKEN" \+ https://api.papra.app/api/organizations/YOUR_ORG_ID/tagging-rules/RULE_ID/apply+```++Response (HTTP 202 Accepted):+```json+{+ "taskId": "task_abc123"+}+```++Where:+- `taskId`: The ID of the background task processing your request++:::note+The API returns a task ID immediately. The actual processing happens in the background and may take some time depending on the number of documents. Task status retrieval will be available in a future release.+:::++## Related Resources++- [API Endpoints Documentation](/resources/api-endpoints)+- [CLI Documentation](/resources/cli)diff --git a/apps/docs/src/content/docs/04-resources/03-api-endpoints.mdx b/apps/docs/src/content/docs/04-resources/03-api-endpoints.mdxindex 17c8b9fd..dd15b254 100644--- a/apps/docs/src/content/docs/04-resources/03-api-endpoints.mdx+++ b/apps/docs/src/content/docs/04-resources/03-api-endpoints.mdx@@ -307,3 +307,13 @@ Remove a tag from a document.- Required API key permissions: `tags:read` and `documents:update`- Response: empty (204 status code)++### Apply tagging rule to existing documents++**POST** `/api/organizations/:organizationId/tagging-rules/:taggingRuleId/apply`++Enqueue a background task to apply a tagging rule to all existing documents in the organization. This endpoint returns immediately with a task ID, and the processing happens asynchronously in the background. The task will check all documents and apply tags where the rule's conditions match.++- Required API key permissions: `tags:read` and `documents:update`+- Response (JSON, HTTP 202)+ - `taskId`: The ID of the background task. You can use this to track the task's progress (task status retrieval coming in a future release).diff --git a/apps/docs/src/content/navigation.ts b/apps/docs/src/content/navigation.tsindex 5182c41b..a157e2a8 100644--- a/apps/docs/src/content/navigation.ts+++ b/apps/docs/src/content/navigation.ts@@ -40,6 +40,10 @@ export const sidebar = [label: 'Document Encryption',slug: 'guides/document-encryption',},+ {+ label: 'Tagging Rules',+ slug: 'guides/tagging-rules',+ },],},{diff --git a/apps/papra-client/src/locales/de.dictionary.ts b/apps/papra-client/src/locales/de.dictionary.tsindex 5798f4c7..38837325 100644--- a/apps/papra-client/src/locales/de.dictionary.ts+++ b/apps/papra-client/src/locales/de.dictionary.ts@@ -401,9 +401,16 @@ export const translations: Partial<TranslationsDictionary> = {'tagging-rules.form.tags.add-tag': 'Tag erstellen','tagging-rules.form.submit': 'Regel erstellen','tagging-rules.update.title': 'Tagging-Regel aktualisieren',- 'tagging-rules.update.error': 'Tagging-Regel konnte nicht aktualisiert werden',+ 'tagging-rules.update.error': 'Fehler beim Aktualisieren der Tagging-Regel','tagging-rules.update.submit': 'Regel aktualisieren','tagging-rules.update.cancel': 'Abbrechen',+ 'tagging-rules.apply.button': 'Auf vorhandene Dokumente anwenden',+ 'tagging-rules.apply.confirm.title': 'Regel auf vorhandene Dokumente anwenden?',+ 'tagging-rules.apply.confirm.description': 'Dies überprüft alle vorhandenen Dokumente in Ihrer Organisation und wendet Tags an, wo Bedingungen übereinstimmen. Die Verarbeitung erfolgt im Hintergrund.',+ 'tagging-rules.apply.confirm.button': 'Regel anwenden',+ 'tagging-rules.apply.success': 'Regelanwendung im Hintergrund gestartet',+ 'tagging-rules.apply.error': 'Fehler beim Starten der Regelanwendung',+ 'tagging-rules.apply.processing': 'Wird gestartet...',// Intake emailsdiff --git a/apps/papra-client/src/locales/en.dictionary.ts b/apps/papra-client/src/locales/en.dictionary.tsindex 79d09796..941457f0 100644--- a/apps/papra-client/src/locales/en.dictionary.ts+++ b/apps/papra-client/src/locales/en.dictionary.ts@@ -402,6 +402,13 @@ export const translations = {'tagging-rules.update.error': 'Failed to update tagging rule','tagging-rules.update.submit': 'Update rule','tagging-rules.update.cancel': 'Cancel',+ 'tagging-rules.apply.button': 'Apply to existing documents',+ 'tagging-rules.apply.confirm.title': 'Apply rule to existing documents?',+ 'tagging-rules.apply.confirm.description': 'This will check all existing documents in your organization and apply tags where conditions match. The processing will happen in the background.',+ 'tagging-rules.apply.confirm.button': 'Apply rule',+ 'tagging-rules.apply.success': 'Rule application started in the background',+ 'tagging-rules.apply.error': 'Failed to start rule application',+ 'tagging-rules.apply.processing': 'Starting...',// Intake emailsdiff --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.tsxindex 429814f4..d2466720 100644--- 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@@ -5,14 +5,17 @@ import { useMutation, useQuery } from '@tanstack/solid-query';import { For, Match, Show, Switch } from 'solid-js';import { useConfig } from '@/modules/config/config.provider';import { useI18n } from '@/modules/i18n/i18n.provider';+import { useConfirmModal } from '@/modules/shared/confirm';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 { deleteTaggingRule, fetchTaggingRules } from '../tagging-rules.services';+import { createToast } from '@/modules/ui/components/sonner';+import { applyTaggingRuleToExistingDocuments, deleteTaggingRule, fetchTaggingRules } from '../tagging-rules.services';const TaggingRuleCard: Component<{ taggingRule: TaggingRule }> = (props) => {const { t } = useI18n();+ const { confirm } = useConfirmModal();const getConditionsLabel = () => {const count = props.taggingRule.conditions.length;@@ -37,6 +40,43 @@ const TaggingRuleCard: Component<{ taggingRule: TaggingRule }> = (props) => {},}));+ const applyRuleMutation = useMutation(() => ({+ mutationFn: async () => {+ return applyTaggingRuleToExistingDocuments({+ organizationId: props.taggingRule.organizationId,+ taggingRuleId: props.taggingRule.id,+ });+ },+ onSuccess: () => {+ createToast({+ message: t('tagging-rules.apply.success'),+ type: 'success',+ });+ // Note: Documents will be processed in the background+ // We'll invalidate this once task status retrieval is implemented+ },+ onError: () => {+ createToast({+ message: t('tagging-rules.apply.error'),+ type: 'error',+ });+ },+ }));++ const handleApplyRule = async () => {+ const isConfirmed = await confirm({+ title: t('tagging-rules.apply.confirm.title'),+ message: t('tagging-rules.apply.confirm.description'),+ confirmButton: {+ text: t('tagging-rules.apply.confirm.button'),+ },+ });++ if (isConfirmed) {+ applyRuleMutation.mutate();+ }+ };+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}`}>@@ -52,12 +92,24 @@ const TaggingRuleCard: Component<{ taggingRule: TaggingRule }> = (props) => {</div><div class="flex items-center gap-2">+ <Button+ variant="outline"+ size="sm"+ onClick={handleApplyRule}+ disabled={applyRuleMutation.isPending}+ aria-label={t('tagging-rules.apply.button')}+ >+ <div class="i-tabler-player-play size-4 mr-1" />+ {applyRuleMutation.isPending ? t('tagging-rules.apply.processing') : t('tagging-rules.apply.button')}+ </Button>+<Buttonas={A}href={`/organizations/${props.taggingRule.organizationId}/tagging-rules/${props.taggingRule.id}`}variant="outline"size="icon"aria-label={t('tagging-rules.list.card.edit')}+ class="size-8"><div class="i-tabler-edit size-4" /></Button>@@ -68,6 +120,7 @@ const TaggingRuleCard: Component<{ taggingRule: TaggingRule }> = (props) => {onClick={() => deleteTaggingRuleMutation.mutate()}disabled={deleteTaggingRuleMutation.isPending}aria-label={t('tagging-rules.list.card.delete')}+ class="size-8"><div class="i-tabler-trash size-4" /></Button>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.tsindex 8f959b94..e53b33a6 100644--- a/apps/papra-client/src/modules/tagging-rules/tagging-rules.services.ts+++ b/apps/papra-client/src/modules/tagging-rules/tagging-rules.services.ts@@ -43,3 +43,18 @@ export async function updateTaggingRule({ organizationId, taggingRuleId, taggingbody: taggingRule,});}++export async function applyTaggingRuleToExistingDocuments({+ organizationId,+ taggingRuleId,+}: {+ organizationId: string;+ taggingRuleId: string;+}) {+ const result = await apiClient<{ taskId: string }>({+ path: `/api/organizations/${organizationId}/tagging-rules/${taggingRuleId}/apply`,+ method: 'POST',+ });++ return result;+}diff --git a/apps/papra-server/src/modules/documents/documents.repository.ts b/apps/papra-server/src/modules/documents/documents.repository.tsindex 545cc40f..b9e03046 100644--- a/apps/papra-server/src/modules/documents/documents.repository.ts+++ b/apps/papra-server/src/modules/documents/documents.repository.ts@@ -34,8 +34,8 @@ export function createDocumentsRepository({ db }: { db: Database }) {getOrganizationDocumentBySha256Hash,getAllOrganizationTrashDocuments,getAllOrganizationDocuments,- getOrganizationDocumentsQuery,getAllOrganizationDocumentsIterator,+ getAllOrganizationUndeletedDocumentsIterator,updateDocument,},{ db },@@ -391,20 +391,38 @@ async function getAllOrganizationDocuments({ organizationId, db }: { organizatio};}-function getOrganizationDocumentsQuery({ organizationId, db }: { organizationId: string; db: Database }) {- return db.select({- id: documentsTable.id,- originalStorageKey: documentsTable.originalStorageKey,- }).from(documentsTable).where(- eq(documentsTable.organizationId, organizationId),- );-}+function getAllOrganizationDocumentsIterator({ organizationId, batchSize = 100, db }: { organizationId: string; batchSize?: number; db: Database }) {+ const query = db+ .select({+ id: documentsTable.id,+ originalStorageKey: documentsTable.originalStorageKey,+ })+ .from(documentsTable)+ .where(+ eq(documentsTable.organizationId, organizationId),+ )+ .orderBy(documentsTable.createdAt)+ .$dynamic();-function getAllOrganizationDocumentsIterator({ organizationId, db, batchSize = 100 }: { organizationId: string; db: Database; batchSize?: number }) {- const query = getOrganizationDocumentsQuery({ organizationId, db }).$dynamic();return createIterator({ query, batchSize }) as AsyncGenerator<{ id: string; originalStorageKey: string }>;}+function getAllOrganizationUndeletedDocumentsIterator({ organizationId, batchSize = 100, db }: { organizationId: string; batchSize?: number; db: Database }) {+ const query = db+ .select()+ .from(documentsTable)+ .where(+ and(+ eq(documentsTable.organizationId, organizationId),+ eq(documentsTable.isDeleted, false),+ ),+ )+ .orderBy(documentsTable.createdAt)+ .$dynamic();++ return createIterator({ query, batchSize });+}+async function updateDocument({ documentId, organizationId, name, content, db }: { documentId: string; organizationId: string; name?: string; content?: string; db: Database }) {const [document] = await db.update(documentsTable)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.tsindex 6b553c41..bd575b72 100644--- a/apps/papra-server/src/modules/tagging-rules/tagging-rules.routes.ts+++ b/apps/papra-server/src/modules/tagging-rules/tagging-rules.routes.ts@@ -6,6 +6,8 @@ import { getUser } from '../app/auth/auth.models';import { organizationIdSchema } from '../organizations/organization.schemas';import { createOrganizationsRepository } from '../organizations/organizations.repository';import { ensureUserIsInOrganization } from '../organizations/organizations.usecases';+import { createError } from '../shared/errors/errors';+import { isNil } from '../shared/utils';import { validateJsonBody, validateParams } from '../shared/validation/validation';import { tagIdRegex } from '../tags/tags.constants';import { TAGGING_RULE_FIELDS, TAGGING_RULE_OPERATORS } from './tagging-rules.constants';@@ -19,6 +21,7 @@ export function registerTaggingRulesRoutes(context: RouteDefinitionContext) {setupDeleteTaggingRuleRoute(context);setupGetTaggingRuleRoute(context);setupUpdateTaggingRuleRoute(context);+ setupApplyTaggingRuleRoute(context);}function setupGetOrganizationTaggingRulesRoute({ app, db }: RouteDefinitionContext) {@@ -175,3 +178,46 @@ function setupUpdateTaggingRuleRoute({ app, db }: RouteDefinitionContext) {},);}++function setupApplyTaggingRuleRoute({ app, db, taskServices }: RouteDefinitionContext) {+ app.post(+ '/api/organizations/:organizationId/tagging-rules/:taggingRuleId/apply',+ requireAuthentication(),+ validateParams(z.object({+ organizationId: organizationIdSchema,+ taggingRuleId: taggingRuleIdSchema,+ })),+ 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 });++ // Verify the tagging rule exists before enqueuing the task+ const { taggingRule } = await taggingRulesRepository.getOrganizationTaggingRule({ organizationId, taggingRuleId });++ if (isNil(taggingRule)) {+ throw createError({+ message: 'Tagging rule not found',+ code: 'tagging-rules.not-found',+ statusCode: 404,+ });+ }++ // Enqueue background task+ const { jobId: taskId } = await taskServices.scheduleJob({+ taskName: 'apply-tagging-rule-to-documents',+ data: {+ organizationId,+ taggingRuleId,+ },+ });++ return context.json({ taskId }, 202);+ },+ );+}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.tsindex 750b7c20..4bc74b33 100644--- 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@@ -2,6 +2,7 @@ import { eq } from 'drizzle-orm';import { describe, expect, test } from 'vitest';import { createInMemoryDatabase } from '../app/database/database.test-utils';import { createDocumentActivityRepository } from '../documents/document-activity/document-activity.repository';+import { createDocumentsRepository } from '../documents/documents.repository';import { documentsTable } from '../documents/documents.table';import { createTestLogger } from '../shared/logger/logger.test-utils';import { isNil } from '../shared/utils';@@ -9,7 +10,7 @@ import { createTagsRepository } from '../tags/tags.repository';import { documentsTagsTable } from '../tags/tags.table';import { createWebhookRepository } from '../webhooks/webhook.repository';import { createTaggingRulesRepository } from './tagging-rules.repository';-import { applyTaggingRules } from './tagging-rules.usecases';+import { applyTaggingRules, applyTaggingRuleToExistingDocuments } from './tagging-rules.usecases';describe('tagging-rules usecases', () => {describe('applyTaggingRules', () => {@@ -47,13 +48,22 @@ describe('tagging-rules usecases', () => {expect(getLogs({ excludeTimestampMs: true })).to.eql([{data: {- tagIdsToApply: ['tag_1'],+ taggingRuleId: 'tr_1',appliedTagIds: ['tag_1'],- taggingRulesIdsToApply: ['tr_1'],+ expectedTagCount: 1,hasAllTagBeenApplied: true,},level: 'info',- message: 'Tagging rules applied',+ message: 'Tagging rule applied to document',+ namespace: 'test',+ },+ {+ data: {+ taggingRulesCount: 1,+ appliedTagIds: ['tag_1'],+ },+ level: 'info',+ message: 'All tagging rules applied to document',namespace: 'test',},]);@@ -112,4 +122,103 @@ describe('tagging-rules usecases', () => {expect(documentTags).to.eql([]);});});++ describe('applyTaggingRuleToExistingDocuments', () => {+ test('applying rule to existing documents tags only matching ones', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_1', name: 'Org 1' }],+ tags: [{ id: 'tag_1', name: 'Invoice', color: '#000000', organizationId: 'org_1' }],+ documents: [+ { id: 'doc_1', organizationId: 'org_1', name: 'Invoice 2024', originalName: 'Invoice 2024', originalStorageKey: 'doc_1', originalSha256Hash: 'hash_1', mimeType: 'text/plain' },+ { id: 'doc_2', organizationId: 'org_1', name: 'Invoice Q1', originalName: 'Invoice Q1', originalStorageKey: 'doc_2', originalSha256Hash: 'hash_2', mimeType: 'text/plain' },+ { id: 'doc_3', organizationId: 'org_1', name: 'Contract', originalName: 'Contract', originalStorageKey: 'doc_3', originalSha256Hash: 'hash_3', mimeType: 'text/plain' },+ ],+ taggingRules: [{ id: 'tr_1', organizationId: 'org_1', name: 'Tag Invoices', enabled: true }],+ taggingRuleConditions: [{ id: 'trc_1', taggingRuleId: 'tr_1', field: 'name', operator: 'contains', value: 'Invoice' }],+ taggingRuleActions: [{ id: 'tra_1', taggingRuleId: 'tr_1', tagId: 'tag_1' }],+ });++ const taggingRulesRepository = createTaggingRulesRepository({ db });+ const documentsRepository = createDocumentsRepository({ db });+ const tagsRepository = createTagsRepository({ db });+ const webhookRepository = createWebhookRepository({ db });+ const documentActivityRepository = createDocumentActivityRepository({ db });++ const result = await applyTaggingRuleToExistingDocuments({+ taggingRuleId: 'tr_1',+ organizationId: 'org_1',+ taggingRulesRepository,+ documentsRepository,+ tagsRepository,+ webhookRepository,+ documentActivityRepository,+ });++ expect(result.processedCount).toBe(3);+ expect(result.taggedDocumentsCount).toBe(2); // All documents are processed (applyTaggingRules is called for each)++ const documentTags = await db.select().from(documentsTagsTable);++ // Only doc_1 and doc_2 should be tagged (they contain "Invoice")+ expect(documentTags).toHaveLength(2);+ expect(documentTags.map(dt => dt.documentId).sort()).toEqual(['doc_1', 'doc_2']);+ expect(documentTags.every(dt => dt.tagId === 'tag_1')).toBe(true);+ });++ test('returns error when tagging rule does not exist', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_1', name: 'Org 1' }],+ });++ const taggingRulesRepository = createTaggingRulesRepository({ db });+ const documentsRepository = createDocumentsRepository({ db });+ const tagsRepository = createTagsRepository({ db });+ const webhookRepository = createWebhookRepository({ db });+ const documentActivityRepository = createDocumentActivityRepository({ db });++ await expect(+ applyTaggingRuleToExistingDocuments({+ taggingRuleId: 'non_existent',+ organizationId: 'org_1',+ taggingRulesRepository,+ documentsRepository,+ tagsRepository,+ webhookRepository,+ documentActivityRepository,+ }),+ ).rejects.toThrow('Tagging rule not found');+ });++ test('processes all documents even when the tagging rule is disabled', 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: 'hash_1', mimeType: 'text/plain' },+ ],+ taggingRules: [{ id: 'tr_1', organizationId: 'org_1', name: 'Rule 1', enabled: false }],+ });++ const taggingRulesRepository = createTaggingRulesRepository({ db });+ const documentsRepository = createDocumentsRepository({ db });+ const tagsRepository = createTagsRepository({ db });+ const webhookRepository = createWebhookRepository({ db });+ const documentActivityRepository = createDocumentActivityRepository({ db });++ const result = await applyTaggingRuleToExistingDocuments({+ taggingRuleId: 'tr_1',+ organizationId: 'org_1',+ taggingRulesRepository,+ documentsRepository,+ tagsRepository,+ webhookRepository,+ documentActivityRepository,+ });++ expect(result.processedCount).toBe(1);+ expect(result.taggedDocumentsCount).toBe(0); // No documents tagged because rule is disabled++ const documentTags = await db.select().from(documentsTagsTable);+ expect(documentTags).toHaveLength(0); // No tags applied because rule is disabled+ });+ });});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.tsindex d9149268..0ce0a83e 100644--- a/apps/papra-server/src/modules/tagging-rules/tagging-rules.usecases.ts+++ b/apps/papra-server/src/modules/tagging-rules/tagging-rules.usecases.ts@@ -1,4 +1,5 @@import type { DocumentActivityRepository } from '../documents/document-activity/document-activity.repository';+import type { DocumentsRepository } from '../documents/documents.repository';import type { Document } from '../documents/documents.types';import type { Logger } from '../shared/logger/logger';import type { TagsRepository } from '../tags/tags.repository';@@ -9,6 +10,7 @@ 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 { createError } from '../shared/errors/errors';import { createLogger } from '../shared/logger/logger';import { isNil } from '../shared/utils';import { addTagToDocument } from '../tags/tags.usecases';@@ -55,10 +57,14 @@ export async function createTaggingRule({]);}-export async function applyTaggingRules({+/**+ * Apply a single tagging rule to a document.+ * Checks if the rule's conditions match the document, and if so, applies the rule's tags.+ * Returns the list of tag IDs that were successfully applied.+ */+export async function applyTaggingRule({document,-- taggingRulesRepository,+ taggingRule,tagsRepository,webhookRepository,documentActivityRepository,@@ -66,17 +72,26 @@ export async function applyTaggingRules({logger = createLogger({ namespace: 'tagging-rules' }),}: {document: Document;-- taggingRulesRepository: TaggingRulesRepository;- taggingRuleOperatorValidatorRegistry?: TaggingRuleOperatorValidatorRegistry;+ taggingRule: {+ id: string;+ conditions: Array<{+ operator: string;+ field: string;+ value: string;+ isCaseSensitive: boolean;+ }>;+ actions: Array<{+ tag: Tag | null;+ }>;+ };tagsRepository: TagsRepository;webhookRepository: WebhookRepository;documentActivityRepository: DocumentActivityRepository;+ taggingRuleOperatorValidatorRegistry?: TaggingRuleOperatorValidatorRegistry;logger?: Logger;-}) {- const { taggingRules } = await taggingRulesRepository.getOrganizationEnabledTaggingRules({ organizationId: document.organizationId });-- const taggingRulesToApplyActions = taggingRules.filter(taggingRule => taggingRule.conditions.every(({ operator, field, value: conditionValue, isCaseSensitive }) => {+}): Promise<{ appliedTagIds: string[] }> {+ // Check if all conditions match+ const allConditionsMatch = taggingRule.conditions.every(({ operator, field, value: conditionValue, isCaseSensitive }) => {const { validate } = taggingRuleOperatorValidatorRegistry.getTaggingRuleOperatorValidator({ operator });const { fieldValue } = getDocumentFieldValue({ document, field });@@ -84,17 +99,22 @@ export async function applyTaggingRules({if (error) {logger.error({ error, conditionValue, fieldValue, isCaseSensitive }, 'Failed to validate tagging rule condition');-return false;}return isValid;- }));+ });++ // If conditions don't match, return empty array+ if (!allConditionsMatch) {+ return { appliedTagIds: [] };+ }- const tagsToApply: Tag[] = uniq(taggingRulesToApplyActions.flatMap(taggingRule => taggingRule.actions.map(action => action.tag).filter(tag => !isNil(tag))));- const tagIdsToApply = tagsToApply.map(tag => tag.id);+ // Get tags to apply from the rule's actions+ const tagsToApply: Tag[] = taggingRule.actions.map(action => action.tag).filter((tag): tag is Tag => !isNil(tag));- const appliedTagIds = await Promise.all(tagsToApply.map(async (tag) => {+ // Apply each tag to the document+ const appliedTagIdsResults = await Promise.all(tagsToApply.map(async (tag) => {const [, error] = await safely(async () => addTagToDocument({tagId: tag.id,documentId: document.id,@@ -107,17 +127,181 @@ export async function applyTaggingRules({if (error) {logger.error({ error, tagId: tag.id, documentId: document.id }, 'Failed to add tag to document');-- return;+ return undefined;}return tag.id;}));+ const appliedTagIds = appliedTagIdsResults.filter((id): id is string => id !== undefined);+logger.info({- taggingRulesIdsToApply: taggingRulesToApplyActions.map(taggingRule => taggingRule.id),+ taggingRuleId: taggingRule.id,appliedTagIds,- tagIdsToApply,- hasAllTagBeenApplied: appliedTagIds.length === tagIdsToApply.length,- }, 'Tagging rules applied');+ expectedTagCount: tagsToApply.length,+ hasAllTagBeenApplied: appliedTagIds.length === tagsToApply.length,+ }, 'Tagging rule applied to document');++ return { appliedTagIds };+}++/**+ * Apply all enabled tagging rules to a document.+ * Fetches all enabled rules for the document's organization and applies each one.+ */+export async function applyTaggingRules({+ document,++ taggingRulesRepository,+ tagsRepository,+ webhookRepository,+ documentActivityRepository,+ taggingRuleOperatorValidatorRegistry = createTaggingRuleOperatorValidatorRegistry(),+ logger = createLogger({ namespace: 'tagging-rules' }),+}: {+ document: Document;++ taggingRulesRepository: TaggingRulesRepository;+ taggingRuleOperatorValidatorRegistry?: TaggingRuleOperatorValidatorRegistry;+ tagsRepository: TagsRepository;+ webhookRepository: WebhookRepository;+ documentActivityRepository: DocumentActivityRepository;+ logger?: Logger;+}) {+ const { taggingRules } = await taggingRulesRepository.getOrganizationEnabledTaggingRules({ organizationId: document.organizationId });++ // Apply each enabled rule to the document+ const appliedTagIdsPerRule = await Promise.all(taggingRules.map(async (taggingRule) => {+ return applyTaggingRule({+ document,+ taggingRule,+ tagsRepository,+ webhookRepository,+ documentActivityRepository,+ taggingRuleOperatorValidatorRegistry,+ logger,+ });+ }));++ const allAppliedTagIds = uniq(appliedTagIdsPerRule.map(({ appliedTagIds }) => appliedTagIds).flat());++ logger.info({+ taggingRulesCount: taggingRules.length,+ appliedTagIds: allAppliedTagIds,+ }, 'All tagging rules applied to document');+}++type ProcessingStats = {+ processedCount: number;+ taggedDocumentsCount: number;+ errorCount: number;+};++async function processDocumentWithTaggingRule({+ document,+ taggingRule,+ tagsRepository,+ webhookRepository,+ documentActivityRepository,+ logger,+}: {+ document: Document;+ taggingRule: {+ id: string;+ conditions: Array<{+ operator: string;+ field: string;+ value: string;+ isCaseSensitive: boolean;+ }>;+ actions: Array<{+ tag: Tag | null;+ }>;+ };+ tagsRepository: TagsRepository;+ webhookRepository: WebhookRepository;+ documentActivityRepository: DocumentActivityRepository;+ logger: Logger;+}) {+ const [result, error] = await safely(async () => {+ return applyTaggingRule({+ document,+ taggingRule,+ tagsRepository,+ webhookRepository,+ documentActivityRepository,+ logger,+ });+ });++ if (error) {+ logger.error({ error, documentId: document.id }, 'Error applying tagging rule to document');+ return { wasTagged: false, hadError: true };+ }++ return { wasTagged: result.appliedTagIds.length > 0, hadError: false };+}++export async function applyTaggingRuleToExistingDocuments({+ taggingRuleId,+ organizationId,+ taggingRulesRepository,+ documentsRepository,+ tagsRepository,+ webhookRepository,+ documentActivityRepository,+ logger = createLogger({ namespace: 'tagging-rules' }),+}: {+ taggingRuleId: string;+ organizationId: string;+ taggingRulesRepository: TaggingRulesRepository;+ documentsRepository: DocumentsRepository;+ tagsRepository: TagsRepository;+ webhookRepository: WebhookRepository;+ documentActivityRepository: DocumentActivityRepository;+ logger?: Logger;+}) {+ const { taggingRule } = await taggingRulesRepository.getOrganizationTaggingRule({ organizationId, taggingRuleId });++ if (!taggingRule) {+ throw createError({+ message: 'Tagging rule not found',+ code: 'tagging-rules.not-found',+ statusCode: 404,+ });+ }++ logger.info({ organizationId, taggingRuleId }, 'Starting to apply tagging rule to existing documents');++ const documentsIterator = documentsRepository.getAllOrganizationUndeletedDocumentsIterator({ organizationId, batchSize: 100 });++ const stats: ProcessingStats = {+ processedCount: 0,+ taggedDocumentsCount: 0,+ errorCount: 0,+ };++ for await (const document of documentsIterator) {+ const result = await processDocumentWithTaggingRule({+ document,+ taggingRule,+ tagsRepository,+ webhookRepository,+ documentActivityRepository,+ logger,+ });++ stats.processedCount += 1;+ stats.taggedDocumentsCount += result.wasTagged ? 1 : 0;+ stats.errorCount += result.hadError ? 1 : 0;++ // Log progress every 100 documents+ if (stats.processedCount % 100 === 0) {+ logger.info({ organizationId, taggingRuleId, ...stats }, 'Re-tagging progress update');+ }+ }++ logger.info({ organizationId, taggingRuleId, ...stats }, 'Completed applying tagging rule to existing documents');++ return stats;}diff --git a/apps/papra-server/src/modules/tagging-rules/tasks/apply-tagging-rule-to-documents.task.ts b/apps/papra-server/src/modules/tagging-rules/tasks/apply-tagging-rule-to-documents.task.tsnew file mode 100644index 00000000..fb2a6004--- /dev/null+++ b/apps/papra-server/src/modules/tagging-rules/tasks/apply-tagging-rule-to-documents.task.ts@@ -0,0 +1,46 @@+import type { Database } from '../../app/database/database.types';+import type { TaskServices } from '../../tasks/tasks.services';+import { createDocumentActivityRepository } from '../../documents/document-activity/document-activity.repository';+import { createDocumentsRepository } from '../../documents/documents.repository';+import { createLogger } from '../../shared/logger/logger';+import { createTagsRepository } from '../../tags/tags.repository';+import { createWebhookRepository } from '../../webhooks/webhook.repository';+import { createTaggingRulesRepository } from '../tagging-rules.repository';+import { applyTaggingRuleToExistingDocuments } from '../tagging-rules.usecases';++const logger = createLogger({ namespace: 'tasks:apply-tagging-rule' });++export async function registerApplyTaggingRuleToDocumentsTask({ taskServices, db }: { taskServices: TaskServices; db: Database }) {+ const taskName = 'apply-tagging-rule-to-documents';++ taskServices.registerTask({+ taskName,+ handler: async ({ data }) => {+ const documentsRepository = createDocumentsRepository({ db });+ const taggingRulesRepository = createTaggingRulesRepository({ db });+ const tagsRepository = createTagsRepository({ db });+ const webhookRepository = createWebhookRepository({ db });+ const documentActivityRepository = createDocumentActivityRepository({ db });++ // TODO: remove type cast once taskServices has proper typing+ const { organizationId, taggingRuleId } = data as { organizationId: string; taggingRuleId: string };++ logger.info({ organizationId, taggingRuleId }, 'Starting background task to apply tagging rule');++ const result = await applyTaggingRuleToExistingDocuments({+ taggingRuleId,+ organizationId,+ taggingRulesRepository,+ documentsRepository,+ tagsRepository,+ webhookRepository,+ documentActivityRepository,+ logger,+ });++ logger.info({ organizationId, taggingRuleId, result }, 'Completed background task to apply tagging rule');++ return result;+ },+ });+}diff --git a/apps/papra-server/src/modules/tasks/tasks.definitions.ts b/apps/papra-server/src/modules/tasks/tasks.definitions.tsindex 0f01bd77..00dc3140 100644--- a/apps/papra-server/src/modules/tasks/tasks.definitions.ts+++ b/apps/papra-server/src/modules/tasks/tasks.definitions.ts@@ -6,10 +6,12 @@ import { registerExtractDocumentFileContentTask } from '../documents/tasks/extraimport { registerHardDeleteExpiredDocumentsTask } from '../documents/tasks/hard-delete-expired-documents.task';import { registerExpireInvitationsTask } from '../organizations/tasks/expire-invitations.task';import { registerPurgeExpiredOrganizationsTask } from '../organizations/tasks/purge-expired-organizations.task';+import { registerApplyTaggingRuleToDocumentsTask } from '../tagging-rules/tasks/apply-tagging-rule-to-documents.task';export async function registerTaskDefinitions({ taskServices, db, config, documentsStorageService }: { taskServices: TaskServices; db: Database; config: Config; documentsStorageService: DocumentStorageService }) {await registerHardDeleteExpiredDocumentsTask({ taskServices, db, config, documentsStorageService });await registerExpireInvitationsTask({ taskServices, db, config });await registerPurgeExpiredOrganizationsTask({ taskServices, db, config, documentsStorageService });await registerExtractDocumentFileContentTask({ taskServices, db, documentsStorageService });+ await registerApplyTaggingRuleToDocumentsTask({ taskServices, db });}