Compare commits

...

4 Commits

Author SHA1 Message Date
EL
64d1ad7896 新增主任范围校验:仅可操作同医院同科室的 DOCTOR 账号
限制主任变更:禁止将医生改为其他角色,禁止跨科室调整归属
新增 DIRECTOR_SCOPE_FORBIDDEN 统一错误文案
前端权限同步:主任可进入用户页,页面文案调整为“医生管理”
前端交互同步:主任创建/编辑时角色固定为医生,医院与科室范围锁定
仪表盘统计按角色收敛,主任视角展示本科室医生相关统计
补充 e2e 场景覆盖与接口文档说明"
2026-03-19 11:08:36 +08:00
EL
6ec2d0b0e0 新增 B 端设备模块(后端 CRUD、分页筛选、权限隔离)并接入前端设备管理页面与路由菜单
鉴权改为登录态回库校验,新增 tokenValidAfter 失效时间,支持密码变更与 seed 重置后旧 token 立即失效
患者字段由 idCardHash 统一迁移为 idCard,新增身份证标准化逻辑并同步 C 端生命周期查询参数
组织模块增加小组删除限制(有成员时返回 409)并补充中文错误消息
任务取消接口支持可选 reason 字段(先透传事件层)
补齐 Prisma 迁移、文档说明和 E2E 用例(含设备模块与 token 失效场景)
2026-03-18 20:23:55 +08:00
EL
5fdf4c80e6 医院管理页新增医院管理员列并支持任命医院管理员
组织架构树展示医院管理员信息
科室与小组弹窗支持设置主任/组长并限制候选角色
患者页优化归属医生选择与字段文案
统一“小组组长”角色文案
2026-03-18 17:07:37 +08:00
EL
b527256874 feat(auth-org): 强化用户权限边界并完善组织负责人配置展示
feat(admin-ui): 医院管理显示医院管理员并限制候选角色
feat(security): 关闭注册入口,新增 system-admin 创建链路与数据脱敏
2026-03-18 17:05:36 +08:00
62 changed files with 3982 additions and 765 deletions

View File

@ -40,11 +40,17 @@ docs/
```env
DATABASE_URL="postgresql://user:password@127.0.0.1:5432/tyt?schema=public"
JWT_SECRET="请替换为强随机密钥"
AUTH_TOKEN_SECRET="请替换为强随机密钥"
JWT_EXPIRES_IN="7d"
SYSTEM_ADMIN_BOOTSTRAP_KEY="初始化系统管理员用密钥"
```
管理员创建链路:
- 可通过 `POST /auth/system-admin` 创建系统管理员(需引导密钥)。
- 系统管理员负责创建医院、系统管理员与医院管理员。
- 医院管理员负责创建本院下级角色(主任/组长/医生/工程师)。
## 4. 启动流程
```bash

View File

@ -2,26 +2,29 @@
## 1. 目标
- 提供注册、登录、`/me` 身份查询。
- 提供系统管理员创建、登录、`/me` 身份查询。
- 使用 JWT 做认证Guard 做鉴权RolesGuard 做 RBAC。
## 2. 核心接口
- `POST /auth/register`:注册账号(支持医生/工程师/院管等角色约束
- `POST /auth/system-admin`:创建系统管理员(需引导密钥
- `POST /auth/login`:手机号 + 角色 + 密码登录(支持同手机号多院场景)
- `GET /auth/me`:返回当前登录用户上下文
## 3. 鉴权流程
1. `AccessTokenGuard``Authorization` 读取 Bearer Token。
2. 校验 JWT 签名与载荷字段。
3. 载荷映射为 `ActorContext` 注入 `request.user`
4. `RolesGuard` 根据 `@Roles(...)` 判断角色是否允许访问。
2. 校验 JWT 签名、`id``iat` 等关键载荷字段。
3. 根据 `id` 回库读取用户当前角色与组织归属,不再直接信任 token 里的角色和范围。
4. 校验 `iat >= user.tokenValidAfter`若用户被重置密码、seed 重刷或账号被清理,则旧 token 立即失效。
5. 当前数据库用户映射为 `ActorContext` 注入 `request.actor`
6. `RolesGuard` 根据 `@Roles(...)` 判断角色是否允许访问。
## 4. Token 约定
- Header`Authorization: Bearer <token>`
- 载荷关键字段:`sub``role``hospitalId``departmentId``groupId`
- 载荷关键字段:`id``iat`
- 角色和组织范围以数据库当前用户记录为准,不以 token 历史载荷为准
## 5. 错误码与中文消息
@ -30,3 +33,8 @@
- 参数非法:`400` + 中文 `msg`
统一由全局异常过滤器输出:`{ code, msg, data: null }`
## 6. 失效策略
- 用户密码被修改后,会刷新 `user.tokenValidAfter`,旧 token 全部失效。
- 执行 E2E 重置并重新 seed 后seed 账号的 `tokenValidAfter` 也会刷新,历史 token 不可继续复用。

27
docs/devices.md Normal file
View File

@ -0,0 +1,27 @@
# 设备模块说明(`src/devices`
## 1. 目标
- 提供 B 端设备 CRUD。
- 管理设备与患者的归属关系。
- 支持管理员按医院、患者、状态和关键词分页查询设备。
## 2. 权限
- `SYSTEM_ADMIN`:可跨院查询和维护设备。
- `HOSPITAL_ADMIN`:仅可操作本院患者名下设备。
- 其他角色:默认拒绝。
## 3. 接口
- `GET /b/devices`:分页查询设备列表
- `GET /b/devices/:id`:查询设备详情
- `POST /b/devices`:创建设备
- `PATCH /b/devices/:id`:更新设备
- `DELETE /b/devices/:id`:删除设备
## 4. 约束
- 设备必须绑定到一个患者。
- 设备 SN 在全库唯一,服务端会统一转成大写后再校验。
- 删除已被任务明细引用的设备会返回 `409`

View File

@ -14,6 +14,7 @@
2. `node prisma/seed.mjs`
这会清空 `.env``DATABASE_URL` 指向数据库的全部数据,请仅在测试库执行。
另外seed 账号会刷新 `tokenValidAfter`,所以重置前签发的旧 token 会全部失效,需要重新登录获取新 token。
## 3. 运行命令

View File

@ -4,16 +4,21 @@
- 登录页:`/auth/login`,支持可选 `hospitalId`
- 首页看板:按角色拉取组织与患者统计。
- 设备页:新增管理员专用设备 CRUD复用真实设备接口。
- 任务页:接入 `publish/accept/complete/cancel` 四个真实任务接口。
- 用户页:修复用户列表响应结构、组织字段联动、工程师分配医院参数。
- 患者页:接入真实患者字段与生命周期查询参数(`phone + idCardHash`)。
- 患者页:接入真实患者字段与生命周期查询参数(`phone + idCard`
后端直接保存身份证号原文,不再做哈希转换。
## 2. 接口契约对齐点
- `GET /users` 当前返回数组,前端已在 `api/users.js` 做本地分页与筛选适配。
- `PATCH /b/users/:id/assign-engineer-hospital` 参数为单个 `hospitalId`,非数组。
- `GET /b/patients` 返回数组,前端已改为本地分页与筛选。
- `GET /c/patients/lifecycle` 必须同时传 `phone``idCardHash`
- `GET /b/devices` 已支持服务端分页与筛选,前端直接透传 `page/pageSize`
- `GET /c/patients/lifecycle` 必须同时传 `phone``idCard`
- 患者表单中的 `idCard` 字段直接传身份证号;
服务端只会做去空格与 `x/X` 标准化,不会转哈希。
- 任务模块暂无任务列表接口,前端改为“表单操作 + 最近结果”模式。
## 3. 角色权限提示
@ -24,8 +29,10 @@
- 患者列表权限:
- `SYSTEM_ADMIN` 查询时必须传 `hospitalId`
- 用户管理接口:
- `SYSTEM_ADMIN/HOSPITAL_ADMIN` 可访问列表与创建
- 删除和工程师绑定医院仅 `SYSTEM_ADMIN`
- `SYSTEM_ADMIN/HOSPITAL_ADMIN/DIRECTOR` 可访问列表与创建
- `DIRECTOR` 页面语义调整为“医生管理”,仅管理本科室医生
- 工程师绑定医院仅 `SYSTEM_ADMIN`
- 删除:`SYSTEM_ADMIN` 可删除任意无关联用户;`DIRECTOR` 可删除本科室无关联医生
## 3.1 结构图页面交互调整
@ -35,27 +42,32 @@
## 3.2 后台页面路由权限(与后端 RBAC 对齐)
- `organization/tree``organization/departments``organization/groups``users`
- `organization/tree``organization/departments`、`organization/groups`
- `organization/tree``organization/groups`
`SYSTEM_ADMIN``HOSPITAL_ADMIN``DIRECTOR``LEADER` 可访问
- `users`:仅 `SYSTEM_ADMIN``HOSPITAL_ADMIN` 可访问
- `organization/departments`
`SYSTEM_ADMIN``HOSPITAL_ADMIN` 可访问
- `users``SYSTEM_ADMIN``HOSPITAL_ADMIN``DIRECTOR` 可访问
- `devices`:仅 `SYSTEM_ADMIN``HOSPITAL_ADMIN` 可访问
- `organization/hospitals`
- 仅 `SYSTEM_ADMIN` 可访问
- `tasks`
- 仅 `DOCTOR``DIRECTOR``LEADER``ENGINEER` 可访问
- `patients`
- `SYSTEM_ADMIN``HOSPITAL_ADMIN``DIRECTOR``LEADER` 可访问
- `SYSTEM_ADMIN``HOSPITAL_ADMIN``DIRECTOR``LEADER`、`DOCTOR` 可访问
前端已在路由守卫和侧边栏菜单同时做权限控制,无权限角色会被拦截并跳转到首页,避免进入页面后触发接口 `403`
## 3.3 主任/组长组织管理范围
- `DIRECTOR`
- 可查看组织架构、科室列表、小组列表(限定本科室范围)
- 可编辑本科室名称、创建/编辑/删除本科室下小组
- 可查看组织架构、小组列表(限定本科室范围)
- 可创建/编辑/删除本科室下小组
- 可进入“医生管理”页,创建/维护本科室医生
- `LEADER`
- 可查看组织架构、科室列表、小组列表(限定本科室/本小组范围)
- 可编辑本科室名称与本小组名称
- 负责人设置(设主任/设组长)与人员管理入口仍仅 `SYSTEM_ADMIN``HOSPITAL_ADMIN` 显示。
- 可查看组织架构、小组列表(限定本科室/本小组范围)
- 可编辑本小组名称
- 主任/组长不再显示独立“科室管理”页面。
- 负责人设置(设主任/设组长)入口仍仅 `SYSTEM_ADMIN``HOSPITAL_ADMIN` 显示。
## 4. 本地运行

View File

@ -3,7 +3,9 @@
## 1. 目标
- B 端:按组织与角色范围查询患者(强依赖 `hospitalId`)。
- C 端:按 `phone + idCardHash` 做跨院聚合查询。
- C 端:按 `phone + idCard` 做跨院聚合查询。
- 患者档案直接保存身份证号原文,不再做哈希转换。
- 服务端只做轻量格式整理:去空格、统一末尾 `x/X` 为大写。
## 2. B 端可见性
@ -28,12 +30,12 @@
## 3. C 端生命周期聚合
接口:`GET /c/patients/lifecycle?phone=...&idCardHash=...`
接口:`GET /c/patients/lifecycle?phone=...&idCard=...`
查询策略:
1. 不做医院隔离(跨租户)
2. 双字段精确匹配 `phone + idCardHash`
2. 先将 `idCard` 做轻量标准化,再做双字段精确匹配
3. 关联查询 `Patient -> Device -> TaskItem -> Task`
4. 返回扁平生命周期列表(按 `Task.createdAt DESC`

View File

@ -18,6 +18,11 @@
- 工程师:接收任务、完成自己接收的任务
- 其他角色:默认拒绝
补充:
- `POST /b/tasks/cancel` 现支持可选 `reason` 字段,便于前端保留取消原因输入。
- 当前取消原因仅透传到事件层,数据库暂未持久化该字段。
## 4. 事件触发
状态变化后会发出事件:

View File

@ -19,6 +19,7 @@
- 医院内数据按 `hospitalId` 强隔离。
- 仅 `SYSTEM_ADMIN` 可执行工程师绑定医院。
- `DIRECTOR/LEADER` 可读取用户列表,但仅返回当前科室可见用户。
- `DIRECTOR` 可创建、查看、编辑、删除本科室医生,但不能跨科室操作,也不能把医生改成其他角色。
- 用户组织字段校验:
- 院管/医生/工程师等需有医院归属;
- 主任/组长需有科室/小组等必要归属;
@ -31,6 +32,13 @@
- `GET /users``GET /users/:id``PATCH /users/:id``DELETE /users/:id`
- `POST /b/users/:id/assign-engineer-hospital`
其中主任侧的常用链路为:
- `POST /users`:创建本科室医生
- `GET /users/:id`:查看本科室医生详情
- `PATCH /users/:id`:修改本科室医生信息
- `DELETE /users/:id`:删除无关联数据的本科室医生
## 5. 开发改造建议
- 若增加角色,请同步修改:

View File

@ -0,0 +1,8 @@
/*
Warnings:
- A unique constraint covering the columns `[phone,role,hospitalId]` on the table `User` will be added. If there are existing duplicate values, this will fail.
*/
-- CreateIndex
CREATE UNIQUE INDEX "User_phone_role_hospitalId_key" ON "User"("phone", "role", "hospitalId");

View File

@ -0,0 +1,2 @@
ALTER TABLE "User"
ADD COLUMN "tokenValidAfter" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP;

View File

@ -0,0 +1,5 @@
ALTER TABLE "Patient"
RENAME COLUMN "idCardHash" TO "idCard";
ALTER INDEX "Patient_phone_idCardHash_idx"
RENAME TO "Patient_phone_idCard_idx";

View File

@ -0,0 +1,8 @@
ALTER TABLE "User"
DROP CONSTRAINT "User_groupId_fkey";
ALTER TABLE "User"
ADD CONSTRAINT "User_groupId_fkey"
FOREIGN KEY ("groupId") REFERENCES "Group"("id")
ON DELETE RESTRICT
ON UPDATE CASCADE;

View File

@ -71,23 +71,27 @@ model Group {
// 用户表:支持后台密码登录与小程序 openId。
model User {
id Int @id @default(autoincrement())
name String
phone String
id Int @id @default(autoincrement())
name String
phone String
// 后台登录密码哈希bcrypt
passwordHash String?
openId String? @unique
role Role
hospitalId Int?
departmentId Int?
groupId Int?
hospital Hospital? @relation(fields: [hospitalId], references: [id])
department Department? @relation(fields: [departmentId], references: [id])
group Group? @relation(fields: [groupId], references: [id])
doctorPatients Patient[] @relation("DoctorPatients")
createdTasks Task[] @relation("TaskCreator")
acceptedTasks Task[] @relation("TaskEngineer")
passwordHash String?
// 该时间点之前签发的 token 一律失效。
tokenValidAfter DateTime @default(now())
openId String? @unique
role Role
hospitalId Int?
departmentId Int?
groupId Int?
hospital Hospital? @relation(fields: [hospitalId], references: [id])
department Department? @relation(fields: [departmentId], references: [id])
// 小组删除必须先清理成员,避免静默把用户 groupId 置空。
group Group? @relation(fields: [groupId], references: [id], onDelete: Restrict)
doctorPatients Patient[] @relation("DoctorPatients")
createdTasks Task[] @relation("TaskCreator")
acceptedTasks Task[] @relation("TaskEngineer")
@@unique([phone, role, hospitalId])
@@index([phone])
@@index([hospitalId, role])
@@index([departmentId, role])
@ -99,14 +103,15 @@ model Patient {
id Int @id @default(autoincrement())
name String
phone String
idCardHash String
// 患者身份证号,录入与查询都使用原始证件号。
idCard String
hospitalId Int
doctorId Int
hospital Hospital @relation(fields: [hospitalId], references: [id])
doctor User @relation("DoctorPatients", fields: [doctorId], references: [id])
devices Device[]
@@index([phone, idCardHash])
@@index([phone, idCard])
@@index([hospitalId, doctorId])
}

View File

@ -48,7 +48,11 @@ async function ensureGroup(departmentId, name) {
async function upsertUserByOpenId(openId, data) {
return prisma.user.upsert({
where: { openId },
update: data,
// 每次重置/补种子时推进失效时间,确保历史 token 无法继续访问。
update: {
...data,
tokenValidAfter: new Date(),
},
create: {
...data,
openId,
@ -56,18 +60,12 @@ async function upsertUserByOpenId(openId, data) {
});
}
async function ensurePatient({
hospitalId,
doctorId,
name,
phone,
idCardHash,
}) {
async function ensurePatient({ hospitalId, doctorId, name, phone, idCard }) {
const existing = await prisma.patient.findFirst({
where: {
hospitalId,
phone,
idCardHash,
idCard,
},
});
@ -87,7 +85,7 @@ async function ensurePatient({
doctorId,
name,
phone,
idCardHash,
idCard,
},
});
}
@ -224,7 +222,7 @@ async function main() {
doctorId: doctorA.id,
name: 'Seed Patient A1',
phone: '13800002001',
idCardHash: 'seed-id-card-cross-hospital',
idCard: '110101199001010011',
});
const patientA2 = await ensurePatient({
@ -232,7 +230,7 @@ async function main() {
doctorId: doctorA2.id,
name: 'Seed Patient A2',
phone: '13800002002',
idCardHash: 'seed-id-card-a2',
idCard: '110101199002020022',
});
const patientA3 = await ensurePatient({
@ -240,7 +238,7 @@ async function main() {
doctorId: doctorA3.id,
name: 'Seed Patient A3',
phone: '13800002003',
idCardHash: 'seed-id-card-a3',
idCard: '110101199003030033',
});
const patientB1 = await ensurePatient({
@ -248,7 +246,7 @@ async function main() {
doctorId: doctorB.id,
name: 'Seed Patient B1',
phone: '13800002001',
idCardHash: 'seed-id-card-cross-hospital',
idCard: '110101199001010011',
});
const deviceA1 = await prisma.device.upsert({

View File

@ -7,6 +7,7 @@ import { PatientsModule } from './patients/patients.module.js';
import { AuthModule } from './auth/auth.module.js';
import { OrganizationModule } from './organization/organization.module.js';
import { NotificationsModule } from './notifications/notifications.module.js';
import { DevicesModule } from './devices/devices.module.js';
@Module({
imports: [
@ -18,6 +19,7 @@ import { NotificationsModule } from './notifications/notifications.module.js';
AuthModule,
OrganizationModule,
NotificationsModule,
DevicesModule,
],
})
export class AppModule {}

View File

@ -5,25 +5,25 @@ import {
UnauthorizedException,
} from '@nestjs/common';
import jwt from 'jsonwebtoken';
import { Role } from '../generated/prisma/enums.js';
import type { ActorContext } from '../common/actor-context.js';
import { MESSAGES } from '../common/messages.js';
import { PrismaService } from '../prisma.service.js';
/**
* AccessToken Bearer JWT actor request
*/
@Injectable()
export class AccessTokenGuard implements CanActivate {
constructor(private readonly prisma: PrismaService) {}
/**
* true 401
*/
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest<
{
headers: Record<string, string | string[] | undefined>;
actor?: unknown;
}
>();
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<{
headers: Record<string, string | string[] | undefined>;
actor?: unknown;
}>();
const authorization = request.headers.authorization;
const headerValue = Array.isArray(authorization)
@ -35,15 +35,15 @@ export class AccessTokenGuard implements CanActivate {
}
const token = headerValue.slice('Bearer '.length).trim();
request.actor = this.verifyAndExtractActor(token);
request.actor = await this.verifyAndExtractActor(token);
return true;
}
/**
* token actor
* token
*/
private verifyAndExtractActor(token: string): ActorContext {
private async verifyAndExtractActor(token: string): Promise<ActorContext> {
const secret = process.env.AUTH_TOKEN_SECRET;
if (!secret) {
throw new UnauthorizedException(MESSAGES.AUTH.TOKEN_SECRET_MISSING);
@ -63,17 +63,39 @@ export class AccessTokenGuard implements CanActivate {
throw new UnauthorizedException(MESSAGES.AUTH.TOKEN_PAYLOAD_INVALID);
}
const role = payload.role;
if (typeof role !== 'string' || !Object.values(Role).includes(role as Role)) {
throw new UnauthorizedException(MESSAGES.AUTH.TOKEN_ROLE_INVALID);
const userId = this.asInt(payload.id, 'id');
const issuedAt = this.asInt(payload.iat, 'iat');
const user = await this.prisma.user.findUnique({
where: { id: userId },
select: {
id: true,
role: true,
hospitalId: true,
departmentId: true,
groupId: true,
tokenValidAfter: true,
},
});
// 数据库里已经没有该用户时,旧 token 必须立即失效。
if (!user) {
throw new UnauthorizedException(MESSAGES.AUTH.TOKEN_USER_NOT_FOUND);
}
// JWT 的 iat 精度是秒,这里按秒比较,避免同秒登录被误伤。
const tokenValidAfterUnix = Math.floor(
user.tokenValidAfter.getTime() / 1000,
);
if (issuedAt < tokenValidAfterUnix) {
throw new UnauthorizedException(MESSAGES.AUTH.TOKEN_REVOKED);
}
return {
id: this.asInt(payload.id, 'id'),
role: role as Role,
hospitalId: this.asNullableInt(payload.hospitalId, 'hospitalId'),
departmentId: this.asNullableInt(payload.departmentId, 'departmentId'),
groupId: this.asNullableInt(payload.groupId, 'groupId'),
id: user.id,
role: user.role,
hospitalId: user.hospitalId,
departmentId: user.departmentId,
groupId: user.groupId,
};
}
@ -82,20 +104,9 @@ export class AccessTokenGuard implements CanActivate {
*/
private asInt(value: unknown, field: string): number {
if (typeof value !== 'number' || !Number.isInteger(value)) {
throw new UnauthorizedException(`${MESSAGES.AUTH.TOKEN_FIELD_INVALID}: ${field}`);
}
return value;
}
/**
* token
*/
private asNullableInt(value: unknown, field: string): number | null {
if (value === null || value === undefined) {
return null;
}
if (typeof value !== 'number' || !Number.isInteger(value)) {
throw new UnauthorizedException(`${MESSAGES.AUTH.TOKEN_FIELD_INVALID}: ${field}`);
throw new UnauthorizedException(
`${MESSAGES.AUTH.TOKEN_FIELD_INVALID}: ${field}`,
);
}
return value;
}

View File

@ -1,18 +1,14 @@
import { Body, Controller, Get, Post, UseGuards } from '@nestjs/common';
import {
ApiBearerAuth,
ApiOperation,
ApiTags,
} from '@nestjs/swagger';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { AuthService } from './auth.service.js';
import { RegisterUserDto } from '../users/dto/register-user.dto.js';
import { LoginDto } from '../users/dto/login.dto.js';
import { AccessTokenGuard } from './access-token.guard.js';
import { CurrentActor } from './current-actor.decorator.js';
import type { ActorContext } from '../common/actor-context.js';
import { CreateSystemAdminDto } from './dto/create-system-admin.dto.js';
/**
*
*
*/
@ApiTags('认证')
@Controller('auth')
@ -20,12 +16,12 @@ export class AuthController {
constructor(private readonly authService: AuthService) {}
/**
*
*
*/
@Post('register')
@ApiOperation({ summary: '注册账号' })
register(@Body() dto: RegisterUserDto) {
return this.authService.register(dto);
@Post('system-admin')
@ApiOperation({ summary: '创建系统管理员' })
createSystemAdmin(@Body() dto: CreateSystemAdminDto) {
return this.authService.createSystemAdmin(dto);
}
/**

View File

@ -1,8 +1,8 @@
import { Injectable } from '@nestjs/common';
import type { ActorContext } from '../common/actor-context.js';
import { UsersService } from '../users/users.service.js';
import { RegisterUserDto } from '../users/dto/register-user.dto.js';
import { LoginDto } from '../users/dto/login.dto.js';
import { CreateSystemAdminDto } from './dto/create-system-admin.dto.js';
/**
*
@ -12,10 +12,10 @@ export class AuthService {
constructor(private readonly usersService: UsersService) {}
/**
*
*
*/
register(dto: RegisterUserDto) {
return this.usersService.register(dto);
createSystemAdmin(dto: CreateSystemAdminDto) {
return this.usersService.createSystemAdmin(dto);
}
/**

View File

@ -0,0 +1,32 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsOptional, IsString } from 'class-validator';
export class CreateSystemAdminDto {
@ApiProperty({ description: '姓名', example: '系统管理员' })
@IsString({ message: 'name 必须是字符串' })
name!: string;
@ApiProperty({ description: '手机号', example: '13800000000' })
@IsString({ message: 'phone 必须是字符串' })
phone!: string;
@ApiProperty({ description: '密码(至少 8 位)', example: 'Admin@12345' })
@IsString({ message: 'password 必须是字符串' })
password!: string;
@ApiPropertyOptional({
description: '可选微信 openId',
example: 'o123abcxyz',
})
@IsOptional()
@IsString({ message: 'openId 必须是字符串' })
openId?: string;
@ApiProperty({
description:
'系统管理员创建引导密钥(来自环境变量 SYSTEM_ADMIN_BOOTSTRAP_KEY',
example: 'init-admin-secret',
})
@IsString({ message: 'systemAdminBootstrapKey 必须是字符串' })
systemAdminBootstrapKey!: string;
}

View File

@ -21,10 +21,13 @@ export const MESSAGES = {
TOKEN_SECRET_MISSING: '服务端未配置认证密钥',
TOKEN_INVALID: 'Token 无效或已过期',
TOKEN_PAYLOAD_INVALID: 'Token 载荷不合法',
TOKEN_USER_NOT_FOUND: 'Token 对应用户不存在,请重新登录',
TOKEN_REVOKED: 'Token 已失效,请重新登录',
TOKEN_ROLE_INVALID: 'Token 中角色信息不合法',
TOKEN_FIELD_INVALID: 'Token 中字段不合法',
INVALID_CREDENTIALS: '手机号、角色或密码错误',
PASSWORD_NOT_ENABLED: '该账号未启用密码登录',
REGISTER_DISABLED: '注册接口已关闭,请联系管理员创建账号',
},
USER: {
@ -53,6 +56,9 @@ export const MESSAGES = {
DELETE_CONFLICT: '用户存在关联患者或任务,无法删除',
MULTI_ACCOUNT_REQUIRE_HOSPITAL:
'检测到多个同手机号账号,请传 hospitalId 指定登录医院',
CREATE_FORBIDDEN: '当前角色无权限创建该用户',
HOSPITAL_ADMIN_SCOPE_FORBIDDEN: '医院管理员仅可操作本院非管理员账号',
DIRECTOR_SCOPE_FORBIDDEN: '科室主任仅可操作本科室医生账号',
},
TASK: {
@ -79,12 +85,25 @@ export const MESSAGES = {
DOCTOR_ROLE_REQUIRED: '归属用户必须为医生/主任/组长角色',
DOCTOR_SCOPE_FORBIDDEN: '仅可选择当前权限范围内医生/主任/组长',
DELETE_CONFLICT: '患者存在关联设备,无法删除',
PHONE_IDCARD_REQUIRED: 'phone 与 idCardHash 均为必填',
LIFE_CYCLE_NOT_FOUND: '未找到匹配的患者档案,请先确认手机号与身份证哈希',
PHONE_IDCARD_REQUIRED: 'phone 与 idCard 均为必填',
LIFE_CYCLE_NOT_FOUND: '未找到匹配的患者档案,请先确认手机号与身份证',
SYSTEM_ADMIN_HOSPITAL_REQUIRED: '系统管理员查询必须显式传入 hospitalId',
ACTOR_HOSPITAL_REQUIRED: '当前登录上下文缺少医院信息',
},
DEVICE: {
NOT_FOUND: '设备不存在或无权限访问',
SN_CODE_REQUIRED: 'snCode 不能为空',
SN_CODE_DUPLICATE: '设备 SN 已存在',
CURRENT_PRESSURE_INVALID: 'currentPressure 必须为大于等于 0 的整数',
STATUS_INVALID: '设备状态不合法',
PATIENT_REQUIRED: 'patientId 必填且必须为整数',
PATIENT_NOT_FOUND: '归属患者不存在',
PATIENT_SCOPE_FORBIDDEN: '仅可绑定当前权限范围内患者',
DELETE_CONFLICT: '设备存在关联任务记录,无法删除',
ACTOR_HOSPITAL_REQUIRED: '当前登录上下文缺少医院信息',
},
ORG: {
HOSPITAL_NOT_FOUND: '医院不存在',
DEPARTMENT_NOT_FOUND: '科室不存在',
@ -105,6 +124,7 @@ export const MESSAGES = {
GROUP_DEPARTMENT_MISMATCH: '小组不属于指定科室',
DEPARTMENT_REPARENT_FORBIDDEN: '科室不允许更换所属医院',
GROUP_REPARENT_FORBIDDEN: '小组不允许更换所属科室',
GROUP_DELETE_HAS_USERS: '小组下仍有成员,无法删除,请先调整用户归属',
DELETE_CONFLICT:
'存在关联数据,无法删除,请先清理用户、患者、任务或下级组织后重试',
},

View File

@ -0,0 +1,102 @@
import {
Body,
Controller,
Delete,
Get,
Param,
ParseIntPipe,
Patch,
Post,
Query,
UseGuards,
} from '@nestjs/common';
import {
ApiBearerAuth,
ApiOperation,
ApiParam,
ApiTags,
} from '@nestjs/swagger';
import { AccessTokenGuard } from '../../auth/access-token.guard.js';
import { CurrentActor } from '../../auth/current-actor.decorator.js';
import { Roles } from '../../auth/roles.decorator.js';
import { RolesGuard } from '../../auth/roles.guard.js';
import type { ActorContext } from '../../common/actor-context.js';
import { Role } from '../../generated/prisma/enums.js';
import { CreateDeviceDto } from '../dto/create-device.dto.js';
import { DeviceQueryDto } from '../dto/device-query.dto.js';
import { UpdateDeviceDto } from '../dto/update-device.dto.js';
import { DevicesService } from '../devices.service.js';
/**
* B 访 CRUD
*/
@ApiTags('设备管理(B端)')
@ApiBearerAuth('bearer')
@Controller('b/devices')
@UseGuards(AccessTokenGuard, RolesGuard)
export class BDevicesController {
constructor(private readonly devicesService: DevicesService) {}
/**
*
*/
@Get()
@Roles(Role.SYSTEM_ADMIN, Role.HOSPITAL_ADMIN)
@ApiOperation({ summary: '查询设备列表' })
findAll(@CurrentActor() actor: ActorContext, @Query() query: DeviceQueryDto) {
return this.devicesService.findAll(actor, query);
}
/**
*
*/
@Get(':id')
@Roles(Role.SYSTEM_ADMIN, Role.HOSPITAL_ADMIN)
@ApiOperation({ summary: '查询设备详情' })
@ApiParam({ name: 'id', description: '设备 ID' })
findOne(
@CurrentActor() actor: ActorContext,
@Param('id', ParseIntPipe) id: number,
) {
return this.devicesService.findOne(actor, id);
}
/**
*
*/
@Post()
@Roles(Role.SYSTEM_ADMIN, Role.HOSPITAL_ADMIN)
@ApiOperation({ summary: '创建设备' })
create(@CurrentActor() actor: ActorContext, @Body() dto: CreateDeviceDto) {
return this.devicesService.create(actor, dto);
}
/**
*
*/
@Patch(':id')
@Roles(Role.SYSTEM_ADMIN, Role.HOSPITAL_ADMIN)
@ApiOperation({ summary: '更新设备' })
@ApiParam({ name: 'id', description: '设备 ID' })
update(
@CurrentActor() actor: ActorContext,
@Param('id', ParseIntPipe) id: number,
@Body() dto: UpdateDeviceDto,
) {
return this.devicesService.update(actor, id, dto);
}
/**
*
*/
@Delete(':id')
@Roles(Role.SYSTEM_ADMIN, Role.HOSPITAL_ADMIN)
@ApiOperation({ summary: '删除设备' })
@ApiParam({ name: 'id', description: '设备 ID' })
remove(
@CurrentActor() actor: ActorContext,
@Param('id', ParseIntPipe) id: number,
) {
return this.devicesService.remove(actor, id);
}
}

View File

@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { AccessTokenGuard } from '../auth/access-token.guard.js';
import { RolesGuard } from '../auth/roles.guard.js';
import { BDevicesController } from './b-devices/b-devices.controller.js';
import { DevicesService } from './devices.service.js';
@Module({
controllers: [BDevicesController],
providers: [DevicesService, AccessTokenGuard, RolesGuard],
exports: [DevicesService],
})
export class DevicesModule {}

View File

@ -0,0 +1,403 @@
import {
BadRequestException,
ConflictException,
ForbiddenException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { Prisma } from '../generated/prisma/client.js';
import { DeviceStatus, Role } from '../generated/prisma/enums.js';
import type { ActorContext } from '../common/actor-context.js';
import { MESSAGES } from '../common/messages.js';
import { PrismaService } from '../prisma.service.js';
import { CreateDeviceDto } from './dto/create-device.dto.js';
import { DeviceQueryDto } from './dto/device-query.dto.js';
import { UpdateDeviceDto } from './dto/update-device.dto.js';
const DEVICE_DETAIL_INCLUDE = {
patient: {
select: {
id: true,
name: true,
phone: true,
hospitalId: true,
hospital: {
select: {
id: true,
name: true,
},
},
doctor: {
select: {
id: true,
name: true,
role: true,
},
},
},
},
_count: {
select: {
taskItems: true,
},
},
} as const;
/**
* CRUD
*/
@Injectable()
export class DevicesService {
constructor(private readonly prisma: PrismaService) {}
/**
*
*/
async findAll(actor: ActorContext, query: DeviceQueryDto) {
this.assertAdmin(actor);
const paging = this.resolvePaging(query);
const scopedHospitalId = this.resolveScopedHospitalId(
actor,
query.hospitalId,
);
const where = this.buildListWhere(query, scopedHospitalId);
const [total, list] = await this.prisma.$transaction([
this.prisma.device.count({ where }),
this.prisma.device.findMany({
where,
include: DEVICE_DETAIL_INCLUDE,
skip: paging.skip,
take: paging.take,
orderBy: { id: 'desc' },
}),
]);
return {
total,
...paging,
list,
};
}
/**
*
*/
async findOne(actor: ActorContext, id: number) {
this.assertAdmin(actor);
const deviceId = this.toInt(id, 'id');
const device = await this.prisma.device.findUnique({
where: { id: deviceId },
include: DEVICE_DETAIL_INCLUDE,
});
if (!device) {
throw new NotFoundException(MESSAGES.DEVICE.NOT_FOUND);
}
this.assertDeviceReadable(actor, device.patient.hospitalId);
return device;
}
/**
*
*/
async create(actor: ActorContext, dto: CreateDeviceDto) {
this.assertAdmin(actor);
const snCode = this.normalizeSnCode(dto.snCode);
const patient = await this.resolveWritablePatient(actor, dto.patientId);
await this.assertSnCodeUnique(snCode);
return this.prisma.device.create({
data: {
snCode,
currentPressure: this.normalizePressure(dto.currentPressure),
status: dto.status ?? DeviceStatus.ACTIVE,
patientId: patient.id,
},
include: DEVICE_DETAIL_INCLUDE,
});
}
/**
* SN
*/
async update(actor: ActorContext, id: number, dto: UpdateDeviceDto) {
const current = await this.findOne(actor, id);
const data: Prisma.DeviceUpdateInput = {};
if (dto.snCode !== undefined) {
const snCode = this.normalizeSnCode(dto.snCode);
await this.assertSnCodeUnique(snCode, current.id);
data.snCode = snCode;
}
if (dto.currentPressure !== undefined) {
data.currentPressure = this.normalizePressure(dto.currentPressure);
}
if (dto.status !== undefined) {
data.status = this.normalizeStatus(dto.status);
}
if (dto.patientId !== undefined) {
const patient = await this.resolveWritablePatient(actor, dto.patientId);
data.patient = { connect: { id: patient.id } };
}
return this.prisma.device.update({
where: { id: current.id },
data,
include: DEVICE_DETAIL_INCLUDE,
});
}
/**
* 409
*/
async remove(actor: ActorContext, id: number) {
const current = await this.findOne(actor, id);
try {
return await this.prisma.device.delete({
where: { id: current.id },
include: DEVICE_DETAIL_INCLUDE,
});
} catch (error) {
if (
error instanceof Prisma.PrismaClientKnownRequestError &&
(error.code === 'P2003' || error.code === 'P2014')
) {
throw new ConflictException(MESSAGES.DEVICE.DELETE_CONFLICT);
}
throw error;
}
}
/**
*
*/
private buildListWhere(query: DeviceQueryDto, scopedHospitalId?: number) {
const andConditions: Prisma.DeviceWhereInput[] = [];
const keyword = query.keyword?.trim();
if (scopedHospitalId != null) {
andConditions.push({
patient: {
is: {
hospitalId: scopedHospitalId,
},
},
});
}
if (query.patientId != null) {
andConditions.push({
patientId: query.patientId,
});
}
if (query.status != null) {
andConditions.push({
status: query.status,
});
}
if (keyword) {
andConditions.push({
OR: [
{
snCode: {
contains: keyword,
mode: 'insensitive',
},
},
{
patient: {
is: {
name: {
contains: keyword,
mode: 'insensitive',
},
},
},
},
{
patient: {
is: {
phone: {
contains: keyword,
},
},
},
},
],
});
}
return andConditions.length > 0 ? { AND: andConditions } : {};
}
/**
*
*/
private resolvePaging(query: DeviceQueryDto) {
const page = query.page && query.page > 0 ? query.page : 1;
const pageSize =
query.pageSize && query.pageSize > 0 && query.pageSize <= 100
? query.pageSize
: 20;
return {
page,
pageSize,
skip: (page - 1) * pageSize,
take: pageSize,
};
}
/**
*
*/
private resolveScopedHospitalId(
actor: ActorContext,
hospitalId?: number,
): number | undefined {
if (actor.role === Role.SYSTEM_ADMIN) {
return hospitalId;
}
return this.requireActorHospitalId(actor);
}
/**
*
*/
private async resolveWritablePatient(actor: ActorContext, patientId: number) {
const normalizedPatientId = this.toInt(
patientId,
MESSAGES.DEVICE.PATIENT_REQUIRED,
);
const patient = await this.prisma.patient.findUnique({
where: { id: normalizedPatientId },
select: {
id: true,
hospitalId: true,
},
});
if (!patient) {
throw new NotFoundException(MESSAGES.DEVICE.PATIENT_NOT_FOUND);
}
if (
actor.role === Role.HOSPITAL_ADMIN &&
patient.hospitalId !== this.requireActorHospitalId(actor)
) {
throw new ForbiddenException(MESSAGES.DEVICE.PATIENT_SCOPE_FORBIDDEN);
}
return patient;
}
/**
* /
*/
private assertDeviceReadable(actor: ActorContext, hospitalId: number) {
if (actor.role === Role.SYSTEM_ADMIN) {
return;
}
if (hospitalId !== this.requireActorHospitalId(actor)) {
throw new ForbiddenException(MESSAGES.DEFAULT_FORBIDDEN);
}
}
/**
*
*/
private assertAdmin(actor: ActorContext) {
if (
actor.role !== Role.SYSTEM_ADMIN &&
actor.role !== Role.HOSPITAL_ADMIN
) {
throw new ForbiddenException(MESSAGES.DEFAULT_FORBIDDEN);
}
}
/**
* SN
*/
private normalizeSnCode(value: unknown) {
if (typeof value !== 'string') {
throw new BadRequestException(MESSAGES.DEVICE.SN_CODE_REQUIRED);
}
const normalized = value.trim().toUpperCase();
if (!normalized) {
throw new BadRequestException(MESSAGES.DEVICE.SN_CODE_REQUIRED);
}
return normalized;
}
/**
*
*/
private normalizePressure(value: unknown) {
const parsed = Number(value);
if (!Number.isInteger(parsed) || parsed < 0) {
throw new BadRequestException(MESSAGES.DEVICE.CURRENT_PRESSURE_INVALID);
}
return parsed;
}
/**
*
*/
private normalizeStatus(value: unknown): DeviceStatus {
if (!Object.values(DeviceStatus).includes(value as DeviceStatus)) {
throw new BadRequestException(MESSAGES.DEVICE.STATUS_INVALID);
}
return value as DeviceStatus;
}
/**
*
*/
private toInt(value: unknown, message: string) {
const parsed = Number(value);
if (!Number.isInteger(parsed) || parsed <= 0) {
throw new BadRequestException(message);
}
return parsed;
}
/**
* ID
*/
private requireActorHospitalId(actor: ActorContext) {
if (
typeof actor.hospitalId !== 'number' ||
!Number.isInteger(actor.hospitalId) ||
actor.hospitalId <= 0
) {
throw new BadRequestException(MESSAGES.DEVICE.ACTOR_HOSPITAL_REQUIRED);
}
return actor.hospitalId;
}
/**
* SN
*/
private async assertSnCodeUnique(snCode: string, selfId?: number) {
const existing = await this.prisma.device.findUnique({
where: { snCode },
select: { id: true },
});
if (existing && existing.id !== selfId) {
throw new ConflictException(MESSAGES.DEVICE.SN_CODE_DUPLICATE);
}
}
}

View File

@ -0,0 +1,34 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { DeviceStatus } from '../../generated/prisma/enums.js';
import { Type } from 'class-transformer';
import { IsEnum, IsInt, IsOptional, IsString, Min } from 'class-validator';
/**
* DTO
*/
export class CreateDeviceDto {
@ApiProperty({ description: '设备 SN', example: 'TYT-SN-10001' })
@IsString({ message: 'snCode 必须是字符串' })
snCode!: string;
@ApiProperty({ description: '当前压力值', example: 120 })
@Type(() => Number)
@IsInt({ message: 'currentPressure 必须是整数' })
@Min(0, { message: 'currentPressure 必须大于等于 0' })
currentPressure!: number;
@ApiPropertyOptional({
description: '设备状态,默认 ACTIVE',
enum: DeviceStatus,
example: DeviceStatus.ACTIVE,
})
@IsOptional()
@IsEnum(DeviceStatus, { message: 'status 枚举值不合法' })
status?: DeviceStatus;
@ApiProperty({ description: '归属患者 ID', example: 1 })
@Type(() => Number)
@IsInt({ message: 'patientId 必须是整数' })
@Min(1, { message: 'patientId 必须大于 0' })
patientId!: number;
}

View File

@ -0,0 +1,68 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { DeviceStatus } from '../../generated/prisma/enums.js';
import { Type } from 'class-transformer';
import { EmptyStringToUndefined } from '../../common/transforms/empty-string-to-undefined.transform.js';
import { IsEnum, IsInt, IsOptional, IsString, Max, Min } from 'class-validator';
/**
* DTO
*/
export class DeviceQueryDto {
@ApiPropertyOptional({
description: '关键词(支持设备 SN / 患者姓名 / 患者手机号)',
example: 'SN-A',
})
@IsOptional()
@IsString({ message: 'keyword 必须是字符串' })
keyword?: string;
@ApiPropertyOptional({
description: '设备状态',
enum: DeviceStatus,
example: DeviceStatus.ACTIVE,
})
@IsOptional()
@IsEnum(DeviceStatus, { message: 'status 枚举值不合法' })
status?: DeviceStatus;
@ApiPropertyOptional({ description: '医院 ID', example: 1 })
@IsOptional()
@EmptyStringToUndefined()
@Type(() => Number)
@IsInt({ message: 'hospitalId 必须是整数' })
@Min(1, { message: 'hospitalId 必须大于 0' })
hospitalId?: number;
@ApiPropertyOptional({ description: '患者 ID', example: 1 })
@IsOptional()
@EmptyStringToUndefined()
@Type(() => Number)
@IsInt({ message: 'patientId 必须是整数' })
@Min(1, { message: 'patientId 必须大于 0' })
patientId?: number;
@ApiPropertyOptional({
description: '页码(默认 1',
example: 1,
default: 1,
})
@IsOptional()
@EmptyStringToUndefined()
@Type(() => Number)
@IsInt({ message: 'page 必须是整数' })
@Min(1, { message: 'page 最小为 1' })
page?: number = 1;
@ApiPropertyOptional({
description: '每页数量(默认 20最大 100',
example: 20,
default: 20,
})
@IsOptional()
@EmptyStringToUndefined()
@Type(() => Number)
@IsInt({ message: 'pageSize 必须是整数' })
@Min(1, { message: 'pageSize 最小为 1' })
@Max(100, { message: 'pageSize 最大为 100' })
pageSize?: number = 20;
}

View File

@ -0,0 +1,7 @@
import { PartialType } from '@nestjs/swagger';
import { CreateDeviceDto } from './create-device.dto.js';
/**
* DTO
*/
export class UpdateDeviceDto extends PartialType(CreateDeviceDto) {}

View File

@ -1,5 +1,6 @@
import {
BadRequestException,
ConflictException,
ForbiddenException,
Injectable,
NotFoundException,
@ -33,7 +34,10 @@ export class GroupsService {
Role.HOSPITAL_ADMIN,
Role.DIRECTOR,
]);
const departmentId = this.access.toInt(dto.departmentId, MESSAGES.ORG.DEPARTMENT_ID_REQUIRED);
const departmentId = this.access.toInt(
dto.departmentId,
MESSAGES.ORG.DEPARTMENT_ID_REQUIRED,
);
const department = await this.access.ensureDepartmentExists(departmentId);
if (actor.role === Role.HOSPITAL_ADMIN) {
this.access.assertHospitalScope(actor, department.hospitalId);
@ -47,7 +51,10 @@ export class GroupsService {
return this.prisma.group.create({
data: {
name: this.access.normalizeName(dto.name, MESSAGES.ORG.GROUP_NAME_REQUIRED),
name: this.access.normalizeName(
dto.name,
MESSAGES.ORG.GROUP_NAME_REQUIRED,
),
departmentId,
},
});
@ -70,18 +77,26 @@ export class GroupsService {
where.name = { contains: query.keyword.trim(), mode: 'insensitive' };
}
if (query.departmentId != null) {
where.departmentId = this.access.toInt(query.departmentId, MESSAGES.ORG.DEPARTMENT_ID_REQUIRED);
where.departmentId = this.access.toInt(
query.departmentId,
MESSAGES.ORG.DEPARTMENT_ID_REQUIRED,
);
}
if (actor.role === Role.HOSPITAL_ADMIN) {
where.department = { hospitalId: this.access.requireActorHospitalId(actor) };
where.department = {
hospitalId: this.access.requireActorHospitalId(actor),
};
} else if (actor.role === Role.DIRECTOR) {
where.departmentId = this.access.requireActorDepartmentId(actor);
} else if (actor.role === Role.LEADER) {
where.id = this.access.requireActorGroupId(actor);
} else if (query.hospitalId != null) {
where.department = {
hospitalId: this.access.toInt(query.hospitalId, MESSAGES.ORG.HOSPITAL_ID_REQUIRED),
hospitalId: this.access.toInt(
query.hospitalId,
MESSAGES.ORG.HOSPITAL_ID_REQUIRED,
),
};
}
@ -153,7 +168,10 @@ export class GroupsService {
}
if (dto.name !== undefined) {
data.name = this.access.normalizeName(dto.name, MESSAGES.ORG.GROUP_NAME_REQUIRED);
data.name = this.access.normalizeName(
dto.name,
MESSAGES.ORG.GROUP_NAME_REQUIRED,
);
}
return this.prisma.group.update({
@ -172,6 +190,12 @@ export class GroupsService {
Role.DIRECTOR,
]);
const current = await this.findOne(actor, id);
// 业务层先拦截,给前端稳定中文提示;数据库层仍保留 RESTRICT 兜底。
if (current._count.users > 0) {
throw new ConflictException(MESSAGES.ORG.GROUP_DELETE_HAS_USERS);
}
try {
return await this.prisma.group.delete({ where: { id: current.id } });
} catch (error) {

View File

@ -10,7 +10,7 @@ import { ResponseEnvelopeInterceptor } from './common/response-envelope.intercep
async function bootstrap() {
// 创建应用实例并加载核心模块。
const app = await NestFactory.create(AppModule);
app.enableCors();
// 全局校验:清理未知字段、自动类型转换,并将校验错误统一为中文信息。
app.useGlobalPipes(
new ValidationPipe({
@ -39,7 +39,7 @@ async function bootstrap() {
.setTitle('TYT 多租户医疗调压系统 API')
.setDescription('后端接口文档含认证、RBAC、任务流转与患者聚合')
.setVersion('1.0.0')
.addServer('http://localhost:3000', 'localhost')
.addServer('http://192.168.0.140:3000', 'localhost')
.addBearerAuth(
{
type: 'http',

View File

@ -15,7 +15,10 @@ export class WechatNotifyService {
/**
* / API
*/
async notifyTaskChange(openIds: Array<string | null | undefined>, payload: TaskNotifyPayload) {
async notifyTaskChange(
openIds: Array<string | null | undefined>,
payload: TaskNotifyPayload,
) {
const targets = Array.from(
new Set(
openIds
@ -32,10 +35,22 @@ export class WechatNotifyService {
}
for (const openId of targets) {
const maskedOpenId = this.maskOpenId(openId);
// TODO: 在此处调用微信服务号/小程序消息推送 API。
this.logger.log(
`模拟推送任务通知 event=${payload.event}, taskId=${payload.taskId}, openId=${openId}`,
`模拟推送任务通知 event=${payload.event}, taskId=${payload.taskId}, openId=${maskedOpenId}`,
);
}
}
/**
* openId
*/
private maskOpenId(openId: string) {
if (openId.length <= 6) {
return '***';
}
return `${openId.slice(0, 3)}***${openId.slice(-3)}`;
}
}

View File

@ -12,6 +12,7 @@ import type { ActorContext } from '../../common/actor-context.js';
import { MESSAGES } from '../../common/messages.js';
import { CreatePatientDto } from '../dto/create-patient.dto.js';
import { UpdatePatientDto } from '../dto/update-patient.dto.js';
import { normalizePatientIdCard } from '../patient-id-card.util.js';
const PATIENT_OWNER_ROLES: Role[] = [Role.DOCTOR, Role.DIRECTOR, Role.LEADER];
@ -98,7 +99,8 @@ export class BPatientsService {
data: {
name: this.normalizeRequiredString(dto.name, 'name'),
phone: this.normalizePhone(dto.phone),
idCardHash: this.normalizeRequiredString(dto.idCardHash, 'idCardHash'),
// 身份证统一做轻量标准化后落库,数据库中保存原始证件号而不是哈希。
idCard: this.normalizeIdCard(dto.idCard),
hospitalId: doctor.hospitalId!,
doctorId: doctor.id,
},
@ -133,8 +135,9 @@ export class BPatientsService {
if (dto.phone !== undefined) {
data.phone = this.normalizePhone(dto.phone);
}
if (dto.idCardHash !== undefined) {
data.idCardHash = this.normalizeRequiredString(dto.idCardHash, 'idCardHash');
if (dto.idCard !== undefined) {
// 更新时沿用同一标准化逻辑,保证查询条件与落库格式一致。
data.idCard = this.normalizeIdCard(dto.idCard);
}
if (dto.doctorId !== undefined) {
const doctor = await this.resolveWritableDoctor(actor, dto.doctorId);
@ -234,7 +237,10 @@ export class BPatientsService {
}
return;
case Role.DIRECTOR:
if (!actor.departmentId || patient.doctor.departmentId !== actor.departmentId) {
if (
!actor.departmentId ||
patient.doctor.departmentId !== actor.departmentId
) {
throw new ForbiddenException(MESSAGES.PATIENT.ROLE_FORBIDDEN);
}
return;
@ -360,7 +366,9 @@ export class BPatientsService {
normalizedHospitalId == null ||
!Number.isInteger(normalizedHospitalId)
) {
throw new BadRequestException(MESSAGES.PATIENT.SYSTEM_ADMIN_HOSPITAL_REQUIRED);
throw new BadRequestException(
MESSAGES.PATIENT.SYSTEM_ADMIN_HOSPITAL_REQUIRED,
);
}
return normalizedHospitalId;
}
@ -390,4 +398,12 @@ export class BPatientsService {
}
return normalized;
}
/**
* x
*/
private normalizeIdCard(value: unknown) {
const normalized = this.normalizeRequiredString(value, 'idCard');
return normalizePatientIdCard(normalized);
}
}

View File

@ -1,5 +1,11 @@
import { Controller, Get, Query } from '@nestjs/common';
import { ApiOperation, ApiQuery, ApiTags } from '@nestjs/swagger';
import { Controller, Get, Query, UseGuards } from '@nestjs/common';
import {
ApiBearerAuth,
ApiOperation,
ApiQuery,
ApiTags,
} from '@nestjs/swagger';
import { AccessTokenGuard } from '../../auth/access-token.guard.js';
import { FamilyLifecycleQueryDto } from '../dto/family-lifecycle-query.dto.js';
import { CPatientsService } from './c-patients.service.js';
@ -7,21 +13,23 @@ import { CPatientsService } from './c-patients.service.js';
* C
*/
@ApiTags('患者管理(C端)')
@ApiBearerAuth('bearer')
@Controller('c/patients')
@UseGuards(AccessTokenGuard)
export class CPatientsController {
constructor(private readonly patientsService: CPatientsService) {}
/**
*
*
*/
@Get('lifecycle')
@ApiOperation({ summary: '跨院患者生命周期查询' })
@ApiQuery({ name: 'phone', description: '手机号' })
@ApiQuery({ name: 'idCardHash', description: '身份证哈希' })
@ApiQuery({ name: 'idCard', description: '身份证' })
getLifecycle(@Query() query: FamilyLifecycleQueryDto) {
return this.patientsService.getFamilyLifecycleByIdentity(
query.phone,
query.idCardHash,
query.idCard,
);
}
}

View File

@ -1,6 +1,11 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import {
BadRequestException,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { PrismaService } from '../../prisma.service.js';
import { MESSAGES } from '../../common/messages.js';
import { normalizePatientIdCard } from '../patient-id-card.util.js';
/**
* C
@ -10,17 +15,20 @@ export class CPatientsService {
constructor(private readonly prisma: PrismaService) {}
/**
* C phone + idCardHash
* C phone + idCard
*/
async getFamilyLifecycleByIdentity(phone: string, idCardHash: string) {
if (!phone || !idCardHash) {
async getFamilyLifecycleByIdentity(phone: string, idCard: string) {
if (!phone || !idCard) {
throw new BadRequestException(MESSAGES.PATIENT.PHONE_IDCARD_REQUIRED);
}
// 查询侧统一整理身份证格式,避免空格或末尾 x 大小写导致查不到。
const normalizedIdCard = normalizePatientIdCard(idCard);
const patients = await this.prisma.patient.findMany({
where: {
phone,
idCardHash,
idCard: normalizedIdCard,
},
include: {
hospital: { select: { id: true, name: true } },
@ -57,7 +65,6 @@ export class CPatientsService {
patient: {
id: this.toJsonNumber(patient.id),
name: patient.name,
phone: patient.phone,
},
device: {
id: this.toJsonNumber(device.id),
@ -68,9 +75,6 @@ export class CPatientsService {
task: {
id: this.toJsonNumber(task.id),
status: task.status,
creatorId: this.toJsonNumber(task.creatorId),
engineerId: this.toJsonNumber(task.engineerId),
hospitalId: this.toJsonNumber(task.hospitalId),
createdAt: task.createdAt,
},
taskItem: {
@ -89,8 +93,9 @@ export class CPatientsService {
);
return {
// 前端详情弹窗和现有 E2E 都依赖这两个回显字段。
phone,
idCardHash,
idCard: normalizedIdCard,
patientCount: patients.length,
lifecycle,
};

View File

@ -1,11 +1,6 @@
import { ApiProperty } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import {
IsInt,
IsString,
Matches,
Min,
} from 'class-validator';
import { IsInt, IsString, Matches, Min } from 'class-validator';
/**
* DTOB 使
@ -21,11 +16,11 @@ export class CreatePatientDto {
phone!: string;
@ApiProperty({
description: '身份证哈希(前端传加密后值)',
example: 'id-card-hash-demo',
description: '身份证号原文',
example: '110101199001010011',
})
@IsString({ message: 'idCardHash 必须是字符串' })
idCardHash!: string;
@IsString({ message: 'idCard 必须是字符串' })
idCard!: string;
@ApiProperty({ description: '归属人员 ID医生/主任/组长)', example: 10001 })
@Type(() => Number)

View File

@ -10,7 +10,10 @@ export class FamilyLifecycleQueryDto {
@Matches(/^1\d{10}$/, { message: 'phone 必须是合法手机号' })
phone!: string;
@ApiProperty({ description: '身份证哈希值', example: 'seed-id-card-hash' })
@IsString({ message: 'idCardHash 必须是字符串' })
idCardHash!: string;
@ApiProperty({
description: '身份证号原文',
example: '110101199001010011',
})
@IsString({ message: 'idCard 必须是字符串' })
idCard!: string;
}

View File

@ -0,0 +1,8 @@
/**
*
* 1.
* 2. x X
*/
export function normalizePatientIdCard(value: string): string {
return value.trim().replace(/\s+/g, '').toUpperCase();
}

View File

@ -1,6 +1,6 @@
import { ApiProperty } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import { IsInt, Min } from 'class-validator';
import { IsInt, IsOptional, IsString, MaxLength, Min } from 'class-validator';
/**
* DTO
@ -11,4 +11,14 @@ export class CancelTaskDto {
@IsInt({ message: 'taskId 必须是整数' })
@Min(1, { message: 'taskId 必须大于 0' })
taskId!: number;
@ApiProperty({
description: '取消原因(可选,当前仅用于接口兼容与后续通知扩展)',
example: '后台手动取消',
required: false,
})
@IsOptional()
@IsString({ message: 'reason 必须是字符串' })
@MaxLength(100, { message: 'reason 长度不能超过 100 个字符' })
reason?: string;
}

View File

@ -43,7 +43,9 @@ export class TaskService {
throw new BadRequestException(`deviceId 非法: ${item.deviceId}`);
}
if (!Number.isInteger(item.targetPressure)) {
throw new BadRequestException(`targetPressure 非法: ${item.targetPressure}`);
throw new BadRequestException(
`targetPressure 非法: ${item.targetPressure}`,
);
}
return item.deviceId;
}),
@ -138,14 +140,30 @@ export class TaskService {
throw new ForbiddenException(MESSAGES.TASK.ENGINEER_ALREADY_ASSIGNED);
}
const updatedTask = await this.prisma.task.update({
where: { id: task.id },
const accepted = await this.prisma.task.updateMany({
where: {
id: task.id,
hospitalId,
status: TaskStatus.PENDING,
OR: [{ engineerId: null }, { engineerId: actor.id }],
},
data: {
status: TaskStatus.ACCEPTED,
engineerId: actor.id,
},
});
if (accepted.count !== 1) {
throw new ConflictException(MESSAGES.TASK.ACCEPT_ONLY_PENDING);
}
const updatedTask = await this.prisma.task.findUnique({
where: { id: task.id },
include: { items: true },
});
if (!updatedTask) {
throw new NotFoundException(MESSAGES.TASK.TASK_NOT_FOUND);
}
await this.eventEmitter.emitAsync('task.accepted', {
taskId: updatedTask.id,
@ -257,6 +275,8 @@ export class TaskService {
hospitalId: cancelledTask.hospitalId,
actorId: actor.id,
status: cancelledTask.status,
// 当前库表未持久化取消原因,但先透传到事件层,方便通知链路后续接入。
reason: dto.reason?.trim() || null,
});
return cancelledTask;

View File

@ -38,22 +38,20 @@ export class UsersController {
*
*/
@Post()
@Roles(Role.SYSTEM_ADMIN, Role.HOSPITAL_ADMIN)
@Roles(Role.SYSTEM_ADMIN, Role.HOSPITAL_ADMIN, Role.DIRECTOR)
@ApiOperation({ summary: '创建用户' })
create(@Body() createUserDto: CreateUserDto) {
return this.usersService.create(createUserDto);
create(
@CurrentActor() actor: ActorContext,
@Body() createUserDto: CreateUserDto,
) {
return this.usersService.create(actor, createUserDto);
}
/**
*
*/
@Get()
@Roles(
Role.SYSTEM_ADMIN,
Role.HOSPITAL_ADMIN,
Role.DIRECTOR,
Role.LEADER,
)
@Roles(Role.SYSTEM_ADMIN, Role.HOSPITAL_ADMIN, Role.DIRECTOR, Role.LEADER)
@ApiOperation({ summary: '查询用户列表' })
findAll(@CurrentActor() actor: ActorContext) {
return this.usersService.findAll(actor);
@ -63,32 +61,36 @@ export class UsersController {
*
*/
@Get(':id')
@Roles(Role.SYSTEM_ADMIN, Role.HOSPITAL_ADMIN)
@Roles(Role.SYSTEM_ADMIN, Role.HOSPITAL_ADMIN, Role.DIRECTOR)
@ApiOperation({ summary: '查询用户详情' })
@ApiParam({ name: 'id', description: '用户 ID' })
findOne(@Param('id') id: string) {
return this.usersService.findOne(+id);
findOne(@CurrentActor() actor: ActorContext, @Param('id') id: string) {
return this.usersService.findOne(actor, +id);
}
/**
*
*/
@Patch(':id')
@Roles(Role.SYSTEM_ADMIN, Role.HOSPITAL_ADMIN)
@Roles(Role.SYSTEM_ADMIN, Role.HOSPITAL_ADMIN, Role.DIRECTOR)
@ApiOperation({ summary: '更新用户' })
@ApiParam({ name: 'id', description: '用户 ID' })
update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
return this.usersService.update(+id, updateUserDto);
update(
@CurrentActor() actor: ActorContext,
@Param('id') id: string,
@Body() updateUserDto: UpdateUserDto,
) {
return this.usersService.update(actor, +id, updateUserDto);
}
/**
*
*/
@Delete(':id')
@Roles(Role.SYSTEM_ADMIN)
@Roles(Role.SYSTEM_ADMIN, Role.DIRECTOR)
@ApiOperation({ summary: '删除用户' })
@ApiParam({ name: 'id', description: '用户 ID' })
remove(@Param('id') id: string) {
return this.usersService.remove(+id);
remove(@CurrentActor() actor: ActorContext, @Param('id') id: string) {
return this.usersService.remove(actor, +id);
}
}

View File

@ -15,9 +15,9 @@ import { Role } from '../generated/prisma/enums.js';
import { PrismaService } from '../prisma.service.js';
import type { ActorContext } from '../common/actor-context.js';
import { AssignEngineerHospitalDto } from './dto/assign-engineer-hospital.dto.js';
import { RegisterUserDto } from './dto/register-user.dto.js';
import { LoginDto } from './dto/login.dto.js';
import { MESSAGES } from '../common/messages.js';
import { CreateSystemAdminDto } from '../auth/dto/create-system-admin.dto.js';
const SAFE_USER_SELECT = {
id: true,
@ -35,25 +35,27 @@ export class UsersService {
constructor(private readonly prisma: PrismaService) {}
/**
* bcrypt
*
*/
async register(dto: RegisterUserDto) {
const role = this.normalizeRole(dto.role);
async register() {
throw new ForbiddenException(MESSAGES.AUTH.REGISTER_DISABLED);
}
/**
*
*/
async createSystemAdmin(dto: CreateSystemAdminDto) {
const name = this.normalizeRequiredString(dto.name, 'name');
const phone = this.normalizePhone(dto.phone);
const password = this.normalizePassword(dto.password);
const openId = this.normalizeOptionalString(dto.openId);
const hospitalId = this.normalizeOptionalInt(dto.hospitalId, 'hospitalId');
const departmentId = this.normalizeOptionalInt(
dto.departmentId,
'departmentId',
);
const groupId = this.normalizeOptionalInt(dto.groupId, 'groupId');
this.assertSystemAdminBootstrapKey(role, dto.systemAdminBootstrapKey);
await this.assertOrganizationScope(role, hospitalId, departmentId, groupId);
this.assertSystemAdminBootstrapKey(
Role.SYSTEM_ADMIN,
dto.systemAdminBootstrapKey,
);
await this.assertOpenIdUnique(openId);
await this.assertPhoneRoleScopeUnique(phone, role, hospitalId);
await this.assertPhoneRoleScopeUnique(phone, Role.SYSTEM_ADMIN, null);
const passwordHash = await hash(password, 12);
@ -63,10 +65,10 @@ export class UsersService {
phone,
passwordHash,
openId,
role,
hospitalId,
departmentId,
groupId,
role: Role.SYSTEM_ADMIN,
hospitalId: null,
departmentId: null,
groupId: null,
},
select: SAFE_USER_SELECT,
});
@ -133,13 +135,13 @@ export class UsersService {
*
*/
async me(actor: ActorContext) {
return this.findOne(actor.id);
return this.findOne(actor, actor.id);
}
/**
* B 使
*/
async create(createUserDto: CreateUserDto) {
async create(actor: ActorContext, createUserDto: CreateUserDto) {
const role = this.normalizeRole(createUserDto.role);
const name = this.normalizeRequiredString(createUserDto.name, 'name');
const phone = this.normalizePhone(createUserDto.phone);
@ -157,9 +159,22 @@ export class UsersService {
);
const groupId = this.normalizeOptionalInt(createUserDto.groupId, 'groupId');
await this.assertOrganizationScope(role, hospitalId, departmentId, groupId);
const scoped = this.resolveCreateScope(
actor,
role,
hospitalId,
departmentId,
groupId,
);
await this.assertOrganizationScope(
role,
scoped.hospitalId,
scoped.departmentId,
scoped.groupId,
);
await this.assertOpenIdUnique(openId);
await this.assertPhoneRoleScopeUnique(phone, role, hospitalId);
await this.assertPhoneRoleScopeUnique(phone, role, scoped.hospitalId);
return this.prisma.user.create({
data: {
@ -168,9 +183,9 @@ export class UsersService {
passwordHash: password ? await hash(password, 12) : null,
openId,
role,
hospitalId,
departmentId,
groupId,
hospitalId: scoped.hospitalId,
departmentId: scoped.departmentId,
groupId: scoped.groupId,
},
select: SAFE_USER_SELECT,
});
@ -210,7 +225,7 @@ export class UsersService {
/**
*
*/
async findOne(id: number) {
async findOne(actor: ActorContext, id: number) {
const userId = this.normalizeRequiredInt(id, 'id');
const user = await this.prisma.user.findUnique({
@ -221,13 +236,15 @@ export class UsersService {
throw new NotFoundException(MESSAGES.USER.NOT_FOUND);
}
this.assertUserReadable(actor, user);
return user;
}
/**
*
*/
async update(id: number, updateUserDto: UpdateUserDto) {
async update(actor: ActorContext, id: number, updateUserDto: UpdateUserDto) {
const userId = this.normalizeRequiredInt(id, 'id');
const current = await this.prisma.user.findUnique({
where: { id: userId },
@ -240,8 +257,12 @@ export class UsersService {
throw new NotFoundException(MESSAGES.USER.NOT_FOUND);
}
this.assertUserWritable(actor, current);
const nextRole =
updateUserDto.role != null ? this.normalizeRole(updateUserDto.role) : current.role;
updateUserDto.role != null
? this.normalizeRole(updateUserDto.role)
: current.role;
const nextHospitalId =
updateUserDto.hospitalId !== undefined
? this.normalizeOptionalInt(updateUserDto.hospitalId, 'hospitalId')
@ -255,6 +276,10 @@ export class UsersService {
? this.normalizeOptionalInt(updateUserDto.groupId, 'groupId')
: current.groupId;
this.assertUpdateTargetRoleAllowed(actor, nextRole);
this.assertUpdateHospitalScopeAllowed(actor, nextHospitalId);
this.assertUpdateDepartmentScopeAllowed(actor, nextDepartmentId);
const assigningDepartmentOrGroup =
(updateUserDto.departmentId !== undefined && nextDepartmentId != null) ||
(updateUserDto.groupId !== undefined && nextGroupId != null);
@ -313,10 +338,12 @@ export class UsersService {
data.openId = nextOpenId;
}
if (updateUserDto.password) {
// 密码变更后立即吊销旧 token避免旧会话继续使用。
data.passwordHash = await hash(
this.normalizePassword(updateUserDto.password),
12,
);
data.tokenValidAfter = new Date();
}
return this.prisma.user.update({
@ -329,9 +356,10 @@ export class UsersService {
/**
*
*/
async remove(id: number) {
async remove(actor: ActorContext, id: number) {
const userId = this.normalizeRequiredInt(id, 'id');
await this.findOne(userId);
const target = await this.findOne(actor, userId);
this.assertUserWritable(actor, target);
try {
return await this.prisma.user.delete({
@ -397,7 +425,9 @@ export class UsersService {
/**
*
*/
private toSafeUser(user: { passwordHash?: string | null } & Record<string, unknown>) {
private toSafeUser(
user: { passwordHash?: string | null } & Record<string, unknown>,
) {
const { passwordHash, ...safe } = user;
return safe;
}
@ -512,7 +542,9 @@ export class UsersService {
select: { id: true, hospitalId: true },
});
if (!department || department.hospitalId !== hospitalId) {
throw new BadRequestException(MESSAGES.USER.DEPARTMENT_HOSPITAL_MISMATCH);
throw new BadRequestException(
MESSAGES.USER.DEPARTMENT_HOSPITAL_MISMATCH,
);
}
}
@ -630,6 +662,268 @@ export class UsersService {
return role as Role;
}
/**
*
*/
private resolveCreateScope(
actor: ActorContext,
targetRole: Role,
hospitalId: number | null,
departmentId: number | null,
groupId: number | null,
) {
if (actor.role === Role.SYSTEM_ADMIN) {
if (targetRole === Role.SYSTEM_ADMIN) {
return { hospitalId: null, departmentId: null, groupId: null };
}
// 系统管理员可创建任意角色,具体归属由后续组织范围校验保证合法。
return { hospitalId, departmentId, groupId };
}
if (actor.role !== Role.HOSPITAL_ADMIN) {
if (actor.role !== Role.DIRECTOR) {
throw new ForbiddenException(MESSAGES.USER.CREATE_FORBIDDEN);
}
// 科室主任仅允许创建本科室医生。
if (targetRole !== Role.DOCTOR) {
throw new ForbiddenException(MESSAGES.USER.CREATE_FORBIDDEN);
}
const actorHospitalId = this.requireActorScopeInt(
actor.hospitalId,
MESSAGES.ORG.ACTOR_HOSPITAL_REQUIRED,
);
const actorDepartmentId = this.requireActorScopeInt(
actor.departmentId,
MESSAGES.ORG.ACTOR_DEPARTMENT_REQUIRED,
);
if (hospitalId != null && hospitalId !== actorHospitalId) {
throw new ForbiddenException(MESSAGES.USER.CREATE_FORBIDDEN);
}
if (departmentId != null && departmentId !== actorDepartmentId) {
throw new ForbiddenException(MESSAGES.USER.CREATE_FORBIDDEN);
}
return {
hospitalId: actorHospitalId,
departmentId: actorDepartmentId,
groupId,
};
}
if (
targetRole === Role.SYSTEM_ADMIN ||
targetRole === Role.HOSPITAL_ADMIN
) {
throw new ForbiddenException(MESSAGES.USER.CREATE_FORBIDDEN);
}
const actorHospitalId = this.requireActorScopeInt(
actor.hospitalId,
MESSAGES.ORG.ACTOR_HOSPITAL_REQUIRED,
);
const scopedHospitalId = hospitalId ?? actorHospitalId;
if (scopedHospitalId !== actorHospitalId) {
throw new ForbiddenException(
MESSAGES.USER.HOSPITAL_ADMIN_SCOPE_FORBIDDEN,
);
}
return {
hospitalId: scopedHospitalId,
departmentId,
groupId,
};
}
/**
*
*/
private assertUserReadable(
actor: ActorContext,
target: Pick<typeof SAFE_USER_SELECT, never> & {
id: number;
role: Role;
hospitalId: number | null;
departmentId: number | null;
},
) {
if (actor.role === Role.SYSTEM_ADMIN) {
return;
}
if (actor.id === target.id) {
return;
}
if (actor.role === Role.HOSPITAL_ADMIN) {
const actorHospitalId = this.requireActorScopeInt(
actor.hospitalId,
MESSAGES.ORG.ACTOR_HOSPITAL_REQUIRED,
);
if (target.hospitalId === actorHospitalId) {
return;
}
}
if (actor.role === Role.DIRECTOR) {
const actorHospitalId = this.requireActorScopeInt(
actor.hospitalId,
MESSAGES.ORG.ACTOR_HOSPITAL_REQUIRED,
);
const actorDepartmentId = this.requireActorScopeInt(
actor.departmentId,
MESSAGES.ORG.ACTOR_DEPARTMENT_REQUIRED,
);
if (
target.role === Role.DOCTOR &&
target.hospitalId === actorHospitalId &&
target.departmentId === actorDepartmentId
) {
return;
}
throw new ForbiddenException(MESSAGES.USER.DIRECTOR_SCOPE_FORBIDDEN);
}
throw new ForbiddenException(MESSAGES.DEFAULT_FORBIDDEN);
}
/**
*
*/
private assertUserWritable(
actor: ActorContext,
target: {
id: number;
role: Role;
hospitalId: number | null;
departmentId: number | null;
},
) {
if (actor.role === Role.SYSTEM_ADMIN) {
return;
}
if (actor.role === Role.DIRECTOR) {
const actorHospitalId = this.requireActorScopeInt(
actor.hospitalId,
MESSAGES.ORG.ACTOR_HOSPITAL_REQUIRED,
);
const actorDepartmentId = this.requireActorScopeInt(
actor.departmentId,
MESSAGES.ORG.ACTOR_DEPARTMENT_REQUIRED,
);
if (
target.role !== Role.DOCTOR ||
target.hospitalId !== actorHospitalId ||
target.departmentId !== actorDepartmentId
) {
throw new ForbiddenException(MESSAGES.USER.DIRECTOR_SCOPE_FORBIDDEN);
}
return;
}
if (actor.role !== Role.HOSPITAL_ADMIN) {
throw new ForbiddenException(MESSAGES.DEFAULT_FORBIDDEN);
}
const actorHospitalId = this.requireActorScopeInt(
actor.hospitalId,
MESSAGES.ORG.ACTOR_HOSPITAL_REQUIRED,
);
if (target.hospitalId !== actorHospitalId) {
throw new ForbiddenException(
MESSAGES.USER.HOSPITAL_ADMIN_SCOPE_FORBIDDEN,
);
}
if (
target.role === Role.HOSPITAL_ADMIN ||
target.role === Role.SYSTEM_ADMIN
) {
throw new ForbiddenException(
MESSAGES.USER.HOSPITAL_ADMIN_SCOPE_FORBIDDEN,
);
}
}
/**
*
*/
private assertUpdateTargetRoleAllowed(actor: ActorContext, nextRole: Role) {
if (actor.role === Role.SYSTEM_ADMIN) {
return;
}
if (actor.role === Role.DIRECTOR && nextRole !== Role.DOCTOR) {
throw new ForbiddenException(MESSAGES.USER.DIRECTOR_SCOPE_FORBIDDEN);
}
if (
actor.role === Role.HOSPITAL_ADMIN &&
(nextRole === Role.SYSTEM_ADMIN || nextRole === Role.HOSPITAL_ADMIN)
) {
throw new ForbiddenException(
MESSAGES.USER.HOSPITAL_ADMIN_SCOPE_FORBIDDEN,
);
}
}
/**
*
*/
private assertUpdateHospitalScopeAllowed(
actor: ActorContext,
hospitalId: number | null,
) {
if (actor.role === Role.DIRECTOR) {
const actorHospitalId = this.requireActorScopeInt(
actor.hospitalId,
MESSAGES.ORG.ACTOR_HOSPITAL_REQUIRED,
);
if (hospitalId !== actorHospitalId) {
throw new ForbiddenException(MESSAGES.USER.DIRECTOR_SCOPE_FORBIDDEN);
}
return;
}
if (actor.role !== Role.HOSPITAL_ADMIN) {
return;
}
const actorHospitalId = this.requireActorScopeInt(
actor.hospitalId,
MESSAGES.ORG.ACTOR_HOSPITAL_REQUIRED,
);
if (hospitalId !== actorHospitalId) {
throw new ForbiddenException(
MESSAGES.USER.HOSPITAL_ADMIN_SCOPE_FORBIDDEN,
);
}
}
/**
*
*/
private assertUpdateDepartmentScopeAllowed(
actor: ActorContext,
departmentId: number | null,
) {
if (actor.role !== Role.DIRECTOR) {
return;
}
const actorDepartmentId = this.requireActorScopeInt(
actor.departmentId,
MESSAGES.ORG.ACTOR_DEPARTMENT_REQUIRED,
);
if (departmentId !== actorDepartmentId) {
throw new ForbiddenException(MESSAGES.USER.DIRECTOR_SCOPE_FORBIDDEN);
}
}
/**
* 访
*/

View File

@ -81,16 +81,14 @@ async function requirePatientId(
prisma: PrismaService,
hospitalId: number,
phone: string,
idCardHash: string,
idCard: string,
): Promise<number> {
const patient = await prisma.patient.findFirst({
where: { hospitalId, phone, idCardHash },
where: { hospitalId, phone, idCard },
select: { id: true },
});
if (!patient) {
throw new NotFoundException(
`Seed patient not found: ${phone}/${idCardHash}`,
);
throw new NotFoundException(`Seed patient not found: ${phone}/${idCard}`);
}
return patient.id;
}
@ -163,25 +161,25 @@ export async function loadSeedFixtures(
prisma,
hospitalAId,
'13800002001',
'seed-id-card-cross-hospital',
'110101199001010011',
),
patientA2Id: await requirePatientId(
prisma,
hospitalAId,
'13800002002',
'seed-id-card-a2',
'110101199002020022',
),
patientA3Id: await requirePatientId(
prisma,
hospitalAId,
'13800002003',
'seed-id-card-a3',
'110101199003030033',
),
patientB1Id: await requirePatientId(
prisma,
hospitalBId,
'13800002001',
'seed-id-card-cross-hospital',
'110101199001010011',
),
},
devices: {

View File

@ -0,0 +1,59 @@
import request from 'supertest';
import { Role } from '../../../src/generated/prisma/enums.js';
import {
closeE2EContext,
createE2EContext,
type E2EContext,
} from '../helpers/e2e-context.helper.js';
import {
expectErrorEnvelope,
expectSuccessEnvelope,
} from '../helpers/e2e-http.helper.js';
describe('Auth token revocation (e2e)', () => {
let ctx: E2EContext;
beforeAll(async () => {
ctx = await createE2EContext();
});
afterAll(async () => {
await closeE2EContext(ctx);
});
it('旧 token 在 tokenValidAfter 推进后失效', async () => {
const token = ctx.tokens[Role.DOCTOR];
const originalUser = await ctx.prisma.user.findUnique({
where: { id: ctx.fixtures.users.doctorAId },
select: { tokenValidAfter: true },
});
const beforeResponse = await request(ctx.app.getHttpServer())
.get('/auth/me')
.set('Authorization', `Bearer ${token}`);
expectSuccessEnvelope(beforeResponse, 200);
try {
await ctx.prisma.user.update({
where: { id: ctx.fixtures.users.doctorAId },
// 往未来推进一分钟,确保当前 token 的 iat 一定早于失效时间。
data: { tokenValidAfter: new Date(Date.now() + 60_000) },
});
const afterResponse = await request(ctx.app.getHttpServer())
.get('/auth/me')
.set('Authorization', `Bearer ${token}`);
expectErrorEnvelope(afterResponse, 401, 'Token 已失效,请重新登录');
} finally {
if (originalUser) {
// 恢复种子用户状态,避免串行 E2E 后续用例继续拿到失效 token。
await ctx.prisma.user.update({
where: { id: ctx.fixtures.users.doctorAId },
data: { tokenValidAfter: originalUser.tokenValidAfter },
});
}
}
});
});

View File

@ -24,39 +24,33 @@ describe('AuthController (e2e)', () => {
await closeE2EContext(ctx);
});
describe('POST /auth/register', () => {
it('成功:注册医生账号', async () => {
describe('POST /auth/system-admin', () => {
it('成功:创建系统管理员账号', async () => {
const response = await request(ctx.app.getHttpServer())
.post('/auth/register')
.post('/auth/system-admin')
.send({
name: uniqueSeedValue('Auth 注册医生'),
name: uniqueSeedValue('Auth 系统管理员'),
phone: uniquePhone(),
password: 'Seed@1234',
role: Role.DOCTOR,
hospitalId: ctx.fixtures.hospitalAId,
departmentId: ctx.fixtures.departmentA1Id,
groupId: ctx.fixtures.groupA1Id,
openId: uniqueSeedValue('auth-register-openid'),
openId: uniqueSeedValue('auth-system-admin-openid'),
systemAdminBootstrapKey: process.env.SYSTEM_ADMIN_BOOTSTRAP_KEY,
});
expectSuccessEnvelope(response, 201);
expect(response.body.data.role).toBe(Role.DOCTOR);
expect(response.body.data.role).toBe(Role.SYSTEM_ADMIN);
});
it('失败:参数不合法返回 400', async () => {
const response = await request(ctx.app.getHttpServer())
.post('/auth/register')
.post('/auth/system-admin')
.send({
name: 'bad-register',
name: 'bad-system-admin',
phone: '13800009999',
password: '123',
role: Role.DOCTOR,
hospitalId: ctx.fixtures.hospitalAId,
departmentId: ctx.fixtures.departmentA1Id,
groupId: ctx.fixtures.groupA1Id,
systemAdminBootstrapKey: process.env.SYSTEM_ADMIN_BOOTSTRAP_KEY,
});
expectErrorEnvelope(response, 400, 'password 长度至少 8 位');
expectErrorEnvelope(response, 400, '密码长度至少 8 位');
});
});

View File

@ -0,0 +1,161 @@
import request from 'supertest';
import { DeviceStatus, Role } from '../../../src/generated/prisma/enums.js';
import {
closeE2EContext,
createE2EContext,
type E2EContext,
} from '../helpers/e2e-context.helper.js';
import { assertRoleMatrix } from '../helpers/e2e-matrix.helper.js';
import {
expectErrorEnvelope,
expectSuccessEnvelope,
uniqueSeedValue,
} from '../helpers/e2e-http.helper.js';
describe('BDevicesController (e2e)', () => {
let ctx: E2EContext;
beforeAll(async () => {
ctx = await createE2EContext();
});
afterAll(async () => {
await closeE2EContext(ctx);
});
async function createDevice(token: string, patientId: number) {
const response = await request(ctx.app.getHttpServer())
.post('/b/devices')
.set('Authorization', `Bearer ${token}`)
.send({
snCode: uniqueSeedValue('device-sn'),
currentPressure: 118,
status: DeviceStatus.ACTIVE,
patientId,
});
expectSuccessEnvelope(response, 201);
return response.body.data as {
id: number;
snCode: string;
status: DeviceStatus;
patient: { id: number };
};
}
describe('GET /b/devices', () => {
it('成功SYSTEM_ADMIN 可分页查询设备列表', async () => {
const response = await request(ctx.app.getHttpServer())
.get('/b/devices')
.set('Authorization', `Bearer ${ctx.tokens[Role.SYSTEM_ADMIN]}`);
expectSuccessEnvelope(response, 200);
expect(Array.isArray(response.body.data.list)).toBe(true);
expect(response.body.data.total).toBeGreaterThan(0);
});
it('成功HOSPITAL_ADMIN 仅能看到本院设备', async () => {
const response = await request(ctx.app.getHttpServer())
.get('/b/devices')
.set('Authorization', `Bearer ${ctx.tokens[Role.HOSPITAL_ADMIN]}`);
expectSuccessEnvelope(response, 200);
const hospitalIds = (
response.body.data.list as Array<{
patient?: { hospital?: { id: number } };
}>
)
.map((item) => item.patient?.hospital?.id)
.filter(Boolean);
expect(hospitalIds.every((id) => id === ctx.fixtures.hospitalAId)).toBe(
true,
);
});
it('角色矩阵:仅 SYSTEM_ADMIN/HOSPITAL_ADMIN 可访问列表,其他角色 403未登录 401', async () => {
await assertRoleMatrix({
name: 'GET /b/devices role matrix',
tokens: ctx.tokens,
expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 200,
[Role.HOSPITAL_ADMIN]: 200,
[Role.DIRECTOR]: 403,
[Role.LEADER]: 403,
[Role.DOCTOR]: 403,
[Role.ENGINEER]: 403,
},
sendAsRole: async (_role, token) =>
request(ctx.app.getHttpServer())
.get('/b/devices')
.set('Authorization', `Bearer ${token}`),
sendWithoutToken: async () =>
request(ctx.app.getHttpServer()).get('/b/devices'),
});
});
});
describe('设备 CRUD 流程', () => {
it('成功HOSPITAL_ADMIN 可创建设备', async () => {
const created = await createDevice(
ctx.tokens[Role.HOSPITAL_ADMIN],
ctx.fixtures.patients.patientA1Id,
);
expect(created.status).toBe(DeviceStatus.ACTIVE);
expect(created.patient.id).toBe(ctx.fixtures.patients.patientA1Id);
expect(created.snCode).toMatch(/^DEVICE-SN-/);
});
it('失败HOSPITAL_ADMIN 绑定跨院患者返回 403', async () => {
const response = await request(ctx.app.getHttpServer())
.post('/b/devices')
.set('Authorization', `Bearer ${ctx.tokens[Role.HOSPITAL_ADMIN]}`)
.send({
snCode: uniqueSeedValue('cross-hospital-device'),
currentPressure: 120,
status: DeviceStatus.ACTIVE,
patientId: ctx.fixtures.patients.patientB1Id,
});
expectErrorEnvelope(response, 403, '仅可绑定当前权限范围内患者');
});
it('成功SYSTEM_ADMIN 可更新设备状态与归属患者', async () => {
const created = await createDevice(
ctx.tokens[Role.SYSTEM_ADMIN],
ctx.fixtures.patients.patientA1Id,
);
const response = await request(ctx.app.getHttpServer())
.patch(`/b/devices/${created.id}`)
.set('Authorization', `Bearer ${ctx.tokens[Role.SYSTEM_ADMIN]}`)
.send({
status: DeviceStatus.INACTIVE,
patientId: ctx.fixtures.patients.patientA2Id,
currentPressure: 99,
});
expectSuccessEnvelope(response, 200);
expect(response.body.data.status).toBe(DeviceStatus.INACTIVE);
expect(response.body.data.patient.id).toBe(
ctx.fixtures.patients.patientA2Id,
);
expect(response.body.data.currentPressure).toBe(99);
});
it('成功SYSTEM_ADMIN 可删除未被任务引用的设备', async () => {
const created = await createDevice(
ctx.tokens[Role.SYSTEM_ADMIN],
ctx.fixtures.patients.patientA1Id,
);
const response = await request(ctx.app.getHttpServer())
.delete(`/b/devices/${created.id}`)
.set('Authorization', `Bearer ${ctx.tokens[Role.SYSTEM_ADMIN]}`);
expectSuccessEnvelope(response, 200);
expect(response.body.data.id).toBe(created.id);
});
});
});

View File

@ -86,15 +86,15 @@ describe('Organization Controllers (e2e)', () => {
expectErrorEnvelope(response, 401, '缺少 Bearer Token');
});
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN 可访问,其他角色 403未登录 401', async () => {
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN/DIRECTOR/LEADER 可访问,其余角色 403未登录 401', async () => {
await assertRoleMatrix({
name: 'GET /b/organization/hospitals role matrix',
tokens: ctx.tokens,
expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 200,
[Role.HOSPITAL_ADMIN]: 200,
[Role.DIRECTOR]: 403,
[Role.LEADER]: 403,
[Role.DIRECTOR]: 200,
[Role.LEADER]: 200,
[Role.DOCTOR]: 403,
[Role.ENGINEER]: 403,
},
@ -126,15 +126,15 @@ describe('Organization Controllers (e2e)', () => {
expectErrorEnvelope(response, 403, '院管仅可操作本院组织数据');
});
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN 可访问,其他角色 403未登录 401', async () => {
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN/DIRECTOR/LEADER 可访问,其余角色 403未登录 401', async () => {
await assertRoleMatrix({
name: 'GET /b/organization/hospitals/:id role matrix',
tokens: ctx.tokens,
expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 200,
[Role.HOSPITAL_ADMIN]: 200,
[Role.DIRECTOR]: 403,
[Role.LEADER]: 403,
[Role.DIRECTOR]: 200,
[Role.LEADER]: 200,
[Role.DOCTOR]: 403,
[Role.ENGINEER]: 403,
},
@ -321,15 +321,15 @@ describe('Organization Controllers (e2e)', () => {
expectErrorEnvelope(response, 401, '缺少 Bearer Token');
});
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN 可访问,其他角色 403未登录 401', async () => {
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN/DIRECTOR/LEADER 可访问,其余角色 403未登录 401', async () => {
await assertRoleMatrix({
name: 'GET /b/organization/departments role matrix',
tokens: ctx.tokens,
expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 200,
[Role.HOSPITAL_ADMIN]: 200,
[Role.DIRECTOR]: 403,
[Role.LEADER]: 403,
[Role.DIRECTOR]: 200,
[Role.LEADER]: 200,
[Role.DOCTOR]: 403,
[Role.ENGINEER]: 403,
},
@ -361,15 +361,15 @@ describe('Organization Controllers (e2e)', () => {
expectErrorEnvelope(response, 403, '院管仅可操作本院组织数据');
});
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN 可访问,其他角色 403未登录 401', async () => {
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN/DIRECTOR/LEADER 可访问,其余角色 403未登录 401', async () => {
await assertRoleMatrix({
name: 'GET /b/organization/departments/:id role matrix',
tokens: ctx.tokens,
expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 200,
[Role.HOSPITAL_ADMIN]: 200,
[Role.DIRECTOR]: 403,
[Role.LEADER]: 403,
[Role.DIRECTOR]: 200,
[Role.LEADER]: 200,
[Role.DOCTOR]: 403,
[Role.ENGINEER]: 403,
},
@ -413,15 +413,15 @@ describe('Organization Controllers (e2e)', () => {
expectErrorEnvelope(response, 403, '院管仅可操作本院组织数据');
});
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN 可进入业务,其他角色 403未登录 401', async () => {
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN/DIRECTOR/LEADER 可进入业务,其余角色 403未登录 401', async () => {
await assertRoleMatrix({
name: 'PATCH /b/organization/departments/:id role matrix',
tokens: ctx.tokens,
expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 404,
[Role.HOSPITAL_ADMIN]: 404,
[Role.DIRECTOR]: 403,
[Role.LEADER]: 403,
[Role.DIRECTOR]: 404,
[Role.LEADER]: 404,
[Role.DOCTOR]: 403,
[Role.ENGINEER]: 403,
},
@ -516,14 +516,14 @@ describe('Organization Controllers (e2e)', () => {
expectErrorEnvelope(response, 403, '院管仅可操作本院组织数据');
});
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN 可进入业务,其他角色 403未登录 401', async () => {
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN/DIRECTOR 可进入业务,其余角色 403未登录 401', async () => {
await assertRoleMatrix({
name: 'POST /b/organization/groups role matrix',
tokens: ctx.tokens,
expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 400,
[Role.HOSPITAL_ADMIN]: 400,
[Role.DIRECTOR]: 403,
[Role.DIRECTOR]: 400,
[Role.LEADER]: 403,
[Role.DOCTOR]: 403,
[Role.ENGINEER]: 403,
@ -558,15 +558,15 @@ describe('Organization Controllers (e2e)', () => {
expectErrorEnvelope(response, 401, '缺少 Bearer Token');
});
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN 可访问,其他角色 403未登录 401', async () => {
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN/DIRECTOR/LEADER 可访问,其余角色 403未登录 401', async () => {
await assertRoleMatrix({
name: 'GET /b/organization/groups role matrix',
tokens: ctx.tokens,
expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 200,
[Role.HOSPITAL_ADMIN]: 200,
[Role.DIRECTOR]: 403,
[Role.LEADER]: 403,
[Role.DIRECTOR]: 200,
[Role.LEADER]: 200,
[Role.DOCTOR]: 403,
[Role.ENGINEER]: 403,
},
@ -598,15 +598,15 @@ describe('Organization Controllers (e2e)', () => {
expectErrorEnvelope(response, 403, '院管仅可操作本院组织数据');
});
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN 可访问,其他角色 403未登录 401', async () => {
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN/DIRECTOR/LEADER 可访问,其余角色 403未登录 401', async () => {
await assertRoleMatrix({
name: 'GET /b/organization/groups/:id role matrix',
tokens: ctx.tokens,
expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 200,
[Role.HOSPITAL_ADMIN]: 200,
[Role.DIRECTOR]: 403,
[Role.LEADER]: 403,
[Role.DIRECTOR]: 200,
[Role.LEADER]: 200,
[Role.DOCTOR]: 403,
[Role.ENGINEER]: 403,
},
@ -650,15 +650,15 @@ describe('Organization Controllers (e2e)', () => {
expectErrorEnvelope(response, 403, '院管仅可操作本院组织数据');
});
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN 可进入业务,其他角色 403未登录 401', async () => {
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN/DIRECTOR/LEADER 可进入业务,其余角色 403未登录 401', async () => {
await assertRoleMatrix({
name: 'PATCH /b/organization/groups/:id role matrix',
tokens: ctx.tokens,
expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 404,
[Role.HOSPITAL_ADMIN]: 404,
[Role.DIRECTOR]: 403,
[Role.LEADER]: 403,
[Role.DIRECTOR]: 404,
[Role.LEADER]: 404,
[Role.DOCTOR]: 403,
[Role.ENGINEER]: 403,
},
@ -702,14 +702,22 @@ describe('Organization Controllers (e2e)', () => {
expectErrorEnvelope(response, 403, '院管仅可操作本院组织数据');
});
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN 可进入业务,其他角色 403未登录 401', async () => {
it('失败:删除有成员的小组返回 409', async () => {
const response = await request(ctx.app.getHttpServer())
.delete(`/b/organization/groups/${ctx.fixtures.groupA1Id}`)
.set('Authorization', `Bearer ${ctx.tokens[Role.SYSTEM_ADMIN]}`);
expectErrorEnvelope(response, 409, '小组下仍有成员,无法删除');
});
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN/DIRECTOR 可进入业务,其余角色 403未登录 401', async () => {
await assertRoleMatrix({
name: 'DELETE /b/organization/groups/:id role matrix',
tokens: ctx.tokens,
expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 404,
[Role.HOSPITAL_ADMIN]: 404,
[Role.DIRECTOR]: 403,
[Role.DIRECTOR]: 404,
[Role.LEADER]: 403,
[Role.DOCTOR]: 403,
[Role.ENGINEER]: 403,

View File

@ -146,17 +146,18 @@ describe('Patients Controllers (e2e)', () => {
});
describe('GET /c/patients/lifecycle', () => {
it('成功:可按 phone + idCardHash 查询跨院生命周期', async () => {
it('成功:已登录用户可按 phone + idCard 查询跨院生命周期', async () => {
const response = await request(ctx.app.getHttpServer())
.get('/c/patients/lifecycle')
.query({
phone: '13800002001',
idCardHash: 'seed-id-card-cross-hospital',
});
idCard: '110101199001010011',
})
.set('Authorization', `Bearer ${ctx.tokens[Role.DOCTOR]}`);
expectSuccessEnvelope(response, 200);
expect(response.body.data.phone).toBe('13800002001');
expect(response.body.data.idCardHash).toBe('seed-id-card-cross-hospital');
expect(response.body.data.idCard).toBe('110101199001010011');
expect(response.body.data.patientCount).toBeGreaterThanOrEqual(2);
expect(Array.isArray(response.body.data.lifecycle)).toBe(true);
});
@ -166,9 +167,10 @@ describe('Patients Controllers (e2e)', () => {
.get('/c/patients/lifecycle')
.query({
phone: '13800002001',
});
})
.set('Authorization', `Bearer ${ctx.tokens[Role.DOCTOR]}`);
expectErrorEnvelope(response, 400, 'idCardHash 必须是字符串');
expectErrorEnvelope(response, 400, 'idCard 必须是字符串');
});
it('失败:不存在患者返回 404', async () => {
@ -176,8 +178,9 @@ describe('Patients Controllers (e2e)', () => {
.get('/c/patients/lifecycle')
.query({
phone: '13800009999',
idCardHash: 'not-exists-idcard-hash',
});
idCard: '110101199009090099',
})
.set('Authorization', `Bearer ${ctx.tokens[Role.DOCTOR]}`);
expectErrorEnvelope(response, 404, '未找到匹配的患者档案');
});

View File

@ -74,15 +74,15 @@ describe('BTasksController (e2e)', () => {
expectErrorEnvelope(response, 404, '存在设备不在当前医院或设备不存在');
});
it('角色矩阵:仅 DOCTOR 可进入业务,其他角色 403未登录 401', async () => {
it('角色矩阵:DOCTOR/DIRECTOR/LEADER 可进入业务,其余角色 403未登录 401', async () => {
await assertRoleMatrix({
name: 'POST /b/tasks/publish role matrix',
tokens: ctx.tokens,
expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 403,
[Role.HOSPITAL_ADMIN]: 403,
[Role.DIRECTOR]: 403,
[Role.LEADER]: 403,
[Role.DIRECTOR]: 400,
[Role.LEADER]: 400,
[Role.DOCTOR]: 400,
[Role.ENGINEER]: 403,
},
@ -298,15 +298,15 @@ describe('BTasksController (e2e)', () => {
expectErrorEnvelope(cancelResponse, 409, '仅待接收/已接收任务可取消');
});
it('角色矩阵:仅 DOCTOR 可进入业务,其他角色 403未登录 401', async () => {
it('角色矩阵:DOCTOR/DIRECTOR/LEADER 可进入业务,其余角色 403未登录 401', async () => {
await assertRoleMatrix({
name: 'POST /b/tasks/cancel role matrix',
tokens: ctx.tokens,
expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 403,
[Role.HOSPITAL_ADMIN]: 403,
[Role.DIRECTOR]: 403,
[Role.LEADER]: 403,
[Role.DIRECTOR]: 404,
[Role.LEADER]: 404,
[Role.DOCTOR]: 404,
[Role.ENGINEER]: 403,
},

View File

@ -65,6 +65,10 @@ describe('UsersController + BUsersController (e2e)', () => {
await createDoctorUser(ctx.tokens[Role.SYSTEM_ADMIN]);
});
it('成功DIRECTOR 可创建本科室医生', async () => {
await createDoctorUser(ctx.tokens[Role.DIRECTOR]);
});
it('失败:参数校验失败返回 400', async () => {
const response = await request(ctx.app.getHttpServer())
.post('/users')
@ -82,14 +86,31 @@ describe('UsersController + BUsersController (e2e)', () => {
expectErrorEnvelope(response, 400, 'phone 必须是合法手机号');
});
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN 可进入业务,其他角色 403未登录 401', async () => {
it('失败DIRECTOR 创建非医生角色返回 403', async () => {
const response = await request(ctx.app.getHttpServer())
.post('/users')
.set('Authorization', `Bearer ${ctx.tokens[Role.DIRECTOR]}`)
.send({
name: uniqueSeedValue('主任创建组长'),
phone: uniquePhone(),
password: 'Seed@1234',
role: Role.LEADER,
hospitalId: ctx.fixtures.hospitalAId,
departmentId: ctx.fixtures.departmentA1Id,
groupId: ctx.fixtures.groupA1Id,
});
expectErrorEnvelope(response, 403, '当前角色无权限创建该用户');
});
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN/DIRECTOR 可进入业务,其他角色 403未登录 401', async () => {
await assertRoleMatrix({
name: 'POST /users role matrix',
tokens: ctx.tokens,
expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 400,
[Role.HOSPITAL_ADMIN]: 400,
[Role.DIRECTOR]: 403,
[Role.DIRECTOR]: 400,
[Role.LEADER]: 403,
[Role.DOCTOR]: 403,
[Role.ENGINEER]: 403,
@ -120,15 +141,15 @@ describe('UsersController + BUsersController (e2e)', () => {
expectErrorEnvelope(response, 401, '缺少 Bearer Token');
});
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN 可访问,其他角色 403未登录 401', async () => {
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN/DIRECTOR/LEADER 可访问,其余角色 403未登录 401', async () => {
await assertRoleMatrix({
name: 'GET /users role matrix',
tokens: ctx.tokens,
expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 200,
[Role.HOSPITAL_ADMIN]: 200,
[Role.DIRECTOR]: 403,
[Role.LEADER]: 403,
[Role.DIRECTOR]: 200,
[Role.LEADER]: 200,
[Role.DOCTOR]: 403,
[Role.ENGINEER]: 403,
},
@ -152,6 +173,15 @@ describe('UsersController + BUsersController (e2e)', () => {
expect(response.body.data.id).toBe(ctx.fixtures.users.doctorAId);
});
it('成功DIRECTOR 可查询本科室医生详情', async () => {
const response = await request(ctx.app.getHttpServer())
.get(`/users/${ctx.fixtures.users.doctorAId}`)
.set('Authorization', `Bearer ${ctx.tokens[Role.DIRECTOR]}`);
expectSuccessEnvelope(response, 200);
expect(response.body.data.id).toBe(ctx.fixtures.users.doctorAId);
});
it('失败:查询不存在用户返回 404', async () => {
const response = await request(ctx.app.getHttpServer())
.get('/users/99999999')
@ -160,14 +190,22 @@ describe('UsersController + BUsersController (e2e)', () => {
expectErrorEnvelope(response, 404, '用户不存在');
});
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN 可访问,其他角色 403未登录 401', async () => {
it('失败DIRECTOR 查询非本科室医生返回 403', async () => {
const response = await request(ctx.app.getHttpServer())
.get(`/users/${ctx.fixtures.users.doctorA3Id}`)
.set('Authorization', `Bearer ${ctx.tokens[Role.DIRECTOR]}`);
expectErrorEnvelope(response, 403, '科室主任仅可操作本科室医生账号');
});
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN/DIRECTOR 可访问,其他角色 403未登录 401', async () => {
await assertRoleMatrix({
name: 'GET /users/:id role matrix',
tokens: ctx.tokens,
expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 200,
[Role.HOSPITAL_ADMIN]: 200,
[Role.DIRECTOR]: 403,
[Role.DIRECTOR]: 200,
[Role.LEADER]: 403,
[Role.DOCTOR]: 403,
[Role.ENGINEER]: 403,
@ -198,6 +236,19 @@ describe('UsersController + BUsersController (e2e)', () => {
expect(response.body.data.name).toBe(nextName);
});
it('成功DIRECTOR 可更新本科室医生姓名', async () => {
const created = await createDoctorUser(ctx.tokens[Role.DIRECTOR]);
const nextName = uniqueSeedValue('主任更新医生名');
const response = await request(ctx.app.getHttpServer())
.patch(`/users/${created.id}`)
.set('Authorization', `Bearer ${ctx.tokens[Role.DIRECTOR]}`)
.send({ name: nextName });
expectSuccessEnvelope(response, 200);
expect(response.body.data.name).toBe(nextName);
});
it('失败:非医生调整科室/小组返回 400', async () => {
const response = await request(ctx.app.getHttpServer())
.patch(`/users/${ctx.fixtures.users.engineerAId}`)
@ -207,17 +258,39 @@ describe('UsersController + BUsersController (e2e)', () => {
groupId: ctx.fixtures.groupA1Id,
});
expectErrorEnvelope(response, 400, '仅医生/主任/组长允许调整科室/小组归属');
expectErrorEnvelope(
response,
400,
'仅医生/主任/组长允许调整科室/小组归属',
);
});
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN 可进入业务,其他角色 403未登录 401', async () => {
it('失败DIRECTOR 不能把医生改成其他角色', async () => {
const response = await request(ctx.app.getHttpServer())
.patch(`/users/${ctx.fixtures.users.doctorAId}`)
.set('Authorization', `Bearer ${ctx.tokens[Role.DIRECTOR]}`)
.send({ role: Role.LEADER });
expectErrorEnvelope(response, 403, '科室主任仅可操作本科室医生账号');
});
it('失败DIRECTOR 不能把医生调整到其他科室', async () => {
const response = await request(ctx.app.getHttpServer())
.patch(`/users/${ctx.fixtures.users.doctorAId}`)
.set('Authorization', `Bearer ${ctx.tokens[Role.DIRECTOR]}`)
.send({ departmentId: ctx.fixtures.departmentA2Id });
expectErrorEnvelope(response, 403, '科室主任仅可操作本科室医生账号');
});
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN/DIRECTOR 可进入业务,其他角色 403未登录 401', async () => {
await assertRoleMatrix({
name: 'PATCH /users/:id role matrix',
tokens: ctx.tokens,
expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 404,
[Role.HOSPITAL_ADMIN]: 404,
[Role.DIRECTOR]: 403,
[Role.DIRECTOR]: 404,
[Role.LEADER]: 403,
[Role.DOCTOR]: 403,
[Role.ENGINEER]: 403,
@ -246,6 +319,16 @@ describe('UsersController + BUsersController (e2e)', () => {
expect(response.body.data.id).toBe(created.id);
});
it('成功DIRECTOR 可删除本科室医生', async () => {
const created = await createDoctorUser(ctx.tokens[Role.DIRECTOR]);
const response = await request(ctx.app.getHttpServer())
.delete(`/users/${created.id}`)
.set('Authorization', `Bearer ${ctx.tokens[Role.DIRECTOR]}`);
expectSuccessEnvelope(response, 200);
expect(response.body.data.id).toBe(created.id);
});
it('失败:存在关联患者/任务时返回 409', async () => {
const response = await request(ctx.app.getHttpServer())
.delete(`/users/${ctx.fixtures.users.doctorAId}`)
@ -254,6 +337,14 @@ describe('UsersController + BUsersController (e2e)', () => {
expectErrorEnvelope(response, 409, '用户存在关联患者或任务,无法删除');
});
it('失败DIRECTOR 删除非本科室医生返回 403', async () => {
const response = await request(ctx.app.getHttpServer())
.delete(`/users/${ctx.fixtures.users.doctorA3Id}`)
.set('Authorization', `Bearer ${ctx.tokens[Role.DIRECTOR]}`);
expectErrorEnvelope(response, 403, '科室主任仅可操作本科室医生账号');
});
it('失败HOSPITAL_ADMIN 无法删除返回 403', async () => {
const response = await request(ctx.app.getHttpServer())
.delete(`/users/${ctx.fixtures.users.doctorAId}`)
@ -262,14 +353,14 @@ describe('UsersController + BUsersController (e2e)', () => {
expectErrorEnvelope(response, 403, '无权限执行当前操作');
});
it('角色矩阵:SYSTEM_ADMIN 可进入业务,其他角色 403未登录 401', async () => {
it('角色矩阵:SYSTEM_ADMIN/DIRECTOR 可进入业务,其他角色 403未登录 401', async () => {
await assertRoleMatrix({
name: 'DELETE /users/:id role matrix',
tokens: ctx.tokens,
expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 404,
[Role.HOSPITAL_ADMIN]: 403,
[Role.DIRECTOR]: 403,
[Role.DIRECTOR]: 404,
[Role.LEADER]: 403,
[Role.DOCTOR]: 403,
[Role.ENGINEER]: 403,

View File

@ -45,6 +45,7 @@ declare module 'vue' {
ElTimeline: typeof import('element-plus/es')['ElTimeline']
ElTimelineItem: typeof import('element-plus/es')['ElTimelineItem']
ElTree: typeof import('element-plus/es')['ElTree']
ElTreeSelect: typeof import('element-plus/es')['ElTreeSelect']
RouterLink: typeof import('vue-router')['RouterLink']
RouterView: typeof import('vue-router')['RouterView']
}

View File

@ -0,0 +1,24 @@
import request from './request';
/**
* 设备列表后端已支持服务端分页与筛选
*/
export const getDevices = (params) => {
return request.get('/b/devices', { params });
};
export const getDeviceById = (id) => {
return request.get(`/b/devices/${id}`);
};
export const createDevice = (data) => {
return request.post('/b/devices', data);
};
export const updateDevice = (id, data) => {
return request.patch(`/b/devices/${id}`, data);
};
export const deleteDevice = (id) => {
return request.delete(`/b/devices/${id}`);
};

View File

@ -4,11 +4,12 @@ import { useUserStore } from '../store/user';
import router from '../router';
const service = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL || '/api', // Use /api as default proxy prefix
// 开发环境默认走 Vite /api 代理,生产环境可用环境变量覆盖。
baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
timeout: 10000,
});
// Request Interceptor
// 请求拦截:统一挂载 Bearer Token避免各页面重复拼接鉴权头。
service.interceptors.request.use(
(config) => {
const userStore = useUserStore();
@ -19,19 +20,18 @@ service.interceptors.request.use(
},
(error) => {
return Promise.reject(error);
}
},
);
// Response Interceptor
// 响应拦截:对齐后端统一响应包裹 { code, msg, data }。
service.interceptors.response.use(
(response) => {
const res = response.data;
// Backend standard format: { code: number, msg: string, data: any }
// Accept code 0 or 2xx as success
// 后端成功响应统一为 code=0这里兼容少量 code=2xx 的历史结构。
if (res.code === 0 || (res.code >= 200 && res.code < 300)) {
return res.data;
} else {
// If backend returns code !== 0/2xx but HTTP status is 200
ElMessage.error(res.msg || '请求失败');
return Promise.reject(new Error(res.msg || 'Error'));
}
@ -39,28 +39,29 @@ service.interceptors.response.use(
(error) => {
const userStore = useUserStore();
let message = error.message;
if (error.response) {
const { status, data } = error.response;
// Backend error response format: { code: number, msg: string, data: null }
message = data?.msg || message;
if (status === 401) {
// Token expired or invalid
// 401 统一视为登录态失效,先清理本地态再跳登录页。
userStore.logout();
router.push(`/login?redirect=${encodeURIComponent(router.currentRoute.value.fullPath)}`);
router.push(
`/login?redirect=${encodeURIComponent(router.currentRoute.value.fullPath)}`,
);
ElMessage.error(message || '登录状态已过期,请重新登录');
return Promise.reject(new Error('Unauthorized'));
} else if (status === 403) {
ElMessage.error(message || '没有权限执行该操作');
} else {
ElMessage.error(message || '请求失败');
ElMessage.error(message || '请求失败');
}
} else {
ElMessage.error(message || '网络连接异常');
}
return Promise.reject(error);
}
},
);
export default service;

View File

@ -8,20 +8,29 @@ const ORG_MANAGER_ROLES = Object.freeze([
'DIRECTOR',
'LEADER',
]);
const USER_MANAGER_ROLES = Object.freeze([
'SYSTEM_ADMIN',
'HOSPITAL_ADMIN',
'DIRECTOR',
]);
const TASK_ROLES = Object.freeze(['DOCTOR', 'DIRECTOR', 'LEADER', 'ENGINEER']);
const PATIENT_ROLES = Object.freeze([
'SYSTEM_ADMIN',
'HOSPITAL_ADMIN',
'DIRECTOR',
'LEADER',
// 后端患者接口允许医生访问,页面侧也应放开,避免前端先把医生拦掉。
'DOCTOR',
]);
export const ROLE_PERMISSIONS = Object.freeze({
ORG_TREE: ORG_MANAGER_ROLES,
ORG_HOSPITALS: Object.freeze(['SYSTEM_ADMIN']),
ORG_DEPARTMENTS: ORG_MANAGER_ROLES,
// 主任/组长仍可通过接口读取科室信息,但不再开放独立“科室管理”页面。
ORG_DEPARTMENTS: ADMIN_ROLES,
ORG_GROUPS: ORG_MANAGER_ROLES,
USERS: ADMIN_ROLES,
USERS: USER_MANAGER_ROLES,
DEVICES: ADMIN_ROLES,
TASKS: TASK_ROLES,
PATIENTS: PATIENT_ROLES,
});

View File

@ -14,7 +14,7 @@
<el-icon><DataLine /></el-icon>
<span>首页</span>
</el-menu-item>
<template v-if="userStore.role === 'SYSTEM_ADMIN'">
<el-sub-menu index="/organization">
<template #title>
@ -22,8 +22,12 @@
<span>组织架构</span>
</template>
<el-menu-item index="/organization/tree">结构图视图</el-menu-item>
<el-menu-item index="/organization/hospitals">医院管理</el-menu-item>
<el-menu-item index="/organization/departments">科室管理</el-menu-item>
<el-menu-item index="/organization/hospitals"
>医院管理</el-menu-item
>
<el-menu-item index="/organization/departments"
>科室管理</el-menu-item
>
<el-menu-item index="/organization/groups">小组管理</el-menu-item>
</el-sub-menu>
</template>
@ -32,7 +36,7 @@
<el-icon><Share /></el-icon>
<span>组织架构图</span>
</el-menu-item>
<el-menu-item index="/organization/departments">
<el-menu-item v-if="canAccessDepartments" index="/organization/departments">
<el-icon><OfficeBuilding /></el-icon>
<span>科室管理</span>
</el-menu-item>
@ -44,7 +48,12 @@
<el-menu-item v-if="canAccessUsers" index="/users">
<el-icon><User /></el-icon>
<span>用户管理</span>
<span>{{ usersMenuLabel }}</span>
</el-menu-item>
<el-menu-item v-if="canAccessDevices" index="/devices">
<el-icon><Monitor /></el-icon>
<span>设备管理</span>
</el-menu-item>
<el-menu-item v-if="canAccessTasks" index="/tasks">
@ -58,11 +67,11 @@
</el-menu-item>
</el-menu>
</el-aside>
<el-container>
<el-header class="header">
<div class="header-left">
<!-- Breadcrumbs can go here -->
<!-- Breadcrumbs can go here -->
</div>
<div class="header-right">
<el-dropdown @command="handleCommand">
@ -80,7 +89,7 @@
</el-dropdown>
</div>
</el-header>
<el-main class="main">
<router-view v-slot="{ Component }">
<transition name="fade-transform" mode="out-in">
@ -100,7 +109,17 @@ import {
ROLE_PERMISSIONS,
hasRolePermission,
} from '../constants/role-permissions';
import { DataLine, OfficeBuilding, User, List, Avatar, ArrowDown, Connection, Share } from '@element-plus/icons-vue';
import {
DataLine,
OfficeBuilding,
User,
List,
Avatar,
ArrowDown,
Connection,
Share,
Monitor,
} from '@element-plus/icons-vue';
const route = useRoute();
const router = useRouter();
@ -110,18 +129,28 @@ const activeMenu = computed(() => {
return route.path;
});
const isDirector = computed(() => userStore.role === 'DIRECTOR');
const canAccessUsers = computed(() =>
hasRolePermission(userStore.role, ROLE_PERMISSIONS.USERS),
);
const canAccessDevices = computed(() =>
hasRolePermission(userStore.role, ROLE_PERMISSIONS.DEVICES),
);
const canAccessOrgTree = computed(() =>
hasRolePermission(userStore.role, ROLE_PERMISSIONS.ORG_TREE),
);
const canAccessDepartments = computed(() =>
hasRolePermission(userStore.role, ROLE_PERMISSIONS.ORG_DEPARTMENTS),
);
const canAccessTasks = computed(() =>
hasRolePermission(userStore.role, ROLE_PERMISSIONS.TASKS),
);
const canAccessPatients = computed(() =>
hasRolePermission(userStore.role, ROLE_PERMISSIONS.PATIENTS),
);
const usersMenuLabel = computed(() =>
isDirector.value ? '医生管理' : '用户管理',
);
const handleCommand = (command) => {
if (command === 'logout') {
@ -174,7 +203,7 @@ const handleCommand = (command) => {
/* fade-transform transition */
.fade-transform-leave-active,
.fade-transform-enter-active {
transition: all .3s;
transition: all 0.3s;
}
.fade-transform-enter-from {
opacity: 0;

View File

@ -77,6 +77,16 @@ const routes = [
allowedRoles: ROLE_PERMISSIONS.USERS,
},
},
{
path: 'devices',
name: 'Devices',
component: () => import('../views/devices/Devices.vue'),
meta: {
title: '设备管理',
requiresAuth: true,
allowedRoles: ROLE_PERMISSIONS.DEVICES,
},
},
{
path: 'tasks',
name: 'Tasks',
@ -96,7 +106,7 @@ const routes = [
requiresAuth: true,
allowedRoles: ROLE_PERMISSIONS.PATIENTS,
},
}
},
],
},
{

View File

@ -5,17 +5,13 @@
<p>当前角色{{ userStore.role || '未登录' }}</p>
</el-card>
<el-card
v-if="isSystemAdmin"
shadow="never"
class="filter-card"
>
<el-card v-if="isSystemAdmin" shadow="never" class="filter-card">
<el-form inline>
<el-form-item label="患者统计医院">
<el-select
v-model="selectedHospitalId"
placeholder="请选择医院"
style="width: 280px;"
style="width: 280px"
@change="fetchDashboardData"
>
<el-option
@ -30,7 +26,13 @@
</el-card>
<el-row :gutter="16" v-loading="loading">
<el-col :xs="24" :sm="12" :lg="6" v-for="item in statCards" :key="item.key">
<el-col
:xs="24"
:sm="12"
:lg="6"
v-for="item in statCards"
:key="item.key"
>
<el-card shadow="hover" class="stat-card">
<div class="stat-title">{{ item.title }}</div>
<div class="stat-value">{{ item.value }}</div>
@ -75,19 +77,44 @@ const isSystemAdmin = computed(() => userStore.role === 'SYSTEM_ADMIN');
const canViewOrg = computed(() =>
['SYSTEM_ADMIN', 'HOSPITAL_ADMIN'].includes(userStore.role),
);
const canViewUsers = computed(() =>
['SYSTEM_ADMIN', 'HOSPITAL_ADMIN', 'DIRECTOR'].includes(userStore.role),
);
const canViewPatients = computed(() =>
['SYSTEM_ADMIN', 'HOSPITAL_ADMIN', 'DIRECTOR', 'LEADER', 'DOCTOR'].includes(
userStore.role,
),
);
const statCards = computed(() => [
{ key: 'hospitals', title: '医院总数', value: stats.value.hospitals },
{ key: 'departments', title: '科室总数', value: stats.value.departments },
{ key: 'groups', title: '小组总数', value: stats.value.groups },
{ key: 'users', title: '用户总数', value: stats.value.users },
{ key: 'patients', title: '可见患者数', value: stats.value.patients },
]);
const statCards = computed(() => {
const cards = [];
if (canViewOrg.value) {
cards.push(
{ key: 'hospitals', title: '医院总数', value: stats.value.hospitals },
{ key: 'departments', title: '科室总数', value: stats.value.departments },
{ key: 'groups', title: '小组总数', value: stats.value.groups },
);
}
if (canViewUsers.value) {
cards.push({
key: 'users',
title: userStore.role === 'DIRECTOR' ? '本科室医生数' : '用户总数',
value: stats.value.users,
});
}
if (canViewPatients.value) {
cards.push({
key: 'patients',
title: '可见患者数',
value: stats.value.patients,
});
}
return cards;
});
const fetchHospitalsForFilter = async () => {
if (!isSystemAdmin.value) {
@ -104,16 +131,23 @@ const fetchDashboardData = async () => {
loading.value = true;
try {
if (canViewOrg.value) {
const [hospitalRes, departmentRes, groupRes, usersRes] = await Promise.all([
const [hospitalRes, departmentRes, groupRes] = await Promise.all([
getHospitals({ page: 1, pageSize: 1 }),
getDepartments({ page: 1, pageSize: 1 }),
getGroups({ page: 1, pageSize: 1 }),
getUsers({ page: 1, pageSize: 1 }),
]);
stats.value.hospitals = hospitalRes.total ?? 0;
stats.value.departments = departmentRes.total ?? 0;
stats.value.groups = groupRes.total ?? 0;
}
if (canViewUsers.value) {
const usersRes = await getUsers({
page: 1,
pageSize: 1,
role: userStore.role === 'DIRECTOR' ? 'DOCTOR' : undefined,
});
stats.value.users = usersRes.total ?? 0;
}
@ -126,7 +160,9 @@ const fetchDashboardData = async () => {
stats.value.patients = 0;
} else {
const patientRes = await getPatients(params);
stats.value.patients = Array.isArray(patientRes) ? patientRes.length : 0;
stats.value.patients = Array.isArray(patientRes)
? patientRes.length
: 0;
}
}
} finally {

View File

@ -4,19 +4,38 @@
<template #header>
<h2 class="login-title">调压通管理后台</h2>
</template>
<el-form :model="loginForm" :rules="rules" ref="loginFormRef" @keyup.enter="handleLogin">
<el-form
:model="loginForm"
:rules="rules"
ref="loginFormRef"
@keyup.enter="handleLogin"
>
<el-form-item prop="phone">
<el-input v-model="loginForm.phone" placeholder="请输入手机号" :prefix-icon="User" />
<el-input
v-model="loginForm.phone"
placeholder="请输入手机号"
:prefix-icon="User"
/>
</el-form-item>
<el-form-item prop="password">
<el-input v-model="loginForm.password" type="password" placeholder="请输入密码" show-password :prefix-icon="Lock" />
<el-input
v-model="loginForm.password"
type="password"
placeholder="请输入密码"
show-password
:prefix-icon="Lock"
/>
</el-form-item>
<el-form-item prop="role">
<el-select v-model="loginForm.role" placeholder="请选择登录角色" style="width: 100%;">
<el-select
v-model="loginForm.role"
placeholder="请选择登录角色"
style="width: 100%"
>
<el-option label="系统管理员" value="SYSTEM_ADMIN" />
<el-option label="医院管理员" value="HOSPITAL_ADMIN" />
<el-option label="科室主任" value="DIRECTOR" />
<el-option label="医疗组长" value="LEADER" />
<el-option label="小组组长" value="LEADER" />
<el-option label="医生" value="DOCTOR" />
<el-option label="工程师" value="ENGINEER" />
</el-select>
@ -27,17 +46,23 @@
:min="1"
:controls="false"
placeholder="医院 ID多账号场景建议填写"
style="width: 100%;"
style="width: 100%"
/>
</el-form-item>
<el-alert
type="info"
:closable="false"
title="若同一手机号在多个医院有同角色账号,请填写医院 ID。"
style="margin-bottom: 16px;"
style="margin-bottom: 16px"
/>
<el-form-item>
<el-button type="primary" class="login-btn" :loading="loading" @click="handleLogin">登录</el-button>
<el-button
type="primary"
class="login-btn"
:loading="loading"
@click="handleLogin"
>登录</el-button
>
</el-form-item>
</el-form>
</el-card>
@ -68,13 +93,13 @@ const loginForm = reactive({
const rules = {
phone: [
{ required: true, message: '请输入手机号', trigger: 'blur' },
{ pattern: /^1\d{10}$/, message: '请输入正确的手机号', trigger: 'blur' }
{ pattern: /^1\d{10}$/, message: '请输入正确的手机号', trigger: 'blur' },
],
password: [
{ required: true, message: '请输入密码', trigger: 'blur' },
{ min: 8, message: '密码长度至少为 8 位', trigger: 'blur' }
{ min: 8, message: '密码长度至少为 8 位', trigger: 'blur' },
],
role: [{ required: true, message: '请选择角色', trigger: 'change' }]
role: [{ required: true, message: '请选择角色', trigger: 'change' }],
};
const handleLogin = async () => {

View File

@ -0,0 +1,531 @@
<template>
<div class="devices-container">
<el-card>
<div class="header-actions">
<el-form :inline="true" :model="searchForm" class="search-form">
<el-form-item label="所属医院" v-if="isSystemAdmin">
<el-select
v-model="searchForm.hospitalId"
clearable
filterable
placeholder="全部医院"
style="width: 220px"
@change="handleSearchHospitalChange"
>
<el-option
v-for="hospital in hospitals"
:key="hospital.id"
:label="hospital.name"
:value="hospital.id"
/>
</el-select>
</el-form-item>
<el-form-item label="归属患者">
<el-select
v-model="searchForm.patientId"
clearable
filterable
placeholder="全部患者"
style="width: 260px"
:disabled="isSystemAdmin && !searchForm.hospitalId"
>
<el-option
v-for="patient in searchPatients"
:key="patient.id"
:label="formatPatientLabel(patient)"
:value="patient.id"
/>
</el-select>
</el-form-item>
<el-form-item label="设备状态">
<el-select
v-model="searchForm.status"
clearable
placeholder="全部状态"
style="width: 160px"
>
<el-option
v-for="item in DEVICE_STATUS_OPTIONS"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
</el-form-item>
<el-form-item label="关键词">
<el-input
v-model="searchForm.keyword"
clearable
placeholder="设备 SN / 患者姓名 / 手机号"
style="width: 260px"
/>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="handleSearch" icon="Search">
查询
</el-button>
<el-button @click="resetSearch" icon="Refresh">重置</el-button>
<el-button type="success" @click="openCreateDialog" icon="Plus">
新增设备
</el-button>
</el-form-item>
</el-form>
</div>
<el-table
:data="tableData"
v-loading="loading"
border
stripe
style="width: 100%"
>
<el-table-column prop="id" label="ID" width="80" align="center" />
<el-table-column prop="snCode" label="设备 SN" min-width="180" />
<el-table-column
prop="currentPressure"
label="当前压力"
width="120"
align="center"
/>
<el-table-column label="设备状态" width="120" align="center">
<template #default="{ row }">
<el-tag :type="getStatusTagType(row.status)">
{{ getStatusName(row.status) }}
</el-tag>
</template>
</el-table-column>
<el-table-column label="归属患者" min-width="140">
<template #default="{ row }">
{{ row.patient?.name || '-' }}
</template>
</el-table-column>
<el-table-column label="患者手机号" min-width="150">
<template #default="{ row }">
{{ row.patient?.phone || '-' }}
</template>
</el-table-column>
<el-table-column label="所属医院" min-width="160">
<template #default="{ row }">
{{ row.patient?.hospital?.name || '-' }}
</template>
</el-table-column>
<el-table-column label="归属医生" min-width="140">
<template #default="{ row }">
{{ row.patient?.doctor?.name || '-' }}
</template>
</el-table-column>
<el-table-column label="关联任务数" width="120" align="center">
<template #default="{ row }">
{{ row._count?.taskItems ?? 0 }}
</template>
</el-table-column>
<el-table-column label="操作" width="180" fixed="right" align="center">
<template #default="{ row }">
<el-button size="small" type="primary" @click="openEditDialog(row)">
编辑
</el-button>
<el-button size="small" type="danger" @click="handleDelete(row)">
删除
</el-button>
</template>
</el-table-column>
</el-table>
<div class="pagination-container">
<el-pagination
v-model:current-page="page"
v-model:page-size="pageSize"
:page-sizes="[10, 20, 50, 100]"
:total="total"
background
layout="total, sizes, prev, pager, next, jumper"
@size-change="fetchData"
@current-change="fetchData"
/>
</div>
</el-card>
<el-dialog
:title="isEdit ? '编辑设备' : '新增设备'"
v-model="dialogVisible"
width="560px"
@close="resetForm"
>
<el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
<el-form-item label="所属医院" prop="hospitalId" v-if="isSystemAdmin">
<el-select
v-model="form.hospitalId"
filterable
placeholder="请选择医院"
style="width: 100%"
@change="handleFormHospitalChange"
>
<el-option
v-for="hospital in hospitals"
:key="hospital.id"
:label="hospital.name"
:value="hospital.id"
/>
</el-select>
</el-form-item>
<el-form-item label="归属患者" prop="patientId">
<el-select
v-model="form.patientId"
filterable
placeholder="请选择患者"
style="width: 100%"
:disabled="isSystemAdmin && !form.hospitalId"
>
<el-option
v-for="patient in formPatients"
:key="patient.id"
:label="formatPatientLabel(patient)"
:value="patient.id"
/>
</el-select>
</el-form-item>
<el-form-item label="设备 SN" prop="snCode">
<el-input
v-model="form.snCode"
placeholder="请输入设备 SN"
maxlength="64"
/>
</el-form-item>
<el-form-item label="当前压力" prop="currentPressure">
<el-input-number
v-model="form.currentPressure"
:min="0"
:step="1"
:controls="false"
style="width: 100%"
/>
</el-form-item>
<el-form-item label="设备状态" prop="status">
<el-select
v-model="form.status"
placeholder="请选择状态"
style="width: 100%"
>
<el-option
v-for="item in DEVICE_STATUS_OPTIONS"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
</el-form-item>
</el-form>
<template #footer>
<div class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button
type="primary"
:loading="submitLoading"
@click="handleSubmit"
>
确定
</el-button>
</div>
</template>
</el-dialog>
</div>
</template>
<script setup>
import { computed, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
getDevices,
createDevice,
updateDevice,
deleteDevice,
} from '../../api/devices';
import { getHospitals } from '../../api/organization';
import { getPatients } from '../../api/patients';
import { useUserStore } from '../../store/user';
const userStore = useUserStore();
const DEVICE_STATUS_OPTIONS = [
{ label: '启用', value: 'ACTIVE' },
{ label: '停用', value: 'INACTIVE' },
];
const isSystemAdmin = computed(() => userStore.role === 'SYSTEM_ADMIN');
const loading = ref(false);
const submitLoading = ref(false);
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref(null);
const currentId = ref(null);
const hospitals = ref([]);
const searchPatients = ref([]);
const formPatients = ref([]);
const tableData = ref([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const searchForm = reactive({
hospitalId: null,
patientId: null,
status: '',
keyword: '',
});
const form = reactive({
hospitalId: null,
patientId: null,
snCode: '',
currentPressure: 0,
status: 'ACTIVE',
});
const rules = computed(() => ({
hospitalId: isSystemAdmin.value
? [{ required: true, message: '请选择所属医院', trigger: 'change' }]
: [],
patientId: [{ required: true, message: '请选择归属患者', trigger: 'change' }],
snCode: [{ required: true, message: '请输入设备 SN', trigger: 'blur' }],
currentPressure: [
{ required: true, message: '请输入当前压力', trigger: 'blur' },
],
status: [{ required: true, message: '请选择设备状态', trigger: 'change' }],
}));
const getStatusName = (status) => {
return (
DEVICE_STATUS_OPTIONS.find((item) => item.value === status)?.label || status
);
};
const getStatusTagType = (status) => {
return status === 'ACTIVE' ? 'success' : 'info';
};
const formatPatientLabel = (patient) => {
const hospitalName = patient.hospital?.name
? ` / ${patient.hospital.name}`
: '';
return `${patient.name}${patient.phone}${hospitalName}`;
};
const fetchHospitals = async () => {
if (!isSystemAdmin.value) {
return;
}
const res = await getHospitals({ page: 1, pageSize: 100 });
hospitals.value = res.list || [];
};
//
const fetchSearchPatients = async () => {
if (isSystemAdmin.value && !searchForm.hospitalId) {
searchPatients.value = [];
searchForm.patientId = null;
return;
}
const params = {};
if (isSystemAdmin.value) {
params.hospitalId = searchForm.hospitalId;
}
const res = await getPatients(params);
searchPatients.value = Array.isArray(res) ? res : [];
if (!searchPatients.value.some((item) => item.id === searchForm.patientId)) {
searchForm.patientId = null;
}
};
// patientId
const fetchFormPatients = async (hospitalId = form.hospitalId) => {
if (isSystemAdmin.value && !hospitalId) {
formPatients.value = [];
form.patientId = null;
return;
}
const params = {};
if (isSystemAdmin.value) {
params.hospitalId = hospitalId;
}
const res = await getPatients(params);
formPatients.value = Array.isArray(res) ? res : [];
if (!formPatients.value.some((item) => item.id === form.patientId)) {
form.patientId = null;
}
};
const fetchData = async () => {
loading.value = true;
try {
const params = {
page: page.value,
pageSize: pageSize.value,
keyword: searchForm.keyword || undefined,
status: searchForm.status || undefined,
patientId: searchForm.patientId || undefined,
};
if (isSystemAdmin.value && searchForm.hospitalId) {
params.hospitalId = searchForm.hospitalId;
}
const res = await getDevices(params);
tableData.value = res.list || [];
total.value = res.total || 0;
} finally {
loading.value = false;
}
};
const handleSearchHospitalChange = async () => {
page.value = 1;
await fetchSearchPatients();
await fetchData();
};
const handleFormHospitalChange = async (hospitalId) => {
form.patientId = null;
await fetchFormPatients(hospitalId);
};
const handleSearch = () => {
page.value = 1;
fetchData();
};
const resetSearch = async () => {
searchForm.hospitalId = null;
searchForm.patientId = null;
searchForm.status = '';
searchForm.keyword = '';
page.value = 1;
await fetchSearchPatients();
await fetchData();
};
const resetForm = () => {
formRef.value?.resetFields();
form.hospitalId = null;
form.patientId = null;
form.snCode = '';
form.currentPressure = 0;
form.status = 'ACTIVE';
currentId.value = null;
formPatients.value = [];
};
const openCreateDialog = async () => {
isEdit.value = false;
resetForm();
// 沿
if (isSystemAdmin.value) {
form.hospitalId = searchForm.hospitalId || null;
} else {
form.hospitalId = userStore.userInfo?.hospitalId || null;
}
await fetchFormPatients(form.hospitalId);
dialogVisible.value = true;
};
const openEditDialog = async (row) => {
isEdit.value = true;
currentId.value = row.id;
form.snCode = row.snCode;
form.currentPressure = row.currentPressure;
form.status = row.status;
form.hospitalId =
row.patient?.hospital?.id || row.patient?.hospitalId || null;
await fetchFormPatients(form.hospitalId);
form.patientId = row.patient?.id || null;
dialogVisible.value = true;
};
const handleSubmit = async () => {
if (!formRef.value) return;
await formRef.value.validate(async (valid) => {
if (!valid) return;
submitLoading.value = true;
try {
const payload = {
snCode: form.snCode,
currentPressure: Number(form.currentPressure),
status: form.status,
patientId: form.patientId,
};
if (isEdit.value) {
await updateDevice(currentId.value, payload);
ElMessage.success('更新成功');
} else {
await createDevice(payload);
ElMessage.success('创建成功');
}
dialogVisible.value = false;
await fetchData();
} finally {
submitLoading.value = false;
}
});
};
const handleDelete = (row) => {
ElMessageBox.confirm(`确定要删除设备 "${row.snCode}" 吗?`, '警告', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
})
.then(async () => {
await deleteDevice(row.id);
ElMessage.success('删除成功');
await fetchData();
})
.catch(() => {});
};
onMounted(async () => {
await fetchHospitals();
await fetchSearchPatients();
await fetchData();
});
</script>
<style scoped>
.devices-container {
padding: 0;
}
.header-actions {
margin-bottom: 20px;
}
.pagination-container {
margin-top: 20px;
display: flex;
justify-content: flex-end;
}
</style>

View File

@ -3,16 +3,35 @@
<el-card>
<template #header>
<div class="card-header">
<span>科室管理 {{ currentHospitalName ? `(${currentHospitalName})` : '' }}</span>
<el-button v-if="currentHospitalName" @click="clearHospitalFilter" type="info" size="small">清除医院筛选</el-button>
<span
>科室管理
{{ currentHospitalName ? `(${currentHospitalName})` : '' }}</span
>
<el-button
v-if="currentHospitalName"
@click="clearHospitalFilter"
type="info"
size="small"
>清除医院筛选</el-button
>
</div>
</template>
<!-- Header / Actions -->
<div class="header-actions">
<el-form :inline="true" :model="searchForm" class="search-form">
<el-form-item label="所属医院" v-if="userStore.role === 'SYSTEM_ADMIN' && !currentHospitalIdFromQuery">
<el-select v-model="searchForm.hospitalId" placeholder="请选择医院" clearable @change="fetchData">
<el-form-item
label="所属医院"
v-if="
userStore.role === 'SYSTEM_ADMIN' && !currentHospitalIdFromQuery
"
>
<el-select
v-model="searchForm.hospitalId"
placeholder="请选择医院"
clearable
@change="fetchData"
>
<el-option
v-for="h in hospitals"
:key="h.id"
@ -22,21 +41,44 @@
</el-select>
</el-form-item>
<el-form-item label="科室名称">
<el-input v-model="searchForm.keyword" placeholder="请输入关键词" clearable />
<el-input
v-model="searchForm.keyword"
placeholder="请输入关键词"
clearable
/>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="fetchData" icon="Search">查询</el-button>
<el-button type="primary" @click="fetchData" icon="Search"
>查询</el-button
>
<el-button @click="resetSearch" icon="Refresh">重置</el-button>
<el-button v-if="canCreateDepartment" type="success" @click="openCreateDialog" icon="Plus">新增科室</el-button>
<el-button
v-if="canCreateDepartment"
type="success"
@click="openCreateDialog"
icon="Plus"
>新增科室</el-button
>
</el-form-item>
</el-form>
</div>
<!-- Table -->
<el-table :data="tableData" v-loading="loading" border stripe style="width: 100%">
<el-table
:data="tableData"
v-loading="loading"
border
stripe
style="width: 100%"
>
<el-table-column prop="id" label="ID" width="80" align="center" />
<el-table-column prop="name" label="科室名称" min-width="150" />
<el-table-column prop="hospital.name" label="所属医院" min-width="200" v-if="userStore.role === 'SYSTEM_ADMIN'" />
<el-table-column
prop="hospital.name"
label="所属医院"
min-width="200"
v-if="userStore.role === 'SYSTEM_ADMIN'"
/>
<el-table-column label="科室主任" min-width="180">
<template #default="{ row }">
{{ getDirectorDisplay(row.id) }}
@ -49,9 +91,23 @@
</el-table-column>
<el-table-column label="操作" width="220" fixed="right" align="center">
<template #default="{ row }">
<el-button size="small" @click="goToGroups(row)">管理小组</el-button>
<el-button v-if="canEditDepartment" size="small" type="primary" @click="openEditDialog(row)">编辑</el-button>
<el-button v-if="canDeleteDepartment" size="small" type="danger" @click="handleDelete(row)">删除</el-button>
<el-button size="small" @click="goToGroups(row)"
>管理小组</el-button
>
<el-button
v-if="canEditDepartment"
size="small"
type="primary"
@click="openEditDialog(row)"
>编辑</el-button
>
<el-button
v-if="canDeleteDepartment"
size="small"
type="danger"
@click="handleDelete(row)"
>删除</el-button
>
</template>
</el-table-column>
</el-table>
@ -72,10 +128,24 @@
</el-card>
<!-- Dialog for Create / Edit -->
<el-dialog :title="isEdit ? '编辑科室' : '新增科室'" v-model="dialogVisible" width="500px" @close="resetForm">
<el-dialog
:title="isEdit ? '编辑科室' : '新增科室'"
v-model="dialogVisible"
width="500px"
@close="resetForm"
>
<el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
<el-form-item label="所属医院" prop="hospitalId" v-if="userStore.role === 'SYSTEM_ADMIN'">
<el-select v-model="form.hospitalId" placeholder="请选择所属医院" style="width: 100%;">
<el-form-item
label="所属医院"
prop="hospitalId"
v-if="userStore.role === 'SYSTEM_ADMIN'"
>
<el-select
v-model="form.hospitalId"
placeholder="请选择所属医院"
style="width: 100%"
@change="handleFormHospitalChange"
>
<el-option
v-for="h in hospitals"
:key="h.id"
@ -87,11 +157,32 @@
<el-form-item label="科室名称" prop="name">
<el-input v-model="form.name" placeholder="请输入科室名称" />
</el-form-item>
<el-form-item label="科室主任" v-if="canAssignDirectorInDialog">
<el-select
v-model="form.directorUserId"
placeholder="可选:选择后将任命为科室主任"
clearable
filterable
style="width: 100%"
>
<el-option
v-for="user in directorOptions"
:key="user.id"
:label="`${user.name}${user.phone} / ${getRoleName(user.role)}`"
:value="user.id"
/>
</el-select>
</el-form-item>
</el-form>
<template #footer>
<div class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
<el-button
type="primary"
@click="handleSubmit"
:loading="submitLoading"
>确定</el-button
>
</div>
</template>
</el-dialog>
@ -102,8 +193,14 @@
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getDepartments, createDepartment, updateDepartment, deleteDepartment, getHospitals } from '../../api/organization';
import { getUsers } from '../../api/users';
import {
getDepartments,
createDepartment,
updateDepartment,
deleteDepartment,
getHospitals,
} from '../../api/organization';
import { getUsers, updateUser } from '../../api/users';
import { useUserStore } from '../../store/user';
const route = useRoute();
@ -118,6 +215,15 @@ const page = ref(1);
const pageSize = ref(10);
const hospitals = ref([]);
const directorNameMap = ref({});
const directorOptions = ref([]);
const roleMap = {
DIRECTOR: '科室主任',
LEADER: '小组组长',
DOCTOR: '医生',
};
const getRoleName = (role) => roleMap[role] || role;
const currentHospitalIdFromQuery = computed(() => {
return route.query.hospitalId ? parseInt(route.query.hospitalId) : null;
@ -129,7 +235,7 @@ const currentHospitalName = computed(() => {
const searchForm = reactive({
keyword: '',
hospitalId: null
hospitalId: null,
});
// Dialog State
@ -141,22 +247,31 @@ const currentId = ref(null);
const form = reactive({
hospitalId: null,
name: ''
name: '',
directorUserId: null,
});
const rules = computed(() => ({
hospitalId: userStore.role === 'SYSTEM_ADMIN' ? [{ required: true, message: '请选择所属医院', trigger: 'change' }] : [],
name: [{ required: true, message: '请输入科室名称', trigger: 'blur' }]
hospitalId:
userStore.role === 'SYSTEM_ADMIN'
? [{ required: true, message: '请选择所属医院', trigger: 'change' }]
: [],
name: [{ required: true, message: '请输入科室名称', trigger: 'blur' }],
}));
const canCreateDepartment = computed(() =>
['SYSTEM_ADMIN', 'HOSPITAL_ADMIN'].includes(userStore.role),
);
const canEditDepartment = computed(() =>
['SYSTEM_ADMIN', 'HOSPITAL_ADMIN', 'DIRECTOR', 'LEADER'].includes(userStore.role),
['SYSTEM_ADMIN', 'HOSPITAL_ADMIN', 'DIRECTOR', 'LEADER'].includes(
userStore.role,
),
);
const canDeleteDepartment = computed(() =>
['SYSTEM_ADMIN', 'HOSPITAL_ADMIN'].includes(userStore.role),
);
const canAssignDirectorInDialog = computed(() =>
['SYSTEM_ADMIN', 'HOSPITAL_ADMIN'].includes(userStore.role),
);
// --- Methods ---
const fetchHospitals = async () => {
@ -171,7 +286,8 @@ const fetchHospitals = async () => {
const fetchData = async () => {
loading.value = true;
try {
const activeHospitalId = currentHospitalIdFromQuery.value || searchForm.hospitalId;
const activeHospitalId =
currentHospitalIdFromQuery.value || searchForm.hospitalId;
const [departmentRes, directorRes] = await Promise.all([
getDepartments({
page: page.value,
@ -224,18 +340,23 @@ const clearHospitalFilter = () => {
const goToGroups = (row) => {
router.push({
path: '/organization/groups',
query: {
departmentId: row.id,
query: {
departmentId: row.id,
departmentName: row.name,
hospitalId: row.hospitalId
}
hospitalId: row.hospitalId,
},
});
};
const openCreateDialog = () => {
isEdit.value = false;
currentId.value = null;
form.hospitalId = userStore.role === 'SYSTEM_ADMIN' ? (currentHospitalIdFromQuery.value || searchForm.hospitalId || null) : userStore.userInfo?.hospitalId;
form.hospitalId =
userStore.role === 'SYSTEM_ADMIN'
? currentHospitalIdFromQuery.value || searchForm.hospitalId || null
: userStore.userInfo?.hospitalId;
form.directorUserId = null;
loadDirectorOptions(form.hospitalId);
dialogVisible.value = true;
};
@ -244,6 +365,8 @@ const openEditDialog = (row) => {
currentId.value = row.id;
form.name = row.name;
form.hospitalId = row.hospitalId;
form.directorUserId = null;
loadDirectorOptions(row.hospitalId, row.id);
dialogVisible.value = true;
};
@ -253,6 +376,34 @@ const resetForm = () => {
}
form.name = '';
form.hospitalId = null;
form.directorUserId = null;
};
const handleFormHospitalChange = (hospitalId) => {
form.directorUserId = null;
loadDirectorOptions(hospitalId);
};
const loadDirectorOptions = async (hospitalId, departmentId) => {
if (!canAssignDirectorInDialog.value || !hospitalId) {
directorOptions.value = [];
return;
}
const userRes = await getUsers();
const users = Array.isArray(userRes?.list) ? userRes.list : [];
directorOptions.value = users.filter((user) => {
if (user.role !== 'DIRECTOR') {
return false;
}
if (user.hospitalId !== hospitalId) {
return false;
}
if (departmentId == null) {
return true;
}
return user.departmentId == null || user.departmentId === departmentId;
});
};
const handleSubmit = async () => {
@ -261,14 +412,41 @@ const handleSubmit = async () => {
if (valid) {
submitLoading.value = true;
try {
let targetDepartmentId = null;
let targetHospitalId = form.hospitalId;
if (isEdit.value) {
// Some backend update APIs don't allow changing hospitalId, but we'll send it if needed, or just name
await updateDepartment(currentId.value, { name: form.name });
const updated = await updateDepartment(currentId.value, {
name: form.name,
});
targetDepartmentId = updated?.id ?? currentId.value;
targetHospitalId = updated?.hospitalId ?? form.hospitalId;
ElMessage.success('更新成功');
} else {
await createDepartment(form);
const created = await createDepartment({
hospitalId: form.hospitalId,
name: form.name,
});
targetDepartmentId = created?.id;
targetHospitalId = created?.hospitalId ?? form.hospitalId;
ElMessage.success('创建成功');
}
if (
canAssignDirectorInDialog.value &&
form.directorUserId &&
targetDepartmentId &&
targetHospitalId
) {
await updateUser(form.directorUserId, {
role: 'DIRECTOR',
hospitalId: targetHospitalId,
departmentId: targetDepartmentId,
groupId: null,
});
ElMessage.success('科室主任已设置');
}
dialogVisible.value = false;
fetchData();
} catch (error) {
@ -281,23 +459,21 @@ const handleSubmit = async () => {
};
const handleDelete = (row) => {
ElMessageBox.confirm(
`确定要删除科室 "${row.name}" 吗?`,
'警告',
{
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
}
).then(async () => {
try {
await deleteDepartment(row.id);
ElMessage.success('删除成功');
fetchData();
} catch (error) {
console.error('Delete failed', error);
}
}).catch(() => {});
ElMessageBox.confirm(`确定要删除科室 "${row.name}" 吗?`, '警告', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
})
.then(async () => {
try {
await deleteDepartment(row.id);
ElMessage.success('删除成功');
fetchData();
} catch (error) {
console.error('Delete failed', error);
}
})
.catch(() => {});
};
// --- Lifecycle ---
@ -313,7 +489,7 @@ watch(
() => {
page.value = 1;
fetchData();
}
},
);
</script>

View File

@ -3,16 +3,37 @@
<el-card>
<template #header>
<div class="card-header">
<span>小组管理 {{ currentDepartmentName ? `(${currentDepartmentName})` : '' }}</span>
<el-button v-if="currentDepartmentIdFromQuery" @click="clearDepartmentFilter" type="info" size="small">清除科室筛选</el-button>
<span
>小组管理
{{
currentDepartmentName ? `(${currentDepartmentName})` : ''
}}</span
>
<el-button
v-if="currentDepartmentIdFromQuery"
@click="clearDepartmentFilter"
type="info"
size="small"
>清除科室筛选</el-button
>
</div>
</template>
<!-- Header / Actions -->
<div class="header-actions">
<el-form :inline="true" :model="searchForm" class="search-form">
<el-form-item label="所属医院" v-if="userStore.role === 'SYSTEM_ADMIN' && !currentDepartmentIdFromQuery">
<el-select v-model="searchForm.hospitalId" placeholder="请选择医院" clearable @change="handleSearchHospitalChange">
<el-form-item
label="所属医院"
v-if="
userStore.role === 'SYSTEM_ADMIN' && !currentDepartmentIdFromQuery
"
>
<el-select
v-model="searchForm.hospitalId"
placeholder="请选择医院"
clearable
@change="handleSearchHospitalChange"
>
<el-option
v-for="h in hospitals"
:key="h.id"
@ -22,7 +43,15 @@
</el-select>
</el-form-item>
<el-form-item label="所属科室" v-if="!currentDepartmentIdFromQuery">
<el-select v-model="searchForm.departmentId" placeholder="请选择科室" clearable @change="fetchData" :disabled="userStore.role === 'SYSTEM_ADMIN' && !searchForm.hospitalId">
<el-select
v-model="searchForm.departmentId"
placeholder="请选择科室"
clearable
@change="fetchData"
:disabled="
userStore.role === 'SYSTEM_ADMIN' && !searchForm.hospitalId
"
>
<el-option
v-for="d in searchDepartments"
:key="d.id"
@ -32,22 +61,49 @@
</el-select>
</el-form-item>
<el-form-item label="小组名称">
<el-input v-model="searchForm.keyword" placeholder="请输入关键词" clearable />
<el-input
v-model="searchForm.keyword"
placeholder="请输入关键词"
clearable
/>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="fetchData" icon="Search">查询</el-button>
<el-button type="primary" @click="fetchData" icon="Search"
>查询</el-button
>
<el-button @click="resetSearch" icon="Refresh">重置</el-button>
<el-button v-if="canCreateGroup" type="success" @click="openCreateDialog" icon="Plus">新增小组</el-button>
<el-button
v-if="canCreateGroup"
type="success"
@click="openCreateDialog"
icon="Plus"
>新增小组</el-button
>
</el-form-item>
</el-form>
</div>
<!-- Table -->
<el-table :data="tableData" v-loading="loading" border stripe style="width: 100%">
<el-table
:data="tableData"
v-loading="loading"
border
stripe
style="width: 100%"
>
<el-table-column prop="id" label="ID" width="80" align="center" />
<el-table-column prop="name" label="小组名称" min-width="150" />
<el-table-column prop="department.name" label="所属科室" min-width="150" />
<el-table-column prop="department.hospital.name" label="所属医院" min-width="150" v-if="userStore.role === 'SYSTEM_ADMIN'" />
<el-table-column
prop="department.name"
label="所属科室"
min-width="150"
/>
<el-table-column
prop="department.hospital.name"
label="所属医院"
min-width="150"
v-if="userStore.role === 'SYSTEM_ADMIN'"
/>
<el-table-column label="小组组长" min-width="180">
<template #default="{ row }">
{{ getLeaderDisplay(row.id) }}
@ -60,8 +116,20 @@
</el-table-column>
<el-table-column label="操作" width="180" fixed="right" align="center">
<template #default="{ row }">
<el-button v-if="canEditGroup" size="small" type="primary" @click="openEditDialog(row)">编辑</el-button>
<el-button v-if="canDeleteGroup" size="small" type="danger" @click="handleDelete(row)">删除</el-button>
<el-button
v-if="canEditGroup"
size="small"
type="primary"
@click="openEditDialog(row)"
>编辑</el-button
>
<el-button
v-if="canDeleteGroup"
size="small"
type="danger"
@click="handleDelete(row)"
>删除</el-button
>
</template>
</el-table-column>
</el-table>
@ -82,10 +150,24 @@
</el-card>
<!-- Dialog for Create / Edit -->
<el-dialog :title="isEdit ? '编辑小组' : '新增小组'" v-model="dialogVisible" width="500px" @close="resetForm">
<el-dialog
:title="isEdit ? '编辑小组' : '新增小组'"
v-model="dialogVisible"
width="500px"
@close="resetForm"
>
<el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
<el-form-item label="所属医院" prop="hospitalId" v-if="userStore.role === 'SYSTEM_ADMIN'">
<el-select v-model="form.hospitalId" placeholder="请选择所属医院" style="width: 100%;" @change="handleFormHospitalChange">
<el-form-item
label="所属医院"
prop="hospitalId"
v-if="userStore.role === 'SYSTEM_ADMIN'"
>
<el-select
v-model="form.hospitalId"
placeholder="请选择所属医院"
style="width: 100%"
@change="handleFormHospitalChange"
>
<el-option
v-for="h in hospitals"
:key="h.id"
@ -95,7 +177,12 @@
</el-select>
</el-form-item>
<el-form-item label="所属科室" prop="departmentId">
<el-select v-model="form.departmentId" placeholder="请选择所属科室" style="width: 100%;" :disabled="userStore.role === 'SYSTEM_ADMIN' && !form.hospitalId">
<el-select
v-model="form.departmentId"
placeholder="请选择所属科室"
style="width: 100%"
:disabled="userStore.role === 'SYSTEM_ADMIN' && !form.hospitalId"
>
<el-option
v-for="d in formDepartments"
:key="d.id"
@ -107,11 +194,32 @@
<el-form-item label="小组名称" prop="name">
<el-input v-model="form.name" placeholder="请输入小组名称" />
</el-form-item>
<el-form-item label="小组组长" v-if="canAssignLeaderInDialog">
<el-select
v-model="form.leaderUserId"
placeholder="可选:选择后将任命为小组组长"
clearable
filterable
style="width: 100%"
>
<el-option
v-for="user in leaderOptions"
:key="user.id"
:label="`${user.name}${user.phone} / ${getRoleName(user.role)}`"
:value="user.id"
/>
</el-select>
</el-form-item>
</el-form>
<template #footer>
<div class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
<el-button
type="primary"
@click="handleSubmit"
:loading="submitLoading"
>确定</el-button
>
</div>
</template>
</el-dialog>
@ -122,8 +230,15 @@
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getGroups, createGroup, updateGroup, deleteGroup, getHospitals, getDepartments } from '../../api/organization';
import { getUsers } from '../../api/users';
import {
getGroups,
createGroup,
updateGroup,
deleteGroup,
getHospitals,
getDepartments,
} from '../../api/organization';
import { getUsers, updateUser } from '../../api/users';
import { useUserStore } from '../../store/user';
const route = useRoute();
@ -138,6 +253,14 @@ const page = ref(1);
const pageSize = ref(10);
const hospitals = ref([]);
const leaderNameMap = ref({});
const leaderOptions = ref([]);
const roleMap = {
LEADER: '小组组长',
DOCTOR: '医生',
};
const getRoleName = (role) => roleMap[role] || role;
const searchDepartments = ref([]);
const formDepartments = ref([]);
@ -157,7 +280,7 @@ const currentDepartmentName = computed(() => {
const searchForm = reactive({
keyword: '',
hospitalId: null,
departmentId: null
departmentId: null,
});
// Dialog State
@ -170,23 +293,34 @@ const currentId = ref(null);
const form = reactive({
hospitalId: null,
departmentId: null,
name: ''
name: '',
leaderUserId: null,
});
const rules = computed(() => ({
hospitalId: userStore.role === 'SYSTEM_ADMIN' ? [{ required: true, message: '请选择所属医院', trigger: 'change' }] : [],
departmentId: [{ required: true, message: '请选择所属科室', trigger: 'change' }],
name: [{ required: true, message: '请输入小组名称', trigger: 'blur' }]
hospitalId:
userStore.role === 'SYSTEM_ADMIN'
? [{ required: true, message: '请选择所属医院', trigger: 'change' }]
: [],
departmentId: [
{ required: true, message: '请选择所属科室', trigger: 'change' },
],
name: [{ required: true, message: '请输入小组名称', trigger: 'blur' }],
}));
const canCreateGroup = computed(() =>
['SYSTEM_ADMIN', 'HOSPITAL_ADMIN', 'DIRECTOR'].includes(userStore.role),
);
const canEditGroup = computed(() =>
['SYSTEM_ADMIN', 'HOSPITAL_ADMIN', 'DIRECTOR', 'LEADER'].includes(userStore.role),
['SYSTEM_ADMIN', 'HOSPITAL_ADMIN', 'DIRECTOR', 'LEADER'].includes(
userStore.role,
),
);
const canDeleteGroup = computed(() =>
['SYSTEM_ADMIN', 'HOSPITAL_ADMIN', 'DIRECTOR'].includes(userStore.role),
);
const canAssignLeaderInDialog = computed(() =>
['SYSTEM_ADMIN', 'HOSPITAL_ADMIN'].includes(userStore.role),
);
// --- Methods ---
const fetchHospitals = async () => {
@ -212,6 +346,7 @@ const handleSearchHospitalChange = async (hospitalId) => {
const handleFormHospitalChange = async (hospitalId) => {
form.departmentId = null;
form.leaderUserId = null;
formDepartments.value = [];
if (hospitalId) {
try {
@ -221,11 +356,35 @@ const handleFormHospitalChange = async (hospitalId) => {
}
};
const loadLeaderOptions = async (hospitalId, departmentId, groupId) => {
if (!canAssignLeaderInDialog.value || !hospitalId || !departmentId) {
leaderOptions.value = [];
return;
}
const userRes = await getUsers();
const users = Array.isArray(userRes?.list) ? userRes.list : [];
leaderOptions.value = users.filter((user) => {
if (user.role !== 'LEADER') {
return false;
}
if (user.hospitalId !== hospitalId || user.departmentId !== departmentId) {
return false;
}
if (groupId == null) {
return true;
}
return user.groupId == null || user.groupId === groupId;
});
};
const fetchData = async () => {
loading.value = true;
try {
const activeDepartmentId = currentDepartmentIdFromQuery.value || searchForm.departmentId;
const activeHospitalId = currentHospitalIdFromQuery.value || searchForm.hospitalId;
const activeDepartmentId =
currentDepartmentIdFromQuery.value || searchForm.departmentId;
const activeHospitalId =
currentHospitalIdFromQuery.value || searchForm.hospitalId;
const [groupRes, leaderRes] = await Promise.all([
getGroups({
page: page.value,
@ -281,11 +440,17 @@ const clearDepartmentFilter = () => {
const openCreateDialog = async () => {
isEdit.value = false;
currentId.value = null;
form.hospitalId = userStore.role === 'SYSTEM_ADMIN' ? (currentHospitalIdFromQuery.value || searchForm.hospitalId || null) : userStore.userInfo?.hospitalId;
form.hospitalId =
userStore.role === 'SYSTEM_ADMIN'
? currentHospitalIdFromQuery.value || searchForm.hospitalId || null
: userStore.userInfo?.hospitalId;
if (userStore.role === 'SYSTEM_ADMIN' && form.hospitalId) {
await handleFormHospitalChange(form.hospitalId);
}
form.departmentId = currentDepartmentIdFromQuery.value || searchForm.departmentId || null;
form.departmentId =
currentDepartmentIdFromQuery.value || searchForm.departmentId || null;
form.leaderUserId = null;
await loadLeaderOptions(form.hospitalId, form.departmentId, null);
dialogVisible.value = true;
};
@ -293,17 +458,19 @@ const openEditDialog = async (row) => {
isEdit.value = true;
currentId.value = row.id;
form.name = row.name;
// Try to find the hospital ID from the nested relation, assuming row.department.hospitalId exists
// if not, we can rely on row.department?.hospital?.id
const hospitalId = row.department?.hospitalId || row.department?.hospital?.id;
form.hospitalId = hospitalId;
if (hospitalId) {
await handleFormHospitalChange(hospitalId);
}
form.departmentId = row.departmentId;
form.leaderUserId = null;
await loadLeaderOptions(form.hospitalId, form.departmentId, row.id);
dialogVisible.value = true;
};
@ -314,7 +481,9 @@ const resetForm = () => {
form.name = '';
form.hospitalId = null;
form.departmentId = null;
form.leaderUserId = null;
formDepartments.value = [];
leaderOptions.value = [];
};
const handleSubmit = async () => {
@ -323,14 +492,44 @@ const handleSubmit = async () => {
if (valid) {
submitLoading.value = true;
try {
let targetGroupId = null;
let targetDepartmentId = form.departmentId;
let targetHospitalId = form.hospitalId;
if (isEdit.value) {
// Backend patch dto might just accept name. Sending departmentId may not be allowed or needed.
await updateGroup(currentId.value, { name: form.name });
const updated = await updateGroup(currentId.value, {
name: form.name,
});
targetGroupId = updated?.id ?? currentId.value;
targetDepartmentId = updated?.departmentId ?? form.departmentId;
targetHospitalId = updated?.department?.hospitalId ?? form.hospitalId;
ElMessage.success('更新成功');
} else {
await createGroup({ name: form.name, departmentId: form.departmentId });
const created = await createGroup({
name: form.name,
departmentId: form.departmentId,
});
targetGroupId = created?.id;
targetDepartmentId = created?.departmentId ?? form.departmentId;
ElMessage.success('创建成功');
}
if (
canAssignLeaderInDialog.value &&
form.leaderUserId &&
targetGroupId &&
targetDepartmentId &&
targetHospitalId
) {
await updateUser(form.leaderUserId, {
role: 'LEADER',
hospitalId: targetHospitalId,
departmentId: targetDepartmentId,
groupId: targetGroupId,
});
ElMessage.success('小组组长已设置');
}
dialogVisible.value = false;
fetchData();
} catch (error) {
@ -343,23 +542,21 @@ const handleSubmit = async () => {
};
const handleDelete = (row) => {
ElMessageBox.confirm(
`确定要删除小组 "${row.name}" 吗?`,
'警告',
{
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
}
).then(async () => {
try {
await deleteGroup(row.id);
ElMessage.success('删除成功');
fetchData();
} catch (error) {
console.error('Delete failed', error);
}
}).catch(() => {});
ElMessageBox.confirm(`确定要删除小组 "${row.name}" 吗?`, '警告', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
})
.then(async () => {
try {
await deleteGroup(row.id);
ElMessage.success('删除成功');
fetchData();
} catch (error) {
console.error('Delete failed', error);
}
})
.catch(() => {});
};
// --- Lifecycle ---
@ -382,7 +579,21 @@ watch(
() => {
page.value = 1;
fetchData();
}
},
);
watch(
() => [form.hospitalId, form.departmentId],
async ([hospitalId, departmentId]) => {
if (!dialogVisible.value) {
return;
}
await loadLeaderOptions(
hospitalId,
departmentId,
isEdit.value ? currentId.value : null,
);
},
);
</script>

View File

@ -5,20 +5,43 @@
<div class="header-actions">
<el-form :inline="true" :model="searchForm" class="search-form">
<el-form-item label="医院名称">
<el-input v-model="searchForm.keyword" placeholder="请输入关键词" clearable />
<el-input
v-model="searchForm.keyword"
placeholder="请输入关键词"
clearable
/>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="fetchData" icon="Search">查询</el-button>
<el-button type="primary" @click="fetchData" icon="Search"
>查询</el-button
>
<el-button @click="resetSearch" icon="Refresh">重置</el-button>
<el-button v-if="userStore.role === 'SYSTEM_ADMIN'" type="success" @click="openCreateDialog" icon="Plus">新增医院</el-button>
<el-button
v-if="userStore.role === 'SYSTEM_ADMIN'"
type="success"
@click="openCreateDialog"
icon="Plus"
>新增医院</el-button
>
</el-form-item>
</el-form>
</div>
<!-- Table -->
<el-table :data="tableData" v-loading="loading" border stripe style="width: 100%">
<el-table
:data="tableData"
v-loading="loading"
border
stripe
style="width: 100%"
>
<el-table-column prop="id" label="ID" width="80" align="center" />
<el-table-column prop="name" label="医院名称" min-width="200" />
<el-table-column prop="adminDisplay" label="医院管理员" min-width="220">
<template #default="{ row }">
{{ row.adminDisplay || '未设置' }}
</template>
</el-table-column>
<el-table-column prop="createdAt" label="创建时间" width="180">
<template #default="{ row }">
{{ new Date(row.createdAt).toLocaleString() }}
@ -26,9 +49,19 @@
</el-table-column>
<el-table-column label="操作" width="250" fixed="right" align="center">
<template #default="{ row }">
<el-button size="small" @click="goToDepartments(row)">管理科室</el-button>
<el-button size="small" type="primary" @click="openEditDialog(row)">编辑</el-button>
<el-button v-if="userStore.role === 'SYSTEM_ADMIN'" size="small" type="danger" @click="handleDelete(row)">删除</el-button>
<el-button size="small" @click="goToDepartments(row)"
>管理科室</el-button
>
<el-button size="small" type="primary" @click="openEditDialog(row)"
>编辑</el-button
>
<el-button
v-if="userStore.role === 'SYSTEM_ADMIN'"
size="small"
type="danger"
@click="handleDelete(row)"
>删除</el-button
>
</template>
</el-table-column>
</el-table>
@ -49,16 +82,45 @@
</el-card>
<!-- Dialog for Create / Edit -->
<el-dialog :title="isEdit ? '编辑医院' : '新增医院'" v-model="dialogVisible" width="500px" @close="resetForm">
<el-dialog
:title="isEdit ? '编辑医院' : '新增医院'"
v-model="dialogVisible"
width="500px"
@close="resetForm"
>
<el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
<el-form-item label="医院名称" prop="name">
<el-input v-model="form.name" placeholder="请输入医院名称" />
</el-form-item>
<el-form-item
label="医院管理员"
v-if="userStore.role === 'SYSTEM_ADMIN'"
>
<el-select
v-model="form.adminUserId"
placeholder="可选:选择后将任命为医院管理员"
clearable
filterable
style="width: 100%"
>
<el-option
v-for="user in hospitalAdminOptions"
:key="user.id"
:label="`${user.name}${user.phone} / ${getRoleName(user.role)}`"
:value="user.id"
/>
</el-select>
</el-form-item>
</el-form>
<template #footer>
<div class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
<el-button
type="primary"
@click="handleSubmit"
:loading="submitLoading"
>确定</el-button
>
</div>
</template>
</el-dialog>
@ -69,7 +131,13 @@
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getHospitals, createHospital, updateHospital, deleteHospital } from '../../api/organization';
import {
getHospitals,
createHospital,
updateHospital,
deleteHospital,
} from '../../api/organization';
import { getUsers, updateUser } from '../../api/users';
import { useUserStore } from '../../store/user';
const router = useRouter();
@ -81,9 +149,21 @@ const tableData = ref([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const hospitalAdminOptions = ref([]);
const roleMap = {
SYSTEM_ADMIN: '系统管理员',
HOSPITAL_ADMIN: '医院管理员',
DIRECTOR: '科室主任',
LEADER: '小组组长',
DOCTOR: '医生',
ENGINEER: '工程师',
};
const getRoleName = (role) => roleMap[role] || role;
const searchForm = reactive({
keyword: ''
keyword: '',
});
// Dialog State
@ -94,11 +174,12 @@ const formRef = ref(null);
const currentId = ref(null);
const form = reactive({
name: ''
name: '',
adminUserId: null,
});
const rules = {
name: [{ required: true, message: '请输入医院名称', trigger: 'blur' }]
name: [{ required: true, message: '请输入医院名称', trigger: 'blur' }],
};
// --- Methods ---
@ -108,9 +189,32 @@ const fetchData = async () => {
const res = await getHospitals({
page: page.value,
pageSize: pageSize.value,
keyword: searchForm.keyword || undefined
keyword: searchForm.keyword || undefined,
});
tableData.value = res.list || [];
let hospitalAdminNameMap = {};
try {
const userRes = await getUsers();
const users = Array.isArray(userRes?.list) ? userRes.list : [];
hospitalAdminNameMap = users.reduce((acc, user) => {
if (user.role !== 'HOSPITAL_ADMIN' || !user.hospitalId) {
return acc;
}
if (!acc[user.hospitalId]) {
acc[user.hospitalId] = [];
}
acc[user.hospitalId].push(user.name || '-');
return acc;
}, {});
} catch (error) {
console.error('Failed to fetch hospital admins', error);
}
tableData.value = (res.list || []).map((hospital) => ({
...hospital,
adminDisplay:
(hospitalAdminNameMap[hospital.id] || []).join('、') || '未设置',
}));
total.value = res.total || 0;
} catch (error) {
console.error('Failed to fetch hospitals', error);
@ -128,6 +232,7 @@ const resetSearch = () => {
const openCreateDialog = () => {
isEdit.value = false;
currentId.value = null;
loadHospitalAdminOptions();
dialogVisible.value = true;
};
@ -135,6 +240,7 @@ const openEditDialog = (row) => {
isEdit.value = true;
currentId.value = row.id;
form.name = row.name;
loadHospitalAdminOptions(row.id);
dialogVisible.value = true;
};
@ -143,6 +249,27 @@ const resetForm = () => {
formRef.value.resetFields();
}
form.name = '';
form.adminUserId = null;
};
const loadHospitalAdminOptions = async (hospitalId) => {
if (userStore.role !== 'SYSTEM_ADMIN') {
hospitalAdminOptions.value = [];
return;
}
const userRes = await getUsers();
const users = Array.isArray(userRes?.list) ? userRes.list : [];
hospitalAdminOptions.value = users.filter((user) => {
//
if (user.role !== 'HOSPITAL_ADMIN') {
return false;
}
if (!hospitalId) {
return true;
}
return user.hospitalId == null || user.hospitalId === hospitalId;
});
};
const handleSubmit = async () => {
@ -151,13 +278,37 @@ const handleSubmit = async () => {
if (valid) {
submitLoading.value = true;
try {
let targetHospitalId = null;
if (isEdit.value) {
await updateHospital(currentId.value, form);
const updated = await updateHospital(currentId.value, {
name: form.name,
});
targetHospitalId = updated?.id ?? currentId.value;
ElMessage.success('更新成功');
} else {
await createHospital(form);
const created = await createHospital({ name: form.name });
targetHospitalId = created?.id;
ElMessage.success('创建成功');
}
if (form.adminUserId && targetHospitalId) {
const selectedAdmin = hospitalAdminOptions.value.find(
(user) => user.id === form.adminUserId,
);
if (!selectedAdmin || selectedAdmin.role !== 'HOSPITAL_ADMIN') {
ElMessage.error('仅可选择医院管理员角色人员');
return;
}
await updateUser(form.adminUserId, {
role: 'HOSPITAL_ADMIN',
hospitalId: targetHospitalId,
departmentId: null,
groupId: null,
});
ElMessage.success('医院管理员已设置');
}
dialogVisible.value = false;
fetchData();
} catch (error) {
@ -170,29 +321,27 @@ const handleSubmit = async () => {
};
const handleDelete = (row) => {
ElMessageBox.confirm(
`确定要删除医院 "${row.name}" 吗?`,
'警告',
{
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
}
).then(async () => {
try {
await deleteHospital(row.id);
ElMessage.success('删除成功');
fetchData();
} catch (error) {
console.error('Delete failed', error);
}
}).catch(() => {});
ElMessageBox.confirm(`确定要删除医院 "${row.name}" 吗?`, '警告', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
})
.then(async () => {
try {
await deleteHospital(row.id);
ElMessage.success('删除成功');
fetchData();
} catch (error) {
console.error('Delete failed', error);
}
})
.catch(() => {});
};
const goToDepartments = (row) => {
router.push({
path: '/organization/departments',
query: { hospitalId: row.id, hospitalName: row.name }
query: { hospitalId: row.id, hospitalName: row.name },
});
};

View File

@ -6,8 +6,17 @@
<el-card shadow="never" class="tree-card">
<template #header>
<div class="card-header">
<span class="header-title"><el-icon><Connection /></el-icon> 组织架构全景图</span>
<el-button type="primary" @click="fetchTreeData" icon="Refresh" round size="small">刷新</el-button>
<span class="header-title"
><el-icon><Connection /></el-icon> 组织架构全景图</span
>
<el-button
type="primary"
@click="fetchTreeData"
icon="Refresh"
round
size="small"
>刷新</el-button
>
</div>
</template>
@ -26,35 +35,58 @@
<div class="custom-tree-node" :class="`node-${data.type}`">
<div class="node-main">
<div class="node-icon-wrapper">
<el-icon v-if="data.type === 'hospital'"><OfficeBuilding /></el-icon>
<el-icon v-else-if="data.type === 'department'"><Filter /></el-icon>
<el-icon v-else-if="data.type === 'group'"><Connection /></el-icon>
<el-icon v-else-if="data.type === 'user'"><UserFilled /></el-icon>
<el-icon v-if="data.type === 'hospital'"
><OfficeBuilding
/></el-icon>
<el-icon v-else-if="data.type === 'department'"
><Filter
/></el-icon>
<el-icon v-else-if="data.type === 'group'"
><Connection
/></el-icon>
<el-icon v-else-if="data.type === 'user'"
><UserFilled
/></el-icon>
</div>
<div class="node-text">
<span class="node-label">{{ node.label }}</span>
<span v-if="data.type === 'department'" class="node-sub-label">
<span
v-if="data.type === 'hospital'"
class="node-sub-label"
>
医院管理员{{ data.adminDisplay || '未设置' }}
</span>
<span
v-else-if="data.type === 'department'"
class="node-sub-label"
>
主任{{ data.directorDisplay || '未设置' }}
</span>
<span v-else-if="data.type === 'group'" class="node-sub-label">
<span
v-else-if="data.type === 'group'"
class="node-sub-label"
>
组长{{ data.leaderDisplay || '未设置' }}
</span>
</div>
<el-tag
v-if="data.type === 'user'"
size="small"
:type="getRoleTagType(data.role)"
effect="light"
<el-tag
v-if="data.type === 'user'"
size="small"
:type="getRoleTagType(data.role)"
effect="light"
class="role-tag"
round
>
{{ getRoleName(data.role) }}
</el-tag>
</div>
<div class="node-actions" v-if="data.type !== 'user'">
<el-button
v-if="canAssignOwner && (data.type === 'department' || data.type === 'group')"
v-if="
canAssignOwner &&
(data.type === 'department' || data.type === 'group')
"
type="warning"
link
size="small"
@ -62,17 +94,34 @@
>
{{ data.type === 'department' ? '设主任' : '设组长' }}
</el-button>
<el-button v-if="canEditNode(data)" type="info" link size="small" @click.stop="openEditDialog(data)" icon="EditPen">
<el-button
v-if="canEditNode(data)"
type="info"
link
size="small"
@click.stop="openEditDialog(data)"
icon="EditPen"
>
编辑
</el-button>
<el-button v-if="canDeleteNode(data)" type="danger" link size="small" @click.stop="handleDelete(data)" icon="Delete">
<el-button
v-if="canDeleteNode(data)"
type="danger"
link
size="small"
@click.stop="handleDelete(data)"
icon="Delete"
>
删除
</el-button>
</div>
</div>
</template>
</el-tree>
<el-empty v-if="!loading && treeData.length === 0" description="暂无组织架构数据" />
<el-empty
v-if="!loading && treeData.length === 0"
description="暂无组织架构数据"
/>
</div>
</el-card>
</el-col>
@ -83,50 +132,62 @@
<template #header>
<div class="card-header">
<span class="header-title">
<el-icon><Menu /></el-icon>
<el-icon><Menu /></el-icon>
{{ activePanelTitle }}
</span>
<div v-if="activeNode && activeNode.type !== 'user'" class="header-actions">
<el-button
v-if="canCreateDepartment(activeNode)"
type="primary"
<div
v-if="activeNode && activeNode.type !== 'user'"
class="header-actions"
>
<el-button
v-if="canCreateDepartment(activeNode)"
type="primary"
size="small"
icon="Plus"
icon="Plus"
@click="openCreateDialog('department', activeNode.id)"
>
新增科室
</el-button>
<el-button
v-if="canCreateGroup(activeNode)"
type="success"
<el-button
v-if="canCreateGroup(activeNode)"
type="success"
size="small"
icon="Plus"
icon="Plus"
@click="openCreateDialog('group', activeNode.id)"
>
新增小组
</el-button>
<el-button
v-if="canAddUser(activeNode)"
type="warning"
<el-button
v-if="canAddUser(activeNode)"
type="warning"
size="small"
icon="User"
icon="User"
@click="goToAddUser(activeNode)"
>
新增人员
</el-button>
<el-button
v-if="canAssignOwner && (activeNode.type === 'department' || activeNode.type === 'group')"
v-if="
canAssignOwner &&
(activeNode.type === 'department' ||
activeNode.type === 'group')
"
type="primary"
size="small"
@click="openSetOwnerDialog(activeNode)"
>
{{ activeNode.type === 'department' ? '设置主任' : '设置组长' }}
{{
activeNode.type === 'department' ? '设置主任' : '设置组长'
}}
</el-button>
</div>
</div>
</template>
<div v-if="activeNode && activeNode.type !== 'user'" class="node-detail-panel">
<div
v-if="activeNode && activeNode.type !== 'user'"
class="node-detail-panel"
>
<el-alert
v-if="activeNodeMeta"
:title="activeNodeMeta"
@ -134,30 +195,55 @@
:closable="false"
class="mb-12"
/>
<el-table :data="activeNodeChildren" border stripe style="width: 100%" max-height="600">
<el-table
:data="activeNodeChildren"
border
stripe
style="width: 100%"
max-height="600"
>
<el-table-column prop="name" label="名称" />
<el-table-column label="类型" width="100" align="center">
<template #default="{ row }">
<el-tag size="small" :type="getNodeTypeTag(row.type)">{{ getTypeName(row.type) }}</el-tag>
<el-tag size="small" :type="getNodeTypeTag(row.type)">{{
getTypeName(row.type)
}}</el-tag>
</template>
</el-table-column>
<el-table-column label="负责人" width="180" align="center">
<template #default="{ row }">
<span v-if="row.type === 'department'">主任{{ row.directorDisplay || '未设置' }}</span>
<span v-else-if="row.type === 'group'">组长{{ row.leaderDisplay || '未设置' }}</span>
<span v-if="row.type === 'hospital'"
>医院管理员{{ row.adminDisplay || '未设置' }}</span
>
<span v-else-if="row.type === 'department'"
>主任{{ row.directorDisplay || '未设置' }}</span
>
<span v-else-if="row.type === 'group'"
>组长{{ row.leaderDisplay || '未设置' }}</span
>
<span v-else>-</span>
</template>
</el-table-column>
<el-table-column label="角色" width="120" align="center">
<template #default="{ row }">
<span v-if="row.type === 'user'">{{ getRoleName(row.role) }}</span>
<span v-if="row.type === 'user'">{{
getRoleName(row.role)
}}</span>
<span v-else>-</span>
</template>
</el-table-column>
<el-table-column label="操作" width="220" align="center" fixed="right">
<el-table-column
label="操作"
width="220"
align="center"
fixed="right"
>
<template #default="{ row }">
<el-button
v-if="canAssignOwner && (row.type === 'department' || row.type === 'group')"
v-if="
canAssignOwner &&
(row.type === 'department' || row.type === 'group')
"
type="warning"
link
size="small"
@ -165,21 +251,47 @@
>
{{ row.type === 'department' ? '设主任' : '设组长' }}
</el-button>
<el-button v-if="canEditNode(row)" type="primary" link size="small" @click="openEditDialog(row)">编辑</el-button>
<el-button v-if="canDeleteNode(row)" type="danger" link size="small" @click="handleDelete(row)">删除</el-button>
<el-button
v-if="canEditNode(row)"
type="primary"
link
size="small"
@click="openEditDialog(row)"
>编辑</el-button
>
<el-button
v-if="canDeleteNode(row)"
type="danger"
link
size="small"
@click="handleDelete(row)"
>删除</el-button
>
</template>
</el-table-column>
</el-table>
</div>
<div v-else-if="selectedUserDetail" class="user-detail-panel">
<el-descriptions :column="2" border>
<el-descriptions-item label="姓名">{{ selectedUserDetail.name || '-' }}</el-descriptions-item>
<el-descriptions-item label="角色">{{ getRoleName(selectedUserDetail.role) }}</el-descriptions-item>
<el-descriptions-item label="手机号">{{ selectedUserDetail.phone || '-' }}</el-descriptions-item>
<el-descriptions-item label="医院">{{ selectedUserDetail.hospitalName || '-' }}</el-descriptions-item>
<el-descriptions-item label="科室">{{ selectedUserDetail.departmentName || '-' }}</el-descriptions-item>
<el-descriptions-item label="小组">{{ selectedUserDetail.groupName || '-' }}</el-descriptions-item>
<el-descriptions-item label="姓名">{{
selectedUserDetail.name || '-'
}}</el-descriptions-item>
<el-descriptions-item label="角色">{{
getRoleName(selectedUserDetail.role)
}}</el-descriptions-item>
<el-descriptions-item label="手机号">{{
selectedUserDetail.phone || '-'
}}</el-descriptions-item>
<el-descriptions-item label="医院">{{
selectedUserDetail.hospitalName || '-'
}}</el-descriptions-item>
<el-descriptions-item label="科室">{{
selectedUserDetail.departmentName || '-'
}}</el-descriptions-item>
<el-descriptions-item label="小组">{{
selectedUserDetail.groupName || '-'
}}</el-descriptions-item>
</el-descriptions>
<el-alert
title="如需修改人员角色或组织归属,请前往“用户管理”页面操作。"
@ -194,16 +306,37 @@
</el-row>
<!-- Dialog for Create / Edit -->
<el-dialog :title="dialogTitle" v-model="dialogVisible" width="450px" @close="resetForm" destroy-on-close>
<el-form :model="form" :rules="rules" ref="formRef" label-width="100px" @submit.prevent>
<el-dialog
:title="dialogTitle"
v-model="dialogVisible"
width="450px"
@close="resetForm"
destroy-on-close
>
<el-form
:model="form"
:rules="rules"
ref="formRef"
label-width="100px"
@submit.prevent
>
<el-form-item :label="formLabel" prop="name">
<el-input v-model="form.name" :placeholder="`请输入${formLabel}`" clearable />
<el-input
v-model="form.name"
:placeholder="`请输入${formLabel}`"
clearable
/>
</el-form-item>
</el-form>
<template #footer>
<div class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
<el-button
type="primary"
@click="handleSubmit"
:loading="submitLoading"
>确定</el-button
>
</div>
</template>
</el-dialog>
@ -220,7 +353,7 @@
v-model="selectedOwnerUserId"
filterable
placeholder="请选择人员"
style="width: 100%;"
style="width: 100%"
>
<el-option
v-for="user in ownerCandidates"
@ -239,7 +372,11 @@
<template #footer>
<div class="dialog-footer">
<el-button @click="ownerDialogVisible = false">取消</el-button>
<el-button type="primary" :loading="ownerSubmitLoading" @click="handleSetOwner">
<el-button
type="primary"
:loading="ownerSubmitLoading"
@click="handleSetOwner"
>
确定
</el-button>
</div>
@ -252,10 +389,33 @@
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getHospitals, getDepartments, getGroups, createDepartment, updateDepartment, deleteDepartment, createGroup, updateGroup, deleteGroup, updateHospital, deleteHospital } from '../../api/organization';
import {
getHospitals,
getDepartments,
getGroups,
createDepartment,
updateDepartment,
deleteDepartment,
createGroup,
updateGroup,
deleteGroup,
updateHospital,
deleteHospital,
} from '../../api/organization';
import { getUsers, updateUser } from '../../api/users';
import { useUserStore } from '../../store/user';
import { OfficeBuilding, Filter, Connection, UserFilled, Refresh, Plus, EditPen, Delete, Menu, User } from '@element-plus/icons-vue';
import {
OfficeBuilding,
Filter,
Connection,
UserFilled,
Refresh,
Plus,
EditPen,
Delete,
Menu,
User,
} from '@element-plus/icons-vue';
const router = useRouter();
const userStore = useUserStore();
@ -282,9 +442,9 @@ const roleMap = {
SYSTEM_ADMIN: '系统管理员',
HOSPITAL_ADMIN: '医院管理员',
DIRECTOR: '科室主任',
LEADER: '医疗组长',
LEADER: '小组组长',
DOCTOR: '医生',
ENGINEER: '工程师'
ENGINEER: '工程师',
};
const getRoleName = (role) => roleMap[role] || role;
@ -298,12 +458,22 @@ const getRoleTagType = (role) => {
};
const getTypeName = (type) => {
const map = { hospital: '医院', department: '科室', group: '小组', user: '人员' };
const map = {
hospital: '医院',
department: '科室',
group: '小组',
user: '人员',
};
return map[type] || type;
};
const getNodeTypeTag = (type) => {
const map = { hospital: 'primary', department: 'success', group: 'warning', user: 'info' };
const map = {
hospital: 'primary',
department: 'success',
group: 'warning',
user: 'info',
};
return map[type] || 'info';
};
@ -322,16 +492,16 @@ const canCreateDepartment = (node) =>
const canCreateGroup = (node) =>
Boolean(
node
&& node.type === 'department'
&& (isOrgAdmin.value || isDirector.value),
node &&
node.type === 'department' &&
(isOrgAdmin.value || isDirector.value),
);
const canAddUser = (node) =>
Boolean(
node
&& (node.type === 'department' || node.type === 'group')
&& isOrgAdmin.value,
node &&
(node.type === 'department' || node.type === 'group') &&
isOrgAdmin.value,
);
const canEditNode = (node) => {
@ -378,9 +548,9 @@ const activePanelTitle = computed(() => {
const activeNodeChildren = computed(() => {
if (
!activeNode.value
|| activeNode.value.type === 'user'
|| !Array.isArray(activeNode.value.children)
!activeNode.value ||
activeNode.value.type === 'user' ||
!Array.isArray(activeNode.value.children)
) {
return [];
}
@ -406,7 +576,9 @@ const selectedUserDetail = computed(() => {
return null;
}
const current = allUsers.value.find((user) => user.id === activeNode.value.id);
const current = allUsers.value.find(
(user) => user.id === activeNode.value.id,
);
const userData = current || activeNode.value;
const hospitalId = userData.hospitalId || null;
const departmentId = userData.departmentId || null;
@ -424,6 +596,9 @@ const activeNodeMeta = computed(() => {
if (!activeNode.value) {
return '';
}
if (activeNode.value.type === 'hospital') {
return `当前医院管理员:${activeNode.value.adminDisplay || '未设置'}`;
}
if (activeNode.value.type === 'department') {
return `当前科室主任:${activeNode.value.directorDisplay || '未设置'}`;
}
@ -459,7 +634,7 @@ const fetchTreeData = async () => {
const [deptRes, groupRes, userRes] = await Promise.all([
getDepartments({ pageSize: 100 }),
getGroups({ pageSize: 100 }),
getUsers()
getUsers(),
]);
const departments = deptRes.list || [];
@ -478,7 +653,14 @@ const fetchTreeData = async () => {
const directorNameMap = {};
const leaderNameMap = {};
const hospitalAdminNameMap = {};
users.forEach((user) => {
if (user.role === 'HOSPITAL_ADMIN' && user.hospitalId) {
if (!hospitalAdminNameMap[user.hospitalId]) {
hospitalAdminNameMap[user.hospitalId] = [];
}
hospitalAdminNameMap[user.hospitalId].push(user.name);
}
if (user.role === 'DIRECTOR' && user.departmentId) {
if (!directorNameMap[user.departmentId]) {
directorNameMap[user.departmentId] = [];
@ -493,49 +675,86 @@ const fetchTreeData = async () => {
}
});
const tree = hospitals.map(h => {
const hDepts = departments.filter(d => d.hospitalId === h.id);
const deptNodes = hDepts.map(d => {
const dGroups = groups.filter(g => g.departmentId === d.id);
const tree = hospitals.map((h) => {
const hDepts = departments.filter((d) => d.hospitalId === h.id);
const adminDisplay =
(hospitalAdminNameMap[h.id] || []).join('、') || '未设置';
const deptNodes = hDepts.map((d) => {
const dGroups = groups.filter((g) => g.departmentId === d.id);
const directorDisplay =
(directorNameMap[d.id] || []).join('、') || '未设置';
const groupNodes = dGroups.map(g => {
const gUsers = users.filter(u => u.groupId === g.id);
const groupNodes = dGroups.map((g) => {
const gUsers = users.filter((u) => u.groupId === g.id);
const leaderDisplay =
(leaderNameMap[g.id] || []).join('、') || '未设置';
const userNodes = gUsers.map(u => ({
key: `u_${u.id}`, id: u.id, name: u.name, type: 'user', role: u.role,
hospitalId: h.id, departmentId: d.id, groupId: g.id
const userNodes = gUsers.map((u) => ({
key: `u_${u.id}`,
id: u.id,
name: u.name,
type: 'user',
role: u.role,
hospitalId: h.id,
departmentId: d.id,
groupId: g.id,
}));
return {
key: `g_${g.id}`, id: g.id, name: g.name, type: 'group',
departmentId: d.id, hospitalId: h.id, leaderDisplay, children: userNodes
key: `g_${g.id}`,
id: g.id,
name: g.name,
type: 'group',
departmentId: d.id,
hospitalId: h.id,
leaderDisplay,
children: userNodes,
};
});
const dUsers = users.filter(u => u.departmentId === d.id && !u.groupId);
const dUserNodes = dUsers.map(u => ({
key: `u_${u.id}`, id: u.id, name: u.name, type: 'user', role: u.role,
hospitalId: h.id, departmentId: d.id
const dUsers = users.filter(
(u) => u.departmentId === d.id && !u.groupId,
);
const dUserNodes = dUsers.map((u) => ({
key: `u_${u.id}`,
id: u.id,
name: u.name,
type: 'user',
role: u.role,
hospitalId: h.id,
departmentId: d.id,
}));
return {
key: `d_${d.id}`, id: d.id, name: d.name, type: 'department',
hospitalId: h.id, directorDisplay, children: [...groupNodes, ...dUserNodes]
key: `d_${d.id}`,
id: d.id,
name: d.name,
type: 'department',
hospitalId: h.id,
directorDisplay,
children: [...groupNodes, ...dUserNodes],
};
});
const hUsers = users.filter(u => u.hospitalId === h.id && !u.departmentId);
const hUserNodes = hUsers.map(u => ({
key: `u_${u.id}`, id: u.id, name: u.name, type: 'user', role: u.role,
hospitalId: h.id
const hUsers = users.filter(
(u) => u.hospitalId === h.id && !u.departmentId,
);
const hUserNodes = hUsers.map((u) => ({
key: `u_${u.id}`,
id: u.id,
name: u.name,
type: 'user',
role: u.role,
hospitalId: h.id,
}));
return {
key: `h_${h.id}`, id: h.id, name: h.name, type: 'hospital', children: [...deptNodes, ...hUserNodes]
key: `h_${h.id}`,
id: h.id,
name: h.name,
type: 'hospital',
adminDisplay,
children: [...deptNodes, ...hUserNodes],
};
});
@ -564,17 +783,19 @@ const openSetOwnerDialog = (node) => {
selectedOwnerUserId.value = null;
if (node.type === 'department') {
ownerCandidates.value = allUsers.value.filter((user) =>
user.hospitalId === node.hospitalId
&& user.departmentId === node.id
&& ['DIRECTOR', 'LEADER'].includes(user.role),
ownerCandidates.value = allUsers.value.filter(
(user) =>
user.hospitalId === node.hospitalId &&
user.departmentId === node.id &&
user.role === 'DIRECTOR',
);
} else {
ownerCandidates.value = allUsers.value.filter((user) =>
user.hospitalId === node.hospitalId
&& user.departmentId === node.departmentId
&& user.groupId === node.id
&& user.role === 'LEADER',
ownerCandidates.value = allUsers.value.filter(
(user) =>
user.hospitalId === node.hospitalId &&
user.departmentId === node.departmentId &&
user.groupId === node.id &&
user.role === 'LEADER',
);
}
@ -584,7 +805,9 @@ const openSetOwnerDialog = (node) => {
}
const currentOwner = ownerCandidates.value.find((user) =>
node.type === 'department' ? user.role === 'DIRECTOR' : user.role === 'LEADER',
node.type === 'department'
? user.role === 'DIRECTOR'
: user.role === 'LEADER',
);
selectedOwnerUserId.value = currentOwner?.id ?? ownerCandidates.value[0].id;
ownerDialogVisible.value = true;
@ -607,14 +830,14 @@ const handleSetOwner = async () => {
const isDepartment = ownerTargetNode.value.type === 'department';
const payload = isDepartment
? {
role: 'DIRECTOR',
// DOCTOR /
//
groupId: null,
}
role: 'DIRECTOR',
// DOCTOR /
//
groupId: null,
}
: {
role: 'LEADER',
};
role: 'LEADER',
};
ownerSubmitLoading.value = true;
try {
@ -628,15 +851,16 @@ const handleSetOwner = async () => {
};
const goToAddUser = (nodeData) => {
// We navigate to the Users list page. In a full implementation, you could
// We navigate to the Users list page. In a full implementation, you could
// pass query params to pre-fill a creation form or open a dialog directly.
router.push({
path: '/users',
query: {
action: 'create',
hospitalId: nodeData.hospitalId,
departmentId: nodeData.type === 'department' ? nodeData.id : nodeData.departmentId,
}
departmentId:
nodeData.type === 'department' ? nodeData.id : nodeData.departmentId,
},
});
};
@ -644,23 +868,51 @@ const goToAddUser = (nodeData) => {
const dialogVisible = ref(false);
const submitLoading = ref(false);
const formRef = ref(null);
const dialogType = ref('');
const dialogMode = ref('');
const dialogType = ref('');
const dialogMode = ref('');
const parentId = ref(null);
const currentId = ref(null);
const form = reactive({ name: '' });
const rules = { name: [{ required: true, message: '请输入名称', trigger: 'blur' }] };
const rules = {
name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
};
const dialogTitle = computed(() => {
const typeName = dialogType.value === 'hospital' ? '医院' : (dialogType.value === 'department' ? '科室' : '小组');
const typeName =
dialogType.value === 'hospital'
? '医院'
: dialogType.value === 'department'
? '科室'
: '小组';
return dialogMode.value === 'create' ? `新增${typeName}` : `编辑${typeName}`;
});
const formLabel = computed(() => dialogType.value === 'hospital' ? '医院名称' : (dialogType.value === 'department' ? '科室名称' : '小组名称'));
const formLabel = computed(() =>
dialogType.value === 'hospital'
? '医院名称'
: dialogType.value === 'department'
? '科室名称'
: '小组名称',
);
const openCreateDialog = (type, pId) => { dialogType.value = type; dialogMode.value = 'create'; parentId.value = pId; currentId.value = null; dialogVisible.value = true; };
const openEditDialog = (data) => { dialogType.value = data.type; dialogMode.value = 'edit'; currentId.value = data.id; form.name = data.name; dialogVisible.value = true; };
const resetForm = () => { if (formRef.value) formRef.value.resetFields(); form.name = ''; };
const openCreateDialog = (type, pId) => {
dialogType.value = type;
dialogMode.value = 'create';
parentId.value = pId;
currentId.value = null;
dialogVisible.value = true;
};
const openEditDialog = (data) => {
dialogType.value = data.type;
dialogMode.value = 'edit';
currentId.value = data.id;
form.name = data.name;
dialogVisible.value = true;
};
const resetForm = () => {
if (formRef.value) formRef.value.resetFields();
form.name = '';
};
const handleSubmit = async () => {
if (!formRef.value) return;
@ -669,45 +921,78 @@ const handleSubmit = async () => {
submitLoading.value = true;
try {
if (dialogMode.value === 'create') {
if (dialogType.value === 'department') await createDepartment({ name: form.name, hospitalId: parentId.value });
else if (dialogType.value === 'group') await createGroup({ name: form.name, departmentId: parentId.value });
if (dialogType.value === 'department')
await createDepartment({
name: form.name,
hospitalId: parentId.value,
});
else if (dialogType.value === 'group')
await createGroup({
name: form.name,
departmentId: parentId.value,
});
ElMessage.success('创建成功');
} else {
if (dialogType.value === 'hospital') await updateHospital(currentId.value, { name: form.name });
else if (dialogType.value === 'department') await updateDepartment(currentId.value, { name: form.name });
else if (dialogType.value === 'group') await updateGroup(currentId.value, { name: form.name });
if (dialogType.value === 'hospital')
await updateHospital(currentId.value, { name: form.name });
else if (dialogType.value === 'department')
await updateDepartment(currentId.value, { name: form.name });
else if (dialogType.value === 'group')
await updateGroup(currentId.value, { name: form.name });
ElMessage.success('更新成功');
// Update activeNode locally if it's the one edited
if (activeNode.value && activeNode.value.id === currentId.value && activeNode.value.type === dialogType.value) {
if (
activeNode.value &&
activeNode.value.id === currentId.value &&
activeNode.value.type === dialogType.value
) {
activeNode.value.name = form.name;
}
}
dialogVisible.value = false;
fetchTreeData();
} catch (error) { console.error(error); } finally { submitLoading.value = false; }
} catch (error) {
console.error(error);
} finally {
submitLoading.value = false;
}
}
});
};
const handleDelete = (data) => {
const typeName = data.type === 'hospital' ? '医院' : (data.type === 'department' ? '科室' : '小组');
ElMessageBox.confirm(`确定要删除${typeName} "${data.name}" 吗?`, '警告', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
.then(async () => {
try {
if (data.type === 'hospital') await deleteHospital(data.id);
else if (data.type === 'department') await deleteDepartment(data.id);
else if (data.type === 'group') await deleteGroup(data.id);
ElMessage.success('删除成功');
if (activeNode.value && activeNode.value.key === data.key) {
activeNode.value = null; // Clear active node if deleted
const typeName =
data.type === 'hospital'
? '医院'
: data.type === 'department'
? '科室'
: '小组';
ElMessageBox.confirm(`确定要删除${typeName} "${data.name}" 吗?`, '警告', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
})
.then(async () => {
try {
if (data.type === 'hospital') await deleteHospital(data.id);
else if (data.type === 'department') await deleteDepartment(data.id);
else if (data.type === 'group') await deleteGroup(data.id);
ElMessage.success('删除成功');
if (activeNode.value && activeNode.value.key === data.key) {
activeNode.value = null; // Clear active node if deleted
}
fetchTreeData();
} catch (error) {
console.error(error);
}
fetchTreeData();
} catch (error) { console.error(error); }
}).catch(() => {});
})
.catch(() => {});
};
onMounted(() => { fetchTreeData(); });
onMounted(() => {
fetchTreeData();
});
</script>
<style scoped>
@ -715,7 +1000,8 @@ onMounted(() => { fetchTreeData(); });
padding: 20px;
}
.tree-card, .detail-card {
.tree-card,
.detail-card {
border-radius: 8px;
height: calc(100vh - 120px);
display: flex;
@ -830,10 +1116,19 @@ onMounted(() => { fetchTreeData(); });
font-size: 16px;
}
.node-hospital .node-icon-wrapper { color: #409EFF; }
.node-department .node-icon-wrapper { color: #67C23A; }
.node-group .node-icon-wrapper { color: #E6A23C; }
.node-user .node-icon-wrapper { color: #909399; font-size: 14px; }
.node-hospital .node-icon-wrapper {
color: #409eff;
}
.node-department .node-icon-wrapper {
color: #67c23a;
}
.node-group .node-icon-wrapper {
color: #e6a23c;
}
.node-user .node-icon-wrapper {
color: #909399;
font-size: 14px;
}
.node-label {
font-size: 14px;

View File

@ -11,7 +11,7 @@
v-model="searchForm.hospitalId"
placeholder="系统管理员必须选择医院"
clearable
style="width: 240px;"
style="width: 240px"
@change="handleSearchHospitalChange"
>
<el-option
@ -29,17 +29,14 @@
clearable
/>
</el-form-item>
<el-form-item label="设备 SN">
<el-input
v-model="searchForm.deviceSn"
placeholder="按设备 SN 过滤"
clearable
/>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="handleSearch" icon="Search">查询</el-button>
<el-button type="primary" @click="handleSearch" icon="Search"
>查询</el-button
>
<el-button @click="resetSearch" icon="Refresh">重置</el-button>
<el-button type="success" @click="openCreateDialog" icon="Plus">新增患者</el-button>
<el-button type="success" @click="openCreateDialog" icon="Plus"
>新增患者</el-button
>
</el-form-item>
</el-form>
</div>
@ -49,37 +46,37 @@
type="warning"
:closable="false"
title="系统管理员查询患者时必须先选择医院。"
style="margin-bottom: 16px;"
style="margin-bottom: 16px"
/>
<el-table :data="tableData" v-loading="loading" border stripe style="width: 100%">
<el-table
:data="tableData"
v-loading="loading"
border
stripe
style="width: 100%"
>
<el-table-column prop="id" label="ID" width="80" align="center" />
<el-table-column prop="name" label="姓名" min-width="120" />
<el-table-column prop="phone" label="手机号" min-width="140" />
<el-table-column prop="idCardHash" label="证件哈希" min-width="200" />
<el-table-column prop="idCard" label="身份证号" min-width="200" />
<el-table-column label="归属医院" min-width="160">
<template #default="{ row }">
{{ row.hospital?.name || '-' }}
</template>
</el-table-column>
<el-table-column label="归属人员" min-width="140">
<el-table-column label="归属医生" min-width="140">
<template #default="{ row }">
{{ row.doctor?.name || '-' }}
</template>
</el-table-column>
<el-table-column label="设备数" width="100" align="center">
<template #default="{ row }">
{{ row.devices?.length || 0 }}
</template>
</el-table-column>
<el-table-column label="设备 SN" min-width="220">
<template #default="{ row }">
{{ formatDeviceSn(row.devices) }}
</template>
</el-table-column>
<el-table-column label="操作" width="260" fixed="right" align="center">
<template #default="{ row }">
<el-button size="small" type="primary" @click="openRecordDialog(row)">
<el-button
size="small"
type="primary"
@click="openRecordDialog(row)"
>
详情
</el-button>
<el-button size="small" @click="openEditDialog(row)">
@ -119,30 +116,31 @@
<el-form-item label="手机号" prop="phone">
<el-input v-model="form.phone" placeholder="请输入手机号" />
</el-form-item>
<el-form-item label="证件哈希" prop="idCardHash">
<el-input v-model="form.idCardHash" placeholder="请输入证件哈希" />
<el-form-item label="身份证号" prop="idCard">
<el-input v-model="form.idCard" placeholder="请输入身份证号" />
</el-form-item>
<el-form-item label="归属人员" prop="doctorId">
<el-select
<el-form-item label="归属医生" prop="doctorId">
<el-tree-select
v-model="form.doctorId"
:data="doctorTreeOptions"
:props="doctorTreeProps"
check-strictly
filterable
placeholder="请选择归属人员(医生/主任/组长)"
style="width: 100%;"
clearable
placeholder="请选择归属医生(按科室/小组)"
style="width: 100%"
:disabled="userStore.role === 'DOCTOR'"
>
<el-option
v-for="doctor in doctorOptions"
:key="doctor.id"
:label="`${doctor.name}${getRoleName(doctor.role)} / ${doctor.phone}`"
:value="doctor.id"
/>
</el-select>
/>
</el-form-item>
</el-form>
<template #footer>
<div class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" :loading="submitLoading" @click="handleSubmit">
<el-button
type="primary"
:loading="submitLoading"
@click="handleSubmit"
>
确定
</el-button>
</div>
@ -151,13 +149,27 @@
<el-dialog title="调压记录详情" v-model="recordDialogVisible" width="860px">
<el-descriptions :column="4" border class="mb-16">
<el-descriptions-item label="患者">{{ currentPatientName || '-' }}</el-descriptions-item>
<el-descriptions-item label="手机号">{{ recordSummary.phone || '-' }}</el-descriptions-item>
<el-descriptions-item label="证件哈希">{{ recordSummary.idCardHash || '-' }}</el-descriptions-item>
<el-descriptions-item label="记录数">{{ recordList.length }}</el-descriptions-item>
<el-descriptions-item label="患者">{{
currentPatientName || '-'
}}</el-descriptions-item>
<el-descriptions-item label="手机号">{{
recordSummary.phone || '-'
}}</el-descriptions-item>
<el-descriptions-item label="身份证号">{{
recordSummary.idCard || '-'
}}</el-descriptions-item>
<el-descriptions-item label="记录数">{{
recordList.length
}}</el-descriptions-item>
</el-descriptions>
<el-table :data="recordList" v-loading="recordLoading" border stripe max-height="520">
<el-table
:data="recordList"
v-loading="recordLoading"
border
stripe
max-height="520"
>
<el-table-column label="时间" width="180">
<template #default="{ row }">
{{ new Date(row.occurredAt).toLocaleString() }}
@ -175,7 +187,8 @@
</el-table-column>
<el-table-column label="压力变更" min-width="140">
<template #default="{ row }">
{{ row.taskItem?.oldPressure ?? '-' }} -> {{ row.taskItem?.targetPressure ?? '-' }}
{{ row.taskItem?.oldPressure ?? '-' }} ->
{{ row.taskItem?.targetPressure ?? '-' }}
</template>
</el-table-column>
<el-table-column label="医院" min-width="140">
@ -199,7 +212,7 @@
</template>
<script setup>
import { reactive, ref, onMounted } from 'vue';
import { reactive, ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
getPatients,
@ -211,13 +224,14 @@ import {
getPatientLifecycle,
} from '../../api/patients';
import { getHospitals } from '../../api/organization';
import { getDepartments, getGroups } from '../../api/organization';
import { useUserStore } from '../../store/user';
const userStore = useUserStore();
const roleMap = {
DIRECTOR: '科室主任',
LEADER: '医疗组长',
LEADER: '小组组长',
DOCTOR: '医生',
};
@ -230,10 +244,11 @@ const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const hospitals = ref([]);
const departments = ref([]);
const groups = ref([]);
const searchForm = reactive({
keyword: '',
deviceSn: '',
hospitalId: null,
});
@ -247,7 +262,7 @@ const doctorOptions = ref([]);
const form = reactive({
name: '',
phone: '',
idCardHash: '',
idCard: '',
doctorId: null,
});
@ -257,7 +272,7 @@ const rules = {
{ required: true, message: '请输入手机号', trigger: 'blur' },
{ pattern: /^1\d{10}$/, message: '请输入正确的手机号', trigger: 'blur' },
],
idCardHash: [{ required: true, message: '请输入证件哈希', trigger: 'blur' }],
idCard: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
doctorId: [{ required: true, message: '请选择归属人员', trigger: 'change' }],
};
@ -266,30 +281,93 @@ const recordLoading = ref(false);
const currentPatientName = ref('');
const recordSummary = reactive({
phone: '',
idCardHash: '',
idCard: '',
});
const recordList = ref([]);
const formatDeviceSn = (devices = []) => {
if (!Array.isArray(devices) || devices.length === 0) {
return '-';
}
return devices.map((item) => item.snCode).join('');
const doctorTreeProps = {
value: 'value',
label: 'label',
children: 'children',
disabled: 'disabled',
};
const departmentNameMap = computed(() => {
return Object.fromEntries(
(departments.value || []).map((item) => [item.id, item.name]),
);
});
const groupNameMap = computed(() => {
return Object.fromEntries(
(groups.value || []).map((item) => [item.id, item.name]),
);
});
const doctorTreeOptions = computed(() => {
const options = Array.isArray(doctorOptions.value) ? doctorOptions.value : [];
const deptMap = new Map();
options.forEach((doctor) => {
const deptId = doctor.departmentId ?? 0;
const groupId = doctor.groupId ?? 0;
const deptKey = `dept_${deptId}`;
const groupKey = `group_${groupId}`;
if (!deptMap.has(deptKey)) {
const deptLabel = deptId
? departmentNameMap.value[deptId] || `科室#${deptId}`
: '未分配科室';
deptMap.set(deptKey, {
value: deptKey,
label: deptLabel,
disabled: true,
children: [],
});
}
const deptNode = deptMap.get(deptKey);
if (groupId) {
let groupNode = deptNode.children.find((item) => item.value === groupKey);
if (!groupNode) {
groupNode = {
value: groupKey,
label: groupNameMap.value[groupId] || `小组#${groupId}`,
disabled: true,
children: [],
};
deptNode.children.push(groupNode);
}
groupNode.children.push({
value: doctor.id,
label: `${doctor.name}${getRoleName(doctor.role)} / ${doctor.phone}`,
});
return;
}
deptNode.children.push({
value: doctor.id,
label: `${doctor.name}${getRoleName(doctor.role)} / ${doctor.phone}`,
});
});
return Array.from(deptMap.values()).sort((a, b) =>
String(a.label).localeCompare(String(b.label), 'zh-Hans-CN'),
);
});
const applyFiltersAndPagination = () => {
const keyword = searchForm.keyword.trim();
const deviceSn = searchForm.deviceSn.trim();
const filtered = allPatients.value.filter((patient) => {
const hitKeyword = !keyword
|| patient.name?.includes(keyword)
|| patient.phone?.includes(keyword);
const hitKeyword =
!keyword ||
patient.name?.includes(keyword) ||
patient.phone?.includes(keyword);
const hitDevice = !deviceSn
|| (patient.devices || []).some((device) => device.snCode?.includes(deviceSn));
return hitKeyword && hitDevice;
return hitKeyword;
});
total.value = filtered.length;
@ -321,6 +399,25 @@ const fetchDoctorOptions = async () => {
doctorOptions.value = Array.isArray(res) ? res : [];
};
const fetchOrgNodesForDoctorTree = async () => {
const params = { pageSize: 100 };
if (userStore.role === 'SYSTEM_ADMIN') {
if (!searchForm.hospitalId) {
departments.value = [];
groups.value = [];
return;
}
params.hospitalId = searchForm.hospitalId;
}
const [deptRes, groupRes] = await Promise.all([
getDepartments(params),
getGroups(params),
]);
departments.value = Array.isArray(deptRes?.list) ? deptRes.list : [];
groups.value = Array.isArray(groupRes?.list) ? groupRes.list : [];
};
const fetchData = async () => {
if (userStore.role === 'SYSTEM_ADMIN' && !searchForm.hospitalId) {
allPatients.value = [];
@ -335,6 +432,8 @@ const fetchData = async () => {
if (userStore.role === 'SYSTEM_ADMIN') {
params.hospitalId = searchForm.hospitalId;
}
//
const res = await getPatients(params);
allPatients.value = Array.isArray(res) ? res : [];
applyFiltersAndPagination();
@ -345,6 +444,7 @@ const fetchData = async () => {
const handleSearchHospitalChange = async () => {
page.value = 1;
await fetchOrgNodesForDoctorTree();
await fetchDoctorOptions();
await fetchData();
};
@ -356,7 +456,6 @@ const handleSearch = () => {
const resetSearch = () => {
searchForm.keyword = '';
searchForm.deviceSn = '';
page.value = 1;
fetchData();
};
@ -365,7 +464,7 @@ const resetForm = () => {
formRef.value?.resetFields();
form.name = '';
form.phone = '';
form.idCardHash = '';
form.idCard = '';
form.doctorId = null;
currentEditId.value = null;
};
@ -373,6 +472,7 @@ const resetForm = () => {
const openCreateDialog = async () => {
isEdit.value = false;
resetForm();
await fetchOrgNodesForDoctorTree();
await fetchDoctorOptions();
if (userStore.role === 'DOCTOR') {
@ -383,12 +483,13 @@ const openCreateDialog = async () => {
const openEditDialog = async (row) => {
isEdit.value = true;
await fetchOrgNodesForDoctorTree();
await fetchDoctorOptions();
const detail = await getPatientById(row.id);
currentEditId.value = detail.id;
form.name = detail.name;
form.phone = detail.phone;
form.idCardHash = detail.idCardHash;
form.idCard = detail.idCard;
form.doctorId = detail.doctorId;
dialogVisible.value = true;
};
@ -400,10 +501,11 @@ const handleSubmit = async () => {
submitLoading.value = true;
try {
// 使
const payload = {
name: form.name,
phone: form.phone,
idCardHash: form.idCardHash,
idCard: form.idCard,
doctorId: form.doctorId,
};
if (isEdit.value) {
@ -422,15 +524,11 @@ const handleSubmit = async () => {
};
const handleDelete = (row) => {
ElMessageBox.confirm(
`确定要删除患者 "${row.name}" 吗?`,
'警告',
{
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
},
)
ElMessageBox.confirm(`确定要删除患者 "${row.name}" 吗?`, '警告', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
})
.then(async () => {
await deletePatient(row.id);
ElMessage.success('删除成功');
@ -440,8 +538,8 @@ const handleDelete = (row) => {
};
const openRecordDialog = async (row) => {
if (!row.phone || !row.idCardHash) {
ElMessage.warning('缺少 phone 或 idCardHash,无法查询调压记录');
if (!row.phone || !row.idCard) {
ElMessage.warning('缺少 phone 或 idCard,无法查询调压记录');
return;
}
@ -449,16 +547,17 @@ const openRecordDialog = async (row) => {
recordLoading.value = true;
currentPatientName.value = row.name || '';
recordSummary.phone = '';
recordSummary.idCardHash = '';
recordSummary.idCard = '';
recordList.value = [];
try {
//
const res = await getPatientLifecycle({
phone: row.phone,
idCardHash: row.idCardHash,
idCard: row.idCard,
});
recordSummary.phone = res.phone || '';
recordSummary.idCardHash = res.idCardHash || '';
recordSummary.idCard = res.idCard || '';
const fullList = Array.isArray(res.lifecycle) ? res.lifecycle : [];
recordList.value = fullList.filter((item) => item.patient?.id === row.id);
} finally {
@ -468,6 +567,7 @@ const openRecordDialog = async (row) => {
onMounted(async () => {
await fetchHospitalsForAdmin();
await fetchOrgNodesForDoctorTree();
await fetchDoctorOptions();
await fetchData();
});

View File

@ -10,18 +10,18 @@
clearable
/>
</el-form-item>
<el-form-item label="角色">
<el-form-item v-if="!isDirector" label="角色">
<el-select
v-model="searchForm.role"
placeholder="请选择角色"
clearable
>
<el-option label="系统管理员" value="SYSTEM_ADMIN" />
<el-option label="医院管理员" value="HOSPITAL_ADMIN" />
<el-option label="科室主任" value="DIRECTOR" />
<el-option label="医疗组长" value="LEADER" />
<el-option label="医生" value="DOCTOR" />
<el-option label="工程师" value="ENGINEER" />
<el-option
v-for="option in roleOptions"
:key="option.value"
:label="option.label"
:value="option.value"
/>
</el-select>
</el-form-item>
<el-form-item>
@ -30,13 +30,19 @@
</el-button>
<el-button @click="resetSearch" icon="Refresh">重置</el-button>
<el-button type="success" @click="openCreateDialog" icon="Plus">
新增用户
{{ createButtonText }}
</el-button>
</el-form-item>
</el-form>
</div>
<el-table :data="tableData" v-loading="loading" border stripe style="width: 100%">
<el-table
:data="tableData"
v-loading="loading"
border
stripe
style="width: 100%"
>
<el-table-column prop="id" label="ID" width="80" align="center" />
<el-table-column prop="name" label="姓名" min-width="120" />
<el-table-column prop="phone" label="手机号" min-width="150" />
@ -65,7 +71,9 @@
<el-table-column label="操作" width="260" fixed="right" align="center">
<template #default="{ row }">
<el-button
v-if="row.role === 'ENGINEER' && userStore.role === 'SYSTEM_ADMIN'"
v-if="
row.role === 'ENGINEER' && userStore.role === 'SYSTEM_ADMIN'
"
size="small"
type="warning"
@click="openAssignDialog(row)"
@ -76,7 +84,7 @@
编辑
</el-button>
<el-button
v-if="userStore.role === 'SYSTEM_ADMIN'"
v-if="canDeleteUser(row)"
size="small"
type="danger"
@click="handleDelete(row)"
@ -102,7 +110,7 @@
</el-card>
<el-dialog
:title="isEdit ? '编辑用户' : '新增用户'"
:title="dialogTitle"
v-model="dialogVisible"
width="620px"
@close="resetForm"
@ -123,13 +131,23 @@
/>
</el-form-item>
<el-form-item label="角色" prop="role">
<el-select v-model="form.role" placeholder="请选择角色" style="width: 100%;">
<el-option label="系统管理员" value="SYSTEM_ADMIN" />
<el-option label="医院管理员" value="HOSPITAL_ADMIN" />
<el-option label="科室主任" value="DIRECTOR" />
<el-option label="医疗组长" value="LEADER" />
<el-option label="医生" value="DOCTOR" />
<el-option label="工程师" value="ENGINEER" />
<el-input
v-if="isDirector"
:model-value="getRoleName('DOCTOR')"
disabled
/>
<el-select
v-else
v-model="form.role"
placeholder="请选择角色"
style="width: 100%"
>
<el-option
v-for="option in roleOptions"
:key="option.value"
:label="option.label"
:value="option.value"
/>
</el-select>
</el-form-item>
@ -137,7 +155,8 @@
<el-select
v-model="form.hospitalId"
placeholder="请选择医院"
style="width: 100%;"
style="width: 100%"
:disabled="lockHospital"
>
<el-option
v-for="hospital in hospitals"
@ -148,11 +167,16 @@
</el-select>
</el-form-item>
<el-form-item label="所属科室" prop="departmentId" v-if="needDepartment">
<el-form-item
label="所属科室"
prop="departmentId"
v-if="needDepartment"
>
<el-select
v-model="form.departmentId"
placeholder="请选择科室"
style="width: 100%;"
style="width: 100%"
:disabled="lockDepartment"
>
<el-option
v-for="department in formDepartments"
@ -167,7 +191,7 @@
<el-select
v-model="form.groupId"
placeholder="请选择小组"
style="width: 100%;"
style="width: 100%"
>
<el-option
v-for="group in formGroups"
@ -181,7 +205,11 @@
<template #footer>
<div class="dialog-footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="handleSubmit" :loading="submitLoading">
<el-button
type="primary"
@click="handleSubmit"
:loading="submitLoading"
>
确定
</el-button>
</div>
@ -201,7 +229,7 @@
<el-select
v-model="assignHospitalId"
placeholder="请选择医院"
style="width: 100%;"
style="width: 100%"
>
<el-option
v-for="hospital in hospitals"
@ -215,7 +243,11 @@
<template #footer>
<div class="dialog-footer">
<el-button @click="assignDialogVisible = false">取消</el-button>
<el-button type="primary" @click="handleAssignSubmit" :loading="submitLoading">
<el-button
type="primary"
@click="handleAssignSubmit"
:loading="submitLoading"
>
确定
</el-button>
</div>
@ -242,6 +274,15 @@ import {
} from '../../api/organization';
import { useUserStore } from '../../store/user';
const roleOptions = [
{ label: '系统管理员', value: 'SYSTEM_ADMIN' },
{ label: '医院管理员', value: 'HOSPITAL_ADMIN' },
{ label: '科室主任', value: 'DIRECTOR' },
{ label: '小组组长', value: 'LEADER' },
{ label: '医生', value: 'DOCTOR' },
{ label: '工程师', value: 'ENGINEER' },
];
const route = useRoute();
const userStore = useUserStore();
@ -255,9 +296,10 @@ const hospitals = ref([]);
const departments = ref([]);
const groups = ref([]);
const isDirector = computed(() => userStore.role === 'DIRECTOR');
const searchForm = reactive({
keyword: '',
role: '',
role: isDirector.value ? 'DOCTOR' : '',
});
const dialogVisible = ref(false);
@ -282,13 +324,24 @@ const assignDialogVisible = ref(false);
const currentAssignUser = ref(null);
const assignHospitalId = ref(null);
const createButtonText = computed(() =>
isDirector.value ? '新增医生' : '新增用户',
);
const dialogTitle = computed(() => {
if (isDirector.value) {
return isEdit.value ? '编辑医生' : '新增医生';
}
return isEdit.value ? '编辑用户' : '新增用户';
});
const needHospital = computed(() => form.role && form.role !== 'SYSTEM_ADMIN');
const needDepartment = computed(() =>
['DIRECTOR', 'LEADER', 'DOCTOR'].includes(form.role),
);
const needGroup = computed(() =>
['LEADER', 'DOCTOR'].includes(form.role),
const needGroup = computed(() => ['LEADER', 'DOCTOR'].includes(form.role));
const lockHospital = computed(() =>
['HOSPITAL_ADMIN', 'DIRECTOR'].includes(userStore.role),
);
const lockDepartment = computed(() => isDirector.value);
const rules = computed(() => ({
name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
@ -299,9 +352,9 @@ const rules = computed(() => ({
password: isEdit.value
? []
: [
{ required: true, message: '请输入密码', trigger: 'blur' },
{ min: 8, message: '密码长度至少为 8 位', trigger: 'blur' },
],
{ required: true, message: '请输入密码', trigger: 'blur' },
{ min: 8, message: '密码长度至少为 8 位', trigger: 'blur' },
],
role: [{ required: true, message: '请选择角色', trigger: 'change' }],
hospitalId: needHospital.value
? [{ required: true, message: '请选择所属医院', trigger: 'change' }]
@ -318,7 +371,7 @@ const roleMap = {
SYSTEM_ADMIN: '系统管理员',
HOSPITAL_ADMIN: '医院管理员',
DIRECTOR: '科室主任',
LEADER: '医疗组长',
LEADER: '小组组长',
DOCTOR: '医生',
ENGINEER: '工程师',
};
@ -332,14 +385,14 @@ const getRoleTagType = (role) => {
return 'info';
};
const hospitalMap = computed(() =>
new Map(hospitals.value.map((item) => [item.id, item.name])),
const hospitalMap = computed(
() => new Map(hospitals.value.map((item) => [item.id, item.name])),
);
const departmentMap = computed(() =>
new Map(departments.value.map((item) => [item.id, item.name])),
const departmentMap = computed(
() => new Map(departments.value.map((item) => [item.id, item.name])),
);
const groupMap = computed(() =>
new Map(groups.value.map((item) => [item.id, item.name])),
const groupMap = computed(
() => new Map(groups.value.map((item) => [item.id, item.name])),
);
const resolveHospitalName = (id) => {
@ -357,6 +410,16 @@ const resolveGroupName = (id) => {
return groupMap.value.get(id) || `#${id}`;
};
const resolveDirectorScope = () => {
const hospitalId = userStore.userInfo?.hospitalId || null;
const departmentId = userStore.userInfo?.departmentId || null;
if (!hospitalId || !departmentId) {
ElMessage.error('当前主任账号缺少医院或科室归属');
return null;
}
return { hospitalId, departmentId };
};
const fetchCommonData = async () => {
const [hospitalRes, departmentRes, groupRes] = await Promise.all([
getHospitals({ page: 1, pageSize: 100 }),
@ -405,7 +468,7 @@ const fetchData = async () => {
const res = await getUsers({
page: page.value,
pageSize: pageSize.value,
role: searchForm.role || undefined,
role: (isDirector.value ? 'DOCTOR' : searchForm.role) || undefined,
keyword: searchForm.keyword || undefined,
});
tableData.value = res.list || [];
@ -422,15 +485,29 @@ const handleSearch = () => {
const resetSearch = () => {
searchForm.keyword = '';
searchForm.role = '';
searchForm.role = isDirector.value ? 'DOCTOR' : '';
page.value = 1;
fetchData();
};
const openCreateDialog = async () => {
resetForm();
isEdit.value = false;
currentId.value = null;
dialogVisible.value = true;
if (isDirector.value) {
const directorScope = resolveDirectorScope();
if (!directorScope) {
return;
}
form.role = 'DOCTOR';
form.hospitalId = directorScope.hospitalId;
await fetchDepartmentsForForm(form.hospitalId);
form.departmentId = directorScope.departmentId;
await fetchGroupsForForm(form.departmentId);
dialogVisible.value = true;
return;
}
if (userStore.role === 'HOSPITAL_ADMIN') {
form.hospitalId = userStore.userInfo?.hospitalId || null;
@ -438,9 +515,16 @@ const openCreateDialog = async () => {
await fetchDepartmentsForForm(form.hospitalId);
}
}
dialogVisible.value = true;
};
const openEditDialog = async (row) => {
if (isDirector.value && row.role !== 'DOCTOR') {
ElMessage.warning('主任仅可编辑本科室医生');
return;
}
isEdit.value = true;
currentId.value = row.id;
@ -483,6 +567,31 @@ const resetForm = () => {
};
const buildSubmitPayload = () => {
if (isDirector.value) {
const directorScope = resolveDirectorScope();
if (!directorScope) {
return null;
}
const payload = {
name: form.name,
phone: form.phone,
role: 'DOCTOR',
hospitalId: directorScope.hospitalId,
departmentId: directorScope.departmentId,
groupId: form.groupId,
};
if (!isEdit.value) {
return {
...payload,
password: form.password,
};
}
return payload;
}
const payload = {
name: form.name,
phone: form.phone,
@ -553,6 +662,9 @@ const handleSubmit = async () => {
submitLoading.value = true;
try {
const payload = buildSubmitPayload();
if (!payload) {
return;
}
if (isEdit.value) {
await updateUser(currentId.value, payload);
ElMessage.success('更新成功');
@ -570,15 +682,16 @@ const handleSubmit = async () => {
};
const handleDelete = (row) => {
ElMessageBox.confirm(
`确定要删除用户 "${row.name}" 吗?`,
'警告',
{
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
},
)
if (isDirector.value && row.role !== 'DOCTOR') {
ElMessage.warning('主任仅可删除本科室医生');
return;
}
ElMessageBox.confirm(`确定要删除用户 "${row.name}" 吗?`, '警告', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning',
})
.then(async () => {
await deleteUser(row.id);
ElMessage.success('删除成功');
@ -601,7 +714,10 @@ const handleAssignSubmit = async () => {
submitLoading.value = true;
try {
await assignEngineerHospital(currentAssignUser.value.id, assignHospitalId.value);
await assignEngineerHospital(
currentAssignUser.value.id,
assignHospitalId.value,
);
ElMessage.success('分配成功');
assignDialogVisible.value = false;
await fetchCommonData();
@ -677,16 +793,24 @@ onMounted(async () => {
if (route.query.action === 'create') {
await openCreateDialog();
if (route.query.hospitalId) {
if (!isDirector.value && route.query.hospitalId) {
form.hospitalId = Number(route.query.hospitalId);
await fetchDepartmentsForForm(form.hospitalId);
}
if (route.query.departmentId) {
if (!isDirector.value && route.query.departmentId) {
form.departmentId = Number(route.query.departmentId);
await fetchGroupsForForm(form.departmentId);
}
}
});
const canDeleteUser = (row) => {
if (userStore.role === 'SYSTEM_ADMIN') {
return true;
}
return isDirector.value && row.role === 'DOCTOR';
};
</script>
<style scoped>