SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
refactor(onboarding-questionaire): use new invite members component (#11875)
Vinicius Lourençoba49b28c5a04
diff --git a/frontend/src/components/InviteMembers/__tests__/InviteMembers.submission.test.tsx b/frontend/src/components/InviteMembers/__tests__/InviteMembers.submission.test.tsxindex 4869dd5f38..b86c0eafca 100644--- a/frontend/src/components/InviteMembers/__tests__/InviteMembers.submission.test.tsx+++ b/frontend/src/components/InviteMembers/__tests__/InviteMembers.submission.test.tsx@@ -167,6 +167,7 @@ describe('InviteMembers - Submission', () => {success: false,}),]),+ expect.any(Array),);});});@@ -243,6 +244,7 @@ describe('InviteMembers - Submission', () => {error: 'User already exists',}),]),+ expect.any(Array),);await expect(diff --git a/frontend/src/components/InviteMembers/types.ts b/frontend/src/components/InviteMembers/types.tsindex e3028175b4..787b1617fd 100644--- a/frontend/src/components/InviteMembers/types.ts+++ b/frontend/src/components/InviteMembers/types.ts@@ -22,9 +22,9 @@ export interface FooterRenderProps {export interface UseInviteMembersOptions {initialRowCount?: number;- onSuccess?: () => void;- onPartialSuccess?: (results: InviteResult[]) => void;- onAllFailed?: (results: InviteResult[]) => void;+ onSuccess?: (results: InviteResult[], rows: InviteMemberRow[]) => void;+ onPartialSuccess?: (results: InviteResult[], rows: InviteMemberRow[]) => void;+ onAllFailed?: (results: InviteResult[], rows: InviteMemberRow[]) => void;}export interface UseInviteMembersReturn {@@ -56,9 +56,9 @@ export interface InviteMembersProps {showHeader?: boolean;showAddButton?: boolean;- onSuccess?: () => void;- onPartialSuccess?: (results: InviteResult[]) => void;- onAllFailed?: (results: InviteResult[]) => void;+ onSuccess?: (results: InviteResult[], rows: InviteMemberRow[]) => void;+ onPartialSuccess?: (results: InviteResult[], rows: InviteMemberRow[]) => void;+ onAllFailed?: (results: InviteResult[], rows: InviteMemberRow[]) => void;renderFooter?: (props: FooterRenderProps) => ReactNode;}diff --git a/frontend/src/components/InviteMembers/useInviteMembers.ts b/frontend/src/components/InviteMembers/useInviteMembers.tsindex 2faf0d8243..00276263fb 100644--- a/frontend/src/components/InviteMembers/useInviteMembers.ts+++ b/frontend/src/components/InviteMembers/useInviteMembers.ts@@ -207,11 +207,11 @@ export function useInviteMembers(const successes = results.filter((r) => r.success);if (failures.length === 0) {- onSuccess?.();+ onSuccess?.(results, touched);} else if (successes.length > 0) {- onPartialSuccess?.(results);+ onPartialSuccess?.(results, touched);} else {- onAllFailed?.(results);+ onAllFailed?.(results, touched);}return results;diff --git a/frontend/src/container/OnboardingQuestionaire/InviteTeamMembers/InviteTeamMembers.tsx b/frontend/src/container/OnboardingQuestionaire/InviteTeamMembers/InviteTeamMembers.tsxindex 2d130747e2..2d43e540ec 100644--- a/frontend/src/container/OnboardingQuestionaire/InviteTeamMembers/InviteTeamMembers.tsx+++ b/frontend/src/container/OnboardingQuestionaire/InviteTeamMembers/InviteTeamMembers.tsx@@ -1,26 +1,12 @@-import { useCallback, useEffect, useState } from 'react';-import { useMutation } from 'react-query';+import { useMemo } from 'react';+import { ArrowRight, LoaderCircle } from '@signozhq/icons';import { Button } from '@signozhq/ui/button';-import { Callout } from '@signozhq/ui/callout';-import { Input } from '@signozhq/ui/input';-import { Select } from 'antd';-import { Typography } from '@signozhq/ui/typography';import logEvent from 'api/common/logEvent';-import inviteUsers from 'api/v1/invite/bulk/create';-import AuthError from 'components/AuthError/AuthError';+import InviteMembers from 'components/InviteMembers/InviteMembers';+import { InviteMemberRow, InviteResult } from 'components/InviteMembers/types';+import { useRoles } from 'components/RolesSelect/RolesSelect';import { useNotifications } from 'hooks/useNotifications';-import { cloneDeep, debounce } from 'lodash-es';-import {- ArrowRight,- ChevronDown,- CircleAlert,- LoaderCircle,- Plus,- Trash2,-} from '@signozhq/icons';-import APIError from 'types/api/error';import { getBaseUrl } from 'utils/basePath';-import { v4 as uuid } from 'uuid';import { OnboardingQuestionHeader } from '../OnboardingQuestionHeader';@@ -36,101 +22,41 @@ interface TeamMember {interface InviteTeamMembersProps {isLoading: boolean;- teamMembers: TeamMember[] | null;- setTeamMembers: (teamMembers: TeamMember[]) => void;onNext: () => void;}function InviteTeamMembers({isLoading,- teamMembers,- setTeamMembers,onNext,}: InviteTeamMembersProps): JSX.Element {- const [teamMembersToInvite, setTeamMembersToInvite] = useState<- TeamMember[] | null- >(teamMembers);- const [emailValidity, setEmailValidity] = useState<Record<string, boolean>>(- {},- );- const [hasInvalidEmails, setHasInvalidEmails] = useState<boolean>(false);- const [hasInvalidRoles, setHasInvalidRoles] = useState<boolean>(false);- const [inviteError, setInviteError] = useState<APIError | null>(null);const { notifications } = useNotifications();+ const { roles } = useRoles();- const defaultTeamMember: TeamMember = {- email: '',- role: '',- name: '',- frontendBaseUrl: getBaseUrl(),- id: '',- };-- useEffect(() => {- if (teamMembers === null) {- const initialTeamMembers = Array.from({ length: 3 }, () => ({- ...defaultTeamMember,- id: uuid(),- }));-- setTeamMembersToInvite(initialTeamMembers);- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [teamMembers]);-- const handleAddTeamMember = (): void => {- const newTeamMember = {- ...defaultTeamMember,- id: uuid(),- };- setTeamMembersToInvite((prev) => [...(prev || []), newTeamMember]);- };-- const handleRemoveTeamMember = (id: string): void => {- setTeamMembersToInvite((prev) => (prev || []).filter((m) => m.id !== id));- };-- const isMemberTouched = (member: TeamMember): boolean =>- member.email.trim() !== '' ||- Boolean(member.role && member.role.trim() !== '');-- const validateAllUsers = (): boolean => {- let isValid = true;- let hasEmailErrors = false;- let hasRoleErrors = false;-- const updatedEmailValidity: Record<string, boolean> = {};-- const touchedMembers = teamMembersToInvite?.filter(isMemberTouched) ?? [];-- touchedMembers?.forEach((member) => {- const emailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(member.email);- const roleValid = Boolean(member.role && member.role.trim() !== '');-- if (!emailValid || !member.email) {- isValid = false;- hasEmailErrors = true;- }- if (!roleValid) {- isValid = false;- hasRoleErrors = true;- }-- if (member.id) {- updatedEmailValidity[member.id] = emailValid;+ const roleIdToName = useMemo(() => {+ const map: Record<string, string> = {};+ roles.forEach((role) => {+ if (role.id && role.name) {+ map[role.id] = role.name;}});-- setEmailValidity(updatedEmailValidity);- setHasInvalidEmails(hasEmailErrors);- setHasInvalidRoles(hasRoleErrors);-- return isValid;- };-- const handleInviteUsersSuccess = (): void => {+ return map;+ }, [roles]);++ const toTeamMembers = (rows: InviteMemberRow[]): TeamMember[] =>+ rows.map((row) => ({+ email: row.email,+ role: roleIdToName[row.roleId] ?? row.roleId,+ name: '',+ frontendBaseUrl: getBaseUrl(),+ id: row.id,+ }));++ const handleSuccess = (+ _results: InviteResult[],+ rows: InviteMemberRow[],+ ): void => {logEvent('Org Onboarding: Invite Team Members Success', {- teamMembers: teamMembersToInvite,+ teamMembers: toTeamMembers(rows),});notifications.success({message: 'Invites sent successfully!',@@ -140,125 +66,34 @@ function InviteTeamMembers({}, 1000);};- const { mutate: sendInvites, isLoading: isSendingInvites } = useMutation(- inviteUsers,- {- onSuccess: (): void => {- handleInviteUsersSuccess();- },- onError: (error: APIError): void => {- logEvent('Org Onboarding: Invite Team Members Failed', {- teamMembers: teamMembersToInvite,- });- setInviteError(error);- },- },- );-- const handleNext = (): void => {- if (validateAllUsers()) {- setTeamMembers(teamMembersToInvite?.filter(isMemberTouched) ?? []);- setHasInvalidEmails(false);- setHasInvalidRoles(false);- setInviteError(null);- sendInvites({- invites: teamMembersToInvite?.filter(isMemberTouched) ?? [],- });- }- };-- // eslint-disable-next-line react-hooks/exhaustive-deps- const debouncedValidateEmail = useCallback(- debounce((email: string, memberId: string, updatedMembers: TeamMember[]) => {- const isValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);- setEmailValidity((prev) => ({ ...prev, [memberId]: isValid }));-- // Clear hasInvalidEmails only when ALL emails are valid- if (hasInvalidEmails) {- const allEmailsValid = updatedMembers.every(- (m) => m.email && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(m.email),- );- if (allEmailsValid) {- setHasInvalidEmails(false);- }- }- }, 500),- [hasInvalidEmails],- );-- const handleEmailChange = useCallback(- (e: React.ChangeEvent<HTMLInputElement>, member: TeamMember): void => {- const { value } = e.target;- const updatedMembers = cloneDeep(teamMembersToInvite || []);-- const memberToUpdate = updatedMembers.find((m) => m.id === member.id);- if (memberToUpdate && member.id) {- memberToUpdate.email = value;- setTeamMembersToInvite(updatedMembers);- debouncedValidateEmail(value, member.id, updatedMembers);- // Clear API error when user starts typing- if (inviteError) {- setInviteError(null);- }- }- },- [debouncedValidateEmail, inviteError, teamMembersToInvite],- );-- const createEmailChangeHandler = useCallback(- (member: TeamMember) =>- (e: React.ChangeEvent<HTMLInputElement>): void => {- handleEmailChange(e, member);- },- [handleEmailChange],- );-- const handleRoleChange = (role: string, member: TeamMember): void => {- const updatedMembers = cloneDeep(teamMembersToInvite || []);- const memberToUpdate = updatedMembers.find((m) => m.id === member.id);- if (memberToUpdate && member.id) {- memberToUpdate.role = role;- setTeamMembersToInvite(updatedMembers);-- // Clear errors when user selects a role- if (hasInvalidRoles) {- // Check if all roles are now valid- const allRolesValid = updatedMembers.every(- (m) => m.role && m.role.trim() !== '',- );- if (allRolesValid) {- setHasInvalidRoles(false);- }- }- if (inviteError) {- setInviteError(null);- }- }+ const handlePartialSuccess = (+ _results: InviteResult[],+ rows: InviteMemberRow[],+ ): void => {+ logEvent('Org Onboarding: Invite Team Members Partial Success', {+ teamMembers: toTeamMembers(rows),+ });+ notifications.warning({+ message: 'Some invites failed. Check the errors above.',+ });};- const getValidationErrorMessage = (): string => {- if (hasInvalidEmails && hasInvalidRoles) {- return 'Please enter valid emails and select roles for team members';- }- if (hasInvalidEmails) {- return 'Please enter valid emails for team members';- }- return 'Please select roles for team members';+ const handleAllFailed = (+ _results: InviteResult[],+ rows: InviteMemberRow[],+ ): void => {+ logEvent('Org Onboarding: Invite Team Members Failed', {+ teamMembers: toTeamMembers(rows),+ });};const handleDoLater = (): void => {logEvent('Org Onboarding: Clicked Do Later', {currentPageID: 4,});-onNext();};- const hasInvites =- (teamMembersToInvite?.filter(isMemberTouched) ?? []).length > 0;- const isButtonDisabled = isSendingInvites || isLoading;- const isInviteButtonDisabled = isButtonDisabled || !hasInvites;-return (<div className="questions-container"><OnboardingQuestionHeader@@ -273,126 +108,52 @@ function InviteTeamMembers({Invite your team to the SigNoz workspace</div>- <div className="invite-team-members-table">- <div className="invite-team-members-table-header">- <div className="table-header-cell email-header">Email address</div>- <div className="table-header-cell role-header">Roles</div>- <div className="table-header-cell action-header" />- </div>-- <div className="invite-team-members-container">- {teamMembersToInvite?.map((member) => (- <div className="team-member-row" key={member.id}>- <div className="team-member-cell email-cell">- <Input- placeholder="e.g. [email protected]"- value={member.email}- type="email"- id={`email-input-${member.id}`}- name={`email-input-${member.id}`}- required- autoComplete="off"- className="team-member-email-input"- onChange={createEmailChangeHandler(member)}- />- {member.id &&- emailValidity[member.id] === false &&- member.email.trim() !== '' && (- <Typography.Text className="email-error-message">- Invalid email address- </Typography.Text>- )}- </div>- <div className="team-member-cell role-cell">- <Select- value={member.role || undefined}- onChange={(value): void => handleRoleChange(value, member)}- className="team-member-role-select"- placeholder="Select roles"- suffixIcon={<ChevronDown size={14} />}- >- <Select.Option value="VIEWER">Viewer</Select.Option>- <Select.Option value="EDITOR">Editor</Select.Option>- <Select.Option value="ADMIN">Admin</Select.Option>- </Select>- </div>- <div className="team-member-cell action-cell">- {teamMembersToInvite && teamMembersToInvite.length > 1 && (- <Button- variant="ghost"- color="secondary"- className="remove-team-member-button"- onClick={(): void => handleRemoveTeamMember(member.id)}- aria-label="Remove team member"- >- <Trash2 size={12} />- </Button>- )}- </div>+ <InviteMembers+ onSuccess={handleSuccess}+ onPartialSuccess={handlePartialSuccess}+ onAllFailed={handleAllFailed}+ showHeader+ renderFooter={({ submit, canSubmit, isSubmitting }): JSX.Element => {+ const isButtonDisabled = isSubmitting || isLoading;+ const isInviteButtonDisabled = isButtonDisabled || !canSubmit;++ return (+ <div className="onboarding-buttons-container">+ <Button+ variant="solid"+ color="primary"+ className={`onboarding-next-button ${+ isInviteButtonDisabled ? 'disabled' : ''+ }`}+ onClick={submit}+ disabled={isInviteButtonDisabled}+ data-testid="send-invites-button"+ suffix={+ isButtonDisabled ? (+ <LoaderCircle className="animate-spin" size={12} />+ ) : (+ <ArrowRight size={12} />+ )+ }+ >+ Send Invites+ </Button>+ <Button+ variant="ghost"+ color="secondary"+ className="onboarding-do-later-button"+ onClick={handleDoLater}+ disabled={isButtonDisabled}+ data-testid="do-later-button"+ >+ I'll do this later+ </Button></div>- ))}- </div>-- <div className="invite-team-members-add-another-member-container">- <Button- variant="dashed"- color="secondary"- className="add-another-member-button"- prefix={<Plus size={12} />}- onClick={handleAddTeamMember}- >- Add another- </Button>- </div>- </div>+ );+ }}+ /></div></div>-- {(hasInvalidEmails || hasInvalidRoles) && (- <Callout- type="error"- size="small"- showIcon- icon={<CircleAlert size={12} />}- className="invite-team-members-error-callout"- >- {getValidationErrorMessage()}- </Callout>- )}-- {inviteError && !hasInvalidEmails && !hasInvalidRoles && (- <AuthError error={inviteError} />- )}-- <div className="onboarding-buttons-container">- <Button- variant="solid"- color="primary"- className={`onboarding-next-button ${- isInviteButtonDisabled ? 'disabled' : ''- }`}- onClick={handleNext}- disabled={isInviteButtonDisabled}- suffix={- isButtonDisabled ? (- <LoaderCircle className="animate-spin" size={12} />- ) : (- <ArrowRight size={12} />- )- }- >- Send Invites- </Button>- <Button- variant="ghost"- color="secondary"- className="onboarding-do-later-button"- onClick={handleDoLater}- disabled={isButtonDisabled}- >- I'll do this later- </Button>- </div></div></div>);diff --git a/frontend/src/container/OnboardingQuestionaire/InviteTeamMembers/__tests__/InviteTeamMembers.test.tsx b/frontend/src/container/OnboardingQuestionaire/InviteTeamMembers/__tests__/InviteTeamMembers.test.tsxindex faba3b9986..843455ba95 100644--- a/frontend/src/container/OnboardingQuestionaire/InviteTeamMembers/__tests__/InviteTeamMembers.test.tsx+++ b/frontend/src/container/OnboardingQuestionaire/InviteTeamMembers/__tests__/InviteTeamMembers.test.tsx@@ -1,97 +1,86 @@-import { rest, server } from 'mocks-server/server';import {- fireEvent,- render,- screen,- userEvent,- waitFor,-} from 'tests/test-utils';+ InviteMemberRow,+ InviteMembersProps,+ InviteResult,+} from 'components/InviteMembers/types';+import logEvent from 'api/common/logEvent';+import { render, screen, userEvent } from 'tests/test-utils';import InviteTeamMembers from '../InviteTeamMembers';-const mockNotificationSuccess = jest.fn() as jest.MockedFunction<- (args: { message: string }) => void->;-const mockNotificationError = jest.fn() as jest.MockedFunction<- (args: { message: string }) => void->;+const mockNotificationSuccess = jest.fn();+const mockNotificationWarning = jest.fn();jest.mock('hooks/useNotifications', () => ({useNotifications: (): any => ({notifications: {success: mockNotificationSuccess,- error: mockNotificationError,+ warning: mockNotificationWarning,},}),}));-const INVITE_USERS_ENDPOINT = '*/api/v1/invite/bulk';--interface TeamMember {- email: string;- role: string;- name: string;- frontendBaseUrl: string;- id: string;-}+jest.mock('api/common/logEvent', () => jest.fn());++jest.mock('components/RolesSelect/RolesSelect', () => ({+ useRoles: (): any => ({+ roles: [+ { id: 'role-viewer-id', name: 'VIEWER' },+ { id: 'role-editor-id', name: 'EDITOR' },+ { id: 'role-admin-id', name: 'ADMIN' },+ ],+ isLoading: false,+ isError: false,+ error: undefined,+ refetch: jest.fn(),+ }),+}));-interface InviteRequestBody {- invites: { email: string; role: string }[];-}+jest.mock('utils/basePath', () => ({+ ...jest.requireActual('utils/basePath'),+ getBaseUrl: (): string => 'http://localhost:3301',+}));-interface RenderProps {- isLoading?: boolean;- teamMembers?: TeamMember[] | null;-}+let mockInviteMembersProps: InviteMembersProps | null = null;++jest.mock('components/InviteMembers/InviteMembers', () => {+ return function MockInviteMembers(props: InviteMembersProps): JSX.Element {+ mockInviteMembersProps = props;+ return (+ <div data-testid="mock-invite-members">+ {props.renderFooter?.({+ submit: jest.fn().mockResolvedValue([]),+ reset: jest.fn(),+ canSubmit: true,+ isSubmitting: false,+ touchedCount: 0,+ })}+ </div>+ );+ };+});-const mockOnNext = jest.fn() as jest.MockedFunction<() => void>;-const mockSetTeamMembers = jest.fn() as jest.MockedFunction<- (members: TeamMember[]) => void->;+const mockOnNext = jest.fn();function renderComponent({isLoading = false,- teamMembers = null,-}: RenderProps = {}): ReturnType<typeof render> {- return render(- <InviteTeamMembers- isLoading={isLoading}- teamMembers={teamMembers}- setTeamMembers={mockSetTeamMembers}- onNext={mockOnNext}- />,- );-}--async function selectRole(- user: ReturnType<typeof userEvent.setup>,- selectIndex: number,- optionLabel: string,-): Promise<void> {- const placeholders = screen.getAllByText(/select roles/i);- await user.click(placeholders[selectIndex]);- const optionContent = await screen.findByText(optionLabel);- fireEvent.click(optionContent);+}: { isLoading?: boolean } = {}): ReturnType<typeof render> {+ return render(<InviteTeamMembers isLoading={isLoading} onNext={mockOnNext} />);}describe('InviteTeamMembers', () => {beforeEach(() => {jest.clearAllMocks();-- server.use(- rest.post(INVITE_USERS_ENDPOINT, (_, res, ctx) =>- res(ctx.status(200), ctx.json({ status: 'success' })),- ),- );+ jest.useFakeTimers();+ mockInviteMembersProps = null;});afterEach(() => {jest.useRealTimers();- server.resetHandlers();});- describe('Initial rendering', () => {- it('renders the page header, column labels, default rows, and action buttons', () => {+ describe('rendering', () => {+ it('renders header and InviteMembers component', () => {renderComponent();expect(@@ -100,11 +89,20 @@ describe('InviteTeamMembers', () => {expect(screen.getByText(/signoz is a lot more useful with collaborators/i),).toBeInTheDocument();- expect(- screen.getAllByPlaceholderText(/e\.g\. john@signoz\.io/i),- ).toHaveLength(3);- expect(screen.getByText('Email address')).toBeInTheDocument();- expect(screen.getByText('Roles')).toBeInTheDocument();+ expect(screen.getByTestId('mock-invite-members')).toBeInTheDocument();+ });++ it('passes showHeader=true to InviteMembers', () => {+ renderComponent();++ expect(mockInviteMembersProps?.showHeader).toBe(true);+ });+ });++ describe('footer buttons', () => {+ it('renders Send Invites and Do Later buttons', () => {+ renderComponent();+expect(screen.getByRole('button', { name: /send invites/i }),).toBeInTheDocument();@@ -113,7 +111,7 @@ describe('InviteTeamMembers', () => {).toBeInTheDocument();});- it('disables both action buttons while isLoading is true', () => {+ it('disables buttons when isLoading=true', () => {renderComponent({ isLoading: true });expect(screen.getByRole('button', { name: /send invites/i })).toBeDisabled();@@ -121,355 +119,181 @@ describe('InviteTeamMembers', () => {screen.getByRole('button', { name: /i'll do this later/i }),).toBeDisabled();});- });- describe('Row management', () => {- it('adds a new empty row when "Add another" is clicked', async () => {- const user = userEvent.setup({ pointerEventsCheck: 0 });- renderComponent();-- expect(- screen.getAllByPlaceholderText(/e\.g\. john@signoz\.io/i),- ).toHaveLength(3);-- await user.click(screen.getByRole('button', { name: /add another/i }));-- expect(- screen.getAllByPlaceholderText(/e\.g\. john@signoz\.io/i),- ).toHaveLength(4);- });-- it('removes the correct row when its trash icon is clicked', async () => {- const user = userEvent.setup({ pointerEventsCheck: 0 });- renderComponent();-- const emailInputs = screen.getAllByPlaceholderText(- /e\.g\. john@signoz\.io/i,+ it('disables Send Invites when canSubmit=false from InviteMembers', () => {+ const { unmount } = renderComponent();+ unmount();++ const { getByTestId } = render(+ mockInviteMembersProps?.renderFooter?.({+ submit: jest.fn().mockResolvedValue([]),+ reset: jest.fn(),+ canSubmit: false,+ isSubmitting: false,+ touchedCount: 0,+ }) as JSX.Element,);- await user.type(emailInputs[0], '[email protected]');- await screen.findByDisplayValue('[email protected]');-- await user.click(- screen.getAllByRole('button', { name: /remove team member/i })[0],- );-- await waitFor(() => {- expect(- screen.queryByDisplayValue('[email protected]'),- ).not.toBeInTheDocument();- expect(- screen.getAllByPlaceholderText(/e\.g\. john@signoz\.io/i),- ).toHaveLength(2);- });- });- it('hides remove buttons when only one row remains', async () => {- renderComponent();- const user = userEvent.setup({ pointerEventsCheck: 0 });-- let removeButtons = screen.getAllByRole('button', {- name: /remove team member/i,- });- while (removeButtons.length > 0) {- await user.click(removeButtons[0]);- removeButtons = screen.queryAllByRole('button', {- name: /remove team member/i,- });- }-- expect(- screen.queryByRole('button', { name: /remove team member/i }),- ).not.toBeInTheDocument();+ expect(getByTestId('send-invites-button')).toBeDisabled();+ expect(getByTestId('do-later-button')).not.toBeDisabled();});- });- describe('Inline email validation', () => {- it('shows an inline error after typing an invalid email and clears it when a valid email is entered', async () => {- jest.useFakeTimers();- const user = userEvent.setup({- advanceTimers: (ms) => jest.advanceTimersByTime(ms),- });- renderComponent();-- const [firstInput] = screen.getAllByPlaceholderText(- /e\.g\. john@signoz\.io/i,+ it('disables buttons when isSubmitting=true from InviteMembers', () => {+ const { unmount } = renderComponent();+ unmount();++ const { getByTestId } = render(+ mockInviteMembersProps?.renderFooter?.({+ submit: jest.fn().mockResolvedValue([]),+ reset: jest.fn(),+ canSubmit: true,+ isSubmitting: true,+ touchedCount: 0,+ }) as JSX.Element,);- await user.type(firstInput, 'not-an-email');- jest.advanceTimersByTime(600);- await waitFor(() => {- expect(screen.getByText(/invalid email address/i)).toBeInTheDocument();- });-- await user.clear(firstInput);- await user.type(firstInput, '[email protected]');- jest.advanceTimersByTime(600);- await waitFor(() => {- expect(- screen.queryByText(/invalid email address/i),- ).not.toBeInTheDocument();- });- });-- it('does not show an inline error when the field is cleared back to empty', async () => {- jest.useFakeTimers();- const user = userEvent.setup({- advanceTimers: (ms) => jest.advanceTimersByTime(ms),- });- renderComponent();-- const [firstInput] = screen.getAllByPlaceholderText(- /e\.g\. john@signoz\.io/i,- );- await user.type(firstInput, 'a');- await user.clear(firstInput);- jest.advanceTimersByTime(600);-- await waitFor(() => {- expect(- screen.queryByText(/invalid email address/i),- ).not.toBeInTheDocument();- });+ expect(getByTestId('send-invites-button')).toBeDisabled();+ expect(getByTestId('do-later-button')).toBeDisabled();});});- describe('Validation callout on Complete', () => {- it('shows the correct callout message for each combination of email/role validity', async () => {- const user = userEvent.setup({ pointerEventsCheck: 0, delay: null });+ describe('handleSuccess callback', () => {+ it('logs event with teamMembers in correct shape, shows success notification, and calls onNext after delay', () => {renderComponent();- const removeButtons = screen.getAllByRole('button', {- name: /remove team member/i,- });- await user.click(removeButtons[0]);- await user.click(- screen.getAllByRole('button', { name: /remove team member/i })[0],- );-- const [firstInput] = screen.getAllByPlaceholderText(- /e\.g\. john@signoz\.io/i,- );-- await user.type(firstInput, 'bad-email');- await user.click(screen.getByRole('button', { name: /send invites/i }));- await waitFor(() => {- expect(- screen.getByText(- /please enter valid emails and select roles for team members/i,- ),- ).toBeInTheDocument();- expect(- screen.queryByText(/please enter valid emails for team members/i),- ).not.toBeInTheDocument();- expect(- screen.queryByText(/please select roles for team members/i),- ).not.toBeInTheDocument();- });-- await selectRole(user, 0, 'Viewer');- await user.click(screen.getByRole('button', { name: /send invites/i }));- await waitFor(() => {- expect(- screen.getByText(/please enter valid emails for team members/i),- ).toBeInTheDocument();- expect(- screen.queryByText(/please select roles for team members/i),- ).not.toBeInTheDocument();- expect(- screen.queryByText(/please enter valid emails and select roles/i),- ).not.toBeInTheDocument();- });-- await user.clear(firstInput);- await user.type(firstInput, '[email protected]');- await user.click(screen.getByRole('button', { name: /add another/i }));- const allInputs = screen.getAllByPlaceholderText(/e\.g\. john@signoz\.io/i);- await user.type(allInputs[1], '[email protected]');- await user.click(screen.getByRole('button', { name: /send invites/i }));- await waitFor(() => {- expect(- screen.getByText(/please select roles for team members/i),- ).toBeInTheDocument();- expect(- screen.queryByText(/please enter valid emails for team members/i),- ).not.toBeInTheDocument();- expect(- screen.queryByText(/please enter valid emails and select roles/i),- ).not.toBeInTheDocument();- });- }, 15000);-- it('treats whitespace as untouched, clears the callout on fix-and-resubmit, and clears role error on role select', async () => {- const user = userEvent.setup({ pointerEventsCheck: 0, delay: null });- renderComponent();-- const removeButtons = screen.getAllByRole('button', {- name: /remove team member/i,- });- await user.click(removeButtons[0]);- await user.click(- screen.getAllByRole('button', { name: /remove team member/i })[0],- );-- const [firstInput] = screen.getAllByPlaceholderText(- /e\.g\. john@signoz\.io/i,+ const mockResults: InviteResult[] = [+ { email: '[email protected]', success: true },+ { email: '[email protected]', success: true },+ ];+ const mockRows: InviteMemberRow[] = [+ { id: 'row-1', email: '[email protected]', roleId: 'role-viewer-id' },+ { id: 'row-2', email: '[email protected]', roleId: 'role-editor-id' },+ ];+ mockInviteMembersProps?.onSuccess?.(mockResults, mockRows);++ expect(logEvent).toHaveBeenCalledWith(+ 'Org Onboarding: Invite Team Members Success',+ {+ teamMembers: [+ {+ email: '[email protected]',+ role: 'VIEWER',+ name: '',+ frontendBaseUrl: 'http://localhost:3301',+ id: 'row-1',+ },+ {+ email: '[email protected]',+ role: 'EDITOR',+ name: '',+ frontendBaseUrl: 'http://localhost:3301',+ id: 'row-2',+ },+ ],+ },);-- await user.type(firstInput, ' ');- await user.click(screen.getByRole('button', { name: /send invites/i }));- await waitFor(() => {- expect(- screen.queryByText(/please enter valid emails/i),- ).not.toBeInTheDocument();- expect(screen.queryByText(/please select roles/i)).not.toBeInTheDocument();+ expect(mockNotificationSuccess).toHaveBeenCalledWith({+ message: 'Invites sent successfully!',});- await user.clear(firstInput);- await user.type(firstInput, 'bad-email');- await user.click(screen.getByRole('button', { name: /send invites/i }));- await waitFor(() => {- expect(- screen.getByText(- /please enter valid emails and select roles for team members/i,- ),- ).toBeInTheDocument();- expect(- screen.queryByText(/please enter valid emails for team members/i),- ).not.toBeInTheDocument();- expect(- screen.queryByText(/please select roles for team members/i),- ).not.toBeInTheDocument();- });-- await user.clear(firstInput);- await user.type(firstInput, '[email protected]');- await selectRole(user, 0, 'Admin');- await user.click(screen.getByRole('button', { name: /send invites/i }));- await waitFor(() => {- expect(- screen.queryByText(/please enter valid emails and select roles/i),- ).not.toBeInTheDocument();- expect(- screen.queryByText(/please enter valid emails for team members/i),- ).not.toBeInTheDocument();- expect(- screen.queryByText(/please select roles for team members/i),- ).not.toBeInTheDocument();- });-- await waitFor(() => expect(mockOnNext).toHaveBeenCalledTimes(1), {- timeout: 1200,- });- }, 15000);-- it('disables the Send Invites button when all rows are untouched (empty)', async () => {- const user = userEvent.setup({ pointerEventsCheck: 0 });- renderComponent();-- const sendInvitesBtn = screen.getByRole('button', { name: /send invites/i });- expect(sendInvitesBtn).toBeDisabled();-- // Type something to make a row touched- const [firstInput] = screen.getAllByPlaceholderText(- /e\.g\. john@signoz\.io/i,- );- await user.type(firstInput, 'a');-- expect(sendInvitesBtn).not.toBeDisabled();+ expect(mockOnNext).not.toHaveBeenCalled();+ jest.advanceTimersByTime(1000);+ expect(mockOnNext).toHaveBeenCalledTimes(1);});});- describe('API integration', () => {- it('only sends touched (non-empty) rows — empty rows are excluded from the invite payload', async () => {- let capturedBody: InviteRequestBody | null = null;-- server.use(- rest.post(INVITE_USERS_ENDPOINT, async (req, res, ctx) => {- capturedBody = await req.json<InviteRequestBody>();- return res(ctx.status(200), ctx.json({ status: 'success' }));- }),- );-- const user = userEvent.setup({ pointerEventsCheck: 0 });+ describe('handlePartialSuccess callback', () => {+ it('logs event with teamMembers in correct shape and shows warning notification', () => {renderComponent();- const [firstInput] = screen.getAllByPlaceholderText(- /e\.g\. john@signoz\.io/i,+ const mockResults: InviteResult[] = [+ { email: '[email protected]', success: true },+ { email: '[email protected]', success: false, error: 'Already exists' },+ ];+ const mockRows: InviteMemberRow[] = [+ { id: 'row-1', email: '[email protected]', roleId: 'role-viewer-id' },+ { id: 'row-2', email: '[email protected]', roleId: 'role-admin-id' },+ ];+ mockInviteMembersProps?.onPartialSuccess?.(mockResults, mockRows);++ expect(logEvent).toHaveBeenCalledWith(+ 'Org Onboarding: Invite Team Members Partial Success',+ {+ teamMembers: [+ {+ email: '[email protected]',+ role: 'VIEWER',+ name: '',+ frontendBaseUrl: 'http://localhost:3301',+ id: 'row-1',+ },+ {+ email: '[email protected]',+ role: 'ADMIN',+ name: '',+ frontendBaseUrl: 'http://localhost:3301',+ id: 'row-2',+ },+ ],+ },);- await user.type(firstInput, '[email protected]');- await selectRole(user, 0, 'Admin');- await user.click(screen.getByRole('button', { name: /send invites/i }));-- await waitFor(() => {- expect(capturedBody).not.toBeNull();- expect(capturedBody?.invites).toHaveLength(1);- expect(capturedBody?.invites[0]).toMatchObject({- email: '[email protected]',- role: 'ADMIN',- });- });- await waitFor(() => expect(mockOnNext).toHaveBeenCalled(), {- timeout: 1200,+ expect(mockNotificationWarning).toHaveBeenCalledWith({+ message: 'Some invites failed. Check the errors above.',});});+ });- it('calls the invite API, shows a success notification, and calls onNext after the 1 s delay', async () => {- const user = userEvent.setup({ pointerEventsCheck: 0 });+ describe('handleAllFailed callback', () => {+ it('logs event with teamMembers in correct shape', () => {renderComponent();- const [firstInput] = screen.getAllByPlaceholderText(- /e\.g\. john@signoz\.io/i,- );- await user.type(firstInput, '[email protected]');- await selectRole(user, 0, 'Admin');- await user.click(screen.getByRole('button', { name: /send invites/i }));-- await waitFor(() => {- expect(mockNotificationSuccess).toHaveBeenCalledWith(- expect.objectContaining({ message: 'Invites sent successfully!' }),- );- });-- await waitFor(- () => {- expect(mockOnNext).toHaveBeenCalledTimes(1);+ const mockResults: InviteResult[] = [+ { email: '[email protected]', success: false, error: 'Error 1' },+ { email: '[email protected]', success: false, error: 'Error 2' },+ ];+ const mockRows: InviteMemberRow[] = [+ { id: 'row-1', email: '[email protected]', roleId: 'role-editor-id' },+ { id: 'row-2', email: '[email protected]', roleId: 'role-viewer-id' },+ ];+ mockInviteMembersProps?.onAllFailed?.(mockResults, mockRows);++ expect(logEvent).toHaveBeenCalledWith(+ 'Org Onboarding: Invite Team Members Failed',+ {+ teamMembers: [+ {+ email: '[email protected]',+ role: 'EDITOR',+ name: '',+ frontendBaseUrl: 'http://localhost:3301',+ id: 'row-1',+ },+ {+ email: '[email protected]',+ role: 'VIEWER',+ name: '',+ frontendBaseUrl: 'http://localhost:3301',+ id: 'row-2',+ },+ ],},- { timeout: 1200 },);});+ });- it('renders an API error container when the invite request fails', async () => {- server.use(- rest.post(INVITE_USERS_ENDPOINT, (_, res, ctx) =>- res(- ctx.status(500),- ctx.json({- errors: [{ code: 'INTERNAL_ERROR', msg: 'Something went wrong' }],- }),- ),- ),- );-- const user = userEvent.setup({ pointerEventsCheck: 0 });+ describe('handleDoLater', () => {+ it('logs event and calls onNext immediately', async () => {+ const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });renderComponent();- const [firstInput] = screen.getAllByPlaceholderText(- /e\.g\. john@signoz\.io/i,+ await user.click(+ screen.getByRole('button', { name: /i'll do this later/i }),);- await user.type(firstInput, '[email protected]');- await selectRole(user, 0, 'Viewer');- await user.click(screen.getByRole('button', { name: /send invites/i }));-- await waitFor(() => {- expect(document.querySelector('.auth-error-container')).toBeInTheDocument();- });- await user.type(firstInput, 'x');- await waitFor(() => {- expect(- document.querySelector('.auth-error-container'),- ).not.toBeInTheDocument();+ expect(logEvent).toHaveBeenCalledWith('Org Onboarding: Clicked Do Later', {+ currentPageID: 4,});+ expect(mockOnNext).toHaveBeenCalledTimes(1);});});});diff --git a/frontend/src/container/OnboardingQuestionaire/OnboardingQuestionaire.styles.scss b/frontend/src/container/OnboardingQuestionaire/OnboardingQuestionaire.styles.scssindex c2c6d5ea3c..bbc9672378 100644--- a/frontend/src/container/OnboardingQuestionaire/OnboardingQuestionaire.styles.scss+++ b/frontend/src/container/OnboardingQuestionaire/OnboardingQuestionaire.styles.scss@@ -143,6 +143,8 @@}&.invite-team-members-form {+ --invite-members-field-background: var(--l3-background);+padding-right: 12px;.form-group {diff --git a/frontend/src/container/OnboardingQuestionaire/__tests__/OnboardingQuestionaire.test.tsx b/frontend/src/container/OnboardingQuestionaire/__tests__/OnboardingQuestionaire.test.tsxindex 8eb5437035..94d1f0a8fa 100644--- a/frontend/src/container/OnboardingQuestionaire/__tests__/OnboardingQuestionaire.test.tsx+++ b/frontend/src/container/OnboardingQuestionaire/__tests__/OnboardingQuestionaire.test.tsx@@ -22,7 +22,8 @@ const ORG_PREFERENCES_ENDPOINT = '*/api/v1/org/preferences/list';const UPDATE_ORG_PREFERENCE_ENDPOINT = '*/api/v1/org/preferences/name/update';const UPDATE_PROFILE_ENDPOINT = '*/api/v2/zeus/profiles';const EDIT_ORG_ENDPOINT = '*/api/v2/orgs/me';-const INVITE_USERS_ENDPOINT = '*/api/v1/invite/bulk/create';+const CREATE_USER_ENDPOINT = '*/api/v2/users';+const LIST_ROLES_ENDPOINT = '*/api/v1/roles';const mockOrgPreferences = {data: {@@ -31,6 +32,12 @@ const mockOrgPreferences = {status: 'success',};+const MOCK_ROLES = [+ { id: 'role-admin', name: 'Admin', description: 'Admin role' },+ { id: 'role-editor', name: 'Editor', description: 'Editor role' },+ { id: 'role-viewer', name: 'Viewer', description: 'Viewer role' },+];+describe('OnboardingQuestionaire Component', () => {beforeEach(() => {jest.clearAllMocks();@@ -48,8 +55,11 @@ describe('OnboardingQuestionaire Component', () => {rest.post(UPDATE_ORG_PREFERENCE_ENDPOINT, (_, res, ctx) =>res(ctx.status(200), ctx.json({ status: 'success' })),),- rest.post(INVITE_USERS_ENDPOINT, (_, res, ctx) =>- res(ctx.status(200), ctx.json({ status: 'success' })),+ rest.get(LIST_ROLES_ENDPOINT, (_, res, ctx) =>+ res(ctx.status(200), ctx.json({ data: MOCK_ROLES })),+ ),+ rest.post(CREATE_USER_ENDPOINT, (_, res, ctx) =>+ res(ctx.status(201), ctx.json({ data: { id: 'user-123' } })),),);});diff --git a/frontend/src/container/OnboardingQuestionaire/index.tsx b/frontend/src/container/OnboardingQuestionaire/index.tsxindex 5dfc03d1c0..9da7fe63e6 100644--- a/frontend/src/container/OnboardingQuestionaire/index.tsx+++ b/frontend/src/container/OnboardingQuestionaire/index.tsx@@ -11,7 +11,6 @@ import { AxiosError } from 'axios';import { SOMETHING_WENT_WRONG } from 'constants/api';import { ORG_PREFERENCES } from 'constants/orgPreferences';import ROUTES from 'constants/routes';-import { InviteTeamMembersProps } from 'container/OrganizationSettings/utils';import { useNotifications } from 'hooks/useNotifications';import history from 'lib/history';import { useAppContext } from 'providers/App/App';@@ -71,9 +70,6 @@ function OnboardingQuestionaire(): JSX.Element {const [optimiseSignozDetails, setOptimiseSignozDetails] =useState<OptimiseSignozDetails>(INITIAL_OPTIMISE_SIGNOZ_DETAILS);- const [teamMembers, setTeamMembers] = useState<- InviteTeamMembersProps[] | null- >(null);const [updatingOrgOnboardingStatus, setUpdatingOrgOnboardingStatus] =useState<boolean>(false);@@ -232,8 +228,6 @@ function OnboardingQuestionaire(): JSX.Element {{currentStep === 4 && (<InviteTeamMembersisLoading={updatingOrgOnboardingStatus}- teamMembers={teamMembers}- setTeamMembers={setTeamMembers}onNext={handleOnboardingComplete}/>)}