feat: computed analytics endpoint, rework Analysis page

Add GET /api/analytics returning real aggregates over the clinic's
patients/appointments/prescriptions/tasks, and rebuild the Analysis page
to render them. Drops the fabricated revenue/profit cards — temetro has no
billing data source.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Khalid Abdi
2026-06-07 19:49:50 +03:00
parent 75940313a4
commit 48378ebc5e
6 changed files with 237 additions and 144 deletions
+3
View File
@@ -6,6 +6,7 @@ import { auth } from "./auth.js";
import { env } from "./env.js";
import { errorHandler, notFound } from "./middleware/error.js";
import { activityRouter } from "./routes/activity.js";
import { analyticsRouter } from "./routes/analytics.js";
import { appointmentsRouter } from "./routes/appointments.js";
import { notesRouter } from "./routes/notes.js";
import { patientsRouter } from "./routes/patients.js";
@@ -53,6 +54,7 @@ app.use("/api/appointments", appointmentsRouter);
app.use("/api/prescriptions", prescriptionsRouter);
app.use("/api/tasks", tasksRouter);
app.use("/api/activity", activityRouter);
app.use("/api/analytics", analyticsRouter);
app.use(notFound);
app.use(errorHandler);
@@ -66,4 +68,5 @@ app.listen(env.PORT, () => {
console.log(` • rx: /api/prescriptions`);
console.log(` • tasks: /api/tasks`);
console.log(` • activity: /api/activity`);
console.log(` • stats: /api/analytics`);
});
+17
View File
@@ -0,0 +1,17 @@
import { Router } from "express";
import { requireAuth, requireOrg } from "../middleware/auth.js";
import * as service from "../services/analytics.js";
export const analyticsRouter = Router();
// Clinic analytics are readable by any member of the active clinic.
analyticsRouter.use(requireAuth, requireOrg);
analyticsRouter.get("/", async (req, res, next) => {
try {
res.json(await service.getAnalytics(req.organizationId!));
} catch (err) {
next(err);
}
});
+121
View File
@@ -0,0 +1,121 @@
import { and, count, eq, gte, lte, type SQL } from "drizzle-orm";
import type { PgTable } from "drizzle-orm/pg-core";
import { db } from "../db/index.js";
import { appointments } from "../db/schema/appointments.js";
import { patients } from "../db/schema/patients.js";
import { prescriptions } from "../db/schema/prescriptions.js";
import { tasks } from "../db/schema/tasks.js";
import type { Analytics } from "../types/analytics.js";
const pad = (n: number) => String(n).padStart(2, "0");
const keyOf = (d: Date) =>
`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
async function countWhere(table: PgTable, where: SQL): Promise<number> {
const [row] = await db.select({ value: count() }).from(table).where(where);
return row?.value ?? 0;
}
export async function getAnalytics(orgId: string): Promise<Analytics> {
const now = new Date();
const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
const startOfWeek = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate() - now.getDay(),
);
const endOfWeek = new Date(startOfWeek);
endOfWeek.setDate(startOfWeek.getDate() + 6);
const weekStartKey = keyOf(startOfWeek);
const weekEndKey = keyOf(endOfWeek);
const todayKey = keyOf(now);
const [
patientsTotal,
patientsNew,
patientsActive,
apptWeek,
apptCompleted,
apptCancelled,
apptUpcoming,
rxTotal,
rxActive,
tasksOpen,
tasksDone,
] = await Promise.all([
countWhere(patients, eq(patients.organizationId, orgId)),
countWhere(
patients,
and(
eq(patients.organizationId, orgId),
gte(patients.createdAt, startOfMonth),
)!,
),
countWhere(
patients,
and(eq(patients.organizationId, orgId), eq(patients.status, "active"))!,
),
countWhere(
appointments,
and(
eq(appointments.organizationId, orgId),
gte(appointments.date, weekStartKey),
lte(appointments.date, weekEndKey),
)!,
),
countWhere(
appointments,
and(
eq(appointments.organizationId, orgId),
eq(appointments.status, "completed"),
)!,
),
countWhere(
appointments,
and(
eq(appointments.organizationId, orgId),
eq(appointments.status, "cancelled"),
)!,
),
countWhere(
appointments,
and(
eq(appointments.organizationId, orgId),
gte(appointments.date, todayKey),
)!,
),
countWhere(prescriptions, eq(prescriptions.organizationId, orgId)),
countWhere(
prescriptions,
and(
eq(prescriptions.organizationId, orgId),
eq(prescriptions.status, "active"),
)!,
),
countWhere(
tasks,
and(eq(tasks.organizationId, orgId), eq(tasks.done, false))!,
),
countWhere(
tasks,
and(eq(tasks.organizationId, orgId), eq(tasks.done, true))!,
),
]);
return {
patients: {
total: patientsTotal,
newThisMonth: patientsNew,
active: patientsActive,
},
appointments: {
thisWeek: apptWeek,
completed: apptCompleted,
cancelled: apptCancelled,
upcoming: apptUpcoming,
},
prescriptions: { total: rxTotal, active: rxActive },
tasks: { open: tasksOpen, done: tasksDone },
};
}
+23
View File
@@ -0,0 +1,23 @@
// Server-computed clinic analytics returned by GET /api/analytics. All figures
// are aggregates over the active clinic's real data (no fabricated financials).
export type Analytics = {
patients: {
total: number;
newThisMonth: number;
active: number;
};
appointments: {
thisWeek: number;
completed: number;
cancelled: number;
upcoming: number;
};
prescriptions: {
total: number;
active: number;
};
tasks: {
open: number;
done: number;
};
};