Skip to content

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

feat(projects): invites name a project, and personal projects move to Roles & access (#15973)

lina-alomarie5ba922d0f55
diff --git a/brain/knowledge/platform-editions-ee/platform-configuration.md b/brain/knowledge/platform-editions-ee/platform-configuration.md
index 6c6eb86a50b..cc38a2aaf03 100644
--- a/brain/knowledge/platform-editions-ee/platform-configuration.md
+++ b/brain/knowledge/platform-editions-ee/platform-configuration.md
@@ -8,7 +8,7 @@ A **Platform** is the top-level tenant namespace in Activepieces. Every install
### Entities & services
- `platform` entity: `ownerId`, `name`, `primaryColor` (drives the whole palette; see *design-system/colour*), `themeColors` (jsonb, set under Platform → General → *Colors*; only `themeColors.status` is rendered, as the status seeds served in the `theme` flag's `statusColors`; see *design-system/colour*), logo/favicon URLs, `cloudAuthEnabled`, `allowedAuthDomains`, `emailAuthEnabled`, `federatedAuthProviders` (jsonb OAuth2 + SAML), `pinnedPieces`, `pieceSelectorConfig` (jsonb, null = default tabs).
-- `platformService`: `create`, `update`, `getOneWithPlanAndUsageOrThrow`, `getOneWithPlanOrThrow` (flags only, used in auth guards), `listPlatformsForIdentityWithAtleastProject` (platform-switcher), `getOldestPlatform` (CE single-platform resolution).
+- `platformService`: `create`, `update`, `getOneWithPlanAndUsageOrThrow`, `getOneWithPlanOrThrow` (flags only, used in auth guards), `listPlatformsForIdentity` (platform-switcher and Cloud sign-in; platforms where the user has a project come first, but a platform where they have none is still listed so they land on its no-projects screen instead of being onboarded onto a new platform). Cloud sign-in (`selectCloudSignInPlatformId`) always takes the last-used platform, even one where they have no project left (they can switch from its no-projects screen); only a first sign-in prefers a platform where they have a project, then any, and accepting an invite through its link sets `lastLoggedInPlatformId` to the invite's platform so the next sign-in lands there; auto-accepted invites (an admin adding an existing user to a project) deliberately don't, `getOldestPlatform` (CE single-platform resolution).
### Endpoints
- `GET /v1/platforms/:id` — plan + usage; sensitive SSO data stripped (`PlatformWithoutSensitiveData`).
diff --git a/brain/knowledge/platform-editions-ee/projects.md b/brain/knowledge/platform-editions-ee/projects.md
index 181268d674a..46dbe0a8717 100644
--- a/brain/knowledge/platform-editions-ee/projects.md
+++ b/brain/knowledge/platform-editions-ee/projects.md
@@ -28,6 +28,7 @@ A **Project** is the workspace within a platform where flows, connections, table
- The web project collection never sends `isDefault` when it saves other project settings, so a stale cache can't undo another admin's change. Defaults are only changed through `projectCollectionUtils.useSetDefaultProjects`.
- A soft-deleted project keeps its flag until the hard delete; reads skip deleted rows. A default project can't be deleted from the app while it is a default: remove it on Roles & Access first (see decision 000049). API-key deletes, SCIM group deletes, and plans without project roles still delete it. The app check is part of the soft delete (`AND "isDefault" = false`), not a read before it, so a project another admin makes a default mid-delete is still refused.
- Default projects only apply when a user is created; existing members are never backfilled or removed (see decision 000050). Only team projects of the same platform, and only on plans with `projectRolesEnabled`. On the server read them with `platformService.listDefaultProjectIds`; in the web, through `platformHooks.useNewMemberSettings()`, which applies the plan gate (`newMemberSettingsUtils.activeDefaultProjectIds`).
+- The personal projects switch lives on Roles & access, not the Projects page, and never depends on default projects. What guarantees a new Member a project is either their personal project or the invite: with personal projects off, the platform invite dialog requires a project for Members (see [User Invitations](./user-invitations.md)).
### Key files
Entry point: `projectService`, a log-taking factory in `project-service.ts` that every project read and write routes through.
diff --git a/brain/knowledge/platform-editions-ee/user-invitations.md b/brain/knowledge/platform-editions-ee/user-invitations.md
index 6301ffb8b20..88075bea9ed 100644
--- a/brain/knowledge/platform-editions-ee/user-invitations.md
+++ b/brain/knowledge/platform-editions-ee/user-invitations.md
@@ -23,6 +23,11 @@ Lets platform owners (and project members with `WRITE_INVITATION`) invite users
- **The "does this invite reserve a seat" rule has three implementations — change them together.** `countReservedInvites` (`platform-plan.service.ts`) expresses it as raw SQL (`status IN (PENDING, ACCEPTED)` + expiry cutoff + `NOT EXISTS` on an existing platform user); `wouldAddNewUser` re-checks the same membership condition in TypeScript; `countAdditionalSeatsNeeded` restates the same predicate in a third query builder. Editing one alone makes the counter and the guard disagree, which silently over- or under-counts seats.
- **Re-inviting a previously deleted user** works only because the CE/EE user delete also removes the now-orphaned `UserIdentity` (see [Users](./users.md)). The invitation itself always succeeds; when that cleanup has not run, the recipient's sign-up is what fails, with `EXISTING_USER`.
- **`POST /accept` answers with `registered`** — `true` when an identity already claims the invited email. The web accept page routes on exactly that field: falsy sends the recipient to `/sign-up`, `true` to `/sign-in`. The route has to spread it onto the invitation explicitly; while it was missing, every invitee landed on `/sign-up`, where an already-registered email dead-ends with `EXISTING_USER`.
+- **A platform invite can carry one project.** The PLATFORM row reuses the `projectId` and `projectRoleId` columns that used to be empty for platform invites, so it is still one row and one email. On accept, `provisionUserInvitation` sets the platform role, then adds the membership through `addToInvitedProject`; it runs after the default projects join, so the picked role wins over Editor. If the plan lost `projectRolesEnabled` before they accept, the project is skipped instead of failing the sign-in.
+- **A platform invite and a project invite for the same email and project never overwrite each other.** They share the unique index on `(email, platformId, projectId)`, so a plain upsert used to turn one into the other. `claimInvitedProject` settles it first: a project invite takes the project off the platform invite, and a platform invite deletes a pending project invite for that project, or drops its own project if an accepted project invite already covers it.
+- **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.
### Key files
Entry 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.json
index 43cde01c3ae..40b92d14838 100644
--- a/packages/core/shared/package.json
+++ b/packages/core/shared/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/shared",
- "version": "0.210.2",
+ "version": "0.210.3",
"type": "commonjs",
"sideEffects": false,
"main": "./dist/src/index.js",
diff --git a/packages/core/shared/src/lib/core/user/user.ts b/packages/core/shared/src/lib/core/user/user.ts
index bef78dbc5e7..8016afe7209 100755
--- a/packages/core/shared/src/lib/core/user/user.ts
+++ b/packages/core/shared/src/lib/core/user/user.ts
@@ -55,6 +55,7 @@ export const UserWithMetaInformation = z.object({
updated: DateOrString,
lastActiveDate: Nullable(DateOrString),
imageUrl: Nullable(z.string()),
+ hasProjects: z.boolean().optional(),
})
export type UserWithMetaInformation = z.infer<typeof UserWithMetaInformation>
diff --git a/packages/core/shared/src/lib/management/invitations/index.ts b/packages/core/shared/src/lib/management/invitations/index.ts
index c9dd5f62fd7..490e73d8579 100644
--- a/packages/core/shared/src/lib/management/invitations/index.ts
+++ b/packages/core/shared/src/lib/management/invitations/index.ts
@@ -43,6 +43,8 @@ export const SendUserInvitationRequest = z.union([
type: z.literal(InvitationType.PLATFORM),
email: z.string(),
platformRole: z.nativeEnum(PlatformRole),
+ projectId: z.string().optional(),
+ projectRole: z.string().optional(),
}),
])
diff --git a/packages/core/shared/src/lib/management/project/project.ts b/packages/core/shared/src/lib/management/project/project.ts
index 566dad704d0..e21b1528af0 100755
--- a/packages/core/shared/src/lib/management/project/project.ts
+++ b/packages/core/shared/src/lib/management/project/project.ts
@@ -90,6 +90,7 @@ export const ProjectMetaData = z.object({
export type ProjectMetaData = z.infer<typeof ProjectMetaData>
export const ProjectWithLimitsWithPlatform = z.object({
+ platformId: z.string(),
platformName: z.string(),
projects: z.array(ProjectWithLimits),
})
diff --git a/packages/server/api/src/app/authentication/authentication.service.ts b/packages/server/api/src/app/authentication/authentication.service.ts
index f56dfdae9b2..7fc2d749352 100644
--- a/packages/server/api/src/app/authentication/authentication.service.ts
+++ b/packages/server/api/src/app/authentication/authentication.service.ts
@@ -135,11 +135,11 @@ export const authenticationService = (log: FastifyBaseLogger) => ({
if (system.getEdition() !== ApEdition.CLOUD) {
return null
}
- const platforms = await platformService(log).listPlatformsForIdentityWithAtleastProject({ identityId })
+ const memberships = await platformService(log).listPlatformMembershipsForIdentity({ identityId })
const identity = await userIdentityService(log).getOneOrFail({ id: identityId })
- const lastUsed = !isNil(identity.lastLoggedInPlatformId) ? platforms.find((p) => p.id === identity.lastLoggedInPlatformId) : undefined
- const licensed = platforms.find((p) => !isNil(p.plan.licenseKey))
- return lastUsed?.id ?? licensed?.id ?? platforms[0]?.id ?? null
+ const lastUsed = memberships.find((membership) => membership.platform.id === identity.lastLoggedInPlatformId)
+ const withProjects = memberships.find((membership) => membership.hasProjects)
+ return (lastUsed ?? withProjects ?? memberships[0])?.platform.id ?? null
},
async federatedAuthn(params: FederatedAuthnParams): Promise<AuthenticationResult> {
const platformId = isNil(params.predefinedPlatformId) ? await selectCloudSignInPlatformIdByEmail({ email: params.email, log }) : params.predefinedPlatformId
@@ -195,7 +195,7 @@ export const authenticationService = (log: FastifyBaseLogger) => ({
return { response, signedUp: created }
},
async switchPlatform(params: SwitchPlatformParams): Promise<AuthenticationResponse> {
- const platforms = await platformService(log).listPlatformsForIdentityWithAtleastProject({ identityId: params.identityId })
+ const platforms = await platformService(log).listPlatformsForIdentity({ identityId: params.identityId })
const platform = platforms.find((platform) => platform.id === params.platformId)
await assertUserCanSwitchToPlatform(platform)
@@ -297,6 +297,7 @@ function refusedSignUpError({ email, provider }: SignUpParams): ActivepiecesErro
})
}
+
type SelectCloudSignInPlatformIdParams = {
identityId: string
}
diff --git a/packages/server/api/src/app/ee/platform/platform-list-controller.ts b/packages/server/api/src/app/ee/platform/platform-list-controller.ts
index 821ffc17f71..5959c3234bc 100644
--- a/packages/server/api/src/app/ee/platform/platform-list-controller.ts
+++ b/packages/server/api/src/app/ee/platform/platform-list-controller.ts
@@ -1,6 +1,5 @@
import { assertNotNullOrUndefined } from '@activepieces/core-utils'
import { PrincipalType, ProjectWithLimitsWithPlatform } from '@activepieces/shared'
-import { FastifyBaseLogger } from 'fastify'
import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'
import { StatusCodes } from 'http-status-codes'
import { z } from 'zod'
@@ -14,7 +13,7 @@ export const platformListController: FastifyPluginAsyncZod = async (app) => {
app.get('/', ListProjectsForPlatforms, async (request) => {
const loggedInUser = await userService(request.log).getOneOrFail({ id: request.principal.id })
- const platforms = await getPlatformsForUser(loggedInUser.identityId, request.log)
+ const platforms = await platformService(request.log).listPlatformsForIdentity({ identityId: loggedInUser.identityId })
const projects = await Promise.all(platforms.map(async (platform) => {
const platformUser = await userService(request.log).getOneByIdentityAndPlatform({ identityId: loggedInUser.identityId, platformId: platform.id })
assertNotNullOrUndefined(platformUser, `Platform user not found for platform ${platform.id}`)
@@ -27,6 +26,7 @@ export const platformListController: FastifyPluginAsyncZod = async (app) => {
isPrivileged: userService(request.log).isUserPrivileged(platformUser),
}).then((projects) => projects.data)
return {
+ platformId: platform.id,
platformName: platform.name,
projects,
}
@@ -35,10 +35,6 @@ export const platformListController: FastifyPluginAsyncZod = async (app) => {
})
}
-async function getPlatformsForUser(identityId: string, log: FastifyBaseLogger) {
- return platformService(log).listPlatformsForIdentityWithAtleastProject({ identityId })
-}
-
const ListProjectsForPlatforms = {
config: {
security: securityAccess.publicPlatform([PrincipalType.USER]),
diff --git a/packages/server/api/src/app/ee/projects/platform-project-jobs.ts b/packages/server/api/src/app/ee/projects/platform-project-jobs.ts
index 8505efd44e4..566f915db34 100644
--- a/packages/server/api/src/app/ee/projects/platform-project-jobs.ts
+++ b/packages/server/api/src/app/ee/projects/platform-project-jobs.ts
@@ -12,6 +12,7 @@ import { flowRepo } from '../../flows/flow/flow.repo'
import { SystemJobData, SystemJobName } from '../../helper/system-jobs/common'
import { systemJobsSchedule } from '../../helper/system-jobs/system-job'
import { ProjectEntity } from '../../project/project-entity'
+import { userInvitationsService } from '../../user-invitations/user-invitation.service'
import { deleteProjectLinkedEntities } from '../platform/platform-teardown-jobs'
const projectRepo = repoFactory(ProjectEntity)
@@ -56,6 +57,7 @@ export const platformProjectBackgroundJobs = (log: FastifyBaseLogger) => ({
scope: AppConnectionScope.PROJECT,
projectIds: ArrayContains([projectId]),
})
+ await userInvitationsService(log).detachProjectFromPlatformInvites({ projectId, entityManager })
await projectRepo(entityManager).delete({
id: projectId,
platformId,
diff --git a/packages/server/api/src/app/ee/projects/project-members/project-member.service.ts b/packages/server/api/src/app/ee/projects/project-members/project-member.service.ts
index af4c0a6ee66..f6cd05ac29b 100644
--- a/packages/server/api/src/app/ee/projects/project-members/project-member.service.ts
+++ b/packages/server/api/src/app/ee/projects/project-members/project-member.service.ts
@@ -24,9 +24,10 @@ export const projectMemberService = (log: FastifyBaseLogger) => ({
userId,
projectId,
projectRoleName,
+ entityManager,
}: UpsertParams): Promise<ProjectMember> {
const { platformId } = await projectService(log).getOneOrThrow(projectId)
- const existingProjectMember = await repo().findOneBy({
+ const existingProjectMember = await repo(entityManager).findOneBy({
projectId,
userId,
platformId,
@@ -47,13 +48,13 @@ export const projectMemberService = (log: FastifyBaseLogger) => ({
projectRoleId: projectRole.id,
}
- await repo().upsert(projectMember, [
+ await repo(entityManager).upsert(projectMember, [
'projectId',
'userId',
'platformId',
])
- return repo().findOneOrFail({
+ return repo(entityManager).findOneOrFail({
where: {
id: projectMemberId,
},
@@ -292,6 +293,7 @@ type UpsertParams = {
userId: string
projectId: ProjectId
projectRoleName: string
+ entityManager?: EntityManager
}
type AddToTeamProjectsParams = {
diff --git a/packages/server/api/src/app/ee/projects/project-role/project-role.controller.ts b/packages/server/api/src/app/ee/projects/project-role/project-role.controller.ts
index 8900b61e291..ce663437abd 100644
--- a/packages/server/api/src/app/ee/projects/project-role/project-role.controller.ts
+++ b/packages/server/api/src/app/ee/projects/project-role/project-role.controller.ts
@@ -1,10 +1,12 @@
-import { ApId, ProjectRole, SeekPage } from '@activepieces/core-utils'
+import { ApId, ProjectRole, RoleType, SeekPage } from '@activepieces/core-utils'
import { ApplicationEventName, CreateProjectRoleRequestBody, ListProjectMembersForProjectRoleRequestQuery, PrincipalType, ProjectMemberWithUser, SERVICE_KEY_SECURITY_OPENAPI, UpdateProjectRoleRequestBody } from '@activepieces/shared'
import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'
import { StatusCodes } from 'http-status-codes'
import { z } from 'zod'
+import { transaction } from '../../../core/db/transaction'
import { securityAccess } from '../../../core/security/authorization/fastify-security'
import { applicationEvents } from '../../../helper/application-events'
+import { userInvitationsService } from '../../../user-invitations/user-invitation.service'
import { platformMustHaveFeatureEnabled } from '../../authentication/ee-authorization'
import { projectMemberService } from '../project-members/project-member.service'
import { projectRoleService } from './project-role.service'
@@ -71,15 +73,22 @@ export const projectRoleController: FastifyPluginAsyncZod = async (app) => {
name: req.params.name,
platformId: req.principal.platform.id,
})
+ if (projectRole.type === RoleType.DEFAULT) {
+ return
+ }
applicationEvents(req.log).sendUserEvent(req, {
action: ApplicationEventName.PROJECT_ROLE_DELETED,
data: {
projectRole,
},
})
- return projectRoleService.delete({
- name: req.params.name,
- platformId: req.principal.platform.id,
+ await transaction(async (entityManager) => {
+ await userInvitationsService(req.log).detachProjectRoleFromPlatformInvites({ projectRoleId: projectRole.id, entityManager })
+ await projectRoleService.delete({
+ name: projectRole.name,
+ platformId: req.principal.platform.id,
+ entityManager,
+ })
})
})
}
diff --git a/packages/server/api/src/app/ee/projects/project-role/project-role.service.ts b/packages/server/api/src/app/ee/projects/project-role/project-role.service.ts
index f505fcabe20..c27be18e564 100644
--- a/packages/server/api/src/app/ee/projects/project-role/project-role.service.ts
+++ b/packages/server/api/src/app/ee/projects/project-role/project-role.service.ts
@@ -110,8 +110,8 @@ export const projectRoleService = {
return projectRoleRepo().findOneByOrFail({ id: params.id, platformId: params.platformId })
},
- async delete({ name, platformId }: DeleteParams): Promise<void> {
- await projectRoleRepo().delete({ name, platformId })
+ async delete({ name, platformId, entityManager }: DeleteParams): Promise<void> {
+ await projectRoleRepo(entityManager).delete({ name, platformId })
},
}
@@ -148,6 +148,7 @@ type ListParams = {
type DeleteParams = {
name: ApId
platformId: PlatformId
+ entityManager?: EntityManager
}
type GetOneByNameParams = {
diff --git a/packages/server/api/src/app/platform/platform.service.ts b/packages/server/api/src/app/platform/platform.service.ts
index bcd8d079426..7d002d6447c 100644
--- a/packages/server/api/src/app/platform/platform.service.ts
+++ b/packages/server/api/src/app/platform/platform.service.ts
@@ -1,4 +1,4 @@
-import { ActivepiecesError, apId, ErrorCode, isNil, PlatformId, spreadIfDefined, spreadIfNotUndefined, tryCatch, UserId } from '@activepieces/core-utils'
+import { ActivepiecesError, apId, ErrorCode, isNil, partition, PlatformId, spreadIfDefined, spreadIfNotUndefined, tryCatch, UserId } from '@activepieces/core-utils'
import { ApEdition, AUDIT_LOG_RETENTION_MAX_DAYS, AUDIT_LOG_RETENTION_MIN_DAYS, AuthenticationResponse, OPEN_SOURCE_PLAN, Platform, PlatformPlanLimits, PlatformResponse, PlatformRole, PlatformUsage, PlatformWithoutFederatedAuth, PlatformWithoutSensitiveData, ProjectType, SsoDomainVerification, SsoDomainVerificationStatus, UpdatePlatformRequestBody, User, UserStatus } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
import { nanoid } from 'nanoid'
@@ -31,23 +31,25 @@ export const platformRepo = repoFactory<Platform>(PlatformEntity)
const DEFAULT_PROJECT_IDS_PAGE_SIZE = 100
export const platformService = (log: FastifyBaseLogger) => ({
- async listPlatformsForIdentityWithAtleastProject(params: ListPlatformsForIdentityParams): Promise<PlatformWithoutSensitiveData[]> {
+ async listPlatformsForIdentity(params: ListPlatformsForIdentityParams): Promise<PlatformWithoutSensitiveData[]> {
+ const memberships = await this.listPlatformMembershipsForIdentity(params)
+ return memberships.map((membership) => membership.platform)
+ },
+ async listPlatformMembershipsForIdentity(params: ListPlatformsForIdentityParams): Promise<PlatformMembershipWithPlatform[]> {
const users = await userService(log).getByIdentityId({ identityId: params.identityId })
-
- const platformsWithProjects = await Promise.all(users.map(async (user) => {
- if (isNil(user.platformId) || user.status === UserStatus.INACTIVE) {
- return null
- }
- const hasProjects = await projectService(log).userHasProjects({
- platformId: user.platformId,
- userId: user.id,
- isPrivileged: userService(log).isUserPrivileged(user),
- })
- return hasProjects ? user.platformId : null
+ const activeUsers = users.flatMap((user) => isNil(user.platformId) || user.status === UserStatus.INACTIVE
+ ? []
+ : [{ userId: user.id, platformId: user.platformId, isPrivileged: userService(log).isUserPrivileged(user) }])
+ const platformIdsWithProjects = new Set(await projectService(log).listPlatformIdsWhereUsersHaveProjects({ users: activeUsers }))
+ const memberships: PlatformMembership[] = activeUsers.map((user) => ({
+ platformId: user.platformId,
+ hasProjects: platformIdsWithProjects.has(user.platformId),
}))
-
- const platforms = await Promise.all(platformsWithProjects.filter((platformId) => !isNil(platformId)).map((platformId) => this.getOneWithPlanOrThrow(platformId)))
- return platforms
+ const [withProjects, withoutProjects] = partition(memberships, (membership) => membership.hasProjects)
+ return Promise.all([...withProjects, ...withoutProjects].map(async (membership) => ({
+ platform: await this.getOneWithPlanOrThrow(membership.platformId),
+ hasProjects: membership.hasProjects,
+ })))
},
async create(params: AddParams): Promise<PlatformWithoutFederatedAuth> {
const {
@@ -544,6 +546,16 @@ type LockPlatformForUpdateParams = {
includeFederatedAuth: boolean
}
+type PlatformMembership = {
+ platformId: PlatformId
+ hasProjects: boolean
+}
+
+type PlatformMembershipWithPlatform = {
+ platform: PlatformWithoutSensitiveData
+ hasProjects: boolean
+}
+
type ListDefaultProjectIdsParams = {
platformId: PlatformId
entityManager?: EntityManager
diff --git a/packages/server/api/src/app/project/project-service.ts b/packages/server/api/src/app/project/project-service.ts
index a4f1e02010f..16e378b51b0 100644
--- a/packages/server/api/src/app/project/project-service.ts
+++ b/packages/server/api/src/app/project/project-service.ts
@@ -1,4 +1,4 @@
-import { ActivepiecesError, ApId, apId, assertNotNullOrUndefined, ErrorCode, isNil, Metadata, ProjectId, spreadIfDefined, spreadIfNotUndefined, UserId } from '@activepieces/core-utils'
+import { ActivepiecesError, ApId, apId, assertNotNullOrUndefined, ErrorCode, isNil, Metadata, ProjectId, spreadIfDefined, spreadIfNotUndefined, unique, UserId } from '@activepieces/core-utils'
import { ColorName, Project, ProjectIcon, ProjectType } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
import { Brackets, EntityManager, IsNull, Not, ObjectLiteral, SelectQueryBuilder } from 'typeorm'
@@ -177,6 +177,49 @@ export const projectService = (log: FastifyBaseLogger) => ({
return queryBuilder.getExists()
},
+ async listUserIdsWithProjects({ platformId, userIds }: ListUserIdsWithProjectsParams): Promise<string[]> {
+ if (userIds.length === 0) {
+ return []
+ }
+ const [owners, members] = await Promise.all([
+ projectRepo()
+ .createQueryBuilder('project')
+ .select('project."ownerId"', 'userId')
+ .where('project."platformId" = :platformId', { platformId })
+ .andWhere('project.type = :personalType', { personalType: ProjectType.PERSONAL })
+ .andWhere('project."ownerId" IN (:...userIds)', { userIds })
+ .getRawMany<{ userId: string }>(),
+ projectRepo()
+ .createQueryBuilder('project')
+ .innerJoin('project_member', 'project_member', 'project_member."projectId" = project.id')
+ .select('project_member."userId"', 'userId')
+ .where('project."platformId" = :platformId', { platformId })
+ .andWhere('project_member."userId" IN (:...userIds)', { userIds })
+ .getRawMany<{ userId: string }>(),
+ ])
+ return unique([...owners, ...members].map((row) => row.userId))
+ },
+ async listPlatformIdsWhereUsersHaveProjects({ users }: ListPlatformIdsWhereUsersHaveProjectsParams): Promise<string[]> {
+ const privilegedPlatformIds = users.filter((user) => user.isPrivileged).map((user) => user.platformId)
+ const memberUserIds = users.filter((user) => !user.isPrivileged).map((user) => user.userId)
+ if (privilegedPlatformIds.length === 0 && memberUserIds.length === 0) {
+ return []
+ }
+ const rows = await projectRepo()
+ .createQueryBuilder('project')
+ .select('DISTINCT project."platformId"', 'platformId')
+ .where(new Brackets((qb) => {
+ if (privilegedPlatformIds.length > 0) {
+ qb.orWhere('project."platformId" IN (:...privilegedPlatformIds)', { privilegedPlatformIds })
+ }
+ if (memberUserIds.length > 0) {
+ qb.orWhere('(project."ownerId" IN (:...memberUserIds) AND project.type = :personalType)', { memberUserIds, personalType: ProjectType.PERSONAL })
+ qb.orWhere('project.id IN (SELECT "projectId" FROM project_member WHERE "userId" IN (:...memberUserIds))', { memberUserIds })
+ }
+ }))
+ .getRawMany<{ platformId: string }>()
+ return rows.map((row) => row.platformId)
+ },
async addProjectToPlatform({ projectId, platformId }: AddProjectToPlatformParams): Promise<void> {
const query = {
id: projectId,
@@ -329,6 +372,19 @@ type GetByPlatformIdAndExternalIdParams = {
externalId: string
}
+type ListPlatformIdsWhereUsersHaveProjectsParams = {
+ users: {
+ userId: string
+ platformId: string
+ isPrivileged: boolean
+ }[]
+}
+
+type ListUserIdsWithProjectsParams = {
+ platformId: string
+ userIds: UserId[]
+}
+
type AddProjectToPlatformParams = {
projectId: ProjectId
platformId: ApId
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.ts
index fec93c87f7e..74c953e475c 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, Principal, PrincipalType, SendUserInvitationRequest, SERVICE_KEY_SECURITY_OPENAPI, TelemetryEvent, TelemetryEventName, UserInvitation, UserInvitationWithLink } from '@activepieces/shared'
+import { InvitationStatus, InvitationType, ListUserInvitationsRequest, PlatformRole, Principal, PrincipalType, ProjectType, 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'
@@ -33,6 +33,7 @@ const invitationController: FastifyPluginAsyncZod = async (app) => {
break
case InvitationType.PLATFORM:
await platformMustBeOwnedByCurrentUser.call(app, request, reply)
+ await assertPlatformInviteProject({ app, request, reply, invitation: request.body, platformId: request.principal.platform.id })
break
}
const platformId = request.principal.platform.id
@@ -44,23 +45,23 @@ const invitationController: FastifyPluginAsyncZod = async (app) => {
type,
platformId,
platformRole: type === InvitationType.PROJECT ? null : request.body.platformRole,
- projectId: type === InvitationType.PLATFORM ? null : request.body.projectId,
- projectRoleId: type === InvitationType.PLATFORM ? null : projectRole?.id ?? null,
+ projectId: request.body.projectId ?? null,
+ projectRoleId: projectRole?.id ?? null,
status,
}
const wouldAddNewUser = await userInvitationsService(request.log).wouldAddNewUser({ email, platformId })
- const userInvitationRecord = wouldAddNewUser
- ? await transaction(async (entityManager) => {
+ const userInvitationRecord = await 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 userInvitationsService(request.log).createInvitationRecord(invitationRecordParams)
+ }
+ return userInvitationsService(request.log).createInvitationRecord({ ...invitationRecordParams, entityManager })
+ })
const invitation = await userInvitationsService(request.log).finalizeInvitation({
userInvitation: userInvitationRecord,
@@ -104,6 +105,7 @@ const invitationController: FastifyPluginAsyncZod = async (app) => {
invitationId: invitation.id,
platformId: invitation.platformId,
})
+ await landNextSignInOnInvitedPlatform({ email: invitation.email, platformId: invitation.platformId, log: request.log })
await reply.status(StatusCodes.OK).send({ ...invitation, registered })
})
@@ -132,11 +134,10 @@ const invitationController: FastifyPluginAsyncZod = async (app) => {
const getProjectRoleAndAssertIfFound = async (platformId: string, request: SendUserInvitationRequest): Promise<ProjectRole | null> => {
- const { type } = request
- if (type === InvitationType.PLATFORM) {
+ const projectRoleName = request.projectRole
+ if (isNil(projectRoleName)) {
return null
}
- const projectRoleName = request.projectRole
const projectRole = await projectRoleService.getOneOrThrow({
name: projectRoleName,
@@ -144,6 +145,46 @@ const getProjectRoleAndAssertIfFound = async (platformId: string, request: SendU
})
return projectRole
}
+async function landNextSignInOnInvitedPlatform({ email, platformId, log }: LandNextSignInOnInvitedPlatformParams): Promise<void> {
+ const identity = await userIdentityService(log).getIdentityByEmail(email)
+ if (isNil(identity)) {
+ return
+ }
+ await userIdentityService(log).updateLastLoggedInPlatformId({ id: identity.id, lastLoggedInPlatformId: platformId })
+}
+
+async function assertPlatformInviteProject({ app, request, reply, invitation, platformId }: AssertPlatformInviteProjectParams): Promise<void> {
+ if (invitation.type !== InvitationType.PLATFORM || (isNil(invitation.projectId) && isNil(invitation.projectRole))) {
+ return
+ }
+ if (isNil(invitation.projectId) || isNil(invitation.projectRole)) {
+ throw new ActivepiecesError({
+ code: ErrorCode.VALIDATION,
+ params: {
+ message: 'projectId and projectRole must be sent together',
+ },
+ })
+ }
+ if (invitation.platformRole !== PlatformRole.MEMBER) {
+ throw new ActivepiecesError({
+ code: ErrorCode.VALIDATION,
+ params: {
+ message: 'Only a Member invite can name a project',
+ },
+ })
+ }
+ await platformMustHaveFeatureEnabled((platform) => platform.plan.projectRolesEnabled).call(app, request, reply)
+ const project = await projectService(request.log).getOne(invitation.projectId)
+ if (isNil(project) || project.platformId !== platformId || project.type !== ProjectType.TEAM) {
+ throw new ActivepiecesError({
+ code: ErrorCode.VALIDATION,
+ params: {
+ message: 'The project must be a team project of this platform',
+ },
+ })
+ }
+}
+
async function getProjectIdAndAssertPermission<R extends Principal>(
app: FastifyInstance,
request: FastifyRequest,
@@ -269,6 +310,20 @@ const UpsertUserInvitationRequestParams = {
},
}
+type LandNextSignInOnInvitedPlatformParams = {
+ email: string
+ platformId: string
+ log: FastifyBaseLogger
+}
+
+type AssertPlatformInviteProjectParams = {
+ app: FastifyInstance
+ request: FastifyRequest
+ reply: FastifyReply
+ invitation: SendUserInvitationRequest
+ platformId: string
+}
+
type TrackInviteSentParams = {
principal: Principal
platformId: string
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.ts
index 53af90346c5..9c55fbe50cb 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,14 +1,14 @@
-import { ActivepiecesError, apId, assertEqual, assertNotNullOrUndefined, ErrorCode, isNil, SeekPage, spreadIfDefined } from '@activepieces/core-utils'
+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 dayjs from 'dayjs'
import { FastifyBaseLogger } from 'fastify'
-import { EntityManager, IsNull, ObjectLiteral, SelectQueryBuilder } from 'typeorm'
+import { EntityManager, In, IsNull, ObjectLiteral, SelectQueryBuilder } from 'typeorm'
import { userIdentityService } from '../authentication/user-identity/user-identity-service'
import { repoFactory } from '../core/db/repo-factory'
import { smtpEmailSender } from '../ee/helper/email/email-sender/smtp-email-sender'
import { emailService } from '../ee/helper/email/email-service'
import { projectMemberService } from '../ee/projects/project-members/project-member.service'
-import { projectRoleService } from '../ee/projects/project-role/project-role.service'
+import { projectRoleRepo, projectRoleService } from '../ee/projects/project-role/project-role.service'
import { domainHelper } from '../helper/domain-helper'
import { JwtAudience, jwtUtils } from '../helper/jwt-utils'
import { buildPaginator } from '../helper/pagination/build-paginator'
@@ -16,12 +16,13 @@ import { paginationHelper } from '../helper/pagination/pagination-utils'
import { rejectedPromiseHandler } from '../helper/promise-handler'
import { telemetry } from '../helper/telemetry.utils'
import { platformService } from '../platform/platform.service'
-import { projectService } from '../project/project-service'
+import { ProjectEntity } from '../project/project-entity'
import { userService } from '../user/user-service'
import { UserInvitationEntity } from './user-invitation.entity'
export const userInvitationRepo = repoFactory(UserInvitationEntity)
const repo = userInvitationRepo
+const projectRepo = repoFactory(ProjectEntity)
export const userInvitationsService = (log: FastifyBaseLogger) => ({
async getOneByInvitationTokenOrThrow(invitationToken: string): Promise<UserInvitation> {
@@ -58,6 +59,7 @@ export const userInvitationsService = (log: FastifyBaseLogger) => ({
if (isNil(identity)) return
log.info({ count: invitations.length }, '[provisionUserInvitation] list invitations')
+ const context = await loadProvisioningContext({ invitations, log })
for (const invitation of invitations) {
log.info({ invitation }, '[provisionUserInvitation] provision')
const { user } = await userService(log).getOrCreateWithProject({
@@ -67,6 +69,9 @@ export const userInvitationsService = (log: FastifyBaseLogger) => ({
switch (invitation.type) {
case InvitationType.PLATFORM: {
assertNotNullOrUndefined(invitation.platformRole, 'platformRole')
+ if (!isNil(invitation.projectId) && !isNil(invitation.projectRoleId)) {
+ await addToInvitedProject({ invitation, userId: user.id, log, context, failsWithoutProjectRoles: false })
+ }
await userService(log).update({
id: user.id,
platformId: invitation.platformId,
@@ -75,27 +80,7 @@ export const userInvitationsService = (log: FastifyBaseLogger) => ({
break
}
case InvitationType.PROJECT: {
- const { projectId, projectRoleId } = invitation
- assertNotNullOrUndefined(projectId, 'projectId')
- assertNotNullOrUndefined(projectRoleId, 'projectRoleId')
- const platform = await platformService(log).getOneWithPlanOrThrow(invitation.platformId)
- assertEqual(platform.plan.projectRolesEnabled, true, 'Project roles are not enabled', 'PROJECT_ROLES_NOT_ENABLED')
-
- const projectRole = await projectRoleService.getOneOrThrowById({
- id: projectRoleId,
- })
-
- const project = await projectService(log).exists({
- projectId,
- isSoftDeleted: false,
- })
- if (!isNil(project)) {
- await projectMemberService(log).upsert({
- projectId,
- userId: user.id,
- projectRoleName: projectRole.name,
- })
- }
+ await addToInvitedProject({ invitation, userId: user.id, log, context, failsWithoutProjectRoles: true })
break
}
}
@@ -104,6 +89,12 @@ export const userInvitationsService = (log: FastifyBaseLogger) => ({
})
}
},
+ async detachProjectFromPlatformInvites({ projectId, entityManager }: DetachProjectFromPlatformInvitesParams): Promise<void> {
+ await repo(entityManager).update({ type: InvitationType.PLATFORM, projectId }, { projectId: null, projectRoleId: null })
+ },
+ async detachProjectRoleFromPlatformInvites({ projectRoleId, entityManager }: DetachProjectRoleFromPlatformInvitesParams): Promise<void> {
+ await repo(entityManager).update({ type: InvitationType.PLATFORM, projectRoleId }, { projectId: null, projectRoleId: null })
+ },
async createInvitationRecord({
email,
platformId,
@@ -114,16 +105,18 @@ export const userInvitationsService = (log: FastifyBaseLogger) => ({
status,
entityManager,
}: 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,
status,
type,
- email: email.toLowerCase().trim(),
+ email: normalizedEmail,
platformId,
- projectRoleId: type === InvitationType.PLATFORM ? undefined : projectRoleId!,
+ projectRoleId: invitedProject.keepsProject ? projectRoleId ?? undefined : undefined,
platformRole: type === InvitationType.PROJECT ? undefined : platformRole!,
- projectId: type === InvitationType.PLATFORM ? undefined : projectId!,
+ projectId: invitedProject.keepsProject ? projectId ?? undefined : undefined,
}, ['email', 'platformId', 'projectId'])
return this.getOneOrThrow({
@@ -336,6 +329,77 @@ const EMAIL_IS_NOT_ALREADY_A_PLATFORM_USER = `NOT EXISTS (
WHERE LOWER(identity.email) = LOWER(invitation.email)
)`
+
+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)))
+ const projectIds = unique(withProject.map((invitation) => invitation.projectId).filter((id): id is string => !isNil(id)))
+ const platformIds = unique(withProject.map((invitation) => invitation.platformId))
+ const [projectRoles, liveProjects, platforms] = await Promise.all([
+ projectRoleIds.length === 0 ? [] : projectRoleRepo().findBy([
+ { id: In(projectRoleIds), platformId: In(platformIds) },
+ { id: In(projectRoleIds), type: RoleType.DEFAULT },
+ ]),
+ projectIds.length === 0 ? [] : projectRepo().findBy({ id: In(projectIds), platformId: In(platformIds) }),
+ Promise.all(platformIds.map((platformId) => platformService(log).getOneWithPlanOrThrow(platformId))),
+ ])
+ return {
+ projectRoleById: new Map(projectRoles.map((projectRole) => [projectRole.id, projectRole])),
+ liveProjectPlatformIdById: new Map(liveProjects.map((project) => [project.id, project.platformId])),
+ projectRolesEnabledByPlatformId: new Map(platforms.map((platform) => [platform.id, platform.plan.projectRolesEnabled])),
+ }
+}
+
+async function addToInvitedProject({ invitation, userId, log, context, failsWithoutProjectRoles }: AddToInvitedProjectParams): Promise<void> {
+ const { projectId, projectRoleId } = invitation
+ assertNotNullOrUndefined(projectId, 'projectId')
+ assertNotNullOrUndefined(projectRoleId, 'projectRoleId')
+ const projectRolesEnabled = context.projectRolesEnabledByPlatformId.get(invitation.platformId) === true
+ if (!projectRolesEnabled && !failsWithoutProjectRoles) {
+ return
+ }
+ assertEqual(projectRolesEnabled, true, 'Project roles are not enabled', 'PROJECT_ROLES_NOT_ENABLED')
+ const projectRole = context.projectRoleById.get(projectRoleId)
+ if (isNil(projectRole) || !isRoleOfPlatform({ projectRole, platformId: invitation.platformId })) {
+ throw new ActivepiecesError({
+ code: ErrorCode.ENTITY_NOT_FOUND,
+ params: { entityType: 'project_role', entityId: projectRoleId },
+ })
+ }
+ if (context.liveProjectPlatformIdById.get(projectId) !== invitation.platformId) {
+ return
+ }
+ await projectMemberService(log).upsert({
+ projectId,
+ userId,
+ projectRoleName: projectRole.name,
+ })
+}
+
+function isRoleOfPlatform({ projectRole, platformId }: { projectRole: ProjectRole, platformId: string }): boolean {
+ return projectRole.type === RoleType.DEFAULT || projectRole.platformId === platformId
+}
+
+async function claimInvitedProject({ email, platformId, projectId, type, entityManager }: ClaimInvitedProjectParams): Promise<{ keepsProject: boolean }> {
+ if (isNil(projectId)) {
+ return { keepsProject: true }
+ }
+ switch (type) {
+ case InvitationType.PROJECT: {
+ await repo(entityManager).update(
+ { type: InvitationType.PLATFORM, email, platformId, projectId },
+ { projectId: null, projectRoleId: null },
+ )
+ return { keepsProject: true }
+ }
+ case InvitationType.PLATFORM: {
+ await repo(entityManager).delete({ type: InvitationType.PROJECT, email, platformId, projectId, status: InvitationStatus.PENDING })
+ const coveredByAcceptedProjectInvite = await repo(entityManager).existsBy({ type: InvitationType.PROJECT, email, platformId, projectId })
+ return { keepsProject: !coveredByAcceptedProjectInvite }
+ }
+ }
+}
+
async function generateInvitationLink(userInvitation: UserInvitation, expireyInSeconds: number): Promise<string> {
const token = await jwtUtils.sign({
payload: {
@@ -364,6 +428,35 @@ const enrichWithInvitationLink = async (userInvitation: UserInvitation, expireyI
})
return userInvitation
}
+type DetachProjectFromPlatformInvitesParams = {
+ projectId: string
+ entityManager: EntityManager
+}
+
+type DetachProjectRoleFromPlatformInvitesParams = {
+ projectRoleId: string
+ entityManager: EntityManager
+}
+
+type LoadProvisioningContextParams = {
+ invitations: UserInvitation[]
+ log: FastifyBaseLogger
+}
+
+type ProvisioningContext = {
+ projectRoleById: Map<string, ProjectRole>
+ liveProjectPlatformIdById: Map<string, string>
+ projectRolesEnabledByPlatformId: Map<string, boolean>
+}
+
+type AddToInvitedProjectParams = {
+ invitation: UserInvitation
+ userId: string
+ log: FastifyBaseLogger
+ context: ProvisioningContext
+ failsWithoutProjectRoles: boolean
+}
+
type ListUserParams = {
platformId: string
type: InvitationType
@@ -442,3 +535,11 @@ type GetAcceptedAdminOrOperatorInviteRoleParams = {
platformId: string
entityManager?: EntityManager
}
+
+type ClaimInvitedProjectParams = {
+ email: string
+ platformId: string
+ projectId: string | null
+ type: InvitationType
+ entityManager?: EntityManager
+}
diff --git a/packages/server/api/src/app/user/user-service.ts b/packages/server/api/src/app/user/user-service.ts
index e67a3ce9739..d2b9a88b6d4 100644
--- a/packages/server/api/src/app/user/user-service.ts
+++ b/packages/server/api/src/app/user/user-service.ts
@@ -147,8 +147,14 @@ export const userService = (log: FastifyBaseLogger) => ({
...spreadIfDefined('externalId', externalId),
}))
- const usersWithMetaInformation = await Promise.all(data.map(this.getMetaInformation))
- return paginationHelper.createPage<UserWithMetaInformation>(usersWithMetaInformation, cursor)
+ const [usersWithMetaInformation, userIdsWithProjects] = await Promise.all([
+ Promise.all(data.map(this.getMetaInformation)),
+ projectService(log).listUserIdsWithProjects({ platformId, userIds: data.map((user) => user.id) }),
+ ])
+ return paginationHelper.createPage<UserWithMetaInformation>(usersWithMetaInformation.map((user) => ({
+ ...user,
+ hasProjects: userIdsWithProjects.includes(user.id),
+ })), cursor)
},
async getByIdentityId({ identityId }: GetByIdentityId): Promise<UserSchema[]> {
return userRepo().find({ where: { identityId } })
diff --git a/packages/server/api/test/integration/cloud/authn/sign-in-without-a-project.test.ts b/packages/server/api/test/integration/cloud/authn/sign-in-without-a-project.test.ts
new file mode 100644
index 00000000000..7efd5809980
--- /dev/null
+++ b/packages/server/api/test/integration/cloud/authn/sign-in-without-a-project.test.ts
@@ -0,0 +1,93 @@
+import { DefaultProjectRole, InvitationType, PlatformRole, PrincipalType, ProjectType } from '@activepieces/shared'
+import { FastifyBaseLogger, FastifyInstance } from 'fastify'
+import { StatusCodes } from 'http-status-codes'
+import { authenticationService } from '../../../../src/app/authentication/authentication.service'
+import { userService } from '../../../../src/app/user/user-service'
+import { generateMockToken } from '../../../helpers/auth'
+import { db } from '../../../helpers/db'
+import { createMockUserIdentity, mockAndSaveBasicSetup } from '../../../helpers/mocks'
+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'
+
+let app: FastifyInstance | null = null
+let mockLog: FastifyBaseLogger
+
+beforeAll(async () => {
+ app = await setupTestEnvironment()
+ mockLog = app!.log!
+})
+
+afterAll(async () => {
+ await teardownTestEnvironment()
+})
+
+describe('Cloud sign-in for someone with no project', () => {
+ it('lands them on their platform instead of none', async () => {
+ const platformId = await platformWithoutPersonalProjects()
+ const identityId = await joinPlatforms({ platformIds: [platformId] })
+
+ const picked = await authenticationService(mockLog).selectCloudSignInPlatformId({ identityId })
+
+ expect(picked).toBe(platformId)
+ })
+
+ it('prefers a platform where they have a project when none was used last', async () => {
+ const emptyPlatformId = await platformWithoutPersonalProjects()
+ const { mockPlatform: busyPlatform } = await mockAndSaveBasicSetup({ plan: { projectRolesEnabled: true }, project: { type: ProjectType.TEAM } })
+ const identityId = await joinPlatforms({ platformIds: [emptyPlatformId, busyPlatform.id] })
+
+ const picked = await authenticationService(mockLog).selectCloudSignInPlatformId({ identityId })
+
+ expect(picked).toBe(busyPlatform.id)
+ })
+
+ it('keeps the last-used platform even when they have no project there', async () => {
+ const emptyPlatformId = await platformWithoutPersonalProjects()
+ const { mockPlatform: busyPlatform } = await mockAndSaveBasicSetup({ plan: { projectRolesEnabled: true }, project: { type: ProjectType.TEAM } })
+ const identityId = await joinPlatforms({ platformIds: [emptyPlatformId, busyPlatform.id] })
+ await db.update('user_identity', identityId, { lastLoggedInPlatformId: emptyPlatformId })
+
+ const picked = await authenticationService(mockLog).selectCloudSignInPlatformId({ identityId })
+
+ expect(picked).toBe(emptyPlatformId)
+ })
+})
+
+describe('Accepting an invite through its link', () => {
+ it('lands the next sign-in on the platform that invited them', async () => {
+ const { mockPlatform: homePlatform } = await mockAndSaveBasicSetup({ plan: { projectRolesEnabled: true }, project: { type: ProjectType.TEAM } })
+ const identity = createMockUserIdentity({ verified: true })
+ await db.save('user_identity', identity)
+ await userService(mockLog).getOrCreateWithProject({ identity, platformId: homePlatform.id })
+ await db.update('user_identity', identity.id, { lastLoggedInPlatformId: homePlatform.id })
+ const { mockPlatform: invitingPlatform, mockOwner, mockProject } = await mockAndSaveBasicSetup({ plan: { projectRolesEnabled: true }, project: { type: ProjectType.TEAM } })
+ const ownerToken = await generateMockToken({ id: mockOwner.id, type: PrincipalType.USER, platform: { id: invitingPlatform.id } })
+ const invite = await app?.inject({
+ method: 'POST',
+ url: '/api/v1/user-invitations',
+ headers: { authorization: `Bearer ${ownerToken}` },
+ body: { email: identity.email, type: InvitationType.PLATFORM, platformRole: PlatformRole.MEMBER, projectId: mockProject.id, projectRole: DefaultProjectRole.EDITOR },
+ })
+ const invitationToken = new URL(invite?.json().link).searchParams.get('token')
+
+ const accept = await app?.inject({ method: 'POST', url: '/api/v1/user-invitations/accept', body: { invitationToken } })
+
+ expect(accept?.statusCode).toBe(StatusCodes.OK)
+ const picked = await authenticationService(mockLog).selectCloudSignInPlatformId({ identityId: identity.id })
+ expect(picked).toBe(invitingPlatform.id)
+ })
+})
+
+async function platformWithoutPersonalProjects(): Promise<string> {
+ const { mockPlatform } = await mockAndSaveBasicSetup({ plan: { projectRolesEnabled: true }, project: { type: ProjectType.TEAM } })
+ await db.update('platform', mockPlatform.id, { autoCreatePersonalProjects: false })
+ return mockPlatform.id
+}
+
+async function joinPlatforms({ platformIds }: { platformIds: string[] }): Promise<string> {
+ const identity = createMockUserIdentity({ verified: true })
+ await db.save('user_identity', identity)
+ for (const platformId of platformIds) {
+ await userService(mockLog).getOrCreateWithProject({ identity, platformId })
+ }
+ return identity.id
+}
diff --git a/packages/server/api/test/integration/cloud/project-role/project-role-events.test.ts b/packages/server/api/test/integration/cloud/project-role/project-role-events.test.ts
index 76788dabd48..05a9b65b2e2 100644
--- a/packages/server/api/test/integration/cloud/project-role/project-role-events.test.ts
+++ b/packages/server/api/test/integration/cloud/project-role/project-role-events.test.ts
@@ -1,3 +1,4 @@
+import { RoleType } from '@activepieces/core-utils'
import { ApplicationEventName } from '@activepieces/shared'
import { faker } from '@faker-js/faker'
import { FastifyInstance } from 'fastify'
@@ -71,7 +72,7 @@ describe('Project role application events', () => {
it('emits PROJECT_ROLE_DELETED on DELETE /v1/project-roles/:name', async () => {
const ctx = await createTestContext(app)
- const projectRole = createMockProjectRole({ platformId: ctx.platform.id })
+ const projectRole = createMockProjectRole({ platformId: ctx.platform.id, type: RoleType.CUSTOM })
await db.save('project_role', projectRole)
const response = await ctx.delete(`/v1/project-roles/${projectRole.name}`)
diff --git a/packages/server/api/test/integration/ee/user-invitations/invite-existing-user-transaction.test.ts b/packages/server/api/test/integration/ee/user-invitations/invite-existing-user-transaction.test.ts
new file mode 100644
index 00000000000..774f810b3ba
--- /dev/null
+++ b/packages/server/api/test/integration/ee/user-invitations/invite-existing-user-transaction.test.ts
@@ -0,0 +1,61 @@
+import { apId } 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 { 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 someone who is already on the platform', () => {
+ it('leaves the platform invite with its project when the project invite fails', async () => {
+ const { mockPlatform, mockProject, mockOwner } = await mockAndSaveBasicSetup({ plan: { projectRolesEnabled: true }, project: { type: ProjectType.TEAM } })
+ const ownerToken = await generateMockToken({ id: mockOwner.id, type: PrincipalType.USER, platform: { id: mockPlatform.id } })
+ const email = faker.internet.email().toLowerCase()
+ await mockBasicUser({ userIdentity: { email }, user: { platformId: mockPlatform.id, platformRole: PlatformRole.MEMBER } })
+ const viewerRole = await databaseConnection().getRepository('project_role').findOneByOrFail({ name: DefaultProjectRole.VIEWER })
+ await databaseConnection().getRepository('user_invitation').save({
+ id: apId(),
+ email,
+ type: InvitationType.PLATFORM,
+ platformRole: PlatformRole.MEMBER,
+ platformId: mockPlatform.id,
+ projectId: mockProject.id,
+ projectRoleId: viewerRole.id,
+ status: InvitationStatus.PENDING,
+ })
+ const originalUpsert = Repository.prototype.upsert
+ const upsert = vi.spyOn(Repository.prototype, 'upsert').mockImplementation(function (this: Repository<ObjectLiteral>, ...args: Parameters<Repository<ObjectLiteral>['upsert']>) {
+ if (this.metadata.tableName === 'user_invitation') {
+ return Promise.reject(new Error('upsert failed'))
+ }
+ return originalUpsert.apply(this, args)
+ })
+
+ const response = await app?.inject({
+ method: 'POST',
+ url: '/api/v1/user-invitations',
+ headers: { authorization: `Bearer ${ownerToken}` },
+ body: { email, type: InvitationType.PROJECT, projectId: mockProject.id, projectRole: DefaultProjectRole.EDITOR },
+ })
+ upsert.mockRestore()
+
+ expect(response?.statusCode).toBe(StatusCodes.INTERNAL_SERVER_ERROR)
+ const invitations = await databaseConnection().getRepository('user_invitation').findBy({ email, platformId: mockPlatform.id })
+ expect(invitations.map((invitation) => ({ type: invitation.type, projectId: invitation.projectId }))).toStrictEqual([
+ { type: InvitationType.PLATFORM, projectId: mockProject.id },
+ ])
+ })
+})
diff --git a/packages/server/api/test/integration/ee/user-invitations/platform-invite-project.test.ts b/packages/server/api/test/integration/ee/user-invitations/platform-invite-project.test.ts
new file mode 100644
index 00000000000..879dcc88e1c
--- /dev/null
+++ b/packages/server/api/test/integration/ee/user-invitations/platform-invite-project.test.ts
@@ -0,0 +1,398 @@
+import { apId, ErrorCode, RoleType } from '@activepieces/core-utils'
+import { DefaultProjectRole, InvitationStatus, InvitationType, PlatformRole, PrincipalType, ProjectType } from '@activepieces/shared'
+import { faker } from '@faker-js/faker'
+import { FastifyBaseLogger, FastifyInstance } from 'fastify'
+import { StatusCodes } from 'http-status-codes'
+import { databaseConnection } from '../../../../src/app/database/database-connection'
+import { platformService } from '../../../../src/app/platform/platform.service'
+import { userService } from '../../../../src/app/user/user-service'
+import { userInvitationsService } from '../../../../src/app/user-invitations/user-invitation.service'
+import { generateMockToken } from '../../../helpers/auth'
+import { createMockProject, createMockProjectMember, createMockProjectRole, createMockUserIdentity, mockAndSaveBasicSetup, mockBasicUser } from '../../../helpers/mocks'
+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'
+
+let app: FastifyInstance | null = null
+let mockLog: FastifyBaseLogger
+
+beforeAll(async () => {
+ app = await setupTestEnvironment()
+ mockLog = app!.log!
+})
+
+afterAll(async () => {
+ await teardownTestEnvironment()
+})
+
+describe('A platform invite can name a project', () => {
+ it('stores the project and adds the member to it with the picked role on accept', async () => {
+ const { mockPlatform, mockProject, ownerToken } = await setupPlatform({ projectRolesEnabled: true })
+ const email = faker.internet.email().toLowerCase()
+
+ const response = await invite({ token: ownerToken, email, projectId: mockProject.id, projectRole: DefaultProjectRole.VIEWER })
+
+ expect(response?.statusCode).toBe(StatusCodes.CREATED)
+ const invitation = await databaseConnection().getRepository('user_invitation').findOneByOrFail({ id: response?.json().id })
+ expect(invitation.projectId).toBe(mockProject.id)
+ expect(invitation.type).toBe(InvitationType.PLATFORM)
+
+ const user = await acceptAndProvision({ invitationId: invitation.id, email, platformId: mockPlatform.id })
+
+ expect(user.platformRole).toBe(PlatformRole.MEMBER)
+ expect(await roleNamesByProject({ userId: user.id })).toStrictEqual({ [mockProject.id]: DefaultProjectRole.VIEWER })
+ })
+
+ it('keeps the picked role when the project is also a default project', async () => {
+ const { mockPlatform, mockProject, ownerToken } = await setupPlatform({ projectRolesEnabled: true })
+ await databaseConnection().getRepository('project').update({ id: mockProject.id }, { isDefault: true })
+ const email = faker.internet.email().toLowerCase()
+
+ const response = await invite({ token: ownerToken, email, projectId: mockProject.id, projectRole: DefaultProjectRole.VIEWER })
+ const user = await acceptAndProvision({ invitationId: response?.json().id, email, platformId: mockPlatform.id })
+
+ expect(await roleNamesByProject({ userId: user.id })).toStrictEqual({ [mockProject.id]: DefaultProjectRole.VIEWER })
+ })
+
+ it('still accepts a platform invite without a project', async () => {
+ const { ownerToken } = await setupPlatform({ projectRolesEnabled: true })
+
+ const response = await invite({ token: ownerToken, email: faker.internet.email() })
+
+ expect(response?.statusCode).toBe(StatusCodes.CREATED)
+ const invitation = await databaseConnection().getRepository('user_invitation').findOneByOrFail({ id: response?.json().id })
+ expect(invitation.projectId).toBeNull()
+ })
+
+ it('refuses a personal project', async () => {
+ const { mockPlatform, mockOwner, ownerToken } = await setupPlatform({ projectRolesEnabled: true })
+ const personalProject = createMockProject({ platformId: mockPlatform.id, ownerId: mockOwner.id, type: ProjectType.PERSONAL })
+ await databaseConnection().getRepository('project').save(personalProject)
+
+ const response = await invite({ token: ownerToken, email: faker.internet.email(), projectId: personalProject.id, projectRole: DefaultProjectRole.EDITOR })
+
+ expect(response?.statusCode).toBe(StatusCodes.CONFLICT)
+ expect(response?.json().code).toBe(ErrorCode.VALIDATION)
+ })
+
+ it.each([PlatformRole.ADMIN, PlatformRole.OPERATOR])('refuses a project on a platform invite for an %s', async (platformRole) => {
+ const { mockPlatform, mockProject, ownerToken } = await setupPlatform({ projectRolesEnabled: true })
+ const email = faker.internet.email().toLowerCase()
+
+ const response = await invite({ token: ownerToken, email, projectId: mockProject.id, projectRole: DefaultProjectRole.VIEWER, platformRole })
+
+ expect(response?.statusCode).toBe(StatusCodes.CONFLICT)
+ expect(response?.json().code).toBe(ErrorCode.VALIDATION)
+ expect(await databaseConnection().getRepository('user_invitation').countBy({ email, platformId: mockPlatform.id })).toBe(0)
+ })
+
+ it('refuses a project of another platform', async () => {
+ const { ownerToken } = await setupPlatform({ projectRolesEnabled: true })
+ const { mockProject: otherProject } = await setupPlatform({ projectRolesEnabled: true })
+
+ const response = await invite({ token: ownerToken, email: faker.internet.email(), projectId: otherProject.id, projectRole: DefaultProjectRole.EDITOR })
+
+ expect(response?.statusCode).toBe(StatusCodes.CONFLICT)
+ expect(response?.json().code).toBe(ErrorCode.VALIDATION)
+ })
+
+ it('refuses a project without a role', async () => {
+ const { mockProject, ownerToken } = await setupPlatform({ projectRolesEnabled: true })
+
+ const response = await invite({ token: ownerToken, email: faker.internet.email(), projectId: mockProject.id })
+
+ expect(response?.statusCode).toBe(StatusCodes.CONFLICT)
+ expect(response?.json().code).toBe(ErrorCode.VALIDATION)
+ })
+
+ it('refuses a project on a plan without project roles', async () => {
+ const { mockProject, ownerToken } = await setupPlatform({ projectRolesEnabled: false })
+
+ const response = await invite({ token: ownerToken, email: faker.internet.email(), projectId: mockProject.id, projectRole: DefaultProjectRole.EDITOR })
+
+ expect(response?.statusCode).toBe(StatusCodes.PAYMENT_REQUIRED)
+ expect(response?.json().code).toBe(ErrorCode.FEATURE_DISABLED)
+ })
+
+ it('still creates the user when the plan lost project roles before they accepted', async () => {
+ const { mockPlatform, mockProject, ownerToken } = await setupPlatform({ projectRolesEnabled: true })
+ const email = faker.internet.email().toLowerCase()
+ const response = await invite({ token: ownerToken, email, projectId: mockProject.id, projectRole: DefaultProjectRole.EDITOR })
+ await databaseConnection().getRepository('platform_plan').update({ platformId: mockPlatform.id }, { projectRolesEnabled: false })
+
+ const user = await acceptAndProvision({ invitationId: response?.json().id, email, platformId: mockPlatform.id })
+
+ expect(user.platformRole).toBe(PlatformRole.MEMBER)
+ expect(await roleNamesByProject({ userId: user.id })).toStrictEqual({})
+ })
+})
+
+describe('A platform invite outlives its project', () => {
+ it('skips a project that was deleted before they accepted, instead of failing the sign-up', async () => {
+ const { mockPlatform, mockProject, ownerToken } = await setupPlatform({ projectRolesEnabled: true })
+ const email = faker.internet.email().toLowerCase()
+ const response = await invite({ token: ownerToken, email, projectId: mockProject.id, projectRole: DefaultProjectRole.EDITOR })
+ await databaseConnection().getRepository('project').softDelete({ id: mockProject.id })
+
+ const user = await acceptAndProvision({ invitationId: response?.json().id, email, platformId: mockPlatform.id })
+
+ expect(user.platformRole).toBe(PlatformRole.MEMBER)
+ expect(await roleNamesByProject({ userId: user.id })).toStrictEqual({})
+ })
+
+ it('keeps the platform invite, without the project, when the project is hard-deleted', async () => {
+ const { mockProject, ownerToken } = await setupPlatform({ projectRolesEnabled: true })
+ const response = await invite({ token: ownerToken, email: faker.internet.email(), projectId: mockProject.id, projectRole: DefaultProjectRole.EDITOR })
+
+ await databaseConnection().transaction(async (entityManager) => {
+ await userInvitationsService(mockLog).detachProjectFromPlatformInvites({ projectId: mockProject.id, entityManager })
+ await entityManager.getRepository('project').delete({ id: mockProject.id })
+ })
+
+ const invitation = await databaseConnection().getRepository('user_invitation').findOneByOrFail({ id: response?.json().id })
+ expect(invitation.projectId).toBeNull()
+ expect(invitation.projectRoleId).toBeNull()
+ })
+
+ it('keeps the platform invite, without the project, when its custom role is deleted', async () => {
+ const { mockPlatform, mockProject, ownerToken } = await setupPlatform({ projectRolesEnabled: true })
+ const role = createMockProjectRole({ platformId: mockPlatform.id, type: RoleType.CUSTOM, name: `Custom ${apId()}` })
+ await databaseConnection().getRepository('project_role').save(role)
+ const response = await invite({ token: ownerToken, email: faker.internet.email(), projectId: mockProject.id, projectRole: role.name })
+
+ const deletion = await app?.inject({ method: 'DELETE', url: `/api/v1/project-roles/${encodeURIComponent(role.name)}`, headers: { authorization: `Bearer ${ownerToken}` } })
+
+ expect(deletion?.statusCode).toBe(StatusCodes.OK)
+ const invitation = await databaseConnection().getRepository('user_invitation').findOneByOrFail({ id: response?.json().id })
+ expect(invitation.projectId).toBeNull()
+ expect(invitation.projectRoleId).toBeNull()
+ })
+
+ it('deletes the custom role when the request spells its name in a different case', async () => {
+ const { mockPlatform, mockProject, ownerToken } = await setupPlatform({ projectRolesEnabled: true })
+ const role = createMockProjectRole({ platformId: mockPlatform.id, type: RoleType.CUSTOM, name: `Reviewer ${apId()}` })
+ await databaseConnection().getRepository('project_role').save(role)
+ const response = await invite({ token: ownerToken, email: faker.internet.email(), projectId: mockProject.id, projectRole: role.name })
+
+ const deletion = await app?.inject({ method: 'DELETE', url: `/api/v1/project-roles/${encodeURIComponent(role.name.toLowerCase())}`, headers: { authorization: `Bearer ${ownerToken}` } })
+
+ expect(deletion?.statusCode).toBe(StatusCodes.OK)
+ expect(await databaseConnection().getRepository('project_role').existsBy({ id: role.id })).toBe(false)
+ const invitation = await databaseConnection().getRepository('user_invitation').findOneByOrFail({ id: response?.json().id })
+ expect(invitation.projectId).toBeNull()
+ })
+
+ it('keeps the project on the invite when someone tries to delete a built-in role', async () => {
+ const { mockProject, ownerToken } = await setupPlatform({ projectRolesEnabled: true })
+ const response = await invite({ token: ownerToken, email: faker.internet.email(), projectId: mockProject.id, projectRole: DefaultProjectRole.EDITOR })
+
+ await app?.inject({ method: 'DELETE', url: `/api/v1/project-roles/${encodeURIComponent(DefaultProjectRole.EDITOR)}`, headers: { authorization: `Bearer ${ownerToken}` } })
+
+ const invitation = await databaseConnection().getRepository('user_invitation').findOneByOrFail({ id: response?.json().id })
+ expect(invitation.projectId).toBe(mockProject.id)
+ expect(invitation.projectRoleId).not.toBeNull()
+ expect(await databaseConnection().getRepository('project_role').existsBy({ name: DefaultProjectRole.EDITOR })).toBe(true)
+ })
+})
+
+describe('A platform invite and a project invite for the same project', () => {
+ it('a project invite takes the project off a platform invite instead of replacing it', async () => {
+ const { mockPlatform, mockProject, ownerToken } = await setupPlatform({ projectRolesEnabled: true })
+ const email = faker.internet.email().toLowerCase()
+ await invite({ token: ownerToken, email, projectId: mockProject.id, projectRole: DefaultProjectRole.VIEWER })
+
+ const response = await inviteToProject({ token: ownerToken, email, projectId: mockProject.id, projectRole: DefaultProjectRole.EDITOR })
+
+ expect(response?.statusCode).toBe(StatusCodes.CREATED)
+ const invitations = await invitationsOf({ email, platformId: mockPlatform.id })
+ expect(invitations).toStrictEqual([
+ { type: InvitationType.PLATFORM, platformRole: PlatformRole.MEMBER, projectId: null },
+ { type: InvitationType.PROJECT, platformRole: null, projectId: mockProject.id },
+ ])
+ })
+
+ it('a platform invite naming a project replaces a pending project invite for it', async () => {
+ const { mockPlatform, mockProject, ownerToken } = await setupPlatform({ projectRolesEnabled: true })
+ const email = faker.internet.email().toLowerCase()
+ await inviteToProject({ token: ownerToken, email, projectId: mockProject.id, projectRole: DefaultProjectRole.EDITOR })
+
+ await invite({ token: ownerToken, email, projectId: mockProject.id, projectRole: DefaultProjectRole.VIEWER })
+
+ expect(await invitationsOf({ email, platformId: mockPlatform.id })).toStrictEqual([
+ { type: InvitationType.PLATFORM, platformRole: PlatformRole.MEMBER, projectId: mockProject.id },
+ ])
+ })
+
+ it('a platform invite leaves the project to a project invite that was already accepted', async () => {
+ const { mockPlatform, mockProject, ownerToken } = await setupPlatform({ projectRolesEnabled: true })
+ const email = faker.internet.email().toLowerCase()
+ const editorRole = await databaseConnection().getRepository('project_role').findOneByOrFail({ name: DefaultProjectRole.EDITOR })
+ await databaseConnection().getRepository('user_invitation').save({
+ id: apId(),
+ email,
+ type: InvitationType.PROJECT,
+ platformId: mockPlatform.id,
+ projectId: mockProject.id,
+ projectRoleId: editorRole.id,
+ status: InvitationStatus.ACCEPTED,
+ })
+
+ await invite({ token: ownerToken, email, projectId: mockProject.id, projectRole: DefaultProjectRole.VIEWER })
+
+ expect(await invitationsOf({ email, platformId: mockPlatform.id })).toStrictEqual([
+ { type: InvitationType.PLATFORM, platformRole: PlatformRole.MEMBER, projectId: null },
+ { type: InvitationType.PROJECT, platformRole: null, projectId: mockProject.id },
+ ])
+ })
+
+ it('never adds someone to another platform\'s project, even when an invite names one', async () => {
+ const { mockPlatform } = await setupPlatform({ projectRolesEnabled: true })
+ const { mockProject: otherPlatformProject } = await setupPlatform({ projectRolesEnabled: true })
+ const email = faker.internet.email().toLowerCase()
+ const editorRole = await databaseConnection().getRepository('project_role').findOneByOrFail({ name: DefaultProjectRole.EDITOR })
+ const invitationId = apId()
+ await databaseConnection().getRepository('user_invitation').save({
+ id: invitationId,
+ email,
+ type: InvitationType.PLATFORM,
+ platformRole: PlatformRole.MEMBER,
+ platformId: mockPlatform.id,
+ projectId: otherPlatformProject.id,
+ projectRoleId: editorRole.id,
+ status: InvitationStatus.PENDING,
+ })
+
+ const user = await acceptAndProvision({ invitationId, email, platformId: mockPlatform.id })
+
+ expect(await roleNamesByProject({ userId: user.id })).not.toHaveProperty(otherPlatformProject.id)
+ })
+})
+
+describe('Platform users list says who has a project', () => {
+ it('ignores a membership in a soft-deleted project', async () => {
+ const { mockPlatform, mockOwner, ownerToken } = await setupPlatform({ projectRolesEnabled: true })
+ const deleted = createMockProject({ platformId: mockPlatform.id, ownerId: mockOwner.id, type: ProjectType.TEAM })
+ await databaseConnection().getRepository('project').save(deleted)
+ const { mockUser: member } = await mockBasicUser({ user: { platformId: mockPlatform.id, platformRole: PlatformRole.MEMBER } })
+ const editorRole = await databaseConnection().getRepository('project_role').findOneByOrFail({ name: DefaultProjectRole.EDITOR })
+ await databaseConnection().getRepository('project_member').save(createMockProjectMember({ platformId: mockPlatform.id, projectId: deleted.id, userId: member.id, projectRoleId: editorRole.id }))
+ await databaseConnection().getRepository('project').softDelete({ id: deleted.id })
+
+ const response = await app?.inject({ method: 'GET', url: '/api/v1/users', headers: { authorization: `Bearer ${ownerToken}` }, query: { limit: '100' } })
+
+ const hasProjectsById = Object.fromEntries(response?.json().data.map((user: { id: string, hasProjects: boolean }) => [user.id, user.hasProjects]))
+ expect(hasProjectsById[member.id]).toBe(false)
+ })
+
+ it('marks members with and without a project', async () => {
+ const { mockPlatform, mockProject, ownerToken } = await setupPlatform({ projectRolesEnabled: true })
+ const { mockUser: withProject } = await mockBasicUser({ user: { platformId: mockPlatform.id, platformRole: PlatformRole.MEMBER } })
+ const { mockUser: withoutProject } = await mockBasicUser({ user: { platformId: mockPlatform.id, platformRole: PlatformRole.MEMBER } })
+ const editorRole = await databaseConnection().getRepository('project_role').findOneByOrFail({ name: DefaultProjectRole.EDITOR })
+ await databaseConnection().getRepository('project_member').save(createMockProjectMember({
+ platformId: mockPlatform.id,
+ projectId: mockProject.id,
+ userId: withProject.id,
+ projectRoleId: editorRole.id,
+ }))
+
+ const response = await app?.inject({
+ method: 'GET',
+ url: '/api/v1/users',
+ headers: { authorization: `Bearer ${ownerToken}` },
+ query: { limit: '100' },
+ })
+
+ expect(response?.statusCode).toBe(StatusCodes.OK)
+ const hasProjectsById = Object.fromEntries(response?.json().data.map((user: { id: string, hasProjects: boolean }) => [user.id, user.hasProjects]))
+ expect(hasProjectsById[withProject.id]).toBe(true)
+ expect(hasProjectsById[withoutProject.id]).toBe(false)
+ })
+})
+
+describe('A platform where someone has no project is still theirs', () => {
+ it('names it in the platform switcher list', async () => {
+ const { mockPlatform } = await setupPlatform({ projectRolesEnabled: true })
+ await databaseConnection().getRepository('platform').update({ id: mockPlatform.id }, { autoCreatePersonalProjects: false })
+ const identity = createMockUserIdentity({ verified: true })
+ await databaseConnection().getRepository('user_identity').save(identity)
+ const { user } = await userService(mockLog).getOrCreateWithProject({ identity, platformId: mockPlatform.id })
+ const token = await generateMockToken({ id: user.id, type: PrincipalType.USER, platform: { id: mockPlatform.id } })
+
+ const response = await app?.inject({ method: 'GET', url: '/api/v1/platforms', headers: { authorization: `Bearer ${token}` } })
+
+ expect(response?.statusCode).toBe(StatusCodes.OK)
+ expect(response?.json()).toStrictEqual([{ platformId: mockPlatform.id, platformName: mockPlatform.name, projects: [] }])
+ })
+
+
+ it('lists it after the platforms where they have a project', async () => {
+ const identity = createMockUserIdentity({ verified: true })
+ await databaseConnection().getRepository('user_identity').save(identity)
+ const { mockPlatform: emptyPlatform } = await setupPlatform({ projectRolesEnabled: true })
+ const { mockPlatform: busyPlatform } = await setupPlatform({ projectRolesEnabled: true })
+ await databaseConnection().getRepository('platform').update({ id: emptyPlatform.id }, { autoCreatePersonalProjects: false })
+ await userService(mockLog).getOrCreateWithProject({ identity, platformId: emptyPlatform.id })
+ await userService(mockLog).getOrCreateWithProject({ identity, platformId: busyPlatform.id })
+
+ const platforms = await platformService(mockLog).listPlatformsForIdentity({ identityId: identity.id })
+
+ expect(platforms.map((platform) => platform.id)).toStrictEqual([busyPlatform.id, emptyPlatform.id])
+ })
+})
+
+async function setupPlatform({ projectRolesEnabled }: { projectRolesEnabled: boolean }) {
+ const setup = await mockAndSaveBasicSetup({
+ plan: { projectRolesEnabled },
+ project: { type: ProjectType.TEAM },
+ })
+ const ownerToken = await generateMockToken({
+ id: setup.mockOwner.id,
+ type: PrincipalType.USER,
+ platform: { id: setup.mockPlatform.id },
+ })
+ return { ...setup, ownerToken }
+}
+
+async function invite({ token, email, projectId, projectRole, platformRole = PlatformRole.MEMBER }: { token: string, email: string, projectId?: string, projectRole?: string, platformRole?: PlatformRole }) {
+ return app?.inject({
+ method: 'POST',
+ url: '/api/v1/user-invitations',
+ headers: { authorization: `Bearer ${token}` },
+ body: {
+ email,
+ type: InvitationType.PLATFORM,
+ platformRole,
+ projectId,
+ projectRole,
+ },
+ })
+}
+
+async function inviteToProject({ 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 invitationsOf({ email, platformId }: { email: string, platformId: string }) {
+ const invitations = await databaseConnection().getRepository('user_invitation').find({ where: { email, platformId }, order: { type: 'ASC' } })
+ return invitations.map((invitation) => ({ type: invitation.type, platformRole: invitation.platformRole, projectId: invitation.projectId }))
+}
+
+async function acceptAndProvision({ invitationId, email, platformId }: { invitationId: string, email: string, platformId: string }) {
+ const identity = createMockUserIdentity({ verified: true, email })
+ await databaseConnection().getRepository('user_identity').save(identity)
+ await databaseConnection().getRepository('user_invitation').update({ id: invitationId }, { status: InvitationStatus.ACCEPTED })
+ await userInvitationsService(mockLog).provisionUserInvitation({ email })
+ return databaseConnection().getRepository('user').findOneByOrFail({ identityId: identity.id, platformId })
+}
+
+async function roleNamesByProject({ userId }: { userId: string }): Promise<Record<string, string>> {
+ const rows: { projectId: string, name: string }[] = await databaseConnection().query(
+ 'SELECT pm."projectId", pr."name" FROM "project_member" pm JOIN "project_role" pr ON pr."id" = pm."projectRoleId" WHERE pm."userId" = $1',
+ [userId],
+ )
+ return Object.fromEntries(rows.map((row) => [row.projectId, row.name]))
+}
diff --git a/packages/server/api/test/integration/ee/users/change-role-with-project.test.ts b/packages/server/api/test/integration/ee/users/change-role-with-project.test.ts
new file mode 100644
index 00000000000..567173b3983
--- /dev/null
+++ b/packages/server/api/test/integration/ee/users/change-role-with-project.test.ts
@@ -0,0 +1,59 @@
+import { DefaultProjectRole, InvitationType, PlatformRole, PrincipalType, ProjectType } from '@activepieces/shared'
+import { FastifyInstance } from 'fastify'
+import { StatusCodes } from 'http-status-codes'
+import { databaseConnection } from '../../../../src/app/database/database-connection'
+import { generateMockToken } from '../../../helpers/auth'
+import { 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('Changing an Operator to Member with a project', () => {
+ it('adds them to the project first, then changes the role, leaving a Member of that project', async () => {
+ const { platformId, projectId, ownerToken } = await setup()
+ const { mockUser: operator, mockUserIdentity } = await mockBasicUser({ user: { platformId, platformRole: PlatformRole.OPERATOR } })
+
+ const added = await app?.inject({
+ method: 'POST',
+ url: '/api/v1/user-invitations',
+ headers: { authorization: `Bearer ${ownerToken}` },
+ body: { email: mockUserIdentity.email, type: InvitationType.PROJECT, projectId, projectRole: DefaultProjectRole.VIEWER },
+ })
+ const changed = await app?.inject({
+ method: 'POST',
+ url: `/api/v1/users/${operator.id}`,
+ headers: { authorization: `Bearer ${ownerToken}` },
+ body: { platformRole: PlatformRole.MEMBER },
+ })
+
+ expect(added?.statusCode).toBe(StatusCodes.CREATED)
+ expect(changed?.statusCode).toBe(StatusCodes.OK)
+ expect(changed?.json().platformRole).toBe(PlatformRole.MEMBER)
+ expect(await roleNamesByProject({ userId: operator.id })).toStrictEqual({ [projectId]: DefaultProjectRole.VIEWER })
+ })
+})
+
+async function setup() {
+ 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 roleNamesByProject({ userId }: { userId: string }): Promise<Record<string, string>> {
+ const rows: { projectId: string, name: string }[] = await databaseConnection().query(
+ 'SELECT pm."projectId", pr."name" FROM "project_member" pm JOIN "project_role" pr ON pr."id" = pm."projectRoleId" WHERE pm."userId" = $1',
+ [userId],
+ )
+ return Object.fromEntries(rows.map((row) => [row.projectId, row.name]))
+}
diff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.json
index f129217d5c7..3a12b58d766 100644
--- a/packages/web/public/locales/en/translation.json
+++ b/packages/web/public/locales/en/translation.json
@@ -26,6 +26,23 @@
"invalidDomain": "Enter a domain like acme.com",
"duplicateDomain": "This domain is already on the list",
"Support": "Support",
+ "Project (optional)": "Project (optional)",
+ "No project": "No project",
+ "Personal projects are off, so pick a project for them to start in.": "Personal projects are off, so pick a project for them to start in.",
+ "Personal projects are off, so they need a project to start in. Create a project first.": "Personal projects are off, so they need a project to start in. Create a project first.",
+ "Couldn't change the role. Try again.": "Couldn't change the role. Try again.",
+ "Members need a project. {name} isn't in one yet.": "Members need a project. {name} isn't in one yet.",
+ "All new members join this project as Editors.": "All new members join this project as Editors.",
+ "Create custom roles, set default projects for new members, and choose whether they get a personal project.": "Create custom roles, set default projects for new members, and choose whether they get a personal project.",
+ "Enable Roles & Access": "Enable Roles & Access",
+ "Turn off if you don't want new members to get a personal project.": "Turn off if you don't want new members to get a personal project.",
+ "New members won't get a personal project. Existing personal projects won't change.": "New members won't get a personal project. Existing personal projects won't change.",
+ "A private project for every new member.": "A private project for every new member.",
+ "Personal projects": "Personal projects",
+ "Turn off personal projects?": "Turn off personal projects?",
+ "Turn off": "Turn off",
+ "You're not in a project yet": "You're not in a project yet",
+ "Ask your admin to add you to one. It'll show up here as soon as they do.": "Ask your admin to add you to one. It'll show up here as soon as they do.",
"New members won't join {project} anymore. Current members keep their access.": "New members won't join {project} anymore. Current members keep their access.",
"Remove {project} from default projects?": "Remove {project} from default projects?",
"New Members join these as Editors, including anyone who signs up through open sign-up or SSO.": "New Members join these as Editors, including anyone who signs up through open sign-up or SSO.",
@@ -604,8 +621,10 @@
"Changelog": "Changelog",
"Community Support": "Community Support",
"Waiting for access": "Waiting for access",
- "You're all signed in, but you've got no projects yet.": "You're all signed in, but you've got no projects yet.",
- "You haven't been added to a project. Ask your workspace admin to invite you and you'll be up and running in no time.": "You haven't been added to a project. Ask your workspace admin to invite you and you'll be up and running in no time.",
+ "Open sidebar": "Open sidebar",
+ "Chat": "Chat",
+ "MCP": "MCP",
+ "Agents": "Agents",
"Impact": "Impact",
"Chat": "Chat",
"Agents": "Agents",
@@ -1791,7 +1810,6 @@
"These flows run on {group}, the project’s group, unless you pick another group for a flow.": "These flows run on {group}, the project’s group, unless you pick another group for a flow.",
"This project has no flows.": "This project has no flows.",
"Created": "Created",
- "Automatic personal project creation updated": "Automatic personal project creation updated",
"Cannot delete active project, switch to another project first": "Cannot delete active project, switch to another project first",
"Personal projects cannot be deleted, and you can't subscribe to their alerts": "Personal projects cannot be deleted, and you can't subscribe to their alerts",
"Go to Roles & Access": "Go to Roles & Access",
@@ -1806,7 +1824,6 @@
"Edit project": "Edit project",
"Manage your automation projects": "Manage your automation projects",
"Automatic personal project creation": "Automatic personal project creation",
- "Create a personal project for every new user on signup. Turn off if you provision users into team projects manually (e.g. via SSO or SCIM).": "Create a personal project for every new user on signup. Turn off if you provision users into team projects manually (e.g. via SSO or SCIM).",
"No projects found": "No projects found",
"Start by creating projects to manage your automation teams": "Start by creating projects to manage your automation teams",
"Manage API keys to access Activepieces APIs.": "Manage API keys to access Activepieces APIs.",
diff --git a/packages/web/src/app/components/no-projects-state.tsx b/packages/web/src/app/components/no-projects-state.tsx
index 5f52bb5a903..916c4357096 100644
--- a/packages/web/src/app/components/no-projects-state.tsx
+++ b/packages/web/src/app/components/no-projects-state.tsx
@@ -17,11 +17,11 @@ export const NoProjectsState = () => {
<div className="flex flex-col gap-2">
<h1 className="text-2xl font-semibold text-gray-12">
- {t("You're all signed in, but you've got no projects yet.")}
+ {t("You're not in a project yet")}
</h1>
<p className="text-base text-gray-11">
{t(
- "You haven't been added to a project. Ask your workspace admin to invite you and you'll be up and running in no time.",
+ "Ask your admin to add you to one. It'll show up here as soon as they do.",
)}
</p>
</div>
diff --git a/packages/web/src/app/routes/platform/plan-feature-sample.tsx b/packages/web/src/app/routes/platform/plan-feature-sample.tsx
index f6a80df5143..d86342cf692 100644
--- a/packages/web/src/app/routes/platform/plan-feature-sample.tsx
+++ b/packages/web/src/app/routes/platform/plan-feature-sample.tsx
@@ -55,9 +55,9 @@ const PLAN_FEATURE_SAMPLES: Record<PlanFeature, PlanFeatureSampleSpec> = {
isLocked: (plan) => !plan.projectRolesEnabled,
teaser: {
featureKey: 'CUSTOM_ROLES',
- title: 'Enable Custom Roles',
+ title: 'Enable Roles & Access',
description:
- 'Define custom roles and permissions to control what your team members can access and modify',
+ 'Create custom roles, set default projects for new members, and choose whether they get a personal project.',
tier: 'team',
},
},
diff --git a/packages/web/src/app/routes/platform/projects/columns.tsx b/packages/web/src/app/routes/platform/projects/columns.tsx
index 742ce5619e0..90cf4b7363d 100644
--- a/packages/web/src/app/routes/platform/projects/columns.tsx
+++ b/packages/web/src/app/routes/platform/projects/columns.tsx
@@ -1,6 +1,6 @@
import { isNil } from '@activepieces/core-utils';
import {
- PlatformWithoutSensitiveData,
+ PlatformResponse,
ProjectWithLimits,
ProjectType,
} from '@activepieces/shared';
@@ -20,10 +20,12 @@ import {
import { RowDataWithActions } from '@/components/custom/data-table';
import { DataTableColumnHeader } from '@/components/custom/data-table/data-table-column-header';
import { FormattedDate } from '@/components/custom/formatted-date';
-
-type ProjectsTableColumnsProps = {
- platform: PlatformWithoutSensitiveData;
-};
+import { Badge } from '@/components/ui/badge';
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from '@/components/ui/tooltip';
export const projectsTableColumns = ({
platform,
@@ -42,12 +44,18 @@ export const projectsTableColumns = ({
cell: ({ row }) => {
const locked = row.original.plan.locked;
const isPersonal = row.original.type === ProjectType.PERSONAL;
+ const isDefault =
+ platform.plan.projectRolesEnabled &&
+ platform.defaultProjectIds.includes(row.original.id);
return (
<div className="text-left flex items-center justify-start ">
{locked && <Lock className="size-3 mr-1.5" strokeWidth={2.5} />}
{isPersonal && <User className="size-4 mr-1.5"></User>}
- <span className="font-medium">{row.original.displayName}</span>
+ <span className="flex items-baseline gap-1.5">
+ <span className="font-medium">{row.original.displayName}</span>
+ {isDefault && <DefaultProjectBadge />}
+ </span>
</div>
);
},
@@ -170,3 +178,20 @@ export const projectsTableColumns = ({
return columns;
};
+
+function DefaultProjectBadge() {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Badge variant="secondary">{t('Default')}</Badge>
+ </TooltipTrigger>
+ <TooltipContent side="top">
+ {t('All new members join this project as Editors.')}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
+type ProjectsTableColumnsProps = {
+ platform: PlatformResponse;
+};
diff --git a/packages/web/src/app/routes/platform/projects/index.tsx b/packages/web/src/app/routes/platform/projects/index.tsx
index 97a94768566..31fcdafafd8 100644
--- a/packages/web/src/app/routes/platform/projects/index.tsx
+++ b/packages/web/src/app/routes/platform/projects/index.tsx
@@ -1,26 +1,21 @@
import { ProjectType, ProjectWithLimits } from '@activepieces/shared';
-import { useMutation, useQueryClient } from '@tanstack/react-query';
import { ColumnDef } from '@tanstack/react-table';
import { t } from 'i18next';
-import { CheckIcon, Package, Pencil, Trash, UserCircle } from 'lucide-react';
+import { CheckIcon, Package, Pencil, Trash } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import { toast } from 'sonner';
-import { platformApi } from '@/api/platforms-api';
import {
AdminDataTable,
AdminPage,
AdminPageHeader,
- SettingsPanel,
- SettingsRow,
adminPageResources,
} from '@/app/components/admin';
import { RowDataWithActions, BulkAction } from '@/components/custom/data-table';
import { ConfirmationDeleteDialog } from '@/components/custom/delete-dialog';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
-import { Switch } from '@/components/ui/switch';
import {
Tooltip,
TooltipContent,
@@ -41,8 +36,7 @@ import { validationUtils } from '@/lib/validation-utils';
import { projectsTableColumns } from './columns';
export default function ProjectsPage() {
- const { platform, setCurrentPlatform } = platformHooks.useCurrentPlatform();
- const queryClient = useQueryClient();
+ const { platform } = platformHooks.useCurrentPlatform();
const navigate = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const { project: currentProject } =
@@ -85,23 +79,6 @@ export default function ProjectsPage() {
const { data: allProjects } =
projectCollectionUtils.useAllPlatformProjects(filters);
- const {
- mutate: toggleAutoCreatePersonalProjects,
- isPending: isAutoCreatePersonalProjectsPending,
- } = useMutation({
- mutationFn: (autoCreatePersonalProjects: boolean) =>
- platformApi.update({ autoCreatePersonalProjects }, platform.id),
- onSuccess: (updatedPlatform) => {
- setCurrentPlatform(queryClient, updatedPlatform);
- toast.success(t('Automatic personal project creation updated'), {
- duration: 3000,
- });
- },
- onError: () => {
- toast.error(t('Failed to save changes. Please try again.'));
- },
- });
-
const [selectedRows, setSelectedRows] = useState<ProjectWithLimits[]>([]);
const [editDialogOpen, setEditDialogOpen] = useState(false);
const [editDialogProjectId, setEditDialogProjectId] = useState<string>('');
@@ -408,25 +385,6 @@ export default function ProjectsPage() {
>
<CreateProjectButton variant="full" projects={allProjects} />
</AdminPageHeader>
- <SettingsPanel flush>
- <SettingsRow
- icon={<UserCircle />}
- title={t('Automatic personal project creation')}
- description={t(
- 'Create a personal project for every new user on signup. Turn off if you provision users into team projects manually (e.g. via SSO or SCIM).',
- )}
- >
- <Switch
- aria-label={t('Automatic personal project creation')}
- checked={platform.autoCreatePersonalProjects}
- onCheckedChange={(checked) =>
- toggleAutoCreatePersonalProjects(checked)
- }
- disabled={isAutoCreatePersonalProjectsPending}
- {...adminControl(AdminControl.PROJECTS_AUTO_PERSONAL_TOGGLE)}
- />
- </SettingsRow>
- </SettingsPanel>
<AdminDataTable
emptyStateTextTitle={t('No projects found')}
emptyStateTextDescription={t(
diff --git a/packages/web/src/app/routes/platform/security/project-role/index.tsx b/packages/web/src/app/routes/platform/security/project-role/index.tsx
index 2bfe4f1ce02..f49205defb1 100644
--- a/packages/web/src/app/routes/platform/security/project-role/index.tsx
+++ b/packages/web/src/app/routes/platform/security/project-role/index.tsx
@@ -11,6 +11,7 @@ import { platformHooks } from '@/hooks/platform-hooks';
import { sampleData } from '../../sample-data';
import { DefaultProjectsSection } from './default-projects-section';
+import { PersonalProjectsSection } from './personal-projects-section';
import { RolesCard } from './roles-card';
const ProjectRolePage = () => {
@@ -34,6 +35,7 @@ const ProjectRolePage = () => {
isError={isSample ? false : isError}
refetch={refetch}
/>
+ <PersonalProjectsSection />
<DefaultProjectsSection />
</AdminPage>
);
diff --git a/packages/web/src/app/routes/platform/security/project-role/personal-projects-section.tsx b/packages/web/src/app/routes/platform/security/project-role/personal-projects-section.tsx
new file mode 100644
index 00000000000..e2c267704f1
--- /dev/null
+++ b/packages/web/src/app/routes/platform/security/project-role/personal-projects-section.tsx
@@ -0,0 +1,97 @@
+import { t } from 'i18next';
+import { useState } from 'react';
+
+import { ConfirmationDeleteDialog } from '@/components/custom/delete-dialog';
+import {
+ Item,
+ ItemActions,
+ ItemContent,
+ ItemDescription,
+ ItemTitle,
+} from '@/components/ui/item';
+import { internalErrorToast } from '@/components/ui/sonner';
+import { Switch } from '@/components/ui/switch';
+import { PLATFORM_FEATURES, useFeatureGate } from '@/features/billing';
+import { newMemberSettingsMutations } from '@/features/platform-admin';
+import { platformHooks } from '@/hooks/platform-hooks';
+import { AdminControl, adminControl } from '@/lib/admin-control';
+
+export function PersonalProjectsSection() {
+ const { platform } = platformHooks.useCurrentPlatform();
+ const [isConfirmOpen, setIsConfirmOpen] = useState(false);
+ const gate = useFeatureGate({
+ locked: !platform.plan.projectRolesEnabled,
+ feature: PLATFORM_FEATURES.projectRoles,
+ });
+ const {
+ mutate: updateSettings,
+ mutateAsync: updateSettingsAsync,
+ isPending,
+ } = newMemberSettingsMutations.useUpdateNewMemberSettings();
+
+ const isEnabled = gate.locked || platform.autoCreatePersonalProjects;
+
+ const onCheckedChange = (checked: boolean) => {
+ if (checked) {
+ updateSettings(
+ { autoCreatePersonalProjects: true },
+ { onError: () => internalErrorToast() },
+ );
+ return;
+ }
+ if (gate.locked) {
+ gate.open();
+ return;
+ }
+ setIsConfirmOpen(true);
+ };
+
+ return (
+ <section className="flex flex-col gap-4">
+ <div className="flex flex-col gap-1">
+ <h2 className="text-base font-medium">{t('Personal projects')}</h2>
+ <p className="max-w-2xl text-sm text-gray-11">
+ {t('A private project for every new member.')}
+ </p>
+ </div>
+ <Item variant="outline" size="sm" className="flex-nowrap bg-panel">
+ <ItemContent className="min-w-0">
+ <ItemTitle>{t('Automatic personal project creation')}</ItemTitle>
+ <ItemDescription>
+ {t(
+ "Turn off if you don't want new members to get a personal project.",
+ )}
+ </ItemDescription>
+ </ItemContent>
+ <ItemActions>
+ <Switch
+ checked={isEnabled}
+ disabled={isPending}
+ aria-label={t('Automatic personal project creation')}
+ onCheckedChange={onCheckedChange}
+ {...adminControl(AdminControl.PROJECTS_AUTO_PERSONAL_TOGGLE)}
+ />
+ </ItemActions>
+ </Item>
+ <ConfirmationDeleteDialog
+ open={isConfirmOpen}
+ onOpenChange={setIsConfirmOpen}
+ title={t('Turn off personal projects?')}
+ message={t(
+ "New members won't get a personal project. Existing personal projects won't change.",
+ )}
+ entityName={t('Personal projects')}
+ buttonText={t('Turn off')}
+ confirmVariant="default"
+ mutationFn={async () => {
+ await updateSettingsAsync({ autoCreatePersonalProjects: false });
+ }}
+ onError={() => {
+ setIsConfirmOpen(false);
+ internalErrorToast();
+ }}
+ />
+ {gate.dialog}
+ </section>
+ );
+}
diff --git a/packages/web/src/app/routes/platform/users/actions/update-user-dialog.tsx b/packages/web/src/app/routes/platform/users/actions/update-user-dialog.tsx
index 86ada85ecac..fd0fcf88de7 100644
--- a/packages/web/src/app/routes/platform/users/actions/update-user-dialog.tsx
+++ b/packages/web/src/app/routes/platform/users/actions/update-user-dialog.tsx
@@ -1,4 +1,6 @@
+import { isNil } from '@activepieces/core-utils';
import {
+ InvitationType,
PlatformRole,
UpdateUserRequestBody,
User,
@@ -6,8 +8,10 @@ import {
import { zodResolver } from '@hookform/resolvers/zod';
import { useMutation } from '@tanstack/react-query';
import { t } from 'i18next';
+import { Info } from 'lucide-react';
import { useState } from 'react';
-import { Resolver, useForm } from 'react-hook-form';
+import { useForm } from 'react-hook-form';
+import { z } from 'zod';
import { platformUserApi } from '@/api/platform-user-api';
import { adminLayout } from '@/app/components/admin';
@@ -24,42 +28,92 @@ import { Form, FormField, FormItem, FormMessage } from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { RoleSelector } from '@/features/members';
+import { userInvitationApi } from '@/features/members/api/user-invitation';
+import { InvitedProjectSelect } from '@/features/members/components/invite-user/invited-project-select';
+import { ProjectRoleSelect } from '@/features/members/components/project-role-select';
+import { platformHooks } from '@/hooks/platform-hooks';
import { AdminControl, adminControl } from '@/lib/admin-control';
export const UpdateUserDialog = ({
children,
onUpdate,
userId,
+ email,
+ firstName,
role,
externalId,
-}: {
- children: React.ReactNode;
- onUpdate: (role: PlatformRole) => void;
- userId: string;
- role: PlatformRole;
- externalId?: string;
-}) => {
+ hasProjects,
+}: UpdateUserDialogProps) => {
const [open, setOpen] = useState(false);
- const form = useForm<{ role: PlatformRole; externalId?: string }>({
+ const { platform } = platformHooks.useCurrentPlatform();
+ const form = useForm<UpdateUserFormValues>({
defaultValues: {
role,
externalId,
+ projectId: undefined,
+ projectRole: undefined,
},
- resolver: zodResolver(UpdateUserRequestBody) as unknown as Resolver<{
- role: PlatformRole;
- externalId?: string;
- }>,
+ resolver: zodResolver(UpdateUserFormValues),
});
- const { mutate, isPending } = useMutation<User, Error, UpdateUserRequestBody>(
- {
- mutationKey: ['update-user'],
- mutationFn: (request) => platformUserApi.update(userId, request),
- onSuccess: (user) => {
- onUpdate(user.platformRole);
- setOpen(false);
- },
+ const selectedRole = form.watch('role');
+ const needsAProject =
+ role !== PlatformRole.MEMBER &&
+ selectedRole === PlatformRole.MEMBER &&
+ !hasProjects &&
+ platform.plan.projectRolesEnabled;
+
+ const { mutate, isPending } = useMutation<User, Error, UpdateUserFormValues>({
+ mutationKey: ['update-user'],
+ mutationFn: async (values) => {
+ if (
+ needsAProject &&
+ !isNil(values.projectId) &&
+ !isNil(values.projectRole)
+ ) {
+ await userInvitationApi.invite({
+ email,
+ type: InvitationType.PROJECT,
+ projectId: values.projectId,
+ projectRole: values.projectRole,
+ });
+ }
+ const request: UpdateUserRequestBody = {
+ platformRole: values.role,
+ externalId: values.externalId,
+ };
+ return platformUserApi.update(userId, request);
},
- );
+ onSuccess: (user) => {
+ onUpdate(user.platformRole);
+ setOpen(false);
+ },
+ onError: () => {
+ form.setError('root.serverError', {
+ type: 'manual',
+ message: t("Couldn't change the role. Try again."),
+ });
+ },
+ });
+
+ const save = () => {
+ form.clearErrors('root.serverError');
+ const values = form.getValues();
+ if (needsAProject && isNil(values.projectId)) {
+ form.setError('projectId', {
+ type: 'required',
+ message: t('Please select a project'),
+ });
+ return;
+ }
+ if (needsAProject && isNil(values.projectRole)) {
+ form.setError('projectRole', {
+ type: 'required',
+ message: t('Please select a project role'),
+ });
+ return;
+ }
+ mutate(values);
+ };
return (
<Dialog
@@ -90,6 +144,31 @@ export const UpdateUserDialog = ({
</FormItem>
)}
/>
+ {needsAProject && (
+ <>
+ <FormField
+ control={form.control}
+ name="projectId"
+ render={({ field }) => (
+ <FormItem className="grid space-y-2">
+ <Label>{t('Project')}</Label>
+ <InvitedProjectSelect
+ value={field.value}
+ onValueChange={field.onChange}
+ />
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <ProjectRoleSelect form={form} />
+ <p className="flex items-start gap-1.5 text-xs text-gray-11">
+ <Info className="mt-px size-3.5 shrink-0" />
+ {t("Members need a project. {name} isn't in one yet.", {
+ name: firstName,
+ })}
+ </p>
+ </>
+ )}
<FormField
name="externalId"
render={({ field }) => (
@@ -129,10 +208,7 @@ export const UpdateUserDialog = ({
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
- mutate({
- platformRole: form.getValues().role,
- externalId: form.getValues().externalId,
- });
+ save();
}}
>
{t('Save')}
@@ -142,3 +218,23 @@ export const UpdateUserDialog = ({
</Dialog>
);
};
+
+const UpdateUserFormValues = z.object({
+ role: z.enum(PlatformRole),
+ externalId: z.string().optional(),
+ projectId: z.string().optional(),
+ projectRole: z.string().optional(),
+});
+
+type UpdateUserFormValues = z.infer<typeof UpdateUserFormValues>;
+
+type UpdateUserDialogProps = {
+ children: React.ReactNode;
+ onUpdate: (role: PlatformRole) => void;
+ userId: string;
+ email: string;
+ firstName: string;
+ role: PlatformRole;
+ externalId?: string;
+ hasProjects: boolean;
+};
diff --git a/packages/web/src/app/routes/platform/users/actions/user-actions.tsx b/packages/web/src/app/routes/platform/users/actions/user-actions.tsx
index 9eaef197097..91bbbb9d0bf 100644
--- a/packages/web/src/app/routes/platform/users/actions/user-actions.tsx
+++ b/packages/web/src/app/routes/platform/users/actions/user-actions.tsx
@@ -55,8 +55,11 @@ export const UserActions = ({
{!isInvitation && (
<UpdateUserDialog
userId={row.data.id}
+ email={row.data.email}
+ firstName={row.data.firstName}
role={row.data.platformRole}
externalId={row.data.externalId ?? undefined}
+ hasProjects={row.data.hasProjects ?? true}
onUpdate={onUpdate}
>
<DropdownMenuItem
diff --git a/packages/web/src/components/custom/delete-dialog.tsx b/packages/web/src/components/custom/delete-dialog.tsx
index 20928c8d5e9..24fa6c635a8 100644
--- a/packages/web/src/components/custom/delete-dialog.tsx
+++ b/packages/web/src/components/custom/delete-dialog.tsx
@@ -39,6 +39,7 @@ interface ConfirmationDeleteDialogProps {
controlId?: AdminControl;
contentClassName?: string;
keepOpenOnOutsideClick?: boolean;
+ confirmVariant?: 'destructive' | 'default';
}
export const ConfirmationDeleteDialog = ({
@@ -59,6 +60,7 @@ export const ConfirmationDeleteDialog = ({
controlId,
contentClassName,
keepOpenOnOutsideClick = false,
+ confirmVariant = 'destructive',
}: ConfirmationDeleteDialogProps) => {
const [isControlled] = useState(
open !== undefined && onOpenChange !== undefined,
@@ -131,7 +133,7 @@ export const ConfirmationDeleteDialog = ({
{t('Cancel')}
</Button>
<Button
- variant="destructive"
+ variant={confirmVariant}
loading={isPending}
disabled={confirmDisabled || !typed.confirmed}
onClick={() => mutate()}
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.tsx
index 0b010c7694c..15af908e59b 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,4 +1,4 @@
-import { Permission } from '@activepieces/core-utils';
+import { isNil, Permission } from '@activepieces/core-utils';
import {
ApFlagId,
InvitationStatus,
@@ -38,6 +38,7 @@ import { userInvitationApi } from '@/features/members/api/user-invitation';
import { PlatformRoleSelect } from '@/features/members/components/platform-role-select';
import { ProjectRoleSelect } from '@/features/members/components/project-role-select';
import { projectMembersHooks } from '@/features/members/hooks/project-members-hooks';
+import { inviteDefaults } from '@/features/members/lib/invite-defaults';
import { platformUserHooks } from '@/features/platform-admin/hooks/platform-user-hooks';
import { projectCollectionUtils } from '@/features/projects/stores/project-collection';
import { useAuthorization } from '@/hooks/authorization-hooks';
@@ -51,6 +52,8 @@ import { formatUtils } from '@/lib/format-utils';
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 { UserSuggestionsPopover } from './user-suggestions-popover';
const buildInvalidEmailsMessage = (emails: string[]): string => {
@@ -92,6 +95,7 @@ const FormSchema = z.object({
message: t('Please select platform role'),
}),
projectRole: z.string().optional(),
+ projectId: z.string().optional(),
});
type FormSchema = z.infer<typeof FormSchema>;
@@ -124,13 +128,18 @@ const InviteUserDialogInternal = ({
>([]);
const [suggestionsOpen, setSuggestionsOpen] = useState(false);
const { platform } = platformHooks.useCurrentPlatform();
+ const { activeDefaultProjectIds, personalProjectsActive } =
+ platformHooks.useNewMemberSettings();
+ const { data: teamProjects } = projectCollectionUtils.useAllPlatformProjects({
+ type: [ProjectType.TEAM],
+ });
const { handleSeatLimitError, ensureSeatsAvailable, seatLimitDialog } =
useSeatLimitGuard();
const { data: isSmtpConfigured } = flagsHooks.useFlag<boolean>(
ApFlagId.SMTP_CONFIGURED,
);
const { refetch } = userInvitationsHooks.useInvitations();
- const { project } = projectCollectionUtils.useCurrentProject();
+ const { project } = projectCollectionUtils.useCurrentProjectOrNull();
const { checkAccess } = useAuthorization();
const location = useLocation();
const isPlatformPage = location.pathname.includes('/platform/');
@@ -159,11 +168,16 @@ const InviteUserDialogInternal = ({
>({
mutationFn: async (data) => {
const promises = data.emails.map((email) =>
- data.type === InvitationType.PLATFORM
+ data.type === InvitationType.PLATFORM || isNil(project)
? userInvitationApi.invite({
email: email.trim().toLowerCase(),
- type: data.type,
+ type: InvitationType.PLATFORM,
platformRole: data.platformRole,
+ ...invitedProjectFields({
+ data,
+ projectRolesEnabled: platform.plan.projectRolesEnabled,
+ personalProjectsActive,
+ }),
})
: userInvitationApi.invite({
email: email.trim().toLowerCase(),
@@ -192,7 +206,7 @@ const InviteUserDialogInternal = ({
addedCount,
invitedCount,
sentCount: results.length - addedCount - invitedCount,
- projectName: project.displayName,
+ projectName: project?.displayName ?? platform.name,
});
if (toastMessage) {
toast.success(toastMessage, { duration: 3000 });
@@ -214,13 +228,16 @@ const InviteUserDialogInternal = ({
resolver: zodResolver(FormSchema),
defaultValues: {
emails: [],
- type: isPlatformPage
- ? InvitationType.PLATFORM
- : platform.plan.projectRolesEnabled && project.type === ProjectType.TEAM
- ? InvitationType.PROJECT
- : InvitationType.PLATFORM,
+ type: inviteDefaults.invitationType({
+ isPlatformPage,
+ projectRolesEnabled: platform.plan.projectRolesEnabled,
+ projectType: project?.type ?? null,
+ }),
platformRole: PlatformRole.OPERATOR,
projectRole: undefined,
+ projectId: personalProjectsActive
+ ? undefined
+ : activeDefaultProjectIds[0],
},
});
@@ -233,9 +250,18 @@ const InviteUserDialogInternal = ({
enteredEmails.some(
(email) => !platformUserEmails.has(email.trim().toLowerCase()),
);
+ const selectedProjectId = form.watch('projectId');
const joinsDefaultProjects =
invitationType === InvitationType.PROJECT ||
selectedPlatformRole === PlatformRole.MEMBER;
+ const projectMode = invitedProjectMode({
+ type: invitationType,
+ platformRole: selectedPlatformRole,
+ projectRolesEnabled: platform.plan.projectRolesEnabled,
+ personalProjectsActive,
+ });
+ const needsAProjectFirst =
+ projectMode === 'required' && teamProjects.length === 0;
const handleEmailsChange = useCallback(
(emails: ReadonlyArray<string>) => {
@@ -259,7 +285,19 @@ const InviteUserDialogInternal = ({
return;
}
- if (data.type === InvitationType.PROJECT && !data.projectRole) {
+ if (projectMode === 'required' && !data.projectId) {
+ form.setError('projectId', {
+ type: 'required',
+ message: t('Please select a project'),
+ });
+ return;
+ }
+
+ if (
+ (data.type === InvitationType.PROJECT ||
+ (projectMode !== 'none' && !isNil(data.projectId))) &&
+ !data.projectRole
+ ) {
form.setError('projectRole', {
type: 'required',
message: t('Please select a project role'),
@@ -316,7 +354,7 @@ const InviteUserDialogInternal = ({
resultsWithLinksCount: resultsWithLinks.length,
invitationType,
isSmtpConfigured: isSmtpConfigured ?? false,
- projectName: project.displayName,
+ projectName: project?.displayName ?? platform.name,
});
return (
@@ -370,6 +408,47 @@ const InviteUserDialogInternal = ({
{form.getValues().type === InvitationType.PLATFORM && (
<PlatformRoleSelect form={form} />
)}
+ {needsAProjectFirst && (
+ <NoTeamProjectsState
+ onCreate={(created) =>
+ form.setValue('projectId', created.id)
+ }
+ />
+ )}
+ {projectMode !== 'none' && !needsAProjectFirst && (
+ <>
+ <FormField
+ control={form.control}
+ name="projectId"
+ render={({ field }) => (
+ <FormItem className="grid gap-3">
+ <Label>
+ {projectMode === 'optional'
+ ? t('Project (optional)')
+ : t('Project')}
+ </Label>
+ <InvitedProjectSelect
+ value={field.value}
+ onValueChange={field.onChange}
+ allowNone={projectMode === 'optional'}
+ />
+ {projectMode === 'required' && (
+ <p className="text-xs text-gray-11">
+ {t(
+ 'Personal projects are off, so pick a project for them to start in.',
+ )}
+ </p>
+ )}
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ {(projectMode === 'required' ||
+ !isNil(selectedProjectId)) && (
+ <ProjectRoleSelect form={form} />
+ )}
+ </>
+ )}
{form.getValues().type === InvitationType.PROJECT && (
<ProjectRoleSelect form={form} />
)}
@@ -377,8 +456,8 @@ const InviteUserDialogInternal = ({
<DefaultProjectsNote
invitedProjectId={
invitationType === InvitationType.PROJECT
- ? project.id
- : undefined
+ ? project?.id
+ : selectedProjectId
}
includesPersonalProject={isPlatformInvite}
invitesSomeoneNew={invitesSomeoneNew}
@@ -399,6 +478,7 @@ const InviteUserDialogInternal = ({
<Button
type="submit"
loading={isPending}
+ disabled={needsAProjectFirst}
{...adminControl(AdminControl.USERS_INVITE_SUBMIT)}
>
{isPlatformInvite ? t('Invite') : t('Add')}
@@ -456,6 +536,39 @@ const InviteUserDialogInternal = ({
);
};
+function invitedProjectMode({
+ type,
+ platformRole,
+ projectRolesEnabled,
+ personalProjectsActive,
+}: InvitedProjectModeParams): InvitedProjectMode {
+ if (
+ type !== InvitationType.PLATFORM ||
+ platformRole !== PlatformRole.MEMBER ||
+ !projectRolesEnabled
+ ) {
+ return 'none';
+ }
+ return personalProjectsActive ? 'optional' : 'required';
+}
+
+function invitedProjectFields({
+ data,
+ projectRolesEnabled,
+ personalProjectsActive,
+}: InvitedProjectFieldsParams): { projectId?: string; projectRole?: string } {
+ const mode = invitedProjectMode({
+ type: data.type,
+ platformRole: data.platformRole,
+ projectRolesEnabled,
+ personalProjectsActive,
+ });
+ if (mode === 'none' || isNil(data.projectId)) {
+ return {};
+ }
+ return { projectId: data.projectId, projectRole: data.projectRole };
+}
+
function getDialogDescription({
hasLinks,
addedMembersCount,
@@ -582,3 +695,18 @@ type InviteUserDialogProps = {
setOpen: (_open: boolean) => void;
onInviteSuccess?: () => void;
};
+
+type InvitedProjectMode = 'none' | 'optional' | 'required';
+
+type InvitedProjectModeParams = {
+ type: InvitationType;
+ platformRole: PlatformRole;
+ projectRolesEnabled: boolean;
+ personalProjectsActive: boolean;
+};
+
+type InvitedProjectFieldsParams = {
+ data: FormSchema;
+ projectRolesEnabled: boolean;
+ personalProjectsActive: boolean;
+};
diff --git a/packages/web/src/features/members/components/invite-user/invited-project-select.tsx b/packages/web/src/features/members/components/invite-user/invited-project-select.tsx
new file mode 100644
index 00000000000..1559f02abbd
--- /dev/null
+++ b/packages/web/src/features/members/components/invite-user/invited-project-select.tsx
@@ -0,0 +1,63 @@
+import { ProjectType } from '@activepieces/shared';
+import { t } from 'i18next';
+
+import { Badge } from '@/components/ui/badge';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import { projectCollectionUtils } from '@/features/projects/stores/project-collection';
+import { platformHooks } from '@/hooks/platform-hooks';
+
+export function InvitedProjectSelect({
+ value,
+ onValueChange,
+ allowNone,
+}: InvitedProjectSelectProps) {
+ const { activeDefaultProjectIds } = platformHooks.useNewMemberSettings();
+ const { data: teamProjects } = projectCollectionUtils.useAllPlatformProjects({
+ type: [ProjectType.TEAM],
+ });
+ const sortedProjects = [...teamProjects].sort((left, right) =>
+ left.displayName.localeCompare(right.displayName),
+ );
+
+ return (
+ <Select
+ value={value ?? (allowNone ? NO_PROJECT : undefined)}
+ onValueChange={(selected) =>
+ onValueChange(selected === NO_PROJECT ? undefined : selected)
+ }
+ >
+ <SelectTrigger aria-label={t('Project')}>
+ <SelectValue placeholder={t('Select a project')} />
+ </SelectTrigger>
+ <SelectContent>
+ {allowNone && (
+ <SelectItem value={NO_PROJECT}>{t('No project')}</SelectItem>
+ )}
+ {sortedProjects.map((project) => (
+ <SelectItem key={project.id} value={project.id}>
+ <span className="flex min-w-0 items-center gap-2">
+ <span className="truncate">{project.displayName}</span>
+ {activeDefaultProjectIds.includes(project.id) && (
+ <Badge variant="secondary">{t('Default')}</Badge>
+ )}
+ </span>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+}
+
+const NO_PROJECT = 'no-project';
+
+type InvitedProjectSelectProps = {
+ value: string | undefined;
+ onValueChange: (projectId: string | undefined) => void;
+ allowNone?: boolean;
+};
diff --git a/packages/web/src/features/members/components/invite-user/no-team-projects-state.tsx b/packages/web/src/features/members/components/invite-user/no-team-projects-state.tsx
new file mode 100644
index 00000000000..2be6ea198d8
--- /dev/null
+++ b/packages/web/src/features/members/components/invite-user/no-team-projects-state.tsx
@@ -0,0 +1,27 @@
+import { ProjectWithLimits } from '@activepieces/shared';
+import { t } from 'i18next';
+
+import { CreateProjectButton } from '@/features/projects';
+
+export function NoTeamProjectsState({ onCreate }: NoTeamProjectsStateProps) {
+ return (
+ <div className="flex flex-col items-start gap-3 rounded-lg border p-3">
+ <p className="text-sm text-gray-11">
+ {t(
+ 'Personal projects are off, so they need a project to start in. Create a project first.',
+ )}
+ </p>
+ <CreateProjectButton
+ variant="full"
+ projects={NO_TEAM_PROJECTS}
+ onCreate={onCreate}
+ />
+ </div>
+ );
+}
+
+const NO_TEAM_PROJECTS: Pick<ProjectWithLimits, 'type'>[] = [];
+
+type NoTeamProjectsStateProps = {
+ onCreate: (project: ProjectWithLimits) => void;
+};
diff --git a/packages/web/src/features/members/lib/invite-defaults.ts b/packages/web/src/features/members/lib/invite-defaults.ts
new file mode 100644
index 00000000000..075e3c91e43
--- /dev/null
+++ b/packages/web/src/features/members/lib/invite-defaults.ts
@@ -0,0 +1,24 @@
+import { InvitationType, ProjectType } from '@activepieces/shared';
+
+function invitationType({
+ isPlatformPage,
+ projectRolesEnabled,
+ projectType,
+}: InvitationTypeParams): InvitationType {
+ if (isPlatformPage) {
+ return InvitationType.PLATFORM;
+ }
+ return projectRolesEnabled && projectType === ProjectType.TEAM
+ ? InvitationType.PROJECT
+ : InvitationType.PLATFORM;
+}
+
+export const inviteDefaults = {
+ invitationType,
+};
+
+type InvitationTypeParams = {
+ isPlatformPage: boolean;
+ projectRolesEnabled: boolean;
+ projectType: ProjectType | null;
+};
diff --git a/packages/web/src/features/platform-admin/hooks/new-member-settings-hooks.ts b/packages/web/src/features/platform-admin/hooks/new-member-settings-hooks.ts
new file mode 100644
index 00000000000..06cc78b6b52
--- /dev/null
+++ b/packages/web/src/features/platform-admin/hooks/new-member-settings-hooks.ts
@@ -0,0 +1,25 @@
+import { UpdatePlatformRequestBody } from '@activepieces/shared';
+import { useMutation, useQueryClient } from '@tanstack/react-query';
+
+import { platformApi } from '@/api/platforms-api';
+import { platformHooks } from '@/hooks/platform-hooks';
+
+export const newMemberSettingsMutations = {
+ useUpdateNewMemberSettings: () => {
+ const queryClient = useQueryClient();
+ const { platform, setCurrentPlatform } = platformHooks.useCurrentPlatform();
+ return useMutation({
+ mutationFn: (request: NewMemberSettingsRequest) =>
+ platformApi.update(request, platform.id),
+ onSuccess: (updatedPlatform) => {
+ setCurrentPlatform(queryClient, updatedPlatform);
+ },
+ onError: () => undefined,
+ });
+ },
+};
+
+type NewMemberSettingsRequest = Pick<
+ UpdatePlatformRequestBody,
+ 'autoCreatePersonalProjects'
+>;
diff --git a/packages/web/src/features/platform-admin/index.ts b/packages/web/src/features/platform-admin/index.ts
index edb2462066d..239d113f567 100644
--- a/packages/web/src/features/platform-admin/index.ts
+++ b/packages/web/src/features/platform-admin/index.ts
@@ -30,6 +30,7 @@ export {
} from './hooks/signing-key-hooks';
export { auditLogQueries, auditLogKeys } from './hooks/audit-log-hooks';
export { ssoMutations } from './hooks/sso-hooks';
+export { newMemberSettingsMutations } from './hooks/new-member-settings-hooks';
export {
projectRoleQueries,
projectRoleMutations,
diff --git a/packages/web/src/features/projects/components/platform-switcher.tsx b/packages/web/src/features/projects/components/platform-switcher.tsx
index dc68f4c0db0..8fdc9cd27a1 100644
--- a/packages/web/src/features/projects/components/platform-switcher.tsx
+++ b/packages/web/src/features/projects/components/platform-switcher.tsx
@@ -32,7 +32,7 @@ export function PlatformSwitcher({ children }: { children: React.ReactNode }) {
if (!allProjects) return [];
return allProjects.map((platform) => ({
name: platform.platformName,
- id: platform.projects[0]?.platformId,
+ id: platform.platformId,
}));
}, [allProjects]);
diff --git a/packages/web/src/features/projects/stores/project-collection.ts b/packages/web/src/features/projects/stores/project-collection.ts
index 28af143c746..eefec13265b 100644
--- a/packages/web/src/features/projects/stores/project-collection.ts
+++ b/packages/web/src/features/projects/stores/project-collection.ts
@@ -227,6 +227,21 @@ export const projectCollectionUtils = {
project: data!,
};
},
+ useCurrentProjectOrNull: () => {
+ const projectId = authenticationSession.getProjectId();
+ const { data } = useLiveSuspenseQuery(
+ (q) =>
+ q
+ .from({ project: projectCollection })
+ .where(({ project }) => eq(project.id, projectId))
+ .select(({ project }) => ({ ...project }))
+ .findOne(),
+ [projectId],
+ );
+ return {
+ project: data ?? null,
+ };
+ },
useAll: () => {
const currentUserId = authenticationSession.getCurrentUserId();
return useLiveSuspenseQuery(
diff --git a/packages/web/src/lib/authentication-session.ts b/packages/web/src/lib/authentication-session.ts
index 5faa9d89ef1..a3ca736527a 100644
--- a/packages/web/src/lib/authentication-session.ts
+++ b/packages/web/src/lib/authentication-session.ts
@@ -24,9 +24,7 @@ export const authenticationSession = {
ApStorage.setInstanceToSessionStorage();
}
ApStorage.getInstance().setItem(tokenKey, response.token);
- if (!isNil(response.projectId)) {
- ApStorage.getInstance().setItem(projectIdKey, response.projectId);
- }
+ saveProjectIdOrClear(response.projectId);
queryClient.invalidateQueries({ queryKey: ['flags'] });
window.dispatchEvent(new Event('storage'));
},
@@ -106,9 +104,7 @@ export const authenticationSession = {
platformId,
});
ApStorage.getInstance().setItem(tokenKey, result.token);
- if (!isNil(result.projectId)) {
- ApStorage.getInstance().setItem(projectIdKey, result.projectId);
- }
+ saveProjectIdOrClear(result.projectId);
window.location.href = '/';
},
switchToProject(projectId: string) {
@@ -142,3 +138,11 @@ export const authenticationSession = {
function getDecodedJwt(token: string): Principal {
return jwtDecode<Principal>(token);
}
+
+function saveProjectIdOrClear(projectId: string | null | undefined): void {
+ if (isNil(projectId)) {
+ ApStorage.getInstance().removeItem(projectIdKey);
+ return;
+ }
+ ApStorage.getInstance().setItem(projectIdKey, projectId);
+}
diff --git a/packages/web/test/features/members/lib/invite-defaults.test.ts b/packages/web/test/features/members/lib/invite-defaults.test.ts
new file mode 100644
index 00000000000..6bee78ba213
--- /dev/null
+++ b/packages/web/test/features/members/lib/invite-defaults.test.ts
@@ -0,0 +1,53 @@
+import { InvitationType, ProjectType } from '@activepieces/shared';
+import { describe, expect, it } from 'vitest';
+
+import { inviteDefaults } from '@/features/members/lib/invite-defaults';
+
+describe('inviteDefaults.invitationType', () => {
+ it('starts on a platform invite when there is no current project', () => {
+ expect(
+ inviteDefaults.invitationType({
+ isPlatformPage: false,
+ projectRolesEnabled: true,
+ projectType: null,
+ }),
+ ).toBe(InvitationType.PLATFORM);
+ });
+
+ it('starts on a platform invite on platform pages', () => {
+ expect(
+ inviteDefaults.invitationType({
+ isPlatformPage: true,
+ projectRolesEnabled: true,
+ projectType: ProjectType.TEAM,
+ }),
+ ).toBe(InvitationType.PLATFORM);
+ });
+
+ it('starts on a project invite in a team project with project roles', () => {
+ expect(
+ inviteDefaults.invitationType({
+ isPlatformPage: false,
+ projectRolesEnabled: true,
+ projectType: ProjectType.TEAM,
+ }),
+ ).toBe(InvitationType.PROJECT);
+ });
+
+ it('starts on a platform invite in a personal project or without project roles', () => {
+ expect(
+ inviteDefaults.invitationType({
+ isPlatformPage: false,
+ projectRolesEnabled: true,
+ projectType: ProjectType.PERSONAL,
+ }),
+ ).toBe(InvitationType.PLATFORM);
+ expect(
+ inviteDefaults.invitationType({
+ isPlatformPage: false,
+ projectRolesEnabled: false,
+ projectType: ProjectType.TEAM,
+ }),
+ ).toBe(InvitationType.PLATFORM);
+ });
+});
diff --git a/packages/web/test/lib/authentication-session.test.ts b/packages/web/test/lib/authentication-session.test.ts
new file mode 100644
index 00000000000..0a88ad77364
--- /dev/null
+++ b/packages/web/test/lib/authentication-session.test.ts
@@ -0,0 +1,102 @@
+/**
+ * @vitest-environment jsdom
+ */
+import {
+ AuthenticationResponse,
+ PlatformRole,
+ UserStatus,
+} from '@activepieces/shared';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { authenticationApi } from '@/api/authentication-api';
+import { authenticationSession } from '@/lib/authentication-session';
+
+vi.mock('@/api/authentication-api', () => ({
+ authenticationApi: {
+ switchPlatform: vi.fn(),
+ },
+}));
+
+vi.mock('@/app/query-client', () => ({
+ queryClient: {
+ invalidateQueries: vi.fn(),
+ },
+}));
+
+const switchPlatform = vi.mocked(authenticationApi.switchPlatform);
+
+describe('authenticationSession', () => {
+ beforeEach(() => {
+ window.localStorage.clear();
+ window.localStorage.setItem('projectId', 'project-on-previous-platform');
+ vi.stubGlobal('location', { href: '' });
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ switchPlatform.mockReset();
+ });
+
+ it('forgets the previous project when switching to a platform where they have none', async () => {
+ switchPlatform.mockResolvedValue(
+ switchResponse({ platformId: 'platform-b', projectId: null }),
+ );
+
+ await authenticationSession.switchToPlatform('platform-b');
+
+ expect(authenticationSession.getProjectId()).toBeNull();
+ });
+
+ it('saves the project the switch lands in', async () => {
+ switchPlatform.mockResolvedValue(
+ switchResponse({ platformId: 'platform-b', projectId: 'project-b' }),
+ );
+
+ await authenticationSession.switchToPlatform('platform-b');
+
+ expect(authenticationSession.getProjectId()).toBe('project-b');
+ });
+
+ it('forgets the previous project when signing in lands where they have none', () => {
+ authenticationSession.saveResponse(
+ switchResponse({ platformId: 'platform-b', projectId: null }),
+ false,
+ );
+
+ expect(authenticationSession.getProjectId()).toBeNull();
+ });
+});
+
+function switchResponse({
+ platformId,
+ projectId,
+}: {
+ platformId: string;
+ projectId: string | null;
+}): AuthenticationResponse {
+ return {
+ id: 'user-1',
+ platformId,
+ projectId,
+ token: userToken({ platformId }),
+ platformRole: PlatformRole.MEMBER,
+ status: UserStatus.ACTIVE,
+ externalId: null,
+ verified: true,
+ firstName: 'Maya',
+ lastName: 'Doe',
+ email: '[email protected]',
+ trackEvents: false,
+ newsLetter: false,
+ };
+}
+
+function userToken({ platformId }: { platformId: string }): string {
+ const encode = (value: object): string =>
+ Buffer.from(JSON.stringify(value)).toString('base64url');
+ return [
+ encode({ alg: 'HS256', typ: 'JWT' }),
+ encode({ id: 'user-1', type: 'USER', platform: { id: platformId } }),
+ 'signature',
+ ].join('.');
+}