The minimalistic document archiving platform.
refactor(organizations): rollback organization management to in-house API (#159)
Corentin Thomasset25379b5be52c
diff --git a/apps/papra-client/src/modules/auth/auth.demo.services.ts b/apps/papra-client/src/modules/auth/auth.demo.services.tsindex c565ab56..38c60677 100644--- a/apps/papra-client/src/modules/auth/auth.demo.services.ts+++ b/apps/papra-client/src/modules/auth/auth.demo.services.ts@@ -1,52 +1,4 @@import type { createAuthClient } from './auth.services';-import slugify from '@sindresorhus/slugify';-import { organizationStorage } from '../demo/demo.storage';-import { getValues } from '../demo/demo.storage.models';--const organizationClient = {- list: async () => {- const organizations = await getValues(organizationStorage);-- return { data: organizations };- },- create: async ({ name }: { name: string }) => {- const organization = {- id: `org_${Math.random().toString(36).slice(2)}`,- slug: `${slugify(name)}-${Math.random().toString(36).slice(2)}`,- name,- createdAt: new Date(),- updatedAt: new Date(),- };-- await organizationStorage.setItem(organization.id, organization);-- return { data: organization };- },-- getFullOrganization: async ({ query: { organizationId } }: { query: { organizationId: string } }) => {- const organization = await organizationStorage.getItem(organizationId);-- return { data: organization };- },-- delete: async ({ organizationId }: { organizationId: string }) => {- await organizationStorage.removeItem(organizationId);- },-- update: async ({ organizationId, data: { name } }: { organizationId: string; data: { name: string } }) => {- const organization = await organizationStorage.getItem(organizationId);-- if (!organization) {- throw new Error('Organization not found');- }-- const newOrganization = { ...organization, name };-- await organizationStorage.setItem(organizationId, newOrganization);-- return { data: newOrganization };- },-};export function createDemoAuthClient() {const baseClient = {@@ -64,7 +16,6 @@ export function createDemoAuthClient() {social: () => Promise.resolve({}),},signOut: () => Promise.resolve({}),- organization: organizationClient,signUp: () => Promise.resolve({}),forgetPassword: () => Promise.resolve({}),resetPassword: () => Promise.resolve({}),diff --git a/apps/papra-client/src/modules/auth/auth.services.ts b/apps/papra-client/src/modules/auth/auth.services.tsindex 269c3c7f..11571d03 100644--- a/apps/papra-client/src/modules/auth/auth.services.ts+++ b/apps/papra-client/src/modules/auth/auth.services.ts@@ -1,4 +1,3 @@-import { organizationClient as organizationClientPlugin } from 'better-auth/client/plugins';import { createAuthClient as createBetterAuthClient } from 'better-auth/solid';import { buildTimeConfig } from '../config/config';@@ -8,7 +7,6 @@ import { createDemoAuthClient } from './auth.demo.services';export function createAuthClient() {const client = createBetterAuthClient({baseURL: buildTimeConfig.baseApiUrl,- plugins: [organizationClientPlugin()],});return {@@ -19,7 +17,6 @@ export function createAuthClient() {resetPassword: client.resetPassword,sendVerificationEmail: client.sendVerificationEmail,useSession: client.useSession,- organization: client.organization,signOut: async () => {trackingServices.capture({ event: 'User logged out' });const result = await client.signOut();@@ -38,7 +35,6 @@ export const {forgetPassword,resetPassword,sendVerificationEmail,- organization: organizationClient,} = buildTimeConfig.isDemoMode? createDemoAuthClient(): createAuthClient();diff --git a/apps/papra-client/src/modules/demo/demo-api-mock.ts b/apps/papra-client/src/modules/demo/demo-api-mock.tsindex b203d42d..32b62406 100644--- a/apps/papra-client/src/modules/demo/demo-api-mock.ts+++ b/apps/papra-client/src/modules/demo/demo-api-mock.ts@@ -385,6 +385,70 @@ const inMemoryApiMock: Record<string, { handler: any }> = {},}),+ ...defineHandler({+ path: '/api/organizations',+ method: 'GET',+ handler: async () => {+ const organizations = await getValues(organizationStorage);++ return { organizations };+ },+ }),++ ...defineHandler({+ path: '/api/organizations',+ method: 'POST',+ handler: async ({ body }) => {+ const organization = {+ id: `org_${Math.random().toString(36).slice(2)}`,+ name: get(body, 'name'),+ createdAt: new Date(),+ updatedAt: new Date(),+ };++ await organizationStorage.setItem(organization.id, organization);++ return { organization };+ },+ }),++ ...defineHandler({+ path: '/api/organizations/:organizationId',+ method: 'GET',+ handler: async ({ params: { organizationId } }) => {+ const organization = await organizationStorage.getItem(organizationId);++ assert(organization, { status: 403 });++ return { organization };+ },+ }),++ ...defineHandler({+ path: '/api/organizations/:organizationId',+ method: 'DELETE',+ handler: async ({ params: { organizationId } }) => {+ await organizationStorage.removeItem(organizationId);+ },+ }),++ ...defineHandler({+ path: '/api/organizations/:organizationId',+ method: 'PUT',+ handler: async ({ params: { organizationId }, body }) => {+ const organization = await organizationStorage.getItem(organizationId);++ assert(organization, { status: 403 });++ organization.name = get(body, 'name');+ organization.updatedAt = new Date();++ await organizationStorage.setItem(organizationId, organization);++ return { organization };+ },+ }),+};export const router = createRouter({ routes: inMemoryApiMock, strictTrailingSlash: false });diff --git a/apps/papra-client/src/modules/organizations/organizations.services.ts b/apps/papra-client/src/modules/organizations/organizations.services.tsindex 41e87c59..b3620098 100644--- a/apps/papra-client/src/modules/organizations/organizations.services.ts+++ b/apps/papra-client/src/modules/organizations/organizations.services.ts@@ -1,51 +1,71 @@-import slugify from '@sindresorhus/slugify';-import { organizationClient } from '../auth/auth.services';+import type { Organization } from './organizations.types';+import { apiClient } from '../shared/http/api-client';export async function fetchOrganizations() {- const { data: organizations } = await organizationClient.list();+ const { organizations } = await apiClient<{ organizations: Organization[] }>({+ path: '/api/organizations',+ method: 'GET',+ });return {- organizations: organizations ?? [],+ organizations: organizations.map(organization => ({+ ...organization,+ createdAt: new Date(organization.createdAt),+ updatedAt: organization.updatedAt ? new Date(organization.updatedAt) : undefined,+ })),};}export async function createOrganization({ name }: { name: string }) {- const { data: organization, error } = await organizationClient.create({- name,- // Currently, we do not need/use the slug, so we generate a random one, as it is required by BetterAuth- slug: `${slugify(name)}-${Math.random().toString(36).substring(2)}`,+ const { organization } = await apiClient<{ organization: Organization }>({+ path: '/api/organizations',+ method: 'POST',+ body: { name },});- if (error) {- throw Object.assign(new Error(error.message), error);- }-return {- organization,+ organization: {+ ...organization,+ createdAt: new Date(organization.createdAt),+ updatedAt: organization.updatedAt ? new Date(organization.updatedAt) : undefined,+ },};}export async function updateOrganization({ organizationId, name }: { organizationId: string; name: string }) {- const { data: organization } = await organizationClient.update({- organizationId,- data: {- name,- },+ const { organization } = await apiClient<{ organization: Organization }>({+ path: `/api/organizations/${organizationId}`,+ method: 'PUT',+ body: { name },});return {- organization,+ organization: {+ ...organization,+ createdAt: new Date(organization.createdAt),+ updatedAt: organization.updatedAt ? new Date(organization.updatedAt) : undefined,+ },};}export async function fetchOrganization({ organizationId }: { organizationId: string }) {- const { data: organization } = await organizationClient.getFullOrganization({ query: { organizationId } });+ const { organization } = await apiClient<{ organization: Organization }>({+ path: `/api/organizations/${organizationId}`,+ method: 'GET',+ });return {- organization,+ organization: {+ ...organization,+ createdAt: new Date(organization.createdAt),+ updatedAt: organization.updatedAt ? new Date(organization.updatedAt) : undefined,+ },};}export async function deleteOrganization({ organizationId }: { organizationId: string }) {- await organizationClient.delete({ organizationId });+ await apiClient({+ path: `/api/organizations/${organizationId}`,+ method: 'DELETE',+ });}diff --git a/apps/papra-client/src/modules/organizations/organizations.types.ts b/apps/papra-client/src/modules/organizations/organizations.types.tsindex 1402c89c..f33e97f4 100644--- a/apps/papra-client/src/modules/organizations/organizations.types.ts+++ b/apps/papra-client/src/modules/organizations/organizations.types.ts@@ -1,6 +1,6 @@-export type Organization = { id: string; name: string; createdAt: Date; updatedAt?: Date };--export type OrganizationWithStats = Organization & {- documentsCount: number;- documentsSize: number;+export type Organization = {+ id: string;+ name: string;+ createdAt: Date;+ updatedAt?: Date;};diff --git a/apps/papra-server/src/modules/app/auth/auth.services.ts b/apps/papra-server/src/modules/app/auth/auth.services.tsindex 6db79e41..0409a83a 100644--- a/apps/papra-server/src/modules/app/auth/auth.services.ts+++ b/apps/papra-server/src/modules/app/auth/auth.services.ts@@ -4,7 +4,6 @@ import type { AuthEmailsServices } from './auth.emails.services';import { betterAuth } from 'better-auth';import { drizzleAdapter } from 'better-auth/adapters/drizzle';import { APIError } from 'better-auth/api';-import { organization } from 'better-auth/plugins';import { organizationInvitationsTable, organizationMembersTable, organizationsTable } from '../../organizations/organizations.table';import { createLogger } from '../../shared/logger/logger';import { usersTable } from '../../users/users.table';@@ -19,9 +18,6 @@ export function getAuth({ db, config, authEmailsServices }: { db: Database; confconst auth = betterAuth({secret,- plugins: [- organization(),- ],baseURL: config.server.baseUrl,trustedOrigins: [config.client.baseUrl],logger: {diff --git a/apps/papra-server/src/modules/app/auth/auth.tables.ts b/apps/papra-server/src/modules/app/auth/auth.tables.tsindex 1b92e603..2fc23874 100644--- a/apps/papra-server/src/modules/app/auth/auth.tables.ts+++ b/apps/papra-server/src/modules/app/auth/auth.tables.ts@@ -11,7 +11,7 @@ export const sessionsTable = sqliteTable(token: text('token').notNull(),userId: text('user_id').references(() => usersTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),- expiresAt: integer('expires_at', { mode: 'timestamp' }).notNull(),+ expiresAt: integer('expires_at', { mode: 'timestamp_ms' }).notNull(),ipAddress: text('ip_address'),userAgent: text('user_agent'),activeOrganizationId: text('active_organization_id').references(() => organizationsTable.id, { onDelete: 'set null', onUpdate: 'cascade' }),@@ -33,8 +33,8 @@ export const accountsTable = sqliteTable(providerId: text('provider_id').notNull(),accessToken: text('access_token'),refreshToken: text('refresh_token'),- accessTokenExpiresAt: integer('access_token_expires_at', { mode: 'timestamp' }),- refreshTokenExpiresAt: integer('refresh_token_expires_at', { mode: 'timestamp' }),+ accessTokenExpiresAt: integer('access_token_expires_at', { mode: 'timestamp_ms' }),+ refreshTokenExpiresAt: integer('refresh_token_expires_at', { mode: 'timestamp_ms' }),scope: text('scope'),idToken: text('id_token'),password: text('password'),@@ -49,7 +49,7 @@ export const verificationsTable = sqliteTable(identifier: text('identifier').notNull(),value: text('value').notNull(),- expiresAt: integer('expires_at', { mode: 'timestamp' }).notNull(),+ expiresAt: integer('expires_at', { mode: 'timestamp_ms' }).notNull(),},table => [// To select verifications by identifierdiff --git a/apps/papra-server/src/modules/app/server.routes.ts b/apps/papra-server/src/modules/app/server.routes.tsindex 8b8f0180..bab972b8 100644--- a/apps/papra-server/src/modules/app/server.routes.ts+++ b/apps/papra-server/src/modules/app/server.routes.ts@@ -2,6 +2,7 @@ import type { ServerInstance } from './server.types';import { registerConfigPublicRoutes } from '../config/config.routes';import { registerDocumentsPrivateRoutes } from '../documents/documents.routes';import { registerIntakeEmailsPrivateRoutes, registerIntakeEmailsPublicRoutes } from '../intake-emails/intake-emails.routes';+import { registerOrganizationsPrivateRoutes } from '../organizations/organizations.routes';import { registerTagsRoutes } from '../tags/tags.routes';import { registerUsersPrivateRoutes } from '../users/users.routes';import { createUnauthorizedError } from './auth/auth.errors';@@ -34,6 +35,7 @@ function registerPrivateRoutes({ app }: { app: ServerInstance }) {});registerUsersPrivateRoutes({ app });+ registerOrganizationsPrivateRoutes({ app });registerDocumentsPrivateRoutes({ app });registerTagsRoutes({ app });registerIntakeEmailsPrivateRoutes({ app });diff --git a/apps/papra-server/src/modules/documents/documents.repository.test.ts b/apps/papra-server/src/modules/documents/documents.repository.test.tsindex 780c59ca..aeb187da 100644--- a/apps/papra-server/src/modules/documents/documents.repository.test.ts+++ b/apps/papra-server/src/modules/documents/documents.repository.test.ts@@ -10,7 +10,7 @@ describe('documents repository', () => {test('a document can be created, retrieved, and soft deleted', async () => {const { db } = await createInMemoryDatabase({users: [{ id: 'user-1', email: '[email protected]' }],- organizations: [{ id: 'organization-1', name: 'Organization 1', slug: 'organization-1' }],+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],organizationMembers: [{ organizationId: 'organization-1', userId: 'user-1', role: ORGANIZATION_ROLE_MEMBER }],});@@ -74,7 +74,7 @@ describe('documents repository', () => {test('a document is unique by organization, an error is raised if a document with the same hash already exists', async () => {const { db } = await createInMemoryDatabase({users: [{ id: 'user-1', email: '[email protected]' }],- organizations: [{ id: 'organization-1', name: 'Organization 1', slug: 'organization-1' }],+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],});const documentsRepository = createDocumentsRepository({ db });@@ -109,7 +109,7 @@ describe('documents repository', () => {test('provides full text search on document name, original name, and content', async () => {const { db } = await createInMemoryDatabase({users: [{ id: 'user-1', email: '[email protected]' }],- organizations: [{ id: 'organization-1', name: 'Organization 1', slug: 'organization-1' }],+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],organizationMembers: [{ organizationId: 'organization-1', userId: 'user-1', role: ORGANIZATION_ROLE_MEMBER }],documents: [{ id: 'doc-1', organizationId: 'organization-1', createdBy: 'user-1', name: 'Document 1', originalName: 'document-1.pdf', content: 'lorem ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash1' },@@ -143,8 +143,8 @@ describe('documents repository', () => {{ id: 'user-2', email: '[email protected]' },],organizations: [- { id: 'organization-1', name: 'Organization 1', slug: 'organization-1' },- { id: 'organization-2', name: 'Organization 2', slug: 'organization-2' },+ { id: 'organization-1', name: 'Organization 1' },+ { id: 'organization-2', name: 'Organization 2' },],organizationMembers: [{ organizationId: 'organization-1', userId: 'user-1', role: ORGANIZATION_ROLE_MEMBER },@@ -176,7 +176,7 @@ describe('documents repository', () => {{ id: 'user-1', email: '[email protected]' },],organizations: [- { id: 'organization-1', name: 'Organization 1', slug: 'organization-1' },+ { id: 'organization-1', name: 'Organization 1' },],organizationMembers: [{ organizationId: 'organization-1', userId: 'user-1', role: ORGANIZATION_ROLE_MEMBER },diff --git a/apps/papra-server/src/modules/documents/documents.table.test.ts b/apps/papra-server/src/modules/documents/documents.table.test.tsindex 0d7aaa23..57df2bd5 100644--- a/apps/papra-server/src/modules/documents/documents.table.test.ts+++ b/apps/papra-server/src/modules/documents/documents.table.test.ts@@ -10,7 +10,7 @@ describe('documents table', () => {test('when inserting a document, a corresponding row is inserted in the documents_fts table', async () => {const { db } = await createInMemoryDatabase({users: [{ id: 'user-1', email: '[email protected]' }],- organizations: [{ id: 'organization-1', name: 'Organization 1', slug: 'organization-1' }],+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],organizationMembers: [{ organizationId: 'organization-1', userId: 'user-1', role: ORGANIZATION_ROLE_MEMBER }],});@@ -71,7 +71,7 @@ describe('documents table', () => {test('when updating a document, the corresponding row in the documents_fts table is updated', async () => {const { db } = await createInMemoryDatabase({users: [{ id: 'user-1', email: '[email protected]' }],- organizations: [{ id: 'organization-1', name: 'Organization 1', slug: 'organization-1' }],+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],organizationMembers: [{ organizationId: 'organization-1', userId: 'user-1', role: ORGANIZATION_ROLE_MEMBER }],});@@ -134,7 +134,7 @@ describe('documents table', () => {test('when deleting a document, the corresponding row in the documents_fts table is deleted', async () => {const { db } = await createInMemoryDatabase({users: [{ id: 'user-1', email: '[email protected]' }],- organizations: [{ id: 'organization-1', name: 'Organization 1', slug: 'organization-1' }],+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],organizationMembers: [{ organizationId: 'organization-1', userId: 'user-1', role: ORGANIZATION_ROLE_MEMBER }],});diff --git a/apps/papra-server/src/modules/documents/documents.usecases.test.ts b/apps/papra-server/src/modules/documents/documents.usecases.test.tsindex ed3d60b3..5ff188b1 100644--- a/apps/papra-server/src/modules/documents/documents.usecases.test.ts+++ b/apps/papra-server/src/modules/documents/documents.usecases.test.ts@@ -14,7 +14,7 @@ describe('documents usecases', () => {test('creating a document save the file to the storage and registers a record in the db', async () => {const { db } = await createInMemoryDatabase({users: [{ id: 'user-1', email: '[email protected]' }],- organizations: [{ id: 'organization-1', name: 'Organization 1', slug: 'organization-1' }],+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],organizationMembers: [{ organizationId: 'organization-1', userId: 'user-1', role: ORGANIZATION_ROLE_MEMBER }],});@@ -63,7 +63,7 @@ describe('documents usecases', () => {test('in the same organization, we should be able to have two documents with the same content, an error is raised if the document already exists', async () => {const { db } = await createInMemoryDatabase({users: [{ id: 'user-1', email: '[email protected]' }],- organizations: [{ id: 'organization-1', name: 'Organization 1', slug: 'organization-1' }],+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],organizationMembers: [{ organizationId: 'organization-1', userId: 'user-1', role: ORGANIZATION_ROLE_MEMBER }],});@@ -123,7 +123,7 @@ describe('documents usecases', () => {test('when there is an issue when inserting the document in the db, the file should not be saved in the storage', async () => {const { db } = await createInMemoryDatabase({users: [{ id: 'user-1', email: '[email protected]' }],- organizations: [{ id: 'organization-1', name: 'Organization 1', slug: 'organization-1' }],+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],organizationMembers: [{ organizationId: 'organization-1', userId: 'user-1', role: ORGANIZATION_ROLE_MEMBER }],});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 d77d6999..49ebcdd7 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@@ -16,7 +16,7 @@ describe('intake-emails usecases', () => {describe('when a email is forwarded to papra api, we look for the recipient in the intake emails repository and create a papra document for each attachment', () => {test(`when an intake email is is configured, enabled and match the recipient, and the sender is allowed, a document is created for each attachment`, async () => {const { db } = await createInMemoryDatabase({- organizations: [{ id: 'org-1', name: 'Organization 1', slug: 'organization-1' }],+ organizations: [{ id: 'org-1', name: 'Organization 1' }],intakeEmails: [{ id: 'ie-1', organizationId: 'org-1', allowedOrigins: ['[email protected]'], emailAddress: '[email protected]' }],});@@ -108,7 +108,7 @@ describe('intake-emails usecases', () => {const logger = createLogger({ transports: [loggerTransport], namespace: 'test' });const { db } = await createInMemoryDatabase({- organizations: [{ id: 'org-1', name: 'Organization 1', slug: 'organization-1' }],+ organizations: [{ id: 'org-1', name: 'Organization 1' }],intakeEmails: [{ id: 'ie-1', organizationId: 'org-1', allowedOrigins: ['[email protected]'], emailAddress: '[email protected]' }],});@@ -145,8 +145,8 @@ describe('intake-emails usecases', () => {test(`when an email is send to multiple intake emails from different organization, the attachments are processed for each of them`, async () => {const { db } = await createInMemoryDatabase({organizations: [- { id: 'org-1', name: 'Organization 1', slug: 'organization-1' },- { id: 'org-2', name: 'Organization 2', slug: 'organization-2' },+ { id: 'org-1', name: 'Organization 1' },+ { id: 'org-2', name: 'Organization 2' },],intakeEmails: [{ id: 'ie-1', organizationId: 'org-1', allowedOrigins: ['[email protected]'], emailAddress: '[email protected]' },diff --git a/apps/papra-server/src/modules/organizations/organizations.repository.ts b/apps/papra-server/src/modules/organizations/organizations.repository.tsindex 127e1d70..e7f39cda 100644--- a/apps/papra-server/src/modules/organizations/organizations.repository.ts+++ b/apps/papra-server/src/modules/organizations/organizations.repository.ts@@ -1,6 +1,7 @@import type { Database } from '../app/database/database.types';+import type { DbInsertableOrganization } from './organizations.types';import { injectArguments } from '@corentinth/chisels';-import { and, eq } from 'drizzle-orm';+import { and, eq, getTableColumns } from 'drizzle-orm';import { organizationMembersTable, organizationsTable } from './organizations.table';export type OrganizationsRepository = ReturnType<typeof createOrganizationsRepository>;@@ -8,13 +9,42 @@ export type OrganizationsRepository = ReturnType<typeof createOrganizationsReposexport function createOrganizationsRepository({ db }: { db: Database }) {return injectArguments({+ saveOrganization,+ getUserOrganizations,+ addUserToOrganization,isUserInOrganization,+ updateOrganization,+ deleteOrganization,getOrganizationById,},{ db },);}+async function saveOrganization({ organization: organizationToInsert, db }: { organization: DbInsertableOrganization; db: Database }) {+ const [organization] = await db.insert(organizationsTable).values(organizationToInsert).returning();++ return { organization };+}++async function getUserOrganizations({ userId, db }: { userId: string; db: Database }) {+ const organizations = await db+ .select({+ organization: getTableColumns(organizationsTable),+ })+ .from(organizationsTable)+ .leftJoin(organizationMembersTable, eq(organizationsTable.id, organizationMembersTable.organizationId))+ .where(eq(organizationMembersTable.userId, userId));++ return {+ organizations: organizations.map(({ organization }) => organization),+ };+}++async function addUserToOrganization({ userId, organizationId, role, db }: { userId: string; organizationId: string; role: string; db: Database }) {+ await db.insert(organizationMembersTable).values({ userId, organizationId, role });+}+async function isUserInOrganization({ userId, organizationId, db }: { userId: string; organizationId: string; db: Database }) {const organizationUser = await db.select()@@ -29,6 +59,22 @@ async function isUserInOrganization({ userId, organizationId, db }: { userId: st};}+async function updateOrganization({ organizationId, organization: organizationToUpdate, db }: { organizationId: string; organization: { name: string }; db: Database }) {+ const [organization] = await db+ .update(organizationsTable)+ .set({+ name: organizationToUpdate.name,+ })+ .where(eq(organizationsTable.id, organizationId))+ .returning();++ return { organization };+}++async function deleteOrganization({ organizationId, db }: { organizationId: string; db: Database }) {+ await db.delete(organizationsTable).where(eq(organizationsTable.id, organizationId));+}+async function getOrganizationById({ organizationId, db }: { organizationId: string; db: Database }) {const [organization] = await db.select()diff --git a/apps/papra-server/src/modules/organizations/organizations.routes.ts b/apps/papra-server/src/modules/organizations/organizations.routes.tsnew file mode 100644index 00000000..7604fd33--- /dev/null+++ b/apps/papra-server/src/modules/organizations/organizations.routes.ts@@ -0,0 +1,125 @@+import type { ServerInstance } from '../app/server.types';+import { z } from 'zod';+import { getUser } from '../app/auth/auth.models';+import { getDb } from '../app/database/database.models';+import { validateJsonBody, validateParams } from '../shared/validation/validation';+import { organizationIdRegex } from './organizations.constants';+import { createOrganizationsRepository } from './organizations.repository';+import { createOrganization, ensureUserIsInOrganization } from './organizations.usecases';++export async function registerOrganizationsPrivateRoutes({ app }: { app: ServerInstance }) {+ setupGetOrganizationsRoute({ app });+ setupCreateOrganizationRoute({ app });+ setupGetOrganizationRoute({ app });+ setupUpdateOrganizationRoute({ app });+ setupDeleteOrganizationRoute({ app });+}++function setupGetOrganizationsRoute({ app }: { app: ServerInstance }) {+ app.get('/api/organizations', async (context) => {+ const { userId } = getUser({ context });+ const { db } = getDb({ context });++ const organizationsRepository = createOrganizationsRepository({ db });++ const { organizations } = await organizationsRepository.getUserOrganizations({ userId });++ return context.json({+ organizations,+ });+ });+}++function setupCreateOrganizationRoute({ app }: { app: ServerInstance }) {+ app.post(+ '/api/organizations',+ validateJsonBody(z.object({+ name: z.string().min(3).max(50),+ })),+ async (context) => {+ const { userId } = getUser({ context });+ const { db } = getDb({ context });+ const { name } = context.req.valid('json');++ const organizationsRepository = createOrganizationsRepository({ db });++ const { organization } = await createOrganization({ userId, name, organizationsRepository });++ return context.json({+ organization,+ });+ },+ );+}++function setupGetOrganizationRoute({ app }: { app: ServerInstance }) {+ app.get(+ '/api/organizations/:organizationId',+ validateParams(z.object({+ organizationId: z.string().regex(organizationIdRegex),+ })),+ async (context) => {+ const { userId } = getUser({ context });+ const { db } = getDb({ context });+ const { organizationId } = context.req.valid('param');++ const organizationsRepository = createOrganizationsRepository({ db });++ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });++ const { organization } = await organizationsRepository.getOrganizationById({ organizationId });++ return context.json({ organization });+ },+ );+}++function setupUpdateOrganizationRoute({ app }: { app: ServerInstance }) {+ app.put(+ '/api/organizations/:organizationId',+ validateJsonBody(z.object({+ name: z.string().min(3).max(50),+ })),+ validateParams(z.object({+ organizationId: z.string().regex(organizationIdRegex),+ })),+ async (context) => {+ const { userId } = getUser({ context });+ const { db } = getDb({ context });+ const { name } = context.req.valid('json');+ const { organizationId } = context.req.valid('param');++ const organizationsRepository = createOrganizationsRepository({ db });++ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });++ const { organization } = await organizationsRepository.updateOrganization({ organizationId, organization: { name } });++ return context.json({+ organization,+ });+ },+ );+}++function setupDeleteOrganizationRoute({ app }: { app: ServerInstance }) {+ app.delete(+ '/api/organizations/:organizationId',+ validateParams(z.object({+ organizationId: z.string().regex(organizationIdRegex),+ })),+ async (context) => {+ const { userId } = getUser({ context });+ const { db } = getDb({ context });+ const { organizationId } = context.req.valid('param');++ const organizationsRepository = createOrganizationsRepository({ db });++ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });++ await organizationsRepository.deleteOrganization({ organizationId });++ return context.body(null, 204);+ },+ );+}diff --git a/apps/papra-server/src/modules/organizations/organizations.table.ts b/apps/papra-server/src/modules/organizations/organizations.table.tsindex aed8e863..ba2666ae 100644--- a/apps/papra-server/src/modules/organizations/organizations.table.ts+++ b/apps/papra-server/src/modules/organizations/organizations.table.ts@@ -1,4 +1,4 @@-import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core';+import { integer, sqliteTable, text, unique } from 'drizzle-orm/sqlite-core';import { createPrimaryKeyField, createTimestampColumns } from '../shared/db/columns.helpers';import { usersTable } from '../users/users.table';@@ -7,19 +7,24 @@ export const organizationsTable = sqliteTable('organizations', {...createTimestampColumns(),name: text('name').notNull(),- slug: text('slug').unique(),- logo: text('logo'),- metadata: text('metadata'),});export const organizationMembersTable = sqliteTable('organization_members', {...createPrimaryKeyField({ prefix: 'org_mem' }),...createTimestampColumns(),- organizationId: text('organization_id').notNull().references(() => organizationsTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),- userId: text('user_id').notNull().references(() => usersTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),+ organizationId: text('organization_id')+ .notNull()+ .references(() => organizationsTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),++ userId: text('user_id')+ .notNull()+ .references(() => usersTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),+role: text('role').notNull(),-});+}, t => [+ unique('organization_members_user_organization_unique').on(t.organizationId, t.userId),+]);export const organizationInvitationsTable = sqliteTable('organization_invitations', {...createPrimaryKeyField({ prefix: 'org_inv' }),@@ -29,6 +34,6 @@ export const organizationInvitationsTable = sqliteTable('organization_invitationemail: text('email').notNull(),role: text('role'),status: text('status').notNull(),- expiresAt: integer('expires_at', { mode: 'timestamp' }).notNull(),+ expiresAt: integer('expires_at', { mode: 'timestamp_ms' }).notNull(),inviterId: text('inviter_id').notNull().references(() => usersTable.id, { onDelete: 'cascade', onUpdate: 'cascade' }),});diff --git a/apps/papra-server/src/modules/organizations/organizations.usecases.test.ts b/apps/papra-server/src/modules/organizations/organizations.usecases.test.tsindex 6d9d20a7..9fe07497 100644--- a/apps/papra-server/src/modules/organizations/organizations.usecases.test.ts+++ b/apps/papra-server/src/modules/organizations/organizations.usecases.test.ts@@ -11,7 +11,7 @@ describe('organizations usecases', () => {test('the user is in the organization and the organization exists', async () => {const { db } = await createInMemoryDatabase({users: [{ id: 'user-1', email: '[email protected]' }],- organizations: [{ id: 'organization-1', name: 'Organization 1', slug: 'organization-1' }],+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],organizationMembers: [{ organizationId: 'organization-1', userId: 'user-1', role: ORGANIZATION_ROLE_MEMBER }],});@@ -29,7 +29,7 @@ describe('organizations usecases', () => {test('the user is not in the organization', async () => {const { db } = await createInMemoryDatabase({users: [{ id: 'user-1', email: '[email protected]' }],- organizations: [{ id: 'organization-1', name: 'Organization 1', slug: 'organization-1' }],+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],});const organizationsRepository = createOrganizationsRepository({ db });diff --git a/apps/papra-server/src/modules/organizations/organizations.usecases.ts b/apps/papra-server/src/modules/organizations/organizations.usecases.tsindex c5f374e5..e19597ff 100644--- a/apps/papra-server/src/modules/organizations/organizations.usecases.ts+++ b/apps/papra-server/src/modules/organizations/organizations.usecases.ts@@ -1,6 +1,19 @@import type { OrganizationsRepository } from './organizations.repository';+import { ORGANIZATION_ROLE_OWNER } from './organizations.constants';import { createUserNotInOrganizationError } from './organizations.errors';+export async function createOrganization({ name, userId, organizationsRepository }: { name: string; userId: string; organizationsRepository: OrganizationsRepository }) {+ const { organization } = await organizationsRepository.saveOrganization({ organization: { name } });++ await organizationsRepository.addUserToOrganization({+ userId,+ organizationId: organization.id,+ role: ORGANIZATION_ROLE_OWNER,+ });++ return { organization };+}+export async function ensureUserIsInOrganization({userId,organizationId,diff --git a/apps/papra-server/src/modules/tags/tags.repository.test.ts b/apps/papra-server/src/modules/tags/tags.repository.test.tsindex f545188e..67108628 100644--- a/apps/papra-server/src/modules/tags/tags.repository.test.ts+++ b/apps/papra-server/src/modules/tags/tags.repository.test.ts@@ -70,7 +70,7 @@ describe('tags repository', () => {test('a tag can be be added only once to a document', async () => {const { db } = await createInMemoryDatabase({users: [{ id: 'user-1', email: '[email protected]' }],- organizations: [{ id: 'organization-1', name: 'Organization 1', slug: 'organization-1' }],+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],organizationMembers: [{ organizationId: 'organization-1', userId: 'user-1', role: ORGANIZATION_ROLE_MEMBER }],documents: [{ id: 'document-1', organizationId: 'organization-1', createdBy: 'user-1', name: 'Document 1', originalName: 'document-1.pdf', content: 'lorem ipsum', originalStorageKey: '', mimeType: 'application/pdf', originalSha256Hash: 'hash' },