feat: add system configuration platform
This commit is contained in:
58
.trellis/spec/backend/deployment.md
Normal file
58
.trellis/spec/backend/deployment.md
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
# Deployment Targets
|
||||||
|
|
||||||
|
## Scenario: Wulanchabu Server Deployment
|
||||||
|
|
||||||
|
### 1. Scope / Trigger
|
||||||
|
|
||||||
|
- Trigger: the user asks to deploy this project.
|
||||||
|
- Default target: Wulanchabu server, reached through SSH host alias `wlcb1`.
|
||||||
|
- This preference is project-specific and should be used for future deployment requests unless the user explicitly names another target.
|
||||||
|
|
||||||
|
### 2. Signatures
|
||||||
|
|
||||||
|
- SSH entrypoint: `ssh wlcb1`
|
||||||
|
- Repository remote: push code to `origin` before deploying.
|
||||||
|
- Database migration command: `pnpm db:migrate`
|
||||||
|
- Production build command: `pnpm build`
|
||||||
|
|
||||||
|
### 3. Contracts
|
||||||
|
|
||||||
|
- Required environment on the server:
|
||||||
|
- `DATABASE_URL` must point to the production PostgreSQL database.
|
||||||
|
- Node.js and pnpm must be available.
|
||||||
|
- Deployment should run from the server-side checkout for this repository.
|
||||||
|
- Code should be pushed to `origin` before server deployment so `wlcb1` deploys committed source.
|
||||||
|
|
||||||
|
### 4. Validation & Error Matrix
|
||||||
|
|
||||||
|
- Missing `DATABASE_URL` -> deployment is not healthy; setup/login APIs return database configuration failures.
|
||||||
|
- Migration failure -> stop deployment and report the failing migration output.
|
||||||
|
- Build failure -> stop deployment and report the failing command output.
|
||||||
|
- SSH failure -> report that `wlcb1` could not be reached.
|
||||||
|
|
||||||
|
### 5. Good/Base/Bad Cases
|
||||||
|
|
||||||
|
- Good: commit locally, push to `origin`, SSH to `wlcb1`, update checkout, install deps, migrate DB, build, restart app.
|
||||||
|
- Base: if the server has a project-specific deploy script, run that script after pushing.
|
||||||
|
- Bad: deploy uncommitted local files, deploy to a different host by default, or skip migrations after schema changes.
|
||||||
|
|
||||||
|
### 6. Tests Required
|
||||||
|
|
||||||
|
- `pnpm lint`
|
||||||
|
- `pnpm type-check`
|
||||||
|
- `pnpm build`
|
||||||
|
- After deploy, verify the app responds and `/api/auth/bootstrap` returns a structured JSON response.
|
||||||
|
|
||||||
|
### 7. Wrong vs Correct
|
||||||
|
|
||||||
|
#### Wrong
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ssh some-other-host
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Correct
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ssh wlcb1
|
||||||
|
```
|
||||||
@@ -21,6 +21,7 @@
|
|||||||
| [authentication.md](./authentication.md) | better-auth, sessions, OAuth, protected procedures | Auth-related features |
|
| [authentication.md](./authentication.md) | better-auth, sessions, OAuth, protected procedures | Auth-related features |
|
||||||
| [logging.md](./logging.md) | Structured logging, Sentry tracing, telemetry | Debugging, observability |
|
| [logging.md](./logging.md) | Structured logging, Sentry tracing, telemetry | Debugging, observability |
|
||||||
| [local-json-mvp.md](./local-json-mvp.md) | Local JSON persistence/session/API contracts before database adoption | Single-repo MVP features without DB/oRPC deps |
|
| [local-json-mvp.md](./local-json-mvp.md) | Local JSON persistence/session/API contracts before database adoption | Single-repo MVP features without DB/oRPC deps |
|
||||||
|
| [deployment.md](./deployment.md) | Wulanchabu deployment target and validation contract | Deploying this project |
|
||||||
| [performance.md](./performance.md) | Concurrency, caching, batch processing, streaming | Performance optimization |
|
| [performance.md](./performance.md) | Concurrency, caching, batch processing, streaming | Performance optimization |
|
||||||
| [ai-sdk-integration.md](./ai-sdk-integration.md) | Vercel AI SDK, tool calling, prompt patterns | AI-powered features |
|
| [ai-sdk-integration.md](./ai-sdk-integration.md) | Vercel AI SDK, tool calling, prompt patterns | AI-powered features |
|
||||||
| [quality.md](./quality.md) | Pre-commit checklist for backend code | Before committing |
|
| [quality.md](./quality.md) | Pre-commit checklist for backend code | Before committing |
|
||||||
|
|||||||
@@ -22,6 +22,8 @@
|
|||||||
- Default data file: `.data/teatea.json`.
|
- Default data file: `.data/teatea.json`.
|
||||||
- Override key: `TEATEA_DATA_DIR` points to the directory containing `teatea.json`.
|
- Override key: `TEATEA_DATA_DIR` points to the directory containing `teatea.json`.
|
||||||
- `.data/` must stay ignored; it may contain account hashes and session IDs.
|
- `.data/` must stay ignored; it may contain account hashes and session IDs.
|
||||||
|
- Routes or layouts that read local JSON state or session cookies must opt out of static prerendering with `export const dynamic = "force-dynamic"`.
|
||||||
|
- API JSON responses backed by local JSON state or session cookies must include `Cache-Control: no-store`.
|
||||||
- API response shape:
|
- API response shape:
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
@@ -51,6 +53,7 @@ type ApiResult<T extends Record<string, unknown>> =
|
|||||||
- Good: UI submits to Route Handler, Route Handler validates input, calls `requirePermission`, mutates data through `updateData`, writes audit log, returns `ApiResult`.
|
- Good: UI submits to Route Handler, Route Handler validates input, calls `requirePermission`, mutates data through `updateData`, writes audit log, returns `ApiResult`.
|
||||||
- Base: Server Component reads data directly via `readData` after session/permission checks.
|
- Base: Server Component reads data directly via `readData` after session/permission checks.
|
||||||
- Bad: UI or route handler reads `.data/teatea.json` directly, bypasses `requirePermission`, or stores auth state in localStorage.
|
- Bad: UI or route handler reads `.data/teatea.json` directly, bypasses `requirePermission`, or stores auth state in localStorage.
|
||||||
|
- Bad: `/app/*`, `/login`, or `/setup` is prerendered as static content and caches a redirect based on build-time empty data.
|
||||||
|
|
||||||
### 6. Tests Required
|
### 6. Tests Required
|
||||||
|
|
||||||
@@ -60,6 +63,8 @@ type ApiResult<T extends Record<string, unknown>> =
|
|||||||
- Manual or automated integration assertions:
|
- Manual or automated integration assertions:
|
||||||
- first setup creates admin and cookie session
|
- first setup creates admin and cookie session
|
||||||
- protected app route redirects without cookie
|
- protected app route redirects without cookie
|
||||||
|
- protected app route renders with a valid cookie after setup and does not return a cached `/setup` redirect
|
||||||
|
- auth/bootstrap/session API responses include `Cache-Control: no-store`
|
||||||
- CRUD mutation persists across reload/API list
|
- CRUD mutation persists across reload/API list
|
||||||
- denied permission returns 403 and writes an audit log
|
- denied permission returns 403 and writes an audit log
|
||||||
|
|
||||||
@@ -84,3 +89,28 @@ cookieStore.set({
|
|||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
|
#### Wrong
|
||||||
|
|
||||||
|
```ts
|
||||||
|
export default async function AppLayout({ children }: AppLayoutProps) {
|
||||||
|
const bootstrap = await getBootstrapState();
|
||||||
|
if (bootstrap.setupRequired) {
|
||||||
|
redirect("/setup");
|
||||||
|
}
|
||||||
|
return children;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Correct
|
||||||
|
|
||||||
|
```ts
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
|
export default async function AppLayout({ children }: AppLayoutProps) {
|
||||||
|
const bootstrap = await getBootstrapState();
|
||||||
|
if (bootstrap.setupRequired) {
|
||||||
|
redirect("/setup");
|
||||||
|
}
|
||||||
|
return children;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|||||||
@@ -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 (
|
return (
|
||||||
<ModulePage
|
<div className="mx-auto flex w-full max-w-7xl flex-col gap-5">
|
||||||
title="床位房间"
|
<section className="flex flex-col gap-4 border-b pb-5 lg:flex-row lg:items-end lg:justify-between">
|
||||||
eyebrow="房间与床位状态"
|
<div>
|
||||||
description="维护楼栋、楼层、房间、床位编号和空闲、占用、维修状态流转。"
|
<Badge variant="success">Facility + Admission</Badge>
|
||||||
icon={BedDouble}
|
<h1 className="mt-3 text-3xl font-semibold tracking-normal">床位房间</h1>
|
||||||
phase="一期"
|
<p className="mt-2 text-sm text-muted-foreground">房间主数据、床位状态、当前占用和入住历史。</p>
|
||||||
metrics={[
|
</div>
|
||||||
{ label: "总床位", value: "154", detail: "护理区 96 张,康复区 58 张" },
|
</section>
|
||||||
{ label: "占用率", value: "82%", detail: "低于阈值时支持入住调度" },
|
|
||||||
{ label: "维修床位", value: "3", detail: "维修完成后恢复可用" },
|
<section className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
|
||||||
]}
|
<Card>
|
||||||
workflows={["维护楼栋与房间", "新增床位编号", "入住时占用床位", "退住或维修后释放床位"]}
|
<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 { getBootstrapState, getCurrentAuthContext } from "@/modules/core/server/auth";
|
||||||
import { AppShell } from "@/modules/shared/components/AppShell";
|
import { AppShell } from "@/modules/shared/components/AppShell";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
type AppLayoutProps = {
|
type AppLayoutProps = {
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
import { getCurrentAuthContext, toPublicAccount } from "@/modules/core/server/auth";
|
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 { readData } from "@/modules/core/server/store";
|
||||||
import { SettingsOverview } from "@/modules/settings/components/SettingsOverview";
|
import { SettingsOverview } from "@/modules/settings/components/SettingsOverview";
|
||||||
|
|
||||||
@@ -11,16 +11,20 @@ export default async function SettingsPage(): Promise<React.ReactElement> {
|
|||||||
redirect("/login");
|
redirect("/login");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!hasPermission(context.account.role, "account:read")) {
|
if (!hasPermission(context.permissions, "account:read")) {
|
||||||
redirect("/app/dashboard");
|
redirect("/app/dashboard");
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await readData();
|
const data = await readData();
|
||||||
|
const roles = await getRoleDefinitions(context.organization?.id);
|
||||||
return (
|
return (
|
||||||
<SettingsOverview
|
<SettingsOverview
|
||||||
accounts={data.accounts.map((account) => toPublicAccount(account))}
|
accounts={data.accounts.map((account) => toPublicAccount(account))}
|
||||||
roles={ROLE_DEFINITIONS}
|
roles={roles}
|
||||||
auditLogs={data.auditLogs.slice(0, 100)}
|
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";
|
import { AuthPanel } from "@/modules/auth/components/AuthPanel";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
export default function LoginPage(): React.ReactElement {
|
export default function LoginPage(): React.ReactElement {
|
||||||
return <AuthPanel mode="login" />;
|
return <AuthPanel mode="login" />;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import { AuthPanel } from "@/modules/auth/components/AuthPanel";
|
import { AuthPanel } from "@/modules/auth/components/AuthPanel";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
export default function RegisterPage(): React.ReactElement {
|
export default function RegisterPage(): React.ReactElement {
|
||||||
return <AuthPanel mode="register" />;
|
return <AuthPanel mode="register" />;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import { AuthPanel } from "@/modules/auth/components/AuthPanel";
|
import { AuthPanel } from "@/modules/auth/components/AuthPanel";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
export default function SetupPage(): React.ReactElement {
|
export default function SetupPage(): React.ReactElement {
|
||||||
return <AuthPanel mode="setup" />;
|
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 { jsonSuccess } from "@/modules/core/server/api";
|
||||||
|
import { listAuditLogs } from "@/modules/core/server/audit";
|
||||||
import { requirePermission } from "@/modules/core/server/auth";
|
import { requirePermission } from "@/modules/core/server/auth";
|
||||||
import { readData } from "@/modules/core/server/store";
|
|
||||||
|
|
||||||
export async function GET(): Promise<Response> {
|
export async function GET(): Promise<Response> {
|
||||||
const auth = await requirePermission("audit:read", {
|
const auth = await requirePermission("audit:read", {
|
||||||
@@ -12,9 +12,8 @@ export async function GET(): Promise<Response> {
|
|||||||
return auth.response;
|
return auth.response;
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await readData();
|
const auditLogs = await listAuditLogs({ organizationId: auth.context.organization?.id, limit: 100 });
|
||||||
return jsonSuccess("审计日志已加载", {
|
return jsonSuccess("审计日志已加载", {
|
||||||
auditLogs: data.auditLogs.slice(0, 100),
|
auditLogs,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,16 @@
|
|||||||
import { getBootstrapState } from "@/modules/core/server/auth";
|
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> {
|
export async function GET(): Promise<Response> {
|
||||||
|
try {
|
||||||
|
await ensureSystemDefaults();
|
||||||
const state = await getBootstrapState();
|
const state = await getBootstrapState();
|
||||||
return jsonSuccess("Bootstrap state loaded", state);
|
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 { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
|
||||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||||
import { updateData } from "@/modules/core/server/store";
|
|
||||||
|
|
||||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||||
@@ -18,45 +17,25 @@ export async function POST(request: Request): Promise<Response> {
|
|||||||
return jsonFailure("请求数据格式无效");
|
return jsonFailure("请求数据格式无效");
|
||||||
}
|
}
|
||||||
|
|
||||||
const email = normalizeEmail(readString(body, "email"));
|
const email = readString(body, "email");
|
||||||
const password = readString(body, "password");
|
const password = readString(body, "password");
|
||||||
|
|
||||||
if (!email || !password) {
|
if (!email || !password) {
|
||||||
return jsonFailure("邮箱和密码不能为空");
|
return jsonFailure("邮箱和密码不能为空");
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await updateData((data) => {
|
try {
|
||||||
const account = data.accounts.find((item) => item.email === email);
|
const result = await loginWithPassword({ email, password });
|
||||||
if (!account || account.status !== "active" || !verifyPassword(password, account)) {
|
await setSessionCookie(result.session.id);
|
||||||
return null;
|
return jsonSuccess("登录成功", { account: result.account });
|
||||||
}
|
} catch (error) {
|
||||||
|
|
||||||
const session = createSessionRecord(account.id);
|
|
||||||
data.sessions.push(session);
|
|
||||||
return { account, session };
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!result) {
|
|
||||||
await recordAuditLog({
|
await recordAuditLog({
|
||||||
action: "auth.login",
|
action: "account.login",
|
||||||
targetType: "account",
|
targetType: "account",
|
||||||
result: "failure",
|
result: "failure",
|
||||||
reason: `登录失败:${email}`,
|
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 { 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> {
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||||
@@ -21,6 +19,7 @@ export async function POST(request: Request): Promise<Response> {
|
|||||||
const name = readString(body, "name");
|
const name = readString(body, "name");
|
||||||
const email = readString(body, "email");
|
const email = readString(body, "email");
|
||||||
const password = readString(body, "password");
|
const password = readString(body, "password");
|
||||||
|
const organizationId = readString(body, "organizationId");
|
||||||
|
|
||||||
if (!name || !email || !password) {
|
if (!name || !email || !password) {
|
||||||
return jsonFailure("姓名、邮箱和密码不能为空");
|
return jsonFailure("姓名、邮箱和密码不能为空");
|
||||||
@@ -30,59 +29,18 @@ export async function POST(request: Request): Promise<Response> {
|
|||||||
return jsonFailure("密码至少需要6位");
|
return jsonFailure("密码至少需要6位");
|
||||||
}
|
}
|
||||||
|
|
||||||
const normalizedEmail = normalizeEmail(email);
|
try {
|
||||||
const created = await updateData((data) => {
|
const created = await createRegistration({
|
||||||
const exists = data.accounts.some((account) => account.email === normalizedEmail);
|
|
||||||
if (exists) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const account = createAccountRecord({
|
|
||||||
name,
|
name,
|
||||||
email,
|
email,
|
||||||
password,
|
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);
|
await setSessionCookie(created.session.id);
|
||||||
await recordAuditLog({
|
return jsonSuccess("账号已创建", { account: created.account });
|
||||||
actor: {
|
} catch (error) {
|
||||||
id: created.account.id,
|
const reason = error instanceof Error ? error.message : "账号创建失败";
|
||||||
name: created.account.name,
|
const status = reason === "账号已存在" ? 409 : 500;
|
||||||
email: created.account.email,
|
return jsonFailure(reason, status);
|
||||||
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 { getCurrentAuthContext } from "@/modules/core/server/auth";
|
||||||
import { jsonSuccess } from "@/modules/core/server/api";
|
import { jsonSuccess } from "@/modules/core/server/api";
|
||||||
|
|
||||||
|
export const dynamic = "force-dynamic";
|
||||||
|
|
||||||
export async function GET(): Promise<Response> {
|
export async function GET(): Promise<Response> {
|
||||||
const context = await getCurrentAuthContext();
|
const context = await getCurrentAuthContext();
|
||||||
|
|
||||||
return jsonSuccess("Session loaded", {
|
return jsonSuccess("Session loaded", {
|
||||||
account: context?.account ?? null,
|
account: context?.account ?? null,
|
||||||
|
organization: context?.organization ?? null,
|
||||||
|
membership: context?.membership ?? null,
|
||||||
permissions: context?.permissions ?? [],
|
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 { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
|
||||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
import { ensureSystemDefaults } from "@/modules/core/server/permissions";
|
||||||
import { updateData } from "@/modules/core/server/store";
|
|
||||||
|
|
||||||
function readString(source: Record<string, unknown>, key: string): string {
|
function readString(source: Record<string, unknown>, key: string): string {
|
||||||
const value = source[key];
|
const value = source[key];
|
||||||
@@ -31,60 +30,14 @@ export async function POST(request: Request): Promise<Response> {
|
|||||||
return jsonFailure("密码至少需要6位");
|
return jsonFailure("密码至少需要6位");
|
||||||
}
|
}
|
||||||
|
|
||||||
const created = await updateData((data) => {
|
try {
|
||||||
if (data.accounts.length > 0) {
|
await ensureSystemDefaults();
|
||||||
return null;
|
const created = await setupFirstPlatformAdmin({ organization, name, email, password });
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
await setSessionCookie(created.session.id);
|
await setSessionCookie(created.session.id);
|
||||||
await recordAuditLog({
|
return jsonSuccess("初始化完成", { account: created.account });
|
||||||
actor: {
|
} catch (error) {
|
||||||
id: created.account.id,
|
const reason = error instanceof Error ? error.message : "初始化失败";
|
||||||
name: created.account.name,
|
const status = reason === "系统已完成初始化" ? 409 : 500;
|
||||||
email: created.account.email,
|
return jsonFailure(reason, status);
|
||||||
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 { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
|
||||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||||
import { requirePermission } from "@/modules/core/server/auth";
|
import { requirePermission } from "@/modules/core/server/auth";
|
||||||
import { 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 = {
|
type RouteContext = {
|
||||||
params: Promise<{
|
params: Promise<{
|
||||||
@@ -22,41 +25,66 @@ export async function PATCH(request: Request, context: RouteContext): Promise<Re
|
|||||||
return auth.response;
|
return auth.response;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const organizationId = auth.context.organization?.id;
|
||||||
|
if (!organizationId) {
|
||||||
|
return jsonFailure("请选择机构后更新老人档案", 400);
|
||||||
|
}
|
||||||
|
|
||||||
const input = validateElderInput(await readJsonBody(request));
|
const input = validateElderInput(await readJsonBody(request));
|
||||||
if (!input.success) {
|
if (!input.success) {
|
||||||
return jsonFailure(input.reason);
|
return jsonFailure(input.reason);
|
||||||
}
|
}
|
||||||
|
|
||||||
const updated = await updateData((data) => {
|
const database = getDatabase();
|
||||||
const elder = data.elders.find((item) => item.id === id);
|
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];
|
||||||
|
|
||||||
if (!elder) {
|
if (!elder) {
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const nextElder = {
|
|
||||||
...elder,
|
|
||||||
...input.data,
|
|
||||||
updatedAt: new Date().toISOString(),
|
|
||||||
};
|
|
||||||
|
|
||||||
data.elders = data.elders.map((item) => (item.id === id ? nextElder : item));
|
|
||||||
return nextElder;
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!updated) {
|
|
||||||
return jsonFailure("老人档案不存在", 404);
|
return jsonFailure("老人档案不存在", 404);
|
||||||
}
|
}
|
||||||
|
|
||||||
await recordAuditLog({
|
await recordAuditLog({
|
||||||
actor: auth.context.account,
|
actor: auth.context.account,
|
||||||
|
organizationId,
|
||||||
action: "elder.update",
|
action: "elder.update",
|
||||||
targetType: "elder",
|
targetType: "elder",
|
||||||
targetId: updated.id,
|
targetId: elder.id,
|
||||||
result: "success",
|
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> {
|
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;
|
return auth.response;
|
||||||
}
|
}
|
||||||
|
|
||||||
const deleted = await updateData((data) => {
|
const organizationId = auth.context.organization?.id;
|
||||||
const elder = data.elders.find((item) => item.id === 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) {
|
if (!elder) {
|
||||||
return null;
|
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;
|
return elder;
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -87,6 +145,7 @@ export async function DELETE(_request: Request, context: RouteContext): Promise<
|
|||||||
|
|
||||||
await recordAuditLog({
|
await recordAuditLog({
|
||||||
actor: auth.context.account,
|
actor: auth.context.account,
|
||||||
|
organizationId,
|
||||||
action: "elder.delete",
|
action: "elder.delete",
|
||||||
targetType: "elder",
|
targetType: "elder",
|
||||||
targetId: deleted.id,
|
targetId: deleted.id,
|
||||||
@@ -94,6 +153,5 @@ export async function DELETE(_request: Request, context: RouteContext): Promise<
|
|||||||
reason: `删除老人档案:${deleted.name}`,
|
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 { randomUUID } from "node:crypto";
|
||||||
|
|
||||||
import type { Elder } from "@/modules/elders/types";
|
import { and, desc, eq } from "drizzle-orm";
|
||||||
import { validateElderInput } from "@/modules/elders/types";
|
|
||||||
import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
|
import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
|
||||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||||
import { requirePermission } from "@/modules/core/server/auth";
|
import { requirePermission } from "@/modules/core/server/auth";
|
||||||
import { 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> {
|
export async function GET(): Promise<Response> {
|
||||||
const auth = await requirePermission("elder:read", {
|
const auth = await requirePermission("elder:read", {
|
||||||
@@ -17,8 +40,19 @@ export async function GET(): Promise<Response> {
|
|||||||
return auth.response;
|
return auth.response;
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await readData();
|
const organizationId = auth.context.organization?.id;
|
||||||
return jsonSuccess("老人档案已加载", { elders: data.elders });
|
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> {
|
export async function POST(request: Request): Promise<Response> {
|
||||||
@@ -31,24 +65,72 @@ export async function POST(request: Request): Promise<Response> {
|
|||||||
return auth.response;
|
return auth.response;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const organizationId = auth.context.organization?.id;
|
||||||
|
if (!organizationId) {
|
||||||
|
return jsonFailure("请选择机构后新增老人档案", 400);
|
||||||
|
}
|
||||||
|
|
||||||
const input = validateElderInput(await readJsonBody(request));
|
const input = validateElderInput(await readJsonBody(request));
|
||||||
if (!input.success) {
|
if (!input.success) {
|
||||||
return jsonFailure(input.reason);
|
return jsonFailure(input.reason);
|
||||||
}
|
}
|
||||||
|
|
||||||
const now = new Date().toISOString();
|
const database = getDatabase();
|
||||||
const elder: Elder = {
|
const created = await database.transaction(async (transaction) => {
|
||||||
...input.data,
|
const elderId = randomUUID();
|
||||||
id: randomUUID(),
|
const elderRows = await transaction
|
||||||
createdAt: now,
|
.insert(elders)
|
||||||
updatedAt: now,
|
.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) => {
|
if (input.data.bedId) {
|
||||||
data.elders = [elder, ...data.elders];
|
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({
|
await recordAuditLog({
|
||||||
actor: auth.context.account,
|
actor: auth.context.account,
|
||||||
|
organizationId,
|
||||||
action: "elder.create",
|
action: "elder.create",
|
||||||
targetType: "elder",
|
targetType: "elder",
|
||||||
targetId: elder.id,
|
targetId: elder.id,
|
||||||
@@ -58,4 +140,3 @@ export async function POST(request: Request): Promise<Response> {
|
|||||||
|
|
||||||
return jsonSuccess("老人档案已创建", { elder }, 201);
|
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 { 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";
|
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> {
|
export async function GET(): Promise<Response> {
|
||||||
const auth = await requirePermission("account:read", {
|
const auth = await requirePermission("account:read", {
|
||||||
action: "account.list",
|
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 { 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 { 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> {
|
export async function GET(): Promise<Response> {
|
||||||
const auth = await requirePermission("account:read", {
|
const auth = await requirePermission("role:read", {
|
||||||
action: "role.list",
|
action: "role.list",
|
||||||
targetType: "role",
|
targetType: "role",
|
||||||
});
|
});
|
||||||
@@ -12,6 +35,85 @@ export async function GET(): Promise<Response> {
|
|||||||
return auth.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(),
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
}
|
||||||
10
drizzle.config.ts
Normal file
10
drizzle.config.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { defineConfig } from "drizzle-kit";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
dialect: "postgresql",
|
||||||
|
schema: "./modules/core/server/schema.ts",
|
||||||
|
out: "./drizzle",
|
||||||
|
dbCredentials: {
|
||||||
|
url: process.env.DATABASE_URL ?? "",
|
||||||
|
},
|
||||||
|
});
|
||||||
235
drizzle/0000_bouncy_micromax.sql
Normal file
235
drizzle/0000_bouncy_micromax.sql
Normal file
@@ -0,0 +1,235 @@
|
|||||||
|
CREATE TYPE "public"."account_status" AS ENUM('active', 'disabled', 'pending');--> statement-breakpoint
|
||||||
|
CREATE TYPE "public"."admission_status" AS ENUM('active', 'transferred', 'discharged');--> statement-breakpoint
|
||||||
|
CREATE TYPE "public"."audit_result" AS ENUM('success', 'denied', 'failure');--> statement-breakpoint
|
||||||
|
CREATE TYPE "public"."bed_status" AS ENUM('available', 'occupied', 'maintenance', 'disabled');--> statement-breakpoint
|
||||||
|
CREATE TYPE "public"."care_level" AS ENUM('self-care', 'semi-assisted', 'assisted', 'intensive');--> statement-breakpoint
|
||||||
|
CREATE TYPE "public"."elder_status" AS ENUM('active', 'pending', 'discharged');--> statement-breakpoint
|
||||||
|
CREATE TYPE "public"."gender" AS ENUM('male', 'female', 'other');--> statement-breakpoint
|
||||||
|
CREATE TYPE "public"."incident_severity" AS ENUM('info', 'warning', 'critical');--> statement-breakpoint
|
||||||
|
CREATE TYPE "public"."incident_status" AS ENUM('open', 'acknowledged', 'resolved', 'closed');--> statement-breakpoint
|
||||||
|
CREATE TYPE "public"."join_request_status" AS ENUM('pending', 'approved', 'rejected');--> statement-breakpoint
|
||||||
|
CREATE TYPE "public"."membership_status" AS ENUM('active', 'disabled', 'pending');--> statement-breakpoint
|
||||||
|
CREATE TYPE "public"."organization_status" AS ENUM('active', 'disabled');--> statement-breakpoint
|
||||||
|
CREATE TYPE "public"."role_scope" AS ENUM('platform', 'organization');--> statement-breakpoint
|
||||||
|
CREATE TABLE "accounts" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"platform_role_id" uuid,
|
||||||
|
"name" text NOT NULL,
|
||||||
|
"email" text NOT NULL,
|
||||||
|
"password_hash" text NOT NULL,
|
||||||
|
"password_salt" text NOT NULL,
|
||||||
|
"status" "account_status" DEFAULT 'active' NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "admissions" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"organization_id" uuid NOT NULL,
|
||||||
|
"elder_id" uuid NOT NULL,
|
||||||
|
"bed_id" uuid NOT NULL,
|
||||||
|
"status" "admission_status" DEFAULT 'active' NOT NULL,
|
||||||
|
"admitted_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"discharged_at" timestamp with time zone,
|
||||||
|
"notes" text DEFAULT '' NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "audit_logs" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"organization_id" uuid,
|
||||||
|
"timestamp" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"actor_account_id" uuid,
|
||||||
|
"actor_email" text,
|
||||||
|
"action" text NOT NULL,
|
||||||
|
"target_type" text NOT NULL,
|
||||||
|
"target_id" text,
|
||||||
|
"result" "audit_result" NOT NULL,
|
||||||
|
"reason" text NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "beds" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"organization_id" uuid NOT NULL,
|
||||||
|
"room_id" uuid NOT NULL,
|
||||||
|
"code" text NOT NULL,
|
||||||
|
"status" "bed_status" DEFAULT 'available' NOT NULL,
|
||||||
|
"notes" text DEFAULT '' NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "buildings" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"organization_id" uuid NOT NULL,
|
||||||
|
"campus_id" uuid NOT NULL,
|
||||||
|
"name" text NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "campuses" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"organization_id" uuid NOT NULL,
|
||||||
|
"name" text NOT NULL,
|
||||||
|
"address" text DEFAULT '' NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "elders" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"organization_id" uuid NOT NULL,
|
||||||
|
"name" text NOT NULL,
|
||||||
|
"gender" "gender" NOT NULL,
|
||||||
|
"age" integer NOT NULL,
|
||||||
|
"care_level" "care_level" NOT NULL,
|
||||||
|
"status" "elder_status" DEFAULT 'pending' NOT NULL,
|
||||||
|
"primary_contact" text NOT NULL,
|
||||||
|
"phone" text NOT NULL,
|
||||||
|
"medical_notes" text DEFAULT '' NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "floors" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"organization_id" uuid NOT NULL,
|
||||||
|
"building_id" uuid NOT NULL,
|
||||||
|
"name" text NOT NULL,
|
||||||
|
"level" integer NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "join_requests" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"account_id" uuid NOT NULL,
|
||||||
|
"organization_id" uuid NOT NULL,
|
||||||
|
"status" "join_request_status" DEFAULT 'pending' NOT NULL,
|
||||||
|
"reason" text DEFAULT '' NOT NULL,
|
||||||
|
"reviewed_by_account_id" uuid,
|
||||||
|
"reviewed_at" timestamp with time zone,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "memberships" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"account_id" uuid NOT NULL,
|
||||||
|
"organization_id" uuid NOT NULL,
|
||||||
|
"role_id" uuid NOT NULL,
|
||||||
|
"status" "membership_status" DEFAULT 'active' NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "organizations" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"name" text NOT NULL,
|
||||||
|
"slug" text NOT NULL,
|
||||||
|
"status" "organization_status" DEFAULT 'active' NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "permissions" (
|
||||||
|
"id" text PRIMARY KEY NOT NULL,
|
||||||
|
"label" text NOT NULL,
|
||||||
|
"category" text NOT NULL,
|
||||||
|
"description" text NOT NULL,
|
||||||
|
"is_enabled" boolean DEFAULT true NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "role_permissions" (
|
||||||
|
"role_id" uuid NOT NULL,
|
||||||
|
"permission_id" text NOT NULL,
|
||||||
|
CONSTRAINT "role_permissions_role_id_permission_id_pk" PRIMARY KEY("role_id","permission_id")
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "roles" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"key" text NOT NULL,
|
||||||
|
"organization_id" uuid,
|
||||||
|
"scope" "role_scope" NOT NULL,
|
||||||
|
"label" text NOT NULL,
|
||||||
|
"description" text NOT NULL,
|
||||||
|
"is_system" boolean DEFAULT false NOT NULL,
|
||||||
|
"is_enabled" boolean DEFAULT true NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "rooms" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"organization_id" uuid NOT NULL,
|
||||||
|
"floor_id" uuid NOT NULL,
|
||||||
|
"name" text NOT NULL,
|
||||||
|
"code" text NOT NULL,
|
||||||
|
"capacity" integer DEFAULT 1 NOT NULL,
|
||||||
|
"status" "organization_status" DEFAULT 'active' NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "sessions" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"account_id" uuid NOT NULL,
|
||||||
|
"active_organization_id" uuid,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"expires_at" timestamp with time zone NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "system_incidents" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"organization_id" uuid,
|
||||||
|
"severity" "incident_severity" NOT NULL,
|
||||||
|
"status" "incident_status" DEFAULT 'open' NOT NULL,
|
||||||
|
"title" text NOT NULL,
|
||||||
|
"description" text NOT NULL,
|
||||||
|
"source" text NOT NULL,
|
||||||
|
"acknowledged_by_account_id" uuid,
|
||||||
|
"acknowledged_at" timestamp with time zone,
|
||||||
|
"resolved_by_account_id" uuid,
|
||||||
|
"resolved_at" timestamp with time zone,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
ALTER TABLE "accounts" ADD CONSTRAINT "accounts_platform_role_id_roles_id_fk" FOREIGN KEY ("platform_role_id") REFERENCES "public"."roles"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "admissions" ADD CONSTRAINT "admissions_organization_id_organizations_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "admissions" ADD CONSTRAINT "admissions_elder_id_elders_id_fk" FOREIGN KEY ("elder_id") REFERENCES "public"."elders"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "admissions" ADD CONSTRAINT "admissions_bed_id_beds_id_fk" FOREIGN KEY ("bed_id") REFERENCES "public"."beds"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "audit_logs" ADD CONSTRAINT "audit_logs_organization_id_organizations_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "audit_logs" ADD CONSTRAINT "audit_logs_actor_account_id_accounts_id_fk" FOREIGN KEY ("actor_account_id") REFERENCES "public"."accounts"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "beds" ADD CONSTRAINT "beds_organization_id_organizations_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "beds" ADD CONSTRAINT "beds_room_id_rooms_id_fk" FOREIGN KEY ("room_id") REFERENCES "public"."rooms"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "buildings" ADD CONSTRAINT "buildings_organization_id_organizations_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "buildings" ADD CONSTRAINT "buildings_campus_id_campuses_id_fk" FOREIGN KEY ("campus_id") REFERENCES "public"."campuses"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "campuses" ADD CONSTRAINT "campuses_organization_id_organizations_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "elders" ADD CONSTRAINT "elders_organization_id_organizations_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "floors" ADD CONSTRAINT "floors_organization_id_organizations_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "floors" ADD CONSTRAINT "floors_building_id_buildings_id_fk" FOREIGN KEY ("building_id") REFERENCES "public"."buildings"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "join_requests" ADD CONSTRAINT "join_requests_account_id_accounts_id_fk" FOREIGN KEY ("account_id") REFERENCES "public"."accounts"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "join_requests" ADD CONSTRAINT "join_requests_organization_id_organizations_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "join_requests" ADD CONSTRAINT "join_requests_reviewed_by_account_id_accounts_id_fk" FOREIGN KEY ("reviewed_by_account_id") REFERENCES "public"."accounts"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "memberships" ADD CONSTRAINT "memberships_account_id_accounts_id_fk" FOREIGN KEY ("account_id") REFERENCES "public"."accounts"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "memberships" ADD CONSTRAINT "memberships_organization_id_organizations_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "memberships" ADD CONSTRAINT "memberships_role_id_roles_id_fk" FOREIGN KEY ("role_id") REFERENCES "public"."roles"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "role_permissions" ADD CONSTRAINT "role_permissions_role_id_roles_id_fk" FOREIGN KEY ("role_id") REFERENCES "public"."roles"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "role_permissions" ADD CONSTRAINT "role_permissions_permission_id_permissions_id_fk" FOREIGN KEY ("permission_id") REFERENCES "public"."permissions"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "roles" ADD CONSTRAINT "roles_organization_id_organizations_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "rooms" ADD CONSTRAINT "rooms_organization_id_organizations_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "rooms" ADD CONSTRAINT "rooms_floor_id_floors_id_fk" FOREIGN KEY ("floor_id") REFERENCES "public"."floors"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "sessions" ADD CONSTRAINT "sessions_account_id_accounts_id_fk" FOREIGN KEY ("account_id") REFERENCES "public"."accounts"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "sessions" ADD CONSTRAINT "sessions_active_organization_id_organizations_id_fk" FOREIGN KEY ("active_organization_id") REFERENCES "public"."organizations"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "system_incidents" ADD CONSTRAINT "system_incidents_organization_id_organizations_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "system_incidents" ADD CONSTRAINT "system_incidents_acknowledged_by_account_id_accounts_id_fk" FOREIGN KEY ("acknowledged_by_account_id") REFERENCES "public"."accounts"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "system_incidents" ADD CONSTRAINT "system_incidents_resolved_by_account_id_accounts_id_fk" FOREIGN KEY ("resolved_by_account_id") REFERENCES "public"."accounts"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||||
|
CREATE UNIQUE INDEX "accounts_email_unique" ON "accounts" USING btree ("email");--> statement-breakpoint
|
||||||
|
CREATE UNIQUE INDEX "beds_code_room_unique" ON "beds" USING btree ("room_id","code");--> statement-breakpoint
|
||||||
|
CREATE UNIQUE INDEX "memberships_account_organization_unique" ON "memberships" USING btree ("account_id","organization_id");--> statement-breakpoint
|
||||||
|
CREATE UNIQUE INDEX "organizations_slug_unique" ON "organizations" USING btree ("slug");--> statement-breakpoint
|
||||||
|
CREATE UNIQUE INDEX "roles_key_organization_unique" ON "roles" USING btree ("key","organization_id");--> statement-breakpoint
|
||||||
|
CREATE UNIQUE INDEX "rooms_code_organization_unique" ON "rooms" USING btree ("organization_id","code");
|
||||||
1772
drizzle/meta/0000_snapshot.json
Normal file
1772
drizzle/meta/0000_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
13
drizzle/meta/_journal.json
Normal file
13
drizzle/meta/_journal.json
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"version": "7",
|
||||||
|
"dialect": "postgresql",
|
||||||
|
"entries": [
|
||||||
|
{
|
||||||
|
"idx": 0,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1782975351852,
|
||||||
|
"tag": "0000_bouncy_micromax",
|
||||||
|
"breakpoints": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -15,11 +15,27 @@ export function jsonSuccess<T extends Record<string, unknown>>(
|
|||||||
payload: T,
|
payload: T,
|
||||||
status = 200,
|
status = 200,
|
||||||
): Response {
|
): Response {
|
||||||
return Response.json({ success: true, reason, ...payload }, { status });
|
return Response.json(
|
||||||
|
{ success: true, reason, ...payload },
|
||||||
|
{
|
||||||
|
status,
|
||||||
|
headers: {
|
||||||
|
"Cache-Control": "no-store",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function jsonFailure(reason: string, status = 400): Response {
|
export function jsonFailure(reason: string, status = 400): Response {
|
||||||
return Response.json({ success: false, reason }, { status });
|
return Response.json(
|
||||||
|
{ success: false, reason },
|
||||||
|
{
|
||||||
|
status,
|
||||||
|
headers: {
|
||||||
|
"Cache-Control": "no-store",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function readJsonBody(request: Request): Promise<unknown> {
|
export async function readJsonBody(request: Request): Promise<unknown> {
|
||||||
@@ -29,4 +45,3 @@ export async function readJsonBody(request: Request): Promise<unknown> {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import { randomUUID } from "node:crypto";
|
import { desc, eq } from "drizzle-orm";
|
||||||
|
|
||||||
|
import { getDatabase } from "@/modules/core/server/db";
|
||||||
|
import { auditLogs } from "@/modules/core/server/schema";
|
||||||
import type { AuditLog, AuditResult, PublicAccount } from "@/modules/core/types";
|
import type { AuditLog, AuditResult, PublicAccount } from "@/modules/core/types";
|
||||||
import { updateData } from "@/modules/core/server/store";
|
|
||||||
|
|
||||||
type AuditInput = {
|
type AuditInput = {
|
||||||
actor?: PublicAccount;
|
actor?: PublicAccount;
|
||||||
|
organizationId?: string;
|
||||||
action: string;
|
action: string;
|
||||||
targetType: string;
|
targetType: string;
|
||||||
targetId?: string;
|
targetId?: string;
|
||||||
@@ -12,13 +14,27 @@ type AuditInput = {
|
|||||||
reason: string;
|
reason: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export async function recordAuditLog(input: AuditInput): Promise<AuditLog> {
|
function toAuditLog(row: typeof auditLogs.$inferSelect): AuditLog {
|
||||||
const timestamp = new Date().toISOString();
|
return {
|
||||||
|
id: row.id,
|
||||||
|
organizationId: row.organizationId ?? undefined,
|
||||||
|
timestamp: row.timestamp.toISOString(),
|
||||||
|
actorAccountId: row.actorAccountId ?? undefined,
|
||||||
|
actorEmail: row.actorEmail ?? undefined,
|
||||||
|
action: row.action,
|
||||||
|
targetType: row.targetType,
|
||||||
|
targetId: row.targetId ?? undefined,
|
||||||
|
result: row.result,
|
||||||
|
reason: row.reason,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
return await updateData((data) => {
|
export async function recordAuditLog(input: AuditInput): Promise<AuditLog> {
|
||||||
const nextLog: AuditLog = {
|
const database = getDatabase();
|
||||||
id: randomUUID(),
|
const rows = await database
|
||||||
timestamp,
|
.insert(auditLogs)
|
||||||
|
.values({
|
||||||
|
organizationId: input.organizationId,
|
||||||
actorAccountId: input.actor?.id,
|
actorAccountId: input.actor?.id,
|
||||||
actorEmail: input.actor?.email,
|
actorEmail: input.actor?.email,
|
||||||
action: input.action,
|
action: input.action,
|
||||||
@@ -26,10 +42,27 @@ export async function recordAuditLog(input: AuditInput): Promise<AuditLog> {
|
|||||||
targetId: input.targetId,
|
targetId: input.targetId,
|
||||||
result: input.result,
|
result: input.result,
|
||||||
reason: input.reason,
|
reason: input.reason,
|
||||||
};
|
})
|
||||||
|
.returning();
|
||||||
data.auditLogs = [nextLog, ...data.auditLogs].slice(0, 500);
|
const row = rows[0];
|
||||||
return nextLog;
|
if (!row) {
|
||||||
});
|
throw new Error("审计日志写入失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return toAuditLog(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listAuditLogs(params: { organizationId?: string; limit?: number }): Promise<AuditLog[]> {
|
||||||
|
const database = getDatabase();
|
||||||
|
const limit = params.limit ?? 100;
|
||||||
|
const rows = params.organizationId
|
||||||
|
? await database
|
||||||
|
.select()
|
||||||
|
.from(auditLogs)
|
||||||
|
.where(eq(auditLogs.organizationId, params.organizationId))
|
||||||
|
.orderBy(desc(auditLogs.timestamp))
|
||||||
|
.limit(limit)
|
||||||
|
: await database.select().from(auditLogs).orderBy(desc(auditLogs.timestamp)).limit(limit);
|
||||||
|
|
||||||
|
return rows.map(toAuditLog);
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,30 +1,83 @@
|
|||||||
import { randomBytes, randomUUID, scryptSync, timingSafeEqual } from "node:crypto";
|
import { randomBytes, scryptSync, timingSafeEqual } from "node:crypto";
|
||||||
|
|
||||||
|
import { and, eq, gt, isNull } from "drizzle-orm";
|
||||||
import { cookies } from "next/headers";
|
import { cookies } from "next/headers";
|
||||||
|
|
||||||
import type { Account, AuthContext, Permission, PublicAccount, RoleId, Session } from "@/modules/core/types";
|
|
||||||
import { jsonFailure } from "@/modules/core/server/api";
|
import { jsonFailure } from "@/modules/core/server/api";
|
||||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||||
import { getPermissionsForRole, hasPermission } from "@/modules/core/server/permissions";
|
import { getDatabase } from "@/modules/core/server/db";
|
||||||
import { readData, updateData } from "@/modules/core/server/store";
|
import { getPermissionsForRole, hasPermission, seedOrganizationRoles } from "@/modules/core/server/permissions";
|
||||||
|
import { accounts, joinRequests, memberships, organizations, roles, sessions } from "@/modules/core/server/schema";
|
||||||
|
import type { Account, AuthContext, Membership, Organization, Permission, PublicAccount, Session } from "@/modules/core/types";
|
||||||
|
|
||||||
const SESSION_COOKIE = "teatea_session";
|
const SESSION_COOKIE = "teatea_session";
|
||||||
const SESSION_MAX_AGE_SECONDS = 60 * 60 * 24 * 7;
|
const SESSION_MAX_AGE_SECONDS = 60 * 60 * 24 * 7;
|
||||||
|
|
||||||
|
type AccountRow = typeof accounts.$inferSelect;
|
||||||
|
type OrganizationRow = typeof organizations.$inferSelect;
|
||||||
|
type MembershipRow = typeof memberships.$inferSelect;
|
||||||
|
type RoleRow = typeof roles.$inferSelect;
|
||||||
|
type SessionRow = typeof sessions.$inferSelect;
|
||||||
|
|
||||||
export function normalizeEmail(email: string): string {
|
export function normalizeEmail(email: string): string {
|
||||||
return email.trim().toLowerCase();
|
return email.trim().toLowerCase();
|
||||||
}
|
}
|
||||||
|
|
||||||
export function toPublicAccount(account: Account): PublicAccount {
|
function toIsoString(value: Date): string {
|
||||||
|
return value.toISOString();
|
||||||
|
}
|
||||||
|
|
||||||
|
function toOrganization(row: OrganizationRow): Organization {
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
name: row.name,
|
||||||
|
slug: row.slug,
|
||||||
|
status: row.status,
|
||||||
|
createdAt: toIsoString(row.createdAt),
|
||||||
|
updatedAt: toIsoString(row.updatedAt),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function toSession(row: SessionRow): Session {
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
accountId: row.accountId,
|
||||||
|
activeOrganizationId: row.activeOrganizationId ?? undefined,
|
||||||
|
createdAt: toIsoString(row.createdAt),
|
||||||
|
expiresAt: toIsoString(row.expiresAt),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function toMembership(row: MembershipRow, role: RoleRow): Membership {
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
accountId: row.accountId,
|
||||||
|
organizationId: row.organizationId,
|
||||||
|
roleId: row.roleId,
|
||||||
|
roleKey: role.key,
|
||||||
|
roleLabel: role.label,
|
||||||
|
status: row.status,
|
||||||
|
createdAt: toIsoString(row.createdAt),
|
||||||
|
updatedAt: toIsoString(row.updatedAt),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toPublicAccount(account: AccountRow | Account, roleKey?: string, organization?: Organization): PublicAccount {
|
||||||
|
const fallbackRole = "role" in account ? account.role : "viewer";
|
||||||
|
const fallbackOrganization = "organization" in account ? account.organization : undefined;
|
||||||
|
const fallbackOrganizationId = "organizationId" in account ? account.organizationId : undefined;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: account.id,
|
id: account.id,
|
||||||
|
platformRoleId: "platformRoleId" in account ? account.platformRoleId ?? undefined : undefined,
|
||||||
name: account.name,
|
name: account.name,
|
||||||
email: account.email,
|
email: account.email,
|
||||||
role: account.role,
|
role: roleKey ?? fallbackRole,
|
||||||
organization: account.organization,
|
organization: organization?.name ?? fallbackOrganization,
|
||||||
|
organizationId: organization?.id ?? fallbackOrganizationId,
|
||||||
status: account.status,
|
status: account.status,
|
||||||
createdAt: account.createdAt,
|
createdAt: typeof account.createdAt === "string" ? account.createdAt : toIsoString(account.createdAt),
|
||||||
updatedAt: account.updatedAt,
|
updatedAt: typeof account.updatedAt === "string" ? account.updatedAt : toIsoString(account.updatedAt),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -38,7 +91,7 @@ export function hashPassword(password: string, salt = randomBytes(16).toString("
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function verifyPassword(password: string, account: Account): boolean {
|
export function verifyPassword(password: string, account: Pick<AccountRow, "passwordHash" | "passwordSalt">): boolean {
|
||||||
const candidate = Buffer.from(hashPassword(password, account.passwordSalt).hash, "hex");
|
const candidate = Buffer.from(hashPassword(password, account.passwordSalt).hash, "hex");
|
||||||
const stored = Buffer.from(account.passwordHash, "hex");
|
const stored = Buffer.from(account.passwordHash, "hex");
|
||||||
|
|
||||||
@@ -49,40 +102,14 @@ export function verifyPassword(password: string, account: Account): boolean {
|
|||||||
return timingSafeEqual(candidate, stored);
|
return timingSafeEqual(candidate, stored);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createAccountRecord(input: {
|
function createSlug(name: string): string {
|
||||||
name: string;
|
const base = name
|
||||||
email: string;
|
.trim()
|
||||||
password: string;
|
.toLowerCase()
|
||||||
role: RoleId;
|
.replace(/[^a-z0-9]+/g, "-")
|
||||||
organization?: string;
|
.replace(/^-|-$/g, "");
|
||||||
}): Account {
|
|
||||||
const now = new Date().toISOString();
|
|
||||||
const password = hashPassword(input.password);
|
|
||||||
|
|
||||||
return {
|
return base.length > 0 ? base : `org-${Date.now()}`;
|
||||||
id: randomUUID(),
|
|
||||||
name: input.name.trim(),
|
|
||||||
email: normalizeEmail(input.email),
|
|
||||||
role: input.role,
|
|
||||||
organization: input.organization?.trim(),
|
|
||||||
passwordHash: password.hash,
|
|
||||||
passwordSalt: password.salt,
|
|
||||||
status: "active",
|
|
||||||
createdAt: now,
|
|
||||||
updatedAt: now,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createSessionRecord(accountId: string): Session {
|
|
||||||
const now = new Date();
|
|
||||||
const expiresAt = new Date(now.getTime() + SESSION_MAX_AGE_SECONDS * 1000);
|
|
||||||
|
|
||||||
return {
|
|
||||||
id: randomUUID(),
|
|
||||||
accountId,
|
|
||||||
createdAt: now.toISOString(),
|
|
||||||
expiresAt: expiresAt.toISOString(),
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function setSessionCookie(sessionId: string): Promise<void> {
|
export async function setSessionCookie(sessionId: string): Promise<void> {
|
||||||
@@ -103,8 +130,255 @@ export async function clearSessionCookie(): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function getBootstrapState(): Promise<{ setupRequired: boolean }> {
|
export async function getBootstrapState(): Promise<{ setupRequired: boolean }> {
|
||||||
const data = await readData();
|
const database = getDatabase();
|
||||||
return { setupRequired: data.accounts.length === 0 };
|
const existingAccounts = await database.select({ id: accounts.id }).from(accounts).limit(1);
|
||||||
|
return { setupRequired: existingAccounts.length === 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setupFirstPlatformAdmin(input: {
|
||||||
|
organization: string;
|
||||||
|
name: string;
|
||||||
|
email: string;
|
||||||
|
password: string;
|
||||||
|
}): Promise<{ account: PublicAccount; session: Session }> {
|
||||||
|
const database = getDatabase();
|
||||||
|
const password = hashPassword(input.password);
|
||||||
|
const expiresAt = new Date(Date.now() + SESSION_MAX_AGE_SECONDS * 1000);
|
||||||
|
|
||||||
|
const created = await database.transaction(async (transaction) => {
|
||||||
|
const existingAccounts = await transaction.select({ id: accounts.id }).from(accounts).limit(1);
|
||||||
|
if (existingAccounts.length > 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const platformRoleRows = await transaction
|
||||||
|
.select()
|
||||||
|
.from(roles)
|
||||||
|
.where(and(eq(roles.key, "platform_admin"), isNull(roles.organizationId)))
|
||||||
|
.limit(1);
|
||||||
|
const platformRole = platformRoleRows[0];
|
||||||
|
if (!platformRole) {
|
||||||
|
throw new Error("平台超管角色未初始化,请先运行数据库初始化");
|
||||||
|
}
|
||||||
|
|
||||||
|
const organizationRows = await transaction
|
||||||
|
.insert(organizations)
|
||||||
|
.values({
|
||||||
|
name: input.organization.trim(),
|
||||||
|
slug: createSlug(input.organization),
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
const organization = organizationRows[0];
|
||||||
|
if (!organization) {
|
||||||
|
throw new Error("机构初始化失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
const accountRows = await transaction
|
||||||
|
.insert(accounts)
|
||||||
|
.values({
|
||||||
|
platformRoleId: platformRole.id,
|
||||||
|
name: input.name.trim(),
|
||||||
|
email: normalizeEmail(input.email),
|
||||||
|
passwordHash: password.hash,
|
||||||
|
passwordSalt: password.salt,
|
||||||
|
status: "active",
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
const account = accountRows[0];
|
||||||
|
if (!account) {
|
||||||
|
throw new Error("账号初始化失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
const sessionRows = await transaction
|
||||||
|
.insert(sessions)
|
||||||
|
.values({
|
||||||
|
accountId: account.id,
|
||||||
|
activeOrganizationId: organization.id,
|
||||||
|
expiresAt,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
const session = sessionRows[0];
|
||||||
|
if (!session) {
|
||||||
|
throw new Error("会话初始化失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
return { account, organization, platformRole, session };
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!created) {
|
||||||
|
throw new Error("系统已完成初始化");
|
||||||
|
}
|
||||||
|
|
||||||
|
await seedOrganizationRoles(created.organization.id);
|
||||||
|
const databaseAfterSeed = getDatabase();
|
||||||
|
const orgAdminRows = await databaseAfterSeed
|
||||||
|
.select()
|
||||||
|
.from(roles)
|
||||||
|
.where(and(eq(roles.organizationId, created.organization.id), eq(roles.key, "org_admin")))
|
||||||
|
.limit(1);
|
||||||
|
const orgAdminRole = orgAdminRows[0];
|
||||||
|
if (orgAdminRole) {
|
||||||
|
await databaseAfterSeed
|
||||||
|
.insert(memberships)
|
||||||
|
.values({
|
||||||
|
accountId: created.account.id,
|
||||||
|
organizationId: created.organization.id,
|
||||||
|
roleId: orgAdminRole.id,
|
||||||
|
status: "active",
|
||||||
|
})
|
||||||
|
.onConflictDoNothing();
|
||||||
|
}
|
||||||
|
|
||||||
|
const organization = toOrganization(created.organization);
|
||||||
|
const publicAccount = toPublicAccount(created.account, created.platformRole.key, organization);
|
||||||
|
const session = toSession(created.session);
|
||||||
|
|
||||||
|
await recordAuditLog({
|
||||||
|
actor: publicAccount,
|
||||||
|
organizationId: organization.id,
|
||||||
|
action: "account.setup",
|
||||||
|
targetType: "account",
|
||||||
|
targetId: publicAccount.id,
|
||||||
|
result: "success",
|
||||||
|
reason: "初始化平台超管与首个机构",
|
||||||
|
});
|
||||||
|
|
||||||
|
return { account: publicAccount, session };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createRegistration(input: {
|
||||||
|
name: string;
|
||||||
|
email: string;
|
||||||
|
password: string;
|
||||||
|
organizationId?: string;
|
||||||
|
}): Promise<{ account: PublicAccount; session: Session }> {
|
||||||
|
const database = getDatabase();
|
||||||
|
const password = hashPassword(input.password);
|
||||||
|
const expiresAt = new Date(Date.now() + SESSION_MAX_AGE_SECONDS * 1000);
|
||||||
|
|
||||||
|
const created = await database.transaction(async (transaction) => {
|
||||||
|
const normalizedEmail = normalizeEmail(input.email);
|
||||||
|
const existing = await transaction.select({ id: accounts.id }).from(accounts).where(eq(accounts.email, normalizedEmail));
|
||||||
|
if (existing.length > 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const accountRows = await transaction
|
||||||
|
.insert(accounts)
|
||||||
|
.values({
|
||||||
|
name: input.name.trim(),
|
||||||
|
email: normalizedEmail,
|
||||||
|
passwordHash: password.hash,
|
||||||
|
passwordSalt: password.salt,
|
||||||
|
status: input.organizationId ? "pending" : "active",
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
const account = accountRows[0];
|
||||||
|
if (!account) {
|
||||||
|
throw new Error("账号创建失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
const sessionRows = await transaction
|
||||||
|
.insert(sessions)
|
||||||
|
.values({
|
||||||
|
accountId: account.id,
|
||||||
|
activeOrganizationId: input.organizationId,
|
||||||
|
expiresAt,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
const session = sessionRows[0];
|
||||||
|
if (!session) {
|
||||||
|
throw new Error("会话创建失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.organizationId) {
|
||||||
|
await transaction.insert(joinRequests).values({
|
||||||
|
accountId: account.id,
|
||||||
|
organizationId: input.organizationId,
|
||||||
|
status: "pending",
|
||||||
|
reason: "公开注册申请加入机构",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return { account, session };
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!created) {
|
||||||
|
throw new Error("账号已存在");
|
||||||
|
}
|
||||||
|
|
||||||
|
const publicAccount = toPublicAccount(created.account);
|
||||||
|
const session = toSession(created.session);
|
||||||
|
await recordAuditLog({
|
||||||
|
actor: publicAccount,
|
||||||
|
organizationId: input.organizationId,
|
||||||
|
action: "account.register",
|
||||||
|
targetType: "account",
|
||||||
|
targetId: publicAccount.id,
|
||||||
|
result: "success",
|
||||||
|
reason: input.organizationId ? "注册账号并申请加入机构" : "注册独立账号",
|
||||||
|
});
|
||||||
|
|
||||||
|
return { account: publicAccount, session };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function loginWithPassword(input: {
|
||||||
|
email: string;
|
||||||
|
password: string;
|
||||||
|
}): Promise<{ account: PublicAccount; session: Session }> {
|
||||||
|
const database = getDatabase();
|
||||||
|
const accountRows = await database
|
||||||
|
.select()
|
||||||
|
.from(accounts)
|
||||||
|
.where(eq(accounts.email, normalizeEmail(input.email)))
|
||||||
|
.limit(1);
|
||||||
|
const account = accountRows[0];
|
||||||
|
|
||||||
|
if (!account || account.status === "disabled" || !verifyPassword(input.password, account)) {
|
||||||
|
throw new Error("邮箱或密码错误");
|
||||||
|
}
|
||||||
|
|
||||||
|
const membershipRows = await database
|
||||||
|
.select({ membership: memberships, organization: organizations, role: roles })
|
||||||
|
.from(memberships)
|
||||||
|
.innerJoin(organizations, eq(organizations.id, memberships.organizationId))
|
||||||
|
.innerJoin(roles, eq(roles.id, memberships.roleId))
|
||||||
|
.where(and(eq(memberships.accountId, account.id), eq(memberships.status, "active")))
|
||||||
|
.limit(1);
|
||||||
|
const membership = membershipRows[0];
|
||||||
|
const expiresAt = new Date(Date.now() + SESSION_MAX_AGE_SECONDS * 1000);
|
||||||
|
const sessionRows = await database
|
||||||
|
.insert(sessions)
|
||||||
|
.values({
|
||||||
|
accountId: account.id,
|
||||||
|
activeOrganizationId: membership?.organization.id,
|
||||||
|
expiresAt,
|
||||||
|
})
|
||||||
|
.returning();
|
||||||
|
const sessionRow = sessionRows[0];
|
||||||
|
if (!sessionRow) {
|
||||||
|
throw new Error("会话创建失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
const platformRoleRows = account.platformRoleId
|
||||||
|
? await database.select().from(roles).where(eq(roles.id, account.platformRoleId)).limit(1)
|
||||||
|
: [];
|
||||||
|
const platformRole = platformRoleRows[0];
|
||||||
|
const organization = membership ? toOrganization(membership.organization) : undefined;
|
||||||
|
const publicAccount = toPublicAccount(account, platformRole?.key ?? membership?.role.key, organization);
|
||||||
|
const session = toSession(sessionRow);
|
||||||
|
|
||||||
|
await recordAuditLog({
|
||||||
|
actor: publicAccount,
|
||||||
|
organizationId: organization?.id,
|
||||||
|
action: "account.login",
|
||||||
|
targetType: "account",
|
||||||
|
targetId: account.id,
|
||||||
|
result: "success",
|
||||||
|
reason: "账号登录",
|
||||||
|
});
|
||||||
|
|
||||||
|
return { account: publicAccount, session };
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getCurrentAuthContext(): Promise<AuthContext | null> {
|
export async function getCurrentAuthContext(): Promise<AuthContext | null> {
|
||||||
@@ -115,20 +389,54 @@ export async function getCurrentAuthContext(): Promise<AuthContext | null> {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await readData();
|
const database = getDatabase();
|
||||||
const session = data.sessions.find((item) => item.id === sessionId);
|
const rows = await database
|
||||||
if (!session || Date.parse(session.expiresAt) <= Date.now()) {
|
.select({ session: sessions, account: accounts })
|
||||||
|
.from(sessions)
|
||||||
|
.innerJoin(accounts, eq(accounts.id, sessions.accountId))
|
||||||
|
.where(and(eq(sessions.id, sessionId), gt(sessions.expiresAt, new Date())))
|
||||||
|
.limit(1);
|
||||||
|
const row = rows[0];
|
||||||
|
if (!row || row.account.status === "disabled") {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const account = data.accounts.find((item) => item.id === session.accountId);
|
const session = toSession(row.session);
|
||||||
if (!account || account.status !== "active") {
|
const platformRoleRows = row.account.platformRoleId
|
||||||
return null;
|
? await database.select().from(roles).where(eq(roles.id, row.account.platformRoleId)).limit(1)
|
||||||
}
|
: [];
|
||||||
|
const platformRole = platformRoleRows[0];
|
||||||
|
const organizationRows = row.session.activeOrganizationId
|
||||||
|
? await database.select().from(organizations).where(eq(organizations.id, row.session.activeOrganizationId)).limit(1)
|
||||||
|
: [];
|
||||||
|
const organizationRow = organizationRows[0];
|
||||||
|
const membershipRows = organizationRow
|
||||||
|
? await database
|
||||||
|
.select({ membership: memberships, role: roles })
|
||||||
|
.from(memberships)
|
||||||
|
.innerJoin(roles, eq(roles.id, memberships.roleId))
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(memberships.accountId, row.account.id),
|
||||||
|
eq(memberships.organizationId, organizationRow.id),
|
||||||
|
eq(memberships.status, "active"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.limit(1)
|
||||||
|
: [];
|
||||||
|
const membershipRow = membershipRows[0];
|
||||||
|
|
||||||
|
const platformPermissions = platformRole ? await getPermissionsForRole(platformRole.id) : [];
|
||||||
|
const organizationPermissions = membershipRow ? await getPermissionsForRole(membershipRow.role.id) : [];
|
||||||
|
const permissions = [...new Set([...platformPermissions, ...organizationPermissions])];
|
||||||
|
const organization = organizationRow ? toOrganization(organizationRow) : undefined;
|
||||||
|
const membership = membershipRow ? toMembership(membershipRow.membership, membershipRow.role) : undefined;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
account: toPublicAccount(account),
|
account: toPublicAccount(row.account, platformRole?.key ?? membership?.roleKey, organization),
|
||||||
permissions: getPermissionsForRole(account.role),
|
organization,
|
||||||
|
membership,
|
||||||
|
permissions,
|
||||||
session,
|
session,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -139,9 +447,8 @@ export async function removeCurrentSession(): Promise<PublicAccount | null> {
|
|||||||
const sessionId = cookieStore.get(SESSION_COOKIE)?.value;
|
const sessionId = cookieStore.get(SESSION_COOKIE)?.value;
|
||||||
|
|
||||||
if (sessionId) {
|
if (sessionId) {
|
||||||
await updateData((data) => {
|
const database = getDatabase();
|
||||||
data.sessions = data.sessions.filter((item) => item.id !== sessionId);
|
await database.delete(sessions).where(eq(sessions.id, sessionId));
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await clearSessionCookie();
|
await clearSessionCookie();
|
||||||
@@ -162,6 +469,7 @@ type DeniedAuditContext = {
|
|||||||
action: string;
|
action: string;
|
||||||
targetType: string;
|
targetType: string;
|
||||||
targetId?: string;
|
targetId?: string;
|
||||||
|
organizationId?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export async function requirePermission(
|
export async function requirePermission(
|
||||||
@@ -172,6 +480,7 @@ export async function requirePermission(
|
|||||||
|
|
||||||
if (!context) {
|
if (!context) {
|
||||||
await recordAuditLog({
|
await recordAuditLog({
|
||||||
|
organizationId: auditContext.organizationId,
|
||||||
action: auditContext.action,
|
action: auditContext.action,
|
||||||
targetType: auditContext.targetType,
|
targetType: auditContext.targetType,
|
||||||
targetId: auditContext.targetId,
|
targetId: auditContext.targetId,
|
||||||
@@ -185,9 +494,10 @@ export async function requirePermission(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!hasPermission(context.account.role, permission)) {
|
if (!hasPermission(context.permissions, permission)) {
|
||||||
await recordAuditLog({
|
await recordAuditLog({
|
||||||
actor: context.account,
|
actor: context.account,
|
||||||
|
organizationId: auditContext.organizationId ?? context.organization?.id,
|
||||||
action: auditContext.action,
|
action: auditContext.action,
|
||||||
targetType: auditContext.targetType,
|
targetType: auditContext.targetType,
|
||||||
targetId: auditContext.targetId,
|
targetId: auditContext.targetId,
|
||||||
|
|||||||
37
modules/core/server/db.ts
Normal file
37
modules/core/server/db.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import "server-only";
|
||||||
|
|
||||||
|
import { sql } from "drizzle-orm";
|
||||||
|
import { drizzle, type PostgresJsDatabase } from "drizzle-orm/postgres-js";
|
||||||
|
import postgres from "postgres";
|
||||||
|
|
||||||
|
import * as schema from "@/modules/core/server/schema";
|
||||||
|
|
||||||
|
export type AppDatabase = PostgresJsDatabase<typeof schema>;
|
||||||
|
|
||||||
|
let cachedDatabase: AppDatabase | null = null;
|
||||||
|
let cachedClient: postgres.Sql | null = null;
|
||||||
|
|
||||||
|
export function getDatabase(): AppDatabase {
|
||||||
|
const databaseUrl = process.env.DATABASE_URL;
|
||||||
|
if (!databaseUrl) {
|
||||||
|
throw new Error("DATABASE_URL is required for database-backed system configuration");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!cachedDatabase) {
|
||||||
|
cachedClient = postgres(databaseUrl, { max: 1 });
|
||||||
|
cachedDatabase = drizzle(cachedClient, { schema });
|
||||||
|
}
|
||||||
|
|
||||||
|
return cachedDatabase;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function checkDatabaseConnection(): Promise<{ ok: boolean; reason: string }> {
|
||||||
|
try {
|
||||||
|
const database = getDatabase();
|
||||||
|
await database.execute(sql`select 1`);
|
||||||
|
return { ok: true, reason: "数据库连接正常" };
|
||||||
|
} catch (error) {
|
||||||
|
const reason = error instanceof Error ? error.message : "数据库连接失败";
|
||||||
|
return { ok: false, reason };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,15 +1,97 @@
|
|||||||
import type { Permission, RoleDefinition, RoleId } from "@/modules/core/types";
|
import { and, eq, inArray, isNull, or } from "drizzle-orm";
|
||||||
import { ROLE_LABELS } from "@/modules/core/types";
|
|
||||||
|
|
||||||
export const ROLE_DEFINITIONS: RoleDefinition[] = [
|
import { getDatabase } from "@/modules/core/server/db";
|
||||||
|
import { permissions, rolePermissions, roles } from "@/modules/core/server/schema";
|
||||||
|
import type { Permission, RoleDefinition, RoleId } from "@/modules/core/types";
|
||||||
|
import { PERMISSIONS, ROLE_LABELS } from "@/modules/core/types";
|
||||||
|
|
||||||
|
type PermissionDefinition = {
|
||||||
|
id: Permission;
|
||||||
|
label: string;
|
||||||
|
category: string;
|
||||||
|
description: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const PERMISSION_DEFINITIONS: PermissionDefinition[] = [
|
||||||
|
{ id: "platform:manage", label: "平台管理", category: "平台", description: "管理平台级配置和跨机构操作。" },
|
||||||
|
{ id: "organization:read", label: "查看机构", category: "机构", description: "查看机构、院区和租户信息。" },
|
||||||
|
{ id: "organization:manage", label: "管理机构", category: "机构", description: "创建、编辑和停用机构。" },
|
||||||
|
{ id: "account:read", label: "查看用户", category: "用户", description: "查看账号、成员和申请。" },
|
||||||
|
{ id: "account:manage", label: "管理用户", category: "用户", description: "创建、审批、启停和分配用户。" },
|
||||||
|
{ id: "role:read", label: "查看角色", category: "权限", description: "查看角色和权限矩阵。" },
|
||||||
|
{ id: "role:manage", label: "管理角色", category: "权限", description: "创建自定义角色并配置权限组合。" },
|
||||||
|
{ id: "permission:read", label: "查看权限", category: "权限", description: "查看系统注册权限点。" },
|
||||||
|
{ id: "audit:read", label: "查看审计", category: "审计", description: "查看关键操作审计日志。" },
|
||||||
|
{ id: "incident:read", label: "查看故障", category: "运维", description: "查看系统健康和故障中心。" },
|
||||||
|
{ id: "incident:manage", label: "处理故障", category: "运维", description: "确认、处理和关闭故障事件。" },
|
||||||
|
{ id: "facility:read", label: "查看房间床位", category: "床位", description: "查看房间、床位和占用状态。" },
|
||||||
|
{ id: "facility:manage", label: "管理房间床位", category: "床位", description: "维护院区、房间、床位和床位状态。" },
|
||||||
|
{ id: "admission:read", label: "查看入住", category: "入住", description: "查看入住、换床、退住历史。" },
|
||||||
|
{ id: "admission:manage", label: "管理入住", category: "入住", description: "办理入住、换床和退住。" },
|
||||||
|
{ id: "elder:read", label: "查看老人档案", category: "老人", description: "查看老人基础档案。" },
|
||||||
|
{ id: "elder:create", label: "新增老人档案", category: "老人", description: "创建老人档案。" },
|
||||||
|
{ id: "elder:update", label: "更新老人档案", category: "老人", description: "更新老人档案和照护信息。" },
|
||||||
|
{ id: "elder:delete", label: "删除老人档案", category: "老人", description: "删除老人档案。" },
|
||||||
|
];
|
||||||
|
|
||||||
|
type SeedRole = {
|
||||||
|
key: RoleId;
|
||||||
|
scope: "platform" | "organization";
|
||||||
|
description: string;
|
||||||
|
permissions: Permission[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export const SYSTEM_ROLE_DEFINITIONS: SeedRole[] = [
|
||||||
{
|
{
|
||||||
id: "admin",
|
key: "platform_admin",
|
||||||
label: ROLE_LABELS.admin,
|
scope: "platform",
|
||||||
description: "管理账号、权限、审计日志与全部业务数据。",
|
description: "平台最高权限,管理所有机构、角色、审计和故障中心。",
|
||||||
|
permissions: [...PERMISSIONS],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "platform_operator",
|
||||||
|
scope: "platform",
|
||||||
|
description: "平台运营角色,管理机构和跨机构用户配置。",
|
||||||
permissions: [
|
permissions: [
|
||||||
|
"organization:read",
|
||||||
|
"organization:manage",
|
||||||
"account:read",
|
"account:read",
|
||||||
"account:manage",
|
"account:manage",
|
||||||
|
"role:read",
|
||||||
|
"permission:read",
|
||||||
"audit:read",
|
"audit:read",
|
||||||
|
"incident:read",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "platform_auditor",
|
||||||
|
scope: "platform",
|
||||||
|
description: "平台审计角色,只读查看机构、审计和故障。",
|
||||||
|
permissions: ["organization:read", "account:read", "role:read", "permission:read", "audit:read", "incident:read"],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "platform_ops",
|
||||||
|
scope: "platform",
|
||||||
|
description: "平台运维角色,处理系统故障和运行状态。",
|
||||||
|
permissions: ["organization:read", "audit:read", "incident:read", "incident:manage"],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "org_admin",
|
||||||
|
scope: "organization",
|
||||||
|
description: "机构管理员,管理本机构用户、角色、房间床位、入住和审计。",
|
||||||
|
permissions: [
|
||||||
|
"organization:read",
|
||||||
|
"account:read",
|
||||||
|
"account:manage",
|
||||||
|
"role:read",
|
||||||
|
"role:manage",
|
||||||
|
"permission:read",
|
||||||
|
"audit:read",
|
||||||
|
"incident:read",
|
||||||
|
"facility:read",
|
||||||
|
"facility:manage",
|
||||||
|
"admission:read",
|
||||||
|
"admission:manage",
|
||||||
"elder:read",
|
"elder:read",
|
||||||
"elder:create",
|
"elder:create",
|
||||||
"elder:update",
|
"elder:update",
|
||||||
@@ -17,43 +99,160 @@ export const ROLE_DEFINITIONS: RoleDefinition[] = [
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: "manager",
|
key: "manager",
|
||||||
label: ROLE_LABELS.manager,
|
scope: "organization",
|
||||||
description: "处理运营业务,可查看账号与审计日志,不管理账号角色。",
|
description: "运营主管,处理老人档案、床位入住和审计查看。",
|
||||||
permissions: ["account:read", "audit:read", "elder:read", "elder:create", "elder:update", "elder:delete"],
|
permissions: [
|
||||||
|
"account:read",
|
||||||
|
"role:read",
|
||||||
|
"audit:read",
|
||||||
|
"facility:read",
|
||||||
|
"facility:manage",
|
||||||
|
"admission:read",
|
||||||
|
"admission:manage",
|
||||||
|
"elder:read",
|
||||||
|
"elder:create",
|
||||||
|
"elder:update",
|
||||||
|
"elder:delete",
|
||||||
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: "caregiver",
|
key: "caregiver",
|
||||||
label: ROLE_LABELS.caregiver,
|
scope: "organization",
|
||||||
description: "查看老人档案并维护照护相关信息。",
|
description: "照护人员,查看床位和维护老人照护信息。",
|
||||||
permissions: ["elder:read", "elder:update"],
|
permissions: ["facility:read", "admission:read", "elder:read", "elder:update"],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: "viewer",
|
key: "viewer",
|
||||||
label: ROLE_LABELS.viewer,
|
scope: "organization",
|
||||||
description: "只读查看老人档案。",
|
description: "只读访客,查看老人、床位和入住信息。",
|
||||||
permissions: ["elder:read"],
|
permissions: ["facility:read", "admission:read", "elder:read"],
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
export function getRoleDefinition(role: RoleId): RoleDefinition {
|
export async function ensureSystemDefaults(): Promise<void> {
|
||||||
const roleDefinition = ROLE_DEFINITIONS.find((item) => item.id === role);
|
const database = getDatabase();
|
||||||
if (roleDefinition) {
|
|
||||||
return roleDefinition;
|
await database
|
||||||
|
.insert(permissions)
|
||||||
|
.values(PERMISSION_DEFINITIONS)
|
||||||
|
.onConflictDoUpdate({
|
||||||
|
target: permissions.id,
|
||||||
|
set: {
|
||||||
|
label: permissions.label,
|
||||||
|
category: permissions.category,
|
||||||
|
description: permissions.description,
|
||||||
|
isEnabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const existingRoles = await database.select().from(roles).where(isNull(roles.organizationId));
|
||||||
|
const existingRoleKeys = new Set(existingRoles.map((role) => role.key));
|
||||||
|
const seedRoles = SYSTEM_ROLE_DEFINITIONS.filter((role) => role.scope === "platform" && !existingRoleKeys.has(role.key));
|
||||||
|
|
||||||
|
if (seedRoles.length > 0) {
|
||||||
|
await database.insert(roles).values(
|
||||||
|
seedRoles.map((role) => ({
|
||||||
|
key: role.key,
|
||||||
|
scope: role.scope,
|
||||||
|
label: ROLE_LABELS[role.key],
|
||||||
|
description: role.description,
|
||||||
|
isSystem: true,
|
||||||
|
isEnabled: true,
|
||||||
|
})),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
const platformRoles = await database.select().from(roles).where(isNull(roles.organizationId));
|
||||||
id: "viewer",
|
const inserts = platformRoles.flatMap((role) => {
|
||||||
label: ROLE_LABELS.viewer,
|
const definition = SYSTEM_ROLE_DEFINITIONS.find((item) => item.key === role.key);
|
||||||
description: "只读查看老人档案。",
|
if (!definition) {
|
||||||
permissions: ["elder:read"],
|
return [];
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getPermissionsForRole(role: RoleId): Permission[] {
|
return definition.permissions.map((permissionId) => ({
|
||||||
return [...getRoleDefinition(role).permissions];
|
roleId: role.id,
|
||||||
|
permissionId,
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
if (inserts.length > 0) {
|
||||||
|
await database.insert(rolePermissions).values(inserts).onConflictDoNothing();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function hasPermission(role: RoleId, permission: Permission): boolean {
|
export async function seedOrganizationRoles(organizationId: string): Promise<void> {
|
||||||
return getRoleDefinition(role).permissions.includes(permission);
|
const database = getDatabase();
|
||||||
|
const organizationRoles = SYSTEM_ROLE_DEFINITIONS.filter((role) => role.scope === "organization");
|
||||||
|
|
||||||
|
await database
|
||||||
|
.insert(roles)
|
||||||
|
.values(
|
||||||
|
organizationRoles.map((role) => ({
|
||||||
|
key: role.key,
|
||||||
|
organizationId,
|
||||||
|
scope: role.scope,
|
||||||
|
label: ROLE_LABELS[role.key],
|
||||||
|
description: role.description,
|
||||||
|
isSystem: true,
|
||||||
|
isEnabled: true,
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
.onConflictDoNothing();
|
||||||
|
|
||||||
|
const seededRoles = await database
|
||||||
|
.select()
|
||||||
|
.from(roles)
|
||||||
|
.where(and(eq(roles.organizationId, organizationId), inArray(roles.key, organizationRoles.map((role) => role.key))));
|
||||||
|
|
||||||
|
const inserts = seededRoles.flatMap((role) => {
|
||||||
|
const definition = SYSTEM_ROLE_DEFINITIONS.find((item) => item.key === role.key);
|
||||||
|
if (!definition) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return definition.permissions.map((permissionId) => ({ roleId: role.id, permissionId }));
|
||||||
|
});
|
||||||
|
|
||||||
|
if (inserts.length > 0) {
|
||||||
|
await database.insert(rolePermissions).values(inserts).onConflictDoNothing();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getRoleDefinitions(organizationId?: string): Promise<RoleDefinition[]> {
|
||||||
|
const database = getDatabase();
|
||||||
|
const rows = await database
|
||||||
|
.select()
|
||||||
|
.from(roles)
|
||||||
|
.where(organizationId ? or(isNull(roles.organizationId), eq(roles.organizationId, organizationId)) : isNull(roles.organizationId));
|
||||||
|
|
||||||
|
const roleIds = rows.map((role) => role.id);
|
||||||
|
const permissionRows =
|
||||||
|
roleIds.length > 0
|
||||||
|
? await database.select().from(rolePermissions).where(inArray(rolePermissions.roleId, roleIds))
|
||||||
|
: [];
|
||||||
|
|
||||||
|
return rows.map((role) => ({
|
||||||
|
id: role.id,
|
||||||
|
key: role.key,
|
||||||
|
label: role.label,
|
||||||
|
description: role.description,
|
||||||
|
scope: role.scope,
|
||||||
|
organizationId: role.organizationId ?? undefined,
|
||||||
|
isSystem: role.isSystem,
|
||||||
|
isEnabled: role.isEnabled,
|
||||||
|
permissions: permissionRows
|
||||||
|
.filter((permission) => permission.roleId === role.id)
|
||||||
|
.map((permission) => permission.permissionId as Permission),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getPermissionsForRole(roleId: string): Promise<Permission[]> {
|
||||||
|
const database = getDatabase();
|
||||||
|
const rows = await database.select().from(rolePermissions).where(eq(rolePermissions.roleId, roleId));
|
||||||
|
return rows.map((row) => row.permissionId as Permission);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasPermission(permissionsList: readonly Permission[], permission: Permission): boolean {
|
||||||
|
return permissionsList.includes(permission);
|
||||||
}
|
}
|
||||||
|
|||||||
227
modules/core/server/schema.ts
Normal file
227
modules/core/server/schema.ts
Normal file
@@ -0,0 +1,227 @@
|
|||||||
|
import {
|
||||||
|
boolean,
|
||||||
|
integer,
|
||||||
|
pgEnum,
|
||||||
|
pgTable,
|
||||||
|
primaryKey,
|
||||||
|
text,
|
||||||
|
timestamp,
|
||||||
|
uniqueIndex,
|
||||||
|
uuid,
|
||||||
|
} from "drizzle-orm/pg-core";
|
||||||
|
|
||||||
|
export const accountStatusEnum = pgEnum("account_status", ["active", "disabled", "pending"]);
|
||||||
|
export const organizationStatusEnum = pgEnum("organization_status", ["active", "disabled"]);
|
||||||
|
export const roleScopeEnum = pgEnum("role_scope", ["platform", "organization"]);
|
||||||
|
export const membershipStatusEnum = pgEnum("membership_status", ["active", "disabled", "pending"]);
|
||||||
|
export const bedStatusEnum = pgEnum("bed_status", ["available", "occupied", "maintenance", "disabled"]);
|
||||||
|
export const elderStatusEnum = pgEnum("elder_status", ["active", "pending", "discharged"]);
|
||||||
|
export const careLevelEnum = pgEnum("care_level", ["self-care", "semi-assisted", "assisted", "intensive"]);
|
||||||
|
export const genderEnum = pgEnum("gender", ["male", "female", "other"]);
|
||||||
|
export const admissionStatusEnum = pgEnum("admission_status", ["active", "transferred", "discharged"]);
|
||||||
|
export const auditResultEnum = pgEnum("audit_result", ["success", "denied", "failure"]);
|
||||||
|
export const incidentStatusEnum = pgEnum("incident_status", ["open", "acknowledged", "resolved", "closed"]);
|
||||||
|
export const incidentSeverityEnum = pgEnum("incident_severity", ["info", "warning", "critical"]);
|
||||||
|
export const joinRequestStatusEnum = pgEnum("join_request_status", ["pending", "approved", "rejected"]);
|
||||||
|
|
||||||
|
export const organizations = pgTable("organizations", {
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
name: text("name").notNull(),
|
||||||
|
slug: text("slug").notNull(),
|
||||||
|
status: organizationStatusEnum("status").notNull().default("active"),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
}, (table) => ({
|
||||||
|
slugUnique: uniqueIndex("organizations_slug_unique").on(table.slug),
|
||||||
|
}));
|
||||||
|
|
||||||
|
export const permissions = pgTable("permissions", {
|
||||||
|
id: text("id").primaryKey(),
|
||||||
|
label: text("label").notNull(),
|
||||||
|
category: text("category").notNull(),
|
||||||
|
description: text("description").notNull(),
|
||||||
|
isEnabled: boolean("is_enabled").notNull().default(true),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const roles = pgTable("roles", {
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
key: text("key").notNull(),
|
||||||
|
organizationId: uuid("organization_id").references(() => organizations.id, { onDelete: "cascade" }),
|
||||||
|
scope: roleScopeEnum("scope").notNull(),
|
||||||
|
label: text("label").notNull(),
|
||||||
|
description: text("description").notNull(),
|
||||||
|
isSystem: boolean("is_system").notNull().default(false),
|
||||||
|
isEnabled: boolean("is_enabled").notNull().default(true),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
}, (table) => ({
|
||||||
|
roleKeyUnique: uniqueIndex("roles_key_organization_unique").on(table.key, table.organizationId),
|
||||||
|
}));
|
||||||
|
|
||||||
|
export const rolePermissions = pgTable("role_permissions", {
|
||||||
|
roleId: uuid("role_id").notNull().references(() => roles.id, { onDelete: "cascade" }),
|
||||||
|
permissionId: text("permission_id").notNull().references(() => permissions.id, { onDelete: "cascade" }),
|
||||||
|
}, (table) => ({
|
||||||
|
pk: primaryKey({ columns: [table.roleId, table.permissionId] }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
export const accounts = pgTable("accounts", {
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
platformRoleId: uuid("platform_role_id").references(() => roles.id),
|
||||||
|
name: text("name").notNull(),
|
||||||
|
email: text("email").notNull(),
|
||||||
|
passwordHash: text("password_hash").notNull(),
|
||||||
|
passwordSalt: text("password_salt").notNull(),
|
||||||
|
status: accountStatusEnum("status").notNull().default("active"),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
}, (table) => ({
|
||||||
|
emailUnique: uniqueIndex("accounts_email_unique").on(table.email),
|
||||||
|
}));
|
||||||
|
|
||||||
|
export const memberships = pgTable("memberships", {
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
accountId: uuid("account_id").notNull().references(() => accounts.id, { onDelete: "cascade" }),
|
||||||
|
organizationId: uuid("organization_id").notNull().references(() => organizations.id, { onDelete: "cascade" }),
|
||||||
|
roleId: uuid("role_id").notNull().references(() => roles.id),
|
||||||
|
status: membershipStatusEnum("status").notNull().default("active"),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
}, (table) => ({
|
||||||
|
accountOrganizationUnique: uniqueIndex("memberships_account_organization_unique").on(
|
||||||
|
table.accountId,
|
||||||
|
table.organizationId,
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
|
||||||
|
export const sessions = pgTable("sessions", {
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
accountId: uuid("account_id").notNull().references(() => accounts.id, { onDelete: "cascade" }),
|
||||||
|
activeOrganizationId: uuid("active_organization_id").references(() => organizations.id),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const joinRequests = pgTable("join_requests", {
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
accountId: uuid("account_id").notNull().references(() => accounts.id, { onDelete: "cascade" }),
|
||||||
|
organizationId: uuid("organization_id").notNull().references(() => organizations.id, { onDelete: "cascade" }),
|
||||||
|
status: joinRequestStatusEnum("status").notNull().default("pending"),
|
||||||
|
reason: text("reason").notNull().default(""),
|
||||||
|
reviewedByAccountId: uuid("reviewed_by_account_id").references(() => accounts.id),
|
||||||
|
reviewedAt: timestamp("reviewed_at", { withTimezone: true }),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const campuses = pgTable("campuses", {
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
organizationId: uuid("organization_id").notNull().references(() => organizations.id, { onDelete: "cascade" }),
|
||||||
|
name: text("name").notNull(),
|
||||||
|
address: text("address").notNull().default(""),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const buildings = pgTable("buildings", {
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
organizationId: uuid("organization_id").notNull().references(() => organizations.id, { onDelete: "cascade" }),
|
||||||
|
campusId: uuid("campus_id").notNull().references(() => campuses.id, { onDelete: "cascade" }),
|
||||||
|
name: text("name").notNull(),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const floors = pgTable("floors", {
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
organizationId: uuid("organization_id").notNull().references(() => organizations.id, { onDelete: "cascade" }),
|
||||||
|
buildingId: uuid("building_id").notNull().references(() => buildings.id, { onDelete: "cascade" }),
|
||||||
|
name: text("name").notNull(),
|
||||||
|
level: integer("level").notNull(),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const rooms = pgTable("rooms", {
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
organizationId: uuid("organization_id").notNull().references(() => organizations.id, { onDelete: "cascade" }),
|
||||||
|
floorId: uuid("floor_id").notNull().references(() => floors.id, { onDelete: "cascade" }),
|
||||||
|
name: text("name").notNull(),
|
||||||
|
code: text("code").notNull(),
|
||||||
|
capacity: integer("capacity").notNull().default(1),
|
||||||
|
status: organizationStatusEnum("status").notNull().default("active"),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
}, (table) => ({
|
||||||
|
roomCodeUnique: uniqueIndex("rooms_code_organization_unique").on(table.organizationId, table.code),
|
||||||
|
}));
|
||||||
|
|
||||||
|
export const beds = pgTable("beds", {
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
organizationId: uuid("organization_id").notNull().references(() => organizations.id, { onDelete: "cascade" }),
|
||||||
|
roomId: uuid("room_id").notNull().references(() => rooms.id, { onDelete: "cascade" }),
|
||||||
|
code: text("code").notNull(),
|
||||||
|
status: bedStatusEnum("status").notNull().default("available"),
|
||||||
|
notes: text("notes").notNull().default(""),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
}, (table) => ({
|
||||||
|
bedCodeUnique: uniqueIndex("beds_code_room_unique").on(table.roomId, table.code),
|
||||||
|
}));
|
||||||
|
|
||||||
|
export const elders = pgTable("elders", {
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
organizationId: uuid("organization_id").notNull().references(() => organizations.id, { onDelete: "cascade" }),
|
||||||
|
name: text("name").notNull(),
|
||||||
|
gender: genderEnum("gender").notNull(),
|
||||||
|
age: integer("age").notNull(),
|
||||||
|
careLevel: careLevelEnum("care_level").notNull(),
|
||||||
|
status: elderStatusEnum("status").notNull().default("pending"),
|
||||||
|
primaryContact: text("primary_contact").notNull(),
|
||||||
|
phone: text("phone").notNull(),
|
||||||
|
medicalNotes: text("medical_notes").notNull().default(""),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const admissions = pgTable("admissions", {
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
organizationId: uuid("organization_id").notNull().references(() => organizations.id, { onDelete: "cascade" }),
|
||||||
|
elderId: uuid("elder_id").notNull().references(() => elders.id, { onDelete: "cascade" }),
|
||||||
|
bedId: uuid("bed_id").notNull().references(() => beds.id),
|
||||||
|
status: admissionStatusEnum("status").notNull().default("active"),
|
||||||
|
admittedAt: timestamp("admitted_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
dischargedAt: timestamp("discharged_at", { withTimezone: true }),
|
||||||
|
notes: text("notes").notNull().default(""),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const auditLogs = pgTable("audit_logs", {
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
organizationId: uuid("organization_id").references(() => organizations.id, { onDelete: "cascade" }),
|
||||||
|
timestamp: timestamp("timestamp", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
actorAccountId: uuid("actor_account_id").references(() => accounts.id),
|
||||||
|
actorEmail: text("actor_email"),
|
||||||
|
action: text("action").notNull(),
|
||||||
|
targetType: text("target_type").notNull(),
|
||||||
|
targetId: text("target_id"),
|
||||||
|
result: auditResultEnum("result").notNull(),
|
||||||
|
reason: text("reason").notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const systemIncidents = pgTable("system_incidents", {
|
||||||
|
id: uuid("id").primaryKey().defaultRandom(),
|
||||||
|
organizationId: uuid("organization_id").references(() => organizations.id, { onDelete: "cascade" }),
|
||||||
|
severity: incidentSeverityEnum("severity").notNull(),
|
||||||
|
status: incidentStatusEnum("status").notNull().default("open"),
|
||||||
|
title: text("title").notNull(),
|
||||||
|
description: text("description").notNull(),
|
||||||
|
source: text("source").notNull(),
|
||||||
|
acknowledgedByAccountId: uuid("acknowledged_by_account_id").references(() => accounts.id),
|
||||||
|
acknowledgedAt: timestamp("acknowledged_at", { withTimezone: true }),
|
||||||
|
resolvedByAccountId: uuid("resolved_by_account_id").references(() => accounts.id),
|
||||||
|
resolvedAt: timestamp("resolved_at", { withTimezone: true }),
|
||||||
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||||
|
});
|
||||||
@@ -1,63 +1,223 @@
|
|||||||
import { promises as fs } from "node:fs";
|
import { desc, eq, sql } from "drizzle-orm";
|
||||||
import path from "node:path";
|
|
||||||
|
|
||||||
import type { AppData } from "@/modules/core/types";
|
import { listAuditLogs } from "@/modules/core/server/audit";
|
||||||
|
import { getDatabase } from "@/modules/core/server/db";
|
||||||
|
import {
|
||||||
|
accounts,
|
||||||
|
admissions,
|
||||||
|
beds,
|
||||||
|
elders,
|
||||||
|
memberships,
|
||||||
|
organizations,
|
||||||
|
roles,
|
||||||
|
rooms,
|
||||||
|
sessions,
|
||||||
|
systemIncidents,
|
||||||
|
} from "@/modules/core/server/schema";
|
||||||
|
import type { Account, Admission, AppData, FacilityBed, Membership, Organization, Room, Session, SystemIncident } from "@/modules/core/types";
|
||||||
|
import type { Elder } from "@/modules/elders/types";
|
||||||
|
|
||||||
const DATA_DIR = process.env.TEATEA_DATA_DIR ?? path.join(process.cwd(), ".data");
|
function iso(value: Date): string {
|
||||||
const DATA_FILE = path.join(DATA_DIR, "teatea.json");
|
return value.toISOString();
|
||||||
|
|
||||||
function createEmptyData(): AppData {
|
|
||||||
return {
|
|
||||||
accounts: [],
|
|
||||||
sessions: [],
|
|
||||||
elders: [],
|
|
||||||
auditLogs: [],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeData(data: Partial<AppData>): AppData {
|
|
||||||
return {
|
|
||||||
accounts: Array.isArray(data.accounts) ? data.accounts : [],
|
|
||||||
sessions: Array.isArray(data.sessions) ? data.sessions : [],
|
|
||||||
elders: Array.isArray(data.elders) ? data.elders : [],
|
|
||||||
auditLogs: Array.isArray(data.auditLogs) ? data.auditLogs : [],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function isMissingFileError(error: unknown): boolean {
|
|
||||||
return (
|
|
||||||
typeof error === "object" &&
|
|
||||||
error !== null &&
|
|
||||||
"code" in error &&
|
|
||||||
(error as { code?: unknown }).code === "ENOENT"
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function readData(): Promise<AppData> {
|
export async function readData(): Promise<AppData> {
|
||||||
try {
|
const database = getDatabase();
|
||||||
const raw = await fs.readFile(DATA_FILE, "utf8");
|
const [
|
||||||
const parsed = JSON.parse(raw) as Partial<AppData>;
|
organizationRows,
|
||||||
return normalizeData(parsed);
|
accountRows,
|
||||||
} catch (error) {
|
membershipRows,
|
||||||
if (isMissingFileError(error)) {
|
sessionRows,
|
||||||
return createEmptyData();
|
elderRows,
|
||||||
|
roomRows,
|
||||||
|
bedRows,
|
||||||
|
admissionRows,
|
||||||
|
auditLogRows,
|
||||||
|
incidentRows,
|
||||||
|
] = await Promise.all([
|
||||||
|
database.select().from(organizations).orderBy(desc(organizations.createdAt)),
|
||||||
|
database.select().from(accounts).orderBy(desc(accounts.createdAt)),
|
||||||
|
database.select({ membership: memberships, role: roles }).from(memberships).innerJoin(roles, eq(roles.id, memberships.roleId)),
|
||||||
|
database.select().from(sessions).orderBy(desc(sessions.createdAt)),
|
||||||
|
database.select().from(elders).orderBy(desc(elders.createdAt)),
|
||||||
|
database.select().from(rooms).orderBy(desc(rooms.createdAt)),
|
||||||
|
database
|
||||||
|
.select({
|
||||||
|
bed: beds,
|
||||||
|
roomName: rooms.name,
|
||||||
|
currentElderName: sql<string | null>`(
|
||||||
|
select ${elders.name}
|
||||||
|
from ${admissions}
|
||||||
|
inner join ${elders} on ${elders.id} = ${admissions.elderId}
|
||||||
|
where ${admissions.bedId} = ${beds.id} and ${admissions.status} = 'active'
|
||||||
|
limit 1
|
||||||
|
)`,
|
||||||
|
})
|
||||||
|
.from(beds)
|
||||||
|
.innerJoin(rooms, eq(rooms.id, beds.roomId))
|
||||||
|
.orderBy(desc(beds.createdAt)),
|
||||||
|
database
|
||||||
|
.select({
|
||||||
|
admission: admissions,
|
||||||
|
elderName: elders.name,
|
||||||
|
bedCode: beds.code,
|
||||||
|
roomName: rooms.name,
|
||||||
|
})
|
||||||
|
.from(admissions)
|
||||||
|
.innerJoin(elders, eq(elders.id, admissions.elderId))
|
||||||
|
.innerJoin(beds, eq(beds.id, admissions.bedId))
|
||||||
|
.innerJoin(rooms, eq(rooms.id, beds.roomId))
|
||||||
|
.orderBy(desc(admissions.admittedAt)),
|
||||||
|
listAuditLogs({ limit: 100 }),
|
||||||
|
database.select().from(systemIncidents).orderBy(desc(systemIncidents.createdAt)),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const roleById = new Map(membershipRows.map((row) => [row.membership.id, row.role]));
|
||||||
|
const bedCounts = new Map<string, { total: number; occupied: number }>();
|
||||||
|
for (const row of bedRows) {
|
||||||
|
const current = bedCounts.get(row.bed.roomId) ?? { total: 0, occupied: 0 };
|
||||||
|
current.total += 1;
|
||||||
|
if (row.bed.status === "occupied") {
|
||||||
|
current.occupied += 1;
|
||||||
|
}
|
||||||
|
bedCounts.set(row.bed.roomId, current);
|
||||||
}
|
}
|
||||||
|
|
||||||
throw error;
|
const organizationsData: Organization[] = organizationRows.map((row) => ({
|
||||||
}
|
id: row.id,
|
||||||
|
name: row.name,
|
||||||
|
slug: row.slug,
|
||||||
|
status: row.status,
|
||||||
|
createdAt: iso(row.createdAt),
|
||||||
|
updatedAt: iso(row.updatedAt),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const accountsData: Account[] = accountRows.map((row) => ({
|
||||||
|
id: row.id,
|
||||||
|
platformRoleId: row.platformRoleId ?? undefined,
|
||||||
|
name: row.name,
|
||||||
|
email: row.email,
|
||||||
|
role: row.platformRoleId ?? "viewer",
|
||||||
|
passwordHash: row.passwordHash,
|
||||||
|
passwordSalt: row.passwordSalt,
|
||||||
|
status: row.status,
|
||||||
|
createdAt: iso(row.createdAt),
|
||||||
|
updatedAt: iso(row.updatedAt),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const membershipsData: Membership[] = membershipRows.map((row) => {
|
||||||
|
const role = roleById.get(row.membership.id) ?? row.role;
|
||||||
|
return {
|
||||||
|
id: row.membership.id,
|
||||||
|
accountId: row.membership.accountId,
|
||||||
|
organizationId: row.membership.organizationId,
|
||||||
|
roleId: row.membership.roleId,
|
||||||
|
roleKey: role.key,
|
||||||
|
roleLabel: role.label,
|
||||||
|
status: row.membership.status,
|
||||||
|
createdAt: iso(row.membership.createdAt),
|
||||||
|
updatedAt: iso(row.membership.updatedAt),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const sessionsData: Session[] = sessionRows.map((row) => ({
|
||||||
|
id: row.id,
|
||||||
|
accountId: row.accountId,
|
||||||
|
activeOrganizationId: row.activeOrganizationId ?? undefined,
|
||||||
|
createdAt: iso(row.createdAt),
|
||||||
|
expiresAt: iso(row.expiresAt),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const eldersData: Elder[] = elderRows.map((row) => ({
|
||||||
|
id: row.id,
|
||||||
|
organizationId: row.organizationId,
|
||||||
|
name: row.name,
|
||||||
|
gender: row.gender,
|
||||||
|
age: row.age,
|
||||||
|
careLevel: row.careLevel,
|
||||||
|
room: "",
|
||||||
|
bed: "",
|
||||||
|
status: row.status,
|
||||||
|
primaryContact: row.primaryContact,
|
||||||
|
phone: row.phone,
|
||||||
|
medicalNotes: row.medicalNotes,
|
||||||
|
createdAt: iso(row.createdAt),
|
||||||
|
updatedAt: iso(row.updatedAt),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const roomsData: Room[] = roomRows.map((row) => {
|
||||||
|
const counts = bedCounts.get(row.id) ?? { total: 0, occupied: 0 };
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
organizationId: row.organizationId,
|
||||||
|
name: row.name,
|
||||||
|
code: row.code,
|
||||||
|
capacity: row.capacity,
|
||||||
|
status: row.status,
|
||||||
|
bedCount: counts.total,
|
||||||
|
occupiedBedCount: counts.occupied,
|
||||||
|
createdAt: iso(row.createdAt),
|
||||||
|
updatedAt: iso(row.updatedAt),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const bedsData: FacilityBed[] = bedRows.map((row) => ({
|
||||||
|
id: row.bed.id,
|
||||||
|
organizationId: row.bed.organizationId,
|
||||||
|
roomId: row.bed.roomId,
|
||||||
|
roomName: row.roomName,
|
||||||
|
code: row.bed.code,
|
||||||
|
status: row.bed.status,
|
||||||
|
notes: row.bed.notes,
|
||||||
|
currentElderName: row.currentElderName ?? undefined,
|
||||||
|
createdAt: iso(row.bed.createdAt),
|
||||||
|
updatedAt: iso(row.bed.updatedAt),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const admissionsData: Admission[] = admissionRows.map((row) => ({
|
||||||
|
id: row.admission.id,
|
||||||
|
organizationId: row.admission.organizationId,
|
||||||
|
elderId: row.admission.elderId,
|
||||||
|
elderName: row.elderName,
|
||||||
|
bedId: row.admission.bedId,
|
||||||
|
bedCode: row.bedCode,
|
||||||
|
roomName: row.roomName,
|
||||||
|
status: row.admission.status,
|
||||||
|
admittedAt: iso(row.admission.admittedAt),
|
||||||
|
dischargedAt: row.admission.dischargedAt ? iso(row.admission.dischargedAt) : undefined,
|
||||||
|
notes: row.admission.notes,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const incidentsData: SystemIncident[] = incidentRows.map((row) => ({
|
||||||
|
id: row.id,
|
||||||
|
organizationId: row.organizationId ?? undefined,
|
||||||
|
severity: row.severity,
|
||||||
|
status: row.status,
|
||||||
|
title: row.title,
|
||||||
|
description: row.description,
|
||||||
|
source: row.source,
|
||||||
|
createdAt: iso(row.createdAt),
|
||||||
|
updatedAt: iso(row.updatedAt),
|
||||||
|
}));
|
||||||
|
|
||||||
|
return {
|
||||||
|
organizations: organizationsData,
|
||||||
|
accounts: accountsData,
|
||||||
|
memberships: membershipsData,
|
||||||
|
sessions: sessionsData,
|
||||||
|
elders: eldersData,
|
||||||
|
rooms: roomsData,
|
||||||
|
beds: bedsData,
|
||||||
|
admissions: admissionsData,
|
||||||
|
auditLogs: auditLogRows,
|
||||||
|
incidents: incidentsData,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function writeData(data: AppData): Promise<void> {
|
export async function writeData(): Promise<void> {
|
||||||
await fs.mkdir(DATA_DIR, { recursive: true });
|
throw new Error("writeData is not available after PostgreSQL migration");
|
||||||
const temporaryFile = `${DATA_FILE}.tmp`;
|
|
||||||
await fs.writeFile(temporaryFile, JSON.stringify(data, null, 2), "utf8");
|
|
||||||
await fs.rename(temporaryFile, DATA_FILE);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function updateData<T>(mutator: (data: AppData) => T): Promise<T> {
|
export async function updateData<T>(): Promise<T> {
|
||||||
const data = await readData();
|
throw new Error("updateData is not available after PostgreSQL migration");
|
||||||
const result = mutator(data);
|
|
||||||
await writeData(data);
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,19 +1,44 @@
|
|||||||
import type { Elder } from "@/modules/elders/types";
|
import type { Elder } from "@/modules/elders/types";
|
||||||
|
|
||||||
export const ROLE_IDS = ["admin", "manager", "caregiver", "viewer"] as const;
|
export const ROLE_IDS = [
|
||||||
|
"platform_admin",
|
||||||
|
"platform_operator",
|
||||||
|
"platform_auditor",
|
||||||
|
"platform_ops",
|
||||||
|
"org_admin",
|
||||||
|
"manager",
|
||||||
|
"caregiver",
|
||||||
|
"viewer",
|
||||||
|
] as const;
|
||||||
export type RoleId = (typeof ROLE_IDS)[number];
|
export type RoleId = (typeof ROLE_IDS)[number];
|
||||||
|
|
||||||
export const ROLE_LABELS: Record<RoleId, string> = {
|
export const ROLE_LABELS: Record<RoleId, string> = {
|
||||||
admin: "系统管理员",
|
platform_admin: "平台超管",
|
||||||
|
platform_operator: "平台运营",
|
||||||
|
platform_auditor: "平台审计",
|
||||||
|
platform_ops: "平台运维",
|
||||||
|
org_admin: "机构管理员",
|
||||||
manager: "运营主管",
|
manager: "运营主管",
|
||||||
caregiver: "照护人员",
|
caregiver: "照护人员",
|
||||||
viewer: "只读访客",
|
viewer: "只读访客",
|
||||||
};
|
};
|
||||||
|
|
||||||
export const PERMISSIONS = [
|
export const PERMISSIONS = [
|
||||||
|
"platform:manage",
|
||||||
|
"organization:read",
|
||||||
|
"organization:manage",
|
||||||
"account:read",
|
"account:read",
|
||||||
"account:manage",
|
"account:manage",
|
||||||
|
"role:read",
|
||||||
|
"role:manage",
|
||||||
|
"permission:read",
|
||||||
"audit:read",
|
"audit:read",
|
||||||
|
"incident:read",
|
||||||
|
"incident:manage",
|
||||||
|
"facility:read",
|
||||||
|
"facility:manage",
|
||||||
|
"admission:read",
|
||||||
|
"admission:manage",
|
||||||
"elder:read",
|
"elder:read",
|
||||||
"elder:create",
|
"elder:create",
|
||||||
"elder:update",
|
"elder:update",
|
||||||
@@ -23,20 +48,52 @@ export const PERMISSIONS = [
|
|||||||
export type Permission = (typeof PERMISSIONS)[number];
|
export type Permission = (typeof PERMISSIONS)[number];
|
||||||
|
|
||||||
export type RoleDefinition = {
|
export type RoleDefinition = {
|
||||||
id: RoleId;
|
id: string;
|
||||||
|
key: RoleId | string;
|
||||||
label: string;
|
label: string;
|
||||||
description: string;
|
description: string;
|
||||||
|
scope: "platform" | "organization";
|
||||||
|
organizationId?: string;
|
||||||
|
isSystem: boolean;
|
||||||
|
isEnabled: boolean;
|
||||||
permissions: Permission[];
|
permissions: Permission[];
|
||||||
};
|
};
|
||||||
|
|
||||||
export type AccountStatus = "active" | "disabled";
|
export type AccountStatus = "active" | "disabled" | "pending";
|
||||||
|
|
||||||
|
export type OrganizationStatus = "active" | "disabled";
|
||||||
|
|
||||||
|
export type Organization = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
slug: string;
|
||||||
|
status: OrganizationStatus;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type MembershipStatus = "active" | "disabled" | "pending";
|
||||||
|
|
||||||
|
export type Membership = {
|
||||||
|
id: string;
|
||||||
|
accountId: string;
|
||||||
|
organizationId: string;
|
||||||
|
roleId: string;
|
||||||
|
roleKey: string;
|
||||||
|
roleLabel: string;
|
||||||
|
status: MembershipStatus;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
};
|
||||||
|
|
||||||
export type Account = {
|
export type Account = {
|
||||||
id: string;
|
id: string;
|
||||||
|
platformRoleId?: string;
|
||||||
name: string;
|
name: string;
|
||||||
email: string;
|
email: string;
|
||||||
role: RoleId;
|
role: RoleId | string;
|
||||||
organization?: string;
|
organization?: string;
|
||||||
|
organizationId?: string;
|
||||||
passwordHash: string;
|
passwordHash: string;
|
||||||
passwordSalt: string;
|
passwordSalt: string;
|
||||||
status: AccountStatus;
|
status: AccountStatus;
|
||||||
@@ -49,6 +106,7 @@ export type PublicAccount = Omit<Account, "passwordHash" | "passwordSalt">;
|
|||||||
export type Session = {
|
export type Session = {
|
||||||
id: string;
|
id: string;
|
||||||
accountId: string;
|
accountId: string;
|
||||||
|
activeOrganizationId?: string;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
expiresAt: string;
|
expiresAt: string;
|
||||||
};
|
};
|
||||||
@@ -57,6 +115,7 @@ export type AuditResult = "success" | "denied" | "failure";
|
|||||||
|
|
||||||
export type AuditLog = {
|
export type AuditLog = {
|
||||||
id: string;
|
id: string;
|
||||||
|
organizationId?: string;
|
||||||
timestamp: string;
|
timestamp: string;
|
||||||
actorAccountId?: string;
|
actorAccountId?: string;
|
||||||
actorEmail?: string;
|
actorEmail?: string;
|
||||||
@@ -67,16 +126,82 @@ export type AuditLog = {
|
|||||||
reason: string;
|
reason: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type BedStatus = "available" | "occupied" | "maintenance" | "disabled";
|
||||||
|
|
||||||
|
export type FacilityBed = {
|
||||||
|
id: string;
|
||||||
|
organizationId: string;
|
||||||
|
roomId: string;
|
||||||
|
roomName: string;
|
||||||
|
code: string;
|
||||||
|
status: BedStatus;
|
||||||
|
notes: string;
|
||||||
|
currentElderName?: string;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type Room = {
|
||||||
|
id: string;
|
||||||
|
organizationId: string;
|
||||||
|
name: string;
|
||||||
|
code: string;
|
||||||
|
capacity: number;
|
||||||
|
status: OrganizationStatus;
|
||||||
|
bedCount: number;
|
||||||
|
occupiedBedCount: number;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AdmissionStatus = "active" | "transferred" | "discharged";
|
||||||
|
|
||||||
|
export type Admission = {
|
||||||
|
id: string;
|
||||||
|
organizationId: string;
|
||||||
|
elderId: string;
|
||||||
|
elderName: string;
|
||||||
|
bedId: string;
|
||||||
|
bedCode: string;
|
||||||
|
roomName: string;
|
||||||
|
status: AdmissionStatus;
|
||||||
|
admittedAt: string;
|
||||||
|
dischargedAt?: string;
|
||||||
|
notes: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type IncidentSeverity = "info" | "warning" | "critical";
|
||||||
|
export type IncidentStatus = "open" | "acknowledged" | "resolved" | "closed";
|
||||||
|
|
||||||
|
export type SystemIncident = {
|
||||||
|
id: string;
|
||||||
|
organizationId?: string;
|
||||||
|
severity: IncidentSeverity;
|
||||||
|
status: IncidentStatus;
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
source: string;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
};
|
||||||
|
|
||||||
export type AppData = {
|
export type AppData = {
|
||||||
|
organizations: Organization[];
|
||||||
accounts: Account[];
|
accounts: Account[];
|
||||||
|
memberships: Membership[];
|
||||||
sessions: Session[];
|
sessions: Session[];
|
||||||
elders: Elder[];
|
elders: Elder[];
|
||||||
|
rooms: Room[];
|
||||||
|
beds: FacilityBed[];
|
||||||
|
admissions: Admission[];
|
||||||
auditLogs: AuditLog[];
|
auditLogs: AuditLog[];
|
||||||
|
incidents: SystemIncident[];
|
||||||
};
|
};
|
||||||
|
|
||||||
export type AuthContext = {
|
export type AuthContext = {
|
||||||
account: PublicAccount;
|
account: PublicAccount;
|
||||||
|
organization?: Organization;
|
||||||
|
membership?: Membership;
|
||||||
permissions: Permission[];
|
permissions: Permission[];
|
||||||
session: Session;
|
session: Session;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -28,12 +28,14 @@ export const ELDER_STATUS_LABELS: Record<ElderStatus, string> = {
|
|||||||
|
|
||||||
export type Elder = {
|
export type Elder = {
|
||||||
id: string;
|
id: string;
|
||||||
|
organizationId?: string;
|
||||||
name: string;
|
name: string;
|
||||||
gender: Gender;
|
gender: Gender;
|
||||||
age: number;
|
age: number;
|
||||||
careLevel: CareLevel;
|
careLevel: CareLevel;
|
||||||
room: string;
|
room: string;
|
||||||
bed: string;
|
bed: string;
|
||||||
|
bedId?: string;
|
||||||
status: ElderStatus;
|
status: ElderStatus;
|
||||||
primaryContact: string;
|
primaryContact: string;
|
||||||
phone: string;
|
phone: string;
|
||||||
@@ -73,6 +75,16 @@ function readRequiredString(
|
|||||||
return { success: true, data: value.trim() };
|
return { success: true, data: value.trim() };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function readOptionalString(source: Record<string, unknown>, key: string): string | undefined {
|
||||||
|
const value = source[key];
|
||||||
|
if (typeof value !== "string") {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const trimmed = value.trim();
|
||||||
|
return trimmed.length > 0 ? trimmed : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
function readEnum<T extends string>(
|
function readEnum<T extends string>(
|
||||||
source: Record<string, unknown>,
|
source: Record<string, unknown>,
|
||||||
key: keyof ElderInput,
|
key: keyof ElderInput,
|
||||||
@@ -128,15 +140,9 @@ export function validateElderInput(value: unknown): ValidationResult<ElderInput>
|
|||||||
return careLevel;
|
return careLevel;
|
||||||
}
|
}
|
||||||
|
|
||||||
const room = readRequiredString(value, "room", "房间");
|
const room = readOptionalString(value, "room") ?? "";
|
||||||
if (!room.success) {
|
const bed = readOptionalString(value, "bed") ?? "";
|
||||||
return room;
|
const bedId = readOptionalString(value, "bedId");
|
||||||
}
|
|
||||||
|
|
||||||
const bed = readRequiredString(value, "bed", "床位");
|
|
||||||
if (!bed.success) {
|
|
||||||
return bed;
|
|
||||||
}
|
|
||||||
|
|
||||||
const status = readEnum(value, "status", ELDER_STATUS_VALUES, "状态");
|
const status = readEnum(value, "status", ELDER_STATUS_VALUES, "状态");
|
||||||
if (!status.success) {
|
if (!status.success) {
|
||||||
@@ -163,8 +169,9 @@ export function validateElderInput(value: unknown): ValidationResult<ElderInput>
|
|||||||
gender: gender.data,
|
gender: gender.data,
|
||||||
age: age.data,
|
age: age.data,
|
||||||
careLevel: careLevel.data,
|
careLevel: careLevel.data,
|
||||||
room: room.data,
|
room,
|
||||||
bed: bed.data,
|
bed,
|
||||||
|
bedId,
|
||||||
status: status.data,
|
status: status.data,
|
||||||
primaryContact: primaryContact.data,
|
primaryContact: primaryContact.data,
|
||||||
phone: phone.data,
|
phone: phone.data,
|
||||||
@@ -172,4 +179,3 @@ export function validateElderInput(value: unknown): ValidationResult<ElderInput>
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,23 +1,40 @@
|
|||||||
import { Activity, AlertTriangle, ShieldCheck, Users } from "lucide-react";
|
import { Activity, Building2, Server, ShieldCheck, Users } from "lucide-react";
|
||||||
|
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import type { AuditLog, PublicAccount, RoleDefinition } from "@/modules/core/types";
|
import type { AuditLog, Membership, Organization, PublicAccount, RoleDefinition, SystemIncident } from "@/modules/core/types";
|
||||||
import { ROLE_LABELS } from "@/modules/core/types";
|
import { ROLE_LABELS } from "@/modules/core/types";
|
||||||
|
import type { RoleId } from "@/modules/core/types";
|
||||||
|
|
||||||
type SettingsOverviewProps = {
|
type SettingsOverviewProps = {
|
||||||
accounts: PublicAccount[];
|
accounts: PublicAccount[];
|
||||||
roles: RoleDefinition[];
|
roles: RoleDefinition[];
|
||||||
auditLogs: AuditLog[];
|
auditLogs: AuditLog[];
|
||||||
|
organizations: Organization[];
|
||||||
|
memberships: Membership[];
|
||||||
|
incidents: SystemIncident[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function formatRoleLabel(role: string): string {
|
||||||
|
if (role in ROLE_LABELS) {
|
||||||
|
return ROLE_LABELS[role as RoleId];
|
||||||
|
}
|
||||||
|
|
||||||
|
return role;
|
||||||
|
}
|
||||||
|
|
||||||
export function SettingsOverview({
|
export function SettingsOverview({
|
||||||
accounts,
|
accounts,
|
||||||
roles,
|
roles,
|
||||||
auditLogs,
|
auditLogs,
|
||||||
|
organizations,
|
||||||
|
memberships,
|
||||||
|
incidents,
|
||||||
}: SettingsOverviewProps): React.ReactElement {
|
}: SettingsOverviewProps): React.ReactElement {
|
||||||
const activeAccountCount = accounts.filter((account) => account.status === "active").length;
|
const activeAccountCount = accounts.filter((account) => account.status === "active").length;
|
||||||
const disabledAccountCount = accounts.length - activeAccountCount;
|
const disabledAccountCount = accounts.length - activeAccountCount;
|
||||||
|
const activeOrganizationCount = organizations.filter((organization) => organization.status === "active").length;
|
||||||
|
const openIncidentCount = incidents.filter((incident) => incident.status === "open").length;
|
||||||
const deniedAuditCount = auditLogs.filter((log) => log.result === "denied").length;
|
const deniedAuditCount = auditLogs.filter((log) => log.result === "denied").length;
|
||||||
const failureAuditCount = auditLogs.filter((log) => log.result === "failure").length;
|
const failureAuditCount = auditLogs.filter((log) => log.result === "failure").length;
|
||||||
const successAuditCount = auditLogs.filter((log) => log.result === "success").length;
|
const successAuditCount = auditLogs.filter((log) => log.result === "success").length;
|
||||||
@@ -33,12 +50,24 @@ export function SettingsOverview({
|
|||||||
return (
|
return (
|
||||||
<div className="mx-auto flex w-full max-w-7xl flex-col gap-5">
|
<div className="mx-auto flex w-full max-w-7xl flex-col gap-5">
|
||||||
<section className="border-b pb-5">
|
<section className="border-b pb-5">
|
||||||
<Badge variant="success">RBAC + Audit</Badge>
|
<Badge variant="success">System configuration</Badge>
|
||||||
<h1 className="mt-3 text-3xl font-semibold tracking-normal">权限设置</h1>
|
<h1 className="mt-3 text-3xl font-semibold tracking-normal">系统设置</h1>
|
||||||
<p className="mt-2 text-sm text-muted-foreground">内置角色、账号状态和关键操作审计。</p>
|
<p className="mt-2 text-sm text-muted-foreground">机构、用户、角色、权限、审计和故障中心。</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
|
<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">{organizations.length}</CardTitle>
|
||||||
|
</div>
|
||||||
|
<Building2 className="size-5 text-primary" aria-hidden="true" />
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="pt-0">
|
||||||
|
<p className="text-sm text-muted-foreground">启用 {activeOrganizationCount} 个,多租户数据隔离</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0">
|
<CardHeader className="flex flex-row items-center justify-between space-y-0">
|
||||||
<div>
|
<div>
|
||||||
@@ -63,16 +92,20 @@ export function SettingsOverview({
|
|||||||
<p className="text-sm text-muted-foreground">累计覆盖 {totalPermissionCount} 项权限</p>
|
<p className="text-sm text-muted-foreground">累计覆盖 {totalPermissionCount} 项权限</p>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
<Card className="border-red-200 bg-red-50/70">
|
<Card className={openIncidentCount > 0 ? "border-red-200 bg-red-50/70" : undefined}>
|
||||||
<CardHeader className="flex flex-row items-center justify-between space-y-0">
|
<CardHeader className="flex flex-row items-center justify-between space-y-0">
|
||||||
<div>
|
<div>
|
||||||
<CardDescription className="text-red-700">红色审计</CardDescription>
|
<CardDescription className={openIncidentCount > 0 ? "text-red-700" : undefined}>故障事件</CardDescription>
|
||||||
<CardTitle className="mt-2 text-3xl text-red-700">{deniedAuditCount + failureAuditCount}</CardTitle>
|
<CardTitle className={openIncidentCount > 0 ? "mt-2 text-3xl text-red-700" : "mt-2 text-3xl"}>
|
||||||
|
{openIncidentCount}
|
||||||
|
</CardTitle>
|
||||||
</div>
|
</div>
|
||||||
<AlertTriangle className="size-5 text-red-600" aria-hidden="true" />
|
<Server className={openIncidentCount > 0 ? "size-5 text-red-600" : "size-5 text-primary"} aria-hidden="true" />
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="pt-0">
|
<CardContent className="pt-0">
|
||||||
<p className="text-sm text-red-700">拒绝 {deniedAuditCount} 条,失败 {failureAuditCount} 条</p>
|
<p className={openIncidentCount > 0 ? "text-sm text-red-700" : "text-sm text-muted-foreground"}>
|
||||||
|
总计 {incidents.length} 条,开放 {openIncidentCount} 条
|
||||||
|
</p>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
<Card>
|
<Card>
|
||||||
@@ -99,6 +132,10 @@ export function SettingsOverview({
|
|||||||
<span className="text-sm text-red-700">红色:拒绝/失败审计</span>
|
<span className="text-sm text-red-700">红色:拒绝/失败审计</span>
|
||||||
<Badge variant="danger">{deniedAuditCount + failureAuditCount}</Badge>
|
<Badge variant="danger">{deniedAuditCount + failureAuditCount}</Badge>
|
||||||
</div>
|
</div>
|
||||||
|
<div className="flex items-center justify-between rounded-md border border-red-200 bg-red-50 p-3">
|
||||||
|
<span className="text-sm text-red-700">开放故障</span>
|
||||||
|
<Badge variant="danger">{openIncidentCount}</Badge>
|
||||||
|
</div>
|
||||||
<div className="flex items-center justify-between rounded-md border border-amber-200 bg-amber-50 p-3">
|
<div className="flex items-center justify-between rounded-md border border-amber-200 bg-amber-50 p-3">
|
||||||
<span className="text-sm text-amber-700">黄色:停用账号</span>
|
<span className="text-sm text-amber-700">黄色:停用账号</span>
|
||||||
<Badge variant="warning">{disabledAccountCount}</Badge>
|
<Badge variant="warning">{disabledAccountCount}</Badge>
|
||||||
@@ -137,7 +174,77 @@ export function SettingsOverview({
|
|||||||
<section className="grid gap-4 xl:grid-cols-[0.9fr_1.1fr]">
|
<section className="grid gap-4 xl:grid-cols-[0.9fr_1.1fr]">
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>内置角色</CardTitle>
|
<CardTitle>机构租户</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="overflow-x-auto rounded-md border">
|
||||||
|
<table className="w-full min-w-[560px] 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">Slug</th>
|
||||||
|
<th className="px-4 py-3 font-medium">状态</th>
|
||||||
|
<th className="px-4 py-3 text-right font-medium">创建时间</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y bg-card">
|
||||||
|
{organizations.map((organization) => (
|
||||||
|
<tr key={organization.id}>
|
||||||
|
<td className="px-4 py-3 font-medium">{organization.name}</td>
|
||||||
|
<td className="px-4 py-3 text-muted-foreground">{organization.slug}</td>
|
||||||
|
<td className="px-4 py-3">
|
||||||
|
<Badge variant={organization.status === "active" ? "success" : "danger"}>
|
||||||
|
{organization.status === "active" ? "启用" : "停用"}
|
||||||
|
</Badge>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-right text-muted-foreground">
|
||||||
|
{new Date(organization.createdAt).toLocaleString("zh-CN")}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
{organizations.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td className="px-4 py-8 text-center text-muted-foreground" colSpan={4}>
|
||||||
|
暂无机构
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : null}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>故障中心</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-3">
|
||||||
|
{incidents.slice(0, 6).map((incident) => (
|
||||||
|
<div key={incident.id} className="rounded-md border p-3">
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<p className="font-medium">{incident.title}</p>
|
||||||
|
<Badge
|
||||||
|
variant={incident.severity === "critical" ? "danger" : incident.severity === "warning" ? "warning" : "secondary"}
|
||||||
|
>
|
||||||
|
{incident.status}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
<p className="mt-2 text-sm text-muted-foreground">{incident.description}</p>
|
||||||
|
<p className="mt-2 text-xs text-muted-foreground">
|
||||||
|
{incident.source} / {new Date(incident.createdAt).toLocaleString("zh-CN")}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{incidents.length === 0 ? <p className="text-sm text-muted-foreground">暂无故障事件</p> : null}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="grid gap-4 xl:grid-cols-[0.9fr_1.1fr]">
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>角色与权限</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-3">
|
<CardContent className="space-y-3">
|
||||||
{roles.map((role) => (
|
{roles.map((role) => (
|
||||||
@@ -181,10 +288,10 @@ export function SettingsOverview({
|
|||||||
<p className="font-medium">{account.name}</p>
|
<p className="font-medium">{account.name}</p>
|
||||||
<p className="text-xs text-muted-foreground">{account.email}</p>
|
<p className="text-xs text-muted-foreground">{account.email}</p>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-4 py-3">{ROLE_LABELS[account.role]}</td>
|
<td className="px-4 py-3">{formatRoleLabel(account.role)}</td>
|
||||||
<td className="px-4 py-3">
|
<td className="px-4 py-3">
|
||||||
<Badge variant={account.status === "active" ? "success" : "danger"}>
|
<Badge variant={account.status === "active" ? "success" : account.status === "pending" ? "warning" : "danger"}>
|
||||||
{account.status === "active" ? "启用" : "停用"}
|
{account.status === "active" ? "启用" : account.status === "pending" ? "待审批" : "停用"}
|
||||||
</Badge>
|
</Badge>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-4 py-3 text-right text-muted-foreground">
|
<td className="px-4 py-3 text-right text-muted-foreground">
|
||||||
@@ -199,6 +306,51 @@ export function SettingsOverview({
|
|||||||
</Card>
|
</Card>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>机构成员关系</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<div className="overflow-x-auto rounded-md border">
|
||||||
|
<table className="w-full min-w-[720px] text-sm">
|
||||||
|
<thead className="bg-secondary text-left text-xs text-muted-foreground">
|
||||||
|
<tr>
|
||||||
|
<th className="px-4 py-3 font-medium">账号 ID</th>
|
||||||
|
<th className="px-4 py-3 font-medium">机构 ID</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 text-right font-medium">创建时间</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y bg-card">
|
||||||
|
{memberships.map((membership) => (
|
||||||
|
<tr key={membership.id}>
|
||||||
|
<td className="px-4 py-3 text-muted-foreground">{membership.accountId.slice(0, 8)}</td>
|
||||||
|
<td className="px-4 py-3 text-muted-foreground">{membership.organizationId.slice(0, 8)}</td>
|
||||||
|
<td className="px-4 py-3">{membership.roleLabel}</td>
|
||||||
|
<td className="px-4 py-3">
|
||||||
|
<Badge variant={membership.status === "active" ? "success" : membership.status === "pending" ? "warning" : "danger"}>
|
||||||
|
{membership.status}
|
||||||
|
</Badge>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 text-right text-muted-foreground">
|
||||||
|
{new Date(membership.createdAt).toLocaleString("zh-CN")}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
{memberships.length === 0 ? (
|
||||||
|
<tr>
|
||||||
|
<td className="px-4 py-8 text-center text-muted-foreground" colSpan={5}>
|
||||||
|
暂无成员关系
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
) : null}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle>审计日志</CardTitle>
|
<CardTitle>审计日志</CardTitle>
|
||||||
|
|||||||
10
package.json
10
package.json
@@ -6,6 +6,9 @@
|
|||||||
"dev": "next dev",
|
"dev": "next dev",
|
||||||
"build": "next build",
|
"build": "next build",
|
||||||
"start": "next start",
|
"start": "next start",
|
||||||
|
"db:generate": "drizzle-kit generate",
|
||||||
|
"db:migrate": "drizzle-kit migrate",
|
||||||
|
"db:studio": "drizzle-kit studio",
|
||||||
"lint": "eslint app components lib modules next.config.ts eslint.config.mjs",
|
"lint": "eslint app components lib modules next.config.ts eslint.config.mjs",
|
||||||
"type-check": "tsc --noEmit"
|
"type-check": "tsc --noEmit"
|
||||||
},
|
},
|
||||||
@@ -13,8 +16,10 @@
|
|||||||
"@radix-ui/react-slot": "^1.2.3",
|
"@radix-ui/react-slot": "^1.2.3",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
|
"drizzle-orm": "^0.45.2",
|
||||||
"lucide-react": "^0.468.0",
|
"lucide-react": "^0.468.0",
|
||||||
"next": "^15.0.0",
|
"next": "^15.0.0",
|
||||||
|
"postgres": "^3.4.9",
|
||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
"react-dom": "^19.0.0",
|
"react-dom": "^19.0.0",
|
||||||
"tailwind-merge": "^3.0.0"
|
"tailwind-merge": "^3.0.0"
|
||||||
@@ -26,10 +31,11 @@
|
|||||||
"@types/node": "^22.0.0",
|
"@types/node": "^22.0.0",
|
||||||
"@types/react": "^19.0.0",
|
"@types/react": "^19.0.0",
|
||||||
"@types/react-dom": "^19.0.0",
|
"@types/react-dom": "^19.0.0",
|
||||||
|
"drizzle-kit": "^0.31.10",
|
||||||
"eslint": "^9.0.0",
|
"eslint": "^9.0.0",
|
||||||
"eslint-config-next": "^15.0.0",
|
"eslint-config-next": "^15.0.0",
|
||||||
"tailwindcss": "^4.0.0",
|
"tailwindcss": "^4.0.0",
|
||||||
"typescript-eslint": "^8.0.0",
|
"typescript": "^5.0.0",
|
||||||
"typescript": "^5.0.0"
|
"typescript-eslint": "^8.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
947
pnpm-lock.yaml
generated
947
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user