mirror of
https://github.com/temetro/temetro.git
synced 2026-09-04 06:45:26 +00:00
feat: admin-provisioned staff, username login & role-based access
Replace the email-invitation flow with admin-provisioned staff accounts and
add role-based access that changes what each member sees.
Backend:
- Enable Better Auth `username` plugin (staff sign in by username); regenerate
auth schema (+ username/displayUsername on user) and migration 0007.
- Add `doctor` and `reception` roles to the access-control RBAC. `reception` is
scoped to scheduling + registration (no `prescription` statement).
- New `/api/staff` route: POST creates a user (auth.api.signUpEmail) and adds
them to the active clinic (auth.api.addMember); GET lists members + usernames.
Gated by requirePermission({ member: ["create"] }).
- Redact clinical PHI for the reception role in the patients service (read,
create and update) so demographics-only is enforced server-side.
Frontend:
- usernameClient + Email|Username tabs on the login form.
- lib/roles.ts: useActiveRole + Better-Auth-permission-driven nav visibility,
default landing, and a route guard (reception -> /appointments, blocked from
clinical routes). Applied to the sidebar, command palette and auth guard.
- Care team page now provisions staff via a two-step Add-team-member dialog
(details -> username/password) hitting /api/staff; removes the email-invite
and pending-invitation UI. New members are contactable from Messages
automatically (they become org members).
- Hide clinical sections of the patient form and the admin-only settings tabs
for non-clinical/non-admin roles.
All permission management stays in Better Auth (per the better-auth skills now
referenced in backend/CLAUDE.md).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
+15
-4
@@ -27,10 +27,21 @@ No test runner is configured. Verify by running the stack (`docker compose up`)
|
|||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
- **`src/auth.ts`** — the Better Auth config (the CLI auto-discovers it). Email/password,
|
- **`src/auth.ts`** — the Better Auth config (the CLI auto-discovers it). Email/password +
|
||||||
organization plugin (clinics) with custom RBAC from **`src/lib/access.ts`**
|
**username** plugin (staff sign in by username) and the organization plugin (clinics) with custom
|
||||||
(`owner`/`admin`/`member`/`viewer` + a `patient` resource). Mounted in `src/index.ts` via
|
RBAC from **`src/lib/access.ts`** (`owner`/`admin`/`doctor`/`reception`/`member`/`viewer` over
|
||||||
`toNodeHandler(auth)` at `/api/auth/*`.
|
`patient`/`appointment`/`prescription`/`task` resources). `reception` has no `prescription`
|
||||||
|
statement — it's scoped to scheduling + registration, and `src/services/patients.ts` redacts
|
||||||
|
clinical fields for it. Mounted in `src/index.ts` via `toNodeHandler(auth)` at `/api/auth/*`.
|
||||||
|
- **`src/routes/staff.ts`** — admin-provisioned staff: `POST /api/staff` creates a user
|
||||||
|
(`auth.api.signUpEmail`) + attaches them to the clinic (`auth.api.addMember`); `GET /api/staff`
|
||||||
|
lists members with usernames. Replaces the old email-invitation flow. Gated by
|
||||||
|
`requirePermission({ member: ["create"] })`.
|
||||||
|
- **Better Auth = the single source of RBAC.** Manage all permissions through Better Auth, not a
|
||||||
|
custom layer. Authoritative references live as repo skills under
|
||||||
|
`.claude/skills/{better-auth-best-practices,organization-best-practices,
|
||||||
|
email-and-password-best-practices,better-auth-security-best-practices}` — consult them before
|
||||||
|
changing `auth.ts`, `src/lib/access.ts`, or the auth schema.
|
||||||
- **`src/db/`** — `index.ts` is the Drizzle client (no schema passed; we use the core query builder).
|
- **`src/db/`** — `index.ts` is the Drizzle client (no schema passed; we use the core query builder).
|
||||||
`schema/auth.ts` is **generated** by the Better Auth CLI; `schema/patients.ts` is hand-written and
|
`schema/auth.ts` is **generated** by the Better Auth CLI; `schema/patients.ts` is hand-written and
|
||||||
references the generated `organization`/`user` tables.
|
references the generated `organization`/`user` tables.
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
ALTER TABLE "user" ADD COLUMN "username" text;--> statement-breakpoint
|
||||||
|
ALTER TABLE "user" ADD COLUMN "display_username" text;--> statement-breakpoint
|
||||||
|
ALTER TABLE "user" ADD CONSTRAINT "user_username_unique" UNIQUE("username");
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -50,6 +50,13 @@
|
|||||||
"when": 1780856647280,
|
"when": 1780856647280,
|
||||||
"tag": "0006_square_wither",
|
"tag": "0006_square_wither",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 7,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1780933857005,
|
||||||
|
"tag": "0007_skinny_bloodstrike",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { betterAuth } from "better-auth";
|
import { betterAuth } from "better-auth";
|
||||||
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
||||||
import { organization } from "better-auth/plugins";
|
import { organization } from "better-auth/plugins";
|
||||||
|
import { username } from "better-auth/plugins/username";
|
||||||
import { eq } from "drizzle-orm";
|
import { eq } from "drizzle-orm";
|
||||||
|
|
||||||
import { db } from "./db/index.js";
|
import { db } from "./db/index.js";
|
||||||
@@ -55,6 +56,13 @@ export const auth = betterAuth({
|
|||||||
},
|
},
|
||||||
|
|
||||||
plugins: [
|
plugins: [
|
||||||
|
// Lets staff sign in with a username (in addition to email). Admin-created
|
||||||
|
// staff accounts (see src/routes/staff.ts) set a username + password the
|
||||||
|
// employee uses to log in. Adds `username` + `displayUsername` to `user`.
|
||||||
|
username({
|
||||||
|
minUsernameLength: 3,
|
||||||
|
maxUsernameLength: 32,
|
||||||
|
}),
|
||||||
organization({
|
organization({
|
||||||
ac,
|
ac,
|
||||||
roles,
|
roles,
|
||||||
|
|||||||
@@ -21,6 +21,8 @@ export const user = pgTable("user", {
|
|||||||
.defaultNow()
|
.defaultNow()
|
||||||
.$onUpdate(() => /* @__PURE__ */ new Date())
|
.$onUpdate(() => /* @__PURE__ */ new Date())
|
||||||
.notNull(),
|
.notNull(),
|
||||||
|
username: text("username").unique(),
|
||||||
|
displayUsername: text("display_username"),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const session = pgTable(
|
export const session = pgTable(
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import { notesRouter } from "./routes/notes.js";
|
|||||||
import { notificationsRouter } from "./routes/notifications.js";
|
import { notificationsRouter } from "./routes/notifications.js";
|
||||||
import { patientsRouter } from "./routes/patients.js";
|
import { patientsRouter } from "./routes/patients.js";
|
||||||
import { prescriptionsRouter } from "./routes/prescriptions.js";
|
import { prescriptionsRouter } from "./routes/prescriptions.js";
|
||||||
|
import { staffRouter } from "./routes/staff.js";
|
||||||
import { tasksRouter } from "./routes/tasks.js";
|
import { tasksRouter } from "./routes/tasks.js";
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
@@ -58,6 +59,7 @@ app.use("/api/notes", notesRouter);
|
|||||||
app.use("/api/appointments", appointmentsRouter);
|
app.use("/api/appointments", appointmentsRouter);
|
||||||
app.use("/api/prescriptions", prescriptionsRouter);
|
app.use("/api/prescriptions", prescriptionsRouter);
|
||||||
app.use("/api/tasks", tasksRouter);
|
app.use("/api/tasks", tasksRouter);
|
||||||
|
app.use("/api/staff", staffRouter);
|
||||||
app.use("/api/activity", activityRouter);
|
app.use("/api/activity", activityRouter);
|
||||||
app.use("/api/analytics", analyticsRouter);
|
app.use("/api/analytics", analyticsRouter);
|
||||||
app.use("/api/conversations", conversationsRouter);
|
app.use("/api/conversations", conversationsRouter);
|
||||||
@@ -78,6 +80,7 @@ server.listen(env.PORT, () => {
|
|||||||
console.log(` • appts: /api/appointments`);
|
console.log(` • appts: /api/appointments`);
|
||||||
console.log(` • rx: /api/prescriptions`);
|
console.log(` • rx: /api/prescriptions`);
|
||||||
console.log(` • tasks: /api/tasks`);
|
console.log(` • tasks: /api/tasks`);
|
||||||
|
console.log(` • staff: /api/staff`);
|
||||||
console.log(` • activity: /api/activity`);
|
console.log(` • activity: /api/activity`);
|
||||||
console.log(` • stats: /api/analytics`);
|
console.log(` • stats: /api/analytics`);
|
||||||
console.log(` • messages: /api/conversations (+ Socket.io)`);
|
console.log(` • messages: /api/conversations (+ Socket.io)`);
|
||||||
|
|||||||
@@ -51,6 +51,29 @@ export const member = ac.newRole({
|
|||||||
task: ["read", "write", "delete"],
|
task: ["read", "write", "delete"],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// doctor (clinician): same clinical access as `member` — the role we provision
|
||||||
|
// for physicians. Kept distinct from `member` so the UI can label/treat it as
|
||||||
|
// "Doctor" and so reception can be a sibling role with narrower access.
|
||||||
|
export const doctor = ac.newRole({
|
||||||
|
...memberAc.statements,
|
||||||
|
patient: ["read", "write"],
|
||||||
|
appointment: ["read", "write", "delete"],
|
||||||
|
prescription: ["read", "write", "delete"],
|
||||||
|
task: ["read", "write", "delete"],
|
||||||
|
});
|
||||||
|
|
||||||
|
// reception (front desk): scheduling + patient registration only. Can manage
|
||||||
|
// appointments and register/edit patient demographics, but has NO access to
|
||||||
|
// clinical records (no prescription statement at all) — least-privilege per
|
||||||
|
// EHR RBAC guidance. The patients service additionally redacts clinical fields
|
||||||
|
// for this role so demographics-only is enforced server-side, not just in UI.
|
||||||
|
export const reception = ac.newRole({
|
||||||
|
...memberAc.statements,
|
||||||
|
patient: ["read", "write"],
|
||||||
|
appointment: ["read", "write", "delete"],
|
||||||
|
task: ["read", "write"],
|
||||||
|
});
|
||||||
|
|
||||||
// viewer: read-only access to clinical records.
|
// viewer: read-only access to clinical records.
|
||||||
export const viewer = ac.newRole({
|
export const viewer = ac.newRole({
|
||||||
patient: ["read"],
|
patient: ["read"],
|
||||||
@@ -59,4 +82,4 @@ export const viewer = ac.newRole({
|
|||||||
task: ["read"],
|
task: ["read"],
|
||||||
});
|
});
|
||||||
|
|
||||||
export const roles = { owner, admin, member, viewer };
|
export const roles = { owner, admin, doctor, reception, member, viewer };
|
||||||
|
|||||||
@@ -15,6 +15,18 @@ import * as service from "../services/patients.js";
|
|||||||
|
|
||||||
export const patientsRouter = Router();
|
export const patientsRouter = Router();
|
||||||
|
|
||||||
|
// The `reception` role is scoped to scheduling + registration: it sees and
|
||||||
|
// writes patient demographics only, never clinical PHI. True only when the
|
||||||
|
// caller's role set is reception without any clinical-capable role.
|
||||||
|
function isReceptionOnly(memberRole?: string): boolean {
|
||||||
|
const names = String(memberRole ?? "")
|
||||||
|
.split(",")
|
||||||
|
.map((s) => s.trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
if (!names.includes("reception")) return false;
|
||||||
|
return !names.some((r) => ["owner", "admin", "doctor", "member"].includes(r));
|
||||||
|
}
|
||||||
|
|
||||||
// Notify the rest of the clinic about a patient record change (best-effort,
|
// Notify the rest of the clinic about a patient record change (best-effort,
|
||||||
// pushed live over the socket).
|
// pushed live over the socket).
|
||||||
async function notifyClinic(
|
async function notifyClinic(
|
||||||
@@ -50,7 +62,12 @@ patientsRouter.get(
|
|||||||
requirePermission({ patient: ["read"] }),
|
requirePermission({ patient: ["read"] }),
|
||||||
async (req, res, next) => {
|
async (req, res, next) => {
|
||||||
try {
|
try {
|
||||||
res.json(await service.listPatients(req.organizationId!));
|
res.json(
|
||||||
|
await service.listPatients(
|
||||||
|
req.organizationId!,
|
||||||
|
isReceptionOnly(req.memberRole),
|
||||||
|
),
|
||||||
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
next(err);
|
next(err);
|
||||||
}
|
}
|
||||||
@@ -65,6 +82,7 @@ patientsRouter.get(
|
|||||||
const patient = await service.getPatient(
|
const patient = await service.getPatient(
|
||||||
req.organizationId!,
|
req.organizationId!,
|
||||||
req.params.fileNumber as string,
|
req.params.fileNumber as string,
|
||||||
|
isReceptionOnly(req.memberRole),
|
||||||
);
|
);
|
||||||
if (!patient) throw new HttpError(404, "Patient not found.");
|
if (!patient) throw new HttpError(404, "Patient not found.");
|
||||||
res.json(patient);
|
res.json(patient);
|
||||||
@@ -84,6 +102,7 @@ patientsRouter.post(
|
|||||||
req.organizationId!,
|
req.organizationId!,
|
||||||
req.user!.id,
|
req.user!.id,
|
||||||
input,
|
input,
|
||||||
|
isReceptionOnly(req.memberRole),
|
||||||
);
|
);
|
||||||
await recordActivity({
|
await recordActivity({
|
||||||
orgId: req.organizationId!,
|
orgId: req.organizationId!,
|
||||||
@@ -117,6 +136,7 @@ patientsRouter.put(
|
|||||||
req.organizationId!,
|
req.organizationId!,
|
||||||
req.params.fileNumber as string,
|
req.params.fileNumber as string,
|
||||||
input,
|
input,
|
||||||
|
isReceptionOnly(req.memberRole),
|
||||||
);
|
);
|
||||||
if (!updated) throw new HttpError(404, "Patient not found.");
|
if (!updated) throw new HttpError(404, "Patient not found.");
|
||||||
await recordActivity({
|
await recordActivity({
|
||||||
|
|||||||
@@ -0,0 +1,134 @@
|
|||||||
|
import { asc, eq } from "drizzle-orm";
|
||||||
|
import { Router } from "express";
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
import { auth } from "../auth.js";
|
||||||
|
import { db } from "../db/index.js";
|
||||||
|
import { member, organization, user } from "../db/schema/auth.js";
|
||||||
|
import { HttpError } from "../lib/http-error.js";
|
||||||
|
import { requireAuth, requireOrg, requirePermission } from "../middleware/auth.js";
|
||||||
|
|
||||||
|
export const staffRouter = Router();
|
||||||
|
|
||||||
|
// Admin-provisioned staff accounts. Instead of emailing an invitation link, an
|
||||||
|
// owner/admin creates the employee's account directly — name, role and a
|
||||||
|
// username + password the employee uses to sign in. Everything is gated by the
|
||||||
|
// Better Auth `member` permission so RBAC stays in one place. The account is
|
||||||
|
// created via `auth.api.signUpEmail` and attached to the active clinic via
|
||||||
|
// `auth.api.addMember`; the new user then shows up everywhere org members do
|
||||||
|
// (e.g. the Messages compose picker) with no extra wiring.
|
||||||
|
|
||||||
|
// Roles an admin may assign — `owner` is intentionally excluded (the clinic
|
||||||
|
// creator is the sole owner; transfer ownership via member-role updates).
|
||||||
|
const PROVISIONABLE_ROLES = ["admin", "doctor", "reception", "viewer"] as const;
|
||||||
|
|
||||||
|
const staffInputSchema = z.object({
|
||||||
|
name: z.string().trim().min(1).max(120),
|
||||||
|
username: z
|
||||||
|
.string()
|
||||||
|
.trim()
|
||||||
|
.min(3)
|
||||||
|
.max(32)
|
||||||
|
.regex(
|
||||||
|
/^[a-zA-Z0-9_.]+$/,
|
||||||
|
"Username may only contain letters, numbers, dots and underscores.",
|
||||||
|
),
|
||||||
|
password: z.string().min(12).max(256),
|
||||||
|
role: z.enum(PROVISIONABLE_ROLES),
|
||||||
|
// Optional real email; staff sign in by username, so when omitted we mint a
|
||||||
|
// placeholder (the email column is required + unique).
|
||||||
|
email: z.preprocess(
|
||||||
|
(v) => (v === "" ? undefined : v),
|
||||||
|
z.string().trim().email().optional(),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
staffRouter.use(requireAuth, requireOrg);
|
||||||
|
|
||||||
|
// List the clinic's members with their usernames (the org client's
|
||||||
|
// getFullOrganization doesn't expose username). Owner/admin only.
|
||||||
|
staffRouter.get(
|
||||||
|
"/",
|
||||||
|
requirePermission({ member: ["create"] }),
|
||||||
|
async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const rows = await db
|
||||||
|
.select({
|
||||||
|
id: member.id,
|
||||||
|
userId: member.userId,
|
||||||
|
role: member.role,
|
||||||
|
name: user.name,
|
||||||
|
email: user.email,
|
||||||
|
username: user.username,
|
||||||
|
})
|
||||||
|
.from(member)
|
||||||
|
.innerJoin(user, eq(user.id, member.userId))
|
||||||
|
.where(eq(member.organizationId, req.organizationId!))
|
||||||
|
.orderBy(asc(user.name));
|
||||||
|
res.json(rows);
|
||||||
|
} catch (err) {
|
||||||
|
next(err);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
// Provision a new staff account and add them to the active clinic.
|
||||||
|
staffRouter.post(
|
||||||
|
"/",
|
||||||
|
requirePermission({ member: ["create"] }),
|
||||||
|
async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const input = staffInputSchema.parse(req.body);
|
||||||
|
|
||||||
|
const [org] = await db
|
||||||
|
.select({ slug: organization.slug })
|
||||||
|
.from(organization)
|
||||||
|
.where(eq(organization.id, req.organizationId!));
|
||||||
|
if (!org) throw new HttpError(404, "Clinic not found.");
|
||||||
|
|
||||||
|
const email =
|
||||||
|
input.email ?? `${input.username.toLowerCase()}@${org.slug}.temetro.local`;
|
||||||
|
|
||||||
|
// Create the credential account (user + hashed password + username).
|
||||||
|
let newUserId: string;
|
||||||
|
try {
|
||||||
|
const result = await auth.api.signUpEmail({
|
||||||
|
body: {
|
||||||
|
name: input.name,
|
||||||
|
email,
|
||||||
|
password: input.password,
|
||||||
|
username: input.username,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
newUserId = result.user.id;
|
||||||
|
} catch (err) {
|
||||||
|
// Surface Better Auth's reason (e.g. username/email already taken).
|
||||||
|
const message =
|
||||||
|
(err as { body?: { message?: string } })?.body?.message ??
|
||||||
|
(err as Error)?.message ??
|
||||||
|
"Could not create the account.";
|
||||||
|
throw new HttpError(400, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Attach the new user to the clinic with the chosen role (server-side,
|
||||||
|
// no invitation step).
|
||||||
|
await auth.api.addMember({
|
||||||
|
body: {
|
||||||
|
userId: newUserId,
|
||||||
|
organizationId: req.organizationId!,
|
||||||
|
role: input.role,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
res.status(201).json({
|
||||||
|
userId: newUserId,
|
||||||
|
name: input.name,
|
||||||
|
email,
|
||||||
|
username: input.username.toLowerCase(),
|
||||||
|
role: input.role,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
next(err);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
@@ -18,6 +18,7 @@ import type {
|
|||||||
Medication,
|
Medication,
|
||||||
Patient,
|
Patient,
|
||||||
Problem,
|
Problem,
|
||||||
|
Trend,
|
||||||
} from "../types/patient.js";
|
} from "../types/patient.js";
|
||||||
|
|
||||||
type PatientRow = typeof patients.$inferSelect;
|
type PatientRow = typeof patients.$inferSelect;
|
||||||
@@ -65,6 +66,27 @@ function toPatient(row: PatientRow, children: Children): Patient {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const EMPTY_TREND: Trend = { label: "", unit: "", points: [] };
|
||||||
|
|
||||||
|
// Strip every clinical section, leaving only registration/demographic fields.
|
||||||
|
// Used for the `reception` role, which is scoped to scheduling + registration
|
||||||
|
// and must never receive PHI (labs, meds, problems, vitals, encounters). This
|
||||||
|
// enforces least-privilege server-side rather than relying on the UI to hide it.
|
||||||
|
function redactClinical(patient: Patient): Patient {
|
||||||
|
return {
|
||||||
|
...patient,
|
||||||
|
allergies: [],
|
||||||
|
alerts: [],
|
||||||
|
medications: [],
|
||||||
|
problems: [],
|
||||||
|
vitals: { bp: "", hr: "", temp: "", spo2: "", takenAt: "" },
|
||||||
|
vitalsTrend: EMPTY_TREND,
|
||||||
|
labs: [],
|
||||||
|
labTrend: EMPTY_TREND,
|
||||||
|
encounters: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Input children are already in the canonical Patient sub-shapes.
|
// Input children are already in the canonical Patient sub-shapes.
|
||||||
function childrenFromInput(input: PatientInput): Children {
|
function childrenFromInput(input: PatientInput): Children {
|
||||||
return {
|
return {
|
||||||
@@ -98,6 +120,49 @@ function patientColumns(orgId: string, input: PatientInput, createdBy?: string)
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Registration columns only — clinical columns get empty values (they are
|
||||||
|
// NOT NULL). Used when the `reception` role creates a patient so they can never
|
||||||
|
// write PHI even if the request body contains clinical fields.
|
||||||
|
function demographicColumns(
|
||||||
|
orgId: string,
|
||||||
|
input: PatientInput,
|
||||||
|
createdBy?: string,
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
organizationId: orgId,
|
||||||
|
fileNumber: input.fileNumber,
|
||||||
|
name: input.name,
|
||||||
|
age: input.age,
|
||||||
|
sex: input.sex,
|
||||||
|
pcp: input.pcp,
|
||||||
|
status: input.status,
|
||||||
|
initials: input.initials,
|
||||||
|
alerts: [] as string[],
|
||||||
|
vitalsBp: "",
|
||||||
|
vitalsHr: "",
|
||||||
|
vitalsTemp: "",
|
||||||
|
vitalsSpo2: "",
|
||||||
|
vitalsTakenAt: "",
|
||||||
|
vitalsTrend: EMPTY_TREND,
|
||||||
|
labTrend: EMPTY_TREND,
|
||||||
|
...(createdBy ? { createdBy } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// The demographic subset for a `reception` update — never touches clinical
|
||||||
|
// columns or child tables, so an existing record's PHI is preserved.
|
||||||
|
function demographicUpdateColumns(input: PatientInput) {
|
||||||
|
return {
|
||||||
|
fileNumber: input.fileNumber,
|
||||||
|
name: input.name,
|
||||||
|
age: input.age,
|
||||||
|
sex: input.sex,
|
||||||
|
pcp: input.pcp,
|
||||||
|
status: input.status,
|
||||||
|
initials: input.initials,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// 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[],
|
||||||
@@ -212,19 +277,26 @@ function isUniqueViolation(err: unknown): boolean {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function listPatients(orgId: string): Promise<Patient[]> {
|
export async function listPatients(
|
||||||
|
orgId: string,
|
||||||
|
demographicsOnly = false,
|
||||||
|
): Promise<Patient[]> {
|
||||||
const rows = await db
|
const rows = await db
|
||||||
.select()
|
.select()
|
||||||
.from(patients)
|
.from(patients)
|
||||||
.where(eq(patients.organizationId, orgId))
|
.where(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) => toPatient(r, children.get(r.id) ?? emptyChildren()));
|
return rows.map((r) => {
|
||||||
|
const patient = toPatient(r, children.get(r.id) ?? emptyChildren());
|
||||||
|
return demographicsOnly ? redactClinical(patient) : patient;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getPatient(
|
export async function getPatient(
|
||||||
orgId: string,
|
orgId: string,
|
||||||
fileNumber: string,
|
fileNumber: string,
|
||||||
|
demographicsOnly = false,
|
||||||
): Promise<Patient | null> {
|
): Promise<Patient | null> {
|
||||||
const [row] = await db
|
const [row] = await db
|
||||||
.select()
|
.select()
|
||||||
@@ -237,16 +309,27 @@ export async function getPatient(
|
|||||||
);
|
);
|
||||||
if (!row) return null;
|
if (!row) return null;
|
||||||
const children = await loadChildren([row.id]);
|
const children = await loadChildren([row.id]);
|
||||||
return toPatient(row, children.get(row.id) ?? emptyChildren());
|
const patient = toPatient(row, children.get(row.id) ?? emptyChildren());
|
||||||
|
return demographicsOnly ? redactClinical(patient) : patient;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createPatient(
|
export async function createPatient(
|
||||||
orgId: string,
|
orgId: string,
|
||||||
userId: string,
|
userId: string,
|
||||||
input: PatientInput,
|
input: PatientInput,
|
||||||
|
demographicsOnly = false,
|
||||||
): Promise<Patient> {
|
): Promise<Patient> {
|
||||||
try {
|
try {
|
||||||
return await db.transaction(async (tx) => {
|
return await db.transaction(async (tx) => {
|
||||||
|
// Reception registers demographics only — clinical input is ignored and
|
||||||
|
// no child (clinical) rows are written.
|
||||||
|
if (demographicsOnly) {
|
||||||
|
const [row] = await tx
|
||||||
|
.insert(patients)
|
||||||
|
.values(demographicColumns(orgId, input, userId))
|
||||||
|
.returning();
|
||||||
|
return toPatient(row!, emptyChildren());
|
||||||
|
}
|
||||||
const [row] = await tx
|
const [row] = await tx
|
||||||
.insert(patients)
|
.insert(patients)
|
||||||
.values(patientColumns(orgId, input, userId))
|
.values(patientColumns(orgId, input, userId))
|
||||||
@@ -269,6 +352,7 @@ export async function updatePatient(
|
|||||||
orgId: string,
|
orgId: string,
|
||||||
fileNumber: string,
|
fileNumber: string,
|
||||||
input: PatientInput,
|
input: PatientInput,
|
||||||
|
demographicsOnly = false,
|
||||||
): Promise<Patient | null> {
|
): Promise<Patient | null> {
|
||||||
try {
|
try {
|
||||||
return await db.transaction(async (tx) => {
|
return await db.transaction(async (tx) => {
|
||||||
@@ -283,6 +367,21 @@ export async function updatePatient(
|
|||||||
);
|
);
|
||||||
if (!existing) return null;
|
if (!existing) return null;
|
||||||
|
|
||||||
|
// Reception edits demographics only: update the registration columns and
|
||||||
|
// leave clinical columns + child tables (existing PHI) untouched, then
|
||||||
|
// return a redacted record.
|
||||||
|
if (demographicsOnly) {
|
||||||
|
const [row] = await tx
|
||||||
|
.update(patients)
|
||||||
|
.set(demographicUpdateColumns(input))
|
||||||
|
.where(eq(patients.id, existing.id))
|
||||||
|
.returning();
|
||||||
|
const children = await loadChildren([existing.id]);
|
||||||
|
return redactClinical(
|
||||||
|
toPatient(row!, children.get(existing.id) ?? emptyChildren()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const [row] = await tx
|
const [row] = await tx
|
||||||
.update(patients)
|
.update(patients)
|
||||||
.set(patientColumns(orgId, input))
|
.set(patientColumns(orgId, input))
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useRouter } from "next/navigation";
|
import { usePathname, useRouter } from "next/navigation";
|
||||||
import { type ReactNode, useEffect, useRef } from "react";
|
import { type ReactNode, useEffect, useRef } from "react";
|
||||||
|
|
||||||
import { authClient } from "@/lib/auth-client";
|
import { authClient } from "@/lib/auth-client";
|
||||||
|
import { canAccessRoute, defaultLandingFor, useActiveRole } from "@/lib/roles";
|
||||||
|
|
||||||
// Authoritative client-side gate for the app shell. Requires a session and an
|
// Authoritative client-side gate for the app shell. Requires a session and an
|
||||||
// active clinic. If the user is signed in without an active clinic but already
|
// active clinic. If the user is signed in without an active clinic but already
|
||||||
@@ -11,6 +12,8 @@ import { authClient } from "@/lib/auth-client";
|
|||||||
// with no clinics at all. The API enforces the same access rules server-side.
|
// with no clinics at all. The API enforces the same access rules server-side.
|
||||||
export function AppAuthGuard({ children }: { children: ReactNode }) {
|
export function AppAuthGuard({ children }: { children: ReactNode }) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const pathname = usePathname();
|
||||||
|
const role = useActiveRole();
|
||||||
const { data: session, isPending } = authClient.useSession();
|
const { data: session, isPending } = authClient.useSession();
|
||||||
const { data: orgs, isPending: orgsPending } =
|
const { data: orgs, isPending: orgsPending } =
|
||||||
authClient.useListOrganizations();
|
authClient.useListOrganizations();
|
||||||
@@ -41,6 +44,17 @@ export function AppAuthGuard({ children }: { children: ReactNode }) {
|
|||||||
}, [isPending, hasUser, activeOrgId, orgsPending, orgs, router]);
|
}, [isPending, hasUser, activeOrgId, orgsPending, orgs, router]);
|
||||||
|
|
||||||
const ready = hasUser && Boolean(activeOrgId);
|
const ready = hasUser && Boolean(activeOrgId);
|
||||||
|
|
||||||
|
// Role-based route guard: keep non-clinical roles (reception) out of clinical
|
||||||
|
// pages — bounce them to their default landing. The backend enforces the same
|
||||||
|
// via per-route RBAC (403); this just avoids showing an empty/erroring page.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!ready || role == null) return;
|
||||||
|
if (!canAccessRoute(pathname, role)) {
|
||||||
|
router.replace(defaultLandingFor(role));
|
||||||
|
}
|
||||||
|
}, [ready, role, pathname, router]);
|
||||||
|
|
||||||
if (!ready) {
|
if (!ready) {
|
||||||
return (
|
return (
|
||||||
<div className="flex h-dvh w-full items-center justify-center text-sm text-muted-foreground">
|
<div className="flex h-dvh w-full items-center justify-center text-sm text-muted-foreground">
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ import {
|
|||||||
type Patient,
|
type Patient,
|
||||||
updatePatient,
|
updatePatient,
|
||||||
} from "@/lib/patients";
|
} from "@/lib/patients";
|
||||||
|
import { hasClinicalAccess, useActiveRole } from "@/lib/roles";
|
||||||
import { notify } from "@/lib/toast";
|
import { notify } from "@/lib/toast";
|
||||||
|
|
||||||
type PatientFormDialogProps = {
|
type PatientFormDialogProps = {
|
||||||
@@ -203,6 +204,11 @@ export function PatientFormDialog({
|
|||||||
}: PatientFormDialogProps) {
|
}: PatientFormDialogProps) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const isEdit = mode === "edit";
|
const isEdit = mode === "edit";
|
||||||
|
// Reception registers demographics only — clinical sections are hidden (the
|
||||||
|
// backend also redacts/ignores clinical data for this role). Show everything
|
||||||
|
// while the role is still loading to avoid a flash for clinical users.
|
||||||
|
const role = useActiveRole();
|
||||||
|
const showClinical = role == null || hasClinicalAccess(role);
|
||||||
|
|
||||||
const [submitting, setSubmitting] = useState(false);
|
const [submitting, setSubmitting] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
@@ -416,6 +422,8 @@ export function PatientFormDialog({
|
|||||||
/>
|
/>
|
||||||
</Field>
|
</Field>
|
||||||
|
|
||||||
|
{showClinical && (
|
||||||
|
<>
|
||||||
<div className="flex flex-col gap-1.5">
|
<div className="flex flex-col gap-1.5">
|
||||||
<span className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
|
<span className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
|
||||||
{t("patientForm.currentVitals")}
|
{t("patientForm.currentVitals")}
|
||||||
@@ -615,6 +623,8 @@ export function PatientFormDialog({
|
|||||||
)}
|
)}
|
||||||
rows={visits}
|
rows={visits}
|
||||||
/>
|
/>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</DialogPanel>
|
</DialogPanel>
|
||||||
|
|
||||||
<DialogFooter className="flex-col items-stretch gap-2 sm:flex-row sm:items-center">
|
<DialogFooter className="flex-col items-stretch gap-2 sm:flex-row sm:items-center">
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ import {
|
|||||||
CommandPanel,
|
CommandPanel,
|
||||||
} from "@/components/ui/command";
|
} from "@/components/ui/command";
|
||||||
import { Kbd, KbdGroup } from "@/components/ui/kbd";
|
import { Kbd, KbdGroup } from "@/components/ui/kbd";
|
||||||
import { navItems } from "@/lib/nav";
|
import { useActiveRole, visibleNavItems } from "@/lib/roles";
|
||||||
|
|
||||||
type CommandPaletteContextValue = { open: () => void };
|
type CommandPaletteContextValue = { open: () => void };
|
||||||
|
|
||||||
@@ -50,6 +50,7 @@ export function useCommandPalette(): CommandPaletteContextValue {
|
|||||||
export function CommandPaletteProvider({ children }: { children: ReactNode }) {
|
export function CommandPaletteProvider({ children }: { children: ReactNode }) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const role = useActiveRole();
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -70,7 +71,8 @@ export function CommandPaletteProvider({ children }: { children: ReactNode }) {
|
|||||||
value: "pages",
|
value: "pages",
|
||||||
label: t("nav.commandGroup"),
|
label: t("nav.commandGroup"),
|
||||||
// Flatten sub-pages so e.g. "Appointments & Schedule" is reachable.
|
// Flatten sub-pages so e.g. "Appointments & Schedule" is reachable.
|
||||||
items: navItems.flatMap((item) =>
|
// Filtered by role so reception can't jump to clinical pages.
|
||||||
|
items: visibleNavItems(role).flatMap((item) =>
|
||||||
item.subs?.length
|
item.subs?.length
|
||||||
? item.subs.map((sub) => ({
|
? item.subs.map((sub) => ({
|
||||||
id: sub.id,
|
id: sub.id,
|
||||||
@@ -89,7 +91,7 @@ export function CommandPaletteProvider({ children }: { children: ReactNode }) {
|
|||||||
),
|
),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
[t],
|
[t, role],
|
||||||
);
|
);
|
||||||
|
|
||||||
type Group = (typeof groups)[number];
|
type Group = (typeof groups)[number];
|
||||||
|
|||||||
@@ -15,17 +15,23 @@ import {
|
|||||||
} from "@/components/ui/card";
|
} from "@/components/ui/card";
|
||||||
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field";
|
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Tabs, TabsList, TabsTab } from "@/components/ui/tabs";
|
||||||
import { authClient } from "@/lib/auth-client";
|
import { authClient } from "@/lib/auth-client";
|
||||||
import { notify } from "@/lib/toast";
|
import { notify } from "@/lib/toast";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
type Mode = "email" | "username";
|
||||||
|
|
||||||
export function LoginForm({
|
export function LoginForm({
|
||||||
className,
|
className,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<"div">) {
|
}: React.ComponentProps<"div">) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [email, setEmail] = useState("");
|
// Staff provisioned by an admin sign in with a username; clinic owners sign in
|
||||||
|
// with the email they signed up with. The tab picks which credential to use.
|
||||||
|
const [mode, setMode] = useState<Mode>("email");
|
||||||
|
const [identifier, setIdentifier] = useState("");
|
||||||
const [password, setPassword] = useState("");
|
const [password, setPassword] = useState("");
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [submitting, setSubmitting] = useState(false);
|
const [submitting, setSubmitting] = useState(false);
|
||||||
@@ -36,11 +42,19 @@ export function LoginForm({
|
|||||||
setSubmitting(true);
|
setSubmitting(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
|
|
||||||
const { error: err } = await authClient.signIn.email({
|
const callbackURL = `${window.location.origin}/`;
|
||||||
email: email.trim(),
|
const { error: err } =
|
||||||
password,
|
mode === "email"
|
||||||
callbackURL: `${window.location.origin}/`,
|
? await authClient.signIn.email({
|
||||||
});
|
email: identifier.trim(),
|
||||||
|
password,
|
||||||
|
callbackURL,
|
||||||
|
})
|
||||||
|
: await authClient.signIn.username({
|
||||||
|
username: identifier.trim(),
|
||||||
|
password,
|
||||||
|
callbackURL,
|
||||||
|
});
|
||||||
|
|
||||||
if (err) {
|
if (err) {
|
||||||
const message = err.message ?? t("auth.login.error");
|
const message = err.message ?? t("auth.login.error");
|
||||||
@@ -68,18 +82,40 @@ export function LoginForm({
|
|||||||
{error}
|
{error}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
<Tabs
|
||||||
|
onValueChange={(value) => {
|
||||||
|
setMode(value as Mode);
|
||||||
|
setError(null);
|
||||||
|
}}
|
||||||
|
value={mode}
|
||||||
|
>
|
||||||
|
<TabsList className="w-full">
|
||||||
|
<TabsTab className="flex-1" value="email">
|
||||||
|
{t("auth.login.tabEmail")}
|
||||||
|
</TabsTab>
|
||||||
|
<TabsTab className="flex-1" value="username">
|
||||||
|
{t("auth.login.tabUsername")}
|
||||||
|
</TabsTab>
|
||||||
|
</TabsList>
|
||||||
|
</Tabs>
|
||||||
<Field>
|
<Field>
|
||||||
<FieldLabel htmlFor="email">
|
<FieldLabel htmlFor="identifier">
|
||||||
{t("auth.login.emailLabel")}
|
{mode === "email"
|
||||||
|
? t("auth.login.emailLabel")
|
||||||
|
: t("auth.login.usernameLabel")}
|
||||||
</FieldLabel>
|
</FieldLabel>
|
||||||
<Input
|
<Input
|
||||||
autoComplete="email"
|
autoComplete={mode === "email" ? "email" : "username"}
|
||||||
id="email"
|
id="identifier"
|
||||||
onChange={(e) => setEmail(e.target.value)}
|
onChange={(e) => setIdentifier(e.target.value)}
|
||||||
placeholder={t("auth.login.emailPlaceholder")}
|
placeholder={
|
||||||
|
mode === "email"
|
||||||
|
? t("auth.login.emailPlaceholder")
|
||||||
|
: t("auth.login.usernamePlaceholder")
|
||||||
|
}
|
||||||
required
|
required
|
||||||
type="email"
|
type={mode === "email" ? "email" : "text"}
|
||||||
value={email}
|
value={identifier}
|
||||||
/>
|
/>
|
||||||
</Field>
|
</Field>
|
||||||
<Field className="w-full">
|
<Field className="w-full">
|
||||||
|
|||||||
@@ -0,0 +1,235 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { type FormEvent, 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 { Field, FieldDescription, FieldLabel } from "@/components/ui/field";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { ROLE_LABELS } from "@/lib/access";
|
||||||
|
import { apiFetch } from "@/lib/api-client";
|
||||||
|
import { PROVISIONABLE_ROLES } from "@/lib/roles";
|
||||||
|
import { notify } from "@/lib/toast";
|
||||||
|
|
||||||
|
const MIN_PASSWORD = 12;
|
||||||
|
const MIN_USERNAME = 3;
|
||||||
|
|
||||||
|
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 = {
|
||||||
|
open: boolean;
|
||||||
|
onOpenChange: (open: boolean) => void;
|
||||||
|
onCreated?: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Admin provisions a staff account in two steps: first the "invitation" (who +
|
||||||
|
// what role), then the credentials (username + password) the employee uses to
|
||||||
|
// sign in. Posts to /api/staff, which creates the account and adds them to the
|
||||||
|
// active clinic via Better Auth.
|
||||||
|
export function AddStaffDialog({ open, onOpenChange, onCreated }: Props) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [step, setStep] = useState<1 | 2>(1);
|
||||||
|
const [name, setName] = useState("");
|
||||||
|
const [role, setRole] = useState<string>("reception");
|
||||||
|
const [username, setUsername] = useState("");
|
||||||
|
const [password, setPassword] = useState("");
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const reset = () => {
|
||||||
|
setStep(1);
|
||||||
|
setName("");
|
||||||
|
setRole("reception");
|
||||||
|
setUsername("");
|
||||||
|
setPassword("");
|
||||||
|
setError(null);
|
||||||
|
setSubmitting(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleOpenChange = (next: boolean) => {
|
||||||
|
if (!next) reset();
|
||||||
|
onOpenChange(next);
|
||||||
|
};
|
||||||
|
|
||||||
|
const submit = async (event: FormEvent) => {
|
||||||
|
event.preventDefault();
|
||||||
|
setError(null);
|
||||||
|
|
||||||
|
// Step 1 → advance to credentials.
|
||||||
|
if (step === 1) {
|
||||||
|
if (!name.trim()) {
|
||||||
|
setError(t("settings.careTeam.add.nameRequired"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setStep(2);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 2 → create the account.
|
||||||
|
if (username.trim().length < MIN_USERNAME) {
|
||||||
|
setError(t("settings.careTeam.add.usernameTooShort", { count: MIN_USERNAME }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (password.length < MIN_PASSWORD) {
|
||||||
|
setError(t("settings.careTeam.add.passwordTooShort", { count: MIN_PASSWORD }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setSubmitting(true);
|
||||||
|
try {
|
||||||
|
await apiFetch("/api/staff", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({
|
||||||
|
name: name.trim(),
|
||||||
|
role,
|
||||||
|
username: username.trim(),
|
||||||
|
password,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
notify.success(
|
||||||
|
t("settings.careTeam.add.createdTitle"),
|
||||||
|
t("settings.careTeam.add.createdBody", {
|
||||||
|
name: name.trim(),
|
||||||
|
username: username.trim().toLowerCase(),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
onCreated?.();
|
||||||
|
handleOpenChange(false);
|
||||||
|
} catch (err) {
|
||||||
|
const message =
|
||||||
|
err instanceof Error ? err.message : t("settings.careTeam.add.error");
|
||||||
|
setError(message);
|
||||||
|
notify.error(t("settings.careTeam.add.errorTitle"), message);
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog onOpenChange={handleOpenChange} open={open}>
|
||||||
|
<DialogPopup className="sm:max-w-md">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{t("settings.careTeam.add.title")}</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
{step === 1
|
||||||
|
? t("settings.careTeam.add.step1Description")
|
||||||
|
: t("settings.careTeam.add.step2Description")}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
<form className="contents" onSubmit={submit}>
|
||||||
|
<DialogPanel className="flex flex-col gap-4">
|
||||||
|
{error && (
|
||||||
|
<p className="rounded-2xl bg-destructive/10 px-3 py-2 text-sm text-destructive">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{step === 1 ? (
|
||||||
|
<>
|
||||||
|
<Field className="w-full">
|
||||||
|
<FieldLabel htmlFor="staff-name">
|
||||||
|
{t("settings.careTeam.add.nameLabel")}
|
||||||
|
</FieldLabel>
|
||||||
|
<Input
|
||||||
|
autoFocus
|
||||||
|
id="staff-name"
|
||||||
|
onChange={(e) => setName(e.target.value)}
|
||||||
|
placeholder={t("settings.careTeam.add.namePlaceholder")}
|
||||||
|
required
|
||||||
|
value={name}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<Field className="w-full">
|
||||||
|
<FieldLabel htmlFor="staff-role">
|
||||||
|
{t("settings.careTeam.add.roleLabel")}
|
||||||
|
</FieldLabel>
|
||||||
|
<select
|
||||||
|
className={selectClass}
|
||||||
|
id="staff-role"
|
||||||
|
onChange={(e) => setRole(e.target.value)}
|
||||||
|
value={role}
|
||||||
|
>
|
||||||
|
{PROVISIONABLE_ROLES.map((r) => (
|
||||||
|
<option key={r} value={r}>
|
||||||
|
{ROLE_LABELS[r]}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</Field>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Field className="w-full">
|
||||||
|
<FieldLabel htmlFor="staff-username">
|
||||||
|
{t("settings.careTeam.add.usernameLabel")}
|
||||||
|
</FieldLabel>
|
||||||
|
<Input
|
||||||
|
autoComplete="off"
|
||||||
|
autoFocus
|
||||||
|
id="staff-username"
|
||||||
|
onChange={(e) => setUsername(e.target.value)}
|
||||||
|
placeholder={t("settings.careTeam.add.usernamePlaceholder")}
|
||||||
|
required
|
||||||
|
value={username}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
<Field className="w-full">
|
||||||
|
<FieldLabel htmlFor="staff-password">
|
||||||
|
{t("settings.careTeam.add.passwordLabel")}
|
||||||
|
</FieldLabel>
|
||||||
|
<Input
|
||||||
|
autoComplete="new-password"
|
||||||
|
id="staff-password"
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
required
|
||||||
|
type="password"
|
||||||
|
value={password}
|
||||||
|
/>
|
||||||
|
<FieldDescription>
|
||||||
|
{t("settings.careTeam.add.passwordHint", { count: MIN_PASSWORD })}
|
||||||
|
</FieldDescription>
|
||||||
|
</Field>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</DialogPanel>
|
||||||
|
|
||||||
|
<DialogFooter>
|
||||||
|
{step === 2 && (
|
||||||
|
<Button
|
||||||
|
onClick={() => {
|
||||||
|
setStep(1);
|
||||||
|
setError(null);
|
||||||
|
}}
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
>
|
||||||
|
{t("settings.careTeam.add.back")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
<DialogClose render={<Button type="button" variant="ghost" />}>
|
||||||
|
{t("settings.careTeam.add.cancel")}
|
||||||
|
</DialogClose>
|
||||||
|
<Button disabled={submitting} type="submit">
|
||||||
|
{step === 1
|
||||||
|
? t("settings.careTeam.add.next")
|
||||||
|
: submitting
|
||||||
|
? t("settings.careTeam.add.creating")
|
||||||
|
: t("settings.careTeam.add.create")}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</form>
|
||||||
|
</DialogPopup>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { X } from "lucide-react";
|
import { UserPlus, X } from "lucide-react";
|
||||||
import { type FormEvent, 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 {
|
import {
|
||||||
SettingsCard,
|
SettingsCard,
|
||||||
SettingsSection,
|
SettingsSection,
|
||||||
@@ -11,27 +12,23 @@ import {
|
|||||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
|
||||||
import { ROLE_LABELS } from "@/lib/access";
|
import { ROLE_LABELS } from "@/lib/access";
|
||||||
|
import { apiFetch } from "@/lib/api-client";
|
||||||
import { authClient } from "@/lib/auth-client";
|
import { authClient } from "@/lib/auth-client";
|
||||||
|
|
||||||
type Member = {
|
// 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;
|
id: string;
|
||||||
role: string;
|
|
||||||
userId: string;
|
userId: string;
|
||||||
user?: { name?: string | null; email?: string | null };
|
role: string;
|
||||||
|
name: string | null;
|
||||||
|
email: string | null;
|
||||||
|
username: string | null;
|
||||||
};
|
};
|
||||||
type Invite = {
|
|
||||||
id: string;
|
|
||||||
email: string;
|
|
||||||
role?: string | null;
|
|
||||||
status: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
const INVITE_ROLES = ["member", "admin", "viewer"] as const;
|
|
||||||
|
|
||||||
function roleLabel(role?: string | null): string {
|
function roleLabel(role?: string | null): string {
|
||||||
if (!role) return "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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -51,32 +48,24 @@ function initials(name?: string | null, email?: string | null): string {
|
|||||||
export function CareTeamPanel() {
|
export function CareTeamPanel() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { data: session } = authClient.useSession();
|
const { data: session } = authClient.useSession();
|
||||||
const [members, setMembers] = useState<Member[]>([]);
|
const [members, setMembers] = useState<StaffMember[]>([]);
|
||||||
const [invites, setInvites] = useState<Invite[]>([]);
|
|
||||||
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 [notice, setNotice] = useState<string | null>(null);
|
const [adding, setAdding] = useState(false);
|
||||||
|
|
||||||
const [email, setEmail] = useState("");
|
|
||||||
const [role, setRole] = useState<(typeof INVITE_ROLES)[number]>("member");
|
|
||||||
const [inviting, setInviting] = useState(false);
|
|
||||||
|
|
||||||
const load = useCallback(async () => {
|
const load = useCallback(async () => {
|
||||||
const { data, error: err } =
|
try {
|
||||||
await authClient.organization.getFullOrganization();
|
const data = await apiFetch<StaffMember[]>("/api/staff");
|
||||||
if (err || !data) {
|
setMembers(data);
|
||||||
setError(err?.message ?? t("settings.careTeam.loadError"));
|
setError(null);
|
||||||
|
} catch (err) {
|
||||||
|
setError(
|
||||||
|
err instanceof Error ? err.message : t("settings.careTeam.loadError"),
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
setMembers((data.members ?? []) as Member[]);
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
setInvites(
|
|
||||||
((data.invitations ?? []) as Invite[]).filter(
|
|
||||||
(i) => i.status === "pending"
|
|
||||||
)
|
|
||||||
);
|
|
||||||
setError(null);
|
|
||||||
setLoading(false);
|
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -86,36 +75,11 @@ export function CareTeamPanel() {
|
|||||||
const myRole = members.find((m) => m.userId === session?.user?.id)?.role;
|
const myRole = members.find((m) => m.userId === session?.user?.id)?.role;
|
||||||
const canManage = myRole === "owner" || myRole === "admin";
|
const canManage = myRole === "owner" || myRole === "admin";
|
||||||
|
|
||||||
const invite = async (event: FormEvent) => {
|
|
||||||
event.preventDefault();
|
|
||||||
if (!email.trim() || inviting) return;
|
|
||||||
setInviting(true);
|
|
||||||
setNotice(null);
|
|
||||||
setError(null);
|
|
||||||
const { error: err } = await authClient.organization.inviteMember({
|
|
||||||
email: email.trim(),
|
|
||||||
role,
|
|
||||||
});
|
|
||||||
setInviting(false);
|
|
||||||
if (err) {
|
|
||||||
setError(err.message ?? t("settings.careTeam.inviteError"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setEmail("");
|
|
||||||
setNotice(t("settings.careTeam.inviteSent", { email: email.trim() }));
|
|
||||||
void load();
|
|
||||||
};
|
|
||||||
|
|
||||||
const removeMember = async (memberId: string) => {
|
const removeMember = async (memberId: string) => {
|
||||||
await authClient.organization.removeMember({ memberIdOrEmail: memberId });
|
await authClient.organization.removeMember({ memberIdOrEmail: memberId });
|
||||||
void load();
|
void load();
|
||||||
};
|
};
|
||||||
|
|
||||||
const cancelInvite = async (invitationId: string) => {
|
|
||||||
await authClient.organization.cancelInvitation({ invitationId });
|
|
||||||
void load();
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SettingsSection
|
<SettingsSection
|
||||||
description={t("settings.careTeam.description")}
|
description={t("settings.careTeam.description")}
|
||||||
@@ -126,46 +90,14 @@ export function CareTeamPanel() {
|
|||||||
{error}
|
{error}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
{notice && (
|
|
||||||
<p className="rounded-2xl bg-primary/10 px-3 py-2 text-sm text-primary">
|
|
||||||
{notice}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{canManage && (
|
{canManage && (
|
||||||
<SettingsCard className="p-4">
|
<div className="flex justify-end">
|
||||||
<form
|
<Button onClick={() => setAdding(true)} type="button">
|
||||||
className="flex flex-col gap-2 sm:flex-row sm:items-center"
|
<UserPlus className="size-4" />
|
||||||
onSubmit={invite}
|
{t("settings.careTeam.addMember")}
|
||||||
>
|
</Button>
|
||||||
<Input
|
</div>
|
||||||
className="flex-1"
|
|
||||||
onChange={(e) => setEmail(e.target.value)}
|
|
||||||
placeholder={t("settings.careTeam.invitePlaceholder")}
|
|
||||||
required
|
|
||||||
type="email"
|
|
||||||
value={email}
|
|
||||||
/>
|
|
||||||
<select
|
|
||||||
className="h-9 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"
|
|
||||||
onChange={(e) =>
|
|
||||||
setRole(e.target.value as (typeof INVITE_ROLES)[number])
|
|
||||||
}
|
|
||||||
value={role}
|
|
||||||
>
|
|
||||||
{INVITE_ROLES.map((r) => (
|
|
||||||
<option key={r} value={r}>
|
|
||||||
{roleLabel(r)}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
<Button disabled={inviting} type="submit">
|
|
||||||
{inviting
|
|
||||||
? t("settings.careTeam.inviting")
|
|
||||||
: t("settings.careTeam.invite")}
|
|
||||||
</Button>
|
|
||||||
</form>
|
|
||||||
</SettingsCard>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<SettingsCard className="divide-y divide-border">
|
<SettingsCard className="divide-y divide-border">
|
||||||
@@ -176,25 +108,28 @@ export function CareTeamPanel() {
|
|||||||
) : (
|
) : (
|
||||||
members.map((m) => {
|
members.map((m) => {
|
||||||
const isSelf = m.userId === session?.user?.id;
|
const isSelf = m.userId === session?.user?.id;
|
||||||
|
// Prefer the login username; fall back to email for owners who
|
||||||
|
// signed up by email.
|
||||||
|
const secondary = m.username ? `@${m.username}` : m.email;
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center gap-3 px-4 py-3" key={m.id}>
|
<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.user?.name, m.user?.email)}
|
{initials(m.name, m.email)}
|
||||||
</AvatarFallback>
|
</AvatarFallback>
|
||||||
</Avatar>
|
</Avatar>
|
||||||
<div className="min-w-0 flex-1">
|
<div className="min-w-0 flex-1">
|
||||||
<p className="truncate text-sm font-medium">
|
<p className="truncate text-sm font-medium">
|
||||||
{m.user?.name || m.user?.email || m.userId}
|
{m.name || m.email || m.userId}
|
||||||
{isSelf && (
|
{isSelf && (
|
||||||
<span className="ml-1 text-xs text-muted-foreground">
|
<span className="ml-1 text-xs text-muted-foreground">
|
||||||
{t("settings.careTeam.you")}
|
{t("settings.careTeam.you")}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</p>
|
</p>
|
||||||
{m.user?.email && (
|
{secondary && (
|
||||||
<p className="truncate text-xs text-muted-foreground">
|
<p className="truncate text-xs text-muted-foreground">
|
||||||
{m.user.email}
|
{secondary}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -218,33 +153,12 @@ export function CareTeamPanel() {
|
|||||||
)}
|
)}
|
||||||
</SettingsCard>
|
</SettingsCard>
|
||||||
|
|
||||||
{invites.length > 0 && (
|
{canManage && (
|
||||||
<SettingsCard className="divide-y divide-border">
|
<AddStaffDialog
|
||||||
<p className="px-4 py-2.5 text-xs font-medium tracking-wide text-muted-foreground uppercase">
|
onCreated={() => void load()}
|
||||||
{t("settings.careTeam.pendingInvitations")}
|
onOpenChange={setAdding}
|
||||||
</p>
|
open={adding}
|
||||||
{invites.map((inv) => (
|
/>
|
||||||
<div className="flex items-center gap-3 px-4 py-3" key={inv.id}>
|
|
||||||
<div className="min-w-0 flex-1">
|
|
||||||
<p className="truncate text-sm">{inv.email}</p>
|
|
||||||
</div>
|
|
||||||
<Badge className="capitalize" variant="outline">
|
|
||||||
{roleLabel(inv.role)}
|
|
||||||
</Badge>
|
|
||||||
{canManage && (
|
|
||||||
<Button
|
|
||||||
aria-label={t("settings.careTeam.cancelInvitation")}
|
|
||||||
onClick={() => cancelInvite(inv.id)}
|
|
||||||
size="icon-sm"
|
|
||||||
type="button"
|
|
||||||
variant="ghost"
|
|
||||||
>
|
|
||||||
<X className="size-4" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</SettingsCard>
|
|
||||||
)}
|
)}
|
||||||
</SettingsSection>
|
</SettingsSection>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import {
|
|||||||
import { SigningPanel } from "@/components/settings/settings-billing";
|
import { SigningPanel } from "@/components/settings/settings-billing";
|
||||||
import { CareTeamPanel } from "@/components/settings/settings-care-team";
|
import { CareTeamPanel } from "@/components/settings/settings-care-team";
|
||||||
import { ProfilePanel } from "@/components/settings/settings-preferences";
|
import { ProfilePanel } from "@/components/settings/settings-preferences";
|
||||||
|
import { useActiveRole } from "@/lib/roles";
|
||||||
|
|
||||||
const TABS = [
|
const TABS = [
|
||||||
{ id: "profile", labelKey: "settings.tabs.profile" },
|
{ id: "profile", labelKey: "settings.tabs.profile" },
|
||||||
@@ -41,20 +42,27 @@ function PlaceholderPanel({
|
|||||||
|
|
||||||
export function SettingsView() {
|
export function SettingsView() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const role = useActiveRole();
|
||||||
const [tab, setTab] = useState<Tab>("profile");
|
const [tab, setTab] = useState<Tab>("profile");
|
||||||
|
|
||||||
|
// Only clinic owners/admins manage clinic-wide settings (care team, records,
|
||||||
|
// signing, developers). Everyone else gets their own profile only.
|
||||||
|
const isAdmin = role === "owner" || role === "admin";
|
||||||
|
const visibleTabs = isAdmin ? TABS : TABS.filter((item) => item.id === "profile");
|
||||||
|
const activeTab = visibleTabs.some((item) => item.id === tab) ? tab : "profile";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto w-full max-w-3xl px-6 py-10">
|
<div className="mx-auto w-full max-w-3xl px-6 py-10">
|
||||||
<div className="flex flex-col gap-5 sm:flex-row sm:items-center sm:justify-between">
|
<div className="flex flex-col gap-5 sm:flex-row sm:items-center sm:justify-between">
|
||||||
<h1 className="text-2xl font-semibold tracking-tight">
|
<h1 className="text-2xl font-semibold tracking-tight">
|
||||||
{t(`settings.tabs.${tab}`)}
|
{t(`settings.tabs.${activeTab}`)}
|
||||||
</h1>
|
</h1>
|
||||||
<nav className="flex flex-wrap items-center gap-1">
|
<nav className="flex flex-wrap items-center gap-1">
|
||||||
{TABS.map((item) => (
|
{visibleTabs.map((item) => (
|
||||||
<button
|
<button
|
||||||
className={cn(
|
className={cn(
|
||||||
"rounded-lg px-3 py-1.5 text-sm transition-colors",
|
"rounded-lg px-3 py-1.5 text-sm transition-colors",
|
||||||
tab === item.id
|
activeTab === item.id
|
||||||
? "bg-muted text-foreground"
|
? "bg-muted text-foreground"
|
||||||
: "text-muted-foreground hover:text-foreground"
|
: "text-muted-foreground hover:text-foreground"
|
||||||
)}
|
)}
|
||||||
@@ -69,16 +77,16 @@ export function SettingsView() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mt-10 space-y-12">
|
<div className="mt-10 space-y-12">
|
||||||
{tab === "profile" && <ProfilePanel />}
|
{activeTab === "profile" && <ProfilePanel />}
|
||||||
{tab === "records" && (
|
{activeTab === "records" && (
|
||||||
<PlaceholderPanel
|
<PlaceholderPanel
|
||||||
description={t("settings.records.description")}
|
description={t("settings.records.description")}
|
||||||
title={t("settings.tabs.records")}
|
title={t("settings.tabs.records")}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{tab === "signing" && <SigningPanel />}
|
{activeTab === "signing" && <SigningPanel />}
|
||||||
{tab === "careTeam" && <CareTeamPanel />}
|
{activeTab === "careTeam" && <CareTeamPanel />}
|
||||||
{tab === "developers" && (
|
{activeTab === "developers" && (
|
||||||
<PlaceholderPanel
|
<PlaceholderPanel
|
||||||
description={t("settings.developers.description")}
|
description={t("settings.developers.description")}
|
||||||
title={t("settings.tabs.developers")}
|
title={t("settings.tabs.developers")}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ import {
|
|||||||
TooltipTrigger,
|
TooltipTrigger,
|
||||||
} from "@/components/ui/tooltip";
|
} from "@/components/ui/tooltip";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
import { navItems } from "@/lib/nav";
|
import { useActiveRole, visibleNavItems } from "@/lib/roles";
|
||||||
import { motion } from "framer-motion";
|
import { motion } from "framer-motion";
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
@@ -26,9 +26,11 @@ import { NavUser } from "@/components/sidebar-02/nav-user";
|
|||||||
export function DashboardSidebar() {
|
export function DashboardSidebar() {
|
||||||
const { state } = useSidebar();
|
const { state } = useSidebar();
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const role = useActiveRole();
|
||||||
const isCollapsed = state === "collapsed";
|
const isCollapsed = state === "collapsed";
|
||||||
|
|
||||||
const dashboardRoutes: Route[] = navItems.map((item) => ({
|
// Hide clinical nav from non-clinical roles (e.g. reception). See lib/roles.ts.
|
||||||
|
const dashboardRoutes: Route[] = visibleNavItems(role).map((item) => ({
|
||||||
id: item.id,
|
id: item.id,
|
||||||
title: t(item.labelKey),
|
title: t(item.labelKey),
|
||||||
icon: <item.icon className="size-4" />,
|
icon: <item.icon className="size-4" />,
|
||||||
|
|||||||
+21
-1
@@ -42,6 +42,24 @@ export const member = ac.newRole({
|
|||||||
task: ["read", "write", "delete"],
|
task: ["read", "write", "delete"],
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// doctor (clinician): mirrors backend/src/lib/access.ts — same clinical access
|
||||||
|
// as `member`.
|
||||||
|
export const doctor = ac.newRole({
|
||||||
|
...memberAc.statements,
|
||||||
|
patient: ["read", "write"],
|
||||||
|
appointment: ["read", "write", "delete"],
|
||||||
|
prescription: ["read", "write", "delete"],
|
||||||
|
task: ["read", "write", "delete"],
|
||||||
|
});
|
||||||
|
|
||||||
|
// reception (front desk): scheduling + registration only, no clinical records.
|
||||||
|
export const reception = ac.newRole({
|
||||||
|
...memberAc.statements,
|
||||||
|
patient: ["read", "write"],
|
||||||
|
appointment: ["read", "write", "delete"],
|
||||||
|
task: ["read", "write"],
|
||||||
|
});
|
||||||
|
|
||||||
export const viewer = ac.newRole({
|
export const viewer = ac.newRole({
|
||||||
patient: ["read"],
|
patient: ["read"],
|
||||||
appointment: ["read"],
|
appointment: ["read"],
|
||||||
@@ -49,12 +67,14 @@ export const viewer = ac.newRole({
|
|||||||
task: ["read"],
|
task: ["read"],
|
||||||
});
|
});
|
||||||
|
|
||||||
export const roles = { owner, admin, member, viewer };
|
export const roles = { owner, admin, doctor, reception, member, viewer };
|
||||||
|
|
||||||
// Human-readable labels for the role keys used in the UI.
|
// Human-readable labels for the role keys used in the UI.
|
||||||
export const ROLE_LABELS: Record<keyof typeof roles, string> = {
|
export const ROLE_LABELS: Record<keyof typeof roles, string> = {
|
||||||
owner: "Owner",
|
owner: "Owner",
|
||||||
admin: "Admin",
|
admin: "Admin",
|
||||||
|
doctor: "Doctor",
|
||||||
|
reception: "Reception",
|
||||||
member: "Clinician",
|
member: "Clinician",
|
||||||
viewer: "Viewer",
|
viewer: "Viewer",
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
import { organizationClient } from "better-auth/client/plugins";
|
import {
|
||||||
|
organizationClient,
|
||||||
|
usernameClient,
|
||||||
|
} from "better-auth/client/plugins";
|
||||||
import { createAuthClient } from "better-auth/react";
|
import { createAuthClient } from "better-auth/react";
|
||||||
|
|
||||||
import { ac, roles } from "@/lib/access";
|
import { ac, roles } from "@/lib/access";
|
||||||
@@ -8,7 +11,9 @@ import { ac, roles } from "@/lib/access";
|
|||||||
// cookie set by the backend is included on every request.
|
// cookie set by the backend is included on every request.
|
||||||
export const authClient = createAuthClient({
|
export const authClient = createAuthClient({
|
||||||
baseURL: process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:4000",
|
baseURL: process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:4000",
|
||||||
plugins: [organizationClient({ ac, roles })],
|
// usernameClient enables signIn.username(...) so admin-provisioned staff can
|
||||||
|
// log in with a username; organizationClient powers clinics + RBAC.
|
||||||
|
plugins: [usernameClient(), organizationClient({ ac, roles })],
|
||||||
});
|
});
|
||||||
|
|
||||||
export const {
|
export const {
|
||||||
|
|||||||
@@ -11,8 +11,12 @@
|
|||||||
"login": {
|
"login": {
|
||||||
"title": "Welcome back",
|
"title": "Welcome back",
|
||||||
"subtitle": "Sign in to your clinician account",
|
"subtitle": "Sign in to your clinician account",
|
||||||
|
"tabEmail": "Email",
|
||||||
|
"tabUsername": "Username",
|
||||||
"emailLabel": "Email",
|
"emailLabel": "Email",
|
||||||
"emailPlaceholder": "you@clinic.org",
|
"emailPlaceholder": "you@clinic.org",
|
||||||
|
"usernameLabel": "Username",
|
||||||
|
"usernamePlaceholder": "jdoe",
|
||||||
"passwordLabel": "Password",
|
"passwordLabel": "Password",
|
||||||
"forgotPassword": "Forgot your password?",
|
"forgotPassword": "Forgot your password?",
|
||||||
"submit": "Sign in",
|
"submit": "Sign in",
|
||||||
@@ -695,18 +699,36 @@
|
|||||||
},
|
},
|
||||||
"careTeam": {
|
"careTeam": {
|
||||||
"title": "Care team",
|
"title": "Care team",
|
||||||
"description": "Clinicians with access to this clinic",
|
"description": "Staff with access to this clinic",
|
||||||
"loadError": "Could not load the care team.",
|
"loadError": "Could not load the care team.",
|
||||||
"invitePlaceholder": "colleague@clinic.org",
|
|
||||||
"inviting": "Sending…",
|
|
||||||
"invite": "Invite",
|
|
||||||
"inviteError": "Could not send the invitation.",
|
|
||||||
"inviteSent": "Invitation sent to {{email}}.",
|
|
||||||
"loading": "Loading care team…",
|
"loading": "Loading care team…",
|
||||||
"you": "(you)",
|
"you": "(you)",
|
||||||
"pendingInvitations": "Pending invitations",
|
"addMember": "Add team member",
|
||||||
"removeMember": "Remove member",
|
"removeMember": "Remove member",
|
||||||
"cancelInvitation": "Cancel invitation"
|
"add": {
|
||||||
|
"title": "Add team member",
|
||||||
|
"step1Description": "Who are you adding, and what can they do?",
|
||||||
|
"step2Description": "Set the username and password they'll sign in with.",
|
||||||
|
"nameLabel": "Full name",
|
||||||
|
"namePlaceholder": "Jane Okafor",
|
||||||
|
"nameRequired": "Enter the person's name.",
|
||||||
|
"roleLabel": "Role",
|
||||||
|
"usernameLabel": "Username",
|
||||||
|
"usernamePlaceholder": "jokafor",
|
||||||
|
"usernameTooShort": "Username must be at least {{count}} characters.",
|
||||||
|
"passwordLabel": "Password",
|
||||||
|
"passwordHint": "Must be at least {{count}} characters long.",
|
||||||
|
"passwordTooShort": "Password must be at least {{count}} characters.",
|
||||||
|
"back": "Back",
|
||||||
|
"cancel": "Cancel",
|
||||||
|
"next": "Next",
|
||||||
|
"create": "Create account",
|
||||||
|
"creating": "Creating…",
|
||||||
|
"createdTitle": "Account created",
|
||||||
|
"createdBody": "{{name}} can now sign in with the username {{username}}.",
|
||||||
|
"error": "Could not create the account.",
|
||||||
|
"errorTitle": "Could not add member"
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"signing": {
|
"signing": {
|
||||||
"keyTitle": "Signing key",
|
"keyTitle": "Signing key",
|
||||||
|
|||||||
+27
-3
@@ -18,6 +18,8 @@ export type NavSubItem = {
|
|||||||
labelKey: string;
|
labelKey: string;
|
||||||
icon?: LucideIcon;
|
icon?: LucideIcon;
|
||||||
link: string;
|
link: string;
|
||||||
|
// Hidden from non-clinical roles (e.g. reception). See lib/roles.ts.
|
||||||
|
requiresClinical?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type NavItem = {
|
export type NavItem = {
|
||||||
@@ -28,13 +30,21 @@ export type NavItem = {
|
|||||||
link: string;
|
link: string;
|
||||||
// Optional sub-pages revealed under this item in the sidebar.
|
// Optional sub-pages revealed under this item in the sidebar.
|
||||||
subs?: NavSubItem[];
|
subs?: NavSubItem[];
|
||||||
|
// Hidden from non-clinical roles (e.g. reception). See lib/roles.ts.
|
||||||
|
requiresClinical?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Single source of truth for the primary navigation. Consumed by the sidebar
|
// Single source of truth for the primary navigation. Consumed by the sidebar
|
||||||
// (components/sidebar-02/app-sidebar.tsx) and the command palette
|
// (components/sidebar-02/app-sidebar.tsx) and the command palette
|
||||||
// (components/command-palette.tsx) so the two never drift.
|
// (components/command-palette.tsx) so the two never drift.
|
||||||
export const navItems: NavItem[] = [
|
export const navItems: NavItem[] = [
|
||||||
{ id: "new-chat", labelKey: "nav.newChat", icon: Plus, link: "/" },
|
{
|
||||||
|
id: "new-chat",
|
||||||
|
labelKey: "nav.newChat",
|
||||||
|
icon: Plus,
|
||||||
|
link: "/",
|
||||||
|
requiresClinical: true,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
id: "patients",
|
id: "patients",
|
||||||
labelKey: "nav.patients",
|
labelKey: "nav.patients",
|
||||||
@@ -53,6 +63,7 @@ export const navItems: NavItem[] = [
|
|||||||
labelKey: "nav.prescriptions",
|
labelKey: "nav.prescriptions",
|
||||||
icon: Pill,
|
icon: Pill,
|
||||||
link: "/prescriptions",
|
link: "/prescriptions",
|
||||||
|
requiresClinical: true,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
@@ -61,10 +72,23 @@ export const navItems: NavItem[] = [
|
|||||||
labelKey: "nav.analysis",
|
labelKey: "nav.analysis",
|
||||||
icon: BarChart3,
|
icon: BarChart3,
|
||||||
link: "/analysis",
|
link: "/analysis",
|
||||||
|
requiresClinical: true,
|
||||||
},
|
},
|
||||||
{ id: "messages", labelKey: "nav.messages", icon: Mail, link: "/messages" },
|
{ id: "messages", labelKey: "nav.messages", icon: Mail, link: "/messages" },
|
||||||
{ id: "notes", labelKey: "nav.notes", icon: NotebookPen, link: "/notes" },
|
{
|
||||||
|
id: "notes",
|
||||||
|
labelKey: "nav.notes",
|
||||||
|
icon: NotebookPen,
|
||||||
|
link: "/notes",
|
||||||
|
requiresClinical: true,
|
||||||
|
},
|
||||||
{ id: "tasks", labelKey: "nav.tasks", icon: ListTodo, link: "/tasks" },
|
{ id: "tasks", labelKey: "nav.tasks", icon: ListTodo, link: "/tasks" },
|
||||||
{ id: "activity", labelKey: "nav.activity", icon: History, link: "/activity" },
|
{
|
||||||
|
id: "activity",
|
||||||
|
labelKey: "nav.activity",
|
||||||
|
icon: History,
|
||||||
|
link: "/activity",
|
||||||
|
requiresClinical: true,
|
||||||
|
},
|
||||||
{ id: "settings", labelKey: "nav.settings", icon: Settings, link: "/settings" },
|
{ id: "settings", labelKey: "nav.settings", icon: Settings, link: "/settings" },
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -0,0 +1,102 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
|
||||||
|
import { type roles } from "@/lib/access";
|
||||||
|
import { authClient } from "@/lib/auth-client";
|
||||||
|
import { type NavItem, navItems } from "@/lib/nav";
|
||||||
|
|
||||||
|
export type RoleKey = keyof typeof roles;
|
||||||
|
|
||||||
|
// Roles an admin can assign when provisioning staff (owner is excluded — the
|
||||||
|
// clinic creator is the sole owner). Mirrors the backend's PROVISIONABLE_ROLES.
|
||||||
|
export const PROVISIONABLE_ROLES: RoleKey[] = [
|
||||||
|
"admin",
|
||||||
|
"doctor",
|
||||||
|
"reception",
|
||||||
|
"viewer",
|
||||||
|
];
|
||||||
|
|
||||||
|
// The current user's role in the active clinic (null while loading or if they
|
||||||
|
// aren't a member). Re-fetches when the active organization changes.
|
||||||
|
export function useActiveRole(): string | null {
|
||||||
|
const { data: activeOrg } = authClient.useActiveOrganization();
|
||||||
|
const [role, setRole] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let cancelled = false;
|
||||||
|
authClient.organization
|
||||||
|
.getActiveMember()
|
||||||
|
.then(({ data }) => {
|
||||||
|
if (!cancelled) setRole(data?.role ?? null);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
if (!cancelled) setRole(null);
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, [activeOrg?.id]);
|
||||||
|
|
||||||
|
return role;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Whether a role may see clinical records (AI lookup, prescriptions, notes,
|
||||||
|
// 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
|
||||||
|
// is false for them and true for every clinical role.
|
||||||
|
export function hasClinicalAccess(role: string | null | undefined): boolean {
|
||||||
|
if (!role) return false;
|
||||||
|
try {
|
||||||
|
return authClient.organization.checkRolePermission({
|
||||||
|
role: role as RoleKey,
|
||||||
|
permissions: { prescription: ["read"] },
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Where a role lands after sign-in. Reception has no AI chat, so they start on
|
||||||
|
// the appointments board; clinical roles start on the chat home.
|
||||||
|
export function defaultLandingFor(role: string | null | undefined): string {
|
||||||
|
return hasClinicalAccess(role) ? "/" : "/appointments";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clinical-only routes — a non-clinical role (reception) is redirected away.
|
||||||
|
// Keyed by path; "/" matches exactly, others match themselves + nested paths.
|
||||||
|
const CLINICAL_ROUTES = [
|
||||||
|
"/",
|
||||||
|
"/prescriptions",
|
||||||
|
"/analysis",
|
||||||
|
"/notes",
|
||||||
|
"/activity",
|
||||||
|
];
|
||||||
|
|
||||||
|
// Whether `path` is reachable by `role`. Returns true while the role is still
|
||||||
|
// loading to avoid redirect flicker; the authoritative check is the backend's
|
||||||
|
// per-route RBAC (which returns 403 regardless).
|
||||||
|
export function canAccessRoute(
|
||||||
|
path: string,
|
||||||
|
role: string | null | undefined,
|
||||||
|
): boolean {
|
||||||
|
if (role == null) return true;
|
||||||
|
if (hasClinicalAccess(role)) return true;
|
||||||
|
return !CLINICAL_ROUTES.some((r) =>
|
||||||
|
r === "/" ? path === "/" : path === r || path.startsWith(`${r}/`),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Nav items visible to a role, with clinical-only items (and sub-items) removed
|
||||||
|
// for non-clinical roles. While the role is loading we optimistically show
|
||||||
|
// everything (clinical users are the common case) — the flash is sub-second.
|
||||||
|
export function visibleNavItems(role: string | null | undefined): NavItem[] {
|
||||||
|
if (role == null) return navItems;
|
||||||
|
const clinical = hasClinicalAccess(role);
|
||||||
|
return navItems
|
||||||
|
.filter((item) => !item.requiresClinical || clinical)
|
||||||
|
.map((item) => ({
|
||||||
|
...item,
|
||||||
|
subs: item.subs?.filter((sub) => !sub.requiresClinical || clinical),
|
||||||
|
}));
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user