mirror of
https://dev.azure.com/globalhealthx/EMR/_git/helix-engage
synced 2026-04-12 02:38:15 +00:00
feat(onboarding/phase-6): setup wizard polish, seed script alignment, doctor visit slots
- Setup wizard: 3-pane layout with right-side live previews, resume banner, edit/copy icons on team step, AI prompt configuration - Forms: employee-create replaces invite-member (no email invites), clinic form with address/hours/payment, doctor form with visit slots - Seed script: aligned to current SDK schema — doctors created as workspace members (HelixEngage Manager role), visitingHours replaced by doctorVisitSlot entity, clinics seeded, portalUserId linked dynamically, SUB/ORIGIN/GQL configurable via env vars - Pages: clinics + doctors CRUD updated for new schema, team settings with temp password + role assignment - New components: time-picker, day-selector, wizard-right-panes, wizard-layout-context, resume-setup-banner - Removed: invite-member-form (replaced by employee-create-form per no-email-invites rule) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -8,21 +8,37 @@ import { SlideoutMenu } from '@/components/application/slideout-menus/slideout-m
|
||||
import { TopBar } from '@/components/layout/top-bar';
|
||||
import {
|
||||
ClinicForm,
|
||||
clinicFormToGraphQLInput,
|
||||
clinicCoreToGraphQLInput,
|
||||
holidayInputsFromForm,
|
||||
requiredDocInputsFromForm,
|
||||
emptyClinicFormValues,
|
||||
type ClinicFormValues,
|
||||
type ClinicStatus,
|
||||
type DocumentType,
|
||||
type ClinicHolidayEntry,
|
||||
} from '@/components/forms/clinic-form';
|
||||
import { formatTimeLabel } from '@/components/application/date-picker/time-picker';
|
||||
import { formatDaySelection, type DaySelection } from '@/components/application/day-selector/day-selector';
|
||||
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).
|
||||
// /settings/clinics — list + add/edit slideout. Schema aligns with the
|
||||
// reworked Clinic entity in helix-engage/src/objects/clinic.object.ts:
|
||||
// - openMonday..openSunday (7 BOOLEANs) for the weekly pattern
|
||||
// - opensAt/closesAt (TEXT, HH:MM) for the shared daily time range
|
||||
// - two child entities: Holiday (closures) and ClinicRequiredDocument
|
||||
// (required-doc selection per clinic)
|
||||
//
|
||||
// Save flow:
|
||||
// 1. createClinic / updateClinic (main record)
|
||||
// 2. Fire child mutations in parallel:
|
||||
// - For holidays: delete-all-recreate on edit (simple, idempotent)
|
||||
// - For required docs: diff old vs new, delete removed, create added
|
||||
|
||||
type Clinic = {
|
||||
// -- Fetched shapes from the platform ----------------------------------------
|
||||
|
||||
type ClinicNode = {
|
||||
id: string;
|
||||
clinicName: string | null;
|
||||
status: ClinicStatus | null;
|
||||
@@ -35,14 +51,28 @@ type Clinic = {
|
||||
} | null;
|
||||
phone: { primaryPhoneNumber: string | null } | null;
|
||||
email: { primaryEmail: string | null } | null;
|
||||
weekdayHours: string | null;
|
||||
saturdayHours: string | null;
|
||||
sundayHours: string | null;
|
||||
openMonday: boolean | null;
|
||||
openTuesday: boolean | null;
|
||||
openWednesday: boolean | null;
|
||||
openThursday: boolean | null;
|
||||
openFriday: boolean | null;
|
||||
openSaturday: boolean | null;
|
||||
openSunday: boolean | null;
|
||||
opensAt: string | null;
|
||||
closesAt: string | null;
|
||||
walkInAllowed: boolean | null;
|
||||
onlineBooking: boolean | null;
|
||||
cancellationWindowHours: number | null;
|
||||
arriveEarlyMin: number | null;
|
||||
requiredDocuments: string | null;
|
||||
// Reverse-side collections. Platform exposes them as Relay edges.
|
||||
holidays?: {
|
||||
edges: Array<{
|
||||
node: { id: string; date: string | null; reasonLabel: string | null };
|
||||
}>;
|
||||
};
|
||||
clinicRequiredDocuments?: {
|
||||
edges: Array<{ node: { id: string; documentType: DocumentType | null } }>;
|
||||
};
|
||||
};
|
||||
|
||||
const CLINICS_QUERY = `{
|
||||
@@ -57,16 +87,34 @@ const CLINICS_QUERY = `{
|
||||
}
|
||||
phone { primaryPhoneNumber }
|
||||
email { primaryEmail }
|
||||
weekdayHours saturdayHours sundayHours
|
||||
openMonday openTuesday openWednesday openThursday openFriday openSaturday openSunday
|
||||
opensAt closesAt
|
||||
walkInAllowed onlineBooking
|
||||
cancellationWindowHours arriveEarlyMin
|
||||
requiredDocuments
|
||||
holidays(first: 50) {
|
||||
edges { node { id date reasonLabel } }
|
||||
}
|
||||
clinicRequiredDocuments(first: 50) {
|
||||
edges { node { id documentType } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}`;
|
||||
|
||||
const toFormValues = (clinic: Clinic): ClinicFormValues => ({
|
||||
// -- Helpers -----------------------------------------------------------------
|
||||
|
||||
const toDaySelection = (c: ClinicNode): DaySelection => ({
|
||||
monday: !!c.openMonday,
|
||||
tuesday: !!c.openTuesday,
|
||||
wednesday: !!c.openWednesday,
|
||||
thursday: !!c.openThursday,
|
||||
friday: !!c.openFriday,
|
||||
saturday: !!c.openSaturday,
|
||||
sunday: !!c.openSunday,
|
||||
});
|
||||
|
||||
const toFormValues = (clinic: ClinicNode): ClinicFormValues => ({
|
||||
clinicName: clinic.clinicName ?? '',
|
||||
addressStreet1: clinic.addressCustom?.addressStreet1 ?? '',
|
||||
addressStreet2: clinic.addressCustom?.addressStreet2 ?? '',
|
||||
@@ -75,15 +123,29 @@ const toFormValues = (clinic: Clinic): ClinicFormValues => ({
|
||||
addressPostcode: clinic.addressCustom?.addressPostcode ?? '',
|
||||
phone: clinic.phone?.primaryPhoneNumber ?? '',
|
||||
email: clinic.email?.primaryEmail ?? '',
|
||||
weekdayHours: clinic.weekdayHours ?? '',
|
||||
saturdayHours: clinic.saturdayHours ?? '',
|
||||
sundayHours: clinic.sundayHours ?? '',
|
||||
openDays: toDaySelection(clinic),
|
||||
opensAt: clinic.opensAt ?? null,
|
||||
closesAt: clinic.closesAt ?? null,
|
||||
status: clinic.status ?? 'ACTIVE',
|
||||
walkInAllowed: clinic.walkInAllowed ?? true,
|
||||
onlineBooking: clinic.onlineBooking ?? true,
|
||||
cancellationWindowHours: clinic.cancellationWindowHours != null ? String(clinic.cancellationWindowHours) : '',
|
||||
cancellationWindowHours:
|
||||
clinic.cancellationWindowHours != null ? String(clinic.cancellationWindowHours) : '',
|
||||
arriveEarlyMin: clinic.arriveEarlyMin != null ? String(clinic.arriveEarlyMin) : '',
|
||||
requiredDocuments: clinic.requiredDocuments ?? '',
|
||||
requiredDocumentTypes:
|
||||
clinic.clinicRequiredDocuments?.edges
|
||||
.map((e) => e.node.documentType)
|
||||
.filter((t): t is DocumentType => t !== null) ?? [],
|
||||
holidays:
|
||||
clinic.holidays?.edges
|
||||
.filter((e) => e.node.date) // date is required on create but platform may have nulls from earlier
|
||||
.map(
|
||||
(e): ClinicHolidayEntry => ({
|
||||
id: e.node.id,
|
||||
date: e.node.date ?? '',
|
||||
label: e.node.reasonLabel ?? '',
|
||||
}),
|
||||
) ?? [],
|
||||
});
|
||||
|
||||
const statusLabel: Record<ClinicStatus, string> = {
|
||||
@@ -98,17 +160,69 @@ const statusColor: Record<ClinicStatus, 'success' | 'warning' | 'gray'> = {
|
||||
PERMANENTLY_CLOSED: 'gray',
|
||||
};
|
||||
|
||||
// Save-flow helpers — each mutation is a thin wrapper so handleSave
|
||||
// reads linearly.
|
||||
const createClinicMutation = (data: Record<string, unknown>) =>
|
||||
apiClient.graphql<{ createClinic: { id: string } }>(
|
||||
`mutation CreateClinic($data: ClinicCreateInput!) {
|
||||
createClinic(data: $data) { id }
|
||||
}`,
|
||||
{ data },
|
||||
);
|
||||
|
||||
const updateClinicMutation = (id: string, data: Record<string, unknown>) =>
|
||||
apiClient.graphql<{ updateClinic: { id: string } }>(
|
||||
`mutation UpdateClinic($id: UUID!, $data: ClinicUpdateInput!) {
|
||||
updateClinic(id: $id, data: $data) { id }
|
||||
}`,
|
||||
{ id, data },
|
||||
);
|
||||
|
||||
const createHolidayMutation = (data: Record<string, unknown>) =>
|
||||
apiClient.graphql(
|
||||
`mutation CreateHoliday($data: HolidayCreateInput!) {
|
||||
createHoliday(data: $data) { id }
|
||||
}`,
|
||||
{ data },
|
||||
);
|
||||
|
||||
const deleteHolidayMutation = (id: string) =>
|
||||
apiClient.graphql(
|
||||
`mutation DeleteHoliday($id: UUID!) { deleteHoliday(id: $id) { id } }`,
|
||||
{ id },
|
||||
);
|
||||
|
||||
const createRequiredDocMutation = (data: Record<string, unknown>) =>
|
||||
apiClient.graphql(
|
||||
`mutation CreateClinicRequiredDocument($data: ClinicRequiredDocumentCreateInput!) {
|
||||
createClinicRequiredDocument(data: $data) { id }
|
||||
}`,
|
||||
{ data },
|
||||
);
|
||||
|
||||
const deleteRequiredDocMutation = (id: string) =>
|
||||
apiClient.graphql(
|
||||
`mutation DeleteClinicRequiredDocument($id: UUID!) {
|
||||
deleteClinicRequiredDocument(id: $id) { id }
|
||||
}`,
|
||||
{ id },
|
||||
);
|
||||
|
||||
// -- Page --------------------------------------------------------------------
|
||||
|
||||
export const ClinicsPage = () => {
|
||||
const [clinics, setClinics] = useState<Clinic[]>([]);
|
||||
const [clinics, setClinics] = useState<ClinicNode[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [slideoutOpen, setSlideoutOpen] = useState(false);
|
||||
const [editTarget, setEditTarget] = useState<Clinic | null>(null);
|
||||
const [editTarget, setEditTarget] = useState<ClinicNode | 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);
|
||||
const data = await apiClient.graphql<{ clinics: { edges: { node: ClinicNode }[] } }>(
|
||||
CLINICS_QUERY,
|
||||
);
|
||||
setClinics(data.clinics.edges.map((e) => e.node));
|
||||
} catch {
|
||||
// toast already shown by apiClient
|
||||
@@ -127,7 +241,7 @@ export const ClinicsPage = () => {
|
||||
setSlideoutOpen(true);
|
||||
};
|
||||
|
||||
const handleEdit = (clinic: Clinic) => {
|
||||
const handleEdit = (clinic: ClinicNode) => {
|
||||
setEditTarget(clinic);
|
||||
setFormValues(toFormValues(clinic));
|
||||
setSlideoutOpen(true);
|
||||
@@ -140,27 +254,47 @@ export const ClinicsPage = () => {
|
||||
}
|
||||
setIsSaving(true);
|
||||
try {
|
||||
const input = clinicFormToGraphQLInput(formValues);
|
||||
const coreInput = clinicCoreToGraphQLInput(formValues);
|
||||
|
||||
// 1. Upsert the clinic itself.
|
||||
let clinicId: string;
|
||||
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.`);
|
||||
await updateClinicMutation(editTarget.id, coreInput);
|
||||
clinicId = editTarget.id;
|
||||
} else {
|
||||
await apiClient.graphql(
|
||||
`mutation CreateClinic($data: ClinicCreateInput!) {
|
||||
createClinic(data: $data) { id }
|
||||
}`,
|
||||
{ data: input },
|
||||
);
|
||||
const res = await createClinicMutation(coreInput);
|
||||
clinicId = res.createClinic.id;
|
||||
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(() => {});
|
||||
}
|
||||
|
||||
// 2. Holidays — delete-all-recreate. Simple, always correct.
|
||||
if (editTarget?.holidays?.edges?.length) {
|
||||
await Promise.all(
|
||||
editTarget.holidays.edges.map((e) => deleteHolidayMutation(e.node.id)),
|
||||
);
|
||||
}
|
||||
if (formValues.holidays.length > 0) {
|
||||
const holidayInputs = holidayInputsFromForm(formValues, clinicId);
|
||||
await Promise.all(holidayInputs.map((data) => createHolidayMutation(data)));
|
||||
}
|
||||
|
||||
// 3. Required docs — delete-all-recreate for symmetry.
|
||||
if (editTarget?.clinicRequiredDocuments?.edges?.length) {
|
||||
await Promise.all(
|
||||
editTarget.clinicRequiredDocuments.edges.map((e) =>
|
||||
deleteRequiredDocMutation(e.node.id),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (formValues.requiredDocumentTypes.length > 0) {
|
||||
const docInputs = requiredDocInputsFromForm(formValues, clinicId);
|
||||
await Promise.all(docInputs.map((data) => createRequiredDocMutation(data)));
|
||||
}
|
||||
|
||||
if (editTarget) {
|
||||
notify.success('Clinic updated', `${formValues.clinicName} has been updated.`);
|
||||
}
|
||||
await fetchClinics();
|
||||
close();
|
||||
} catch (err) {
|
||||
@@ -170,7 +304,10 @@ export const ClinicsPage = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const activeCount = useMemo(() => clinics.filter((c) => c.status === 'ACTIVE').length, [clinics]);
|
||||
const activeCount = useMemo(
|
||||
() => clinics.filter((c) => c.status === 'ACTIVE').length,
|
||||
[clinics],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col overflow-hidden">
|
||||
@@ -231,6 +368,11 @@ export const ClinicsPage = () => {
|
||||
.filter(Boolean)
|
||||
.join(', ');
|
||||
const status = clinic.status ?? 'ACTIVE';
|
||||
const dayLabel = formatDaySelection(toDaySelection(clinic));
|
||||
const hoursLabel =
|
||||
clinic.opensAt && clinic.closesAt
|
||||
? `${formatTimeLabel(clinic.opensAt)}–${formatTimeLabel(clinic.closesAt)}`
|
||||
: 'Not set';
|
||||
return (
|
||||
<Table.Row id={clinic.id}>
|
||||
<Table.Cell>
|
||||
@@ -252,9 +394,10 @@ export const ClinicsPage = () => {
|
||||
</div>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<span className="text-xs text-tertiary">
|
||||
{clinic.weekdayHours ?? 'Not set'}
|
||||
</span>
|
||||
<div className="flex flex-col">
|
||||
<span className="text-sm text-primary">{dayLabel}</span>
|
||||
<span className="text-xs text-tertiary">{hoursLabel}</span>
|
||||
</div>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<Badge size="sm" color={statusColor[status]} type="pill-color">
|
||||
|
||||
@@ -8,36 +8,54 @@ import { SlideoutMenu } from '@/components/application/slideout-menus/slideout-m
|
||||
import { TopBar } from '@/components/layout/top-bar';
|
||||
import {
|
||||
DoctorForm,
|
||||
doctorFormToGraphQLInput,
|
||||
doctorCoreToGraphQLInput,
|
||||
visitSlotInputsFromForm,
|
||||
emptyDoctorFormValues,
|
||||
type DoctorDepartment,
|
||||
type DoctorFormValues,
|
||||
type DayOfWeek,
|
||||
type DoctorVisitSlotEntry,
|
||||
} 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.
|
||||
// /settings/doctors — list + add/edit slideout. Doctors are hospital-
|
||||
// wide; their multi-clinic visiting schedule is modelled as a list of
|
||||
// DoctorVisitSlot child records fetched through the reverse relation.
|
||||
//
|
||||
// Save flow mirrors clinics.tsx: create/update the core doctor row,
|
||||
// then delete-all-recreate the visit slots. Slots are recreated in
|
||||
// parallel (Promise.all). Pre-existing slots from the fetched record
|
||||
// get their id propagated into form state so edit mode shows the
|
||||
// current schedule.
|
||||
|
||||
type Doctor = {
|
||||
type DoctorNode = {
|
||||
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;
|
||||
// Reverse-side relation to DoctorVisitSlot records.
|
||||
doctorVisitSlots?: {
|
||||
edges: Array<{
|
||||
node: {
|
||||
id: string;
|
||||
clinicId: string | null;
|
||||
clinic: { id: string; clinicName: string | null } | null;
|
||||
dayOfWeek: DayOfWeek | null;
|
||||
startTime: string | null;
|
||||
endTime: string | null;
|
||||
};
|
||||
}>;
|
||||
};
|
||||
};
|
||||
|
||||
type ClinicLite = { id: string; clinicName: string | null };
|
||||
@@ -49,15 +67,24 @@ const DOCTORS_QUERY = `{
|
||||
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 }
|
||||
doctorVisitSlots(first: 50) {
|
||||
edges {
|
||||
node {
|
||||
id
|
||||
clinicId
|
||||
clinic { id clinicName }
|
||||
dayOfWeek
|
||||
startTime
|
||||
endTime
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -75,15 +102,23 @@ const departmentLabel: Record<DoctorDepartment, string> = {
|
||||
ONCOLOGY: 'Oncology',
|
||||
};
|
||||
|
||||
const toFormValues = (doctor: Doctor): DoctorFormValues => ({
|
||||
const dayLabel: Record<DayOfWeek, string> = {
|
||||
MONDAY: 'Mon',
|
||||
TUESDAY: 'Tue',
|
||||
WEDNESDAY: 'Wed',
|
||||
THURSDAY: 'Thu',
|
||||
FRIDAY: 'Fri',
|
||||
SATURDAY: 'Sat',
|
||||
SUNDAY: 'Sun',
|
||||
};
|
||||
|
||||
const toFormValues = (doctor: DoctorNode): 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))
|
||||
: '',
|
||||
@@ -94,6 +129,16 @@ const toFormValues = (doctor: Doctor): DoctorFormValues => ({
|
||||
email: doctor.email?.primaryEmail ?? '',
|
||||
registrationNumber: doctor.registrationNumber ?? '',
|
||||
active: doctor.active ?? true,
|
||||
visitSlots:
|
||||
doctor.doctorVisitSlots?.edges.map(
|
||||
(e): DoctorVisitSlotEntry => ({
|
||||
id: e.node.id,
|
||||
clinicId: e.node.clinicId ?? e.node.clinic?.id ?? '',
|
||||
dayOfWeek: e.node.dayOfWeek ?? '',
|
||||
startTime: e.node.startTime ?? null,
|
||||
endTime: e.node.endTime ?? null,
|
||||
}),
|
||||
) ?? [],
|
||||
});
|
||||
|
||||
const formatFee = (money: { amountMicros: number | null } | null): string => {
|
||||
@@ -101,19 +146,79 @@ const formatFee = (money: { amountMicros: number | null } | null): string => {
|
||||
return `₹${Math.round(money.amountMicros / 1_000_000).toLocaleString('en-IN')}`;
|
||||
};
|
||||
|
||||
// Compact "clinics + days" summary for the list row. Groups by clinic
|
||||
// so "Koramangala: Mon Wed / Whitefield: Tue Thu Fri" is one string.
|
||||
const summariseVisitSlots = (
|
||||
doctor: DoctorNode,
|
||||
clinicNameById: Map<string, string>,
|
||||
): string => {
|
||||
const edges = doctor.doctorVisitSlots?.edges ?? [];
|
||||
if (edges.length === 0) return 'No slots';
|
||||
const byClinic = new Map<string, DayOfWeek[]>();
|
||||
for (const e of edges) {
|
||||
const cid = e.node.clinicId ?? e.node.clinic?.id;
|
||||
if (!cid || !e.node.dayOfWeek) continue;
|
||||
if (!byClinic.has(cid)) byClinic.set(cid, []);
|
||||
byClinic.get(cid)!.push(e.node.dayOfWeek);
|
||||
}
|
||||
const parts: string[] = [];
|
||||
for (const [cid, days] of byClinic.entries()) {
|
||||
const name = clinicNameById.get(cid) ?? 'Unknown clinic';
|
||||
const dayStr = days.map((d) => dayLabel[d]).join(' ');
|
||||
parts.push(`${name}: ${dayStr}`);
|
||||
}
|
||||
return parts.join(' · ');
|
||||
};
|
||||
|
||||
// -- Mutation helpers --------------------------------------------------------
|
||||
|
||||
const createDoctorMutation = (data: Record<string, unknown>) =>
|
||||
apiClient.graphql<{ createDoctor: { id: string } }>(
|
||||
`mutation CreateDoctor($data: DoctorCreateInput!) {
|
||||
createDoctor(data: $data) { id }
|
||||
}`,
|
||||
{ data },
|
||||
);
|
||||
|
||||
const updateDoctorMutation = (id: string, data: Record<string, unknown>) =>
|
||||
apiClient.graphql<{ updateDoctor: { id: string } }>(
|
||||
`mutation UpdateDoctor($id: UUID!, $data: DoctorUpdateInput!) {
|
||||
updateDoctor(id: $id, data: $data) { id }
|
||||
}`,
|
||||
{ id, data },
|
||||
);
|
||||
|
||||
const createVisitSlotMutation = (data: Record<string, unknown>) =>
|
||||
apiClient.graphql(
|
||||
`mutation CreateDoctorVisitSlot($data: DoctorVisitSlotCreateInput!) {
|
||||
createDoctorVisitSlot(data: $data) { id }
|
||||
}`,
|
||||
{ data },
|
||||
);
|
||||
|
||||
const deleteVisitSlotMutation = (id: string) =>
|
||||
apiClient.graphql(
|
||||
`mutation DeleteDoctorVisitSlot($id: UUID!) {
|
||||
deleteDoctorVisitSlot(id: $id) { id }
|
||||
}`,
|
||||
{ id },
|
||||
);
|
||||
|
||||
// -- Page --------------------------------------------------------------------
|
||||
|
||||
export const DoctorsPage = () => {
|
||||
const [doctors, setDoctors] = useState<Doctor[]>([]);
|
||||
const [doctors, setDoctors] = useState<DoctorNode[]>([]);
|
||||
const [clinics, setClinics] = useState<ClinicLite[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [slideoutOpen, setSlideoutOpen] = useState(false);
|
||||
const [editTarget, setEditTarget] = useState<Doctor | null>(null);
|
||||
const [editTarget, setEditTarget] = useState<DoctorNode | 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 }[] };
|
||||
doctors: { edges: { node: DoctorNode }[] };
|
||||
clinics: { edges: { node: ClinicLite }[] };
|
||||
}>(DOCTORS_QUERY);
|
||||
setDoctors(data.doctors.edges.map((e) => e.node));
|
||||
@@ -152,7 +257,7 @@ export const DoctorsPage = () => {
|
||||
setSlideoutOpen(true);
|
||||
};
|
||||
|
||||
const handleEdit = (doctor: Doctor) => {
|
||||
const handleEdit = (doctor: DoctorNode) => {
|
||||
setEditTarget(doctor);
|
||||
setFormValues(toFormValues(doctor));
|
||||
setSlideoutOpen(true);
|
||||
@@ -165,25 +270,36 @@ export const DoctorsPage = () => {
|
||||
}
|
||||
setIsSaving(true);
|
||||
try {
|
||||
const input = doctorFormToGraphQLInput(formValues);
|
||||
const coreInput = doctorCoreToGraphQLInput(formValues);
|
||||
|
||||
// 1. Upsert doctor
|
||||
let doctorId: string;
|
||||
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}`);
|
||||
await updateDoctorMutation(editTarget.id, coreInput);
|
||||
doctorId = editTarget.id;
|
||||
} else {
|
||||
await apiClient.graphql(
|
||||
`mutation CreateDoctor($data: DoctorCreateInput!) {
|
||||
createDoctor(data: $data) { id }
|
||||
}`,
|
||||
{ data: input },
|
||||
);
|
||||
const res = await createDoctorMutation(coreInput);
|
||||
doctorId = res.createDoctor.id;
|
||||
notify.success('Doctor added', `Dr. ${formValues.firstName} ${formValues.lastName}`);
|
||||
markSetupStepComplete('doctors').catch(() => {});
|
||||
}
|
||||
|
||||
// 2. Visit slots — delete-all-recreate, same pattern as
|
||||
// clinics.tsx holidays/requiredDocs. Simple, always correct,
|
||||
// acceptable overhead at human-edit frequency.
|
||||
if (editTarget?.doctorVisitSlots?.edges?.length) {
|
||||
await Promise.all(
|
||||
editTarget.doctorVisitSlots.edges.map((e) => deleteVisitSlotMutation(e.node.id)),
|
||||
);
|
||||
}
|
||||
const slotInputs = visitSlotInputsFromForm(formValues, doctorId);
|
||||
if (slotInputs.length > 0) {
|
||||
await Promise.all(slotInputs.map((data) => createVisitSlotMutation(data)));
|
||||
}
|
||||
|
||||
if (editTarget) {
|
||||
notify.success('Doctor updated', `Dr. ${formValues.firstName} ${formValues.lastName}`);
|
||||
}
|
||||
await fetchAll();
|
||||
close();
|
||||
} catch (err) {
|
||||
@@ -242,7 +358,7 @@ export const DoctorsPage = () => {
|
||||
<Table.Header>
|
||||
<Table.Head label="DOCTOR" isRowHeader />
|
||||
<Table.Head label="DEPARTMENT" />
|
||||
<Table.Head label="CLINIC" />
|
||||
<Table.Head label="VISITING SCHEDULE" />
|
||||
<Table.Head label="FEE (NEW)" />
|
||||
<Table.Head label="STATUS" />
|
||||
<Table.Head label="" />
|
||||
@@ -252,10 +368,6 @@ export const DoctorsPage = () => {
|
||||
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>
|
||||
@@ -272,7 +384,9 @@ export const DoctorsPage = () => {
|
||||
</span>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<span className="text-sm text-tertiary">{clinicName}</span>
|
||||
<span className="text-xs text-tertiary">
|
||||
{summariseVisitSlots(doctor, clinicNameById)}
|
||||
</span>
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<span className="text-sm text-tertiary">
|
||||
@@ -323,7 +437,7 @@ export const DoctorsPage = () => {
|
||||
</h2>
|
||||
<p className="text-sm text-tertiary">
|
||||
{editTarget
|
||||
? 'Update clinician details and clinic assignment'
|
||||
? 'Update clinician details and visiting schedule'
|
||||
: 'Add a new clinician to your hospital'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -80,14 +80,13 @@ export const SetupWizardPage = () => {
|
||||
const onNext = !isLastStep ? () => setActiveStep(SETUP_STEP_NAMES[activeIndex + 1]) : null;
|
||||
|
||||
const handleComplete = async (step: SetupStepName) => {
|
||||
try {
|
||||
const updated = await markSetupStepComplete(step, user?.email);
|
||||
setState(updated);
|
||||
} catch (err) {
|
||||
console.error('Failed to mark step complete', err);
|
||||
// Non-fatal — the step's own save already succeeded. We just
|
||||
// couldn't persist the wizard-state badge.
|
||||
}
|
||||
// No try/catch here — if the setup-state PUT fails, we WANT
|
||||
// the error to propagate up to the step's handleSave so the
|
||||
// agent sees a toast AND the advance flow pauses until the
|
||||
// issue is resolved. Silent swallowing hid the real failure
|
||||
// mode during the Ramaiah local test.
|
||||
const updated = await markSetupStepComplete(step, user?.email);
|
||||
setState(updated);
|
||||
};
|
||||
|
||||
const handleAdvance = () => {
|
||||
|
||||
@@ -9,25 +9,21 @@ 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,
|
||||
EmployeeCreateForm,
|
||||
emptyEmployeeCreateFormValues,
|
||||
type EmployeeCreateFormValues,
|
||||
type RoleOption,
|
||||
} from '@/components/forms/invite-member-form';
|
||||
} from '@/components/forms/employee-create-form';
|
||||
import { apiClient } from '@/lib/api-client';
|
||||
import { notify } from '@/lib/toast';
|
||||
import { getInitials } from '@/lib/format';
|
||||
import { markSetupStepComplete } from '@/lib/setup-state';
|
||||
|
||||
// /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.
|
||||
//
|
||||
// Invitations mark the setup-state `team` step complete on first success so
|
||||
// the wizard can advance.
|
||||
// /settings/team — in-place employee management. Fetches real roles + SIP
|
||||
// seats from the platform and uses the sidecar's /api/team/members
|
||||
// endpoint to create workspace members directly with a temp password
|
||||
// that the admin hands out (no email invitations — see
|
||||
// feedback-no-invites in memory). Also lets admins change a member's
|
||||
// role via updateWorkspaceMemberRole.
|
||||
|
||||
type MemberRole = {
|
||||
id: string;
|
||||
@@ -39,10 +35,22 @@ type WorkspaceMember = {
|
||||
name: { firstName: string; lastName: string } | null;
|
||||
userEmail: string;
|
||||
avatarUrl: string | null;
|
||||
roles: MemberRole[];
|
||||
// Platform returns null (not []) for members with no role assigned —
|
||||
// optional-chain when reading.
|
||||
roles: MemberRole[] | null;
|
||||
};
|
||||
|
||||
const MEMBERS_QUERY = `{
|
||||
type CreatedMemberResponse = {
|
||||
id: string;
|
||||
userEmail: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
roleId: string;
|
||||
};
|
||||
|
||||
// Combined query — workspace members + assignable roles. Bundled to
|
||||
// save a round-trip and keep the table consistent across the join.
|
||||
const TEAM_QUERY = `{
|
||||
workspaceMembers(first: 100) {
|
||||
edges {
|
||||
node {
|
||||
@@ -54,9 +62,6 @@ const MEMBERS_QUERY = `{
|
||||
}
|
||||
}
|
||||
}
|
||||
}`;
|
||||
|
||||
const ROLES_QUERY = `{
|
||||
getRoles {
|
||||
id
|
||||
label
|
||||
@@ -69,31 +74,32 @@ 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);
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [createValues, setCreateValues] = useState<EmployeeCreateFormValues>(
|
||||
emptyEmployeeCreateFormValues,
|
||||
);
|
||||
const [isCreating, setIsCreating] = useState(false);
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
try {
|
||||
const [memberData, roleData] = await Promise.all([
|
||||
apiClient.graphql<{ workspaceMembers: { edges: { node: WorkspaceMember }[] } }>(
|
||||
MEMBERS_QUERY,
|
||||
undefined,
|
||||
{ silent: true },
|
||||
),
|
||||
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));
|
||||
const data = await apiClient.graphql<{
|
||||
workspaceMembers: { edges: { node: WorkspaceMember }[] };
|
||||
getRoles: {
|
||||
id: string;
|
||||
label: string;
|
||||
description: string | null;
|
||||
canBeAssignedToUsers: boolean;
|
||||
}[];
|
||||
}>(TEAM_QUERY, undefined, { silent: true });
|
||||
|
||||
setMembers(data.workspaceMembers.edges.map((e) => e.node));
|
||||
const assignable = data.getRoles.filter((r) => r.canBeAssignedToUsers);
|
||||
setRoles(
|
||||
roleData.getRoles
|
||||
.filter((r) => r.canBeAssignedToUsers)
|
||||
.map((r) => ({
|
||||
id: r.id,
|
||||
label: r.label,
|
||||
supportingText: r.description ?? undefined,
|
||||
})),
|
||||
assignable.map((r) => ({
|
||||
id: r.id,
|
||||
label: r.label,
|
||||
supportingText: r.description ?? undefined,
|
||||
})),
|
||||
);
|
||||
} catch {
|
||||
// silently fail
|
||||
@@ -150,38 +156,46 @@ export const TeamSettingsPage = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleSendInvites = async (close: () => void) => {
|
||||
if (inviteValues.emails.length === 0) {
|
||||
notify.error('Add at least one email');
|
||||
const handleCreateMember = async (close: () => void) => {
|
||||
const firstName = createValues.firstName.trim();
|
||||
const email = createValues.email.trim();
|
||||
if (!firstName) {
|
||||
notify.error('First name is required');
|
||||
return;
|
||||
}
|
||||
setIsSending(true);
|
||||
if (!email) {
|
||||
notify.error('Email is required');
|
||||
return;
|
||||
}
|
||||
if (!createValues.password) {
|
||||
notify.error('Temporary password is required');
|
||||
return;
|
||||
}
|
||||
if (!createValues.roleId) {
|
||||
notify.error('Pick a role');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsCreating(true);
|
||||
try {
|
||||
await apiClient.graphql(
|
||||
`mutation SendInvitations($emails: [String!]!) {
|
||||
sendInvitations(emails: $emails) {
|
||||
success
|
||||
errors
|
||||
result {
|
||||
email
|
||||
id
|
||||
}
|
||||
}
|
||||
}`,
|
||||
{ emails: inviteValues.emails },
|
||||
);
|
||||
await apiClient.post<CreatedMemberResponse>('/api/team/members', {
|
||||
firstName,
|
||||
lastName: createValues.lastName.trim(),
|
||||
email,
|
||||
password: createValues.password,
|
||||
roleId: createValues.roleId,
|
||||
});
|
||||
notify.success(
|
||||
'Invitations sent',
|
||||
`${inviteValues.emails.length} invitation${inviteValues.emails.length === 1 ? '' : 's'} sent.`,
|
||||
'Employee created',
|
||||
`${firstName} ${createValues.lastName.trim()}`.trim() || email,
|
||||
);
|
||||
markSetupStepComplete('team').catch(() => {});
|
||||
setInviteValues({ emails: [], roleId: '' });
|
||||
setCreateValues(emptyEmployeeCreateFormValues);
|
||||
await fetchData();
|
||||
close();
|
||||
} catch (err) {
|
||||
console.error('[team] invite failed', err);
|
||||
console.error('[team] create failed', err);
|
||||
} finally {
|
||||
setIsSending(false);
|
||||
setIsCreating(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -215,11 +229,11 @@ export const TeamSettingsPage = () => {
|
||||
<FontAwesomeIcon icon={faUserPlus} className={className} />
|
||||
)}
|
||||
onClick={() => {
|
||||
setInviteValues({ emails: [], roleId: '' });
|
||||
setInviteOpen(true);
|
||||
setCreateValues(emptyEmployeeCreateFormValues);
|
||||
setCreateOpen(true);
|
||||
}}
|
||||
>
|
||||
Invite members
|
||||
Add employee
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
@@ -244,7 +258,8 @@ export const TeamSettingsPage = () => {
|
||||
const lastName = member.name?.lastName ?? '';
|
||||
const fullName = `${firstName} ${lastName}`.trim() || 'Unnamed';
|
||||
const initials = getInitials(firstName || '?', lastName || '?');
|
||||
const currentRoleId = member.roles[0]?.id ?? null;
|
||||
const memberRoles = member.roles ?? [];
|
||||
const currentRoleId = memberRoles[0]?.id ?? null;
|
||||
|
||||
return (
|
||||
<Table.Row id={member.id}>
|
||||
@@ -284,9 +299,9 @@ export const TeamSettingsPage = () => {
|
||||
)}
|
||||
</Select>
|
||||
</div>
|
||||
) : member.roles.length > 0 ? (
|
||||
) : memberRoles.length > 0 ? (
|
||||
<Badge size="sm" color="gray">
|
||||
{member.roles[0].label}
|
||||
{memberRoles[0].label}
|
||||
</Badge>
|
||||
) : (
|
||||
<span className="text-xs text-quaternary">No role</span>
|
||||
@@ -344,7 +359,7 @@ export const TeamSettingsPage = () => {
|
||||
</TableCard.Root>
|
||||
</div>
|
||||
|
||||
<SlideoutMenu isOpen={inviteOpen} onOpenChange={setInviteOpen} isDismissable>
|
||||
<SlideoutMenu isOpen={createOpen} onOpenChange={setCreateOpen} isDismissable>
|
||||
{({ close }) => (
|
||||
<>
|
||||
<SlideoutMenu.Header onClose={close}>
|
||||
@@ -353,19 +368,23 @@ export const TeamSettingsPage = () => {
|
||||
<FontAwesomeIcon icon={faUserPlus} className="size-5 text-fg-brand-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-primary">Invite members</h2>
|
||||
<h2 className="text-lg font-semibold text-primary">Add employee</h2>
|
||||
<p className="text-sm text-tertiary">
|
||||
Send invitations to supervisors, agents, and doctors
|
||||
Create supervisors, CC agents and admins in place
|
||||
</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.
|
||||
<EmployeeCreateForm
|
||||
value={createValues}
|
||||
onChange={setCreateValues}
|
||||
roles={roles}
|
||||
/>
|
||||
<p className="mt-4 text-xs text-tertiary">
|
||||
The employee logs in with this email and the temporary password
|
||||
you set. Share both with them directly — no email is sent.
|
||||
</p>
|
||||
</SlideoutMenu.Content>
|
||||
|
||||
@@ -377,16 +396,11 @@ export const TeamSettingsPage = () => {
|
||||
<Button
|
||||
size="md"
|
||||
color="primary"
|
||||
isLoading={isSending}
|
||||
isLoading={isCreating}
|
||||
showTextWhileLoading
|
||||
onClick={() => handleSendInvites(close)}
|
||||
isDisabled={inviteValues.emails.length === 0}
|
||||
onClick={() => handleCreateMember(close)}
|
||||
>
|
||||
{isSending
|
||||
? 'Sending...'
|
||||
: `Send ${inviteValues.emails.length || ''} invitation${
|
||||
inviteValues.emails.length === 1 ? '' : 's'
|
||||
}`.trim()}
|
||||
{isCreating ? 'Creating…' : 'Create employee'}
|
||||
</Button>
|
||||
</div>
|
||||
</SlideoutMenu.Footer>
|
||||
|
||||
Reference in New Issue
Block a user