feat: introduce role selector when inviting members to a workspace (#18085)

This PR adds an explicit role selector to the "Invite by email" flow,
requires a role choice before sending, and stores the selected role with
each invitation. The backend now accepts and persists `roleId` on
invitations and applies it when the invite is accepted, while keeping it
optional to avoid breaking existing clients and legacy invites.

---

### Frontend

- **Settings → Members → Invite by email**
- New **Role** dropdown (same `Select` pattern as member/API key role
selectors) between the email input and Invite button.
- Roles are loaded via `SettingsRolesQueryEffect` and
`settingsAllRolesSelector`; only roles with `canBeAssignedToUsers` are
shown.
- Role is **required**: form validates `roleId` (e.g.
`z.string().min(1)`) and the Invite button is disabled until a role is
selected and emails are valid.
- `WorkspaceInviteTeam` receives `roles` as a prop from the parent;
layout is responsive (e.g. stacked on small viewports).
- **Pending invitations table**
- New **Role** column showing the invitation’s role label (or "Unknown
role" for legacy invites without `roleId`), using the same roles source
for lookup.
- **Onboarding invite step**
- When sending invites during onboarding, the workspace **default role**
is used when available (`currentWorkspace?.defaultRole?.id`), so no role
selector is added there.
- **GraphQL**
- `sendInvitations` mutation accepts optional `roleId`;
`findWorkspaceInvitations` and resend mutation responses include
`roleId` on `WorkspaceInvitation`. Frontend types (e.g.
`WorkspaceInvitation`, hook variables) updated accordingly.

---

### Backend

- **API**
- `SendInvitationsInput` has an **optional** `roleId` (UUID, nullable).
The resolver normalises `null` to `undefined` so existing callers and
legacy flows are not broken.
- **Validation (when `roleId` is provided)**
- Role checks are centralised in **RoleValidationService**
(`RoleValidationModule`, in `metadata-modules/role-validation/`). It
validates that the role exists in the workspace and has
`canBeAssignedToUsers`, and throws a permissions-style error otherwise.
This avoids circular dependencies (e.g. `RoleModule` imports
`UserWorkspaceModule`, so invite/accept flows cannot depend on
`RoleModule`).
- **Send flow:** `WorkspaceInvitationResolver` and
`WorkspaceInvitationService.sendInvitations` both call
`RoleValidationService.validateRoleAssignableToUsersOrThrow` when
`roleId` is present (resolver before calling the service; service again
before creating tokens so that **resend** also validates the stored role
and fails fast if the role was deleted or made unassignable).
- **Accept flow:**
`UserWorkspaceService.addUserToWorkspaceIfUserNotInWorkspace` uses the
same service in `resolveRoleIdForNewMember` when an invitation provides
a `roleId`, then falls back to `workspace.defaultRoleId` when not.
Role/default is resolved and validated before any user/workspace/member
creation.
- **Persistence**
- Invitation app tokens store `roleId` in `context` next to `email`
(`context: { email, roleId? }`). `generateInvitationToken` and
`createWorkspaceInvitation` accept an optional `roleId` and only add it
to `context` when defined.
- **Resend**
- Resend passes the existing invitation’s `context.roleId` into
`sendInvitations`. The service validates that role (when present) before
creating the new token, so if the role was deleted or made unassignable,
resend fails with a clear error instead of sending a broken link.
- **Response shape**
- `SendInvitationsOutput.result` remains `WorkspaceInvitation[]`. When
`usePersonalInvitation` is false we only push full invitation records
(from `castAppTokenToWorkspaceInvitationUtil`), so the result always
matches the GraphQL type (`id`, `email`, `roleId`, `expiresAt`).
- **Modules**
- `WorkspaceInvitationModule` and `UserWorkspaceModule` import
**RoleValidationModule** (not `RoleModule`) and inject
**RoleValidationService** for validation. `RoleModule` imports
`RoleValidationModule` and `RoleService` delegates to
`RoleValidationService` for the same validation where the module graph
allows.

---

### Backward compatibility

- **Optional `roleId`**: Clients that don’t send `roleId` (or send
`null`) are unchanged; invitations are created without a role and the
accept flow uses the workspace default role.
- **Legacy invitations**: App tokens with only `context.email` still
work; `context.roleId` is optional and the UI can show e.g. "Unknown
role" for those in the pending-invitations table.
This commit is contained in:
Abdullah.
2026-03-02 22:58:32 +05:00
committed by GitHub
parent 1eb284c87f
commit 20a2c3836e
30 changed files with 630 additions and 337 deletions
@@ -4,88 +4,143 @@ import { useEffect } from 'react';
import { Controller, useForm } from 'react-hook-form';
import { z } from 'zod';
import { type RoleWithPartialMembers } from '@/settings/roles/types/RoleWithPartialMembers';
import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';
import { Select } from '@/ui/input/components/Select';
import { SettingsTextInput } from '@/ui/input/components/SettingsTextInput';
import { useCreateWorkspaceInvitation } from '@/workspace-invitation/hooks/useCreateWorkspaceInvitation';
import { sanitizeEmailList } from '@/workspace/utils/sanitizeEmailList';
import { i18n } from '@lingui/core';
import { msg } from '@lingui/core/macro';
import { useLingui } from '@lingui/react/macro';
import { isDefined } from 'twenty-shared/utils';
import { IconSend } from 'twenty-ui/display';
import {
IconLock,
IconSend,
IconUser,
useIcons,
type IconComponent,
} from 'twenty-ui/display';
import { Button } from 'twenty-ui/input';
import { useCreateWorkspaceInvitation } from '@/workspace-invitation/hooks/useCreateWorkspaceInvitation';
import { MOBILE_VIEWPORT } from 'twenty-ui/theme';
const StyledContainer = styled.div`
display: flex;
flex-direction: row;
align-items: center;
gap: ${({ theme }) => theme.spacing(2)};
padding-bottom: ${({ theme }) => theme.spacing(3)};
@media (max-width: ${MOBILE_VIEWPORT}px) {
flex-wrap: wrap;
}
`;
const StyledLinkContainer = styled.div`
flex: 1;
margin-right: ${({ theme }) => theme.spacing(2)};
flex: 1 1 auto;
min-width: 0;
@media (max-width: ${MOBILE_VIEWPORT}px) {
flex: 1 1 100%;
}
`;
const StyledRoleContainer = styled.div`
flex: 0 0 130px;
min-width: 130px;
@media (max-width: ${MOBILE_VIEWPORT}px) {
flex: 1 1 100%;
}
`;
const emailsEmptyErrorMessage = msg`Emails should not be empty`;
const validationSchema = z
.object({
emails: z.string().superRefine((value, ctx) => {
if (!value.length) {
return;
const validationSchema = z.object({
emails: z.string().superRefine((value, ctx) => {
if (!value.length) {
return;
}
const emails = sanitizeEmailList(value.split(','));
if (emails.length === 0) {
ctx.addIssue({
code: 'custom',
message: i18n._(emailsEmptyErrorMessage),
});
}
const invalidEmails: string[] = [];
for (const email of emails) {
const result = z.email().safeParse(email);
if (!result.success) {
invalidEmails.push(email);
}
const emails = sanitizeEmailList(value.split(','));
if (emails.length === 0) {
ctx.addIssue({
code: 'custom',
message: i18n._(emailsEmptyErrorMessage),
});
}
const invalidEmails: string[] = [];
for (const email of emails) {
const result = z.email().safeParse(email);
if (!result.success) {
invalidEmails.push(email);
}
}
if (invalidEmails.length > 0) {
const invalidEmailsList = invalidEmails.join(', ');
ctx.addIssue({
code: 'custom',
message:
invalidEmails.length > 1
? `Invalid emails: ${invalidEmailsList}`
: `Invalid email: ${invalidEmailsList}`,
});
}
}),
})
.required();
}
if (invalidEmails.length > 0) {
const invalidEmailsList = invalidEmails.join(', ');
ctx.addIssue({
code: 'custom',
message:
invalidEmails.length > 1
? `Invalid emails: ${invalidEmailsList}`
: `Invalid email: ${invalidEmailsList}`,
});
}
}),
roleId: z.string().optional(),
});
type FormInput = {
emails: string;
roleId?: string;
};
export const WorkspaceInviteTeam = () => {
type WorkspaceInviteTeamProps = {
roles: RoleWithPartialMembers[];
};
export const WorkspaceInviteTeam = ({ roles }: WorkspaceInviteTeamProps) => {
const { t } = useLingui();
const { getIcon } = useIcons();
const { enqueueSuccessSnackBar, enqueueErrorSnackBar } = useSnackBar();
const { sendInvitation } = useCreateWorkspaceInvitation();
const roleOptions: Array<{
label: string;
value: string;
Icon?: IconComponent;
}> = roles
.filter((role) => role.canBeAssignedToUsers)
.map((role) => ({
label: role.label,
value: role.id,
Icon: getIcon(role.icon) ?? IconUser,
}));
const emptyRoleOption = {
label: t`Default role`,
value: '',
Icon: IconLock,
};
const { reset, handleSubmit, control, formState, watch } = useForm<FormInput>(
{
mode: 'onSubmit',
resolver: zodResolver(validationSchema),
defaultValues: {
emails: '',
roleId: '',
},
},
);
const isEmailsEmpty = !watch('emails');
const submit = handleSubmit(async ({ emails }) => {
const submit = handleSubmit(async ({ emails, roleId }) => {
const emailsList = sanitizeEmailList(emails.split(','));
const { data } = await sendInvitation({ emails: emailsList });
const { data } = await sendInvitation({
emails: emailsList,
...(roleId ? { roleId } : {}),
});
if (!isDefined(data)) {
return;
}
@@ -142,6 +197,26 @@ export const WorkspaceInviteTeam = () => {
}}
/>
</StyledLinkContainer>
<StyledRoleContainer>
<Controller
name="roleId"
control={control}
render={({ field: { value, onChange } }) => {
return (
<Select
dropdownId="workspace-invite-team-role"
options={roleOptions}
emptyOption={emptyRoleOption}
value={value}
onChange={onChange}
withSearchInput
fullWidth
disabled={roleOptions.length === 0}
/>
);
}}
/>
</StyledRoleContainer>
<Button
Icon={IconSend}
variant="primary"