The minimalistic document archiving platform.
feat(admin): add organization soft deletion (#1580)
Corentin Thomassetd0638d11e1ca
diff --git a/.changeset/short-planets-post.md b/.changeset/short-planets-post.mdnew file mode 100644index 00000000..ede684e4--- /dev/null+++ b/.changeset/short-planets-post.md@@ -0,0 +1,5 @@+---+'@papra/app': minor+---++Admins can now delete organizations from their details page in the admin panel.diff --git a/apps/papra-client/src/locales/en.dictionary.ts b/apps/papra-client/src/locales/en.dictionary.tsindex 09faee65..94650551 100644--- a/apps/papra-client/src/locales/en.dictionary.ts+++ b/apps/papra-client/src/locales/en.dictionary.ts@@ -1349,6 +1349,17 @@ export const translations = {'admin.organization-detail.stats.deleted-storage': 'Deleted Storage','admin.organization-detail.stats.total-documents': 'Total Documents','admin.organization-detail.stats.total-storage': 'Total Storage',+ 'admin.organization-detail.delete.title': 'Delete organization',+ 'admin.organization-detail.delete.description':+ 'Remove all members and invitations and schedule this organization and its documents for permanent deletion.',+ 'admin.organization-detail.delete.button': 'Delete organization',+ 'admin.organization-detail.delete.confirm.title': 'Delete organization?',+ 'admin.organization-detail.delete.confirm.message':+ 'Are you sure you want to delete "{{ name }}"? All members will lose access immediately and pending invitations will be removed. The organization and its documents will be scheduled for permanent deletion.',+ 'admin.organization-detail.delete.confirm.cancel-button': 'Cancel',+ 'admin.organization-detail.delete.has-active-subscription':+ 'This organization has an active subscription. Cancel it or schedule its cancellation before deleting the organization.',+ 'admin.organization-detail.delete.success': 'Organization deleted successfully.','admin.users.title': 'User Management','admin.users.description': 'Manage and view all users in the system',diff --git a/apps/papra-client/src/modules/admin/organizations/organizations.services.ts b/apps/papra-client/src/modules/admin/organizations/organizations.services.tsindex 935a7826..34ea6882 100644--- a/apps/papra-client/src/modules/admin/organizations/organizations.services.ts+++ b/apps/papra-client/src/modules/admin/organizations/organizations.services.ts@@ -58,6 +58,13 @@ export async function getOrganizationBasicInfo({ organizationId }: { organizatioreturn { organization };}+export async function deleteOrganization({ organizationId }: { organizationId: string }) {+ await apiClient({+ method: 'DELETE',+ path: `/api/admin/organizations/${organizationId}`,+ });+}+export async function getOrganizationMembers({ organizationId }: { organizationId: string }) {const { members } = await apiClient<{members: OrganizationMember[];diff --git a/apps/papra-client/src/modules/admin/organizations/pages/organization-detail.page.tsx b/apps/papra-client/src/modules/admin/organizations/pages/organization-detail.page.tsxindex 1a2572e9..2806a643 100644--- a/apps/papra-client/src/modules/admin/organizations/pages/organization-detail.page.tsx+++ b/apps/papra-client/src/modules/admin/organizations/pages/organization-detail.page.tsx@@ -1,19 +1,24 @@import type { Component } from 'solid-js';import { formatBytes } from '@corentinth/chisels';-import { A, useParams } from '@solidjs/router';-import { useQuery } from '@tanstack/solid-query';+import { A, useNavigate, useParams } from '@solidjs/router';+import { useMutation, useQuery, useQueryClient } from '@tanstack/solid-query';import { For, Show, Suspense } from 'solid-js';import { RelativeTime } from '@/modules/i18n/components/RelativeTime';import { useI18n } from '@/modules/i18n/i18n.provider';+import { useConfirmModal } from '@/modules/shared/confirm';+import { useI18nApiErrors } from '@/modules/shared/http/composables/i18n-api-errors';+import { isHttpErrorWithCode } from '@/modules/shared/http/http-errors';import { Badge } from '@/modules/ui/components/badge';import { Button } from '@/modules/ui/components/button';import {Card,CardContent,CardDescription,+ CardFooter,CardHeader,CardTitle,} from '@/modules/ui/components/card';+import { createToast } from '@/modules/ui/components/sonner';import {Table,TableBody,@@ -24,6 +29,7 @@ import {} from '@/modules/ui/components/table';import { UserListDetail } from '../../users/components/user-list-detail.component';import {+ deleteOrganization,getOrganizationBasicInfo,getOrganizationIntakeEmails,getOrganizationMembers,@@ -345,6 +351,80 @@ const OrganizationStats: Component<{ organizationId: string }> = (props) => {);};+const DeleteOrganizationCard: Component<{ organizationId: string }> = (props) => {+ const { t } = useI18n();+ const { confirm } = useConfirmModal();+ const { getErrorMessage } = useI18nApiErrors({ t });+ const navigate = useNavigate();+ const queryClient = useQueryClient();++ const query = useQuery(() => ({+ queryKey: ['admin', 'organizations', props.organizationId, 'basic'],+ queryFn: async () => getOrganizationBasicInfo({ organizationId: props.organizationId }),+ }));++ const deleteMutation = useMutation(() => ({+ mutationFn: deleteOrganization,+ onSuccess: async () => {+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: ['admin', 'organizations'] }),+ queryClient.invalidateQueries({ queryKey: ['admin', 'users'] }),+ queryClient.invalidateQueries({ queryKey: ['organizations'] }),+ ]);+ createToast({ type: 'success', message: t('admin.organization-detail.delete.success') });+ navigate('/admin/organizations');+ },+ onError: (error) => {+ createToast({+ type: 'error',+ message: isHttpErrorWithCode({ error, code: 'organization.has_active_subscription' })+ ? t('admin.organization-detail.delete.has-active-subscription')+ : getErrorMessage({ error }),+ });+ },+ }));++ const handleDelete = async () => {+ const organization = query.data?.organization;++ if (!organization || organization.deletedAt || deleteMutation.isPending) {+ return;+ }++ const confirmed = await confirm({+ title: t('admin.organization-detail.delete.confirm.title'),+ message: t('admin.organization-detail.delete.confirm.message', { name: organization.name }),+ confirmButton: {+ text: t('admin.organization-detail.delete.button'),+ variant: 'destructive',+ },+ cancelButton: {+ text: t('admin.organization-detail.delete.confirm.cancel-button'),+ },+ });++ if (confirmed) {+ deleteMutation.mutate({ organizationId: organization.id });+ }+ };++ return (+ <Show when={query.data?.organization && !query.data.organization.deletedAt}>+ <Card class="border-destructive">+ <CardHeader>+ <CardTitle>{t('admin.organization-detail.delete.title')}</CardTitle>+ <CardDescription>{t('admin.organization-detail.delete.description')}</CardDescription>+ </CardHeader>+ <CardFooter>+ <Button variant="destructive" onClick={handleDelete} isLoading={deleteMutation.isPending}>+ {t('admin.organization-detail.delete.button')}+ </Button>+ </CardFooter>+ </Card>+ </Show>+ );+};+export const AdminOrganizationDetailPage: Component = () => {const { t } = useI18n();const params = useParams<{ organizationId: string }>();@@ -415,6 +495,10 @@ export const AdminOrganizationDetailPage: Component = () => {><OrganizationMembers organizationId={params.organizationId} /></Suspense>++ <Suspense>+ <DeleteOrganizationCard organizationId={params.organizationId} />+ </Suspense></div></div>);diff --git a/apps/papra-server/src/modules/admin/organizations/organizations.api.contracts.ts b/apps/papra-server/src/modules/admin/organizations/organizations.api.contracts.tsnew file mode 100644index 00000000..987c69f3--- /dev/null+++ b/apps/papra-server/src/modules/admin/organizations/organizations.api.contracts.ts@@ -0,0 +1,37 @@+import * as v from 'valibot';+import { defineApiContract } from '../../api/api.contracts';+import { errorResponseDefinition } from '../../api/api.contracts.errors';+import { organizationIdSchema } from '../../organizations/organization.schemas';++export const adminSoftDeleteOrganizationContract = defineApiContract({+ operationId: 'adminSoftDeleteOrganization',+ path: '/api/admin/organizations/:organizationId',+ method: 'DELETE',+ request: {+ params: v.strictObject({+ organizationId: organizationIdSchema,+ }),+ },+ responses: {+ 204: {+ description:+ 'Soft-deletes the organization and schedules its purge. Already-deleted organizations are left unchanged.',+ content: {},+ },+ ...errorResponseDefinition({+ statusCode: 401,+ code: 'auth.unauthorized',+ message: 'An authenticated session with the organizations:delete permission is required.',+ }),+ ...errorResponseDefinition({+ statusCode: 403,+ code: 'organization.has_active_subscription',+ message: 'A subscription blocks organization deletion.',+ }),+ ...errorResponseDefinition({+ statusCode: 404,+ code: 'organization.not_found',+ message: 'Organization not found.',+ }),+ },+});diff --git a/apps/papra-server/src/modules/admin/organizations/organizations.api.routes.ts b/apps/papra-server/src/modules/admin/organizations/organizations.api.routes.tsnew file mode 100644index 00000000..94d9a706--- /dev/null+++ b/apps/papra-server/src/modules/admin/organizations/organizations.api.routes.ts@@ -0,0 +1,48 @@+import type { ApiDependencies } from '../../app/server.types';+import { defineApiRoute } from '../../api/api.routes';+import { createUnauthorizedError } from '../../app/auth/auth.errors';+import { createOrganizationsRepository } from '../../organizations/organizations.repository';+import { PERMISSIONS } from '../../roles/roles.constants';+import { getPermissionsForRoles } from '../../roles/roles.methods';+import { createRolesRepository } from '../../roles/roles.repository';+import { createSubscriptionsRepository } from '../../subscriptions/subscriptions.repository';+import { adminSoftDeleteOrganizationContract } from './organizations.api.contracts';+import { buildAdminSoftDeleteOrganization } from './organizations.usecases';++export function buildAdminOrganizationsApiRoutes(deps: ApiDependencies) {+ return [setupAdminSoftDeleteOrganizationRoute(deps)];+}++function setupAdminSoftDeleteOrganizationRoute({+ resolveAuthenticationContext,+ db,+ config,+}: ApiDependencies) {+ const authenticate = resolveAuthenticationContext();+ const rolesRepository = createRolesRepository({ db });+ const softDeleteOrganization = buildAdminSoftDeleteOrganization({+ organizationsRepository: createOrganizationsRepository({ db }),+ subscriptionsRepository: createSubscriptionsRepository({ db }),+ config,+ });++ return defineApiRoute({+ contract: adminSoftDeleteOrganizationContract,+ resolveContext: async ({ request }) => {+ const context = await authenticate({ request });+ const { roles } = await rolesRepository.getUserRoles({ userId: context.userId });+ const { permissions } = getPermissionsForRoles({ roles });++ if (!permissions.includes(PERMISSIONS.DELETE_ORGANIZATIONS)) {+ throw createUnauthorizedError();+ }++ return context;+ },+ handler: async ({ context: { userId }, params: { organizationId } }) => {+ await softDeleteOrganization({ organizationId, deletedBy: userId });++ return { status: 204 };+ },+ });+}diff --git a/apps/papra-server/src/modules/admin/organizations/organizations.usecases.test.ts b/apps/papra-server/src/modules/admin/organizations/organizations.usecases.test.tsnew file mode 100644index 00000000..d873403a--- /dev/null+++ b/apps/papra-server/src/modules/admin/organizations/organizations.usecases.test.ts@@ -0,0 +1,389 @@+import { eq } from 'drizzle-orm';+import { describe, expect, test } from 'vitest';+import { createInMemoryDatabase } from '../../app/database/database.test-utils';+import { overrideConfig } from '../../config/config.test-utils';+import { documentsTable } from '../../documents/documents.table';+import {+ createOnlyPreviousOwnerCanRestoreError,+ createOrganizationHasActiveSubscriptionError,+ createOrganizationNotFoundError,+} from '../../organizations/organizations.errors';+import { createOrganizationsRepository } from '../../organizations/organizations.repository';+import {+ organizationInvitationsTable,+ organizationMembersTable,+ organizationsTable,+} from '../../organizations/organizations.table';+import { restoreOrganization } from '../../organizations/organizations.usecases';+import { createTestClock } from '../../shared/clock/clock.test-utils';+import { createSubscriptionsRepository } from '../../subscriptions/subscriptions.repository';+import { createUsersRepository } from '../../users/users.repository';+import { usersTable } from '../../users/users.table';+import { deleteUser } from '../../users/users.usecases';+import { buildAdminSoftDeleteOrganization } from './organizations.usecases';++const organizationId = 'organization-1';+const ownerId = 'owner';+const adminId = 'admin';++describe('buildAdminSoftDeleteOrganization', () => {+ test('deleting an empty organization records the admin, schedules its purge, and allows deleting its owner', async () => {+ const { db } = await createInMemoryDatabase({+ users: [+ { id: ownerId, email: '[email protected]' },+ { id: adminId, email: '[email protected]' },+ ],+ organizations: [{ id: organizationId, name: 'Test organization' }],+ organizationMembers: [{ organizationId, userId: ownerId, role: 'owner' }],+ organizationInvitations: [+ {+ organizationId,+ email: '[email protected]',+ role: 'member',+ inviterId: ownerId,+ status: 'pending',+ expiresAt: new Date('2026-06-01'),+ },+ ],+ });+ const { clock } = createTestClock({ now: '2026-05-12T00:00:00Z' });+ const organizationsRepository = createOrganizationsRepository({ db });+ const softDeleteOrganization = buildAdminSoftDeleteOrganization({+ organizationsRepository,+ subscriptionsRepository: createSubscriptionsRepository({ db }),+ config: overrideConfig({ organizations: { deletedOrganizationsPurgeDaysDelay: 7 } }),+ clock,+ });+ clock.advanceBy({ hours: 24 });++ await softDeleteOrganization({ organizationId, deletedBy: adminId });++ const organizations = await db.select().from(organizationsTable);+ const members = await db.select().from(organizationMembersTable);+ const invitations = await db.select().from(organizationInvitationsTable);+ expect(organizations[0]).toMatchObject({+ id: organizationId,+ deletedBy: adminId,+ deletedAt: new Date('2026-05-13T00:00:00Z'),+ scheduledPurgeAt: new Date('2026-05-20T00:00:00Z'),+ });+ expect(members).toEqual([]);+ expect(invitations).toEqual([]);++ await deleteUser({+ userId: ownerId,+ organizationsRepository,+ usersRepository: createUsersRepository({ db }),+ });++ expect(await db.select().from(usersTable).where(eq(usersTable.id, ownerId))).toEqual([]);+ });++ test('a shared, non-empty organization can be deleted without affecting its documents or other organizations', async () => {+ const otherOrganizationId = 'organization-2';+ const { db } = await createInMemoryDatabase({+ users: [+ { id: ownerId, email: '[email protected]' },+ { id: adminId, email: '[email protected]' },+ { id: 'member', email: '[email protected]' },+ ],+ organizations: [+ { id: organizationId, name: 'Test organization' },+ { id: otherOrganizationId, name: 'Other' },+ ],+ organizationMembers: [+ { organizationId, userId: ownerId, role: 'owner' },+ { organizationId, userId: 'member', role: 'member' },+ { organizationId: otherOrganizationId, userId: 'member', role: 'owner' },+ ],+ organizationInvitations: [+ {+ organizationId,+ email: '[email protected]',+ role: 'member',+ inviterId: ownerId,+ status: 'pending',+ expiresAt: new Date('2026-06-01'),+ },+ {+ organizationId: otherOrganizationId,+ email: '[email protected]',+ role: 'member',+ inviterId: 'member',+ status: 'pending',+ expiresAt: new Date('2026-06-01'),+ },+ ],+ documents: [+ {+ organizationId,+ name: 'Document',+ originalName: 'document.pdf',+ originalStorageKey: 'document.pdf',+ originalSha256Hash: 'hash',+ mimeType: 'application/pdf',+ },+ ],+ });+ const { clock } = createTestClock({ now: '2026-05-12T00:00:00Z' });+ const softDeleteOrganization = buildAdminSoftDeleteOrganization({+ organizationsRepository: createOrganizationsRepository({ db }),+ subscriptionsRepository: createSubscriptionsRepository({ db }),+ config: overrideConfig({ organizations: { deletedOrganizationsPurgeDaysDelay: 7 } }),+ clock,+ });+ const before = {+ organizations: await db.select().from(organizationsTable),+ members: await db.select().from(organizationMembersTable),+ invitations: await db.select().from(organizationInvitationsTable),+ };+ const documentsBefore = await db.select().from(documentsTable);++ await softDeleteOrganization({ organizationId, deletedBy: adminId });++ const organizations = await db.select().from(organizationsTable);+ const members = await db.select().from(organizationMembersTable);+ const invitations = await db.select().from(organizationInvitationsTable);+ expect(organizations.find(({ id }) => id === organizationId)).toMatchObject({+ deletedBy: adminId,+ deletedAt: new Date('2026-05-12T00:00:00Z'),+ });+ expect(organizations.find(({ id }) => id === otherOrganizationId)).toEqual(+ before.organizations.find(({ id }) => id === otherOrganizationId),+ );+ expect(members).toEqual(+ before.members.filter(({ organizationId }) => organizationId === otherOrganizationId),+ );+ expect(invitations).toEqual(+ before.invitations.filter(({ organizationId }) => organizationId === otherOrganizationId),+ );+ expect(await db.select().from(documentsTable)).toEqual(documentsBefore);+ });++ test('a blocking subscription leaves the organization, memberships, and invitations unchanged', async () => {+ const { db } = await createInMemoryDatabase({+ users: [+ { id: ownerId, email: '[email protected]' },+ { id: adminId, email: '[email protected]' },+ ],+ organizations: [{ id: organizationId, name: 'Test organization' }],+ organizationMembers: [{ organizationId, userId: ownerId, role: 'owner' }],+ organizationInvitations: [+ {+ organizationId,+ email: '[email protected]',+ role: 'member',+ inviterId: ownerId,+ status: 'pending',+ expiresAt: new Date('2026-06-01'),+ },+ ],+ organizationSubscriptions: [+ {+ id: 'sub_test',+ organizationId,+ customerId: 'cus_test',+ planId: 'pro',+ status: 'active',+ seatsCount: 2,+ currentPeriodStart: new Date('2026-05-01'),+ currentPeriodEnd: new Date('2026-06-01'),+ cancelAtPeriodEnd: false,+ },+ ],+ });+ const { clock } = createTestClock({ now: '2026-05-12T00:00:00Z' });+ const softDeleteOrganization = buildAdminSoftDeleteOrganization({+ organizationsRepository: createOrganizationsRepository({ db }),+ subscriptionsRepository: createSubscriptionsRepository({ db }),+ config: overrideConfig({ organizations: { deletedOrganizationsPurgeDaysDelay: 7 } }),+ clock,+ });+ const before = {+ organizations: await db.select().from(organizationsTable),+ members: await db.select().from(organizationMembersTable),+ invitations: await db.select().from(organizationInvitationsTable),+ };++ await expect(softDeleteOrganization({ organizationId, deletedBy: adminId })).rejects.toThrow(+ createOrganizationHasActiveSubscriptionError(),+ );++ expect({+ organizations: await db.select().from(organizationsTable),+ members: await db.select().from(organizationMembersTable),+ invitations: await db.select().from(organizationInvitationsTable),+ }).toEqual(before);+ });++ test('a subscription scheduled to cancel does not block deletion', async () => {+ const { db } = await createInMemoryDatabase({+ users: [+ { id: ownerId, email: '[email protected]' },+ { id: adminId, email: '[email protected]' },+ ],+ organizations: [{ id: organizationId, name: 'Test organization' }],+ organizationMembers: [{ organizationId, userId: ownerId, role: 'owner' }],+ organizationInvitations: [+ {+ organizationId,+ email: '[email protected]',+ role: 'member',+ inviterId: ownerId,+ status: 'pending',+ expiresAt: new Date('2026-06-01'),+ },+ ],+ organizationSubscriptions: [+ {+ id: 'sub_test',+ organizationId,+ customerId: 'cus_test',+ planId: 'pro',+ status: 'active',+ seatsCount: 2,+ currentPeriodStart: new Date('2026-05-01'),+ currentPeriodEnd: new Date('2026-06-01'),+ cancelAtPeriodEnd: true,+ },+ ],+ });+ const { clock } = createTestClock({ now: '2026-05-12T00:00:00Z' });+ const softDeleteOrganization = buildAdminSoftDeleteOrganization({+ organizationsRepository: createOrganizationsRepository({ db }),+ subscriptionsRepository: createSubscriptionsRepository({ db }),+ config: overrideConfig({ organizations: { deletedOrganizationsPurgeDaysDelay: 7 } }),+ clock,+ });++ await softDeleteOrganization({ organizationId, deletedBy: adminId });++ const organizations = await db.select().from(organizationsTable);+ const members = await db.select().from(organizationMembersTable);+ const invitations = await db.select().from(organizationInvitationsTable);+ expect(organizations[0]).toMatchObject({+ deletedBy: adminId,+ deletedAt: new Date('2026-05-12T00:00:00Z'),+ scheduledPurgeAt: new Date('2026-05-19T00:00:00Z'),+ });+ expect(members).toEqual([]);+ expect(invitations).toEqual([]);+ });++ test('deleting an already-deleted organization preserves its original actor and purge deadline', async () => {+ const { db } = await createInMemoryDatabase({+ users: [+ { id: ownerId, email: '[email protected]' },+ { id: adminId, email: '[email protected]' },+ { id: 'another-admin', email: '[email protected]' },+ ],+ organizations: [{ id: organizationId, name: 'Test organization' }],+ organizationMembers: [{ organizationId, userId: ownerId, role: 'owner' }],+ });+ const { clock } = createTestClock({ now: '2026-05-12T00:00:00Z' });+ const softDeleteOrganization = buildAdminSoftDeleteOrganization({+ organizationsRepository: createOrganizationsRepository({ db }),+ subscriptionsRepository: createSubscriptionsRepository({ db }),+ config: overrideConfig({ organizations: { deletedOrganizationsPurgeDaysDelay: 7 } }),+ clock,+ });+ await softDeleteOrganization({ organizationId, deletedBy: adminId });+ const before = {+ organizations: await db.select().from(organizationsTable),+ members: await db.select().from(organizationMembersTable),+ invitations: await db.select().from(organizationInvitationsTable),+ };+ clock.advanceBy({ hours: 48 });++ await softDeleteOrganization({ organizationId, deletedBy: 'another-admin' });++ expect({+ organizations: await db.select().from(organizationsTable),+ members: await db.select().from(organizationMembersTable),+ invitations: await db.select().from(organizationInvitationsTable),+ }).toEqual(before);+ });++ test('a missing organization raises a not-found error without changing existing organizations', async () => {+ const { db } = await createInMemoryDatabase({+ users: [+ { id: ownerId, email: '[email protected]' },+ { id: adminId, email: '[email protected]' },+ ],+ organizations: [{ id: organizationId, name: 'Test organization' }],+ organizationMembers: [{ organizationId, userId: ownerId, role: 'owner' }],+ organizationInvitations: [+ {+ organizationId,+ email: '[email protected]',+ role: 'member',+ inviterId: ownerId,+ status: 'pending',+ expiresAt: new Date('2026-06-01'),+ },+ ],+ });+ const { clock } = createTestClock({ now: '2026-05-12T00:00:00Z' });+ const softDeleteOrganization = buildAdminSoftDeleteOrganization({+ organizationsRepository: createOrganizationsRepository({ db }),+ subscriptionsRepository: createSubscriptionsRepository({ db }),+ config: overrideConfig({ organizations: { deletedOrganizationsPurgeDaysDelay: 7 } }),+ clock,+ });+ const before = {+ organizations: await db.select().from(organizationsTable),+ members: await db.select().from(organizationMembersTable),+ invitations: await db.select().from(organizationInvitationsTable),+ };++ await expect(+ softDeleteOrganization({ organizationId: 'missing', deletedBy: adminId }),+ ).rejects.toThrow(createOrganizationNotFoundError());++ expect({+ organizations: await db.select().from(organizationsTable),+ members: await db.select().from(organizationMembersTable),+ invitations: await db.select().from(organizationInvitationsTable),+ }).toEqual(before);+ });++ test('the previous owner cannot restore an organization deleted by an admin', async () => {+ const { db } = await createInMemoryDatabase({+ users: [+ { id: ownerId, email: '[email protected]' },+ { id: adminId, email: '[email protected]' },+ ],+ organizations: [{ id: organizationId, name: 'Test organization' }],+ organizationMembers: [{ organizationId, userId: ownerId, role: 'owner' }],+ });+ const { clock } = createTestClock({ now: '2026-05-12T00:00:00Z' });+ const organizationsRepository = createOrganizationsRepository({ db });+ const softDeleteOrganization = buildAdminSoftDeleteOrganization({+ organizationsRepository,+ subscriptionsRepository: createSubscriptionsRepository({ db }),+ config: overrideConfig({ organizations: { deletedOrganizationsPurgeDaysDelay: 7 } }),+ clock,+ });+ await softDeleteOrganization({ organizationId, deletedBy: adminId });+ const before = {+ organizations: await db.select().from(organizationsTable),+ members: await db.select().from(organizationMembersTable),+ invitations: await db.select().from(organizationInvitationsTable),+ };++ await expect(+ restoreOrganization({+ organizationId,+ restoredBy: ownerId,+ organizationsRepository,+ now: new Date('2026-05-13T00:00:00Z'),+ }),+ ).rejects.toThrow(createOnlyPreviousOwnerCanRestoreError());++ expect({+ organizations: await db.select().from(organizationsTable),+ members: await db.select().from(organizationMembersTable),+ invitations: await db.select().from(organizationInvitationsTable),+ }).toEqual(before);+ });+});diff --git a/apps/papra-server/src/modules/admin/organizations/organizations.usecases.ts b/apps/papra-server/src/modules/admin/organizations/organizations.usecases.tsnew file mode 100644index 00000000..06bb3b11--- /dev/null+++ b/apps/papra-server/src/modules/admin/organizations/organizations.usecases.ts@@ -0,0 +1,58 @@+import type { Config } from '../../config/config.types';+import type { OrganizationsRepository } from '../../organizations/organizations.repository';+import type { Clock } from '../../shared/clock/clock.types';+import type { SubscriptionsRepository } from '../../subscriptions/subscriptions.repository';+import {+ createOrganizationHasActiveSubscriptionError,+ createOrganizationNotFoundError,+} from '../../organizations/organizations.errors';+import { systemClock } from '../../shared/clock/clock';+import { doesSubscriptionBlockDeletion } from '../../subscriptions/subscriptions.models';+import type { Logger } from '../../shared/logger/logger';+import { createLogger } from '../../shared/logger/logger';++export function buildAdminSoftDeleteOrganization({+ organizationsRepository,+ subscriptionsRepository,+ config,+ clock = systemClock,+ logger = createLogger({ namespace: 'admin:organizations' }),+}: {+ organizationsRepository: OrganizationsRepository;+ subscriptionsRepository: SubscriptionsRepository;+ config: Config;+ clock?: Clock;+ logger?: Logger;+}) {+ return async ({ organizationId, deletedBy }: { organizationId: string; deletedBy: string }) => {+ const { organization } = await organizationsRepository.getOrganizationById({ organizationId });++ if (!organization) {+ throw createOrganizationNotFoundError();+ }++ // Retrying must not reset the purge deadline or change who can restore the organization.+ if (organization.deletedAt) {+ return;+ }++ const { subscription } = await subscriptionsRepository.getActiveOrganizationSubscription({+ organizationId,+ });++ if (doesSubscriptionBlockDeletion(subscription)) {+ throw createOrganizationHasActiveSubscriptionError();+ }++ await organizationsRepository.deleteAllMembersFromOrganization({ organizationId });+ await organizationsRepository.deleteAllOrganizationInvitations({ organizationId });+ await organizationsRepository.softDeleteOrganization({+ organizationId,+ deletedBy,+ now: new Date(clock.now().epochMilliseconds),+ purgeDaysDelay: config.organizations.deletedOrganizationsPurgeDaysDelay,+ });++ logger.info({ organizationId, deletedBy }, 'Organization soft-deleted by admin');+ };+}diff --git a/apps/papra-server/src/modules/api/api.contracts.registry.ts b/apps/papra-server/src/modules/api/api.contracts.registry.tsindex 6cda360c..58fa1b1e 100644--- a/apps/papra-server/src/modules/api/api.contracts.registry.ts+++ b/apps/papra-server/src/modules/api/api.contracts.registry.ts@@ -1,3 +1,4 @@+import { adminSoftDeleteOrganizationContract } from '../admin/organizations/organizations.api.contracts';import { healthCheckContract, pingContract } from '../app/health-check/health-check.api.contracts';import { getPublicConfigContract } from '../config/config.api.contracts';import {@@ -21,6 +22,7 @@ import {export type { ApiContract } from './api.contracts';export const apiContracts = {+ adminSoftDeleteOrganizationContract,pingContract,healthCheckContract,getPublicConfigContract,diff --git a/apps/papra-server/src/modules/app/server.api.routes.ts b/apps/papra-server/src/modules/app/server.api.routes.tsindex ff2d4045..f7d2285f 100644--- a/apps/papra-server/src/modules/app/server.api.routes.ts+++ b/apps/papra-server/src/modules/app/server.api.routes.ts@@ -1,5 +1,6 @@import type { ApiDependencies, RouteDefinitionContext } from './server.types';+import { buildAdminOrganizationsApiRoutes } from '../admin/organizations/organizations.api.routes';import { buildApiRequestHandler } from '../api/api.request-handler';import { buildConfigApiRoutes } from '../config/config.api.routes';import { buildOrganizationsApiRoutes } from '../organizations/organizations.api.routes';@@ -14,6 +15,7 @@ import {function buildApiRoutes(deps: ApiDependencies) {return [+ ...buildAdminOrganizationsApiRoutes(deps),...buildHealthCheckApiRoutes(deps),...buildConfigApiRoutes(deps),...buildUserApiRoutes(deps),diff --git a/apps/papra-server/src/modules/roles/roles.constants.ts b/apps/papra-server/src/modules/roles/roles.constants.tsindex 4ed04e41..467c632b 100644--- a/apps/papra-server/src/modules/roles/roles.constants.ts+++ b/apps/papra-server/src/modules/roles/roles.constants.ts@@ -6,6 +6,7 @@ export const PERMISSIONS = {BO_ACCESS: 'bo:access',VIEW_USERS: 'users:view',DELETE_USERS: 'users:delete',+ DELETE_ORGANIZATIONS: 'organizations:delete',VIEW_ANALYTICS: 'analytics:view',MANAGE_PLAN_ENTITLEMENTS: 'plan-entitlements:manage',} as const;@@ -14,6 +15,7 @@ export const PERMISSIONS_BY_ROLE = {[ROLES.ADMIN]: [PERMISSIONS.VIEW_USERS,PERMISSIONS.DELETE_USERS,+ PERMISSIONS.DELETE_ORGANIZATIONS,PERMISSIONS.BO_ACCESS,PERMISSIONS.VIEW_ANALYTICS,PERMISSIONS.MANAGE_PLAN_ENTITLEMENTS,