The minimalistic document archiving platform.
feat(documents): added document activity logging (#317)
Corentin Thomasset79c1d3206b14
diff --git a/.changeset/hip-maps-buy.md b/.changeset/hip-maps-buy.mdnew file mode 100644index 00000000..7a0c7ff1--- /dev/null+++ b/.changeset/hip-maps-buy.md@@ -0,0 +1,6 @@+---+"@papra/app-client": minor+"@papra/app-server": minor+---++Added document activity logdiff --git a/apps/papra-client/src/locales/en.yml b/apps/papra-client/src/locales/en.ymlindex 22b8f93d..fe45aeef 100644--- a/apps/papra-client/src/locales/en.yml+++ b/apps/papra-client/src/locales/en.yml@@ -192,6 +192,7 @@ documents.list.no-results: No documents founddocuments.tabs.info: Infodocuments.tabs.content: Content+documents.tabs.activity: Activitydocuments.deleted.message: This document has been deleted and will be permanently removed in {{ days }} days.documents.actions.download: Downloaddocuments.actions.open-in-new-tab: Open in new tab@@ -246,6 +247,20 @@ trash.delete.confirm.cancel: Canceltrash.deleted.success.title: Document deletedtrash.deleted.success.description: The document has been permanently deleted.+activity.document.created: The document has been created+activity.document.updated.single: The {{ field }} has been updated+activity.document.updated.multiple: The {{ fields }} have been updated+activity.document.updated: The document has been updated+activity.document.deleted: The document has been deleted+activity.document.restored: The document has been restored+activity.document.tagged: Tag {{ tag }} has been added+activity.document.untagged: Tag {{ tag }} has been removed++activity.document.user.name: by {{ name }}++activity.load-more: Load more+activity.no-more-activities: No more activities for this document+# Tagstags.no-tags.title: No tags yetdiff --git a/apps/papra-client/src/modules/documents/document.models.ts b/apps/papra-client/src/modules/documents/document.models.tsindex 04481d82..406c431c 100644--- a/apps/papra-client/src/modules/documents/document.models.ts+++ b/apps/papra-client/src/modules/documents/document.models.ts@@ -1,3 +1,4 @@+import type { DocumentActivityEvent } from './documents.types';import { addDays, differenceInDays } from 'date-fns';export const iconByFileType = {@@ -79,3 +80,16 @@ export function getDocumentNameExtension({ name }: { name: string }) {return dotSplittedName[dotCount];}++export const documentActivityIcon: Record<DocumentActivityEvent, string> = {+ created: 'i-tabler-file-plus',+ updated: 'i-tabler-file-diff',+ deleted: 'i-tabler-file-x',+ restored: 'i-tabler-file-check',+ tagged: 'i-tabler-tag',+ untagged: 'i-tabler-tag-off',+} as const;++export function getDocumentActivityIcon({ event }: { event: DocumentActivityEvent }) {+ return documentActivityIcon[event] ?? 'i-tabler-file';+}diff --git a/apps/papra-client/src/modules/documents/documents.constants.ts b/apps/papra-client/src/modules/documents/documents.constants.tsnew file mode 100644index 00000000..c8ece6ec--- /dev/null+++ b/apps/papra-client/src/modules/documents/documents.constants.ts@@ -0,0 +1,10 @@+export const DOCUMENT_ACTIVITY_EVENTS = {+ CREATED: 'created',+ UPDATED: 'updated',+ DELETED: 'deleted',+ RESTORED: 'restored',+ TAGGED: 'tagged',+ UNTAGGED: 'untagged',+} as const;++export const DOCUMENT_ACTIVITY_EVENT_LIST = Object.values(DOCUMENT_ACTIVITY_EVENTS);diff --git a/apps/papra-client/src/modules/documents/documents.services.ts b/apps/papra-client/src/modules/documents/documents.services.tsindex 89ab2c66..77ee02d4 100644--- a/apps/papra-client/src/modules/documents/documents.services.ts+++ b/apps/papra-client/src/modules/documents/documents.services.ts@@ -1,5 +1,5 @@import type { AsDto } from '../shared/http/http-client.types';-import type { Document } from './documents.types';+import type { Document, DocumentActivity } from './documents.types';import { apiClient } from '../shared/http/api-client';import { coerceDates, getFormData } from '../shared/http/http-client.models';@@ -211,3 +211,28 @@ export async function updateDocument({document: coerceDates(document),};}++export async function fetchDocumentActivities({+ documentId,+ organizationId,+ pageIndex,+ pageSize,+}: {+ documentId: string;+ organizationId: string;+ pageIndex: number;+ pageSize: number;+}) {+ const { activities } = await apiClient<{ activities: AsDto<DocumentActivity>[] }>({+ method: 'GET',+ path: `/api/organizations/${organizationId}/documents/${documentId}/activity`,+ query: {+ pageIndex,+ pageSize,+ },+ });++ return {+ activities: activities.map(coerceDates),+ };+}diff --git a/apps/papra-client/src/modules/documents/documents.types.ts b/apps/papra-client/src/modules/documents/documents.types.tsindex 023e93ce..14a7e84d 100644--- a/apps/papra-client/src/modules/documents/documents.types.ts+++ b/apps/papra-client/src/modules/documents/documents.types.ts@@ -1,4 +1,6 @@import type { Tag } from '../tags/tags.types';+import type { User } from '../users/users.types';+import type { DOCUMENT_ACTIVITY_EVENTS } from './documents.constants';export type Document = {id: string;@@ -14,3 +16,17 @@ export type Document = {content: string;tags: Tag[];};++export type DocumentActivityEvent = (typeof DOCUMENT_ACTIVITY_EVENTS)[keyof typeof DOCUMENT_ACTIVITY_EVENTS];++export type DocumentActivity = {+ id: string;+ documentId: string;+ event: DocumentActivityEvent;+ eventData: Record<string, unknown>;+ userId?: string;+ createdAt: Date;+ updatedAt?: Date;+ tag?: Pick<Tag, 'id' | 'name' | 'color' | 'description'>;+ user?: Pick<User, 'id' | 'name'>;+};diff --git a/apps/papra-client/src/modules/documents/pages/document.page.tsx b/apps/papra-client/src/modules/documents/pages/document.page.tsxindex 4159893b..4751a4ea 100644--- a/apps/papra-client/src/modules/documents/pages/document.page.tsx+++ b/apps/papra-client/src/modules/documents/pages/document.page.tsx@@ -1,14 +1,17 @@import type { Component, JSX } from 'solid-js';+import type { DocumentActivity } from '../documents.types';import { formatBytes, safely } from '@corentinth/chisels';-import { useNavigate, useParams } from '@solidjs/router';-import { createQueries } from '@tanstack/solid-query';-import { createSignal, For, Show, Suspense } from 'solid-js';+import { A, useNavigate, useParams, useSearchParams } from '@solidjs/router';+import { createQueries, useInfiniteQuery } from '@tanstack/solid-query';+import { createEffect, createSignal, For, Match, Show, Suspense, Switch } from 'solid-js';import { useConfig } from '@/modules/config/config.provider';import { useI18n } from '@/modules/i18n/i18n.provider';import { timeAgo } from '@/modules/shared/date/time-ago';import { downloadFile } from '@/modules/shared/files/download';import { queryClient } from '@/modules/shared/query/query-client';+import { cn } from '@/modules/shared/style/cn';import { DocumentTagPicker } from '@/modules/tags/components/tag-picker.component';+import { TagLink } from '@/modules/tags/components/tag.component';import { CreateTagModal } from '@/modules/tags/pages/tags.page';import { addTagToDocument, removeTagFromDocument } from '@/modules/tags/tags.services';import { Alert, AlertDescription } from '@/modules/ui/components/alert';@@ -20,9 +23,9 @@ import { TextArea } from '@/modules/ui/components/textarea';import { TextFieldRoot } from '@/modules/ui/components/textfield';import { DocumentPreview } from '../components/document-preview.component';import { useRenameDocumentDialog } from '../components/rename-document-button.component';-import { getDaysBeforePermanentDeletion } from '../document.models';+import { getDaysBeforePermanentDeletion, getDocumentActivityIcon } from '../document.models';import { useDeleteDocument, useRestoreDocument } from '../documents.composables';-import { fetchDocument, fetchDocumentFile, updateDocument } from '../documents.services';+import { fetchDocument, fetchDocumentActivities, fetchDocumentFile, updateDocument } from '../documents.services';import '@pdfslick/solid/dist/pdf_viewer.css';type KeyValueItem = {@@ -51,15 +54,79 @@ const KeyValues: Component<{ data?: KeyValueItem[] }> = (props) => {);};+const ActivityItem: Component<{ activity: DocumentActivity }> = (props) => {+ const { t, te } = useI18n();+ const params = useParams();++ return (+ <div class="border-b py-3 flex items-center gap-2">+ <div>+ <div class={cn(getDocumentActivityIcon({ event: props.activity.event }), 'size-6 text-muted-foreground')} />+ </div>+ <div>+ <Switch fallback={<span class="text-sm">{t(`activity.document.${props.activity.event}`)}</span>}>+ <Match when={['tagged', 'untagged'].includes(props.activity.event)}>+ <span class="text-sm flex items-baseline gap-1">+ {te(`activity.document.${props.activity.event}`, { tag: props.activity.tag ? <TagLink {...props.activity.tag} organizationId={params.organizationId} class="text-xs" /> : undefined })}+ </span>+ </Match>++ <Match when={props.activity.event === 'updated' && (props.activity.eventData.updatedFields as string[]).length === 1}>+ <span class="text-sm flex items-baseline gap-1">+ {te(`activity.document.updated.single`, {+ field: <span class="font-bold">{(props.activity.eventData.updatedFields as string[])[0]}</span>,+ })}+ </span>+ </Match>++ <Match when={props.activity.event === 'updated' && (props.activity.eventData.updatedFields as string[]).length > 1}>+ <span class="text-sm flex items-baseline gap-1">+ {te(`activity.document.updated.multiple`, { fields: (props.activity.eventData.updatedFields as string[]).join(', ') })}+ </span>+ </Match>++ </Switch>++ <div class="flex items-center gap-1 text-xs text-muted-foreground">+ <span title={props.activity.createdAt.toLocaleString()}>{timeAgo({ date: props.activity.createdAt })}</span>+ <Show when={props.activity.user}>+ {getUser => (+ <span>{te('activity.document.user.name', { name: <A href={`/organizations/${params.organizationId}/members`} class="underline hover:text-primary transition">{getUser().name}</A> })}</span>+ )}+ </Show>+ </div>+ </div>+ </div>+ );+};++const tabs = ['info', 'content', 'activity'] as const;+type Tab = typeof tabs[number];+export const DocumentPage: Component = () => {const { t } = useI18n();const params = useParams();+ const [searchParams, setSearchParams] = useSearchParams();const { deleteDocument } = useDeleteDocument();const { restore, getIsRestoring } = useRestoreDocument();const navigate = useNavigate();const { config } = useConfig();const { openRenameDialog } = useRenameDocumentDialog();+ const getInitialTab = (): Tab => {+ const tab = searchParams.tab;+ if (tab && typeof tab === 'string' && tabs.includes(tab as Tab)) {+ return tab as Tab;+ }+ return 'info';+ };++ const [getTab, setTab] = createSignal<Tab>(getInitialTab());++ createEffect(() => {+ setSearchParams({ tab: getTab() }, { replace: true });+ });+const queries = createQueries(() => ({queries: [{@@ -73,6 +140,30 @@ export const DocumentPage: Component = () => {],}));+ const activityPageSize = 20;+ const activityQuery = useInfiniteQuery(() => ({+ enabled: getTab() === 'activity',+ queryKey: ['organizations', params.organizationId, 'documents', params.documentId, 'activity'],+ queryFn: async ({ pageParam }) => {+ const { activities } = await fetchDocumentActivities({+ documentId: params.documentId,+ organizationId: params.organizationId,+ pageIndex: pageParam,+ pageSize: activityPageSize,+ });++ return activities;+ },+ getNextPageParam: (lastPage, _pages, lastPageParam) => {+ if (lastPage.length < activityPageSize) {+ return undefined;+ }++ return lastPageParam + 1;+ },+ initialPageParam: 0,+ }));+const deleteDoc = async () => {if (!queries[0].data) {return;@@ -243,10 +334,11 @@ export const DocumentPage: Component = () => {<Separator class="my-3" />- <Tabs defaultValue="info" class="w-full">+ <Tabs value={getTab()} onChange={setTab} class="w-full"><TabsList class="w-full h-8"><TabsTrigger value="info">{t('documents.tabs.info')}</TabsTrigger><TabsTrigger value="content">{t('documents.tabs.content')}</TabsTrigger>+ <TabsTrigger value="activity">{t('documents.tabs.activity')}</TabsTrigger><TabsIndicator /></TabsList>@@ -342,6 +434,40 @@ export const DocumentPage: Component = () => {</div></Show></TabsContent>+ <TabsContent value="activity">+ <Show when={activityQuery.data?.pages}>+ {getActivitiesPages => (+ <div class="flex flex-col">+ <For each={getActivitiesPages() ?? []}>+ {activities => (+ <For each={activities}>+ {activity => (+ <ActivityItem activity={activity} />+ )}+ </For>+ )}+ </For>++ <Show+ when={activityQuery.hasNextPage}+ fallback={(+ <div class="text-sm text-muted-foreground text-center py-4">+ {t('activity.no-more-activities')}+ </div>+ )}+ >+ <Button+ variant="outline"+ onClick={() => activityQuery.fetchNextPage()}+ isLoading={activityQuery.isFetchingNextPage}+ >+ {t('activity.load-more')}+ </Button>+ </Show>+ </div>+ )}+ </Show>+ </TabsContent></Tabs></div>diff --git a/apps/papra-client/src/modules/i18n/locales.test.ts b/apps/papra-client/src/modules/i18n/locales.test.tsindex 88e9a37d..2a33700f 100644--- a/apps/papra-client/src/modules/i18n/locales.test.ts+++ b/apps/papra-client/src/modules/i18n/locales.test.ts@@ -41,6 +41,7 @@ describe('locales', () => {/^webhooks\.events\.documents\.[a-z0-9:]+.description$/, // webhooks.events.organization.organization:created/^api-keys\.permissions\.[a-z0-9:]+\.[a-z0-9:]+$/, // api-keys.permissions.documents.documents:delete/^organizations\.members\.roles\.[a-z0-9]+$/, // organizations.members.roles.admin+ /^activity\.document\.[a-z0-9:]+$/, // activity.document.created];const keys = new Set(diff --git a/apps/papra-client/src/modules/i18n/locales.types.ts b/apps/papra-client/src/modules/i18n/locales.types.tsindex 89d2479c..055aaf3d 100644--- a/apps/papra-client/src/modules/i18n/locales.types.ts+++ b/apps/papra-client/src/modules/i18n/locales.types.ts@@ -170,6 +170,7 @@ export type LocaleKeys =| 'documents.list.no-results'| 'documents.tabs.info'| 'documents.tabs.content'+ | 'documents.tabs.activity'| 'documents.deleted.message'| 'documents.actions.download'| 'documents.actions.open-in-new-tab'@@ -219,6 +220,17 @@ export type LocaleKeys =| 'trash.delete.confirm.cancel'| 'trash.deleted.success.title'| 'trash.deleted.success.description'+ | 'activity.document.created'+ | 'activity.document.updated.single'+ | 'activity.document.updated.multiple'+ | 'activity.document.updated'+ | 'activity.document.deleted'+ | 'activity.document.restored'+ | 'activity.document.tagged'+ | 'activity.document.untagged'+ | 'activity.document.user.name'+ | 'activity.load-more'+ | 'activity.no-more-activities'| 'tags.no-tags.title'| 'tags.no-tags.description'| 'tags.no-tags.create-tag'diff --git a/apps/papra-client/src/modules/users/users.types.ts b/apps/papra-client/src/modules/users/users.types.tsindex 8ab93d59..4df73ad5 100644--- a/apps/papra-client/src/modules/users/users.types.ts+++ b/apps/papra-client/src/modules/users/users.types.ts@@ -9,6 +9,7 @@ export type UserMe = {export type User = {id: string;email: string;+ name: string;createdAt: Date;updatedAt: Date;provider: string;diff --git a/apps/papra-client/uno.config.ts b/apps/papra-client/uno.config.tsindex 6bf54938..aa19b97f 100644--- a/apps/papra-client/uno.config.ts+++ b/apps/papra-client/uno.config.ts@@ -9,7 +9,7 @@ import {} from 'unocss';import { presetAnimations } from 'unocss-preset-animations';import { ssoProviders } from './src/modules/auth/auth.constants';-import { iconByFileType } from './src/modules/documents/document.models';+import { documentActivityIcon, iconByFileType } from './src/modules/documents/document.models';export default defineConfig({presets: [@@ -113,7 +113,10 @@ export default defineConfig({},},safelist: [- ...uniq(values(iconByFileType)),- ...(ssoProviders.map(p => p.icon)),+ ...uniq([+ ...values(iconByFileType),+ ...values(documentActivityIcon),+ ...(ssoProviders.map(p => p.icon)),+ ]),],});diff --git a/apps/papra-server/migrations/0006_document-activity-log.sql b/apps/papra-server/migrations/0006_document-activity-log.sqlnew file mode 100644index 00000000..f41de3d9--- /dev/null+++ b/apps/papra-server/migrations/0006_document-activity-log.sql@@ -0,0 +1,12 @@+CREATE TABLE `document_activity_log` (+ `id` text PRIMARY KEY NOT NULL,+ `created_at` integer NOT NULL,+ `document_id` text NOT NULL,+ `event` text NOT NULL,+ `event_data` text,+ `user_id` text,+ `tag_id` text,+ FOREIGN KEY (`document_id`) REFERENCES `documents`(`id`) ON UPDATE cascade ON DELETE cascade,+ FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE cascade ON DELETE no action,+ FOREIGN KEY (`tag_id`) REFERENCES `tags`(`id`) ON UPDATE cascade ON DELETE no action+);diff --git a/apps/papra-server/migrations/meta/0006_snapshot.json b/apps/papra-server/migrations/meta/0006_snapshot.jsonnew file mode 100644index 00000000..c7e59c1c--- /dev/null+++ b/apps/papra-server/migrations/meta/0006_snapshot.json@@ -0,0 +1,1970 @@+{+ "version": "6",+ "dialect": "sqlite",+ "id": "2033ceb9-a1e6-4b1a-972d-84922f2ed9b0",+ "prevId": "df039595-1e23-4acc-be89-8e6fcc1775b5",+ "tables": {+ "document_activity_log": {+ "name": "document_activity_log",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "document_id": {+ "name": "document_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "event": {+ "name": "event",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "event_data": {+ "name": "event_data",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "tag_id": {+ "name": "tag_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "document_activity_log_document_id_documents_id_fk": {+ "name": "document_activity_log_document_id_documents_id_fk",+ "tableFrom": "document_activity_log",+ "tableTo": "documents",+ "columnsFrom": [+ "document_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "document_activity_log_user_id_users_id_fk": {+ "name": "document_activity_log_user_id_users_id_fk",+ "tableFrom": "document_activity_log",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "cascade"+ },+ "document_activity_log_tag_id_tags_id_fk": {+ "name": "document_activity_log_tag_id_tags_id_fk",+ "tableFrom": "document_activity_log",+ "tableTo": "tags",+ "columnsFrom": [+ "tag_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "documents": {+ "name": "documents",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "is_deleted": {+ "name": "is_deleted",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "deleted_at": {+ "name": "deleted_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "deleted_by": {+ "name": "deleted_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "original_name": {+ "name": "original_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "original_size": {+ "name": "original_size",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "original_storage_key": {+ "name": "original_storage_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "original_sha256_hash": {+ "name": "original_sha256_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "mime_type": {+ "name": "mime_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ }+ },+ "indexes": {+ "documents_organization_id_is_deleted_created_at_index": {+ "name": "documents_organization_id_is_deleted_created_at_index",+ "columns": [+ "organization_id",+ "is_deleted",+ "created_at"+ ],+ "isUnique": false+ },+ "documents_organization_id_is_deleted_index": {+ "name": "documents_organization_id_is_deleted_index",+ "columns": [+ "organization_id",+ "is_deleted"+ ],+ "isUnique": false+ },+ "documents_organization_id_original_sha256_hash_unique": {+ "name": "documents_organization_id_original_sha256_hash_unique",+ "columns": [+ "organization_id",+ "original_sha256_hash"+ ],+ "isUnique": true+ },+ "documents_original_sha256_hash_index": {+ "name": "documents_original_sha256_hash_index",+ "columns": [+ "original_sha256_hash"+ ],+ "isUnique": false+ },+ "documents_organization_id_size_index": {+ "name": "documents_organization_id_size_index",+ "columns": [+ "organization_id",+ "original_size"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "documents_organization_id_organizations_id_fk": {+ "name": "documents_organization_id_organizations_id_fk",+ "tableFrom": "documents",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "documents_created_by_users_id_fk": {+ "name": "documents_created_by_users_id_fk",+ "tableFrom": "documents",+ "tableTo": "users",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ },+ "documents_deleted_by_users_id_fk": {+ "name": "documents_deleted_by_users_id_fk",+ "tableFrom": "documents",+ "tableTo": "users",+ "columnsFrom": [+ "deleted_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "organization_invitations": {+ "name": "organization_invitations",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'pending'"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "inviter_id": {+ "name": "inviter_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "organization_invitations_organization_email_unique": {+ "name": "organization_invitations_organization_email_unique",+ "columns": [+ "organization_id",+ "email"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "organization_invitations_organization_id_organizations_id_fk": {+ "name": "organization_invitations_organization_id_organizations_id_fk",+ "tableFrom": "organization_invitations",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "organization_invitations_inviter_id_users_id_fk": {+ "name": "organization_invitations_inviter_id_users_id_fk",+ "tableFrom": "organization_invitations",+ "tableTo": "users",+ "columnsFrom": [+ "inviter_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "organization_members": {+ "name": "organization_members",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "organization_members_user_organization_unique": {+ "name": "organization_members_user_organization_unique",+ "columns": [+ "organization_id",+ "user_id"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "organization_members_organization_id_organizations_id_fk": {+ "name": "organization_members_organization_id_organizations_id_fk",+ "tableFrom": "organization_members",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "organization_members_user_id_users_id_fk": {+ "name": "organization_members_user_id_users_id_fk",+ "tableFrom": "organization_members",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "organizations": {+ "name": "organizations",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "customer_id": {+ "name": "customer_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "user_roles": {+ "name": "user_roles",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "user_roles_role_index": {+ "name": "user_roles_role_index",+ "columns": [+ "role"+ ],+ "isUnique": false+ },+ "user_roles_user_id_role_unique_index": {+ "name": "user_roles_user_id_role_unique_index",+ "columns": [+ "user_id",+ "role"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "user_roles_user_id_users_id_fk": {+ "name": "user_roles_user_id_users_id_fk",+ "tableFrom": "user_roles",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "documents_tags": {+ "name": "documents_tags",+ "columns": {+ "document_id": {+ "name": "document_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tag_id": {+ "name": "tag_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "documents_tags_document_id_documents_id_fk": {+ "name": "documents_tags_document_id_documents_id_fk",+ "tableFrom": "documents_tags",+ "tableTo": "documents",+ "columnsFrom": [+ "document_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "documents_tags_tag_id_tags_id_fk": {+ "name": "documents_tags_tag_id_tags_id_fk",+ "tableFrom": "documents_tags",+ "tableTo": "tags",+ "columnsFrom": [+ "tag_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {+ "documents_tags_pkey": {+ "columns": [+ "document_id",+ "tag_id"+ ],+ "name": "documents_tags_pkey"+ }+ },+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "tags": {+ "name": "tags",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "tags_organization_id_name_unique": {+ "name": "tags_organization_id_name_unique",+ "columns": [+ "organization_id",+ "name"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "tags_organization_id_organizations_id_fk": {+ "name": "tags_organization_id_organizations_id_fk",+ "tableFrom": "tags",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "users": {+ "name": "users",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email_verified": {+ "name": "email_verified",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "max_organization_count": {+ "name": "max_organization_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "users_email_unique": {+ "name": "users_email_unique",+ "columns": [+ "email"+ ],+ "isUnique": true+ },+ "users_email_index": {+ "name": "users_email_index",+ "columns": [+ "email"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "api_key_organizations": {+ "name": "api_key_organizations",+ "columns": {+ "api_key_id": {+ "name": "api_key_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_member_id": {+ "name": "organization_member_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "api_key_organizations_api_key_id_api_keys_id_fk": {+ "name": "api_key_organizations_api_key_id_api_keys_id_fk",+ "tableFrom": "api_key_organizations",+ "tableTo": "api_keys",+ "columnsFrom": [+ "api_key_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "api_key_organizations_organization_member_id_organization_members_id_fk": {+ "name": "api_key_organizations_organization_member_id_organization_members_id_fk",+ "tableFrom": "api_key_organizations",+ "tableTo": "organization_members",+ "columnsFrom": [+ "organization_member_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "api_keys": {+ "name": "api_keys",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "key_hash": {+ "name": "key_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "prefix": {+ "name": "prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "last_used_at": {+ "name": "last_used_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "permissions": {+ "name": "permissions",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "all_organizations": {+ "name": "all_organizations",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ }+ },+ "indexes": {+ "api_keys_key_hash_unique": {+ "name": "api_keys_key_hash_unique",+ "columns": [+ "key_hash"+ ],+ "isUnique": true+ },+ "key_hash_index": {+ "name": "key_hash_index",+ "columns": [+ "key_hash"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "api_keys_user_id_users_id_fk": {+ "name": "api_keys_user_id_users_id_fk",+ "tableFrom": "api_keys",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "auth_accounts": {+ "name": "auth_accounts",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "auth_accounts_user_id_users_id_fk": {+ "name": "auth_accounts_user_id_users_id_fk",+ "tableFrom": "auth_accounts",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "auth_sessions": {+ "name": "auth_sessions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "active_organization_id": {+ "name": "active_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "auth_sessions_token_index": {+ "name": "auth_sessions_token_index",+ "columns": [+ "token"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "auth_sessions_user_id_users_id_fk": {+ "name": "auth_sessions_user_id_users_id_fk",+ "tableFrom": "auth_sessions",+ "tableTo": "users",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "auth_sessions_active_organization_id_organizations_id_fk": {+ "name": "auth_sessions_active_organization_id_organizations_id_fk",+ "tableFrom": "auth_sessions",+ "tableTo": "organizations",+ "columnsFrom": [+ "active_organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "auth_verifications": {+ "name": "auth_verifications",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "auth_verifications_identifier_index": {+ "name": "auth_verifications_identifier_index",+ "columns": [+ "identifier"+ ],+ "isUnique": false+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "intake_emails": {+ "name": "intake_emails",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "email_address": {+ "name": "email_address",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "allowed_origins": {+ "name": "allowed_origins",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'[]'"+ },+ "is_enabled": {+ "name": "is_enabled",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ }+ },+ "indexes": {+ "intake_emails_email_address_unique": {+ "name": "intake_emails_email_address_unique",+ "columns": [+ "email_address"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "intake_emails_organization_id_organizations_id_fk": {+ "name": "intake_emails_organization_id_organizations_id_fk",+ "tableFrom": "intake_emails",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "organization_subscriptions": {+ "name": "organization_subscriptions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "customer_id": {+ "name": "customer_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "plan_id": {+ "name": "plan_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "seats_count": {+ "name": "seats_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "current_period_end": {+ "name": "current_period_end",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "current_period_start": {+ "name": "current_period_start",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "cancel_at_period_end": {+ "name": "cancel_at_period_end",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "organization_subscriptions_organization_id_organizations_id_fk": {+ "name": "organization_subscriptions_organization_id_organizations_id_fk",+ "tableFrom": "organization_subscriptions",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "tagging_rule_actions": {+ "name": "tagging_rule_actions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tagging_rule_id": {+ "name": "tagging_rule_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tag_id": {+ "name": "tag_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "tagging_rule_actions_tagging_rule_id_tagging_rules_id_fk": {+ "name": "tagging_rule_actions_tagging_rule_id_tagging_rules_id_fk",+ "tableFrom": "tagging_rule_actions",+ "tableTo": "tagging_rules",+ "columnsFrom": [+ "tagging_rule_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "tagging_rule_actions_tag_id_tags_id_fk": {+ "name": "tagging_rule_actions_tag_id_tags_id_fk",+ "tableFrom": "tagging_rule_actions",+ "tableTo": "tags",+ "columnsFrom": [+ "tag_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "tagging_rule_conditions": {+ "name": "tagging_rule_conditions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "tagging_rule_id": {+ "name": "tagging_rule_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "field": {+ "name": "field",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "operator": {+ "name": "operator",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "is_case_sensitive": {+ "name": "is_case_sensitive",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "tagging_rule_conditions_tagging_rule_id_tagging_rules_id_fk": {+ "name": "tagging_rule_conditions_tagging_rule_id_tagging_rules_id_fk",+ "tableFrom": "tagging_rule_conditions",+ "tableTo": "tagging_rules",+ "columnsFrom": [+ "tagging_rule_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "tagging_rules": {+ "name": "tagging_rules",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "enabled": {+ "name": "enabled",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "tagging_rules_organization_id_organizations_id_fk": {+ "name": "tagging_rules_organization_id_organizations_id_fk",+ "tableFrom": "tagging_rules",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "webhook_deliveries": {+ "name": "webhook_deliveries",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "webhook_id": {+ "name": "webhook_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "event_name": {+ "name": "event_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "request_payload": {+ "name": "request_payload",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "response_payload": {+ "name": "response_payload",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "response_status": {+ "name": "response_status",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "webhook_deliveries_webhook_id_webhooks_id_fk": {+ "name": "webhook_deliveries_webhook_id_webhooks_id_fk",+ "tableFrom": "webhook_deliveries",+ "tableTo": "webhooks",+ "columnsFrom": [+ "webhook_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "webhook_events": {+ "name": "webhook_events",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "webhook_id": {+ "name": "webhook_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "event_name": {+ "name": "event_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "webhook_events_webhook_id_event_name_unique": {+ "name": "webhook_events_webhook_id_event_name_unique",+ "columns": [+ "webhook_id",+ "event_name"+ ],+ "isUnique": true+ }+ },+ "foreignKeys": {+ "webhook_events_webhook_id_webhooks_id_fk": {+ "name": "webhook_events_webhook_id_webhooks_id_fk",+ "tableFrom": "webhook_events",+ "tableTo": "webhooks",+ "columnsFrom": [+ "webhook_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "webhooks": {+ "name": "webhooks",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "secret": {+ "name": "secret",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "enabled": {+ "name": "enabled",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": true+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "webhooks_created_by_users_id_fk": {+ "name": "webhooks_created_by_users_id_fk",+ "tableFrom": "webhooks",+ "tableTo": "users",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "cascade"+ },+ "webhooks_organization_id_organizations_id_fk": {+ "name": "webhooks_organization_id_organizations_id_fk",+ "tableFrom": "webhooks",+ "tableTo": "organizations",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ }+ },+ "views": {},+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ },+ "internal": {+ "indexes": {}+ }+}diff --git a/apps/papra-server/migrations/meta/_journal.json b/apps/papra-server/migrations/meta/_journal.jsonindex 88b93f0d..9fa4aaa3 100644--- a/apps/papra-server/migrations/meta/_journal.json+++ b/apps/papra-server/migrations/meta/_journal.json@@ -43,6 +43,13 @@"when": 1747575029264,"tag": "0005_organizations-invitations-improvement","breakpoints": true+ },+ {+ "idx": 6,+ "version": "6",+ "when": 1748554484124,+ "tag": "0006_document-activity-log",+ "breakpoints": true}]}diff --git a/apps/papra-server/src/modules/app/server.routes.ts b/apps/papra-server/src/modules/app/server.routes.tsindex d4f65687..7ebe1c84 100644--- a/apps/papra-server/src/modules/app/server.routes.ts+++ b/apps/papra-server/src/modules/app/server.routes.ts@@ -1,6 +1,7 @@import type { RouteDefinitionContext } from './server.types';import { registerApiKeysRoutes } from '../api-keys/api-keys.routes';import { registerConfigRoutes } from '../config/config.routes';+import { registerDocumentActivityRoutes } from '../documents/document-activity/document-activity.routes';import { registerDocumentsRoutes } from '../documents/documents.routes';import { registerIntakeEmailsRoutes } from '../intake-emails/intake-emails.routes';import { registerInvitationsRoutes } from '../invitations/invitations.routes';@@ -27,4 +28,5 @@ export function registerRoutes(context: RouteDefinitionContext) {registerApiKeysRoutes(context);registerWebhooksRoutes(context);registerInvitationsRoutes(context);+ registerDocumentActivityRoutes(context);}diff --git a/apps/papra-server/src/modules/documents/document-activity/document-activity.constants.ts b/apps/papra-server/src/modules/documents/document-activity/document-activity.constants.tsnew file mode 100644index 00000000..c8ece6ec--- /dev/null+++ b/apps/papra-server/src/modules/documents/document-activity/document-activity.constants.ts@@ -0,0 +1,10 @@+export const DOCUMENT_ACTIVITY_EVENTS = {+ CREATED: 'created',+ UPDATED: 'updated',+ DELETED: 'deleted',+ RESTORED: 'restored',+ TAGGED: 'tagged',+ UNTAGGED: 'untagged',+} as const;++export const DOCUMENT_ACTIVITY_EVENT_LIST = Object.values(DOCUMENT_ACTIVITY_EVENTS);diff --git a/apps/papra-server/src/modules/documents/document-activity/document-activity.repository.ts b/apps/papra-server/src/modules/documents/document-activity/document-activity.repository.tsnew file mode 100644index 00000000..96e4d2e8--- /dev/null+++ b/apps/papra-server/src/modules/documents/document-activity/document-activity.repository.ts@@ -0,0 +1,101 @@+import type { Database } from '../../app/database/database.types';+import type { DocumentActivityEvent } from './document-activity.types';+import { injectArguments } from '@corentinth/chisels';+import { and, desc, eq, getTableColumns } from 'drizzle-orm';+import { withPagination } from '../../shared/db/pagination';+import { tagsTable } from '../../tags/tags.table';+import { usersTable } from '../../users/users.table';+import { documentsTable } from '../documents.table';+import { documentActivityLogTable } from './document-activity.table';++export type DocumentActivityRepository = ReturnType<typeof createDocumentActivityRepository>;++export function createDocumentActivityRepository({ db }: { db: Database }) {+ return injectArguments(+ {+ saveDocumentActivity,+ getOrganizationDocumentActivities,+ },+ { db },+ );+}++async function saveDocumentActivity({+ documentId,+ event,+ eventData,+ userId,+ tagId,+ db,+}: {+ documentId: string;+ event: DocumentActivityEvent;+ eventData?: Record<string, unknown>;+ userId?: string;+ tagId?: string;+ db: Database;+}) {+ const [activity] = await db+ .insert(documentActivityLogTable)+ .values({+ documentId,+ event,+ eventData,+ userId,+ tagId,+ })+ .returning();++ return { activity };+}++async function getOrganizationDocumentActivities({+ organizationId,+ documentId,+ pageIndex,+ pageSize,+ db,+}: {+ organizationId: string;+ documentId: string;+ pageIndex: number;+ pageSize: number;+ db: Database;+}) {+ const query = db+ .select({+ ...getTableColumns(documentActivityLogTable),+ user: {+ id: usersTable.id,+ name: usersTable.name,+ },+ tag: {+ id: tagsTable.id,+ name: tagsTable.name,+ color: tagsTable.color,+ description: tagsTable.description,+ },+ })+ .from(documentActivityLogTable)+ // Join with documents table to ensure the document exists in the organization+ .innerJoin(documentsTable, eq(documentActivityLogTable.documentId, documentsTable.id))+ .leftJoin(usersTable, eq(documentActivityLogTable.userId, usersTable.id))+ .leftJoin(tagsTable, eq(documentActivityLogTable.tagId, tagsTable.id))+ .where(+ and(+ eq(documentsTable.organizationId, organizationId),+ eq(documentActivityLogTable.documentId, documentId),+ ),+ );++ const activities = await withPagination(+ query.$dynamic(),+ {+ orderByColumn: desc(documentActivityLogTable.createdAt),+ pageIndex,+ pageSize,+ },+ );++ return { activities };+}diff --git a/apps/papra-server/src/modules/documents/document-activity/document-activity.routes.ts b/apps/papra-server/src/modules/documents/document-activity/document-activity.routes.tsnew file mode 100644index 00000000..5f6b678b--- /dev/null+++ b/apps/papra-server/src/modules/documents/document-activity/document-activity.routes.ts@@ -0,0 +1,51 @@+import type { RouteDefinitionContext } from '../../app/server.types';+import { z } from 'zod';+import { requireAuthentication } from '../../app/auth/auth.middleware';+import { getUser } from '../../app/auth/auth.models';+import { organizationIdSchema } from '../../organizations/organization.schemas';+import { createOrganizationsRepository } from '../../organizations/organizations.repository';+import { ensureUserIsInOrganization } from '../../organizations/organizations.usecases';+import { validateParams, validateQuery } from '../../shared/validation/validation';+import { documentIdSchema } from '../documents.schemas';+import { createDocumentActivityRepository } from './document-activity.repository';++export function registerDocumentActivityRoutes(context: RouteDefinitionContext) {+ setupGetOrganizationDocumentActivitiesRoute(context);+}++function setupGetOrganizationDocumentActivitiesRoute({ app, db }: RouteDefinitionContext) {+ app.get(+ '/api/organizations/:organizationId/documents/:documentId/activity',+ requireAuthentication({ apiKeyPermissions: ['documents:read'] }),+ validateParams(z.object({+ organizationId: organizationIdSchema,+ documentId: documentIdSchema,+ })),+ validateQuery(+ z.object({+ pageIndex: z.coerce.number().min(0).int().optional().default(0),+ pageSize: z.coerce.number().min(1).max(100).int().optional().default(100),+ }),+ ),+ async (context) => {+ const { userId } = getUser({ context });++ const { organizationId, documentId } = context.req.valid('param');+ const { pageIndex, pageSize } = context.req.valid('query');++ const organizationsRepository = createOrganizationsRepository({ db });+ const documentActivityRepository = createDocumentActivityRepository({ db });++ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });++ const { activities } = await documentActivityRepository.getOrganizationDocumentActivities({+ organizationId,+ documentId,+ pageIndex,+ pageSize,+ });++ return context.json({ activities });+ },+ );+}diff --git a/apps/papra-server/src/modules/documents/document-activity/document-activity.table.ts b/apps/papra-server/src/modules/documents/document-activity/document-activity.table.tsnew file mode 100644index 00000000..9a8a1921--- /dev/null+++ b/apps/papra-server/src/modules/documents/document-activity/document-activity.table.ts@@ -0,0 +1,20 @@+import type { NonEmptyArray } from '../../shared/types';+import type { DocumentActivityEvent } from './document-activity.types';+import { sqliteTable, text } from 'drizzle-orm/sqlite-core';+import { createCreatedAtField, createPrimaryKeyField } from '../../shared/db/columns.helpers';+import { tagsTable } from '../../tags/tags.table';+import { usersTable } from '../../users/users.table';+import { documentsTable } from '../documents.table';+import { DOCUMENT_ACTIVITY_EVENT_LIST } from './document-activity.constants';++export const documentActivityLogTable = sqliteTable('document_activity_log', {+ ...createPrimaryKeyField({ prefix: 'doc_act' }),+ ...createCreatedAtField(),++ documentId: text('document_id').notNull().references(() => documentsTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),+ event: text('event', { enum: DOCUMENT_ACTIVITY_EVENT_LIST as NonEmptyArray<DocumentActivityEvent> }).notNull(),+ eventData: text('event_data', { mode: 'json' }).$type<Record<string, unknown>>(),++ userId: text('user_id').references(() => usersTable.id, { onDelete: 'no action', onUpdate: 'cascade' }),+ tagId: text('tag_id').references(() => tagsTable.id, { onDelete: 'no action', onUpdate: 'cascade' }),+});diff --git a/apps/papra-server/src/modules/documents/document-activity/document-activity.types.ts b/apps/papra-server/src/modules/documents/document-activity/document-activity.types.tsnew file mode 100644index 00000000..27a1f019--- /dev/null+++ b/apps/papra-server/src/modules/documents/document-activity/document-activity.types.ts@@ -0,0 +1,3 @@+import type { DOCUMENT_ACTIVITY_EVENTS } from './document-activity.constants';++export type DocumentActivityEvent = (typeof DOCUMENT_ACTIVITY_EVENTS)[keyof typeof DOCUMENT_ACTIVITY_EVENTS];diff --git a/apps/papra-server/src/modules/documents/document-activity/document-activity.usecases.ts b/apps/papra-server/src/modules/documents/document-activity/document-activity.usecases.tsnew file mode 100644index 00000000..4811c7ee--- /dev/null+++ b/apps/papra-server/src/modules/documents/document-activity/document-activity.usecases.ts@@ -0,0 +1,41 @@+import type { Logger } from '@crowlog/logger';+import type { DocumentActivityRepository } from './document-activity.repository';+import type { DocumentActivityEvent } from './document-activity.types';+import { createDeferable } from '../../shared/async/defer';+import { createLogger } from '../../shared/logger/logger';++export async function registerDocumentActivityLog({+ documentId,+ event,+ eventData,+ userId,+ tagId,+ documentActivityRepository,+ logger = createLogger({ namespace: 'document-activity-log' }),+}: {+ documentId: string;+ event: DocumentActivityEvent;+ eventData?: Record<string, unknown>;+ userId?: string;+ tagId?: string;+ documentActivityRepository: DocumentActivityRepository;+ logger?: Logger;+}) {+ await documentActivityRepository.saveDocumentActivity({+ documentId,+ event,+ eventData,+ userId,+ tagId,+ });++ logger.info({+ documentId,+ event,+ eventData,+ userId,+ tagId,+ }, 'Document activity log registered');+}++export const deferRegisterDocumentActivityLog = createDeferable(registerDocumentActivityLog);diff --git a/apps/papra-server/src/modules/documents/documents.routes.ts b/apps/papra-server/src/modules/documents/documents.routes.tsindex 0354f511..edf975b0 100644--- a/apps/papra-server/src/modules/documents/documents.routes.ts+++ b/apps/papra-server/src/modules/documents/documents.routes.ts@@ -6,19 +6,17 @@ import { getUser } from '../app/auth/auth.models';import { organizationIdSchema } from '../organizations/organization.schemas';import { createOrganizationsRepository } from '../organizations/organizations.repository';import { ensureUserIsInOrganization } from '../organizations/organizations.usecases';-import { createPlansRepository } from '../plans/plans.repository';import { createError } from '../shared/errors/errors';import { validateFormData, validateJsonBody, validateParams, validateQuery } from '../shared/validation/validation';-import { createSubscriptionsRepository } from '../subscriptions/subscriptions.repository';-import { createTaggingRulesRepository } from '../tagging-rules/tagging-rules.repository';-import { createTagsRepository } from '../tags/tags.repository';import { createWebhookRepository } from '../webhooks/webhook.repository';import { triggerWebhooks } from '../webhooks/webhook.usecases';+import { createDocumentActivityRepository } from './document-activity/document-activity.repository';+import { deferRegisterDocumentActivityLog } from './document-activity/document-activity.usecases';import { createDocumentIsNotDeletedError } from './documents.errors';import { isDocumentSizeLimitEnabled } from './documents.models';import { createDocumentsRepository } from './documents.repository';import { documentIdSchema } from './documents.schemas';-import { createDocument, deleteAllTrashDocuments, deleteTrashDocument, ensureDocumentExists, getDocumentOrThrow } from './documents.usecases';+import { createDocumentCreationUsecase, deleteAllTrashDocuments, deleteTrashDocument, ensureDocumentExists, getDocumentOrThrow } from './documents.usecases';import { createDocumentStorageService } from './storage/documents.storage.services';export function registerDocumentsRoutes(context: RouteDefinitionContext) {@@ -89,26 +87,16 @@ function setupCreateDocumentRoute({ app, config, db, trackingServices }: RouteDe});}- const documentsRepository = createDocumentsRepository({ db });- const documentsStorageService = await createDocumentStorageService({ config });- const plansRepository = createPlansRepository({ config });- const subscriptionsRepository = createSubscriptionsRepository({ db });- const taggingRulesRepository = createTaggingRulesRepository({ db });- const tagsRepository = createTagsRepository({ db });- const webhookRepository = createWebhookRepository({ db });+ const createDocument = await createDocumentCreationUsecase({+ db,+ config,+ trackingServices,+ });const { document } = await createDocument({file,userId,organizationId,- documentsRepository,- documentsStorageService,- plansRepository,- subscriptionsRepository,- trackingServices,- taggingRulesRepository,- tagsRepository,- webhookRepository,});return context.json({@@ -245,6 +233,8 @@ function setupDeleteDocumentRoute({ app, db }: RouteDefinitionContext) {const documentsRepository = createDocumentsRepository({ db });const organizationsRepository = createOrganizationsRepository({ db });const webhookRepository = createWebhookRepository({ db });+ const documentActivityRepository = createDocumentActivityRepository({ db });+await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });await ensureDocumentExists({ documentId, organizationId, documentsRepository });@@ -257,6 +247,13 @@ function setupDeleteDocumentRoute({ app, db }: RouteDefinitionContext) {payload: { documentId, organizationId },});+ deferRegisterDocumentActivityLog({+ documentId,+ event: 'deleted',+ userId,+ documentActivityRepository,+ });+return context.json({success: true,});@@ -279,6 +276,7 @@ function setupRestoreDocumentRoute({ app, db }: RouteDefinitionContext) {const documentsRepository = createDocumentsRepository({ db });const organizationsRepository = createOrganizationsRepository({ db });+ const documentActivityRepository = createDocumentActivityRepository({ db });await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });@@ -290,6 +288,13 @@ function setupRestoreDocumentRoute({ app, db }: RouteDefinitionContext) {await documentsRepository.restoreDocument({ documentId, organizationId });+ deferRegisterDocumentActivityLog({+ documentId,+ event: 'restored',+ userId,+ documentActivityRepository,+ });+return context.body(null, 204);},);@@ -469,6 +474,7 @@ function setupUpdateDocumentRoute({ app, db }: RouteDefinitionContext) {const documentsRepository = createDocumentsRepository({ db });const organizationsRepository = createOrganizationsRepository({ db });+ const documentActivityRepository = createDocumentActivityRepository({ db });await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });await ensureDocumentExists({ documentId, organizationId, documentsRepository });@@ -479,6 +485,16 @@ function setupUpdateDocumentRoute({ app, db }: RouteDefinitionContext) {...updateData,});+ deferRegisterDocumentActivityLog({+ documentId,+ event: 'updated',+ userId,+ documentActivityRepository,+ eventData: {+ updatedFields: Object.entries(updateData).filter(([_, value]) => value !== undefined).map(([key]) => key),+ },+ });+return context.json({ document });},);diff --git a/apps/papra-server/src/modules/documents/documents.usecases.test.ts b/apps/papra-server/src/modules/documents/documents.usecases.test.tsindex c1b8007c..80e51a4b 100644--- a/apps/papra-server/src/modules/documents/documents.usecases.test.ts+++ b/apps/papra-server/src/modules/documents/documents.usecases.test.ts@@ -1,19 +1,15 @@-import type { Config } from '../config/config.types';import { describe, expect, test } from 'vitest';import { createInMemoryDatabase } from '../app/database/database.test-utils';+import { overrideConfig } from '../config/config.test-utils';import { ORGANIZATION_ROLES } from '../organizations/organizations.constants';-import { createPlansRepository } from '../plans/plans.repository';+import { nextTick } from '../shared/async/defer.test-utils';import { collectReadableStreamToString } from '../shared/streams/readable-stream';-import { createSubscriptionsRepository } from '../subscriptions/subscriptions.repository';-import { createTaggingRulesRepository } from '../tagging-rules/tagging-rules.repository';-import { createTagsRepository } from '../tags/tags.repository';import { documentsTagsTable } from '../tags/tags.table';-import { createDummyTrackingServices } from '../tracking/tracking.services';-import { createWebhookRepository } from '../webhooks/webhook.repository';+import { documentActivityLogTable } from './document-activity/document-activity.table';import { createDocumentAlreadyExistsError } from './documents.errors';import { createDocumentsRepository } from './documents.repository';import { documentsTable } from './documents.table';-import { createDocument } from './documents.usecases';+import { createDocumentCreationUsecase } from './documents.usecases';import { createDocumentStorageService } from './storage/documents.storage.services';describe('documents usecases', () => {@@ -25,15 +21,18 @@ describe('documents usecases', () => {organizationMembers: [{ organizationId: 'organization-1', userId: 'user-1', role: ORGANIZATION_ROLES.OWNER }],});- const documentsRepository = createDocumentsRepository({ db });- const documentsStorageService = await createDocumentStorageService({ config: { documentsStorage: { driver: 'in-memory' } } as Config });- const plansRepository = createPlansRepository({ config: { organizationPlans: { isFreePlanUnlimited: true } } as Config });- const subscriptionsRepository = createSubscriptionsRepository({ db });- const trackingServices = createDummyTrackingServices();- const taggingRulesRepository = createTaggingRulesRepository({ db });- const tagsRepository = createTagsRepository({ db });- const webhookRepository = createWebhookRepository({ db });- const generateDocumentId = () => 'doc_1';+ const config = overrideConfig({+ organizationPlans: { isFreePlanUnlimited: true },+ documentsStorage: { driver: 'in-memory' },+ });+ const documentsStorageService = await createDocumentStorageService({ config });++ const createDocument = await createDocumentCreationUsecase({+ db,+ config,+ generateDocumentId: () => 'doc_1',+ documentsStorageService,+ });const file = new File(['content'], 'file.txt', { type: 'text/plain' });const userId = 'user-1';@@ -43,15 +42,6 @@ describe('documents usecases', () => {file,userId,organizationId,- documentsRepository,- documentsStorageService,- generateDocumentId,- plansRepository,- subscriptionsRepository,- trackingServices,- taggingRulesRepository,- tagsRepository,- webhookRepository,});expect(document).to.include({@@ -86,16 +76,20 @@ describe('documents usecases', () => {organizationMembers: [{ organizationId: 'organization-1', userId: 'user-1', role: ORGANIZATION_ROLES.OWNER }],});- const documentsRepository = createDocumentsRepository({ db });- const documentsStorageService = await createDocumentStorageService({ config: { documentsStorage: { driver: 'in-memory' } } as Config });- const plansRepository = createPlansRepository({ config: { organizationPlans: { isFreePlanUnlimited: true } } as Config });- const subscriptionsRepository = createSubscriptionsRepository({ db });- const trackingServices = createDummyTrackingServices();- const taggingRulesRepository = createTaggingRulesRepository({ db });- const tagsRepository = createTagsRepository({ db });- const webhookRepository = createWebhookRepository({ db });+ const config = overrideConfig({+ organizationPlans: { isFreePlanUnlimited: true },+ documentsStorage: { driver: 'in-memory' },+ });++ const documentsStorageService = await createDocumentStorageService({ config });+let documentIdIndex = 1;- const generateDocumentId = () => `doc_${documentIdIndex++}`;+ const createDocument = await createDocumentCreationUsecase({+ db,+ config,+ generateDocumentId: () => `doc_${documentIdIndex++}`,+ documentsStorageService,+ });const file = new File(['content'], 'file.txt', { type: 'text/plain' });const userId = 'user-1';@@ -105,15 +99,6 @@ describe('documents usecases', () => {file,userId,organizationId,- documentsRepository,- documentsStorageService,- plansRepository,- subscriptionsRepository,- generateDocumentId,- trackingServices,- taggingRulesRepository,- tagsRepository,- webhookRepository,});expect(document1).to.include({@@ -134,15 +119,6 @@ describe('documents usecases', () => {file,userId,organizationId,- documentsRepository,- documentsStorageService,- plansRepository,- subscriptionsRepository,- generateDocumentId,- trackingServices,- taggingRulesRepository,- tagsRepository,- webhookRepository,}),).rejects.toThrow(createDocumentAlreadyExistsError(),@@ -202,26 +178,20 @@ describe('documents usecases', () => {],});- const documentsRepository = createDocumentsRepository({ db });- const documentsStorageService = await createDocumentStorageService({ config: { documentsStorage: { driver: 'in-memory' } } as Config });- const plansRepository = createPlansRepository({ config: { organizationPlans: { isFreePlanUnlimited: true } } as Config });- const subscriptionsRepository = createSubscriptionsRepository({ db });- const trackingServices = createDummyTrackingServices();- const taggingRulesRepository = createTaggingRulesRepository({ db });- const tagsRepository = createTagsRepository({ db });- const webhookRepository = createWebhookRepository({ db });+ const config = overrideConfig({+ organizationPlans: { isFreePlanUnlimited: true },+ documentsStorage: { driver: 'in-memory' },+ });++ const createDocument = await createDocumentCreationUsecase({+ db,+ config,+ });+// 3. Re-create the documentconst { document: documentRestored } = await createDocument({file: new File(['hello world'], 'file-2.txt', { type: 'text/plain' }),organizationId: 'organization-1',- documentsRepository,- documentsStorageService,- plansRepository,- subscriptionsRepository,- trackingServices,- taggingRulesRepository,- tagsRepository,- webhookRepository,});expect(documentRestored).to.deep.include({@@ -255,15 +225,25 @@ describe('documents usecases', () => {organizationMembers: [{ organizationId: 'organization-1', userId: 'user-1', role: ORGANIZATION_ROLES.OWNER }],});+ const config = overrideConfig({+ organizationPlans: { isFreePlanUnlimited: true },+ documentsStorage: { driver: 'in-memory' },+ });+const documentsRepository = createDocumentsRepository({ db });- const documentsStorageService = await createDocumentStorageService({ config: { documentsStorage: { driver: 'in-memory' } } as Config });- const plansRepository = createPlansRepository({ config: { organizationPlans: { isFreePlanUnlimited: true } } as Config });- const subscriptionsRepository = createSubscriptionsRepository({ db });- const trackingServices = createDummyTrackingServices();- const taggingRulesRepository = createTaggingRulesRepository({ db });- const tagsRepository = createTagsRepository({ db });- const webhookRepository = createWebhookRepository({ db });- const generateDocumentId = () => 'doc_1';+ const documentsStorageService = await createDocumentStorageService({ config });++ const createDocument = await createDocumentCreationUsecase({+ db,+ config,+ generateDocumentId: () => 'doc_1',+ documentsRepository: {+ ...documentsRepository,+ saveOrganizationDocument: async () => {+ throw new Error('Macron, explosion!');+ },+ },+ });const file = new File(['content'], 'file.txt', { type: 'text/plain' });const userId = 'user-1';@@ -274,20 +254,6 @@ describe('documents usecases', () => {file,userId,organizationId,- documentsRepository: {- ...documentsRepository,- saveOrganizationDocument: async () => {- throw new Error('Macron, explosion!');- },- },- documentsStorageService,- plansRepository,- subscriptionsRepository,- generateDocumentId,- trackingServices,- taggingRulesRepository,- tagsRepository,- webhookRepository,}),).rejects.toThrow(new Error('Macron, explosion!'));@@ -299,5 +265,56 @@ describe('documents usecases', () => {documentsStorageService.getFileStream({ storageKey: 'organization-1/originals/doc_1.txt' }),).rejects.toThrow('File not found');});++ test('when a document is created by a user, a document activity log is registered with the user id', async () => {+ const { db } = await createInMemoryDatabase({+ users: [{ id: 'user-1', email: '[email protected]' }],+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],+ organizationMembers: [{ organizationId: 'organization-1', userId: 'user-1', role: ORGANIZATION_ROLES.OWNER }],+ });++ const config = overrideConfig({+ organizationPlans: { isFreePlanUnlimited: true },+ documentsStorage: { driver: 'in-memory' },+ });++ let documentIdIndex = 1;+ const createDocument = await createDocumentCreationUsecase({+ db,+ config,+ generateDocumentId: () => `doc_${documentIdIndex++}`,+ });++ await createDocument({+ file: new File(['content-1'], 'file.txt', { type: 'text/plain' }),+ userId: 'user-1',+ organizationId: 'organization-1',+ });++ await createDocument({+ file: new File(['content-2'], 'file.txt', { type: 'text/plain' }),+ organizationId: 'organization-1',+ });++ await nextTick();++ const documentActivityLogRecords = await db.select().from(documentActivityLogTable);++ expect(documentActivityLogRecords.length).to.eql(2);++ expect(documentActivityLogRecords[0]).to.deep.include({+ event: 'created',+ eventData: null,+ userId: 'user-1',+ documentId: 'doc_1',+ });++ expect(documentActivityLogRecords[1]).to.deep.include({+ event: 'created',+ eventData: null,+ userId: null,+ documentId: 'doc_2',+ });+ });});});diff --git a/apps/papra-server/src/modules/documents/documents.usecases.ts b/apps/papra-server/src/modules/documents/documents.usecases.tsindex 6bc28a07..21876b71 100644--- a/apps/papra-server/src/modules/documents/documents.usecases.ts+++ b/apps/papra-server/src/modules/documents/documents.usecases.ts@@ -7,6 +7,7 @@ import type { TaggingRulesRepository } from '../tagging-rules/tagging-rules.repoimport type { TagsRepository } from '../tags/tags.repository';import type { TrackingServices } from '../tracking/tracking.services';import type { WebhookRepository } from '../webhooks/webhook.repository';+import type { DocumentActivityRepository } from './document-activity/document-activity.repository';import type { DocumentsRepository } from './documents.repository';import type { Document } from './documents.types';import type { DocumentStorageService } from './storage/documents.storage.services';@@ -23,6 +24,8 @@ import { createTagsRepository } from '../tags/tags.repository';import { createTrackingServices } from '../tracking/tracking.services';import { createWebhookRepository } from '../webhooks/webhook.repository';import { triggerWebhooks } from '../webhooks/webhook.usecases';+import { createDocumentActivityRepository } from './document-activity/document-activity.repository';+import { deferRegisterDocumentActivityLog } from './document-activity/document-activity.usecases';import { createDocumentAlreadyExistsError, createDocumentNotDeletedError, createDocumentNotFoundError } from './documents.errors';import { buildOriginalDocumentKey, generateDocumentId as generateDocumentIdImpl } from './documents.models';import { createDocumentsRepository } from './documents.repository';@@ -56,6 +59,7 @@ export async function createDocument({taggingRulesRepository,tagsRepository,webhookRepository,+ documentActivityRepository,logger = createLogger({ namespace: 'documents:usecases' }),}: {file: File;@@ -70,6 +74,7 @@ export async function createDocument({taggingRulesRepository: TaggingRulesRepository;tagsRepository: TagsRepository;webhookRepository: WebhookRepository;+ documentActivityRepository: DocumentActivityRepository;logger?: Logger;}) {const {@@ -115,6 +120,13 @@ export async function createDocument({logger,});+ deferRegisterDocumentActivityLog({+ documentId: document.id,+ event: 'created',+ userId,+ documentActivityRepository,+ });+await applyTaggingRules({ document, taggingRulesRepository, tagsRepository });await triggerWebhooks({@@ -134,38 +146,32 @@ export async function createDocument({}export type CreateDocumentUsecase = Awaited<ReturnType<typeof createDocumentCreationUsecase>>;+export type DocumentUsecaseDependencies = Omit<Parameters<typeof createDocument>[0], 'file' | 'userId' | 'organizationId'>;+export async function createDocumentCreationUsecase({db,config,- logger = createLogger({ namespace: 'documents:usecases' }),- generateDocumentId = generateDocumentIdImpl,- documentsStorageService,+ ...initialDeps}: {db: Database;config: Config;- logger?: Logger;- documentsStorageService?: DocumentStorageService;- generateDocumentId?: () => string;-}) {+} & Partial<DocumentUsecaseDependencies>) {const deps = {- documentsRepository: createDocumentsRepository({ db }),- documentsStorageService: documentsStorageService ?? await createDocumentStorageService({ config }),- plansRepository: createPlansRepository({ config }),- subscriptionsRepository: createSubscriptionsRepository({ db }),- trackingServices: createTrackingServices({ config }),- taggingRulesRepository: createTaggingRulesRepository({ db }),- tagsRepository: createTagsRepository({ db }),- webhookRepository: createWebhookRepository({ db }),- generateDocumentId,- logger,+ documentsRepository: initialDeps.documentsRepository ?? createDocumentsRepository({ db }),+ documentsStorageService: initialDeps.documentsStorageService ?? await createDocumentStorageService({ config }),+ plansRepository: initialDeps.plansRepository ?? createPlansRepository({ config }),+ subscriptionsRepository: initialDeps.subscriptionsRepository ?? createSubscriptionsRepository({ db }),+ trackingServices: initialDeps.trackingServices ?? createTrackingServices({ config }),+ taggingRulesRepository: initialDeps.taggingRulesRepository ?? createTaggingRulesRepository({ db }),+ tagsRepository: initialDeps.tagsRepository ?? createTagsRepository({ db }),+ webhookRepository: initialDeps.webhookRepository ?? createWebhookRepository({ db }),+ documentActivityRepository: initialDeps.documentActivityRepository ?? createDocumentActivityRepository({ db }),++ generateDocumentId: initialDeps.generateDocumentId,+ logger: initialDeps.logger,};- return async ({ file, userId, organizationId }: { file: File; userId?: string; organizationId: string }) => createDocument({- file,- userId,- organizationId,- ...deps,- });+ return async (args: { file: File; userId?: string; organizationId: string }) => createDocument({ ...args, ...deps });}async function handleExistingDocument({diff --git a/apps/papra-server/src/modules/intake-emails/intake-emails.routes.ts b/apps/papra-server/src/modules/intake-emails/intake-emails.routes.tsindex f9df4841..5d9869af 100644--- a/apps/papra-server/src/modules/intake-emails/intake-emails.routes.ts+++ b/apps/papra-server/src/modules/intake-emails/intake-emails.routes.ts@@ -4,8 +4,7 @@ import { z } from 'zod';import { createUnauthorizedError } from '../app/auth/auth.errors';import { requireAuthentication } from '../app/auth/auth.middleware';import { getUser } from '../app/auth/auth.models';-import { createDocumentsRepository } from '../documents/documents.repository';-import { createDocumentStorageService } from '../documents/storage/documents.storage.services';+import { createDocumentCreationUsecase } from '../documents/documents.usecases';import { organizationIdSchema } from '../organizations/organization.schemas';import { createOrganizationsRepository } from '../organizations/organizations.repository';import { ensureUserIsInOrganization } from '../organizations/organizations.usecases';@@ -15,9 +14,6 @@ import { getHeader } from '../shared/headers/headers.models';import { createLogger } from '../shared/logger/logger';import { validateFormData, validateJsonBody, validateParams } from '../shared/validation/validation';import { createSubscriptionsRepository } from '../subscriptions/subscriptions.repository';-import { createTaggingRulesRepository } from '../tagging-rules/tagging-rules.repository';-import { createTagsRepository } from '../tags/tags.repository';-import { createWebhookRepository } from '../webhooks/webhook.repository';import { INTAKE_EMAILS_INGEST_ROUTE } from './intake-emails.constants';import { createIntakeEmailsRepository } from './intake-emails.repository';import { intakeEmailIdSchema, intakeEmailsIngestionMetaSchema, parseJson } from './intake-emails.schemas';@@ -191,27 +187,19 @@ function setupIngestIntakeEmailRoute({ app, db, config, trackingServices }: Rout}const intakeEmailsRepository = createIntakeEmailsRepository({ db });- const documentsRepository = createDocumentsRepository({ db });- const documentsStorageService = await createDocumentStorageService({ config });- const plansRepository = createPlansRepository({ config });- const subscriptionsRepository = createSubscriptionsRepository({ db });- const taggingRulesRepository = createTaggingRulesRepository({ db });- const tagsRepository = createTagsRepository({ db });- const webhookRepository = createWebhookRepository({ db });++ const createDocument = await createDocumentCreationUsecase({+ db,+ config,+ trackingServices,+ });await processIntakeEmailIngestion({fromAddress: email.from.address,recipientsAddresses: email.to.map(({ address }) => address),attachments,intakeEmailsRepository,- documentsRepository,- documentsStorageService,- plansRepository,- subscriptionsRepository,- trackingServices,- taggingRulesRepository,- tagsRepository,- webhookRepository,+ createDocument,});return context.body(null, 202);diff --git a/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.test.ts b/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.test.tsindex 205c67cf..1eabf67c 100644--- a/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.test.ts+++ b/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.test.ts@@ -1,21 +1,15 @@-import type { Config } from '../config/config.types';import type { PlansRepository } from '../plans/plans.repository';import { createInMemoryLoggerTransport } from '@crowlog/logger';import { asc } from 'drizzle-orm';import { pick } from 'lodash-es';import { describe, expect, test } from 'vitest';import { createInMemoryDatabase } from '../app/database/database.test-utils';-import { createDocumentsRepository } from '../documents/documents.repository';+import { overrideConfig } from '../config/config.test-utils';import { documentsTable } from '../documents/documents.table';-import { createDocumentStorageService } from '../documents/storage/documents.storage.services';+import { createDocumentCreationUsecase } from '../documents/documents.usecases';import { PLUS_PLAN_ID } from '../plans/plans.constants';-import { createPlansRepository } from '../plans/plans.repository';import { createLogger } from '../shared/logger/logger';import { createSubscriptionsRepository } from '../subscriptions/subscriptions.repository';-import { createTaggingRulesRepository } from '../tagging-rules/tagging-rules.repository';-import { createTagsRepository } from '../tags/tags.repository';-import { createDummyTrackingServices } from '../tracking/tracking.services';-import { createWebhookRepository } from '../webhooks/webhook.repository';import { createIntakeEmailLimitReachedError } from './intake-emails.errors';import { createIntakeEmailsRepository } from './intake-emails.repository';import { intakeEmailsTable } from './intake-emails.tables';@@ -31,14 +25,14 @@ describe('intake-emails usecases', () => {});const intakeEmailsRepository = createIntakeEmailsRepository({ db });- const documentsRepository = createDocumentsRepository({ db });- const documentsStorageService = await createDocumentStorageService({ config: { documentsStorage: { driver: 'in-memory' } } as Config });- const plansRepository = createPlansRepository({ config: { organizationPlans: { isFreePlanUnlimited: true } } as Config });- const subscriptionsRepository = createSubscriptionsRepository({ db });- const trackingServices = createDummyTrackingServices();- const taggingRulesRepository = createTaggingRulesRepository({ db });- const tagsRepository = createTagsRepository({ db });- const webhookRepository = createWebhookRepository({ db });++ const createDocument = await createDocumentCreationUsecase({+ db,+ config: overrideConfig({+ documentsStorage: { driver: 'in-memory' },+ organizationPlans: { isFreePlanUnlimited: true },+ }),+ });await ingestEmailForRecipient({fromAddress: '[email protected]',@@ -48,14 +42,7 @@ describe('intake-emails usecases', () => {new File(['content2'], 'file2.txt', { type: 'text/plain' }),],intakeEmailsRepository,- documentsRepository,- documentsStorageService,- plansRepository,- subscriptionsRepository,- trackingServices,- taggingRulesRepository,- tagsRepository,- webhookRepository,+ createDocument,});const documents = await db.select().from(documentsTable).orderBy(asc(documentsTable.name));@@ -78,29 +65,22 @@ describe('intake-emails usecases', () => {});const intakeEmailsRepository = createIntakeEmailsRepository({ db });- const documentsRepository = createDocumentsRepository({ db });- const documentsStorageService = await createDocumentStorageService({ config: { documentsStorage: { driver: 'in-memory' } } as Config });- const plansRepository = createPlansRepository({ config: { organizationPlans: { isFreePlanUnlimited: true } } as Config });- const subscriptionsRepository = createSubscriptionsRepository({ db });- const trackingServices = createDummyTrackingServices();- const taggingRulesRepository = createTaggingRulesRepository({ db });- const tagsRepository = createTagsRepository({ db });- const webhookRepository = createWebhookRepository({ db });++ const createDocument = await createDocumentCreationUsecase({+ db,+ config: overrideConfig({+ documentsStorage: { driver: 'in-memory' },+ organizationPlans: { isFreePlanUnlimited: true },+ }),+ });await ingestEmailForRecipient({fromAddress: '[email protected]',recipientAddress: '[email protected]',attachments: [new File(['content'], 'file.txt', { type: 'text/plain' })],intakeEmailsRepository,- documentsRepository,- documentsStorageService,- plansRepository,- subscriptionsRepository,- trackingServices,+ createDocument,logger,- taggingRulesRepository,- tagsRepository,- webhookRepository,});expect(loggerTransport.getLogs({ excludeTimestampMs: true })).to.eql([@@ -116,29 +96,22 @@ describe('intake-emails usecases', () => {const { db } = await createInMemoryDatabase();const intakeEmailsRepository = createIntakeEmailsRepository({ db });- const documentsRepository = createDocumentsRepository({ db });- const documentsStorageService = await createDocumentStorageService({ config: { documentsStorage: { driver: 'in-memory' } } as Config });- const plansRepository = createPlansRepository({ config: { organizationPlans: { isFreePlanUnlimited: true } } as Config });- const subscriptionsRepository = createSubscriptionsRepository({ db });- const trackingServices = createDummyTrackingServices();- const taggingRulesRepository = createTaggingRulesRepository({ db });- const tagsRepository = createTagsRepository({ db });- const webhookRepository = createWebhookRepository({ db });++ const createDocument = await createDocumentCreationUsecase({+ db,+ config: overrideConfig({+ documentsStorage: { driver: 'in-memory' },+ organizationPlans: { isFreePlanUnlimited: true },+ }),+ });await ingestEmailForRecipient({fromAddress: '[email protected]',recipientAddress: '[email protected]',attachments: [new File(['content'], 'file.txt', { type: 'text/plain' })],intakeEmailsRepository,- documentsRepository,- documentsStorageService,- plansRepository,- subscriptionsRepository,- trackingServices,- taggingRulesRepository,- tagsRepository,+ createDocument,logger,- webhookRepository,});expect(loggerTransport.getLogs({ excludeTimestampMs: true })).to.eql([@@ -159,29 +132,22 @@ describe('intake-emails usecases', () => {});const intakeEmailsRepository = createIntakeEmailsRepository({ db });- const documentsRepository = createDocumentsRepository({ db });- const documentsStorageService = await createDocumentStorageService({ config: { documentsStorage: { driver: 'in-memory' } } as Config });- const plansRepository = createPlansRepository({ config: { organizationPlans: { isFreePlanUnlimited: true } } as Config });- const subscriptionsRepository = createSubscriptionsRepository({ db });- const trackingServices = createDummyTrackingServices();- const taggingRulesRepository = createTaggingRulesRepository({ db });- const tagsRepository = createTagsRepository({ db });- const webhookRepository = createWebhookRepository({ db });++ const createDocument = await createDocumentCreationUsecase({+ db,+ config: overrideConfig({+ documentsStorage: { driver: 'in-memory' },+ organizationPlans: { isFreePlanUnlimited: true },+ }),+ });await ingestEmailForRecipient({fromAddress: '[email protected]',recipientAddress: '[email protected]',attachments: [new File(['content'], 'file.txt', { type: 'text/plain' })],intakeEmailsRepository,- documentsRepository,- documentsStorageService,- plansRepository,- subscriptionsRepository,- trackingServices,- taggingRulesRepository,- tagsRepository,+ createDocument,logger,- webhookRepository,});expect(loggerTransport.getLogs({ excludeTimestampMs: true })).to.eql([@@ -213,14 +179,14 @@ describe('intake-emails usecases', () => {});const intakeEmailsRepository = createIntakeEmailsRepository({ db });- const documentsRepository = createDocumentsRepository({ db });- const documentsStorageService = await createDocumentStorageService({ config: { documentsStorage: { driver: 'in-memory' } } as Config });- const plansRepository = createPlansRepository({ config: { organizationPlans: { isFreePlanUnlimited: true } } as Config });- const subscriptionsRepository = createSubscriptionsRepository({ db });- const trackingServices = createDummyTrackingServices();- const taggingRulesRepository = createTaggingRulesRepository({ db });- const tagsRepository = createTagsRepository({ db });- const webhookRepository = createWebhookRepository({ db });++ const createDocument = await createDocumentCreationUsecase({+ db,+ config: overrideConfig({+ documentsStorage: { driver: 'in-memory' },+ organizationPlans: { isFreePlanUnlimited: true },+ }),+ });await processIntakeEmailIngestion({fromAddress: '[email protected]',@@ -229,14 +195,7 @@ describe('intake-emails usecases', () => {new File(['content1'], 'file1.txt', { type: 'text/plain' }),],intakeEmailsRepository,- documentsRepository,- documentsStorageService,- plansRepository,- subscriptionsRepository,- trackingServices,- taggingRulesRepository,- tagsRepository,- webhookRepository,+ createDocument,});const documents = await db.select().from(documentsTable).orderBy(asc(documentsTable.organizationId));diff --git a/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.ts b/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.tsindex c68a0849..f6b324fd 100644--- a/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.ts+++ b/apps/papra-server/src/modules/intake-emails/intake-emails.usecases.ts@@ -1,16 +1,10 @@-import type { DocumentsRepository } from '../documents/documents.repository';-import type { DocumentStorageService } from '../documents/storage/documents.storage.services';+import type { CreateDocumentUsecase } from '../documents/documents.usecases';import type { PlansRepository } from '../plans/plans.repository';import type { Logger } from '../shared/logger/logger';import type { SubscriptionsRepository } from '../subscriptions/subscriptions.repository';-import type { TaggingRulesRepository } from '../tagging-rules/tagging-rules.repository';-import type { TagsRepository } from '../tags/tags.repository';-import type { TrackingServices } from '../tracking/tracking.services';-import type { WebhookRepository } from '../webhooks/webhook.repository';import type { IntakeEmailsServices } from './drivers/intake-emails.drivers.models';import type { IntakeEmailsRepository } from './intake-emails.repository';import { safely } from '@corentinth/chisels';-import { createDocument } from '../documents/documents.usecases';import { getOrganizationPlan } from '../plans/plans.usecases';import { addLogContext, createLogger } from '../shared/logger/logger';import { createIntakeEmailLimitReachedError, createIntakeEmailNotFoundError } from './intake-emails.errors';@@ -48,27 +42,13 @@ export function processIntakeEmailIngestion({recipientsAddresses,attachments,intakeEmailsRepository,- documentsRepository,- documentsStorageService,- plansRepository,- subscriptionsRepository,- trackingServices,- taggingRulesRepository,- tagsRepository,- webhookRepository,+ createDocument,}: {fromAddress: string;recipientsAddresses: string[];attachments: File[];intakeEmailsRepository: IntakeEmailsRepository;- documentsRepository: DocumentsRepository;- documentsStorageService: DocumentStorageService;- plansRepository: PlansRepository;- subscriptionsRepository: SubscriptionsRepository;- trackingServices: TrackingServices;- taggingRulesRepository: TaggingRulesRepository;- tagsRepository: TagsRepository;- webhookRepository: WebhookRepository;+ createDocument: CreateDocumentUsecase;}) {return Promise.all(recipientsAddresses.map(recipientAddress => safely(@@ -77,14 +57,7 @@ export function processIntakeEmailIngestion({recipientAddress,attachments,intakeEmailsRepository,- documentsRepository,- documentsStorageService,- plansRepository,- subscriptionsRepository,- trackingServices,- taggingRulesRepository,- tagsRepository,- webhookRepository,+ createDocument,}),)),);@@ -95,29 +68,15 @@ export async function ingestEmailForRecipient({recipientAddress,attachments,intakeEmailsRepository,- documentsRepository,- documentsStorageService,logger = createLogger({ namespace: 'intake-emails.ingest' }),- plansRepository,- trackingServices,- subscriptionsRepository,- taggingRulesRepository,- tagsRepository,- webhookRepository,+ createDocument,}: {fromAddress: string;recipientAddress: string;attachments: File[];intakeEmailsRepository: IntakeEmailsRepository;- documentsRepository: DocumentsRepository;- documentsStorageService: DocumentStorageService;- plansRepository: PlansRepository;- subscriptionsRepository: SubscriptionsRepository;- trackingServices: TrackingServices;- taggingRulesRepository: TaggingRulesRepository;- tagsRepository: TagsRepository;- webhookRepository: WebhookRepository;logger?: Logger;+ createDocument: CreateDocumentUsecase;}) {const { intakeEmail } = await intakeEmailsRepository.getIntakeEmailByEmailAddress({ emailAddress: recipientAddress });@@ -150,14 +109,6 @@ export async function ingestEmailForRecipient({const [result, error] = await safely(createDocument({file,organizationId: intakeEmail.organizationId,- documentsStorageService,- documentsRepository,- plansRepository,- subscriptionsRepository,- trackingServices,- taggingRulesRepository,- tagsRepository,- webhookRepository,}));if (error) {diff --git a/apps/papra-server/src/modules/shared/async/defer.test-utils.ts b/apps/papra-server/src/modules/shared/async/defer.test-utils.tsnew file mode 100644index 00000000..80a52075--- /dev/null+++ b/apps/papra-server/src/modules/shared/async/defer.test-utils.ts@@ -0,0 +1 @@+export const nextTick = () => new Promise(resolve => setImmediate(resolve));diff --git a/apps/papra-server/src/modules/shared/async/defer.test.ts b/apps/papra-server/src/modules/shared/async/defer.test.tsnew file mode 100644index 00000000..d24cbb1a--- /dev/null+++ b/apps/papra-server/src/modules/shared/async/defer.test.ts@@ -0,0 +1,47 @@+import { describe, expect, test } from 'vitest';+import { createTestLogger } from '../logger/logger.test-utils';+import { safelyDefer } from './defer';+import { nextTick } from './defer.test-utils';++describe('defer', () => {+ describe('safelyDefer', () => {+ test('execute a function in the next tick in order to avoid blocking the event loop', async () => {+ let called = false;++ safelyDefer(async () => {+ called = true;+ });++ expect(called).to.equal(false);++ await nextTick();++ expect(called).to.equal(true);+ });++ test('if the function throws an error, the error is logged', async () => {+ const { logger, getLogs } = createTestLogger({ namespace: 'defer' });++ safelyDefer(async () => {+ throw new Error('test');+ }, { logger });++ expect(getLogs()).to.deep.equal([]);++ await nextTick();++ const logs = getLogs({ excludeTimestampMs: true });+ expect(logs.length).to.equal(1);++ expect(logs[0]).to.deep.include({++ level: 'error',+ message: 'Error in safelyDefer',+ namespace: 'defer',+ data: {+ error: new Error('test'),+ },+ });+ });+ });+});diff --git a/apps/papra-server/src/modules/shared/async/defer.ts b/apps/papra-server/src/modules/shared/async/defer.tsnew file mode 100644index 00000000..47ef8e5f--- /dev/null+++ b/apps/papra-server/src/modules/shared/async/defer.ts@@ -0,0 +1,17 @@+import type { Logger } from '../logger/logger';+import { safely } from '@corentinth/chisels';+import { createLogger } from '../logger/logger';++export function safelyDefer(fn: () => Promise<void>, { logger = createLogger({ namespace: 'defer' }) }: { logger?: Logger } = {}) {+ setImmediate(async () => {+ const [, error] = await safely(fn);++ if (error) {+ logger.error({ error }, 'Error in safelyDefer');+ }+ });+}++export function createDeferable<Args extends unknown[]>(fn: (...args: Args) => Promise<void>) {+ return (...args: Args) => safelyDefer(() => fn(...args));+}diff --git a/apps/papra-server/src/modules/tags/tags.routes.ts b/apps/papra-server/src/modules/tags/tags.routes.tsindex e5fcdc56..d204c63e 100644--- a/apps/papra-server/src/modules/tags/tags.routes.ts+++ b/apps/papra-server/src/modules/tags/tags.routes.ts@@ -2,6 +2,8 @@ import type { RouteDefinitionContext } from '../app/server.types';import { z } from 'zod';import { requireAuthentication } from '../app/auth/auth.middleware';import { getUser } from '../app/auth/auth.models';+import { createDocumentActivityRepository } from '../documents/document-activity/document-activity.repository';+import { deferRegisterDocumentActivityLog } from '../documents/document-activity/document-activity.usecases';import { documentIdSchema } from '../documents/documents.schemas';import { organizationIdSchema } from '../organizations/organization.schemas';import { createOrganizationsRepository } from '../organizations/organizations.repository';@@ -158,11 +160,20 @@ function setupAddTagToDocumentRoute({ app, db }: RouteDefinitionContext) {const tagsRepository = createTagsRepository({ db });const organizationsRepository = createOrganizationsRepository({ db });+ const documentActivityRepository = createDocumentActivityRepository({ db });await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });await tagsRepository.addTagToDocument({ tagId, documentId });+ deferRegisterDocumentActivityLog({+ documentId,+ event: 'tagged',+ userId,+ documentActivityRepository,+ tagId,+ });+return context.body(null, 204);},);@@ -185,11 +196,20 @@ function setupRemoveTagFromDocumentRoute({ app, db }: RouteDefinitionContext) {const tagsRepository = createTagsRepository({ db });const organizationsRepository = createOrganizationsRepository({ db });+ const documentActivityRepository = createDocumentActivityRepository({ db });await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });await tagsRepository.removeTagFromDocument({ tagId, documentId });+ deferRegisterDocumentActivityLog({+ documentId,+ event: 'untagged',+ userId,+ documentActivityRepository,+ tagId,+ });+return context.body(null, 204);},);