Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(search): support custom properties (#965)

Corentin Thomasset87d80af2ac1e
diff --git a/.changeset/sour-hoops-read.md b/.changeset/sour-hoops-read.md
new file mode 100644
index 00000000..97e653de
--- /dev/null
+++ b/.changeset/sour-hoops-read.md
@@ -0,0 +1,5 @@
+---
+"@papra/app": patch
+---
+
+Added support for searching by custom properties. For example, given a custom property `status` of type `select` with options `todo`, `in progress` and `done`, you could search for `status:todo` to find all documents with the status set to todo, or `has:status` to find all documents with a status set (and `-has:status` for documents without a status).
diff --git a/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.models.ts b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.models.ts
index c535cd18..4b81b14d 100644
--- a/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.models.ts
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.models.ts
@@ -1,13 +1,18 @@
import type { Database } from '../../../app/database/database.types';
+import type { CustomPropertyDefinition } from './query-builder/query-builder.custom-properties';
import { parseSearchQuery } from '@papra/search-parser';
import { and, eq } from 'drizzle-orm';
import { documentsTable } from '../../documents.table';
import { buildQueryFromExpression } from './query-builder/query-builder';
-export function makeSearchWhereClause({ query, organizationId, db, now = new Date() }: { query: string; organizationId: string; db: Database; now?: Date }) {
+export function makeSearchWhereClause({ query, organizationId, db, now = new Date(), customPropertyDefinitions = [] }: { query: string; organizationId: string; db: Database; now?: Date; customPropertyDefinitions?: CustomPropertyDefinition[] }) {
const { expression, issues: parsedIssues } = parseSearchQuery({ query });
- const { sqlQuery, issues } = buildQueryFromExpression({ expression, organizationId, db, now });
+ const customPropertyDefinitionsByKey = Object.fromEntries(
+ customPropertyDefinitions.map(definition => [definition.key, definition]),
+ );
+
+ const { sqlQuery, issues } = buildQueryFromExpression({ expression, organizationId, db, now, customPropertyDefinitionsByKey });
return {
searchWhereClause: and(
diff --git a/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.test.ts b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.test.ts
index ff6b52fc..13a614d9 100644
--- a/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.test.ts
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.test.ts
@@ -639,4 +639,627 @@ describe('database-fts5 repository', () => {
expect(afterDelete.documents).to.have.length(0);
});
});
+
+ describe('custom property filters', () => {
+ describe('boolean property', () => {
+ const documents = [
+ { id: 'doc_1', organizationId: 'org_1', name: 'Laptop', originalName: 'laptop.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash1', isDeleted: false },
+ { id: 'doc_2', organizationId: 'org_1', name: 'Phone', originalName: 'phone.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash2', isDeleted: false },
+ { id: 'doc_3', organizationId: 'org_1', name: 'Desk', originalName: 'desk.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash3', isDeleted: false },
+ ];
+
+ const setupDb = async () => {
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org_1', name: 'Organization 1' }],
+ documents,
+ customPropertyDefinitions: [
+ { id: 'cpd_1', organizationId: 'org_1', name: 'Warranty', key: 'warranty', type: 'boolean', displayOrder: 0 },
+ ],
+ documentCustomPropertyValues: [
+ { id: 'dcpv_1', documentId: 'doc_1', propertyDefinitionId: 'cpd_1', booleanValue: true },
+ { id: 'dcpv_2', documentId: 'doc_2', propertyDefinitionId: 'cpd_1', booleanValue: false },
+ // doc_3 has no warranty value set
+ ],
+ });
+
+ const documentsSearchRepository = createDocumentSearchRepository({ db });
+
+ await Promise.all(
+ documents.map(async document => documentsSearchRepository.indexDocument({ document })),
+ );
+
+ return { documentsSearchRepository };
+ };
+
+ test('warranty:true returns only documents with warranty = true', async () => {
+ const { documentsSearchRepository } = await setupDb();
+
+ const { documents: results } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'warranty:true',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(results.map(d => d.id)).to.eql(['doc_1']);
+ });
+
+ test('warranty:false returns only documents with warranty = false', async () => {
+ const { documentsSearchRepository } = await setupDb();
+
+ const { documents: results } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'warranty:false',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(results.map(d => d.id)).to.eql(['doc_2']);
+ });
+
+ test('warranty:yes is accepted as truthy alias', async () => {
+ const { documentsSearchRepository } = await setupDb();
+
+ const { documents: results } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'warranty:yes',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(results.map(d => d.id)).to.eql(['doc_1']);
+ });
+
+ test('-warranty:true (NOT) returns documents without warranty = true', async () => {
+ const { documentsSearchRepository } = await setupDb();
+
+ const { documents: results } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: '-warranty:true',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(results.map(d => d.id).toSorted()).to.eql(['doc_2', 'doc_3'].toSorted());
+ });
+ });
+
+ describe('text property', () => {
+ const documents = [
+ { id: 'doc_1', organizationId: 'org_1', name: 'File A', originalName: 'a.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash1', isDeleted: false },
+ { id: 'doc_2', organizationId: 'org_1', name: 'File B', originalName: 'b.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash2', isDeleted: false },
+ { id: 'doc_3', organizationId: 'org_1', name: 'File C', originalName: 'c.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash3', isDeleted: false },
+ ];
+
+ test('category:invoice returns only documents where category text = "invoice"', async () => {
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org_1', name: 'Organization 1' }],
+ documents,
+ customPropertyDefinitions: [
+ { id: 'cpd_2', organizationId: 'org_1', name: 'Category', key: 'category', type: 'text', displayOrder: 0 },
+ ],
+ documentCustomPropertyValues: [
+ { id: 'dcpv_1', documentId: 'doc_1', propertyDefinitionId: 'cpd_2', textValue: 'invoice' },
+ { id: 'dcpv_2', documentId: 'doc_2', propertyDefinitionId: 'cpd_2', textValue: 'contract' },
+ ],
+ });
+
+ const documentsSearchRepository = createDocumentSearchRepository({ db });
+
+ await Promise.all(
+ documents.map(async document => documentsSearchRepository.indexDocument({ document })),
+ );
+
+ const { documents: results } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'category:invoice',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(results.map(d => d.id)).to.eql(['doc_1']);
+ });
+ });
+
+ describe('number property', () => {
+ const documents = [
+ { id: 'doc_1', organizationId: 'org_1', name: 'Small', originalName: 's.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash1', isDeleted: false },
+ { id: 'doc_2', organizationId: 'org_1', name: 'Medium', originalName: 'm.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash2', isDeleted: false },
+ { id: 'doc_3', organizationId: 'org_1', name: 'Large', originalName: 'l.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash3', isDeleted: false },
+ ];
+
+ const setupDb = async () => {
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org_1', name: 'Organization 1' }],
+ documents,
+ customPropertyDefinitions: [
+ { id: 'cpd_3', organizationId: 'org_1', name: 'Amount', key: 'amount', type: 'number', displayOrder: 0 },
+ ],
+ documentCustomPropertyValues: [
+ { id: 'dcpv_1', documentId: 'doc_1', propertyDefinitionId: 'cpd_3', numberValue: 50 },
+ { id: 'dcpv_2', documentId: 'doc_2', propertyDefinitionId: 'cpd_3', numberValue: 150 },
+ { id: 'dcpv_3', documentId: 'doc_3', propertyDefinitionId: 'cpd_3', numberValue: 300 },
+ ],
+ });
+
+ const documentsSearchRepository = createDocumentSearchRepository({ db });
+
+ await Promise.all(
+ documents.map(async document => documentsSearchRepository.indexDocument({ document })),
+ );
+
+ return { documentsSearchRepository };
+ };
+
+ test('amount:150 returns only the document with amount = 150', async () => {
+ const { documentsSearchRepository } = await setupDb();
+
+ const { documents: results } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'amount:150',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(results.map(d => d.id)).to.eql(['doc_2']);
+ });
+
+ test('amount:>100 returns documents with amount greater than 100', async () => {
+ const { documentsSearchRepository } = await setupDb();
+
+ const { documents: results } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'amount:>100',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(results.map(d => d.id).toSorted()).to.eql(['doc_2', 'doc_3'].toSorted());
+ });
+
+ test('amount:>=150 amount:<=200 (AND) returns only doc_2', async () => {
+ const { documentsSearchRepository } = await setupDb();
+
+ const { documents: results } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'amount:>=150 amount:<=200',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(results.map(d => d.id)).to.eql(['doc_2']);
+ });
+ });
+
+ describe('date property', () => {
+ const documents = [
+ { id: 'doc_1', organizationId: 'org_1', name: 'Old', originalName: 'old.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash1', isDeleted: false },
+ { id: 'doc_2', organizationId: 'org_1', name: 'Recent', originalName: 'recent.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash2', isDeleted: false },
+ { id: 'doc_3', organizationId: 'org_1', name: 'Future', originalName: 'future.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash3', isDeleted: false },
+ ];
+
+ test('expiry:>2025-06-01 returns documents with expiry date after 2025-06-01', async () => {
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org_1', name: 'Organization 1' }],
+ documents,
+ customPropertyDefinitions: [
+ { id: 'cpd_4', organizationId: 'org_1', name: 'Expiry', key: 'expiry', type: 'date', displayOrder: 0 },
+ ],
+ documentCustomPropertyValues: [
+ { id: 'dcpv_1', documentId: 'doc_1', propertyDefinitionId: 'cpd_4', dateValue: new Date('2024-01-01') },
+ { id: 'dcpv_2', documentId: 'doc_2', propertyDefinitionId: 'cpd_4', dateValue: new Date('2025-07-01') },
+ { id: 'dcpv_3', documentId: 'doc_3', propertyDefinitionId: 'cpd_4', dateValue: new Date('2026-01-01') },
+ ],
+ });
+
+ const documentsSearchRepository = createDocumentSearchRepository({ db });
+
+ await Promise.all(
+ documents.map(async document => documentsSearchRepository.indexDocument({ document })),
+ );
+
+ const { documents: results } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'expiry:>2025-06-01',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(results.map(d => d.id).toSorted()).to.eql(['doc_2', 'doc_3'].toSorted());
+ });
+ });
+
+ describe('select property', () => {
+ const documents = [
+ { id: 'doc_1', organizationId: 'org_1', name: 'Draft', originalName: 'd.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash1', isDeleted: false },
+ { id: 'doc_2', organizationId: 'org_1', name: 'Approved', originalName: 'a.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash2', isDeleted: false },
+ { id: 'doc_3', organizationId: 'org_1', name: 'Rejected', originalName: 'r.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash3', isDeleted: false },
+ ];
+
+ test('status:approved returns only documents whose select option key is "approved"', async () => {
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org_1', name: 'Organization 1' }],
+ documents,
+ customPropertyDefinitions: [
+ { id: 'cpd_5', organizationId: 'org_1', name: 'Status', key: 'status', type: 'select', displayOrder: 0 },
+ ],
+ customPropertySelectOptions: [
+ { id: 'cpso_1', propertyDefinitionId: 'cpd_5', name: 'Draft', key: 'draft', displayOrder: 0 },
+ { id: 'cpso_2', propertyDefinitionId: 'cpd_5', name: 'Approved', key: 'approved', displayOrder: 1 },
+ { id: 'cpso_3', propertyDefinitionId: 'cpd_5', name: 'Rejected', key: 'rejected', displayOrder: 2 },
+ ],
+ documentCustomPropertyValues: [
+ { id: 'dcpv_1', documentId: 'doc_1', propertyDefinitionId: 'cpd_5', selectOptionId: 'cpso_1' },
+ { id: 'dcpv_2', documentId: 'doc_2', propertyDefinitionId: 'cpd_5', selectOptionId: 'cpso_2' },
+ { id: 'dcpv_3', documentId: 'doc_3', propertyDefinitionId: 'cpd_5', selectOptionId: 'cpso_3' },
+ ],
+ });
+
+ const documentsSearchRepository = createDocumentSearchRepository({ db });
+
+ await Promise.all(
+ documents.map(async document => documentsSearchRepository.indexDocument({ document })),
+ );
+
+ const { documents: results } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'status:approved',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(results.map(d => d.id)).to.eql(['doc_2']);
+ });
+ });
+
+ describe('multi_select property', () => {
+ test('labels:urgent returns documents that have the "urgent" option among their multi-select values', async () => {
+ const documents = [
+ { id: 'doc_1', organizationId: 'org_1', name: 'File A', originalName: 'a.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash1', isDeleted: false },
+ { id: 'doc_2', organizationId: 'org_1', name: 'File B', originalName: 'b.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash2', isDeleted: false },
+ ];
+
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org_1', name: 'Organization 1' }],
+ documents,
+ customPropertyDefinitions: [
+ { id: 'cpd_6', organizationId: 'org_1', name: 'Labels', key: 'labels', type: 'multi_select', displayOrder: 0 },
+ ],
+ customPropertySelectOptions: [
+ { id: 'cpso_1', propertyDefinitionId: 'cpd_6', name: 'Urgent', key: 'urgent', displayOrder: 0 },
+ { id: 'cpso_2', propertyDefinitionId: 'cpd_6', name: 'Low Priority', key: 'low-priority', displayOrder: 1 },
+ ],
+ documentCustomPropertyValues: [
+ // doc_1 has both "urgent" and "low-priority"
+ { id: 'dcpv_1', documentId: 'doc_1', propertyDefinitionId: 'cpd_6', selectOptionId: 'cpso_1' },
+ { id: 'dcpv_2', documentId: 'doc_1', propertyDefinitionId: 'cpd_6', selectOptionId: 'cpso_2' },
+ // doc_2 has only "low-priority"
+ { id: 'dcpv_3', documentId: 'doc_2', propertyDefinitionId: 'cpd_6', selectOptionId: 'cpso_2' },
+ ],
+ });
+
+ const documentsSearchRepository = createDocumentSearchRepository({ db });
+
+ await Promise.all(
+ documents.map(async document => documentsSearchRepository.indexDocument({ document })),
+ );
+
+ const { documents: results } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'labels:urgent',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(results.map(d => d.id)).to.eql(['doc_1']);
+ });
+ });
+
+ describe('combined filters', () => {
+ test('warranty:true AND category:invoice returns only documents matching both conditions', async () => {
+ const documents = [
+ { id: 'doc_1', organizationId: 'org_1', name: 'A', originalName: 'a.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash1', isDeleted: false },
+ { id: 'doc_2', organizationId: 'org_1', name: 'B', originalName: 'b.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash2', isDeleted: false },
+ { id: 'doc_3', organizationId: 'org_1', name: 'C', originalName: 'c.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash3', isDeleted: false },
+ ];
+
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org_1', name: 'Organization 1' }],
+ documents,
+ customPropertyDefinitions: [
+ { id: 'cpd_1', organizationId: 'org_1', name: 'Warranty', key: 'warranty', type: 'boolean', displayOrder: 0 },
+ { id: 'cpd_2', organizationId: 'org_1', name: 'Category', key: 'category', type: 'text', displayOrder: 1 },
+ ],
+ documentCustomPropertyValues: [
+ // doc_1: warranty=true, category=invoice → should match
+ { id: 'dcpv_1', documentId: 'doc_1', propertyDefinitionId: 'cpd_1', booleanValue: true },
+ { id: 'dcpv_2', documentId: 'doc_1', propertyDefinitionId: 'cpd_2', textValue: 'invoice' },
+ // doc_2: warranty=true, category=contract → should not match
+ { id: 'dcpv_3', documentId: 'doc_2', propertyDefinitionId: 'cpd_1', booleanValue: true },
+ { id: 'dcpv_4', documentId: 'doc_2', propertyDefinitionId: 'cpd_2', textValue: 'contract' },
+ // doc_3: warranty=false, category=invoice → should not match
+ { id: 'dcpv_5', documentId: 'doc_3', propertyDefinitionId: 'cpd_1', booleanValue: false },
+ { id: 'dcpv_6', documentId: 'doc_3', propertyDefinitionId: 'cpd_2', textValue: 'invoice' },
+ ],
+ });
+
+ const documentsSearchRepository = createDocumentSearchRepository({ db });
+
+ await Promise.all(
+ documents.map(async document => documentsSearchRepository.indexDocument({ document })),
+ );
+
+ const { documents: results } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'warranty:true AND category:invoice',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(results.map(d => d.id)).to.eql(['doc_1']);
+ });
+ });
+
+ describe('unknown custom property key', () => {
+ test('a filter for an unknown key returns no results without crashing', async () => {
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org_1', name: 'Organization 1' }],
+ documents: [
+ { id: 'doc_1', organizationId: 'org_1', name: 'File', originalName: 'f.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash1', isDeleted: false },
+ ],
+ });
+
+ const documentsSearchRepository = createDocumentSearchRepository({ db });
+
+ await documentsSearchRepository.indexDocument({
+ document: { id: 'doc_1', organizationId: 'org_1', name: 'File', originalName: 'f.pdf', content: '', isDeleted: false },
+ });
+
+ const { documents: results } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'unknownprop:foo',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(results).to.have.length(0);
+ });
+ });
+
+ describe('organization isolation', () => {
+ test('a custom property key from org_2 does not match documents in org_1', async () => {
+ const { db } = await createInMemoryDatabase({
+ organizations: [
+ { id: 'org_1', name: 'Organization 1' },
+ { id: 'org_2', name: 'Organization 2' },
+ ],
+ documents: [
+ { id: 'doc_1', organizationId: 'org_1', name: 'Org1 File', originalName: 'a.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash1', isDeleted: false },
+ { id: 'doc_2', organizationId: 'org_2', name: 'Org2 File', originalName: 'b.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash2', isDeleted: false },
+ ],
+ customPropertyDefinitions: [
+ // Same key "warranty" exists in both orgs
+ { id: 'cpd_org1', organizationId: 'org_1', name: 'Warranty', key: 'warranty', type: 'boolean', displayOrder: 0 },
+ { id: 'cpd_org2', organizationId: 'org_2', name: 'Warranty', key: 'warranty', type: 'boolean', displayOrder: 0 },
+ ],
+ documentCustomPropertyValues: [
+ { id: 'dcpv_1', documentId: 'doc_1', propertyDefinitionId: 'cpd_org1', booleanValue: true },
+ { id: 'dcpv_2', documentId: 'doc_2', propertyDefinitionId: 'cpd_org2', booleanValue: true },
+ ],
+ });
+
+ const documentsSearchRepository = createDocumentSearchRepository({ db });
+
+ await documentsSearchRepository.indexDocument({
+ document: { id: 'doc_1', organizationId: 'org_1', name: 'Org1 File', originalName: 'a.pdf', content: '', isDeleted: false },
+ });
+ await documentsSearchRepository.indexDocument({
+ document: { id: 'doc_2', organizationId: 'org_2', name: 'Org2 File', originalName: 'b.pdf', content: '', isDeleted: false },
+ });
+
+ const { documents: org1Results } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'warranty:true',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(org1Results.map(d => d.id)).to.eql(['doc_1']);
+ });
+ });
+
+ describe('user_relation property', () => {
+ const documents = [
+ { id: 'doc_1', organizationId: 'org_1', name: 'File A', originalName: 'a.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash1', isDeleted: false },
+ { id: 'doc_2', organizationId: 'org_1', name: 'File B', originalName: 'b.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash2', isDeleted: false },
+ { id: 'doc_3', organizationId: 'org_1', name: 'File C', originalName: 'c.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash3', isDeleted: false },
+ ];
+
+ const setupDb = async () => {
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org_1', name: 'Organization 1' }],
+ users: [
+ { id: 'usr_1', email: '[email protected]' },
+ { id: 'usr_2', email: '[email protected]' },
+ ],
+ documents,
+ customPropertyDefinitions: [
+ { id: 'cpd_7', organizationId: 'org_1', name: 'Assignee', key: 'assignee', type: 'user_relation', displayOrder: 0 },
+ ],
+ documentCustomPropertyValues: [
+ { id: 'dcpv_1', documentId: 'doc_1', propertyDefinitionId: 'cpd_7', userId: 'usr_1' },
+ { id: 'dcpv_2', documentId: 'doc_2', propertyDefinitionId: 'cpd_7', userId: 'usr_2' },
+ // doc_3 has no assignee
+ ],
+ });
+
+ const documentsSearchRepository = createDocumentSearchRepository({ db });
+
+ await Promise.all(
+ documents.map(async document => documentsSearchRepository.indexDocument({ document })),
+ );
+
+ return { documentsSearchRepository };
+ };
+
+ test('assignee:usr_1 returns only documents assigned to user with that id', async () => {
+ const { documentsSearchRepository } = await setupDb();
+
+ const { documents: results } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'assignee:usr_1',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(results.map(d => d.id)).to.eql(['doc_1']);
+ });
+
+ test('assignee:[email protected] returns the document assigned to that email', async () => {
+ const { documentsSearchRepository } = await setupDb();
+
+ const { documents: results } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'assignee:[email protected]',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(results.map(d => d.id)).to.eql(['doc_1']);
+ });
+
+ test('-assignee:usr_1 (NOT) returns documents not assigned to that user', async () => {
+ const { documentsSearchRepository } = await setupDb();
+
+ const { documents: results } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: '-assignee:usr_1',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(results.map(d => d.id).toSorted()).to.eql(['doc_2', 'doc_3'].toSorted());
+ });
+ });
+
+ describe('document_relation property', () => {
+ const documents = [
+ { id: 'doc_1', organizationId: 'org_1', name: 'Contract', originalName: 'contract.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash1', isDeleted: false },
+ { id: 'doc_2', organizationId: 'org_1', name: 'Amendment', originalName: 'amendment.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash2', isDeleted: false },
+ { id: 'doc_3', organizationId: 'org_1', name: 'Standalone', originalName: 'standalone.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash3', isDeleted: false },
+ ];
+
+ test('related:doc_1 returns only documents whose relation points to doc_1', async () => {
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org_1', name: 'Organization 1' }],
+ documents,
+ customPropertyDefinitions: [
+ { id: 'cpd_8', organizationId: 'org_1', name: 'Related Document', key: 'related', type: 'document_relation', displayOrder: 0 },
+ ],
+ documentCustomPropertyValues: [
+ { id: 'dcpv_1', documentId: 'doc_2', propertyDefinitionId: 'cpd_8', relatedDocumentId: 'doc_1' },
+ // doc_3 has no relation
+ ],
+ });
+
+ const documentsSearchRepository = createDocumentSearchRepository({ db });
+
+ await Promise.all(
+ documents.map(async document => documentsSearchRepository.indexDocument({ document })),
+ );
+
+ const { documents: results } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'related:doc_1',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(results.map(d => d.id)).to.eql(['doc_2']);
+ });
+ });
+
+ describe('has: filter for custom properties', () => {
+ const documents = [
+ { id: 'doc_1', organizationId: 'org_1', name: 'With warranty', originalName: 'a.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash1', isDeleted: false },
+ { id: 'doc_2', organizationId: 'org_1', name: 'Also with warranty', originalName: 'b.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash2', isDeleted: false },
+ { id: 'doc_3', organizationId: 'org_1', name: 'No warranty', originalName: 'c.pdf', content: '', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash3', isDeleted: false },
+ ];
+
+ const setupDb = async () => {
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'org_1', name: 'Organization 1' }],
+ documents,
+ customPropertyDefinitions: [
+ { id: 'cpd_1', organizationId: 'org_1', name: 'Warranty', key: 'warranty', type: 'boolean', displayOrder: 0 },
+ ],
+ documentCustomPropertyValues: [
+ { id: 'dcpv_1', documentId: 'doc_1', propertyDefinitionId: 'cpd_1', booleanValue: true },
+ { id: 'dcpv_2', documentId: 'doc_2', propertyDefinitionId: 'cpd_1', booleanValue: false },
+ // doc_3 has no warranty value at all
+ ],
+ });
+
+ const documentsSearchRepository = createDocumentSearchRepository({ db });
+
+ await Promise.all(
+ documents.map(async document => documentsSearchRepository.indexDocument({ document })),
+ );
+
+ return { documentsSearchRepository };
+ };
+
+ test('has:warranty returns all documents that have any value set for the property', async () => {
+ const { documentsSearchRepository } = await setupDb();
+
+ const { documents: results } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'has:warranty',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(results.map(d => d.id).toSorted()).to.eql(['doc_1', 'doc_2'].toSorted());
+ });
+
+ test('-has:warranty returns only documents with no value set for the property', async () => {
+ const { documentsSearchRepository } = await setupDb();
+
+ const { documents: results } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: '-has:warranty',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(results.map(d => d.id)).to.eql(['doc_3']);
+ });
+
+ test('has:warranty combined with a value filter narrows results correctly', async () => {
+ const { documentsSearchRepository } = await setupDb();
+
+ const { documents: results } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'has:warranty warranty:true',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(results.map(d => d.id)).to.eql(['doc_1']);
+ });
+
+ test('has:unknownprop returns no results without crashing', async () => {
+ const { documentsSearchRepository } = await setupDb();
+
+ const { documents: results } = await documentsSearchRepository.searchOrganizationDocuments({
+ organizationId: 'org_1',
+ searchQuery: 'has:unknownprop',
+ pageIndex: 0,
+ pageSize: 10,
+ });
+
+ expect(results).to.have.length(0);
+ });
+ });
+ });
});
diff --git a/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.ts b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.ts
index 2a2e6bc9..42f7e8dd 100644
--- a/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.ts
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/database-fts5.repository.ts
@@ -3,6 +3,7 @@ import type { DocumentSearchableData } from '../document-search.types';
import { injectArguments } from '@corentinth/chisels';
import { desc, eq, getTableColumns, sql } from 'drizzle-orm';
import { omit } from 'lodash-es';
+import { customPropertyDefinitionsTable } from '../../../custom-properties/custom-properties.table';
import { omitUndefined } from '../../../shared/utils';
import { documentsTable } from '../../documents.table';
import { makeSearchWhereClause } from './database-fts5.repository.models';
@@ -20,7 +21,12 @@ export function createDocumentSearchRepository({ db }: { db: Database }) {
}
async function searchOrganizationDocuments({ organizationId, searchQuery, pageIndex, pageSize, db, now = new Date() }: { organizationId: string; searchQuery: string; pageIndex: number; pageSize: number; db: Database; now?: Date }) {
- const { searchWhereClause } = makeSearchWhereClause({ organizationId, query: searchQuery, db, now });
+ const customPropertyDefinitions = await db
+ .select()
+ .from(customPropertyDefinitionsTable)
+ .where(eq(customPropertyDefinitionsTable.organizationId, organizationId));
+
+ const { searchWhereClause } = makeSearchWhereClause({ organizationId, query: searchQuery, db, now, customPropertyDefinitions });
const paginatedIdsSubquery = db
.selectDistinct({ id: documentsTable.id, createdAt: documentsTable.createdAt })
diff --git a/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.custom-properties.models.ts b/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.custom-properties.models.ts
new file mode 100644
index 00000000..2a794c57
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.custom-properties.models.ts
@@ -0,0 +1,8 @@
+import type { CustomPropertyDefinitionsByKey } from './query-builder.custom-properties';
+import { generatePropertyKey } from '../../../../custom-properties/custom-properties.repository.models';
+
+export function getCustomPropertyDefinition({ name, customPropertyDefinitionsByKey }: { name: string; customPropertyDefinitionsByKey: CustomPropertyDefinitionsByKey }) {
+ const key = generatePropertyKey({ name });
+
+ return customPropertyDefinitionsByKey[key];
+}
diff --git a/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.custom-properties.test.ts b/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.custom-properties.test.ts
new file mode 100644
index 00000000..131b83a2
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.custom-properties.test.ts
@@ -0,0 +1,469 @@
+import type { SQL } from 'drizzle-orm';
+import type { CustomPropertyDefinition } from './query-builder.custom-properties';
+import { SQLiteSyncDialect } from 'drizzle-orm/sqlite-core';
+import { describe, expect, test } from 'vitest';
+import { createInMemoryDatabase } from '../../../../app/database/database.test-utils';
+import { handleCustomPropertyFilter, handleHasCustomPropertyFilter } from './query-builder.custom-properties';
+
+describe('query-builder - custom properties', async () => {
+ const { db } = await createInMemoryDatabase();
+ const sqliteDialect = new SQLiteSyncDialect();
+ const now = new Date('2025-06-15');
+
+ const getSqlString = (query?: SQL) => {
+ if (!query) {
+ return { sql: '', params: [] };
+ }
+
+ const { sql, params } = sqliteDialect.sqlToQuery(query);
+
+ return { sql, params };
+ };
+
+ function makeDefinition(overrides: Partial<CustomPropertyDefinition> = {}): CustomPropertyDefinition {
+ return {
+ id: 'cpd_1',
+ organizationId: 'org_1',
+ name: 'Warranty',
+ key: 'warranty',
+ description: null,
+ type: 'boolean',
+ config: null,
+ displayOrder: 0,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ ...overrides,
+ };
+ }
+
+ describe('boolean property filter', () => {
+ test('warranty:true builds a subquery matching booleanValue = 1', () => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'warranty', operator: '=', value: 'true' },
+ definition: makeDefinition({ type: 'boolean' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([]);
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `"documents"."id" in (select "document_id" from "document_custom_property_values" where ("document_custom_property_values"."property_definition_id" = ? and "document_custom_property_values"."boolean_value" = ?))`,
+ params: ['cpd_1', 1],
+ });
+ });
+
+ test('warranty:false builds a subquery matching booleanValue = 0', () => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'warranty', operator: '=', value: 'false' },
+ definition: makeDefinition({ type: 'boolean' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([]);
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `"documents"."id" in (select "document_id" from "document_custom_property_values" where ("document_custom_property_values"."property_definition_id" = ? and "document_custom_property_values"."boolean_value" = ?))`,
+ params: ['cpd_1', 0],
+ });
+ });
+
+ test.each([
+ ['yes', 1],
+ ['y', 1],
+ ['1', 1],
+ ['on', 1],
+ ['enabled', 1],
+ ['YES', 1],
+ ['TRUE', 1],
+ ['no', 0],
+ ['n', 0],
+ ['0', 0],
+ ['off', 0],
+ ['disabled', 0],
+ ['NO', 0],
+ ['FALSE', 0],
+ ])('warranty:%s is accepted as a valid boolean value', (value, expected) => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'warranty', operator: '=', value },
+ definition: makeDefinition({ type: 'boolean' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([]);
+ expect(getSqlString(sqlQuery).params[1]).to.equal(expected);
+ });
+
+ test('warranty:maybe returns an INVALID_BOOLEAN_VALUE issue and a no-match query', () => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'warranty', operator: '=', value: 'maybe' },
+ definition: makeDefinition({ type: 'boolean' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([{
+ message: 'Invalid boolean value "maybe" for warranty filter. Expected one of: true, yes, y, 1, on, enabled, false, no, n, 0, off, disabled',
+ code: 'INVALID_BOOLEAN_VALUE',
+ }]);
+ expect(getSqlString(sqlQuery)).to.eql({ sql: '0', params: [] });
+ });
+
+ test('warranty:>true returns an UNSUPPORTED_FILTER_OPERATOR issue for non-equality operators', () => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'warranty', operator: '>', value: 'true' },
+ definition: makeDefinition({ type: 'boolean' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([{
+ message: 'Unsupported operator ">" for warranty filter',
+ code: 'UNSUPPORTED_FILTER_OPERATOR',
+ }]);
+ expect(getSqlString(sqlQuery)).to.eql({ sql: '0', params: [] });
+ });
+ });
+
+ describe('text property filter', () => {
+ test('category:invoice builds an exact-match subquery on textValue', () => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'category', operator: '=', value: 'invoice' },
+ definition: makeDefinition({ id: 'cpd_2', type: 'text', key: 'category' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([]);
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `"documents"."id" in (select "document_id" from "document_custom_property_values" where ("document_custom_property_values"."property_definition_id" = ? and "document_custom_property_values"."text_value" = ?))`,
+ params: ['cpd_2', 'invoice'],
+ });
+ });
+
+ test('category:>invoice returns an UNSUPPORTED_FILTER_OPERATOR issue', () => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'category', operator: '>', value: 'invoice' },
+ definition: makeDefinition({ id: 'cpd_2', type: 'text', key: 'category' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([{
+ message: 'Unsupported operator ">" for category filter',
+ code: 'UNSUPPORTED_FILTER_OPERATOR',
+ }]);
+ expect(getSqlString(sqlQuery)).to.eql({ sql: '0', params: [] });
+ });
+ });
+
+ describe('number property filter', () => {
+ test('amount:100 builds an equality subquery on numberValue', () => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'amount', operator: '=', value: '100' },
+ definition: makeDefinition({ id: 'cpd_3', type: 'number', key: 'amount' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([]);
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `"documents"."id" in (select "document_id" from "document_custom_property_values" where ("document_custom_property_values"."property_definition_id" = ? and "document_custom_property_values"."number_value" = ?))`,
+ params: ['cpd_3', 100],
+ });
+ });
+
+ test('amount:>100 uses the greater-than operator', () => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'amount', operator: '>', value: '100' },
+ definition: makeDefinition({ id: 'cpd_3', type: 'number', key: 'amount' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([]);
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `"documents"."id" in (select "document_id" from "document_custom_property_values" where ("document_custom_property_values"."property_definition_id" = ? and "document_custom_property_values"."number_value" > ?))`,
+ params: ['cpd_3', 100],
+ });
+ });
+
+ test('amount:>=100 uses the greater-than-or-equal operator', () => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'amount', operator: '>=', value: '100' },
+ definition: makeDefinition({ id: 'cpd_3', type: 'number', key: 'amount' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([]);
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `"documents"."id" in (select "document_id" from "document_custom_property_values" where ("document_custom_property_values"."property_definition_id" = ? and "document_custom_property_values"."number_value" >= ?))`,
+ params: ['cpd_3', 100],
+ });
+ });
+
+ test('amount:<100 uses the less-than operator', () => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'amount', operator: '<', value: '100' },
+ definition: makeDefinition({ id: 'cpd_3', type: 'number', key: 'amount' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([]);
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `"documents"."id" in (select "document_id" from "document_custom_property_values" where ("document_custom_property_values"."property_definition_id" = ? and "document_custom_property_values"."number_value" < ?))`,
+ params: ['cpd_3', 100],
+ });
+ });
+
+ test('amount:<=100 uses the less-than-or-equal operator', () => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'amount', operator: '<=', value: '100' },
+ definition: makeDefinition({ id: 'cpd_3', type: 'number', key: 'amount' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([]);
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `"documents"."id" in (select "document_id" from "document_custom_property_values" where ("document_custom_property_values"."property_definition_id" = ? and "document_custom_property_values"."number_value" <= ?))`,
+ params: ['cpd_3', 100],
+ });
+ });
+
+ test('amount:notanumber returns an INVALID_NUMBER_VALUE issue', () => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'amount', operator: '=', value: 'notanumber' },
+ definition: makeDefinition({ id: 'cpd_3', type: 'number', key: 'amount' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([{
+ message: 'Invalid number value "notanumber" for amount filter. Expected a numeric value.',
+ code: 'INVALID_NUMBER_VALUE',
+ }]);
+ expect(getSqlString(sqlQuery)).to.eql({ sql: '0', params: [] });
+ });
+ });
+
+ describe('date property filter', () => {
+ test('expiry:2025-01-01 builds an equality subquery on dateValue', () => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'expiry', operator: '=', value: '2025-01-01' },
+ definition: makeDefinition({ id: 'cpd_4', type: 'date', key: 'expiry' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([]);
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `"documents"."id" in (select "document_id" from "document_custom_property_values" where ("document_custom_property_values"."property_definition_id" = ? and "document_custom_property_values"."date_value" = ?))`,
+ params: ['cpd_4', 1735689600000],
+ });
+ });
+
+ test('expiry:>2025-01-01 uses the greater-than operator', () => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'expiry', operator: '>', value: '2025-01-01' },
+ definition: makeDefinition({ id: 'cpd_4', type: 'date', key: 'expiry' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([]);
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `"documents"."id" in (select "document_id" from "document_custom_property_values" where ("document_custom_property_values"."property_definition_id" = ? and "document_custom_property_values"."date_value" > ?))`,
+ params: ['cpd_4', 1735689600000],
+ });
+ });
+
+ test('expiry:now uses the current timestamp', () => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'expiry', operator: '=', value: 'now' },
+ definition: makeDefinition({ id: 'cpd_4', type: 'date', key: 'expiry' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([]);
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `"documents"."id" in (select "document_id" from "document_custom_property_values" where ("document_custom_property_values"."property_definition_id" = ? and "document_custom_property_values"."date_value" = ?))`,
+ params: ['cpd_4', now.getTime()],
+ });
+ });
+
+ test('expiry:not-a-date returns an INVALID_DATE_FORMAT issue', () => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'expiry', operator: '=', value: 'not-a-date' },
+ definition: makeDefinition({ id: 'cpd_4', type: 'date', key: 'expiry' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([{
+ message: 'Invalid date format for expiry filter: "not-a-date". Expected a valid date string.',
+ code: 'INVALID_DATE_FORMAT',
+ }]);
+ expect(getSqlString(sqlQuery)).to.eql({ sql: '0', params: [] });
+ });
+ });
+
+ describe('select property filter', () => {
+ test('status:approved builds a subquery joining select options by key', () => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'status', operator: '=', value: 'approved' },
+ definition: makeDefinition({ id: 'cpd_5', type: 'select', key: 'status' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([]);
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `"documents"."id" in (select "document_custom_property_values"."document_id" from "document_custom_property_values" inner join "custom_property_select_options" on "document_custom_property_values"."select_option_id" = "custom_property_select_options"."id" where ("document_custom_property_values"."property_definition_id" = ? and "custom_property_select_options"."key" = ?))`,
+ params: ['cpd_5', 'approved'],
+ });
+ });
+
+ test('status:>approved returns an UNSUPPORTED_FILTER_OPERATOR issue', () => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'status', operator: '>', value: 'approved' },
+ definition: makeDefinition({ id: 'cpd_5', type: 'select', key: 'status' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([{
+ message: 'Unsupported operator ">" for status filter',
+ code: 'UNSUPPORTED_FILTER_OPERATOR',
+ }]);
+ expect(getSqlString(sqlQuery)).to.eql({ sql: '0', params: [] });
+ });
+ });
+
+ describe('multi_select property filter', () => {
+ test('labels:urgent builds a subquery joining select options by key (same as select)', () => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'labels', operator: '=', value: 'urgent' },
+ definition: makeDefinition({ id: 'cpd_6', type: 'multi_select', key: 'labels' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([]);
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `"documents"."id" in (select "document_custom_property_values"."document_id" from "document_custom_property_values" inner join "custom_property_select_options" on "document_custom_property_values"."select_option_id" = "custom_property_select_options"."id" where ("document_custom_property_values"."property_definition_id" = ? and "custom_property_select_options"."key" = ?))`,
+ params: ['cpd_6', 'urgent'],
+ });
+ });
+ });
+
+ describe('user_relation property filter', () => {
+ test('assignee:usr_1 builds a subquery matching userId directly', () => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'assignee', operator: '=', value: 'usr_1' },
+ definition: makeDefinition({ id: 'cpd_7', type: 'user_relation', key: 'assignee' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([]);
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `"documents"."id" in (select "document_custom_property_values"."document_id" from "document_custom_property_values" left join "users" on "document_custom_property_values"."user_id" = "users"."id" where ("document_custom_property_values"."property_definition_id" = ? and ("document_custom_property_values"."user_id" = ? or "users"."email" = ? or "users"."name" = ?)))`,
+ params: ['cpd_7', 'usr_1', 'usr_1', 'usr_1'],
+ });
+ });
+
+ test('assignee:[email protected] builds a subquery matching by email via left join', () => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'assignee', operator: '=', value: '[email protected]' },
+ definition: makeDefinition({ id: 'cpd_7', type: 'user_relation', key: 'assignee' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([]);
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `"documents"."id" in (select "document_custom_property_values"."document_id" from "document_custom_property_values" left join "users" on "document_custom_property_values"."user_id" = "users"."id" where ("document_custom_property_values"."property_definition_id" = ? and ("document_custom_property_values"."user_id" = ? or "users"."email" = ? or "users"."name" = ?)))`,
+ });
+ });
+
+ test('assignee:>usr_1 returns an UNSUPPORTED_FILTER_OPERATOR issue', () => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'assignee', operator: '>', value: 'usr_1' },
+ definition: makeDefinition({ id: 'cpd_7', type: 'user_relation', key: 'assignee' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([{
+ message: 'Unsupported operator ">" for assignee filter',
+ code: 'UNSUPPORTED_FILTER_OPERATOR',
+ }]);
+ expect(getSqlString(sqlQuery)).to.eql({ sql: '0', params: [] });
+ });
+ });
+
+ describe('document_relation property filter', () => {
+ test('related:doc_1 builds a subquery matching relatedDocumentId directly', () => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'related', operator: '=', value: 'doc_1' },
+ definition: makeDefinition({ id: 'cpd_8', type: 'document_relation', key: 'related' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([]);
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `"documents"."id" in (select "document_id" from "document_custom_property_values" where ("document_custom_property_values"."property_definition_id" = ? and "document_custom_property_values"."related_document_id" = ?))`,
+ params: ['cpd_8', 'doc_1'],
+ });
+ });
+
+ test('related:>doc_1 returns an UNSUPPORTED_FILTER_OPERATOR issue', () => {
+ const { sqlQuery, issues } = handleCustomPropertyFilter({
+ expression: { type: 'filter', field: 'related', operator: '>', value: 'doc_1' },
+ definition: makeDefinition({ id: 'cpd_8', type: 'document_relation', key: 'related' }),
+ db,
+ now,
+ });
+
+ expect(issues).to.eql([{
+ message: 'Unsupported operator ">" for related filter',
+ code: 'UNSUPPORTED_FILTER_OPERATOR',
+ }]);
+ expect(getSqlString(sqlQuery)).to.eql({ sql: '0', params: [] });
+ });
+ });
+
+ describe('has custom property filter', () => {
+ test('has:warranty builds a subquery checking for any row with that property definition id', () => {
+ const { sqlQuery, issues } = handleHasCustomPropertyFilter({
+ definition: makeDefinition({ id: 'cpd_1', type: 'boolean', key: 'warranty' }),
+ db,
+ });
+
+ expect(issues).to.eql([]);
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `"documents"."id" in (select "document_id" from "document_custom_property_values" where ("document_custom_property_values"."property_definition_id" = ? and "document_custom_property_values"."boolean_value" is not null))`,
+ params: ['cpd_1'],
+ });
+ });
+
+ test('works for any property type — text example', () => {
+ const { sqlQuery, issues } = handleHasCustomPropertyFilter({
+ definition: makeDefinition({ id: 'cpd_2', type: 'text', key: 'category' }),
+ db,
+ });
+
+ expect(issues).to.eql([]);
+ expect(getSqlString(sqlQuery)).to.eql({
+ sql: `"documents"."id" in (select "document_id" from "document_custom_property_values" where ("document_custom_property_values"."property_definition_id" = ? and "document_custom_property_values"."text_value" is not null))`,
+ params: ['cpd_2'],
+ });
+ });
+ });
+});
diff --git a/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.custom-properties.ts b/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.custom-properties.ts
new file mode 100644
index 00000000..bfdc2a3d
--- /dev/null
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.custom-properties.ts
@@ -0,0 +1,262 @@
+import type { FilterExpression } from '@papra/search-parser';
+import type { Database } from '../../../../app/database/database.types';
+import type { customPropertyDefinitionsTable } from '../../../../custom-properties/custom-properties.table';
+import type { QueryResult } from './query-builder.types';
+import { and, eq, inArray, isNotNull, or } from 'drizzle-orm';
+import { generatePropertyKey } from '../../../../custom-properties/custom-properties.repository.models';
+import { documentCustomPropertyValuesTable } from '../../../../custom-properties/custom-properties.table';
+import { customPropertySelectOptionsTable } from '../../../../custom-properties/options/custom-properties-options.table';
+import { isValidDate } from '../../../../shared/date';
+import { usersTable } from '../../../../users/users.table';
+import { documentsTable } from '../../../documents.table';
+import { createInvalidDateFormatQueryResult, createInvalidQueryResult, createUnsupportedOperatorQueryResult, getSqlOperator } from './query-builder.models';
+
+export type CustomPropertyDefinition = typeof customPropertyDefinitionsTable.$inferSelect;
+export type CustomPropertyDefinitionsByKey = Record<string, CustomPropertyDefinition>;
+
+const BOOLEAN_TRUE_VALUES = new Set(['true', 'yes', 'y', '1', 'on', 'enabled']);
+const BOOLEAN_FALSE_VALUES = new Set(['false', 'no', 'n', '0', 'off', 'disabled']);
+
+function parseBooleanValue({ value }: { value: string }): boolean | null {
+ const lower = value.toLowerCase();
+
+ if (BOOLEAN_TRUE_VALUES.has(lower)) {
+ return true;
+ }
+
+ if (BOOLEAN_FALSE_VALUES.has(lower)) {
+ return false;
+ }
+
+ return null;
+}
+
+function handleBooleanPropertyFilter({ expression, definition, db }: { expression: FilterExpression; definition: CustomPropertyDefinition; db: Database }): QueryResult {
+ const { value, operator, field } = expression;
+
+ if (operator !== '=') {
+ return createUnsupportedOperatorQueryResult({ operator, field });
+ }
+
+ const parsed = parseBooleanValue({ value });
+
+ if (parsed === null) {
+ return createInvalidQueryResult({
+ message: `Invalid boolean value "${value}" for ${field} filter. Expected one of: true, yes, y, 1, on, enabled, false, no, n, 0, off, disabled`,
+ code: 'INVALID_BOOLEAN_VALUE',
+ });
+ }
+
+ return {
+ sqlQuery: inArray(
+ documentsTable.id,
+ db.select({ id: documentCustomPropertyValuesTable.documentId })
+ .from(documentCustomPropertyValuesTable)
+ .where(and(
+ eq(documentCustomPropertyValuesTable.propertyDefinitionId, definition.id),
+ eq(documentCustomPropertyValuesTable.booleanValue, parsed),
+ )),
+ ),
+ issues: [],
+ };
+}
+
+function handleTextPropertyFilter({ expression, definition, db }: { expression: FilterExpression; definition: CustomPropertyDefinition; db: Database }): QueryResult {
+ const { value, operator, field } = expression;
+
+ if (operator !== '=') {
+ return createUnsupportedOperatorQueryResult({ operator, field });
+ }
+
+ return {
+ sqlQuery: inArray(
+ documentsTable.id,
+ db.select({ id: documentCustomPropertyValuesTable.documentId })
+ .from(documentCustomPropertyValuesTable)
+ .where(and(
+ eq(documentCustomPropertyValuesTable.propertyDefinitionId, definition.id),
+ eq(documentCustomPropertyValuesTable.textValue, value),
+ )),
+ ),
+ issues: [],
+ };
+}
+
+function handleNumberPropertyFilter({ expression, definition, db }: { expression: FilterExpression; definition: CustomPropertyDefinition; db: Database }): QueryResult {
+ const { value, field } = expression;
+
+ const parsed = Number(value);
+
+ if (Number.isNaN(parsed)) {
+ return createInvalidQueryResult({
+ message: `Invalid number value "${value}" for ${field} filter. Expected a numeric value.`,
+ code: 'INVALID_NUMBER_VALUE',
+ });
+ }
+
+ const sqlOperator = getSqlOperator({ operator: expression.operator });
+
+ return {
+ sqlQuery: inArray(
+ documentsTable.id,
+ db.select({ id: documentCustomPropertyValuesTable.documentId })
+ .from(documentCustomPropertyValuesTable)
+ .where(and(
+ eq(documentCustomPropertyValuesTable.propertyDefinitionId, definition.id),
+ sqlOperator(documentCustomPropertyValuesTable.numberValue, parsed),
+ )),
+ ),
+ issues: [],
+ };
+}
+
+function getDateValue({ value, now }: { value: string; now: Date }): Date {
+ if (value === 'now') {
+ return now;
+ }
+
+ return new Date(value);
+}
+
+function handleDatePropertyFilter({ expression, definition, db, now }: { expression: FilterExpression; definition: CustomPropertyDefinition; db: Database; now: Date }): QueryResult {
+ const { value, field } = expression;
+
+ const dateValue = getDateValue({ value, now });
+
+ if (!isValidDate(dateValue)) {
+ return createInvalidDateFormatQueryResult({ field, value });
+ }
+
+ const sqlOperator = getSqlOperator({ operator: expression.operator });
+
+ return {
+ sqlQuery: inArray(
+ documentsTable.id,
+ db.select({ id: documentCustomPropertyValuesTable.documentId })
+ .from(documentCustomPropertyValuesTable)
+ .where(and(
+ eq(documentCustomPropertyValuesTable.propertyDefinitionId, definition.id),
+ sqlOperator(documentCustomPropertyValuesTable.dateValue, dateValue),
+ )),
+ ),
+ issues: [],
+ };
+}
+
+function handleSelectPropertyFilter({ expression, definition, db }: { expression: FilterExpression; definition: CustomPropertyDefinition; db: Database }): QueryResult {
+ const { value, operator, field } = expression;
+
+ if (operator !== '=') {
+ return createUnsupportedOperatorQueryResult({ operator, field });
+ }
+
+ return {
+ sqlQuery: inArray(
+ documentsTable.id,
+ db.select({ id: documentCustomPropertyValuesTable.documentId })
+ .from(documentCustomPropertyValuesTable)
+ .innerJoin(
+ customPropertySelectOptionsTable,
+ eq(documentCustomPropertyValuesTable.selectOptionId, customPropertySelectOptionsTable.id),
+ )
+ .where(and(
+ eq(documentCustomPropertyValuesTable.propertyDefinitionId, definition.id),
+ eq(customPropertySelectOptionsTable.key, generatePropertyKey({ name: value })),
+ )),
+ ),
+ issues: [],
+ };
+}
+
+function handleUserRelationPropertyFilter({ expression, definition, db }: { expression: FilterExpression; definition: CustomPropertyDefinition; db: Database }): QueryResult {
+ const { value, operator, field } = expression;
+
+ if (operator !== '=') {
+ return createUnsupportedOperatorQueryResult({ operator, field });
+ }
+
+ return {
+ sqlQuery: inArray(
+ documentsTable.id,
+ db.select({ id: documentCustomPropertyValuesTable.documentId })
+ .from(documentCustomPropertyValuesTable)
+ .leftJoin(usersTable, eq(documentCustomPropertyValuesTable.userId, usersTable.id))
+ .where(and(
+ eq(documentCustomPropertyValuesTable.propertyDefinitionId, definition.id),
+ or(
+ eq(documentCustomPropertyValuesTable.userId, value),
+ eq(usersTable.email, value),
+ eq(usersTable.name, value),
+ ),
+ )),
+ ),
+ issues: [],
+ };
+}
+
+function handleDocumentRelationPropertyFilter({ expression, definition, db }: { expression: FilterExpression; definition: CustomPropertyDefinition; db: Database }): QueryResult {
+ const { value, operator, field } = expression;
+
+ if (operator !== '=') {
+ return createUnsupportedOperatorQueryResult({ operator, field });
+ }
+
+ return {
+ sqlQuery: inArray(
+ documentsTable.id,
+ db.select({ id: documentCustomPropertyValuesTable.documentId })
+ .from(documentCustomPropertyValuesTable)
+ .where(and(
+ eq(documentCustomPropertyValuesTable.propertyDefinitionId, definition.id),
+ eq(documentCustomPropertyValuesTable.relatedDocumentId, value),
+ )),
+ ),
+ issues: [],
+ };
+}
+
+export function handleHasCustomPropertyFilter({ definition, db }: { definition: CustomPropertyDefinition; db: Database }): QueryResult {
+ const fieldByTypes = {
+ boolean: documentCustomPropertyValuesTable.booleanValue,
+ text: documentCustomPropertyValuesTable.textValue,
+ number: documentCustomPropertyValuesTable.numberValue,
+ date: documentCustomPropertyValuesTable.dateValue,
+ select: documentCustomPropertyValuesTable.selectOptionId,
+ multi_select: documentCustomPropertyValuesTable.selectOptionId,
+ user_relation: documentCustomPropertyValuesTable.userId,
+ document_relation: documentCustomPropertyValuesTable.relatedDocumentId,
+ };
+
+ const field = fieldByTypes[definition.type];
+
+ return {
+ sqlQuery: inArray(
+ documentsTable.id,
+ db.select({ id: documentCustomPropertyValuesTable.documentId })
+ .from(documentCustomPropertyValuesTable)
+ .where(and(
+ eq(documentCustomPropertyValuesTable.propertyDefinitionId, definition.id),
+ isNotNull(field),
+ )),
+ ),
+ issues: [],
+ };
+}
+
+export function handleCustomPropertyFilter({ expression, definition, db, now }: { expression: FilterExpression; definition: CustomPropertyDefinition; db: Database; now: Date }): QueryResult {
+ switch (definition.type) {
+ case 'boolean': return handleBooleanPropertyFilter({ expression, definition, db });
+ case 'text': return handleTextPropertyFilter({ expression, definition, db });
+ case 'number': return handleNumberPropertyFilter({ expression, definition, db });
+ case 'date': return handleDatePropertyFilter({ expression, definition, db, now });
+ case 'select': return handleSelectPropertyFilter({ expression, definition, db });
+ case 'multi_select': return handleSelectPropertyFilter({ expression, definition, db });
+ case 'user_relation': return handleUserRelationPropertyFilter({ expression, definition, db });
+ case 'document_relation': return handleDocumentRelationPropertyFilter({ expression, definition, db });
+ default:
+ return createInvalidQueryResult({
+ message: `Unsupported custom property type for filter`,
+ code: 'UNSUPPORTED_CUSTOM_PROPERTY_TYPE',
+ });
+ }
+}
diff --git a/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.ts b/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.ts
index a56c48dd..f4372aee 100644
--- a/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.ts
+++ b/apps/papra-server/src/modules/documents/document-search/database-fts5/query-builder/query-builder.ts
@@ -1,5 +1,6 @@
import type { AndExpression, Expression, FilterExpression, NotExpression, OrExpression, TextExpression } from '@papra/search-parser';
import type { Database } from '../../../../app/database/database.types';
+import type { CustomPropertyDefinitionsByKey } from './query-builder.custom-properties';
import type { QueryResult } from './query-builder.types';
import { and, eq, inArray, isNotNull, not, or, sql } from 'drizzle-orm';
import { isValidDate } from '../../../../shared/date';
@@ -8,6 +9,8 @@ import { normalizeTagName } from '../../../../tags/tags.repository.models';
import { documentsTagsTable, tagsTable } from '../../../../tags/tags.table';
import { documentsTable } from '../../../documents.table';
import { documentsFtsTable } from '../database-fts5.tables';
+import { handleCustomPropertyFilter, handleHasCustomPropertyFilter } from './query-builder.custom-properties';
+import { getCustomPropertyDefinition } from './query-builder.custom-properties.models';
import {
createInvalidDateFormatQueryResult,
createInvalidQueryResult,
@@ -91,8 +94,8 @@ export function handleTextExpression({ expression, organizationId, db }: { expre
};
}
-export function handleAndExpression({ expression, organizationId, db, now }: { expression: AndExpression; organizationId: string; db: Database; now: Date }): QueryResult {
- const subQueries = expression.operands.map(expression => buildQueryFromExpression({ expression, organizationId, db, now }));
+export function handleAndExpression({ expression, organizationId, db, now, customPropertyDefinitionsByKey = {} }: { expression: AndExpression; organizationId: string; db: Database; now: Date; customPropertyDefinitionsByKey?: CustomPropertyDefinitionsByKey }): QueryResult {
+ const subQueries = expression.operands.map(expression => buildQueryFromExpression({ expression, organizationId, db, now, customPropertyDefinitionsByKey }));
return {
sqlQuery: and(...subQueries.map(sq => sq.sqlQuery)),
@@ -100,8 +103,8 @@ export function handleAndExpression({ expression, organizationId, db, now }: { e
};
}
-export function handleOrExpression({ expression, organizationId, db, now }: { expression: OrExpression; organizationId: string; db: Database; now: Date }): QueryResult {
- const subQueries = expression.operands.map(expression => buildQueryFromExpression({ expression, organizationId, db, now }));
+export function handleOrExpression({ expression, organizationId, db, now, customPropertyDefinitionsByKey = {} }: { expression: OrExpression; organizationId: string; db: Database; now: Date; customPropertyDefinitionsByKey?: CustomPropertyDefinitionsByKey }): QueryResult {
+ const subQueries = expression.operands.map(expression => buildQueryFromExpression({ expression, organizationId, db, now, customPropertyDefinitionsByKey }));
return {
sqlQuery: or(...subQueries.map(sq => sq.sqlQuery)),
@@ -109,8 +112,8 @@ export function handleOrExpression({ expression, organizationId, db, now }: { ex
};
}
-export function handleNotExpression({ expression, organizationId, db, now }: { expression: NotExpression; organizationId: string; db: Database; now: Date }): QueryResult {
- const subQuery = buildQueryFromExpression({ expression: expression.operand, organizationId, db, now });
+export function handleNotExpression({ expression, organizationId, db, now, customPropertyDefinitionsByKey = {} }: { expression: NotExpression; organizationId: string; db: Database; now: Date; customPropertyDefinitionsByKey?: CustomPropertyDefinitionsByKey }): QueryResult {
+ const subQuery = buildQueryFromExpression({ expression: expression.operand, organizationId, db, now, customPropertyDefinitionsByKey });
if (!subQuery.sqlQuery) {
// Should not happen, but just for type safety
@@ -242,14 +245,14 @@ export function handleInvalidHasValue({ expression }: { expression: FilterExpres
});
}
-export function buildQueryFromExpression({ expression, organizationId, db, now }: { expression: Expression; organizationId: string; db: Database; now: Date }): QueryResult {
+export function buildQueryFromExpression({ expression, organizationId, db, now, customPropertyDefinitionsByKey = {} }: { expression: Expression; organizationId: string; db: Database; now: Date; customPropertyDefinitionsByKey?: CustomPropertyDefinitionsByKey }): QueryResult {
// I usually prefer a LUT, but for type narrowing, switch is more convenient and avoids casting
switch (expression.type) {
case 'empty': return handleEmptyExpression();
case 'text': return handleTextExpression({ expression, organizationId, db });
- case 'and': return handleAndExpression({ expression, organizationId, db, now });
- case 'or': return handleOrExpression({ expression, organizationId, db, now });
- case 'not': return handleNotExpression({ expression, organizationId, db, now });
+ case 'and': return handleAndExpression({ expression, organizationId, db, now, customPropertyDefinitionsByKey });
+ case 'or': return handleOrExpression({ expression, organizationId, db, now, customPropertyDefinitionsByKey });
+ case 'not': return handleNotExpression({ expression, organizationId, db, now, customPropertyDefinitionsByKey });
case 'filter':
switch (expression.field) {
case 'tag': return handleTagFilter({ expression, organizationId, db });
@@ -261,9 +264,25 @@ export function buildQueryFromExpression({ expression, organizationId, db, now }
switch (expression.value) {
case 'tags': return handleHasTagsFilter({ expression, organizationId, db });
case 'date': return handleDocumentHasDateFilter({ expression, organizationId, db });
- default: return handleInvalidHasValue({ expression });
+ default: {
+ const hasDefinition = getCustomPropertyDefinition({ name: expression.value, customPropertyDefinitionsByKey });
+
+ if (hasDefinition) {
+ return handleHasCustomPropertyFilter({ definition: hasDefinition, db });
+ }
+
+ return handleInvalidHasValue({ expression });
+ }
}
- default: return handleUnsupportedExpression();
+ default: {
+ const definition = getCustomPropertyDefinition({ name: expression.field, customPropertyDefinitionsByKey });
+
+ if (definition) {
+ return handleCustomPropertyFilter({ expression, definition, db, now });
+ }
+
+ return handleUnsupportedExpression();
+ }
}
default: return handleUnsupportedExpression();
}