新增 B 端设备模块(后端 CRUD、分页筛选、权限隔离)并接入前端设备管理页面与路由菜单

鉴权改为登录态回库校验,新增 tokenValidAfter 失效时间,支持密码变更与 seed 重置后旧 token 立即失效
患者字段由 idCardHash 统一迁移为 idCard,新增身份证标准化逻辑并同步 C 端生命周期查询参数
组织模块增加小组删除限制(有成员时返回 409)并补充中文错误消息
任务取消接口支持可选 reason 字段(先透传事件层)
补齐 Prisma 迁移、文档说明和 E2E 用例(含设备模块与 token 失效场景)
This commit is contained in:
EL 2026-03-18 20:23:55 +08:00
parent 5fdf4c80e6
commit 6ec2d0b0e0
46 changed files with 1838 additions and 220 deletions

View File

@ -14,14 +14,17 @@
## 3. 鉴权流程 ## 3. 鉴权流程
1. `AccessTokenGuard``Authorization` 读取 Bearer Token。 1. `AccessTokenGuard``Authorization` 读取 Bearer Token。
2. 校验 JWT 签名与载荷字段。 2. 校验 JWT 签名、`id``iat` 等关键载荷字段。
3. 载荷映射为 `ActorContext` 注入 `request.actor` 3. 根据 `id` 回库读取用户当前角色与组织归属,不再直接信任 token 里的角色和范围。
4. `RolesGuard` 根据 `@Roles(...)` 判断角色是否允许访问。 4. 校验 `iat >= user.tokenValidAfter`若用户被重置密码、seed 重刷或账号被清理,则旧 token 立即失效。
5. 当前数据库用户映射为 `ActorContext` 注入 `request.actor`
6. `RolesGuard` 根据 `@Roles(...)` 判断角色是否允许访问。
## 4. Token 约定 ## 4. Token 约定
- Header`Authorization: Bearer <token>` - Header`Authorization: Bearer <token>`
- 载荷关键字段:`id``role``hospitalId``departmentId``groupId` - 载荷关键字段:`id``iat`
- 角色和组织范围以数据库当前用户记录为准,不以 token 历史载荷为准
## 5. 错误码与中文消息 ## 5. 错误码与中文消息
@ -30,3 +33,8 @@
- 参数非法:`400` + 中文 `msg` - 参数非法:`400` + 中文 `msg`
统一由全局异常过滤器输出:`{ code, msg, data: null }` 统一由全局异常过滤器输出:`{ 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` 2. `node prisma/seed.mjs`
这会清空 `.env``DATABASE_URL` 指向数据库的全部数据,请仅在测试库执行。 这会清空 `.env``DATABASE_URL` 指向数据库的全部数据,请仅在测试库执行。
另外seed 账号会刷新 `tokenValidAfter`,所以重置前签发的旧 token 会全部失效,需要重新登录获取新 token。
## 3. 运行命令 ## 3. 运行命令

View File

@ -4,16 +4,21 @@
- 登录页:`/auth/login`,支持可选 `hospitalId` - 登录页:`/auth/login`,支持可选 `hospitalId`
- 首页看板:按角色拉取组织与患者统计。 - 首页看板:按角色拉取组织与患者统计。
- 设备页:新增管理员专用设备 CRUD复用真实设备接口。
- 任务页:接入 `publish/accept/complete/cancel` 四个真实任务接口。 - 任务页:接入 `publish/accept/complete/cancel` 四个真实任务接口。
- 用户页:修复用户列表响应结构、组织字段联动、工程师分配医院参数。 - 用户页:修复用户列表响应结构、组织字段联动、工程师分配医院参数。
- 患者页:接入真实患者字段与生命周期查询参数(`phone + idCardHash`)。 - 患者页:接入真实患者字段与生命周期查询参数(`phone + idCard`
后端直接保存身份证号原文,不再做哈希转换。
## 2. 接口契约对齐点 ## 2. 接口契约对齐点
- `GET /users` 当前返回数组,前端已在 `api/users.js` 做本地分页与筛选适配。 - `GET /users` 当前返回数组,前端已在 `api/users.js` 做本地分页与筛选适配。
- `PATCH /b/users/:id/assign-engineer-hospital` 参数为单个 `hospitalId`,非数组。 - `PATCH /b/users/:id/assign-engineer-hospital` 参数为单个 `hospitalId`,非数组。
- `GET /b/patients` 返回数组,前端已改为本地分页与筛选。 - `GET /b/patients` 返回数组,前端已改为本地分页与筛选。
- `GET /c/patients/lifecycle` 必须同时传 `phone``idCardHash` - `GET /b/devices` 已支持服务端分页与筛选,前端直接透传 `page/pageSize`
- `GET /c/patients/lifecycle` 必须同时传 `phone``idCard`
- 患者表单中的 `idCard` 字段直接传身份证号;
服务端只会做去空格与 `x/X` 标准化,不会转哈希。
- 任务模块暂无任务列表接口,前端改为“表单操作 + 最近结果”模式。 - 任务模块暂无任务列表接口,前端改为“表单操作 + 最近结果”模式。
## 3. 角色权限提示 ## 3. 角色权限提示
@ -38,12 +43,13 @@
- `organization/tree``organization/departments``organization/groups` - `organization/tree``organization/departments``organization/groups`
`SYSTEM_ADMIN``HOSPITAL_ADMIN``DIRECTOR``LEADER` 可访问 `SYSTEM_ADMIN``HOSPITAL_ADMIN``DIRECTOR``LEADER` 可访问
- `users`:仅 `SYSTEM_ADMIN``HOSPITAL_ADMIN` 可访问 - `users`:仅 `SYSTEM_ADMIN``HOSPITAL_ADMIN` 可访问
- `devices`:仅 `SYSTEM_ADMIN``HOSPITAL_ADMIN` 可访问
- `organization/hospitals` - `organization/hospitals`
- 仅 `SYSTEM_ADMIN` 可访问 - 仅 `SYSTEM_ADMIN` 可访问
- `tasks` - `tasks`
- 仅 `DOCTOR``DIRECTOR``LEADER``ENGINEER` 可访问 - 仅 `DOCTOR``DIRECTOR``LEADER``ENGINEER` 可访问
- `patients` - `patients`
- `SYSTEM_ADMIN``HOSPITAL_ADMIN``DIRECTOR``LEADER` 可访问 - `SYSTEM_ADMIN``HOSPITAL_ADMIN``DIRECTOR``LEADER`、`DOCTOR` 可访问
前端已在路由守卫和侧边栏菜单同时做权限控制,无权限角色会被拦截并跳转到首页,避免进入页面后触发接口 `403` 前端已在路由守卫和侧边栏菜单同时做权限控制,无权限角色会被拦截并跳转到首页,避免进入页面后触发接口 `403`

View File

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

View File

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

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

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

View File

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

View File

@ -5,25 +5,25 @@ import {
UnauthorizedException, UnauthorizedException,
} from '@nestjs/common'; } from '@nestjs/common';
import jwt from 'jsonwebtoken'; import jwt from 'jsonwebtoken';
import { Role } from '../generated/prisma/enums.js';
import type { ActorContext } from '../common/actor-context.js'; import type { ActorContext } from '../common/actor-context.js';
import { MESSAGES } from '../common/messages.js'; import { MESSAGES } from '../common/messages.js';
import { PrismaService } from '../prisma.service.js';
/** /**
* AccessToken Bearer JWT actor request * AccessToken Bearer JWT actor request
*/ */
@Injectable() @Injectable()
export class AccessTokenGuard implements CanActivate { export class AccessTokenGuard implements CanActivate {
constructor(private readonly prisma: PrismaService) {}
/** /**
* true 401 * true 401
*/ */
canActivate(context: ExecutionContext): boolean { async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest< const request = context.switchToHttp().getRequest<{
{
headers: Record<string, string | string[] | undefined>; headers: Record<string, string | string[] | undefined>;
actor?: unknown; actor?: unknown;
} }>();
>();
const authorization = request.headers.authorization; const authorization = request.headers.authorization;
const headerValue = Array.isArray(authorization) const headerValue = Array.isArray(authorization)
@ -35,15 +35,15 @@ export class AccessTokenGuard implements CanActivate {
} }
const token = headerValue.slice('Bearer '.length).trim(); const token = headerValue.slice('Bearer '.length).trim();
request.actor = this.verifyAndExtractActor(token); request.actor = await this.verifyAndExtractActor(token);
return true; return true;
} }
/** /**
* token actor * token
*/ */
private verifyAndExtractActor(token: string): ActorContext { private async verifyAndExtractActor(token: string): Promise<ActorContext> {
const secret = process.env.AUTH_TOKEN_SECRET; const secret = process.env.AUTH_TOKEN_SECRET;
if (!secret) { if (!secret) {
throw new UnauthorizedException(MESSAGES.AUTH.TOKEN_SECRET_MISSING); 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); throw new UnauthorizedException(MESSAGES.AUTH.TOKEN_PAYLOAD_INVALID);
} }
const role = payload.role; const userId = this.asInt(payload.id, 'id');
if (typeof role !== 'string' || !Object.values(Role).includes(role as Role)) { const issuedAt = this.asInt(payload.iat, 'iat');
throw new UnauthorizedException(MESSAGES.AUTH.TOKEN_ROLE_INVALID); 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 { return {
id: this.asInt(payload.id, 'id'), id: user.id,
role: role as Role, role: user.role,
hospitalId: this.asNullableInt(payload.hospitalId, 'hospitalId'), hospitalId: user.hospitalId,
departmentId: this.asNullableInt(payload.departmentId, 'departmentId'), departmentId: user.departmentId,
groupId: this.asNullableInt(payload.groupId, 'groupId'), groupId: user.groupId,
}; };
} }
@ -82,20 +104,9 @@ export class AccessTokenGuard implements CanActivate {
*/ */
private asInt(value: unknown, field: string): number { private asInt(value: unknown, field: string): number {
if (typeof value !== 'number' || !Number.isInteger(value)) { 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; );
}
/**
* 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}`);
} }
return value; return value;
} }

View File

@ -21,6 +21,8 @@ export const MESSAGES = {
TOKEN_SECRET_MISSING: '服务端未配置认证密钥', TOKEN_SECRET_MISSING: '服务端未配置认证密钥',
TOKEN_INVALID: 'Token 无效或已过期', TOKEN_INVALID: 'Token 无效或已过期',
TOKEN_PAYLOAD_INVALID: 'Token 载荷不合法', TOKEN_PAYLOAD_INVALID: 'Token 载荷不合法',
TOKEN_USER_NOT_FOUND: 'Token 对应用户不存在,请重新登录',
TOKEN_REVOKED: 'Token 已失效,请重新登录',
TOKEN_ROLE_INVALID: 'Token 中角色信息不合法', TOKEN_ROLE_INVALID: 'Token 中角色信息不合法',
TOKEN_FIELD_INVALID: 'Token 中字段不合法', TOKEN_FIELD_INVALID: 'Token 中字段不合法',
INVALID_CREDENTIALS: '手机号、角色或密码错误', INVALID_CREDENTIALS: '手机号、角色或密码错误',
@ -82,12 +84,25 @@ export const MESSAGES = {
DOCTOR_ROLE_REQUIRED: '归属用户必须为医生/主任/组长角色', DOCTOR_ROLE_REQUIRED: '归属用户必须为医生/主任/组长角色',
DOCTOR_SCOPE_FORBIDDEN: '仅可选择当前权限范围内医生/主任/组长', DOCTOR_SCOPE_FORBIDDEN: '仅可选择当前权限范围内医生/主任/组长',
DELETE_CONFLICT: '患者存在关联设备,无法删除', DELETE_CONFLICT: '患者存在关联设备,无法删除',
PHONE_IDCARD_REQUIRED: 'phone 与 idCardHash 均为必填', PHONE_IDCARD_REQUIRED: 'phone 与 idCard 均为必填',
LIFE_CYCLE_NOT_FOUND: '未找到匹配的患者档案,请先确认手机号与身份证哈希', LIFE_CYCLE_NOT_FOUND: '未找到匹配的患者档案,请先确认手机号与身份证',
SYSTEM_ADMIN_HOSPITAL_REQUIRED: '系统管理员查询必须显式传入 hospitalId', SYSTEM_ADMIN_HOSPITAL_REQUIRED: '系统管理员查询必须显式传入 hospitalId',
ACTOR_HOSPITAL_REQUIRED: '当前登录上下文缺少医院信息', 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: { ORG: {
HOSPITAL_NOT_FOUND: '医院不存在', HOSPITAL_NOT_FOUND: '医院不存在',
DEPARTMENT_NOT_FOUND: '科室不存在', DEPARTMENT_NOT_FOUND: '科室不存在',
@ -108,6 +123,7 @@ export const MESSAGES = {
GROUP_DEPARTMENT_MISMATCH: '小组不属于指定科室', GROUP_DEPARTMENT_MISMATCH: '小组不属于指定科室',
DEPARTMENT_REPARENT_FORBIDDEN: '科室不允许更换所属医院', DEPARTMENT_REPARENT_FORBIDDEN: '科室不允许更换所属医院',
GROUP_REPARENT_FORBIDDEN: '小组不允许更换所属科室', GROUP_REPARENT_FORBIDDEN: '小组不允许更换所属科室',
GROUP_DELETE_HAS_USERS: '小组下仍有成员,无法删除,请先调整用户归属',
DELETE_CONFLICT: 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 { import {
BadRequestException, BadRequestException,
ConflictException,
ForbiddenException, ForbiddenException,
Injectable, Injectable,
NotFoundException, NotFoundException,
@ -33,7 +34,10 @@ export class GroupsService {
Role.HOSPITAL_ADMIN, Role.HOSPITAL_ADMIN,
Role.DIRECTOR, 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); const department = await this.access.ensureDepartmentExists(departmentId);
if (actor.role === Role.HOSPITAL_ADMIN) { if (actor.role === Role.HOSPITAL_ADMIN) {
this.access.assertHospitalScope(actor, department.hospitalId); this.access.assertHospitalScope(actor, department.hospitalId);
@ -47,7 +51,10 @@ export class GroupsService {
return this.prisma.group.create({ return this.prisma.group.create({
data: { data: {
name: this.access.normalizeName(dto.name, MESSAGES.ORG.GROUP_NAME_REQUIRED), name: this.access.normalizeName(
dto.name,
MESSAGES.ORG.GROUP_NAME_REQUIRED,
),
departmentId, departmentId,
}, },
}); });
@ -70,18 +77,26 @@ export class GroupsService {
where.name = { contains: query.keyword.trim(), mode: 'insensitive' }; where.name = { contains: query.keyword.trim(), mode: 'insensitive' };
} }
if (query.departmentId != null) { 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) { 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) { } else if (actor.role === Role.DIRECTOR) {
where.departmentId = this.access.requireActorDepartmentId(actor); where.departmentId = this.access.requireActorDepartmentId(actor);
} else if (actor.role === Role.LEADER) { } else if (actor.role === Role.LEADER) {
where.id = this.access.requireActorGroupId(actor); where.id = this.access.requireActorGroupId(actor);
} else if (query.hospitalId != null) { } else if (query.hospitalId != null) {
where.department = { 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) { 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({ return this.prisma.group.update({
@ -172,6 +190,12 @@ export class GroupsService {
Role.DIRECTOR, Role.DIRECTOR,
]); ]);
const current = await this.findOne(actor, id); const current = await this.findOne(actor, id);
// 业务层先拦截,给前端稳定中文提示;数据库层仍保留 RESTRICT 兜底。
if (current._count.users > 0) {
throw new ConflictException(MESSAGES.ORG.GROUP_DELETE_HAS_USERS);
}
try { try {
return await this.prisma.group.delete({ where: { id: current.id } }); return await this.prisma.group.delete({ where: { id: current.id } });
} catch (error) { } catch (error) {

View File

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

View File

@ -20,16 +20,16 @@ export class CPatientsController {
constructor(private readonly patientsService: CPatientsService) {} constructor(private readonly patientsService: CPatientsService) {}
/** /**
* *
*/ */
@Get('lifecycle') @Get('lifecycle')
@ApiOperation({ summary: '跨院患者生命周期查询' }) @ApiOperation({ summary: '跨院患者生命周期查询' })
@ApiQuery({ name: 'phone', description: '手机号' }) @ApiQuery({ name: 'phone', description: '手机号' })
@ApiQuery({ name: 'idCardHash', description: '身份证哈希' }) @ApiQuery({ name: 'idCard', description: '身份证' })
getLifecycle(@Query() query: FamilyLifecycleQueryDto) { getLifecycle(@Query() query: FamilyLifecycleQueryDto) {
return this.patientsService.getFamilyLifecycleByIdentity( return this.patientsService.getFamilyLifecycleByIdentity(
query.phone, query.phone,
query.idCardHash, query.idCard,
); );
} }
} }

View File

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

View File

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

View File

@ -10,7 +10,10 @@ export class FamilyLifecycleQueryDto {
@Matches(/^1\d{10}$/, { message: 'phone 必须是合法手机号' }) @Matches(/^1\d{10}$/, { message: 'phone 必须是合法手机号' })
phone!: string; phone!: string;
@ApiProperty({ description: '身份证哈希值', example: 'seed-id-card-hash' }) @ApiProperty({
@IsString({ message: 'idCardHash 必须是字符串' }) description: '身份证号原文',
idCardHash!: string; 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 { ApiProperty } from '@nestjs/swagger';
import { Type } from 'class-transformer'; import { Type } from 'class-transformer';
import { IsInt, Min } from 'class-validator'; import { IsInt, IsOptional, IsString, MaxLength, Min } from 'class-validator';
/** /**
* DTO * DTO
@ -11,4 +11,14 @@ export class CancelTaskDto {
@IsInt({ message: 'taskId 必须是整数' }) @IsInt({ message: 'taskId 必须是整数' })
@Min(1, { message: 'taskId 必须大于 0' }) @Min(1, { message: 'taskId 必须大于 0' })
taskId!: number; taskId!: number;
@ApiProperty({
description: '取消原因(可选,当前仅用于接口兼容与后续通知扩展)',
example: '后台手动取消',
required: false,
})
@IsOptional()
@IsString({ message: 'reason 必须是字符串' })
@MaxLength(100, { message: 'reason 长度不能超过 100 个字符' })
reason?: string;
} }

View File

@ -275,6 +275,8 @@ export class TaskService {
hospitalId: cancelledTask.hospitalId, hospitalId: cancelledTask.hospitalId,
actorId: actor.id, actorId: actor.id,
status: cancelledTask.status, status: cancelledTask.status,
// 当前库表未持久化取消原因,但先透传到事件层,方便通知链路后续接入。
reason: dto.reason?.trim() || null,
}); });
return cancelledTask; return cancelledTask;

View File

@ -337,10 +337,12 @@ export class UsersService {
data.openId = nextOpenId; data.openId = nextOpenId;
} }
if (updateUserDto.password) { if (updateUserDto.password) {
// 密码变更后立即吊销旧 token避免旧会话继续使用。
data.passwordHash = await hash( data.passwordHash = await hash(
this.normalizePassword(updateUserDto.password), this.normalizePassword(updateUserDto.password),
12, 12,
); );
data.tokenValidAfter = new Date();
} }
return this.prisma.user.update({ return this.prisma.user.update({

View File

@ -81,16 +81,14 @@ async function requirePatientId(
prisma: PrismaService, prisma: PrismaService,
hospitalId: number, hospitalId: number,
phone: string, phone: string,
idCardHash: string, idCard: string,
): Promise<number> { ): Promise<number> {
const patient = await prisma.patient.findFirst({ const patient = await prisma.patient.findFirst({
where: { hospitalId, phone, idCardHash }, where: { hospitalId, phone, idCard },
select: { id: true }, select: { id: true },
}); });
if (!patient) { if (!patient) {
throw new NotFoundException( throw new NotFoundException(`Seed patient not found: ${phone}/${idCard}`);
`Seed patient not found: ${phone}/${idCardHash}`,
);
} }
return patient.id; return patient.id;
} }
@ -163,25 +161,25 @@ export async function loadSeedFixtures(
prisma, prisma,
hospitalAId, hospitalAId,
'13800002001', '13800002001',
'seed-id-card-cross-hospital', '110101199001010011',
), ),
patientA2Id: await requirePatientId( patientA2Id: await requirePatientId(
prisma, prisma,
hospitalAId, hospitalAId,
'13800002002', '13800002002',
'seed-id-card-a2', '110101199002020022',
), ),
patientA3Id: await requirePatientId( patientA3Id: await requirePatientId(
prisma, prisma,
hospitalAId, hospitalAId,
'13800002003', '13800002003',
'seed-id-card-a3', '110101199003030033',
), ),
patientB1Id: await requirePatientId( patientB1Id: await requirePatientId(
prisma, prisma,
hospitalBId, hospitalBId,
'13800002001', '13800002001',
'seed-id-card-cross-hospital', '110101199001010011',
), ),
}, },
devices: { 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); await closeE2EContext(ctx);
}); });
describe('POST /auth/register', () => { describe('POST /auth/system-admin', () => {
it('成功:注册医生账号', async () => { it('成功:创建系统管理员账号', async () => {
const response = await request(ctx.app.getHttpServer()) const response = await request(ctx.app.getHttpServer())
.post('/auth/register') .post('/auth/system-admin')
.send({ .send({
name: uniqueSeedValue('Auth 注册医生'), name: uniqueSeedValue('Auth 系统管理员'),
phone: uniquePhone(), phone: uniquePhone(),
password: 'Seed@1234', password: 'Seed@1234',
role: Role.DOCTOR, openId: uniqueSeedValue('auth-system-admin-openid'),
hospitalId: ctx.fixtures.hospitalAId, systemAdminBootstrapKey: process.env.SYSTEM_ADMIN_BOOTSTRAP_KEY,
departmentId: ctx.fixtures.departmentA1Id,
groupId: ctx.fixtures.groupA1Id,
openId: uniqueSeedValue('auth-register-openid'),
}); });
expectSuccessEnvelope(response, 201); expectSuccessEnvelope(response, 201);
expect(response.body.data.role).toBe(Role.DOCTOR); expect(response.body.data.role).toBe(Role.SYSTEM_ADMIN);
}); });
it('失败:参数不合法返回 400', async () => { it('失败:参数不合法返回 400', async () => {
const response = await request(ctx.app.getHttpServer()) const response = await request(ctx.app.getHttpServer())
.post('/auth/register') .post('/auth/system-admin')
.send({ .send({
name: 'bad-register', name: 'bad-system-admin',
phone: '13800009999', phone: '13800009999',
password: '123', password: '123',
role: Role.DOCTOR, systemAdminBootstrapKey: process.env.SYSTEM_ADMIN_BOOTSTRAP_KEY,
hospitalId: ctx.fixtures.hospitalAId,
departmentId: ctx.fixtures.departmentA1Id,
groupId: ctx.fixtures.groupA1Id,
}); });
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'); 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({ await assertRoleMatrix({
name: 'GET /b/organization/hospitals role matrix', name: 'GET /b/organization/hospitals role matrix',
tokens: ctx.tokens, tokens: ctx.tokens,
expectedStatusByRole: { expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 200, [Role.SYSTEM_ADMIN]: 200,
[Role.HOSPITAL_ADMIN]: 200, [Role.HOSPITAL_ADMIN]: 200,
[Role.DIRECTOR]: 403, [Role.DIRECTOR]: 200,
[Role.LEADER]: 403, [Role.LEADER]: 200,
[Role.DOCTOR]: 403, [Role.DOCTOR]: 403,
[Role.ENGINEER]: 403, [Role.ENGINEER]: 403,
}, },
@ -126,15 +126,15 @@ describe('Organization Controllers (e2e)', () => {
expectErrorEnvelope(response, 403, '院管仅可操作本院组织数据'); expectErrorEnvelope(response, 403, '院管仅可操作本院组织数据');
}); });
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN 可访问,其他角色 403未登录 401', async () => { it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN/DIRECTOR/LEADER 可访问,其余角色 403未登录 401', async () => {
await assertRoleMatrix({ await assertRoleMatrix({
name: 'GET /b/organization/hospitals/:id role matrix', name: 'GET /b/organization/hospitals/:id role matrix',
tokens: ctx.tokens, tokens: ctx.tokens,
expectedStatusByRole: { expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 200, [Role.SYSTEM_ADMIN]: 200,
[Role.HOSPITAL_ADMIN]: 200, [Role.HOSPITAL_ADMIN]: 200,
[Role.DIRECTOR]: 403, [Role.DIRECTOR]: 200,
[Role.LEADER]: 403, [Role.LEADER]: 200,
[Role.DOCTOR]: 403, [Role.DOCTOR]: 403,
[Role.ENGINEER]: 403, [Role.ENGINEER]: 403,
}, },
@ -321,15 +321,15 @@ describe('Organization Controllers (e2e)', () => {
expectErrorEnvelope(response, 401, '缺少 Bearer Token'); 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({ await assertRoleMatrix({
name: 'GET /b/organization/departments role matrix', name: 'GET /b/organization/departments role matrix',
tokens: ctx.tokens, tokens: ctx.tokens,
expectedStatusByRole: { expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 200, [Role.SYSTEM_ADMIN]: 200,
[Role.HOSPITAL_ADMIN]: 200, [Role.HOSPITAL_ADMIN]: 200,
[Role.DIRECTOR]: 403, [Role.DIRECTOR]: 200,
[Role.LEADER]: 403, [Role.LEADER]: 200,
[Role.DOCTOR]: 403, [Role.DOCTOR]: 403,
[Role.ENGINEER]: 403, [Role.ENGINEER]: 403,
}, },
@ -361,15 +361,15 @@ describe('Organization Controllers (e2e)', () => {
expectErrorEnvelope(response, 403, '院管仅可操作本院组织数据'); expectErrorEnvelope(response, 403, '院管仅可操作本院组织数据');
}); });
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN 可访问,其他角色 403未登录 401', async () => { it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN/DIRECTOR/LEADER 可访问,其余角色 403未登录 401', async () => {
await assertRoleMatrix({ await assertRoleMatrix({
name: 'GET /b/organization/departments/:id role matrix', name: 'GET /b/organization/departments/:id role matrix',
tokens: ctx.tokens, tokens: ctx.tokens,
expectedStatusByRole: { expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 200, [Role.SYSTEM_ADMIN]: 200,
[Role.HOSPITAL_ADMIN]: 200, [Role.HOSPITAL_ADMIN]: 200,
[Role.DIRECTOR]: 403, [Role.DIRECTOR]: 200,
[Role.LEADER]: 403, [Role.LEADER]: 200,
[Role.DOCTOR]: 403, [Role.DOCTOR]: 403,
[Role.ENGINEER]: 403, [Role.ENGINEER]: 403,
}, },
@ -413,15 +413,15 @@ describe('Organization Controllers (e2e)', () => {
expectErrorEnvelope(response, 403, '院管仅可操作本院组织数据'); expectErrorEnvelope(response, 403, '院管仅可操作本院组织数据');
}); });
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN 可进入业务,其他角色 403未登录 401', async () => { it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN/DIRECTOR/LEADER 可进入业务,其余角色 403未登录 401', async () => {
await assertRoleMatrix({ await assertRoleMatrix({
name: 'PATCH /b/organization/departments/:id role matrix', name: 'PATCH /b/organization/departments/:id role matrix',
tokens: ctx.tokens, tokens: ctx.tokens,
expectedStatusByRole: { expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 404, [Role.SYSTEM_ADMIN]: 404,
[Role.HOSPITAL_ADMIN]: 404, [Role.HOSPITAL_ADMIN]: 404,
[Role.DIRECTOR]: 403, [Role.DIRECTOR]: 404,
[Role.LEADER]: 403, [Role.LEADER]: 404,
[Role.DOCTOR]: 403, [Role.DOCTOR]: 403,
[Role.ENGINEER]: 403, [Role.ENGINEER]: 403,
}, },
@ -516,14 +516,14 @@ describe('Organization Controllers (e2e)', () => {
expectErrorEnvelope(response, 403, '院管仅可操作本院组织数据'); expectErrorEnvelope(response, 403, '院管仅可操作本院组织数据');
}); });
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN 可进入业务,其他角色 403未登录 401', async () => { it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN/DIRECTOR 可进入业务,其余角色 403未登录 401', async () => {
await assertRoleMatrix({ await assertRoleMatrix({
name: 'POST /b/organization/groups role matrix', name: 'POST /b/organization/groups role matrix',
tokens: ctx.tokens, tokens: ctx.tokens,
expectedStatusByRole: { expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 400, [Role.SYSTEM_ADMIN]: 400,
[Role.HOSPITAL_ADMIN]: 400, [Role.HOSPITAL_ADMIN]: 400,
[Role.DIRECTOR]: 403, [Role.DIRECTOR]: 400,
[Role.LEADER]: 403, [Role.LEADER]: 403,
[Role.DOCTOR]: 403, [Role.DOCTOR]: 403,
[Role.ENGINEER]: 403, [Role.ENGINEER]: 403,
@ -558,15 +558,15 @@ describe('Organization Controllers (e2e)', () => {
expectErrorEnvelope(response, 401, '缺少 Bearer Token'); 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({ await assertRoleMatrix({
name: 'GET /b/organization/groups role matrix', name: 'GET /b/organization/groups role matrix',
tokens: ctx.tokens, tokens: ctx.tokens,
expectedStatusByRole: { expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 200, [Role.SYSTEM_ADMIN]: 200,
[Role.HOSPITAL_ADMIN]: 200, [Role.HOSPITAL_ADMIN]: 200,
[Role.DIRECTOR]: 403, [Role.DIRECTOR]: 200,
[Role.LEADER]: 403, [Role.LEADER]: 200,
[Role.DOCTOR]: 403, [Role.DOCTOR]: 403,
[Role.ENGINEER]: 403, [Role.ENGINEER]: 403,
}, },
@ -598,15 +598,15 @@ describe('Organization Controllers (e2e)', () => {
expectErrorEnvelope(response, 403, '院管仅可操作本院组织数据'); expectErrorEnvelope(response, 403, '院管仅可操作本院组织数据');
}); });
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN 可访问,其他角色 403未登录 401', async () => { it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN/DIRECTOR/LEADER 可访问,其余角色 403未登录 401', async () => {
await assertRoleMatrix({ await assertRoleMatrix({
name: 'GET /b/organization/groups/:id role matrix', name: 'GET /b/organization/groups/:id role matrix',
tokens: ctx.tokens, tokens: ctx.tokens,
expectedStatusByRole: { expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 200, [Role.SYSTEM_ADMIN]: 200,
[Role.HOSPITAL_ADMIN]: 200, [Role.HOSPITAL_ADMIN]: 200,
[Role.DIRECTOR]: 403, [Role.DIRECTOR]: 200,
[Role.LEADER]: 403, [Role.LEADER]: 200,
[Role.DOCTOR]: 403, [Role.DOCTOR]: 403,
[Role.ENGINEER]: 403, [Role.ENGINEER]: 403,
}, },
@ -650,15 +650,15 @@ describe('Organization Controllers (e2e)', () => {
expectErrorEnvelope(response, 403, '院管仅可操作本院组织数据'); expectErrorEnvelope(response, 403, '院管仅可操作本院组织数据');
}); });
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN 可进入业务,其他角色 403未登录 401', async () => { it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN/DIRECTOR/LEADER 可进入业务,其余角色 403未登录 401', async () => {
await assertRoleMatrix({ await assertRoleMatrix({
name: 'PATCH /b/organization/groups/:id role matrix', name: 'PATCH /b/organization/groups/:id role matrix',
tokens: ctx.tokens, tokens: ctx.tokens,
expectedStatusByRole: { expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 404, [Role.SYSTEM_ADMIN]: 404,
[Role.HOSPITAL_ADMIN]: 404, [Role.HOSPITAL_ADMIN]: 404,
[Role.DIRECTOR]: 403, [Role.DIRECTOR]: 404,
[Role.LEADER]: 403, [Role.LEADER]: 404,
[Role.DOCTOR]: 403, [Role.DOCTOR]: 403,
[Role.ENGINEER]: 403, [Role.ENGINEER]: 403,
}, },
@ -702,14 +702,22 @@ describe('Organization Controllers (e2e)', () => {
expectErrorEnvelope(response, 403, '院管仅可操作本院组织数据'); 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({ await assertRoleMatrix({
name: 'DELETE /b/organization/groups/:id role matrix', name: 'DELETE /b/organization/groups/:id role matrix',
tokens: ctx.tokens, tokens: ctx.tokens,
expectedStatusByRole: { expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 404, [Role.SYSTEM_ADMIN]: 404,
[Role.HOSPITAL_ADMIN]: 404, [Role.HOSPITAL_ADMIN]: 404,
[Role.DIRECTOR]: 403, [Role.DIRECTOR]: 404,
[Role.LEADER]: 403, [Role.LEADER]: 403,
[Role.DOCTOR]: 403, [Role.DOCTOR]: 403,
[Role.ENGINEER]: 403, [Role.ENGINEER]: 403,

View File

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

View File

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

View File

@ -120,15 +120,15 @@ describe('UsersController + BUsersController (e2e)', () => {
expectErrorEnvelope(response, 401, '缺少 Bearer Token'); 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({ await assertRoleMatrix({
name: 'GET /users role matrix', name: 'GET /users role matrix',
tokens: ctx.tokens, tokens: ctx.tokens,
expectedStatusByRole: { expectedStatusByRole: {
[Role.SYSTEM_ADMIN]: 200, [Role.SYSTEM_ADMIN]: 200,
[Role.HOSPITAL_ADMIN]: 200, [Role.HOSPITAL_ADMIN]: 200,
[Role.DIRECTOR]: 403, [Role.DIRECTOR]: 200,
[Role.LEADER]: 403, [Role.LEADER]: 200,
[Role.DOCTOR]: 403, [Role.DOCTOR]: 403,
[Role.ENGINEER]: 403, [Role.ENGINEER]: 403,
}, },
@ -207,7 +207,11 @@ describe('UsersController + BUsersController (e2e)', () => {
groupId: ctx.fixtures.groupA1Id, groupId: ctx.fixtures.groupA1Id,
}); });
expectErrorEnvelope(response, 400, '仅医生/主任/组长允许调整科室/小组归属'); expectErrorEnvelope(
response,
400,
'仅医生/主任/组长允许调整科室/小组归属',
);
}); });
it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN 可进入业务,其他角色 403未登录 401', async () => { it('角色矩阵SYSTEM_ADMIN/HOSPITAL_ADMIN 可进入业务,其他角色 403未登录 401', async () => {

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'; import router from '../router';
const service = axios.create({ 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, timeout: 10000,
}); });
// Request Interceptor // 请求拦截:统一挂载 Bearer Token避免各页面重复拼接鉴权头。
service.interceptors.request.use( service.interceptors.request.use(
(config) => { (config) => {
const userStore = useUserStore(); const userStore = useUserStore();
@ -19,19 +20,18 @@ service.interceptors.request.use(
}, },
(error) => { (error) => {
return Promise.reject(error); return Promise.reject(error);
} },
); );
// Response Interceptor // 响应拦截:对齐后端统一响应包裹 { code, msg, data }。
service.interceptors.response.use( service.interceptors.response.use(
(response) => { (response) => {
const res = response.data; 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)) { if (res.code === 0 || (res.code >= 200 && res.code < 300)) {
return res.data; return res.data;
} else { } else {
// If backend returns code !== 0/2xx but HTTP status is 200
ElMessage.error(res.msg || '请求失败'); ElMessage.error(res.msg || '请求失败');
return Promise.reject(new Error(res.msg || 'Error')); return Promise.reject(new Error(res.msg || 'Error'));
} }
@ -42,13 +42,14 @@ service.interceptors.response.use(
if (error.response) { if (error.response) {
const { status, data } = error.response; const { status, data } = error.response;
// Backend error response format: { code: number, msg: string, data: null }
message = data?.msg || message; message = data?.msg || message;
if (status === 401) { if (status === 401) {
// Token expired or invalid // 401 统一视为登录态失效,先清理本地态再跳登录页。
userStore.logout(); userStore.logout();
router.push(`/login?redirect=${encodeURIComponent(router.currentRoute.value.fullPath)}`); router.push(
`/login?redirect=${encodeURIComponent(router.currentRoute.value.fullPath)}`,
);
ElMessage.error(message || '登录状态已过期,请重新登录'); ElMessage.error(message || '登录状态已过期,请重新登录');
return Promise.reject(new Error('Unauthorized')); return Promise.reject(new Error('Unauthorized'));
} else if (status === 403) { } else if (status === 403) {
@ -60,7 +61,7 @@ service.interceptors.response.use(
ElMessage.error(message || '网络连接异常'); ElMessage.error(message || '网络连接异常');
} }
return Promise.reject(error); return Promise.reject(error);
} },
); );
export default service; export default service;

View File

@ -14,6 +14,8 @@ const PATIENT_ROLES = Object.freeze([
'HOSPITAL_ADMIN', 'HOSPITAL_ADMIN',
'DIRECTOR', 'DIRECTOR',
'LEADER', 'LEADER',
// 后端患者接口允许医生访问,页面侧也应放开,避免前端先把医生拦掉。
'DOCTOR',
]); ]);
export const ROLE_PERMISSIONS = Object.freeze({ export const ROLE_PERMISSIONS = Object.freeze({
@ -22,6 +24,7 @@ export const ROLE_PERMISSIONS = Object.freeze({
ORG_DEPARTMENTS: ORG_MANAGER_ROLES, ORG_DEPARTMENTS: ORG_MANAGER_ROLES,
ORG_GROUPS: ORG_MANAGER_ROLES, ORG_GROUPS: ORG_MANAGER_ROLES,
USERS: ADMIN_ROLES, USERS: ADMIN_ROLES,
DEVICES: ADMIN_ROLES,
TASKS: TASK_ROLES, TASKS: TASK_ROLES,
PATIENTS: PATIENT_ROLES, PATIENTS: PATIENT_ROLES,
}); });

View File

@ -22,8 +22,12 @@
<span>组织架构</span> <span>组织架构</span>
</template> </template>
<el-menu-item index="/organization/tree">结构图视图</el-menu-item> <el-menu-item index="/organization/tree">结构图视图</el-menu-item>
<el-menu-item index="/organization/hospitals">医院管理</el-menu-item> <el-menu-item index="/organization/hospitals"
<el-menu-item index="/organization/departments">科室管理</el-menu-item> >医院管理</el-menu-item
>
<el-menu-item index="/organization/departments"
>科室管理</el-menu-item
>
<el-menu-item index="/organization/groups">小组管理</el-menu-item> <el-menu-item index="/organization/groups">小组管理</el-menu-item>
</el-sub-menu> </el-sub-menu>
</template> </template>
@ -47,6 +51,11 @@
<span>用户管理</span> <span>用户管理</span>
</el-menu-item> </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"> <el-menu-item v-if="canAccessTasks" index="/tasks">
<el-icon><List /></el-icon> <el-icon><List /></el-icon>
<span>任务管理</span> <span>任务管理</span>
@ -100,7 +109,17 @@ import {
ROLE_PERMISSIONS, ROLE_PERMISSIONS,
hasRolePermission, hasRolePermission,
} from '../constants/role-permissions'; } 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 route = useRoute();
const router = useRouter(); const router = useRouter();
@ -113,6 +132,9 @@ const activeMenu = computed(() => {
const canAccessUsers = computed(() => const canAccessUsers = computed(() =>
hasRolePermission(userStore.role, ROLE_PERMISSIONS.USERS), hasRolePermission(userStore.role, ROLE_PERMISSIONS.USERS),
); );
const canAccessDevices = computed(() =>
hasRolePermission(userStore.role, ROLE_PERMISSIONS.DEVICES),
);
const canAccessOrgTree = computed(() => const canAccessOrgTree = computed(() =>
hasRolePermission(userStore.role, ROLE_PERMISSIONS.ORG_TREE), hasRolePermission(userStore.role, ROLE_PERMISSIONS.ORG_TREE),
); );
@ -174,7 +196,7 @@ const handleCommand = (command) => {
/* fade-transform transition */ /* fade-transform transition */
.fade-transform-leave-active, .fade-transform-leave-active,
.fade-transform-enter-active { .fade-transform-enter-active {
transition: all .3s; transition: all 0.3s;
} }
.fade-transform-enter-from { .fade-transform-enter-from {
opacity: 0; opacity: 0;

View File

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

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

@ -59,7 +59,7 @@
<el-table-column prop="id" label="ID" width="80" align="center" /> <el-table-column prop="id" label="ID" width="80" align="center" />
<el-table-column prop="name" label="姓名" min-width="120" /> <el-table-column prop="name" label="姓名" min-width="120" />
<el-table-column prop="phone" label="手机号" min-width="140" /> <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"> <el-table-column label="归属医院" min-width="160">
<template #default="{ row }"> <template #default="{ row }">
{{ row.hospital?.name || '-' }} {{ row.hospital?.name || '-' }}
@ -116,8 +116,8 @@
<el-form-item label="手机号" prop="phone"> <el-form-item label="手机号" prop="phone">
<el-input v-model="form.phone" placeholder="请输入手机号" /> <el-input v-model="form.phone" placeholder="请输入手机号" />
</el-form-item> </el-form-item>
<el-form-item label="身份证" prop="idCardHash"> <el-form-item label="身份证" prop="idCard">
<el-input v-model="form.idCardHash" placeholder="请输入身份证号" /> <el-input v-model="form.idCard" placeholder="请输入身份证号" />
</el-form-item> </el-form-item>
<el-form-item label="归属医生" prop="doctorId"> <el-form-item label="归属医生" prop="doctorId">
<el-tree-select <el-tree-select
@ -155,8 +155,8 @@
<el-descriptions-item label="手机号">{{ <el-descriptions-item label="手机号">{{
recordSummary.phone || '-' recordSummary.phone || '-'
}}</el-descriptions-item> }}</el-descriptions-item>
<el-descriptions-item label="身份证">{{ <el-descriptions-item label="身份证">{{
recordSummary.idCardHash || '-' recordSummary.idCard || '-'
}}</el-descriptions-item> }}</el-descriptions-item>
<el-descriptions-item label="记录数">{{ <el-descriptions-item label="记录数">{{
recordList.length recordList.length
@ -262,7 +262,7 @@ const doctorOptions = ref([]);
const form = reactive({ const form = reactive({
name: '', name: '',
phone: '', phone: '',
idCardHash: '', idCard: '',
doctorId: null, doctorId: null,
}); });
@ -272,7 +272,7 @@ const rules = {
{ required: true, message: '请输入手机号', trigger: 'blur' }, { required: true, message: '请输入手机号', trigger: 'blur' },
{ pattern: /^1\d{10}$/, 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' }], doctorId: [{ required: true, message: '请选择归属人员', trigger: 'change' }],
}; };
@ -281,7 +281,7 @@ const recordLoading = ref(false);
const currentPatientName = ref(''); const currentPatientName = ref('');
const recordSummary = reactive({ const recordSummary = reactive({
phone: '', phone: '',
idCardHash: '', idCard: '',
}); });
const recordList = ref([]); const recordList = ref([]);
@ -432,6 +432,8 @@ const fetchData = async () => {
if (userStore.role === 'SYSTEM_ADMIN') { if (userStore.role === 'SYSTEM_ADMIN') {
params.hospitalId = searchForm.hospitalId; params.hospitalId = searchForm.hospitalId;
} }
//
const res = await getPatients(params); const res = await getPatients(params);
allPatients.value = Array.isArray(res) ? res : []; allPatients.value = Array.isArray(res) ? res : [];
applyFiltersAndPagination(); applyFiltersAndPagination();
@ -462,7 +464,7 @@ const resetForm = () => {
formRef.value?.resetFields(); formRef.value?.resetFields();
form.name = ''; form.name = '';
form.phone = ''; form.phone = '';
form.idCardHash = ''; form.idCard = '';
form.doctorId = null; form.doctorId = null;
currentEditId.value = null; currentEditId.value = null;
}; };
@ -487,7 +489,7 @@ const openEditDialog = async (row) => {
currentEditId.value = detail.id; currentEditId.value = detail.id;
form.name = detail.name; form.name = detail.name;
form.phone = detail.phone; form.phone = detail.phone;
form.idCardHash = detail.idCardHash; form.idCard = detail.idCard;
form.doctorId = detail.doctorId; form.doctorId = detail.doctorId;
dialogVisible.value = true; dialogVisible.value = true;
}; };
@ -499,10 +501,11 @@ const handleSubmit = async () => {
submitLoading.value = true; submitLoading.value = true;
try { try {
// 使
const payload = { const payload = {
name: form.name, name: form.name,
phone: form.phone, phone: form.phone,
idCardHash: form.idCardHash, idCard: form.idCard,
doctorId: form.doctorId, doctorId: form.doctorId,
}; };
if (isEdit.value) { if (isEdit.value) {
@ -535,8 +538,8 @@ const handleDelete = (row) => {
}; };
const openRecordDialog = async (row) => { const openRecordDialog = async (row) => {
if (!row.phone || !row.idCardHash) { if (!row.phone || !row.idCard) {
ElMessage.warning('缺少 phone 或 idCardHash,无法查询调压记录'); ElMessage.warning('缺少 phone 或 idCard,无法查询调压记录');
return; return;
} }
@ -544,16 +547,17 @@ const openRecordDialog = async (row) => {
recordLoading.value = true; recordLoading.value = true;
currentPatientName.value = row.name || ''; currentPatientName.value = row.name || '';
recordSummary.phone = ''; recordSummary.phone = '';
recordSummary.idCardHash = ''; recordSummary.idCard = '';
recordList.value = []; recordList.value = [];
try { try {
//
const res = await getPatientLifecycle({ const res = await getPatientLifecycle({
phone: row.phone, phone: row.phone,
idCardHash: row.idCardHash, idCard: row.idCard,
}); });
recordSummary.phone = res.phone || ''; recordSummary.phone = res.phone || '';
recordSummary.idCardHash = res.idCardHash || ''; recordSummary.idCard = res.idCard || '';
const fullList = Array.isArray(res.lifecycle) ? res.lifecycle : []; const fullList = Array.isArray(res.lifecycle) ? res.lifecycle : [];
recordList.value = fullList.filter((item) => item.patient?.id === row.id); recordList.value = fullList.filter((item) => item.patient?.id === row.id);
} finally { } finally {