Skip to content

armgit / papra

Public Imported from GitHub
0

The minimalistic document archiving platform.

fix(invitations): allow reinviting former members (#1534)

Corentin Thomasseta03dc5ab2406
diff --git a/.changeset/silent-years-train.md b/.changeset/silent-years-train.md
new file mode 100644
index 00000000..a9a6e512
--- /dev/null
+++ b/.changeset/silent-years-train.md
@@ -0,0 +1,5 @@
+---
+'@papra/app': patch
+---
+
+Fix an issue that prevented reinviting users who left or were removed from an organisation.
diff --git a/apps/papra-server/src/migrations/list/0028-pending-organization-invitations-unique.migration.test.ts b/apps/papra-server/src/migrations/list/0028-pending-organization-invitations-unique.migration.test.ts
new file mode 100644
index 00000000..67965a94
--- /dev/null
+++ b/apps/papra-server/src/migrations/list/0028-pending-organization-invitations-unique.migration.test.ts
@@ -0,0 +1,124 @@
+import { createNoopLogger } from '@crowlog/logger';
+import { eq } from 'drizzle-orm';
+import { describe, expect, test } from 'vitest';
+import { setupDatabase } from '../../modules/app/database/database';
+import {
+ createInMemoryDatabase,
+ seedDatabase,
+} from '../../modules/app/database/database.test-utils';
+import { organizationInvitationsTable } from '../../modules/organizations/organizations.table';
+import { migrations } from '../migrations.registry';
+import { runMigrations } from '../migrations.usecases';
+import { pendingOrganizationInvitationsUniqueMigration } from './0028-pending-organization-invitations-unique.migration';
+
+describe('pending organization invitations unique migration', () => {
+ test('existing accepted invitations are preserved and no longer block new invitations after upgrading', async () => {
+ const { db } = setupDatabase({ url: ':memory:' });
+ await runMigrations({
+ db,
+ migrations: migrations.slice(
+ 0,
+ migrations.indexOf(pendingOrganizationInvitationsUniqueMigration),
+ ),
+ logger: createNoopLogger(),
+ });
+ const invitation = {
+ organizationId: 'org',
+ email: '[email protected]',
+ inviterId: 'owner',
+ role: 'member' as const,
+ expiresAt: new Date('2025-10-12'),
+ };
+ await seedDatabase({
+ db,
+ users: [{ id: 'owner', email: '[email protected]' }],
+ organizations: [
+ { id: 'org', name: 'Organization' },
+ { id: 'other-org', name: 'Other organization' },
+ ],
+ organizationInvitations: [{ ...invitation, id: 'accepted', status: 'accepted' }],
+ });
+ const [acceptedInvitation] = await db.select().from(organizationInvitationsTable);
+
+ await expect(
+ db
+ .insert(organizationInvitationsTable)
+ .values({ ...invitation, id: 'pending', status: 'pending' }),
+ ).rejects.toThrow();
+
+ await pendingOrganizationInvitationsUniqueMigration.up({ db });
+ await pendingOrganizationInvitationsUniqueMigration.up({ db });
+
+ await db
+ .insert(organizationInvitationsTable)
+ .values({ ...invitation, id: 'pending', status: 'pending' });
+ await expect(
+ db
+ .insert(organizationInvitationsTable)
+ .values({ ...invitation, id: 'duplicate', status: 'pending' }),
+ ).rejects.toThrow();
+ await db.insert(organizationInvitationsTable).values({
+ ...invitation,
+ id: 'other-org-invitation',
+ organizationId: 'other-org',
+ status: 'pending',
+ });
+
+ const invitations = await db
+ .select()
+ .from(organizationInvitationsTable)
+ .orderBy(organizationInvitationsTable.id);
+ expect(invitations).toHaveLength(3);
+ expect(invitations[0]).toEqual(acceptedInvitation);
+ });
+
+ test('rollback discards invitation history while preserving pending invitations and restoring uniqueness', async () => {
+ const invitation = {
+ organizationId: 'org',
+ email: '[email protected]',
+ inviterId: 'owner',
+ role: 'member' as const,
+ expiresAt: new Date('2025-10-12'),
+ };
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'owner', email: '[email protected]' }],
+ organizations: [
+ { id: 'org', name: 'Organization' },
+ { id: 'other-org', name: 'Other organization' },
+ ],
+ organizationInvitations: [
+ { ...invitation, id: 'accepted', status: 'accepted' },
+ { ...invitation, id: 'cancelled', status: 'cancelled' },
+ { ...invitation, id: 'expired', status: 'expired' },
+ { ...invitation, id: 'rejected', status: 'rejected' },
+ { ...invitation, id: 'pending', status: 'pending' },
+ { ...invitation, id: 'other-pending', organizationId: 'other-org', status: 'pending' },
+ { ...invitation, id: 'history-only', email: '[email protected]', status: 'accepted' },
+ ],
+ });
+ const pendingInvitations = await db
+ .select()
+ .from(organizationInvitationsTable)
+ .where(eq(organizationInvitationsTable.status, 'pending'))
+ .orderBy(organizationInvitationsTable.id);
+
+ await pendingOrganizationInvitationsUniqueMigration.down({ db });
+
+ expect(
+ await db.select().from(organizationInvitationsTable).orderBy(organizationInvitationsTable.id),
+ ).toEqual(pendingInvitations);
+
+ await expect(
+ db
+ .insert(organizationInvitationsTable)
+ .values({ ...invitation, id: 'duplicate', status: 'accepted' }),
+ ).rejects.toThrow();
+
+ await pendingOrganizationInvitationsUniqueMigration.up({ db });
+
+ await db
+ .insert(organizationInvitationsTable)
+ .values({ ...invitation, id: 'new-history', status: 'accepted' });
+ expect(await db.select().from(organizationInvitationsTable)).toHaveLength(3);
+ });
+});
diff --git a/apps/papra-server/src/migrations/list/0028-pending-organization-invitations-unique.migration.ts b/apps/papra-server/src/migrations/list/0028-pending-organization-invitations-unique.migration.ts
new file mode 100644
index 00000000..ab26b8f7
--- /dev/null
+++ b/apps/papra-server/src/migrations/list/0028-pending-organization-invitations-unique.migration.ts
@@ -0,0 +1,27 @@
+import type { Migration } from '../migrations.types';
+import { sql } from 'drizzle-orm';
+
+export const pendingOrganizationInvitationsUniqueMigration = {
+ name: 'pending-organization-invitations-unique',
+
+ up: async ({ db }) => {
+ await db.batch([
+ db.run(sql`DROP INDEX IF EXISTS organization_invitations_organization_email_unique`),
+ db.run(
+ sql`CREATE UNIQUE INDEX IF NOT EXISTS organization_invitations_pending_organization_email_unique ON organization_invitations (organization_id, email) WHERE status = 'pending'`,
+ ),
+ ]);
+ },
+
+ down: async ({ db }) => {
+ await db.batch([
+ // Rollback discards invitation history to restore the old uniqueness constraint.
+ // The pending-only index guarantees the remaining invitations are unique.
+ db.run(sql`DELETE FROM organization_invitations WHERE status <> 'pending'`),
+ db.run(
+ sql`CREATE UNIQUE INDEX IF NOT EXISTS "organization_invitations_organization_email_unique" ON "organization_invitations" ("organization_id","email")`,
+ ),
+ db.run(sql`DROP INDEX IF EXISTS organization_invitations_pending_organization_email_unique`),
+ ]);
+ },
+} satisfies Migration;
diff --git a/apps/papra-server/src/migrations/migrations.registry.test.ts b/apps/papra-server/src/migrations/migrations.registry.test.ts
index f1502400..518e76a1 100644
--- a/apps/papra-server/src/migrations/migrations.registry.test.ts
+++ b/apps/papra-server/src/migrations/migrations.registry.test.ts
@@ -116,7 +116,7 @@ describe('migrations registry', () => {
CREATE INDEX migrations_run_at_index ON migrations (run_at);
CREATE INDEX "organization_ai_credits_usage_organization_id_created_at_index" ON "organization_ai_credits_usage" ("organization_id", "created_at");
CREATE INDEX "organization_ai_credits_usage_organization_id_index" ON "organization_ai_credits_usage" ("organization_id");
- CREATE UNIQUE INDEX "organization_invitations_organization_email_unique" ON "organization_invitations" ("organization_id","email");
+ CREATE UNIQUE INDEX organization_invitations_pending_organization_email_unique ON organization_invitations (organization_id, email) WHERE status = 'pending';
CREATE INDEX "organization_members_user_id_index" ON "organization_members" ("user_id");
CREATE UNIQUE INDEX "organization_members_user_organization_unique" ON "organization_members" ("organization_id","user_id");
CREATE INDEX "organization_subscriptions_organization_id_index" ON "organization_subscriptions" ("organization_id");
diff --git a/apps/papra-server/src/migrations/migrations.registry.ts b/apps/papra-server/src/migrations/migrations.registry.ts
index 9337a48b..fb3ed92e 100644
--- a/apps/papra-server/src/migrations/migrations.registry.ts
+++ b/apps/papra-server/src/migrations/migrations.registry.ts
@@ -27,6 +27,7 @@ import { userPlanEntitlementsMigration } from './list/0024-user-plan-entitlement
import { addOrganizationSettingsTableMigration } from './list/0025-add-organization-settings-table.migration';
import { addIndexesMigration } from './list/0026-add-indexes.migration';
import { aiCreditsMigration } from './list/0027-ai-credits.migration';
+import { pendingOrganizationInvitationsUniqueMigration } from './list/0028-pending-organization-invitations-unique.migration';
export const migrations: Migration[] = [
initialSchemaSetupMigration,
@@ -56,4 +57,5 @@ export const migrations: Migration[] = [
addOrganizationSettingsTableMigration,
addIndexesMigration,
aiCreditsMigration,
+ pendingOrganizationInvitationsUniqueMigration,
];
diff --git a/apps/papra-server/src/modules/invitations/invitations.routes.ts b/apps/papra-server/src/modules/invitations/invitations.routes.ts
index f48a1c9d..32994d8d 100644
--- a/apps/papra-server/src/modules/invitations/invitations.routes.ts
+++ b/apps/papra-server/src/modules/invitations/invitations.routes.ts
@@ -9,10 +9,18 @@ import {
ORGANIZATION_ROLES,
} from '../organizations/organizations.constants';
import { createOrganizationsRepository } from '../organizations/organizations.repository';
-import { resendOrganizationInvitation } from '../organizations/organizations.usecases';
+import {
+ buildResendOrganizationInvitation,
+ checkIfUserHasReachedOrganizationInvitationLimit,
+ sendOrganizationInvitationEmail,
+} from '../organizations/organizations.usecases';
+import { createPlanEntitlementsRepository } from '../plan-entitlements/plan-entitlements.repository';
+import { createPlansRepository } from '../plans/plans.repository';
+import { createGetOrganizationPlanUsecase } from '../plans/plans.usecases';
import { createError } from '../shared/errors/errors';
import { createLogger } from '../shared/logger/logger';
import { validateParams } from '../shared/validation/validation';
+import { createSubscriptionsRepository } from '../subscriptions/subscriptions.repository';
import { createUsersRepository } from '../users/users.repository';
const logger = createLogger({ namespace: 'invitations' });
@@ -216,7 +224,40 @@ function setupCancelInvitationRoute({ app, db }: RouteDefinitionContext) {
);
}
-function setupResendInvitationRoute({ app, db, config, emailsServices }: RouteDefinitionContext) {
+function setupResendInvitationRoute({
+ app,
+ db,
+ config,
+ emailsServices,
+ planEntitlementDefinitionRegistry,
+}: RouteDefinitionContext) {
+ const organizationsRepository = createOrganizationsRepository({ db });
+ const resendOrganizationInvitation = buildResendOrganizationInvitation({
+ organizationsRepository,
+ getOrganizationPlan: createGetOrganizationPlanUsecase({
+ subscriptionsRepository: createSubscriptionsRepository({ db }),
+ plansRepository: createPlansRepository({ config }),
+ planEntitlementsRepository: createPlanEntitlementsRepository({ db }),
+ planEntitlementDefinitionRegistry,
+ }),
+ checkIfUserHasReachedOrganizationInvitationLimit: async ({ userId, now }) =>
+ checkIfUserHasReachedOrganizationInvitationLimit({
+ userId,
+ now,
+ maxInvitationsPerDay: config.organizations.maxUserInvitationsPerDay,
+ organizationsRepository,
+ }),
+ sendOrganizationInvitationEmail: async ({ email, organizationId }) =>
+ sendOrganizationInvitationEmail({
+ email,
+ organizationId,
+ organizationsRepository,
+ emailsServices,
+ config,
+ }),
+ expirationDelayDays: config.organizations.invitationExpirationDelayDays,
+ });
+
app.post(
'/api/invitations/:invitationId/resend',
requireAuthentication(),
@@ -229,14 +270,9 @@ function setupResendInvitationRoute({ app, db, config, emailsServices }: RouteDe
const { invitationId } = context.req.valid('param');
const { userId } = getUser({ context });
- const organizationsRepository = createOrganizationsRepository({ db });
-
await resendOrganizationInvitation({
invitationId,
userId,
- organizationsRepository,
- emailsServices,
- config,
});
return context.body(null, 204);
diff --git a/apps/papra-server/src/modules/organizations/organizations.repository.test.ts b/apps/papra-server/src/modules/organizations/organizations.repository.test.ts
index 9026be14..abc777d6 100644
--- a/apps/papra-server/src/modules/organizations/organizations.repository.test.ts
+++ b/apps/papra-server/src/modules/organizations/organizations.repository.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, test } from 'vitest';
import { createInMemoryDatabase } from '../app/database/database.test-utils';
+import { createOrganizationInvitationAlreadyExistsError } from './organizations.errors';
import { createOrganizationsRepository } from './organizations.repository';
import {
organizationInvitationsTable,
@@ -8,6 +9,73 @@ import {
} from './organizations.table';
describe('organizations repository', () => {
+ describe('pending invitation uniqueness', () => {
+ test('concurrent invitations for the same recipient yield one invitation and a duplicate invitation error', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'owner', email: '[email protected]' }],
+ organizations: [{ id: 'org', name: 'Organization' }],
+ });
+ const organizationsRepository = createOrganizationsRepository({ db });
+ const invitation = {
+ organizationId: 'org',
+ email: '[email protected]',
+ inviterId: 'owner',
+ role: 'member' as const,
+ };
+
+ const results = await Promise.allSettled([
+ organizationsRepository.saveOrganizationInvitation(invitation),
+ organizationsRepository.saveOrganizationInvitation(invitation),
+ ]);
+
+ expect(results.filter(({ status }) => status === 'fulfilled')).toHaveLength(1);
+ expect(results.find(({ status }) => status === 'rejected')).toMatchObject({
+ status: 'rejected',
+ reason: createOrganizationInvitationAlreadyExistsError(),
+ });
+ expect(await db.select().from(organizationInvitationsTable)).toHaveLength(1);
+ });
+
+ test('reactivating a historical invitation cannot create a second pending invitation', async () => {
+ const invitation = {
+ organizationId: 'org',
+ email: '[email protected]',
+ inviterId: 'owner',
+ role: 'member' as const,
+ expiresAt: new Date('2025-10-12'),
+ };
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'owner', email: '[email protected]' }],
+ organizations: [{ id: 'org', name: 'Organization' }],
+ organizationInvitations: [
+ { ...invitation, id: 'cancelled', status: 'cancelled' },
+ { ...invitation, id: 'pending', status: 'pending' },
+ ],
+ });
+ const organizationsRepository = createOrganizationsRepository({ db });
+
+ await expect(
+ organizationsRepository.updateOrganizationInvitation({
+ invitationId: 'cancelled',
+ status: 'pending',
+ }),
+ ).rejects.toThrow(createOrganizationInvitationAlreadyExistsError());
+
+ expect(
+ await db
+ .select({
+ id: organizationInvitationsTable.id,
+ status: organizationInvitationsTable.status,
+ })
+ .from(organizationInvitationsTable)
+ .orderBy(organizationInvitationsTable.id),
+ ).toEqual([
+ { id: 'cancelled', status: 'cancelled' },
+ { id: 'pending', status: 'pending' },
+ ]);
+ });
+ });
+
describe('updateExpiredPendingInvitationsStatus', () => {
test('the pending invitations that are expired (expiredAt < now) are updated to expired', async () => {
const commonInvitation = {
diff --git a/apps/papra-server/src/modules/organizations/organizations.repository.ts b/apps/papra-server/src/modules/organizations/organizations.repository.ts
index 96b79b35..7401d102 100644
--- a/apps/papra-server/src/modules/organizations/organizations.repository.ts
+++ b/apps/papra-server/src/modules/organizations/organizations.repository.ts
@@ -4,14 +4,18 @@ import type {
OrganizationInvitationStatus,
OrganizationRole,
} from './organizations.types';
-import { injectArguments } from '@corentinth/chisels';
+import { injectArguments, safely } from '@corentinth/chisels';
import { and, count, desc, eq, getTableColumns, gte, isNotNull, isNull, lte } from 'drizzle-orm';
import { addDays, startOfDay } from '../shared/date';
+import { isUniqueConstraintError } from '../shared/db/constraints.models';
import { withPagination } from '../shared/db/pagination';
import { omitUndefined } from '../shared/objects';
import { usersTable } from '../users/users.table';
import { ORGANIZATION_INVITATION_STATUS, ORGANIZATION_ROLES } from './organizations.constants';
-import { createOrganizationNotFoundError } from './organizations.errors';
+import {
+ createOrganizationInvitationAlreadyExistsError,
+ createOrganizationNotFoundError,
+} from './organizations.errors';
import {
createSearchOrganizationWhereClause,
ensureInvitationStatus,
@@ -50,7 +54,7 @@ export function createOrganizationsRepository({ db }: { db: Database }) {
getOrganizationInvitationById,
updateOrganizationInvitation,
getPendingInvitationsCount,
- getInvitationForEmailAndOrganization,
+ getPendingInvitationForEmailAndOrganization,
getOrganizationMemberByEmail,
getOrganizationInvitations,
updateExpiredPendingInvitationsStatus,
@@ -401,17 +405,29 @@ async function saveOrganizationInvitation({
expirationDelayDays?: number;
now?: Date;
}) {
- const [organizationInvitation] = await db
- .insert(organizationInvitationsTable)
- .values({
- organizationId,
- email,
- role,
- inviterId,
- status: ORGANIZATION_INVITATION_STATUS.PENDING,
- expiresAt: addDays(now, expirationDelayDays),
- })
- .returning();
+ const [result, error] = await safely(
+ db
+ .insert(organizationInvitationsTable)
+ .values({
+ organizationId,
+ email,
+ role,
+ inviterId,
+ status: ORGANIZATION_INVITATION_STATUS.PENDING,
+ expiresAt: addDays(now, expirationDelayDays),
+ })
+ .returning(),
+ );
+
+ if (isUniqueConstraintError({ error })) {
+ throw createOrganizationInvitationAlreadyExistsError();
+ }
+
+ if (error) {
+ throw error;
+ }
+
+ const [organizationInvitation] = result;
return { organizationInvitation };
}
@@ -513,15 +529,25 @@ async function updateOrganizationInvitation({
expiresAt?: Date;
db: Database;
}) {
- await db
- .update(organizationInvitationsTable)
- .set(
- omitUndefined({
- status,
- expiresAt,
- }),
- )
- .where(eq(organizationInvitationsTable.id, invitationId));
+ const [, error] = await safely(
+ db
+ .update(organizationInvitationsTable)
+ .set(
+ omitUndefined({
+ status,
+ expiresAt,
+ }),
+ )
+ .where(eq(organizationInvitationsTable.id, invitationId)),
+ );
+
+ if (isUniqueConstraintError({ error })) {
+ throw createOrganizationInvitationAlreadyExistsError();
+ }
+
+ if (error) {
+ throw error;
+ }
}
async function getPendingInvitationsCount({
@@ -558,16 +584,14 @@ async function getPendingInvitationsCount({
};
}
-async function getInvitationForEmailAndOrganization({
+async function getPendingInvitationForEmailAndOrganization({
email,
organizationId,
db,
- now = new Date(),
}: {
email: string;
organizationId: string;
db: Database;
- now?: Date;
}) {
const [invitation] = await db
.select()
@@ -576,11 +600,12 @@ async function getInvitationForEmailAndOrganization({
and(
eq(organizationInvitationsTable.email, email),
eq(organizationInvitationsTable.organizationId, organizationId),
+ eq(organizationInvitationsTable.status, ORGANIZATION_INVITATION_STATUS.PENDING),
),
);
return {
- invitation: ensureInvitationStatus({ invitation, now }),
+ invitation,
};
}
@@ -627,9 +652,11 @@ async function getOrganizationInvitations({
async function updateExpiredPendingInvitationsStatus({
db,
+ organizationId,
now = new Date(),
}: {
db: Database;
+ organizationId?: string;
now?: Date;
}) {
await db
@@ -639,6 +666,9 @@ async function updateExpiredPendingInvitationsStatus({
and(
lte(organizationInvitationsTable.expiresAt, now),
eq(organizationInvitationsTable.status, ORGANIZATION_INVITATION_STATUS.PENDING),
+ organizationId === undefined
+ ? undefined
+ : eq(organizationInvitationsTable.organizationId, organizationId),
),
);
}
diff --git a/apps/papra-server/src/modules/organizations/organizations.usecases.test.ts b/apps/papra-server/src/modules/organizations/organizations.usecases.test.ts
index bb501c2d..49d05b43 100644
--- a/apps/papra-server/src/modules/organizations/organizations.usecases.test.ts
+++ b/apps/papra-server/src/modules/organizations/organizations.usecases.test.ts
@@ -1,6 +1,7 @@
import type { StorageService } from '../storage/storage.services';
import type { EmailsServices } from '../emails/emails.services';
import type { SubscriptionsServices } from '../subscriptions/subscriptions.services';
+import type { OrganizationInvitationStatus } from './organizations.types';
import { assert, describe, expect, test } from 'vitest';
import { createForbiddenError } from '../app/auth/auth.errors';
import { createInMemoryDatabase } from '../app/database/database.test-utils';
@@ -10,7 +11,7 @@ import { createTestClock } from '../shared/clock/clock.test-utils';
import { createTestLogger } from '../shared/logger/logger.test-utils';
import { createSubscriptionsRepository } from '../subscriptions/subscriptions.repository';
import { createUsersRepository } from '../users/users.repository';
-import { ORGANIZATION_ROLES } from './organizations.constants';
+import { ORGANIZATION_INVITATION_STATUS, ORGANIZATION_ROLES } from './organizations.constants';
import {
createMaxOrganizationMembersCountReachedError,
createOrganizationHasActiveSubscriptionError,
@@ -30,6 +31,7 @@ import {
} from './organizations.table';
import {
buildInviteMemberToOrganization,
+ buildResendOrganizationInvitation,
checkIfUserCanCreateNewOrganization,
checkIfUserHasReachedOrganizationInvitationLimit,
ensureUserIsInOrganization,
@@ -637,8 +639,288 @@ describe('organizations usecases', () => {
]);
});
+ test('a former member can be reinvited after being removed from the organization', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [
+ { id: 'user-1', email: '[email protected]' },
+ { id: 'user-2', email: '[email protected]' },
+ ],
+ organizations: [{ id: 'organization-1', name: 'Organization 1' }],
+ organizationMembers: [
+ { organizationId: 'organization-1', userId: 'user-1', role: ORGANIZATION_ROLES.OWNER },
+ ],
+ });
+
+ const organizationsRepository = createOrganizationsRepository({ db });
+ const { logger } = createTestLogger();
+ const { clock } = createTestClock({ now: '2025-10-05T12:00:00Z' });
+ const inviteMemberToOrganization = buildInviteMemberToOrganization({
+ organizationsRepository,
+ getOrganizationPlan: async () => ({
+ organizationPlan: { limits: { maxOrganizationsMembersCount: 100 } },
+ }),
+ checkIfUserHasReachedOrganizationInvitationLimit: async () => {},
+ sendOrganizationInvitationEmail: async () => {},
+ expirationDelayDays: 7,
+ clock,
+ logger,
+ });
+
+ // Invite a member to the organization
+ const { organizationInvitation: initialInvitation } = await inviteMemberToOrganization({
+ email: '[email protected]',
+ role: ORGANIZATION_ROLES.MEMBER,
+ organizationId: 'organization-1',
+ inviterId: 'user-1',
+ });
+
+ expect.assert(initialInvitation);
+
+ // Accept the invitation to become a member
+ await organizationsRepository.updateOrganizationInvitation({
+ invitationId: initialInvitation.id,
+ status: ORGANIZATION_INVITATION_STATUS.ACCEPTED,
+ });
+ await organizationsRepository.addUserToOrganization({
+ organizationId: 'organization-1',
+ userId: 'user-2',
+ role: ORGANIZATION_ROLES.MEMBER,
+ });
+ const { member } = await organizationsRepository.getOrganizationMemberByUserId({
+ organizationId: 'organization-1',
+ userId: 'user-2',
+ });
+ assert(member);
+
+ await removeMemberFromOrganization({
+ memberId: member.id,
+ userId: 'user-1',
+ organizationId: 'organization-1',
+ organizationsRepository,
+ });
+
+ const { organizationInvitation } = await inviteMemberToOrganization({
+ email: '[email protected]',
+ role: ORGANIZATION_ROLES.ADMIN,
+ organizationId: 'organization-1',
+ inviterId: 'user-1',
+ });
+
+ assert(organizationInvitation);
+ expect(organizationInvitation).toMatchObject({
+ email: '[email protected]',
+ organizationId: 'organization-1',
+ status: ORGANIZATION_INVITATION_STATUS.PENDING,
+ role: ORGANIZATION_ROLES.ADMIN,
+ expiresAt: new Date('2025-10-12T12:00:00Z'),
+ });
+ expect(organizationInvitation.id).not.toEqual(initialInvitation.id);
+ expect(
+ await organizationsRepository.isUserInOrganization({
+ organizationId: 'organization-1',
+ userId: 'user-2',
+ }),
+ ).toEqual({ isInOrganization: false });
+
+ await expect(
+ inviteMemberToOrganization({
+ email: '[email protected]',
+ role: ORGANIZATION_ROLES.MEMBER,
+ organizationId: 'organization-1',
+ inviterId: 'user-1',
+ }),
+ ).rejects.toThrow(createOrganizationInvitationAlreadyExistsError());
+
+ const invitations = await db
+ .select({
+ id: organizationInvitationsTable.id,
+ status: organizationInvitationsTable.status,
+ })
+ .from(organizationInvitationsTable)
+ .orderBy(organizationInvitationsTable.status);
+
+ expect(invitations).toEqual([
+ { id: initialInvitation.id, status: 'accepted' },
+ { id: organizationInvitation.id, status: 'pending' },
+ ]);
+ });
+
+ test('a member who leaves can be reinvited repeatedly while keeping accepted invitations', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [
+ { id: 'owner', email: '[email protected]' },
+ { id: 'member', email: '[email protected]' },
+ ],
+ organizations: [{ id: 'org', name: 'Organization' }],
+ organizationMembers: [{ organizationId: 'org', userId: 'owner', role: 'owner' }],
+ });
+ const organizationsRepository = createOrganizationsRepository({ db });
+ const { clock } = createTestClock({ now: '2025-10-05T12:00:00Z' });
+ const inviteMemberToOrganization = buildInviteMemberToOrganization({
+ organizationsRepository,
+ getOrganizationPlan: async () => ({
+ organizationPlan: { limits: { maxOrganizationsMembersCount: 2 } },
+ }),
+ checkIfUserHasReachedOrganizationInvitationLimit: async () => {},
+ sendOrganizationInvitationEmail: async () => {},
+ expirationDelayDays: 7,
+ clock,
+ });
+ const invitationIds: string[] = [];
+
+ for (const role of [
+ ORGANIZATION_ROLES.MEMBER,
+ ORGANIZATION_ROLES.ADMIN,
+ ORGANIZATION_ROLES.MEMBER,
+ ]) {
+ const { organizationInvitation } = await inviteMemberToOrganization({
+ email: '[email protected]',
+ organizationId: 'org',
+ inviterId: 'owner',
+ role,
+ });
+ assert(organizationInvitation);
+ invitationIds.push(organizationInvitation.id);
+
+ await organizationsRepository.addUserToOrganization({
+ userId: 'member',
+ organizationId: 'org',
+ role: organizationInvitation.role,
+ });
+ await organizationsRepository.updateOrganizationInvitation({
+ invitationId: organizationInvitation.id,
+ status: 'accepted',
+ });
+ await organizationsRepository.removeUserFromOrganization({
+ userId: 'member',
+ organizationId: 'org',
+ });
+ clock.advanceBy({ hours: 24 });
+ }
+
+ const invitations = await db.select().from(organizationInvitationsTable);
+ expect(new Set(invitationIds).size).toEqual(3);
+ expect(invitations.map(({ status }) => status)).toEqual(['accepted', 'accepted', 'accepted']);
+ });
+
+ test('expired, cancelled and rejected invitations do not prevent a fresh invitation', async () => {
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'owner', email: '[email protected]' }],
+ organizations: [{ id: 'org', name: 'Organization' }],
+ organizationMembers: [{ organizationId: 'org', userId: 'owner', role: 'owner' }],
+ organizationInvitations: (['expired', 'cancelled', 'rejected'] as const).map((status) => ({
+ id: status,
+ organizationId: 'org',
+ email: '[email protected]',
+ role: 'member',
+ inviterId: 'owner',
+ status,
+ expiresAt: new Date('2025-10-01'),
+ })),
+ });
+ const organizationsRepository = createOrganizationsRepository({ db });
+ const { clock } = createTestClock({ now: '2025-10-05T12:00:00Z' });
+ const inviteMemberToOrganization = buildInviteMemberToOrganization({
+ organizationsRepository,
+ getOrganizationPlan: async () => ({
+ organizationPlan: { limits: { maxOrganizationsMembersCount: 2 } },
+ }),
+ checkIfUserHasReachedOrganizationInvitationLimit: async () => {},
+ sendOrganizationInvitationEmail: async () => {},
+ expirationDelayDays: 7,
+ clock,
+ });
+
+ const { organizationInvitation } = await inviteMemberToOrganization({
+ email: '[email protected]',
+ organizationId: 'org',
+ inviterId: 'owner',
+ role: 'admin',
+ });
+
+ expect(organizationInvitation).toMatchObject({
+ status: 'pending',
+ role: 'admin',
+ expiresAt: new Date('2025-10-12T12:00:00Z'),
+ });
+ expect(await db.select().from(organizationInvitationsTable)).toHaveLength(4);
+ });
+
+ test('stale pending invitations expire immediately and stop consuming organization capacity', async () => {
+ const commonInvitation = {
+ role: ORGANIZATION_ROLES.MEMBER,
+ inviterId: 'owner',
+ status: ORGANIZATION_INVITATION_STATUS.PENDING,
+ expiresAt: new Date('2025-10-05T12:00:00Z'),
+ };
+ const { db } = await createInMemoryDatabase({
+ users: [{ id: 'owner', email: '[email protected]' }],
+ organizations: [
+ { id: 'org', name: 'Organization' },
+ { id: 'other-org', name: 'Other organization' },
+ ],
+ organizationMembers: [{ organizationId: 'org', userId: 'owner', role: 'owner' }],
+ organizationInvitations: [
+ {
+ ...commonInvitation,
+ id: 'stale-recipient',
+ organizationId: 'org',
+ email: '[email protected]',
+ },
+ {
+ ...commonInvitation,
+ id: 'stale-other-recipient',
+ organizationId: 'org',
+ email: '[email protected]',
+ },
+ {
+ ...commonInvitation,
+ id: 'other-org-invitation',
+ organizationId: 'other-org',
+ email: '[email protected]',
+ },
+ ],
+ });
+ const organizationsRepository = createOrganizationsRepository({ db });
+ const { clock } = createTestClock({ now: '2025-10-05T12:00:00Z' });
+ const inviteMemberToOrganization = buildInviteMemberToOrganization({
+ organizationsRepository,
+ getOrganizationPlan: async () => ({
+ organizationPlan: { limits: { maxOrganizationsMembersCount: 2 } },
+ }),
+ checkIfUserHasReachedOrganizationInvitationLimit: async () => {},
+ sendOrganizationInvitationEmail: async () => {},
+ expirationDelayDays: 7,
+ clock,
+ });
+
+ const { organizationInvitation } = await inviteMemberToOrganization({
+ email: '[email protected]',
+ organizationId: 'org',
+ inviterId: 'owner',
+ role: 'member',
+ });
+
+ expect(organizationInvitation?.status).toEqual('pending');
+ expect(
+ await db
+ .select({
+ id: organizationInvitationsTable.id,
+ status: organizationInvitationsTable.status,
+ })
+ .from(organizationInvitationsTable)
+ .orderBy(organizationInvitationsTable.id),
+ ).toEqual([
+ { id: organizationInvitation?.id, status: 'pending' },
+ { id: 'other-org-invitation', status: 'pending' },
+ { id: 'stale-other-recipient', status: 'expired' },
+ { id: 'stale-recipient', status: 'expired' },
+ ]);
+ });
+
test('cannot create multiple invitations for the same email address to the same organization to prevent spam and confusion', async () => {
const { logger, getLogs } = createTestLogger();
+ const { clock } = createTestClock({ now: '2025-10-05T12:00:00Z' });
const { db } = await createInMemoryDatabase({
users: [{ id: 'user-1', email: '[email protected]' }],
organizations: [{ id: 'organization-1', name: 'Organization 1' }],
@@ -672,6 +954,7 @@ describe('organizations usecases', () => {
sendOrganizationInvitationEmail: async () => {},
expirationDelayDays: 7,
logger,
+ clock,
});
await expect(
@@ -700,6 +983,7 @@ describe('organizations usecases', () => {
test('cannot invite new members when the organization has reached its maximum member count (including pending invitations) defined by the plan to enforce subscription limits', async () => {
const { logger, getLogs } = createTestLogger();
+ const { clock } = createTestClock({ now: '2025-10-05T12:00:00Z' });
const { db } = await createInMemoryDatabase({
users: [{ id: 'user-1', email: '[email protected]' }],
organizations: [{ id: 'organization-1', name: 'Organization 1' }],
@@ -732,6 +1016,7 @@ describe('organizations usecases', () => {
sendOrganizationInvitationEmail: async () => {},
expirationDelayDays: 7,
logger,
+ clock,
});
await expect(
@@ -1020,6 +1305,214 @@ describe('organizations usecases', () => {
});
});
+ describe('resendOrganizationInvitation', () => {
+ async function setupResendTest({
+ status = 'cancelled',
+ maxMembers = 2,
+ maxInvitationsPerDay = 10,
+ }: {
+ status?: OrganizationInvitationStatus;
+ maxMembers?: number;
+ maxInvitationsPerDay?: number;
+ } = {}) {
+ const { db } = await createInMemoryDatabase({
+ users: [
+ { id: 'owner', email: '[email protected]' },
+ { id: 'member', email: '[email protected]' },
+ ],
+ organizations: [{ id: 'org', name: 'Organization' }],
+ organizationMembers: [{ organizationId: 'org', userId: 'owner', role: 'owner' }],
+ organizationInvitations: [
+ {
+ id: 'invitation',
+ organizationId: 'org',
+ email: '[email protected]',
+ role: 'admin',
+ inviterId: 'owner',
+ status,
+ expiresAt: new Date('2025-10-05T12:00:00Z'),
+ createdAt: new Date('2025-10-01'),
+ },
+ ],
+ });
+ const organizationsRepository = createOrganizationsRepository({ db });
+ const { clock } = createTestClock({ now: '2025-10-05T12:00:00Z' });
+ const { logger } = createTestLogger();
+ const sentEmails: { email: string; organizationId: string }[] = [];
+ const resendOrganizationInvitation = buildResendOrganizationInvitation({
+ organizationsRepository,
+ getOrganizationPlan: async () => ({
+ organizationPlan: { limits: { maxOrganizationsMembersCount: maxMembers } },
+ }),
+ checkIfUserHasReachedOrganizationInvitationLimit: async ({ userId, now }) =>
+ checkIfUserHasReachedOrganizationInvitationLimit({
+ userId,
+ now,
+ maxInvitationsPerDay,
+ organizationsRepository,
+ }),
+ sendOrganizationInvitationEmail: async (args) => {
+ sentEmails.push(args);
+ },
+ expirationDelayDays: 7,
+ clock,
+ logger,
+ });
+ return { db, organizationsRepository, clock, sentEmails, resendOrganizationInvitation };
+ }
+
+ test('an old invitation cannot be resent to a current member', async () => {
+ const { db, organizationsRepository, resendOrganizationInvitation, sentEmails } =
+ await setupResendTest();
+ await organizationsRepository.addUserToOrganization({
+ userId: 'member',
+ organizationId: 'org',
+ role: 'member',
+ });
+
+ await expect(
+ resendOrganizationInvitation({ invitationId: 'invitation', userId: 'owner' }),
+ ).rejects.toThrow(createUserAlreadyInOrganizationError());
+
+ expect(sentEmails).toEqual([]);
+ expect(await db.select().from(organizationInvitationsTable)).toMatchObject([
+ { id: 'invitation', status: 'cancelled' },
+ ]);
+ });
+
+ test('an old invitation cannot be resent when another active invitation exists', async () => {
+ const { organizationsRepository, resendOrganizationInvitation, sentEmails } =
+ await setupResendTest();
+ await organizationsRepository.saveOrganizationInvitation({
+ organizationId: 'org',
+ email: '[email protected]',
+ inviterId: 'owner',
+ role: 'member',
+ now: new Date('2025-10-05'),
+ });
+
+ await expect(
+ resendOrganizationInvitation({ invitationId: 'invitation', userId: 'owner' }),
+ ).rejects.toThrow(createOrganizationInvitationAlreadyExistsError());
+ expect(sentEmails).toEqual([]);
+ });
+
+ test('resend immediately renews an expired invitation still stored as pending', async () => {
+ const { db, resendOrganizationInvitation, sentEmails } = await setupResendTest({
+ status: 'pending',
+ });
+ await db.insert(organizationInvitationsTable).values([
+ {
+ id: 'accepted',
+ organizationId: 'org',
+ email: '[email protected]',
+ role: 'member',
+ inviterId: 'owner',
+ status: 'accepted',
+ expiresAt: new Date('2025-10-01'),
+ },
+ {
+ id: 'stale',
+ organizationId: 'org',
+ email: '[email protected]',
+ role: 'member',
+ inviterId: 'owner',
+ status: 'pending',
+ expiresAt: new Date('2025-10-05T12:00:00Z'),
+ },
+ ]);
+
+ await resendOrganizationInvitation({ invitationId: 'invitation', userId: 'owner' });
+
+ expect(
+ await db
+ .select()
+ .from(organizationInvitationsTable)
+ .orderBy(organizationInvitationsTable.id),
+ ).toMatchObject([
+ { id: 'accepted', status: 'accepted' },
+ {
+ id: 'invitation',
+ status: 'pending',
+ role: 'admin',
+ expiresAt: new Date('2025-10-12T12:00:00Z'),
+ },
+ { id: 'stale', status: 'expired' },
+ ]);
+ expect(sentEmails).toEqual([{ email: '[email protected]', organizationId: 'org' }]);
+ });
+
+ test('a cancelled invitation can be resent after a newer invitation expires', async () => {
+ const { db, organizationsRepository, resendOrganizationInvitation, sentEmails } =
+ await setupResendTest();
+ await organizationsRepository.saveOrganizationInvitation({
+ organizationId: 'org',
+ email: '[email protected]',
+ inviterId: 'owner',
+ role: 'member',
+ now: new Date('2025-09-01'),
+ });
+
+ await resendOrganizationInvitation({ invitationId: 'invitation', userId: 'owner' });
+
+ expect(
+ await db
+ .select()
+ .from(organizationInvitationsTable)
+ .orderBy(organizationInvitationsTable.id),
+ ).toMatchObject([
+ { id: 'invitation', status: 'pending', expiresAt: new Date('2025-10-12T12:00:00Z') },
+ { status: 'expired' },
+ ]);
+ expect(sentEmails).toHaveLength(1);
+ });
+
+ test('resending an invitation respects organization capacity', async () => {
+ const { organizationsRepository, resendOrganizationInvitation, sentEmails } =
+ await setupResendTest();
+ await organizationsRepository.saveOrganizationInvitation({
+ organizationId: 'org',
+ email: '[email protected]',
+ inviterId: 'owner',
+ role: 'member',
+ now: new Date('2025-10-05'),
+ });
+
+ await expect(
+ resendOrganizationInvitation({ invitationId: 'invitation', userId: 'owner' }),
+ ).rejects.toThrow(createMaxOrganizationMembersCountReachedError());
+ expect(sentEmails).toEqual([]);
+ });
+
+ test('resending an invitation respects the senders daily invitation limit', async () => {
+ const { organizationsRepository, resendOrganizationInvitation, sentEmails } =
+ await setupResendTest({ maxMembers: 10, maxInvitationsPerDay: 1 });
+ await organizationsRepository.saveOrganizationInvitation({
+ organizationId: 'org',
+ email: '[email protected]',
+ inviterId: 'owner',
+ role: 'member',
+ now: new Date('2025-10-05'),
+ });
+
+ await expect(
+ resendOrganizationInvitation({ invitationId: 'invitation', userId: 'owner' }),
+ ).rejects.toThrow(createUserOrganizationInvitationLimitReachedError());
+ expect(sentEmails).toEqual([]);
+ });
+
+ test('accepted invitations remain historical and cannot be resent', async () => {
+ const { resendOrganizationInvitation, sentEmails } = await setupResendTest({
+ status: 'accepted',
+ });
+
+ await expect(
+ resendOrganizationInvitation({ invitationId: 'invitation', userId: 'owner' }),
+ ).rejects.toThrow(createForbiddenError());
+ expect(sentEmails).toEqual([]);
+ });
+ });
+
describe('softDeleteOrganization', () => {
describe('when an organization owner wants to delete their organization, the organization is soft-deleted to allow for recovery within a grace period', () => {
test('owner can soft-delete organization with all metadata set correctly', async () => {
diff --git a/apps/papra-server/src/modules/organizations/organizations.usecases.ts b/apps/papra-server/src/modules/organizations/organizations.usecases.ts
index 38b73524..74fae22f 100644
--- a/apps/papra-server/src/modules/organizations/organizations.usecases.ts
+++ b/apps/papra-server/src/modules/organizations/organizations.usecases.ts
@@ -243,7 +243,8 @@ export function buildInviteMemberToOrganization({
OrganizationsRepository,
| 'getOrganizationMemberByUserId'
| 'getOrganizationMemberByEmail'
- | 'getInvitationForEmailAndOrganization'
+ | 'getPendingInvitationForEmailAndOrganization'
+ | 'updateExpiredPendingInvitationsStatus'
| 'getOrganizationMembersCount'
| 'getOrganizationPendingInvitationsCount'
| 'saveOrganizationInvitation'
@@ -311,10 +312,13 @@ export function buildInviteMemberToOrganization({
throw createUserAlreadyInOrganizationError();
}
- const { invitation } = await organizationsRepository.getInvitationForEmailAndOrganization({
- email,
- organizationId,
- });
+ await organizationsRepository.updateExpiredPendingInvitationsStatus({ organizationId, now });
+
+ const { invitation } =
+ await organizationsRepository.getPendingInvitationForEmailAndOrganization({
+ email,
+ organizationId,
+ });
if (invitation) {
logger.error(
@@ -456,82 +460,139 @@ export async function updateOrganizationMemberRole({
return { member: updatedMember };
}
-export async function resendOrganizationInvitation({
- invitationId,
- userId,
+export function buildResendOrganizationInvitation({
organizationsRepository,
- emailsServices,
- config,
+ getOrganizationPlan,
+ checkIfUserHasReachedOrganizationInvitationLimit,
+ sendOrganizationInvitationEmail,
+ expirationDelayDays,
logger = createLogger({ namespace: 'organizations.resend-invitation' }),
- now = new Date(),
+ clock = systemClock,
}: {
- invitationId: string;
- userId: string;
- organizationsRepository: OrganizationsRepository;
- emailsServices: EmailsServices;
- config: Config;
+ organizationsRepository: Pick<
+ OrganizationsRepository,
+ | 'getOrganizationInvitationById'
+ | 'getOrganizationMemberByUserId'
+ | 'getOrganizationMemberByEmail'
+ | 'updateExpiredPendingInvitationsStatus'
+ | 'getPendingInvitationForEmailAndOrganization'
+ | 'getOrganizationMembersCount'
+ | 'getOrganizationPendingInvitationsCount'
+ | 'updateOrganizationInvitation'
+ >;
+ getOrganizationPlan: (args: { organizationId: string }) => Promise<{
+ organizationPlan: { limits: { maxOrganizationsMembersCount: number } };
+ }>;
+ checkIfUserHasReachedOrganizationInvitationLimit: (args: {
+ userId: string;
+ now: Date;
+ }) => Promise<void>;
+ sendOrganizationInvitationEmail: (args: {
+ email: string;
+ organizationId: string;
+ }) => Promise<void>;
+ expirationDelayDays: number;
logger?: Logger;
- now?: Date;
+ clock?: Clock;
}) {
- const { invitation } = await organizationsRepository.getOrganizationInvitationById({
- invitationId,
- });
+ return async ({ invitationId, userId }: { invitationId: string; userId: string }) => {
+ const now = new Date(clock.now().epochMilliseconds);
+ const { invitation } = await organizationsRepository.getOrganizationInvitationById({
+ invitationId,
+ now,
+ });
- if (!invitation) {
- logger.error({ invitationId }, 'Invitation not found');
- throw createForbiddenError();
- }
+ if (!invitation) {
+ logger.error({ invitationId }, 'Invitation not found');
+ throw createForbiddenError();
+ }
- if (
- ![
- ORGANIZATION_INVITATION_STATUS.EXPIRED,
- ORGANIZATION_INVITATION_STATUS.CANCELLED,
- ORGANIZATION_INVITATION_STATUS.REJECTED,
- ].includes(invitation.status)
- ) {
- logger.error(
- { invitationId, invitationStatus: invitation.status },
- 'Cannot resend invitation that is neither expired, cancelled nor rejected',
- );
- throw createForbiddenError();
- }
+ if (
+ ![
+ ORGANIZATION_INVITATION_STATUS.EXPIRED,
+ ORGANIZATION_INVITATION_STATUS.CANCELLED,
+ ORGANIZATION_INVITATION_STATUS.REJECTED,
+ ].includes(invitation.status)
+ ) {
+ logger.error(
+ { invitationId, invitationStatus: invitation.status },
+ 'Cannot resend invitation that is neither expired, cancelled nor rejected',
+ );
+ throw createForbiddenError();
+ }
- const { member: inviterMember } = await organizationsRepository.getOrganizationMemberByUserId({
- userId,
- organizationId: invitation.organizationId,
- });
+ const { member: inviterMember } = await organizationsRepository.getOrganizationMemberByUserId({
+ userId,
+ organizationId: invitation.organizationId,
+ });
- if (!inviterMember) {
- logger.error({ invitationId, userId }, 'Inviter not found in organization');
- throw createForbiddenError();
- }
+ if (!inviterMember) {
+ logger.error({ invitationId, userId }, 'Inviter not found in organization');
+ throw createForbiddenError();
+ }
- if (![ORGANIZATION_ROLES.OWNER, ORGANIZATION_ROLES.ADMIN].includes(inviterMember.role)) {
- logger.error(
- {
- invitationId,
- userId,
- memberId: inviterMember.id,
- memberRole: inviterMember.role,
- },
- 'Inviter does not have permission to resend invitation',
- );
- throw createForbiddenError();
- }
+ if (![ORGANIZATION_ROLES.OWNER, ORGANIZATION_ROLES.ADMIN].includes(inviterMember.role)) {
+ logger.error(
+ {
+ invitationId,
+ userId,
+ memberId: inviterMember.id,
+ memberRole: inviterMember.role,
+ },
+ 'Inviter does not have permission to resend invitation',
+ );
+ throw createForbiddenError();
+ }
- await organizationsRepository.updateOrganizationInvitation({
- invitationId,
- status: ORGANIZATION_INVITATION_STATUS.PENDING,
- expiresAt: addDays(now, config.organizations.invitationExpirationDelayDays),
- });
+ const { organizationId, email } = invitation;
+ const { member } = await organizationsRepository.getOrganizationMemberByEmail({
+ organizationId,
+ email,
+ });
- await sendOrganizationInvitationEmail({
- email: invitation.email,
- organizationId: invitation.organizationId,
- organizationsRepository,
- emailsServices,
- config,
- });
+ if (member) {
+ throw createUserAlreadyInOrganizationError();
+ }
+
+ await organizationsRepository.updateExpiredPendingInvitationsStatus({ organizationId, now });
+
+ const { invitation: pendingInvitation } =
+ await organizationsRepository.getPendingInvitationForEmailAndOrganization({
+ organizationId,
+ email,
+ });
+
+ if (pendingInvitation) {
+ throw createOrganizationInvitationAlreadyExistsError();
+ }
+
+ const { membersCount } = await organizationsRepository.getOrganizationMembersCount({
+ organizationId,
+ });
+ const { pendingInvitationsCount } =
+ await organizationsRepository.getOrganizationPendingInvitationsCount({ organizationId });
+ const { organizationPlan } = await getOrganizationPlan({ organizationId });
+
+ if (
+ membersCount + pendingInvitationsCount >=
+ organizationPlan.limits.maxOrganizationsMembersCount
+ ) {
+ throw createMaxOrganizationMembersCountReachedError();
+ }
+
+ await checkIfUserHasReachedOrganizationInvitationLimit({ userId, now });
+
+ await organizationsRepository.updateOrganizationInvitation({
+ invitationId,
+ status: ORGANIZATION_INVITATION_STATUS.PENDING,
+ expiresAt: addDays(now, expirationDelayDays),
+ });
+
+ await sendOrganizationInvitationEmail({
+ email,
+ organizationId,
+ });
+ };
}
export async function getOrganizationStorageLimits({