feat: add system configuration platform
This commit is contained in:
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