mirror of
https://github.com/temetro/temetro.git
synced 2026-08-06 00:47:41 +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:
@@ -2,3 +2,4 @@ export * from "./auth.js";
|
||||
export * from "./patients.js";
|
||||
export * from "./notes.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 { notesRouter } from "./routes/notes.js";
|
||||
import { patientsRouter } from "./routes/patients.js";
|
||||
import { prescriptionsRouter } from "./routes/prescriptions.js";
|
||||
|
||||
const app = express();
|
||||
|
||||
@@ -47,6 +48,7 @@ app.get("/health", (_req, res) => {
|
||||
app.use("/api/patients", patientsRouter);
|
||||
app.use("/api/notes", notesRouter);
|
||||
app.use("/api/appointments", appointmentsRouter);
|
||||
app.use("/api/prescriptions", prescriptionsRouter);
|
||||
|
||||
app.use(notFound);
|
||||
app.use(errorHandler);
|
||||
@@ -57,4 +59,5 @@ app.listen(env.PORT, () => {
|
||||
console.log(` • patients: /api/patients`);
|
||||
console.log(` • notes: /api/notes`);
|
||||
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;
|
||||
};
|
||||
Reference in New Issue
Block a user