mirror of
https://github.com/temetro/temetro.git
synced 2026-08-30 12:19:07 +00:00
Merge pull request #1 from temetro/feat/clinic-six-improvements
Six improvements: messages search, care-team admin, per-doctor patients + transfer, activity, analytics
This commit is contained in:
@@ -0,0 +1,2 @@
|
|||||||
|
ALTER TABLE "patients" ADD COLUMN "primary_provider_id" text;--> statement-breakpoint
|
||||||
|
ALTER TABLE "patients" ADD CONSTRAINT "patients_primary_provider_id_user_id_fk" FOREIGN KEY ("primary_provider_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -64,6 +64,13 @@
|
|||||||
"when": 1780937195597,
|
"when": 1780937195597,
|
||||||
"tag": "0008_luxuriant_blue_blade",
|
"tag": "0008_luxuriant_blue_blade",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 9,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1781022080228,
|
||||||
|
"tag": "0009_melted_puck",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -44,6 +44,12 @@ export const patients = pgTable(
|
|||||||
vitalsTakenAt: text("vitals_taken_at").notNull(),
|
vitalsTakenAt: text("vitals_taken_at").notNull(),
|
||||||
vitalsTrend: jsonb("vitals_trend").$type<Trend>().notNull(),
|
vitalsTrend: jsonb("vitals_trend").$type<Trend>().notNull(),
|
||||||
labTrend: jsonb("lab_trend").$type<Trend>().notNull(),
|
labTrend: jsonb("lab_trend").$type<Trend>().notNull(),
|
||||||
|
// The clinician responsible for this chart (the patient's "PCP"). Used to
|
||||||
|
// scope what each doctor sees and to transfer a patient between providers.
|
||||||
|
// Nullable: legacy/unassigned rows and patients registered by reception.
|
||||||
|
primaryProviderId: text("primary_provider_id").references(() => user.id, {
|
||||||
|
onDelete: "set null",
|
||||||
|
}),
|
||||||
createdBy: text("created_by").references(() => user.id, {
|
createdBy: text("created_by").references(() => user.id, {
|
||||||
onDelete: "set null",
|
onDelete: "set null",
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -55,6 +55,11 @@ export const patientInputSchema = z.object({
|
|||||||
age: z.number().int().min(0).max(150),
|
age: z.number().int().min(0).max(150),
|
||||||
sex: z.enum(["M", "F"]),
|
sex: z.enum(["M", "F"]),
|
||||||
pcp: z.string(),
|
pcp: z.string(),
|
||||||
|
// Optional link to the responsible clinician (user id). Empty string ⇒ null.
|
||||||
|
primaryProviderId: z.preprocess(
|
||||||
|
(v) => (v === "" ? null : v),
|
||||||
|
z.string().nullable().optional(),
|
||||||
|
),
|
||||||
status: z.enum(["active", "inpatient", "discharged"]),
|
status: z.enum(["active", "inpatient", "discharged"]),
|
||||||
initials: z.string().trim().min(1).max(4),
|
initials: z.string().trim().min(1).max(4),
|
||||||
allergies: z.array(allergySchema).default([]),
|
allergies: z.array(allergySchema).default([]),
|
||||||
|
|||||||
@@ -8,9 +8,19 @@ export const activityRouter = Router();
|
|||||||
// The audit feed is readable by any clinic member.
|
// The audit feed is readable by any clinic member.
|
||||||
activityRouter.use(requireAuth, requireOrg);
|
activityRouter.use(requireAuth, requireOrg);
|
||||||
|
|
||||||
|
// Whether the caller runs the clinic (owner/admin) and may therefore see the
|
||||||
|
// whole feed. Everyone else is scoped to their own actions.
|
||||||
|
function isClinicAdmin(memberRole: string | undefined): boolean {
|
||||||
|
return String(memberRole ?? "")
|
||||||
|
.split(",")
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.some((r) => r === "owner" || r === "admin");
|
||||||
|
}
|
||||||
|
|
||||||
activityRouter.get("/", async (req, res, next) => {
|
activityRouter.get("/", async (req, res, next) => {
|
||||||
try {
|
try {
|
||||||
res.json(await service.listActivity(req.organizationId!));
|
const actorId = isClinicAdmin(req.memberRole) ? undefined : req.user!.id;
|
||||||
|
res.json(await service.listActivity(req.organizationId!, { actorId }));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
next(err);
|
next(err);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
|
import { and, eq } from "drizzle-orm";
|
||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
import { db } from "../db/index.js";
|
||||||
|
import { member, user } from "../db/schema/auth.js";
|
||||||
import { HttpError } from "../lib/http-error.js";
|
import { HttpError } from "../lib/http-error.js";
|
||||||
import { patientInputSchema } from "../lib/patient-validation.js";
|
import { patientInputSchema } from "../lib/patient-validation.js";
|
||||||
import {
|
import {
|
||||||
@@ -15,6 +19,29 @@ import * as service from "../services/patients.js";
|
|||||||
|
|
||||||
export const patientsRouter = Router();
|
export const patientsRouter = Router();
|
||||||
|
|
||||||
|
const transferInputSchema = z.object({
|
||||||
|
providerId: z.string().trim().min(1),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Only the `doctor` role is scoped to its own panel of patients. Any elevated
|
||||||
|
// clinical role (owner / admin / member) sees the whole clinic, so scoping never
|
||||||
|
// applies when the caller also holds one of those. Returns the user id to scope
|
||||||
|
// by, or undefined for "see everything".
|
||||||
|
function providerScope(
|
||||||
|
memberRole: string | undefined,
|
||||||
|
userId: string,
|
||||||
|
): string | undefined {
|
||||||
|
const names = String(memberRole ?? "")
|
||||||
|
.split(",")
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
if (!names.includes("doctor")) return undefined;
|
||||||
|
if (names.some((r) => ["owner", "admin", "member"].includes(r))) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return userId;
|
||||||
|
}
|
||||||
|
|
||||||
// The `reception` role is scoped to scheduling + registration: it sees and
|
// The `reception` role is scoped to scheduling + registration: it sees and
|
||||||
// writes patient demographics only, never clinical PHI. True only when the
|
// writes patient demographics only, never clinical PHI. True only when the
|
||||||
// caller's role set is reception without any clinical-capable role.
|
// caller's role set is reception without any clinical-capable role.
|
||||||
@@ -66,6 +93,7 @@ patientsRouter.get(
|
|||||||
await service.listPatients(
|
await service.listPatients(
|
||||||
req.organizationId!,
|
req.organizationId!,
|
||||||
isReceptionOnly(req.memberRole),
|
isReceptionOnly(req.memberRole),
|
||||||
|
providerScope(req.memberRole, req.user!.id),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -83,6 +111,7 @@ patientsRouter.get(
|
|||||||
req.organizationId!,
|
req.organizationId!,
|
||||||
req.params.fileNumber as string,
|
req.params.fileNumber as string,
|
||||||
isReceptionOnly(req.memberRole),
|
isReceptionOnly(req.memberRole),
|
||||||
|
providerScope(req.memberRole, req.user!.id),
|
||||||
);
|
);
|
||||||
if (!patient) throw new HttpError(404, "Patient not found.");
|
if (!patient) throw new HttpError(404, "Patient not found.");
|
||||||
res.json(patient);
|
res.json(patient);
|
||||||
@@ -161,6 +190,59 @@ patientsRouter.put(
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Reassign a patient to another clinician ("transfer"). Gated on patient:write
|
||||||
|
// like any edit; the new provider must be a member of the same clinic.
|
||||||
|
patientsRouter.post(
|
||||||
|
"/:fileNumber/transfer",
|
||||||
|
requirePermission({ patient: ["write"] }),
|
||||||
|
async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const { providerId } = transferInputSchema.parse(req.body);
|
||||||
|
const [provider] = await db
|
||||||
|
.select({ name: user.name })
|
||||||
|
.from(member)
|
||||||
|
.innerJoin(user, eq(user.id, member.userId))
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(member.organizationId, req.organizationId!),
|
||||||
|
eq(member.userId, providerId),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (!provider) {
|
||||||
|
throw new HttpError(400, "Selected provider is not a member of this clinic.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const updated = await service.transferPatient(
|
||||||
|
req.organizationId!,
|
||||||
|
req.params.fileNumber as string,
|
||||||
|
providerId,
|
||||||
|
provider.name,
|
||||||
|
providerScope(req.memberRole, req.user!.id),
|
||||||
|
);
|
||||||
|
if (!updated) throw new HttpError(404, "Patient not found.");
|
||||||
|
|
||||||
|
await recordActivity({
|
||||||
|
orgId: req.organizationId!,
|
||||||
|
actor: { id: req.user!.id, name: req.user!.name },
|
||||||
|
action: `Transferred patient ${updated.name} to ${provider.name}`,
|
||||||
|
entityType: "patient",
|
||||||
|
entityId: updated.fileNumber,
|
||||||
|
patientName: updated.name,
|
||||||
|
patientFileNumber: updated.fileNumber,
|
||||||
|
});
|
||||||
|
await notifyClinic(
|
||||||
|
req.organizationId!,
|
||||||
|
{ id: req.user!.id, name: req.user!.name },
|
||||||
|
`${req.user!.name} transferred ${updated.name} to ${provider.name}`,
|
||||||
|
updated.fileNumber,
|
||||||
|
);
|
||||||
|
res.json(updated);
|
||||||
|
} catch (err) {
|
||||||
|
next(err);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
patientsRouter.delete(
|
patientsRouter.delete(
|
||||||
"/:fileNumber",
|
"/:fileNumber",
|
||||||
requirePermission({ patient: ["delete"] }),
|
requirePermission({ patient: ["delete"] }),
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { asc, eq } from "drizzle-orm";
|
import { and, asc, eq, inArray } from "drizzle-orm";
|
||||||
import { Router } from "express";
|
import { Router } from "express";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
@@ -45,6 +45,36 @@ const staffInputSchema = z.object({
|
|||||||
|
|
||||||
staffRouter.use(requireAuth, requireOrg);
|
staffRouter.use(requireAuth, requireOrg);
|
||||||
|
|
||||||
|
// Clinical-capable roles that can be a patient's primary provider. Reception
|
||||||
|
// (front desk) and viewer (read-only) are excluded.
|
||||||
|
const PROVIDER_ROLES = ["owner", "admin", "doctor", "member"] as const;
|
||||||
|
|
||||||
|
// List clinicians who can be assigned as a patient's primary provider. Readable
|
||||||
|
// by ANY clinic member (no `member:create` gate) so doctors and reception can
|
||||||
|
// pick a provider when registering/transferring a patient. Returns user ids.
|
||||||
|
staffRouter.get("/providers", async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const rows = await db
|
||||||
|
.select({
|
||||||
|
userId: member.userId,
|
||||||
|
name: user.name,
|
||||||
|
role: member.role,
|
||||||
|
})
|
||||||
|
.from(member)
|
||||||
|
.innerJoin(user, eq(user.id, member.userId))
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(member.organizationId, req.organizationId!),
|
||||||
|
inArray(member.role, PROVIDER_ROLES as unknown as string[]),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.orderBy(asc(user.name));
|
||||||
|
res.json(rows);
|
||||||
|
} catch (err) {
|
||||||
|
next(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// List the clinic's members with their usernames (the org client's
|
// List the clinic's members with their usernames (the org client's
|
||||||
// getFullOrganization doesn't expose username). Owner/admin only.
|
// getFullOrganization doesn't expose username). Owner/admin only.
|
||||||
staffRouter.get(
|
staffRouter.get(
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { desc, eq } from "drizzle-orm";
|
import { and, desc, eq } from "drizzle-orm";
|
||||||
|
|
||||||
import { db } from "../db/index.js";
|
import { db } from "../db/index.js";
|
||||||
import { activityLog } from "../db/schema/activity.js";
|
import { activityLog } from "../db/schema/activity.js";
|
||||||
@@ -54,14 +54,25 @@ export async function recordActivity(params: {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Lists the clinic's audit feed. When `actorId` is given, only that user's own
|
||||||
|
// actions are returned (each employee sees their own activity); admins/owners
|
||||||
|
// call without it to see the whole clinic.
|
||||||
export async function listActivity(
|
export async function listActivity(
|
||||||
orgId: string,
|
orgId: string,
|
||||||
limit = 100,
|
options: { actorId?: string; limit?: number } = {},
|
||||||
): Promise<ActivityEntry[]> {
|
): Promise<ActivityEntry[]> {
|
||||||
|
const { actorId, limit = 100 } = options;
|
||||||
const rows = await db
|
const rows = await db
|
||||||
.select()
|
.select()
|
||||||
.from(activityLog)
|
.from(activityLog)
|
||||||
.where(eq(activityLog.organizationId, orgId))
|
.where(
|
||||||
|
actorId
|
||||||
|
? and(
|
||||||
|
eq(activityLog.organizationId, orgId),
|
||||||
|
eq(activityLog.actorId, actorId),
|
||||||
|
)
|
||||||
|
: eq(activityLog.organizationId, orgId),
|
||||||
|
)
|
||||||
.orderBy(desc(activityLog.createdAt))
|
.orderBy(desc(activityLog.createdAt))
|
||||||
.limit(limit);
|
.limit(limit);
|
||||||
return rows.map(toEntry);
|
return rows.map(toEntry);
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { and, asc, eq, inArray } from "drizzle-orm";
|
import { and, asc, eq, inArray, isNull, or } from "drizzle-orm";
|
||||||
|
import type { SQL } from "drizzle-orm";
|
||||||
|
|
||||||
import { db } from "../db/index.js";
|
import { db } from "../db/index.js";
|
||||||
import {
|
import {
|
||||||
@@ -46,6 +47,7 @@ function toPatient(row: PatientRow, children: Children): Patient {
|
|||||||
age: row.age,
|
age: row.age,
|
||||||
sex: row.sex,
|
sex: row.sex,
|
||||||
pcp: row.pcp,
|
pcp: row.pcp,
|
||||||
|
primaryProviderId: row.primaryProviderId,
|
||||||
status: row.status,
|
status: row.status,
|
||||||
initials: row.initials,
|
initials: row.initials,
|
||||||
allergies: children.allergies,
|
allergies: children.allergies,
|
||||||
@@ -106,6 +108,7 @@ function patientColumns(orgId: string, input: PatientInput, createdBy?: string)
|
|||||||
age: input.age,
|
age: input.age,
|
||||||
sex: input.sex,
|
sex: input.sex,
|
||||||
pcp: input.pcp,
|
pcp: input.pcp,
|
||||||
|
primaryProviderId: input.primaryProviderId ?? null,
|
||||||
status: input.status,
|
status: input.status,
|
||||||
initials: input.initials,
|
initials: input.initials,
|
||||||
alerts: input.alerts,
|
alerts: input.alerts,
|
||||||
@@ -135,6 +138,7 @@ function demographicColumns(
|
|||||||
age: input.age,
|
age: input.age,
|
||||||
sex: input.sex,
|
sex: input.sex,
|
||||||
pcp: input.pcp,
|
pcp: input.pcp,
|
||||||
|
primaryProviderId: input.primaryProviderId ?? null,
|
||||||
status: input.status,
|
status: input.status,
|
||||||
initials: input.initials,
|
initials: input.initials,
|
||||||
alerts: [] as string[],
|
alerts: [] as string[],
|
||||||
@@ -158,11 +162,23 @@ function demographicUpdateColumns(input: PatientInput) {
|
|||||||
age: input.age,
|
age: input.age,
|
||||||
sex: input.sex,
|
sex: input.sex,
|
||||||
pcp: input.pcp,
|
pcp: input.pcp,
|
||||||
|
primaryProviderId: input.primaryProviderId ?? null,
|
||||||
status: input.status,
|
status: input.status,
|
||||||
initials: input.initials,
|
initials: input.initials,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Scope clinical reads to a single provider's panel: their own patients plus any
|
||||||
|
// legacy/unassigned rows they created (so a freshly scoped doctor isn't left
|
||||||
|
// with an empty list). Returns undefined when no scoping should apply.
|
||||||
|
function providerScopeFilter(providerId?: string): SQL | undefined {
|
||||||
|
if (!providerId) return undefined;
|
||||||
|
return or(
|
||||||
|
eq(patients.primaryProviderId, providerId),
|
||||||
|
and(isNull(patients.primaryProviderId), eq(patients.createdBy, providerId)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Loads and groups child rows for a set of patients in one round-trip each.
|
// Loads and groups child rows for a set of patients in one round-trip each.
|
||||||
async function loadChildren(
|
async function loadChildren(
|
||||||
patientIds: string[],
|
patientIds: string[],
|
||||||
@@ -280,11 +296,15 @@ function isUniqueViolation(err: unknown): boolean {
|
|||||||
export async function listPatients(
|
export async function listPatients(
|
||||||
orgId: string,
|
orgId: string,
|
||||||
demographicsOnly = false,
|
demographicsOnly = false,
|
||||||
|
providerId?: string,
|
||||||
): Promise<Patient[]> {
|
): Promise<Patient[]> {
|
||||||
|
const scope = providerScopeFilter(providerId);
|
||||||
const rows = await db
|
const rows = await db
|
||||||
.select()
|
.select()
|
||||||
.from(patients)
|
.from(patients)
|
||||||
.where(eq(patients.organizationId, orgId))
|
.where(
|
||||||
|
scope ? and(eq(patients.organizationId, orgId), scope) : eq(patients.organizationId, orgId),
|
||||||
|
)
|
||||||
.orderBy(asc(patients.name));
|
.orderBy(asc(patients.name));
|
||||||
const children = await loadChildren(rows.map((r) => r.id));
|
const children = await loadChildren(rows.map((r) => r.id));
|
||||||
return rows.map((r) => {
|
return rows.map((r) => {
|
||||||
@@ -297,7 +317,9 @@ export async function getPatient(
|
|||||||
orgId: string,
|
orgId: string,
|
||||||
fileNumber: string,
|
fileNumber: string,
|
||||||
demographicsOnly = false,
|
demographicsOnly = false,
|
||||||
|
providerId?: string,
|
||||||
): Promise<Patient | null> {
|
): Promise<Patient | null> {
|
||||||
|
const scope = providerScopeFilter(providerId);
|
||||||
const [row] = await db
|
const [row] = await db
|
||||||
.select()
|
.select()
|
||||||
.from(patients)
|
.from(patients)
|
||||||
@@ -305,6 +327,7 @@ export async function getPatient(
|
|||||||
and(
|
and(
|
||||||
eq(patients.organizationId, orgId),
|
eq(patients.organizationId, orgId),
|
||||||
eq(patients.fileNumber, fileNumber),
|
eq(patients.fileNumber, fileNumber),
|
||||||
|
...(scope ? [scope] : []),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
if (!row) return null;
|
if (!row) return null;
|
||||||
@@ -313,6 +336,33 @@ export async function getPatient(
|
|||||||
return demographicsOnly ? redactClinical(patient) : patient;
|
return demographicsOnly ? redactClinical(patient) : patient;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Reassign a patient to another clinician. Updates both the machine link
|
||||||
|
// (primaryProviderId — drives per-doctor visibility) and the display string
|
||||||
|
// (pcp). Org-scoped; returns null when the patient isn't in this clinic.
|
||||||
|
export async function transferPatient(
|
||||||
|
orgId: string,
|
||||||
|
fileNumber: string,
|
||||||
|
providerId: string,
|
||||||
|
providerName: string,
|
||||||
|
scopeProviderId?: string,
|
||||||
|
): Promise<Patient | null> {
|
||||||
|
const scope = providerScopeFilter(scopeProviderId);
|
||||||
|
const [row] = await db
|
||||||
|
.update(patients)
|
||||||
|
.set({ primaryProviderId: providerId, pcp: providerName })
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(patients.organizationId, orgId),
|
||||||
|
eq(patients.fileNumber, fileNumber),
|
||||||
|
...(scope ? [scope] : []),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.returning();
|
||||||
|
if (!row) return null;
|
||||||
|
const children = await loadChildren([row.id]);
|
||||||
|
return toPatient(row, children.get(row.id) ?? emptyChildren());
|
||||||
|
}
|
||||||
|
|
||||||
export async function createPatient(
|
export async function createPatient(
|
||||||
orgId: string,
|
orgId: string,
|
||||||
userId: string,
|
userId: string,
|
||||||
|
|||||||
@@ -57,7 +57,8 @@ export type Patient = {
|
|||||||
name: string;
|
name: string;
|
||||||
age: number;
|
age: number;
|
||||||
sex: Sex;
|
sex: Sex;
|
||||||
pcp: string; // primary care provider
|
pcp: string; // primary care provider (display name)
|
||||||
|
primaryProviderId?: string | null; // user id of the responsible clinician
|
||||||
status: PatientStatus;
|
status: PatientStatus;
|
||||||
initials: string; // for AvatarFallback
|
initials: string; // for AvatarFallback
|
||||||
allergies: Allergy[];
|
allergies: Allergy[];
|
||||||
|
|||||||
@@ -17,6 +17,17 @@ import { useTranslation } from "react-i18next";
|
|||||||
|
|
||||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||||
import { Card } from "@/components/ui/card";
|
import { Card } from "@/components/ui/card";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogClose,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogPanel,
|
||||||
|
DialogPopup,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
import {
|
import {
|
||||||
type ActivityEntityType,
|
type ActivityEntityType,
|
||||||
type ActivityEntry,
|
type ActivityEntry,
|
||||||
@@ -56,6 +67,14 @@ function formatTime(iso: string): string {
|
|||||||
return `${d.toLocaleDateString("en-US", { month: "short", day: "numeric" })}, ${time}`;
|
return `${d.toLocaleDateString("en-US", { month: "short", day: "numeric" })}, ${time}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Full, unambiguous timestamp for the detail dialog.
|
||||||
|
function formatFullTime(iso: string): string {
|
||||||
|
return new Date(iso).toLocaleString("en-US", {
|
||||||
|
dateStyle: "medium",
|
||||||
|
timeStyle: "short",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function Kpi({
|
function Kpi({
|
||||||
label,
|
label,
|
||||||
value,
|
value,
|
||||||
@@ -80,9 +99,19 @@ function Kpi({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function DetailRow({ label, value }: { label: string; value: string }) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-baseline justify-between gap-3">
|
||||||
|
<span className="shrink-0 text-muted-foreground text-xs">{label}</span>
|
||||||
|
<span className="text-right text-foreground text-sm">{value}</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function ActivityView() {
|
export function ActivityView() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [entries, setEntries] = useState<ActivityEntry[]>([]);
|
const [entries, setEntries] = useState<ActivityEntry[]>([]);
|
||||||
|
const [selected, setSelected] = useState<ActivityEntry | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
let active = true;
|
let active = true;
|
||||||
@@ -166,7 +195,14 @@ export function ActivityView() {
|
|||||||
{!isLast && <div className="mt-1 w-px flex-1 bg-border" />}
|
{!isLast && <div className="mt-1 w-px flex-1 bg-border" />}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className={cn("flex-1", isLast ? "pb-0" : "pb-6")}>
|
<button
|
||||||
|
className={cn(
|
||||||
|
"-mx-2 flex-1 rounded-lg px-2 py-1 text-left transition-colors hover:bg-accent/40",
|
||||||
|
isLast ? "pb-1" : "mb-5",
|
||||||
|
)}
|
||||||
|
onClick={() => setSelected(entry)}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
<span className="font-medium text-foreground text-sm">
|
<span className="font-medium text-foreground text-sm">
|
||||||
{entry.action}
|
{entry.action}
|
||||||
</span>
|
</span>
|
||||||
@@ -185,12 +221,63 @@ export function ActivityView() {
|
|||||||
<div className="mt-2 text-muted-foreground text-xs">
|
<div className="mt-2 text-muted-foreground text-xs">
|
||||||
{formatTime(entry.createdAt)}
|
{formatTime(entry.createdAt)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</button>
|
||||||
</li>
|
</li>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</ol>
|
</ol>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<Dialog
|
||||||
|
onOpenChange={(o) => !o && setSelected(null)}
|
||||||
|
open={selected !== null}
|
||||||
|
>
|
||||||
|
<DialogPopup className="sm:max-w-md">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{t("activity.detail.title")}</DialogTitle>
|
||||||
|
<DialogDescription>{selected?.action}</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<DialogPanel className="flex flex-col gap-2.5">
|
||||||
|
<DetailRow
|
||||||
|
label={t("activity.detail.person")}
|
||||||
|
value={selected?.actorName ?? ""}
|
||||||
|
/>
|
||||||
|
<DetailRow
|
||||||
|
label={t("activity.detail.record")}
|
||||||
|
value={
|
||||||
|
selected
|
||||||
|
? t(`activity.detail.entityTypes.${selected.entityType}`)
|
||||||
|
: ""
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{selected?.patientName && (
|
||||||
|
<DetailRow
|
||||||
|
label={t("activity.detail.patient")}
|
||||||
|
value={`${selected.patientName}${
|
||||||
|
selected.patientFileNumber
|
||||||
|
? ` (#${selected.patientFileNumber})`
|
||||||
|
: ""
|
||||||
|
}`}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{selected?.entityId && !selected?.patientFileNumber && (
|
||||||
|
<DetailRow
|
||||||
|
label={t("activity.detail.reference")}
|
||||||
|
value={selected.entityId}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<DetailRow
|
||||||
|
label={t("activity.detail.time")}
|
||||||
|
value={selected ? formatFullTime(selected.createdAt) : ""}
|
||||||
|
/>
|
||||||
|
</DialogPanel>
|
||||||
|
<DialogFooter>
|
||||||
|
<DialogClose render={<Button type="button" variant="outline" />}>
|
||||||
|
{t("activity.detail.close")}
|
||||||
|
</DialogClose>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogPopup>
|
||||||
|
</Dialog>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,13 +24,24 @@ function StatCard({ label, value }: Metric) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Each section's grid fills its row evenly: the column count matches the number
|
||||||
|
// of cards so there's never an orphan card on its own row. Static class strings
|
||||||
|
// (no interpolation) so Tailwind can see them.
|
||||||
|
const GRID_BY_COLUMNS: Record<2 | 3 | 4, string> = {
|
||||||
|
2: "grid grid-cols-1 gap-4 sm:grid-cols-2",
|
||||||
|
3: "grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3",
|
||||||
|
4: "grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4",
|
||||||
|
};
|
||||||
|
|
||||||
function Section({
|
function Section({
|
||||||
title,
|
title,
|
||||||
description,
|
description,
|
||||||
|
columns,
|
||||||
children,
|
children,
|
||||||
}: {
|
}: {
|
||||||
title: string;
|
title: string;
|
||||||
description: string;
|
description: string;
|
||||||
|
columns: 2 | 3 | 4;
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
@@ -39,9 +50,7 @@ function Section({
|
|||||||
<h2 className="font-semibold text-lg tracking-tight">{title}</h2>
|
<h2 className="font-semibold text-lg tracking-tight">{title}</h2>
|
||||||
<p className="text-muted-foreground text-sm">{description}</p>
|
<p className="text-muted-foreground text-sm">{description}</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
<div className={GRID_BY_COLUMNS[columns]}>{children}</div>
|
||||||
{children}
|
|
||||||
</div>
|
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -77,6 +86,7 @@ export function AnalysisView() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Section
|
<Section
|
||||||
|
columns={3}
|
||||||
description={t("analysis.patientVolume.description")}
|
description={t("analysis.patientVolume.description")}
|
||||||
title={t("analysis.patientVolume.title")}
|
title={t("analysis.patientVolume.title")}
|
||||||
>
|
>
|
||||||
@@ -122,6 +132,7 @@ export function AnalysisView() {
|
|||||||
</section>
|
</section>
|
||||||
|
|
||||||
<Section
|
<Section
|
||||||
|
columns={4}
|
||||||
description={t("analysis.appointments.description")}
|
description={t("analysis.appointments.description")}
|
||||||
title={t("analysis.appointments.title")}
|
title={t("analysis.appointments.title")}
|
||||||
>
|
>
|
||||||
@@ -144,6 +155,7 @@ export function AnalysisView() {
|
|||||||
</Section>
|
</Section>
|
||||||
|
|
||||||
<Section
|
<Section
|
||||||
|
columns={2}
|
||||||
description={t("analysis.prescriptions.description")}
|
description={t("analysis.prescriptions.description")}
|
||||||
title={t("analysis.prescriptions.title")}
|
title={t("analysis.prescriptions.title")}
|
||||||
>
|
>
|
||||||
@@ -158,6 +170,7 @@ export function AnalysisView() {
|
|||||||
</Section>
|
</Section>
|
||||||
|
|
||||||
<Section
|
<Section
|
||||||
|
columns={2}
|
||||||
description={t("analysis.tasks.description")}
|
description={t("analysis.tasks.description")}
|
||||||
title={t("analysis.tasks.title")}
|
title={t("analysis.tasks.title")}
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { CalendarIcon, Plus, RefreshCw, X } from "lucide-react";
|
import { CalendarIcon, Plus, RefreshCw, X } from "lucide-react";
|
||||||
import { type FormEvent, type ReactNode, useState } from "react";
|
import { type FormEvent, type ReactNode, useEffect, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
@@ -22,6 +22,8 @@ import {
|
|||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from "@/components/ui/dialog";
|
} from "@/components/ui/dialog";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { ROLE_LABELS } from "@/lib/access";
|
||||||
|
import { authClient } from "@/lib/auth-client";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import {
|
import {
|
||||||
type AllergySeverity,
|
type AllergySeverity,
|
||||||
@@ -32,6 +34,7 @@ import {
|
|||||||
updatePatient,
|
updatePatient,
|
||||||
} from "@/lib/patients";
|
} from "@/lib/patients";
|
||||||
import { hasClinicalAccess, useActiveRole } from "@/lib/roles";
|
import { hasClinicalAccess, useActiveRole } from "@/lib/roles";
|
||||||
|
import { listProviders, type Provider } from "@/lib/staff";
|
||||||
import { notify } from "@/lib/toast";
|
import { notify } from "@/lib/toast";
|
||||||
|
|
||||||
type PatientFormDialogProps = {
|
type PatientFormDialogProps = {
|
||||||
@@ -209,6 +212,8 @@ export function PatientFormDialog({
|
|||||||
// while the role is still loading to avoid a flash for clinical users.
|
// while the role is still loading to avoid a flash for clinical users.
|
||||||
const role = useActiveRole();
|
const role = useActiveRole();
|
||||||
const showClinical = role == null || hasClinicalAccess(role);
|
const showClinical = role == null || hasClinicalAccess(role);
|
||||||
|
const { data: session } = authClient.useSession();
|
||||||
|
const myId = session?.user?.id;
|
||||||
|
|
||||||
const [submitting, setSubmitting] = useState(false);
|
const [submitting, setSubmitting] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
@@ -222,7 +227,10 @@ export function PatientFormDialog({
|
|||||||
const [status, setStatus] = useState<Patient["status"]>(
|
const [status, setStatus] = useState<Patient["status"]>(
|
||||||
patient?.status ?? "active"
|
patient?.status ?? "active"
|
||||||
);
|
);
|
||||||
const [pcp, setPcp] = useState(patient?.pcp ?? "");
|
// Primary care provider is picked from the clinic's clinicians (drives
|
||||||
|
// per-doctor visibility), not free text. `providerId` is the selected user id.
|
||||||
|
const [providers, setProviders] = useState<Provider[]>([]);
|
||||||
|
const [providerId, setProviderId] = useState(patient?.primaryProviderId ?? "");
|
||||||
const [bp, setBp] = useState(patient?.vitals.bp ?? "");
|
const [bp, setBp] = useState(patient?.vitals.bp ?? "");
|
||||||
const [hr, setHr] = useState(patient?.vitals.hr ?? "");
|
const [hr, setHr] = useState(patient?.vitals.hr ?? "");
|
||||||
const [temp, setTemp] = useState(patient?.vitals.temp ?? "");
|
const [temp, setTemp] = useState(patient?.vitals.temp ?? "");
|
||||||
@@ -249,18 +257,45 @@ export function PatientFormDialog({
|
|||||||
})) ?? []
|
})) ?? []
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Load the clinic's clinicians for the PCP picker. When creating, default the
|
||||||
|
// PCP to the current user if they're a provider (a doctor registering their
|
||||||
|
// own patient).
|
||||||
|
useEffect(() => {
|
||||||
|
let active = true;
|
||||||
|
listProviders()
|
||||||
|
.then((list) => {
|
||||||
|
if (!active) return;
|
||||||
|
setProviders(list);
|
||||||
|
if (!isEdit && myId && list.some((p) => p.userId === myId)) {
|
||||||
|
setProviderId((cur) => cur || myId);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
/* leave the picker empty; PCP just stays unassigned */
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
active = false;
|
||||||
|
};
|
||||||
|
}, [isEdit, myId]);
|
||||||
|
|
||||||
const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
|
const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
if (!name.trim() || submitting) {
|
if (!name.trim() || submitting) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const selectedProvider = providers.find((p) => p.userId === providerId);
|
||||||
|
// Display name follows the selected provider; preserve any existing label
|
||||||
|
// when nothing is selected so legacy free-text PCPs aren't wiped on edit.
|
||||||
|
const pcpName = selectedProvider?.name ?? (patient?.pcp || "—");
|
||||||
|
|
||||||
const built: Patient = {
|
const built: Patient = {
|
||||||
fileNumber,
|
fileNumber,
|
||||||
name: name.trim(),
|
name: name.trim(),
|
||||||
age: Number(age) || 0,
|
age: Number(age) || 0,
|
||||||
sex,
|
sex,
|
||||||
pcp: pcp.trim() || "—",
|
pcp: pcpName,
|
||||||
|
primaryProviderId: providerId || null,
|
||||||
status,
|
status,
|
||||||
initials: initialsFromName(name),
|
initials: initialsFromName(name),
|
||||||
allergies: allergies.filter((a) => a.substance.trim()),
|
allergies: allergies.filter((a) => a.substance.trim()),
|
||||||
@@ -415,11 +450,20 @@ export function PatientFormDialog({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Field label={t("patientForm.primaryCare")}>
|
<Field label={t("patientForm.primaryCare")}>
|
||||||
<Input
|
<select
|
||||||
onChange={(event) => setPcp(event.target.value)}
|
className={controlClass}
|
||||||
placeholder={t("patientForm.primaryCarePlaceholder")}
|
onChange={(event) => setProviderId(event.target.value)}
|
||||||
value={pcp}
|
value={providerId}
|
||||||
/>
|
>
|
||||||
|
<option value="">
|
||||||
|
{t("patientForm.primaryCareUnassigned")}
|
||||||
|
</option>
|
||||||
|
{providers.map((p) => (
|
||||||
|
<option key={p.userId} value={p.userId}>
|
||||||
|
{p.name} · {ROLE_LABELS[p.role as keyof typeof ROLE_LABELS] ?? p.role}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
</Field>
|
</Field>
|
||||||
|
|
||||||
{showClinical && (
|
{showClinical && (
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { Mail, Plus, SendHorizonal } from "lucide-react";
|
import { Mail, Plus, Search, SendHorizonal } from "lucide-react";
|
||||||
import {
|
import {
|
||||||
type FormEvent,
|
type FormEvent,
|
||||||
useEffect,
|
useEffect,
|
||||||
@@ -68,9 +68,11 @@ export function MessagesView() {
|
|||||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||||
const [messages, setMessages] = useState<ConversationMessage[]>([]);
|
const [messages, setMessages] = useState<ConversationMessage[]>([]);
|
||||||
const [showUnreadOnly, setShowUnreadOnly] = useState(false);
|
const [showUnreadOnly, setShowUnreadOnly] = useState(false);
|
||||||
|
const [inboxQuery, setInboxQuery] = useState("");
|
||||||
const [draft, setDraft] = useState("");
|
const [draft, setDraft] = useState("");
|
||||||
const [composeOpen, setComposeOpen] = useState(false);
|
const [composeOpen, setComposeOpen] = useState(false);
|
||||||
const [members, setMembers] = useState<Participant[]>([]);
|
const [members, setMembers] = useState<Participant[]>([]);
|
||||||
|
const [memberQuery, setMemberQuery] = useState("");
|
||||||
|
|
||||||
// Refs so the socket handler (registered once) reads current values.
|
// Refs so the socket handler (registered once) reads current values.
|
||||||
const selectedIdRef = useRef<string | null>(null);
|
const selectedIdRef = useRef<string | null>(null);
|
||||||
@@ -135,11 +137,22 @@ export function MessagesView() {
|
|||||||
const unreadCount = conversations.filter((c) => c.unread).length;
|
const unreadCount = conversations.filter((c) => c.unread).length;
|
||||||
const selected = conversations.find((c) => c.id === selectedId) ?? null;
|
const selected = conversations.find((c) => c.id === selectedId) ?? null;
|
||||||
|
|
||||||
const visible = useMemo(
|
const visible = useMemo(() => {
|
||||||
() =>
|
const q = inboxQuery.trim().toLowerCase();
|
||||||
showUnreadOnly ? conversations.filter((c) => c.unread) : conversations,
|
return conversations.filter((c) => {
|
||||||
[conversations, showUnreadOnly],
|
if (showUnreadOnly && !c.unread) return false;
|
||||||
);
|
if (!q) return true;
|
||||||
|
return (
|
||||||
|
c.name.toLowerCase().includes(q) ||
|
||||||
|
(c.lastMessage?.body.toLowerCase().includes(q) ?? false)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}, [conversations, showUnreadOnly, inboxQuery]);
|
||||||
|
|
||||||
|
const visibleMembers = useMemo(() => {
|
||||||
|
const q = memberQuery.trim().toLowerCase();
|
||||||
|
return q ? members.filter((m) => m.name.toLowerCase().includes(q)) : members;
|
||||||
|
}, [members, memberQuery]);
|
||||||
|
|
||||||
const open = (id: string) => {
|
const open = (id: string) => {
|
||||||
setSelectedId(id);
|
setSelectedId(id);
|
||||||
@@ -170,6 +183,7 @@ export function MessagesView() {
|
|||||||
|
|
||||||
const openCompose = () => {
|
const openCompose = () => {
|
||||||
setComposeOpen(true);
|
setComposeOpen(true);
|
||||||
|
setMemberQuery("");
|
||||||
listClinicMembers()
|
listClinicMembers()
|
||||||
.then(setMembers)
|
.then(setMembers)
|
||||||
.catch(() => setMembers([]));
|
.catch(() => setMembers([]));
|
||||||
@@ -220,12 +234,27 @@ export function MessagesView() {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="border-border border-b px-3 py-2">
|
||||||
|
<div className="relative">
|
||||||
|
<Search className="-translate-y-1/2 absolute top-1/2 left-3 size-4 text-muted-foreground" />
|
||||||
|
<Input
|
||||||
|
aria-label={t("messages.searchPlaceholder")}
|
||||||
|
className="pl-9"
|
||||||
|
onChange={(e) => setInboxQuery(e.target.value)}
|
||||||
|
placeholder={t("messages.searchPlaceholder")}
|
||||||
|
size="sm"
|
||||||
|
value={inboxQuery}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<div className="flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto p-2">
|
<div className="flex min-h-0 flex-1 flex-col gap-1 overflow-y-auto p-2">
|
||||||
{visible.length === 0 ? (
|
{visible.length === 0 ? (
|
||||||
<p className="px-2 py-1.5 text-muted-foreground text-sm">
|
<p className="px-2 py-1.5 text-muted-foreground text-sm">
|
||||||
{showUnreadOnly
|
{inboxQuery.trim()
|
||||||
? t("messages.noUnread")
|
? t("messages.noMatches")
|
||||||
: t("messages.noConversations")}
|
: showUnreadOnly
|
||||||
|
? t("messages.noUnread")
|
||||||
|
: t("messages.noConversations")}
|
||||||
</p>
|
</p>
|
||||||
) : (
|
) : (
|
||||||
visible.map((c) => {
|
visible.map((c) => {
|
||||||
@@ -379,28 +408,45 @@ export function MessagesView() {
|
|||||||
{t("messages.compose.description")}
|
{t("messages.compose.description")}
|
||||||
</DialogDescription>
|
</DialogDescription>
|
||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
<DialogPanel className="flex flex-col gap-1">
|
<DialogPanel className="flex flex-col gap-2">
|
||||||
{members.length === 0 ? (
|
<div className="relative">
|
||||||
<p className="px-1 py-4 text-center text-muted-foreground text-sm">
|
<Search className="-translate-y-1/2 absolute top-1/2 left-3 size-4 text-muted-foreground" />
|
||||||
{t("messages.compose.noMembers")}
|
<Input
|
||||||
</p>
|
aria-label={t("messages.compose.searchPlaceholder")}
|
||||||
) : (
|
className="pl-9"
|
||||||
members.map((m) => (
|
onChange={(e) => setMemberQuery(e.target.value)}
|
||||||
<button
|
placeholder={t("messages.compose.searchPlaceholder")}
|
||||||
className="flex w-full items-center gap-3 rounded-lg px-2 py-2 text-left transition-colors hover:bg-accent"
|
size="sm"
|
||||||
key={m.id}
|
value={memberQuery}
|
||||||
onClick={() => startConversation(m.id)}
|
/>
|
||||||
type="button"
|
</div>
|
||||||
>
|
<div className="flex max-h-72 flex-col gap-1 overflow-y-auto">
|
||||||
<Avatar className="size-8">
|
{members.length === 0 ? (
|
||||||
<AvatarFallback>{initials(m.name)}</AvatarFallback>
|
<p className="px-1 py-4 text-center text-muted-foreground text-sm">
|
||||||
</Avatar>
|
{t("messages.compose.noMembers")}
|
||||||
<span className="truncate text-foreground text-sm">
|
</p>
|
||||||
{m.name}
|
) : visibleMembers.length === 0 ? (
|
||||||
</span>
|
<p className="px-1 py-4 text-center text-muted-foreground text-sm">
|
||||||
</button>
|
{t("messages.compose.noMatches")}
|
||||||
))
|
</p>
|
||||||
)}
|
) : (
|
||||||
|
visibleMembers.map((m) => (
|
||||||
|
<button
|
||||||
|
className="flex w-full items-center gap-3 rounded-lg px-2 py-2 text-left transition-colors hover:bg-accent"
|
||||||
|
key={m.id}
|
||||||
|
onClick={() => startConversation(m.id)}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<Avatar className="size-8">
|
||||||
|
<AvatarFallback>{initials(m.name)}</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<span className="truncate text-foreground text-sm">
|
||||||
|
{m.name}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</DialogPanel>
|
</DialogPanel>
|
||||||
</DialogPopup>
|
</DialogPopup>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { useTranslation } from "react-i18next";
|
|||||||
|
|
||||||
import { PatientFormDialog } from "@/components/chat/patient-form-dialog";
|
import { PatientFormDialog } from "@/components/chat/patient-form-dialog";
|
||||||
import { PatientDetail } from "@/components/patients/patient-detail";
|
import { PatientDetail } from "@/components/patients/patient-detail";
|
||||||
|
import { TransferPatientDialog } from "@/components/patients/transfer-patient-dialog";
|
||||||
import {
|
import {
|
||||||
Sheet,
|
Sheet,
|
||||||
SheetHeader,
|
SheetHeader,
|
||||||
@@ -14,6 +15,7 @@ import {
|
|||||||
} from "@/components/ui/sheet";
|
} from "@/components/ui/sheet";
|
||||||
import { Skeleton } from "@/components/ui/skeleton";
|
import { Skeleton } from "@/components/ui/skeleton";
|
||||||
import { getPatient, type Patient } from "@/lib/patients";
|
import { getPatient, type Patient } from "@/lib/patients";
|
||||||
|
import { hasClinicalAccess, useActiveRole } from "@/lib/roles";
|
||||||
|
|
||||||
type Status = "loading" | "ready" | "not-found";
|
type Status = "loading" | "ready" | "not-found";
|
||||||
|
|
||||||
@@ -54,9 +56,13 @@ export function PatientDetailSheet({
|
|||||||
onOpenChange: (open: boolean) => void;
|
onOpenChange: (open: boolean) => void;
|
||||||
}) {
|
}) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const role = useActiveRole();
|
||||||
|
// Clinical roles can reassign a chart; show optimistically while role loads.
|
||||||
|
const canTransfer = role == null || hasClinicalAccess(role);
|
||||||
const [patient, setPatient] = useState<Patient | null>(null);
|
const [patient, setPatient] = useState<Patient | null>(null);
|
||||||
const [status, setStatus] = useState<Status>("loading");
|
const [status, setStatus] = useState<Status>("loading");
|
||||||
const [editOpen, setEditOpen] = useState(false);
|
const [editOpen, setEditOpen] = useState(false);
|
||||||
|
const [transferOpen, setTransferOpen] = useState(false);
|
||||||
// Bumped on open so the editor remounts with the latest patient data.
|
// Bumped on open so the editor remounts with the latest patient data.
|
||||||
const [editKey, setEditKey] = useState(0);
|
const [editKey, setEditKey] = useState(0);
|
||||||
|
|
||||||
@@ -106,6 +112,9 @@ export function PatientDetailSheet({
|
|||||||
setEditKey((k) => k + 1);
|
setEditKey((k) => k + 1);
|
||||||
setEditOpen(true);
|
setEditOpen(true);
|
||||||
}}
|
}}
|
||||||
|
onTransfer={
|
||||||
|
canTransfer ? () => setTransferOpen(true) : undefined
|
||||||
|
}
|
||||||
patient={patient}
|
patient={patient}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
@@ -123,6 +132,15 @@ export function PatientDetailSheet({
|
|||||||
patient={patient}
|
patient={patient}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{patient && (
|
||||||
|
<TransferPatientDialog
|
||||||
|
onOpenChange={setTransferOpen}
|
||||||
|
onTransferred={(updated) => setPatient(updated)}
|
||||||
|
open={transferOpen}
|
||||||
|
patient={patient}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { Pencil } from "lucide-react";
|
import { ArrowLeftRight, Pencil } from "lucide-react";
|
||||||
import type { ReactNode } from "react";
|
import type { ReactNode } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
@@ -81,9 +81,11 @@ function TrendBlock({ trend }: { trend: Trend }) {
|
|||||||
export function PatientDetail({
|
export function PatientDetail({
|
||||||
patient,
|
patient,
|
||||||
onEdit,
|
onEdit,
|
||||||
|
onTransfer,
|
||||||
}: {
|
}: {
|
||||||
patient: Patient;
|
patient: Patient;
|
||||||
onEdit?: () => void;
|
onEdit?: () => void;
|
||||||
|
onTransfer?: () => void;
|
||||||
}) {
|
}) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const sex = t(`patientCard.sex.${patient.sex}`);
|
const sex = t(`patientCard.sex.${patient.sex}`);
|
||||||
@@ -115,12 +117,25 @@ export function PatientDetail({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{onEdit && (
|
<div className="flex shrink-0 items-center gap-2">
|
||||||
<Button onClick={onEdit} size="sm" type="button" variant="outline">
|
{onTransfer && (
|
||||||
<Pencil className="size-4" />
|
<Button
|
||||||
{t("patientCard.edit")}
|
onClick={onTransfer}
|
||||||
</Button>
|
size="sm"
|
||||||
)}
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
>
|
||||||
|
<ArrowLeftRight className="size-4" />
|
||||||
|
{t("patients.transfer.action")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
{onEdit && (
|
||||||
|
<Button onClick={onEdit} size="sm" type="button" variant="outline">
|
||||||
|
<Pencil className="size-4" />
|
||||||
|
{t("patientCard.edit")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Section title={t("patientCard.overview")}>
|
<Section title={t("patientCard.overview")}>
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogClose,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogPanel,
|
||||||
|
DialogPopup,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import { ROLE_LABELS } from "@/lib/access";
|
||||||
|
import { type Patient, transferPatient } from "@/lib/patients";
|
||||||
|
import { listProviders, type Provider } from "@/lib/staff";
|
||||||
|
import { notify } from "@/lib/toast";
|
||||||
|
|
||||||
|
const selectClass =
|
||||||
|
"h-9 w-full rounded-3xl border border-transparent bg-input/50 px-3 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/30";
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
patient: Patient;
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
onTransferred: (patient: Patient) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Reassign a patient to another clinician. The new provider becomes the
|
||||||
|
// patient's primary provider (and PCP label), which moves the chart into their
|
||||||
|
// panel under per-doctor visibility.
|
||||||
|
export function TransferPatientDialog({
|
||||||
|
patient,
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
onTransferred,
|
||||||
|
}: Props) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [providers, setProviders] = useState<Provider[]>([]);
|
||||||
|
const [providerId, setProviderId] = useState(patient.primaryProviderId ?? "");
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
setProviderId(patient.primaryProviderId ?? "");
|
||||||
|
setError(null);
|
||||||
|
let active = true;
|
||||||
|
listProviders()
|
||||||
|
.then((list) => active && setProviders(list))
|
||||||
|
.catch(() => active && setProviders([]));
|
||||||
|
return () => {
|
||||||
|
active = false;
|
||||||
|
};
|
||||||
|
}, [open, patient.primaryProviderId]);
|
||||||
|
|
||||||
|
const submit = async () => {
|
||||||
|
if (!providerId || submitting) return;
|
||||||
|
setSubmitting(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const updated = await transferPatient(patient.fileNumber, providerId);
|
||||||
|
onTransferred(updated);
|
||||||
|
notify.success(
|
||||||
|
t("patients.transfer.successTitle"),
|
||||||
|
t("patients.transfer.successBody", {
|
||||||
|
name: updated.name,
|
||||||
|
provider: updated.pcp,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
onOpenChange(false);
|
||||||
|
} catch (err) {
|
||||||
|
const message =
|
||||||
|
err instanceof Error ? err.message : t("patients.transfer.error");
|
||||||
|
setError(message);
|
||||||
|
notify.error(t("patients.transfer.errorTitle"), message);
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog onOpenChange={onOpenChange} open={open}>
|
||||||
|
<DialogPopup className="sm:max-w-sm">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{t("patients.transfer.title")}</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
{t("patients.transfer.description", { name: patient.name })}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<DialogPanel className="flex flex-col gap-3">
|
||||||
|
{error && (
|
||||||
|
<p className="rounded-2xl bg-destructive/10 px-3 py-2 text-sm text-destructive">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<label className="flex flex-col gap-1.5">
|
||||||
|
<span className="text-xs text-muted-foreground">
|
||||||
|
{t("patients.transfer.providerLabel")}
|
||||||
|
</span>
|
||||||
|
<select
|
||||||
|
className={selectClass}
|
||||||
|
onChange={(e) => setProviderId(e.target.value)}
|
||||||
|
value={providerId}
|
||||||
|
>
|
||||||
|
<option value="">{t("patients.transfer.choose")}</option>
|
||||||
|
{providers.map((p) => (
|
||||||
|
<option key={p.userId} value={p.userId}>
|
||||||
|
{p.name} ·{" "}
|
||||||
|
{ROLE_LABELS[p.role as keyof typeof ROLE_LABELS] ?? p.role}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
</DialogPanel>
|
||||||
|
<DialogFooter>
|
||||||
|
<DialogClose render={<Button type="button" variant="outline" />}>
|
||||||
|
{t("patients.transfer.cancel")}
|
||||||
|
</DialogClose>
|
||||||
|
<Button
|
||||||
|
disabled={
|
||||||
|
submitting ||
|
||||||
|
!providerId ||
|
||||||
|
providerId === patient.primaryProviderId
|
||||||
|
}
|
||||||
|
onClick={submit}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
{submitting
|
||||||
|
? t("patients.transfer.transferring")
|
||||||
|
: t("patients.transfer.confirm")}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogPopup>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,230 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Trash2 } from "lucide-react";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
|
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogClose,
|
||||||
|
DialogDescription,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogPanel,
|
||||||
|
DialogPopup,
|
||||||
|
DialogTitle,
|
||||||
|
} from "@/components/ui/dialog";
|
||||||
|
import { ROLE_LABELS } from "@/lib/access";
|
||||||
|
import { authClient } from "@/lib/auth-client";
|
||||||
|
import { PROVISIONABLE_ROLES, rolePermissionSummary } from "@/lib/roles";
|
||||||
|
import { notify } from "@/lib/toast";
|
||||||
|
|
||||||
|
// One row of /api/staff — shared with the Care Team panel.
|
||||||
|
export type StaffMember = {
|
||||||
|
id: string;
|
||||||
|
userId: string;
|
||||||
|
role: string;
|
||||||
|
name: string | null;
|
||||||
|
email: string | null;
|
||||||
|
username: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const selectClass =
|
||||||
|
"h-9 w-full rounded-3xl border border-transparent bg-input/50 px-3 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/30";
|
||||||
|
|
||||||
|
function roleLabel(role?: string | null): string {
|
||||||
|
if (!role) return ROLE_LABELS.member;
|
||||||
|
return (ROLE_LABELS as Record<string, string>)[role] ?? role;
|
||||||
|
}
|
||||||
|
|
||||||
|
function initials(name?: string | null, email?: string | null): string {
|
||||||
|
const source = name?.trim() || email?.trim() || "?";
|
||||||
|
return (
|
||||||
|
source
|
||||||
|
.split(/\s+/)
|
||||||
|
.map((w) => w[0])
|
||||||
|
.filter(Boolean)
|
||||||
|
.join("")
|
||||||
|
.slice(0, 2)
|
||||||
|
.toUpperCase() || "?"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
member: StaffMember | null;
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
// True when the viewer may change/remove this member (admin, not self, not an
|
||||||
|
// owner). When false the dialog is read-only.
|
||||||
|
editable: boolean;
|
||||||
|
onChanged: () => void;
|
||||||
|
onRemove: (member: StaffMember) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Admin-facing detail view for a single clinic member: shows who they are, what
|
||||||
|
// their role lets them do, and (when editable) lets an admin change the role —
|
||||||
|
// which swaps the whole permission bundle — or remove them.
|
||||||
|
export function EmployeeDetailDialog({
|
||||||
|
member,
|
||||||
|
open,
|
||||||
|
onOpenChange,
|
||||||
|
editable,
|
||||||
|
onChanged,
|
||||||
|
onRemove,
|
||||||
|
}: Props) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [role, setRole] = useState<string>(member?.role ?? "");
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setRole(member?.role ?? "");
|
||||||
|
}, [member?.id, member?.role]);
|
||||||
|
|
||||||
|
const summary = rolePermissionSummary(member?.role);
|
||||||
|
const secondary = member?.username ? `@${member.username}` : member?.email;
|
||||||
|
// Keep the member's current role selectable even if it isn't admin-assignable
|
||||||
|
// (e.g. the "member"/Clinician role).
|
||||||
|
const roleOptions = Array.from(
|
||||||
|
new Set([member?.role, ...PROVISIONABLE_ROLES].filter(Boolean) as string[]),
|
||||||
|
);
|
||||||
|
|
||||||
|
const changeRole = async () => {
|
||||||
|
if (!member || saving || role === member.role) return;
|
||||||
|
setSaving(true);
|
||||||
|
const { error } = await authClient.organization.updateMemberRole({
|
||||||
|
memberId: member.id,
|
||||||
|
role,
|
||||||
|
});
|
||||||
|
setSaving(false);
|
||||||
|
if (error) {
|
||||||
|
notify.error(
|
||||||
|
t("settings.careTeam.employee.roleFailedTitle"),
|
||||||
|
error.message ?? t("settings.careTeam.employee.roleFailedBody"),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
notify.success(
|
||||||
|
t("settings.careTeam.employee.roleUpdatedTitle"),
|
||||||
|
t("settings.careTeam.employee.roleUpdatedBody", {
|
||||||
|
name: member.name ?? member.email ?? "",
|
||||||
|
role: roleLabel(role),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
onChanged();
|
||||||
|
onOpenChange(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog onOpenChange={onOpenChange} open={open}>
|
||||||
|
<DialogPopup className="sm:max-w-md">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{t("settings.careTeam.employee.title")}</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
{t("settings.careTeam.employee.description")}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<DialogPanel className="flex flex-col gap-5">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<Avatar className="size-10">
|
||||||
|
<AvatarFallback>
|
||||||
|
{initials(member?.name, member?.email)}
|
||||||
|
</AvatarFallback>
|
||||||
|
</Avatar>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="truncate text-sm font-medium">
|
||||||
|
{member?.name || member?.email || member?.userId}
|
||||||
|
</p>
|
||||||
|
{secondary && (
|
||||||
|
<p className="truncate text-xs text-muted-foreground">
|
||||||
|
{secondary}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Badge className="capitalize" variant="secondary">
|
||||||
|
{roleLabel(member?.role)}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<span className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
|
||||||
|
{t("settings.careTeam.employee.permissions")}
|
||||||
|
</span>
|
||||||
|
<div className="flex flex-col gap-1.5 rounded-2xl border bg-card/30 px-3 py-2.5">
|
||||||
|
{summary.map(({ resource, actions }) => (
|
||||||
|
<div
|
||||||
|
className="flex items-center justify-between gap-3"
|
||||||
|
key={resource}
|
||||||
|
>
|
||||||
|
<span className="text-sm text-foreground">
|
||||||
|
{t(`settings.careTeam.employee.resources.${resource}`)}
|
||||||
|
</span>
|
||||||
|
<span className="text-xs text-muted-foreground">
|
||||||
|
{actions.length === 0
|
||||||
|
? t("settings.careTeam.employee.noAccess")
|
||||||
|
: actions
|
||||||
|
.map((a) =>
|
||||||
|
t(`settings.careTeam.employee.actions.${a}`),
|
||||||
|
)
|
||||||
|
.join(" · ")}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{editable && (
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<span className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
|
||||||
|
{t("settings.careTeam.employee.changeRole")}
|
||||||
|
</span>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<select
|
||||||
|
aria-label={t("settings.careTeam.employee.changeRole")}
|
||||||
|
className={selectClass}
|
||||||
|
onChange={(e) => setRole(e.target.value)}
|
||||||
|
value={role}
|
||||||
|
>
|
||||||
|
{roleOptions.map((r) => (
|
||||||
|
<option key={r} value={r}>
|
||||||
|
{roleLabel(r)}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<Button
|
||||||
|
disabled={saving || role === member?.role}
|
||||||
|
onClick={changeRole}
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
{saving
|
||||||
|
? t("settings.careTeam.employee.saving")
|
||||||
|
: t("settings.careTeam.employee.save")}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</DialogPanel>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
{editable && member && (
|
||||||
|
<Button
|
||||||
|
className="sm:mr-auto"
|
||||||
|
onClick={() => onRemove(member)}
|
||||||
|
type="button"
|
||||||
|
variant="destructive"
|
||||||
|
>
|
||||||
|
<Trash2 className="size-4" />
|
||||||
|
{t("settings.careTeam.employee.remove")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<DialogClose render={<Button type="button" variant="outline" />}>
|
||||||
|
{t("settings.careTeam.employee.close")}
|
||||||
|
</DialogClose>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogPopup>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,10 +1,14 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { UserPlus, X } from "lucide-react";
|
import { UserPlus } from "lucide-react";
|
||||||
import { useCallback, useEffect, useState } from "react";
|
import { useCallback, useEffect, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
import { AddStaffDialog } from "@/components/settings/add-staff-dialog";
|
import { AddStaffDialog } from "@/components/settings/add-staff-dialog";
|
||||||
|
import {
|
||||||
|
EmployeeDetailDialog,
|
||||||
|
type StaffMember,
|
||||||
|
} from "@/components/settings/employee-detail-dialog";
|
||||||
import {
|
import {
|
||||||
SettingsCard,
|
SettingsCard,
|
||||||
SettingsSection,
|
SettingsSection,
|
||||||
@@ -26,17 +30,6 @@ import { apiFetch } from "@/lib/api-client";
|
|||||||
import { authClient } from "@/lib/auth-client";
|
import { authClient } from "@/lib/auth-client";
|
||||||
import { notify } from "@/lib/toast";
|
import { notify } from "@/lib/toast";
|
||||||
|
|
||||||
// One row of /api/staff — clinic members joined to their user record (incl. the
|
|
||||||
// username admin-provisioned staff sign in with).
|
|
||||||
type StaffMember = {
|
|
||||||
id: string;
|
|
||||||
userId: string;
|
|
||||||
role: string;
|
|
||||||
name: string | null;
|
|
||||||
email: string | null;
|
|
||||||
username: string | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
function roleLabel(role?: string | null): string {
|
function roleLabel(role?: string | null): string {
|
||||||
if (!role) return ROLE_LABELS.member;
|
if (!role) return ROLE_LABELS.member;
|
||||||
return (ROLE_LABELS as Record<string, string>)[role] ?? role;
|
return (ROLE_LABELS as Record<string, string>)[role] ?? role;
|
||||||
@@ -62,6 +55,7 @@ export function CareTeamPanel() {
|
|||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [adding, setAdding] = useState(false);
|
const [adding, setAdding] = useState(false);
|
||||||
|
const [selected, setSelected] = useState<StaffMember | null>(null);
|
||||||
const [pendingRemove, setPendingRemove] = useState<StaffMember | null>(null);
|
const [pendingRemove, setPendingRemove] = useState<StaffMember | null>(null);
|
||||||
const [removing, setRemoving] = useState(false);
|
const [removing, setRemoving] = useState(false);
|
||||||
|
|
||||||
@@ -142,14 +136,14 @@ export function CareTeamPanel() {
|
|||||||
// Prefer the login username; fall back to email for owners who
|
// Prefer the login username; fall back to email for owners who
|
||||||
// signed up by email.
|
// signed up by email.
|
||||||
const secondary = m.username ? `@${m.username}` : m.email;
|
const secondary = m.username ? `@${m.username}` : m.email;
|
||||||
return (
|
const body = (
|
||||||
<div className="flex items-center gap-3 px-4 py-3" key={m.id}>
|
<>
|
||||||
<Avatar className="size-8">
|
<Avatar className="size-8">
|
||||||
<AvatarFallback>
|
<AvatarFallback>
|
||||||
{initials(m.name, m.email)}
|
{initials(m.name, m.email)}
|
||||||
</AvatarFallback>
|
</AvatarFallback>
|
||||||
</Avatar>
|
</Avatar>
|
||||||
<div className="min-w-0 flex-1">
|
<div className="min-w-0 flex-1 text-left">
|
||||||
<p className="truncate text-sm font-medium">
|
<p className="truncate text-sm font-medium">
|
||||||
{m.name || m.email || m.userId}
|
{m.name || m.email || m.userId}
|
||||||
{isSelf && (
|
{isSelf && (
|
||||||
@@ -167,17 +161,22 @@ export function CareTeamPanel() {
|
|||||||
<Badge className="capitalize" variant="secondary">
|
<Badge className="capitalize" variant="secondary">
|
||||||
{roleLabel(m.role)}
|
{roleLabel(m.role)}
|
||||||
</Badge>
|
</Badge>
|
||||||
{canManage && !isSelf && m.role !== "owner" && (
|
</>
|
||||||
<Button
|
);
|
||||||
aria-label={t("settings.careTeam.removeMember")}
|
// Admins click a row to open the employee detail dialog (view
|
||||||
onClick={() => setPendingRemove(m)}
|
// permissions, change role, remove). Non-managers see a static row.
|
||||||
size="icon-sm"
|
return canManage ? (
|
||||||
type="button"
|
<button
|
||||||
variant="ghost"
|
className="flex w-full items-center gap-3 px-4 py-3 transition-colors hover:bg-accent/50"
|
||||||
>
|
key={m.id}
|
||||||
<X className="size-4" />
|
onClick={() => setSelected(m)}
|
||||||
</Button>
|
type="button"
|
||||||
)}
|
>
|
||||||
|
{body}
|
||||||
|
</button>
|
||||||
|
) : (
|
||||||
|
<div className="flex items-center gap-3 px-4 py-3" key={m.id}>
|
||||||
|
{body}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
})
|
})
|
||||||
@@ -192,6 +191,23 @@ export function CareTeamPanel() {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Click a member to view details, change role, or remove. */}
|
||||||
|
<EmployeeDetailDialog
|
||||||
|
editable={
|
||||||
|
canManage &&
|
||||||
|
selected?.userId !== session?.user?.id &&
|
||||||
|
selected?.role !== "owner"
|
||||||
|
}
|
||||||
|
member={selected}
|
||||||
|
onChanged={() => void load()}
|
||||||
|
onOpenChange={(o) => !o && setSelected(null)}
|
||||||
|
onRemove={(m) => {
|
||||||
|
setSelected(null);
|
||||||
|
setPendingRemove(m);
|
||||||
|
}}
|
||||||
|
open={selected !== null}
|
||||||
|
/>
|
||||||
|
|
||||||
{/* Confirm before removing a member — destructive and not reversible. */}
|
{/* Confirm before removing a member — destructive and not reversible. */}
|
||||||
<Dialog
|
<Dialog
|
||||||
onOpenChange={(o) => !o && setPendingRemove(null)}
|
onOpenChange={(o) => !o && setPendingRemove(null)}
|
||||||
|
|||||||
@@ -187,6 +187,20 @@
|
|||||||
"notFound": "Patient not found",
|
"notFound": "Patient not found",
|
||||||
"loading": "Loading patient…",
|
"loading": "Loading patient…",
|
||||||
"noPatientForFile": "No patient found for file #{{number}}."
|
"noPatientForFile": "No patient found for file #{{number}}."
|
||||||
|
},
|
||||||
|
"transfer": {
|
||||||
|
"action": "Transfer",
|
||||||
|
"title": "Transfer patient",
|
||||||
|
"description": "Reassign {{name}} to another clinician. They become this patient's primary provider.",
|
||||||
|
"providerLabel": "New primary provider",
|
||||||
|
"choose": "Choose a provider…",
|
||||||
|
"cancel": "Cancel",
|
||||||
|
"confirm": "Transfer patient",
|
||||||
|
"transferring": "Transferring…",
|
||||||
|
"successTitle": "Patient transferred",
|
||||||
|
"successBody": "{{name}} is now with {{provider}}.",
|
||||||
|
"errorTitle": "Couldn't transfer patient",
|
||||||
|
"error": "Please try again."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"appointments": {
|
"appointments": {
|
||||||
@@ -366,6 +380,8 @@
|
|||||||
"inbox": "Inbox",
|
"inbox": "Inbox",
|
||||||
"unread": "Unread · {{count}}",
|
"unread": "Unread · {{count}}",
|
||||||
"newMessage": "New message",
|
"newMessage": "New message",
|
||||||
|
"searchPlaceholder": "Search conversations",
|
||||||
|
"noMatches": "No conversations match your search.",
|
||||||
"noUnread": "No unread messages.",
|
"noUnread": "No unread messages.",
|
||||||
"noConversations": "No conversations yet.",
|
"noConversations": "No conversations yet.",
|
||||||
"you": "You: ",
|
"you": "You: ",
|
||||||
@@ -378,6 +394,8 @@
|
|||||||
"compose": {
|
"compose": {
|
||||||
"title": "New message",
|
"title": "New message",
|
||||||
"description": "Start a conversation with a member of your clinic.",
|
"description": "Start a conversation with a member of your clinic.",
|
||||||
|
"searchPlaceholder": "Search people",
|
||||||
|
"noMatches": "No people match your search.",
|
||||||
"noMembers": "No other clinic members yet. Invite colleagues from Settings → Care team."
|
"noMembers": "No other clinic members yet. Invite colleagues from Settings → Care team."
|
||||||
},
|
},
|
||||||
"startFailedTitle": "Couldn't start conversation",
|
"startFailedTitle": "Couldn't start conversation",
|
||||||
@@ -430,7 +448,23 @@
|
|||||||
"changesToday": "Changes today",
|
"changesToday": "Changes today",
|
||||||
"thisWeek": "This week",
|
"thisWeek": "This week",
|
||||||
"totalRecorded": "Total recorded",
|
"totalRecorded": "Total recorded",
|
||||||
"empty": "No activity yet. Changes to patients, notes, appointments, prescriptions and tasks will appear here."
|
"empty": "No activity yet. Changes to patients, notes, appointments, prescriptions and tasks will appear here.",
|
||||||
|
"detail": {
|
||||||
|
"title": "Activity detail",
|
||||||
|
"person": "Performed by",
|
||||||
|
"record": "Record type",
|
||||||
|
"patient": "Patient",
|
||||||
|
"reference": "Reference",
|
||||||
|
"time": "Time",
|
||||||
|
"close": "Close",
|
||||||
|
"entityTypes": {
|
||||||
|
"patient": "Patient",
|
||||||
|
"note": "Note",
|
||||||
|
"appointment": "Appointment",
|
||||||
|
"prescription": "Prescription",
|
||||||
|
"task": "Task"
|
||||||
|
}
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"notes": {
|
"notes": {
|
||||||
"title": "Notes",
|
"title": "Notes",
|
||||||
@@ -603,6 +637,7 @@
|
|||||||
"status": "Status",
|
"status": "Status",
|
||||||
"primaryCare": "Primary care",
|
"primaryCare": "Primary care",
|
||||||
"primaryCarePlaceholder": "e.g. Dr. Lena Ortiz",
|
"primaryCarePlaceholder": "e.g. Dr. Lena Ortiz",
|
||||||
|
"primaryCareUnassigned": "Unassigned",
|
||||||
"currentVitals": "Current vitals",
|
"currentVitals": "Current vitals",
|
||||||
"bp": "Blood pressure",
|
"bp": "Blood pressure",
|
||||||
"hr": "Heart rate",
|
"hr": "Heart rate",
|
||||||
@@ -725,6 +760,32 @@
|
|||||||
"you": "(you)",
|
"you": "(you)",
|
||||||
"addMember": "Add team member",
|
"addMember": "Add team member",
|
||||||
"removeMember": "Remove member",
|
"removeMember": "Remove member",
|
||||||
|
"employee": {
|
||||||
|
"title": "Team member",
|
||||||
|
"description": "View this member's access, change their role, or remove them.",
|
||||||
|
"permissions": "Permissions",
|
||||||
|
"noAccess": "No access",
|
||||||
|
"changeRole": "Change role",
|
||||||
|
"save": "Save",
|
||||||
|
"saving": "Saving…",
|
||||||
|
"remove": "Remove employee",
|
||||||
|
"close": "Close",
|
||||||
|
"roleUpdatedTitle": "Role updated",
|
||||||
|
"roleUpdatedBody": "{{name}} is now {{role}}.",
|
||||||
|
"roleFailedTitle": "Couldn't update role",
|
||||||
|
"roleFailedBody": "Please try again.",
|
||||||
|
"resources": {
|
||||||
|
"patient": "Patients",
|
||||||
|
"appointment": "Appointments",
|
||||||
|
"prescription": "Prescriptions",
|
||||||
|
"task": "Tasks"
|
||||||
|
},
|
||||||
|
"actions": {
|
||||||
|
"read": "View",
|
||||||
|
"write": "Edit",
|
||||||
|
"delete": "Delete"
|
||||||
|
}
|
||||||
|
},
|
||||||
"remove": {
|
"remove": {
|
||||||
"title": "Remove team member?",
|
"title": "Remove team member?",
|
||||||
"description": "{{name}} will lose access to this clinic. This can't be undone.",
|
"description": "{{name}} will lose access to this clinic. This can't be undone.",
|
||||||
|
|||||||
@@ -62,7 +62,8 @@ export type Patient = {
|
|||||||
name: string;
|
name: string;
|
||||||
age: number;
|
age: number;
|
||||||
sex: "M" | "F";
|
sex: "M" | "F";
|
||||||
pcp: string; // primary care provider
|
pcp: string; // primary care provider (display name)
|
||||||
|
primaryProviderId?: string | null; // user id of the responsible clinician
|
||||||
status: "active" | "inpatient" | "discharged";
|
status: "active" | "inpatient" | "discharged";
|
||||||
initials: string; // for AvatarFallback
|
initials: string; // for AvatarFallback
|
||||||
allergies: Allergy[];
|
allergies: Allergy[];
|
||||||
@@ -112,6 +113,20 @@ export async function updatePatient(patient: Patient): Promise<Patient> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Reassign a patient to another clinician (sets their primary provider + PCP).
|
||||||
|
export async function transferPatient(
|
||||||
|
fileNumber: string,
|
||||||
|
providerId: string,
|
||||||
|
): Promise<Patient> {
|
||||||
|
return apiFetch<Patient>(
|
||||||
|
`/api/patients/${encodeURIComponent(fileNumber)}/transfer`,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ providerId }),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Suggest a unique-ish 5-digit file number for new charts. The server is the
|
// Suggest a unique-ish 5-digit file number for new charts. The server is the
|
||||||
// source of truth and rejects collisions with a 409.
|
// source of truth and rejects collisions with a 409.
|
||||||
export function generateFileNumber(): string {
|
export function generateFileNumber(): string {
|
||||||
|
|||||||
@@ -45,6 +45,42 @@ export function useActiveRole(): string | null {
|
|||||||
return role;
|
return role;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The clinical resources + actions we surface in the Care Team permissions
|
||||||
|
// summary. Mirrors the statements in lib/access.ts.
|
||||||
|
export const CLINICAL_RESOURCES = [
|
||||||
|
"patient",
|
||||||
|
"appointment",
|
||||||
|
"prescription",
|
||||||
|
"task",
|
||||||
|
] as const;
|
||||||
|
const RESOURCE_ACTIONS = ["read", "write", "delete"] as const;
|
||||||
|
|
||||||
|
type PermissionArg = Parameters<
|
||||||
|
typeof authClient.organization.checkRolePermission
|
||||||
|
>[0]["permissions"];
|
||||||
|
|
||||||
|
// For a given role, the allowed actions on each clinical resource — computed
|
||||||
|
// from Better Auth so it stays in lock-step with lib/access.ts. Used by the
|
||||||
|
// Care Team employee dialog to show what a role can do.
|
||||||
|
export function rolePermissionSummary(
|
||||||
|
role: string | null | undefined,
|
||||||
|
): { resource: (typeof CLINICAL_RESOURCES)[number]; actions: string[] }[] {
|
||||||
|
if (!role) return [];
|
||||||
|
return CLINICAL_RESOURCES.map((resource) => {
|
||||||
|
const actions = RESOURCE_ACTIONS.filter((action) => {
|
||||||
|
try {
|
||||||
|
return authClient.organization.checkRolePermission({
|
||||||
|
role: role as RoleKey,
|
||||||
|
permissions: { [resource]: [action] } as PermissionArg,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return { resource, actions };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Whether a role may see clinical records (AI lookup, prescriptions, notes,
|
// Whether a role may see clinical records (AI lookup, prescriptions, notes,
|
||||||
// analysis). Driven by Better Auth permissions so it stays in lock-step with
|
// analysis). Driven by Better Auth permissions so it stays in lock-step with
|
||||||
// lib/access.ts: the `reception` role has no `prescription` statement, so this
|
// lib/access.ts: the `reception` role has no `prescription` statement, so this
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { apiFetch } from "@/lib/api-client";
|
||||||
|
|
||||||
|
// A clinician who can be assigned as a patient's primary provider. Returned by
|
||||||
|
// the backend's GET /api/staff/providers (clinical roles only — excludes
|
||||||
|
// reception/viewer). Readable by any clinic member.
|
||||||
|
export type Provider = {
|
||||||
|
userId: string;
|
||||||
|
name: string;
|
||||||
|
role: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function listProviders(): Promise<Provider[]> {
|
||||||
|
return apiFetch<Provider[]>("/api/staff/providers");
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user