The minimalistic document archiving platform.
refactor(tagging-rules): enhance tagging rules repository with tag associations (#539)
Corentin Thomasset60982da847d5
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.tsindex e93cf674..1a7097a0 100644--- 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@@ -1,3 +1,4 @@+import type { Tag } from '../tags/tags.types';import type { TaggingRule, TaggingRuleAction, TaggingRuleCondition } from './tagging-rules.types';export function aggregateTaggingRules({@@ -7,6 +8,7 @@ export function aggregateTaggingRules({tagging_rules: TaggingRule;tagging_rule_conditions: TaggingRuleCondition | null;tagging_rule_actions: TaggingRuleAction | null;+ tags: Tag | null;}[];}) {const taggingRulesRecord = rawTaggingRules.reduce((acc, rawTaggingRule) => {@@ -25,11 +27,15 @@ export function aggregateTaggingRules({}if (rawTaggingRule.tagging_rule_actions) {- acc[taggingRuleId].actions[rawTaggingRule.tagging_rule_actions.id] = rawTaggingRule.tagging_rule_actions;+ const action = {+ ...rawTaggingRule.tagging_rule_actions,+ tag: rawTaggingRule.tags,+ };+ acc[taggingRuleId].actions[rawTaggingRule.tagging_rule_actions.id] = action;}return acc;- }, {} as Record<string, TaggingRule & { conditions: Record<string, TaggingRuleCondition>; actions: Record<string, TaggingRuleAction> }>);+ }, {} as Record<string, TaggingRule & { conditions: Record<string, TaggingRuleCondition>; actions: Record<string, TaggingRuleAction & { tag: Tag | null }> }>);return {taggingRules: Objectdiff --git a/apps/papra-server/src/modules/tagging-rules/tagging-rules.repository.test.ts b/apps/papra-server/src/modules/tagging-rules/tagging-rules.repository.test.tsnew file mode 100644index 00000000..3689a746--- /dev/null+++ b/apps/papra-server/src/modules/tagging-rules/tagging-rules.repository.test.ts@@ -0,0 +1,250 @@+import { describe, expect, test } from 'vitest';+import { createInMemoryDatabase } from '../app/database/database.test-utils';+import { createTaggingRulesRepository } from './tagging-rules.repository';++describe('tagging-rules repository', () => {+ describe('getOrganizationEnabledTaggingRules', () => {+ test('getting enabled tagging rules includes all related conditions and actions', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_1', name: 'Org 1' }],+ tags: [+ { id: 'tag_1', name: 'Tag 1', color: '#000000', organizationId: 'org_1', createdAt: new Date('2023-01-01'), updatedAt: new Date('2023-02-01') },+ { id: 'tag_2', name: 'Tag 2', color: '#111111', organizationId: 'org_1', createdAt: new Date('2023-01-02'), updatedAt: new Date('2023-02-02') },+ ],+ taggingRules: [+ { id: 'tr_1', organizationId: 'org_1', name: 'Enabled Rule 1', enabled: true, createdAt: new Date('2023-03-01'), updatedAt: new Date('2023-04-01') },+ ],+ taggingRuleConditions: [+ { id: 'trc_1', taggingRuleId: 'tr_1', field: 'name', operator: 'equal', value: 'Doc 1', createdAt: new Date('2023-05-01'), updatedAt: new Date('2023-06-01') },+ { id: 'trc_2', taggingRuleId: 'tr_1', field: 'content', operator: 'contains', value: 'invoice', createdAt: new Date('2023-05-01'), updatedAt: new Date('2023-06-01') },+ ],+ taggingRuleActions: [+ { id: 'tra_1', taggingRuleId: 'tr_1', tagId: 'tag_1', createdAt: new Date('2023-07-01'), updatedAt: new Date('2023-08-01') },+ { id: 'tra_2', taggingRuleId: 'tr_1', tagId: 'tag_2', createdAt: new Date('2023-07-01'), updatedAt: new Date('2023-08-01') },+ ],+ });++ const taggingRulesRepository = createTaggingRulesRepository({ db });++ const { taggingRules } = await taggingRulesRepository.getOrganizationEnabledTaggingRules({ organizationId: 'org_1' });++ expect(taggingRules).to.eql([+ {+ createdAt: new Date('2023-03-01T00:00:00.000Z'),+ description: null,+ enabled: true,+ id: 'tr_1',+ name: 'Enabled Rule 1',+ organizationId: 'org_1',+ updatedAt: new Date('2023-04-01T00:00:00.000Z'),+ actions: [+ {+ createdAt: new Date('2023-07-01T00:00:00.000Z'),+ id: 'tra_1',+ tagId: 'tag_1',+ taggingRuleId: 'tr_1',+ updatedAt: new Date('2023-08-01T00:00:00.000Z'),+ tag: {+ id: 'tag_1',+ name: 'Tag 1',+ color: '#000000',+ description: null,+ organizationId: 'org_1',+ createdAt: new Date('2023-01-01T00:00:00.000Z'),+ updatedAt: new Date('2023-02-01T00:00:00.000Z'),+ },+ },+ {+ createdAt: new Date('2023-07-01T00:00:00.000Z'),+ id: 'tra_2',+ tagId: 'tag_2',+ taggingRuleId: 'tr_1',+ updatedAt: new Date('2023-08-01T00:00:00.000Z'),+ tag: {+ id: 'tag_2',+ name: 'Tag 2',+ color: '#111111',+ description: null,+ organizationId: 'org_1',+ createdAt: new Date('2023-01-02T00:00:00.000Z'),+ updatedAt: new Date('2023-02-02T00:00:00.000Z'),+ },+ },+ ],+ conditions: [+ {+ createdAt: new Date('2023-05-01T00:00:00.000Z'),+ field: 'name',+ id: 'trc_1',+ isCaseSensitive: false,+ operator: 'equal',+ taggingRuleId: 'tr_1',+ updatedAt: new Date('2023-06-01T00:00:00.000Z'),+ value: 'Doc 1',+ },+ {+ createdAt: new Date('2023-05-01T00:00:00.000Z'),+ field: 'content',+ id: 'trc_2',+ isCaseSensitive: false,+ operator: 'contains',+ taggingRuleId: 'tr_1',+ updatedAt: new Date('2023-06-01T00:00:00.000Z'),+ value: 'invoice',+ },+ ],++ },+ ]);+ });++ test('disabled tagging rules are excluded from the results', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_1', name: 'Org 1' }],+ tags: [{ id: 'tag_1', name: 'Tag 1', color: '#000000', organizationId: 'org_1' }],+ taggingRules: [+ { id: 'tr_1', organizationId: 'org_1', name: 'Enabled Rule', enabled: true },+ { id: 'tr_2', organizationId: 'org_1', name: 'Disabled Rule', enabled: false },+ ],+ taggingRuleConditions: [+ { id: 'trc_1', taggingRuleId: 'tr_1', field: 'name', operator: 'equal', value: 'Doc 1' },+ { id: 'trc_2', taggingRuleId: 'tr_2', field: 'name', operator: 'equal', value: 'Doc 2' },+ ],+ taggingRuleActions: [+ { id: 'tra_1', taggingRuleId: 'tr_1', tagId: 'tag_1' },+ { id: 'tra_2', taggingRuleId: 'tr_2', tagId: 'tag_1' },+ ],+ });++ const taggingRulesRepository = createTaggingRulesRepository({ db });++ const { taggingRules } = await taggingRulesRepository.getOrganizationEnabledTaggingRules({ organizationId: 'org_1' });++ expect(taggingRules).toHaveLength(1);+ expect(taggingRules[0]?.id).toBe('tr_1');+ expect(taggingRules[0]?.enabled).toBe(true);+ });++ test('tagging rules from other organizations are not included', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [+ { id: 'org_1', name: 'Org 1' },+ { id: 'org_2', name: 'Org 2' },+ ],+ tags: [+ { id: 'tag_1', name: 'Tag 1', color: '#000000', organizationId: 'org_1' },+ { id: 'tag_2', name: 'Tag 2', color: '#111111', organizationId: 'org_2' },+ ],+ taggingRules: [+ { id: 'tr_1', organizationId: 'org_1', name: 'Rule Org 1', enabled: true },+ { id: 'tr_2', organizationId: 'org_2', name: 'Rule Org 2', enabled: true },+ ],+ taggingRuleActions: [+ { id: 'tra_1', taggingRuleId: 'tr_1', tagId: 'tag_1' },+ { id: 'tra_2', taggingRuleId: 'tr_2', tagId: 'tag_2' },+ ],+ });++ const taggingRulesRepository = createTaggingRulesRepository({ db });++ const { taggingRules } = await taggingRulesRepository.getOrganizationEnabledTaggingRules({ organizationId: 'org_1' });++ expect(taggingRules).toHaveLength(1);+ expect(taggingRules[0]?.id).toBe('tr_1');+ expect(taggingRules[0]?.organizationId).toBe('org_1');+ });++ test('organizations with only disabled rules get an empty result', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_1', name: 'Org 1' }],+ tags: [{ id: 'tag_1', name: 'Tag 1', color: '#000000', organizationId: 'org_1' }],+ taggingRules: [+ { id: 'tr_1', organizationId: 'org_1', name: 'Disabled Rule', enabled: false },+ ],+ taggingRuleActions: [+ { id: 'tra_1', taggingRuleId: 'tr_1', tagId: 'tag_1' },+ ],+ });++ const taggingRulesRepository = createTaggingRulesRepository({ db });++ const { taggingRules } = await taggingRulesRepository.getOrganizationEnabledTaggingRules({ organizationId: 'org_1' });++ expect(taggingRules).toEqual([]);+ });++ test('organizations without any tagging rules get an empty result', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_1', name: 'Org 1' }],+ });++ const taggingRulesRepository = createTaggingRulesRepository({ db });++ const { taggingRules } = await taggingRulesRepository.getOrganizationEnabledTaggingRules({ organizationId: 'org_1' });++ expect(taggingRules).toEqual([]);+ });++ test('tagging rules without conditions are properly retrieved with empty conditions array', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_1', name: 'Org 1' }],+ tags: [{ id: 'tag_1', name: 'Tag 1', color: '#000000', organizationId: 'org_1' }],+ taggingRules: [+ { id: 'tr_1', organizationId: 'org_1', name: 'Rule Without Conditions', enabled: true },+ ],+ taggingRuleActions: [+ { id: 'tra_1', taggingRuleId: 'tr_1', tagId: 'tag_1' },+ ],+ });++ const taggingRulesRepository = createTaggingRulesRepository({ db });++ const { taggingRules } = await taggingRulesRepository.getOrganizationEnabledTaggingRules({ organizationId: 'org_1' });++ expect(taggingRules).toHaveLength(1);+ expect(taggingRules[0]?.conditions).toEqual([]);+ expect(taggingRules[0]?.actions).toHaveLength(1);+ });++ test('multiple enabled rules are retrieved with their respective conditions and actions', async () => {+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_1', name: 'Org 1' }],+ tags: [+ { id: 'tag_1', name: 'Tag 1', color: '#000000', organizationId: 'org_1' },+ { id: 'tag_2', name: 'Tag 2', color: '#111111', organizationId: 'org_1' },+ ],+ taggingRules: [+ { id: 'tr_1', organizationId: 'org_1', name: 'Rule 1', enabled: true },+ { id: 'tr_2', organizationId: 'org_1', name: 'Rule 2', enabled: true },+ { id: 'tr_3', organizationId: 'org_1', name: 'Rule 3 Disabled', enabled: false },+ ],+ taggingRuleConditions: [+ { id: 'trc_1', taggingRuleId: 'tr_1', field: 'name', operator: 'equal', value: 'Doc 1' },+ { id: 'trc_2', taggingRuleId: 'tr_2', field: 'name', operator: 'contains', value: 'Invoice' },+ ],+ taggingRuleActions: [+ { id: 'tra_1', taggingRuleId: 'tr_1', tagId: 'tag_1' },+ { id: 'tra_2', taggingRuleId: 'tr_2', tagId: 'tag_2' },+ { id: 'tra_3', taggingRuleId: 'tr_3', tagId: 'tag_1' },+ ],+ });++ const taggingRulesRepository = createTaggingRulesRepository({ db });++ const { taggingRules } = await taggingRulesRepository.getOrganizationEnabledTaggingRules({ organizationId: 'org_1' });++ expect(taggingRules).toHaveLength(2);++ const rule1 = taggingRules.find(r => r.id === 'tr_1');+ const rule2 = taggingRules.find(r => r.id === 'tr_2');++ expect(rule1).toBeDefined();+ expect(rule1?.conditions).toHaveLength(1);+ expect(rule1?.actions).toHaveLength(1);++ expect(rule2).toBeDefined();+ expect(rule2?.conditions).toHaveLength(1);+ expect(rule2?.actions).toHaveLength(1);+ });+ });+});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.tsindex 3ae2d5fc..955f26d6 100644--- a/apps/papra-server/src/modules/tagging-rules/tagging-rules.repository.ts+++ b/apps/papra-server/src/modules/tagging-rules/tagging-rules.repository.ts@@ -4,6 +4,7 @@ import { injectArguments } from '@corentinth/chisels';import { and, eq } from 'drizzle-orm';import { createError } from '../shared/errors/errors';import { omitUndefined } from '../shared/utils';+import { tagsTable } from '../tags/tags.table';import { aggregateTaggingRules } from './tagging-rules.repository.models';import { taggingRuleActionsTable, taggingRuleConditionsTable, taggingRulesTable } from './tagging-rules.tables';@@ -31,7 +32,8 @@ async function getOrganizationTaggingRules({ organizationId, db }: { organizatio.from(taggingRulesTable).where(eq(taggingRulesTable.organizationId, organizationId)).leftJoin(taggingRuleConditionsTable, eq(taggingRulesTable.id, taggingRuleConditionsTable.taggingRuleId))- .leftJoin(taggingRuleActionsTable, eq(taggingRulesTable.id, taggingRuleActionsTable.taggingRuleId));+ .leftJoin(taggingRuleActionsTable, eq(taggingRulesTable.id, taggingRuleActionsTable.taggingRuleId))+ .leftJoin(tagsTable, eq(taggingRuleActionsTable.tagId, tagsTable.id));return aggregateTaggingRules({ rawTaggingRules });}@@ -42,7 +44,8 @@ async function getOrganizationTaggingRule({ organizationId, taggingRuleId, db }:.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));+ .leftJoin(taggingRuleActionsTable, eq(taggingRulesTable.id, taggingRuleActionsTable.taggingRuleId))+ .leftJoin(tagsTable, eq(taggingRuleActionsTable.tagId, tagsTable.id));const { taggingRules = [] } = aggregateTaggingRules({ rawTaggingRules });const [taggingRule] = taggingRules;@@ -61,7 +64,8 @@ async function getOrganizationEnabledTaggingRules({ organizationId, db }: { orgaeq(taggingRulesTable.enabled, true),)).leftJoin(taggingRuleConditionsTable, eq(taggingRulesTable.id, taggingRuleConditionsTable.taggingRuleId))- .leftJoin(taggingRuleActionsTable, eq(taggingRulesTable.id, taggingRuleActionsTable.taggingRuleId));+ .leftJoin(taggingRuleActionsTable, eq(taggingRulesTable.id, taggingRuleActionsTable.taggingRuleId))+ .leftJoin(tagsTable, eq(taggingRuleActionsTable.tagId, tagsTable.id));return aggregateTaggingRules({ rawTaggingRules });}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 3ccb6793..d9149268 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@@ -2,6 +2,7 @@ import type { DocumentActivityRepository } from '../documents/document-activity/import type { Document } from '../documents/documents.types';import type { Logger } from '../shared/logger/logger';import type { TagsRepository } from '../tags/tags.repository';+import type { Tag } from '../tags/tags.types';import type { WebhookRepository } from '../webhooks/webhook.repository';import type { TaggingRuleOperatorValidatorRegistry } from './conditions/tagging-rule-conditions.registry';import type { TaggingRulesRepository } from './tagging-rules.repository';@@ -9,6 +10,7 @@ import type { TaggingRuleField, TaggingRuleOperator } from './tagging-rules.typeimport { safely, safelySync } from '@corentinth/chisels';import { uniq } from 'lodash-es';import { createLogger } from '../shared/logger/logger';+import { isNil } from '../shared/utils';import { addTagToDocument } from '../tags/tags.usecases';import { createTaggingRuleOperatorValidatorRegistry } from './conditions/tagging-rule-conditions.registry';import { getDocumentFieldValue } from './tagging-rules.models';@@ -89,11 +91,10 @@ export async function applyTaggingRules({return isValid;}));- const tagIdsToApply: string[] = uniq(taggingRulesToApplyActions.flatMap(taggingRule => taggingRule.actions.map(action => action.tagId)));+ const tagsToApply: Tag[] = uniq(taggingRulesToApplyActions.flatMap(taggingRule => taggingRule.actions.map(action => action.tag).filter(tag => !isNil(tag))));+ const tagIdsToApply = tagsToApply.map(tag => tag.id);- const tagsToApply = await tagsRepository.getTagsByIds({ tagIds: tagIdsToApply, organizationId: document.organizationId });-- const appliedTagIds = await Promise.all(tagsToApply.tags.map(async (tag) => {+ const appliedTagIds = await Promise.all(tagsToApply.map(async (tag) => {const [, error] = await safely(async () => addTagToDocument({tagId: tag.id,documentId: document.id,diff --git a/apps/papra-server/src/modules/tags/tags.repository.ts b/apps/papra-server/src/modules/tags/tags.repository.tsindex db7d61e7..c58ed7be 100644--- a/apps/papra-server/src/modules/tags/tags.repository.ts+++ b/apps/papra-server/src/modules/tags/tags.repository.ts@@ -1,7 +1,7 @@import type { Database } from '../app/database/database.types';import type { DbInsertableTag } from './tags.types';import { injectArguments, safely } from '@corentinth/chisels';-import { and, eq, getTableColumns, inArray, sql } from 'drizzle-orm';+import { and, eq, getTableColumns, sql } from 'drizzle-orm';import { get } from 'lodash-es';import { documentsTable } from '../documents/documents.table';import { isUniqueConstraintError } from '../shared/db/constraints.models';@@ -16,7 +16,6 @@ export function createTagsRepository({ db }: { db: Database }) {{getOrganizationTags,getTagById,- getTagsByIds,createTag,deleteTag,updateTag,@@ -58,24 +57,6 @@ async function getTagById({ tagId, organizationId, db }: { tagId: string; organireturn { tag };}-async function getTagsByIds({ tagIds, organizationId, db }: { tagIds: string[]; organizationId: string; db: Database }) {- if (tagIds.length === 0) {- return { tags: [] };- }-- const tags = await db- .select()- .from(tagsTable)- .where(- and(- inArray(tagsTable.id, tagIds),- eq(tagsTable.organizationId, organizationId),- ),- );-- return { tags };-}-async function createTag({ tag, db }: { tag: DbInsertableTag; db: Database }) {const [result, error] = await safely(db.insert(tagsTable).values(tag).returning());