AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
fix(invitations): re-inviting at platform level updates the invite, and the dialog says why (#16320)
lina-alomaria95445a19ad9
diff --git a/brain/knowledge/platform-editions-ee/user-invitations.md b/brain/knowledge/platform-editions-ee/user-invitations.mdindex 88075bea9ed..9f942d53e53 100644--- a/brain/knowledge/platform-editions-ee/user-invitations.md+++ b/brain/knowledge/platform-editions-ee/user-invitations.md@@ -11,7 +11,7 @@ Lets platform owners (and project members with `WRITE_INVITATION`) invite users### How it works- Endpoints under `/v1/user-invitations`: `POST /` (create/upsert, USER+SERVICE), `GET /` (list), `POST /accept` (**fully public** — JWT is the security), `DELETE /:id` (revoke).-- Create is split in two. When the invite would add a *new* platform user (`wouldAddNewUser`), `createInvitationRecord` (upsert by `(email, platformId, projectId)`) runs inside a transaction where `countAdditionalSeatsNeeded` feeds `checkUsersExceededLimit`, which takes a `pessimistic_write` lock on the platform's `platform_plan` row and counts reserved invites — the seat is reserved at invite creation, concurrent invites can't overshoot `usersLimit`, and an over-limit invite fast-fails with `QUOTA_EXCEEDED`. `finalizeInvitation` then runs after commit, outside the lock (SMTP/JWT work never holds it): if ACCEPTED → immediate `accept()`; if PENDING + SMTP configured → emails link, else returns link in response.+- Create is split in two. When the invite would add a *new* platform user (`wouldAddNewUser`), `createInvitationRecord` (one PLATFORM row per email and platform, one PROJECT row per email and project) runs inside a transaction where `countAdditionalSeatsNeeded` feeds `checkUsersExceededLimit`, which takes a `pessimistic_write` lock on the platform's `platform_plan` row and counts reserved invites — the seat is reserved at invite creation, concurrent invites can't overshoot `usersLimit`, and an over-limit invite fast-fails with `QUOTA_EXCEEDED`. `finalizeInvitation` then runs after commit, outside the lock (SMTP/JWT work never holds it): if ACCEPTED → immediate `accept()`; if PENDING + SMTP configured → emails link, else returns link in response.- `provisionUserInvitation` applies all ACCEPTED invites for an email (platform role update or ProjectMember upsert), deleting each after. It performs **no seat check** — accepting is seat-neutral (reserved invite −1, active user +1) and never blocks on `usersLimit`.- Invitation link: JWT-signed URL (7-day default) to `<platform-domain>/invitation?token=...&email=...`.@@ -28,6 +28,8 @@ Lets platform owners (and project members with `WRITE_INVITATION`) invite users- **Accepting reads the invited project and role scoped to the invite's platform.** `loadProvisioningContext` filters both by `platformId` (built-in roles have none), and `addToInvitedProject` skips a project or refuses a role that belongs to another platform.- **The web requires that project only when personal projects are off; the API never does.** For a Member on a plan with project roles, the invite dialog's Project field is optional while personal projects are on (they start in their personal project) and required while they are off, with a line saying why. With personal projects off and no team project at all, the dialog shows "Create a project first" with a Create project button and disables Invite, so nobody is invited into nowhere and nobody is stuck at an empty list. `POST /v1/user-invitations` keeps both fields optional on purpose: API callers (onboarding scripts, embedding customers) often send a platform invite and then a project invite as two calls, and requiring the field would quietly break that automation. The no-projects screen catches anyone a script leaves without a project.- **Changing an Admin or Operator to Member asks for a project only when they have none.** `GET /v1/users` returns `hasProjects` (one batched query, `projectService.listUserIdsWithProjects`), and the Update User Role dialog makes two calls: a project invite first (accepted automatically, since they're already on the platform), then the role change. Project access stays on the project-member resource, not on `POST /v1/users/:id`, and the order means a failure part-way leaves an Admin who is also in a project, never a Member with no project.+- **Re-inviting an email at platform level updates its existing invite.** The unique index `(email, platformId, projectId)` never matches a PLATFORM row without a project (NULL is never equal), so an upsert alone inserted a duplicate each time. `createInvitationRecord` now finds the PLATFORM row by email and platform and updates it, removing any older duplicates, and the route holds a `distributedLock` per platform and email so two concurrent invites can't both insert. Because a PLATFORM row can now carry a `projectId`, it shares that index key with a PROJECT invite to the same project: a platform invite naming project X deletes the pending project invite to X, and a project invite to X takes X off the platform invite, so neither silently overwrites the other's type. An invite someone already accepted (they clicked the link but haven't signed up yet) stays `ACCEPTED` when it's re-sent, and an accepted project invite is never deleted; if it covers the project, the platform invite simply doesn't take that project. `provisionUserInvitation` only deletes an invite if it is unchanged since it read it, so a re-send that lands mid-acceptance isn't lost.+- **Re-sending an invite someone already accepted keeps it accepted, and still sends them a way in.** Accepted means they clicked the link, so it stays accepted to keep sign-up open for them. When they have no account yet, `finalizeInvitation` (with `resent`) treats it as a normal invite: a fresh link (a newly signed token for the same invite, valid 7 days) when SMTP isn't configured, or the invitation email again. API-key invites, which are accepted on the first send, keep their old behaviour. The dialog only calls someone "added" when they're already on the platform.### Key filesEntry point: `userInvitationsService`, defined in `user-invitation.service.ts` and called from the routes in `user-invitation.module.ts` (which exports `invitationModule`).diff --git a/packages/core/shared/package.json b/packages/core/shared/package.jsonindex cacb722049a..8d4cf03db52 100644--- a/packages/core/shared/package.json+++ b/packages/core/shared/package.json@@ -1,6 +1,6 @@{"name": "@activepieces/shared",- "version": "0.210.5",+ "version": "0.210.6","type": "commonjs","sideEffects": false,"main": "./dist/src/index.js",diff --git a/packages/core/shared/src/lib/management/invitations/index.ts b/packages/core/shared/src/lib/management/invitations/index.tsindex 490e73d8579..50a02a8849c 100644--- a/packages/core/shared/src/lib/management/invitations/index.ts+++ b/packages/core/shared/src/lib/management/invitations/index.ts@@ -28,10 +28,18 @@ export type UserInvitation = z.infer<typeof UserInvitation>export const UserInvitationWithLink = UserInvitation.extend({link: z.string().optional(),+ addedNow: z.boolean().optional(),})export type UserInvitationWithLink = z.infer<typeof UserInvitationWithLink>+export const RemoveProjectFromInvitationResponse = z.object({+ revoked: z.boolean(),+ invitation: UserInvitation.nullable(),+})++export type RemoveProjectFromInvitationResponse = z.infer<typeof RemoveProjectFromInvitationResponse>+export const SendUserInvitationRequest = z.union([z.object({type: z.literal(InvitationType.PROJECT),diff --git a/packages/server/api/src/app/user-invitations/user-invitation.module.ts b/packages/server/api/src/app/user-invitations/user-invitation.module.tsindex 74c953e475c..c06b13e681c 100644--- a/packages/server/api/src/app/user-invitations/user-invitation.module.ts+++ b/packages/server/api/src/app/user-invitations/user-invitation.module.ts@@ -1,5 +1,5 @@import { ActivepiecesError, assertNotNullOrUndefined, ErrorCode, isNil, Permission, ProjectRole, SeekPage } from '@activepieces/core-utils'-import { InvitationStatus, InvitationType, ListUserInvitationsRequest, PlatformRole, Principal, PrincipalType, ProjectType, SendUserInvitationRequest, SERVICE_KEY_SECURITY_OPENAPI, TelemetryEvent, TelemetryEventName, UserInvitation, UserInvitationWithLink } from '@activepieces/shared'+import { InvitationStatus, InvitationType, ListUserInvitationsRequest, PlatformRole, Principal, PrincipalType, ProjectType, RemoveProjectFromInvitationResponse, SendUserInvitationRequest, SERVICE_KEY_SECURITY_OPENAPI, TelemetryEvent, TelemetryEventName, UserInvitation, UserInvitationWithLink } from '@activepieces/shared'import { FastifyBaseLogger, FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'import { StatusCodes } from 'http-status-codes'@@ -8,6 +8,7 @@ import { userIdentityService } from '../authentication/user-identity/user-identiimport { transaction } from '../core/db/transaction'import { ProjectResourceType } from '../core/security/authorization/common'import { securityAccess } from '../core/security/authorization/fastify-security'+import { distributedLock } from '../database/redis-connections'import { platformMustBeOwnedByCurrentUser, platformMustHaveFeatureEnabled, projectMustBeTeamType } from '../ee/authentication/ee-authorization'import { assertRoleHasPermission } from '../ee/authentication/project-role/rbac-middleware'import { platformPlanService } from '../ee/platform/platform-plan/platform-plan.service'@@ -50,22 +51,29 @@ const invitationController: FastifyPluginAsyncZod = async (app) => {status,}- const wouldAddNewUser = await userInvitationsService(request.log).wouldAddNewUser({ email, platformId })- const userInvitationRecord = await transaction(async (entityManager) => {- if (wouldAddNewUser) {- const additionalSeatsNeeded = await userInvitationsService(request.log).countAdditionalSeatsNeeded({- email,- platformId,- entityManager,+ const userInvitationRecord = await distributedLock(request.log).runExclusive({+ key: `user-invitation:${platformId}:${email.toLowerCase().trim()}`,+ timeoutInSeconds: 30,+ fn: async () => {+ const wouldAddNewUser = await userInvitationsService(request.log).wouldAddNewUser({ email, platformId })+ return transaction(async (entityManager) => {+ if (wouldAddNewUser) {+ const additionalSeatsNeeded = await userInvitationsService(request.log).countAdditionalSeatsNeeded({+ email,+ platformId,+ entityManager,+ })+ await platformPlanService(request.log).checkUsersExceededLimit({ platformId, entityManager, additionalSeatsNeeded })+ }+ return userInvitationsService(request.log).createInvitationRecord({ ...invitationRecordParams, entityManager })})- await platformPlanService(request.log).checkUsersExceededLimit({ platformId, entityManager, additionalSeatsNeeded })- }- return userInvitationsService(request.log).createInvitationRecord({ ...invitationRecordParams, entityManager })+ },})const invitation = await userInvitationsService(request.log).finalizeInvitation({userInvitation: userInvitationRecord,invitationExpirySeconds: INVITATION_EXPIRY_SECONDS,+ resent: status === InvitationStatus.PENDING && userInvitationRecord.status === InvitationStatus.ACCEPTED,})rejectedPromiseHandler(trackInviteSent({principal: request.principal,@@ -87,10 +95,13 @@ const invitationController: FastifyPluginAsyncZod = async (app) => {if (!isNil(request.query.projectId) && request.query.type === InvitationType.PROJECT) {await projectMustBeTeamType.call(app, request, reply)}- const projectId = await getProjectIdAndAssertPermission(app, request, reply, request.principal, request.query)+ const projectId = await getProjectIdAndAssertPermission(app, request, reply, request.principal, {+ ...request.query,+ projectId: request.query.projectId === '' ? null : request.query.projectId,+ })const invitations = await userInvitationsService(request.log).list({platformId: request.principal.platform.id,- projectId: request.query.type === InvitationType.PROJECT ? projectId : null,+ projectId,type: request.query.type,status: request.query.status,cursor: request.query.cursor ?? null,@@ -109,6 +120,16 @@ const invitationController: FastifyPluginAsyncZod = async (app) => {await reply.status(StatusCodes.OK).send({ ...invitation, registered })})+ app.post('/:id/remove-project', RemoveProjectFromInvitationRequestParams, async (request, reply) => {+ await platformMustBeOwnedByCurrentUser.call(app, request, reply)+ const result = await userInvitationsService(request.log).removeProjectFromPlatformInvite({+ id: request.params.id,+ platformId: request.principal.platform.id,+ projectId: request.body.projectId,+ })+ await reply.status(StatusCodes.OK).send(result)+ })+app.delete('/:id', DeleteInvitationRequestParams, async (request, reply) => {const invitation = await userInvitationsService(request.log).getOneOrThrow({id: request.params.id,@@ -293,6 +314,26 @@ const DeleteInvitationRequestParams = {},}+const RemoveProjectFromInvitationRequestParams = {+ config: {+ security: securityAccess.unscoped([PrincipalType.USER, PrincipalType.SERVICE]),+ },+ schema: {+ tags: ['user-invitations'],+ security: [SERVICE_KEY_SECURITY_OPENAPI],+ description: 'Take the project off a platform invitation. When it is a Member invite and new members get no personal project and no default projects, the invitation is revoked instead, since they would have nowhere to land; their project invitations are not affected.',+ params: z.object({+ id: z.string(),+ }),+ body: z.object({+ projectId: z.string(),+ }),+ response: {+ [StatusCodes.OK]: RemoveProjectFromInvitationResponse,+ },+ },+}+const UpsertUserInvitationRequestParams = {config: {security: securityAccess.publicPlatform([PrincipalType.USER, PrincipalType.SERVICE], {diff --git a/packages/server/api/src/app/user-invitations/user-invitation.service.ts b/packages/server/api/src/app/user-invitations/user-invitation.service.tsindex 9c55fbe50cb..8d97b9a8beb 100644--- a/packages/server/api/src/app/user-invitations/user-invitation.service.ts+++ b/packages/server/api/src/app/user-invitations/user-invitation.service.ts@@ -1,5 +1,5 @@import { ActivepiecesError, apId, assertEqual, assertNotNullOrUndefined, ErrorCode, isNil, ProjectRole, RoleType, SeekPage, spreadIfDefined, unique } from '@activepieces/core-utils'-import { InvitationStatus, InvitationType, PlatformRole, TelemetryEventName, UserInvitation, UserInvitationWithLink } from '@activepieces/shared'+import { ApEdition, InvitationStatus, InvitationType, PlatformRole, RemoveProjectFromInvitationResponse, TelemetryEventName, UserInvitation, UserInvitationWithLink } from '@activepieces/shared'import dayjs from 'dayjs'import { FastifyBaseLogger } from 'fastify'import { EntityManager, In, IsNull, ObjectLiteral, SelectQueryBuilder } from 'typeorm'@@ -14,6 +14,7 @@ import { JwtAudience, jwtUtils } from '../helper/jwt-utils'import { buildPaginator } from '../helper/pagination/build-paginator'import { paginationHelper } from '../helper/pagination/pagination-utils'import { rejectedPromiseHandler } from '../helper/promise-handler'+import { system } from '../helper/system/system'import { telemetry } from '../helper/telemetry.utils'import { platformService } from '../platform/platform.service'import { ProjectEntity } from '../project/project-entity'@@ -84,14 +85,58 @@ export const userInvitationsService = (log: FastifyBaseLogger) => ({break}}- await repo().delete({- id: invitation.id,- })+ await deleteIfUnchanged({ invitation })}},async detachProjectFromPlatformInvites({ projectId, entityManager }: DetachProjectFromPlatformInvitesParams): Promise<void> {await repo(entityManager).update({ type: InvitationType.PLATFORM, projectId }, { projectId: null, projectRoleId: null })},+ async removeProjectFromPlatformInvite({ id, platformId, projectId }: RemoveProjectFromPlatformInviteParams): Promise<RemoveProjectFromInvitationResponse> {+ if (system.getEdition() !== ApEdition.COMMUNITY) {+ const deleted = await repo().createQueryBuilder()+ .delete()+ .where('"id" = :id AND "platformId" = :platformId AND "type" = :type AND "platformRole" = :platformRole AND "projectId" = :projectId', {+ id,+ platformId,+ type: InvitationType.PLATFORM,+ platformRole: PlatformRole.MEMBER,+ projectId,+ })+ .andWhere('EXISTS (SELECT 1 FROM "platform" WHERE "platform"."id" = :platformId AND "platform"."autoCreatePersonalProjects" = false)')+ .andWhere('EXISTS (SELECT 1 FROM "platform_plan" WHERE "platform_plan"."platformId" = :platformId AND "platform_plan"."projectRolesEnabled" = true)')+ .andWhere('NOT EXISTS (SELECT 1 FROM "project" "default_project" WHERE "default_project"."platformId" = :platformId AND "default_project"."isDefault" = true AND "default_project"."deleted" IS NULL)')+ .returning('id')+ .execute()+ if (rowsOf(deleted).length > 0) {+ return { revoked: true, invitation: null }+ }+ }+ const cleared = await repo().createQueryBuilder()+ .update()+ .set({ projectId: null, projectRoleId: null, updated: () => '"updated"' })+ .where('"id" = :id AND "platformId" = :platformId AND "type" = :type AND "projectId" = :projectId', {+ id,+ platformId,+ type: InvitationType.PLATFORM,+ projectId,+ })+ .returning('*')+ .execute()+ const [clearedRow] = rowsOf(cleared)+ if (!isNil(clearedRow)) {+ return { revoked: false, invitation: { ...repo().create(clearedRow), projectRole: null } }+ }+ const invitation = await this.getOneOrThrow({ id, platformId })+ if (invitation.type !== InvitationType.PLATFORM) {+ throw new ActivepiecesError({+ code: ErrorCode.VALIDATION,+ params: {+ message: 'Only a platform invitation can have its project removed',+ },+ })+ }+ return { revoked: false, invitation }+ },async detachProjectRoleFromPlatformInvites({ projectRoleId, entityManager }: DetachProjectRoleFromPlatformInvitesParams): Promise<void> {await repo(entityManager).update({ type: InvitationType.PLATFORM, projectRoleId }, { projectId: null, projectRoleId: null })},@@ -107,39 +152,67 @@ export const userInvitationsService = (log: FastifyBaseLogger) => ({}: CreateInvitationRecordParams): Promise<UserInvitation> {const normalizedEmail = email.toLowerCase().trim()const invitedProject = await claimInvitedProject({ email: normalizedEmail, platformId, projectId, type, entityManager })- const id = apId()- await repo(entityManager).upsert({- id,+ const record = {status,type,email: normalizedEmail,platformId,- projectRoleId: invitedProject.keepsProject ? projectRoleId ?? undefined : undefined,- platformRole: type === InvitationType.PROJECT ? undefined : platformRole!,- projectId: invitedProject.keepsProject ? projectId ?? undefined : undefined,- }, ['email', 'platformId', 'projectId'])-- return this.getOneOrThrow({- id,- platformId,- entityManager,- })+ projectRoleId: invitedProject.keepsProject ? projectRoleId : null,+ platformRole: type === InvitationType.PROJECT ? null : platformRole,+ projectId: invitedProject.keepsProject ? projectId : null,+ }+ switch (type) {+ case InvitationType.PLATFORM: {+ const replaced = await replacePlatformInvites({ email: normalizedEmail, platformId, entityManager })+ const resentStatus = replaced.wasAccepted ? InvitationStatus.ACCEPTED : status+ if (replaced.existed) {+ await repo(entityManager).createQueryBuilder()+ .update()+ .set({+ ...record,+ status: () => 'CASE WHEN "status" = :acceptedStatus THEN :acceptedStatus ELSE :resentStatus END',+ updated: dayjs().toISOString(),+ })+ .setParameters({ acceptedStatus: InvitationStatus.ACCEPTED, resentStatus })+ .where({ id: replaced.id })+ .execute()+ }+ else {+ await repo(entityManager).save({+ id: replaced.id,+ ...record,+ status: resentStatus,+ updated: dayjs().toISOString(),+ })+ }+ return this.getOneOrThrow({ id: replaced.id, platformId, entityManager })+ }+ case InvitationType.PROJECT: {+ const id = apId()+ await repo(entityManager).upsert({ id, ...record }, ['email', 'platformId', 'projectId'])+ return this.getOneOrThrow({ id, platformId, entityManager })+ }+ }},async finalizeInvitation({userInvitation,invitationExpirySeconds,+ resent,}: FinalizeInvitationParams): Promise<UserInvitationWithLink> {if (userInvitation.status === InvitationStatus.ACCEPTED) {- await this.accept({+ const { registered } = await this.accept({invitationId: userInvitation.id,platformId: userInvitation.platformId,})+ if (resent && !registered) {+ return enrichWithInvitationLink(userInvitation, invitationExpirySeconds, log)+ }if (smtpEmailSender(log).isSmtpConfigured()) {await emailService(log).sendProjectMemberAdded({userInvitation,})}- return userInvitation+ return { ...userInvitation, addedNow: registered }}return enrichWithInvitationLink(userInvitation, invitationExpirySeconds, log)},@@ -330,6 +403,37 @@ const EMAIL_IS_NOT_ALREADY_A_PLATFORM_USER = `NOT EXISTS ()`+async function replacePlatformInvites({ email, platformId, entityManager }: ReplacePlatformInvitesParams): Promise<ReplacedPlatformInvite> {+ const invitations = await repo(entityManager).find({+ where: { type: InvitationType.PLATFORM, email, platformId },+ order: { created: 'DESC' },+ lock: { mode: 'pessimistic_write' },+ })+ const [latest, ...duplicates] = invitations+ if (duplicates.length > 0) {+ await repo(entityManager).delete(duplicates.map((invitation) => invitation.id))+ }+ return {+ id: latest?.id ?? apId(),+ existed: !isNil(latest),+ wasAccepted: invitations.some((invitation) => invitation.status === InvitationStatus.ACCEPTED),+ }+}++async function deleteIfUnchanged({ invitation }: { invitation: UserInvitation }): Promise<void> {+ await repo().delete({+ id: invitation.id,+ status: invitation.status,+ platformRole: isNil(invitation.platformRole) ? IsNull() : invitation.platformRole,+ projectId: isNil(invitation.projectId) ? IsNull() : invitation.projectId,+ projectRoleId: isNil(invitation.projectRoleId) ? IsNull() : invitation.projectRoleId,+ })+}++function rowsOf(result: { raw: unknown }): ObjectLiteral[] {+ return Array.isArray(result.raw) ? result.raw : []+}+async function loadProvisioningContext({ invitations, log }: LoadProvisioningContextParams): Promise<ProvisioningContext> {const withProject = invitations.filter((invitation) => !isNil(invitation.projectId) && !isNil(invitation.projectRoleId))const projectRoleIds = unique(withProject.map((invitation) => invitation.projectRoleId).filter((id): id is string => !isNil(id)))@@ -428,6 +532,18 @@ const enrichWithInvitationLink = async (userInvitation: UserInvitation, expireyI})return userInvitation}+type ReplacedPlatformInvite = {+ id: string+ existed: boolean+ wasAccepted: boolean+}++type ReplacePlatformInvitesParams = {+ email: string+ platformId: string+ entityManager?: EntityManager+}+type DetachProjectFromPlatformInvitesParams = {projectId: stringentityManager: EntityManager@@ -479,6 +595,12 @@ type PlatformAndIdParams = {platformId: stringentityManager?: EntityManager}++type RemoveProjectFromPlatformInviteParams = {+ id: string+ platformId: string+ projectId: string+}export type UserInvitationToken = {id: string}@@ -506,6 +628,7 @@ export type CreateInvitationRecordParams = {export type FinalizeInvitationParams = {userInvitation: UserInvitationinvitationExpirySeconds: number+ resent: boolean}export type CountAdditionalSeatsNeededParams = {diff --git a/packages/server/api/test/integration/cloud/user-invitations/seat-reservation.test.ts b/packages/server/api/test/integration/cloud/user-invitations/seat-reservation.test.tsindex dd593710773..62ff6abe1bc 100644--- a/packages/server/api/test/integration/cloud/user-invitations/seat-reservation.test.ts+++ b/packages/server/api/test/integration/cloud/user-invitations/seat-reservation.test.ts@@ -98,6 +98,16 @@ describe('Seat reservation (ADR-0010) + active-user floor (ADR-0009)', () => {expect(response?.statusCode).toBe(StatusCodes.CREATED)})+ it('refuses re-sending an expired invite when the seats are full', async () => {+ const { mockOwnerToken, mockPlatform, mockProject } = await setupPlatform({ usersLimit: 1 })+ const expiredEmail = faker.internet.email().toLowerCase()+ await seedInvitation({ platformId: mockPlatform.id, status: InvitationStatus.PENDING, email: expiredEmail, createdDaysAgo: 8 })++ const response = await invite({ token: mockOwnerToken, projectId: mockProject.id, email: expiredEmail })++ expectSeatQuotaExceeded(response)+ })+it('counts accepted-but-not-yet-provisioned invitations toward the seat limit', async () => {const { mockOwnerToken, mockPlatform, mockProject } = await setupPlatform({ usersLimit: 2 })await seedInvitation({ platformId: mockPlatform.id, status: InvitationStatus.ACCEPTED })diff --git a/packages/server/api/test/integration/ee/user-invitations/repeat-platform-invite.test.ts b/packages/server/api/test/integration/ee/user-invitations/repeat-platform-invite.test.tsnew file mode 100644index 00000000000..260a6ff13d1--- /dev/null+++ b/packages/server/api/test/integration/ee/user-invitations/repeat-platform-invite.test.ts@@ -0,0 +1,546 @@+import { ErrorCode, isNil } from '@activepieces/core-utils'+import { DefaultProjectRole, InvitationStatus, InvitationType, PlatformRole, PrincipalType, ProjectType } from '@activepieces/shared'+import { faker } from '@faker-js/faker'+import { FastifyInstance } from 'fastify'+import { StatusCodes } from 'http-status-codes'+import { ObjectLiteral, Repository } from 'typeorm'+import { databaseConnection } from '../../../../src/app/database/database-connection'+import { generateMockToken } from '../../../helpers/auth'+import { createMockApiKey, createMockProject, createMockUserInvitation, mockAndSaveBasicSetup, mockBasicUser } from '../../../helpers/mocks'+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'++let app: FastifyInstance | null = null++beforeAll(async () => {+ app = await setupTestEnvironment()+})++afterAll(async () => {+ await teardownTestEnvironment()+})++describe('Inviting the same email to the platform again', () => {+ it('updates the pending invite instead of adding a second one', async () => {+ const { platformId, ownerToken } = await setupPlatform()+ const email = faker.internet.email().toLowerCase()++ const first = await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.OPERATOR })+ const second = await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.ADMIN })++ expect(second?.statusCode).toBe(StatusCodes.CREATED)+ expect(second?.json().id).toBe(first?.json().id)+ const invitations = await platformInvitesOf({ email, platformId })+ expect(invitations).toHaveLength(1)+ expect(invitations[0].platformRole).toBe(PlatformRole.ADMIN)+ })++ it('matches the email regardless of case', async () => {+ const { platformId, ownerToken } = await setupPlatform()+ const email = faker.internet.email().toLowerCase()++ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.OPERATOR })+ await invitePlatform({ token: ownerToken, email: email.toUpperCase(), platformRole: PlatformRole.OPERATOR })++ expect(await platformInvitesOf({ email, platformId })).toHaveLength(1)+ })++ it('replaces the project and role on the existing invite', async () => {+ const { platformId, projectId, ownerToken } = await setupPlatform()+ const otherProject = createMockProject({ platformId, ownerId: (await ownerOf({ platformId })), type: ProjectType.TEAM })+ await databaseConnection().getRepository('project').save(otherProject)+ const email = faker.internet.email().toLowerCase()++ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.MEMBER, projectId, projectRole: DefaultProjectRole.EDITOR })+ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.MEMBER, projectId: otherProject.id, projectRole: DefaultProjectRole.VIEWER })++ const invitations = await platformInvitesOf({ email, platformId })+ expect(invitations).toHaveLength(1)+ expect(invitations[0].projectId).toBe(otherProject.id)+ expect(await roleNameOf({ projectRoleId: invitations[0].projectRoleId })).toBe(DefaultProjectRole.VIEWER)+ })++ it('drops the project when the new invite has none', async () => {+ const { platformId, projectId, ownerToken } = await setupPlatform()+ const email = faker.internet.email().toLowerCase()++ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.MEMBER, projectId, projectRole: DefaultProjectRole.EDITOR })+ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.OPERATOR })++ const invitations = await platformInvitesOf({ email, platformId })+ expect(invitations).toHaveLength(1)+ expect(invitations[0].projectId).toBeNull()+ expect(invitations[0].projectRoleId).toBeNull()+ })++ it('collapses duplicates left from before into one invite', async () => {+ const { platformId, ownerToken } = await setupPlatform()+ const email = faker.internet.email().toLowerCase()+ await databaseConnection().getRepository('user_invitation').save([+ createMockUserInvitation({ email, platformId, type: InvitationType.PLATFORM, platformRole: PlatformRole.MEMBER, status: InvitationStatus.PENDING, created: '2026-01-01T00:00:00.000Z' }),+ createMockUserInvitation({ email, platformId, type: InvitationType.PLATFORM, platformRole: PlatformRole.MEMBER, status: InvitationStatus.PENDING, created: '2026-02-01T00:00:00.000Z' }),+ ])++ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.ADMIN })++ const invitations = await platformInvitesOf({ email, platformId })+ expect(invitations).toHaveLength(1)+ expect(invitations[0].platformRole).toBe(PlatformRole.ADMIN)+ })++ it('creates one invite when two arrive at the same time', async () => {+ const { platformId, ownerToken } = await setupPlatform()+ const email = faker.internet.email().toLowerCase()++ const responses = await Promise.all([+ invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.OPERATOR }),+ invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.OPERATOR }),+ ])++ expect(responses.map((response) => response?.statusCode)).toStrictEqual([StatusCodes.CREATED, StatusCodes.CREATED])+ expect(await platformInvitesOf({ email, platformId })).toHaveLength(1)+ })++ it('keeps one invite per platform for the same email', async () => {+ const first = await setupPlatform()+ const second = await setupPlatform()+ const email = faker.internet.email().toLowerCase()++ await invitePlatform({ token: first.ownerToken, email, platformRole: PlatformRole.OPERATOR })+ await invitePlatform({ token: second.ownerToken, email, platformRole: PlatformRole.OPERATOR })++ expect(await platformInvitesOf({ email, platformId: first.platformId })).toHaveLength(1)+ expect(await platformInvitesOf({ email, platformId: second.platformId })).toHaveLength(1)+ })+})++describe('Re-inviting someone who already accepted', () => {+ it('keeps the invite accepted and updates its role', async () => {+ const { platformId, ownerToken } = await setupPlatform()+ const email = faker.internet.email().toLowerCase()+ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.OPERATOR })+ await databaseConnection().getRepository('user_invitation').update({ email, platformId }, { status: InvitationStatus.ACCEPTED })++ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.ADMIN })++ const invitations = await platformInvitesOf({ email, platformId })+ expect(invitations).toHaveLength(1)+ expect(invitations[0].status).toBe(InvitationStatus.ACCEPTED)+ expect(invitations[0].platformRole).toBe(PlatformRole.ADMIN)+ })++ it('renews the seat reservation when re-sent unchanged', async () => {+ const { platformId, projectId, ownerToken } = await setupPlatform()+ const email = faker.internet.email().toLowerCase()+ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.MEMBER, projectId, projectRole: DefaultProjectRole.EDITOR })+ const [invitation] = await platformInvitesOf({ email, platformId })+ const sixDaysAgo = new Date(Date.now() - 6 * 24 * 60 * 60 * 1000).toISOString()+ await databaseConnection().getRepository('user_invitation').update({ id: invitation.id }, { updated: sixDaysAgo })++ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.MEMBER, projectId, projectRole: DefaultProjectRole.EDITOR })++ const [after] = await platformInvitesOf({ email, platformId })+ expect(Date.now() - new Date(after.updated).getTime()).toBeLessThan(60 * 1000)+ })++ it('locks the invite rows it is about to update, so acceptance and sign-up wait for the re-send', async () => {+ const { ownerToken } = await setupPlatform()+ const email = faker.internet.email().toLowerCase()+ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.OPERATOR })+ const find = vi.spyOn(Repository.prototype, 'find')++ try {+ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.ADMIN })+ const invitationReads = find.mock.calls.filter((_call, index) => {+ const repository = find.mock.contexts[index]+ return repository instanceof Repository && repository.metadata.tableName === 'user_invitation'+ })+ expect(invitationReads.some(([options]) => options?.lock?.mode === 'pessimistic_write')).toBe(true)+ }+ finally {+ find.mockRestore()+ }+ })++ it('keeps an acceptance made during a re-send', async () => {+ const { platformId, ownerToken } = await setupPlatform()+ const email = faker.internet.email().toLowerCase()+ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.OPERATOR })+ const originalFind = Repository.prototype.find+ let acceptance: Promise<unknown> | null = null+ const find = vi.spyOn(Repository.prototype, 'find').mockImplementation(async function (this: Repository<ObjectLiteral>, ...args: Parameters<Repository<ObjectLiteral>['find']>) {+ const rows = await originalFind.apply(this, args)+ if (this.metadata.tableName === 'user_invitation' && isNil(acceptance)) {+ acceptance = databaseConnection().getRepository('user_invitation').update({ email, platformId }, { status: InvitationStatus.ACCEPTED })+ }+ return rows+ })++ try {+ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.OPERATOR })+ }+ finally {+ find.mockRestore()+ }++ expect(acceptance).not.toBeNull()+ await acceptance+ expect((await platformInvitesOf({ email, platformId }))[0].status).toBe(InvitationStatus.ACCEPTED)+ })++ it('gives a fresh link when re-sent to someone who clicked it but never signed up', async () => {+ const { platformId, ownerToken } = await setupPlatform()+ const email = faker.internet.email().toLowerCase()+ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.OPERATOR })+ await databaseConnection().getRepository('user_invitation').update({ email, platformId }, { status: InvitationStatus.ACCEPTED })++ const response = await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.OPERATOR })++ expect(response?.statusCode).toBe(StatusCodes.CREATED)+ expect(response?.json().link).toEqual(expect.stringContaining('/invitation?token='))+ expect((await platformInvitesOf({ email, platformId }))[0].status).toBe(InvitationStatus.ACCEPTED)+ })++ it('keeps an accepted project invite, and the platform invite does not take that project', async () => {+ const { platformId, projectId, ownerToken } = await setupPlatform()+ const email = faker.internet.email().toLowerCase()+ await inviteProject({ token: ownerToken, email, projectId, projectRole: DefaultProjectRole.VIEWER })+ await databaseConnection().getRepository('user_invitation').update({ email, platformId, type: InvitationType.PROJECT }, { status: InvitationStatus.ACCEPTED })++ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.MEMBER, projectId, projectRole: DefaultProjectRole.EDITOR })++ const invitations = await invitesOf({ email, platformId })+ const projectInvite = invitations.find((invitation) => invitation.type === InvitationType.PROJECT)+ const platformInvite = invitations.find((invitation) => invitation.type === InvitationType.PLATFORM)+ expect(projectInvite?.status).toBe(InvitationStatus.ACCEPTED)+ expect(platformInvite?.projectId).toBeNull()+ })+})++describe('Adding someone to a project', () => {+ it('says they were added now when they already have an account on the platform', async () => {+ const { platformId, projectId, ownerToken } = await setupPlatform()+ const email = faker.internet.email().toLowerCase()+ await mockBasicUser({ userIdentity: { email }, user: { platformId, platformRole: PlatformRole.MEMBER } })++ const response = await inviteProject({ token: ownerToken, email, projectId, projectRole: DefaultProjectRole.VIEWER })++ expect(response?.statusCode).toBe(StatusCodes.CREATED)+ expect(response?.json().addedNow).toBe(true)+ })++ it('does not say they were added now when they still have to accept', async () => {+ const { projectId, ownerToken } = await setupPlatform()++ const response = await inviteProject({ token: ownerToken, email: faker.internet.email().toLowerCase(), projectId, projectRole: DefaultProjectRole.VIEWER })++ expect(response?.statusCode).toBe(StatusCodes.CREATED)+ expect(response?.json().addedNow).not.toBe(true)+ })+})++describe('A platform invite and a project invite for the same project', () => {+ it('a platform invite naming the project replaces the pending project invite', async () => {+ const { platformId, projectId, ownerToken } = await setupPlatform()+ const email = faker.internet.email().toLowerCase()++ await inviteProject({ token: ownerToken, email, projectId, projectRole: DefaultProjectRole.VIEWER })+ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.MEMBER, projectId, projectRole: DefaultProjectRole.EDITOR })++ const invitations = await invitesOf({ email, platformId })+ expect(invitations).toHaveLength(1)+ expect(invitations[0].type).toBe(InvitationType.PLATFORM)+ expect(invitations[0].projectId).toBe(projectId)+ })++ it('a project invite takes the project off the platform invite, and both stay', async () => {+ const { platformId, projectId, ownerToken } = await setupPlatform()+ const email = faker.internet.email().toLowerCase()++ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.MEMBER, projectId, projectRole: DefaultProjectRole.EDITOR })+ await inviteProject({ token: ownerToken, email, projectId, projectRole: DefaultProjectRole.VIEWER })++ const invitations = await invitesOf({ email, platformId })+ const platformInvite = invitations.find((invitation) => invitation.type === InvitationType.PLATFORM)+ const projectInvite = invitations.find((invitation) => invitation.type === InvitationType.PROJECT)+ expect(invitations).toHaveLength(2)+ expect(platformInvite?.platformRole).toBe(PlatformRole.MEMBER)+ expect(platformInvite?.projectId).toBeNull()+ expect(projectInvite?.projectId).toBe(projectId)+ })+})++describe('Removing a platform invite from a project', () => {+ it('takes the project off the invite and keeps the invite', async () => {+ const { platformId, projectId, ownerToken } = await setupPlatform()+ const email = faker.internet.email().toLowerCase()+ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.MEMBER, projectId, projectRole: DefaultProjectRole.EDITOR })+ const [invitation] = await platformInvitesOf({ email, platformId })++ const response = await removeProject({ token: ownerToken, invitationId: invitation.id, projectId })++ expect(response?.statusCode).toBe(StatusCodes.OK)+ const [after] = await platformInvitesOf({ email, platformId })+ expect(after.id).toBe(invitation.id)+ expect(after.platformRole).toBe(PlatformRole.MEMBER)+ expect(after.projectId).toBeNull()+ expect(after.projectRoleId).toBeNull()+ })++ it('leaves the invite alone when it was re-sent for another project since the page loaded', async () => {+ const { platformId, projectId, ownerToken } = await setupPlatform()+ const otherProject = createMockProject({ platformId, ownerId: (await ownerOf({ platformId })), type: ProjectType.TEAM })+ await databaseConnection().getRepository('project').save(otherProject)+ const email = faker.internet.email().toLowerCase()+ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.MEMBER, projectId, projectRole: DefaultProjectRole.EDITOR })+ const [invitation] = await platformInvitesOf({ email, platformId })+ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.MEMBER, projectId: otherProject.id, projectRole: DefaultProjectRole.VIEWER })++ const response = await removeProject({ token: ownerToken, invitationId: invitation.id, projectId })++ expect(response?.statusCode).toBe(StatusCodes.OK)+ const [after] = await platformInvitesOf({ email, platformId })+ expect(after.projectId).toBe(otherProject.id)+ })++ it('keeps an expired invite expired, so it does not take a seat again', async () => {+ const { platformId, projectId, ownerToken } = await setupPlatform()+ const email = faker.internet.email().toLowerCase()+ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.MEMBER, projectId, projectRole: DefaultProjectRole.EDITOR })+ const [invitation] = await platformInvitesOf({ email, platformId })+ const tenDaysAgo = new Date(Date.now() - 10 * 24 * 60 * 60 * 1000).toISOString()+ await databaseConnection().getRepository('user_invitation').update({ id: invitation.id }, { updated: tenDaysAgo })++ await removeProject({ token: ownerToken, invitationId: invitation.id, projectId })++ const [after] = await platformInvitesOf({ email, platformId })+ expect(after.projectId).toBeNull()+ expect(new Date(after.updated).toISOString()).toBe(tenDaysAgo)+ })++ it('is refused to a member who is not a platform admin', async () => {+ const { platformId, projectId, ownerToken } = await setupPlatform()+ const email = faker.internet.email().toLowerCase()+ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.MEMBER, projectId, projectRole: DefaultProjectRole.EDITOR })+ const [invitation] = await platformInvitesOf({ email, platformId })+ const { mockUser } = await mockBasicUser({ user: { platformId, platformRole: PlatformRole.MEMBER } })+ const memberToken = await generateMockToken({ id: mockUser.id, type: PrincipalType.USER, platform: { id: platformId } })++ const response = await removeProject({ token: memberToken, invitationId: invitation.id, projectId })++ expect(response?.statusCode).toBe(StatusCodes.FORBIDDEN)+ const [after] = await platformInvitesOf({ email, platformId })+ expect(after.projectId).toBe(projectId)+ })++ it('refuses a project invite', async () => {+ const { platformId, projectId, ownerToken } = await setupPlatform()+ const email = faker.internet.email().toLowerCase()+ await inviteProject({ token: ownerToken, email, projectId, projectRole: DefaultProjectRole.VIEWER })+ const [invitation] = await invitesOf({ email, platformId })++ const response = await removeProject({ token: ownerToken, invitationId: invitation.id, projectId })++ expect(response?.json().code).toBe(ErrorCode.VALIDATION)+ })++ it('revokes a Member invite instead when new members get no personal project and there are no default projects', async () => {+ const { platformId, projectId, ownerToken } = await setupPlatform()+ await turnOffPersonalProjects({ platformId })+ const email = faker.internet.email().toLowerCase()+ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.MEMBER, projectId, projectRole: DefaultProjectRole.EDITOR })+ const [invitation] = await platformInvitesOf({ email, platformId })++ const response = await removeProject({ token: ownerToken, invitationId: invitation.id, projectId })++ expect(response?.statusCode).toBe(StatusCodes.OK)+ expect(response?.json()).toStrictEqual({ revoked: true, invitation: null })+ expect(await platformInvitesOf({ email, platformId })).toHaveLength(0)+ })++ it('keeps their invites to other projects when it revokes the platform invite', async () => {+ const { platformId, projectId, ownerToken } = await setupPlatform()+ await turnOffPersonalProjects({ platformId })+ const sales = await saveTeamProject({ platformId })+ const email = faker.internet.email().toLowerCase()+ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.MEMBER, projectId, projectRole: DefaultProjectRole.EDITOR })+ await inviteProject({ token: ownerToken, email, projectId: sales.id, projectRole: DefaultProjectRole.VIEWER })+ const [invitation] = await platformInvitesOf({ email, platformId })++ await removeProject({ token: ownerToken, invitationId: invitation.id, projectId })++ const remaining = await invitesOf({ email, platformId })+ expect(remaining.map((row) => [row.type, row.projectId])).toStrictEqual([[InvitationType.PROJECT, sales.id]])+ })++ it('revokes it the same way for an API key', async () => {+ const { platformId, projectId, ownerToken } = await setupPlatform()+ await turnOffPersonalProjects({ platformId })+ const email = faker.internet.email().toLowerCase()+ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.MEMBER, projectId, projectRole: DefaultProjectRole.EDITOR })+ const [invitation] = await platformInvitesOf({ email, platformId })+ const apiKey = createMockApiKey({ platformId })+ await databaseConnection().getRepository('api_key').save(apiKey)++ const response = await removeProject({ token: apiKey.value, invitationId: invitation.id, projectId })++ expect(response?.json().revoked).toBe(true)+ expect(await platformInvitesOf({ email, platformId })).toHaveLength(0)+ })++ it('only takes the project off when a default project is still there for them', async () => {+ const { platformId, projectId, ownerToken } = await setupPlatform()+ await turnOffPersonalProjects({ platformId })+ const defaultProject = await saveTeamProject({ platformId })+ await databaseConnection().getRepository('project').update({ id: defaultProject.id }, { isDefault: true })+ const email = faker.internet.email().toLowerCase()+ await invitePlatform({ token: ownerToken, email, platformRole: PlatformRole.MEMBER, projectId, projectRole: DefaultProjectRole.EDITOR })+ const [invitation] = await platformInvitesOf({ email, platformId })++ const response = await removeProject({ token: ownerToken, invitationId: invitation.id, projectId })++ expect(response?.json().revoked).toBe(false)+ expect(response?.json().invitation.projectId).toBeNull()+ const [after] = await platformInvitesOf({ email, platformId })+ expect(after.projectId).toBeNull()+ })++ it('only takes the project off an invite that is not for a Member', async () => {+ const { platformId, projectId, ownerToken } = await setupPlatform()+ await turnOffPersonalProjects({ platformId })+ const email = faker.internet.email().toLowerCase()+ const invitation = createMockUserInvitation({ email, platformId, type: InvitationType.PLATFORM, platformRole: PlatformRole.OPERATOR, projectId, status: InvitationStatus.PENDING })+ await databaseConnection().getRepository('user_invitation').save(invitation)++ const response = await removeProject({ token: ownerToken, invitationId: invitation.id, projectId })++ expect(response?.json().revoked).toBe(false)+ const [after] = await platformInvitesOf({ email, platformId })+ expect(after.projectId).toBeNull()+ })++ it('does not find another platform\'s invite', async () => {+ const first = await setupPlatform()+ const second = await setupPlatform()+ const email = faker.internet.email().toLowerCase()+ await invitePlatform({ token: second.ownerToken, email, platformRole: PlatformRole.MEMBER, projectId: second.projectId, projectRole: DefaultProjectRole.EDITOR })+ const [invitation] = await platformInvitesOf({ email, platformId: second.platformId })++ const response = await removeProject({ token: first.ownerToken, invitationId: invitation.id, projectId: second.projectId })++ expect(response?.statusCode).toBe(StatusCodes.NOT_FOUND)+ const [after] = await platformInvitesOf({ email, platformId: second.platformId })+ expect(after.projectId).toBe(second.projectId)+ })+})++describe('Listing the platform invites that name a project', () => {+ it('returns only the platform invites for that project', async () => {+ const { platformId, projectId, ownerToken } = await setupPlatform()+ const named = faker.internet.email().toLowerCase()+ const unnamed = faker.internet.email().toLowerCase()+ await invitePlatform({ token: ownerToken, email: named, platformRole: PlatformRole.MEMBER, projectId, projectRole: DefaultProjectRole.EDITOR })+ await invitePlatform({ token: ownerToken, email: unnamed, platformRole: PlatformRole.OPERATOR })++ const response = await app?.inject({+ method: 'GET',+ url: `/api/v1/user-invitations?type=${InvitationType.PLATFORM}&projectId=${projectId}`,+ headers: { authorization: `Bearer ${ownerToken}` },+ })++ expect(response?.statusCode).toBe(StatusCodes.OK)+ const emails = response?.json().data.map((invitation: { email: string }) => invitation.email)+ expect(emails).toStrictEqual([named])+ expect(await platformInvitesOf({ email: unnamed, platformId })).toHaveLength(1)+ })++ it('treats an empty project filter as no filter, as the web client sends it', async () => {+ const { ownerToken } = await setupPlatform()+ await invitePlatform({ token: ownerToken, email: faker.internet.email().toLowerCase(), platformRole: PlatformRole.OPERATOR })++ const response = await app?.inject({+ method: 'GET',+ url: `/api/v1/user-invitations?type=${InvitationType.PLATFORM}&projectId=`,+ headers: { authorization: `Bearer ${ownerToken}` },+ })++ expect(response?.json().data).toHaveLength(1)+ })++ it('still returns every platform invite without a project filter', async () => {+ const { projectId, ownerToken } = await setupPlatform()+ await invitePlatform({ token: ownerToken, email: faker.internet.email().toLowerCase(), platformRole: PlatformRole.MEMBER, projectId, projectRole: DefaultProjectRole.EDITOR })+ await invitePlatform({ token: ownerToken, email: faker.internet.email().toLowerCase(), platformRole: PlatformRole.OPERATOR })++ const response = await app?.inject({+ method: 'GET',+ url: `/api/v1/user-invitations?type=${InvitationType.PLATFORM}`,+ headers: { authorization: `Bearer ${ownerToken}` },+ })++ expect(response?.json().data).toHaveLength(2)+ })+})++async function setupPlatform() {+ const { mockPlatform, mockOwner, mockProject } = await mockAndSaveBasicSetup({+ plan: { projectRolesEnabled: true },+ project: { type: ProjectType.TEAM },+ })+ const ownerToken = await generateMockToken({ id: mockOwner.id, type: PrincipalType.USER, platform: { id: mockPlatform.id } })+ return { platformId: mockPlatform.id, projectId: mockProject.id, ownerToken }+}++async function invitePlatform({ token, email, platformRole, projectId, projectRole }: { token: string, email: string, platformRole: PlatformRole, projectId?: string, projectRole?: string }) {+ return app?.inject({+ method: 'POST',+ url: '/api/v1/user-invitations',+ headers: { authorization: `Bearer ${token}` },+ body: { email, type: InvitationType.PLATFORM, platformRole, projectId, projectRole },+ })+}++async function inviteProject({ token, email, projectId, projectRole }: { token: string, email: string, projectId: string, projectRole: string }) {+ return app?.inject({+ method: 'POST',+ url: '/api/v1/user-invitations',+ headers: { authorization: `Bearer ${token}` },+ body: { email, type: InvitationType.PROJECT, projectId, projectRole },+ })+}++async function invitesOf({ email, platformId }: { email: string, platformId: string }) {+ return databaseConnection().getRepository('user_invitation').findBy({ email, platformId })+}++async function platformInvitesOf({ email, platformId }: { email: string, platformId: string }) {+ return databaseConnection().getRepository('user_invitation').findBy({ email, platformId, type: InvitationType.PLATFORM })+}++async function roleNameOf({ projectRoleId }: { projectRoleId: string }) {+ const role = await databaseConnection().getRepository('project_role').findOneByOrFail({ id: projectRoleId })+ return role.name+}++async function ownerOf({ platformId }: { platformId: string }) {+ const platform = await databaseConnection().getRepository('platform').findOneByOrFail({ id: platformId })+ return platform.ownerId+}++async function turnOffPersonalProjects({ platformId }: { platformId: string }) {+ await databaseConnection().getRepository('platform').update({ id: platformId }, { autoCreatePersonalProjects: false })+}++async function saveTeamProject({ platformId }: { platformId: string }) {+ const project = createMockProject({ platformId, ownerId: await ownerOf({ platformId }), type: ProjectType.TEAM })+ await databaseConnection().getRepository('project').save(project)+ return project+}++async function removeProject({ token, invitationId, projectId }: { token: string, invitationId: string, projectId: string }) {+ return app?.inject({+ method: 'POST',+ url: `/api/v1/user-invitations/${invitationId}/remove-project`,+ headers: { authorization: `Bearer ${token}` },+ body: { projectId },+ })+}diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.jsonindex 8290139d54c..f5acf08205f 100644--- a/packages/web/public/locales/en/translation.json+++ b/packages/web/public/locales/en/translation.json@@ -66,6 +66,17 @@"Access to any team projects they're invited to. New members also join the default projects.": "Access to any team projects they're invited to. New members also join the default projects.","inviteJoinsDefaults": "New members also join the {defaultProjects} as Editors.","default projects": "default projects",+ "reinviteReplacesInvite": "{count, plural, =1 {{list} already has an invite. Sending again replaces it with the {namesProject, select, true {role and project} other {role}} below.} other {{list} already have invites. Sending again replaces them with the {namesProject, select, true {role and project} other {role}} below.}}",+ "alreadyOnPlatformNotInvited": "{count, plural, =1 {{list} is already on the platform. To change their role, edit them in Members. To add them to a project, invite them from that project.} other {{list} are already on the platform. To change their roles, edit them in Members. To add them to a project, invite them from that project.}}",+ "Already on the platform": "Already on the platform",+ "Updates their invite": "Updates their invite",+ "Platform invite": "Platform invite",+ "Invited to the platform with this project.": "Invited to the platform with this project.",+ "Remove from this project?": "Remove from this project?",+ "removePlatformInviteFromDefaultProject": "{projectName} is a default project, so {email} will still join it as an Editor when they accept.",+ "removePlatformInviteFromProject": "{email} won't join {projectName} when they accept. Their platform invite stays, so they still join the platform.",+ "removePlatformInviteRevokesIt": "This revokes {email}'s platform invite. If they're invited to other projects, they can still join the platform through those invites.",+ "Revoke invite": "Revoke invite","inviteJoinsDefaultsAndPersonal": "New members also join the {defaultProjects} as Editors and get a personal project.","They'll get a personal project to start in.": "They'll get a personal project to start in.","No default projects yet": "No default projects yet",diff --git a/packages/web/src/app/components/project-settings/members/columns.tsx b/packages/web/src/app/components/project-settings/members/columns.tsxindex a489cf9df0a..e620886e7e6 100644--- a/packages/web/src/app/components/project-settings/members/columns.tsx+++ b/packages/web/src/app/components/project-settings/members/columns.tsx@@ -1,5 +1,7 @@import { ErrorCode, Permission } from '@activepieces/core-utils';import {+ InvitationType,+ PlatformRole,ProjectMemberWithUser,UserInvitation,UserWithMetaInformation,@@ -16,6 +18,7 @@ import { ConfirmationDeleteDialog } from '@/components/custom/delete-dialog';import { PermissionNeededTooltip } from '@/components/custom/permission-needed-tooltip';import { TextWithTooltip } from '@/components/custom/text-with-tooltip';import { UserAvatar } from '@/components/custom/user-avatar';+import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import { internalErrorToast } from '@/components/ui/sonner';import {@@ -33,6 +36,8 @@ import {import { projectRoleQueries } from '@/features/platform-admin';import { projectCollectionUtils } from '@/features/projects';import { useAuthorization } from '@/hooks/authorization-hooks';+import { platformHooks } from '@/hooks/platform-hooks';+import { userHooks } from '@/hooks/user-hooks';import { api } from '@/lib/api';import { formatUtils } from '@/lib/format-utils';@@ -171,6 +176,10 @@ const ActionsCell = ({}) => {const { checkAccess } = useAuthorization();const { project } = projectCollectionUtils.useCurrentProject();+ const { activeDefaultProjectIds, personalProjectsActive } =+ platformHooks.useNewMemberSettings();+ const { data: currentUser } = userHooks.useCurrentUser();+ const isPlatformAdmin = currentUser?.platformRole === PlatformRole.ADMIN;const [isConfirmOpen, setIsConfirmOpen] = useState(false);const [isLastProjectOpen, setIsLastProjectOpen] = useState(false);const isLastProject =@@ -188,16 +197,42 @@ const ActionsCell = ({const isPlatformAdminOrOperator =row.original.type === 'platform-admin-operator';+ const isPlatformInvitation =+ row.original.type === 'invitation' &&+ row.original.data.type === InvitationType.PLATFORM;++ const stillJoinsAsDefaultProject =+ row.original.type === 'invitation' &&+ row.original.data.type === InvitationType.PLATFORM &&+ row.original.data.platformRole === PlatformRole.MEMBER &&+ activeDefaultProjectIds.includes(project.id);++ const revokesInvite =+ row.original.type === 'invitation' &&+ row.original.data.type === InvitationType.PLATFORM &&+ row.original.data.platformRole === PlatformRole.MEMBER &&+ !personalProjectsActive &&+ activeDefaultProjectIds.length === 0;+const deleteMember = async () => {if (row.original.type === 'member') {await projectMembersApi.delete(row.original.data.id);+ } else if (isPlatformInvitation) {+ await userInvitationApi.removeProject({+ id: row.original.data.id,+ projectId: project.id,+ });} else {await userInvitationApi.delete(row.original.data.id);}refetch();};- if (isOwner || isPlatformAdminOrOperator) {+ if (+ isOwner ||+ isPlatformAdminOrOperator ||+ (isPlatformInvitation && !isPlatformAdmin)+ ) {return null;}@@ -227,17 +262,34 @@ const ActionsCell = ({internalErrorToast();}}title={- row.original.type === 'invitation'+ isPlatformInvitation+ ? t('Remove from this project?')+ : row.original.type === 'invitation'? t('Remove Invitation'): t('Remove Member')}message={- row.original.type === 'invitation'+ stillJoinsAsDefaultProject+ ? t('removePlatformInviteFromDefaultProject', {+ email: displayName,+ projectName: project.displayName,+ })+ : revokesInvite+ ? t('removePlatformInviteRevokesIt', {+ email: displayName,+ })+ : isPlatformInvitation+ ? t('removePlatformInviteFromProject', {+ email: displayName,+ projectName: project.displayName,+ })+ : row.original.type === 'invitation'? t('This invitation will be revoked immediately.'): t('This member will lose access to the project immediately.')}mutationFn={() => deleteMember()}entityName={displayName}+ buttonText={revokesInvite ? t('Revoke invite') : undefined}><Buttonvariant="ghost"@@ -256,6 +308,21 @@ const ActionsCell = ({);};+const PlatformInviteBadge = () => (+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <Badge variant="outline" className="w-fit text-gray-11">+ {t('Platform invite')}+ </Badge>+ </TooltipTrigger>+ <TooltipContent>+ {t('Invited to the platform with this project.')}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+);+export const membersTableColumns = ({refetch,}: MembersTableColumnsProps): (ColumnDef<RowDataWithActions<MemberRowData>> & {@@ -286,6 +353,9 @@ export const membersTableColumns = ({<TextWithTooltip tooltipMessage={email}><p className="text-sm text-warning-11">{email}</p></TextWithTooltip>+ {row.original.data.type === InvitationType.PLATFORM && (+ <PlatformInviteBadge />+ )}</div></div>);diff --git a/packages/web/src/app/components/project-settings/members/index.tsx b/packages/web/src/app/components/project-settings/members/index.tsxindex 456ca80b9ab..4b9a0439fec 100644--- a/packages/web/src/app/components/project-settings/members/index.tsx+++ b/packages/web/src/app/components/project-settings/members/index.tsx@@ -32,6 +32,15 @@ export const MembersSettings = () => {isError: invitationsFailed,refetch: refetchInvitations,} = userInvitationsHooks.useInvitations();+ const currentProjectId = authenticationSession.getProjectId();+ const {+ data: platformInvitations,+ isLoading: platformInvitationsIsPending,+ isError: platformInvitationsFailed,+ refetch: refetchPlatformInvitations,+ } = userInvitationsHooks.useProjectPlatformInvitations({+ projectId: currentProjectId,+ });const {data: platformUsersData,isLoading: platformUsersIsPending,@@ -49,11 +58,10 @@ export const MembersSettings = () => {const refetch = useCallback(() => {refetchProjectMembers();refetchInvitations();- }, [refetchProjectMembers, refetchInvitations]);+ refetchPlatformInvitations();+ }, [refetchProjectMembers, refetchInvitations, refetchPlatformInvitations]);const combinedData: MemberRowData[] = useMemo(() => {- const currentProjectId = authenticationSession.getProjectId();-const members: MemberRowData[] =projectMembers?.filter((member) => member.user.status === UserStatus.ACTIVE)@@ -76,6 +84,15 @@ export const MembersSettings = () => {data: invitation,})) ?? [];+ const pendingPlatformInvitations: MemberRowData[] =+ platformInvitations+ ?.filter((invitation) => invitation.projectId === currentProjectId)+ .map((invitation) => ({+ id: invitation.id,+ type: 'invitation' as const,+ data: invitation,+ })) ?? [];+const projectMemberEmails = new Set(projectMembers?.map((member) => member.user.email.toLowerCase()) ?? [],);@@ -95,8 +112,19 @@ export const MembersSettings = () => {data: user,})) ?? [];- return [...members, ...platformAdminsAndOperators, ...pendingInvitations];- }, [projectMembers, invitations, platformUsersData]);+ return [+ ...members,+ ...platformAdminsAndOperators,+ ...pendingInvitations,+ ...pendingPlatformInvitations,+ ];+ }, [+ projectMembers,+ invitations,+ platformInvitations,+ platformUsersData,+ currentProjectId,+ ]);const filteredData = useMemo(() => {if (!filterValue) {@@ -158,10 +186,14 @@ export const MembersSettings = () => {isLoading={projectMembersIsPending ||invitationsIsPending ||+ platformInvitationsIsPending ||platformUsersIsPending}isError={- projectMembersFailed || invitationsFailed || platformUsersFailed+ projectMembersFailed ||+ invitationsFailed ||+ platformInvitationsFailed ||+ platformUsersFailed}errorStateEntity={t('members')}onRetry={refetch}@@ -172,7 +204,11 @@ export const MembersSettings = () => {)}emptyStateIcon={<Users className="size-14" />}/>- <InviteUserDialog open={inviteOpen} setOpen={setInviteOpen} />+ <InviteUserDialog+ open={inviteOpen}+ setOpen={setInviteOpen}+ onInviteSuccess={refetch}+ /></div>);};diff --git a/packages/web/src/app/routes/platform/users/index.tsx b/packages/web/src/app/routes/platform/users/index.tsxindex fc7f95f8fa5..e06b3671d53 100644--- a/packages/web/src/app/routes/platform/users/index.tsx+++ b/packages/web/src/app/routes/platform/users/index.tsx@@ -41,12 +41,8 @@ export type UserRowData =export default function UsersPage() {const [inviteOpen, setInviteOpen] = useState(false);- const {- isOutOfSeats,- ensureSeatsAvailable,- handleSeatLimitError,- seatLimitDialog,- } = useSeatLimitGuard();+ const { isOutOfSeats, handleSeatLimitError, seatLimitDialog } =+ useSeatLimitGuard();const {data: usersData,@@ -136,11 +132,7 @@ export default function UsersPage() {><Button{...adminControl(AdminControl.USERS_INVITE_OPEN)}- onClick={() => {- if (ensureSeatsAvailable(1)) {- setInviteOpen(true);- }- }}+ onClick={() => setInviteOpen(true)}>{isOutOfSeats ? (<Gem className="text-on-accent/90" />diff --git a/packages/web/src/features/members/api/user-invitation.ts b/packages/web/src/features/members/api/user-invitation.tsindex 0a1d75f0804..328a070cbb2 100644--- a/packages/web/src/features/members/api/user-invitation.ts+++ b/packages/web/src/features/members/api/user-invitation.ts@@ -1,6 +1,7 @@import { SeekPage } from '@activepieces/core-utils';import {ListUserInvitationsRequest,+ RemoveProjectFromInvitationResponse,SendUserInvitationRequest,UserInvitation,UserInvitationWithLink,@@ -15,6 +16,15 @@ export const userInvitationApi = {list: (request: ListUserInvitationsRequest) => {return api.get<SeekPage<UserInvitation>>('/v1/user-invitations', request);},+ listAll: (request: Omit<ListUserInvitationsRequest, 'cursor'>) => {+ return listAllPages({ request, cursor: undefined });+ },+ removeProject({ id, projectId }: { id: string; projectId: string }) {+ return api.post<RemoveProjectFromInvitationResponse>(+ `/v1/user-invitations/${id}/remove-project`,+ { projectId },+ );+ },delete(id: string): Promise<void> {return api.delete<void>(`/v1/user-invitations/${id}`);},@@ -24,3 +34,23 @@ export const userInvitationApi = {});},};++async function listAllPages({+ request,+ cursor,+}: {+ request: Omit<ListUserInvitationsRequest, 'cursor'>;+ cursor: string | undefined;+}): Promise<UserInvitation[]> {+ const page = await api.get<SeekPage<UserInvitation>>('/v1/user-invitations', {+ ...request,+ cursor,+ });+ if (!page.next) {+ return page.data;+ }+ return [+ ...page.data,+ ...(await listAllPages({ request, cursor: page.next })),+ ];+}diff --git a/packages/web/src/features/members/components/invite-user/invite-user-dialog.tsx b/packages/web/src/features/members/components/invite-user/invite-user-dialog.tsxindex 15af908e59b..8f01b660613 100644--- a/packages/web/src/features/members/components/invite-user/invite-user-dialog.tsx+++ b/packages/web/src/features/members/components/invite-user/invite-user-dialog.tsx@@ -1,7 +1,6 @@import { isNil, Permission } from '@activepieces/core-utils';import {ApFlagId,- InvitationStatus,InvitationType,PlatformRole,ProjectType,@@ -54,6 +53,7 @@ import { userInvitationsHooks } from '../../hooks/user-invitations-hooks';import { DefaultProjectsNote } from './default-projects-note';import { InvitedProjectSelect } from './invited-project-select';import { NoTeamProjectsState } from './no-team-projects-state';+import { ExistingEmailStatus } from './types';import { UserSuggestionsPopover } from './user-suggestions-popover';const buildInvalidEmailsMessage = (emails: string[]): string => {@@ -157,8 +157,8 @@ const InviteUserDialogInternal = ({const resultsWithLinks = invitationResults.filter((r) => r.link);const hasLinks = resultsWithLinks.length > 0;- const addedMembersCount = invitationResults.filter(- (r) => r.status === InvitationStatus.ACCEPTED,+ const addedMembersCount = invitationResults.filter((result) =>+ wasAddedNow({ result }),).length;const { mutate, isPending } = useMutation<@@ -190,8 +190,8 @@ const InviteUserDialogInternal = ({return Promise.all(promises);},onSuccess: (results) => {- const addedCount = results.filter(- (r) => r.status === InvitationStatus.ACCEPTED,+ const addedCount = results.filter((result) =>+ wasAddedNow({ result }),).length;const invitedCount = results.filter((r) => r.link).length;@@ -243,6 +243,14 @@ const InviteUserDialogInternal = ({const invitationType = form.getValues().type;const isPlatformInvite = invitationType === InvitationType.PLATFORM;+ const { data: platformInvitations } =+ platformUserHooks.usePlatformInvitations({+ enabled: open && isPlatformInvite,+ });+ const platformInviteEmails = new Set(+ platformInvitations?.map((invitation) => invitation.email.toLowerCase()) ??+ [],+ );const selectedPlatformRole = form.watch('platformRole');const enteredEmails = form.watch('emails');const invitesSomeoneNew =@@ -250,6 +258,20 @@ const InviteUserDialogInternal = ({enteredEmails.some((email) => !platformUserEmails.has(email.trim().toLowerCase()),);+ const existingEmails = isPlatformInvite+ ? existingPlatformInviteEmails({+ emails: enteredEmails,+ platformUserEmails,+ platformInviteEmails,+ })+ : new Map<string, ExistingEmailStatus>();+ const skippedEmails = new Set(+ [...existingEmails.entries()]+ .filter(([, status]) => status === 'on-platform')+ .map(([email]) => email),+ );+ const everyEmailIsSkipped =+ enteredEmails.length > 0 && skippedEmails.size === enteredEmails.length;const selectedProjectId = form.watch('projectId');const joinsDefaultProjects =invitationType === InvitationType.PROJECT ||@@ -265,15 +287,13 @@ const InviteUserDialogInternal = ({const handleEmailsChange = useCallback((emails: ReadonlyArray<string>) => {- const filtered = emails.filter((e) => {- const lower = e.toLowerCase();- if (isPlatformInvite) return !platformUserEmails.has(lower);- return !projectMemberEmails.has(lower);- });+ const filtered = isPlatformInvite+ ? emails+ : emails.filter((e) => !projectMemberEmails.has(e.toLowerCase()));form.setValue('emails', [...filtered]);form.trigger('emails');},- [form, isPlatformInvite, platformUserEmails, projectMemberEmails],+ [form, isPlatformInvite, projectMemberEmails],);const onSubmit = (data: FormSchema) => {@@ -305,11 +325,21 @@ const InviteUserDialogInternal = ({return;}- if (!ensureSeatsAvailable(data.emails.length)) {+ const emailsToInvite = data.emails.filter(+ (email) => !skippedEmails.has(email.trim().toLowerCase()),+ );+ if (emailsToInvite.length === 0) {+ return;+ }++ const newEmailsCount = emailsToInvite.filter(+ (email) => !existingEmails.has(email.trim().toLowerCase()),+ ).length;+ if (newEmailsCount > 0 && !ensureSeatsAvailable(newEmailsCount)) {return;}- mutate(data);+ mutate({ ...data, emails: emailsToInvite });};const copyAllLinks = () => {@@ -399,7 +429,17 @@ const InviteUserDialogInternal = ({placeholder={t('Invite users by email')}invitationType={invitationType}onOpenChange={setSuggestionsOpen}+ existingEmails={existingEmails}/>+ {existingEmailsMessages({+ existingEmails,+ namesProject:+ projectMode !== 'none' && !isNil(selectedProjectId),+ }).map((message) => (+ <p key={message} className="text-xs text-gray-11">+ {message}+ </p>+ ))}<FormMessage /></FormItem>)}@@ -478,7 +518,7 @@ const InviteUserDialogInternal = ({<Buttontype="submit"loading={isPending}- disabled={needsAProjectFirst}+ disabled={needsAProjectFirst || everyEmailIsSkipped}{...adminControl(AdminControl.USERS_INVITE_SUBMIT)}>{isPlatformInvite ? t('Invite') : t('Add')}@@ -536,6 +576,10 @@ const InviteUserDialogInternal = ({);};+function wasAddedNow({ result }: WasAddedNowParams): boolean {+ return result.addedNow === true;+}+function invitedProjectMode({type,platformRole,@@ -552,6 +596,53 @@ function invitedProjectMode({return personalProjectsActive ? 'optional' : 'required';}+function existingPlatformInviteEmails({+ emails,+ platformUserEmails,+ platformInviteEmails,+}: ExistingPlatformInviteEmailsParams): Map<string, ExistingEmailStatus> {+ return new Map(+ emails.flatMap((email): [string, ExistingEmailStatus][] => {+ const normalized = email.trim().toLowerCase();+ if (platformUserEmails.has(normalized)) {+ return [[normalized, 'on-platform']];+ }+ if (platformInviteEmails.has(normalized)) {+ return [[normalized, 'already-invited']];+ }+ return [];+ }),+ );+}++function existingEmailsMessages({+ existingEmails,+ namesProject,+}: ExistingEmailsMessagesParams): string[] {+ const entries = [...existingEmails.entries()];+ const alreadyInvited = entries+ .filter(([, status]) => status === 'already-invited')+ .map(([email]) => email);+ const onPlatform = entries+ .filter(([, status]) => status === 'on-platform')+ .map(([email]) => email);+ return [+ alreadyInvited.length > 0+ ? t('reinviteReplacesInvite', {+ count: alreadyInvited.length,+ list: alreadyInvited.join(', '),+ namesProject: String(namesProject),+ })+ : null,+ onPlatform.length > 0+ ? t('alreadyOnPlatformNotInvited', {+ count: onPlatform.length,+ list: onPlatform.join(', '),+ })+ : null,+ ].filter((message) => message !== null);+}+function invitedProjectFields({data,projectRolesEnabled,@@ -705,8 +796,23 @@ type InvitedProjectModeParams = {personalProjectsActive: boolean;};+type ExistingEmailsMessagesParams = {+ existingEmails: Map<string, ExistingEmailStatus>;+ namesProject: boolean;+};++type ExistingPlatformInviteEmailsParams = {+ emails: string[];+ platformUserEmails: Set<string>;+ platformInviteEmails: Set<string>;+};+type InvitedProjectFieldsParams = {data: FormSchema;projectRolesEnabled: boolean;personalProjectsActive: boolean;};++type WasAddedNowParams = {+ result: UserInvitationWithLink;+};diff --git a/packages/web/src/features/members/components/invite-user/types.ts b/packages/web/src/features/members/components/invite-user/types.tsindex 3ab3c316caf..45a5065bd8c 100644--- a/packages/web/src/features/members/components/invite-user/types.ts+++ b/packages/web/src/features/members/components/invite-user/types.ts@@ -11,3 +11,5 @@ export type EmailStatusType =type: 'new-user';user: undefined;};++export type ExistingEmailStatus = 'on-platform' | 'already-invited';diff --git a/packages/web/src/features/members/components/invite-user/user-suggestions-popover.tsx b/packages/web/src/features/members/components/invite-user/user-suggestions-popover.tsxindex c26a848cc61..256610f784a 100644--- a/packages/web/src/features/members/components/invite-user/user-suggestions-popover.tsx+++ b/packages/web/src/features/members/components/invite-user/user-suggestions-popover.tsx@@ -1,6 +1,6 @@import { InvitationType } from '@activepieces/shared';import { t } from 'i18next';-import { Globe, UserCheck } from 'lucide-react';+import { Globe, Mail, UserCheck } from 'lucide-react';import React, { useCallback, useRef, useState } from 'react';import { TagInput, TagMeta } from '@/components/custom/tag-input';@@ -9,6 +9,7 @@ import { ScrollArea } from '@/components/ui/scroll-area';import { formatUtils } from '@/lib/format-utils';import { SuggestedUserItem } from './suggested-user-item';+import { ExistingEmailStatus } from './types';import { useUserSuggestions } from './use-user-suggestions';function UserSuggestionsPopover({@@ -17,6 +18,7 @@ function UserSuggestionsPopover({placeholder,invitationType,onOpenChange,+ existingEmails,}: UserSuggestionsPopoverProps) {const [inputValue, setInputValue] = useState('');const [showSuggestions, setShowSuggestions] = useState(false);@@ -43,6 +45,21 @@ function UserSuggestionsPopover({if (!formatUtils.emailRegex.test(trimmed)) {return { tooltip: t('Invalid email') };}+ const existingStatus = existingEmails?.get(trimmed.toLowerCase());+ if (existingStatus === 'on-platform') {+ return {+ className: SKIPPED_TAG_CLASS_NAME,+ icon: <UserCheck className="size-3 shrink-0" />,+ tooltip: t('Already on the platform'),+ };+ }+ if (existingStatus === 'already-invited') {+ return {+ className: UPDATED_INVITE_TAG_CLASS_NAME,+ icon: <Mail className="size-3 shrink-0" />,+ tooltip: t('Updates their invite'),+ };+ }if (platformUserEmails.has(trimmed.toLowerCase())) {return {className: 'text-accent-11 bg-accent-3 border-accent-7',@@ -56,7 +73,7 @@ function UserSuggestionsPopover({tooltip: isPlatformInvite ? t('New User') : t('New Member'),};},- [platformUserEmails, isPlatformInvite],+ [platformUserEmails, isPlatformInvite, existingEmails],);const handleSelectUser = (email: string) => {@@ -165,12 +182,19 @@ function UserSuggestionsPopover({);}+const SKIPPED_TAG_CLASS_NAME =+ 'text-gray-11 bg-transparent border-dashed border-gray-7';++const UPDATED_INVITE_TAG_CLASS_NAME =+ 'text-gray-12 bg-transparent border-dashed border-gray-8';+type UserSuggestionsPopoverProps = {value: ReadonlyArray<string>;onChange: (emails: ReadonlyArray<string>) => void;placeholder?: string;invitationType: InvitationType;onOpenChange?: (open: boolean) => void;+ existingEmails?: Map<string, ExistingEmailStatus>;};export { UserSuggestionsPopover };diff --git a/packages/web/src/features/members/hooks/user-invitations-hooks.ts b/packages/web/src/features/members/hooks/user-invitations-hooks.tsindex f7095a44daa..e6b1867a6fa 100644--- a/packages/web/src/features/members/hooks/user-invitations-hooks.ts+++ b/packages/web/src/features/members/hooks/user-invitations-hooks.ts@@ -1,3 +1,4 @@+import { isNil } from '@activepieces/core-utils';import { InvitationType, UserInvitation } from '@activepieces/shared';import { useMutation, useQuery } from '@tanstack/react-query';@@ -27,6 +28,24 @@ export const userInvitationsHooks = {refetch: query.refetch,};},+ useProjectPlatformInvitations: ({+ projectId,+ }: {+ projectId: string | null;+ }) => {+ return useQuery<UserInvitation[]>({+ queryFn: () => {+ return userInvitationApi.listAll({+ type: InvitationType.PLATFORM,+ projectId,+ limit: 100,+ });+ },+ queryKey: [userInvitationsQueryKey, 'platform', projectId],+ enabled: !isNil(projectId),+ staleTime: 0,+ });+ },};export const userInvitationMutations = {diff --git a/packages/web/src/features/platform-admin/hooks/platform-user-hooks.ts b/packages/web/src/features/platform-admin/hooks/platform-user-hooks.tsindex 709cf954988..db3455c8344 100644--- a/packages/web/src/features/platform-admin/hooks/platform-user-hooks.ts+++ b/packages/web/src/features/platform-admin/hooks/platform-user-hooks.ts@@ -38,20 +38,18 @@ export const platformUserHooks = {enabled: canListUsers,});},- usePlatformInvitations: () => {+ usePlatformInvitations: ({ enabled = true }: { enabled?: boolean } = {}) => {return useQuery({queryFn: () => {- return userInvitationApi- .list({- type: InvitationType.PLATFORM,- cursor: undefined,- limit: 100,- projectId: null,- })- .then((res) => res.data);+ return userInvitationApi.listAll({+ type: InvitationType.PLATFORM,+ limit: 100,+ projectId: null,+ });},queryKey: platformUserKeys.invitations,staleTime: 0,+ enabled,});},};