feat(onboarding/phase-3): clinics, doctors, team invite/role CRUD

Replaces Phase 2 placeholder routes for /settings/clinics and
/settings/doctors with real list + add/edit slideouts backed directly by
the platform's ClinicCreateInput / DoctorCreateInput mutations. Rewrites
/settings/team to fetch roles via getRoles and let admins invite members
(sendInvitations) and change roles (updateWorkspaceMemberRole).

- src/components/forms/clinic-form.tsx — reusable form + GraphQL input
  transformer, handles address/phone/email composite types
- src/components/forms/doctor-form.tsx — reusable form with clinic
  dropdown and currency conversion for consultation fees
- src/components/forms/invite-member-form.tsx — multi-email chip input
  with comma-to-commit UX (AriaTextField doesn't expose onKeyDown)
- src/pages/clinics.tsx — list + slideout using ClinicForm, marks the
  clinics setup step complete on first successful add
- src/pages/doctors.tsx — list + slideout with parallel clinic fetch,
  disabled-state when no clinics exist, marks doctors step complete
- src/pages/team-settings.tsx — replaces email-pattern role inference
  with real getRoles + in-row role Select, adds invite slideout, marks
  team step complete on successful invitation
- src/main.tsx — routes /settings/clinics and /settings/doctors to real
  pages instead of SettingsPlaceholder stubs

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-07 07:33:25 +05:30
parent c1b636cb6d
commit 4420b648d4
7 changed files with 1682 additions and 133 deletions

View File

@@ -1,64 +1,110 @@
import { useEffect, useMemo, useState } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faKey, faToggleOn } from '@fortawesome/pro-duotone-svg-icons';
import { faKey, faToggleOn, faUserPlus, faUserShield } from '@fortawesome/pro-duotone-svg-icons';
import { Avatar } from '@/components/base/avatar/avatar';
import { Badge } from '@/components/base/badges/badges';
import { Button } from '@/components/base/buttons/button';
import { Select } from '@/components/base/select/select';
import { Table, TableCard } from '@/components/application/table/table';
import { SlideoutMenu } from '@/components/application/slideout-menus/slideout-menu';
import { TopBar } from '@/components/layout/top-bar';
import {
InviteMemberForm,
type InviteMemberFormValues,
type RoleOption,
} from '@/components/forms/invite-member-form';
import { apiClient } from '@/lib/api-client';
import { notify } from '@/lib/toast';
import { getInitials } from '@/lib/format';
import { markSetupStepComplete } from '@/lib/setup-state';
// Workspace member listing — moved here from the old monolithic SettingsPage
// when /settings became the Settings hub. This page is mounted at /settings/team.
// /settings/team — Phase 3 rewrite. The Phase 2 version was read-only and
// inferred roles from the email string; this version:
// 1. Fetches real roles via getRoles (platform mutation).
// 2. Fetches workspace members WITH their role assignments so the listing
// shows actual roles.
// 3. Lets admins invite via sendInvitations (multi-email).
// 4. Lets admins change a member's role via updateWorkspaceMemberRole.
//
// Phase 2: read-only listing (same as before).
// Phase 3: invite form + role assignment editor will be added here.
// Invitations mark the setup-state `team` step complete on first success so
// the wizard can advance.
type MemberRole = {
id: string;
label: string;
};
type WorkspaceMember = {
id: string;
name: { firstName: string; lastName: string } | null;
userEmail: string;
avatarUrl: string | null;
roles: { id: string; label: string }[];
roles: MemberRole[];
};
const MEMBERS_QUERY = `{
workspaceMembers(first: 100) {
edges {
node {
id
name { firstName lastName }
userEmail
avatarUrl
roles { id label }
}
}
}
}`;
const ROLES_QUERY = `{
getRoles {
id
label
description
canBeAssignedToUsers
}
}`;
export const TeamSettingsPage = () => {
const [members, setMembers] = useState<WorkspaceMember[]>([]);
const [roles, setRoles] = useState<RoleOption[]>([]);
const [loading, setLoading] = useState(true);
const [inviteOpen, setInviteOpen] = useState(false);
const [inviteValues, setInviteValues] = useState<InviteMemberFormValues>({ emails: [], roleId: '' });
const [isSending, setIsSending] = useState(false);
useEffect(() => {
const fetchMembers = async () => {
try {
const data = await apiClient.graphql<any>(
`{ workspaceMembers(first: 50) { edges { node { id name { firstName lastName } userEmail avatarUrl } } } }`,
const fetchData = useCallback(async () => {
try {
const [memberData, roleData] = await Promise.all([
apiClient.graphql<{ workspaceMembers: { edges: { node: WorkspaceMember }[] } }>(
MEMBERS_QUERY,
undefined,
{ silent: true },
);
const rawMembers = data?.workspaceMembers?.edges?.map((e: any) => e.node) ?? [];
// Roles come from the platform's role assignment — Phase 3 wires the
// real getRoles query; for now infer from email convention.
setMembers(rawMembers.map((m: any) => ({
...m,
roles: inferRoles(m.userEmail),
})));
} catch {
// silently fail
} finally {
setLoading(false);
}
};
fetchMembers();
),
apiClient.graphql<{
getRoles: { id: string; label: string; description: string | null; canBeAssignedToUsers: boolean }[];
}>(ROLES_QUERY, undefined, { silent: true }),
]);
setMembers(memberData.workspaceMembers.edges.map((e) => e.node));
setRoles(
roleData.getRoles
.filter((r) => r.canBeAssignedToUsers)
.map((r) => ({
id: r.id,
label: r.label,
supportingText: r.description ?? undefined,
})),
);
} catch {
// silently fail
} finally {
setLoading(false);
}
}, []);
const inferRoles = (email: string): { id: string; label: string }[] => {
if (email.includes('ramesh') || email.includes('admin')) return [{ id: 'mgr', label: 'HelixEngage Manager' }];
if (email.includes('cc')) return [{ id: 'cc', label: 'HelixEngage User (CC Agent)' }];
if (email.includes('marketing') || email.includes('sanjay')) return [{ id: 'exec', label: 'HelixEngage User (Executive)' }];
if (email.includes('dr.')) return [{ id: 'doc', label: 'HelixEngage User (Doctor)' }];
return [{ id: 'user', label: 'HelixEngage User' }];
};
useEffect(() => {
fetchData();
}, [fetchData]);
const [search, setSearch] = useState('');
const [page, setPage] = useState(1);
@@ -80,6 +126,65 @@ export const TeamSettingsPage = () => {
notify.info('Password Reset', `Password reset link would be sent to ${member.userEmail}`);
};
const handleChangeRole = async (memberId: string, newRoleId: string) => {
try {
await apiClient.graphql(
`mutation UpdateRole($workspaceMemberId: UUID!, $roleId: UUID!) {
updateWorkspaceMemberRole(workspaceMemberId: $workspaceMemberId, roleId: $roleId) {
id
}
}`,
{ workspaceMemberId: memberId, roleId: newRoleId },
);
const newRole = roles.find((r) => r.id === newRoleId);
setMembers((prev) =>
prev.map((m) =>
m.id === memberId
? { ...m, roles: newRole ? [{ id: newRole.id, label: newRole.label }] : [] }
: m,
),
);
notify.success('Role updated', newRole ? `Role set to ${newRole.label}` : 'Role updated');
} catch (err) {
console.error('[team] role update failed', err);
}
};
const handleSendInvites = async (close: () => void) => {
if (inviteValues.emails.length === 0) {
notify.error('Add at least one email');
return;
}
setIsSending(true);
try {
await apiClient.graphql(
`mutation SendInvitations($emails: [String!]!) {
sendInvitations(emails: $emails) {
success
errors
result {
email
id
}
}
}`,
{ emails: inviteValues.emails },
);
notify.success(
'Invitations sent',
`${inviteValues.emails.length} invitation${inviteValues.emails.length === 1 ? '' : 's'} sent.`,
);
markSetupStepComplete('team').catch(() => {});
setInviteValues({ emails: [], roleId: '' });
await fetchData();
close();
} catch (err) {
console.error('[team] invite failed', err);
} finally {
setIsSending(false);
}
};
return (
<div className="flex flex-1 flex-col overflow-hidden">
<TopBar title="Team" subtitle="Manage workspace members and their roles" />
@@ -91,13 +196,31 @@ export const TeamSettingsPage = () => {
badge={members.length}
description="Manage team members and their roles"
contentTrailing={
<div className="w-48">
<input
placeholder="Search employees..."
value={search}
onChange={(e) => { setSearch(e.target.value); setPage(1); }}
className="w-full rounded-lg border border-secondary bg-primary px-3 py-1.5 text-sm text-primary placeholder:text-placeholder outline-none focus:border-brand focus:ring-2 focus:ring-brand-100"
/>
<div className="flex items-center gap-3">
<div className="w-48">
<input
placeholder="Search employees..."
value={search}
onChange={(e) => {
setSearch(e.target.value);
setPage(1);
}}
className="w-full rounded-lg border border-secondary bg-primary px-3 py-1.5 text-sm text-primary placeholder:text-placeholder outline-none focus:border-brand focus:ring-2 focus:ring-brand-100"
/>
</div>
<Button
size="sm"
color="primary"
iconLeading={({ className }: { className?: string }) => (
<FontAwesomeIcon icon={faUserPlus} className={className} />
)}
onClick={() => {
setInviteValues({ emails: [], roleId: '' });
setInviteOpen(true);
}}
>
Invite members
</Button>
</div>
}
/>
@@ -105,84 +228,171 @@ export const TeamSettingsPage = () => {
<div className="flex items-center justify-center py-12">
<p className="text-sm text-tertiary">Loading employees...</p>
</div>
) : (<>
<Table>
<Table.Header>
<Table.Head label="EMPLOYEE" isRowHeader />
<Table.Head label="EMAIL" />
<Table.Head label="ROLES" />
<Table.Head label="STATUS" />
<Table.Head label="ACTIONS" />
</Table.Header>
<Table.Body items={paged}>
{(member) => {
const firstName = member.name?.firstName ?? '';
const lastName = member.name?.lastName ?? '';
const fullName = `${firstName} ${lastName}`.trim() || 'Unnamed';
const initials = getInitials(firstName || '?', lastName || '?');
const roles = member.roles?.map((r) => r.label) ?? [];
) : (
<>
<Table>
<Table.Header>
<Table.Head label="EMPLOYEE" isRowHeader />
<Table.Head label="EMAIL" />
<Table.Head label="ROLE" />
<Table.Head label="STATUS" />
<Table.Head label="ACTIONS" />
</Table.Header>
<Table.Body items={paged}>
{(member) => {
const firstName = member.name?.firstName ?? '';
const lastName = member.name?.lastName ?? '';
const fullName = `${firstName} ${lastName}`.trim() || 'Unnamed';
const initials = getInitials(firstName || '?', lastName || '?');
const currentRoleId = member.roles[0]?.id ?? null;
return (
<Table.Row id={member.id}>
<Table.Cell>
<div className="flex items-center gap-3">
<Avatar size="sm" initials={initials} src={member.avatarUrl ?? undefined} />
<span className="text-sm font-medium text-primary">{fullName}</span>
</div>
</Table.Cell>
<Table.Cell>
<span className="text-sm text-tertiary">{member.userEmail}</span>
</Table.Cell>
<Table.Cell>
<div className="flex flex-wrap gap-1">
{roles.length > 0 ? roles.map((role) => (
<Badge key={role} size="sm" color={role.includes('Manager') ? 'brand' : 'gray'}>
{role}
return (
<Table.Row id={member.id}>
<Table.Cell>
<div className="flex items-center gap-3">
<Avatar
size="sm"
initials={initials}
src={member.avatarUrl ?? undefined}
/>
<span className="text-sm font-medium text-primary">{fullName}</span>
</div>
</Table.Cell>
<Table.Cell>
<span className="text-sm text-tertiary">{member.userEmail}</span>
</Table.Cell>
<Table.Cell>
{roles.length > 0 ? (
<div className="w-56">
<Select
placeholder="No role"
placeholderIcon={
<FontAwesomeIcon
icon={faUserShield}
data-icon
className="size-4"
/>
}
items={roles}
selectedKey={currentRoleId}
onSelectionChange={(key) =>
handleChangeRole(member.id, key as string)
}
>
{(item) => (
<Select.Item id={item.id} label={item.label} />
)}
</Select>
</div>
) : member.roles.length > 0 ? (
<Badge size="sm" color="gray">
{member.roles[0].label}
</Badge>
)) : (
<span className="text-xs text-quaternary">No roles</span>
) : (
<span className="text-xs text-quaternary">No role</span>
)}
</div>
</Table.Cell>
<Table.Cell>
<Badge size="sm" color="success" type="pill-color">
<FontAwesomeIcon icon={faToggleOn} className="mr-1 size-3" />
Active
</Badge>
</Table.Cell>
<Table.Cell>
<Button
size="sm"
color="secondary"
iconLeading={({ className }: { className?: string }) => (
<FontAwesomeIcon icon={faKey} className={className} />
)}
onClick={() => handleResetPassword(member)}
>
Reset Password
</Button>
</Table.Cell>
</Table.Row>
);
}}
</Table.Body>
</Table>
{totalPages > 1 && (
<div className="flex items-center justify-between border-t border-secondary px-5 py-3">
<span className="text-xs text-tertiary">
{(page - 1) * PAGE_SIZE + 1}&ndash;{Math.min(page * PAGE_SIZE, filtered.length)} of {filtered.length}
</span>
<div className="flex items-center gap-1">
<button onClick={() => setPage(Math.max(1, page - 1))} disabled={page === 1}
className="px-2 py-1 text-xs font-medium text-secondary rounded-md hover:bg-primary_hover disabled:text-disabled disabled:cursor-not-allowed">Previous</button>
<button onClick={() => setPage(Math.min(totalPages, page + 1))} disabled={page === totalPages}
className="px-2 py-1 text-xs font-medium text-secondary rounded-md hover:bg-primary_hover disabled:text-disabled disabled:cursor-not-allowed">Next</button>
</Table.Cell>
<Table.Cell>
<Badge size="sm" color="success" type="pill-color">
<FontAwesomeIcon icon={faToggleOn} className="mr-1 size-3" />
Active
</Badge>
</Table.Cell>
<Table.Cell>
<Button
size="sm"
color="secondary"
iconLeading={({ className }: { className?: string }) => (
<FontAwesomeIcon icon={faKey} className={className} />
)}
onClick={() => handleResetPassword(member)}
>
Reset Password
</Button>
</Table.Cell>
</Table.Row>
);
}}
</Table.Body>
</Table>
{totalPages > 1 && (
<div className="flex items-center justify-between border-t border-secondary px-5 py-3">
<span className="text-xs text-tertiary">
{(page - 1) * PAGE_SIZE + 1}&ndash;{Math.min(page * PAGE_SIZE, filtered.length)} of{' '}
{filtered.length}
</span>
<div className="flex items-center gap-1">
<button
onClick={() => setPage(Math.max(1, page - 1))}
disabled={page === 1}
className="px-2 py-1 text-xs font-medium text-secondary rounded-md hover:bg-primary_hover disabled:text-disabled disabled:cursor-not-allowed"
>
Previous
</button>
<button
onClick={() => setPage(Math.min(totalPages, page + 1))}
disabled={page === totalPages}
className="px-2 py-1 text-xs font-medium text-secondary rounded-md hover:bg-primary_hover disabled:text-disabled disabled:cursor-not-allowed"
>
Next
</button>
</div>
</div>
</div>
)}
</> )}
)}
</>
)}
</TableCard.Root>
</div>
<SlideoutMenu isOpen={inviteOpen} onOpenChange={setInviteOpen} isDismissable>
{({ close }) => (
<>
<SlideoutMenu.Header onClose={close}>
<div className="flex items-center gap-3 pr-8">
<div className="flex size-10 items-center justify-center rounded-lg bg-brand-secondary">
<FontAwesomeIcon icon={faUserPlus} className="size-5 text-fg-brand-primary" />
</div>
<div>
<h2 className="text-lg font-semibold text-primary">Invite members</h2>
<p className="text-sm text-tertiary">
Send invitations to supervisors, agents, and doctors
</p>
</div>
</div>
</SlideoutMenu.Header>
<SlideoutMenu.Content>
<InviteMemberForm value={inviteValues} onChange={setInviteValues} roles={roles} />
<p className="text-xs text-tertiary">
Invitees receive an email with a link to set their password. Role assignment can be changed
from the employees table after they accept.
</p>
</SlideoutMenu.Content>
<SlideoutMenu.Footer>
<div className="flex items-center justify-end gap-3">
<Button size="md" color="secondary" onClick={close}>
Cancel
</Button>
<Button
size="md"
color="primary"
isLoading={isSending}
showTextWhileLoading
onClick={() => handleSendInvites(close)}
isDisabled={inviteValues.emails.length === 0}
>
{isSending
? 'Sending...'
: `Send ${inviteValues.emails.length || ''} invitation${
inviteValues.emails.length === 1 ? '' : 's'
}`.trim()}
</Button>
</div>
</SlideoutMenu.Footer>
</>
)}
</SlideoutMenu>
</div>
);
};