mirror of
https://github.com/temetro/temetro.git
synced 2026-08-19 14:46:29 +00:00
feat: org-scoped prescriptions backend, wire prescriptions page
Add the prescriptions table, validation, service and CRUD routes (/api/prescriptions, RBAC-gated; prescriber defaults to the signed-in clinician, prescribedAt to today) and the frontend data module. The page now loads/persists real data and computes its status KPIs. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,22 @@
|
|||||||
|
CREATE TABLE "prescriptions" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"organization_id" text NOT NULL,
|
||||||
|
"patient_file_number" text DEFAULT '' NOT NULL,
|
||||||
|
"patient_name" text NOT NULL,
|
||||||
|
"patient_initials" text NOT NULL,
|
||||||
|
"medication" text NOT NULL,
|
||||||
|
"dose" text DEFAULT '' NOT NULL,
|
||||||
|
"frequency" text NOT NULL,
|
||||||
|
"prescriber" text NOT NULL,
|
||||||
|
"prescribed_at" date DEFAULT now() NOT NULL,
|
||||||
|
"status" text NOT NULL,
|
||||||
|
"duration" text,
|
||||||
|
"notes" text,
|
||||||
|
"created_by" text,
|
||||||
|
"created_at" timestamp DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
ALTER TABLE "prescriptions" ADD CONSTRAINT "prescriptions_organization_id_organization_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organization"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "prescriptions" ADD CONSTRAINT "prescriptions_created_by_user_id_fk" FOREIGN KEY ("created_by") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||||
|
CREATE INDEX "prescriptions_org_idx" ON "prescriptions" USING btree ("organization_id");
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -22,6 +22,13 @@
|
|||||||
"when": 1780849813505,
|
"when": 1780849813505,
|
||||||
"tag": "0002_fluffy_longshot",
|
"tag": "0002_fluffy_longshot",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 3,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1780850147682,
|
||||||
|
"tag": "0003_lame_rawhide_kid",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -2,3 +2,4 @@ export * from "./auth.js";
|
|||||||
export * from "./patients.js";
|
export * from "./patients.js";
|
||||||
export * from "./notes.js";
|
export * from "./notes.js";
|
||||||
export * from "./appointments.js";
|
export * from "./appointments.js";
|
||||||
|
export * from "./prescriptions.js";
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import {
|
||||||
|
date,
|
||||||
|
index,
|
||||||
|
pgTable,
|
||||||
|
text,
|
||||||
|
timestamp,
|
||||||
|
uuid,
|
||||||
|
} from "drizzle-orm/pg-core";
|
||||||
|
|
||||||
|
import type { PrescriptionStatus } from "../../types/prescription.js";
|
||||||
|
import { organization, user } from "./auth.js";
|
||||||
|
|
||||||
|
// One row per prescribed medication, scoped to a clinic (organization). Patient
|
||||||
|
// identity is denormalized (name/initials/file number) so the ledger renders
|
||||||
|
// without joining. `prescribedAt` defaults to today.
|
||||||
|
export const prescriptions = pgTable(
|
||||||
|
"prescriptions",
|
||||||
|
{
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
organizationId: text("organization_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => organization.id, { onDelete: "cascade" }),
|
||||||
|
patientFileNumber: text("patient_file_number").notNull().default(""),
|
||||||
|
patientName: text("patient_name").notNull(),
|
||||||
|
patientInitials: text("patient_initials").notNull(),
|
||||||
|
medication: text("medication").notNull(),
|
||||||
|
dose: text("dose").notNull().default(""),
|
||||||
|
frequency: text("frequency").notNull(),
|
||||||
|
prescriber: text("prescriber").notNull(),
|
||||||
|
prescribedAt: date("prescribed_at").defaultNow().notNull(),
|
||||||
|
status: text("status").$type<PrescriptionStatus>().notNull(),
|
||||||
|
duration: text("duration"),
|
||||||
|
notes: text("notes"),
|
||||||
|
createdBy: text("created_by").references(() => user.id, {
|
||||||
|
onDelete: "set null",
|
||||||
|
}),
|
||||||
|
createdAt: timestamp("created_at").defaultNow().notNull(),
|
||||||
|
updatedAt: timestamp("updated_at")
|
||||||
|
.defaultNow()
|
||||||
|
.$onUpdate(() => new Date())
|
||||||
|
.notNull(),
|
||||||
|
},
|
||||||
|
(t) => [index("prescriptions_org_idx").on(t.organizationId)],
|
||||||
|
);
|
||||||
@@ -8,6 +8,7 @@ import { errorHandler, notFound } from "./middleware/error.js";
|
|||||||
import { appointmentsRouter } from "./routes/appointments.js";
|
import { appointmentsRouter } from "./routes/appointments.js";
|
||||||
import { notesRouter } from "./routes/notes.js";
|
import { notesRouter } from "./routes/notes.js";
|
||||||
import { patientsRouter } from "./routes/patients.js";
|
import { patientsRouter } from "./routes/patients.js";
|
||||||
|
import { prescriptionsRouter } from "./routes/prescriptions.js";
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
|
|
||||||
@@ -47,6 +48,7 @@ app.get("/health", (_req, res) => {
|
|||||||
app.use("/api/patients", patientsRouter);
|
app.use("/api/patients", patientsRouter);
|
||||||
app.use("/api/notes", notesRouter);
|
app.use("/api/notes", notesRouter);
|
||||||
app.use("/api/appointments", appointmentsRouter);
|
app.use("/api/appointments", appointmentsRouter);
|
||||||
|
app.use("/api/prescriptions", prescriptionsRouter);
|
||||||
|
|
||||||
app.use(notFound);
|
app.use(notFound);
|
||||||
app.use(errorHandler);
|
app.use(errorHandler);
|
||||||
@@ -57,4 +59,5 @@ app.listen(env.PORT, () => {
|
|||||||
console.log(` • patients: /api/patients`);
|
console.log(` • patients: /api/patients`);
|
||||||
console.log(` • notes: /api/notes`);
|
console.log(` • notes: /api/notes`);
|
||||||
console.log(` • appts: /api/appointments`);
|
console.log(` • appts: /api/appointments`);
|
||||||
|
console.log(` • rx: /api/prescriptions`);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
const nonEmpty = z.string().trim().min(1);
|
||||||
|
|
||||||
|
// Payload accepted by POST/PUT /api/prescriptions. The frontend dialog omits
|
||||||
|
// prescriber / prescribedAt / status on create — the route fills the prescriber
|
||||||
|
// from the signed-in user, the DB defaults prescribedAt to today, and status
|
||||||
|
// defaults to "active".
|
||||||
|
export const prescriptionInputSchema = z.object({
|
||||||
|
fileNumber: z.string().trim().default(""),
|
||||||
|
name: nonEmpty.max(200),
|
||||||
|
initials: z.string().trim().min(1).max(4),
|
||||||
|
medication: nonEmpty.max(200),
|
||||||
|
dose: z.string().trim().max(120).default(""),
|
||||||
|
frequency: nonEmpty.max(120),
|
||||||
|
prescriber: z.string().trim().max(200).default(""),
|
||||||
|
prescribedAt: z
|
||||||
|
.string()
|
||||||
|
.regex(/^\d{4}-\d{2}-\d{2}$/, "Date must be YYYY-MM-DD.")
|
||||||
|
.optional(),
|
||||||
|
status: z.enum(["active", "completed", "expired"]).default("active"),
|
||||||
|
duration: z.string().trim().max(120).nullish(),
|
||||||
|
notes: z.string().max(5000).nullish(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type PrescriptionInput = z.infer<typeof prescriptionInputSchema>;
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import { Router } from "express";
|
||||||
|
|
||||||
|
import { HttpError } from "../lib/http-error.js";
|
||||||
|
import { prescriptionInputSchema } from "../lib/prescription-validation.js";
|
||||||
|
import {
|
||||||
|
requireAuth,
|
||||||
|
requireOrg,
|
||||||
|
requirePermission,
|
||||||
|
} from "../middleware/auth.js";
|
||||||
|
import * as service from "../services/prescriptions.js";
|
||||||
|
|
||||||
|
export const prescriptionsRouter = Router();
|
||||||
|
|
||||||
|
prescriptionsRouter.use(requireAuth, requireOrg);
|
||||||
|
|
||||||
|
prescriptionsRouter.get(
|
||||||
|
"/",
|
||||||
|
requirePermission({ prescription: ["read"] }),
|
||||||
|
async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
res.json(await service.listPrescriptions(req.organizationId!));
|
||||||
|
} catch (err) {
|
||||||
|
next(err);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
prescriptionsRouter.post(
|
||||||
|
"/",
|
||||||
|
requirePermission({ prescription: ["write"] }),
|
||||||
|
async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const input = prescriptionInputSchema.parse(req.body);
|
||||||
|
// Default the prescriber to the signed-in clinician when not provided.
|
||||||
|
input.prescriber = input.prescriber || req.user!.name || "Clinician";
|
||||||
|
const created = await service.createPrescription(
|
||||||
|
req.organizationId!,
|
||||||
|
req.user!.id,
|
||||||
|
input,
|
||||||
|
);
|
||||||
|
res.status(201).json(created);
|
||||||
|
} catch (err) {
|
||||||
|
next(err);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
prescriptionsRouter.put(
|
||||||
|
"/:id",
|
||||||
|
requirePermission({ prescription: ["write"] }),
|
||||||
|
async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const input = prescriptionInputSchema.parse(req.body);
|
||||||
|
input.prescriber = input.prescriber || req.user!.name || "Clinician";
|
||||||
|
const updated = await service.updatePrescription(
|
||||||
|
req.organizationId!,
|
||||||
|
req.params.id as string,
|
||||||
|
input,
|
||||||
|
);
|
||||||
|
if (!updated) throw new HttpError(404, "Prescription not found.");
|
||||||
|
res.json(updated);
|
||||||
|
} catch (err) {
|
||||||
|
next(err);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
prescriptionsRouter.delete(
|
||||||
|
"/:id",
|
||||||
|
requirePermission({ prescription: ["delete"] }),
|
||||||
|
async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const ok = await service.deletePrescription(
|
||||||
|
req.organizationId!,
|
||||||
|
req.params.id as string,
|
||||||
|
);
|
||||||
|
if (!ok) throw new HttpError(404, "Prescription not found.");
|
||||||
|
res.status(204).end();
|
||||||
|
} catch (err) {
|
||||||
|
next(err);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import { and, desc, eq } from "drizzle-orm";
|
||||||
|
|
||||||
|
import { db } from "../db/index.js";
|
||||||
|
import { prescriptions } from "../db/schema/prescriptions.js";
|
||||||
|
import type { PrescriptionInput } from "../lib/prescription-validation.js";
|
||||||
|
import type { Prescription } from "../types/prescription.js";
|
||||||
|
|
||||||
|
type PrescriptionRow = typeof prescriptions.$inferSelect;
|
||||||
|
|
||||||
|
// Postgres throws on a malformed uuid; treat non-uuid ids as "not found".
|
||||||
|
const UUID_RE =
|
||||||
|
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||||
|
|
||||||
|
function toPrescription(row: PrescriptionRow): Prescription {
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
fileNumber: row.patientFileNumber,
|
||||||
|
name: row.patientName,
|
||||||
|
initials: row.patientInitials,
|
||||||
|
medication: row.medication,
|
||||||
|
dose: row.dose,
|
||||||
|
frequency: row.frequency,
|
||||||
|
prescriber: row.prescriber,
|
||||||
|
prescribedAt: row.prescribedAt,
|
||||||
|
status: row.status,
|
||||||
|
duration: row.duration,
|
||||||
|
notes: row.notes,
|
||||||
|
createdAt: row.createdAt.toISOString(),
|
||||||
|
updatedAt: row.updatedAt.toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function columns(orgId: string, input: PrescriptionInput, createdBy?: string) {
|
||||||
|
return {
|
||||||
|
organizationId: orgId,
|
||||||
|
patientFileNumber: input.fileNumber,
|
||||||
|
patientName: input.name,
|
||||||
|
patientInitials: input.initials,
|
||||||
|
medication: input.medication,
|
||||||
|
dose: input.dose,
|
||||||
|
frequency: input.frequency,
|
||||||
|
prescriber: input.prescriber,
|
||||||
|
status: input.status,
|
||||||
|
duration: input.duration ?? null,
|
||||||
|
notes: input.notes ?? null,
|
||||||
|
// Only set prescribedAt when supplied; otherwise the column default (today).
|
||||||
|
...(input.prescribedAt ? { prescribedAt: input.prescribedAt } : {}),
|
||||||
|
...(createdBy ? { createdBy } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listPrescriptions(
|
||||||
|
orgId: string,
|
||||||
|
): Promise<Prescription[]> {
|
||||||
|
const rows = await db
|
||||||
|
.select()
|
||||||
|
.from(prescriptions)
|
||||||
|
.where(eq(prescriptions.organizationId, orgId))
|
||||||
|
.orderBy(desc(prescriptions.prescribedAt), desc(prescriptions.createdAt));
|
||||||
|
return rows.map(toPrescription);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createPrescription(
|
||||||
|
orgId: string,
|
||||||
|
userId: string,
|
||||||
|
input: PrescriptionInput,
|
||||||
|
): Promise<Prescription> {
|
||||||
|
const [row] = await db
|
||||||
|
.insert(prescriptions)
|
||||||
|
.values(columns(orgId, input, userId))
|
||||||
|
.returning();
|
||||||
|
return toPrescription(row!);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updatePrescription(
|
||||||
|
orgId: string,
|
||||||
|
id: string,
|
||||||
|
input: PrescriptionInput,
|
||||||
|
): Promise<Prescription | null> {
|
||||||
|
if (!UUID_RE.test(id)) return null;
|
||||||
|
const [row] = await db
|
||||||
|
.update(prescriptions)
|
||||||
|
.set(columns(orgId, input))
|
||||||
|
.where(
|
||||||
|
and(eq(prescriptions.id, id), eq(prescriptions.organizationId, orgId)),
|
||||||
|
)
|
||||||
|
.returning();
|
||||||
|
return row ? toPrescription(row) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deletePrescription(
|
||||||
|
orgId: string,
|
||||||
|
id: string,
|
||||||
|
): Promise<boolean> {
|
||||||
|
if (!UUID_RE.test(id)) return false;
|
||||||
|
const deleted = await db
|
||||||
|
.delete(prescriptions)
|
||||||
|
.where(
|
||||||
|
and(eq(prescriptions.id, id), eq(prescriptions.organizationId, orgId)),
|
||||||
|
)
|
||||||
|
.returning({ id: prescriptions.id });
|
||||||
|
return deleted.length > 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
// The canonical Prescription shape returned by the API. Mirrors the frontend
|
||||||
|
// `lib/prescriptions.ts` Prescription type. Scoped to the active clinic; patient
|
||||||
|
// fields are denormalized for display and `fileNumber` links to a patient.
|
||||||
|
export type PrescriptionStatus = "active" | "completed" | "expired";
|
||||||
|
|
||||||
|
export type Prescription = {
|
||||||
|
id: string;
|
||||||
|
fileNumber: string;
|
||||||
|
name: string;
|
||||||
|
initials: string;
|
||||||
|
medication: string;
|
||||||
|
dose: string;
|
||||||
|
frequency: string;
|
||||||
|
prescriber: string;
|
||||||
|
prescribedAt: string; // YYYY-MM-DD
|
||||||
|
status: PrescriptionStatus;
|
||||||
|
duration: string | null;
|
||||||
|
notes: string | null;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
};
|
||||||
@@ -111,8 +111,8 @@ function Field({ label, children }: { label: string; children: ReactNode }) {
|
|||||||
|
|
||||||
// Compact "New prescription" dialog. The patient is chosen via a quick search by
|
// Compact "New prescription" dialog. The patient is chosen via a quick search by
|
||||||
// name or file number (same pattern as the appointment dialog); the rest is the
|
// name or file number (same pattern as the appointment dialog); the rest is the
|
||||||
// medication detail. Prescriptions are mock-only, so the new entry is handed back
|
// medication detail. The new entry is handed back to the page via onAdd, which
|
||||||
// to the page via onAdd.
|
// persists it through the prescriptions API.
|
||||||
export function AddPrescriptionDialog({
|
export function AddPrescriptionDialog({
|
||||||
open,
|
open,
|
||||||
onOpenChange,
|
onOpenChange,
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
SheetTitle,
|
SheetTitle,
|
||||||
} from "@/components/ui/sheet";
|
} from "@/components/ui/sheet";
|
||||||
import type { Prescription, RxStatus } from "@/components/prescriptions/prescriptions-view";
|
import type { Prescription, RxStatus } from "@/components/prescriptions/prescriptions-view";
|
||||||
|
import { formatPrescribedAt } from "@/lib/prescriptions";
|
||||||
|
|
||||||
const statusVariant: Record<
|
const statusVariant: Record<
|
||||||
RxStatus,
|
RxStatus,
|
||||||
@@ -28,7 +29,7 @@ const statusLabel: Record<RxStatus, string> = {
|
|||||||
|
|
||||||
// Right-side Sheet showing one prescription's full detail, opened by clicking a
|
// Right-side Sheet showing one prescription's full detail, opened by clicking a
|
||||||
// row in the Prescriptions list (mirrors the Patients table → side Sheet
|
// row in the Prescriptions list (mirrors the Patients table → side Sheet
|
||||||
// pattern). Prescriptions live in local state, so the record is passed in.
|
// pattern). The selected record is passed in from the page.
|
||||||
export function PrescriptionDetailSheet({
|
export function PrescriptionDetailSheet({
|
||||||
rx,
|
rx,
|
||||||
open,
|
open,
|
||||||
@@ -82,7 +83,9 @@ export function PrescriptionDetailSheet({
|
|||||||
<dt className="text-muted-foreground">Prescriber</dt>
|
<dt className="text-muted-foreground">Prescriber</dt>
|
||||||
<dd className="text-foreground">{rx.prescriber}</dd>
|
<dd className="text-foreground">{rx.prescriber}</dd>
|
||||||
<dt className="text-muted-foreground">Date</dt>
|
<dt className="text-muted-foreground">Date</dt>
|
||||||
<dd className="text-foreground">{rx.date}</dd>
|
<dd className="text-foreground">
|
||||||
|
{formatPrescribedAt(rx.prescribedAt)}
|
||||||
|
</dd>
|
||||||
<dt className="text-muted-foreground">Status</dt>
|
<dt className="text-muted-foreground">Status</dt>
|
||||||
<dd className="text-foreground">{statusLabel[rx.status]}</dd>
|
<dd className="text-foreground">{statusLabel[rx.status]}</dd>
|
||||||
</dl>
|
</dl>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { CircleCheck, Clock, Pill, Plus } from "lucide-react";
|
import { CircleCheck, Clock, Pill, Plus } from "lucide-react";
|
||||||
import { type ReactNode, useState } from "react";
|
import { type ReactNode, useEffect, useMemo, useState } from "react";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
AddPrescriptionDialog,
|
AddPrescriptionDialog,
|
||||||
@@ -12,25 +12,16 @@ 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 { Card } from "@/components/ui/card";
|
import { Card } from "@/components/ui/card";
|
||||||
|
import {
|
||||||
|
type Prescription,
|
||||||
|
type RxStatus,
|
||||||
|
createPrescription,
|
||||||
|
formatPrescribedAt,
|
||||||
|
listPrescriptions,
|
||||||
|
} from "@/lib/prescriptions";
|
||||||
|
import { notify } from "@/lib/toast";
|
||||||
|
|
||||||
// All figures here are mock/placeholder data — there is no prescriptions backend.
|
export type { Prescription, RxStatus } from "@/lib/prescriptions";
|
||||||
// They illustrate the Prescriptions layout.
|
|
||||||
|
|
||||||
export type RxStatus = "active" | "completed" | "expired";
|
|
||||||
|
|
||||||
export type Prescription = {
|
|
||||||
fileNumber: string;
|
|
||||||
name: string;
|
|
||||||
initials: string;
|
|
||||||
medication: string;
|
|
||||||
dose: string;
|
|
||||||
frequency: string;
|
|
||||||
prescriber: string;
|
|
||||||
date: string;
|
|
||||||
status: RxStatus;
|
|
||||||
duration?: string;
|
|
||||||
notes?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
const statusVariant: Record<
|
const statusVariant: Record<
|
||||||
RxStatus,
|
RxStatus,
|
||||||
@@ -47,70 +38,6 @@ const statusLabel: Record<RxStatus, string> = {
|
|||||||
expired: "Expired",
|
expired: "Expired",
|
||||||
};
|
};
|
||||||
|
|
||||||
const kpis = [
|
|
||||||
{ label: "Active", value: "8", icon: Pill },
|
|
||||||
{ label: "Due refill", value: "3", icon: Clock },
|
|
||||||
{ label: "Completed", value: "27", icon: CircleCheck },
|
|
||||||
];
|
|
||||||
|
|
||||||
const initial: Prescription[] = [
|
|
||||||
{
|
|
||||||
fileNumber: "10293",
|
|
||||||
name: "Amina Yusuf",
|
|
||||||
initials: "AY",
|
|
||||||
medication: "Lisinopril",
|
|
||||||
dose: "10 mg",
|
|
||||||
frequency: "Once daily",
|
|
||||||
prescriber: "Dr. Okafor",
|
|
||||||
date: "Jun 5, 2026",
|
|
||||||
status: "active",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
fileNumber: "10311",
|
|
||||||
name: "Daniel Mensah",
|
|
||||||
initials: "DM",
|
|
||||||
medication: "Metformin",
|
|
||||||
dose: "500 mg",
|
|
||||||
frequency: "Twice daily",
|
|
||||||
prescriber: "Dr. Okafor",
|
|
||||||
date: "Jun 4, 2026",
|
|
||||||
status: "active",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
fileNumber: "10342",
|
|
||||||
name: "Leila Haddad",
|
|
||||||
initials: "LH",
|
|
||||||
medication: "Amoxicillin",
|
|
||||||
dose: "500 mg",
|
|
||||||
frequency: "Three times daily",
|
|
||||||
prescriber: "Dr. Stein",
|
|
||||||
date: "May 28, 2026",
|
|
||||||
status: "completed",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
fileNumber: "10358",
|
|
||||||
name: "Carlos Rivera",
|
|
||||||
initials: "CR",
|
|
||||||
medication: "Atorvastatin",
|
|
||||||
dose: "20 mg",
|
|
||||||
frequency: "Once daily",
|
|
||||||
prescriber: "Dr. Okafor",
|
|
||||||
date: "May 12, 2026",
|
|
||||||
status: "expired",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
fileNumber: "10377",
|
|
||||||
name: "Priya Nair",
|
|
||||||
initials: "PN",
|
|
||||||
medication: "Salbutamol inhaler",
|
|
||||||
dose: "100 mcg",
|
|
||||||
frequency: "As needed",
|
|
||||||
prescriber: "Dr. Stein",
|
|
||||||
date: "Jun 1, 2026",
|
|
||||||
status: "active",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
function Kpi({
|
function Kpi({
|
||||||
label,
|
label,
|
||||||
value,
|
value,
|
||||||
@@ -165,7 +92,9 @@ function RxRow({ rx, onOpen }: { rx: Prescription; onOpen: () => void }) {
|
|||||||
</div>
|
</div>
|
||||||
<div className="hidden min-w-0 flex-col items-end sm:flex">
|
<div className="hidden min-w-0 flex-col items-end sm:flex">
|
||||||
<span className="truncate text-foreground text-xs">{rx.prescriber}</span>
|
<span className="truncate text-foreground text-xs">{rx.prescriber}</span>
|
||||||
<span className="text-muted-foreground text-xs">{rx.date}</span>
|
<span className="text-muted-foreground text-xs">
|
||||||
|
{formatPrescribedAt(rx.prescribedAt)}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<Badge variant={statusVariant[rx.status]}>{statusLabel[rx.status]}</Badge>
|
<Badge variant={statusVariant[rx.status]}>{statusLabel[rx.status]}</Badge>
|
||||||
</div>
|
</div>
|
||||||
@@ -196,46 +125,76 @@ function Section({
|
|||||||
|
|
||||||
export function PrescriptionsView() {
|
export function PrescriptionsView() {
|
||||||
const [addOpen, setAddOpen] = useState(false);
|
const [addOpen, setAddOpen] = useState(false);
|
||||||
const [list, setList] = useState<Prescription[]>(initial);
|
const [list, setList] = useState<Prescription[]>([]);
|
||||||
const [selected, setSelected] = useState<Prescription | null>(null);
|
const [selected, setSelected] = useState<Prescription | null>(null);
|
||||||
const [sheetOpen, setSheetOpen] = useState(false);
|
const [sheetOpen, setSheetOpen] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
let active = true;
|
||||||
|
listPrescriptions()
|
||||||
|
.then((data) => {
|
||||||
|
if (active) setList(data);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
/* api-client redirects on 401; otherwise leave the list empty */
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
active = false;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
const openRx = (rx: Prescription) => {
|
const openRx = (rx: Prescription) => {
|
||||||
setSelected(rx);
|
setSelected(rx);
|
||||||
setSheetOpen(true);
|
setSheetOpen(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Insert a new (mock) prescription at the top of the list, marked active.
|
// Persist a new prescription, then add the saved record to the top of the list.
|
||||||
const addPrescription = (rx: NewPrescription) => {
|
const addPrescription = async (rx: NewPrescription) => {
|
||||||
setList((prev) => [
|
try {
|
||||||
{
|
const created = await createPrescription({
|
||||||
fileNumber: rx.fileNumber,
|
fileNumber: rx.fileNumber,
|
||||||
name: rx.name,
|
name: rx.name,
|
||||||
initials: rx.initials,
|
initials: rx.initials,
|
||||||
medication: rx.medication,
|
medication: rx.medication,
|
||||||
dose: rx.dose,
|
dose: rx.dose,
|
||||||
frequency: rx.frequency,
|
frequency: rx.frequency,
|
||||||
duration: rx.duration || undefined,
|
duration: rx.duration || null,
|
||||||
notes: rx.notes || undefined,
|
notes: rx.notes || null,
|
||||||
prescriber: "Dr. Okafor",
|
});
|
||||||
date: new Date().toLocaleDateString("en-US", {
|
setList((prev) => [created, ...prev]);
|
||||||
month: "short",
|
} catch {
|
||||||
day: "numeric",
|
notify.error("Couldn't add prescription", "Please try again.");
|
||||||
year: "numeric",
|
}
|
||||||
}),
|
|
||||||
status: "active" as const,
|
|
||||||
},
|
|
||||||
...prev,
|
|
||||||
]);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const kpis = useMemo(
|
||||||
|
() => [
|
||||||
|
{
|
||||||
|
label: "Active",
|
||||||
|
value: String(list.filter((r) => r.status === "active").length),
|
||||||
|
icon: Pill,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Completed",
|
||||||
|
value: String(list.filter((r) => r.status === "completed").length),
|
||||||
|
icon: CircleCheck,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Expired",
|
||||||
|
value: String(list.filter((r) => r.status === "expired").length),
|
||||||
|
icon: Clock,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
[list],
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto flex w-full max-w-5xl flex-col gap-10 px-6 py-10">
|
<div className="mx-auto flex w-full max-w-5xl flex-col gap-10 px-6 py-10">
|
||||||
<div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
|
<div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="font-semibold text-2xl tracking-tight">Prescriptions</h1>
|
<h1 className="font-semibold text-2xl tracking-tight">Prescriptions</h1>
|
||||||
<p className="text-muted-foreground text-sm">
|
<p className="text-muted-foreground text-sm">
|
||||||
Medications prescribed across the clinic. Sample data.
|
Medications prescribed across the clinic.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<Button
|
<Button
|
||||||
@@ -257,11 +216,7 @@ export function PrescriptionsView() {
|
|||||||
<Section description="Most recent first" title="Recent prescriptions">
|
<Section description="Most recent first" title="Recent prescriptions">
|
||||||
<div className="divide-y divide-border overflow-hidden rounded-2xl border bg-card/30">
|
<div className="divide-y divide-border overflow-hidden rounded-2xl border bg-card/30">
|
||||||
{list.map((rx) => (
|
{list.map((rx) => (
|
||||||
<RxRow
|
<RxRow key={rx.id} onOpen={() => openRx(rx)} rx={rx} />
|
||||||
key={rx.fileNumber + rx.medication + rx.date}
|
|
||||||
onOpen={() => openRx(rx)}
|
|
||||||
rx={rx}
|
|
||||||
/>
|
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</Section>
|
</Section>
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import { apiFetch } from "@/lib/api-client";
|
||||||
|
|
||||||
|
// A prescription. Mirrors the backend `src/types/prescription.ts`. Scoped to the
|
||||||
|
// active clinic. `prescribedAt` is an ISO YYYY-MM-DD date.
|
||||||
|
export type RxStatus = "active" | "completed" | "expired";
|
||||||
|
|
||||||
|
export type Prescription = {
|
||||||
|
id: string;
|
||||||
|
fileNumber: string;
|
||||||
|
name: string;
|
||||||
|
initials: string;
|
||||||
|
medication: string;
|
||||||
|
dose: string;
|
||||||
|
frequency: string;
|
||||||
|
prescriber: string;
|
||||||
|
prescribedAt: string; // YYYY-MM-DD
|
||||||
|
status: RxStatus;
|
||||||
|
duration: string | null;
|
||||||
|
notes: string | null;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
// The fields the "New prescription" dialog collects; the backend fills the
|
||||||
|
// prescriber (from the signed-in user), prescribedAt (today) and status.
|
||||||
|
export type PrescriptionInput = {
|
||||||
|
fileNumber: string;
|
||||||
|
name: string;
|
||||||
|
initials: string;
|
||||||
|
medication: string;
|
||||||
|
dose: string;
|
||||||
|
frequency: string;
|
||||||
|
duration?: string | null;
|
||||||
|
notes?: string | null;
|
||||||
|
prescriber?: string;
|
||||||
|
prescribedAt?: string;
|
||||||
|
status?: RxStatus;
|
||||||
|
};
|
||||||
|
|
||||||
|
// "2026-06-05" -> "Jun 5, 2026" (matches the previous mock display format).
|
||||||
|
export function formatPrescribedAt(iso: string): string {
|
||||||
|
return new Date(`${iso}T00:00:00`).toLocaleDateString("en-US", {
|
||||||
|
month: "short",
|
||||||
|
day: "numeric",
|
||||||
|
year: "numeric",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listPrescriptions(): Promise<Prescription[]> {
|
||||||
|
return apiFetch<Prescription[]>("/api/prescriptions");
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createPrescription(
|
||||||
|
input: PrescriptionInput,
|
||||||
|
): Promise<Prescription> {
|
||||||
|
return apiFetch<Prescription>("/api/prescriptions", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(input),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updatePrescription(
|
||||||
|
id: string,
|
||||||
|
input: PrescriptionInput,
|
||||||
|
): Promise<Prescription> {
|
||||||
|
return apiFetch<Prescription>(`/api/prescriptions/${id}`, {
|
||||||
|
method: "PUT",
|
||||||
|
body: JSON.stringify(input),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deletePrescription(id: string): Promise<void> {
|
||||||
|
return apiFetch<void>(`/api/prescriptions/${id}`, { method: "DELETE" });
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user