Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

feat(organizations): auto tagging settings management (#1201)

Corentin Thomasset167fb8ca2535
diff --git a/.changeset/purple-pens-visit.md b/.changeset/purple-pens-visit.md
new file mode 100644
index 00000000..0cb0eb0a
--- /dev/null
+++ b/.changeset/purple-pens-visit.md
@@ -0,0 +1,9 @@
+---
+'@papra/app': patch
+---
+
+Auto tagging can be configured per organization, with a dedicated page in organization settings. Owners can manage the following settings:
+
+- Enable or disable auto tagging for their organization.
+- Enable the creation of new tags if relevant tags do not exist.
+- Configure the maximum number of tags that can be automatically added to a document.
diff --git a/apps/papra-client/src/locales/en.dictionary.ts b/apps/papra-client/src/locales/en.dictionary.ts
index 12605983..1b246bc8 100644
--- a/apps/papra-client/src/locales/en.dictionary.ts
+++ b/apps/papra-client/src/locales/en.dictionary.ts
@@ -261,6 +261,21 @@ export const translations = {
'organization.settings.delete.has-active-subscription':
'Cannot delete organization with an active subscription, please cancel your subscription above first.',
+ 'organization.settings.auto-tagging.page.title': 'Auto Tagging Settings',
+ 'organization.settings.auto-tagging.page.description':
+ 'Auto tagging settings for your organization. This feature allows you to automatically tag content based on AI predictions.',
+ 'organization.settings.auto-tagging.unavailable':
+ 'Auto tagging is currently not available for your organization. Please contact support for more information.',
+ 'organization.settings.auto-tagging.enabled.label': 'Enable auto tagging',
+ 'organization.settings.auto-tagging.enabled.description':
+ 'When enabled, documents added to this organization are automatically tagged by the AI.',
+ 'organization.settings.auto-tagging.create-tags.label': 'Allow creating new tags',
+ 'organization.settings.auto-tagging.create-tags.description':
+ 'When enabled, the AI can create new tags. Otherwise, it can only use existing ones.',
+ 'organization.settings.auto-tagging.max-tags.label': 'Maximum tags per document',
+ 'organization.settings.auto-tagging.max-tags.description':
+ 'The most tags the AI can apply to a single document (between {{ min }} and {{ max }}).',
+
'organization.usage.page.title': 'Usage',
'organization.usage.page.description': "View your organization's current usage and limits.",
'organization.usage.storage.title': 'Document storage',
@@ -1005,6 +1020,7 @@ export const translations = {
'layout.menu.settings': 'Settings',
'layout.menu.account': 'Account',
'layout.menu.general-settings': 'General settings',
+ 'layout.menu.auto-tagging': 'Auto tagging',
'layout.menu.usage': 'Usage',
'layout.menu.intake-emails': 'Intake emails',
'layout.menu.webhooks': 'Webhooks',
diff --git a/apps/papra-client/src/modules/config/config.ts b/apps/papra-client/src/modules/config/config.ts
index 1a18eef8..f112d658 100644
--- a/apps/papra-client/src/modules/config/config.ts
+++ b/apps/papra-client/src/modules/config/config.ts
@@ -74,6 +74,9 @@ export const buildTimeConfig = {
isEnabled: asBoolean(import.meta.env.VITE_INTAKE_EMAILS_IS_ENABLED, false),
},
isSubscriptionsEnabled: asBoolean(import.meta.env.VITE_IS_SUBSCRIPTIONS_ENABLED, false),
+ autoTagging: {
+ isEnabled: false,
+ },
} as const;
export type Config = typeof buildTimeConfig;
@@ -86,4 +89,5 @@ export type RuntimePublicConfig = Pick<
| 'documents'
| 'intakeEmails'
| 'organizations'
+ | 'autoTagging'
>;
diff --git a/apps/papra-client/src/modules/organizations/organizations.queries.ts b/apps/papra-client/src/modules/organizations/organizations.queries.ts
new file mode 100644
index 00000000..fc4d4f56
--- /dev/null
+++ b/apps/papra-client/src/modules/organizations/organizations.queries.ts
@@ -0,0 +1,12 @@
+import { queryOptions } from '@tanstack/solid-query';
+import { fetchOrganizationSettings } from './organizations.services';
+
+export const getOrganizationSettingsQueryOptions = ({
+ organizationId,
+}: {
+ organizationId: string;
+}) =>
+ queryOptions({
+ queryKey: ['organizations', organizationId, 'settings'],
+ queryFn: async () => fetchOrganizationSettings({ organizationId }),
+ });
diff --git a/apps/papra-client/src/modules/organizations/organizations.services.ts b/apps/papra-client/src/modules/organizations/organizations.services.ts
index e252e19b..1c1ba64d 100644
--- a/apps/papra-client/src/modules/organizations/organizations.services.ts
+++ b/apps/papra-client/src/modules/organizations/organizations.services.ts
@@ -166,3 +166,46 @@ export async function restoreOrganization({ organizationId }: { organizationId:
method: 'POST',
});
}
+
+export async function fetchOrganizationSettings({ organizationId }: { organizationId: string }) {
+ const { organizationSettings } = await apiClient<{
+ organizationSettings: {
+ ai: {
+ autoTagging: {
+ isEnabled: boolean;
+ canCreateNewTags: boolean;
+ maxTags: number;
+ };
+ };
+ };
+ }>({
+ path: `/api/organizations/${organizationId}/settings`,
+ method: 'GET',
+ });
+
+ return {
+ organizationSettings,
+ };
+}
+
+export async function updateOrganizationSettings({
+ organizationId,
+ organizationSettingsPartials,
+}: {
+ organizationId: string;
+ organizationSettingsPartials: {
+ ai?: {
+ autoTagging?: {
+ isEnabled?: boolean;
+ canCreateNewTags?: boolean;
+ maxTags?: number;
+ };
+ };
+ };
+}) {
+ await apiClient<void>({
+ path: `/api/organizations/${organizationId}/settings`,
+ method: 'PATCH',
+ body: organizationSettingsPartials,
+ });
+}
diff --git a/apps/papra-client/src/modules/organizations/pages/organizations-auto-tagging-settings.page.tsx b/apps/papra-client/src/modules/organizations/pages/organizations-auto-tagging-settings.page.tsx
new file mode 100644
index 00000000..124c6967
--- /dev/null
+++ b/apps/papra-client/src/modules/organizations/pages/organizations-auto-tagging-settings.page.tsx
@@ -0,0 +1,209 @@
+import type { Component } from 'solid-js';
+import { safely } from '@corentinth/chisels';
+import { useParams } from '@solidjs/router';
+import { useQuery, useQueryClient } from '@tanstack/solid-query';
+import { createEffect, createSignal, Show, Suspense } from 'solid-js';
+import { useI18n } from '@/modules/i18n/i18n.provider';
+import { useI18nApiErrors } from '@/modules/shared/http/composables/i18n-api-errors';
+import { Card, CardContent } from '@/modules/ui/components/card';
+import {
+ NumberField,
+ NumberFieldDecrementTrigger,
+ NumberFieldDescription,
+ NumberFieldGroup,
+ NumberFieldIncrementTrigger,
+ NumberFieldInput,
+ NumberFieldLabel,
+} from '@/modules/ui/components/number-field';
+import { createToast } from '@/modules/ui/components/sonner';
+import {
+ Switch,
+ SwitchControl,
+ SwitchDescription,
+ SwitchLabel,
+ SwitchThumb,
+} from '@/modules/ui/components/switch';
+import { getOrganizationSettingsQueryOptions } from '../organizations.queries';
+import { updateOrganizationSettings } from '../organizations.services';
+import { textfieldLabel } from '@/modules/ui/components/textfield';
+import { useConfig } from '@/modules/config/config.provider';
+
+const MIN_MAX_TAGS = 1;
+const MAX_MAX_TAGS = 100;
+
+type AutoTaggingSettings = {
+ isEnabled: boolean;
+ canCreateNewTags: boolean;
+ maxTags: number;
+};
+
+const AutoTaggingSettingsCard: Component<{
+ organizationId: string;
+ settings: AutoTaggingSettings;
+}> = (props) => {
+ const queryClient = useQueryClient();
+ const { getErrorMessage } = useI18nApiErrors();
+ const { t } = useI18n();
+
+ const [getMaxTags, setMaxTags] = createSignal(props.settings.maxTags);
+
+ // Keep the local max tags input in sync with the latest fetched settings.
+ createEffect(() => {
+ setMaxTags(props.settings.maxTags);
+ });
+
+ const updateSettings = async (autoTagging: Partial<AutoTaggingSettings>) => {
+ const [, error] = await safely(
+ updateOrganizationSettings({
+ organizationId: props.organizationId,
+ organizationSettingsPartials: { ai: { autoTagging } },
+ }),
+ );
+
+ if (error) {
+ createToast({ type: 'error', message: getErrorMessage({ error }) });
+ return;
+ }
+
+ await queryClient.invalidateQueries(
+ getOrganizationSettingsQueryOptions({ organizationId: props.organizationId }),
+ );
+ };
+
+ const commitMaxTags = async () => {
+ const clamped = Math.min(Math.max(Math.round(getMaxTags()), MIN_MAX_TAGS), MAX_MAX_TAGS);
+
+ if (clamped === props.settings.maxTags) {
+ setMaxTags(clamped);
+ return;
+ }
+
+ setMaxTags(clamped);
+ await updateSettings({ maxTags: clamped });
+ };
+
+ return (
+ <Card>
+ <CardContent class="pt-6 flex flex-col gap-6">
+ <Switch
+ class="flex items-center justify-between gap-4"
+ checked={props.settings.isEnabled}
+ onChange={(isEnabled) => updateSettings({ isEnabled })}
+ >
+ <div class="flex flex-col gap-0.5">
+ <SwitchLabel class={textfieldLabel({ label: true })}>
+ {t('organization.settings.auto-tagging.enabled.label')}
+ </SwitchLabel>
+ <SwitchDescription class={textfieldLabel({ label: false, description: true })}>
+ {t('organization.settings.auto-tagging.enabled.description')}
+ </SwitchDescription>
+ </div>
+ <SwitchControl>
+ <SwitchThumb />
+ </SwitchControl>
+ </Switch>
+
+ <hr />
+
+ <Switch
+ class="flex items-center justify-between gap-4"
+ checked={props.settings.canCreateNewTags}
+ onChange={(canCreateNewTags) => updateSettings({ canCreateNewTags })}
+ disabled={!props.settings.isEnabled}
+ >
+ <div class="flex flex-col gap-0.5">
+ <SwitchLabel class={textfieldLabel({ label: true })}>
+ {t('organization.settings.auto-tagging.create-tags.label')}
+ </SwitchLabel>
+ <SwitchDescription class={textfieldLabel({ label: false, description: true })}>
+ {t('organization.settings.auto-tagging.create-tags.description')}
+ </SwitchDescription>
+ </div>
+ <SwitchControl>
+ <SwitchThumb />
+ </SwitchControl>
+ </Switch>
+
+ <NumberField
+ class="flex items-center justify-between gap-4"
+ rawValue={getMaxTags()}
+ onRawValueChange={setMaxTags}
+ onChange={() => commitMaxTags()}
+ minValue={MIN_MAX_TAGS}
+ maxValue={MAX_MAX_TAGS}
+ step={1}
+ disabled={!props.settings.isEnabled}
+ >
+ <div class="flex flex-col gap-0.5">
+ <NumberFieldLabel>
+ {t('organization.settings.auto-tagging.max-tags.label')}
+ </NumberFieldLabel>
+ <NumberFieldDescription>
+ {t('organization.settings.auto-tagging.max-tags.description', {
+ min: MIN_MAX_TAGS,
+ max: MAX_MAX_TAGS,
+ })}
+ </NumberFieldDescription>
+ </div>
+
+ <NumberFieldGroup class="max-w-150px w-full">
+ <NumberFieldInput />
+ <NumberFieldIncrementTrigger />
+ <NumberFieldDecrementTrigger />
+ </NumberFieldGroup>
+ </NumberField>
+ </CardContent>
+ </Card>
+ );
+};
+
+export const OrganizationsAutoTaggingSettingsPage: Component = () => {
+ const params = useParams();
+ const { t } = useI18n();
+ const { config } = useConfig();
+
+ const organizationSettingsQuery = useQuery(() =>
+ getOrganizationSettingsQueryOptions({ organizationId: params.organizationId }),
+ );
+
+ const getIsAutoTaggingAvailableForOrganization = () => config.autoTagging.isEnabled;
+
+ return (
+ <div class="p-6 mt-10 pb-32 mx-auto max-w-screen-md w-full">
+ <Suspense>
+ <Show when={organizationSettingsQuery.data?.organizationSettings}>
+ {(getOrganizationSettings) => (
+ <>
+ <h1 class="text-xl font-semibold mb-2">
+ {t('organization.settings.auto-tagging.page.title')}
+ </h1>
+
+ <p class="text-muted-foreground">
+ {t('organization.settings.auto-tagging.page.description')}
+ </p>
+
+ <div class="mt-6 flex flex-col gap-6">
+ <Show
+ when={getIsAutoTaggingAvailableForOrganization()}
+ fallback={
+ <Card>
+ <CardContent class="pt-6 flex items-center gap-3 text-muted-foreground">
+ <div class="i-tabler-tag-off size-5 flex-shrink-0" />
+ <p class="text-sm">{t('organization.settings.auto-tagging.unavailable')}</p>
+ </CardContent>
+ </Card>
+ }
+ >
+ <AutoTaggingSettingsCard
+ organizationId={params.organizationId}
+ settings={getOrganizationSettings().ai.autoTagging}
+ />
+ </Show>
+ </div>
+ </>
+ )}
+ </Show>
+ </Suspense>
+ </div>
+ );
+};
diff --git a/apps/papra-client/src/modules/ui/layouts/organization-settings.layout.tsx b/apps/papra-client/src/modules/ui/layouts/organization-settings.layout.tsx
index 9df0c73b..6a8f94c8 100644
--- a/apps/papra-client/src/modules/ui/layouts/organization-settings.layout.tsx
+++ b/apps/papra-client/src/modules/ui/layouts/organization-settings.layout.tsx
@@ -16,6 +16,11 @@ export const OrganizationSettingsLayout: ParentComponent = (props) => {
href: `/organizations/${params.organizationId}/settings`,
icon: 'i-tabler-settings',
},
+ {
+ label: t('layout.menu.auto-tagging'),
+ href: `/organizations/${params.organizationId}/settings/auto-tagging`,
+ icon: 'i-tabler-tag',
+ },
{
label: t('layout.menu.usage'),
href: `/organizations/${params.organizationId}/settings/usage`,
diff --git a/apps/papra-client/src/routes.tsx b/apps/papra-client/src/routes.tsx
index 0d16a035..7d1a076d 100644
--- a/apps/papra-client/src/routes.tsx
+++ b/apps/papra-client/src/routes.tsx
@@ -53,6 +53,7 @@ import { UserSettingsPage } from './modules/users/pages/user-settings.page';
import { CreateWebhookPage } from './modules/webhooks/pages/create-webhook.page';
import { EditWebhookPage } from './modules/webhooks/pages/edit-webhook.page';
import { WebhooksPage } from './modules/webhooks/pages/webhooks.page';
+import { OrganizationsAutoTaggingSettingsPage } from './modules/organizations/pages/organizations-auto-tagging-settings.page';
export const routes: RouteDefinition[] = [
{
@@ -213,6 +214,10 @@ export const routes: RouteDefinition[] = [
path: '/',
component: OrganizationsSettingsPage,
},
+ {
+ path: '/auto-tagging',
+ component: OrganizationsAutoTaggingSettingsPage,
+ },
{
path: '/usage',
component: OrganizationUsagePage,
diff --git a/apps/papra-server/src/modules/ai/ai.config.ts b/apps/papra-server/src/modules/ai/ai.config.ts
index 2e30815b..521b1bae 100644
--- a/apps/papra-server/src/modules/ai/ai.config.ts
+++ b/apps/papra-server/src/modules/ai/ai.config.ts
@@ -5,7 +5,7 @@ import type { AppConfigDefinition } from '../config/config.types';
import { AI_DEFAULT_MODEL_ENV_KEY } from './ai.constants';
export const aiConfig = {
- aiIsEnabled: {
+ isEnabled: {
doc: 'Whether AI features are enabled',
schema: booleanishSchema,
env: 'AI_IS_ENABLED',
diff --git a/apps/papra-server/src/modules/app/server.routes.ts b/apps/papra-server/src/modules/app/server.routes.ts
index 0e631bca..53d26c1b 100644
--- a/apps/papra-server/src/modules/app/server.routes.ts
+++ b/apps/papra-server/src/modules/app/server.routes.ts
@@ -18,6 +18,7 @@ import { registerUsersRoutes } from '../users/users.routes';
import { registerWebhooksRoutes } from '../webhooks/webhooks.routes';
import { registerAuthRoutes } from './auth/auth.routes';
import { registerHealthCheckRoutes } from './health-check/health-check.routes';
+import { registerOrganizationSettingsRoutes } from '../organizations/organization-settings/organization-settings.routes';
export function registerRoutes(context: RouteDefinitionContext) {
registerAuthRoutes(context);
@@ -27,6 +28,7 @@ export function registerRoutes(context: RouteDefinitionContext) {
registerSubscriptionsRoutes(context);
registerUsersRoutes(context);
registerOrganizationsRoutes(context);
+ registerOrganizationSettingsRoutes(context);
registerDocumentsRoutes(context);
registerDocumentsBatchRoutes(context);
registerTagsRoutes(context);
diff --git a/apps/papra-server/src/modules/auto-tagging/auto-tagging.config.ts b/apps/papra-server/src/modules/auto-tagging/auto-tagging.config.ts
index d3806ce9..4f807716 100644
--- a/apps/papra-server/src/modules/auto-tagging/auto-tagging.config.ts
+++ b/apps/papra-server/src/modules/auto-tagging/auto-tagging.config.ts
@@ -3,8 +3,16 @@ import type { AppConfigDefinition } from '../config/config.types';
import { AI_DEFAULT_MODEL_ENV_KEY } from '../ai/ai.constants';
import { aiModelIdSchema } from '../ai/ai.schemas';
import { strictlyPositiveIntegerSchema } from '../shared/schemas/number.schemas';
+import { booleanishSchema } from '../config/config.schemas';
export const autoTaggingConfig = {
+ isEnabled: {
+ doc: 'Whether AI auto-tagging can be used in the application. Organization needs to enable it in their settings. Needs to enable global AI features too, with `AI_IS_ENABLED`.',
+ schema: booleanishSchema,
+ env: 'AUTO_TAGGING_ENABLED',
+ default: true,
+ showInDocumentation: false,
+ },
model: {
doc: 'Default AI model to use when no specific model is specified, the format is <adapterId>:<modelName>, e.g. "ollama:llama3.1:8b", where the <adapterId> is the id of the adapter defined in the AI_ADAPTERS env variable.',
schema: v.optional(aiModelIdSchema),
diff --git a/apps/papra-server/src/modules/auto-tagging/tasks/auto-tag-document.task.ts b/apps/papra-server/src/modules/auto-tagging/tasks/auto-tag-document.task.ts
index 52454be5..c9039981 100644
--- a/apps/papra-server/src/modules/auto-tagging/tasks/auto-tag-document.task.ts
+++ b/apps/papra-server/src/modules/auto-tagging/tasks/auto-tag-document.task.ts
@@ -22,7 +22,7 @@ export async function registerAutoTagDocumentTask({
config: Config;
eventServices: EventServices;
}) {
- if (!config.ai.aiIsEnabled) {
+ if (!config.ai.isEnabled || !config.autoTagging.isEnabled) {
return;
}
diff --git a/apps/papra-server/src/modules/config/config.models.test.ts b/apps/papra-server/src/modules/config/config.models.test.ts
index 38e5b89a..94e590c9 100644
--- a/apps/papra-server/src/modules/config/config.models.test.ts
+++ b/apps/papra-server/src/modules/config/config.models.test.ts
@@ -16,7 +16,7 @@ describe('config models', () => {
- intakeEmails.isEnabled Whether intake emails are enabled
- auth.providers.email.isEnabled Whether email/password authentication is enabled
- organizations.deletedOrganizationsPurgeDaysDelay The delay in days before a soft-deleted organization is permanently purged
-
+
Any other config should not be exposed.`, () => {
const config = overrideConfig({
foo: 'bar',
@@ -79,6 +79,9 @@ describe('config models', () => {
organizations: {
deletedOrganizationsPurgeDaysDelay: 30,
},
+ autoTagging: {
+ isEnabled: false,
+ },
},
});
});
diff --git a/apps/papra-server/src/modules/config/config.models.ts b/apps/papra-server/src/modules/config/config.models.ts
index 227caf50..ca68c5b2 100644
--- a/apps/papra-server/src/modules/config/config.models.ts
+++ b/apps/papra-server/src/modules/config/config.models.ts
@@ -30,6 +30,9 @@ export function getPublicConfig({ config }: { config: Config }) {
organizations: {
deletedOrganizationsPurgeDaysDelay: config.organizations.deletedOrganizationsPurgeDaysDelay,
},
+ autoTagging: {
+ isEnabled: config.autoTagging.isEnabled && config.ai.isEnabled,
+ },
};
return {
diff --git a/apps/papra-server/src/modules/documents/tasks/extract-document-file-content.task.ts b/apps/papra-server/src/modules/documents/tasks/extract-document-file-content.task.ts
index d1cdbf7d..8a2d12c3 100644
--- a/apps/papra-server/src/modules/documents/tasks/extract-document-file-content.task.ts
+++ b/apps/papra-server/src/modules/documents/tasks/extract-document-file-content.task.ts
@@ -48,7 +48,7 @@ export async function registerExtractDocumentFileContentTask({
eventServices,
});
- if (!config.ai.aiIsEnabled) {
+ if (!config.ai.isEnabled || !config.autoTagging.isEnabled) {
return;
}
diff --git a/apps/papra-server/src/modules/organizations/organization-settings/organization-settings.models.ts b/apps/papra-server/src/modules/organizations/organization-settings/organization-settings.models.ts
new file mode 100644
index 00000000..362b334d
--- /dev/null
+++ b/apps/papra-server/src/modules/organizations/organization-settings/organization-settings.models.ts
@@ -0,0 +1,18 @@
+import { pick } from '../../shared/objects';
+import type { OrganizationSettings } from './organization-settings.types';
+
+export function formatOrganizationSettingsForApiResponse({
+ organizationSettings,
+}: {
+ organizationSettings: OrganizationSettings;
+}) {
+ return {
+ ai: {
+ autoTagging: pick(organizationSettings.ai.autoTagging, [
+ 'isEnabled',
+ 'canCreateNewTags',
+ 'maxTags',
+ ]),
+ },
+ };
+}
diff --git a/apps/papra-server/src/modules/organizations/organization-settings/organization-settings.routes.ts b/apps/papra-server/src/modules/organizations/organization-settings/organization-settings.routes.ts
new file mode 100644
index 00000000..9fd4730c
--- /dev/null
+++ b/apps/papra-server/src/modules/organizations/organization-settings/organization-settings.routes.ts
@@ -0,0 +1,101 @@
+import { requireAuthentication } from '../../app/auth/auth.middleware';
+import type { RouteDefinitionContext } from '../../app/server.types';
+import { validateJsonBody, validateParams } from '../../shared/validation/validation';
+import * as v from 'valibot';
+import { organizationIdSchema } from '../organization.schemas';
+import { getUser } from '../../app/auth/auth.models';
+import { createOrganizationsRepository } from '../organizations.repository';
+import {
+ ensureUserIsInOrganization,
+ ensureUserIsOwnerOfOrganization,
+} from '../organizations.usecases';
+import { createOrganizationSettingsRepository } from './organization-settings.repository';
+import { resolveOrganizationSettings } from './organization-settings.usecases';
+import { formatOrganizationSettingsForApiResponse } from './organization-settings.models';
+
+export function registerOrganizationSettingsRoutes(context: RouteDefinitionContext) {
+ setupGetOrganizationSettingsRoute(context);
+ setupUpdateOrganizationSettingsRoute(context);
+}
+
+export function setupGetOrganizationSettingsRoute({ app, db, config }: RouteDefinitionContext) {
+ app.get(
+ '/api/organizations/:organizationId/settings',
+ requireAuthentication({ apiKeyPermissions: ['organizations:read'] }),
+ validateParams(
+ v.strictObject({
+ organizationId: organizationIdSchema,
+ }),
+ ),
+ async (context) => {
+ const { userId } = getUser({ context });
+ const { organizationId } = context.req.valid('param');
+
+ const organizationsRepository = createOrganizationsRepository({ db });
+ const organizationSettingsRepository = createOrganizationSettingsRepository({ db });
+
+ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });
+
+ const { organizationSettings } = await resolveOrganizationSettings({
+ organizationId,
+ organizationSettingsRepository,
+ config,
+ });
+
+ return context.json({
+ organizationSettings: formatOrganizationSettingsForApiResponse({ organizationSettings }),
+ });
+ },
+ );
+}
+
+export function setupUpdateOrganizationSettingsRoute({ app, db }: RouteDefinitionContext) {
+ app.patch(
+ '/api/organizations/:organizationId/settings',
+ requireAuthentication({ apiKeyPermissions: ['organizations:update'] }),
+ validateParams(
+ v.strictObject({
+ organizationId: organizationIdSchema,
+ }),
+ ),
+ validateJsonBody(
+ v.strictObject({
+ ai: v.optional(
+ v.strictObject({
+ autoTagging: v.optional(
+ v.strictObject({
+ isEnabled: v.optional(v.boolean()),
+ canCreateNewTags: v.optional(v.boolean()),
+ maxTags: v.optional(
+ v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(100)),
+ ),
+ }),
+ ),
+ }),
+ ),
+ }),
+ ),
+ async (context) => {
+ const { userId } = getUser({ context });
+ const { organizationId } = context.req.valid('param');
+ const organizationSettingsPartials = context.req.valid('json');
+
+ const organizationsRepository = createOrganizationsRepository({ db });
+ const organizationSettingsRepository = createOrganizationSettingsRepository({ db });
+
+ await ensureUserIsOwnerOfOrganization({ userId, organizationId, organizationsRepository });
+
+ await organizationSettingsRepository.createOrUpdateOrganizationSettings({
+ organizationId,
+ settings: {
+ aiAutoTaggingCanCreateNewTags:
+ organizationSettingsPartials.ai?.autoTagging?.canCreateNewTags,
+ aiAutoTaggingEnabled: organizationSettingsPartials.ai?.autoTagging?.isEnabled,
+ aiAutoTaggingMaxTags: organizationSettingsPartials.ai?.autoTagging?.maxTags,
+ },
+ });
+
+ return context.body(null, 204);
+ },
+ );
+}
diff --git a/apps/papra-server/src/modules/organizations/organization-settings/organization-settings.usecases.ts b/apps/papra-server/src/modules/organizations/organization-settings/organization-settings.usecases.ts
index 45c70659..3c9a5a57 100644
--- a/apps/papra-server/src/modules/organizations/organization-settings/organization-settings.usecases.ts
+++ b/apps/papra-server/src/modules/organizations/organization-settings/organization-settings.usecases.ts
@@ -20,30 +20,47 @@ export function createResolveOrganizationSettingsUsecase({
organizationId: string;
}): Promise<{
organizationSettings: OrganizationSettings;
- }> => {
- const { organizationRawSettings } =
- await organizationSettingsRepository.getOrganizationSettings({
- organizationId,
- });
-
- return {
- organizationSettings: {
- ai: {
- autoTagging: {
- isEnabled: organizationRawSettings?.aiAutoTaggingEnabled ?? false,
-
- canCreateNewTags: organizationRawSettings?.aiAutoTaggingCanCreateNewTags ?? false,
-
- maxTags:
- organizationRawSettings?.aiAutoTaggingMaxTags ?? config.autoTagging.defaultMaxTags,
-
- model:
- parseOptionalModelId(organizationRawSettings?.aiAutoTaggingModelId) ??
- config.autoTagging.model ??
- config.ai.defaultModel,
- },
+ }> =>
+ resolveOrganizationSettings({
+ organizationId,
+ config,
+ organizationSettingsRepository,
+ });
+}
+
+export async function resolveOrganizationSettings({
+ organizationId,
+ config,
+ organizationSettingsRepository,
+}: {
+ organizationId: string;
+
+ config: Config;
+ organizationSettingsRepository: OrganizationSettingsRepository;
+}): Promise<{
+ organizationSettings: OrganizationSettings;
+}> {
+ const { organizationRawSettings } = await organizationSettingsRepository.getOrganizationSettings({
+ organizationId,
+ });
+
+ return {
+ organizationSettings: {
+ ai: {
+ autoTagging: {
+ isEnabled: organizationRawSettings?.aiAutoTaggingEnabled ?? false,
+
+ canCreateNewTags: organizationRawSettings?.aiAutoTaggingCanCreateNewTags ?? false,
+
+ maxTags:
+ organizationRawSettings?.aiAutoTaggingMaxTags ?? config.autoTagging.defaultMaxTags,
+
+ model:
+ parseOptionalModelId(organizationRawSettings?.aiAutoTaggingModelId) ??
+ config.autoTagging.model ??
+ config.ai.defaultModel,
},
},
- };
+ },
};
}