mirror of
https://github.com/temetro/temetro.git
synced 2026-08-24 17:16:34 +00:00
feat: org-scoped tasks backend, wire tasks page
Add the tasks table, validation, service and routes (/api/tasks with a PATCH for partial updates / the done toggle, RBAC-gated) and the frontend data module. The tasks board now loads, creates and toggles real data (optimistic toggle with rollback). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -3,3 +3,4 @@ export * from "./patients.js";
|
||||
export * from "./notes.js";
|
||||
export * from "./appointments.js";
|
||||
export * from "./prescriptions.js";
|
||||
export * from "./tasks.js";
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import {
|
||||
boolean,
|
||||
index,
|
||||
pgTable,
|
||||
text,
|
||||
timestamp,
|
||||
uuid,
|
||||
} from "drizzle-orm/pg-core";
|
||||
|
||||
import type { TaskPriority } from "../../types/task.js";
|
||||
import { organization, user } from "./auth.js";
|
||||
|
||||
// One row per care-team to-do, scoped to a clinic (organization). Shared across
|
||||
// the clinic (unlike notes, which are per-author). `assignee`/`due`/`patient`
|
||||
// are free text to match the lightweight board UI.
|
||||
export const tasks = pgTable(
|
||||
"tasks",
|
||||
{
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
organizationId: text("organization_id")
|
||||
.notNull()
|
||||
.references(() => organization.id, { onDelete: "cascade" }),
|
||||
title: text("title").notNull(),
|
||||
assignee: text("assignee").notNull().default("Unassigned"),
|
||||
due: text("due").notNull().default("No due date"),
|
||||
priority: text("priority").$type<TaskPriority>().notNull(),
|
||||
patient: text("patient"),
|
||||
notes: text("notes"),
|
||||
done: boolean("done").notNull().default(false),
|
||||
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("tasks_org_idx").on(t.organizationId)],
|
||||
);
|
||||
@@ -9,6 +9,7 @@ import { appointmentsRouter } from "./routes/appointments.js";
|
||||
import { notesRouter } from "./routes/notes.js";
|
||||
import { patientsRouter } from "./routes/patients.js";
|
||||
import { prescriptionsRouter } from "./routes/prescriptions.js";
|
||||
import { tasksRouter } from "./routes/tasks.js";
|
||||
|
||||
const app = express();
|
||||
|
||||
@@ -49,6 +50,7 @@ app.use("/api/patients", patientsRouter);
|
||||
app.use("/api/notes", notesRouter);
|
||||
app.use("/api/appointments", appointmentsRouter);
|
||||
app.use("/api/prescriptions", prescriptionsRouter);
|
||||
app.use("/api/tasks", tasksRouter);
|
||||
|
||||
app.use(notFound);
|
||||
app.use(errorHandler);
|
||||
@@ -60,4 +62,5 @@ app.listen(env.PORT, () => {
|
||||
console.log(` • notes: /api/notes`);
|
||||
console.log(` • appts: /api/appointments`);
|
||||
console.log(` • rx: /api/prescriptions`);
|
||||
console.log(` • tasks: /api/tasks`);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { z } from "zod";
|
||||
|
||||
// Payload accepted by POST /api/tasks (full create).
|
||||
export const taskInputSchema = z.object({
|
||||
title: z.string().trim().min(1, "A task subject is required.").max(200),
|
||||
assignee: z.string().trim().max(200).default("Unassigned"),
|
||||
due: z.string().trim().max(120).default("No due date"),
|
||||
priority: z.enum(["high", "medium", "low"]).default("medium"),
|
||||
patient: z.string().trim().max(200).nullish(),
|
||||
notes: z.string().max(5000).nullish(),
|
||||
});
|
||||
|
||||
// Payload accepted by PATCH /api/tasks/:id — any subset of fields, plus `done`
|
||||
// (used by the list/detail toggle).
|
||||
export const taskPatchSchema = taskInputSchema.partial().extend({
|
||||
done: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export type TaskInput = z.infer<typeof taskInputSchema>;
|
||||
export type TaskPatch = z.infer<typeof taskPatchSchema>;
|
||||
@@ -0,0 +1,80 @@
|
||||
import { Router } from "express";
|
||||
|
||||
import { HttpError } from "../lib/http-error.js";
|
||||
import { taskInputSchema, taskPatchSchema } from "../lib/task-validation.js";
|
||||
import {
|
||||
requireAuth,
|
||||
requireOrg,
|
||||
requirePermission,
|
||||
} from "../middleware/auth.js";
|
||||
import * as service from "../services/tasks.js";
|
||||
|
||||
export const tasksRouter = Router();
|
||||
|
||||
tasksRouter.use(requireAuth, requireOrg);
|
||||
|
||||
tasksRouter.get(
|
||||
"/",
|
||||
requirePermission({ task: ["read"] }),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
res.json(await service.listTasks(req.organizationId!));
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
tasksRouter.post(
|
||||
"/",
|
||||
requirePermission({ task: ["write"] }),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
const input = taskInputSchema.parse(req.body);
|
||||
const created = await service.createTask(
|
||||
req.organizationId!,
|
||||
req.user!.id,
|
||||
input,
|
||||
);
|
||||
res.status(201).json(created);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
tasksRouter.patch(
|
||||
"/:id",
|
||||
requirePermission({ task: ["write"] }),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
const patch = taskPatchSchema.parse(req.body);
|
||||
const updated = await service.updateTask(
|
||||
req.organizationId!,
|
||||
req.params.id as string,
|
||||
patch,
|
||||
);
|
||||
if (!updated) throw new HttpError(404, "Task not found.");
|
||||
res.json(updated);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
tasksRouter.delete(
|
||||
"/:id",
|
||||
requirePermission({ task: ["delete"] }),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
const ok = await service.deleteTask(
|
||||
req.organizationId!,
|
||||
req.params.id as string,
|
||||
);
|
||||
if (!ok) throw new HttpError(404, "Task not found.");
|
||||
res.status(204).end();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,99 @@
|
||||
import { and, desc, eq } from "drizzle-orm";
|
||||
|
||||
import { db } from "../db/index.js";
|
||||
import { tasks } from "../db/schema/tasks.js";
|
||||
import type { TaskInput, TaskPatch } from "../lib/task-validation.js";
|
||||
import type { Task } from "../types/task.js";
|
||||
|
||||
type TaskRow = typeof tasks.$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 toTask(row: TaskRow): Task {
|
||||
return {
|
||||
id: row.id,
|
||||
title: row.title,
|
||||
assignee: row.assignee,
|
||||
due: row.due,
|
||||
priority: row.priority,
|
||||
patient: row.patient,
|
||||
notes: row.notes,
|
||||
done: row.done,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
updatedAt: row.updatedAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
export async function listTasks(orgId: string): Promise<Task[]> {
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(tasks)
|
||||
.where(eq(tasks.organizationId, orgId))
|
||||
.orderBy(desc(tasks.createdAt));
|
||||
return rows.map(toTask);
|
||||
}
|
||||
|
||||
export async function createTask(
|
||||
orgId: string,
|
||||
userId: string,
|
||||
input: TaskInput,
|
||||
): Promise<Task> {
|
||||
const [row] = await db
|
||||
.insert(tasks)
|
||||
.values({
|
||||
organizationId: orgId,
|
||||
title: input.title,
|
||||
assignee: input.assignee,
|
||||
due: input.due,
|
||||
priority: input.priority,
|
||||
patient: input.patient ?? null,
|
||||
notes: input.notes ?? null,
|
||||
createdBy: userId,
|
||||
})
|
||||
.returning();
|
||||
return toTask(row!);
|
||||
}
|
||||
|
||||
export async function updateTask(
|
||||
orgId: string,
|
||||
id: string,
|
||||
patch: TaskPatch,
|
||||
): Promise<Task | null> {
|
||||
if (!UUID_RE.test(id)) return null;
|
||||
|
||||
// Build a set object from only the provided fields.
|
||||
const set: Partial<typeof tasks.$inferInsert> = {};
|
||||
if (patch.title !== undefined) set.title = patch.title;
|
||||
if (patch.assignee !== undefined) set.assignee = patch.assignee;
|
||||
if (patch.due !== undefined) set.due = patch.due;
|
||||
if (patch.priority !== undefined) set.priority = patch.priority;
|
||||
if (patch.patient !== undefined) set.patient = patch.patient ?? null;
|
||||
if (patch.notes !== undefined) set.notes = patch.notes ?? null;
|
||||
if (patch.done !== undefined) set.done = patch.done;
|
||||
|
||||
if (Object.keys(set).length === 0) {
|
||||
const [row] = await db
|
||||
.select()
|
||||
.from(tasks)
|
||||
.where(and(eq(tasks.id, id), eq(tasks.organizationId, orgId)));
|
||||
return row ? toTask(row) : null;
|
||||
}
|
||||
|
||||
const [row] = await db
|
||||
.update(tasks)
|
||||
.set(set)
|
||||
.where(and(eq(tasks.id, id), eq(tasks.organizationId, orgId)))
|
||||
.returning();
|
||||
return row ? toTask(row) : null;
|
||||
}
|
||||
|
||||
export async function deleteTask(orgId: string, id: string): Promise<boolean> {
|
||||
if (!UUID_RE.test(id)) return false;
|
||||
const deleted = await db
|
||||
.delete(tasks)
|
||||
.where(and(eq(tasks.id, id), eq(tasks.organizationId, orgId)))
|
||||
.returning({ id: tasks.id });
|
||||
return deleted.length > 0;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// The canonical Task shape returned by the API. Mirrors the frontend
|
||||
// `lib/tasks.ts` Task type. Scoped to the active clinic (a shared care-team
|
||||
// to-do board). `patient` is an optional free-text reference for context.
|
||||
export type TaskPriority = "high" | "medium" | "low";
|
||||
|
||||
export type Task = {
|
||||
id: string;
|
||||
title: string;
|
||||
assignee: string;
|
||||
due: string;
|
||||
priority: TaskPriority;
|
||||
patient: string | null;
|
||||
notes: string | null;
|
||||
done: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
Reference in New Issue
Block a user