fix: tighten real operations data paths
This commit is contained in:
@@ -1,8 +1,13 @@
|
|||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
import { getCurrentAuthContext } from "@/modules/core/server/auth";
|
import { getCurrentAuthContext } from "@/modules/core/server/auth";
|
||||||
|
import {
|
||||||
|
listOperationalAdmissions,
|
||||||
|
listOperationalBeds,
|
||||||
|
listOperationalElders,
|
||||||
|
listOperationalRooms,
|
||||||
|
} from "@/modules/core/server/operations";
|
||||||
import { hasPermission } from "@/modules/core/server/permissions";
|
import { hasPermission } from "@/modules/core/server/permissions";
|
||||||
import { readData } from "@/modules/core/server/store";
|
|
||||||
import { BedsWorkspace } from "@/modules/facilities/components/BedsWorkspace";
|
import { BedsWorkspace } from "@/modules/facilities/components/BedsWorkspace";
|
||||||
|
|
||||||
export default async function BedsPage(): Promise<React.ReactElement> {
|
export default async function BedsPage(): Promise<React.ReactElement> {
|
||||||
@@ -15,14 +20,13 @@ export default async function BedsPage(): Promise<React.ReactElement> {
|
|||||||
redirect("/app/dashboard");
|
redirect("/app/dashboard");
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await readData();
|
|
||||||
const organizationId = context.organization?.id;
|
const organizationId = context.organization?.id;
|
||||||
const rooms = organizationId ? data.rooms.filter((room) => room.organizationId === organizationId) : data.rooms;
|
const [rooms, beds, admissions, elders] = await Promise.all([
|
||||||
const beds = organizationId ? data.beds.filter((bed) => bed.organizationId === organizationId) : data.beds;
|
listOperationalRooms(organizationId),
|
||||||
const admissions = organizationId
|
listOperationalBeds(organizationId),
|
||||||
? data.admissions.filter((admission) => admission.organizationId === organizationId)
|
listOperationalAdmissions(organizationId),
|
||||||
: data.admissions;
|
listOperationalElders(organizationId),
|
||||||
const elders = organizationId ? data.elders.filter((elder) => elder.organizationId === organizationId) : data.elders;
|
]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<BedsWorkspace
|
<BedsWorkspace
|
||||||
|
|||||||
@@ -1,7 +1,12 @@
|
|||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
import { getCurrentAuthContext } from "@/modules/core/server/auth";
|
import { getCurrentAuthContext } from "@/modules/core/server/auth";
|
||||||
import { readData } from "@/modules/core/server/store";
|
import {
|
||||||
|
listOperationalAdmissions,
|
||||||
|
listOperationalBeds,
|
||||||
|
listOperationalElders,
|
||||||
|
listOperationalIncidents,
|
||||||
|
} from "@/modules/core/server/operations";
|
||||||
import type { BedStatus } from "@/modules/core/types";
|
import type { BedStatus } from "@/modules/core/types";
|
||||||
import { DashboardHome, type DashboardMetric } from "@/modules/dashboard/components/DashboardHome";
|
import { DashboardHome, type DashboardMetric } from "@/modules/dashboard/components/DashboardHome";
|
||||||
|
|
||||||
@@ -13,16 +18,13 @@ export default async function DashboardPage(): Promise<React.ReactElement> {
|
|||||||
redirect("/login");
|
redirect("/login");
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await readData();
|
|
||||||
const organizationId = context.organization?.id;
|
const organizationId = context.organization?.id;
|
||||||
const elders = organizationId ? data.elders.filter((elder) => elder.organizationId === organizationId) : data.elders;
|
const [elders, beds, admissions, incidents] = await Promise.all([
|
||||||
const beds = organizationId ? data.beds.filter((bed) => bed.organizationId === organizationId) : data.beds;
|
listOperationalElders(organizationId),
|
||||||
const admissions = organizationId
|
listOperationalBeds(organizationId),
|
||||||
? data.admissions.filter((admission) => admission.organizationId === organizationId)
|
listOperationalAdmissions(organizationId),
|
||||||
: data.admissions;
|
listOperationalIncidents(organizationId),
|
||||||
const incidents = organizationId
|
]);
|
||||||
? data.incidents.filter((incident) => !incident.organizationId || incident.organizationId === organizationId)
|
|
||||||
: data.incidents;
|
|
||||||
|
|
||||||
const activeElders = elders.filter((elder) => elder.status === "active").length;
|
const activeElders = elders.filter((elder) => elder.status === "active").length;
|
||||||
const pendingElders = elders.filter((elder) => elder.status === "pending").length;
|
const pendingElders = elders.filter((elder) => elder.status === "pending").length;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
import { getCurrentAuthContext } from "@/modules/core/server/auth";
|
import { getCurrentAuthContext } from "@/modules/core/server/auth";
|
||||||
import { readData } from "@/modules/core/server/store";
|
import { listOperationalElders } from "@/modules/core/server/operations";
|
||||||
import { EldersClient } from "@/modules/elders/components/EldersClient";
|
import { EldersClient } from "@/modules/elders/components/EldersClient";
|
||||||
|
|
||||||
export default async function EldersPage(): Promise<React.ReactElement> {
|
export default async function EldersPage(): Promise<React.ReactElement> {
|
||||||
@@ -10,11 +10,7 @@ export default async function EldersPage(): Promise<React.ReactElement> {
|
|||||||
redirect("/login");
|
redirect("/login");
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await readData();
|
const elders = await listOperationalElders(context.organization?.id);
|
||||||
const organizationId = context.organization?.id;
|
|
||||||
const elders = organizationId
|
|
||||||
? data.elders.filter((elder) => elder.organizationId === organizationId)
|
|
||||||
: data.elders;
|
|
||||||
|
|
||||||
return <EldersClient initialElders={elders} permissions={context.permissions} />;
|
return <EldersClient initialElders={elders} permissions={context.permissions} />;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,8 +4,8 @@ import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/ap
|
|||||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||||
import { requirePermission } from "@/modules/core/server/auth";
|
import { requirePermission } from "@/modules/core/server/auth";
|
||||||
import { getDatabase } from "@/modules/core/server/db";
|
import { getDatabase } from "@/modules/core/server/db";
|
||||||
|
import { listOperationalAdmissions } from "@/modules/core/server/operations";
|
||||||
import { admissions, beds, elders } from "@/modules/core/server/schema";
|
import { admissions, beds, elders } from "@/modules/core/server/schema";
|
||||||
import { readData } from "@/modules/core/server/store";
|
|
||||||
|
|
||||||
type AdmissionRow = typeof admissions.$inferSelect;
|
type AdmissionRow = typeof admissions.$inferSelect;
|
||||||
|
|
||||||
@@ -39,13 +39,8 @@ export async function GET(): Promise<Response> {
|
|||||||
return auth.response;
|
return auth.response;
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await readData();
|
const admissionsData = await listOperationalAdmissions(auth.context.organization?.id);
|
||||||
const organizationId = auth.context.organization?.id;
|
return jsonSuccess("入住记录已加载", { admissions: admissionsData });
|
||||||
return jsonSuccess("入住记录已加载", {
|
|
||||||
admissions: organizationId
|
|
||||||
? data.admissions.filter((admission) => admission.organizationId === organizationId)
|
|
||||||
: data.admissions,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function POST(request: Request): Promise<Response> {
|
export async function POST(request: Request): Promise<Response> {
|
||||||
|
|||||||
@@ -4,8 +4,8 @@ import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/ap
|
|||||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||||
import { requirePermission } from "@/modules/core/server/auth";
|
import { requirePermission } from "@/modules/core/server/auth";
|
||||||
import { getDatabase } from "@/modules/core/server/db";
|
import { getDatabase } from "@/modules/core/server/db";
|
||||||
|
import { listOperationalBeds } from "@/modules/core/server/operations";
|
||||||
import { beds, rooms } from "@/modules/core/server/schema";
|
import { beds, rooms } from "@/modules/core/server/schema";
|
||||||
import { readData } from "@/modules/core/server/store";
|
|
||||||
import type { BedStatus } from "@/modules/core/types";
|
import type { BedStatus } from "@/modules/core/types";
|
||||||
|
|
||||||
const BED_STATUS_VALUES: BedStatus[] = ["available", "occupied", "maintenance", "disabled"];
|
const BED_STATUS_VALUES: BedStatus[] = ["available", "occupied", "maintenance", "disabled"];
|
||||||
@@ -19,8 +19,12 @@ function readString(source: Record<string, unknown>, key: string): string {
|
|||||||
return typeof value === "string" ? value.trim() : "";
|
return typeof value === "string" ? value.trim() : "";
|
||||||
}
|
}
|
||||||
|
|
||||||
function readBedStatus(value: string): BedStatus {
|
function readOptionalBedStatus(value: string): BedStatus | null | undefined {
|
||||||
return BED_STATUS_VALUES.find((status) => status === value) ?? "available";
|
if (!value) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
return BED_STATUS_VALUES.find((status) => status === value) ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function GET(): Promise<Response> {
|
export async function GET(): Promise<Response> {
|
||||||
@@ -33,11 +37,8 @@ export async function GET(): Promise<Response> {
|
|||||||
return auth.response;
|
return auth.response;
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await readData();
|
const bedsData = await listOperationalBeds(auth.context.organization?.id);
|
||||||
const organizationId = auth.context.organization?.id;
|
return jsonSuccess("床位列表已加载", { beds: bedsData });
|
||||||
return jsonSuccess("床位列表已加载", {
|
|
||||||
beds: organizationId ? data.beds.filter((bed) => bed.organizationId === organizationId) : data.beds,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function POST(request: Request): Promise<Response> {
|
export async function POST(request: Request): Promise<Response> {
|
||||||
@@ -65,6 +66,10 @@ export async function POST(request: Request): Promise<Response> {
|
|||||||
if (!roomId || !code) {
|
if (!roomId || !code) {
|
||||||
return jsonFailure("房间和床位编号不能为空");
|
return jsonFailure("房间和床位编号不能为空");
|
||||||
}
|
}
|
||||||
|
const status = readOptionalBedStatus(readString(body, "status"));
|
||||||
|
if (status === null) {
|
||||||
|
return jsonFailure("床位状态无效");
|
||||||
|
}
|
||||||
|
|
||||||
const database = getDatabase();
|
const database = getDatabase();
|
||||||
const roomRows = await database
|
const roomRows = await database
|
||||||
@@ -83,7 +88,7 @@ export async function POST(request: Request): Promise<Response> {
|
|||||||
organizationId,
|
organizationId,
|
||||||
roomId,
|
roomId,
|
||||||
code,
|
code,
|
||||||
status: readBedStatus(readString(body, "status")),
|
status: status ?? "available",
|
||||||
notes: readString(body, "notes"),
|
notes: readString(body, "notes"),
|
||||||
})
|
})
|
||||||
.returning();
|
.returning();
|
||||||
|
|||||||
@@ -1,13 +1,11 @@
|
|||||||
import { randomUUID } from "node:crypto";
|
import { and, eq } from "drizzle-orm";
|
||||||
|
|
||||||
import { eq } from "drizzle-orm";
|
|
||||||
|
|
||||||
import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
|
import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
|
||||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||||
import { requirePermission } from "@/modules/core/server/auth";
|
import { requirePermission } from "@/modules/core/server/auth";
|
||||||
import { getDatabase } from "@/modules/core/server/db";
|
import { getDatabase } from "@/modules/core/server/db";
|
||||||
import { campuses, buildings, floors, rooms } from "@/modules/core/server/schema";
|
import { listOperationalRooms } from "@/modules/core/server/operations";
|
||||||
import { readData } from "@/modules/core/server/store";
|
import { floors, rooms } from "@/modules/core/server/schema";
|
||||||
|
|
||||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||||
@@ -18,10 +16,14 @@ function readString(source: Record<string, unknown>, key: string): string {
|
|||||||
return typeof value === "string" ? value.trim() : "";
|
return typeof value === "string" ? value.trim() : "";
|
||||||
}
|
}
|
||||||
|
|
||||||
function readPositiveNumber(source: Record<string, unknown>, key: string, fallback: number): number {
|
function readOptionalPositiveNumber(source: Record<string, unknown>, key: string): number | null | undefined {
|
||||||
const value = source[key];
|
const value = source[key];
|
||||||
|
if (value === undefined || value === null || value === "") {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
const numeric = typeof value === "number" ? value : Number(value);
|
const numeric = typeof value === "number" ? value : Number(value);
|
||||||
return Number.isInteger(numeric) && numeric > 0 ? numeric : fallback;
|
return Number.isInteger(numeric) && numeric > 0 ? numeric : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function GET(): Promise<Response> {
|
export async function GET(): Promise<Response> {
|
||||||
@@ -34,11 +36,8 @@ export async function GET(): Promise<Response> {
|
|||||||
return auth.response;
|
return auth.response;
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await readData();
|
const roomsData = await listOperationalRooms(auth.context.organization?.id);
|
||||||
const organizationId = auth.context.organization?.id;
|
return jsonSuccess("房间列表已加载", { rooms: roomsData });
|
||||||
return jsonSuccess("房间列表已加载", {
|
|
||||||
rooms: organizationId ? data.rooms.filter((room) => room.organizationId === organizationId) : data.rooms,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function POST(request: Request): Promise<Response> {
|
export async function POST(request: Request): Promise<Response> {
|
||||||
@@ -63,63 +62,37 @@ export async function POST(request: Request): Promise<Response> {
|
|||||||
|
|
||||||
const roomName = readString(body, "name");
|
const roomName = readString(body, "name");
|
||||||
const roomCode = readString(body, "code");
|
const roomCode = readString(body, "code");
|
||||||
if (!roomName || !roomCode) {
|
const floorId = readString(body, "floorId");
|
||||||
return jsonFailure("房间名称和编号不能为空");
|
if (!roomName || !roomCode || !floorId) {
|
||||||
|
return jsonFailure("房间名称、编号和楼层不能为空");
|
||||||
}
|
}
|
||||||
|
const capacityInput = readOptionalPositiveNumber(body, "capacity");
|
||||||
|
if (capacityInput === null) {
|
||||||
|
return jsonFailure("房间容量需为正整数");
|
||||||
|
}
|
||||||
|
const capacity = capacityInput ?? 1;
|
||||||
|
|
||||||
const database = getDatabase();
|
const database = getDatabase();
|
||||||
const createdRows = await database.transaction(async (transaction) => {
|
const floorRows = await database
|
||||||
const campusRows = await transaction.select().from(campuses).where(eq(campuses.organizationId, organizationId)).limit(1);
|
.select({ id: floors.id })
|
||||||
const campus =
|
.from(floors)
|
||||||
campusRows[0] ??
|
.where(and(eq(floors.id, floorId), eq(floors.organizationId, organizationId)))
|
||||||
(
|
.limit(1);
|
||||||
await transaction
|
const floor = floorRows[0];
|
||||||
.insert(campuses)
|
|
||||||
.values({ organizationId, name: "默认院区", address: "" })
|
|
||||||
.returning()
|
|
||||||
)[0];
|
|
||||||
if (!campus) {
|
|
||||||
throw new Error("院区初始化失败");
|
|
||||||
}
|
|
||||||
|
|
||||||
const buildingRows = await transaction.select().from(buildings).where(eq(buildings.campusId, campus.id)).limit(1);
|
|
||||||
const building =
|
|
||||||
buildingRows[0] ??
|
|
||||||
(
|
|
||||||
await transaction
|
|
||||||
.insert(buildings)
|
|
||||||
.values({ organizationId, campusId: campus.id, name: "默认楼栋" })
|
|
||||||
.returning()
|
|
||||||
)[0];
|
|
||||||
if (!building) {
|
|
||||||
throw new Error("楼栋初始化失败");
|
|
||||||
}
|
|
||||||
|
|
||||||
const floorRows = await transaction.select().from(floors).where(eq(floors.buildingId, building.id)).limit(1);
|
|
||||||
const floor =
|
|
||||||
floorRows[0] ??
|
|
||||||
(
|
|
||||||
await transaction
|
|
||||||
.insert(floors)
|
|
||||||
.values({ organizationId, buildingId: building.id, name: "默认楼层", level: 1 })
|
|
||||||
.returning()
|
|
||||||
)[0];
|
|
||||||
if (!floor) {
|
if (!floor) {
|
||||||
throw new Error("楼层初始化失败");
|
return jsonFailure("楼层不存在", 404);
|
||||||
}
|
}
|
||||||
|
|
||||||
return await transaction
|
const createdRows = await database
|
||||||
.insert(rooms)
|
.insert(rooms)
|
||||||
.values({
|
.values({
|
||||||
id: randomUUID(),
|
|
||||||
organizationId,
|
organizationId,
|
||||||
floorId: floor.id,
|
floorId: floor.id,
|
||||||
name: roomName,
|
name: roomName,
|
||||||
code: roomCode,
|
code: roomCode,
|
||||||
capacity: readPositiveNumber(body, "capacity", 1),
|
capacity,
|
||||||
})
|
})
|
||||||
.returning();
|
.returning();
|
||||||
});
|
|
||||||
|
|
||||||
const room = createdRows[0];
|
const room = createdRows[0];
|
||||||
if (!room) {
|
if (!room) {
|
||||||
|
|||||||
@@ -64,18 +64,9 @@ export async function PATCH(request: Request, context: RouteContext): Promise<Re
|
|||||||
throw new Error("申请已处理");
|
throw new Error("申请已处理");
|
||||||
}
|
}
|
||||||
|
|
||||||
let roleId = readString(body, "roleId");
|
const roleId = readString(body, "roleId");
|
||||||
if (decision === "approved" && !roleId) {
|
if (decision === "approved" && !roleId) {
|
||||||
const defaultRoleRows = await transaction
|
throw new Error("请选择审批角色");
|
||||||
.select()
|
|
||||||
.from(roles)
|
|
||||||
.where(and(eq(roles.organizationId, joinRequest.organizationId), eq(roles.key, "caregiver")))
|
|
||||||
.limit(1);
|
|
||||||
const defaultRole = defaultRoleRows[0];
|
|
||||||
if (!defaultRole) {
|
|
||||||
throw new Error("默认角色不存在");
|
|
||||||
}
|
|
||||||
roleId = defaultRole.id;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (decision === "approved") {
|
if (decision === "approved") {
|
||||||
|
|||||||
203
modules/core/server/operations.ts
Normal file
203
modules/core/server/operations.ts
Normal file
@@ -0,0 +1,203 @@
|
|||||||
|
import { and, desc, eq, isNull, or, sql } from "drizzle-orm";
|
||||||
|
|
||||||
|
import { getDatabase } from "@/modules/core/server/db";
|
||||||
|
import { admissions, beds, elders, rooms, systemIncidents } from "@/modules/core/server/schema";
|
||||||
|
import type { Admission, FacilityBed, Room, SystemIncident } from "@/modules/core/types";
|
||||||
|
import type { Elder } from "@/modules/elders/types";
|
||||||
|
|
||||||
|
function iso(value: Date): string {
|
||||||
|
return value.toISOString();
|
||||||
|
}
|
||||||
|
|
||||||
|
type ActiveBedLabel = {
|
||||||
|
bed: string;
|
||||||
|
bedId: string;
|
||||||
|
room: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
function toElder(row: typeof elders.$inferSelect, activeBed?: ActiveBedLabel): Elder {
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
organizationId: row.organizationId,
|
||||||
|
name: row.name,
|
||||||
|
gender: row.gender,
|
||||||
|
age: row.age,
|
||||||
|
careLevel: row.careLevel,
|
||||||
|
room: activeBed?.room ?? "",
|
||||||
|
bed: activeBed?.bed ?? "",
|
||||||
|
bedId: activeBed?.bedId,
|
||||||
|
status: row.status,
|
||||||
|
primaryContact: row.primaryContact,
|
||||||
|
phone: row.phone,
|
||||||
|
medicalNotes: row.medicalNotes,
|
||||||
|
createdAt: iso(row.createdAt),
|
||||||
|
updatedAt: iso(row.updatedAt),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listOperationalElders(organizationId?: string): Promise<Elder[]> {
|
||||||
|
const database = getDatabase();
|
||||||
|
const [elderRows, activeAdmissionRows] = await Promise.all([
|
||||||
|
database
|
||||||
|
.select()
|
||||||
|
.from(elders)
|
||||||
|
.where(organizationId ? eq(elders.organizationId, organizationId) : sql`true`)
|
||||||
|
.orderBy(desc(elders.createdAt)),
|
||||||
|
database
|
||||||
|
.select({
|
||||||
|
bedCode: beds.code,
|
||||||
|
bedId: admissions.bedId,
|
||||||
|
elderId: admissions.elderId,
|
||||||
|
roomName: rooms.name,
|
||||||
|
})
|
||||||
|
.from(admissions)
|
||||||
|
.innerJoin(beds, eq(beds.id, admissions.bedId))
|
||||||
|
.innerJoin(rooms, eq(rooms.id, beds.roomId))
|
||||||
|
.where(
|
||||||
|
organizationId
|
||||||
|
? and(eq(admissions.organizationId, organizationId), eq(admissions.status, "active"))
|
||||||
|
: eq(admissions.status, "active"),
|
||||||
|
)
|
||||||
|
.orderBy(desc(admissions.admittedAt)),
|
||||||
|
]);
|
||||||
|
const bedLabelByElderId = new Map<string, ActiveBedLabel>();
|
||||||
|
for (const row of activeAdmissionRows) {
|
||||||
|
if (bedLabelByElderId.has(row.elderId)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
bedLabelByElderId.set(row.elderId, {
|
||||||
|
room: row.roomName,
|
||||||
|
bed: row.bedCode,
|
||||||
|
bedId: row.bedId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return elderRows.map((row) => toElder(row, bedLabelByElderId.get(row.id)));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listOperationalRooms(organizationId?: string): Promise<Room[]> {
|
||||||
|
const database = getDatabase();
|
||||||
|
const [roomRows, bedRows] = await Promise.all([
|
||||||
|
database
|
||||||
|
.select()
|
||||||
|
.from(rooms)
|
||||||
|
.where(organizationId ? eq(rooms.organizationId, organizationId) : sql`true`)
|
||||||
|
.orderBy(desc(rooms.createdAt)),
|
||||||
|
database
|
||||||
|
.select()
|
||||||
|
.from(beds)
|
||||||
|
.where(organizationId ? eq(beds.organizationId, organizationId) : sql`true`),
|
||||||
|
]);
|
||||||
|
const bedCounts = new Map<string, { occupied: number; total: number }>();
|
||||||
|
for (const bed of bedRows) {
|
||||||
|
const current = bedCounts.get(bed.roomId) ?? { occupied: 0, total: 0 };
|
||||||
|
current.total += 1;
|
||||||
|
if (bed.status === "occupied") {
|
||||||
|
current.occupied += 1;
|
||||||
|
}
|
||||||
|
bedCounts.set(bed.roomId, current);
|
||||||
|
}
|
||||||
|
|
||||||
|
return roomRows.map((room) => {
|
||||||
|
const counts = bedCounts.get(room.id) ?? { occupied: 0, total: 0 };
|
||||||
|
return {
|
||||||
|
id: room.id,
|
||||||
|
organizationId: room.organizationId,
|
||||||
|
name: room.name,
|
||||||
|
code: room.code,
|
||||||
|
capacity: room.capacity,
|
||||||
|
status: room.status,
|
||||||
|
bedCount: counts.total,
|
||||||
|
occupiedBedCount: counts.occupied,
|
||||||
|
createdAt: iso(room.createdAt),
|
||||||
|
updatedAt: iso(room.updatedAt),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listOperationalBeds(organizationId?: string): Promise<FacilityBed[]> {
|
||||||
|
const database = getDatabase();
|
||||||
|
const bedRows = await database
|
||||||
|
.select({
|
||||||
|
bed: beds,
|
||||||
|
currentElderName: sql<string | null>`(
|
||||||
|
select ${elders.name}
|
||||||
|
from ${admissions}
|
||||||
|
inner join ${elders} on ${elders.id} = ${admissions.elderId}
|
||||||
|
where ${admissions.bedId} = ${beds.id} and ${admissions.status} = 'active'
|
||||||
|
order by ${admissions.admittedAt} desc
|
||||||
|
limit 1
|
||||||
|
)`,
|
||||||
|
roomName: rooms.name,
|
||||||
|
})
|
||||||
|
.from(beds)
|
||||||
|
.innerJoin(rooms, eq(rooms.id, beds.roomId))
|
||||||
|
.where(organizationId ? eq(beds.organizationId, organizationId) : sql`true`)
|
||||||
|
.orderBy(desc(beds.createdAt));
|
||||||
|
|
||||||
|
return bedRows.map((row) => ({
|
||||||
|
id: row.bed.id,
|
||||||
|
organizationId: row.bed.organizationId,
|
||||||
|
roomId: row.bed.roomId,
|
||||||
|
roomName: row.roomName,
|
||||||
|
code: row.bed.code,
|
||||||
|
status: row.bed.status,
|
||||||
|
notes: row.bed.notes,
|
||||||
|
currentElderName: row.currentElderName ?? undefined,
|
||||||
|
createdAt: iso(row.bed.createdAt),
|
||||||
|
updatedAt: iso(row.bed.updatedAt),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listOperationalAdmissions(organizationId?: string): Promise<Admission[]> {
|
||||||
|
const database = getDatabase();
|
||||||
|
const admissionRows = await database
|
||||||
|
.select({
|
||||||
|
admission: admissions,
|
||||||
|
bedCode: beds.code,
|
||||||
|
elderName: elders.name,
|
||||||
|
roomName: rooms.name,
|
||||||
|
})
|
||||||
|
.from(admissions)
|
||||||
|
.innerJoin(elders, eq(elders.id, admissions.elderId))
|
||||||
|
.innerJoin(beds, eq(beds.id, admissions.bedId))
|
||||||
|
.innerJoin(rooms, eq(rooms.id, beds.roomId))
|
||||||
|
.where(organizationId ? eq(admissions.organizationId, organizationId) : sql`true`)
|
||||||
|
.orderBy(desc(admissions.admittedAt));
|
||||||
|
|
||||||
|
return admissionRows.map((row) => ({
|
||||||
|
id: row.admission.id,
|
||||||
|
organizationId: row.admission.organizationId,
|
||||||
|
elderId: row.admission.elderId,
|
||||||
|
elderName: row.elderName,
|
||||||
|
bedId: row.admission.bedId,
|
||||||
|
bedCode: row.bedCode,
|
||||||
|
roomName: row.roomName,
|
||||||
|
status: row.admission.status,
|
||||||
|
admittedAt: iso(row.admission.admittedAt),
|
||||||
|
dischargedAt: row.admission.dischargedAt ? iso(row.admission.dischargedAt) : undefined,
|
||||||
|
notes: row.admission.notes,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listOperationalIncidents(organizationId?: string): Promise<SystemIncident[]> {
|
||||||
|
const database = getDatabase();
|
||||||
|
const incidentRows = await database
|
||||||
|
.select()
|
||||||
|
.from(systemIncidents)
|
||||||
|
.where(organizationId ? or(isNull(systemIncidents.organizationId), eq(systemIncidents.organizationId, organizationId)) : sql`true`)
|
||||||
|
.orderBy(desc(systemIncidents.createdAt));
|
||||||
|
|
||||||
|
return incidentRows.map((incident) => ({
|
||||||
|
id: incident.id,
|
||||||
|
organizationId: incident.organizationId ?? undefined,
|
||||||
|
severity: incident.severity,
|
||||||
|
status: incident.status,
|
||||||
|
title: incident.title,
|
||||||
|
description: incident.description,
|
||||||
|
source: incident.source,
|
||||||
|
createdAt: iso(incident.createdAt),
|
||||||
|
updatedAt: iso(incident.updatedAt),
|
||||||
|
}));
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user