feat: add system configuration platform
This commit is contained in:
@@ -1,21 +1,234 @@
|
||||
import { BedDouble } from "lucide-react";
|
||||
import { redirect } from "next/navigation";
|
||||
import { BedDouble, DoorOpen, History, Wrench } from "lucide-react";
|
||||
|
||||
import { ModulePage } from "@/modules/shared/components/ModulePage";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { getCurrentAuthContext } from "@/modules/core/server/auth";
|
||||
import { hasPermission } from "@/modules/core/server/permissions";
|
||||
import { readData } from "@/modules/core/server/store";
|
||||
|
||||
export default async function BedsPage(): Promise<React.ReactElement> {
|
||||
const context = await getCurrentAuthContext();
|
||||
if (!context) {
|
||||
redirect("/login");
|
||||
}
|
||||
|
||||
if (!hasPermission(context.permissions, "facility:read")) {
|
||||
redirect("/app/dashboard");
|
||||
}
|
||||
|
||||
const data = await readData();
|
||||
const organizationId = context.organization?.id;
|
||||
const rooms = organizationId ? data.rooms.filter((room) => room.organizationId === organizationId) : data.rooms;
|
||||
const beds = organizationId ? data.beds.filter((bed) => bed.organizationId === organizationId) : data.beds;
|
||||
const admissions = organizationId
|
||||
? data.admissions.filter((admission) => admission.organizationId === organizationId)
|
||||
: data.admissions;
|
||||
|
||||
const occupiedBeds = beds.filter((bed) => bed.status === "occupied").length;
|
||||
const maintenanceBeds = beds.filter((bed) => bed.status === "maintenance").length;
|
||||
const occupancyRate = beds.length > 0 ? Math.round((occupiedBeds / beds.length) * 100) : 0;
|
||||
|
||||
export default function BedsPage(): React.ReactElement {
|
||||
return (
|
||||
<ModulePage
|
||||
title="床位房间"
|
||||
eyebrow="房间与床位状态"
|
||||
description="维护楼栋、楼层、房间、床位编号和空闲、占用、维修状态流转。"
|
||||
icon={BedDouble}
|
||||
phase="一期"
|
||||
metrics={[
|
||||
{ label: "总床位", value: "154", detail: "护理区 96 张,康复区 58 张" },
|
||||
{ label: "占用率", value: "82%", detail: "低于阈值时支持入住调度" },
|
||||
{ label: "维修床位", value: "3", detail: "维修完成后恢复可用" },
|
||||
]}
|
||||
workflows={["维护楼栋与房间", "新增床位编号", "入住时占用床位", "退住或维修后释放床位"]}
|
||||
/>
|
||||
<div className="mx-auto flex w-full max-w-7xl flex-col gap-5">
|
||||
<section className="flex flex-col gap-4 border-b pb-5 lg:flex-row lg:items-end lg:justify-between">
|
||||
<div>
|
||||
<Badge variant="success">Facility + Admission</Badge>
|
||||
<h1 className="mt-3 text-3xl font-semibold tracking-normal">床位房间</h1>
|
||||
<p className="mt-2 text-sm text-muted-foreground">房间主数据、床位状态、当前占用和入住历史。</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0">
|
||||
<div>
|
||||
<CardDescription>房间</CardDescription>
|
||||
<CardTitle className="mt-2 text-3xl">{rooms.length}</CardTitle>
|
||||
</div>
|
||||
<DoorOpen className="size-5 text-primary" aria-hidden="true" />
|
||||
</CardHeader>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0">
|
||||
<div>
|
||||
<CardDescription>床位</CardDescription>
|
||||
<CardTitle className="mt-2 text-3xl">{beds.length}</CardTitle>
|
||||
</div>
|
||||
<BedDouble className="size-5 text-primary" aria-hidden="true" />
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
<p className="text-sm text-muted-foreground">占用率 {occupancyRate}%</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card className={maintenanceBeds > 0 ? "border-amber-200 bg-amber-50/70" : undefined}>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0">
|
||||
<div>
|
||||
<CardDescription className={maintenanceBeds > 0 ? "text-amber-700" : undefined}>维修床位</CardDescription>
|
||||
<CardTitle className={maintenanceBeds > 0 ? "mt-2 text-3xl text-amber-700" : "mt-2 text-3xl"}>
|
||||
{maintenanceBeds}
|
||||
</CardTitle>
|
||||
</div>
|
||||
<Wrench className={maintenanceBeds > 0 ? "size-5 text-amber-700" : "size-5 text-primary"} aria-hidden="true" />
|
||||
</CardHeader>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0">
|
||||
<div>
|
||||
<CardDescription>入住历史</CardDescription>
|
||||
<CardTitle className="mt-2 text-3xl">{admissions.length}</CardTitle>
|
||||
</div>
|
||||
<History className="size-5 text-primary" aria-hidden="true" />
|
||||
</CardHeader>
|
||||
</Card>
|
||||
</section>
|
||||
|
||||
<section className="grid gap-4 xl:grid-cols-[0.9fr_1.1fr]">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>房间台账</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="overflow-x-auto rounded-md border">
|
||||
<table className="w-full min-w-[620px] text-sm">
|
||||
<thead className="bg-secondary text-left text-xs text-muted-foreground">
|
||||
<tr>
|
||||
<th className="px-4 py-3 font-medium">房间</th>
|
||||
<th className="px-4 py-3 font-medium">编号</th>
|
||||
<th className="px-4 py-3 font-medium">容量</th>
|
||||
<th className="px-4 py-3 font-medium">床位</th>
|
||||
<th className="px-4 py-3 font-medium">状态</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y bg-card">
|
||||
{rooms.map((room) => (
|
||||
<tr key={room.id}>
|
||||
<td className="px-4 py-3 font-medium">{room.name}</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">{room.code}</td>
|
||||
<td className="px-4 py-3">{room.capacity}</td>
|
||||
<td className="px-4 py-3">
|
||||
{room.occupiedBedCount}/{room.bedCount}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<Badge variant={room.status === "active" ? "success" : "danger"}>{room.status}</Badge>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
{rooms.length === 0 ? (
|
||||
<tr>
|
||||
<td className="px-4 py-8 text-center text-muted-foreground" colSpan={5}>
|
||||
暂无房间,请通过 /api/facilities/rooms 创建
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>床位状态</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="overflow-x-auto rounded-md border">
|
||||
<table className="w-full min-w-[700px] text-sm">
|
||||
<thead className="bg-secondary text-left text-xs text-muted-foreground">
|
||||
<tr>
|
||||
<th className="px-4 py-3 font-medium">房间</th>
|
||||
<th className="px-4 py-3 font-medium">床位</th>
|
||||
<th className="px-4 py-3 font-medium">状态</th>
|
||||
<th className="px-4 py-3 font-medium">当前老人</th>
|
||||
<th className="px-4 py-3 font-medium">备注</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y bg-card">
|
||||
{beds.map((bed) => (
|
||||
<tr key={bed.id}>
|
||||
<td className="px-4 py-3">{bed.roomName}</td>
|
||||
<td className="px-4 py-3 font-medium">{bed.code}</td>
|
||||
<td className="px-4 py-3">
|
||||
<Badge
|
||||
variant={
|
||||
bed.status === "available"
|
||||
? "success"
|
||||
: bed.status === "occupied"
|
||||
? "secondary"
|
||||
: bed.status === "maintenance"
|
||||
? "warning"
|
||||
: "danger"
|
||||
}
|
||||
>
|
||||
{bed.status}
|
||||
</Badge>
|
||||
</td>
|
||||
<td className="px-4 py-3">{bed.currentElderName ?? "-"}</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">{bed.notes || "-"}</td>
|
||||
</tr>
|
||||
))}
|
||||
{beds.length === 0 ? (
|
||||
<tr>
|
||||
<td className="px-4 py-8 text-center text-muted-foreground" colSpan={5}>
|
||||
暂无床位,请通过 /api/facilities/beds 创建
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</section>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>入住与换床历史</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="overflow-x-auto rounded-md border">
|
||||
<table className="w-full min-w-[820px] text-sm">
|
||||
<thead className="bg-secondary text-left text-xs text-muted-foreground">
|
||||
<tr>
|
||||
<th className="px-4 py-3 font-medium">老人</th>
|
||||
<th className="px-4 py-3 font-medium">床位</th>
|
||||
<th className="px-4 py-3 font-medium">状态</th>
|
||||
<th className="px-4 py-3 font-medium">入住时间</th>
|
||||
<th className="px-4 py-3 font-medium">结束时间</th>
|
||||
<th className="px-4 py-3 font-medium">备注</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y bg-card">
|
||||
{admissions.map((admission) => (
|
||||
<tr key={admission.id}>
|
||||
<td className="px-4 py-3 font-medium">{admission.elderName}</td>
|
||||
<td className="px-4 py-3">
|
||||
{admission.roomName}-{admission.bedCode}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<Badge variant={admission.status === "active" ? "success" : "secondary"}>{admission.status}</Badge>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">
|
||||
{new Date(admission.admittedAt).toLocaleString("zh-CN")}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">
|
||||
{admission.dischargedAt ? new Date(admission.dischargedAt).toLocaleString("zh-CN") : "-"}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">{admission.notes || "-"}</td>
|
||||
</tr>
|
||||
))}
|
||||
{admissions.length === 0 ? (
|
||||
<tr>
|
||||
<td className="px-4 py-8 text-center text-muted-foreground" colSpan={6}>
|
||||
暂无入住历史
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ import { redirect } from "next/navigation";
|
||||
import { getBootstrapState, getCurrentAuthContext } from "@/modules/core/server/auth";
|
||||
import { AppShell } from "@/modules/shared/components/AppShell";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
type AppLayoutProps = {
|
||||
children: React.ReactNode;
|
||||
};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
import { getCurrentAuthContext, toPublicAccount } from "@/modules/core/server/auth";
|
||||
import { hasPermission, ROLE_DEFINITIONS } from "@/modules/core/server/permissions";
|
||||
import { getRoleDefinitions, hasPermission } from "@/modules/core/server/permissions";
|
||||
import { readData } from "@/modules/core/server/store";
|
||||
import { SettingsOverview } from "@/modules/settings/components/SettingsOverview";
|
||||
|
||||
@@ -11,16 +11,20 @@ export default async function SettingsPage(): Promise<React.ReactElement> {
|
||||
redirect("/login");
|
||||
}
|
||||
|
||||
if (!hasPermission(context.account.role, "account:read")) {
|
||||
if (!hasPermission(context.permissions, "account:read")) {
|
||||
redirect("/app/dashboard");
|
||||
}
|
||||
|
||||
const data = await readData();
|
||||
const roles = await getRoleDefinitions(context.organization?.id);
|
||||
return (
|
||||
<SettingsOverview
|
||||
accounts={data.accounts.map((account) => toPublicAccount(account))}
|
||||
roles={ROLE_DEFINITIONS}
|
||||
roles={roles}
|
||||
auditLogs={data.auditLogs.slice(0, 100)}
|
||||
organizations={data.organizations}
|
||||
memberships={data.memberships}
|
||||
incidents={data.incidents}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { AuthPanel } from "@/modules/auth/components/AuthPanel";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default function LoginPage(): React.ReactElement {
|
||||
return <AuthPanel mode="login" />;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { AuthPanel } from "@/modules/auth/components/AuthPanel";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default function RegisterPage(): React.ReactElement {
|
||||
return <AuthPanel mode="register" />;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { AuthPanel } from "@/modules/auth/components/AuthPanel";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default function SetupPage(): React.ReactElement {
|
||||
return <AuthPanel mode="setup" />;
|
||||
}
|
||||
|
||||
138
app/api/admissions/route.ts
Normal file
138
app/api/admissions/route.ts
Normal file
@@ -0,0 +1,138 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
|
||||
import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
|
||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||
import { requirePermission } from "@/modules/core/server/auth";
|
||||
import { getDatabase } from "@/modules/core/server/db";
|
||||
import { admissions, beds, elders } from "@/modules/core/server/schema";
|
||||
import { readData } from "@/modules/core/server/store";
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function readString(source: Record<string, unknown>, key: string): string {
|
||||
const value = source[key];
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
export async function GET(): Promise<Response> {
|
||||
const auth = await requirePermission("admission:read", {
|
||||
action: "admission.list",
|
||||
targetType: "admission",
|
||||
});
|
||||
|
||||
if (!auth.success) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const data = await readData();
|
||||
const organizationId = auth.context.organization?.id;
|
||||
return jsonSuccess("入住记录已加载", {
|
||||
admissions: organizationId
|
||||
? data.admissions.filter((admission) => admission.organizationId === organizationId)
|
||||
: data.admissions,
|
||||
});
|
||||
}
|
||||
|
||||
export async function POST(request: Request): Promise<Response> {
|
||||
const auth = await requirePermission("admission:manage", {
|
||||
action: "admission.create",
|
||||
targetType: "admission",
|
||||
});
|
||||
|
||||
if (!auth.success) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const organizationId = auth.context.organization?.id;
|
||||
if (!organizationId) {
|
||||
return jsonFailure("请选择机构后办理入住", 400);
|
||||
}
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
if (!isRecord(body)) {
|
||||
return jsonFailure("请求数据格式无效");
|
||||
}
|
||||
|
||||
const elderId = readString(body, "elderId");
|
||||
const bedId = readString(body, "bedId");
|
||||
if (!elderId || !bedId) {
|
||||
return jsonFailure("老人和床位不能为空");
|
||||
}
|
||||
|
||||
const database = getDatabase();
|
||||
const admission = await database.transaction(async (transaction) => {
|
||||
const elderRows = await transaction
|
||||
.select()
|
||||
.from(elders)
|
||||
.where(and(eq(elders.id, elderId), eq(elders.organizationId, organizationId)))
|
||||
.limit(1);
|
||||
const elder = elderRows[0];
|
||||
if (!elder) {
|
||||
throw new Error("老人档案不存在");
|
||||
}
|
||||
|
||||
const bedRows = await transaction
|
||||
.select()
|
||||
.from(beds)
|
||||
.where(and(eq(beds.id, bedId), eq(beds.organizationId, organizationId)))
|
||||
.limit(1);
|
||||
const bed = bedRows[0];
|
||||
if (!bed) {
|
||||
throw new Error("床位不存在");
|
||||
}
|
||||
if (bed.status !== "available") {
|
||||
throw new Error("床位不可分配");
|
||||
}
|
||||
|
||||
const activeAdmissions = await transaction
|
||||
.select()
|
||||
.from(admissions)
|
||||
.where(and(eq(admissions.elderId, elderId), eq(admissions.status, "active")));
|
||||
await Promise.all(
|
||||
activeAdmissions.map((activeAdmission) =>
|
||||
transaction
|
||||
.update(admissions)
|
||||
.set({ status: "transferred", dischargedAt: new Date(), updatedAt: new Date() })
|
||||
.where(eq(admissions.id, activeAdmission.id)),
|
||||
),
|
||||
);
|
||||
await Promise.all(
|
||||
activeAdmissions.map((activeAdmission) =>
|
||||
transaction.update(beds).set({ status: "available", updatedAt: new Date() }).where(eq(beds.id, activeAdmission.bedId)),
|
||||
),
|
||||
);
|
||||
|
||||
const rows = await transaction
|
||||
.insert(admissions)
|
||||
.values({
|
||||
organizationId,
|
||||
elderId,
|
||||
bedId,
|
||||
status: "active",
|
||||
notes: readString(body, "notes"),
|
||||
})
|
||||
.returning();
|
||||
const row = rows[0];
|
||||
if (!row) {
|
||||
throw new Error("入住记录创建失败");
|
||||
}
|
||||
|
||||
await transaction.update(beds).set({ status: "occupied", updatedAt: new Date() }).where(eq(beds.id, bedId));
|
||||
await transaction.update(elders).set({ status: "active", updatedAt: new Date() }).where(eq(elders.id, elderId));
|
||||
return row;
|
||||
});
|
||||
|
||||
await recordAuditLog({
|
||||
actor: auth.context.account,
|
||||
organizationId,
|
||||
action: "admission.create",
|
||||
targetType: "admission",
|
||||
targetId: admission.id,
|
||||
result: "success",
|
||||
reason: "办理入住/换床",
|
||||
});
|
||||
|
||||
return jsonSuccess("入住记录已创建", { admission }, 201);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { jsonSuccess } from "@/modules/core/server/api";
|
||||
import { listAuditLogs } from "@/modules/core/server/audit";
|
||||
import { requirePermission } from "@/modules/core/server/auth";
|
||||
import { readData } from "@/modules/core/server/store";
|
||||
|
||||
export async function GET(): Promise<Response> {
|
||||
const auth = await requirePermission("audit:read", {
|
||||
@@ -12,9 +12,8 @@ export async function GET(): Promise<Response> {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const data = await readData();
|
||||
const auditLogs = await listAuditLogs({ organizationId: auth.context.organization?.id, limit: 100 });
|
||||
return jsonSuccess("审计日志已加载", {
|
||||
auditLogs: data.auditLogs.slice(0, 100),
|
||||
auditLogs,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,16 @@
|
||||
import { getBootstrapState } from "@/modules/core/server/auth";
|
||||
import { jsonSuccess } from "@/modules/core/server/api";
|
||||
import { jsonFailure, jsonSuccess } from "@/modules/core/server/api";
|
||||
import { ensureSystemDefaults } from "@/modules/core/server/permissions";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(): Promise<Response> {
|
||||
const state = await getBootstrapState();
|
||||
return jsonSuccess("Bootstrap state loaded", state);
|
||||
try {
|
||||
await ensureSystemDefaults();
|
||||
const state = await getBootstrapState();
|
||||
return jsonSuccess("Bootstrap state loaded", state);
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : "系统初始化状态读取失败";
|
||||
return jsonFailure(reason, 503);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { createSessionRecord, normalizeEmail, setSessionCookie, toPublicAccount, verifyPassword } from "@/modules/core/server/auth";
|
||||
import { loginWithPassword, setSessionCookie } from "@/modules/core/server/auth";
|
||||
import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
|
||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||
import { updateData } from "@/modules/core/server/store";
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
@@ -18,45 +17,25 @@ export async function POST(request: Request): Promise<Response> {
|
||||
return jsonFailure("请求数据格式无效");
|
||||
}
|
||||
|
||||
const email = normalizeEmail(readString(body, "email"));
|
||||
const email = readString(body, "email");
|
||||
const password = readString(body, "password");
|
||||
|
||||
if (!email || !password) {
|
||||
return jsonFailure("邮箱和密码不能为空");
|
||||
}
|
||||
|
||||
const result = await updateData((data) => {
|
||||
const account = data.accounts.find((item) => item.email === email);
|
||||
if (!account || account.status !== "active" || !verifyPassword(password, account)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const session = createSessionRecord(account.id);
|
||||
data.sessions.push(session);
|
||||
return { account, session };
|
||||
});
|
||||
|
||||
if (!result) {
|
||||
try {
|
||||
const result = await loginWithPassword({ email, password });
|
||||
await setSessionCookie(result.session.id);
|
||||
return jsonSuccess("登录成功", { account: result.account });
|
||||
} catch (error) {
|
||||
await recordAuditLog({
|
||||
action: "auth.login",
|
||||
action: "account.login",
|
||||
targetType: "account",
|
||||
result: "failure",
|
||||
reason: `登录失败:${email}`,
|
||||
});
|
||||
return jsonFailure("账号或密码错误", 401);
|
||||
const reason = error instanceof Error ? error.message : "登录失败";
|
||||
return jsonFailure(reason, 401);
|
||||
}
|
||||
|
||||
await setSessionCookie(result.session.id);
|
||||
const account = toPublicAccount(result.account);
|
||||
await recordAuditLog({
|
||||
actor: account,
|
||||
action: "auth.login",
|
||||
targetType: "account",
|
||||
targetId: account.id,
|
||||
result: "success",
|
||||
reason: "登录成功",
|
||||
});
|
||||
|
||||
return jsonSuccess("登录成功", { account });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { createAccountRecord, createSessionRecord, normalizeEmail, setSessionCookie } from "@/modules/core/server/auth";
|
||||
import { createRegistration, setSessionCookie } from "@/modules/core/server/auth";
|
||||
import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
|
||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||
import { updateData } from "@/modules/core/server/store";
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
@@ -21,6 +19,7 @@ export async function POST(request: Request): Promise<Response> {
|
||||
const name = readString(body, "name");
|
||||
const email = readString(body, "email");
|
||||
const password = readString(body, "password");
|
||||
const organizationId = readString(body, "organizationId");
|
||||
|
||||
if (!name || !email || !password) {
|
||||
return jsonFailure("姓名、邮箱和密码不能为空");
|
||||
@@ -30,59 +29,18 @@ export async function POST(request: Request): Promise<Response> {
|
||||
return jsonFailure("密码至少需要6位");
|
||||
}
|
||||
|
||||
const normalizedEmail = normalizeEmail(email);
|
||||
const created = await updateData((data) => {
|
||||
const exists = data.accounts.some((account) => account.email === normalizedEmail);
|
||||
if (exists) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const account = createAccountRecord({
|
||||
try {
|
||||
const created = await createRegistration({
|
||||
name,
|
||||
email,
|
||||
password,
|
||||
role: "caregiver",
|
||||
organizationId: organizationId || undefined,
|
||||
});
|
||||
const session = createSessionRecord(account.id);
|
||||
|
||||
data.accounts.push(account);
|
||||
data.sessions.push(session);
|
||||
|
||||
return { account, session };
|
||||
});
|
||||
|
||||
if (!created) {
|
||||
return jsonFailure("账号已存在", 409);
|
||||
await setSessionCookie(created.session.id);
|
||||
return jsonSuccess("账号已创建", { account: created.account });
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : "账号创建失败";
|
||||
const status = reason === "账号已存在" ? 409 : 500;
|
||||
return jsonFailure(reason, status);
|
||||
}
|
||||
|
||||
await setSessionCookie(created.session.id);
|
||||
await recordAuditLog({
|
||||
actor: {
|
||||
id: created.account.id,
|
||||
name: created.account.name,
|
||||
email: created.account.email,
|
||||
role: created.account.role,
|
||||
status: created.account.status,
|
||||
createdAt: created.account.createdAt,
|
||||
updatedAt: created.account.updatedAt,
|
||||
},
|
||||
action: "account.register",
|
||||
targetType: "account",
|
||||
targetId: created.account.id,
|
||||
result: "success",
|
||||
reason: "创建照护人员账号",
|
||||
});
|
||||
|
||||
return jsonSuccess("账号已创建", {
|
||||
account: {
|
||||
id: created.account.id,
|
||||
name: created.account.name,
|
||||
email: created.account.email,
|
||||
role: created.account.role,
|
||||
status: created.account.status,
|
||||
createdAt: created.account.createdAt,
|
||||
updatedAt: created.account.updatedAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
import { getCurrentAuthContext } from "@/modules/core/server/auth";
|
||||
import { jsonSuccess } from "@/modules/core/server/api";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function GET(): Promise<Response> {
|
||||
const context = await getCurrentAuthContext();
|
||||
|
||||
return jsonSuccess("Session loaded", {
|
||||
account: context?.account ?? null,
|
||||
organization: context?.organization ?? null,
|
||||
membership: context?.membership ?? null,
|
||||
permissions: context?.permissions ?? [],
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { createAccountRecord, createSessionRecord, setSessionCookie } from "@/modules/core/server/auth";
|
||||
import { setSessionCookie, setupFirstPlatformAdmin } from "@/modules/core/server/auth";
|
||||
import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
|
||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||
import { updateData } from "@/modules/core/server/store";
|
||||
import { ensureSystemDefaults } from "@/modules/core/server/permissions";
|
||||
|
||||
function readString(source: Record<string, unknown>, key: string): string {
|
||||
const value = source[key];
|
||||
@@ -31,60 +30,14 @@ export async function POST(request: Request): Promise<Response> {
|
||||
return jsonFailure("密码至少需要6位");
|
||||
}
|
||||
|
||||
const created = await updateData((data) => {
|
||||
if (data.accounts.length > 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const account = createAccountRecord({
|
||||
name,
|
||||
email,
|
||||
password,
|
||||
role: "admin",
|
||||
organization,
|
||||
});
|
||||
const session = createSessionRecord(account.id);
|
||||
|
||||
data.accounts.push(account);
|
||||
data.sessions.push(session);
|
||||
|
||||
return { account, session };
|
||||
});
|
||||
|
||||
if (!created) {
|
||||
return jsonFailure("系统已完成初始化", 409);
|
||||
try {
|
||||
await ensureSystemDefaults();
|
||||
const created = await setupFirstPlatformAdmin({ organization, name, email, password });
|
||||
await setSessionCookie(created.session.id);
|
||||
return jsonSuccess("初始化完成", { account: created.account });
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : "初始化失败";
|
||||
const status = reason === "系统已完成初始化" ? 409 : 500;
|
||||
return jsonFailure(reason, status);
|
||||
}
|
||||
|
||||
await setSessionCookie(created.session.id);
|
||||
await recordAuditLog({
|
||||
actor: {
|
||||
id: created.account.id,
|
||||
name: created.account.name,
|
||||
email: created.account.email,
|
||||
role: created.account.role,
|
||||
organization: created.account.organization,
|
||||
status: created.account.status,
|
||||
createdAt: created.account.createdAt,
|
||||
updatedAt: created.account.updatedAt,
|
||||
},
|
||||
action: "account.setup",
|
||||
targetType: "account",
|
||||
targetId: created.account.id,
|
||||
result: "success",
|
||||
reason: "初始化管理员账号",
|
||||
});
|
||||
|
||||
return jsonSuccess("初始化完成", {
|
||||
account: {
|
||||
id: created.account.id,
|
||||
name: created.account.name,
|
||||
email: created.account.email,
|
||||
role: created.account.role,
|
||||
organization: created.account.organization,
|
||||
status: created.account.status,
|
||||
createdAt: created.account.createdAt,
|
||||
updatedAt: created.account.updatedAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { validateElderInput } from "@/modules/elders/types";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
|
||||
import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
|
||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||
import { requirePermission } from "@/modules/core/server/auth";
|
||||
import { updateData } from "@/modules/core/server/store";
|
||||
import { getDatabase } from "@/modules/core/server/db";
|
||||
import { admissions, beds, elders } from "@/modules/core/server/schema";
|
||||
import { validateElderInput } from "@/modules/elders/types";
|
||||
|
||||
type RouteContext = {
|
||||
params: Promise<{
|
||||
@@ -22,41 +25,66 @@ export async function PATCH(request: Request, context: RouteContext): Promise<Re
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const organizationId = auth.context.organization?.id;
|
||||
if (!organizationId) {
|
||||
return jsonFailure("请选择机构后更新老人档案", 400);
|
||||
}
|
||||
|
||||
const input = validateElderInput(await readJsonBody(request));
|
||||
if (!input.success) {
|
||||
return jsonFailure(input.reason);
|
||||
}
|
||||
|
||||
const updated = await updateData((data) => {
|
||||
const elder = data.elders.find((item) => item.id === id);
|
||||
if (!elder) {
|
||||
return null;
|
||||
}
|
||||
const database = getDatabase();
|
||||
const updated = await database
|
||||
.update(elders)
|
||||
.set({
|
||||
name: input.data.name,
|
||||
gender: input.data.gender,
|
||||
age: input.data.age,
|
||||
careLevel: input.data.careLevel,
|
||||
status: input.data.status,
|
||||
primaryContact: input.data.primaryContact,
|
||||
phone: input.data.phone,
|
||||
medicalNotes: input.data.medicalNotes,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(and(eq(elders.id, id), eq(elders.organizationId, organizationId)))
|
||||
.returning();
|
||||
const elder = updated[0];
|
||||
|
||||
const nextElder = {
|
||||
...elder,
|
||||
...input.data,
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
data.elders = data.elders.map((item) => (item.id === id ? nextElder : item));
|
||||
return nextElder;
|
||||
});
|
||||
|
||||
if (!updated) {
|
||||
if (!elder) {
|
||||
return jsonFailure("老人档案不存在", 404);
|
||||
}
|
||||
|
||||
await recordAuditLog({
|
||||
actor: auth.context.account,
|
||||
organizationId,
|
||||
action: "elder.update",
|
||||
targetType: "elder",
|
||||
targetId: updated.id,
|
||||
targetId: elder.id,
|
||||
result: "success",
|
||||
reason: `更新老人档案:${updated.name}`,
|
||||
reason: `更新老人档案:${elder.name}`,
|
||||
});
|
||||
|
||||
return jsonSuccess("老人档案已更新", { elder: updated });
|
||||
return jsonSuccess("老人档案已更新", {
|
||||
elder: {
|
||||
id: elder.id,
|
||||
organizationId: elder.organizationId,
|
||||
name: elder.name,
|
||||
gender: elder.gender,
|
||||
age: elder.age,
|
||||
careLevel: elder.careLevel,
|
||||
room: "",
|
||||
bed: "",
|
||||
status: elder.status,
|
||||
primaryContact: elder.primaryContact,
|
||||
phone: elder.phone,
|
||||
medicalNotes: elder.medicalNotes,
|
||||
createdAt: elder.createdAt.toISOString(),
|
||||
updatedAt: elder.updatedAt.toISOString(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function DELETE(_request: Request, context: RouteContext): Promise<Response> {
|
||||
@@ -71,13 +99,43 @@ export async function DELETE(_request: Request, context: RouteContext): Promise<
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const deleted = await updateData((data) => {
|
||||
const elder = data.elders.find((item) => item.id === id);
|
||||
const organizationId = auth.context.organization?.id;
|
||||
if (!organizationId) {
|
||||
return jsonFailure("请选择机构后删除老人档案", 400);
|
||||
}
|
||||
|
||||
const database = getDatabase();
|
||||
const deleted = await database.transaction(async (transaction) => {
|
||||
const elderRows = await transaction
|
||||
.select()
|
||||
.from(elders)
|
||||
.where(and(eq(elders.id, id), eq(elders.organizationId, organizationId)))
|
||||
.limit(1);
|
||||
const elder = elderRows[0];
|
||||
if (!elder) {
|
||||
return null;
|
||||
}
|
||||
|
||||
data.elders = data.elders.filter((item) => item.id !== id);
|
||||
const activeAdmissions = await transaction
|
||||
.select()
|
||||
.from(admissions)
|
||||
.where(and(eq(admissions.elderId, id), eq(admissions.status, "active")));
|
||||
|
||||
await Promise.all(
|
||||
activeAdmissions.map((admission) =>
|
||||
transaction
|
||||
.update(admissions)
|
||||
.set({ status: "discharged", dischargedAt: new Date(), updatedAt: new Date() })
|
||||
.where(eq(admissions.id, admission.id)),
|
||||
),
|
||||
);
|
||||
await Promise.all(
|
||||
activeAdmissions.map((admission) =>
|
||||
transaction.update(beds).set({ status: "available", updatedAt: new Date() }).where(eq(beds.id, admission.bedId)),
|
||||
),
|
||||
);
|
||||
|
||||
await transaction.delete(elders).where(eq(elders.id, id));
|
||||
return elder;
|
||||
});
|
||||
|
||||
@@ -87,6 +145,7 @@ export async function DELETE(_request: Request, context: RouteContext): Promise<
|
||||
|
||||
await recordAuditLog({
|
||||
actor: auth.context.account,
|
||||
organizationId,
|
||||
action: "elder.delete",
|
||||
targetType: "elder",
|
||||
targetId: deleted.id,
|
||||
@@ -94,6 +153,5 @@ export async function DELETE(_request: Request, context: RouteContext): Promise<
|
||||
reason: `删除老人档案:${deleted.name}`,
|
||||
});
|
||||
|
||||
return jsonSuccess("老人档案已删除", { elder: deleted });
|
||||
return jsonSuccess("老人档案已删除", { elder: { id: deleted.id, name: deleted.name } });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,34 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import type { Elder } from "@/modules/elders/types";
|
||||
import { validateElderInput } from "@/modules/elders/types";
|
||||
import { and, desc, eq } from "drizzle-orm";
|
||||
|
||||
import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
|
||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||
import { requirePermission } from "@/modules/core/server/auth";
|
||||
import { readData, updateData } from "@/modules/core/server/store";
|
||||
import { getDatabase } from "@/modules/core/server/db";
|
||||
import { admissions, beds, elders } from "@/modules/core/server/schema";
|
||||
import { validateElderInput } from "@/modules/elders/types";
|
||||
import type { Elder } from "@/modules/elders/types";
|
||||
|
||||
function toElder(row: typeof elders.$inferSelect, bedLabel?: { room: string; bed: string; bedId: string }): Elder {
|
||||
return {
|
||||
id: row.id,
|
||||
organizationId: row.organizationId,
|
||||
name: row.name,
|
||||
gender: row.gender,
|
||||
age: row.age,
|
||||
careLevel: row.careLevel,
|
||||
room: bedLabel?.room ?? "",
|
||||
bed: bedLabel?.bed ?? "",
|
||||
bedId: bedLabel?.bedId,
|
||||
status: row.status,
|
||||
primaryContact: row.primaryContact,
|
||||
phone: row.phone,
|
||||
medicalNotes: row.medicalNotes,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
updatedAt: row.updatedAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
export async function GET(): Promise<Response> {
|
||||
const auth = await requirePermission("elder:read", {
|
||||
@@ -17,8 +40,19 @@ export async function GET(): Promise<Response> {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const data = await readData();
|
||||
return jsonSuccess("老人档案已加载", { elders: data.elders });
|
||||
const organizationId = auth.context.organization?.id;
|
||||
if (!organizationId) {
|
||||
return jsonFailure("请选择机构后查看老人档案", 400);
|
||||
}
|
||||
|
||||
const database = getDatabase();
|
||||
const rows = await database
|
||||
.select()
|
||||
.from(elders)
|
||||
.where(eq(elders.organizationId, organizationId))
|
||||
.orderBy(desc(elders.createdAt));
|
||||
|
||||
return jsonSuccess("老人档案已加载", { elders: rows.map((row) => toElder(row)) });
|
||||
}
|
||||
|
||||
export async function POST(request: Request): Promise<Response> {
|
||||
@@ -31,24 +65,72 @@ export async function POST(request: Request): Promise<Response> {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const organizationId = auth.context.organization?.id;
|
||||
if (!organizationId) {
|
||||
return jsonFailure("请选择机构后新增老人档案", 400);
|
||||
}
|
||||
|
||||
const input = validateElderInput(await readJsonBody(request));
|
||||
if (!input.success) {
|
||||
return jsonFailure(input.reason);
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
const elder: Elder = {
|
||||
...input.data,
|
||||
id: randomUUID(),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
const database = getDatabase();
|
||||
const created = await database.transaction(async (transaction) => {
|
||||
const elderId = randomUUID();
|
||||
const elderRows = await transaction
|
||||
.insert(elders)
|
||||
.values({
|
||||
id: elderId,
|
||||
organizationId,
|
||||
name: input.data.name,
|
||||
gender: input.data.gender,
|
||||
age: input.data.age,
|
||||
careLevel: input.data.careLevel,
|
||||
status: input.data.status,
|
||||
primaryContact: input.data.primaryContact,
|
||||
phone: input.data.phone,
|
||||
medicalNotes: input.data.medicalNotes,
|
||||
})
|
||||
.returning();
|
||||
const elder = elderRows[0];
|
||||
if (!elder) {
|
||||
throw new Error("老人档案创建失败");
|
||||
}
|
||||
|
||||
await updateData((data) => {
|
||||
data.elders = [elder, ...data.elders];
|
||||
if (input.data.bedId) {
|
||||
const bedRows = await transaction
|
||||
.select()
|
||||
.from(beds)
|
||||
.where(and(eq(beds.id, input.data.bedId), eq(beds.organizationId, organizationId)))
|
||||
.limit(1);
|
||||
const bed = bedRows[0];
|
||||
if (!bed) {
|
||||
throw new Error("床位不存在");
|
||||
}
|
||||
if (bed.status !== "available") {
|
||||
throw new Error("床位不可分配");
|
||||
}
|
||||
|
||||
await transaction
|
||||
.insert(admissions)
|
||||
.values({
|
||||
organizationId,
|
||||
elderId: elder.id,
|
||||
bedId: bed.id,
|
||||
status: "active",
|
||||
notes: "新增档案时办理入住",
|
||||
});
|
||||
await transaction.update(beds).set({ status: "occupied", updatedAt: new Date() }).where(eq(beds.id, bed.id));
|
||||
}
|
||||
|
||||
return elder;
|
||||
});
|
||||
|
||||
const elder = toElder(created);
|
||||
await recordAuditLog({
|
||||
actor: auth.context.account,
|
||||
organizationId,
|
||||
action: "elder.create",
|
||||
targetType: "elder",
|
||||
targetId: elder.id,
|
||||
@@ -58,4 +140,3 @@ export async function POST(request: Request): Promise<Response> {
|
||||
|
||||
return jsonSuccess("老人档案已创建", { elder }, 201);
|
||||
}
|
||||
|
||||
|
||||
106
app/api/facilities/beds/route.ts
Normal file
106
app/api/facilities/beds/route.ts
Normal file
@@ -0,0 +1,106 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
|
||||
import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
|
||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||
import { requirePermission } from "@/modules/core/server/auth";
|
||||
import { getDatabase } from "@/modules/core/server/db";
|
||||
import { beds, rooms } from "@/modules/core/server/schema";
|
||||
import { readData } from "@/modules/core/server/store";
|
||||
import type { BedStatus } from "@/modules/core/types";
|
||||
|
||||
const BED_STATUS_VALUES: BedStatus[] = ["available", "occupied", "maintenance", "disabled"];
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function readString(source: Record<string, unknown>, key: string): string {
|
||||
const value = source[key];
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
function readBedStatus(value: string): BedStatus {
|
||||
return BED_STATUS_VALUES.find((status) => status === value) ?? "available";
|
||||
}
|
||||
|
||||
export async function GET(): Promise<Response> {
|
||||
const auth = await requirePermission("facility:read", {
|
||||
action: "bed.list",
|
||||
targetType: "bed",
|
||||
});
|
||||
|
||||
if (!auth.success) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const data = await readData();
|
||||
const organizationId = auth.context.organization?.id;
|
||||
return jsonSuccess("床位列表已加载", {
|
||||
beds: organizationId ? data.beds.filter((bed) => bed.organizationId === organizationId) : data.beds,
|
||||
});
|
||||
}
|
||||
|
||||
export async function POST(request: Request): Promise<Response> {
|
||||
const auth = await requirePermission("facility:manage", {
|
||||
action: "bed.create",
|
||||
targetType: "bed",
|
||||
});
|
||||
|
||||
if (!auth.success) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const organizationId = auth.context.organization?.id;
|
||||
if (!organizationId) {
|
||||
return jsonFailure("请选择机构后维护床位", 400);
|
||||
}
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
if (!isRecord(body)) {
|
||||
return jsonFailure("请求数据格式无效");
|
||||
}
|
||||
|
||||
const roomId = readString(body, "roomId");
|
||||
const code = readString(body, "code");
|
||||
if (!roomId || !code) {
|
||||
return jsonFailure("房间和床位编号不能为空");
|
||||
}
|
||||
|
||||
const database = getDatabase();
|
||||
const roomRows = await database
|
||||
.select()
|
||||
.from(rooms)
|
||||
.where(and(eq(rooms.id, roomId), eq(rooms.organizationId, organizationId)))
|
||||
.limit(1);
|
||||
const room = roomRows[0];
|
||||
if (!room) {
|
||||
return jsonFailure("房间不存在", 404);
|
||||
}
|
||||
|
||||
const createdRows = await database
|
||||
.insert(beds)
|
||||
.values({
|
||||
organizationId,
|
||||
roomId,
|
||||
code,
|
||||
status: readBedStatus(readString(body, "status")),
|
||||
notes: readString(body, "notes"),
|
||||
})
|
||||
.returning();
|
||||
const bed = createdRows[0];
|
||||
if (!bed) {
|
||||
return jsonFailure("床位创建失败", 500);
|
||||
}
|
||||
|
||||
await recordAuditLog({
|
||||
actor: auth.context.account,
|
||||
organizationId,
|
||||
action: "bed.create",
|
||||
targetType: "bed",
|
||||
targetId: bed.id,
|
||||
result: "success",
|
||||
reason: `新增床位:${room.name}-${bed.code}`,
|
||||
});
|
||||
|
||||
return jsonSuccess("床位已创建", { bed }, 201);
|
||||
}
|
||||
140
app/api/facilities/rooms/route.ts
Normal file
140
app/api/facilities/rooms/route.ts
Normal file
@@ -0,0 +1,140 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
|
||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||
import { requirePermission } from "@/modules/core/server/auth";
|
||||
import { getDatabase } from "@/modules/core/server/db";
|
||||
import { campuses, buildings, floors, rooms } from "@/modules/core/server/schema";
|
||||
import { readData } from "@/modules/core/server/store";
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function readString(source: Record<string, unknown>, key: string): string {
|
||||
const value = source[key];
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
function readPositiveNumber(source: Record<string, unknown>, key: string, fallback: number): number {
|
||||
const value = source[key];
|
||||
const numeric = typeof value === "number" ? value : Number(value);
|
||||
return Number.isInteger(numeric) && numeric > 0 ? numeric : fallback;
|
||||
}
|
||||
|
||||
export async function GET(): Promise<Response> {
|
||||
const auth = await requirePermission("facility:read", {
|
||||
action: "room.list",
|
||||
targetType: "room",
|
||||
});
|
||||
|
||||
if (!auth.success) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const data = await readData();
|
||||
const organizationId = auth.context.organization?.id;
|
||||
return jsonSuccess("房间列表已加载", {
|
||||
rooms: organizationId ? data.rooms.filter((room) => room.organizationId === organizationId) : data.rooms,
|
||||
});
|
||||
}
|
||||
|
||||
export async function POST(request: Request): Promise<Response> {
|
||||
const auth = await requirePermission("facility:manage", {
|
||||
action: "room.create",
|
||||
targetType: "room",
|
||||
});
|
||||
|
||||
if (!auth.success) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const organizationId = auth.context.organization?.id;
|
||||
if (!organizationId) {
|
||||
return jsonFailure("请选择机构后维护房间", 400);
|
||||
}
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
if (!isRecord(body)) {
|
||||
return jsonFailure("请求数据格式无效");
|
||||
}
|
||||
|
||||
const roomName = readString(body, "name");
|
||||
const roomCode = readString(body, "code");
|
||||
if (!roomName || !roomCode) {
|
||||
return jsonFailure("房间名称和编号不能为空");
|
||||
}
|
||||
|
||||
const database = getDatabase();
|
||||
const createdRows = await database.transaction(async (transaction) => {
|
||||
const campusRows = await transaction.select().from(campuses).where(eq(campuses.organizationId, organizationId)).limit(1);
|
||||
const campus =
|
||||
campusRows[0] ??
|
||||
(
|
||||
await transaction
|
||||
.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) {
|
||||
throw new Error("楼层初始化失败");
|
||||
}
|
||||
|
||||
return await transaction
|
||||
.insert(rooms)
|
||||
.values({
|
||||
id: randomUUID(),
|
||||
organizationId,
|
||||
floorId: floor.id,
|
||||
name: roomName,
|
||||
code: roomCode,
|
||||
capacity: readPositiveNumber(body, "capacity", 1),
|
||||
})
|
||||
.returning();
|
||||
});
|
||||
|
||||
const room = createdRows[0];
|
||||
if (!room) {
|
||||
return jsonFailure("房间创建失败", 500);
|
||||
}
|
||||
|
||||
await recordAuditLog({
|
||||
actor: auth.context.account,
|
||||
organizationId,
|
||||
action: "room.create",
|
||||
targetType: "room",
|
||||
targetId: room.id,
|
||||
result: "success",
|
||||
reason: `新增房间:${room.name}`,
|
||||
});
|
||||
|
||||
return jsonSuccess("房间已创建", { room }, 201);
|
||||
}
|
||||
@@ -1,7 +1,22 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
|
||||
import { jsonSuccess } from "@/modules/core/server/api";
|
||||
import { requirePermission, toPublicAccount } from "@/modules/core/server/auth";
|
||||
import { hashPassword, normalizeEmail, requirePermission, toPublicAccount } from "@/modules/core/server/auth";
|
||||
import { jsonFailure, readJsonBody } from "@/modules/core/server/api";
|
||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||
import { getDatabase } from "@/modules/core/server/db";
|
||||
import { accounts, memberships, organizations, roles } from "@/modules/core/server/schema";
|
||||
import { readData } from "@/modules/core/server/store";
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function readString(source: Record<string, unknown>, key: string): string {
|
||||
const value = source[key];
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
export async function GET(): Promise<Response> {
|
||||
const auth = await requirePermission("account:read", {
|
||||
action: "account.list",
|
||||
@@ -18,3 +33,93 @@ export async function GET(): Promise<Response> {
|
||||
});
|
||||
}
|
||||
|
||||
export async function POST(request: Request): Promise<Response> {
|
||||
const auth = await requirePermission("account:manage", {
|
||||
action: "account.create",
|
||||
targetType: "account",
|
||||
});
|
||||
|
||||
if (!auth.success) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
if (!isRecord(body)) {
|
||||
return jsonFailure("请求数据格式无效");
|
||||
}
|
||||
|
||||
const name = readString(body, "name");
|
||||
const email = readString(body, "email");
|
||||
const password = readString(body, "password");
|
||||
const roleId = readString(body, "roleId");
|
||||
const organizationId = readString(body, "organizationId") || auth.context.organization?.id;
|
||||
|
||||
if (!name || !email || !password || !roleId || !organizationId) {
|
||||
return jsonFailure("姓名、邮箱、密码、机构和角色不能为空");
|
||||
}
|
||||
|
||||
const database = getDatabase();
|
||||
const passwordHash = hashPassword(password);
|
||||
const created = await database.transaction(async (transaction) => {
|
||||
const organizationRows = await transaction.select().from(organizations).where(eq(organizations.id, organizationId)).limit(1);
|
||||
const organization = organizationRows[0];
|
||||
if (!organization) {
|
||||
throw new Error("机构不存在");
|
||||
}
|
||||
|
||||
const roleRows = await transaction
|
||||
.select()
|
||||
.from(roles)
|
||||
.where(and(eq(roles.id, roleId), eq(roles.organizationId, organizationId)))
|
||||
.limit(1);
|
||||
const role = roleRows[0];
|
||||
if (!role) {
|
||||
throw new Error("角色不存在");
|
||||
}
|
||||
|
||||
const accountRows = await transaction
|
||||
.insert(accounts)
|
||||
.values({
|
||||
name,
|
||||
email: normalizeEmail(email),
|
||||
passwordHash: passwordHash.hash,
|
||||
passwordSalt: passwordHash.salt,
|
||||
status: "active",
|
||||
})
|
||||
.returning();
|
||||
const account = accountRows[0];
|
||||
if (!account) {
|
||||
throw new Error("账号创建失败");
|
||||
}
|
||||
|
||||
await transaction.insert(memberships).values({
|
||||
accountId: account.id,
|
||||
organizationId,
|
||||
roleId,
|
||||
status: "active",
|
||||
});
|
||||
|
||||
return { account, organization, role };
|
||||
});
|
||||
|
||||
await recordAuditLog({
|
||||
actor: auth.context.account,
|
||||
organizationId,
|
||||
action: "account.create",
|
||||
targetType: "account",
|
||||
targetId: created.account.id,
|
||||
result: "success",
|
||||
reason: `创建机构用户:${created.account.email}`,
|
||||
});
|
||||
|
||||
return jsonSuccess("账号已创建", {
|
||||
account: toPublicAccount(created.account, created.role.key, {
|
||||
id: created.organization.id,
|
||||
name: created.organization.name,
|
||||
slug: created.organization.slug,
|
||||
status: created.organization.status,
|
||||
createdAt: created.organization.createdAt.toISOString(),
|
||||
updatedAt: created.organization.updatedAt.toISOString(),
|
||||
}),
|
||||
}, 201);
|
||||
}
|
||||
|
||||
16
app/api/settings/permissions/route.ts
Normal file
16
app/api/settings/permissions/route.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { jsonSuccess } from "@/modules/core/server/api";
|
||||
import { requirePermission } from "@/modules/core/server/auth";
|
||||
import { PERMISSION_DEFINITIONS } from "@/modules/core/server/permissions";
|
||||
|
||||
export async function GET(): Promise<Response> {
|
||||
const auth = await requirePermission("permission:read", {
|
||||
action: "permission.list",
|
||||
targetType: "permission",
|
||||
});
|
||||
|
||||
if (!auth.success) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
return jsonSuccess("权限点已加载", { permissions: PERMISSION_DEFINITIONS });
|
||||
}
|
||||
@@ -1,9 +1,32 @@
|
||||
import { jsonSuccess } from "@/modules/core/server/api";
|
||||
import { jsonFailure, readJsonBody } from "@/modules/core/server/api";
|
||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||
import { requirePermission } from "@/modules/core/server/auth";
|
||||
import { ROLE_DEFINITIONS } from "@/modules/core/server/permissions";
|
||||
import { getDatabase } from "@/modules/core/server/db";
|
||||
import { getRoleDefinitions } from "@/modules/core/server/permissions";
|
||||
import { rolePermissions, roles } from "@/modules/core/server/schema";
|
||||
import type { Permission } from "@/modules/core/types";
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function readString(source: Record<string, unknown>, key: string): string {
|
||||
const value = source[key];
|
||||
return typeof value === "string" ? value.trim() : "";
|
||||
}
|
||||
|
||||
function readPermissionArray(source: Record<string, unknown>): Permission[] {
|
||||
const value = source.permissions;
|
||||
if (!Array.isArray(value)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return value.filter((item): item is Permission => typeof item === "string");
|
||||
}
|
||||
|
||||
export async function GET(): Promise<Response> {
|
||||
const auth = await requirePermission("account:read", {
|
||||
const auth = await requirePermission("role:read", {
|
||||
action: "role.list",
|
||||
targetType: "role",
|
||||
});
|
||||
@@ -12,6 +35,85 @@ export async function GET(): Promise<Response> {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
return jsonSuccess("角色列表已加载", { roles: ROLE_DEFINITIONS });
|
||||
const roles = await getRoleDefinitions(auth.context.organization?.id);
|
||||
return jsonSuccess("角色列表已加载", { roles });
|
||||
}
|
||||
|
||||
export async function POST(request: Request): Promise<Response> {
|
||||
const auth = await requirePermission("role:manage", {
|
||||
action: "role.create",
|
||||
targetType: "role",
|
||||
});
|
||||
|
||||
if (!auth.success) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const organizationId = auth.context.organization?.id;
|
||||
if (!organizationId) {
|
||||
return jsonFailure("请选择机构后创建角色", 400);
|
||||
}
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
if (!isRecord(body)) {
|
||||
return jsonFailure("请求数据格式无效");
|
||||
}
|
||||
|
||||
const label = readString(body, "label");
|
||||
const key = readString(body, "key") || label.toLowerCase().replace(/[^a-z0-9]+/g, "_");
|
||||
const description = readString(body, "description");
|
||||
const permissions = readPermissionArray(body);
|
||||
|
||||
if (!label || !key) {
|
||||
return jsonFailure("角色名称不能为空");
|
||||
}
|
||||
|
||||
const database = getDatabase();
|
||||
const created = await database.transaction(async (transaction) => {
|
||||
const rows = await transaction
|
||||
.insert(roles)
|
||||
.values({
|
||||
key,
|
||||
organizationId,
|
||||
scope: "organization",
|
||||
label,
|
||||
description: description || "机构自定义角色",
|
||||
isSystem: false,
|
||||
isEnabled: true,
|
||||
})
|
||||
.returning();
|
||||
const role = rows[0];
|
||||
if (!role) {
|
||||
throw new Error("角色创建失败");
|
||||
}
|
||||
|
||||
if (permissions.length > 0) {
|
||||
await transaction.insert(rolePermissions).values(
|
||||
permissions.map((permissionId) => ({
|
||||
roleId: role.id,
|
||||
permissionId,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
return role;
|
||||
});
|
||||
|
||||
await recordAuditLog({
|
||||
actor: auth.context.account,
|
||||
organizationId,
|
||||
action: "role.create",
|
||||
targetType: "role",
|
||||
targetId: created.id,
|
||||
result: "success",
|
||||
reason: `创建自定义角色:${created.label}`,
|
||||
});
|
||||
|
||||
const roleRows = await getRoleDefinitions(organizationId);
|
||||
const role = roleRows.find((item) => item.id === created.id);
|
||||
if (!role) {
|
||||
return jsonFailure("角色创建后读取失败", 500);
|
||||
}
|
||||
|
||||
return jsonSuccess("角色已创建", { role }, 201);
|
||||
}
|
||||
|
||||
85
app/api/system/incidents/[id]/route.ts
Normal file
85
app/api/system/incidents/[id]/route.ts
Normal file
@@ -0,0 +1,85 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
|
||||
import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
|
||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||
import { requirePermission } from "@/modules/core/server/auth";
|
||||
import { getDatabase } from "@/modules/core/server/db";
|
||||
import { systemIncidents } from "@/modules/core/server/schema";
|
||||
import type { IncidentStatus } from "@/modules/core/types";
|
||||
|
||||
type RouteContext = {
|
||||
params: Promise<{
|
||||
id: string;
|
||||
}>;
|
||||
};
|
||||
|
||||
const INCIDENT_STATUSES: IncidentStatus[] = ["open", "acknowledged", "resolved", "closed"];
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function readStatus(value: unknown): IncidentStatus | null {
|
||||
if (typeof value !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
return INCIDENT_STATUSES.find((status) => status === value) ?? null;
|
||||
}
|
||||
|
||||
export async function PATCH(request: Request, context: RouteContext): Promise<Response> {
|
||||
const { id } = await context.params;
|
||||
const auth = await requirePermission("incident:manage", {
|
||||
action: "incident.update",
|
||||
targetType: "incident",
|
||||
targetId: id,
|
||||
});
|
||||
|
||||
if (!auth.success) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const body = await readJsonBody(request);
|
||||
if (!isRecord(body)) {
|
||||
return jsonFailure("请求数据格式无效");
|
||||
}
|
||||
|
||||
const status = readStatus(body.status);
|
||||
if (!status) {
|
||||
return jsonFailure("故障状态无效");
|
||||
}
|
||||
|
||||
const database = getDatabase();
|
||||
const organizationId = auth.context.organization?.id;
|
||||
const updateValues = {
|
||||
status,
|
||||
updatedAt: new Date(),
|
||||
acknowledgedByAccountId: status === "acknowledged" ? auth.context.account.id : undefined,
|
||||
acknowledgedAt: status === "acknowledged" ? new Date() : undefined,
|
||||
resolvedByAccountId: status === "resolved" || status === "closed" ? auth.context.account.id : undefined,
|
||||
resolvedAt: status === "resolved" || status === "closed" ? new Date() : undefined,
|
||||
};
|
||||
const rows = organizationId
|
||||
? await database
|
||||
.update(systemIncidents)
|
||||
.set(updateValues)
|
||||
.where(and(eq(systemIncidents.id, id), eq(systemIncidents.organizationId, organizationId)))
|
||||
.returning()
|
||||
: await database.update(systemIncidents).set(updateValues).where(eq(systemIncidents.id, id)).returning();
|
||||
const incident = rows[0];
|
||||
if (!incident) {
|
||||
return jsonFailure("故障事件不存在", 404);
|
||||
}
|
||||
|
||||
await recordAuditLog({
|
||||
actor: auth.context.account,
|
||||
organizationId: incident.organizationId ?? undefined,
|
||||
action: "incident.update",
|
||||
targetType: "incident",
|
||||
targetId: incident.id,
|
||||
result: "success",
|
||||
reason: `故障状态更新为:${status}`,
|
||||
});
|
||||
|
||||
return jsonSuccess("故障事件已更新", { incident });
|
||||
}
|
||||
49
app/api/system/status/route.ts
Normal file
49
app/api/system/status/route.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { desc } from "drizzle-orm";
|
||||
|
||||
import { jsonSuccess } from "@/modules/core/server/api";
|
||||
import { requirePermission } from "@/modules/core/server/auth";
|
||||
import { checkDatabaseConnection, getDatabase } from "@/modules/core/server/db";
|
||||
import { accounts, beds, elders, organizations, systemIncidents } from "@/modules/core/server/schema";
|
||||
|
||||
export async function GET(): Promise<Response> {
|
||||
const auth = await requirePermission("incident:read", {
|
||||
action: "system.status",
|
||||
targetType: "systemStatus",
|
||||
});
|
||||
|
||||
if (!auth.success) {
|
||||
return auth.response;
|
||||
}
|
||||
|
||||
const health = await checkDatabaseConnection();
|
||||
const database = getDatabase();
|
||||
const [organizationRows, accountRows, elderRows, bedRows, incidentRows] = await Promise.all([
|
||||
database.select({ id: organizations.id }).from(organizations),
|
||||
database.select({ id: accounts.id }).from(accounts),
|
||||
database.select({ id: elders.id }).from(elders),
|
||||
database.select({ id: beds.id }).from(beds),
|
||||
database.select().from(systemIncidents).orderBy(desc(systemIncidents.createdAt)).limit(20),
|
||||
]);
|
||||
|
||||
return jsonSuccess("系统运行状态已加载", {
|
||||
health,
|
||||
metrics: {
|
||||
organizations: organizationRows.length,
|
||||
accounts: accountRows.length,
|
||||
elders: elderRows.length,
|
||||
beds: bedRows.length,
|
||||
incidents: incidentRows.length,
|
||||
},
|
||||
incidents: incidentRows.map((incident) => ({
|
||||
id: incident.id,
|
||||
organizationId: incident.organizationId,
|
||||
severity: incident.severity,
|
||||
status: incident.status,
|
||||
title: incident.title,
|
||||
description: incident.description,
|
||||
source: incident.source,
|
||||
createdAt: incident.createdAt.toISOString(),
|
||||
updatedAt: incident.updatedAt.toISOString(),
|
||||
})),
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user