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

@@ -0,0 +1,263 @@
import { Input } from '@/components/base/input/input';
import { Select } from '@/components/base/select/select';
import { TextArea } from '@/components/base/textarea/textarea';
import { Toggle } from '@/components/base/toggle/toggle';
// Reusable clinic form used by both the /settings/clinics slideout and the
// /setup wizard step. The parent owns the form state so it can also own the
// submit button and the loading/error UI.
//
// Field shapes mirror the platform's ClinicCreateInput (which uses
// `addressCustom`, not `address`, and `onlineBooking`, not
// `onlineBookingEnabled` as the SDK field). See
// FortyTwoApps/helix-engage/src/objects/clinic.object.ts for the SDK source of
// truth; GraphQL-level differences are normalised in clinicFormToGraphQLInput.
export type ClinicStatus = 'ACTIVE' | 'TEMPORARILY_CLOSED' | 'PERMANENTLY_CLOSED';
export type ClinicFormValues = {
clinicName: string;
addressStreet1: string;
addressStreet2: string;
addressCity: string;
addressState: string;
addressPostcode: string;
phone: string;
email: string;
weekdayHours: string;
saturdayHours: string;
sundayHours: string;
status: ClinicStatus;
walkInAllowed: boolean;
onlineBooking: boolean;
cancellationWindowHours: string;
arriveEarlyMin: string;
requiredDocuments: string;
};
export const emptyClinicFormValues = (): ClinicFormValues => ({
clinicName: '',
addressStreet1: '',
addressStreet2: '',
addressCity: '',
addressState: '',
addressPostcode: '',
phone: '',
email: '',
weekdayHours: '9:00 AM - 6:00 PM',
saturdayHours: '9:00 AM - 2:00 PM',
sundayHours: 'Closed',
status: 'ACTIVE',
walkInAllowed: true,
onlineBooking: true,
cancellationWindowHours: '24',
arriveEarlyMin: '15',
requiredDocuments: '',
});
const STATUS_ITEMS = [
{ id: 'ACTIVE', label: 'Active' },
{ id: 'TEMPORARILY_CLOSED', label: 'Temporarily closed' },
{ id: 'PERMANENTLY_CLOSED', label: 'Permanently closed' },
];
// Convert form state into the shape the platform's createClinic / updateClinic
// mutations expect. Only non-empty fields are included so the platform can
// apply its own defaults for the rest.
export const clinicFormToGraphQLInput = (v: ClinicFormValues): Record<string, unknown> => {
const input: Record<string, unknown> = {
clinicName: v.clinicName.trim(),
status: v.status,
walkInAllowed: v.walkInAllowed,
onlineBooking: v.onlineBooking,
};
const hasAddress = v.addressStreet1 || v.addressCity || v.addressState || v.addressPostcode;
if (hasAddress) {
input.addressCustom = {
addressStreet1: v.addressStreet1 || null,
addressStreet2: v.addressStreet2 || null,
addressCity: v.addressCity || null,
addressState: v.addressState || null,
addressPostcode: v.addressPostcode || null,
addressCountry: 'India',
};
}
if (v.phone.trim()) {
input.phone = {
primaryPhoneNumber: v.phone.trim(),
primaryPhoneCountryCode: 'IN',
primaryPhoneCallingCode: '+91',
additionalPhones: null,
};
}
if (v.email.trim()) {
input.email = {
primaryEmail: v.email.trim(),
additionalEmails: null,
};
}
if (v.weekdayHours.trim()) input.weekdayHours = v.weekdayHours.trim();
if (v.saturdayHours.trim()) input.saturdayHours = v.saturdayHours.trim();
if (v.sundayHours.trim()) input.sundayHours = v.sundayHours.trim();
if (v.cancellationWindowHours.trim()) {
const n = Number(v.cancellationWindowHours);
if (!Number.isNaN(n)) input.cancellationWindowHours = n;
}
if (v.arriveEarlyMin.trim()) {
const n = Number(v.arriveEarlyMin);
if (!Number.isNaN(n)) input.arriveEarlyMin = n;
}
if (v.requiredDocuments.trim()) input.requiredDocuments = v.requiredDocuments.trim();
return input;
};
type ClinicFormProps = {
value: ClinicFormValues;
onChange: (value: ClinicFormValues) => void;
};
export const ClinicForm = ({ value, onChange }: ClinicFormProps) => {
const patch = (updates: Partial<ClinicFormValues>) => onChange({ ...value, ...updates });
return (
<div className="flex flex-col gap-4">
<Input
label="Clinic name"
isRequired
placeholder="e.g. Main Hospital Campus"
value={value.clinicName}
onChange={(v) => patch({ clinicName: v })}
/>
<Select
label="Status"
placeholder="Select status"
items={STATUS_ITEMS}
selectedKey={value.status}
onSelectionChange={(key) => patch({ status: key as ClinicStatus })}
>
{(item) => <Select.Item id={item.id} label={item.label} />}
</Select>
<div className="flex flex-col gap-3">
<p className="text-xs font-semibold uppercase tracking-wider text-quaternary">Address</p>
<Input
label="Street address"
placeholder="Street / building / landmark"
value={value.addressStreet1}
onChange={(v) => patch({ addressStreet1: v })}
/>
<Input
label="Area / locality (optional)"
placeholder="Area, neighbourhood"
value={value.addressStreet2}
onChange={(v) => patch({ addressStreet2: v })}
/>
<div className="grid grid-cols-2 gap-3">
<Input
label="City"
placeholder="Bengaluru"
value={value.addressCity}
onChange={(v) => patch({ addressCity: v })}
/>
<Input
label="State"
placeholder="Karnataka"
value={value.addressState}
onChange={(v) => patch({ addressState: v })}
/>
</div>
<Input
label="Postcode"
placeholder="560034"
value={value.addressPostcode}
onChange={(v) => patch({ addressPostcode: v })}
/>
</div>
<div className="flex flex-col gap-3">
<p className="text-xs font-semibold uppercase tracking-wider text-quaternary">Contact</p>
<Input
label="Phone"
type="tel"
placeholder="9876543210"
value={value.phone}
onChange={(v) => patch({ phone: v })}
/>
<Input
label="Email"
type="email"
placeholder="branch@hospital.com"
value={value.email}
onChange={(v) => patch({ email: v })}
/>
</div>
<div className="flex flex-col gap-3">
<p className="text-xs font-semibold uppercase tracking-wider text-quaternary">Visiting hours</p>
<Input
label="Weekdays"
placeholder="9:00 AM - 6:00 PM"
value={value.weekdayHours}
onChange={(v) => patch({ weekdayHours: v })}
/>
<div className="grid grid-cols-2 gap-3">
<Input
label="Saturday"
placeholder="9:00 AM - 2:00 PM"
value={value.saturdayHours}
onChange={(v) => patch({ saturdayHours: v })}
/>
<Input
label="Sunday"
placeholder="Closed"
value={value.sundayHours}
onChange={(v) => patch({ sundayHours: v })}
/>
</div>
</div>
<div className="flex flex-col gap-3">
<p className="text-xs font-semibold uppercase tracking-wider text-quaternary">Booking policy</p>
<div className="flex flex-col gap-3 rounded-lg border border-secondary bg-secondary p-4">
<Toggle
label="Walk-ins allowed"
isSelected={value.walkInAllowed}
onChange={(checked) => patch({ walkInAllowed: checked })}
/>
<Toggle
label="Accept online bookings"
isSelected={value.onlineBooking}
onChange={(checked) => patch({ onlineBooking: checked })}
/>
</div>
<div className="grid grid-cols-2 gap-3">
<Input
label="Cancel window (hours)"
type="number"
value={value.cancellationWindowHours}
onChange={(v) => patch({ cancellationWindowHours: v })}
/>
<Input
label="Arrive early (min)"
type="number"
value={value.arriveEarlyMin}
onChange={(v) => patch({ arriveEarlyMin: v })}
/>
</div>
<TextArea
label="Required documents"
placeholder="ID proof, referral letter, previous reports..."
value={value.requiredDocuments}
onChange={(v) => patch({ requiredDocuments: v })}
rows={3}
/>
</div>
</div>
);
};

View File

@@ -0,0 +1,260 @@
import { Input } from '@/components/base/input/input';
import { Select } from '@/components/base/select/select';
import { TextArea } from '@/components/base/textarea/textarea';
import { Toggle } from '@/components/base/toggle/toggle';
// Reusable doctor form used by /settings/doctors and the /setup wizard. The
// parent owns both the form state and the list of clinics to populate the
// clinic dropdown (since the list page will already have it loaded).
//
// Field names mirror the platform's DoctorCreateInput — notably `active`, not
// `isActive`, and `clinicId` for the relation.
export type DoctorDepartment =
| 'CARDIOLOGY'
| 'GYNECOLOGY'
| 'ORTHOPEDICS'
| 'GENERAL_MEDICINE'
| 'ENT'
| 'DERMATOLOGY'
| 'PEDIATRICS'
| 'ONCOLOGY';
export type DoctorFormValues = {
firstName: string;
lastName: string;
department: DoctorDepartment | '';
specialty: string;
qualifications: string;
yearsOfExperience: string;
clinicId: string;
visitingHours: string;
consultationFeeNew: string;
consultationFeeFollowUp: string;
phone: string;
email: string;
registrationNumber: string;
active: boolean;
};
export const emptyDoctorFormValues = (): DoctorFormValues => ({
firstName: '',
lastName: '',
department: '',
specialty: '',
qualifications: '',
yearsOfExperience: '',
clinicId: '',
visitingHours: '',
consultationFeeNew: '',
consultationFeeFollowUp: '',
phone: '',
email: '',
registrationNumber: '',
active: true,
});
const DEPARTMENT_ITEMS: { id: DoctorDepartment; label: string }[] = [
{ id: 'CARDIOLOGY', label: 'Cardiology' },
{ id: 'GYNECOLOGY', label: 'Gynecology' },
{ id: 'ORTHOPEDICS', label: 'Orthopedics' },
{ id: 'GENERAL_MEDICINE', label: 'General medicine' },
{ id: 'ENT', label: 'ENT' },
{ id: 'DERMATOLOGY', label: 'Dermatology' },
{ id: 'PEDIATRICS', label: 'Pediatrics' },
{ id: 'ONCOLOGY', label: 'Oncology' },
];
// Convert form state into the shape createDoctor/updateDoctor mutations
// expect. yearsOfExperience and consultation fees are text fields in the UI
// but typed in GraphQL, so we parse + validate here.
export const doctorFormToGraphQLInput = (v: DoctorFormValues): Record<string, unknown> => {
const input: Record<string, unknown> = {
fullName: {
firstName: v.firstName.trim(),
lastName: v.lastName.trim(),
},
active: v.active,
};
if (v.department) input.department = v.department;
if (v.specialty.trim()) input.specialty = v.specialty.trim();
if (v.qualifications.trim()) input.qualifications = v.qualifications.trim();
if (v.yearsOfExperience.trim()) {
const n = Number(v.yearsOfExperience);
if (!Number.isNaN(n)) input.yearsOfExperience = n;
}
if (v.clinicId) input.clinicId = v.clinicId;
if (v.visitingHours.trim()) input.visitingHours = v.visitingHours.trim();
if (v.consultationFeeNew.trim()) {
const n = Number(v.consultationFeeNew);
if (!Number.isNaN(n)) {
input.consultationFeeNew = {
amountMicros: Math.round(n * 1_000_000),
currencyCode: 'INR',
};
}
}
if (v.consultationFeeFollowUp.trim()) {
const n = Number(v.consultationFeeFollowUp);
if (!Number.isNaN(n)) {
input.consultationFeeFollowUp = {
amountMicros: Math.round(n * 1_000_000),
currencyCode: 'INR',
};
}
}
if (v.phone.trim()) {
input.phone = {
primaryPhoneNumber: v.phone.trim(),
primaryPhoneCountryCode: 'IN',
primaryPhoneCallingCode: '+91',
additionalPhones: null,
};
}
if (v.email.trim()) {
input.email = {
primaryEmail: v.email.trim(),
additionalEmails: null,
};
}
if (v.registrationNumber.trim()) input.registrationNumber = v.registrationNumber.trim();
return input;
};
type ClinicOption = { id: string; label: string };
type DoctorFormProps = {
value: DoctorFormValues;
onChange: (value: DoctorFormValues) => void;
clinics: ClinicOption[];
};
export const DoctorForm = ({ value, onChange, clinics }: DoctorFormProps) => {
const patch = (updates: Partial<DoctorFormValues>) => onChange({ ...value, ...updates });
return (
<div className="flex flex-col gap-4">
<div className="grid grid-cols-2 gap-3">
<Input
label="First name"
isRequired
placeholder="Ananya"
value={value.firstName}
onChange={(v) => patch({ firstName: v })}
/>
<Input
label="Last name"
isRequired
placeholder="Rao"
value={value.lastName}
onChange={(v) => patch({ lastName: v })}
/>
</div>
<Select
label="Department"
placeholder="Select department"
items={DEPARTMENT_ITEMS}
selectedKey={value.department || null}
onSelectionChange={(key) => patch({ department: (key as DoctorDepartment) || '' })}
>
{(item) => <Select.Item id={item.id} label={item.label} />}
</Select>
<Input
label="Specialty"
placeholder="e.g. Interventional cardiology"
value={value.specialty}
onChange={(v) => patch({ specialty: v })}
/>
<div className="grid grid-cols-2 gap-3">
<Input
label="Qualifications"
placeholder="MBBS, MD"
value={value.qualifications}
onChange={(v) => patch({ qualifications: v })}
/>
<Input
label="Experience (years)"
type="number"
value={value.yearsOfExperience}
onChange={(v) => patch({ yearsOfExperience: v })}
/>
</div>
<Select
label="Clinic"
placeholder={clinics.length === 0 ? 'Add a clinic first' : 'Assign to a clinic'}
isDisabled={clinics.length === 0}
items={clinics}
selectedKey={value.clinicId || null}
onSelectionChange={(key) => patch({ clinicId: (key as string) || '' })}
>
{(item) => <Select.Item id={item.id} label={item.label} />}
</Select>
<TextArea
label="Visiting hours"
placeholder="MonFri 10 AM 2 PM, Sat 10 AM 12 PM"
value={value.visitingHours}
onChange={(v) => patch({ visitingHours: v })}
rows={2}
/>
<div className="grid grid-cols-2 gap-3">
<Input
label="New consult fee (₹)"
type="number"
placeholder="800"
value={value.consultationFeeNew}
onChange={(v) => patch({ consultationFeeNew: v })}
/>
<Input
label="Follow-up fee (₹)"
type="number"
placeholder="500"
value={value.consultationFeeFollowUp}
onChange={(v) => patch({ consultationFeeFollowUp: v })}
/>
</div>
<div className="flex flex-col gap-3">
<p className="text-xs font-semibold uppercase tracking-wider text-quaternary">Contact</p>
<Input
label="Phone"
type="tel"
placeholder="9876543210"
value={value.phone}
onChange={(v) => patch({ phone: v })}
/>
<Input
label="Email"
type="email"
placeholder="doctor@hospital.com"
value={value.email}
onChange={(v) => patch({ email: v })}
/>
<Input
label="Registration number"
placeholder="Medical council reg no."
value={value.registrationNumber}
onChange={(v) => patch({ registrationNumber: v })}
/>
</div>
<div className="flex flex-col gap-2 rounded-lg border border-secondary bg-secondary p-4">
<Toggle
label="Accepting appointments"
isSelected={value.active}
onChange={(checked) => patch({ active: checked })}
/>
<p className="text-xs text-tertiary">
Inactive doctors are hidden from appointment booking and call-desk transfer lists.
</p>
</div>
</div>
);
};

View File

@@ -0,0 +1,143 @@
import { useState } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faUserPlus, faTrash, faPlus } from '@fortawesome/pro-duotone-svg-icons';
import { Input } from '@/components/base/input/input';
import { Select } from '@/components/base/select/select';
import { Button } from '@/components/base/buttons/button';
// Multi-email invite form. Uses the platform's sendInvitations mutation which
// takes a list of emails; the invited members all get the same role (the
// platform doesn't support per-email roles in a single call). If the admin
// needs different roles, they invite in multiple batches, or edit roles
// afterwards via the team listing.
//
// Role selection is optional — leaving it blank invites members without a
// role, matching the platform's default. When a role is selected, the caller
// is expected to apply it via updateWorkspaceMemberRole after the invited
// member accepts (this form just reports the selected roleId back).
export type RoleOption = {
id: string;
label: string;
supportingText?: string;
};
export type InviteMemberFormValues = {
emails: string[];
roleId: string;
};
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
type InviteMemberFormProps = {
value: InviteMemberFormValues;
onChange: (value: InviteMemberFormValues) => void;
roles: RoleOption[];
};
export const InviteMemberForm = ({ value, onChange, roles }: InviteMemberFormProps) => {
const [draft, setDraft] = useState('');
const addEmail = (rawValue?: string) => {
const source = (rawValue ?? draft).trim();
if (!source) return;
const trimmed = source.replace(/,+$/, '').trim();
if (!trimmed) return;
if (!EMAIL_REGEX.test(trimmed)) return;
if (value.emails.includes(trimmed)) {
setDraft('');
return;
}
onChange({ ...value, emails: [...value.emails, trimmed] });
setDraft('');
};
const removeEmail = (email: string) => {
onChange({ ...value, emails: value.emails.filter((e) => e !== email) });
};
// The Input component wraps react-aria TextField which doesn't expose
// onKeyDown via its typed props — so we commit on comma via the onChange
// handler instead. Users can also press the Add button or tab onto it.
const handleChange = (next: string) => {
if (next.endsWith(',')) {
addEmail(next);
return;
}
setDraft(next);
};
return (
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
<label className="text-sm font-medium text-secondary">
Emails <span className="text-error-primary">*</span>
</label>
<div className="flex items-center gap-2">
<div className="flex-1">
<Input
placeholder="colleague@hospital.com"
type="email"
value={draft}
onChange={handleChange}
/>
</div>
<Button
size="sm"
color="secondary"
iconLeading={({ className }: { className?: string }) => (
<FontAwesomeIcon icon={faPlus} className={className} />
)}
onClick={() => addEmail()}
isDisabled={!draft.trim() || !EMAIL_REGEX.test(draft.trim())}
>
Add
</Button>
</div>
<p className="text-xs text-tertiary">
Type a comma to add multiple emails, or click Add.
</p>
</div>
{value.emails.length > 0 && (
<div className="flex flex-col gap-2 rounded-lg border border-secondary bg-secondary p-3">
<p className="text-xs font-semibold uppercase tracking-wider text-quaternary">
{value.emails.length} invitee{value.emails.length === 1 ? '' : 's'}
</p>
<ul className="flex flex-col gap-1.5">
{value.emails.map((email) => (
<li
key={email}
className="flex items-center justify-between rounded-md bg-primary px-3 py-2 text-sm"
>
<span className="flex items-center gap-2 text-primary">
<FontAwesomeIcon icon={faUserPlus} className="size-3.5 text-fg-brand-primary" />
{email}
</span>
<button
type="button"
onClick={() => removeEmail(email)}
className="flex size-6 items-center justify-center rounded-md text-fg-quaternary hover:bg-secondary_hover hover:text-fg-error-primary"
title="Remove"
>
<FontAwesomeIcon icon={faTrash} className="size-3" />
</button>
</li>
))}
</ul>
</div>
)}
<Select
label="Role"
placeholder={roles.length === 0 ? 'No roles available' : 'Assign a role'}
isDisabled={roles.length === 0}
items={roles}
selectedKey={value.roleId || null}
onSelectionChange={(key) => onChange({ ...value, roleId: (key as string) || '' })}
>
{(item) => <Select.Item id={item.id} label={item.label} supportingText={item.supportingText} />}
</Select>
</div>
);
};

View File

@@ -33,6 +33,8 @@ import { BrandingSettingsPage } from "@/pages/branding-settings";
import { TeamSettingsPage } from "@/pages/team-settings";
import { SetupWizardPage } from "@/pages/setup-wizard";
import { SettingsPlaceholder } from "@/pages/settings-placeholder";
import { ClinicsPage } from "@/pages/clinics";
import { DoctorsPage } from "@/pages/doctors";
import { AuthProvider } from "@/providers/auth-provider";
import { DataProvider } from "@/providers/data-provider";
import { RouteProvider } from "@/providers/router-provider";
@@ -84,26 +86,8 @@ createRoot(document.getElementById("root")!).render(
{/* Settings hub + section pages */}
<Route path="/settings" element={<SettingsPage />} />
<Route path="/settings/team" element={<TeamSettingsPage />} />
<Route
path="/settings/clinics"
element={
<SettingsPlaceholder
title="Clinics"
description="Add hospital branches with addresses, phones, and visiting hours"
phase="Phase 3"
/>
}
/>
<Route
path="/settings/doctors"
element={
<SettingsPlaceholder
title="Doctors"
description="Add clinicians, specialties, and clinic assignments"
phase="Phase 3"
/>
}
/>
<Route path="/settings/clinics" element={<ClinicsPage />} />
<Route path="/settings/doctors" element={<DoctorsPage />} />
<Route
path="/settings/telephony"
element={

331
src/pages/clinics.tsx Normal file
View File

@@ -0,0 +1,331 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faBuilding, faPlus, faPenToSquare } from '@fortawesome/pro-duotone-svg-icons';
import { Button } from '@/components/base/buttons/button';
import { Badge } from '@/components/base/badges/badges';
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 {
ClinicForm,
clinicFormToGraphQLInput,
emptyClinicFormValues,
type ClinicFormValues,
type ClinicStatus,
} from '@/components/forms/clinic-form';
import { apiClient } from '@/lib/api-client';
import { notify } from '@/lib/toast';
import { markSetupStepComplete } from '@/lib/setup-state';
// /settings/clinics — list + add/edit slideout for the clinic entity. Uses the
// platform GraphQL API directly; there's no wrapping hook because this is the
// only consumer of clinics CRUD (the call desk uses a read-only doctors
// query and bypasses clinics entirely).
type Clinic = {
id: string;
clinicName: string | null;
status: ClinicStatus | null;
addressCustom: {
addressStreet1: string | null;
addressStreet2: string | null;
addressCity: string | null;
addressState: string | null;
addressPostcode: string | null;
} | null;
phone: { primaryPhoneNumber: string | null } | null;
email: { primaryEmail: string | null } | null;
weekdayHours: string | null;
saturdayHours: string | null;
sundayHours: string | null;
walkInAllowed: boolean | null;
onlineBooking: boolean | null;
cancellationWindowHours: number | null;
arriveEarlyMin: number | null;
requiredDocuments: string | null;
};
const CLINICS_QUERY = `{
clinics(first: 100) {
edges {
node {
id
clinicName
status
addressCustom {
addressStreet1 addressStreet2 addressCity addressState addressPostcode
}
phone { primaryPhoneNumber }
email { primaryEmail }
weekdayHours saturdayHours sundayHours
walkInAllowed onlineBooking
cancellationWindowHours arriveEarlyMin
requiredDocuments
}
}
}
}`;
const toFormValues = (clinic: Clinic): ClinicFormValues => ({
clinicName: clinic.clinicName ?? '',
addressStreet1: clinic.addressCustom?.addressStreet1 ?? '',
addressStreet2: clinic.addressCustom?.addressStreet2 ?? '',
addressCity: clinic.addressCustom?.addressCity ?? '',
addressState: clinic.addressCustom?.addressState ?? '',
addressPostcode: clinic.addressCustom?.addressPostcode ?? '',
phone: clinic.phone?.primaryPhoneNumber ?? '',
email: clinic.email?.primaryEmail ?? '',
weekdayHours: clinic.weekdayHours ?? '',
saturdayHours: clinic.saturdayHours ?? '',
sundayHours: clinic.sundayHours ?? '',
status: clinic.status ?? 'ACTIVE',
walkInAllowed: clinic.walkInAllowed ?? true,
onlineBooking: clinic.onlineBooking ?? true,
cancellationWindowHours: clinic.cancellationWindowHours != null ? String(clinic.cancellationWindowHours) : '',
arriveEarlyMin: clinic.arriveEarlyMin != null ? String(clinic.arriveEarlyMin) : '',
requiredDocuments: clinic.requiredDocuments ?? '',
});
const statusLabel: Record<ClinicStatus, string> = {
ACTIVE: 'Active',
TEMPORARILY_CLOSED: 'Temporarily closed',
PERMANENTLY_CLOSED: 'Permanently closed',
};
const statusColor: Record<ClinicStatus, 'success' | 'warning' | 'gray'> = {
ACTIVE: 'success',
TEMPORARILY_CLOSED: 'warning',
PERMANENTLY_CLOSED: 'gray',
};
export const ClinicsPage = () => {
const [clinics, setClinics] = useState<Clinic[]>([]);
const [loading, setLoading] = useState(true);
const [slideoutOpen, setSlideoutOpen] = useState(false);
const [editTarget, setEditTarget] = useState<Clinic | null>(null);
const [formValues, setFormValues] = useState<ClinicFormValues>(emptyClinicFormValues);
const [isSaving, setIsSaving] = useState(false);
const fetchClinics = useCallback(async () => {
try {
const data = await apiClient.graphql<{ clinics: { edges: { node: Clinic }[] } }>(CLINICS_QUERY);
setClinics(data.clinics.edges.map((e) => e.node));
} catch {
// toast already shown by apiClient
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchClinics();
}, [fetchClinics]);
const handleAdd = () => {
setEditTarget(null);
setFormValues(emptyClinicFormValues());
setSlideoutOpen(true);
};
const handleEdit = (clinic: Clinic) => {
setEditTarget(clinic);
setFormValues(toFormValues(clinic));
setSlideoutOpen(true);
};
const handleSave = async (close: () => void) => {
if (!formValues.clinicName.trim()) {
notify.error('Clinic name is required');
return;
}
setIsSaving(true);
try {
const input = clinicFormToGraphQLInput(formValues);
if (editTarget) {
await apiClient.graphql(
`mutation UpdateClinic($id: UUID!, $data: ClinicUpdateInput!) {
updateClinic(id: $id, data: $data) { id }
}`,
{ id: editTarget.id, data: input },
);
notify.success('Clinic updated', `${formValues.clinicName} has been updated.`);
} else {
await apiClient.graphql(
`mutation CreateClinic($data: ClinicCreateInput!) {
createClinic(data: $data) { id }
}`,
{ data: input },
);
notify.success('Clinic added', `${formValues.clinicName} has been added.`);
// First clinic added unblocks the wizard's clinics step. Failures
// here are silent — the badge will just be stale until next load.
markSetupStepComplete('clinics').catch(() => {});
}
await fetchClinics();
close();
} catch (err) {
console.error('[clinics] save failed', err);
} finally {
setIsSaving(false);
}
};
const activeCount = useMemo(() => clinics.filter((c) => c.status === 'ACTIVE').length, [clinics]);
return (
<div className="flex flex-1 flex-col overflow-hidden">
<TopBar title="Clinics" subtitle="Manage hospital branches and visiting hours" />
<div className="flex-1 overflow-y-auto p-6">
<TableCard.Root size="sm">
<TableCard.Header
title="Clinic branches"
badge={clinics.length}
description={`${activeCount} active`}
contentTrailing={
<Button
size="sm"
color="primary"
iconLeading={({ className }: { className?: string }) => (
<FontAwesomeIcon icon={faPlus} className={className} />
)}
onClick={handleAdd}
>
Add clinic
</Button>
}
/>
{loading ? (
<div className="flex items-center justify-center py-12">
<p className="text-sm text-tertiary">Loading clinics...</p>
</div>
) : clinics.length === 0 ? (
<div className="flex flex-col items-center justify-center gap-3 py-16">
<div className="flex size-12 items-center justify-center rounded-full bg-brand-secondary">
<FontAwesomeIcon icon={faBuilding} className="size-5 text-fg-brand-primary" />
</div>
<p className="text-sm font-semibold text-primary">No clinics yet</p>
<p className="max-w-xs text-center text-xs text-tertiary">
Add your first clinic branch to start booking appointments and assigning doctors.
</p>
<Button size="sm" color="primary" onClick={handleAdd}>
Add clinic
</Button>
</div>
) : (
<Table>
<Table.Header>
<Table.Head label="NAME" isRowHeader />
<Table.Head label="ADDRESS" />
<Table.Head label="CONTACT" />
<Table.Head label="HOURS" />
<Table.Head label="STATUS" />
<Table.Head label="" />
</Table.Header>
<Table.Body items={clinics}>
{(clinic) => {
const addressLine = [
clinic.addressCustom?.addressStreet1,
clinic.addressCustom?.addressCity,
]
.filter(Boolean)
.join(', ');
const status = clinic.status ?? 'ACTIVE';
return (
<Table.Row id={clinic.id}>
<Table.Cell>
<span className="text-sm font-medium text-primary">
{clinic.clinicName ?? 'Unnamed clinic'}
</span>
</Table.Cell>
<Table.Cell>
<span className="text-sm text-tertiary">{addressLine || '—'}</span>
</Table.Cell>
<Table.Cell>
<div className="flex flex-col">
<span className="text-sm text-primary">
{clinic.phone?.primaryPhoneNumber ?? '—'}
</span>
<span className="text-xs text-tertiary">
{clinic.email?.primaryEmail ?? ''}
</span>
</div>
</Table.Cell>
<Table.Cell>
<span className="text-xs text-tertiary">
{clinic.weekdayHours ?? 'Not set'}
</span>
</Table.Cell>
<Table.Cell>
<Badge size="sm" color={statusColor[status]} type="pill-color">
{statusLabel[status]}
</Badge>
</Table.Cell>
<Table.Cell>
<Button
size="sm"
color="secondary"
iconLeading={({ className }: { className?: string }) => (
<FontAwesomeIcon icon={faPenToSquare} className={className} />
)}
onClick={() => handleEdit(clinic)}
>
Edit
</Button>
</Table.Cell>
</Table.Row>
);
}}
</Table.Body>
</Table>
)}
</TableCard.Root>
</div>
<SlideoutMenu isOpen={slideoutOpen} onOpenChange={setSlideoutOpen} 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={faBuilding} className="size-5 text-fg-brand-primary" />
</div>
<div>
<h2 className="text-lg font-semibold text-primary">
{editTarget ? 'Edit clinic' : 'Add clinic'}
</h2>
<p className="text-sm text-tertiary">
{editTarget
? 'Update branch details, hours, and policy'
: 'Add a new hospital branch'}
</p>
</div>
</div>
</SlideoutMenu.Header>
<SlideoutMenu.Content>
<ClinicForm value={formValues} onChange={setFormValues} />
</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={isSaving}
showTextWhileLoading
onClick={() => handleSave(close)}
>
{isSaving ? 'Saving...' : editTarget ? 'Save changes' : 'Add clinic'}
</Button>
</div>
</SlideoutMenu.Footer>
</>
)}
</SlideoutMenu>
</div>
);
};

358
src/pages/doctors.tsx Normal file
View File

@@ -0,0 +1,358 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faStethoscope, faPlus, faPenToSquare } from '@fortawesome/pro-duotone-svg-icons';
import { Button } from '@/components/base/buttons/button';
import { Badge } from '@/components/base/badges/badges';
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 {
DoctorForm,
doctorFormToGraphQLInput,
emptyDoctorFormValues,
type DoctorDepartment,
type DoctorFormValues,
} from '@/components/forms/doctor-form';
import { apiClient } from '@/lib/api-client';
import { notify } from '@/lib/toast';
import { markSetupStepComplete } from '@/lib/setup-state';
// /settings/doctors — list + add/edit slideout. Loads clinics in parallel to
// populate the clinic dropdown in the form. If there are no clinics yet, the
// form's clinic select is disabled and the CTA copy steers the admin back to
// /settings/clinics first.
type Doctor = {
id: string;
fullName: { firstName: string | null; lastName: string | null } | null;
department: DoctorDepartment | null;
specialty: string | null;
qualifications: string | null;
yearsOfExperience: number | null;
visitingHours: string | null;
consultationFeeNew: { amountMicros: number | null; currencyCode: string | null } | null;
consultationFeeFollowUp: { amountMicros: number | null; currencyCode: string | null } | null;
phone: { primaryPhoneNumber: string | null } | null;
email: { primaryEmail: string | null } | null;
registrationNumber: string | null;
active: boolean | null;
clinicId: string | null;
clinic: { id: string; clinicName: string | null } | null;
};
type ClinicLite = { id: string; clinicName: string | null };
const DOCTORS_QUERY = `{
doctors(first: 100) {
edges {
node {
id
fullName { firstName lastName }
department specialty qualifications yearsOfExperience
visitingHours
consultationFeeNew { amountMicros currencyCode }
consultationFeeFollowUp { amountMicros currencyCode }
phone { primaryPhoneNumber }
email { primaryEmail }
registrationNumber
active
clinicId
clinic { id clinicName }
}
}
}
clinics(first: 100) { edges { node { id clinicName } } }
}`;
const departmentLabel: Record<DoctorDepartment, string> = {
CARDIOLOGY: 'Cardiology',
GYNECOLOGY: 'Gynecology',
ORTHOPEDICS: 'Orthopedics',
GENERAL_MEDICINE: 'General medicine',
ENT: 'ENT',
DERMATOLOGY: 'Dermatology',
PEDIATRICS: 'Pediatrics',
ONCOLOGY: 'Oncology',
};
const toFormValues = (doctor: Doctor): DoctorFormValues => ({
firstName: doctor.fullName?.firstName ?? '',
lastName: doctor.fullName?.lastName ?? '',
department: doctor.department ?? '',
specialty: doctor.specialty ?? '',
qualifications: doctor.qualifications ?? '',
yearsOfExperience: doctor.yearsOfExperience != null ? String(doctor.yearsOfExperience) : '',
clinicId: doctor.clinicId ?? '',
visitingHours: doctor.visitingHours ?? '',
consultationFeeNew: doctor.consultationFeeNew?.amountMicros
? String(Math.round(doctor.consultationFeeNew.amountMicros / 1_000_000))
: '',
consultationFeeFollowUp: doctor.consultationFeeFollowUp?.amountMicros
? String(Math.round(doctor.consultationFeeFollowUp.amountMicros / 1_000_000))
: '',
phone: doctor.phone?.primaryPhoneNumber ?? '',
email: doctor.email?.primaryEmail ?? '',
registrationNumber: doctor.registrationNumber ?? '',
active: doctor.active ?? true,
});
const formatFee = (money: { amountMicros: number | null } | null): string => {
if (!money?.amountMicros) return '—';
return `${Math.round(money.amountMicros / 1_000_000).toLocaleString('en-IN')}`;
};
export const DoctorsPage = () => {
const [doctors, setDoctors] = useState<Doctor[]>([]);
const [clinics, setClinics] = useState<ClinicLite[]>([]);
const [loading, setLoading] = useState(true);
const [slideoutOpen, setSlideoutOpen] = useState(false);
const [editTarget, setEditTarget] = useState<Doctor | null>(null);
const [formValues, setFormValues] = useState<DoctorFormValues>(emptyDoctorFormValues);
const [isSaving, setIsSaving] = useState(false);
const fetchAll = useCallback(async () => {
try {
const data = await apiClient.graphql<{
doctors: { edges: { node: Doctor }[] };
clinics: { edges: { node: ClinicLite }[] };
}>(DOCTORS_QUERY);
setDoctors(data.doctors.edges.map((e) => e.node));
setClinics(data.clinics.edges.map((e) => e.node));
} catch {
// toast already shown by apiClient
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchAll();
}, [fetchAll]);
const clinicOptions = useMemo(
() =>
clinics.map((c) => ({
id: c.id,
label: c.clinicName ?? 'Unnamed clinic',
})),
[clinics],
);
const clinicNameById = useMemo(() => {
const map = new Map<string, string>();
for (const c of clinics) {
if (c.clinicName) map.set(c.id, c.clinicName);
}
return map;
}, [clinics]);
const handleAdd = () => {
setEditTarget(null);
setFormValues(emptyDoctorFormValues());
setSlideoutOpen(true);
};
const handleEdit = (doctor: Doctor) => {
setEditTarget(doctor);
setFormValues(toFormValues(doctor));
setSlideoutOpen(true);
};
const handleSave = async (close: () => void) => {
if (!formValues.firstName.trim() || !formValues.lastName.trim()) {
notify.error('First and last name are required');
return;
}
setIsSaving(true);
try {
const input = doctorFormToGraphQLInput(formValues);
if (editTarget) {
await apiClient.graphql(
`mutation UpdateDoctor($id: UUID!, $data: DoctorUpdateInput!) {
updateDoctor(id: $id, data: $data) { id }
}`,
{ id: editTarget.id, data: input },
);
notify.success('Doctor updated', `Dr. ${formValues.firstName} ${formValues.lastName}`);
} else {
await apiClient.graphql(
`mutation CreateDoctor($data: DoctorCreateInput!) {
createDoctor(data: $data) { id }
}`,
{ data: input },
);
notify.success('Doctor added', `Dr. ${formValues.firstName} ${formValues.lastName}`);
markSetupStepComplete('doctors').catch(() => {});
}
await fetchAll();
close();
} catch (err) {
console.error('[doctors] save failed', err);
} finally {
setIsSaving(false);
}
};
const activeCount = useMemo(() => doctors.filter((d) => d.active).length, [doctors]);
return (
<div className="flex flex-1 flex-col overflow-hidden">
<TopBar title="Doctors" subtitle="Manage clinicians and appointment booking" />
<div className="flex-1 overflow-y-auto p-6">
<TableCard.Root size="sm">
<TableCard.Header
title="Clinicians"
badge={doctors.length}
description={`${activeCount} accepting appointments`}
contentTrailing={
<Button
size="sm"
color="primary"
iconLeading={({ className }: { className?: string }) => (
<FontAwesomeIcon icon={faPlus} className={className} />
)}
onClick={handleAdd}
>
Add doctor
</Button>
}
/>
{loading ? (
<div className="flex items-center justify-center py-12">
<p className="text-sm text-tertiary">Loading doctors...</p>
</div>
) : doctors.length === 0 ? (
<div className="flex flex-col items-center justify-center gap-3 py-16">
<div className="flex size-12 items-center justify-center rounded-full bg-brand-secondary">
<FontAwesomeIcon icon={faStethoscope} className="size-5 text-fg-brand-primary" />
</div>
<p className="text-sm font-semibold text-primary">No doctors yet</p>
<p className="max-w-xs text-center text-xs text-tertiary">
{clinics.length === 0
? 'Add a clinic first, then add doctors to assign them.'
: 'Add your first doctor to start booking consultations.'}
</p>
<Button size="sm" color="primary" onClick={handleAdd} isDisabled={clinics.length === 0}>
Add doctor
</Button>
</div>
) : (
<Table>
<Table.Header>
<Table.Head label="DOCTOR" isRowHeader />
<Table.Head label="DEPARTMENT" />
<Table.Head label="CLINIC" />
<Table.Head label="FEE (NEW)" />
<Table.Head label="STATUS" />
<Table.Head label="" />
</Table.Header>
<Table.Body items={doctors}>
{(doctor) => {
const firstName = doctor.fullName?.firstName ?? '';
const lastName = doctor.fullName?.lastName ?? '';
const name = `Dr. ${firstName} ${lastName}`.trim();
const clinicName =
doctor.clinic?.clinicName ??
(doctor.clinicId ? clinicNameById.get(doctor.clinicId) : null) ??
'—';
return (
<Table.Row id={doctor.id}>
<Table.Cell>
<div className="flex flex-col">
<span className="text-sm font-medium text-primary">{name}</span>
{doctor.specialty && (
<span className="text-xs text-tertiary">{doctor.specialty}</span>
)}
</div>
</Table.Cell>
<Table.Cell>
<span className="text-sm text-tertiary">
{doctor.department ? departmentLabel[doctor.department] : '—'}
</span>
</Table.Cell>
<Table.Cell>
<span className="text-sm text-tertiary">{clinicName}</span>
</Table.Cell>
<Table.Cell>
<span className="text-sm text-tertiary">
{formatFee(doctor.consultationFeeNew)}
</span>
</Table.Cell>
<Table.Cell>
<Badge
size="sm"
color={doctor.active ? 'success' : 'gray'}
type="pill-color"
>
{doctor.active ? 'Accepting' : 'Inactive'}
</Badge>
</Table.Cell>
<Table.Cell>
<Button
size="sm"
color="secondary"
iconLeading={({ className }: { className?: string }) => (
<FontAwesomeIcon icon={faPenToSquare} className={className} />
)}
onClick={() => handleEdit(doctor)}
>
Edit
</Button>
</Table.Cell>
</Table.Row>
);
}}
</Table.Body>
</Table>
)}
</TableCard.Root>
</div>
<SlideoutMenu isOpen={slideoutOpen} onOpenChange={setSlideoutOpen} 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={faStethoscope} className="size-5 text-fg-brand-primary" />
</div>
<div>
<h2 className="text-lg font-semibold text-primary">
{editTarget ? 'Edit doctor' : 'Add doctor'}
</h2>
<p className="text-sm text-tertiary">
{editTarget
? 'Update clinician details and clinic assignment'
: 'Add a new clinician to your hospital'}
</p>
</div>
</div>
</SlideoutMenu.Header>
<SlideoutMenu.Content>
<DoctorForm value={formValues} onChange={setFormValues} clinics={clinicOptions} />
</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={isSaving}
showTextWhileLoading
onClick={() => handleSave(close)}
>
{isSaving ? 'Saving...' : editTarget ? 'Save changes' : 'Add doctor'}
</Button>
</div>
</SlideoutMenu.Footer>
</>
)}
</SlideoutMenu>
</div>
);
};

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>
);
};