Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(storage): support organization names in patterns (#1529)

Corentin Thomasset1c993e431058
diff --git a/.changeset/fast-singers-hope.md b/.changeset/fast-singers-hope.md
new file mode 100644
index 00000000..5ea8cbe2
--- /dev/null
+++ b/.changeset/fast-singers-hope.md
@@ -0,0 +1,5 @@
+---
+'@papra/app': patch
+---
+
+Add support for `{{organization.name}}` in document storage key patterns to organize files into folders named after your organizations.
diff --git a/apps/docs/src/content/docs/03-guides/09-storage-key-patterns.mdx b/apps/docs/src/content/docs/03-guides/09-storage-key-patterns.mdx
index fc77aa6e..fbbfdf6c 100644
--- a/apps/docs/src/content/docs/03-guides/09-storage-key-patterns.mdx
+++ b/apps/docs/src/content/docs/03-guides/09-storage-key-patterns.mdx
@@ -63,7 +63,7 @@ DOCUMENT_STORAGE_KEY_PATTERN={{organization.id}}/{{document.name}}
DOCUMENT_STORAGE_KEY_SYNC_ENABLED=true
```
-The configuration option is `documentsStorage.pattern.isStorageKeySyncEnabled` and defaults to `false`. When enabled, qualifying document updates trigger pattern re-evaluation using the document's current metadata. Currently, synchronization is triggered by document name changes. Papra copies the stored file to the new key, updates its database reference, and removes the old file. Encrypted files retain their encryption metadata.
+The configuration option is `documentsStorage.pattern.isStorageKeySyncEnabled` and defaults to `false`. When enabled, qualifying document updates trigger pattern re-evaluation using the document's current metadata. Currently, synchronization is triggered by document name or document date changes. Papra copies the stored file to the new key, updates its database reference, and removes the old file. Encrypted files retain their encryption metadata.
Enabling synchronization does not immediately move existing files: it applies to subsequent updates that trigger synchronization.
@@ -112,6 +112,7 @@ Multiple transformers can be chained, and each transformer receives the output o
| `document.date` | The document date in ISO 8601 format, or `no-date` when unset | `2025-06-15T00:00:00.000Z` |
| `document.createdAt` | The document's creation timestamp in ISO 8601 format | `2025-06-15T14:30:00.000Z` |
| `organization.id` | The organization identifier | `org_123456789012345678901234` |
+| `organization.name` | The current organization name (sanitized for safe filesystem use) | `Acme Finance` |
| `currentDate` | The current date and time in ISO 8601 format | `2025-06-15T14:30:00.000Z` |
| `currentDate.yyyy` | Current year (4 digits) | `2025` |
| `currentDate.MM` | Current month (2 digits, zero-padded) | `06` |
@@ -130,9 +131,21 @@ Example:
```
<Aside type="note">
-The `document.name` expression automatically sanitizes the file name by replacing unsafe filesystem characters with underscores (`_`).
+The `document.name` and `organization.name` expressions automatically sanitize names by replacing unsafe filesystem characters with underscores (`_`).
</Aside>
+### Organization Names and Renames
+
+Use `organization.name` for readable organization folders. Organization names are not unique, so include `organization.id` to keep folders distinct:
+
+```bash
+DOCUMENT_STORAGE_KEY_PATTERN={{organization.id}}-{{organization.name}}/{{document.name}}
+```
+
+Renaming an organization does not move its existing documents, even when storage-key synchronization is enabled. Their persisted keys remain usable. New uploads use the current organization name. With synchronization enabled, a later document name or document date change re-evaluates the entire pattern and uses the current organization name too. An explicit [storage migration](/guides/migrate-document-storage/) also uses the current name.
+
+Papra looks up the organization name only when the pattern references `organization.name`.
+
## Available Transformers
Both `document.date` and `document.createdAt` support the `formatDate` transformer:
diff --git a/apps/papra-server/src/modules/documents/document-storage.usecases.test.ts b/apps/papra-server/src/modules/documents/document-storage.usecases.test.ts
index 0f36af7d..91d4c739 100644
--- a/apps/papra-server/src/modules/documents/document-storage.usecases.test.ts
+++ b/apps/papra-server/src/modules/documents/document-storage.usecases.test.ts
@@ -3,6 +3,7 @@ import { Buffer } from 'node:buffer';
import { createNoopLogger } from '@crowlog/logger';
import { describe, expect, test, vi } from 'vitest';
import { createInMemoryDatabase } from '../app/database/database.test-utils';
+import { createOrganizationsRepository } from '../organizations/organizations.repository';
import { createTestClock } from '../shared/clock/clock.test-utils';
import {
collectReadableStreamToString,
@@ -10,8 +11,12 @@ import {
} from '../shared/streams/readable-stream';
import { inMemoryStorageDriverFactory } from '../storage/drivers/memory/memory.storage-driver';
import { wrapWithEncryptionLayer } from '../storage/encryption/storage-encryption.services';
-import { buildSyncDocumentStorageKey, createDocumentStorageKey } from './document-storage.usecases';
+import {
+ buildSyncDocumentStorageKey,
+ buildCreateDocumentStorageKey,
+} from './document-storage.usecases';
import { createDocumentsRepository } from './documents.repository';
+import { buildResolveStoragePatternContext } from './storage-patterns/storage-pattern.usecases';
const baseStoragePatternConfig = {
isStorageKeySyncEnabled: true,
@@ -64,6 +69,9 @@ async function setupSync({ sourceStorageKey = 'old.pdf', isEncryptionEnabled = f
documentsRepository,
documentsStorageService,
storagePatternConfig: baseStoragePatternConfig,
+ resolveStoragePatternContext: buildResolveStoragePatternContext({
+ organizationsRepository: createOrganizationsRepository({ db }),
+ }),
logger: createNoopLogger(),
};
return {
@@ -169,12 +177,17 @@ describe('syncDocumentStorageKey', () => {
test('is opt-in and does not synchronize legacy keys', async () => {
const { args, dependencies, keys } = await setupSync();
+ const resolveStoragePatternContext = async () => {
+ throw new Error('Unexpected context resolution');
+ };
await buildSyncDocumentStorageKey({
...dependencies,
+ resolveStoragePatternContext,
storagePatternConfig: { ...baseStoragePatternConfig, isStorageKeySyncEnabled: false },
})(args);
await buildSyncDocumentStorageKey({
...dependencies,
+ resolveStoragePatternContext,
storagePatternConfig: {
...baseStoragePatternConfig,
useLegacyStorageKeyDefinitionSystem: true,
@@ -436,34 +449,45 @@ describe('syncDocumentStorageKey', () => {
describe('document-storage usecases', () => {
describe('createDocumentStorageKey', () => {
+ const resolveStoragePatternContext = buildResolveStoragePatternContext({
+ organizationsRepository: {
+ getOrganizationById: async () => {
+ throw new Error('Unexpected organization lookup');
+ },
+ },
+ });
+
test('uses the supplied document dates when generating a key for an existing document', async () => {
await expect(
- createDocumentStorageKey({
- ...documentContext,
- documentDate: new Date('2024-03-12T00:00:00.000Z'),
+ buildCreateDocumentStorageKey({
+ resolveStoragePatternContext,
storagePatternConfig: {
...baseStoragePatternConfig,
storageKeyPattern:
'{{document.date | formatDate}}/{{document.createdAt | formatDate}}/{{document.name}}',
},
documentsStorageService: { fileExists: async () => false },
+ })({
+ ...documentContext,
+ documentDate: new Date('2024-03-12T00:00:00.000Z'),
}),
).resolves.toEqual({ storageKey: '2024-03-12/2025-12-01/invoice.pdf' });
});
- test('uses the legacy document key without checking for collisions', async () => {
+ test('uses the legacy document key without checking for collisions or loading organization names', async () => {
const fileExists = vi.fn(async () => false);
await expect(
- createDocumentStorageKey({
- ...documentContext,
+ buildCreateDocumentStorageKey({
+ resolveStoragePatternContext,
storagePatternConfig: {
...baseStoragePatternConfig,
useLegacyStorageKeyDefinitionSystem: true,
+ storageKeyPattern: '{{organization.name}}/{{document.name}}',
},
documentsStorageService: { fileExists },
logger: createNoopLogger(),
- }),
+ })(documentContext),
).resolves.toEqual({ storageKey: 'org_1/originals/doc_1.pdf' });
expect(fileExists).not.toHaveBeenCalled();
});
@@ -474,12 +498,12 @@ describe('document-storage usecases', () => {
);
await expect(
- createDocumentStorageKey({
- ...documentContext,
+ buildCreateDocumentStorageKey({
+ resolveStoragePatternContext,
storagePatternConfig: baseStoragePatternConfig,
documentsStorageService: { fileExists },
logger: createNoopLogger(),
- }),
+ })(documentContext),
).resolves.toEqual({ storageKey: 'org_1/invoice_1.pdf' });
expect(fileExists).toHaveBeenNthCalledWith(1, { storageKey: 'org_1/invoice.pdf' });
expect(fileExists).toHaveBeenNthCalledWith(2, { storageKey: 'org_1/invoice_1.pdf' });
@@ -491,15 +515,15 @@ describe('document-storage usecases', () => {
.mockResolvedValueOnce(true)
.mockResolvedValueOnce(false);
- const result = await createDocumentStorageKey({
- ...documentContext,
+ const result = await buildCreateDocumentStorageKey({
+ resolveStoragePatternContext,
storagePatternConfig: {
...baseStoragePatternConfig,
maxIncrementalSuffixAttempts: 0,
},
documentsStorageService: { fileExists },
logger: createNoopLogger(),
- });
+ })(documentContext);
expect(result.storageKey).toMatch(/^org_1\/invoice_[A-Za-z0-9]{8}\.pdf$/);
expect(fileExists).toHaveBeenCalledTimes(2);
diff --git a/apps/papra-server/src/modules/documents/document-storage.usecases.ts b/apps/papra-server/src/modules/documents/document-storage.usecases.ts
index 08110a68..69047572 100644
--- a/apps/papra-server/src/modules/documents/document-storage.usecases.ts
+++ b/apps/papra-server/src/modules/documents/document-storage.usecases.ts
@@ -2,7 +2,11 @@ import type { Clock } from '../shared/clock/clock.types';
import type { Logger } from '../shared/logger/logger';
import type { StorageService } from '../storage/drivers/drivers.models';
import type { DocumentsRepository } from './documents.repository';
-import type { StoragePatternConfig } from './storage-patterns/storage-pattern.types';
+import type {
+ ResolveStoragePatternContext,
+ StoragePatternConfig,
+ StoragePatternInterpolationContext,
+} from './storage-patterns/storage-pattern.types';
import { systemClock } from '../shared/clock/clock';
import { createLogger } from '../shared/logger/logger';
import { ensureStorageKeyIsAvailable } from '../storage/storage.usecases';
@@ -19,12 +23,14 @@ export function buildSyncDocumentStorageKey({
storagePatternConfig,
documentsRepository,
documentsStorageService,
+ resolveStoragePatternContext,
logger = createLogger({ namespace: 'sync-document-storage-key' }),
clock = systemClock,
}: {
storagePatternConfig: StoragePatternConfig;
documentsRepository: Pick<DocumentsRepository, 'getDocumentById' | 'updateDocumentStorageKey'>;
documentsStorageService: Pick<StorageService, 'fileExists' | 'copyFile' | 'deleteFile'>;
+ resolveStoragePatternContext: ResolveStoragePatternContext;
logger?: Logger;
clock?: Clock;
}): SyncDocumentStorageKey {
@@ -50,7 +56,7 @@ export function buildSyncDocumentStorageKey({
}
const sourceStorageKey = document.originalStorageKey;
- const { storageKey: initialStorageKey } = buildStorageKey({
+ const context = await resolveStoragePatternContext({
storageKeyPattern: storagePatternConfig.storageKeyPattern,
documentId,
organizationId,
@@ -59,6 +65,10 @@ export function buildSyncDocumentStorageKey({
documentCreatedAt: document.createdAt,
now: new Date(clock.now().epochMilliseconds),
});
+ const { storageKey: initialStorageKey } = buildStorageKey({
+ storageKeyPattern: storagePatternConfig.storageKeyPattern,
+ ...context,
+ });
if (sourceStorageKey === initialStorageKey) {
return;
@@ -105,27 +115,21 @@ export function buildSyncDocumentStorageKey({
};
}
-export async function createDocumentStorageKey({
+export type CreateDocumentStorageKey = (
+ args: Omit<StoragePatternInterpolationContext, 'organizationName' | 'now'> & { now?: Date },
+) => Promise<{ storageKey: string }>;
+
+export function buildCreateDocumentStorageKey({
storagePatternConfig,
- documentId,
- documentName,
- documentDate,
- documentCreatedAt,
- organizationId,
+ resolveStoragePatternContext,
documentsStorageService,
logger,
- now = new Date(),
}: {
storagePatternConfig: StoragePatternConfig;
- documentId: string;
- documentName: string;
- documentDate: Date | null;
- documentCreatedAt: Date;
- organizationId: string;
+ resolveStoragePatternContext: ResolveStoragePatternContext;
documentsStorageService: Pick<StorageService, 'fileExists'>;
logger?: Logger;
- now?: Date;
-}) {
+}): CreateDocumentStorageKey {
const {
useLegacyStorageKeyDefinitionSystem,
storageKeyPattern,
@@ -133,31 +137,30 @@ export async function createDocumentStorageKey({
maxIncrementalSuffixAttempts,
} = storagePatternConfig;
- if (useLegacyStorageKeyDefinitionSystem) {
- const { originalDocumentStorageKey } = buildOriginalDocumentKey({
- documentId,
- fileName: documentName,
- organizationId,
- });
+ return async ({ now = new Date(), ...documentContext }) => {
+ if (useLegacyStorageKeyDefinitionSystem) {
+ const { originalDocumentStorageKey } = buildOriginalDocumentKey({
+ documentId: documentContext.documentId,
+ fileName: documentContext.documentName,
+ organizationId: documentContext.organizationId,
+ });
- return { storageKey: originalDocumentStorageKey };
- }
+ return { storageKey: originalDocumentStorageKey };
+ }
- const { storageKey: initialStorageKey } = buildStorageKey({
- storageKeyPattern,
- documentId,
- documentName,
- documentDate,
- documentCreatedAt,
- organizationId,
- now,
- });
-
- return ensureStorageKeyIsAvailable({
- initialStorageKey,
- maxIncrementalSuffixAttempts,
- enableRandomSuffixFallback,
- storageService: documentsStorageService,
- logger,
- });
+ const context = await resolveStoragePatternContext({
+ storageKeyPattern,
+ ...documentContext,
+ now,
+ });
+ const { storageKey: initialStorageKey } = buildStorageKey({ storageKeyPattern, ...context });
+
+ return ensureStorageKeyIsAvailable({
+ initialStorageKey,
+ maxIncrementalSuffixAttempts,
+ enableRandomSuffixFallback,
+ storageService: documentsStorageService,
+ logger,
+ });
+ };
}
diff --git a/apps/papra-server/src/modules/documents/documents.usecases.test.ts b/apps/papra-server/src/modules/documents/documents.usecases.test.ts
index 16a212ce..f7233f97 100644
--- a/apps/papra-server/src/modules/documents/documents.usecases.test.ts
+++ b/apps/papra-server/src/modules/documents/documents.usecases.test.ts
@@ -7,6 +7,7 @@ import { overrideConfig } from '../config/config.test-utils';
import { createCustomPropertiesRepository } from '../custom-properties/custom-properties.repository';
import { ORGANIZATION_ROLES } from '../organizations/organizations.constants';
import { createOrganizationDocumentStorageLimitReachedError } from '../organizations/organizations.errors';
+import { createOrganizationsRepository } from '../organizations/organizations.repository';
import { createDeterministicIdGenerator } from '../shared/random/ids';
import {
collectReadableStreamToString,
@@ -35,6 +36,62 @@ import { createInMemoryStorageService } from '../storage/storage.test-utils';
describe('documents usecases', () => {
describe('createDocument', () => {
+ test('new uploads use the current organization name while older uploads retain their keys', async () => {
+ const { db } = await createInMemoryDatabase({
+ organizations: [{ id: 'organization-1', name: 'Acme/Finance' }],
+ });
+ const documentsStorageService = createInMemoryStorageService();
+ const createDocument = createDocumentCreationUsecase({
+ db,
+ config: overrideConfig({
+ organizationPlans: { isFreePlanUnlimited: true },
+ documentsStorage: {
+ pattern: {
+ useLegacyStorageKeyDefinitionSystem: false,
+ storageKeyPattern: '{{organization.name | lowercase}}/{{document.name}}',
+ },
+ },
+ }),
+ documentsStorageService,
+ taskServices: createInMemoryTaskServices(),
+ eventServices: createTestEventServices(),
+ });
+
+ const { document: firstDocument } = await createDocument({
+ fileStream: createReadableStream({ content: 'First upload' }),
+ fileName: 'file.txt',
+ mimeType: 'text/plain',
+ organizationId: 'organization-1',
+ });
+
+ await createOrganizationsRepository({ db }).updateOrganization({
+ organizationId: 'organization-1',
+ organization: { name: 'New Organization' },
+ });
+
+ const { document: secondDocument } = await createDocument({
+ fileStream: createReadableStream({ content: 'Second upload' }),
+ fileName: 'file.txt',
+ mimeType: 'text/plain',
+ organizationId: 'organization-1',
+ });
+
+ expect(firstDocument.originalStorageKey).toEqual('acme_finance/file.txt');
+ expect(secondDocument.originalStorageKey).toEqual('new organization/file.txt');
+ expect(
+ (
+ await createDocumentsRepository({ db }).getDocumentById({
+ documentId: firstDocument.id,
+ organizationId: 'organization-1',
+ })
+ ).document?.originalStorageKey,
+ ).toEqual('acme_finance/file.txt');
+ expect([...documentsStorageService._getStorage().keys()].sort()).toEqual([
+ 'acme_finance/file.txt',
+ 'new organization/file.txt',
+ ]);
+ });
+
test('a new document key uses its persisted creation timestamp and the missing-date fallback', async () => {
const { db } = await createInMemoryDatabase({
organizations: [{ id: 'organization-1', name: 'Organization 1' }],
diff --git a/apps/papra-server/src/modules/documents/documents.usecases.ts b/apps/papra-server/src/modules/documents/documents.usecases.ts
index b68072db..7434fa26 100644
--- a/apps/papra-server/src/modules/documents/documents.usecases.ts
+++ b/apps/papra-server/src/modules/documents/documents.usecases.ts
@@ -16,13 +16,14 @@ import type { DocumentsRepository } from './documents.repository';
import type { Document } from './documents.types';
import type { StorageService } from '../storage/storage.services';
import type { EncryptionContext } from '../storage/drivers/drivers.models';
-import type { StoragePatternConfig } from './storage-patterns/storage-pattern.types';
+import type { CreateDocumentStorageKey } from './document-storage.usecases';
import { PassThrough } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { safely } from '@corentinth/chisels';
import pLimit from 'p-limit';
import { buildCustomPropertiesArray } from '../custom-properties/custom-properties.models';
import { createOrganizationDocumentStorageLimitReachedError } from '../organizations/organizations.errors';
+import { createOrganizationsRepository } from '../organizations/organizations.repository';
import { getOrganizationStorageLimits } from '../organizations/organizations.usecases';
import { createPlanEntitlementsRepository } from '../plan-entitlements/plan-entitlements.repository';
import { createPlanEntitlementDefinitionRegistry } from '../plan-entitlements/plan-entitlements.registry';
@@ -48,7 +49,8 @@ import {
generateDocumentId as generateDocumentIdImpl,
} from './documents.models';
import { createDocumentsRepository } from './documents.repository';
-import { createDocumentStorageKey } from './document-storage.usecases';
+import { buildCreateDocumentStorageKey } from './document-storage.usecases';
+import { buildResolveStoragePatternContext } from './storage-patterns/storage-pattern.usecases';
import type { ExtractDocumentTextUsecase } from './content-extraction/content-extraction.usecases';
type DocumentStorageContext = {
@@ -63,7 +65,7 @@ export async function createDocument({
organizationId,
ocrLanguages = [],
isContentExtractionEnabled = true,
- storagePatternConfig,
+ createDocumentStorageKey,
documentsRepository,
documentsStorageService,
generateDocumentId = generateDocumentIdImpl,
@@ -84,7 +86,7 @@ export async function createDocument({
organizationId: string;
ocrLanguages?: string[];
isContentExtractionEnabled?: boolean;
- storagePatternConfig: StoragePatternConfig;
+ createDocumentStorageKey: CreateDocumentStorageKey;
documentsRepository: DocumentsRepository;
documentsStorageService: StorageService;
generateDocumentId?: () => string;
@@ -115,8 +117,6 @@ export async function createDocument({
documentDate: null,
documentCreatedAt: createdAt,
organizationId,
- documentsStorageService,
- storagePatternConfig,
});
const { tap: hashStream, getHash } = createSha256HashTransformer();
@@ -238,7 +238,15 @@ export function createDocumentCreationUsecase({
initialDeps.taggingRulesRepository ?? createTaggingRulesRepository({ db }),
tagsRepository: initialDeps.tagsRepository ?? createTagsRepository({ db }),
- storagePatternConfig: initialDeps.storagePatternConfig ?? config.documentsStorage.pattern,
+ createDocumentStorageKey:
+ initialDeps.createDocumentStorageKey ??
+ buildCreateDocumentStorageKey({
+ storagePatternConfig: config.documentsStorage.pattern,
+ documentsStorageService,
+ resolveStoragePatternContext: buildResolveStoragePatternContext({
+ organizationsRepository: createOrganizationsRepository({ db }),
+ }),
+ }),
ocrLanguages: initialDeps.ocrLanguages ?? config.documents.ocrLanguages,
isContentExtractionEnabled:
initialDeps.isContentExtractionEnabled ?? config.documents.isContentExtractionEnabled,
diff --git a/apps/papra-server/src/modules/documents/events/storage-key.document-updated.test.ts b/apps/papra-server/src/modules/documents/events/storage-key.document-updated.test.ts
index 3deac3a4..4b4bcba6 100644
--- a/apps/papra-server/src/modules/documents/events/storage-key.document-updated.test.ts
+++ b/apps/papra-server/src/modules/documents/events/storage-key.document-updated.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, test } from 'vitest';
import { createInMemoryDatabase } from '../../app/database/database.test-utils';
import { createEventServices } from '../../app/events/events.services';
import { overrideConfig } from '../../config/config.test-utils';
+import { createOrganizationsRepository } from '../../organizations/organizations.repository';
import { nextTick } from '../../shared/async/defer.test-utils';
import { createReadableStream } from '../../shared/streams/readable-stream';
import { createInMemoryStorageService } from '../../storage/storage.test-utils';
@@ -10,7 +11,9 @@ import { createDocumentsRepository } from '../documents.repository';
import { updateDocument } from '../documents.usecases';
import { registerSyncDocumentStorageKeyHandler } from './storage-key.document-updated';
-async function setup() {
+async function setup({
+ storageKeyPattern = '{{document.date | formatDate}}/{{document.name}}',
+} = {}) {
const { db } = await createInMemoryDatabase({
organizations: [{ id: 'org_1', name: 'Organization' }],
});
@@ -41,7 +44,7 @@ async function setup() {
pattern: {
isStorageKeySyncEnabled: true,
useLegacyStorageKeyDefinitionSystem: false,
- storageKeyPattern: '{{document.date | formatDate}}/{{document.name}}',
+ storageKeyPattern,
},
},
}),
@@ -49,6 +52,11 @@ async function setup() {
const args = { documentId: document.id, organizationId: document.organizationId };
return {
+ renameOrganization: async (name: string) =>
+ createOrganizationsRepository({ db }).updateOrganization({
+ organizationId: document.organizationId,
+ organization: { name },
+ }),
update: async (changes: Parameters<typeof updateDocument>[0]['changes']) =>
updateDocument({ ...args, changes, documentsRepository, eventServices }),
getStorageKey: async () =>
@@ -58,6 +66,26 @@ async function setup() {
}
describe('storage-key document.updated handler', () => {
+ test('an organization rename keeps existing keys until a later qualifying document update', async () => {
+ const { update, getStorageKey, keys, renameOrganization } = await setup({
+ storageKeyPattern: '{{organization.name}}/{{document.name}}',
+ });
+
+ await update({ name: 'renamed.pdf' });
+ await expect.poll(getStorageKey).toEqual('Organization/renamed.pdf');
+ await expect.poll(keys).toEqual(['Organization/renamed.pdf']);
+
+ await renameOrganization('New/Organization');
+ await nextTick();
+
+ expect(await getStorageKey()).toEqual('Organization/renamed.pdf');
+ expect(keys()).toEqual(['Organization/renamed.pdf']);
+
+ await update({ documentDate: new Date('2024-03-12T00:00:00.000Z') });
+ await expect.poll(getStorageKey).toEqual('New_Organization/renamed.pdf');
+ await expect.poll(keys).toEqual(['New_Organization/renamed.pdf']);
+ });
+
test('setting, changing, and clearing a document date move the file to the matching key', async () => {
const { update, getStorageKey, keys } = await setup();
diff --git a/apps/papra-server/src/modules/documents/events/storage-key.document-updated.ts b/apps/papra-server/src/modules/documents/events/storage-key.document-updated.ts
index 7a2799c1..e186b7b8 100644
--- a/apps/papra-server/src/modules/documents/events/storage-key.document-updated.ts
+++ b/apps/papra-server/src/modules/documents/events/storage-key.document-updated.ts
@@ -2,8 +2,10 @@ import type { Database } from '../../app/database/database.types';
import type { EventServices } from '../../app/events/events.services';
import type { Config } from '../../config/config.types';
import type { StorageService } from '../../storage/storage.services';
+import { createOrganizationsRepository } from '../../organizations/organizations.repository';
import { buildSyncDocumentStorageKey } from '../document-storage.usecases';
import { createDocumentsRepository } from '../documents.repository';
+import { buildResolveStoragePatternContext } from '../storage-patterns/storage-pattern.usecases';
export function registerSyncDocumentStorageKeyHandler({
eventServices,
@@ -20,6 +22,9 @@ export function registerSyncDocumentStorageKeyHandler({
storagePatternConfig: config.documentsStorage.pattern,
documentsRepository: createDocumentsRepository({ db }),
documentsStorageService,
+ resolveStoragePatternContext: buildResolveStoragePatternContext({
+ organizationsRepository: createOrganizationsRepository({ db }),
+ }),
});
eventServices.onEvent({
diff --git a/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.definitions.ts b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.definitions.ts
index 92b8a47e..8047fac8 100644
--- a/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.definitions.ts
+++ b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.definitions.ts
@@ -17,6 +17,12 @@ export const expressionsDefinitions: Record<string, StoragePatternExpressionDefi
},
'document.createdAt': { resolve: (context) => context.documentCreatedAt.toISOString() },
'organization.id': { resolve: (context) => context.organizationId },
+ 'organization.name': {
+ resolve: (context) =>
+ context.organizationName === undefined
+ ? undefined
+ : ensureSafeFileName(context.organizationName),
+ },
'currentDate': { resolve: (context) => context.now.toISOString() },
'random': { resolve: () => generateRandomString({ length: 8 }) },
...['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'SSS'].reduce(
diff --git a/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.models.ts b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.models.ts
index 15655696..62e9fe98 100644
--- a/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.models.ts
+++ b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.models.ts
@@ -1,9 +1,36 @@
import type {
StoragePatternExpressionDefinition,
StoragePatternInterpolationContext,
+ StoragePatternPart,
} from './storage-pattern.types';
import { isNilOrEmptyString } from '../../shared/utils';
-import { expressionTransformers } from './storage-pattern.definitions';
+import { expressionsDefinitions, expressionTransformers } from './storage-pattern.definitions';
+
+export function parseStoragePattern({ storageKeyPattern }: { storageKeyPattern: string }) {
+ const parts: StoragePatternPart[] = [];
+ const expressionIds = new Set<string>();
+ let position = 0;
+
+ for (const match of storageKeyPattern.matchAll(/\{\{(.*?)\}\}(?!\})/g)) {
+ const [expressionId, ...transformerParts] = match[1]!.split('|').map((part) => part.trim());
+
+ if (isNilOrEmptyString(expressionId)) {
+ throw new Error('Expression cannot be empty');
+ }
+
+ if (!Object.hasOwn(expressionsDefinitions, expressionId)) {
+ throw new Error(`Unknown expression: ${expressionId}`);
+ }
+
+ parts.push(storageKeyPattern.slice(position, match.index), { expressionId, transformerParts });
+ expressionIds.add(expressionId);
+ position = match.index + match[0].length;
+ }
+
+ parts.push(storageKeyPattern.slice(position));
+
+ return { parts, expressionIds };
+}
export function evaluateStoragePatternExpression({
expressionDefinition,
diff --git a/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.types.ts b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.types.ts
index ac33ef7d..ceac2696 100644
--- a/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.types.ts
+++ b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.types.ts
@@ -6,9 +6,19 @@ export type StoragePatternInterpolationContext = {
documentDate: Date | null;
documentCreatedAt: Date;
organizationId: string;
+ organizationName?: string;
now: Date;
};
+export type StoragePatternPart = string | { expressionId: string; transformerParts: string[] };
+
+export type ResolveStoragePatternContext = (
+ args: { storageKeyPattern: string } & Omit<
+ StoragePatternInterpolationContext,
+ 'organizationName'
+ >,
+) => Promise<StoragePatternInterpolationContext>;
+
export type StoragePatternExpressionDefinition = {
resolve: (context: StoragePatternInterpolationContext) => string | null | undefined;
fallback?: string;
diff --git a/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.usecases.test.ts b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.usecases.test.ts
index 40186c54..73e3ff12 100644
--- a/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.usecases.test.ts
+++ b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.usecases.test.ts
@@ -1,17 +1,124 @@
import type { StoragePatternInterpolationContext } from './storage-pattern.types';
import { describe, expect, test } from 'vitest';
-import { buildStorageKey, isStoragePatternValid } from './storage-pattern.usecases';
+import { createInMemoryDatabase } from '../../app/database/database.test-utils';
+import { createOrganizationNotFoundError } from '../../organizations/organizations.errors';
+import { createOrganizationsRepository } from '../../organizations/organizations.repository';
+import {
+ buildResolveStoragePatternContext,
+ buildStorageKey,
+ isStoragePatternValid,
+} from './storage-pattern.usecases';
describe('storage-pattern usecases', () => {
+ const context: StoragePatternInterpolationContext = {
+ documentId: 'doc_012345678901234567890123',
+ documentName: 'My Document.pdf',
+ documentDate: new Date('2024-03-12T00:00:00.000Z'),
+ documentCreatedAt: new Date('2025-01-02T10:20:30.456Z'),
+ organizationId: 'org_012345678901234567890123',
+ now: new Date('2025-05-15T12:34:56.789Z'),
+ };
+
+ describe('resolveStoragePatternContext', () => {
+ test('patterns without an organization name expression need no organization lookup', async () => {
+ const resolveContext = buildResolveStoragePatternContext({
+ organizationsRepository: {
+ getOrganizationById: async () => {
+ throw new Error('Unexpected organization lookup');
+ },
+ },
+ });
+
+ const storageKeyPattern =
+ 'organization.name/{{organization.id}}/{{document.name | default "organization.name"}}';
+ const resolvedContext = await resolveContext({ storageKeyPattern, ...context });
+
+ expect(resolvedContext).toEqual(context);
+ expect(buildStorageKey({ storageKeyPattern, ...resolvedContext })).toEqual({
+ storageKey: 'organization.name/org_012345678901234567890123/My Document.pdf',
+ });
+ });
+
+ test('repeated organization name expressions share one lookup and use the requested organization', async () => {
+ const { db } = await createInMemoryDatabase({
+ organizations: [
+ { id: 'other-org', name: 'Other Organization' },
+ { id: context.organizationId, name: 'Acme/Finance' },
+ ],
+ });
+ const organizationsRepository = createOrganizationsRepository({ db });
+ const organizationIds: string[] = [];
+ const resolveContext = buildResolveStoragePatternContext({
+ organizationsRepository: {
+ getOrganizationById: async (args) => {
+ organizationIds.push(args.organizationId);
+ return organizationsRepository.getOrganizationById(args);
+ },
+ },
+ });
+ const storageKeyPattern =
+ '{{ organization.name | lowercase }}/{{organization.name}}/{{document.name}}';
+
+ const resolvedContext = await resolveContext({ storageKeyPattern, ...context });
+
+ expect(organizationIds).toEqual([context.organizationId]);
+ expect(buildStorageKey({ storageKeyPattern, ...resolvedContext })).toEqual({
+ storageKey: 'acme_finance/Acme_Finance/My Document.pdf',
+ });
+ });
+
+ test('a missing organization fails resolution even when the expression has a default', async () => {
+ const resolveContext = buildResolveStoragePatternContext({
+ organizationsRepository: {
+ getOrganizationById: async () => ({ organization: undefined }),
+ },
+ });
+
+ await expect(
+ resolveContext({
+ ...context,
+ storageKeyPattern: '{{organization.name | default "unknown"}}/{{document.name}}',
+ }),
+ ).rejects.toThrow(createOrganizationNotFoundError());
+ });
+
+ test('organization lookup failures are propagated', async () => {
+ const resolveContext = buildResolveStoragePatternContext({
+ organizationsRepository: {
+ getOrganizationById: async () => {
+ throw new Error('Database unavailable');
+ },
+ },
+ });
+
+ await expect(
+ resolveContext({
+ ...context,
+ storageKeyPattern: '{{organization.name}}/{{document.name}}',
+ }),
+ ).rejects.toThrow('Database unavailable');
+ });
+ });
+
describe('buildStorageKey', () => {
- const context: StoragePatternInterpolationContext = {
- documentId: 'doc_012345678901234567890123',
- documentName: 'My Document.pdf',
- documentDate: new Date('2024-03-12T00:00:00.000Z'),
- documentCreatedAt: new Date('2025-01-02T10:20:30.456Z'),
- organizationId: 'org_012345678901234567890123',
- now: new Date('2025-05-15T12:34:56.789Z'),
- };
+ test('organization names are sanitized as a single path component before transformers', () => {
+ expect(
+ buildStorageKey({
+ ...context,
+ organizationName: '../Acme\\Finance:Team',
+ storageKeyPattern: '{{organization.name | uppercase}}/{{document.name}}',
+ }),
+ ).toEqual({ storageKey: '_ACME_FINANCE_TEAM/My Document.pdf' });
+ });
+
+ test('a missing organization name cannot silently become an undefined path component', () => {
+ expect(() =>
+ buildStorageKey({
+ ...context,
+ storageKeyPattern: '{{organization.name}}/{{document.name}}',
+ }),
+ ).toThrow('Expression resolved to an empty value');
+ });
describe('given a storage key pattern, returns a function that can interpolate it with a context', () => {
const patterns = [
@@ -157,6 +264,14 @@ describe('storage-pattern usecases', () => {
});
describe('isStoragePatternValid', () => {
+ test('organization name expressions with transformers are valid without a database', () => {
+ expect(
+ isStoragePatternValid({
+ storageKeyPattern: '{{organization.name | lowercase}}/{{document.name}}',
+ }),
+ ).toEqual({ isValid: true });
+ });
+
test('document date and creation date expressions with formatting are valid', () => {
expect(
isStoragePatternValid({
diff --git a/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.usecases.ts b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.usecases.ts
index f3894098..c3618d26 100644
--- a/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.usecases.ts
+++ b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.usecases.ts
@@ -1,40 +1,56 @@
-import type { StoragePatternInterpolationContext } from './storage-pattern.types';
+import type { OrganizationsRepository } from '../../organizations/organizations.repository';
+import type {
+ ResolveStoragePatternContext,
+ StoragePatternInterpolationContext,
+} from './storage-pattern.types';
import { castError } from '@corentinth/chisels';
-import { isNil, isNilOrEmptyString } from '../../shared/utils';
+import { createOrganizationNotFoundError } from '../../organizations/organizations.errors';
import { DUMMY_DOCUMENT_ID, DUMMY_ORGANIZATION_ID } from './storage-pattern.constants';
import { expressionsDefinitions } from './storage-pattern.definitions';
-import { evaluateStoragePatternExpression } from './storage-pattern.models';
+import { evaluateStoragePatternExpression, parseStoragePattern } from './storage-pattern.models';
-export function buildStorageKey({
- storageKeyPattern,
- ...context
-}: { storageKeyPattern: string } & StoragePatternInterpolationContext) {
- const storageKey = storageKeyPattern.replace(/\{\{(.*?)\}\}(?!\})/g, (_match, rawExpression) => {
- if (isNil(rawExpression) || typeof rawExpression !== 'string') {
- throw new Error('Expression cannot be empty');
- }
-
- const [expression, ...transformerParts] = rawExpression.split('|').map((part) => part.trim());
+export function buildResolveStoragePatternContext({
+ organizationsRepository,
+}: {
+ organizationsRepository: Pick<OrganizationsRepository, 'getOrganizationById'>;
+}): ResolveStoragePatternContext {
+ return async ({ storageKeyPattern, ...context }) => {
+ const { expressionIds } = parseStoragePattern({ storageKeyPattern });
- if (isNilOrEmptyString(expression)) {
- throw new Error('Expression cannot be empty');
+ if (!expressionIds.has('organization.name')) {
+ return context;
}
- const expressionExists = expression in expressionsDefinitions;
+ const { organization } = await organizationsRepository.getOrganizationById({
+ organizationId: context.organizationId,
+ });
- if (!expressionExists) {
- throw new Error(`Unknown expression: ${expression}`);
+ if (!organization) {
+ throw createOrganizationNotFoundError();
}
- const expressionDefinition = expressionsDefinitions[expression];
+ return { ...context, organizationName: organization.name };
+ };
+}
- if (!expressionDefinition) {
- // This should never happen because of the check above, but for type safety
- throw new Error(`No definition found for expression: ${expression}`);
- }
+export function buildStorageKey({
+ storageKeyPattern,
+ ...context
+}: { storageKeyPattern: string } & StoragePatternInterpolationContext) {
+ const { parts } = parseStoragePattern({ storageKeyPattern });
+ const storageKey = parts
+ .map((part) => {
+ if (typeof part === 'string') {
+ return part;
+ }
- return evaluateStoragePatternExpression({ expressionDefinition, context, transformerParts });
- });
+ return evaluateStoragePatternExpression({
+ expressionDefinition: expressionsDefinitions[part.expressionId]!,
+ context,
+ transformerParts: part.transformerParts,
+ });
+ })
+ .join('');
return { storageKey };
}
@@ -61,6 +77,7 @@ export function isStoragePatternValid({
documentDate: new Date(),
documentCreatedAt: new Date(),
organizationId: DUMMY_ORGANIZATION_ID,
+ organizationName: 'My Organization',
now: new Date(),
});
diff --git a/apps/papra-server/src/scripts/migrate-document-storage.script.ts b/apps/papra-server/src/scripts/migrate-document-storage.script.ts
index 5f59fd6b..3156054b 100644
--- a/apps/papra-server/src/scripts/migrate-document-storage.script.ts
+++ b/apps/papra-server/src/scripts/migrate-document-storage.script.ts
@@ -9,7 +9,9 @@ import { count, eq } from 'drizzle-orm';
import { createIterator } from '../modules/app/database/database.usecases';
import { parseConfig } from '../modules/config/config';
import { documentsTable } from '../modules/documents/documents.table';
-import { createDocumentStorageKey } from '../modules/documents/document-storage.usecases';
+import { buildCreateDocumentStorageKey } from '../modules/documents/document-storage.usecases';
+import { buildResolveStoragePatternContext } from '../modules/documents/storage-patterns/storage-pattern.usecases';
+import { createOrganizationsRepository } from '../modules/organizations/organizations.repository';
import { createStorageService } from '../modules/storage/storage.services';
import { ensureBooleanArg } from './commons/args.utils';
import { runScriptWithDb } from './commons/run-script';
@@ -52,6 +54,15 @@ export async function migrateDocumentStorage({
prompts?.intro('Document Storage Migration');
+ const createDocumentStorageKey = buildCreateDocumentStorageKey({
+ storagePatternConfig: toConfig.documentsStorage.pattern,
+ documentsStorageService: toStorageService,
+ resolveStoragePatternContext: buildResolveStoragePatternContext({
+ organizationsRepository: createOrganizationsRepository({ db }),
+ }),
+ logger: createNoopLogger(),
+ });
+
if (isDryRun) {
prompts?.log.info(
'This is a dry run, no actual migration will be performed.\nJust logging the documents that would be migrated.',
@@ -129,14 +140,11 @@ export async function migrateDocumentStorage({
});
const { storageKey: newStorageKey } = await createDocumentStorageKey({
- storagePatternConfig: toConfig.documentsStorage.pattern,
documentId: id,
organizationId,
documentName: originalName,
documentDate: document.documentDate,
documentCreatedAt: document.createdAt,
- documentsStorageService: toStorageService,
- logger: createNoopLogger(),
});
const encryptionFields = await toStorageService.saveFile({