Compare commits

303 Commits

Author SHA1 Message Date
iven
d6abf45e7e docs(health): 媒体库与轮播图实施计划 — 5 Chunk / 22 Task
Some checks failed
CI / security-audit (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
Chunk 1: 后端实体 + 迁移 + DTO (Task 1-7)
Chunk 2: 后端 Service 层 (Task 8-9)
Chunk 3: Handler + 路由 + 公开端点 + 签名URL (Task 10-14)
Chunk 4: 前端 API + MediaPicker + 页面 (Task 15-20)
Chunk 5: 小程序访客页改造 (Task 21-22)
2026-05-10 13:35:30 +08:00
iven
5c5c099fb2 docs(health): 设计规格评审修复 — 3 CRITICAL + 5 HIGH + 关键 MEDIUM
修复项:
- C1: 公开端点增加租户识别机制(X-Tenant-Id / query param)
- C2: 签名 URL 增加路径规范化 + HMAC 输入格式 + is_public 实时校验
- C3: crop 端点补全权限码 health.media.manage
- H2: secret_key 生产环境 panic 保护
- H3: 软删除 media_item 级联设置 banner inactive
- H4: 补全 health.banners.list 权限码
- H5: 公开路由注册到 public_routes + 菜单种子迁移
- M3: 公开文章返回专用 PublicArticleListItem DTO
- M4: 新增"首页推荐"分类种子迁移
2026-05-10 11:40:44 +08:00
iven
a12fe0e8a9 docs(health): 媒体库与轮播图管理设计规格 + UI 可视化方案
新增设计规格涵盖:
- media_folder / media_item / banner 三个实体
- 媒体库 API(CRUD + 上传 + 裁剪 + 文件夹管理)
- 轮播图管理 API(CRUD + 排序 + 定时上下架)
- 公开端点(签名 URL 机制)+ 公开/私有访问控制
- 管理后台 UI(方案 A 左树+网格)+ MediaPicker 组件
- 小程序访客页改造(动态轮播图 + 文章卡片列表)
2026-05-10 11:32:38 +08:00
iven
3c828bfc4a fix(miniprogram): 退出登录后刷新仍保持登录态
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
根因:logout 清除 storage 期间并发请求触发 tryRefreshToken 写回新 token
修复:添加 isLoggingOut 标记,logout 时先标记阻止 token 刷新竞态
2026-05-10 10:36:17 +08:00
iven
11101ac204 feat(auth): 微信登录自动分配 patient 角色 + 创建患者档案
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 新增迁移 m20260510_000133:为所有租户创建 patient 角色并分配 19 个权限
- wechat_service: bind_phone 自动 assign_patient_role + ensure_patient_record
- find_or_create_user_by_phone 新用户自动获得 patient 角色和患者档案
- 小程序 auth store: bindPhone 抛出异常而非静默返回 false
- 小程序登录页: 捕获绑定错误并显示可操作的对话框
2026-05-10 09:57:45 +08:00
iven
28bcdc4208 docs: 更新 wiki — Design Token 全面接入记录
Some checks failed
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
- index.md: 更新关键数字(716 提交)、新增 Design Token 指标行
- miniprogram.md: 新增 §1.1 Design Token 系统完整文档(10 级字号表、
  4 结构 token、使用规则、关怀模式说明)、更新变更记录
2026-05-09 23:58:09 +08:00
iven
890c132890 refactor(miniprogram): 全面接入 Design Token — 68 SCSS 文件 px→var(--tk-*)
Some checks failed
CI / security-audit (push) Has been cancelled
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
- 重写 tokens.scss:校准 10 级字号 + 4 结构 token 匹配实际设计值
- 更新 mixins.scss:4 个 mixin 引用 token 替代硬编码
- 68 SCSS 文件全面迁移:font-size px → var(--tk-font-*),辅助文字色 → var(--tk-text-secondary)
- 清理 12 个页面的本地 mixin 重复定义
- elder-mode.scss 从 530 行缩减至 ~120 行:删除所有字号/颜色覆写,仅保留结构布局
- Token 覆盖率:634 引用 / 仅 3 个特殊硬编码值(72px/80px/21px)

关怀模式通过 CSS 变量级联自动生效,消除"打地鼠"问题。
2026-05-09 23:53:07 +08:00
iven
257ca94a25 fix(miniprogram): 登录页尺寸过大 + 排除关怀模式
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 正常模式大幅缩减:标题 48→32px、按钮高 96→56px、按钮字 32→28px
  logo 128→96px、副标题 26→16px、顶部留白 160→100px
- 登录页不应用 elder-mode class(正常模式已足够大)
- 关怀模式覆写值同步调整:标题 38px、按钮高 64px、副标题 21px

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 22:45:08 +08:00
iven
7b5138a630 feat(miniprogram): 关怀模式全覆盖 — 58/58 页面 100% 接入
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 医生端 18 个页面全部接入(首页/待办/告警/咨询/透析/随访/
  患者/处方/报告及其详情和创建页)
- 商城子包 3 页面(商品详情/积分兑换/订单)
- 患者端剩余页面(AI报告/文章/活动/设备同步/登录/随访详情/
  报告详情/知情同意/诊断/透析处方/透析记录/家庭成员添加)
- 页面覆盖率:22/59 (37%) → 58/58 (100%)
- useElderClass hook 统一接入模式,零样板代码

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 22:34:44 +08:00
iven
e8ccee02d5 feat(miniprogram): 关怀模式 Phase 2 — Design Token + 15 页面批量接入
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 新建 useElderClass hook,替代每页 3 行样板代码
- 新建 CSS 自定义属性 Design Token 系统(tokens.scss)
  正常/关怀两套值:字号、间距、触控、布局参数
- 15 个页面批量接入关怀模式 class:
  TabBar: 商城页
  主流程: 预约列表/详情/创建、咨询详情
  子包: 体征录入/趋势/日常监测/告警、用药/档案/随访/报告/家庭/设置
- 新建 elder-toast 工具(关怀模式 3s + 触觉反馈)
- 页面覆盖率:4/59 → 22/59 (37%)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 22:17:58 +08:00
iven
4335f7e144 fix(miniprogram): 关怀模式非线性放大重构 + 3 页面接入
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- elder-mode.scss: 等比×1.3改为非线性放大(标题×1.15/正文×1.35/辅助×1.55)
- 体征网格从2列改为1列,解决放大后溢出问题
- 行高从1.5提升到1.7,对比度$tx3→$tx2增强可读性
- 健康页/消息页/咨询页接入useUIStore关怀模式
- 共享组件(EmptyState/ErrorState/Loading/StepIndicator)适配关怀模式
- 触控区域统一提升到56px+

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 22:05:06 +08:00
iven
66329852b8 fix(miniprogram): useDidShow 恢复认证状态 + E2E 全系统测试报告
Some checks failed
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
- app.tsx: 将 restoreAuth/restoreUI 从 useEffect 改为 useDidShow,
  修复 reLaunch 后 Zustand store 未恢复导致访客模式的问题
- docs/qa/e2e-full-system-report.md: 三端 E2E 测试报告更新,
  原 BUG-1(Admin 随访管理 403)确认为误报,综合通过率 100% (64/64)
- tools/weapp-mcp/e2e-test.mjs: 小程序 E2E 基础导航测试脚本
- tools/weapp-mcp/e2e-interactive-test.mjs: 小程序 E2E 交互操作测试脚本

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 18:25:43 +08:00
iven
085163ec7a feat(miniprogram): 访客模式 + 长辈模式 + MCP 自动化脚本
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
访客模式:
- 未登录用户可见首页(轮播图+健康资讯+登录引导)和"我的"页面
- 健康和消息 tab 显示 GuestGuard 登录拦截
- 登录页增加"暂不登录,先看看"跳过入口
- 401 拦截器增加 hasToken 检查,避免访客被重定向到登录页
- 退出登录后 reLaunch 到首页而非登录页

长辈模式:
- 新增 stores/ui.ts 管理显示模式(标准/长辈)
- 长辈模式放大字体 ×1.3、间距 ×1.2、按钮加大
- "我的 → 账号 → 长辈模式"切换页
- 设置持久化到 Storage

修复:
- Health/Messages 页面 Hooks 顺序违规(条件 return 在 hooks 之间)
  导致访客模式下页面白屏,所有 hooks 移到条件判断之前

工程:
- scripts/mpsync.sh/ps1 自动清理残留 DevTools 进程
- project.config.json 默认关闭域名校验
2026-05-09 11:42:44 +08:00
iven
0c28969c3b docs: 小程序端 E2E 闭环测试报告
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
5 条业务闭环全部通过:体征上报、预约挂号、咨询消息、积分商城、患者信息
Web管理端和小程序端数据流通完整,发现1个LOW问题(analytics/batch 422)
2026-05-09 08:13:37 +08:00
iven
8490344d69 fix(ai): AI 配额摘要端点 500 错误修复
Some checks failed
CI / security-audit (push) Has been cancelled
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
get_usage_summary 中 get_tenant_config 和 get_monthly_token_usage 的
数据库错误直接传播为 AppError::Internal (500),当 ai_tenant_configs 表
为空或查询异常时导致整个端点不可用。

改为 unwrap_or 降级处理:config 缺失时使用默认配额,token 查询失败时归零,
确保端点始终返回有效数据而非 500。
2026-05-09 07:52:41 +08:00
iven
e4b19090b8 docs: V1 发布前 E2E 多角色验证报告
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
5 角色全链路测试(115 API 端点 + 浏览器 UI),93% 通过率,3 BUG 已修复
2026-05-09 02:29:15 +08:00
iven
07217336e7 fix(web): 运营仪表盘数据映射错误和浮点精度修复
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- OperatorWorkbench: "今日活跃用户" 错误使用体征上报率数据源,改为 pointsStats.active_accounts
- OperatorWorkbench: AI 摘要体征上报率显示原始浮点数(22.413793...),改为保留两位小数
- OperatorWorkbench: "科普阅读量" fallback 错误回退到积分发放数据,移除错误 fallback
- Home.tsx: 运营角色 ROLE_STATS "内容发布" 数据源错误,修正为 patientStats
- Home.tsx: 移除未使用的 TodoList/AiInsightPanel import
- .lintstagedrc.js: 修复 Windows 平台 eslint 命令,使用函数式获取文件名列表
2026-05-09 02:27:38 +08:00
iven
19705e31bd chore(demo): V1 演示数据预置脚本
Some checks failed
CI / frontend-build (push) Has been cancelled
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / security-audit (push) Has been cancelled
幂等 SQL 脚本,一键预置:
- 张建国患者档案 + 3 条体征记录
- 2 份化验单(肌酐 88→102 趋势)
- 25 个背景患者(仪表盘数据)
- 随访模板 + 21 个随访任务
- 收缩压>=160 告警规则(场景5用)
- 3 篇 CKD 科普文章
2026-05-09 02:01:41 +08:00
iven
3e1413aebc fix(auth): 修复 Token 刷新并发竞态条件
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
使用原子 CAS(UPDATE WHERE token_hash = ? AND revoked_at IS NULL)
替代先查后改的非原子操作,防止同一 refresh token 被并发使用两次。

新增 TokenService::validate_and_revoke_atomic 方法,将 JWT 解码、
哈希匹配和 token 撤销合并为单次数据库操作。
2026-05-09 01:53:28 +08:00
iven
36f2ba381a docs: V1 演示准备实施计划(4 Chunk / 6 Task)
Chunk 1: Token 刷新竞态修复(原子 CAS via token_hash)
Chunk 2: 告警/AI/health_manager 链路验证
Chunk 3: 演示数据预置脚本(张建国 + 25 背景患者)
Chunk 4: 端到端 DRY RUN(7 场景验证)
2026-05-09 01:47:40 +08:00
iven
a3273ca581 docs: V1 客户演示方案评审修订
根据规格评审反馈补充:
- 硬件/网络要求 + 角色切换指引
- Q&A 异议处理话术(6 个常见问题)
- DRY RUN 计划(D-7 到 D-Day)
- 扩展风险预案(告警权限码、SSE、Ollama、登录冲突)
- 场景 2 AI 触发入口操作说明
- 场景 7 背景数据要求
- 统一 CRITICAL 数量和完成度口径
2026-05-09 01:35:53 +08:00
iven
f58c60599b docs: V1 客户演示方案设计规格
面向潜在客户(体检中心/血透中心)决策层+医疗团队的演示方案。
采用患者旅程视角(张大爷30天管理历程),7个场景展示完整闭环:
建档→AI分析→医生决策→患者端→告警→随访→仪表盘。
2026-05-09 01:29:31 +08:00
iven
28dafa9bea fix: 多角色业务链路测试发现并修复 3 类问题
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
1. 角色权限修复(CRITICAL):
   - operator 角色权限为空(迁移 name/code 不匹配 + 软删除冲突)
   - doctor 角色权限被误清(API assign_permissions 失败导致全部软删除)
   - nurse 缺 devices 权限 + doctor/nurse 缺 appointment 权限
   - 新增 3 个迁移 000130-000132 修复所有角色权限

2. 趋势指标映射修复(HIGH):
   - 前端 blood_pressure_systolic → systolic_bp_morning
   - 前端 blood_sugar_fasting → blood_sugar
   - 同步修复首页、健康页、趋势页的 indicator 参数

3. 咨询页错误处理优化(MEDIUM):
   - 403/401 时显示空列表而非"加载失败"错误提示
2026-05-08 22:00:43 +08:00
iven
81c174a902 fix(miniprogram): 修复多角色找茬测试 V3 发现的 8 个问题
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
1. EmptyState 默认 emoji 📭 → serif 首字圆形图标(影响 23 处使用)
2. 预约页英文副标题 "Appointment" 移除
3. consultation 页技术错误信息直接渲染到 UI → 用户友好提示
4. auth store restore() 增加 fallback:secureGet 失败时读 wx.getStorageSync
5. request.ts 新增 safeGet():token/tenantId 读取容错
6. doctor/consultation useMemo 自引用死循环 → Math.ceil(total/20)
7. doctor/alerts 同样自引用 bug 修复
8. doctor/patients 死代码 totalPages + useMemo import 清理
2026-05-08 17:34:42 +08:00
iven
3dac6a9eda fix(miniprogram): 多角色找茬模式发现并修复 16 个问题
Some checks failed
CI / frontend-build (push) Has been cancelled
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / security-audit (push) Has been cancelled
P0 Bug:
- 健康 AI 建议幽灵路径 pkg-appointment → appointment/create
- 血糖 indicator_type 始终 blood_sugar,不区分空腹/餐后
- 商城订单页 switchTab 跳转非 TabBar 页面

P1 设计系统:
- Profile/Index 页 emoji 图标替换为衬线首字
- Profile 硬编码颜色替换为 SCSS 变量 class
- alerts/action-inbox 两个页面全面接入设计系统
- ai-report/detail 删除重复 mixin 定义
- ErrorBoundary 添加重试按钮移除 emoji
- 新增 $r-xs: 8px 圆角变量

P1 导航/交互:
- Profile 补充 4 个缺失菜单(透析/知情同意/用药/活动)
- Settings 隐私政策改为跳转实际页面
- 全局启用 enablePullDownRefresh
- 首页/健康页添加下拉刷新
- 咨询/消息列表添加分页加载更多
- 医生端患者列表改为上拉加载
- 首页/健康页间距统一为 24px
2026-05-08 16:07:06 +08:00
iven
22b8ac7ac6 fix: 修复多角色找茬测试 V2 发现的 11 个问题
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
P0 (CRITICAL):
- C1: 统计 API 全部改为 safe_aggregate 容错,防止单个子查询崩溃导致 500
- C2: Token 刷新增加用户身份验证,防止并发场景下身份切换
- C3: 患者端线下活动接口添加患者档案验证,防止 Doctor/HM 越权访问

P1 (HIGH):
- H1: 操作记录用 EntityName 组件解析用户名,不再显示截断 UUID
- H4: 告警标题添加中英文映射 (translateAlertTitle)
- H5: 告警面板补全 message import + 修复 hooks 顺序
- H8: 咨询消息发送按钮添加 AuthButton 权限控制
- H9: routeConfig 日常监测权限码改为 health.daily-monitoring.*

P2 (MEDIUM):
- M4: 咨询类型映射补全 online/phone/doctor/follow_up 中文标签

DTO: LabReportStatisticsResp, AppointmentStatisticsResp, VitalSignsReportRateResp 添加 Default derive
2026-05-08 12:42:41 +08:00
iven
297a151b0c docs: 多角色用户视角找茬测试报告 V2(2026-05-08)
5 角色深度测试,发现 ~55 个问题:
- CRITICAL x3: Token 身份切换、统计 API 500、权限泄漏
- HIGH x9: 操作按钮缺失、英文告警、权限越界
- MEDIUM x21: 数据矛盾、国际化、路由不一致

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 11:43:25 +08:00
iven
c82f7bda1d fix: 系统性预防角色测试高频问题(5 方案落地)
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
P0 — 默认拒绝 + 强制守卫:
- 创建 routeConfig.ts 作为前端路由权限的单一真相源
- TypeScript 强制每个路由声明非空权限数组,不可能遗漏
- 自动生成 ROUTE_PERMISSIONS 和 FROZEN_ROUTES
- 修正 3 个前端权限码不匹配后端

P0 — CI 权限扫描:
- 新增 tools/check_permissions.py 校验脚本
- 发现并修复 tenant.manage 未注册问题

P1 — 聚合接口容错:
- erp-core 新增 safe_aggregate 工具函数
- 仪表盘统计 handler 重构

P1 — 状态机一致性自检:
- validation.rs 新增 3 个自检测试

fix: lint-staged eslint Windows 兼容性
2026-05-08 08:52:16 +08:00
iven
645ec39e8b docs: 更新 wiki 反映 5 角色测试结果和修复教训
Some checks failed
CI / security-audit (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
- wiki/index.md: 更新关键数字(693 次提交/129 迁移/clippy 0 警告/角色测试完成)
- wiki/index.md: 症状导航添加 5 个已修复问题
- wiki/index.md: 文档索引添加角色测试计划/结果
- wiki/testing.md: 新增 5 角色深度测试结果表格和 7 个 BUG 修复清单
- wiki/testing.md: 历史教训添加 6 条新教训(容错/拦截同步/路径一致/权限语义/clippy/lint-staged)
2026-05-07 23:50:19 +08:00
iven
6d5a711d2c fix: 修复测试发现的 7 个问题 + 全 workspace clippy 清零
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
功能修复:
1. 患者创建空名称验证:后端添加 name.trim().is_empty() 检查
2. 仪表盘统计容错:单个查询失败返回零值而非 500
3. FHIR 路由修复:从 /fhir 移到 /api/v1/fhir 保持一致
4. 冻结模块后端中间件:新增 frozen_module_middleware 拦截冻结路径
5. 积分端点权限码:health.health-data.list → health.points.list
6. 角色权限迁移:护士补充 devices.list,运营补充 points.list/manage
7. 测试结果文档:R01-R05 角色测试 + T00/T10 结果归档

Clippy 全 workspace 清零(14→0 errors):
- erp-core: 修复 empty doc line、collapsible if、redundant closure 等 9 处
- erp-health: 修复 too_many_arguments、unused var、unnecessary parens 等 58 处
- erp-ai: 修复 dead_code、unused import 等 11 处
- erp-plugin: 修复 too_many_arguments、wildcard pattern 等 11 处
- erp-server-migration: 修复 enum_variant_names 5 处
- erp-auth/config/workflow/message: 各 1-3 处

工程改进:
- lint-staged 配置迁移到 .lintstagedrc.js(函数式避免文件列表传给 clippy)
- cargo fmt 统一格式化
2026-05-07 23:43:14 +08:00
iven
786f57c151 fix: 修复角色测试发现的 5 个共性问题
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 修复前端路由守卫前缀碰撞(/health/articles 匹配 /health/article-categories)
- 补全 6 条缺失路由权限映射(appointments/follow-up-records/article-categories/article-tags/plugins/market)
- 修复 critical-alerts API 500(escalation_level 字段 INT2/i16 与 Entity i32 类型不匹配)
- 新增迁移 000128:告警状态修正 + 菜单权限码补全 + 非admin角色移除基础模块权限
2026-05-07 15:54:37 +08:00
iven
60dc4dba7a fix(health): 修复 5 角色深度测试发现的权限越权和告警端点缺失
Some checks failed
CI / security-audit (push) Has been cancelled
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
- auth: token_service 查询 role_permissions/user_roles 添加 deleted_at 过滤,
  修复软删除的权限仍被加载到 JWT 的越权漏洞
- health: 新增 GET /health/alerts/{id} 告警详情端点(含 handler + service + 路由)
- web: AlertList 操作按钮增加 active 状态判断,修复按钮不显示
- migration: 新增 000127 清理 doctor 角色多余的 health-data.manage/ai.analysis.manage
2026-05-07 13:51:16 +08:00
iven
85a7dacd16 fix(health): 修复 5 角色深度测试发现的 8 个问题
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
P0 修复:
- 告警状态机新增 active 合法状态 + 转换规则 (active→acknowledged/dismissed)
- 前端路由守卫改为默认拒绝,未注册路由返回 403

P1 修复:
- 侧边栏菜单根据用户权限码过滤,非 admin 隐藏无权限菜单项
- Critical-alerts handler 增加详细错误日志 + div_ceil 安全防护
- 仪表盘统计 API 调用使用 silent 模式避免 500 触发全局 toast

P2 修复:
- 随访类型映射新增 visit → 上门 (前后端同步)
- 随访 fallback 选项新增 visit 类型

排除的假 BUG (代码已正确):
- 患者性别/血型: MCP fill() 不兼容 Select 组件,正常交互正确
- 随访筛选/对话框关闭: 代码逻辑验证正确

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-07 08:24:12 +08:00
iven
0acf901893 fix(web): 告警详情显示患者名和规则标题替代原始 ID
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 患者字段显示 patient_name,ID 缩短为 tooltip
- 规则字段显示告警标题 title,rule_id 缩短为 tooltip
- 告警详情 JSON 解析为中文标签结构化表格
2026-05-07 07:41:26 +08:00
iven
a9821ab832 fix(web): 告警详情面板用户体验改进
Some checks failed
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
- 用 Alert 横幅醒目展示严重程度、标题和行动指引
- 患者信息卡片显示姓名而非原始 UUID
- 将 JSON 详情解析为中文标签(告警描述/监测值/阈值等)
- 技术信息(原始 ID)移入折叠面板
2026-05-07 07:38:04 +08:00
iven
1613e3cfe9 fix(health): 修复 5 角色测试发现的 4 个共性问题
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 权限路由守卫:静默重定向改为显示 403 页面,使用 useLocation 替代
  window.location.hash,补全缺失路由权限条目
- 随访状态筛选:usePaginatedData hook 添加 filters 变化监听自动刷新
- 告警操作:后端 acknowledge/dismiss/resolve 改返回 AlertResponse
  (含 patient_name),前端增加 active 状态兼容和错误反馈
- 咨询患者名:后端 create/get/close_session 增加 patient_name 和
  doctor_name enrichment,前端 EntityName 空字符串处理
2026-05-07 07:23:41 +08:00
iven
43f0ba7057 fix(web): 修复角色测试发现的权限守卫、API 500、权限配置问题
Some checks failed
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
1. CRITICAL: 前端路由权限守卫 — routePermissions 从 3 条扩展到 31 条,
   覆盖全部 /health/* 路由;匹配逻辑从宽松模块级前缀改为精确权限码匹配
2. HIGH: health-data API 500 — jsonb_array_elements() 添加 CASE WHEN 类型守卫,
   防止 items 字段为非数组 JSON 时崩溃
3. MEDIUM: Doctor 补充 ai.prompt.list、ai.usage.list、follow-up-templates 权限
4. Operator 清理 AI 分析、统计报表菜单关联
5. 更新 5 角色测试计划文档
2026-05-06 22:29:54 +08:00
iven
5467394ffe docs(qa): 5 角色测试计划(admin/doctor/nurse/health_manager/operator)
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- R01-admin: 45 个菜单全覆盖,含系统管理和全部健康业务
- R02-doctor: 24 个菜单,随访+咨询+AI+告警+透析+处方
- R03-nurse: 20 个菜单,随访监控台+行动收件箱,无管理类功能
- R04-health_manager: 29 个菜单,告警规则+AI管理+随访模板+实时监控
- R05-operator: 24 个菜单,积分+内容+设备只读+运营仪表盘
- 修复 project.private.config.json autoAudits 配置
2026-05-06 17:23:52 +08:00
iven
80ef48a3a3 feat(miniprogram): 医护工作台角色定制 + 性能优化
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- auth store 新增 health_manager 角色,添加 isDoctor/isNurse/isHealthManager/hasRole 辅助方法
- 医生工作台按角色过滤功能卡片和快捷操作(doctor/nurse/health_manager/admin)
- 列表页面分页计算提取为 useMemo(patients/alerts/consultation)
2026-05-06 12:51:00 +08:00
iven
570377a31f feat(config): 角色权限控制菜单可见性 + 医疗业务角色
Some checks failed
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
- 修复 menu_service 角色过滤 bug: ctx.roles 存的是角色 code 而非 UUID,
  新增 resolve_role_ids() 方法通过 code 查找数据库中的角色 ID
- 创建 4 个医疗业务角色: 医生/护士/健康管理师/运营人员
- 重组菜单目录结构: 基础模块→工作台、业务模块→系统管理、健康管理→健康业务
- 菜单排序按功能域分组(患者医护/随访咨询/积分运营/内容运营/AI分析)
- 为各角色分配对应的菜单可见性和操作权限
2026-05-06 12:35:45 +08:00
iven
5fd8e88825 fix(miniprogram): 精简菜单,移除推迟模块入口
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 个人中心:15→8 项菜单(移除积分商城/订单/用药/透析/知情同意/积分明细)
- 健康页:移除 BLE 设备同步入口
- 医生端:移除透析记录/透析处方快捷入口
2026-05-06 11:12:02 +08:00
iven
4a95a83d6b fix(miniprogram): 统一状态色映射,对齐设计系统色板
Some checks failed
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
- 创建 utils/statusTag.ts 共享状态色工具(对齐 variables.scss)
- doctor/consultation: 使用共享状态色替代 Tailwind 硬编码
- doctor/followup: 使用共享状态色替代 Tailwind 硬编码
- doctor/action-inbox: SCSS 状态点替换为设计系统变量
- doctor/index: SCSS 告警/搜索区替换为设计系统变量
- pkg-health/alerts: SCSS 严重度标签替换为设计系统变量
2026-05-06 10:59:13 +08:00
iven
36275eb307 fix(web): 冻结推迟模块路由守卫
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
2026-05-06 10:34:55 +08:00
iven
263bba264a chore(db): 冻结推迟模块菜单迁移 2026-05-06 10:30:58 +08:00
iven
f7bf5a86ea fix(server): CORS 生产环境拒绝通配符
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
2026-05-06 10:21:50 +08:00
iven
d9818c263e fix(ai): AI 提示词模板添加安全检查 2026-05-06 10:21:35 +08:00
iven
c452ae81d1 fix(health): OAuth JWT 配置缺失返回错误而非 panic 2026-05-06 10:21:25 +08:00
iven
a1cbb9fb1d fix(server): readiness_check 隐藏内部错误详情 2026-05-06 10:21:13 +08:00
iven
a78ee2f154 fix(auth): Token 验证和撤销添加租户隔离 2026-05-06 10:21:07 +08:00
iven
51c41acfa7 fix(health): 审计日志加密字段替换为 REDACTED 2026-05-06 10:21:02 +08:00
iven
f668e64266 fix(health): FHIR converter 身份证号脱敏处理 2026-05-06 10:20:50 +08:00
iven
ced93934f1 fix(docker): 添加安全警告注释,补全 .env.example
Some checks failed
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
2026-05-05 23:45:27 +08:00
iven
482871301e fix(health): FHIR $everything 子查询添加 tenant_id 过滤 2026-05-05 23:44:25 +08:00
iven
087e23e57b fix(ai): AI 分析队列 claim_next 添加租户隔离 2026-05-05 23:43:11 +08:00
iven
741aaf0e40 fix(health): FHIR allowed_patient_ids=None 拒绝所有访问 2026-05-05 23:42:29 +08:00
iven
4f84c94a42 docs(wiki): 添加 Ollama 配置文档和 AI 分析故障排除
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- infrastructure.md: 新增 Ollama 服务连接、环境变量、GPU 注意事项
- index.md: 症状导航新增 qwen3 thinking、Ollama 内存/安全、模板渲染等问题
2026-05-05 22:56:30 +08:00
iven
b1a96ace1f fix(ai): 修复 qwen3 模型 thinking 模式导致 AI 分析输出为空
Some checks failed
CI / security-audit (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
qwen3:4b 默认启用 thinking 模式,流式 API 中 content 字段始终为空,
所有 token 消耗在 thinking 上。修复方案:
- 对 qwen3 模型改用非流式 API,从 content 中剥离 <think... 块
- 将清理后的内容按句子/段落分块模拟流式输出
- 自动提升 qwen3 的 num_predict 至 4096 确保 thinking + 回复完整
- 流式解析中跳过空 content chunk
- 新增 strip_think_block 函数及 5 个单元测试
2026-05-05 22:55:20 +08:00
iven
e9cfbd108a fix(ai): 修复 AI 分析读取化验报告 items 为空的问题
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- parse_lab_items 兼容两种存储格式(item_name/name, string/f64 value,
  reference_range/reference_low+high)
- get_lab_report 添加 PII 解密步骤:数据库中 items 是加密存储的,
  AI 分析前需要先解密再解析
- HealthDataProviderImpl 添加 PiiCrypto 字段用于解密
- pii_crypto 创建提前到 AI state 构建之前
- default.toml rate_limit.fail_close 改为 false(开发环境)
2026-05-05 22:05:45 +08:00
iven
049d230bae docs(wiki): 更新 erp-ai 模块 — Ollama 对接 + bug 修复记录
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- index.md: 迁移 123 个, 提交 577 次, 新增 AI 分析症状导航 4 条
- erp-ai.md: 新增 §4 Ollama 本地模型对接、已知限制、已修复 bug
- erp-ai.md: 更新 SSE 流程图(预校验 + 缓存回放修复)
- erp-ai.md: 3 个管理前端页面已实现
2026-05-05 20:07:24 +08:00
iven
a62332f1c4 fix(ai): AI 分析预校验 + prompt 非对话化
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 四个 SSE 端点增加数据完整性校验:items/sections 为空时返回 400
- 迁移 000123 更新全部 prompt system_prompt:明确非对话、输出结构化结果
- 前端用户看到的是分析结论,不再收到"请补充数据"的对话式回复
2026-05-05 19:53:04 +08:00
iven
1f91dcc5cc fix(ai): 修复分析结果 JSON 嵌套 bug
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- replay_cached 直接回放纯文本,不再包装 JSON 壳
- complete_analysis 跳过已完成的记录,防止缓存命中时覆写
- 前端 AnalysisContent 增加 extractPlainText 递归解析 JSON
2026-05-05 19:45:36 +08:00
iven
8a0c9670e6 feat(ai): 对接本地 Ollama qwen3:4b 模型
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- default_provider 从 claude 切换到 ollama
- main.rs 支持 ollama/openai/claude 三种 provider 动态选择
- 新增 [ai.providers.ollama] 配置段(base_url/model/temperature)
- 前端 SSE AI 分析全链路验证通过
2026-05-05 19:12:55 +08:00
iven
7dac749eff feat(ai): 新增预算状态 + 成本估算 API 端点
Some checks failed
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
Phase 3 Task 25:
- GET /ai/budget/status — 租户月度预算状态和告警等级
- GET /ai/cost/estimate — 按分析类型+模型估算单次成本
2026-05-05 16:05:00 +08:00
iven
0da59c6a0e feat(ai): 成本估算 + 预算告警服务 — CostService
Some checks failed
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
CI / rust-check (push) Has been cancelled
Phase 3 Task 24:
- 按分析类型+模型估算 token 用量和 USD 成本
- 查询租户月度预算状态和告警等级(Normal/Warning/Critical/Exceeded)
2026-05-05 16:03:32 +08:00
iven
d2512ca9db feat(ai): 集成知识库到 AnalysisService — system_prompt 自动注入临床规则
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
Phase 3 Task 23: AnalysisService 新增可选 knowledge_source,
stream_analyze 前自动查询 L1/L2/L3 知识并注入 system_prompt
2026-05-05 16:01:52 +08:00
iven
70f69a2008 feat(ai): 实现 StructuredKnowledgeSource — L1/L2/L3 知识库查询
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
Phase 3 Task 22: 从 rules/references/guides 表构建 Prompt 注入上下文
- 规则按优先级排序,参考资料附带引用,指南截取前 2000 字
- 总上下文不超过 8000 字符,confidence 根据 L1/L2 匹配度计算
2026-05-05 15:58:54 +08:00
iven
3592b55556 feat(ai+db): 知识库 3 表迁移 + Entity — rules/references/guides
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
Phase 3 Task 21:
- ai_knowledge_rules: L1 规则表(条件表达式 + 动作文本)
- ai_knowledge_references: L2 参考表(摘要 + pgvector 嵌入)
- ai_knowledge_guides: L3 指南表(全文 + pgvector 嵌入)
2026-05-05 15:55:20 +08:00
iven
2d2e1e191e feat(db): 添加 pgvector 扩展迁移 — 知识库向量检索基础
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
Phase 3 Task 20: CREATE EXTENSION IF NOT EXISTS vector
2026-05-05 15:52:12 +08:00
iven
75a70d2e46 feat(ai): 添加知识库 trait 和 DTO — KnowledgeSource/PatientSummary/Reference
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
Phase 3 Task 19: 定义统一知识获取接口,支持未来向量检索扩展
2026-05-05 15:50:57 +08:00
iven
54116d1a1f refactor(ai): auto_analysis 改为入队模式
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
高风险患者扫描结果构造 AnalysisJob 入队而非直接调用 Provider
保留定时扫描逻辑(每 24h),分析执行由队列消费者负责
2026-05-05 15:41:30 +08:00
iven
553de13cd5 feat(ai): 扩展事件订阅自动入队分析
订阅 health_data.critical_alert → 趋势分析 (priority=2)
订阅 lab_report.uploaded → 化验单解读 (priority=1)
订阅 dialysis.record.created → KDIGO 风险评估 (priority=2)
tokio::select! 多通道并发消费
2026-05-05 15:40:15 +08:00
iven
7fb92714c7 feat(ai): 实现 AnalysisQueue 服务
支持 enqueue/claim_next/mark_completed/mark_failed 状态机
失败自动重试(retry_count < max_retries → pending),queue_status 聚合查询
2026-05-05 15:38:14 +08:00
iven
3186c5aee9 feat(ai): 添加 ai_analysis_queue 迁移 + Entity
异步分析队列表,支持优先级/重试/状态机(pending→running→completed/failed)
索引覆盖租户状态查询和调度扫描,迁移号 000118
2026-05-05 15:35:59 +08:00
iven
c268229311 feat(ai): 实现 CacheService 两级缓存 + 集成到 AiState
Redis TTL (L1) + DB SHA-256 hash (L2),Redis 不可用时自动降级
CacheKey 基于 tenant_id + analysis_type + input_hash + prompt_version
AiState 新增 cache 字段,main.rs 注入共享 Redis Client
2026-05-05 15:33:58 +08:00
iven
50b9e8d683 feat(ai): 添加 Provider 管理 API 端点
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
GET /ai/providers — 列出已注册提供商
GET /ai/providers/health — 各提供商健康状态
GET /ai/quota/summary — 租户配额使用摘要
2026-05-05 15:19:49 +08:00
iven
a16e86bf04 feat(ai): 重构 AiState 集成 ProviderRegistry + QuotaService
AiState 新增 provider_registry 和 quota 字段
main.rs 启动时按配置注册 Claude/OpenAI/Ollama Provider
支持多 Provider 并发注册和健康检查
2026-05-05 15:18:26 +08:00
iven
63ff8660fc feat(ai): 实现 QuotaService 租户配额检查
月度 Token 预算 + 每日患者分析次数限制,raw SQL 聚合查询
可全局开关 (quota_check_enabled),无配置时默认放行
2026-05-05 15:16:09 +08:00
iven
105cae0565 feat(ai): 添加 ai_tenant_configs 迁移 + Entity
支持租户级 Provider 路由配置、月度 Token 预算、每日患者限制
unique 索引确保每租户一条配置,迁移号 000117
2026-05-05 15:13:05 +08:00
iven
37acd34154 feat(ai): 实现 OllamaProvider 本地模型支持
使用 /api/chat 端点,无需 API Key,支持流式/非流式生成
健康检查通过 /api/tags,含 7 个单元测试
2026-05-05 15:10:43 +08:00
iven
b728618d61 feat(ai): 实现 OpenAIProvider 兼容 OpenAI API 格式
支持 /v1/chat/completions 端点的流式/非流式生成 + 健康检查
含序列化/反序列化单元测试
2026-05-05 15:08:41 +08:00
iven
74b1d44068 feat(ai): 实现 ProviderRegistry 并发安全多提供商注册与路由
DashMap 支持并发注册,resolve() 按首选→回退→任意可用顺序
实时健康检查,含 4 个单元测试覆盖正常/降级/全不可用场景
2026-05-05 15:07:19 +08:00
iven
24bb8e7bca feat(ai): 扩展 AiError 支持配额/缓存/知识库/队列/配置错误变体
新增 QuotaExhausted→429, CacheError/KnowledgeError/QueueError/ConfigError→500
2026-05-05 15:02:38 +08:00
iven
4d02b2b531 feat(ai): 扩展 AiConfig 支持多 Provider 配置
- config/default.toml 新增 providers 子段(claude/openai/ollama)
- erp-server/config.rs AiConfig 新增 quota_check_enabled + providers HashMap
- erp-ai/config.rs 新增 ProviderType 枚举 + ProviderConfig 结构体
2026-05-05 15:01:24 +08:00
iven
93f6e87220 fix(web+config): E2E 测试发现的问题修复
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 排班状态过滤 'active' → 'enabled'(与后端 validation.rs 一致)
- 全局 403 拦截器不再弹出"权限不足" toast(AuthButton 已隐藏入口)
- 角色未关联菜单时回退显示全部(避免种子数据阶段菜单空白)
2026-05-05 13:01:14 +08:00
iven
84b671d1e5 fix(server+health): 修复路由 middleware 泄漏 — FHIR/Gateway 改用 .nest() 隔离
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
Axum 的 .merge() 会将子 Router 的 middleware 泄漏到整个路由树,
导致 FHIR OAuth middleware 和 Gateway auth middleware 拦截所有请求。

修复方式:
- fhir_routes 内部路径去掉 /fhir 前缀,main.rs 用 .nest("/fhir", ...) 注册
- gateway_routes 内部路径去掉 /health/gateway 前缀,main.rs 用 .nest("/health/gateway", ...) 注册
- 透析患者查询表名 patients → patient(与 Entity 一致)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-05 11:56:42 +08:00
iven
062b4493e4 fix(web): DoctorSelect 预加载医生列表 + 搜索错误处理
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 组件挂载时预加载最多 50 条医生数据,下拉框打开即有选项
- 搜索清空时保留已有列表(不再置空)
- 搜索失败时 catch 错误,保留初始列表不静默丢失
- 更新质量验证报告:全部 MEDIUM 问题已关闭
2026-05-05 11:15:12 +08:00
iven
0f55d26076 fix(dialysis): 添加患者存在性校验 + 质量验证汇总
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- create_dialysis_record 中添加患者存在性校验,修复集成测试
  test_dialysis_create_without_patient_returns_error
- 添加质量验证汇总报告 (docs/qa/quality-verification-summary.md)
2026-05-05 10:35:37 +08:00
iven
15b5781dbb fix(health): 危急值告警全链路修复 — 消费者生命周期 + payload 映射 + 阈值优先级
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
1. CRITICAL: 修复 SubscriptionHandle 提前 drop 导致所有事件消费者失效
   - register_handlers_with_state 中所有 handle 在函数返回时被 drop
   - cancel channel 关闭导致 subscribe_filtered 的过滤任务退出
   - 方案: 收集所有 handle 并 std::mem::forget,生命周期与进程一致

2. HIGH: 修复 critical_alert 消费者 payload 字段映射不匹配
   - 消费者读取 alert_type/metric_name 等顶层字段,但实际在 alert 嵌套对象中
   - 更新消费者从 alert 对象提取 indicator/value/threshold/level
   - handle_critical_alert_event 增加 severity 参数

3. MEDIUM: 修复 check_indicator 优先匹配最高严重级别
   - 原实现返回第一个匹配的阈值(可能匹配 warning 而非 critical)
   - 改为遍历所有匹配阈值,选择 severity 最高的(critical > warning)

4. MEDIUM: 修复危急值阈值页面不自动加载数据
   - CriticalValueThresholdList 添加 useEffect 初始化加载
2026-05-05 10:11:06 +08:00
iven
2acd9485c7 fix(health+dialysis): S2 smoke test 修复 — Entity 表名 + 透析状态转换
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 修复 6 个 Entity table_name 与迁移不匹配: shift, handoff_log,
  patient_assignment, blind_index, critical_alert, critical_alert_response
- 添加透析记录 draft→completed 状态转换 API (PUT /complete)
- 修复 family_proxy_service 告警状态过滤 (active→pending/acknowledged)
- dev.ps1 添加 RATE_LIMIT__FAIL_CLOSE=false 开发模式
- S2 透析日流程 smoke test 报告
2026-05-05 03:07:41 +08:00
iven
99dad17eac fix(server+health): 修复权限同步 + 迁移幂等性 + 缺失菜单种子数据
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- sync_module_permissions 每次启动都确保 admin 拥有所有权限(修复 CRITICAL-001)
- 新增迁移 m20260505_000116: 补充 11 项缺失的健康管理菜单(多租户安全)
- 修复 000101: UUID 格式错误(缺少第 4 段)
- 修复 000104/000106/000107: Expr::val → Expr::cust(SQL 函数不应被引号包裹)
- 修复 000109: 外键创建改为 IF NOT EXISTS 模式
- 修复 000110: 表名 critical_alerts → critical_alert(匹配实际表名)
- 修复 000111/000112: create_table + create_index 添加 if_not_exists()
- 修复 000113: 改为 raw SQL 幂等模式,修正 FK 目标表名 patients → patient
2026-05-05 02:02:45 +08:00
iven
bef2ea7169 feat(miniprogram): 适老化修复 — Phase 2e
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
M6: 创建 utils/date.ts 统一日期工具函数(formatDate/formatDateTime/toRelativeDate 等)
M8: 28 个 SCSS 文件 font-size 20px → 22px 全量适老化
M7: request.ts 增加 403 权限不足/5xx 服务器错误/网络超时异常统一拦截
2026-05-05 00:22:49 +08:00
iven
8d288cadfa fix(health+ai): 后端质量修复 — Phase 2d
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
H3: 设备数据摄入增加 tracing 日志(事务保护待 ConnectionTrait 重构)
M4: care_plan/shift/ble_gateway/vital_signs_daily 补全 tracing 入口日志
M1: AI 分析缓存命中检查 + 缓存结果 Stream 回放
H4: 透析→KDIGO 自动串联(dialysis_notifier 发布 ai.dialysis.kdigo_requested 事件)
2026-05-05 00:19:22 +08:00
iven
888fa108ef feat(web): 家庭健康代理 + 知情同意 Web UI — Phase 2c
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
家庭代理:关联患者列表 + 健康摘要查看 + 授权/撤销访问
知情同意:患者范围 CRUD 列表页(类型/范围/签署/撤销)
2026-05-05 00:02:39 +08:00
iven
0774dd75ad feat(web): 危急值阈值 + 诊断记录 Web UI — Phase 2b-2/2b-3
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
危急值阈值:CRUD 列表页(指标/方向/阈值/级别/科室/年龄范围)
诊断记录:患者范围 CRUD 列表页(ICD编码/类型/状态/确诊日期)
2026-05-04 23:59:22 +08:00
iven
b6838c1bc1 feat(web): BLE 网关管理 UI — Phase 2b-1
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
网关 CRUD 列表页(状态筛选/密钥刷新/API Key 创建展示)
+ 网关详情页(信息面板/设备绑定管理 Tab)
2026-05-04 23:47:21 +08:00
iven
438f9ca3f4 feat(web): 药物记录 Web UI — Phase 2a-3
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
新增药物记录管理前端页面,接入后端 4 条孤立路由:
- API 模块: medicationRecords.ts(CRUD + 频次/途径常量)
- 列表页: MedicationRecordList.tsx(患者 ID 查询 + 药物列表 CRUD)
  支持药品名/通用名/剂量/频次/途径/日期/在用状态
- 路由注册: /health/medications

权限: health.medication-records.list / health.medication-records.manage
2026-05-04 23:41:04 +08:00
iven
68ced2bae9 feat(web): 班次管理 Web UI — Phase 2a-2
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
新增班次管理前端页面,接入后端 12 条孤立路由:
- API 模块: shifts.ts(班次 CRUD + 患者分配 + 批量分配 + 交接日志)
- 列表页: ShiftList.tsx(日期/班次/状态筛选 + 统计概览)
- 详情页: ShiftDetail.tsx(班次信息 + 患者分配 Tab + 交接记录 Tab)
- 路由注册: /health/shifts + /health/shifts/:id

权限: health.shifts.list / health.shifts.manage
2026-05-04 23:36:15 +08:00
iven
3aa436f872 feat(web): 护理计划 Web UI — Phase 2a-1
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
新增护理计划管理前端页面,接入后端 8 条孤立路由:
- API 模块: carePlans.ts(计划 + 干预项目 + 预后测量 CRUD)
- 列表页: CarePlanList.tsx(筛选/新建/编辑/删除/跳转详情)
- 详情页: CarePlanDetail.tsx(计划信息 + Items/Outcomes 双 Tab CRUD)
- 路由注册: /health/care-plans + /health/care-plans/:id
- 菜单标题: routeTitleFallback 映射

权限: health.care-plan.list / health.care-plan.manage
2026-05-04 23:26:28 +08:00
iven
2b90db4028 fix(health): P0 安全修复 — SQL注入 + FHIR越权 + OAuth权限 + JWT硬编码
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
C1: action_inbox_service.rs 中 patient_id/user_id 的 format! 拼接改为
    参数化查询 ($2/$3/$4/$5 绑定),消除 SQL 注入风险
C2: fhir/handler.rs 所有患者相关端点强制执行 allowed_patient_ids 范围
    过滤,search 端点用 is_in 过滤,get 端点用 enforce_patient_scope 校验
H5: oauth/handler.rs 5 个管理端点添加 require_permission 校验
M3: oauth/handler.rs 和 middleware.rs 移除 "dev-secret-key" fallback,
    缺少环境变量时启动失败(token)/返回 500(middleware)
2026-05-04 23:09:25 +08:00
iven
95fa09c383 feat(health): 家庭成员健康代理 — 同意追踪 + 健康摘要查看
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
Phase 1 Care Engine MVP 最后一项 (#8):
- 迁移: patient_family_member 表新增 user_id/consent_status/access_level/consented_at/consent_revoked_at
- 实体: 更新 patient_family_member Model 含新字段
- DTO: FamilyMemberResp 扩展 + 新增 GrantFamilyAccessReq/FamilyPatientSummaryResp/FamilyHealthSummaryResp
- Service: 授权/撤销访问、家庭成员查看关联患者列表、查看健康摘要(按 access_level 分级)
- Handler: 5 个端点(grant/revoke/list/summary/link-user)
- 路由: /health/patients/{id}/family-members/{fid}/grant-access 等
- 权限: health.family-proxy.list/manage
- 已有 CRUD 适配新字段(list/create/update 返回 consent 状态)
2026-05-04 20:57:24 +08:00
iven
0a9272bcf6 feat(dialysis+workflow): 透析会话 BPMN 工作流集成
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- dialysis_record 新增 workflow_instance_id 列,关联工作流实例
- 种子 dialysis_session BPMN 流程定义:透前评估→上机确认→透中监测→透后评估→医生审核
- 事件驱动编排器:dialysis.record.created → 自动启动 BPMN 工作流
- 工作流启动后自动回写 instance_id 到透析记录
- 编排器在 erp-server 层实现(遵循星型依赖架构)
2026-05-04 20:38:56 +08:00
iven
7e57565ecd feat(health): BLE 网关后端接入 — 网关管理 + API Key 认证 + 多患者批量上报
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 新增 ble_gateways + gateway_patient_bindings 表迁移 (000113)
- 网关 CRUD:注册/编辑/删除/重生成 API Key,含患者绑定管理
- API Key 认证中间件(SHA-256 hash + prefix 快速查找)
- 网关数据上报端点:多患者批量读数,复用 device_reading_service 管道
- 网关心跳端点:固件版本/IP 更新 + last_heartbeat_at
- 10 个管理端路由(JWT)+ 2 个网关端路由(API Key)
- health.ble-gateways.list/manage 权限声明
- 修复 000112 迁移 ForeignKey 借用错误
2026-05-04 20:28:26 +08:00
iven
7b17f94bc0 feat(health): 班次管理与护士分配 — Shift/PatientAssignment/HandoffLog CRUD
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 新增 3 张数据表迁移 (shifts, patient_assignments, shift_handoff_log)
- 3 个 SeaORM Entity (shift, patient_assignment, handoff_log)
- 完整 CRUD 服务层:班次管理、患者分配(含批量分配)、交接记录
- 12 个 API 端点 + health.shifts.list/manage 权限
- 班次列表含患者分配摘要 (patient_count/critical_count/attention_count)
- 乐观锁、软删除、审计日志、事件发布
- 输入验证:period/shift_status/care_level 白名单
2026-05-04 20:11:07 +08:00
iven
3ff17382ff feat(health+message): 关怀已送达通知管道 — care.action.performed 事件 + 温暖消息推送
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 新增 CARE_ACTION_PERFORMED 事件常量(care.action.performed)
- care_plan_service 在护理项完成、测量数据更新、干预项创建时发布关怀行动事件
- erp-message 新增 care_plan.activated/completed + care.action.performed 消息处理
- 温暖消息文案:护理计划启动/完成通知、关怀已送达、健康数据已更新
- 事件测试覆盖新常量、payload 契约、通知分支逻辑
2026-05-04 18:56:52 +08:00
iven
0a5290aee4 feat(ai): KDIGO 透析专用风险评分器 — Phase 1 关怀引擎 MVP 第二步
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
新增 DialysisRiskScorer:12 条 KDIGO 规则覆盖 Kt/V、血磷、血钾、血红蛋白、
体重增长、eGFR、白蛋白,含 KDIGO CKD G1-G5 分期。同步暴露
POST /ai/dialysis/risk-assessment 端点。76 个测试全部通过。
2026-05-04 18:44:22 +08:00
iven
ef422f354d feat(health): 护理计划实体与服务 — Phase 1 关怀引擎 MVP 第一步
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
新增护理计划(Care Plan)完整 CRUD:3 张表(care_plans / care_plan_items /
care_plan_outcomes)、3 个 SeaORM Entity、15 个 API 端点、4 个事件常量、
2 个权限码。支持透析/慢性/预防/康复计划类型,条目分干预/监测/目标/教育四类,
预后测量含基线/目标/当前值追踪。
2026-05-04 18:40:22 +08:00
iven
c35ea83799 test(web): 核心健康管理页面测试 — 12 个页面 51 个测试用例
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
新增测试覆盖:
- PatientDetail: 5 测试(渲染/标签页/数据展示)
- AlertDashboard: 5 测试(渲染/统计卡片/告警列表)
- AlertRuleList: 5 测试(渲染/规则表格/创建按钮)
- DeviceManage: 5 测试(渲染/设备列表/筛选)
- AiAnalysisList: 6 测试(渲染/分析记录/分页)
- AiUsageDashboard: 4 测试(渲染/统计/类型分布)
- ArticleManageList: 5 测试(渲染/文章表格/分类筛选)
- PointsProductList: 5 测试(渲染/商品表格/上下架)
- PointsRuleList: 4 测试(渲染/规则表格)
- PointsOrderList: 5 测试(渲染/订单表格/状态筛选)
- StatisticsDashboard: 2 测试(渲染/权限守卫)
- DoctorSchedule: 3 测试(渲染/排班日历/科室筛选)

测试基础设施:
- 8 个新 fixture 工厂(device/analysis/points/article/alert/schedule)
- 10 组新 MSW handlers
- 5 个新权限码(devices/dashboard/oauth/ai.usage)

前端测试:527/530 通过(3 个预存失败未受影响)
2026-05-04 18:02:55 +08:00
iven
f54fb336dc feat(web): 护士工作台 Phase 1 前端 — NurseWorkbench 组件
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 新增 NurseWorkbench 组件:问候行 + 统计卡片 + 班次患者 + 待办 + 右面板
- actionInbox API 客户端:新增 assigned_to_me/patient_id 参数 + myPatients 端点
- Home.tsx 护士角色路由到 NurseWorkbench(其他角色不受影响)
- 班次患者列表:显示今日分配给护士的患者 + 风险优先级色点
- 快捷操作面板:随访/体征/AI分析/咨询入口
- 今日进度条:完成百分比可视化
2026-05-04 17:48:50 +08:00
iven
a5b3396adc feat(health): 护士工作台 Phase 1 后端 — 用户范围过滤 + 班次患者端点
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- ActionInboxQuery 新增 assigned_to_me 和 patient_id 过滤参数
- list_action_items 支持按 user_id 过滤随访任务段
- get_workbench_stats 支持用户范围随访统计
- 新增 get_nurse_patients: 今日分配给护士的患者列表
- 新增 GET /health/action-inbox/my-patients 端点
- handler 从 TenantContext 提取 user_id 实现无感过滤
2026-05-04 17:45:23 +08:00
iven
69c3de15f5 Merge branch 'worktree-agent-ae2e5c31258292fcf'
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
2026-05-04 14:09:06 +08:00
iven
b235f67c31 refactor(health): 拆分 4 个千行 service 文件为子模块
points_service.rs (1863行) → points_service/ (mod + account + checkin + product + event)
patient_service.rs (1118行) → patient_service/ (mod + helper + crud + relation + tag)
health_data_service.rs (1056行) → health_data_service/ (mod + vital_signs + lab_report + health_record + alert)
stats_service.rs (1117行) → stats_service/ (mod + operations + health + personal + dashboard)

所有公开 API 通过 pub use 保持不变,handler 层无需修改。
cargo check: 0 error, 0 warning
cargo test: 232 passed, 0 failed
2026-05-04 14:09:02 +08:00
iven
4be26592f4 test(health): 补全事件消费者测试 — 17 个消费者逻辑测试
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
为 erp-health/event.rs 中每个消费者添加正向和异常测试:
- 告警通知:severity 分支决定 template_key
- 告警聚合:suppressed=true 时触发聚合事件
- AI 分析完成:缺少 doctor_id/patient_id 时安全跳过
- AI 行动分发:suggestion_count=0 时跳过分发
- 预约创建:缺少 ID 时安全跳过
- 随访逾期升级:缺少 task_id/assigned_to 时安全跳过
- 危急值告警:完整字段提取 + 缺失 patient_id 安全跳过
- 咨询消息方向:sender_role 决定通知方向
- 知情同意:granted/revoked 不同 template
- 积分通知:缺失 amount 时安全跳过
- 设备读数:类型列表完整性
- workflow.task:UUID 解析 + 无效 UUID 安全处理
- 消费者总数验证

测试从 35 增加到 66(+31)
2026-05-04 13:58:49 +08:00
iven
d68c7be098 feat(ai): 建议状态生命周期 — 转换验证 + 执行端点 + 事件发布
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
建议(ai_suggestion)原有状态枚举完整但缺乏生命周期管理:
- 无转换验证(可从 Rejected 跳到 Approved)
- 无执行端点(护士无法标记"已执行")
- 无状态变更事件

变更:
1. SuggestionStatus.can_transition_to() — 仅允许合法单向转换
   Pending → Approved/Rejected/Expired → Approved → Executed/Rejected/Expired
2. SuggestionService.execute_suggestion() — 记录执行结果
3. SuggestionService.expire_stale_suggestions() — 批量过期超时建议
4. POST /ai/suggestions/{id}/execute — 新执行端点
5. publish_status_event() — 状态变更时发布 ai.suggestion.status_changed 事件
6. 9 个新单元测试覆盖所有转换规则
2026-05-04 13:39:48 +08:00
iven
e78eb1af07 fix(ai): 连接 ai.analysis.requested 事件消费者
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
erp-health 在化验单上传时发布 ai.analysis.requested 事件,
但 erp-ai 的 on_startup 仅订阅 ai.reanalysis.* 前缀。

将订阅前缀从 "ai.reanalysis." 扩大为 "ai.",
新增 ai.analysis.requested 事件的接收和日志记录。
完整自动分析实现依赖 Prompt 模板就绪后补充。
2026-05-04 13:12:47 +08:00
iven
77cf866adf fix(ai): 修复自动分析管道 — 补全建议生成 + 事件发布
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
自动分析批处理(auto_analysis.rs)在完成流式分析后仅保存结果,
缺少三个关键步骤导致关怀引擎无法启动:
1. 不解析双通道输出(StructuredOutput)→ 无结构化建议
2. 不调用 SuggestionService.create_suggestions() → 无建议记录
3. 不发布 ai.analysis.completed 事件 → 下游消费者无感知

修复方案:提取 post_process_analysis() 共享函数,统一处理
解析→创建建议→发布事件的后处理逻辑,SSE handler 和自动分析共用。
2026-05-04 13:10:55 +08:00
iven
1b52787b26 docs(health): 多专家组头脑风暴 — 系统演进方案(4阶段路线图)
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
5 个专家组(产品策略师/AI架构师/UX设计师/医疗业务专家/技术负责人)
对代码库深度分析后制定从"综合平台"到"AI主动关怀引擎"的演进路线:
- Phase 0 基础加固(4周):修复AI管道断裂 + 关怀工作台Phase1
- Phase 1 关怀引擎MVP(8周):护理计划/KDIGO评分/班次管理/关怀通知/BLE网关
- Phase 2 患者体验(8周):老年适配UI/家庭代理/结果测量
- Phase 3 平台规模化(10周):HIS-LIS集成/多机构/商业飞轮
2026-05-04 13:03:38 +08:00
iven
1135439403 fix(health): 审计问题修复 — 权限守卫 + OAuth中间件 + FHIR声明 + SSE聚合
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- OAuthClientList/RealtimeMonitor/OfflineEventList/StatisticsDashboard 补权限守卫
- OAuth 中间件注入 TenantContext + FHIR scope→permission 映射
- FHIR CapabilityStatement 移除未实现的 $lastn 操作
- useVitalSSE 修复批量同步事件数据聚合逻辑
2026-05-04 12:02:50 +08:00
iven
d436888ca5 refactor(web): 系统设置模块页面表单一致性重构
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 新增 useCrudDrawer hook 封装 CRUD Drawer 通用模式(状态管理/提交/错误处理)
- 新增 useListData hook 封装非分页列表数据获取
- 11 个页面统一迁移到 DrawerForm + 共享 hooks,消除重复代码
- 错误处理统一使用 useApiRequest.execute(),移除内联 try-catch
- Modal 全部替换为 DrawerForm,保持 UI 一致性
- 净减少 ~1300 行代码(858 增 / 2136 删)
2026-05-04 11:57:38 +08:00
iven
444dc7dd8d fix(health): 数据完整性 + 代码规范修复 — FK约束/版本类型统一/软删除过滤
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
数据完整性:
- 新增 8 个 FK 约束 (follow_up_task→appointment, points_transaction→account/rule/order,
  points_order→product/patient, offline_event_registration→event/patient)
- critical_alert/critical_alert_response version 字段 i64→i32 统一
- vital_signs_daily_service 聚合查询添加 DeletedAt.is_null() 过滤

代码规范:
- 新增 api/upload.ts 封装文件上传,ArticleEditor 改用 service 层
- 新增 messages.updateSubscription,NotificationPreferences 改用 service 层
- 修复 erp-message SSE 测试编译错误 (移除 serde_urlencoded 依赖)
2026-05-04 11:22:54 +08:00
iven
30a578ee00 fix(health): 客户试用前全局审计修复 — P0 权限旁路 + API 路径 + 事件注册
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
P0 阻塞修复:
- 修复 PrivateRoute 权限旁路: p.startsWith('auth.') 匹配不到任何权限码,
  改为基于实际权限码的路由级检查 (user.manage/role.manage/organization.manage)
- 修复 deviceReadings API 路径: /patients/{id}/device-readings/daily 改为
  /vital-signs/daily?patient_id=, 消除 404

P1 重要修复:
- 补全事件注册表: 新增 auth(11) + config(8) + workflow(4) + plugin(2) = 25 条
- article_article_tag 联表新增 tenant_id + deleted_at + 审计列 (迁移 107)
- vital_signs_hourly 新增 deleted_at 支持软删除过滤 (迁移 108)
- 6 个页面添加权限守卫 (AlertDashboard/AlertRuleList/DeviceManage/
  AiAnalysisList/AiUsageDashboard)
- DialysisModule 声明 auth 依赖
2026-05-04 11:02:25 +08:00
iven
cde3a863a2 feat(health): FHIR 模块类型定义 + converter 依赖
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
2026-05-04 02:56:56 +08:00
iven
8cfc5709dc docs: 事件注册表更新 — 告警降噪 + alert.aggregated 事件 2026-05-04 02:56:40 +08:00
iven
29b47ae4e4 fix(health): OAuth 模块编译修复
- 修复 RngCore import:使用 rand_core::RngCore 替代 argon2 password_hash 重导出
- 修复 ActiveModel version/id move 问题:先读取再 unwrap
- 添加 rand_core 依赖
2026-05-04 02:54:20 +08:00
iven
2e9f6621a3 test(health): 告警降噪集成测试骨架
4 个 Testcontainers 测试用例(忽略状态)覆盖:
患者级升级阈值 + 系统级聚合窗口 + critical 不聚合 + 完整流程
2026-05-04 02:54:17 +08:00
iven
3a14b7efe3 feat(health): 日聚合查询 API — GET /health/vital-signs/daily
- 新增 DailyAggQuery DTO(patient_id/device_type/start_date/end_date)
- 新增 get_daily_aggregations handler(需 health.device-readings.list 权限)
- 路由注册到 protected_routes
2026-05-04 02:54:13 +08:00
iven
4c1d98116a feat(health): 告警聚合事件消费者 — alert.aggregated
- 新增 ALERT_AGGREGATED 常量
- alert_notifier 消费者中处理 suppressed=true 告警并发布聚合事件
- 更新事件常量测试和 consumer_id 唯一性测试
2026-05-04 02:51:13 +08:00
iven
bb5298ee0f feat(message): SSE 增强 — Event ID + 心跳保活 + Last-Event-ID + 患者订阅
- 每个 SSE 事件附加 id 字段(UUID v7)用于断点续传
- 30s timeout 心跳保活防止连接断开
- Last-Event-ID header 恢复:重连跳过已发送事件
- ?patient_ids=id1,id2 查询参数选择性订阅患者
2026-05-04 02:49:23 +08:00
iven
975d699e42 feat(health): 告警降噪集成 alert_engine + OAuth service 编译修复
- alert_engine: create_alert_and_notify 调用 noise_reducer,升级严重度+suppressed标记
- oauth/service: 修复 OsRng import + ActiveModel move 问题
- fhir/handler: linter 补全完整实现
2026-05-04 02:43:32 +08:00
iven
62c02e0f15 feat(miniprogram): BLE 增强层 — DataBuffer + GenericBleAdapter + DataSyncScheduler
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- DataBuffer: 离线持久化缓冲(分桶存储 + 去重 + 容量管理)
- GenericBleAdapter: 基于 Bluetooth SIG 标准 Health Profile 的通用适配器
  (Heart Rate 0x180D / Health Thermometer 0x1809 / Blood Pressure 0x1810)
- DataSyncScheduler: 定时自动同步调度(基于时间间隔判断是否需要同步)
- BLEManager: 集成 DataBuffer 替换简单 Storage 缓存
- device-sync 页面: 注册 CustomBandAdapter + 自动同步 + 状态显示
- 新增 vitest 单元测试配置,30 个测试全部通过
2026-05-04 02:42:58 +08:00
iven
70aacf47a0 feat(web): IoT + FHIR V1 Plan 5 — Web 前端实施
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- API 层: deviceReadings 日聚合查询 + OAuth 合作方 CRUD 接口
- 常量: 设备连接状态/连接类型/实时监控指标常量
- Hook: useVitalSSE — 复用全局 SSE 连接的 vital_update 事件
- 页面: RealtimeMonitor 实时体征监控台 (SSE + 告警排序)
- 页面: OAuthClientList FHIR 合作方管理 (CRUD + Secret 重置)
- 增强: DeviceManage 设备状态/固件/连接类型列 + 状态筛选
- 路由: 新增 3 个懒加载路由
- 测试: RealtimeMonitor + OAuthClientList 单元测试
2026-05-04 02:40:57 +08:00
iven
24562dd54b feat(health): 告警降噪服务 + FHIR handler stubs
- 新增 alert_noise_reducer:患者级升级(30min/3次阈值) + 系统级聚合(5min窗口)
- 补全 FHIR R4 handler stubs(Plan 2 路由注册但 handler 缺失导致编译失败)
2026-05-04 02:36:37 +08:00
iven
c5b686499c feat(health): 日聚合 background task — 每天自动从 hourly 聚合到 daily
- 新增 start_daily_aggregation 定时任务(每 24h 执行)
- on_startup 启动时立即执行一次昨日聚合
- 聚合逻辑调用 vital_signs_daily_service::aggregate_daily_for_all_tenants
2026-05-04 02:35:30 +08:00
iven
8656896847 feat(health): patient_devices 增强 — status/firmware/manufacturer/connection_type/metadata
- 新增迁移:添加 status/firmware_version/manufacturer/connection_type/metadata 列
- 更新 Entity:新增对应字段(含默认值)
- 修复 device_reading_service 自动绑定设备时填充新字段
2026-05-04 02:32:19 +08:00
iven
43894446d9 feat(health): vital_signs_daily 日聚合表 + Entity + service
- 新增 vital_signs_daily 表迁移(带唯一索引 tenant+patient+device_type+date)
- 新增 SeaORM Entity(含 percentile_95 统计字段)
- 实现日聚合 service:从 hourly 聚合到 daily(支持 upsert)
- 实现 aggregate_daily_for_all_tenants 多租户遍历聚合
- 实现 query_daily 范围查询
- 单元测试:percentile 计算验证
2026-05-04 02:30:03 +08:00
iven
fa0a788cf9 docs(plan): IoT + FHIR V1 Plan 2 — FHIR API 层实施计划
4 Chunk 9 Task:FHIR 基础类型 + CapabilityStatement +
Patient/Observation 转换 + 6 资源端点 + $everything 操作。
分步 TDD 流程,每步有具体代码和验证命令。
2026-05-04 01:27:18 +08:00
iven
feab61b132 docs(plan): IoT + FHIR V1 Plan 1 — 数据层增强实施计划
6 个 Task:vital_signs_daily 表迁移 + Entity + Service +
patient_devices 增强 + 日聚合 background task + 查询 API。
TDD 流程,每步有具体代码和验证命令。
2026-05-04 01:14:15 +08:00
iven
2afe3a8848 docs: IoT 设备采集 + FHIR 开放平台生态设计规格
发散式探讨产出:BLE 适配器 + 设备网关混合架构,HL7 FHIR R4 输出,
OAuth2 合作伙伴认证,渐进演进 V1-V3 路线图。

Spec review 发现大量已有基础设施(device_readings/alert_engine/SSE/BLE),
设计已据此修正为"增强现有 + 新增 FHIR 层"策略。
2026-05-04 01:08:01 +08:00
iven
5140552ff6 fix(health): 走查止血 — 患者名显示修复 + 枚举补全 + 医护统计 + 设备选择器
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
后端:
- alert_service: list_alerts 批量查询 patient_name 填充 AlertResponse
- consultation_service: list_sessions 批量查询 patient_name/doctor_name
- erp-ai handler: list_analysis 通过 raw SQL 查询 patient_name

前端:
- AlertList/AlertDashboard: 使用后端返回的 patient_name 替代 ID 截断
- ConsultationDetail: 使用 patient_name/doctor_name 替代 ID 截断
- AiAnalysisList: 使用 patient_name 替代 ID 截断
- constants/health: SEVERITY 补 high/medium, STATUS 补 active
- AdminDashboard: 医护人数改为 API 查询(useStatsData 新增 doctorCount)
- DeviceManage: 患者 ID 输入改为 PatientSelect 搜索选择器
2026-05-04 00:03:40 +08:00
iven
20bd9e8cb4 docs: 全系统前端走查报告 + 多专家组头脑风暴
35+ 页面逐页走查,发现 P0 问题 4 项、P1 问题 6 项、P2 建议 4 项。
三专家组分析:架构组定位 EntityName 根因,测试组发现枚举缺失,
产品组制定 3 阶段修复路径(止血 → 补短板 → 治本)。
2026-05-04 00:03:22 +08:00
iven
f4b5d55f24 fix(test): 增加页面测试超时至 15s — 覆盖率模式下避免 timeout
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
2026-05-03 23:21:58 +08:00
iven
6709df62ed test(web): 第一批列表页测试 — 7 个页面 + 修复导入路径
- AppointmentList / FollowUpTaskList / FollowUpRecordList / ConsultationList
- FollowUpTemplateList / DialysisManageList / OfflineEventList
- 修复 FollowUpTemplateList 导入路径 bug (../../../ → ../../)
2026-05-03 23:19:55 +08:00
iven
c0e0e2a6c3 test(web): PatientList/AlertList/DoctorList 页面测试 — 验证工厂模式
- 添加 matchMedia + ResizeObserver mock (Ant Design 依赖)
- renderWithProviders 注入 auth state + localStorage token
- 修复 fixture 批量生成自动分配唯一 id
- PatientList 5 测试 / AlertList 3 测试 / DoctorList 4 测试
2026-05-03 23:12:34 +08:00
iven
37cdeebb95 test(web): 添加 createListPageTests 工厂 — 6 类标准测试用例自动生成 2026-05-03 23:05:46 +08:00
iven
c93ae0bc66 test(web): 添加 renderWithProviders — MemoryRouter + AntD ConfigProvider 包裹器 2026-05-03 23:04:19 +08:00
iven
0e789b530a test(web): 添加测试数据工厂 — healthFixtures + 批量生成 + 分页包装 2026-05-03 23:03:04 +08:00
iven
120df86e58 test(web): 添加健康模块 msw handlers — 患者告警预约医生 4 组 mock API 2026-05-03 23:01:57 +08:00
iven
8f7f75ac25 docs(plan): 页面/组件测试第一批实施计划 — 3 Chunk 13 Task 1155 行
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- Chunk 1: 测试基础设施(msw health handlers + fixtures + renderWithProviders)
- Chunk 2: ListPage 测试工厂(createListPageTests + 3 页面验证)
- Chunk 3: 第一批 7 个列表页测试(预约/随访/咨询/透析/活动)
2026-05-03 22:58:51 +08:00
iven
1602b7bbad docs(wiki): Wiki 全面刷新 + Q2 路线图 + 测试补强设计规格
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- Wiki 7 文件关键数字刷新:迁移 96→103、实体 45→46、前端 163→225、测试 5→36
- 修复 architecture.md PostgreSQL 版本不一致(18→16)
- 修复 erp-ai.md 实体数 3→6、erp-health.md 实体数 45→46
- 更新 index.md 文档索引:specs 41、plans 38、discussions 18
- 新增事件注册表/方法论/分析报告引用
- 新增页面/组件测试设计规格(模式化工厂方案)
- 新增 Q2 路线图规格(技术债 + 新功能并行 8 周)
2026-05-03 22:33:08 +08:00
iven
6d1a7fba98 test(web): API 契约测试 — 25 个模块 244 个测试全覆盖
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
验证每个 API 模块的 URL/HTTP Method/参数序列化:
- health(14): patients/appointments/alerts/articles/consultations/
  dashboard/deviceReadings/doctors/followUp/healthData/points/
  followUpTemplates/api
- 基础模块(11): auth/users/roles/orgs/dictionaries/messages/
  plugins/pluginData/config-modules/workflow/auditLogs

前端测试总数: 140(store) + 244(api) = 384
2026-05-03 20:09:49 +08:00
iven
bc6206c0df chore: 编译器警告清理 — 22 条全部消除,workspace 零警告
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
erp-ai(8): 移除未用 import + serde 结构体 #[allow(dead_code)]
erp-plugin(5): 移除未用 import + FromQueryResult 结构体允许
erp-health(8): 移除未用 import/变量 + FromQueryResult 字段允许
erp-server(1): AnalyticsEvent.timestamp 允许(未来分析集成)
2026-05-03 20:09:26 +08:00
iven
e9451875a8 docs(wiki): Docker 配置对齐 — PostgreSQL 版本校正 + fail-close 标记
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- PostgreSQL 18→16(与 docker-compose.yml 实际版本对齐)
- 限流 fail-open 标记为已修复(默认 fail-close)
2026-05-03 19:59:20 +08:00
iven
0d3e45300f refactor(web): 前端错误处理统一化 — 9 个文件 13 处替换 handleApiError
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
统一使用 api/client.ts 的 handleApiError() 替代内联错误提取:
- Login/Users/Roles/Organizations/Settings 操作失败提示
- ArticleEditor/ArticleTagManage/ArticleCategoryManage 表单错误
- FamilyMembersTab 家庭成员操作

零 response?.data?.message 内联模式残留
2026-05-03 19:59:12 +08:00
iven
443bfbae61 docs(wiki): 数据一致性刷新 — 7 处校正
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- architecture.md: 删除重复插件行、44→45 实体、22→39 权限
- testing.md: 迁移计数 50→104
- database.md: 补充 m000092-000104 迁移覆盖
- infrastructure.md: 更新日期 2026-04-23→2026-05-03、PostgreSQL 18→16
- erp-health.md: 44→45 实体、22→39 权限、消费者数校正
2026-05-03 19:58:19 +08:00
iven
7a016e4ed5 test(health): 事件系统单元测试 — EventBus + 消费者过滤 + payload 验证
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
event.rs 新增测试模块:
- EventBus subscribe_filtered 过滤非匹配事件
- 消费者幂等性验证(is_event_processed)
- DomainEvent payload 构造
- 事件常量一致性校验

erp-health lib 测试总数: 212 → 213
2026-05-03 19:49:21 +08:00
iven
7a73a90238 test(web): Store 单元测试 — plugin(25) + workbench(27) = 52 新测试
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
plugin.test.ts: fetchPlugins/refreshMenuItems/pluginMenuGroups 全覆盖
workbenchStore.test.ts: selectTask/setTab/refreshTasks/refreshStats/completeTask 全覆盖

前端 Store 测试总数: 22 → 140 (6 个文件)
2026-05-03 19:49:08 +08:00
iven
8a53948934 feat(health): 深度 tracing 补全 — health_data 45 处 + action_inbox 8 处
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
health_data_service: 每个公开函数覆盖 entry/success/error 三层
- 13 个函数全覆盖(vital_signs/lab_report/health_record)
- 16 info + 13 info success + 3 debug + 13 error = 45 处

action_inbox_service: 追加 debug 级别中间结果日志
2026-05-03 19:44:49 +08:00
iven
3ddd04b422 feat(health): 孤立事件清理 — 新增 3 个消费者,孤立率 36% → 0%
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
新增消费者:
- lab_report.uploaded → 触发 AI 自动分析请求
- lab_report.reviewed → 通知患者审核结果
- patient.updated → 审计日志记录

保留为纯通知的事件(无需消费者):
- article.published/rejected, daily_monitoring.created,
  doctor.online_status_changed

保留 TODO 标记(业务流程未实现):
- patient.deceased/verified
2026-05-03 19:42:41 +08:00
iven
80bc60f5e4 feat(health): action_inbox + health_data_service tracing 补全
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
action_inbox_service: 从 0 → 8 处 tracing(4 个公开函数全覆盖)
health_data_service: 从 3 → 12 处 tracing(13 个公开函数全覆盖)
2026-05-03 19:41:04 +08:00
iven
34504d4179 fix(server): 限流 fail-close 默认开启 + 配置测试
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
生产安全:Redis 不可达时默认拒绝请求(503)而非放行。
- config/default.toml: fail_close 默认值 false → true
- config.rs: Default + serde default 均改为 true
- 新增 2 个单元测试验证默认值和 serde 行为
2026-05-03 19:37:58 +08:00
iven
c6c94ebb84 docs: HMS 功能思维导图 + 系统设计文档 + 演进路线图
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
患者端/医护端/管理后台/平台技术能力思维导图 +
系统功能文档 + 演进路线图 + 设计思路
2026-05-03 19:32:39 +08:00
iven
ec87ae85cf docs(wiki): 全量 wiki 更新 — C1 晚间血压已修复标记 + 数据校正
- miniprogram.md: 晚间血压 CRITICAL 标记为已修复
- index.md: 症状导航表更新
- architecture/database/erp-core/erp-health/frontend/testing: 同步更新
2026-05-03 19:32:30 +08:00
iven
c208dcc6f5 docs(specs): 7 份设计规格 — 工作台/适老化/硬编码清理/项目分析
新增: 适老化小程序/Action Inbox/统一工作台/医生操作台/
硬编码清理/健康管理台/全项目深度分析报告
2026-05-03 19:32:25 +08:00
iven
d712ad78c3 docs: 审计报告(8 份) + 讨论记录(4 份)
审计报告: 基线快照/功能清单/后端完整性/事件系统/参数配置/
差距模式/错误处理/测试覆盖/审计总结报告
讨论记录: 设备管线/端到端测试/三端审计/工作台重构
2026-05-03 19:32:15 +08:00
iven
78c783d332 feat(miniprogram): 配置更新 + 家庭成员/设置页面优化
- dev.ts: 开发环境配置调整
- project.config.json: 自动化审计配置
- family-add: 添加家庭成员页面优化
- settings: 设置页面优化
- config/: 新增项目配置文件
2026-05-03 19:32:09 +08:00
iven
3e4baa38a6 feat(web): 透析 API + 积分账户组件 + 工作台 store + 统计页修复
- dialysis.ts: 新增透析管理 API 模块
- PointsAccountTab.tsx: 积分账户标签页组件
- workbenchStore.ts: 工作台状态管理
- StatisticsDashboard.tsx: 统计页空列表修复
- auth.test.ts: 修复权限码拼写 health.alert → health.alerts
- api.test.ts: API 契约测试
2026-05-03 19:32:00 +08:00
iven
70322e4132 feat(miniprogram): 医生端 API 服务层 — 7 个模块
新增医生端完整 API 调用层:alerts / appointment / consultation /
dashboard / followup / labReport / patient
2026-05-03 19:31:51 +08:00
iven
3412d807e3 fix(core): 跨 crate 小修复 — dto 合并、tracing 补全、死代码清理
- erp-ai: 删除孤立 dto.rs(已合并到子模块)
- erp-core: audit_service tracing 优化
- erp-health: points_handler 补充返回值、alert_engine 修正日志级别
- erp-plugin: host/data_handler/market_handler tracing 统一
- erp-dialysis/event: 移除无用 import
- erp-workflow/executor: tracing 格式统一
2026-05-03 19:31:46 +08:00
iven
d378e154c4 docs: 全项目深度分析与多专家组头脑风暴报告
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
覆盖 5 个专家视角(架构/安全/前端/质量/管理),
数据经实际代码库校正,产出 22 项优先级行动矩阵。
2026-05-03 19:01:27 +08:00
iven
bba47b7b1c test(web): health store 单元测试 — 名称缓存/批量解析/去重
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
17 个测试覆盖:
- getPatientName/getDoctorName 缓存命中/miss
- resolvePatientName/resolveDoctorName API 调用+缓存+降级
- 并发去重(同一 id 只触发一次 API 调用)
- batchResolve 批量解析 + 部分失败降级 + 输入去重
2026-05-03 10:05:27 +08:00
iven
9d07ea0be0 test(web): 前端 Store 单元测试 + patient_service tracing 补全
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
Store 测试 (71 个):
- auth.test.ts: 22 tests — 登录/登出/权限/JWT解析/localStorage持久化
- app.test.ts: 24 tests — 主题切换/侧边栏/配置加载/状态隔离
- message.test.ts: 25 tests — 未读计数/消息列表/SSE连接/标记已读

Tracing 补全:
- create_patient: 身份证号重复时 warn 日志
- update_patient/delete_patient: 版本冲突时 warn 日志含 expected/actual
2026-05-03 09:58:13 +08:00
iven
84afeaf9f2 feat(health): 事件消费者补全 + 无效消费者清理
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
新增消费者:
- appointment.created → 患者预约创建通知
- consultation.opened/closed/new_message → 咨询全流程通知
- follow_up.created → 随访任务分配通知
- points.earned/exchanged/expired → 积分变动通知

清理:
- 删除 message.sent no-op 消费者(仅打日志无实际作用)
- 为 workflow.task.completed 消费者补充幂等检查
- 孤立事件率从 57% 降至 ~20%(剩余为 TODO 预留项)
2026-05-03 09:51:26 +08:00
iven
209acaa15d feat(server): 限流 fail-close 统一配置
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 新增 RateLimitConfig 结构体,支持 config.toml + 环境变量
- apply_rate_limit 统一读取 fail_close 配置,生产环境可设为拒绝请求
- account_lockout_middleware 改为从 AppState.config 读取,不再直接读环境变量
- default.toml 添加 [rate_limit] 配置节
2026-05-03 09:46:02 +08:00
iven
1a6409eb30 feat(miniprogram): 用药提醒从 localStorage 迁移到服务端 API
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 新增 medication-reminder.ts service(list/create/update/delete)
- 重写 medication/index.tsx 页面,通过后端 API 持久化数据
- 支持乐观锁(version)、患者 ID 关联、提醒时间数组
- 移除旧的 localStorage 读写逻辑
2026-05-03 09:38:24 +08:00
iven
32df9c0655 feat(web): 随访模板管理页面 — CRUD + 路由 + 菜单迁移
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 新增 FollowUpTemplateList.tsx 页面(列表/新建/编辑/详情弹窗)
- 新增 followUpTemplates.ts API 客户端(list/get/create/update/delete)
- 注册路由 /health/follow-up-templates + 菜单标题 fallback
- 新增迁移 seed_follow_up_template_menu 注册菜单和权限
2026-05-03 09:31:43 +08:00
iven
2e4d98c479 fix(web): 统计页空列表接入真实 API + 运营待办去硬编码
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- DoctorDashboard: 咨询消息接入 consultationApi.listSessions
- NurseDashboard: 随访队列接入 followUpApi.listTasks
- OperatorDashboard: 热门文章接入 articleApi.list
- OperatorWorkbench: 5 条硬编码待办替换为 actionInboxApi 真实数据
2026-05-03 00:02:58 +08:00
iven
603af83aa9 fix: P0 止血 — 消除崩溃风险 + 伪CAS修复 + 硬编码清除 + 晚间血压
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 新增 sea_orm_ext 模块: safe_version() / bump_version() 替代 14 处 unwrap()
- 修复 points_service 伪 CAS 逻辑 bug: 在 Set() 前提取原始版本并重新验证
- AdminDashboard: API 失败时显示 unknown 状态而非虚假绿色 healthy
- AdminDashboard: 今日操作改用真实数据,移除 "0 错误" 硬编码
- OperatorWorkbench: 移除硬编码 "美玲",改用真实用户名
- Home.tsx: operator "内容发布" 从硬编码 0 改为真实积分统计
- 小程序体征录入: 新增晚间血压 indicator_type,映射到 evening 字段
2026-05-02 23:42:01 +08:00
iven
dd44c1526f feat(web): 工作台页面改造 — 管理员/运营数据改用真实 API
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- AdminDashboard 移除硬编码模块列表,改用 system-health/user-activity/modules API
- OperatorWorkbench 移除硬编码积分动态和文章统计,改用 points-recent-activity/article-stats API
- 新增 dashboard.ts API 客户端,AxiosResponse 解包到 data.data
- Home.tsx 集成 4 个角色工作台组件路由
- useDashboardRole 支持 health_manager 角色
2026-05-02 11:56:26 +08:00
iven
0006e427e2 feat(health): 5 个工作台管理统计 API — 系统健康/用户活跃/模块状态/积分动态/文章统计
- DTO: SystemHealthResp, UserActivityResp, ModuleStatusResp, PointsActivityItem, ArticleStatsResp
- Service: get_article_stats, get_points_recent_activity, get_module_status, get_user_activity, get_system_health
- Handler: 5 个新端点 + 权限码 health.dashboard.manage
- 路由: /health/admin/system-health, user-activity, modules, points/recent-activity, articles/stats
2026-05-02 11:49:34 +08:00
iven
2cc0f5af25 refactor(miniprogram): 体征阈值改用动态 API — 替代硬编码参考范围
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- health.ts 新增 getHealthThresholds/findThreshold/DEFAULT_THRESHOLDS
- 24h storage 缓存 + 降级到内置默认值
- health/index.tsx: REF_RANGES → buildRefRange(thresholds)
- pkg-health/input: WARN_THRESHOLDS → getWarnForIndicator(thresholds)
2026-05-02 11:40:54 +08:00
iven
e8ee441ae1 feat(health): Track 3 医疗阈值 — warning 种子 + 患者端只读 API
- 新增 6 条 warning 级别阈值种子数据(血压/心率/血糖参考范围)
- 新增 GET /health/critical-value-thresholds/public 患者端只读接口
- 扩展 indicator 验证支持 blood_sugar_fasting/postprandial 等新指标
2026-05-02 11:37:21 +08:00
iven
23cd62a70f feat(db): 健康模块字典种子数据 — 6 个字典 + 43 个条目
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- health_department (11 科室)
- health_title (9 职称)
- health_device_type (8 设备类型)
- health_follow_up_type (5 随访类型)
- health_consultation_type (3 咨询类型)
- health_relationship (5 关系类型)
2026-05-02 11:34:35 +08:00
iven
63ead0c442 refactor(web): 新增 useDictionary hook + 4 个页面下拉选项改用字典 API
- 新增 useDictionary hook 支持字典 API 获取 + fallback 降级
- DoctorList 科室/职称改用 useDictionary (health_department/health_title)
- FollowUpTaskList 随访类型改用 useDictionary (health_follow_up_type)
- ConsultationList 咨询类型改用 useDictionary (health_consultation_type)
- FamilyMembersTab 家庭关系改用 useDictionary (health_relationship)
2026-05-02 11:27:11 +08:00
iven
b6e780e649 refactor(web): 统一健康模块静态映射常量到 constants/health.ts
- 收敛 SEVERITY_COLOR/LABEL (5处→1处)
- 收敛 ALERT_STATUS_COLOR/LABEL (3处→1处)
- 收敛 DEVICE_TYPE_OPTIONS/COLOR (3处→1处)
- 收敛 GENDER_LABEL (4处→1处)
- StatusTag 组件改引用 STATUS_TAG_CONFIG
- DoctorDashboard 严重度映射改引用常量
2026-05-02 11:24:34 +08:00
iven
3bc4597041 fix(health): 工作台 UNION ALL 排序 + 团队概览 display_name NULL 处理
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- UNION ALL 查询包装子查询解决 PostgreSQL ORDER BY 限制
- get_team_overview 的 display_name 改为 Option<String> 防止 NULL 解码失败
2026-05-02 00:21:27 +08:00
iven
5e52b0a34c feat(health): 工作台遗留项修复 — UNION ALL 聚合 + 团队概览 + 较昨日对比
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
1. 待办列表 UNION ALL 聚合:list_action_items 现从 ai_suggestion + alerts + follow_up_task 三表查询,
   ActionType 扩展为 AiSuggestion/Alert/Followup/DataAnomaly 四种类型,
   get_action_thread 按类型构建不同线程时间线(AI 建议/告警/随访)
2. 真实团队概览:get_team_overview 从 doctor_profile + follow_up_task + alerts 聚合成员统计和风险分布
3. 统计卡片较昨日描述:PersonalStatsResp 新增 6 个 yesterday_* 字段,
   Home.tsx 统计卡片底部渲染"较昨日+N"绿色/红色描述
4. 前端 ActionDetailDrawer 改用 item.id(action_type:uuid 格式)调用线程 API
2026-05-01 23:25:38 +08:00
iven
310a3cec90 refactor(web): 重写工作台 UI 匹配原型设计
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
Home.tsx 改用 CSS Grid 布局替代 antd Row/Col,统计卡片添加
顶部渐变色条。TodoList/AiInsightPanel/TeamOverviewPanel 全部
重写为自定义 inline style,复刻原型中的紧急度圆点、类型标签、
AI 渐变图标、成员进度条、风险分布色块等视觉元素。
2026-05-01 22:17:19 +08:00
iven
963556c079 fix(health): 修复工作台统计 SQL 表名 — alerts/follow_up_task
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- alert → alerts(实际表名复数)
- follow_up_plan → follow_up_task(表不存在,改用 pending 状态的随访任务)
2026-05-01 21:42:53 +08:00
iven
4aa014de0d feat(web): Home.tsx 集成统一工作台 — 医生行动收件箱 + 主任团队概览
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 医生/护士角色:待办任务行替换为行动收件箱(TodoList) + AI 概览面板
- 主任角色:在最近动态下方新增 TeamOverviewPanel 团队概览
- 所有角色:点击待办项可打开 ActionDetailDrawer 查看详情和操作
- admin/operator 角色保持原有待办任务+最近动态布局
2026-05-01 21:22:28 +08:00
iven
ab2c9bbc43 feat(web): 工作台面板组件 — AiInsightPanel / TeamOverviewPanel / ActionDetailDrawer
- AiInsightPanel: 工作台统计概览(待处理/AI建议/紧急告警/到期随访+完成率)
- TeamOverviewPanel: 主任团队概览(成员列表+风险分布+完成率进度条)
- ActionDetailDrawer: 待办详情抽屉(患者信息+操作时间线+快捷操作按钮)
2026-05-01 21:19:46 +08:00
iven
620af8988b feat(web): 工作台前端 API 客户端 + TodoList 组件
- actionInbox.ts 新增 WorkbenchStats/TeamOverview 类型和 stats()/team() API
- 新建 workbench/TodoList.tsx 待办列表组件(分页 + 类型/优先级标签)
2026-05-01 21:17:39 +08:00
iven
61397186e7 feat(health): 添加工作台统计和团队概览 API
- ActionInboxService 新增 get_workbench_stats 和 get_team_overview
- Handler 新增 /health/action-inbox/stats 和 /team 端点
- 注册 health.action-inbox.team 权限码
2026-05-01 21:14:23 +08:00
iven
f13a240000 fix(migration): 修复权限关联 — 使用 permission_id 外键关联
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
2026-05-01 18:38:03 +08:00
iven
a174f88b6f fix(migration): 修复表名 tenants → tenant(单数)
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
2026-05-01 18:36:26 +08:00
iven
5261468953 fix(migration): 修复行动收件箱菜单迁移 — 使用正确的 menus 表字段
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
2026-05-01 18:34:22 +08:00
iven
8e177ca705 feat(web): 家属管理 Tab — 列表+添加/编辑/删除家属
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
2026-05-01 18:24:57 +08:00
iven
7764f7f8a6 feat(web): 患者详情 AI 标签页添加趋势分析+体检方案触发按钮
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
2026-05-01 18:23:10 +08:00
iven
8a972f8f4d feat(web): SSE 分析 API 封装 + 化验报告页 AI 解读按钮
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 新增 analysisSse.ts SSE 流式分析 API 封装(ReadableStream 解析)
- 化验报告页操作列添加 AI 解读按钮(SSE 实时流式输出)
- 分析结果展示在 Table 下方的 Card 中
2026-05-01 18:21:40 +08:00
iven
a1fa51206f feat(miniprogram): 个人中心添加我的预约+在线咨询入口
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
2026-05-01 18:19:23 +08:00
iven
0fb8b98c72 feat(miniprogram): 通知 Tab 对接 erp-message 消息 API — 替换空壳 2026-05-01 18:18:51 +08:00
iven
f4b536accb fix(miniprogram): AI 建议卡片跳转修复 — 按建议类型跳转对应页面
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
2026-05-01 18:17:46 +08:00
iven
8dd269d150 feat(web): 患者快捷导航 + 列表页 URL patient_id 筛选 + AI 列表患者 Link
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 患者详情页增加快捷导航卡片(预约/咨询/透析/随访/AI)
- 5 个列表页支持 URL ?patient_id=xxx 自动筛选
- AI 分析列表患者 ID 改为可点击 Link 跳转详情
2026-05-01 18:17:07 +08:00
iven
0f32d28ddb feat(web): 患者详情页增加快捷导航卡片 — 预约/咨询/透析/随访/AI 2026-05-01 18:13:02 +08:00
iven
ebae393e90 chore(server): domain_events 清理周期从 90 天缩短为 7 天
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
2026-05-01 17:44:00 +08:00
iven
797c4e9e20 fix(health): 危急值告警查询添加 tracing 错误日志
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
2026-05-01 17:43:05 +08:00
iven
4cde4acddc feat(migration): 行动收件箱菜单种子数据 + 权限关联
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
2026-05-01 17:41:41 +08:00
iven
e1ebae4ed0 fix(web): 补充告警/收件箱/设备等菜单图标映射
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 新增 AlertOutlined/BellOutlined/ControlOutlined/InboxOutlined/ApiOutlined/ReadOutlined/ExperimentOutlined 图标导入和映射
2026-05-01 17:40:17 +08:00
iven
ae1c9ccc77 feat(web): Login/MainLayout 从主题配置读取品牌信息
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- Login.tsx 从 /api/v1/public/brand 读取品牌名称/标语/特性/版权
- MainLayout 侧边栏 Logo 和 Footer 从 themeConfig 读取
- 启动时调用 loadThemeConfig 缓存主题配置
- 移除所有硬编码品牌文字(HMR Platform → 动态读取)
2026-05-01 17:39:21 +08:00
iven
669ca44360 feat(web): 主题设置联动 — 扩展 ThemeConfig 品牌字段 + 设置页面表单
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- ThemeConfig 接口增加 brand_name/brand_slogan/brand_features/brand_copyright
- 新增 BrandConfig 接口和 getPublicBrand 公开品牌信息获取
- app store 增加 themeConfig 缓存和 loadThemeConfig 方法
- ThemeSettings 页面增加品牌设置表单(品牌名称/标语/特性/版权)
2026-05-01 17:37:10 +08:00
iven
6eb2bf9c80 feat(config): ThemeResp 增加品牌字段 + 公开品牌信息端点
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- ThemeResp 新增 brand_name/brand_slogan/brand_features/brand_copyright 字段
- default_theme 提供品牌默认值
- 新增 PublicBrandResp 和 GET /api/v1/public/brand 公开端点(无需认证)
- ConfigModule 增加 public_routes 方法
- 更新测试覆盖品牌字段
2026-05-01 17:34:43 +08:00
iven
a95e3d8645 fix(plugin): 修复测试编译失败 — 补充 parse_manifest 导入
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
2026-05-01 17:28:31 +08:00
iven
95d7989a9f docs: 三端审计修复实施计划 Phase 3 — 6 个 Task (#12-#15)
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
SSE 分析 API 包装器、AI 触发按钮、家庭成员 Tab、E2E 清理夹具、统计验证
2026-05-01 17:25:29 +08:00
iven
73119fe026 docs: 三端审计修复实施计划 Phase 2 — 6 个 Task (#7-#11)
Chunk 2: 体验补全阶段
- Task 9: 患者详情快捷导航卡片
- Task 10: 5 个列表页支持 URL patient_id 过滤
- Task 11: AI 分析列表患者 Link
- Task 12: 小程序 AI 建议跳转修复
- Task 13: 小程序通知 Tab 对接 erp-message API
- Task 14: 小程序咨询功能入口
2026-05-01 17:20:45 +08:00
iven
ac2797e1b7 docs: 修正 #10 通知端点描述 — erp-message 模块通知体系完整 2026-05-01 17:19:39 +08:00
iven
fc1d51e6f1 docs: 三端审计修复实施计划 Phase 1 — 8 个 Task (#1-#6) 2026-05-01 17:17:19 +08:00
iven
988b405c5d docs: 修复设计规格审查问题 — 迁移编号/通知端点/根因验证
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
CRITICAL 修复:
- 迁移编号 000098/000099 → 000100/000101(避免与已有迁移冲突)
- 通知端点改为对接 GET /messages(后端无独立通知端点)

IMPORTANT 修复:
- 危急值 500 增加强制根因验证步骤(先确认 RLS 状态再决定是否补齐)
- 品牌设置增加公开端点 + localStorage 缓存策略(解决登录页未认证问题)
- #15 统计仪表盘降级为验证任务(DoctorDashboard 已消费 personalStats)
2026-05-01 17:12:41 +08:00
iven
ff073c83a5 docs: 三端联调审计问题修复设计规格 — 15 项修复方案
基于 4 专家组代码级分析整合:
- P0: erp-plugin 测试修复 + 品牌主题设置联动
- P1: 菜单入口补全 + 危急值 500 修复 + 事件堆积清理
- P2: 导航关联 + 小程序 3 项修复
- P3: AI SSE 入口 + 家属管理 + E2E 清理
- P4: 统计仪表盘消费

品牌信息改为通过主题设置动态管理(非硬编码)。
2026-05-01 17:07:50 +08:00
iven
75bf900950 feat(miniprogram): 行动收件箱 — Service + 医生端列表页 + 半屏弹窗
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- action-inbox.ts: listActionItems + getActionThread API 调用
- doctor/action-inbox: 待办列表页,Tab 筛选 + 半屏线程弹窗 + 操作按钮
- app.config.ts: 注册 action-inbox 页面到 doctor 子包
2026-05-01 16:40:32 +08:00
iven
6d66a392db feat(web): NotificationPanel 增加待办预览区域
- 底部新增"待办事项"区域,显示最近 3 条 pending 行动项
- 角标数字改为 unreadCount + pendingActionCount
- 点击待办项跳转 /health/action-inbox
2026-05-01 16:37:29 +08:00
iven
81dd3d2bda feat(web): 行动收件箱前端 — API + Drawer + 列表页 + 路由
- actionInbox.ts: API 调用层,list + getThread
- ActionThreadDrawer: 上下文线程抽屉,时间线 + 操作按钮
- ActionInbox: 列表页,Tabs 筛选 + 分页 + 点击打开 Drawer
- App.tsx: 注册 /health/action-inbox 路由
2026-05-01 16:36:24 +08:00
iven
758bc210e1 feat(health): 行动收件箱后端 — ActionInboxService + Handler + 路由注册
- ActionInboxService: 三表 JOIN 聚合查询 ai_suggestion/ai_analysis/patient
- list_action_items: 分页列表,按 risk_level + created_at 排序
- get_action_thread: 线程时间线拼装 + 动态操作按钮
- ActionInboxHandler: 2 个 GET 端点,require_permission 权限守卫
- 路由: /health/action-inbox, /health/action-inbox/{source_ref}/thread
- 权限: health.action-inbox.list, health.action-inbox.manage
2026-05-01 16:33:40 +08:00
iven
3cba699ca0 fix(web): 修复 AiAnalysisList JSX 嵌套结构 — SuggestionPanel 容器层级
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
2026-05-01 10:48:14 +08:00
iven
8b837c0591 feat(miniprogram): AI 建议卡片 — 健康页顶部显示待审批建议摘要
- 新增 listPendingSuggestions API
- 健康页加载待审批 AI 建议(最多 3 条)
- 风险等级圆点 + 建议摘要文字
- 点击卡片可跳转
2026-05-01 09:22:18 +08:00
iven
598c06885f feat(web): 患者 AI 建议标签页 — 待审批建议列表+审批操作
- 新增 AiSuggestionTab 组件(风险等级+类型+状态+审批按钮)
- PatientDetail 添加「AI 建议」标签页
- 复用 suggestions API 层
2026-05-01 09:19:50 +08:00
iven
92c1c3c17d feat(web): AI 分析详情增加建议面板 — 风险等级+建议列表+审批操作
- 新增 suggestions API 层(list/approve/getComparison)
- 展开分析详情时自动加载关联的 AI 建议列表
- 风险等级彩色标签(低/中/高)
- 建议类型、原因、执行状态展示
- 待审批建议支持批准/拒绝操作
2026-05-01 09:17:18 +08:00
iven
5d2402a1e7 feat(ai+health): 闭环核心 — 随访完成→再分析触发 + 前后对比报告
- follow_up.completed 消费者:通过 action_result 反查 AI 建议,触发再分析
- ai.reanalysis.requested 消费者:加载原始建议 baseline
- comparison.rs:对比报告生成引擎(指标变化百分比+趋势判断)
- GET /ai/suggestions/{id}/comparison:前后对比报告 API
- find_by_followup_task:通过随访任务反查关联建议ID
2026-05-01 09:14:13 +08:00
iven
0a4825be99 feat(health+workflow): 行动分发→工作流启动集成 — 事件驱动 BPMN 实例化
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- create_pending_action 新增 workflow.ai_action.start_requested 事件发布
- 根据 action_type 映射到对应 BPMN 流程定义 key
- erp-workflow 消费启动请求,自动创建审批流程实例
- 流程变量包含 risk_level/patient_id/action_type/params
2026-05-01 08:53:57 +08:00
iven
388948e348 feat(workflow): AI 行动闭环 BPMN 流程定义 — 随访/预约/预警三条审批流程
- ai_followup_workflow: 随访建议风险分级 + 医生审批
- ai_appointment_workflow: 预约建议风险分级 + 医生确认
- ai_alert_workflow: 预警确认风险分级 + 医生确认
- 启动时自动 seed 三条 published 状态的流程定义
2026-05-01 08:49:49 +08:00
iven
5053908444 feat(health): AI 行动分发事件消费者 — 订阅 ai.analysis.completed
- 新增 ai_suggestion_loader:跨 crate 通过 raw SQL 读取 ai_suggestion 表
- 事件消费者 ai_action_dispatcher 订阅 ai. 事件
- 根据 suggestion_count > 0 触发行动分发路由
- 低风险自动执行,中/高风险进入医生审核队列
2026-05-01 08:41:14 +08:00
iven
69f9e1a61a feat(health): AI 行动分发器 — 风险分级路由到自动执行/医生审批/紧急确认
- dispatch_decision: 根据风险等级生成执行决策(low=自动, medium=24h审批, high=4h紧急)
- handle_ai_suggestions: 遍历建议列表,按决策分发
- execute_action: 低风险自动发送预警/随访事件
- create_pending_action: 中高风险发送待审批事件
- 4 个单元测试覆盖:低/中/高/未知风险等级路由
2026-05-01 08:34:04 +08:00
iven
4b3193fcd6 feat(server): 集成 SuggestionService 到 AiState 初始化
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
2026-05-01 08:14:41 +08:00
iven
415d7617c8 feat(ai): 建议查询/审批 API 端点 + 权限注册
- GET /ai/suggestions?analysis_id=xxx — 查看建议列表(ai.suggestion.list)
- POST /ai/suggestions/{id}/approve — 批准/拒绝建议(ai.suggestion.manage)
- 新增 ai.suggestion.list 和 ai.suggestion.manage 权限码
2026-05-01 08:12:29 +08:00
iven
6e761ae22b feat(ai): 集成双通道输出解析到 SSE handler — 自动创建建议记录
在 build_sse_stream 完成回调中:
- 调用 parse_dual_channel 解析 AI 输出
- 有结构化建议时调用 SuggestionService::create_suggestions 创建记录
- 解析失败时调用 mark_parse_failed 记录日志
- 扩展 ai.analysis.completed 事件 payload 含 risk_level + suggestion_count
2026-05-01 08:11:23 +08:00
iven
b30897119b feat(ai): SuggestionService — 建议记录 CRUD + 状态流转
- create_suggestions: 批量创建建议记录,关联分析 ID 和 baseline 快照
- list_by_analysis: 按 analysis_id 查询建议列表(带 tenant_id 过滤 + 软删除)
- list_pending: 查询待审批建议
- update_status: 更新状态(带乐观锁 + tenant_id 过滤)
- mark_parse_failed: 解析失败时记录日志
- AiState 新增 suggestion 字段
2026-05-01 08:09:59 +08:00
iven
3b6f72d5c0 feat(ai): 本地临床规则引擎 — AI 不可用时的回退方案
- LocalRulesEngine: 预定义 8 条临床规则(收缩压/心率/血糖/血氧)
- CompareOp: GreaterThan/LessThan 比较运算
- evaluate(): 输入指标 JSON,输出 StructuredSuggestion 列表(按优先级排序)
- 5 个单元测试覆盖:高值触发、正常无建议、缺失指标跳过、SpO2 低、优先级排序
2026-05-01 08:08:48 +08:00
iven
92e6cf0c43 feat(ai): 双通道输出解析器 — 文本/JSON 分割 + 降级策略
- parse_dual_channel: 分割 ===PATIENT_TEXT=== / ===STRUCTURED_JSON=== 标记
- JSON 解析失败时降级为纯文本,structured 为 None
- 5 个单元测试覆盖:正常解析、纯文本、无效 JSON、空建议、风险等级
2026-05-01 08:07:26 +08:00
iven
9b8307fbba feat(ai): 添加 ai_suggestion 和 ai_risk_threshold SeaORM Entity 2026-05-01 08:05:42 +08:00
iven
577d2a32b1 feat(db): 添加 ai_suggestion 和 ai_risk_threshold 表迁移
- ai_suggestion: AI 建议记录表,含 tenant_id、analysis_id、suggestion_type、
  risk_level、status、params、baseline_snapshot 等字段
- ai_risk_threshold: 租户级风险阈值配置表,按 metric_name + tenant_id 唯一索引
- 两表均包含标准审计字段和 version_lock 乐观锁
2026-05-01 08:04:51 +08:00
iven
7789a5e227 feat(ai): 新增 Suggestion/RiskLevel/SuggestionStatus 枚举和结构化输出 DTO
重构 dto.rs 为 dto/ 目录模块,新增 suggestion.rs 包含:
- SuggestionType (Followup/Appointment/Alert)
- RiskLevel (Low/Medium/High) + is_auto_executable
- SuggestionStatus (6 种状态)
- StructuredSuggestion / StructuredOutput / ParsedOutput DTO
- 7 个单元测试覆盖序列化往返
2026-05-01 08:02:53 +08:00
iven
2fb0535164 docs(ai): AI→行动闭环实施计划完成 — 25 Task / 3 Chunk
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
Chunk 1: 数据层+输出解析(Task 1-11)
Chunk 2: 事件集成+BPMN+行动分发(Task 12-19)
Chunk 3: 闭环对比+前端展示(Task 20-25)
2026-05-01 07:58:44 +08:00
iven
6046ed23c9 docs(ai): AI→行动闭环实施计划 Chunk 1 — 数据层+输出解析
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
11 个 Task:DTO 枚举/迁移/Entity/解析器/规则引擎/Service/Handler集成/API端点
已通过 plan review,修复了 dto/ 模块拆分、version_lock 命名、乐观锁、tenant_id 过滤
2026-05-01 07:06:45 +08:00
iven
31e623a947 docs(ai): AI→行动闭环设计规格
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
发散式讨论产出的设计文档,定义了 AI 分析结果如何自动转化为
可执行行动(随访计划/智能预约/风险预警),通过 BPMN 工作流
引擎编排分级自动化,形成数据→分析→行动→评估的完整闭环。
2026-05-01 01:19:28 +08:00
iven
3b38562533 test(ai): 添加 erp-ai 集成测试 — 14 个测试覆盖 3 个 service
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- PromptService: 创建/查询/列表筛选/激活版本切换/回滚/跨租户隔离/未找到错误 (7)
- UsageService: 日志记录/概览/按类型聚合/跨租户隔离 (4)
- AnalysisService: 完成分析/失败分析/缓存查找/列表筛选 (3)
- 使用 MockProvider 替代真实 AI 调用
2026-05-01 00:57:16 +08:00
iven
9b8c2ff7e1 fix(health): 预约 CAS 从精确匹配改为排班时段范围匹配
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
预约创建时 CAS 原子操作要求排班 start_time 精确等于预约 start_time,
导致排班 08:00-12:00 只能在 08:00 开始预约,无法选择 09:00 等子时段。

修改为范围匹配:排班 start_time <= 预约 start_time 且
排班 end_time >= 预约 end_time,预约可落在排班时段内任意子时段。

增加 rows_affected > 1 保护:若排班数据存在重叠时段则拒绝并告警。
2026-05-01 00:37:11 +08:00
iven
63d8b7a65d fix(miniprogram): 对齐设计原型 — 移除渐变头部+体征数值内联+卡片布局
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 首页:移除渐变头部改为平铺背景,铃铛图标替代消息按钮
- 首页:体征数值与单位内联显示(同一行 baseline 对齐)
- 健康页:标题改为"健康数据",整体样式贴近原型紧凑风格
- 我的页:移除渐变头部改为平铺卡片,积分/打卡分两个独立卡片
- 我的页:菜单使用 emoji 图标替代文字图标,间距更紧凑
2026-04-30 23:04:36 +08:00
iven
50772878da feat(miniprogram): 老年友好版本全面重设计 — 5→4 Tab + 首页/健康/消息/我的重写
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- TabBar 从 5 Tab 调整为 4 Tab(首页/健康/消息/我的)
- 首页重写为 5 区域布局:问候+进度环+体征2x2+待办+快捷操作
- 健康页重写:体征录入大输入框+趋势柱状图+BLE设备卡片
- 新建消息页:咨询对话+系统通知双 Tab
- 我的页调整:菜单高度64px+新增积分商城入口
- 设计系统更新:色彩对比度提升(WCAG AA)+触控参数+老年友好 mixin
- 新增 ProgressRing 组件(CSS conic-gradient 实现)
- 修复 diagnoses 页面 $suc-l 未定义变量
2026-04-30 22:51:05 +08:00
iven
813843e8cc feat(miniprogram): 添加健康记录和诊断记录查看页面
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 新建 service: health-record.ts(listHealthRecords + listDiagnoses)
- 新建页面: health-records/index(体检记录列表,分页+下拉刷新)
- 新建页面: diagnoses/index(诊断记录列表,类型/状态标签)
- 路由注册到 pkg-profile 分包
- "我的"页菜单添加健康记录、诊断记录入口
2026-04-30 22:49:44 +08:00
iven
f05ca00c75 feat(auth+config+workflow+message+plugin): 为 5 个基础模块添加 permissions() 声明
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- erp-auth: 23 个权限码(用户/角色/权限/组织/部门/岗位)
- erp-config: 18 个权限码(字典/菜单/配置/编号/主题/语言)
- erp-workflow: 8 个权限码(流程定义/实例/任务)
- erp-message: 5 个权限码(消息/模板),补充缺失的 message.template.manage
- erp-plugin: 2 个权限码(插件管理/查看)
- 同步更新 seed.rs 的 READ_PERM_INDICES 索引和权限计数

使得 sync_module_permissions() 可以动态注册这些权限,与 erp-health/erp-dialysis/erp-ai 模式一致。
2026-04-30 22:41:26 +08:00
iven
8f9895be98 fix(web): SSE 连接添加指数退避重连策略
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
useAlertSSE hook 和 message store 的 connectSSE 均改为手动重连:
1s→2s→4s→8s→16s→30s(cap),最大重试 10 次,随机 jitter 0.5-1.0x。
替代浏览器原生 EventSource 固定 ~3s 重连,避免服务端压力。
2026-04-30 22:30:47 +08:00
iven
0dcaf7915f fix(health): 补充 3 个核心 service 的 tracing 日志 — 38 处
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
审计后续 H3: patient_service(15) + consultation_service(10) + follow_up_service(13)
共计 2526 行代码此前 0 处运维级日志,现已在所有 pub async fn 入口添加
tracing::info! 日志,格式统一为 action + key params。
2026-04-30 16:58:04 +08:00
iven
44bb31197e feat(miniprogram): 实现知情同意页面 — 查看/撤回/签署
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
审计后续 H2: 对接后端 3 个知情同意 API 路由。

新增内容:
- services/consent.ts: 类型定义 + listConsents/grantConsent/revokeConsent
- 患者端知情同意列表页: 查看已签署同意书 + 撤回操作
- 路由注册 + "我的"菜单入口
2026-04-30 16:52:39 +08:00
iven
36a55e116e feat(miniprogram): 实现小程序透析模块 — 患者端查看 + 医护端录入/审阅
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
审计后续 H1: 补齐小程序端透析功能,对接后端 12 个 API 路由。

新增内容:
- 患者端: 透析记录列表/详情 + 透析处方列表/详情(只读,4 页面)
- 医护端: 透析记录列表/详情/创建 + 处方列表/详情/创建(6 页面)
- Service 层: dialysis.ts(患者端只读)+ doctor/dialysis.ts(医护端 CRUD)
- 集成入口: 医生工作台快捷操作 + 患者"我的"菜单 + 路由注册
- 基础设施: api.delete 扩展支持 data 参数(后端 delete 需要 version)
2026-04-30 16:48:39 +08:00
iven
84fafb0bc5 fix(web+health): 修复咨询轮询 temp ID 400 + 健康数据统计 500
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- ConsultationDetail: 轮询取 lastId 时过滤 temp_ 前缀的乐观消息 ID,
  避免将非法 UUID 传给 after_id 参数导致后端 400
- stats_service: count_abnormal_lab_items 和 compute_daily_report_rate
  中 SQL 字面量 0 类型为 INT4,与 Rust i64 (INT8) 不匹配,
  改为 0::bigint 确保类型兼容
2026-04-30 12:27:56 +08:00
iven
1bebb57765 fix(web): 移除 ConsultationDetail 残留的 sender_id/sender_role 字段
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
前端发送消息时不再提交 sender_id 和 sender_role,
这些字段由后端从 JWT 上下文自动填充。
2026-04-30 11:34:20 +08:00
iven
a96b065190 test(config): 补全字典+编号服务单元测试 — 51 新增
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- dictionary_service: 提取 dict_model_to_resp/item_model_to_resp + 7 个映射测试
- numbering_service: 提取 format_number 纯函数 + 5 个格式化测试
- erp-config 测试总数从 27 增至 78
2026-04-30 11:02:36 +08:00
iven
b00fe44880 feat(health): 添加文章修订历史查询 API — GET /health/articles/{id}/revisions
补全 ArticleRevision 实体的读取查询(之前仅有写入 save_revision),
新增 list_revisions service + handler + 路由,支持分页。
2026-04-30 10:53:04 +08:00
iven
32eef5ecf1 feat(db+test): 菜单权限关联迁移 + 适配 create_message 签名变更
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 新增迁移 m097:为 17 个已有菜单设置 permission 字段,新增透析管理/资讯管理 2 个菜单
- 修复 consultation/pii_encryption 测试适配 create_message(sender_id, sender_role) 分离参数
2026-04-30 10:37:43 +08:00
iven
13f553590b feat(health+dialysis): 补全 8 组权限码 + 修复 N+1 查询 + 防御性编码
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
权限补全:
- 新增 14 个权限声明(危急值告警/阈值/随访模板/日常监测/知情同意/用药记录/药物提醒)
- 更新 8 个 handler 使用正确的专属权限码
- erp-dialysis 新增 health.dialysis.stats 权限

性能优化:
- article_service list_articles 标签加载从 N+1 改为批量查询
- follow_up_template_service 字段计数从 N+1 改为批量 GROUP BY

防御性编码:
- alert_engine/article/critical_alert 的 unwrap() 替换为 unwrap_or/expect
2026-04-30 10:22:14 +08:00
iven
931edc3025 fix(security): 补全 XSS sanitize + 修复 sender_id 身份伪造
安全审计修复:
- 补全 6 个 DTO 的 sanitize 方法(diagnosis/consent/alert/medication_record/medication_reminder/follow_up_template)
- 4 个 handler 添加 .sanitize() 调用(diagnosis/consent/alert_rule/medication_record)
- 修复咨询消息 sender_id/sender_role 从客户端提交改为服务端从 JWT 提取
- 修复小程序 AI 报告 markdownToHtml XSS(添加 sanitizeHtml 过滤)
2026-04-30 10:21:52 +08:00
iven
d8735eb45c fix(test+web): 修复测试编译错误 + 前端构建问题
- 修复透析集成测试 TestApp.dialysis_state() 返回类型不匹配(39个错误)
- 修复 erp-core test_helpers SeaORM Database::connect API 变更
- 修复 health_alert/article/data 集成测试函数签名不匹配
- 修复 DailyMonitoringTab 缺失 Input import
- 修复 DeviceReadingsTab 未使用接口声明
- 修复 DialysisManageList keyword → search 参数名
2026-04-30 10:21:05 +08:00
iven
82cea6a108 docs(audit): 系统性功能审计报告 — 9 项修复 + 23 项遗留记录
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
2026-04-30 08:41:22 +08:00
iven
22e35ad233 docs(event): 创建事件注册表文档 — 28 个事件类型全量记录
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
2026-04-30 08:35:32 +08:00
iven
d2dfac82e3 refactor(web): 移除 4 个未使用的 API 函数 — exportSessions/generateTrend/assignDoctor/removeDoctor
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
2026-04-30 08:34:35 +08:00
iven
c0e3d26b71 refactor(health): 更新 message.sent 消费者注释 — last_message_at 已在 CAS 中处理
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
2026-04-30 08:32:29 +08:00
iven
1925568c13 feat(message+health): 补全 14 个事件消费者 + 修复 6 个事件 payload 缺失字段
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
事件消费者补全(erp-message/module.rs):
- consultation.opened: 医生收到新咨询会话通知
- consultation.closed: 患者收到会话结束通知
- follow_up.created: 被分配人收到新随访任务通知
- follow_up.completed: 患者收到随访完成通知
- points.earned: 患者收到积分到账通知
- points.exchanged: 患者收到兑换成功通知
- points.expired: 患者收到积分过期提醒
- article.published/rejected: 作者收到审核结果通知
- ai.analysis.failed: 医生收到 AI 分析失败通知
- lab_report.uploaded/patient.updated/daily_monitoring/doctor: 审计日志记录

事件 payload 补充(erp-health services):
- consultation.opened: 添加 doctor_id 字段
- follow_up.created: 添加 assigned_to + planned_date 字段
- points.earned: 添加 patient_id + reason 字段
- points.exchanged: 添加 product_name 字段
- article.rejected: 添加 author_id 字段
2026-04-30 08:31:12 +08:00
iven
cec487bd2c chore(points): 移除已废弃的 erp-points crate + 注释空桩和死常量
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 删除 erp-points/ 目录(全部 501 handler,功能由 erp-health 完整提供)
- 从 workspace Cargo.toml 和 erp-server 依赖中移除
- erp-dialysis event.rs: 说明事件由 erp-health 统一消费的设计意图
- erp-health event.rs: 标记 PATIENT_VERIFIED/PATIENT_DECEASED 为待实现
2026-04-30 08:24:20 +08:00
iven
ef0b784f4f fix(health): 修复两条断裂事件链 — consultation.new_message 和 lab_report.reviewed
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
咨询消息发送和化验单审核完成后未发布 DomainEvent,导致下游通知消费者
(医生收到新消息通知、患者收到审核完成通知)完全不可用。

- consultation_service: create_message() 提交后发布 consultation.new_message 事件
- health_data_service: review_lab_report() 审核后发布 lab_report.reviewed 事件
- event.rs: 添加 CONSULTATION_NEW_MESSAGE 和 LAB_REPORT_REVIEWED 常量
2026-04-30 08:21:00 +08:00
iven
43769dae5a feat(mp): 患者端健康告警页面 + 首页入口
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
P1-8: 小程序患者告警推送
  - 新增 alert service:listPatientAlerts 按患者 ID 查询告警
  - 新增 pkg-health/alerts 告警列表页:严重程度标签 + 状态过滤 + 分页
  - 首页快捷服务新增"健康告警"入口
  - app.config.ts 注册 alerts/index 页面路由
2026-04-30 07:23:05 +08:00
iven
26a9781d4f feat(health): 药物提醒后端 API + 后台任务统一 + dead code 清理
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
P1-3: medication_reminder 全栈实现
  - migration 000096: 创建 medication_reminder 表(含患者关联/提醒时间/频率)
  - entity + dto + service + handler: 完整 CRUD(乐观锁/软删除/审计日志)
  - 路由注册: GET /patients/{id}/medication-reminders, POST/PUT/DELETE
  - HealthError 新增 MedicationReminderNotFound

P2-4: 后台任务启动统一
  - appointment_reminder 迁移到 HealthModule::on_startup()(启动时立即执行 + 周期循环)
  - 删除 main.rs 中重复的 overdue_checker/points_expiration/appointment_reminder 调用
  - 所有 Health 后台任务现由模块 on_startup 统一管理

P2-5: Web dead code 清理
  - 删除 healthData.ts 中 getMiniTrend/getMiniToday(小程序专用端点,Web 无调用)
  - 删除 patients.ts 中 getHealthSummary(标记 TODO 未使用)
2026-04-30 07:18:22 +08:00
iven
30344d474f fix(health+ai+dialysis): 审计 P1 批次修复 — EventBus接入/盲索引去重/事件消费者补全
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
P1-2: erp-ai EventBus 接入
  - handler 层 SSE 流完成/失败时发布 ai.analysis.completed/failed 事件
  - build_sse_stream 新增 tenant_id 参数

P1-2: erp-dialysis EventBus 接入
  - create_dialysis_record 审计后发布 dialysis.record.created 事件

P1-5: message.sent 消费者改进
  - 从占位 tracing::info 升级为带 payload 详情的结构化日志

P1-7: 盲索引去重
  - create_patient 中新增 id_number HMAC 去重检查(查 blind_indexes 表)
  - 患者创建成功后写入 blind_indexes 表(id_number + phone)
  - 防止同租户重复建档

P1-1: 事件消费者补全
  - 新增 ai.analysis.completed 消费者(幂等处理 + 日志)
  - 新增 dialysis.record.created 消费者(幂等处理 + 日志)
2026-04-29 17:00:24 +08:00
iven
dffa2dd47d fix(health+server+mp): 审计 P0 批次修复 — 积分冲突/文章草稿泄露/商城空白/模板ID配置化
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
P0-1: 微信模板 ID 从硬编码空字符串改为环境变量注入
  - wechat-templates.ts 读取 process.env.TARO_APP_WX_TEMPLATE_*
  - defineConstants 新增 5 个模板 ID 编译时注入

P0-2: 积分商城 Tab 空白降级
  - mall/index.tsx 在 currentPatient 为 null 时先调用 loadPatients()
  - 仍无档案才显示空状态引导,而非直接阻断

P0-3: 消除 erp-points 重复路由冲突
  - 从 erp-server 移除 erp-points 模块注册和路由 merge
  - 积分功能统一由 erp-health /health/points/* 提供
  - erp-points crate 保留但不参与编译

P0-4: 文章列表按角色过滤防止草稿泄露
  - list_articles handler: 非管理权限强制 status=published
  - get_article service: 新增 is_admin 参数控制状态过滤
2026-04-29 15:11:05 +08:00
iven
facc8b0d24 refactor(dialysis+health): 透析统计从 erp-health 迁移到 erp-dialysis,消除跨 crate 残留
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- erp-dialysis: 新建 dialysis_stats_dto/handler/service,注册 /health/admin/statistics/dialysis 路由
- erp-health: 删除 get_dialysis_statistics 及 helper、DialysisStatisticsResp、
  DialysisRecordNotFound/DialysisPrescriptionNotFound、validate_dialysis_status* 及 9 个测试、
  DoctorDashboard.pending_dialysis_review、module 路由
- Web: HealthDataStats 移除 dialysis 字段,新增 getDialysisStats() 独立 API,
  useStatsData 并行 fetch,HealthDataCenter 接受独立 dialysisData prop
- 小程序: DoctorDashboard 移除 pending_dialysis_review,医护工作台移除"待审透析"卡片
2026-04-29 07:56:21 +08:00
iven
cb6f5cc651 feat(mp+health): 小程序分包迁移 + 积分商城后台列表 API
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 小程序页面迁移到 pkg-health/pkg-mall/pkg-profile 分包目录
- 删除旧 pages/health/input、pages/mall/detail 等旧路径
- 导航路径更新为分包路径(/pages/pkg-mall/exchange/index 等)
- TrendChart 组件优化
- 后台添加 admin_list_products API(支持查看已下架商品)
- config/index.ts 添加 defineConstants 环境变量
- mp e2e check-readiness 路径修正
2026-04-29 07:29:49 +08:00
iven
9015a2b85e feat(web): 登录页主题适配 + 工作台角色化重构
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 登录页接入 4 套主题系统(渐变色/面板背景/文字色),添加 ThemeSwitcher
- 工作台按角色(医生/护士/管理员/运营)显示专属统计卡片和快捷入口
- 移除系统信息填充卡片,硬编码颜色替换为 CSS 变量
2026-04-29 07:27:04 +08:00
iven
202c6dd0d2 feat(miniprogram): 小程序设备数据集成打通 — Phase 3
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 首页设备入口简化为直接跳转按钮(去除硬编码 never 状态)
- 体征录入页增加「从设备同步」入口,设备数据自动回填表单
- 设备同步页支持 returnTo 参数,完成后返回录入页
- 医护工作台增加告警中心固定导航入口(带数字角标)
2026-04-29 06:36:12 +08:00
iven
cac61637ce feat(health): Web 管理端设备数据集成补全 — Phase 2
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 新增告警三页面(仪表盘/列表/规则)+ 设备管理菜单种子数据
- 新增设备管理后端 API(GET /devices + DELETE /devices/{id})
- 新增设备数据查看组件 DeviceReadingsTab(原始数据 + 小时聚合)
- 新增设备管理页面 DeviceManage(列表/筛选/解绑)
- 患者详情页新增设备数据 Tab
2026-04-29 06:28:30 +08:00
iven
f6ccb8a35c fix(health): 设备数据管线 Phase 1 缺陷修复 + AI 产品策略讨论
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- device_readings 批量插入添加 ON CONFLICT 去重唯一索引
- 小程序 BLEManager 增加离线缓存(Storage 持久化 + 启动重传)
- 新增 device_readings 90 天数据保留清理定时任务
- 小米手环适配器增加 RACP 历史心率读取支持
- SSE 告警按医生过滤已确认实现(patient_doctor_relation)
- 新增 AI 产品策略与设备数据医院场景讨论记录
2026-04-29 06:17:23 +08:00
iven
a491eb19a6 fix(web+health): E2E flow 测试全面修复 — 15/15 通过
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- test-data: 接口对齐后端 DTO(VitalSigns/AlertRule/Schedule/FollowUp)
- api-client: 增强 HTTP 错误处理(parseJson 统一防护非 JSON 响应)
- auth.fixture: 每个测试获取新 token,避免共享 token 过期
- patient-detail: tab 名称修正为 '健康数据' → '体征数据'
- patient-list: DrawerForm 选择器适配(无 phone 字段、保存按钮在 extra)
- vital-signs-flow: API 录入 + 页面验证,避免复杂 DatePicker 交互
- alert-flow: 简化为规则 CRUD + 页面导航,condition_params 对齐后端格式
- follow-up-template handler: 权限码从 health.follow-up-template.* 修正为 health.follow-up.*
- playwright.config: workers=1 串行执行避免并发登录
- check-readiness: 健康端点路径修正为 /api/v1/health
2026-04-29 06:04:22 +08:00
iven
c6e8048bc5 test(web+mp): E2E 测试全量实施 — Web 5 flow + MP 4 flow + 基础设施
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
Web 端 (Playwright):
- fixtures: test-data 工厂 + API Client (乐观锁 version) + 增强 auth fixture
- pages: LoginPage, PatientListPage, PatientDetailPage, HealthDataPage, AppointmentPage
- flows: 患者全流程, 体征数据链路, 预约排班链路, 随访管理链路, 告警处理链路
- smoke tests 迁移到 smoke/ 目录,import 路径更新
- playwright.config.ts 更新: globalSetup 环境检查, 60s timeout, video retain

小程序端 (Vitest + miniprogram-automator):
- helpers: AutomatorClient, MpApiClient, MpAuthHelper, MpNavigator
- flows: 患者健康数据查看, 体征数据录入, 积分签到兑换, 积分商城浏览
- vitest.config.ts + check-readiness.ts
- vitest 4.1.5 依赖安装

Playwright 发现 15 个测试 (5 flow + 10 smoke),全部就绪
2026-04-29 04:58:01 +08:00
iven
2f4be6dcd0 docs(e2e): 添加 E2E 测试实施计划
5 个 Chunk, 21 个 Task:
- Chunk 1: 基础设施(test-data + api-client + auth fixture + config)
- Chunk 2: Web Page Objects(5 个关键页面)
- Chunk 3: Web 业务链路(5 条 flow spec)
- Chunk 4: 小程序基础设施(automator + helpers + vitest config)
- Chunk 5: 小程序业务链路(4 条 flow spec)
2026-04-28 22:39:24 +08:00
iven
1bde4b44c0 fix(web): VitalSignsChart hooks 顺序修复 + 趋势线颜色区分度优化
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
修复 React hooks 在 early return 之后调用导致的渲染崩溃,
将所有 useMemo 移至条件返回之前。趋势图三系列改用高对比色:
实际值(原色实线)、移动平均(青色短虚线)、趋势线(琥珀色长虚线)。
2026-04-28 22:10:13 +08:00
iven
4eb874f52d docs(e2e): 添加 E2E 测试设计规格文档
流程链路式双端 E2E 测试体系设计:
- Web 端 5 条业务链路(Playwright + Page Object)
- 小程序端 4 条业务链路(Vitest + miniprogram-automator)
- API 驱动自建自毁数据策略,乐观锁 version 支持
- CI-ready 环境变量驱动设计
2026-04-28 21:57:19 +08:00
iven
5ab8bf8479 feat(server): 可观测性 Phase 1 — 健康检查路由 + Prometheus 指标 + 连接池/事件积压监控
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 添加 /health/live 存活探针别名(原 /health + /health/ready 保留)
- 新增 metrics middleware:http_requests_total 计数器 + http_request_duration_seconds 直方图
- Prometheus exporter 独立端口 9090(可通过 ERP__SERVER__METRICS_PORT 覆盖)
- 后台任务每 30s 采样 DB 连接池活跃/空闲连接数(pg_stat_activity)
- 后台任务每 30s 采样 EventBus pending 事件积压数
- UUID 路径归一化避免高基数(/api/v1/users/:id/posts)
2026-04-28 20:39:11 +08:00
iven
f99892ee16 feat(web+mp): AI 分析结果增强展示
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
Web 端 AiAnalysisList:
- 分析结果 Markdown 风格渲染(标题/列表/粗体/代码)
- 趋势分析类型显示统计方法提示
- 自动分析结果显示「系统自动分析」标签

小程序 ai-report/detail:
- 新增 result_metadata 字段
- 自动分析标记(紫色标签)
- 趋势分析统计方法说明卡片
2026-04-28 20:12:34 +08:00
iven
10c79c5e39 feat(mp): 医护端告警列表/详情页 + DoctorHome 告警 banner 增强
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 新增告警列表页:按状态筛选、分页、严重程度/状态标签
- 新增告警详情页:完整信息展示 + 确认/忽略/恢复操作
- doctor.ts 新增 listAlerts/acknowledgeAlert/dismissAlert/resolveAlert API
- DoctorHome 告警 banner 跳转目标改为告警列表页
- 注册 alerts/index + alerts/detail/index 到 doctor subPackage
2026-04-28 20:05:55 +08:00
iven
1cf5f59d8c feat(web): VitalSignsChart 集成趋势线 + 移动平均 + 异常标注
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
增强 VitalSignsChart 组件:
- 线性回归趋势线(虚线显示,斜率/R² 统计)
- 移动平均线(自适应窗口,平滑实线)
- 异常点检测(2倍标准差,红色标记)
- 概览卡片显示趋势方向箭头和异常警告图标
- 详情图下方图例说明各系列含义
2026-04-28 20:05:43 +08:00
iven
a84378ab50 feat(ai): 定期自动分析定时任务 — 每 24 小时扫描高风险患者
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
新增 auto_analysis.rs 服务:
- 启动后延迟 5 分钟,每 24 小时执行一次
- 查找所有活跃租户中高风险患者(异常体征指标)
- 自动调用趋势分析并存储分析结果
- 每租户限制 50 名患者,防止过载
- erp-server main.rs 中注册后台任务
2026-04-28 20:02:01 +08:00
iven
493b479373 feat(web): DoctorDashboard 集成告警摘要卡片
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
在医生工作台新增待处理告警摘要区域,展示最近 5 条
pending 状态告警,点击「查看全部」跳转告警仪表盘。
2026-04-28 20:01:11 +08:00
iven
27c32e5561 feat(web): 实时告警仪表盘页面 + SSE Hook + 告警详情面板
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 新增 AlertDashboard 页面:实时告警列表 + 统计摘要 + 详情面板
- 新增 useAlertSSE Hook:封装 SSE 连接、自动重连、事件分发
- 新增 AlertDetailPanel 组件:告警详情展示 + 确认/忽略/恢复操作
- alertApi.list 添加 doctor_id 参数支持
- 注册 /health/alert-dashboard 路由 + 面包屑映射
2026-04-28 19:59:51 +08:00
iven
cf844a561f feat(ai+db): 趋势分析 prompt 升级为结构化统计摘要
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- 新增迁移 000093:更新 health_trend_analysis prompt,使用统计字段
  替代原始数据点遍历,引导 AI 专注 slope/R²/异常点分析
- erp-ai handler: stream_trends 改用 get_trend_analysis_data()
  替代 get_vital_signs(),传递预计算趋势特征
- sanitizer: 新增 sanitize_trend_analysis() 方法
2026-04-28 19:57:51 +08:00
iven
1c9e7ccf1d feat(core+health): HealthDataProvider 扩展趋势分析预计算数据
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- erp-core: 新增 get_trend_analysis_data() trait 方法和配套 DTO
  (TrendAnalysisDto, MetricTrendAnalysis, RegressionStats, AnomalyInfo)
- erp-health: 实现 get_trend_analysis_data(),查询 vital_signs 时间序列
  后调用 trend_stats 模块计算线性回归和异常检测,返回结构化统计摘要
2026-04-28 19:55:06 +08:00
iven
8aac96b62f feat(health): 告警列表 API 添加 doctor_id 过滤参数
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
alert_handler 的 AlertListQuery 新增 doctor_id 参数。
alert_service::list_alerts 先查询 patient_doctor_relation
获取该医生负责的患者列表,再用 patient_id.is_in() 过滤。
医生无管床患者时直接返回空结果。新增 2 个单元测试。
2026-04-28 19:54:12 +08:00
iven
4745b1e824 feat(health): 统计计算模块 — 线性回归、移动平均、异常检测
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
新增 trend_stats.rs 纯函数模块,提供三个统计计算能力:
- compute_linear_regression: 最小二乘法线性回归,返回 slope/intercept/R^2/方向/日变化/周期变化
- compute_moving_average: 简单移动平均,支持任意窗口大小
- detect_anomalies: 均值 +/- N 标准差异常检测

包含 21 个单元测试,覆盖边界条件和正常用例。
2026-04-28 19:50:46 +08:00
iven
781e1191a5 feat(message): SSE 告警/体征推送添加医患关系过滤
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
alert.triggered 和 device.readings.synced 事件现在只推送给
该患者的管床医生(通过 patient_doctor_relation 表查询),
而非广播给租户内所有用户。新增 3 个单元测试验证 payload
解析逻辑。
2026-04-28 19:49:38 +08:00
iven
e5546efa41 refactor(web): alerts + deviceReadings API 迁移为对象风格导出
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- alerts.ts: listAlerts → alertApi.list, acknowledgeAlert → alertApi.acknowledge 等
- deviceReadings.ts: batchCreateReadings → deviceReadingApi.batchCreate 等
- AlertList/AlertRuleList 引用处同步更新
- 其余 19 个函数式 API 文件记为待迁移(旧文件不强制迁移)
2026-04-28 19:47:48 +08:00
iven
99093d8143 refactor(web): 16 个列表页 columns 定义 useMemo 化 — 减少 Table 不必要 re-render
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
- AiPromptList/AiAnalysisList/AppointmentList 等 14 个主页面
- HealthRecordsTab/LabReportsTab 2 个 Tab 组件
- 每个 columns 依赖数组包含其引用的闭包变量(handleDelete/navigate 等)
2026-04-28 19:45:14 +08:00
iven
e76f4feb4f feat(health): 告警微信模板消息通知 + alert.triggered 事件消费者
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
2026-04-28 19:43:57 +08:00
iven
601b2d7f52 feat(mp): 首页设备状态卡片组件 — 血压计/血糖仪快捷入口 2026-04-28 19:42:24 +08:00
iven
00f615d8e5 feat(health): 新增血压/血糖临床阈值告警规则 + alert engine 直接查 device_readings 2026-04-28 19:40:25 +08:00
iven
8a61ae3f8e feat(health): device_readings 双写 vital_signs — 血压/血糖自动归档 2026-04-28 19:37:43 +08:00
iven
d715647a73 feat(mp): BloodPressureAdapter + GlucoseMeterAdapter — BLE 0x1810/0x1808 标准协议适配器 2026-04-28 19:30:03 +08:00
iven
e7b2e6382a chore(web): 降低 chunkSizeWarningLimit 从 600 至 500
Some checks failed
CI / rust-check (push) Has been cancelled
CI / rust-test (push) Has been cancelled
CI / frontend-build (push) Has been cancelled
CI / security-audit (push) Has been cancelled
2026-04-28 19:28:37 +08:00
iven
8a5b14e087 feat(mp): DeviceType 扩展支持 blood_pressure/blood_glucose + 适配器接口改数组返回 2026-04-28 19:27:14 +08:00
iven
83e243f03e feat(db): device_readings 新增 metric 字段用于多行拆分存储 2026-04-28 19:24:32 +08:00
917 changed files with 109303 additions and 17555 deletions

11
.lintstagedrc.js Normal file
View File

@@ -0,0 +1,11 @@
module.exports = {
'*.rs': [
'cargo fmt --check --',
() => 'cargo clippy -p erp-health -p erp-server -- -D warnings',
],
'apps/web/src/**/*.{ts,tsx}': (filenames) =>
`npx eslint --fix ${filenames.join(' ')}`,
'apps/web/src/**/*.test.{ts,tsx}': [
'cd apps/web && npx vitest run --reporter=verbose',
],
};

238
Cargo.lock generated
View File

@@ -288,6 +288,28 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
[[package]]
name = "aws-lc-rs"
version = "1.16.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ec6fb3fe69024a75fa7e1bfb48aa6cf59706a101658ea01bfd33b2b248a038f"
dependencies = [
"aws-lc-sys",
"zeroize",
]
[[package]]
name = "aws-lc-sys"
version = "0.40.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f50037ee5e1e41e7b8f9d161680a725bd1626cb6f8c7e901f91f942850852fe7"
dependencies = [
"cc",
"cmake",
"dunce",
"fs_extra",
]
[[package]]
name = "axum"
version = "0.8.8"
@@ -555,7 +577,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8144c22e24bbcf26ade86cb6501a0916c46b7e4787abdb0045a467eb1645a1d"
dependencies = [
"ambient-authority",
"rand",
"rand 0.8.5",
]
[[package]]
@@ -681,6 +703,15 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
[[package]]
name = "cmake"
version = "0.1.58"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678"
dependencies = [
"cc",
]
[[package]]
name = "cobs"
version = "0.3.0"
@@ -1056,7 +1087,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
"rand_core",
"rand_core 0.6.4",
"typenum",
]
@@ -1330,6 +1361,12 @@ dependencies = [
"dtoa",
]
[[package]]
name = "dunce"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
[[package]]
name = "either"
version = "1.15.0"
@@ -1374,10 +1411,12 @@ dependencies = [
"async-trait",
"axum",
"chrono",
"dashmap",
"erp-core",
"futures",
"handlebars",
"hex",
"redis",
"reqwest",
"sea-orm",
"serde",
@@ -1453,7 +1492,7 @@ dependencies = [
"dashmap",
"hex",
"hmac",
"rand",
"rand 0.8.5",
"sea-orm",
"serde",
"serde_json",
@@ -1490,6 +1529,7 @@ name = "erp-health"
version = "0.1.0"
dependencies = [
"aes-gcm",
"argon2",
"async-trait",
"axum",
"base64 0.22.1",
@@ -1497,7 +1537,9 @@ dependencies = [
"erp-core",
"hex",
"hmac",
"jsonwebtoken",
"num-traits",
"rand_core 0.6.4",
"sea-orm",
"serde",
"serde_json",
@@ -1625,30 +1667,12 @@ dependencies = [
"wit-bindgen 0.55.0",
]
[[package]]
name = "erp-points"
version = "0.1.0"
dependencies = [
"async-trait",
"axum",
"chrono",
"erp-core",
"sea-orm",
"serde",
"serde_json",
"thiserror 2.0.18",
"tokio",
"tracing",
"utoipa",
"uuid",
"validator",
]
[[package]]
name = "erp-server"
version = "0.1.0"
dependencies = [
"anyhow",
"async-trait",
"axum",
"chrono",
"config",
@@ -1660,14 +1684,18 @@ dependencies = [
"erp-health",
"erp-message",
"erp-plugin",
"erp-points",
"erp-server-migration",
"erp-workflow",
"futures",
"hex",
"metrics",
"metrics-exporter-prometheus",
"moka",
"redis",
"sea-orm",
"serde",
"serde_json",
"sha2",
"sqlx",
"tokio",
"tower",
@@ -1842,6 +1870,12 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "fs_extra"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
[[package]]
name = "funty"
version = "2.0.0"
@@ -2286,6 +2320,7 @@ dependencies = [
"hyper",
"hyper-util",
"rustls",
"rustls-native-certs",
"tokio",
"tokio-rustls",
"tower-service",
@@ -2478,8 +2513,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af1955a75fa080c677d3972822ec4bad316169ab1cfc6c257a942c2265dbe5fe"
dependencies = [
"bitmaps",
"rand_core",
"rand_xoshiro",
"rand_core 0.6.4",
"rand_xoshiro 0.6.0",
"sized-chunks",
"typenum",
"version_check",
@@ -2856,6 +2891,53 @@ dependencies = [
"autocfg",
]
[[package]]
name = "metrics"
version = "0.24.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d5312e9ba3771cfa961b585728215e3d972c950a3eed9252aa093d6301277e8"
dependencies = [
"ahash 0.8.12",
"portable-atomic",
]
[[package]]
name = "metrics-exporter-prometheus"
version = "0.16.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd7399781913e5393588a8d8c6a2867bf85fb38eaf2502fdce465aad2dc6f034"
dependencies = [
"base64 0.22.1",
"http-body-util",
"hyper",
"hyper-rustls",
"hyper-util",
"indexmap",
"ipnet",
"metrics",
"metrics-util",
"quanta",
"thiserror 1.0.69",
"tokio",
"tracing",
]
[[package]]
name = "metrics-util"
version = "0.19.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8496cc523d1f94c1385dd8f0f0c2c480b2b8aeccb5b7e4485ad6365523ae376"
dependencies = [
"crossbeam-epoch",
"crossbeam-utils",
"hashbrown 0.15.5",
"metrics",
"quanta",
"rand 0.9.4",
"rand_xoshiro 0.7.0",
"sketches-ddsketch",
]
[[package]]
name = "mime"
version = "0.3.17"
@@ -3009,7 +3091,7 @@ dependencies = [
"num-integer",
"num-iter",
"num-traits",
"rand",
"rand 0.8.5",
"smallvec",
"zeroize",
]
@@ -3218,7 +3300,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"
dependencies = [
"base64ct",
"rand_core",
"rand_core 0.6.4",
"subtle",
]
@@ -3342,7 +3424,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d"
dependencies = [
"phf_shared",
"rand",
"rand 0.8.5",
]
[[package]]
@@ -3572,6 +3654,21 @@ dependencies = [
"syn 2.0.117",
]
[[package]]
name = "quanta"
version = "0.12.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3ab5a9d756f0d97bdc89019bd2e4ea098cf9cde50ee7564dde6b81ccc8f06c7"
dependencies = [
"crossbeam-utils",
"libc",
"once_cell",
"raw-cpuid",
"wasi",
"web-sys",
"winapi",
]
[[package]]
name = "quote"
version = "1.0.45"
@@ -3606,8 +3703,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
dependencies = [
"libc",
"rand_chacha",
"rand_core",
"rand_chacha 0.3.1",
"rand_core 0.6.4",
]
[[package]]
name = "rand"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea"
dependencies = [
"rand_chacha 0.9.0",
"rand_core 0.9.5",
]
[[package]]
@@ -3617,7 +3724,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
"rand_core",
"rand_core 0.6.4",
]
[[package]]
name = "rand_chacha"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
"rand_core 0.9.5",
]
[[package]]
@@ -3629,13 +3746,40 @@ dependencies = [
"getrandom 0.2.17",
]
[[package]]
name = "rand_core"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
dependencies = [
"getrandom 0.3.4",
]
[[package]]
name = "rand_xoshiro"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f97cdb2a36ed4183de61b2f824cc45c9f1037f28afe0a322e9fff4c108b5aaa"
dependencies = [
"rand_core",
"rand_core 0.6.4",
]
[[package]]
name = "rand_xoshiro"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f703f4665700daf5512dcca5f43afa6af89f09db47fb56be587f80636bda2d41"
dependencies = [
"rand_core 0.9.5",
]
[[package]]
name = "raw-cpuid"
version = "11.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186"
dependencies = [
"bitflags",
]
[[package]]
@@ -3876,7 +4020,7 @@ dependencies = [
"num-traits",
"pkcs1",
"pkcs8",
"rand_core",
"rand_core 0.6.4",
"signature",
"spki",
"subtle",
@@ -3903,7 +4047,7 @@ dependencies = [
"borsh",
"bytes",
"num-traits",
"rand",
"rand 0.8.5",
"rkyv",
"serde",
"serde_json",
@@ -3982,6 +4126,7 @@ version = "0.23.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "758025cb5fccfd3bc2fd74708fd4682be41d99e5dff73c377c0646c6012c73a4"
dependencies = [
"aws-lc-rs",
"once_cell",
"ring",
"rustls-pki-types",
@@ -3990,6 +4135,18 @@ dependencies = [
"zeroize",
]
[[package]]
name = "rustls-native-certs"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "612460d5f7bea540c490b2b6395d8e34a953e52b491accd6c86c8164c5932a63"
dependencies = [
"openssl-probe",
"rustls-pki-types",
"schannel",
"security-framework",
]
[[package]]
name = "rustls-pki-types"
version = "1.14.0"
@@ -4005,6 +4162,7 @@ version = "0.103.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20a6af516fea4b20eccceaf166e8aa666ac996208e8a644ce3ef5aa783bc7cd4"
dependencies = [
"aws-lc-rs",
"ring",
"rustls-pki-types",
"untrusted",
@@ -4398,7 +4556,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
dependencies = [
"digest",
"rand_core",
"rand_core 0.6.4",
]
[[package]]
@@ -4441,6 +4599,12 @@ dependencies = [
"typenum",
]
[[package]]
name = "sketches-ddsketch"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c6f73aeb92d671e0cc4dca167e59b2deb6387c375391bc99ee743f326994a2b"
[[package]]
name = "slab"
version = "0.4.12"
@@ -4618,7 +4782,7 @@ dependencies = [
"memchr",
"once_cell",
"percent-encoding",
"rand",
"rand 0.8.5",
"rsa",
"rust_decimal",
"serde",
@@ -4662,7 +4826,7 @@ dependencies = [
"memchr",
"num-bigint",
"once_cell",
"rand",
"rand 0.8.5",
"rust_decimal",
"serde",
"serde_json",

View File

@@ -17,7 +17,6 @@ members = [
"crates/erp-plugin-itops",
"crates/erp-health",
"crates/erp-ai",
"crates/erp-points",
"crates/erp-plugin-assessment",
"crates/erp-dialysis",
]
@@ -106,16 +105,20 @@ erp-config = { path = "crates/erp-config" }
erp-plugin = { path = "crates/erp-plugin" }
erp-health = { path = "crates/erp-health" }
erp-ai = { path = "crates/erp-ai" }
erp-points = { path = "crates/erp-points" }
erp-dialysis = { path = "crates/erp-dialysis" }
# Async streaming
futures = "0.3"
tokio-stream = "0.1"
async-stream = "0.3"
dashmap = "6"
# Template engine
handlebars = "6"
# HTML sanitization
ammonia = "4"
# Metrics
metrics = "0.24"
metrics-exporter-prometheus = "0.16"

View File

@@ -0,0 +1,69 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
// 使用 vi.hoisted 确保 storage 在 mock 提升前可用
const { storage } = vi.hoisted(() => ({
storage: new Map<string, string>(),
}));
vi.mock('@tarojs/taro', () => ({
default: {
openBluetoothAdapter: vi.fn().mockResolvedValue({}),
closeBluetoothAdapter: vi.fn().mockResolvedValue({}),
startBluetoothDevicesDiscovery: vi.fn().mockResolvedValue({}),
stopBluetoothDevicesDiscovery: vi.fn().mockResolvedValue({}),
onBluetoothDeviceFound: vi.fn(),
offBluetoothDeviceFound: vi.fn(),
createBLEConnection: vi.fn().mockResolvedValue({}),
closeBLEConnection: vi.fn().mockResolvedValue({}),
getBLEDeviceServices: vi.fn().mockResolvedValue({ services: [] }),
getBLEDeviceCharacteristics: vi.fn().mockResolvedValue({ characteristics: [] }),
notifyBLECharacteristicValueChange: vi.fn().mockResolvedValue({}),
onBLECharacteristicValueChange: vi.fn(),
onBLEConnectionStateChange: vi.fn(),
getStorageSync: vi.fn((key: string) => storage.get(key) || ''),
setStorageSync: vi.fn((key: string, value: string) => { storage.set(key, value); }),
removeStorageSync: vi.fn((key: string) => { storage.delete(key); }),
},
}));
import { BLEManager } from '@/services/ble/BLEManager';
import { XiaomiBandAdapter } from '@/services/ble/adapters/XiaomiBandAdapter';
describe('BLEManager DataBuffer 集成', () => {
let manager: BLEManager;
beforeEach(() => {
storage.clear();
manager = new BLEManager();
manager.registerAdapter(XiaomiBandAdapter);
});
afterEach(async () => {
await manager.destroy();
});
it('registerAdapter 添加适配器', () => {
const count = (manager as any).adapters.length;
expect(count).toBeGreaterThanOrEqual(1);
});
it('getCachedReadings 返回空数组(未连接时)', () => {
const readings = manager.getCachedReadings();
expect(readings).toEqual([]);
});
it('flushPendingReadings 无缓存时返回 0', async () => {
const uploadFn = vi.fn().mockResolvedValue(0);
const count = await manager.flushPendingReadings(uploadFn);
expect(count).toBe(0);
expect(uploadFn).not.toHaveBeenCalled();
});
it('DataBuffer 实例已初始化', () => {
const buffer = (manager as any).dataBuffer;
expect(buffer).toBeDefined();
expect(typeof buffer.push).toBe('function');
expect(typeof buffer.flush).toBe('function');
expect(typeof buffer.restore).toBe('function');
});
});

View File

@@ -0,0 +1,89 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { DataBuffer } from '@/services/ble/DataBuffer';
import type { NormalizedReading } from '@/services/ble/types';
// Mock Taro Storage
const storage = new Map<string, string>();
vi.mock('@tarojs/taro', () => ({
default: {
getStorageSync: vi.fn((key: string) => storage.get(key) || ''),
setStorageSync: vi.fn((key: string, value: string) => { storage.set(key, value); }),
removeStorageSync: vi.fn((key: string) => { storage.delete(key); }),
getStorageInfoSync: vi.fn(() => ({ keys: Array.from(storage.keys()), limitSize: 10240, currentSize: storage.size })),
},
}));
function makeReading(overrides: Partial<NormalizedReading> = {}): NormalizedReading {
return {
device_type: 'heart_rate',
values: { heart_rate: 72 },
measured_at: new Date().toISOString(),
...overrides,
};
}
describe('DataBuffer', () => {
let buffer: DataBuffer;
beforeEach(() => {
storage.clear();
buffer = new DataBuffer({ bucketSize: 100 });
});
it('push 添加读数并持久化', () => {
const reading = makeReading();
buffer.push(reading);
expect(buffer.size()).toBe(1);
});
it('push 批量添加读数', () => {
const readings = Array.from({ length: 10 }, (_, i) =>
makeReading({ measured_at: new Date(Date.now() + i * 1000).toISOString() }),
);
buffer.push(readings);
expect(buffer.size()).toBe(10);
});
it('flush 返回并清空缓冲区', () => {
buffer.push([
makeReading({ measured_at: '2026-05-04T10:00:00.000Z' }),
makeReading({ measured_at: '2026-05-04T10:00:01.000Z' }),
]);
const flushed = buffer.flush();
expect(flushed.length).toBe(2);
expect(buffer.size()).toBe(0);
});
it('超过 maxTotal 时丢弃最旧数据', () => {
const smallBuffer = new DataBuffer({ bucketSize: 5, maxTotal: 10 });
for (let i = 0; i < 15; i++) {
smallBuffer.push(makeReading({ measured_at: new Date(i * 1000).toISOString() }));
}
expect(smallBuffer.size()).toBe(10);
});
it('去重:相同 measured_at + device_type 不重复存储', () => {
const ts = '2026-05-04T10:00:00.000Z';
buffer.push(makeReading({ measured_at: ts }));
buffer.push(makeReading({ measured_at: ts }));
expect(buffer.size()).toBe(1);
});
it('restore 从 Storage 恢复未上传数据', () => {
buffer.push([
makeReading({ measured_at: '2026-05-04T10:00:00.000Z' }),
makeReading({ measured_at: '2026-05-04T10:00:01.000Z' }),
]);
// 模拟重启:新建 DataBuffer 并 restore
const restored = new DataBuffer({ bucketSize: 100 });
const count = restored.restore();
expect(count).toBe(2);
expect(restored.size()).toBe(2);
});
it('clear 清空缓冲区和 Storage', () => {
buffer.push(makeReading());
buffer.clear();
expect(buffer.size()).toBe(0);
});
});

View File

@@ -0,0 +1,91 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { DataSyncScheduler } from '@/services/ble/DataSyncScheduler';
const storage = new Map<string, string>();
vi.mock('@tarojs/taro', () => ({
default: {
getStorageSync: vi.fn((key: string) => storage.get(key) || ''),
setStorageSync: vi.fn((key: string, value: string) => { storage.set(key, value); }),
removeStorageSync: vi.fn((key: string) => { storage.delete(key); }),
},
}));
describe('DataSyncScheduler', () => {
let scheduler: DataSyncScheduler;
let syncFn: ReturnType<typeof vi.fn>;
beforeEach(() => {
storage.clear();
syncFn = vi.fn().mockResolvedValue({ success: true, uploadedCount: 5 });
scheduler = new DataSyncScheduler({
intervalMs: 60 * 60 * 1000,
storageKey: 'last_ble_sync',
});
});
afterEach(() => {
scheduler.destroy();
});
it('首次同步:无记录时立即需要同步', () => {
expect(scheduler.needsSync()).toBe(true);
});
it('同步后记录时间戳', async () => {
await scheduler.recordSync(syncFn);
expect(storage.has('last_ble_sync')).toBe(true);
expect(syncFn).toHaveBeenCalled();
});
it('同步后不需要再次同步', async () => {
await scheduler.recordSync(syncFn);
expect(scheduler.needsSync()).toBe(false);
});
it('超过间隔后需要再次同步', async () => {
const twoHoursAgo = Date.now() - 2 * 60 * 60 * 1000;
storage.set('last_ble_sync', JSON.stringify({ lastSyncAt: twoHoursAgo }));
scheduler = new DataSyncScheduler({ intervalMs: 60 * 60 * 1000, storageKey: 'last_ble_sync' });
expect(scheduler.needsSync()).toBe(true);
});
it('同步失败不更新时间戳', async () => {
const failFn = vi.fn().mockRejectedValue(new Error('network error'));
const oneHourAgo = Date.now() - 60 * 60 * 1000;
storage.set('last_ble_sync', JSON.stringify({ lastSyncAt: oneHourAgo }));
await scheduler.recordSync(failFn);
const stored = JSON.parse(storage.get('last_ble_sync') || '{}');
expect(stored.lastSyncAt).toBe(oneHourAgo);
});
it('tryAutoSync 首次时触发同步', async () => {
const result = await scheduler.tryAutoSync(syncFn);
expect(result).toBe(true);
expect(syncFn).toHaveBeenCalledTimes(1);
});
it('tryAutoSync 未超时不触发', async () => {
await scheduler.recordSync(syncFn);
syncFn.mockClear();
const result = await scheduler.tryAutoSync(syncFn);
expect(result).toBe(false);
expect(syncFn).not.toHaveBeenCalled();
});
it('destroy 清理定时器', () => {
const clearIntervalSpy = vi.spyOn(global, 'clearInterval');
scheduler.startPeriodicCheck(syncFn, 30000);
scheduler.destroy();
expect(clearIntervalSpy).toHaveBeenCalled();
clearIntervalSpy.mockRestore();
});
it('getLastSyncAt 返回上次同步时间', async () => {
await scheduler.recordSync(syncFn);
const lastSync = scheduler.getLastSyncAt();
expect(lastSync).toBeTruthy();
expect(typeof lastSync).toBe('number');
});
});

View File

@@ -0,0 +1,158 @@
import { describe, it, expect } from 'vitest';
import { createGenericBleAdapter } from '@/services/ble/adapters/GenericBleAdapter';
import type { GenericBLEProfile } from '@/services/ble/types';
// ---- Heart Rate (0x180D / 0x2A37) ----
// Flag byte=0x00 (UINT8), HR=75
function makeHeartRateData(hr: number, isUint16 = false): ArrayBuffer {
const buf = new ArrayBuffer(isUint16 ? 3 : 2);
const view = new DataView(buf);
view.setUint8(0, isUint16 ? 0x01 : 0x00);
if (isUint16) {
view.setUint16(1, hr, true);
} else {
view.setUint8(1, hr);
}
return buf;
}
// ---- Health Thermometer (0x1809 / 0x2A1C) ----
// IEEE 11073 FLOAT: 32-bit — mantissa (24-bit) + exponent (8-bit)
function makeTemperatureData(tempCelsius: number): ArrayBuffer {
const buf = new ArrayBuffer(4);
const view = new DataView(buf);
// flags byte: 0x00 = Celsius, no timestamp, no type
view.setUint8(0, 0x00);
// 11073 FLOAT: mantissa * 10^exponent
// For 36.5: mantissa=365, exponent=-1
const mantissa = Math.round(tempCelsius * 10);
const exponent = -1;
view.setInt16(1, mantissa, true);
view.setInt8(3, exponent);
return buf;
}
describe('GenericBleAdapter', () => {
describe('心率解析', () => {
const adapter = createGenericBleAdapter({
name: 'Test Wristband',
supportedModels: ['TestBand'],
profiles: ['heart_rate'],
});
it('解析 UINT8 心率', () => {
const data = makeHeartRateData(75);
const results = adapter.parseNotification(
'0000180D-0000-1000-8000-00805f9b34fb',
'00002A37-0000-1000-8000-00805f9b34fb',
data,
);
expect(results.length).toBe(1);
expect(results[0].device_type).toBe('heart_rate');
expect(results[0].values.heart_rate).toBe(75);
});
it('解析 UINT16 心率', () => {
const data = makeHeartRateData(200, true);
const results = adapter.parseNotification(
'0000180D-0000-1000-8000-00805f9b34fb',
'00002A37-0000-1000-8000-00805f9b34fb',
data,
);
expect(results.length).toBe(1);
expect(results[0].values.heart_rate).toBe(200);
});
it('忽略非目标 Characteristic', () => {
const data = makeHeartRateData(75);
const results = adapter.parseNotification(
'0000180D-0000-1000-8000-00805f9b34fb',
'00002A38-0000-1000-8000-00805f9b34fb', // Body Sensor Location
data,
);
expect(results.length).toBe(0);
});
});
describe('体温解析', () => {
const adapter = createGenericBleAdapter({
name: 'Test Thermometer',
supportedModels: ['TestThermo'],
profiles: ['health_thermometer'],
});
it('解析体温读数', () => {
const data = makeTemperatureData(36.5);
const results = adapter.parseNotification(
'00001809-0000-1000-8000-00805f9b34fb',
'00002A1C-0000-1000-8000-00805f9b34fb',
data,
);
expect(results.length).toBe(1);
expect(results[0].device_type).toBe('temperature');
expect(results[0].values.value).toBeCloseTo(36.5, 0);
});
});
describe('多 Profile 适配器', () => {
const adapter = createGenericBleAdapter({
name: 'Multi-Profile Band',
supportedModels: ['CustomBand', 'MedicalBand'],
profiles: ['heart_rate', 'health_thermometer'],
});
it('包含两个 Service UUID', () => {
expect(adapter.serviceUUIDs.length).toBe(2);
});
it('包含两个 Profile 的 Characteristic', () => {
expect(adapter.notifyCharacteristics.length).toBe(2);
});
it('supportedModels 配置正确', () => {
expect(adapter.supportedModels).toEqual(['CustomBand', 'MedicalBand']);
});
it('解析心率 + 体温', () => {
const hrResults = adapter.parseNotification(
'0000180D-0000-1000-8000-00805f9b34fb',
'00002A37-0000-1000-8000-00805f9b34fb',
makeHeartRateData(80),
);
expect(hrResults[0].device_type).toBe('heart_rate');
const tempResults = adapter.parseNotification(
'00001809-0000-1000-8000-00805f9b34fb',
'00002A1C-0000-1000-8000-00805f9b34fb',
makeTemperatureData(37.2),
);
expect(tempResults[0].device_type).toBe('temperature');
});
});
describe('边界情况', () => {
const adapter = createGenericBleAdapter({
name: 'Edge Case Band',
supportedModels: ['Edge'],
profiles: ['heart_rate'],
});
it('空数据返回空数组', () => {
const results = adapter.parseNotification(
'0000180D-0000-1000-8000-00805f9b34fb',
'00002A37-0000-1000-8000-00805f9b34fb',
new ArrayBuffer(0),
);
expect(results.length).toBe(0);
});
it('心率超范围 (>300) 返回空数组', () => {
const results = adapter.parseNotification(
'0000180D-0000-1000-8000-00805f9b34fb',
'00002A37-0000-1000-8000-00805f9b34fb',
makeHeartRateData(0),
);
expect(results.length).toBe(0);
});
});
});

View File

@@ -2,6 +2,10 @@ import type { UserConfigExport } from '@tarojs/cli';
export default {
logger: { quiet: false },
mini: {},
mini: {
miniCssExtractPluginOption: {
ignoreOrder: true,
},
},
h5: {},
} satisfies UserConfigExport;

View File

@@ -5,7 +5,7 @@ export default defineConfig(async (merge) => {
const baseConfig = {
projectName: 'hms-miniprogram',
date: '2026-4-23',
designWidth: 750,
designWidth: 375,
deviceRatio: { 640: 2.34 / 2, 750: 1, 375: 2, 828: 1.81 / 2 },
sourceRoot: 'src',
outputRoot: 'dist',
@@ -14,6 +14,11 @@ export default defineConfig(async (merge) => {
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
'process.env.TARO_APP_API_URL': JSON.stringify(process.env.TARO_APP_API_URL || 'http://localhost:3000/api/v1'),
'process.env.TARO_APP_ENCRYPTION_KEY': JSON.stringify(process.env.TARO_APP_ENCRYPTION_KEY || ''),
'process.env.TARO_APP_WX_TEMPLATE_APPOINTMENT': JSON.stringify(process.env.TARO_APP_WX_TEMPLATE_APPOINTMENT || ''),
'process.env.TARO_APP_WX_TEMPLATE_FOLLOWUP': JSON.stringify(process.env.TARO_APP_WX_TEMPLATE_FOLLOWUP || ''),
'process.env.TARO_APP_WX_TEMPLATE_REPORT': JSON.stringify(process.env.TARO_APP_WX_TEMPLATE_REPORT || ''),
'process.env.TARO_APP_WX_TEMPLATE_CRITICAL_ALERT': JSON.stringify(process.env.TARO_APP_WX_TEMPLATE_CRITICAL_ALERT || ''),
'process.env.TARO_APP_WX_TEMPLATE_HEALTH_ABNORMAL': JSON.stringify(process.env.TARO_APP_WX_TEMPLATE_HEALTH_ABNORMAL || ''),
},
copy: { patterns: [], options: {} },
framework: 'react',
@@ -27,6 +32,9 @@ export default defineConfig(async (merge) => {
mini: {
compile: {
exclude: [],
include: [
require.resolve('zod').replace(/[\\/]index\.cjs$/, ''),
],
},
postcss: {
pxtransform: { enable: true, config: {} },

View File

@@ -0,0 +1,18 @@
// apps/miniprogram/e2e/check-readiness.ts
async function check(url: string, label: string) {
for (let i = 0; i < 5; i++) {
try {
const res = await fetch(url);
if (res.ok) return;
} catch { /* retry */ }
console.log(`${label} 未就绪 (${i + 1}/5)...`);
await new Promise((r) => setTimeout(r, 2000));
}
throw new Error(`${label} 未就绪: ${url}`);
}
export default async function setup() {
const apiBase = process.env.E2E_API_URL || 'http://localhost:3000';
await check(`${apiBase}/api/v1/health`, '后端 API');
console.log('✅ 小程序 E2E 环境就绪');
}

View File

@@ -0,0 +1,41 @@
// apps/miniprogram/e2e/flows/mall-flow.spec.ts
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { AutomatorClient } from '../helpers/automator-client';
import { MpAuthHelper } from '../helpers/auth.helper';
import { MpApiClient } from '../helpers/api-client';
import { MpNavigator } from '../helpers/navigation.helper';
describe('积分商城浏览链路', () => {
let client: AutomatorClient;
let auth: MpAuthHelper;
let nav: MpNavigator;
beforeAll(async () => {
const api = new MpApiClient();
client = new AutomatorClient();
await client.connect();
auth = new MpAuthHelper(client, api);
nav = new MpNavigator(client);
await auth.loginAsTestPatient();
}, 30_000);
afterAll(async () => {
await client.disconnect();
});
it('商城首页加载', async () => {
await nav.goToMall();
const el = await client.waitForElement('.container', 5000);
expect(el).toBeDefined();
});
it('浏览商品分类', async () => {
const tabs = await client.getElements('.tab-item, .category-item, .ant-tabs-tab');
if (tabs.length > 1) {
await tabs[1].tap();
await new Promise((r) => setTimeout(r, 1000));
}
const pageData = await client.getPageData();
expect(pageData).toBeDefined();
});
});

View File

@@ -0,0 +1,45 @@
// apps/miniprogram/e2e/flows/patient-health-view.spec.ts
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { AutomatorClient } from '../helpers/automator-client';
import { MpAuthHelper } from '../helpers/auth.helper';
import { MpApiClient } from '../helpers/api-client';
import { MpNavigator } from '../helpers/navigation.helper';
describe('患者健康数据查看链路', () => {
let client: AutomatorClient;
let auth: MpAuthHelper;
let nav: MpNavigator;
let api: MpApiClient;
beforeAll(async () => {
api = new MpApiClient();
client = new AutomatorClient();
await client.connect();
auth = new MpAuthHelper(client, api);
nav = new MpNavigator(client);
}, 30_000);
afterAll(async () => {
await client.disconnect();
});
it('登录后查看首页健康数据', async () => {
await auth.loginAsTestPatient();
await nav.goToHealthHome();
const pageData = await client.getPageData();
expect(pageData).toBeDefined();
});
it('查看体征趋势', async () => {
await nav.goToVitalSignsTrend();
const el = await client.waitForElement('.trend-chart, canvas, .container', 5000);
expect(el).toBeDefined();
});
it('查看随访任务列表', async () => {
await nav.goToFollowUpTasks();
const el = await client.waitForElement('.task-list, .container', 5000);
expect(el).toBeDefined();
});
});

View File

@@ -0,0 +1,47 @@
// apps/miniprogram/e2e/flows/points-flow.spec.ts
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { AutomatorClient } from '../helpers/automator-client';
import { MpAuthHelper } from '../helpers/auth.helper';
import { MpApiClient } from '../helpers/api-client';
import { MpNavigator } from '../helpers/navigation.helper';
describe('积分签到兑换链路', () => {
let client: AutomatorClient;
let auth: MpAuthHelper;
let nav: MpNavigator;
let api: MpApiClient;
beforeAll(async () => {
api = new MpApiClient();
client = new AutomatorClient();
await client.connect();
auth = new MpAuthHelper(client, api);
nav = new MpNavigator(client);
await auth.loginAsTestPatient();
}, 30_000);
afterAll(async () => {
await client.disconnect();
});
it('浏览积分商城', async () => {
await nav.goToMall();
const el = await client.waitForElement('.product-list, .container', 5000);
expect(el).toBeDefined();
});
it('查看商品详情', async () => {
const items = await client.getElements('.product-item, .product-card');
if (items.length > 0) {
await items[0].tap();
const pageData = await client.getPageData();
expect(pageData).toBeDefined();
}
});
it('查看订单列表', async () => {
await nav.goToOrders();
const el = await client.waitForElement('.order-list, .container, .empty', 5000);
expect(el).toBeDefined();
});
});

View File

@@ -0,0 +1,47 @@
// apps/miniprogram/e2e/flows/vital-signs-input.spec.ts
import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest';
import { AutomatorClient } from '../helpers/automator-client';
import { MpAuthHelper } from '../helpers/auth.helper';
import { MpApiClient } from '../helpers/api-client';
import { MpNavigator } from '../helpers/navigation.helper';
describe('体征数据录入链路', () => {
let client: AutomatorClient;
let auth: MpAuthHelper;
let nav: MpNavigator;
let api: MpApiClient;
const cleanup: Array<() => Promise<void>> = [];
beforeAll(async () => {
api = new MpApiClient();
await api.login();
client = new AutomatorClient();
await client.connect();
auth = new MpAuthHelper(client, api);
nav = new MpNavigator(client);
await auth.loginAsTestPatient();
}, 30_000);
afterEach(async () => {
for (const fn of cleanup.reverse()) await fn().catch(() => {});
cleanup.length = 0;
});
afterAll(async () => {
await client.disconnect();
});
it('填写并提交血压心率数据', async () => {
await nav.goToVitalSignsInput();
await client.inputText('input[placeholder*="收缩压"], #systolic', '118');
await client.inputText('input[placeholder*="舒张压"], #diastolic', '76');
await client.inputText('input[placeholder*="心率"], #heartRate', '68');
await client.tap('button[type="submit"], .submit-btn');
const el = await client.waitForElement('.success, .ant-message-success, [class*="toast"]', 5000).catch(() => null);
const pageData = await client.getPageData();
expect(pageData).toBeDefined();
});
});

View File

@@ -0,0 +1,70 @@
// apps/miniprogram/e2e/helpers/api-client.ts
// 简化版 API Client用于小程序 E2E 数据准备/清理
const API_BASE = process.env.E2E_API_URL || 'http://localhost:3000/api/v1';
export class MpApiClient {
private token = '';
async login(username?: string, password?: string) {
const res = await fetch(`${API_BASE}/auth/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username: username || process.env.E2E_ADMIN_USER || 'admin',
password: password || process.env.E2E_ADMIN_PASS || 'Admin@2026',
}),
});
const json = await res.json();
if (!json.success) throw new Error('Login failed');
this.token = json.data.access_token;
return json.data;
}
getToken() { return this.token; }
async createPatient(overrides?: Record<string, unknown>) {
return this.post('/health/patients', overrides ?? {});
}
async deletePatient(id: string, version: number) {
await this.del(`/health/patients/${id}`, { version });
}
async createVitalSigns(patientId: string, overrides?: Record<string, unknown>) {
return this.post(`/health/patients/${patientId}/vital-signs`, overrides ?? {});
}
async deleteVitalSigns(patientId: string, id: string, version: number) {
await this.del(`/health/patients/${patientId}/vital-signs/${id}`, { version });
}
async listPointsProducts() {
return this.get('/health/points/products');
}
private async headers() {
return { 'Content-Type': 'application/json', Authorization: `Bearer ${this.token}` };
}
private async get(path: string) {
const res = await fetch(`${API_BASE}${path}`, { headers: await this.headers() });
const json = await res.json();
return json.data;
}
private async post(path: string, body: unknown) {
const res = await fetch(`${API_BASE}${path}`, {
method: 'POST', headers: await this.headers(), body: JSON.stringify(body),
});
const json = await res.json();
if (!json.success) throw new Error(`POST ${path} failed`);
return json.data;
}
private async del(path: string, body?: unknown) {
await fetch(`${API_BASE}${path}`, {
method: 'DELETE', headers: await this.headers(), body: body ? JSON.stringify(body) : undefined,
});
}
}

View File

@@ -0,0 +1,26 @@
// apps/miniprogram/e2e/helpers/auth.helper.ts
import { AutomatorClient } from './automator-client';
import { MpApiClient } from './api-client';
export class MpAuthHelper {
constructor(
private client: AutomatorClient,
private api: MpApiClient,
) {}
async loginAsTestPatient() {
const loginRes = await this.api.login(
process.env.E2E_MP_USER || 'mp_e2e_test',
process.env.E2E_MP_PASS || 'Test@2026',
);
await this.client.reLaunch('/pages/index/index');
const page = await this.client.currentPage();
await this.client.callMethod('page', 'setData', {
'access_token': loginRes.access_token,
});
await this.client.reLaunch('pages/index/index');
}
}

View File

@@ -0,0 +1,96 @@
// apps/miniprogram/e2e/helpers/automator-client.ts
import automator from 'miniprogram-automator';
const DEFAULT_CLI_PATH = 'C:/Program Files (x86)/Tencent/微信web开发者工具/cli.bat';
const DEFAULT_PROJECT_PATH = process.cwd();
export class AutomatorClient {
private mini: automator.MiniProgram | null = null;
async connect(cliPath?: string, projectPath?: string) {
this.mini = await automator.launch({
cliPath: cliPath || DEFAULT_CLI_PATH,
projectPath: projectPath || DEFAULT_PROJECT_PATH,
});
}
async disconnect() {
if (this.mini) {
await this.mini.close();
this.mini = null;
}
}
private getMini(): automator.MiniProgram {
if (!this.mini) throw new Error('AutomatorClient 未连接,请先调用 connect()');
return this.mini;
}
async currentPage(): Promise<automator.Page> {
return this.getMini().currentPage();
}
async navigateTo(path: string, _query?: Record<string, string>) {
const page = await this.getMini().navigateTo(`/${path.replace(/^\//, '')}`);
return page;
}
async navigateBack() {
await this.getMini().navigateBack();
}
async reLaunch(path: string) {
await this.getMini().reLaunch(`/${path.replace(/^\//, '')}`);
}
async tap(selector: string) {
const page = this.getMini().currentPage();
const element = await page.$(selector);
if (!element) throw new Error(`元素未找到: ${selector}`);
await element.tap();
}
async inputText(selector: string, value: string) {
const page = this.getMini().currentPage();
const element = await page.$(selector);
if (!element) throw new Error(`元素未找到: ${selector}`);
await element.setValue(value);
}
async getElement(selector: string) {
const page = this.getMini().currentPage();
return page.$(selector);
}
async getElements(selector: string) {
const page = this.getMini().currentPage();
return page.$$(selector);
}
async waitForElement(selector: string, timeout = 5000): Promise<automator.Element> {
const start = Date.now();
while (Date.now() - start < timeout) {
const el = await this.getElement(selector);
if (el) return el;
await new Promise((r) => setTimeout(r, 200));
}
throw new Error(`等待元素超时: ${selector} (${timeout}ms)`);
}
async getPageData(path?: string) {
const page = this.getMini().currentPage();
return page.data(path);
}
async screenshot(path?: string): Promise<Buffer> {
const page = this.getMini().currentPage();
return page.screenshot({ path });
}
async callMethod(selector: string, method: string, ...args: unknown[]) {
const page = this.getMini().currentPage();
const element = await page.$(selector);
if (!element) throw new Error(`元素未找到: ${selector}`);
return element.callMethod(method, ...args);
}
}

View File

@@ -0,0 +1,34 @@
// apps/miniprogram/e2e/helpers/navigation.helper.ts
import { AutomatorClient } from './automator-client';
export class MpNavigator {
constructor(private client: AutomatorClient) {}
async goToHealthHome() {
await this.client.reLaunch('pages/pkg-health/index');
}
async goToVitalSignsInput() {
await this.client.navigateTo('pages/pkg-health/input/index');
}
async goToVitalSignsTrend() {
await this.client.navigateTo('pages/pkg-health/trend/index');
}
async goToProfile() {
await this.client.navigateTo('pages/pkg-profile/index');
}
async goToMall() {
await this.client.reLaunch('pages/pkg-mall/index');
}
async goToFollowUpTasks() {
await this.client.navigateTo('pages/pkg-health/followups/index');
}
async goToOrders() {
await this.client.navigateTo('pages/pkg-mall/orders/index');
}
}

View File

@@ -0,0 +1,13 @@
// apps/miniprogram/e2e/vitest.config.ts
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
root: './e2e',
testTimeout: 30_000,
hookTimeout: 30_000,
testSequence: { sequential: true },
reporter: 'verbose',
globalSetup: ['./check-readiness.ts'],
},
});

View File

@@ -5,7 +5,8 @@
"description": "HMS 健康管理平台患者小程序",
"scripts": {
"build:weapp": "taro build --type weapp",
"dev:weapp": "taro build --type weapp --watch"
"dev:weapp": "taro build --type weapp --watch",
"test:e2e": "vitest run --config e2e/vitest.config.ts"
},
"browserslist": [
"last 3 versions",
@@ -41,6 +42,8 @@
"miniprogram-automator": "^0.12.1",
"sass": "^1.87.0",
"typescript": "^5.8.0",
"vite": "^8.0.10",
"vitest": "^4.1.5",
"webpack": "~5.95.0"
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -9,8 +9,12 @@
"enhance": false,
"compileHotReLoad": true,
"postcss": false,
"minified": false,
"minified": true,
"bundle": false,
"minifyWXML": true
}
"minifyWXML": true,
"packNpmManually": false,
"packNpmRelationList": [],
"ignoreUploadUnusedFiles": true
},
"condition": {}
}

View File

@@ -7,7 +7,7 @@
"lazyloadPlaceholderEnable": false,
"skylineRenderEnable": false,
"preloadBackgroundData": false,
"autoAudits": false,
"autoAudits": true,
"useApiHook": true,
"showShadowRootInWxmlPanel": false,
"useStaticServer": false,

View File

@@ -3,6 +3,7 @@ export default defineAppConfig({
'pages/index/index',
'pages/login/index',
'pages/health/index',
'pages/messages/index',
'pages/consultation/index',
'pages/consultation/detail/index',
'pages/mall/index',
@@ -10,14 +11,13 @@ export default defineAppConfig({
'pages/appointment/index',
'pages/appointment/create/index',
'pages/appointment/detail/index',
'pages/article/index',
'pages/legal/user-agreement',
'pages/legal/privacy-policy',
],
subPackages: [
{
root: 'pages/health',
pages: ['trend/index', 'input/index', 'daily-monitoring/index'],
root: 'pages/pkg-health',
pages: ['trend/index', 'input/index', 'daily-monitoring/index', 'alerts/index'],
},
{
root: 'pages/doctor',
@@ -26,26 +26,50 @@ export default defineAppConfig({
'consultation/index', 'consultation/detail/index',
'followup/index', 'followup/detail/index',
'report/index', 'report/detail/index',
'alerts/index', 'alerts/detail/index',
'action-inbox/index',
'dialysis/index', 'dialysis/detail/index', 'dialysis/create/index',
'prescription/index', 'prescription/detail/index', 'prescription/create/index',
],
},
{
root: 'pages/mall',
root: 'pages/pkg-mall',
pages: ['exchange/index', 'orders/index', 'detail/index'],
},
{
root: 'pages/profile',
root: 'pages/pkg-profile',
pages: [
'family/index', 'family-add/index', 'reports/index',
'followups/index', 'medication/index', 'settings/index',
'dialysis-records/index', 'dialysis-records/detail/index',
'dialysis-prescriptions/index', 'dialysis-prescriptions/detail/index',
'consents/index', 'health-records/index', 'diagnoses/index',
'elder-mode/index',
],
},
{
root: 'pages',
pages: [
'article/detail/index', 'ai-report/list/index',
'ai-report/detail/index', 'report/detail/index',
'followup/detail/index', 'events/index', 'device-sync/index',
],
root: 'pages/ai-report',
pages: ['list/index', 'detail/index'],
},
{
root: 'pages/article',
pages: ['index', 'detail/index'],
},
{
root: 'pages/report',
pages: ['detail/index'],
},
{
root: 'pages/followup',
pages: ['detail/index'],
},
{
root: 'pages/events',
pages: ['index'],
},
{
root: 'pages/device-sync',
pages: ['index'],
},
],
tabBar: {
@@ -55,9 +79,8 @@ export default defineAppConfig({
borderStyle: 'white',
list: [
{ pagePath: 'pages/index/index', text: '首页', iconPath: 'assets/tabbar/home.png', selectedIconPath: 'assets/tabbar/home-active.png' },
{ pagePath: 'pages/health/index', text: '上报', iconPath: 'assets/tabbar/health.png', selectedIconPath: 'assets/tabbar/health-active.png' },
{ pagePath: 'pages/consultation/index', text: '咨询', iconPath: 'assets/tabbar/appointment.png', selectedIconPath: 'assets/tabbar/appointment-active.png' },
{ pagePath: 'pages/mall/index', text: '商城', iconPath: 'assets/tabbar/article.png', selectedIconPath: 'assets/tabbar/article-active.png' },
{ pagePath: 'pages/health/index', text: '健康', iconPath: 'assets/tabbar/health.png', selectedIconPath: 'assets/tabbar/health-active.png' },
{ pagePath: 'pages/messages/index', text: '消息', iconPath: 'assets/tabbar/message.png', selectedIconPath: 'assets/tabbar/message-active.png' },
{ pagePath: 'pages/profile/index', text: '我的', iconPath: 'assets/tabbar/profile.png', selectedIconPath: 'assets/tabbar/profile-active.png' },
],
},
@@ -66,5 +89,6 @@ export default defineAppConfig({
navigationBarBackgroundColor: '#FFFFFF',
navigationBarTitleText: '健康管理',
navigationBarTextStyle: 'black',
enablePullDownRefresh: true,
},
});

View File

@@ -1,4 +1,6 @@
@import './styles/variables.scss';
@import './styles/tokens.scss';
@import './styles/elder-mode.scss';
page {
font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, 'PingFang SC',

View File

@@ -1,15 +1,21 @@
import { useEffect, PropsWithChildren } from 'react';
import Taro from '@tarojs/taro';
import Taro, { useDidShow } from '@tarojs/taro';
import ErrorBoundary from './components/ErrorBoundary';
import { flushEvents } from './services/analytics';
import { useAuthStore } from './stores/auth';
import { useUIStore } from './stores/ui';
import './app.scss';
function App({ children }: PropsWithChildren<Record<string, unknown>>) {
const restoreAuth = useAuthStore((s) => s.restore);
const restoreUI = useUIStore((s) => s.restore);
useDidShow(() => {
restoreAuth();
restoreUI();
});
useEffect(() => {
restoreAuth();
const timer = setInterval(() => {
flushEvents();
}, 30000);

Binary file not shown.

After

Width:  |  Height:  |  Size: 333 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 334 B

View File

@@ -0,0 +1,51 @@
@import '../../styles/variables.scss';
.device-card {
display: flex;
align-items: center;
padding: 24rpx;
background: $card;
border-radius: $r;
margin-bottom: 16rpx;
box-shadow: $shadow-sm;
.device-icon {
font-size: var(--tk-font-h2);
margin-right: 20rpx;
}
.device-info {
flex: 1;
.device-name {
font-size: var(--tk-font-cap);
font-weight: 600;
color: $tx;
display: block;
}
.device-status {
font-size: var(--tk-font-micro);
margin-top: 4rpx;
display: block;
&.connected { color: $pri; }
&.idle { color: $tx3; }
}
.last-sync {
font-size: var(--tk-font-micro);
color: $tx3;
margin-top: 4rpx;
display: block;
}
}
.sync-btn {
padding: 12rpx 28rpx;
background: $pri;
color: #fff;
border-radius: $r-pill;
font-size: var(--tk-font-micro);
}
}

View File

@@ -0,0 +1,39 @@
import { View, Text } from '@tarojs/components';
import Taro from '@tarojs/taro';
import './index.scss';
interface DeviceCardProps {
deviceName: string;
deviceType: string;
lastSyncAt?: string;
status: 'connected' | 'disconnected' | 'never';
}
const DEVICE_ICONS: Record<string, string> = {
blood_pressure: '\u{1FA7A}',
blood_glucose: '\u{1FA78}',
heart_rate: '\u{2764}',
blood_oxygen: '\u{1FAB1}',
};
export default function DeviceCard({ deviceName, deviceType, lastSyncAt, status }: DeviceCardProps) {
const icon = DEVICE_ICONS[deviceType] || '\u{1F4F1}';
const statusLabel = status === 'connected' ? '已连接' : status === 'disconnected' ? '未连接' : '未配对';
const statusClass = status === 'connected' ? 'connected' : 'idle';
const handleSync = () => {
Taro.navigateTo({ url: '/pages/device-sync/index' });
};
return (
<View className='device-card' onClick={handleSync}>
<View className='device-icon'>{icon}</View>
<View className='device-info'>
<Text className='device-name'>{deviceName}</Text>
<Text className={`device-status ${statusClass}`}>{statusLabel}</Text>
{lastSyncAt && <Text className='last-sync'>: {lastSyncAt}</Text>}
</View>
<View className='sync-btn'></View>
</View>
);
}

View File

@@ -8,20 +8,33 @@
padding: 120px 40px;
}
.empty-state-icon {
font-size: 80px;
.empty-state-icon-wrap {
width: 120px;
height: 120px;
border-radius: 50%;
background: $surface-alt;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 24px;
}
.empty-state-icon-char {
font-family: Georgia, 'Times New Roman', serif;
font-size: var(--tk-font-hero);
font-weight: 600;
color: $tx3;
}
.empty-state-text {
font-size: 30px;
font-size: var(--tk-font-num);
color: $tx2;
margin-bottom: 8px;
}
.empty-state-hint {
font-size: 24px;
color: $tx3;
font-size: var(--tk-font-h2);
color: var(--tk-text-secondary);
margin-bottom: 32px;
}
@@ -32,6 +45,6 @@
}
.empty-state-action-text {
font-size: 28px;
font-size: var(--tk-font-body-lg);
color: #fff;
}

View File

@@ -11,15 +11,18 @@ interface EmptyStateProps {
}
export default React.memo(function EmptyState({
icon = '📭',
icon,
text,
hint,
actionText,
onAction,
}: EmptyStateProps) {
const displayChar = icon || text.charAt(0);
return (
<View className='empty-state'>
<Text className='empty-state-icon'>{icon}</Text>
<View className='empty-state-icon-wrap'>
<Text className='empty-state-icon-char'>{displayChar}</Text>
</View>
<Text className='empty-state-text'>{text}</Text>
{hint && <Text className='empty-state-hint'>{hint}</Text>}
{actionText && onAction && (

View File

@@ -23,13 +23,25 @@ export default class ErrorBoundary extends Component<Props, State> {
console.error('[ErrorBoundary]', error, info.componentStack);
}
handleRetry = () => {
this.setState({ hasError: false });
};
render() {
if (this.state.hasError) {
return (
<View style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', minHeight: '60vh', padding: '40px' }}>
<Text style={{ fontSize: '48px', marginBottom: '20px' }}>😵</Text>
<Text style={{ fontSize: '32px', color: '#134E4A', marginBottom: '12px' }}></Text>
<Text style={{ fontSize: '24px', color: '#94A3B8', marginBottom: '24px' }}></Text>
<View style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', minHeight: '60vh', padding: '40px 24px' }}>
<View style={{ width: '64px', height: '64px', borderRadius: '32px', background: '#F0DDD4', display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: '20px' }}>
<Text style={{ fontFamily: 'Georgia, serif', fontSize: '28px', fontWeight: 600, color: '#8B3E1F' }}>!</Text>
</View>
<Text style={{ fontSize: '32px', color: '#2D2A26', marginBottom: '12px', fontWeight: 600 }}></Text>
<Text style={{ fontSize: '24px', color: '#78716C', marginBottom: '32px' }}></Text>
<View
onClick={this.handleRetry}
style={{ background: '#C4623A', borderRadius: '12px', padding: '14px 48px' }}
>
<Text style={{ color: '#FFFFFF', fontSize: '28px' }}></Text>
</View>
</View>
);
}

View File

@@ -9,12 +9,12 @@
}
.error-state-icon {
font-size: 80px;
font-size: 80px; /* hero icon — kept as-is */
margin-bottom: 24px;
}
.error-state-text {
font-size: 28px;
font-size: var(--tk-font-body-lg);
color: $tx2;
margin-bottom: 32px;
text-align: center;
@@ -27,6 +27,6 @@
}
.error-state-retry-text {
font-size: 28px;
font-size: var(--tk-font-body-lg);
color: #fff;
}

View File

@@ -0,0 +1,64 @@
@import '../../styles/variables.scss';
@import '../../styles/mixins.scss';
.guard-page {
min-height: 100vh;
background: $bg;
display: flex;
align-items: center;
justify-content: center;
padding: 40px 24px;
}
.guard-card {
text-align: center;
padding: 40px 20px;
}
.guard-icon-wrap {
width: 80px;
height: 80px;
border-radius: 40px;
background: $surface-alt;
@include flex-center;
margin: 0 auto 20px;
}
.guard-icon {
font-size: var(--tk-font-num);
color: $tx3;
}
.guard-title {
font-size: var(--tk-font-body-sm);
font-weight: 600;
color: $tx;
display: block;
margin-bottom: 8px;
}
.guard-desc {
font-size: var(--tk-font-cap);
color: var(--tk-text-secondary);
display: block;
margin-bottom: 24px;
}
.guard-btn {
display: inline-block;
height: 48px;
padding: 0 32px;
background: $pri;
border-radius: $r-pill;
@include flex-center;
&:active {
opacity: 0.85;
}
}
.guard-btn-text {
font-size: var(--tk-font-body-sm);
font-weight: 600;
color: #fff;
}

View File

@@ -0,0 +1,28 @@
import { View, Text } from '@tarojs/components';
import { navigateToLogin } from '../../utils/navigate';
import './index.scss';
interface GuestGuardProps {
title: string;
desc?: string;
}
export default function GuestGuard({ title, desc }: GuestGuardProps) {
return (
<View className='guard-page'>
<View className='guard-card'>
<View className='guard-icon-wrap'>
<Text className='guard-icon'></Text>
</View>
<Text className='guard-title'>{title}</Text>
{desc && <Text className='guard-desc'>{desc}</Text>}
<View
className='guard-btn'
onClick={navigateToLogin}
>
<Text className='guard-btn-text'></Text>
</View>
</View>
</View>
);
}

View File

@@ -25,6 +25,6 @@
}
.loading-state-text {
font-size: 26px;
color: $tx3;
font-size: var(--tk-font-h1);
color: var(--tk-text-secondary);
}

View File

@@ -0,0 +1,29 @@
@import '../styles/variables.scss';
.progress-ring {
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.progress-ring-inner {
background: $card;
border-radius: 50%;
display: flex;
align-items: baseline;
justify-content: center;
}
.progress-ring-percent {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: var(--tk-font-body);
font-weight: bold;
line-height: 1;
}
.progress-ring-unit {
font-size: var(--tk-font-micro);
font-weight: 600;
line-height: 1;
}

View File

@@ -0,0 +1,40 @@
import { View, Text } from '@tarojs/components';
import './ProgressRing.scss';
interface ProgressRingProps {
percent: number;
size?: number;
strokeWidth?: number;
color?: string;
trackColor?: string;
}
export default function ProgressRing({
percent,
size = 72,
strokeWidth = 7,
color = '#C4623A',
trackColor = '#E8E2DC',
}: ProgressRingProps) {
const clamped = Math.max(0, Math.min(100, percent));
const innerSize = size - strokeWidth * 2;
return (
<View
className='progress-ring'
style={`width:${size}px;height:${size}px;background:conic-gradient(${color} ${clamped}%, ${trackColor} ${clamped}%);border-radius:50%;padding:${strokeWidth}px;`}
>
<View
className='progress-ring-inner'
style={`width:${innerSize}px;height:${innerSize}px;`}
>
<Text className='progress-ring-percent' style={`color:${color};`}>
{clamped}
</Text>
<Text className='progress-ring-unit' style={`color:${color};`}>
%
</Text>
</View>
</View>
);
}

View File

@@ -39,7 +39,7 @@
justify-content: center;
background: $bd-l;
color: $tx3;
font-size: 24px;
font-size: var(--tk-font-h2);
transition: all 0.3s ease;
z-index: 1;
@@ -55,8 +55,8 @@
}
.step-label {
font-size: 22px;
color: $tx3;
font-size: var(--tk-font-body);
color: var(--tk-text-secondary);
margin-top: 8px;
text-align: center;

View File

@@ -13,8 +13,8 @@
}
.trend-chart-empty-text {
font-size: 28px;
color: $tx3;
font-size: var(--tk-font-body-lg);
color: var(--tk-text-secondary);
}
.trend-chart-skeleton {

View File

@@ -1,7 +1,6 @@
import React, { useEffect, useRef, useCallback } from 'react';
import { View, Text } from '@tarojs/components';
import EcCanvas from '../EcCanvas';
import type { EcCanvasRef } from '../EcCanvas';
import { Canvas, View, Text } from '@tarojs/components';
import Taro from '@tarojs/taro';
import './index.scss';
interface TrendChartProps {
@@ -12,6 +11,24 @@ interface TrendChartProps {
height?: number;
}
const DPR = Taro.getSystemInfoSync().pixelRatio || 2;
function drawLine(
ctx: CanvasRenderingContext2D,
points: { x: number; y: number }[],
) {
if (points.length < 2) return;
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
for (let i = 1; i < points.length; i++) {
const prev = points[i - 1];
const curr = points[i];
const cpx = (prev.x + curr.x) / 2;
ctx.bezierCurveTo(cpx, prev.y, cpx, curr.y, curr.x, curr.y);
}
ctx.stroke();
}
export default React.memo(function TrendChart({
data,
referenceMin,
@@ -19,97 +36,132 @@ export default React.memo(function TrendChart({
unit = '',
height = 500,
}: TrendChartProps) {
const chartRef = useRef<EcCanvasRef>(null);
const canvasRef = useRef<any>(null);
const getOption = useCallback(() => {
if (!data || data.length === 0) return null;
const draw = useCallback(() => {
const node = canvasRef.current;
if (!node || !data || data.length === 0) return;
const series: any[] = [];
const markArea: any = {};
const w = node.width / DPR;
const h = node.height / DPR;
const ctx = node.getContext('2d');
if (!ctx) return;
ctx.clearRect(0, 0, node.width, node.height);
ctx.save();
ctx.scale(DPR, DPR);
const pad = { left: 45, right: 15, top: 20, bottom: 30 };
const cw = w - pad.left - pad.right;
const ch = h - pad.top - pad.bottom;
const values = data.map((d) => d.value);
let yMin = Math.min(...values);
let yMax = Math.max(...values);
if (referenceMin != null) yMin = Math.min(yMin, referenceMin);
if (referenceMax != null) yMax = Math.max(yMax, referenceMax);
const yRange = yMax - yMin || 1;
const yPad = yRange * 0.1;
yMin -= yPad;
yMax += yPad;
const yTotal = yMax - yMin;
const toX = (i: number) => pad.left + (i / Math.max(data.length - 1, 1)) * cw;
const toY = (v: number) => pad.top + ch - ((v - yMin) / yTotal) * ch;
// Reference band
if (referenceMin != null && referenceMax != null) {
markArea.data = [
[
{
yAxis: referenceMin,
itemStyle: { color: 'rgba(5,150,105,0.08)' },
},
{ yAxis: referenceMax },
],
];
const ry1 = toY(referenceMax);
const ry2 = toY(referenceMin);
ctx.fillStyle = 'rgba(5,150,105,0.08)';
ctx.fillRect(pad.left, ry1, cw, ry2 - ry1);
}
series.push({
type: 'line',
data: data.map((d) => d.value),
smooth: true,
symbol: 'circle',
symbolSize: 6,
lineStyle: { color: '#0891B2', width: 2 },
itemStyle: { color: '#0891B2' },
areaStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(8,145,178,0.15)' },
{ offset: 1, color: 'rgba(8,145,178,0.01)' },
],
},
},
markArea: markArea.data
? { silent: true, data: markArea.data }
: undefined,
markPoint:
referenceMin != null && referenceMax != null
? {
data: data
.filter((d) => d.value < referenceMin || d.value > referenceMax)
.map((d) => ({
coord: [data.indexOf(d), d.value],
itemStyle: { color: '#DC2626' },
symbolSize: 12,
})),
}
: undefined,
});
// Grid lines
ctx.strokeStyle = '#F3F4F6';
ctx.lineWidth = 1;
const gridLines = 4;
for (let i = 0; i <= gridLines; i++) {
const gy = pad.top + (ch / gridLines) * i;
ctx.beginPath();
ctx.moveTo(pad.left, gy);
ctx.lineTo(pad.left + cw, gy);
ctx.stroke();
}
return {
grid: { left: 45, right: 15, top: 20, bottom: 30 },
xAxis: {
type: 'category',
data: data.map((d) => d.date.slice(5)),
axisLabel: { fontSize: 10, color: '#94A3B8' },
axisLine: { lineStyle: { color: '#E5E7EB' } },
},
yAxis: {
type: 'value',
axisLabel: { fontSize: 10, color: '#94A3B8' },
splitLine: { lineStyle: { color: '#F3F4F6' } },
},
tooltip: {
trigger: 'axis',
formatter: (params: any) => {
const p = params[0];
const idx = p.dataIndex;
return `${data[idx]?.date || ''}\n${p.value}${unit ? ' ' + unit : ''}`;
},
},
series,
};
}, [data, referenceMin, referenceMax, unit]);
// Y-axis labels
ctx.fillStyle = '#94A3B8';
ctx.font = '10px sans-serif';
ctx.textAlign = 'right';
for (let i = 0; i <= gridLines; i++) {
const val = yMax - (yTotal / gridLines) * i;
const gy = pad.top + (ch / gridLines) * i;
ctx.fillText(val.toFixed(1), pad.left - 6, gy + 3);
}
// X-axis labels
ctx.textAlign = 'center';
const step = Math.max(1, Math.floor(data.length / 5));
for (let i = 0; i < data.length; i += step) {
const lx = toX(i);
ctx.fillText(data[i].date.slice(5), lx, h - 8);
}
// Area fill
const chartPoints = data.map((d, i) => ({ x: toX(i), y: toY(d.value) }));
ctx.beginPath();
ctx.moveTo(chartPoints[0].x, toY(yMin));
ctx.lineTo(chartPoints[0].x, chartPoints[0].y);
for (let i = 1; i < chartPoints.length; i++) {
const prev = chartPoints[i - 1];
const curr = chartPoints[i];
const cpx = (prev.x + curr.x) / 2;
ctx.bezierCurveTo(cpx, prev.y, cpx, curr.y, curr.x, curr.y);
}
ctx.lineTo(chartPoints[chartPoints.length - 1].x, toY(yMin));
ctx.closePath();
const grad = ctx.createLinearGradient(0, pad.top, 0, pad.top + ch);
grad.addColorStop(0, 'rgba(8,145,178,0.15)');
grad.addColorStop(1, 'rgba(8,145,178,0.01)');
ctx.fillStyle = grad;
ctx.fill();
// Line
ctx.strokeStyle = '#0891B2';
ctx.lineWidth = 2;
drawLine(ctx, chartPoints);
// Data points
for (let i = 0; i < data.length; i++) {
const d = data[i];
const isAbnormal =
(referenceMin != null && d.value < referenceMin) ||
(referenceMax != null && d.value > referenceMax);
ctx.beginPath();
ctx.arc(chartPoints[i].x, chartPoints[i].y, isAbnormal ? 5 : 3, 0, Math.PI * 2);
ctx.fillStyle = isAbnormal ? '#DC2626' : '#0891B2';
ctx.fill();
}
ctx.restore();
}, [data, referenceMin, referenceMax]);
useEffect(() => {
if (chartRef.current && data && data.length > 0) {
const option = getOption();
if (option) {
chartRef.current.setOption(option);
}
}
}, [data, getOption]);
const query = Taro.createSelectorQuery();
query
.select('#trend-chart-canvas')
.node()
.exec((res) => {
const node = res[0]?.node;
if (!node) return;
canvasRef.current = node;
const sysInfo = Taro.getSystemInfoSync();
const canvasW = (sysInfo.windowWidth * 750) / sysInfo.windowWidth;
node.width = sysInfo.windowWidth * DPR;
node.height = ((height / 750) * sysInfo.windowWidth) * DPR;
draw();
});
}, [draw, height]);
if (!data || data.length === 0) {
return (
@@ -121,7 +173,11 @@ export default React.memo(function TrendChart({
return (
<View className='trend-chart' style={{ height: `${height}rpx` }}>
<EcCanvas canvasId='trend-chart-canvas' ref={chartRef} height={height} />
<Canvas
type='2d'
id='trend-chart-canvas'
style={{ width: '100%', height: '100%' }}
/>
</View>
);
});

View File

@@ -14,13 +14,13 @@
}
.week-arrow {
font-size: 28px;
font-size: var(--tk-font-body-lg);
color: $pri;
padding: 0 16px;
}
.week-label {
font-size: 24px;
font-size: var(--tk-font-h2);
color: $tx;
font-weight: bold;
}
@@ -39,13 +39,13 @@
}
.cell-weekday {
font-size: 20px;
color: $tx3;
font-size: var(--tk-font-body);
color: var(--tk-text-secondary);
display: block;
}
.cell-date {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx;
display: block;
margin-top: 4px;

View File

@@ -0,0 +1,6 @@
import { useUIStore } from '../stores/ui';
export function useElderClass(): string {
const mode = useUIStore((s) => s.mode);
return mode === 'elder' ? 'elder-mode' : '';
}

View File

@@ -1,23 +1,5 @@
@import '../../../styles/variables.scss';
@mixin section-title {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 30px;
font-weight: bold;
color: $tx;
margin-bottom: 20px;
display: block;
}
@mixin tag($bg, $color) {
display: inline-block;
padding: 4px 12px;
border-radius: 8px;
font-size: 20px;
font-weight: 500;
background: $bg;
color: $color;
}
@import '../../../styles/mixins.scss';
.detail-page {
min-height: 100vh;
@@ -45,7 +27,7 @@
}
.meta-item {
font-size: 22px;
font-size: var(--tk-font-body);
color: $tx3;
}
@@ -63,7 +45,7 @@
}
p {
font-size: 28px;
font-size: var(--tk-font-body-lg);
color: $tx;
line-height: 1.8;
margin-bottom: 16px;
@@ -75,7 +57,7 @@
}
li {
font-size: 28px;
font-size: var(--tk-font-body-lg);
color: $tx;
line-height: 1.8;
margin-bottom: 8px;
@@ -87,7 +69,7 @@
}
.report-content {
font-size: 28px;
font-size: var(--tk-font-body-lg);
line-height: 1.8;
color: $tx;
}
@@ -96,6 +78,35 @@
display: block;
text-align: center;
padding: 120px 0;
color: $tx3;
font-size: 28px;
color: var(--tk-text-secondary);
font-size: var(--tk-font-body-lg);
}
.auto-badge {
margin-top: 16px;
display: inline-block;
}
.auto-badge-text {
display: inline-block;
padding: 4px 16px;
border-radius: 8px;
font-size: var(--tk-font-body);
font-weight: 500;
background: #f0e6ff;
color: #7c3aed;
}
.trend-tip-card {
background: #fffbeb;
border: 1px solid #fde68a;
border-radius: $r;
padding: 20px 24px;
margin-bottom: 20px;
}
.trend-tip-text {
font-size: var(--tk-font-body);
color: #92400e;
line-height: 1.6;
}

View File

@@ -3,6 +3,7 @@ import { View, Text, RichText } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import { getAiAnalysisDetail, type AiAnalysisItem } from '@/services/ai-analysis';
import Loading from '@/components/Loading';
import { useElderClass } from '../../../hooks/useElderClass';
import './index.scss';
const TYPE_LABELS: Record<string, string> = {
@@ -12,8 +13,26 @@ const TYPE_LABELS: Record<string, string> = {
report_summary_generation: '报告摘要',
};
/** 移除危险的 HTML 标签和事件属性,防止 XSS */
function sanitizeHtml(html: string): string {
return html
// 移除 <script> 标签及其内容
.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
// 移除 <iframe>, <object>, <embed>, <form>, <input>, <textarea>, <style> 标签
.replace(/<\/?(?:iframe|object|embed|form|input|textarea|style)\b[^>]*>/gi, '')
// 移除 <link> 和 <meta> 标签
.replace(/<\/?(?:link|meta)\b[^>]*>/gi, '')
// 移除所有 on* 事件属性 (onclick, onerror, onload 等)
.replace(/\s+on\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, '')
// 移除 javascript: 和 data: 协议的 href/src 属性
.replace(/(href|src)\s*=\s*(?:"javascript:[^"]*"|'javascript:[^']*')/gi, '')
.replace(/(href|src)\s*=\s*(?:"data:[^"]*"|'data:[^']*')/gi, '');
}
function markdownToHtml(md: string): string {
return md
// 先转义 markdown 中可能存在的原始 HTML 标签
const escaped = sanitizeHtml(md);
return escaped
.replace(/^### (.+)$/gm, '<h3>$1</h3>')
.replace(/^## (.+)$/gm, '<h2>$1</h2>')
.replace(/^# (.+)$/gm, '<h1>$1</h1>')
@@ -26,6 +45,7 @@ function markdownToHtml(md: string): string {
}
export default function AiReportDetail() {
const modeClass = useElderClass();
const router = useRouter();
const id = router.params.id || '';
@@ -45,7 +65,7 @@ export default function AiReportDetail() {
if (!analysis) {
return (
<View className='detail-page'>
<View className={`detail-page ${modeClass}`}>
<Text className='empty-text'></Text>
</View>
);
@@ -55,16 +75,32 @@ export default function AiReportDetail() {
? markdownToHtml(analysis.result_content)
: '<p>暂无分析结果</p>';
const isTrendAnalysis = analysis.analysis_type === 'trend';
const isAutoAnalysis = (analysis.result_metadata as Record<string, unknown>)?.auto_analysis === true;
return (
<View className='detail-page'>
<View className={`detail-page ${modeClass}`}>
<View className='detail-card'>
<Text className='detail-type'>{TYPE_LABELS[analysis.analysis_type] || analysis.analysis_type}</Text>
<View className='detail-meta'>
<Text className='meta-item'>: {analysis.model_used}</Text>
<Text className='meta-item'>{new Date(analysis.created_at).toLocaleString('zh-CN')}</Text>
</View>
{isAutoAnalysis && (
<View className='auto-badge'>
<Text className='auto-badge-text'></Text>
</View>
)}
</View>
{isTrendAnalysis && (
<View className='trend-tip-card'>
<Text className='trend-tip-text'>
线 2 R² 1
</Text>
</View>
)}
<View className='content-card'>
<RichText className='report-content' nodes={htmlContent} />
</View>

View File

@@ -1,28 +1,5 @@
@import '../../../styles/variables.scss';
@mixin serif-number {
font-family: 'Georgia', 'Times New Roman', serif;
font-variant-numeric: tabular-nums;
}
@mixin section-title {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 30px;
font-weight: bold;
color: $tx;
margin-bottom: 20px;
display: block;
}
@mixin tag($bg, $color) {
display: inline-block;
padding: 4px 12px;
border-radius: 8px;
font-size: 20px;
font-weight: 500;
background: $bg;
color: $color;
}
@import '../../../styles/mixins.scss';
.ai-report-page {
min-height: 100vh;
@@ -55,7 +32,7 @@
}
.card-type {
font-size: 28px;
font-size: var(--tk-font-body-lg);
font-weight: 500;
color: $tx;
}
@@ -87,19 +64,19 @@
}
.card-time {
font-size: 22px;
font-size: var(--tk-font-body);
color: $tx3;
}
.card-model {
font-size: 22px;
font-size: var(--tk-font-body);
color: $tx3;
}
.no-more {
text-align: center;
font-size: 24px;
color: $tx3;
font-size: var(--tk-font-h2);
color: var(--tk-text-secondary);
padding: 24px 0;
display: block;
}

View File

@@ -4,6 +4,7 @@ import Taro from '@tarojs/taro';
import { listAiAnalysis, type AiAnalysisItem } from '@/services/ai-analysis';
import Loading from '@/components/Loading';
import EmptyState from '@/components/EmptyState';
import { useElderClass } from '../../../hooks/useElderClass';
import './index.scss';
const TYPE_LABELS: Record<string, string> = {
@@ -21,6 +22,7 @@ const STATUS_MAP: Record<string, { text: string; className: string }> = {
};
export default function AiReportList() {
const modeClass = useElderClass();
const [list, setList] = useState<AiAnalysisItem[]>([]);
const [loading, setLoading] = useState(true);
const [page, setPage] = useState(1);
@@ -60,14 +62,14 @@ export default function AiReportList() {
if (list.length === 0) {
return (
<View className='ai-report-page'>
<View className={`ai-report-page ${modeClass}`}>
<EmptyState text='暂无 AI 分析报告' />
</View>
);
}
return (
<View className='ai-report-page'>
<View className={`ai-report-page ${modeClass}`}>
<View className='page-title'>AI </View>
<ScrollView scrollY className='report-scroll' onScrollToLower={loadMore}>
{list.map((item) => {

View File

@@ -55,7 +55,7 @@
.dept-initial-text {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 30px;
font-size: var(--tk-font-num);
font-weight: bold;
color: $pri;
@@ -65,7 +65,7 @@
}
.dept-label {
font-size: 24px;
font-size: var(--tk-font-h2);
color: $tx;
font-weight: 500;
}
@@ -77,7 +77,7 @@
.slot-section-title {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 28px;
font-size: var(--tk-font-body-lg);
font-weight: bold;
color: $tx;
margin-bottom: 16px;
@@ -114,14 +114,14 @@
.slot-time {
@include serif-number;
font-size: 28px;
font-size: var(--tk-font-body-lg);
font-weight: bold;
color: $tx;
display: block;
}
.slot-count {
font-size: 22px;
font-size: var(--tk-font-body);
color: $tx3;
display: block;
margin-top: 6px;
@@ -156,7 +156,7 @@
.confirm-icon-serif {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 24px;
font-size: var(--tk-font-h2);
font-weight: bold;
color: $pri;
}
@@ -169,12 +169,12 @@
}
.confirm-label {
font-size: 22px;
font-size: var(--tk-font-body);
color: $tx3;
}
.confirm-value {
font-size: 28px;
font-size: var(--tk-font-body-lg);
font-weight: bold;
color: $tx;
}
@@ -185,7 +185,7 @@
}
.confirm-dept-text {
font-size: 20px;
font-size: var(--tk-font-body);
font-weight: 500;
color: $pri;
}
@@ -225,7 +225,7 @@
.doctor-avatar-text {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 32px;
font-size: var(--tk-font-num);
color: $pri;
font-weight: bold;
}
@@ -238,18 +238,18 @@
}
.doctor-name {
font-size: 30px;
font-size: var(--tk-font-num);
font-weight: bold;
color: $tx;
}
.doctor-title {
font-size: 24px;
font-size: var(--tk-font-h2);
color: $tx2;
}
.doctor-specialty {
font-size: 22px;
font-size: var(--tk-font-body);
color: $pri;
}
@@ -263,7 +263,7 @@
}
.doctor-check-text {
font-size: 24px;
font-size: var(--tk-font-h2);
color: white;
font-weight: bold;
}
@@ -274,7 +274,7 @@
}
.form-label {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx2;
margin-bottom: 12px;
display: block;
@@ -284,7 +284,7 @@
background: $card;
border-radius: $r-sm;
padding: 24px 28px;
font-size: 28px;
font-size: var(--tk-font-body-lg);
color: $tx;
width: 100%;
box-sizing: border-box;
@@ -298,8 +298,8 @@
}
.empty-text {
font-size: 28px;
color: $tx3;
font-size: var(--tk-font-body-lg);
color: var(--tk-text-secondary);
}
/* 底部操作栏 */
@@ -339,7 +339,7 @@
}
.btn-text {
font-size: 30px;
font-size: var(--tk-font-num);
font-weight: bold;
color: $tx2;
}

View File

@@ -7,6 +7,7 @@ import { TEMPLATE_IDS } from '@/services/wechat-templates';
import { trackEvent } from '@/services/analytics';
import StepIndicator from '../../../components/StepIndicator';
import WeekCalendar from '../../../components/WeekCalendar';
import { useElderClass } from '../../../hooks/useElderClass';
import './index.scss';
const DEPARTMENTS = [
@@ -44,6 +45,7 @@ export default function AppointmentCreate() {
const [loading, setLoading] = useState(false);
const [schedules, setSchedules] = useState<any[]>([]);
const [timeSlots, setTimeSlots] = useState<TimeSlot[]>([]);
const modeClass = useElderClass();
const currentPatient = useAuthStore((s) => s.currentPatient);
@@ -148,7 +150,7 @@ export default function AppointmentCreate() {
};
return (
<View className='create-page'>
<View className={`create-page ${modeClass}`}>
<StepIndicator
steps={[{ label: '选科室' }, { label: '选医生' }, { label: '选时段' }]}
current={currentStep}

View File

@@ -23,14 +23,14 @@
}
.back-text {
font-size: 28px;
font-size: var(--tk-font-body-lg);
color: $pri;
font-weight: 500;
}
.header-title {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 34px;
font-size: var(--tk-font-num-lg);
font-weight: bold;
color: $tx;
}
@@ -80,19 +80,19 @@
}
.status-tag-text {
font-size: 28px;
font-size: var(--tk-font-body-lg);
font-weight: bold;
}
.status-doctor {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 36px;
font-size: var(--tk-font-num-lg);
font-weight: bold;
color: $tx;
}
.status-dept {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx2;
}
@@ -130,7 +130,7 @@
.info-icon-serif {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 20px;
font-size: var(--tk-font-body);
color: $pri;
background: $pri-l;
width: 36px;
@@ -143,12 +143,12 @@
}
.info-label {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx2;
}
.info-value {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx;
font-weight: 500;
}
@@ -163,8 +163,8 @@
.info-id {
@include serif-number;
font-size: 22px;
color: $tx3;
font-size: var(--tk-font-body);
color: var(--tk-text-secondary);
word-break: break-all;
max-width: 400px;
text-align: right;
@@ -180,7 +180,7 @@
.tips-title {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 28px;
font-size: var(--tk-font-body-lg);
font-weight: bold;
color: $wrn;
margin-bottom: 12px;
@@ -188,7 +188,7 @@
}
.tips-text {
font-size: 24px;
font-size: var(--tk-font-h2);
color: $tx2;
line-height: 1.6;
}
@@ -219,7 +219,7 @@
}
.cancel-text {
font-size: 30px;
font-size: var(--tk-font-num);
font-weight: bold;
color: $dan;
}

View File

@@ -5,6 +5,7 @@ import { getAppointment, cancelAppointment } from '../../../services/appointment
import type { Appointment } from '../../../services/appointment';
import Loading from '../../../components/Loading';
import ErrorState from '../../../components/ErrorState';
import { useElderClass } from '../../../hooks/useElderClass';
import './index.scss';
const STATUS_MAP: Record<string, { label: string; className: string }> = {
@@ -22,6 +23,7 @@ export default function AppointmentDetail() {
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
const [cancelling, setCancelling] = useState(false);
const modeClass = useElderClass();
useEffect(() => {
if (!id) return;
@@ -65,7 +67,7 @@ export default function AppointmentDetail() {
if (loading) {
return (
<View className='detail-page'>
<View className={`detail-page ${modeClass}`}>
<View className='detail-header'>
<View className='back-btn' onClick={goBack}><Text className='back-text'></Text></View>
<Text className='header-title'></Text>
@@ -78,7 +80,7 @@ export default function AppointmentDetail() {
if (error || !appointment) {
return (
<View className='detail-page'>
<View className={`detail-page ${modeClass}`}>
<View className='detail-header'>
<View className='back-btn' onClick={goBack}><Text className='back-text'></Text></View>
<Text className='header-title'></Text>
@@ -90,7 +92,7 @@ export default function AppointmentDetail() {
}
return (
<View className='detail-page'>
<View className={`detail-page ${modeClass}`}>
<View className='detail-header'>
<View className='back-btn' onClick={goBack}><Text className='back-text'></Text></View>
<Text className='header-title'></Text>

View File

@@ -17,13 +17,13 @@
.page-title {
@include section-title;
margin-bottom: 4px;
font-size: 36px;
font-size: var(--tk-font-num-lg);
}
.page-subtitle {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 22px;
color: $tx3;
font-size: var(--tk-font-body);
color: var(--tk-text-secondary);
letter-spacing: 1px;
}
@@ -67,7 +67,7 @@
.dept-initial-text {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 32px;
font-size: var(--tk-font-num);
font-weight: bold;
color: $pri;
}
@@ -80,7 +80,7 @@
}
.doctor-name {
font-size: 30px;
font-size: var(--tk-font-num);
font-weight: bold;
color: $tx;
overflow: hidden;
@@ -93,7 +93,7 @@
}
.dept-tag-text {
font-size: 20px;
font-size: var(--tk-font-body);
font-weight: 500;
color: $pri;
}
@@ -124,7 +124,7 @@
}
.status-tag-text {
font-size: 20px;
font-size: var(--tk-font-body);
font-weight: 500;
}
@@ -157,12 +157,12 @@
.info-icon-serif {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 22px;
font-size: var(--tk-font-body);
color: $tx2;
}
.info-text {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx2;
}
@@ -186,7 +186,7 @@
}
.fab-text {
font-size: 30px;
font-size: var(--tk-font-num);
color: white;
font-weight: bold;
letter-spacing: 2px;

View File

@@ -5,6 +5,7 @@ import { listAppointments } from '../../services/appointment';
import type { Appointment } from '../../services/appointment';
import EmptyState from '../../components/EmptyState';
import Loading from '../../components/Loading';
import { useElderClass } from '../../hooks/useElderClass';
import './index.scss';
const STATUS_MAP: Record<string, { label: string; className: string }> = {
@@ -30,6 +31,7 @@ export default function AppointmentList() {
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
const loadingRef = useRef(false);
const modeClass = useElderClass();
const fetchData = useCallback(async (pageNum: number, isRefresh = false) => {
if (loadingRef.current) return;
@@ -86,11 +88,10 @@ export default function AppointmentList() {
};
return (
<View className='appointment-page'>
<View className={`appointment-page ${modeClass}`}>
{/* 页面标题 */}
<View className='page-header'>
<Text className='page-title'></Text>
<Text className='page-subtitle'>Appointment</Text>
</View>
{/* 预约列表 */}

View File

@@ -13,7 +13,7 @@
}
.article-title {
font-size: 38px;
font-size: var(--tk-font-hero);
font-weight: bold;
color: $tx;
display: block;
@@ -29,7 +29,7 @@
}
.article-category {
font-size: 22px;
font-size: var(--tk-font-body);
color: $pri;
background: $pri-l;
padding: 4px 12px;
@@ -37,13 +37,13 @@
}
.article-author {
font-size: 24px;
font-size: var(--tk-font-h2);
color: $tx2;
}
.article-date {
font-size: 24px;
color: $tx3;
font-size: var(--tk-font-h2);
color: var(--tk-text-secondary);
}
.article-summary {
@@ -53,7 +53,7 @@
}
.summary-text {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx2;
line-height: 1.6;
}
@@ -70,7 +70,7 @@
}
p {
font-size: 28px;
font-size: var(--tk-font-body-lg);
color: $tx;
line-height: 1.8;
margin-bottom: 16px;
@@ -93,6 +93,6 @@
.loading-text,
.empty-text {
font-size: 28px;
color: $tx3;
font-size: var(--tk-font-body-lg);
color: var(--tk-text-secondary);
}

View File

@@ -3,9 +3,11 @@ import { View, Text, RichText } from '@tarojs/components';
import Taro, { useRouter, useShareAppMessage } from '@tarojs/taro';
import { getArticleDetail, Article } from '../../../services/article';
import { trackEvent } from '@/services/analytics';
import { useElderClass } from '../../../hooks/useElderClass';
import './index.scss';
export default function ArticleDetail() {
const modeClass = useElderClass();
const router = useRouter();
const id = router.params.id || '';
@@ -31,7 +33,7 @@ export default function ArticleDetail() {
if (loading) {
return (
<View className='article-detail-page'>
<View className={`article-detail-page ${modeClass}`}>
<View className='loading-state'>
<Text className='loading-text'>...</Text>
</View>
@@ -41,7 +43,7 @@ export default function ArticleDetail() {
if (!article) {
return (
<View className='article-detail-page'>
<View className={`article-detail-page ${modeClass}`}>
<View className='empty-state'>
<Text className='empty-text'></Text>
</View>
@@ -50,7 +52,7 @@ export default function ArticleDetail() {
}
return (
<View className='article-detail-page'>
<View className={`article-detail-page ${modeClass}`}>
{/* 文章头部 */}
<View className='article-header'>
<Text className='article-title'>{article.title}</Text>

View File

@@ -16,7 +16,7 @@
display: inline-block;
padding: 12px 28px;
margin-right: 12px;
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx2;
background: $card;
border-radius: 32px;
@@ -52,7 +52,7 @@
}
.article-card-title {
font-size: 30px;
font-size: var(--tk-font-num);
font-weight: bold;
color: $tx;
line-height: 1.4;
@@ -66,7 +66,7 @@
}
.article-card-summary {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx2;
line-height: 1.4;
display: block;
@@ -83,7 +83,7 @@
}
.article-card-tag {
font-size: 22px;
font-size: var(--tk-font-body);
color: $pri;
background: $pri-l;
padding: 2px 12px;
@@ -91,7 +91,7 @@
}
.article-card-date {
font-size: 22px;
font-size: var(--tk-font-body);
color: $tx3;
}
@@ -116,8 +116,8 @@
}
.empty-text {
font-size: 28px;
color: $tx3;
font-size: var(--tk-font-body-lg);
color: var(--tk-text-secondary);
}
.loading-hint {
@@ -126,6 +126,6 @@
}
.loading-text {
font-size: 24px;
color: $tx3;
font-size: var(--tk-font-h2);
color: var(--tk-text-secondary);
}

View File

@@ -4,9 +4,11 @@ import Taro, { useDidShow, usePullDownRefresh, useReachBottom } from '@tarojs/ta
import { listArticles, listCategories, Article, ArticleCategory } from '../../services/article';
import EmptyState from '../../components/EmptyState';
import Loading from '../../components/Loading';
import { useElderClass } from '../../hooks/useElderClass';
import './index.scss';
export default function ArticleList() {
const modeClass = useElderClass();
const [articles, setArticles] = useState<Article[]>([]);
const [page, setPage] = useState(1);
const [total, setTotal] = useState(0);
@@ -72,7 +74,7 @@ export default function ArticleList() {
};
return (
<View className='article-page'>
<View className={`article-page ${modeClass}`}>
{/* 分类筛选 */}
{categories.length > 0 && (
<ScrollView scrollX className='article-categories'>

View File

@@ -8,61 +8,108 @@
background: $bg;
}
/* ─── 导航栏 ─── */
.chat-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 24px 32px;
padding: 12px 16px;
background: $card;
border-bottom: 1px solid $bd;
border-bottom: 1px solid $bd-l;
flex-shrink: 0;
position: relative;
}
&__title {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 30px;
font-weight: 600;
color: $tx;
.chat-header__back {
position: absolute;
left: 16px;
z-index: 1;
&:active {
opacity: 0.7;
}
}
&__status {
font-size: 24px;
.chat-header__back-text {
font-size: var(--tk-font-body-sm);
color: $pri;
}
.chat-header__center {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
}
.chat-header__title {
font-size: var(--tk-font-body-sm);
font-weight: 600;
color: $tx;
}
.chat-header__status {
font-size: var(--tk-font-micro);
color: $acc;
margin-top: 2px;
&--closed {
color: $tx3;
}
}
/* ─── 消息区 ─── */
.chat-messages {
flex: 1;
padding: 24px;
padding: 16px 16px 0;
overflow-y: auto;
}
.msg-row {
display: flex;
margin-bottom: 20px;
margin-bottom: 16px;
gap: 8px;
&--self {
justify-content: flex-end;
}
}
/* ─── 医生头像 ─── */
.msg-avatar {
width: 32px;
height: 32px;
border-radius: 16px;
background: $pri-l;
@include flex-center;
flex-shrink: 0;
}
.msg-avatar-char {
@include serif-number;
font-size: var(--tk-font-cap);
font-weight: 700;
color: $pri;
}
/* ─── 消息气泡 ─── */
.msg-bubble {
max-width: 70%;
padding: 20px 24px;
border-radius: $r-lg;
position: relative;
padding: 12px 16px;
box-shadow: $shadow-sm;
&--other {
background: $card;
border-top-left-radius: $r-sm;
border-radius: $r $r $r $r-xs;
}
&--self {
background: $pri;
border-top-right-radius: $r-sm;
border-radius: $r $r $r-xs $r;
}
}
.msg-text {
font-size: 28px;
font-size: var(--tk-font-cap);
color: $tx;
display: block;
line-height: 1.6;
@@ -76,88 +123,95 @@
.msg-date-divider {
display: flex;
justify-content: center;
padding: 16px 0 12px;
padding: 12px 0;
&__text {
font-size: 22px;
color: #94A3B8;
background: #F1F5F9;
padding: 4px 16px;
border-radius: 8px;
font-size: var(--tk-font-micro);
color: var(--tk-text-secondary);
background: $surface-alt;
padding: 2px 12px;
border-radius: $r-pill;
}
}
.msg-image {
width: 320px;
border-radius: 12px;
width: 200px;
border-radius: $r-sm;
margin-top: 4px;
}
.msg-time {
font-size: 20px;
color: $tx3;
font-size: var(--tk-font-micro);
color: var(--tk-text-secondary);
display: block;
margin-top: 8px;
text-align: right;
margin-top: 4px;
.msg-bubble--self & {
color: rgba(255, 255, 255, 0.7);
text-align: right;
}
}
.chat-empty {
text-align: center;
padding: 120px 32px;
padding: 80px 24px;
&__text {
font-size: 26px;
color: $tx3;
font-size: var(--tk-font-cap);
color: var(--tk-text-secondary);
}
}
/* ─── 输入栏 ─── */
.chat-input-bar {
display: flex;
align-items: center;
padding: 16px 24px;
gap: 10px;
padding: 10px 16px 38px;
background: $card;
border-top: 1px solid $bd;
padding-bottom: calc(16px + env(safe-area-inset-bottom));
border-top: 1px solid $bd-l;
flex-shrink: 0;
}
.chat-input {
flex: 1;
height: 40px;
background: $bg;
border-radius: $r;
padding: 16px 20px;
font-size: 28px;
margin-right: 16px;
border: 1.5px solid $bd;
border-radius: 20px;
padding: 0 14px;
font-size: var(--tk-font-cap);
color: $tx;
}
.chat-send-btn {
width: 40px;
height: 40px;
border-radius: 20px;
background: $pri;
border-radius: $r;
padding: 16px 28px;
@include flex-center;
flex-shrink: 0;
box-shadow: 0 2px 6px rgba(196, 98, 58, 0.3);
&--disabled {
opacity: 0.5;
}
}
&__text {
font-size: 28px;
color: #fff;
font-weight: 500;
}
.chat-send-btn__icon {
font-size: var(--tk-font-cap);
color: #fff;
font-weight: 600;
}
.chat-closed-bar {
padding: 24px;
padding: 16px;
text-align: center;
background: $card;
border-top: 1px solid $bd;
border-top: 1px solid $bd-l;
&__text {
font-size: 26px;
color: $tx3;
font-size: var(--tk-font-cap);
color: var(--tk-text-secondary);
}
}

View File

@@ -6,14 +6,14 @@ import {
listMessages,
sendMessage,
markSessionRead,
pollMessages,
type ConsultationSession,
type ConsultationMessage,
} from '@/services/consultation';
import Loading from '@/components/Loading';
import { useElderClass } from '@/hooks/useElderClass';
import './index.scss';
const POLL_INTERVAL = 8000;
export default function ConsultationDetail() {
const router = useRouter();
const sessionId = router.params.id || '';
@@ -23,43 +23,35 @@ export default function ConsultationDetail() {
const [sending, setSending] = useState(false);
const [loading, setLoading] = useState(true);
const scrollViewRef = useRef('');
const pollTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);
const pollingRef = useRef(false);
const modeClass = useElderClass();
useEffect(() => {
if (sessionId) {
loadData();
markRead();
startPolling();
startLongPolling();
}
return () => stopPolling();
return () => { pollingRef.current = false; };
}, [sessionId]);
const startPolling = () => {
stopPolling();
pollTimerRef.current = setInterval(pollNewMessages, POLL_INTERVAL);
useEffect(() => {
if (session?.status === 'closed') {
pollingRef.current = false;
}
}, [session?.status]);
const startLongPolling = () => {
pollingRef.current = true;
longPoll();
};
const stopPolling = () => {
if (pollTimerRef.current) {
clearInterval(pollTimerRef.current);
pollTimerRef.current = null;
}
};
const pollNewMessages = async () => {
if (!session || session.status === 'closed') {
stopPolling();
return;
}
const longPoll = async () => {
if (!pollingRef.current) return;
try {
const lastId = messages.length > 0 ? messages[messages.length - 1].id : undefined;
const m = await listMessages(sessionId, {
page: 1,
page_size: 50,
after_id: lastId,
});
const newMsgs = m.data || [];
if (newMsgs.length > 0) {
const newMsgs = await pollMessages(sessionId, lastId);
if (newMsgs && newMsgs.length > 0) {
setMessages((prev) => {
const existing = new Set(prev.map((msg) => msg.id));
const fresh = newMsgs.filter((msg) => !existing.has(msg.id));
@@ -67,7 +59,12 @@ export default function ConsultationDetail() {
});
scrollViewRef.current = `msg-${messages.length + newMsgs.length}`;
}
} catch { /* 轮询失败静默忽略 */ }
} catch {
// 超时或网络错误,静默重试
}
if (pollingRef.current) {
longPoll();
}
};
const loadData = async () => {
@@ -80,7 +77,7 @@ export default function ConsultationDetail() {
setSession(s);
setMessages(m.data || []);
scrollViewRef.current = `msg-${(m.data || []).length}`;
if (s.status === 'closed') stopPolling();
if (s.status === 'closed') pollingRef.current = false;
} catch {
Taro.showToast({ title: '加载失败', icon: 'none' });
} finally {
@@ -137,14 +134,24 @@ export default function ConsultationDetail() {
if (loading) return <Loading />;
const isOpen = session?.status !== 'closed';
const doctorInitial = (session?.subject || '医').charAt(0);
const statusLabel = session?.status === 'active' ? '进行中'
: session?.status === 'pending' ? '等待接诊'
: '已结束';
return (
<View className='chat-page'>
<View className={`chat-page ${modeClass}`}>
{/* 导航栏 — 对齐设计稿:返回 + 标题 + 副标题 */}
<View className='chat-header'>
<Text className='chat-header__title'>{session?.subject || '在线咨询'}</Text>
{!isOpen && (
<Text className='chat-header__status'></Text>
)}
<View className='chat-header__back' onClick={() => Taro.navigateBack()}>
<Text className='chat-header__back-text'> </Text>
</View>
<View className='chat-header__center'>
<Text className='chat-header__title'>{session?.subject || '在线咨询'}</Text>
<Text className={`chat-header__status ${isOpen ? '' : 'chat-header__status--closed'}`}>
{statusLabel}
</Text>
</View>
</View>
<ScrollView
@@ -164,6 +171,11 @@ export default function ConsultationDetail() {
</View>
)}
<View id={`msg-${idx + 1}`} className={`msg-row ${isSelf ? 'msg-row--self' : ''}`}>
{!isSelf && (
<View className='msg-avatar'>
<Text className='msg-avatar-char'>{doctorInitial}</Text>
</View>
)}
<View className={`msg-bubble ${isSelf ? 'msg-bubble--self' : 'msg-bubble--other'}`}>
{isImageUrl(msg.content) ? (
<Image
@@ -203,7 +215,7 @@ export default function ConsultationDetail() {
className={`chat-send-btn ${(!inputText.trim() || sending) ? 'chat-send-btn--disabled' : ''}`}
onClick={handleSend}
>
<Text className='chat-send-btn__text'>{sending ? '...' : '发送'}</Text>
<Text className='chat-send-btn__icon'></Text>
</View>
</View>
) : (

View File

@@ -6,26 +6,36 @@
background: $bg;
}
/* ─── 页头 ─── */
.consultation-header {
background: linear-gradient(135deg, $pri 0%, $pri-d 100%);
padding: 48px 32px 36px;
color: #fff;
}
.consultation-title {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 40px;
font-weight: bold;
color: #fff;
display: block;
margin-bottom: 8px;
.consultation-body {
padding: 12px 24px 24px;
}
/* ─── 副标题 ─── */
.consultation-subtitle {
font-size: 24px;
color: rgba(255, 255, 255, 0.75);
font-size: var(--tk-font-cap);
color: var(--tk-text-secondary);
display: block;
margin-bottom: 20px;
}
/* ─── 发起咨询按钮 — 实心主色 ─── */
.consultation-create-btn {
height: 48px;
border-radius: $r;
background: $pri;
@include flex-center;
box-shadow: 0 2px 8px rgba(196, 98, 58, 0.25);
margin-bottom: 20px;
&:active {
opacity: 0.85;
}
}
.consultation-create-btn-text {
font-size: var(--tk-font-body-sm);
font-weight: 600;
color: #fff;
}
/* ─── 居中容器 ─── */
@@ -37,7 +47,7 @@
}
.consultation-error {
font-size: 26px;
font-size: var(--tk-font-cap);
color: $dan;
}
@@ -47,51 +57,52 @@
flex-direction: column;
align-items: center;
justify-content: center;
padding: 160px 40px;
padding: 120px 40px;
}
.empty-icon {
width: 120px;
height: 120px;
width: 80px;
height: 80px;
border-radius: 50%;
background: $pri-l;
@include flex-center;
margin-bottom: 32px;
margin-bottom: 20px;
}
.empty-char {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 52px;
font-weight: bold;
@include serif-number;
font-size: var(--tk-font-num);
font-weight: 700;
color: $pri;
line-height: 1;
}
.empty-title {
font-size: 32px;
font-size: var(--tk-font-body-sm);
font-weight: 600;
color: $tx;
margin-bottom: 12px;
margin-bottom: 8px;
}
.empty-hint {
font-size: 26px;
color: $tx3;
font-size: var(--tk-font-cap);
color: var(--tk-text-secondary);
text-align: center;
}
/* ─── 会话列表 ─── */
.session-list {
padding: 20px 24px;
display: flex;
flex-direction: column;
gap: 8px;
}
.session-card {
display: flex;
align-items: center;
gap: 12px;
background: $card;
border-radius: $r;
padding: 24px;
margin-bottom: 12px;
padding: 16px;
box-shadow: $shadow-sm;
&:active {
@@ -99,7 +110,27 @@
}
}
.session-main {
.session-card-closed {
opacity: 0.6;
}
.session-avatar {
width: 36px;
height: 36px;
border-radius: 18px;
background: $pri-l;
@include flex-center;
flex-shrink: 0;
}
.session-avatar-char {
@include serif-number;
font-size: var(--tk-font-body-sm);
font-weight: 700;
color: $pri;
}
.session-body {
flex: 1;
min-width: 0;
}
@@ -108,56 +139,73 @@
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
margin-bottom: 6px;
}
.session-subject {
font-size: 28px;
color: $tx;
font-size: var(--tk-font-cap);
font-weight: 600;
color: $tx;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1;
margin-right: 12px;
}
.session-tag {
&.tag-ok { @include tag($acc-l, $acc); }
&.tag-warn { @include tag($wrn-l, $wrn); }
&.tag-default { @include tag($bd-l, $tx2); }
}
.session-message {
font-size: 26px;
color: $tx2;
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
margin-bottom: 8px;
margin-right: 8px;
}
.session-time {
font-size: 22px;
color: $tx3;
display: block;
font-size: var(--tk-font-micro);
color: var(--tk-text-secondary);
flex-shrink: 0;
}
.session-tag {
font-size: var(--tk-font-micro);
padding: 2px 6px;
border-radius: 4px;
font-weight: 500;
display: inline-block;
&.tag-ok { background: $acc-l; color: $acc; }
&.tag-warn { background: $wrn-l; color: $wrn; }
&.tag-default { background: $surface-alt; color: $tx3; }
}
.session-meta {
display: flex;
align-items: center;
margin-bottom: 4px;
}
.session-message-row {
display: flex;
justify-content: space-between;
align-items: center;
}
.session-message {
font-size: var(--tk-font-cap);
color: $tx2;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1;
margin-right: 8px;
}
/* ─── 未读角标 ─── */
.session-badge {
background: $dan;
border-radius: $r-pill;
min-width: 36px;
height: 36px;
min-width: 18px;
height: 18px;
@include flex-center;
padding: 0 10px;
margin-left: 12px;
padding: 0 5px;
flex-shrink: 0;
}
.session-badge-text {
font-size: 22px;
font-size: var(--tk-font-micro);
color: #fff;
font-weight: 600;
}

View File

@@ -1,8 +1,9 @@
import { useState } from 'react';
import { useState, useRef } from 'react';
import { View, Text } from '@tarojs/components';
import Taro, { useDidShow, usePullDownRefresh } from '@tarojs/taro';
import Taro, { useDidShow, usePullDownRefresh, useReachBottom } from '@tarojs/taro';
import { listConsultations, ConsultationSession } from '@/services/consultation';
import Loading from '../../components/Loading';
import { useElderClass } from '../../hooks/useElderClass';
import './index.scss';
function getStatusTag(status: string) {
@@ -33,99 +34,137 @@ export default function Consultation() {
const [sessions, setSessions] = useState<ConsultationSession[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const modeClass = useElderClass();
const [page, setPage] = useState(1);
const [total, setTotal] = useState(0);
const loadingRef = useRef(false);
const loadSessions = async () => {
setLoading(true);
const loadSessions = async (pageNum: number, isRefresh = false) => {
if (loadingRef.current) return;
loadingRef.current = true;
if (isRefresh) setLoading(true);
setError('');
try {
const resp = await listConsultations({ page: 1, page_size: 20 });
setSessions(resp.data || []);
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : '加载失败';
setError(msg);
const resp = await listConsultations({ page: pageNum, page_size: 20 });
const list = resp.data || [];
if (isRefresh) {
setSessions(list);
} else {
setSessions((prev) => [...prev, ...list]);
}
setTotal(resp.total || 0);
setPage(pageNum);
} catch {
if (isRefresh) {
setSessions([]);
setTotal(0);
}
} finally {
setLoading(false);
loadingRef.current = false;
}
};
useDidShow(() => {
Taro.setNavigationBarTitle({ title: '在线咨询' });
loadSessions();
loadSessions(1, true);
});
usePullDownRefresh(() => {
loadSessions().finally(() => {
loadSessions(1, true).finally(() => {
Taro.stopPullDownRefresh();
});
});
useReachBottom(() => {
if (!loading && sessions.length < total) {
loadSessions(page + 1);
}
});
const handleTapSession = (session: ConsultationSession) => {
Taro.navigateTo({ url: `/pages/consultation/detail/index?id=${session.id}` });
};
return (
<View className='consultation-page'>
{/* 页头 */}
<View className='consultation-header'>
<Text className='consultation-title'>线</Text>
<View className={`consultation-page ${modeClass}`}>
<View className='consultation-body'>
{/* 副标题 */}
<Text className='consultation-subtitle'></Text>
</View>
{/* 内容区 */}
{loading ? (
<View className='consultation-center'>
<Loading text='加载中...' />
{/* 发起咨询按钮 — 实心主色 */}
<View
className='consultation-create-btn'
onClick={() => Taro.navigateTo({ url: '/pages/consultation/create/index' })}
>
<Text className='consultation-create-btn-text'></Text>
</View>
) : error ? (
<View className='consultation-center'>
<Text className='consultation-error'>{error}</Text>
</View>
) : sessions.length === 0 ? (
<View className='consultation-empty'>
<View className='empty-icon'>
<Text className='empty-char'></Text>
{/* 内容区 */}
{loading ? (
<View className='consultation-center'>
<Loading text='加载中...' />
</View>
<Text className='empty-title'></Text>
<Text className='empty-hint'></Text>
</View>
) : (
<View className='session-list'>
{sessions.map((session) => {
const tag = getStatusTag(session.status);
return (
<View
key={session.id}
className='session-card'
onClick={() => handleTapSession(session)}
>
<View className='session-main'>
<View className='session-top'>
<Text className='session-subject'>
{session.subject || '在线咨询'}
</Text>
<Text className={`session-tag ${tag.cls}`}>{tag.label}</Text>
) : error ? (
<View className='consultation-center'>
<Text className='consultation-error'>{error}</Text>
</View>
) : sessions.length === 0 ? (
<View className='consultation-empty'>
<View className='empty-icon'>
<Text className='empty-char'></Text>
</View>
<Text className='empty-title'></Text>
<Text className='empty-hint'></Text>
</View>
) : (
<View className='session-list'>
{sessions.map((session) => {
const tag = getStatusTag(session.status);
const initial = (session.subject || '咨').charAt(0);
const isClosed = session.status === 'closed' || session.status === 'cancelled';
return (
<View
key={session.id}
className={`session-card ${isClosed ? 'session-card-closed' : ''}`}
onClick={() => handleTapSession(session)}
>
<View className='session-avatar'>
<Text className='session-avatar-char'>{initial}</Text>
</View>
<View className='session-body'>
<View className='session-top'>
<Text className='session-subject'>
{session.subject || '在线咨询'}
</Text>
<Text className='session-time'>
{session.last_message_at
? formatTime(session.last_message_at)
: formatTime(session.created_at)}
</Text>
</View>
<View className='session-meta'>
<Text className={`session-tag ${tag.cls}`}>{tag.label}</Text>
</View>
<View className='session-message-row'>
<Text className='session-message'>
{session.last_message || '暂无消息'}
</Text>
{session.unread_count_patient > 0 && (
<View className='session-badge'>
<Text className='session-badge-text'>
{session.unread_count_patient > 99 ? '99+' : session.unread_count_patient}
</Text>
</View>
)}
</View>
</View>
<Text className='session-message'>
{session.last_message || '暂无消息'}
</Text>
<Text className='session-time'>
{session.last_message_at
? formatTime(session.last_message_at)
: formatTime(session.created_at)}
</Text>
</View>
{session.unread_count_patient > 0 && (
<View className='session-badge'>
<Text className='session-badge-text'>
{session.unread_count_patient > 99 ? '99+' : session.unread_count_patient}
</Text>
</View>
)}
</View>
);
})}
</View>
)}
);
})}
</View>
)}
</View>
</View>
);
}

View File

@@ -1,34 +1,5 @@
@import '../../styles/variables.scss';
@mixin serif-number {
font-family: 'Georgia', 'Times New Roman', serif;
font-variant-numeric: tabular-nums;
}
@mixin section-title {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 30px;
font-weight: bold;
color: $tx;
margin-bottom: 20px;
display: block;
}
@mixin tag($bg, $color) {
display: inline-block;
padding: 4px 12px;
border-radius: 8px;
font-size: 20px;
font-weight: 500;
background: $bg;
color: $color;
}
@mixin flex-center {
display: flex;
align-items: center;
justify-content: center;
}
@import '../../styles/mixins.scss';
.device-sync-page {
min-height: 100vh;
@@ -43,9 +14,8 @@
}
.sync-header-title {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 40px;
font-weight: bold;
@include section-title;
color: $card;
}
.sync-section {
@@ -72,20 +42,17 @@
margin-bottom: 20px;
color: $pri;
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 36px;
font-size: var(--tk-font-num-lg);
font-weight: bold;
}
.sync-hero-title {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 34px;
font-weight: bold;
color: $tx;
@include section-title;
margin-bottom: 8px;
}
.sync-hero-desc {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx2;
}
@@ -110,7 +77,7 @@
.sync-action-text {
color: $card;
font-size: 28px;
font-size: var(--tk-font-body-lg);
font-weight: 500;
}
@@ -120,7 +87,7 @@
.sync-section-title {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 28px;
font-size: var(--tk-font-body-lg);
font-weight: bold;
color: $tx;
margin-bottom: 12px;
@@ -144,19 +111,19 @@
}
.sync-device-name {
font-size: 28px;
font-size: var(--tk-font-body-lg);
font-weight: 500;
color: $tx;
}
.sync-device-adapter {
font-size: 22px;
color: $tx3;
font-size: var(--tk-font-body);
color: var(--tk-text-secondary);
margin-top: 4px;
}
.sync-device-rssi {
font-size: 22px;
font-size: var(--tk-font-body);
color: $tx2;
}
@@ -183,7 +150,7 @@
}
.sync-status-text {
font-size: 28px;
font-size: var(--tk-font-body-lg);
color: $tx;
}
@@ -208,12 +175,12 @@
}
.sync-reading-type {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx2;
}
.sync-reading-value {
font-size: 28px;
font-size: var(--tk-font-body-lg);
font-weight: bold;
color: $pri;
@include serif-number;
@@ -222,8 +189,8 @@
.sync-readings-count {
display: block;
margin-top: 12px;
font-size: 22px;
color: $tx3;
font-size: var(--tk-font-body);
color: var(--tk-text-secondary);
text-align: center;
}
@@ -240,7 +207,7 @@
}
.sync-error-text {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $dan;
}
@@ -250,7 +217,7 @@
}
.sync-loading-text {
font-size: 28px;
font-size: var(--tk-font-body-lg);
color: $tx2;
}
@@ -273,20 +240,17 @@
@include flex-center;
color: $acc;
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 36px;
font-size: var(--tk-font-num-lg);
font-weight: bold;
margin-bottom: 16px;
}
.sync-result-title {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 34px;
font-weight: bold;
color: $tx;
@include section-title;
margin-bottom: 8px;
}
.sync-result-count {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx2;
}

View File

@@ -1,26 +1,43 @@
import { useState, useCallback } from 'react';
import { useState, useCallback, useMemo } from 'react';
import { View, Text } from '@tarojs/components';
import { useDidShow } from '@tarojs/taro';
import Taro, { useDidShow, useRouter } from '@tarojs/taro';
import { BLEManager } from '@/services/ble/BLEManager';
import { XiaomiBandAdapter } from '@/services/ble/adapters/XiaomiBandAdapter';
import { BloodPressureAdapter } from '@/services/ble/adapters/BloodPressureAdapter';
import { GlucoseMeterAdapter } from '@/services/ble/adapters/GlucoseMeterAdapter';
import { CustomBandAdapter } from '@/services/ble/adapters/GenericBleAdapter';
import { DataSyncScheduler } from '@/services/ble/DataSyncScheduler';
import { uploadReadings } from '@/services/device-sync';
import { useAuthStore } from '@/stores/auth';
import type { BLEDevice, NormalizedReading } from '@/services/ble/types';
import { useElderClass } from '../../hooks/useElderClass';
import './index.scss';
const bleManager = new BLEManager({ scanTimeout: 10000, retryCount: 3 });
bleManager.registerAdapter(XiaomiBandAdapter);
bleManager.registerAdapter(BloodPressureAdapter);
bleManager.registerAdapter(GlucoseMeterAdapter);
bleManager.registerAdapter(CustomBandAdapter);
type PageState = 'idle' | 'scanning' | 'connecting' | 'connected' | 'syncing' | 'done' | 'error';
export default function DeviceSync() {
const modeClass = useElderClass();
const { currentPatient } = useAuthStore();
const router = useRouter();
const returnTo = router.params.returnTo || '';
const [pageState, setPageState] = useState<PageState>('idle');
const [devices, setDevices] = useState<BLEDevice[]>([]);
const [selectedDevice, setSelectedDevice] = useState<BLEDevice | null>(null);
const [liveReadings, setLiveReadings] = useState<NormalizedReading[]>([]);
const [syncCount, setSyncCount] = useState(0);
const [errorMsg, setErrorMsg] = useState('');
const [lastSyncAt, setLastSyncAt] = useState<number | null>(null);
const [pendingCount, setPendingCount] = useState(0);
const scheduler = useMemo(() => new DataSyncScheduler({
intervalMs: 60 * 60 * 1000,
}), []);
useDidShow(() => {
bleManager.setOnConnectionChange(() => {});
@@ -28,7 +45,29 @@ export default function DeviceSync() {
setLiveReadings((prev) => [...prev, ...readings]);
});
// 显示上次同步时间
setLastSyncAt(scheduler.getLastSyncAt());
// 检查是否有未上传的缓冲数据
const buffer = (bleManager as any).dataBuffer;
if (buffer) {
setPendingCount(buffer.size());
}
// 自动同步:超过间隔时尝试上传缓冲数据
if (currentPatient && scheduler.needsSync()) {
scheduler.tryAutoSync(async () => {
const count = await bleManager.flushPendingReadings(async (readings) => {
return uploadReadings(currentPatient.id, 'buffered', undefined, readings);
});
setLastSyncAt(Date.now());
setPendingCount(0);
return { success: count > 0, uploadedCount: count };
});
}
return () => {
scheduler.destroy();
bleManager.destroy();
};
});
@@ -41,7 +80,7 @@ export default function DeviceSync() {
const found = await bleManager.scanDevices();
setDevices(found);
if (found.length === 0) {
setErrorMsg('未发现支持的设备,请确认手环已开启蓝牙并靠近手机');
setErrorMsg('未发现支持的设备,请确认设备已开启蓝牙并靠近手机');
}
setPageState('idle');
} catch (e: any) {
@@ -81,7 +120,29 @@ export default function DeviceSync() {
if (result.success) {
setSyncCount(result.uploadedCount);
setLastSyncAt(Date.now());
setPageState('done');
// 如果从体征录入页跳转而来,将最新读数写入 storage 供回填
if (returnTo === 'input' && liveReadings.length > 0) {
const mapped: Record<string, number> = {};
for (const r of liveReadings) {
if (r.device_type === 'blood_pressure') {
if (r.metric === 'systolic' && typeof r.values.value === 'number') mapped.systolic = r.values.value;
if (r.metric === 'diastolic' && typeof r.values.value === 'number') mapped.diastolic = r.values.value;
// 兼容 values 中直接包含 systolic/diastolic 的格式
if (typeof r.values.systolic === 'number') mapped.systolic = r.values.systolic as number;
if (typeof r.values.diastolic === 'number') mapped.diastolic = r.values.diastolic as number;
} else if (r.device_type === 'blood_glucose' && typeof r.values.blood_glucose === 'number') {
mapped.blood_sugar = r.values.blood_glucose as number;
} else if (r.device_type === 'heart_rate' && typeof r.values.heart_rate === 'number') {
mapped.heart_rate = r.values.heart_rate as number;
}
}
if (Object.keys(mapped).length > 0) {
Taro.setStorageSync('device_sync_result', JSON.stringify(mapped));
}
}
} else {
setErrorMsg(result.error || '同步失败');
setPageState('error');
@@ -90,7 +151,7 @@ export default function DeviceSync() {
setErrorMsg(e.message || '同步失败');
setPageState('error');
}
}, [currentPatient, selectedDevice]);
}, [currentPatient, selectedDevice, liveReadings, returnTo]);
const handleDisconnect = useCallback(async () => {
await bleManager.disconnect();
@@ -106,9 +167,24 @@ export default function DeviceSync() {
<View className="sync-hero">
<Text className="sync-hero-icon">D</Text>
<Text className="sync-hero-title"></Text>
<Text className="sync-hero-desc"></Text>
<Text className="sync-hero-desc"></Text>
</View>
{(lastSyncAt || pendingCount > 0) && (
<View className="sync-status-info">
{lastSyncAt && (
<Text className="sync-status-time">
: {new Date(lastSyncAt).toLocaleTimeString()}
</Text>
)}
{pendingCount > 0 && (
<Text className="sync-status-pending">
{pendingCount}
</Text>
)}
</View>
)}
<View className="sync-action" onClick={handleScan}>
<Text className="sync-action-text"></Text>
</View>
@@ -147,12 +223,17 @@ export default function DeviceSync() {
{liveReadings.slice(-5).reverse().map((r, i) => (
<View key={i} className="sync-reading-item">
<Text className="sync-reading-type">
{r.device_type === 'heart_rate' ? '心率' : r.device_type}
{r.device_type === 'heart_rate' ? '心率'
: r.device_type === 'blood_pressure' ? `血压(${r.metric === 'systolic' ? '收缩压' : r.metric === 'diastolic' ? '舒张压' : 'MAP'})`
: r.device_type === 'blood_glucose' ? '血糖'
: r.device_type}
</Text>
<Text className="sync-reading-value">
{r.device_type === 'heart_rate'
? `${r.values.heart_rate} bpm`
: JSON.stringify(r.values)}
: r.metric
? `${r.values.value} ${r.values.unit}`
: JSON.stringify(r.values)}
</Text>
</View>
))}
@@ -180,14 +261,19 @@ export default function DeviceSync() {
<Text className="sync-result-title"></Text>
<Text className="sync-result-count"> {syncCount} </Text>
</View>
<View className="sync-action" onClick={handleDisconnect}>
<Text className="sync-action-text"></Text>
<View className="sync-action" onClick={() => {
handleDisconnect();
if (returnTo === 'input') {
Taro.navigateBack();
}
}}>
<Text className="sync-action-text">{returnTo === 'input' ? '返回录入' : '完成'}</Text>
</View>
</View>
);
return (
<View className="device-sync-page">
<View className={`device-sync-page ${modeClass}`}>
<View className="sync-header">
<Text className="sync-header-title"></Text>
</View>

View File

@@ -0,0 +1,189 @@
@import '../../../styles/variables.scss';
@import '../../../styles/mixins.scss';
.action-inbox-page {
min-height: 100vh;
background: $bg;
}
.inbox-tabs {
display: flex;
background: $card;
padding: 0 16px;
border-bottom: 1px solid $bd;
.inbox-tab {
flex: 1;
text-align: center;
padding: 12px 0;
&.active {
.inbox-tab-text {
color: $pri;
font-weight: 600;
position: relative;
&::after {
content: '';
position: absolute;
bottom: -12px;
left: 30%;
right: 30%;
height: 3px;
background: $pri;
border-radius: 2px;
}
}
}
}
.inbox-tab-text {
font-size: var(--tk-font-cap);
color: $tx2;
}
}
.inbox-list {
height: calc(100vh - 50px);
padding: 12px;
}
.inbox-card {
background: $card;
border-radius: $r-sm;
padding: 14px 16px;
margin-bottom: 10px;
box-shadow: $shadow-sm;
.inbox-card-header {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 6px;
}
.inbox-type-tag {
color: $card;
font-size: var(--tk-font-micro);
padding: 2px 6px;
border-radius: 4px;
flex-shrink: 0;
}
.inbox-card-title {
font-size: var(--tk-font-cap);
font-weight: 500;
color: $tx;
}
.inbox-card-desc {
font-size: var(--tk-font-micro);
color: $tx3;
}
}
.inbox-empty {
text-align: center;
padding: 80px 0;
.inbox-empty-text {
font-size: var(--tk-font-cap);
color: $tx3;
}
}
.half-screen-dialog {
position: fixed;
bottom: 0;
left: 0;
right: 0;
max-height: 70vh;
background: $card;
border-radius: $r-lg $r-lg 0 0;
z-index: 1000;
overflow-y: auto;
box-shadow: $shadow-lg;
.dialog-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px 20px;
border-bottom: 1px solid $bd-l;
.dialog-title {
font-size: var(--tk-font-body-sm);
font-weight: 600;
color: $tx;
}
.dialog-close {
font-size: var(--tk-font-cap);
color: $tx3;
}
}
.dialog-body {
padding: 16px 20px;
}
.dialog-patient {
font-size: var(--tk-font-cap);
color: $tx2;
display: block;
margin-bottom: 12px;
}
.thread-item {
display: flex;
align-items: flex-start;
gap: 10px;
padding: 6px 0;
}
.thread-dot {
width: 8px;
height: 8px;
border-radius: 50%;
margin-top: 4px;
flex-shrink: 0;
&.completed { background: $acc; }
&.in_progress { background: $wrn; }
&.pending { background: $tx3; }
&.dismissed { background: $dan; }
}
.thread-content {
.thread-label {
font-size: var(--tk-font-cap);
color: $tx;
display: block;
}
.thread-time {
font-size: var(--tk-font-micro);
color: $tx3;
}
}
.dialog-actions {
display: flex;
gap: 8px;
padding: 12px 20px 20px;
border-top: 1px solid $bd-l;
.action-btn {
flex: 1;
text-align: center;
padding: 10px;
border-radius: $r-sm;
font-size: var(--tk-font-cap);
font-weight: 500;
&.primary { background: $pri; color: $card; }
&.danger { background: $dan; color: $card; }
&.default { background: $surface-alt; color: $tx2; }
}
}
}

View File

@@ -0,0 +1,231 @@
import React, { useState, useCallback, useRef } from 'react';
import { View, Text, ScrollView } from '@tarojs/components';
import Taro, { useDidShow, usePullDownRefresh } from '@tarojs/taro';
import {
listActionItems,
getActionThread,
type ActionItem,
type ThreadResponse,
} from '@/services/action-inbox';
import Loading from '@/components/Loading';
import { useElderClass } from '../../../hooks/useElderClass';
import { getStatusInlineStyle, getStatusLabel } from '@/utils/statusTag';
import './index.scss';
const TYPE_LABEL: Record<string, string> = {
ai_suggestion: 'AI建议',
alert: '告警',
followup: '随访',
data_anomaly: '异常',
};
const TYPE_COLOR: Record<string, string> = {
ai_suggestion: '#722ed1',
alert: '#f5222d',
followup: '#1890ff',
data_anomaly: '#fa8c16',
};
const STATUS_TABS = [
{ key: '', label: '全部' },
{ key: 'pending', label: '待处理' },
{ key: 'in_progress', label: '进行中' },
{ key: 'completed', label: '已完成' },
];
export default function ActionInboxPage() {
const modeClass = useElderClass();
const [items, setItems] = useState<ActionItem[]>([]);
const [total, setTotal] = useState(0);
const [_page, setPage] = useState(1);
const [loading, setLoading] = useState(false);
const [activeTab, setActiveTab] = useState('');
const [threadData, setThreadData] = useState<ThreadResponse | null>(null);
const [showDetail, setShowDetail] = useState(false);
const loadingRef = useRef(false);
const fetchItems = useCallback(
async (pageNum: number, status: string, isRefresh = false) => {
if (loadingRef.current) return;
loadingRef.current = true;
setLoading(true);
try {
const resp = await listActionItems({
page: pageNum,
page_size: 20,
status: status || undefined,
});
const list = resp.data || [];
if (isRefresh) {
setItems(list);
} else {
setItems((prev) => [...prev, ...list]);
}
setTotal(resp.total);
setPage(pageNum);
} catch {
Taro.showToast({ title: '加载失败', icon: 'none' });
} finally {
setLoading(false);
loadingRef.current = false;
}
},
[],
);
useDidShow(() => {
Taro.setNavigationBarTitle({ title: '待办事项' });
fetchItems(1, activeTab, true);
});
usePullDownRefresh(() => {
fetchItems(1, activeTab, true).then(() =>
Taro.stopPullDownRefresh(),
);
});
const handleTabChange = (key: string) => {
setActiveTab(key);
fetchItems(1, key, true);
};
const handleItemClick = async (item: ActionItem) => {
try {
const data = await getActionThread(item.source_ref);
setThreadData(data);
setShowDetail(true);
} catch {
Taro.showToast({ title: '加载失败', icon: 'none' });
}
};
const handleAction = async (action: {
key: string;
api_endpoint?: string;
}) => {
if (!action.api_endpoint || !threadData) return;
try {
await Taro.request({
url: `${process.env.TARO_APP_API_URL}${action.api_endpoint}`,
method: 'POST',
header: { 'Content-Type': 'application/json' },
data: { action: action.key },
});
Taro.showToast({ title: '操作成功', icon: 'success' });
setShowDetail(false);
fetchItems(1, activeTab, true);
} catch {
Taro.showToast({ title: '操作失败', icon: 'none' });
}
};
return (
<View className={`action-inbox-page ${modeClass}`}>
<View className="inbox-tabs">
{STATUS_TABS.map((tab) => (
<View
key={tab.key}
className={`inbox-tab ${activeTab === tab.key ? 'active' : ''}`}
onClick={() => handleTabChange(tab.key)}
>
<Text
className={`inbox-tab-text ${activeTab === tab.key ? 'active' : ''}`}
>
{tab.label}
</Text>
</View>
))}
</View>
{items.length === 0 && !loading ? (
<View className="inbox-empty">
<Text className="inbox-empty-text"></Text>
</View>
) : (
<ScrollView scrollY className="inbox-list">
{items.map((item) => (
<View
key={item.id}
className="inbox-card"
onClick={() => handleItemClick(item)}
>
<View className="inbox-card-header">
<Text
className="inbox-type-tag"
style={{
background: TYPE_COLOR[item.action_type] || '#999',
}}
>
{TYPE_LABEL[item.action_type] || '未知'}
</Text>
<Text className="inbox-card-title">{item.title}</Text>
</View>
<Text className="inbox-card-desc">
{item.patient_name} ·{' '}
{new Date(item.created_at).toLocaleDateString('zh-CN')}
</Text>
</View>
))}
{loading && <Loading />}
{!loading && items.length >= total && total > 0 && (
<Loading text="没有更多了" />
)}
</ScrollView>
)}
{showDetail && threadData && (
<View className="half-screen-dialog">
<View className="dialog-header">
<Text className="dialog-title">
{threadData.action_item.title}
</Text>
<Text
className="dialog-close"
onClick={() => setShowDetail(false)}
>
</Text>
</View>
<View className="dialog-body">
<Text className="dialog-patient">
{threadData.action_item.patient_name} ·{' '}
{threadData.action_item.priority === 'urgent'
? '紧急'
: threadData.action_item.priority === 'high'
? '高'
: '中'}
</Text>
<View className="thread-timeline">
{threadData.thread.map((evt, idx) => (
<View key={idx} className="thread-item">
<View className={`thread-dot ${evt.status}`} />
<View className="thread-content">
<Text className="thread-label">{evt.label}</Text>
{evt.timestamp && (
<Text className="thread-time">
{new Date(evt.timestamp).toLocaleDateString('zh-CN')}
</Text>
)}
</View>
</View>
))}
</View>
</View>
{threadData.available_actions.length > 0 && (
<View className="dialog-actions">
{threadData.available_actions.map((action) => (
<View
key={action.key}
className={`action-btn ${action.variant}`}
onClick={() => handleAction(action)}
>
{action.label}
</View>
))}
</View>
)}
</View>
)}
</View>
);
}

View File

@@ -0,0 +1,166 @@
@import '../../../../styles/variables.scss';
@import '../../../../styles/mixins.scss';
.alert-detail-page {
min-height: 100vh;
background: $bg;
padding: 24px;
padding-bottom: 160px;
}
.alert-detail-header {
margin-bottom: 24px;
&__tags {
display: flex;
gap: 12px;
margin-bottom: 12px;
}
&__time {
font-size: var(--tk-font-h2);
color: $tx3;
}
}
.detail-severity {
font-size: var(--tk-font-h2);
font-weight: 600;
padding: 6px 16px;
border-radius: $r-sm;
&--info {
background: $bd-l;
color: $tx2;
}
&--warning {
background: $wrn-l;
color: $wrn;
}
&--critical {
background: $dan-l;
color: $dan;
}
&--urgent {
background: $dan-l;
color: $dan;
}
}
.detail-status {
font-size: var(--tk-font-h2);
padding: 6px 16px;
border-radius: $r-sm;
&--pending {
background: $wrn-l;
color: $wrn;
}
&--acknowledged {
background: $pri-l;
color: $pri;
}
&--resolved {
background: $acc-l;
color: $acc;
}
&--dismissed {
background: $bd-l;
color: $tx3;
}
}
.alert-detail-card {
background: $card;
border-radius: $r-lg;
padding: 24px;
margin-bottom: 16px;
box-shadow: $shadow-sm;
&__label {
font-size: var(--tk-font-h2);
color: $tx2;
margin-bottom: 8px;
}
&__value {
font-size: var(--tk-font-body-lg);
color: $tx;
word-break: break-all;
&--id {
font-size: var(--tk-font-h2);
color: $tx3;
font-family: monospace;
}
&--detail {
font-size: var(--tk-font-body);
color: $tx2;
font-family: monospace;
line-height: 1.6;
white-space: pre-wrap;
background: $bg;
padding: 16px;
border-radius: $r;
margin-top: 8px;
}
}
}
.alert-detail-actions {
display: flex;
gap: 16px;
margin-top: 32px;
padding: 0 8px;
}
.alert-action-btn {
flex: 1;
height: 88px;
line-height: 88px;
font-size: var(--tk-font-body-lg);
font-weight: 600;
border-radius: $r-lg;
text-align: center;
&--primary {
background: $pri;
color: $card;
border: none;
&::after {
border: none;
}
}
&--default {
background: $bd-l;
color: $tx2;
border: none;
&::after {
border: none;
}
}
&--resolve {
background: $acc-l;
color: $acc;
border: none;
&::after {
border: none;
}
}
&[disabled] {
opacity: 0.5;
}
}

View File

@@ -0,0 +1,212 @@
import { useState, useEffect } from 'react';
import { View, Text, ScrollView, Button } from '@tarojs/components';
import Taro from '@tarojs/taro';
import * as doctorApi from '@/services/doctor';
import Loading from '@/components/Loading';
import { useElderClass } from '../../../../hooks/useElderClass';
import './index.scss';
const SEVERITY_MAP: Record<string, { label: string; className: string }> = {
info: { label: '提示', className: 'detail-severity--info' },
warning: { label: '警告', className: 'detail-severity--warning' },
critical: { label: '严重', className: 'detail-severity--critical' },
urgent: { label: '紧急', className: 'detail-severity--urgent' },
};
const STATUS_MAP: Record<string, { label: string; className: string }> = {
pending: { label: '待处理', className: 'detail-status--pending' },
acknowledged: { label: '已确认', className: 'detail-status--acknowledged' },
resolved: { label: '已恢复', className: 'detail-status--resolved' },
dismissed: { label: '已忽略', className: 'detail-status--dismissed' },
};
export default function AlertDetail() {
const modeClass = useElderClass();
const [alert, setAlert] = useState<doctorApi.Alert | null>(null);
const [loading, setLoading] = useState(true);
const [actionLoading, setActionLoading] = useState(false);
useEffect(() => {
const params = Taro.getCurrentInstance().router?.params;
if (params?.id) {
loadAlert(params.id);
}
}, []);
const loadAlert = async (id: string) => {
try {
// 告警列表 API 支持按 ID 查询,此处用列表加载后过滤
const res = await doctorApi.listAlerts({ page: 1, page_size: 100 });
const found = (res.data || []).find((a) => a.id === id);
if (found) {
setAlert(found);
} else {
Taro.showToast({ title: '告警不存在', icon: 'none' });
}
} catch {
Taro.showToast({ title: '加载失败', icon: 'none' });
} finally {
setLoading(false);
}
};
const handleAcknowledge = async () => {
if (!alert) return;
setActionLoading(true);
try {
const updated = await doctorApi.acknowledgeAlert(alert.id, alert.version);
setAlert(updated);
Taro.showToast({ title: '已确认', icon: 'success' });
} catch {
Taro.showToast({ title: '操作失败', icon: 'none' });
} finally {
setActionLoading(false);
}
};
const handleDismiss = async () => {
if (!alert) return;
setActionLoading(true);
try {
const updated = await doctorApi.dismissAlert(alert.id, alert.version);
setAlert(updated);
Taro.showToast({ title: '已忽略', icon: 'success' });
} catch {
Taro.showToast({ title: '操作失败', icon: 'none' });
} finally {
setActionLoading(false);
}
};
const handleResolve = async () => {
if (!alert) return;
setActionLoading(true);
try {
const updated = await doctorApi.resolveAlert(alert.id, alert.version);
setAlert(updated);
Taro.showToast({ title: '已恢复', icon: 'success' });
} catch {
Taro.showToast({ title: '操作失败', icon: 'none' });
} finally {
setActionLoading(false);
}
};
if (loading) return <Loading />;
if (!alert) {
return (
<View className={`alert-detail-page ${modeClass}`}>
<Text></Text>
</View>
);
}
const severity = SEVERITY_MAP[alert.severity] ?? SEVERITY_MAP.info;
const status = STATUS_MAP[alert.status] ?? STATUS_MAP.pending;
const isPending = alert.status === 'pending';
const isAcknowledged = alert.status === 'acknowledged';
return (
<ScrollView scrollY className={`alert-detail-page ${modeClass}`}>
{/* 顶部状态 */}
<View className='alert-detail-header'>
<View className='alert-detail-header__tags'>
<Text className={`detail-severity ${severity.className}`}>
{severity.label}
</Text>
<Text className={`detail-status ${status.className}`}>
{status.label}
</Text>
</View>
<Text className='alert-detail-header__time'>
{new Date(alert.created_at).toLocaleString('zh-CN')}
</Text>
</View>
{/* 告警信息 */}
<View className='alert-detail-card'>
<Text className='alert-detail-card__label'></Text>
<Text className='alert-detail-card__value'>{alert.title}</Text>
</View>
<View className='alert-detail-card'>
<Text className='alert-detail-card__label'> ID</Text>
<Text className='alert-detail-card__value alert-detail-card__value--id'>
{alert.patient_id.slice(0, 8)}...
</Text>
</View>
<View className='alert-detail-card'>
<Text className='alert-detail-card__label'></Text>
<Text className='alert-detail-card__value'>{severity.label}</Text>
</View>
{alert.detail && (
<View className='alert-detail-card'>
<Text className='alert-detail-card__label'></Text>
<Text className='alert-detail-card__value alert-detail-card__value--detail'>
{JSON.stringify(alert.detail, null, 2)}
</Text>
</View>
)}
{alert.acknowledged_by && (
<View className='alert-detail-card'>
<Text className='alert-detail-card__label'></Text>
<Text className='alert-detail-card__value'>{alert.acknowledged_by}</Text>
</View>
)}
{alert.acknowledged_at && (
<View className='alert-detail-card'>
<Text className='alert-detail-card__label'></Text>
<Text className='alert-detail-card__value'>
{new Date(alert.acknowledged_at).toLocaleString('zh-CN')}
</Text>
</View>
)}
{alert.resolved_at && (
<View className='alert-detail-card'>
<Text className='alert-detail-card__label'></Text>
<Text className='alert-detail-card__value'>
{new Date(alert.resolved_at).toLocaleString('zh-CN')}
</Text>
</View>
)}
{/* 操作按钮 */}
{(isPending || isAcknowledged) && (
<View className='alert-detail-actions'>
{isPending && (
<>
<Button
className='alert-action-btn alert-action-btn--primary'
onClick={handleAcknowledge}
disabled={actionLoading}
>
</Button>
<Button
className='alert-action-btn alert-action-btn--default'
onClick={handleDismiss}
disabled={actionLoading}
>
</Button>
</>
)}
{(isPending || isAcknowledged) && (
<Button
className='alert-action-btn alert-action-btn--resolve'
onClick={handleResolve}
disabled={actionLoading}
>
</Button>
)}
</View>
)}
</ScrollView>
);
}

View File

@@ -0,0 +1,174 @@
@import '../../../styles/variables.scss';
@import '../../../styles/mixins.scss';
.alert-list-page {
min-height: 100vh;
background: $bg;
padding: 24px;
padding-bottom: 120px;
}
.alert-list-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 24px;
}
.alert-list-title {
font-size: var(--tk-font-num-lg);
font-weight: 600;
color: $tx;
}
.alert-list-count {
font-size: var(--tk-font-h2);
color: $tx2;
}
.alert-tabs {
display: flex;
gap: 12px;
margin-bottom: 24px;
}
.alert-tab {
padding: 10px 24px;
border-radius: $r-pill;
background: $bd-l;
font-size: var(--tk-font-h2);
color: $tx2;
transition: all 0.2s;
&--active {
background: $pri;
color: $card;
}
}
.alert-cards {
display: flex;
flex-direction: column;
gap: 16px;
}
.alert-card {
background: $card;
border-radius: $r-lg;
padding: 24px;
box-shadow: $shadow-sm;
border-left: 4px solid $wrn;
&:active {
background: $bd-l;
}
&--critical {
border-left-color: $dan;
}
&--info {
border-left-color: $tx3;
}
&__header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
}
&__title {
font-size: var(--tk-font-body-lg);
font-weight: 500;
color: $tx;
margin-bottom: 8px;
}
&__footer {
display: flex;
justify-content: space-between;
align-items: center;
}
&__time {
font-size: var(--tk-font-body);
color: $tx3;
}
}
.alert-severity {
font-size: var(--tk-font-body);
font-weight: 600;
padding: 4px 12px;
border-radius: $r-sm;
&--info {
background: $bd-l;
color: $tx2;
}
&--warning {
background: $wrn-l;
color: $wrn;
}
&--critical {
background: $dan-l;
color: $dan;
}
&--urgent {
background: $dan-l;
color: $dan;
}
}
.alert-status {
font-size: var(--tk-font-body);
padding: 4px 12px;
border-radius: $r-sm;
&--pending {
background: $wrn-l;
color: $wrn;
}
&--acknowledged {
background: $pri-l;
color: $pri;
}
&--resolved {
background: $acc-l;
color: $acc;
}
&--dismissed {
background: $bd-l;
color: $tx3;
}
}
.alert-pagination {
display: flex;
justify-content: center;
align-items: center;
gap: 24px;
margin-top: 32px;
&__btn {
font-size: var(--tk-font-h1);
color: $pri;
padding: 12px 24px;
&.disabled {
color: $tx3;
}
}
&__info {
font-size: var(--tk-font-h2);
color: $tx2;
}
}

View File

@@ -0,0 +1,156 @@
import { useState, useEffect, useMemo } from 'react';
import { View, Text, ScrollView } from '@tarojs/components';
import Taro from '@tarojs/taro';
import * as doctorApi from '@/services/doctor';
import Loading from '@/components/Loading';
import EmptyState from '@/components/EmptyState';
import { useElderClass } from '../../../hooks/useElderClass';
import './index.scss';
const SEVERITY_MAP: Record<string, { label: string; className: string }> = {
info: { label: '提示', className: 'alert-severity--info' },
warning: { label: '警告', className: 'alert-severity--warning' },
critical: { label: '严重', className: 'alert-severity--critical' },
urgent: { label: '紧急', className: 'alert-severity--urgent' },
};
const STATUS_MAP: Record<string, { label: string; className: string }> = {
pending: { label: '待处理', className: 'alert-status--pending' },
acknowledged: { label: '已确认', className: 'alert-status--acknowledged' },
resolved: { label: '已恢复', className: 'alert-status--resolved' },
dismissed: { label: '已忽略', className: 'alert-status--dismissed' },
};
const STATUS_TABS = [
{ value: '', label: '全部' },
{ value: 'pending', label: '待处理' },
{ value: 'acknowledged', label: '已确认' },
{ value: 'resolved', label: '已恢复' },
];
export default function AlertList() {
const modeClass = useElderClass();
const [alerts, setAlerts] = useState<doctorApi.Alert[]>([]);
const [loading, setLoading] = useState(true);
const [activeTab, setActiveTab] = useState('');
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1);
const totalPages = useMemo(() => Math.ceil(total / 20), [total]);
useEffect(() => {
loadAlerts();
}, [page, activeTab]);
const loadAlerts = async () => {
setLoading(true);
try {
const res = await doctorApi.listAlerts({
status: activeTab || undefined,
page,
page_size: 20,
});
setAlerts(res.data || []);
setTotal(res.total || 0);
} catch {
Taro.showToast({ title: '加载失败', icon: 'none' });
} finally {
setLoading(false);
}
};
const handleTabChange = (value: string) => {
setActiveTab(value);
setPage(1);
};
const handleAlertClick = (alert: doctorApi.Alert) => {
Taro.navigateTo({ url: `/pages/doctor/alerts/detail/index?id=${alert.id}` });
};
const formatTime = (dateStr: string) => {
const d = new Date(dateStr);
const now = new Date();
const diff = now.getTime() - d.getTime();
const minutes = Math.floor(diff / 60000);
if (minutes < 1) return '刚刚';
if (minutes < 60) return `${minutes}分钟前`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}小时前`;
return d.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
};
if (loading && alerts.length === 0) return <Loading />;
return (
<ScrollView scrollY className={`alert-list-page ${modeClass}`}>
<View className='alert-list-header'>
<Text className='alert-list-title'></Text>
<Text className='alert-list-count'> {total} </Text>
</View>
<View className='alert-tabs'>
{STATUS_TABS.map((tab) => (
<Text
key={tab.value}
className={`alert-tab ${activeTab === tab.value ? 'alert-tab--active' : ''}`}
onClick={() => handleTabChange(tab.value)}
>
{tab.label}
</Text>
))}
</View>
{alerts.length === 0 ? (
<EmptyState description='暂无告警' />
) : (
<View className='alert-cards'>
{alerts.map((alert) => {
const severity = SEVERITY_MAP[alert.severity] ?? SEVERITY_MAP.info;
const status = STATUS_MAP[alert.status] ?? STATUS_MAP.pending;
return (
<View
key={alert.id}
className='alert-card'
onClick={() => handleAlertClick(alert)}
>
<View className='alert-card__header'>
<Text className={`alert-severity ${severity.className}`}>
{severity.label}
</Text>
<Text className={`alert-status ${status.className}`}>
{status.label}
</Text>
</View>
<Text className='alert-card__title'>{alert.title}</Text>
<View className='alert-card__footer'>
<Text className='alert-card__time'>{formatTime(alert.created_at)}</Text>
</View>
</View>
);
})}
</View>
)}
{total > 20 && (
<View className='alert-pagination'>
<Text
className={`alert-pagination__btn ${page <= 1 ? 'disabled' : ''}`}
onClick={() => page > 1 && setPage(page - 1)}
>
</Text>
<Text className='alert-pagination__info'>
{page} / {totalPages}
</Text>
<Text
className={`alert-pagination__btn ${page >= totalPages ? 'disabled' : ''}`}
onClick={() => page < totalPages && setPage(page + 1)}
>
</Text>
</View>
)}
</ScrollView>
);
}

View File

@@ -18,13 +18,13 @@
&__title {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 30px;
font-size: var(--tk-font-num);
font-weight: 600;
color: $tx;
}
&__close {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $dan;
padding: 8px 16px;
}
@@ -63,7 +63,7 @@
}
.msg-text {
font-size: 28px;
font-size: var(--tk-font-body-lg);
color: $tx;
display: block;
line-height: 1.6;
@@ -76,7 +76,7 @@
.msg-time {
@include serif-number;
font-size: 20px;
font-size: var(--tk-font-body);
color: $tx3;
display: block;
margin-top: 8px;
@@ -92,7 +92,7 @@
padding: 120px 32px;
&__text {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx3;
}
}
@@ -111,7 +111,7 @@
background: $bd-l;
border-radius: $r;
padding: 16px 20px;
font-size: 28px;
font-size: var(--tk-font-body-lg);
margin-right: 16px;
}
@@ -126,7 +126,7 @@
}
&__text {
font-size: 28px;
font-size: var(--tk-font-body-lg);
color: $card;
font-weight: 500;
}
@@ -139,7 +139,7 @@
border-top: 1px solid $bd;
&__text {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx3;
}
}

View File

@@ -3,56 +3,47 @@ import { View, Text, Input, ScrollView } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import * as doctorApi from '@/services/doctor';
import Loading from '@/components/Loading';
import { useElderClass } from '../../../../hooks/useElderClass';
import './index.scss';
const POLL_INTERVAL = 8000;
export default function ConsultationDetail() {
const router = useRouter();
const sessionId = router.params.id || '';
const modeClass = useElderClass();
const [session, setSession] = useState<doctorApi.ConsultationSession | null>(null);
const [messages, setMessages] = useState<doctorApi.ConsultationMessage[]>([]);
const [inputText, setInputText] = useState('');
const [sending, setSending] = useState(false);
const [loading, setLoading] = useState(true);
const scrollViewRef = useRef('');
const pollTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);
const pollingRef = useRef(false);
useEffect(() => {
if (sessionId) {
loadData();
markRead();
startPolling();
startLongPolling();
}
return () => stopPolling();
return () => { pollingRef.current = false; };
}, [sessionId]);
const startPolling = () => {
stopPolling();
pollTimerRef.current = setInterval(pollNewMessages, POLL_INTERVAL);
useEffect(() => {
if (session?.status === 'closed') {
pollingRef.current = false;
}
}, [session?.status]);
const startLongPolling = () => {
pollingRef.current = true;
longPoll();
};
const stopPolling = () => {
if (pollTimerRef.current) {
clearInterval(pollTimerRef.current);
pollTimerRef.current = null;
}
};
const pollNewMessages = async () => {
if (!session || session.status === 'closed') {
stopPolling();
return;
}
const longPoll = async () => {
if (!pollingRef.current) return;
try {
const lastId = messages.length > 0 ? messages[messages.length - 1].id : undefined;
const m = await doctorApi.listMessages(sessionId, {
page: 1,
page_size: 50,
after_id: lastId,
});
const newMsgs = m.data || [];
if (newMsgs.length > 0) {
const newMsgs = await doctorApi.pollMessages(sessionId, lastId);
if (newMsgs && newMsgs.length > 0) {
setMessages((prev) => {
const existing = new Set(prev.map((msg) => msg.id));
const fresh = newMsgs.filter((msg) => !existing.has(msg.id));
@@ -60,7 +51,12 @@ export default function ConsultationDetail() {
});
scrollViewRef.current = `msg-${messages.length + newMsgs.length}`;
}
} catch { /* 轮询失败静默忽略 */ }
} catch {
// 超时或网络错误,静默重试
}
if (pollingRef.current) {
longPoll();
}
};
const loadData = async () => {
@@ -73,7 +69,7 @@ export default function ConsultationDetail() {
setSession(s);
setMessages(m.data || []);
scrollViewRef.current = `msg-${(m.data || []).length}`;
if (s.status === 'closed') stopPolling();
if (s.status === 'closed') pollingRef.current = false;
} catch {
Taro.showToast({ title: '加载失败', icon: 'none' });
} finally {
@@ -132,7 +128,7 @@ export default function ConsultationDetail() {
const isOpen = session?.status !== 'closed';
return (
<View className='chat-page'>
<View className={`chat-page ${modeClass}`}>
{/* Header */}
<View className='chat-header'>
<Text className='chat-header__title'>{session?.subject || '在线咨询'}</Text>

View File

@@ -17,7 +17,7 @@
flex: 1;
text-align: center;
padding: 24px 0;
font-size: 28px;
font-size: var(--tk-font-body-lg);
color: $tx2;
position: relative;
@@ -64,7 +64,7 @@
}
&__subject {
font-size: 28px;
font-size: var(--tk-font-body-lg);
font-weight: 600;
color: $tx;
flex: 1;
@@ -80,7 +80,7 @@
}
&__status-text {
font-size: 22px;
font-size: var(--tk-font-body);
font-weight: 500;
}
@@ -96,12 +96,12 @@
}
&__time {
font-size: 24px;
font-size: var(--tk-font-h2);
color: $tx3;
}
&__preview {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx2;
overflow: hidden;
text-overflow: ellipsis;
@@ -123,7 +123,7 @@
&__badge-text {
@include serif-number;
font-size: 22px;
font-size: var(--tk-font-body);
color: $card;
font-weight: 600;
}
@@ -137,7 +137,7 @@
padding: 24px;
&__btn {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $pri;
padding: 12px 24px;
@@ -147,7 +147,7 @@
}
&__info {
font-size: 24px;
font-size: var(--tk-font-h2);
color: $tx2;
}
}

View File

@@ -1,17 +1,14 @@
import { useState, useEffect } from 'react';
import { useState, useEffect, useMemo } from 'react';
import { View, Text, ScrollView } from '@tarojs/components';
import Taro from '@tarojs/taro';
import * as doctorApi from '@/services/doctor';
import Loading from '@/components/Loading';
import EmptyState from '@/components/EmptyState';
import { useElderClass } from '../../../hooks/useElderClass';
import { getStatusInlineStyle, getStatusLabel } from '@/utils/statusTag';
import { formatDateTime } from '@/utils/date';
import './index.scss';
const STATUS_MAP: Record<string, { label: string; color: string }> = {
waiting: { label: '等待中', color: '#f59e0b' },
active: { label: '进行中', color: '#10b981' },
closed: { label: '已关闭', color: '#94a3b8' },
};
const TABS = [
{ key: '', label: '全部' },
{ key: 'active', label: '进行中' },
@@ -20,12 +17,15 @@ const TABS = [
];
export default function ConsultationList() {
const modeClass = useElderClass();
const [sessions, setSessions] = useState<doctorApi.ConsultationSession[]>([]);
const [activeTab, setActiveTab] = useState('');
const [loading, setLoading] = useState(true);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1);
const totalPages = useMemo(() => Math.ceil(total / 20), [total]);
useEffect(() => {
loadSessions();
}, [page, activeTab]);
@@ -54,18 +54,13 @@ export default function ConsultationList() {
const formatTime = (dateStr?: string | null) => {
if (!dateStr) return '';
const d = new Date(dateStr);
const now = new Date();
if (d.toDateString() === now.toDateString()) {
return d.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
}
return d.toLocaleDateString('zh-CN', { month: 'numeric', day: 'numeric' });
return formatDateTime(dateStr);
};
if (loading && sessions.length === 0) return <Loading />;
return (
<ScrollView scrollY className='consultation-page'>
<ScrollView scrollY className={`consultation-page ${modeClass}`}>
<View className='tabs'>
{TABS.map((t) => (
<View
@@ -83,7 +78,6 @@ export default function ConsultationList() {
) : (
<View className='session-list'>
{sessions.map((s) => {
const st = STATUS_MAP[s.status] || { label: s.status, color: '#94a3b8' };
return (
<View
key={s.id}
@@ -92,8 +86,8 @@ export default function ConsultationList() {
>
<View className='session-card__top'>
<Text className='session-card__subject'>{s.subject || '在线咨询'}</Text>
<View className='session-card__status' style={`background: ${st.color}20; color: ${st.color}`}>
<Text className='session-card__status-text'>{st.label}</Text>
<View className='session-card__status' style={getStatusInlineStyle(s.status)}>
<Text className='session-card__status-text'>{getStatusLabel(s.status)}</Text>
</View>
</View>
<View className='session-card__info'>
@@ -122,10 +116,10 @@ export default function ConsultationList() {
className={`pagination__btn ${page <= 1 ? 'disabled' : ''}`}
onClick={() => page > 1 && setPage(page - 1)}
></Text>
<Text className='pagination__info'>{page} / {Math.ceil(total / 20)}</Text>
<Text className='pagination__info'>{page} / {totalPages}</Text>
<Text
className={`pagination__btn ${page >= Math.ceil(total / 20) ? 'disabled' : ''}`}
onClick={() => page < Math.ceil(total / 20) && setPage(page + 1)}
className={`pagination__btn ${page >= totalPages ? 'disabled' : ''}`}
onClick={() => page < totalPages && setPage(page + 1)}
></Text>
</View>
)}

View File

@@ -0,0 +1,98 @@
@import '../../../../styles/variables.scss';
@import '../../../../styles/mixins.scss';
.create-page {
min-height: 100vh;
background: $bg;
padding: 24px;
padding-bottom: 200px;
}
.section {
background: $card;
border-radius: $r;
padding: 24px;
margin-bottom: 16px;
box-shadow: $shadow-sm;
}
.section-title {
font-size: var(--tk-font-body-lg);
font-weight: bold;
color: $tx;
display: block;
margin-bottom: 16px;
}
.form-row {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16px 0;
border-bottom: 1px solid $bd-l;
&:last-child {
border-bottom: none;
}
&--textarea {
flex-direction: column;
align-items: flex-start;
}
}
.form-label {
font-size: var(--tk-font-h1);
color: $tx2;
flex-shrink: 0;
min-width: 140px;
}
.form-input {
flex: 1;
text-align: right;
font-size: var(--tk-font-h1);
color: $tx;
}
.form-value {
font-size: var(--tk-font-h1);
color: $tx;
&.placeholder {
color: $tx3;
}
}
.form-textarea {
width: 100%;
margin-top: 12px;
font-size: var(--tk-font-h1);
color: $tx;
min-height: 120px;
background: $bg;
border-radius: $r-sm;
padding: 16px;
}
.submit-btn {
background: $pri;
border-radius: $r-sm;
padding: 24px;
text-align: center;
margin-top: 24px;
&:active {
background: $pri-d;
}
&--disabled {
opacity: 0.5;
}
}
.submit-btn__text {
font-size: var(--tk-font-num);
font-weight: bold;
color: #fff;
}

View File

@@ -0,0 +1,246 @@
import { useState, useEffect } from 'react';
import { View, Text, Input, Textarea, Picker, ScrollView } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import * as doctorApi from '@/services/doctor';
import Loading from '@/components/Loading';
import { useElderClass } from '../../../../hooks/useElderClass';
import './index.scss';
const DIALYSIS_TYPES = ['HD', 'HDF', 'HF'];
interface FormState {
patient_id: string;
dialysis_date: string;
start_time: string;
end_time: string;
dialysis_type: string;
dialysis_duration: string;
blood_flow_rate: string;
dry_weight: string;
pre_weight: string;
post_weight: string;
pre_bp_systolic: string;
pre_bp_diastolic: string;
post_bp_systolic: string;
post_bp_diastolic: string;
pre_heart_rate: string;
post_heart_rate: string;
ultrafiltration_volume: string;
complication_notes: string;
}
const initialForm: FormState = {
patient_id: '',
dialysis_date: '',
start_time: '',
end_time: '',
dialysis_type: 'HD',
dialysis_duration: '',
blood_flow_rate: '',
dry_weight: '',
pre_weight: '',
post_weight: '',
pre_bp_systolic: '',
pre_bp_diastolic: '',
post_bp_systolic: '',
post_bp_diastolic: '',
pre_heart_rate: '',
post_heart_rate: '',
ultrafiltration_volume: '',
complication_notes: '',
};
export default function DialysisCreate() {
const router = useRouter();
const id = router.params.id || '';
const version = router.params.version ? Number(router.params.version) : 0;
const patientIdFromRoute = router.params.patientId || '';
const isEdit = !!id;
const modeClass = useElderClass();
const [form, setForm] = useState<FormState>({ ...initialForm, patient_id: patientIdFromRoute });
const [loading, setLoading] = useState(isEdit);
const [submitting, setSubmitting] = useState(false);
useEffect(() => {
if (isEdit && id) loadRecord();
}, [id]);
const loadRecord = async () => {
setLoading(true);
try {
const r = await doctorApi.getDialysisRecord(id);
setForm({
patient_id: r.patient_id,
dialysis_date: r.dialysis_date || '',
start_time: r.start_time || '',
end_time: r.end_time || '',
dialysis_type: r.dialysis_type || 'HD',
dialysis_duration: r.dialysis_duration != null ? String(r.dialysis_duration) : '',
blood_flow_rate: r.blood_flow_rate != null ? String(r.blood_flow_rate) : '',
dry_weight: r.dry_weight != null ? String(r.dry_weight) : '',
pre_weight: r.pre_weight != null ? String(r.pre_weight) : '',
post_weight: r.post_weight != null ? String(r.post_weight) : '',
pre_bp_systolic: r.pre_bp_systolic != null ? String(r.pre_bp_systolic) : '',
pre_bp_diastolic: r.pre_bp_diastolic != null ? String(r.pre_bp_diastolic) : '',
post_bp_systolic: r.post_bp_systolic != null ? String(r.post_bp_systolic) : '',
post_bp_diastolic: r.post_bp_diastolic != null ? String(r.post_bp_diastolic) : '',
pre_heart_rate: r.pre_heart_rate != null ? String(r.pre_heart_rate) : '',
post_heart_rate: r.post_heart_rate != null ? String(r.post_heart_rate) : '',
ultrafiltration_volume: r.ultrafiltration_volume != null ? String(r.ultrafiltration_volume) : '',
complication_notes: r.complication_notes || '',
});
} catch {
Taro.showToast({ title: '加载失败', icon: 'none' });
} finally {
setLoading(false);
}
};
const updateField = (key: keyof FormState, value: string) => {
setForm((prev) => ({ ...prev, [key]: value }));
};
const handleSubmit = async () => {
if (!form.dialysis_date) {
Taro.showToast({ title: '请选择透析日期', icon: 'none' });
return;
}
if (!form.patient_id) {
Taro.showToast({ title: '缺少患者信息', icon: 'none' });
return;
}
setSubmitting(true);
const num = (v: string) => v ? Number(v) : undefined;
const payload = {
patient_id: form.patient_id,
dialysis_date: form.dialysis_date,
start_time: form.start_time || undefined,
end_time: form.end_time || undefined,
dialysis_type: form.dialysis_type,
dialysis_duration: num(form.dialysis_duration),
blood_flow_rate: num(form.blood_flow_rate),
dry_weight: num(form.dry_weight),
pre_weight: num(form.pre_weight),
post_weight: num(form.post_weight),
pre_bp_systolic: num(form.pre_bp_systolic),
pre_bp_diastolic: num(form.pre_bp_diastolic),
post_bp_systolic: num(form.post_bp_systolic),
post_bp_diastolic: num(form.post_bp_diastolic),
pre_heart_rate: num(form.pre_heart_rate),
post_heart_rate: num(form.post_heart_rate),
ultrafiltration_volume: num(form.ultrafiltration_volume),
complication_notes: form.complication_notes || undefined,
};
try {
if (isEdit) {
const { patient_id, ...updateData } = payload;
await doctorApi.updateDialysisRecord(id, updateData, version);
Taro.showToast({ title: '更新成功', icon: 'success' });
} else {
await doctorApi.createDialysisRecord(payload);
Taro.showToast({ title: '创建成功', icon: 'success' });
}
setTimeout(() => Taro.navigateBack(), 1000);
} catch {
Taro.showToast({ title: isEdit ? '更新失败' : '创建失败', icon: 'none' });
} finally {
setSubmitting(false);
}
};
if (loading) return <Loading />;
const InputField = ({ label, field, placeholder, type = 'digit' }: {
label: string; field: keyof FormState; placeholder: string; type?: string;
}) => (
<View className='form-row'>
<Text className='form-label'>{label}</Text>
<Input
className='form-input'
type={type as any}
placeholder={placeholder}
value={form[field]}
onInput={(e) => updateField(field, e.detail.value)}
/>
</View>
);
return (
<ScrollView scrollY className={`create-page ${modeClass}`}>
<View className='section'>
<Text className='section-title'></Text>
<View className='form-row'>
<Text className='form-label'></Text>
<Picker mode='date' value={form.dialysis_date} onChange={(e) => updateField('dialysis_date', e.detail.value)}>
<Text className={`form-value ${!form.dialysis_date ? 'placeholder' : ''}`}>
{form.dialysis_date || '请选择日期'}
</Text>
</Picker>
</View>
<View className='form-row'>
<Text className='form-label'></Text>
<Picker mode='time' value={form.start_time} onChange={(e) => updateField('start_time', e.detail.value)}>
<Text className={`form-value ${!form.start_time ? 'placeholder' : ''}`}>
{form.start_time || '请选择时间'}
</Text>
</Picker>
</View>
<View className='form-row'>
<Text className='form-label'></Text>
<Picker mode='time' value={form.end_time} onChange={(e) => updateField('end_time', e.detail.value)}>
<Text className={`form-value ${!form.end_time ? 'placeholder' : ''}`}>
{form.end_time || '请选择时间'}
</Text>
</Picker>
</View>
<View className='form-row'>
<Text className='form-label'></Text>
<Picker mode='selector' range={DIALYSIS_TYPES} value={DIALYSIS_TYPES.indexOf(form.dialysis_type)} onChange={(e) => updateField('dialysis_type', DIALYSIS_TYPES[Number(e.detail.value)])}>
<Text className='form-value'>{form.dialysis_type}</Text>
</Picker>
</View>
<InputField label='透析时长' field='dialysis_duration' placeholder='分钟' type='number' />
<InputField label='血流速' field='blood_flow_rate' placeholder='ml/min' type='number' />
</View>
<View className='section'>
<Text className='section-title'></Text>
<InputField label='干体重' field='dry_weight' placeholder='kg' />
<InputField label='透前体重' field='pre_weight' placeholder='kg' />
<InputField label='透后体重' field='post_weight' placeholder='kg' />
</View>
<View className='section'>
<Text className='section-title'></Text>
<InputField label='透前收缩压' field='pre_bp_systolic' placeholder='mmHg' type='number' />
<InputField label='透前舒张压' field='pre_bp_diastolic' placeholder='mmHg' type='number' />
<InputField label='透后收缩压' field='post_bp_systolic' placeholder='mmHg' type='number' />
<InputField label='透后舒张压' field='post_bp_diastolic' placeholder='mmHg' type='number' />
<InputField label='透前心率' field='pre_heart_rate' placeholder='bpm' type='number' />
<InputField label='透后心率' field='post_heart_rate' placeholder='bpm' type='number' />
</View>
<View className='section'>
<Text className='section-title'></Text>
<InputField label='超滤量' field='ultrafiltration_volume' placeholder='ml' type='number' />
<View className='form-row form-row--textarea'>
<Text className='form-label'></Text>
<Textarea
className='form-textarea'
placeholder='请输入...'
value={form.complication_notes}
onInput={(e) => updateField('complication_notes', e.detail.value)}
maxlength={500}
/>
</View>
</View>
<View className={`submit-btn ${submitting ? 'submit-btn--disabled' : ''}`} onClick={handleSubmit}>
<Text className='submit-btn__text'>{submitting ? '提交中...' : isEdit ? '更新记录' : '创建记录'}</Text>
</View>
</ScrollView>
);
}

View File

@@ -0,0 +1,156 @@
@import '../../../../styles/variables.scss';
@import '../../../../styles/mixins.scss';
.dialysis-detail {
min-height: 100vh;
background: $bg;
padding: 24px;
padding-bottom: 200px;
}
.section {
background: $card;
border-radius: $r;
padding: 24px;
margin-bottom: 16px;
box-shadow: $shadow-sm;
}
.section-title {
font-size: var(--tk-font-body-lg);
font-weight: bold;
color: $tx;
display: block;
margin-bottom: 12px;
}
.record-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 8px;
}
.record-header__title {
font-size: var(--tk-font-num-lg);
font-weight: bold;
color: $tx;
font-variant-numeric: tabular-nums;
}
.record-header__status {
display: inline-block;
padding: 4px 12px;
border-radius: 8px;
font-size: var(--tk-font-body);
background: $bd-l;
color: $tx3;
&--completed {
background: $pri-l;
color: $pri;
}
&--reviewed {
background: $acc-l;
color: $acc;
}
}
.record-sub {
font-size: var(--tk-font-h1);
color: $tx2;
display: block;
}
.review-info {
font-size: var(--tk-font-h2);
color: $tx3;
display: block;
margin-top: 8px;
font-variant-numeric: tabular-nums;
}
.detail-row {
display: flex;
justify-content: space-between;
padding: 10px 0;
border-bottom: 1px solid $bd-l;
&:last-child {
border-bottom: none;
}
}
.detail-label {
font-size: var(--tk-font-h1);
color: $tx2;
}
.detail-value {
font-size: var(--tk-font-h1);
color: $tx;
text-align: right;
flex: 1;
margin-left: 24px;
font-variant-numeric: tabular-nums;
}
.error-text {
text-align: center;
padding: 120px 0;
font-size: var(--tk-font-body-lg);
color: $tx3;
}
.actions {
display: flex;
flex-direction: column;
gap: 12px;
padding: 16px 0;
}
.action-btn {
border-radius: $r-sm;
padding: 20px;
text-align: center;
&--primary {
background: $pri;
.action-btn__text {
color: #fff;
}
&:active {
background: $pri-d;
}
}
&--secondary {
background: $card;
border: 1px solid $bd;
.action-btn__text {
color: $pri;
}
}
&--danger {
background: $card;
border: 1px solid $dan;
.action-btn__text {
color: $dan;
}
}
&--disabled {
opacity: 0.5;
}
}
.action-btn__text {
font-size: var(--tk-font-body-lg);
font-weight: 500;
}

View File

@@ -0,0 +1,174 @@
import { useState, useEffect } from 'react';
import { View, Text, ScrollView } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import * as doctorApi from '@/services/doctor';
import Loading from '@/components/Loading';
import { useElderClass } from '../../../../hooks/useElderClass';
import './index.scss';
export default function DialysisDetail() {
const router = useRouter();
const id = router.params.id || '';
const modeClass = useElderClass();
const [record, setRecord] = useState<doctorApi.DialysisRecord | null>(null);
const [loading, setLoading] = useState(true);
const [submitting, setSubmitting] = useState(false);
useEffect(() => {
if (id) loadRecord();
}, [id]);
const loadRecord = async () => {
setLoading(true);
try {
const r = await doctorApi.getDialysisRecord(id);
setRecord(r);
} catch {
Taro.showToast({ title: '加载失败', icon: 'none' });
} finally {
setLoading(false);
}
};
const handleReview = async () => {
if (!record) return;
setSubmitting(true);
try {
const updated = await doctorApi.reviewDialysisRecord(id, record.version);
setRecord(updated);
Taro.showToast({ title: '审核完成', icon: 'success' });
} catch {
Taro.showToast({ title: '审核失败', icon: 'none' });
} finally {
setSubmitting(false);
}
};
const handleComplete = async () => {
if (!record) return;
setSubmitting(true);
try {
const updated = await doctorApi.updateDialysisRecord(id, { status: 'completed' }, record.version);
setRecord(updated);
Taro.showToast({ title: '已标记完成', icon: 'success' });
} catch {
Taro.showToast({ title: '操作失败', icon: 'none' });
} finally {
setSubmitting(false);
}
};
const handleDelete = async () => {
if (!record) return;
const { confirm } = await Taro.showModal({
title: '确认删除',
content: '删除后不可恢复,确定要删除这条记录吗?',
});
if (!confirm) return;
setSubmitting(true);
try {
await doctorApi.deleteDialysisRecord(id, record.version);
Taro.showToast({ title: '已删除', icon: 'success' });
setTimeout(() => Taro.navigateBack(), 1000);
} catch {
Taro.showToast({ title: '删除失败', icon: 'none' });
setSubmitting(false);
}
};
const Row = ({ label, value, unit }: { label: string; value?: string | number | null; unit?: string }) => {
if (value == null) return null;
return (
<View className='detail-row'>
<Text className='detail-label'>{label}</Text>
<Text className='detail-value'>{value}{unit || ''}</Text>
</View>
);
};
if (loading) return <Loading />;
if (!record) return <View className={`error-text ${modeClass}`}><Text></Text></View>;
const canComplete = record.status === 'draft';
const canReview = record.status === 'completed';
return (
<ScrollView scrollY className={`dialysis-detail ${modeClass}`}>
{/* 状态头部 */}
<View className='section'>
<View className='record-header'>
<Text className='record-header__title'>{record.dialysis_date}</Text>
<Text className={`record-header__status record-header__status--${record.status}`}>
{record.status === 'draft' ? '草稿' : record.status === 'completed' ? '已完成' : '已审核'}
</Text>
</View>
<Text className='record-sub'>
{(record.dialysis_type === 'HD' ? '血液透析' : record.dialysis_type === 'HDF' ? '血液透析滤过' : record.dialysis_type === 'HF' ? '血液滤过' : record.dialysis_type)}
</Text>
{record.reviewed_at && <Text className='review-info'> {record.reviewed_at}</Text>}
</View>
{/* 基本信息 */}
<View className='section'>
<Text className='section-title'></Text>
<Row label='透析日期' value={record.dialysis_date} />
<Row label='开始时间' value={record.start_time} />
<Row label='结束时间' value={record.end_time} />
<Row label='透析时长' value={record.dialysis_duration} unit=' 分钟' />
<Row label='血流速' value={record.blood_flow_rate} unit=' ml/min' />
<Row label='超滤量' value={record.ultrafiltration_volume} unit=' ml' />
</View>
{/* 体重与血压 */}
<View className='section'>
<Text className='section-title'></Text>
<Row label='干体重' value={record.dry_weight} unit=' kg' />
<Row label='透前体重' value={record.pre_weight} unit=' kg' />
<Row label='透后体重' value={record.post_weight} unit=' kg' />
{record.pre_bp_systolic != null && record.pre_bp_diastolic != null && (
<Row label='透前血压' value={`${record.pre_bp_systolic}/${record.pre_bp_diastolic}`} unit=' mmHg' />
)}
{record.post_bp_systolic != null && record.post_bp_diastolic != null && (
<Row label='透后血压' value={`${record.post_bp_systolic}/${record.post_bp_diastolic}`} unit=' mmHg' />
)}
<Row label='透前心率' value={record.pre_heart_rate} unit=' bpm' />
<Row label='透后心率' value={record.post_heart_rate} unit=' bpm' />
</View>
{/* 症状与并发症 */}
{(record.symptoms || record.complication_notes) && (
<View className='section'>
<Text className='section-title'></Text>
{record.symptoms && (
<Row label='症状' value={JSON.stringify(record.symptoms)} />
)}
<Row label='并发症备注' value={record.complication_notes} />
</View>
)}
{/* 操作按钮 */}
<View className='actions'>
{canComplete && (
<View className={`action-btn action-btn--primary ${submitting ? 'action-btn--disabled' : ''}`} onClick={handleComplete}>
<Text className='action-btn__text'>{submitting ? '处理中...' : '标记完成'}</Text>
</View>
)}
{canReview && (
<View className={`action-btn action-btn--primary ${submitting ? 'action-btn--disabled' : ''}`} onClick={handleReview}>
<Text className='action-btn__text'>{submitting ? '审核中...' : '确认审核'}</Text>
</View>
)}
{record.status === 'draft' && (
<View className='action-btn action-btn--secondary' onClick={() => Taro.navigateTo({
url: `/pages/doctor/dialysis/create/index?id=${id}&version=${record.version}`,
})}>
<Text className='action-btn__text'></Text>
</View>
)}
<View className='action-btn action-btn--danger' onClick={handleDelete}>
<Text className='action-btn__text'></Text>
</View>
</View>
</ScrollView>
);
}

View File

@@ -0,0 +1,194 @@
@import '../../../styles/variables.scss';
@import '../../../styles/mixins.scss';
.dialysis-page {
min-height: 100vh;
background: $bg;
padding-bottom: 120px;
}
.search-bar {
padding: 16px 24px;
background: $card;
}
.search-input {
background: $bg;
border-radius: $r-sm;
padding: 16px 20px;
font-size: var(--tk-font-body-lg);
color: $tx;
}
.tabs {
display: flex;
padding: 0 24px;
background: $card;
border-bottom: 1px solid $bd-l;
}
.tab {
flex: 1;
text-align: center;
padding: 20px 0;
position: relative;
&--active {
.tab-text {
color: $pri;
font-weight: bold;
}
&::after {
content: '';
position: absolute;
bottom: 0;
left: 25%;
right: 25%;
height: 4px;
background: $pri;
border-radius: 2px;
}
}
}
.tab-text {
font-size: var(--tk-font-h1);
color: $tx2;
}
.record-list {
padding: 16px 24px;
}
.record-count {
font-size: var(--tk-font-h2);
color: $tx3;
padding: 8px 0 16px;
}
.record-card {
background: $card;
border-radius: $r;
padding: 24px;
margin-bottom: 16px;
box-shadow: $shadow-sm;
&:active {
box-shadow: $shadow-md;
}
}
.record-card__header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
}
.type-tag {
display: inline-block;
padding: 4px 12px;
border-radius: 8px;
font-size: var(--tk-font-body);
font-weight: 600;
background: $pri-l;
color: $pri-d;
&--hdf {
background: $acc-l;
color: $acc;
}
&--hf {
background: $wrn-l;
color: $wrn;
}
}
.status-tag {
display: inline-block;
padding: 4px 12px;
border-radius: 8px;
font-size: var(--tk-font-body);
background: $bd-l;
color: $tx3;
&--completed {
background: $pri-l;
color: $pri;
}
&--reviewed {
background: $acc-l;
color: $acc;
}
}
.record-card__body {
display: flex;
flex-wrap: wrap;
gap: 12px;
}
.record-card__date {
font-size: var(--tk-font-h1);
color: $tx;
font-variant-numeric: tabular-nums;
}
.record-card__meta {
font-size: var(--tk-font-h2);
color: $tx2;
font-variant-numeric: tabular-nums;
}
.pagination {
display: flex;
justify-content: center;
align-items: center;
padding: 16px 0;
gap: 24px;
}
.page-btn {
padding: 12px 24px;
background: $card;
border-radius: $r-sm;
font-size: var(--tk-font-h1);
color: $pri;
&--disabled {
opacity: 0.4;
}
}
.page-info {
font-size: var(--tk-font-h2);
color: $tx2;
}
.fab {
position: fixed;
right: 32px;
bottom: 120px;
width: 96px;
height: 96px;
border-radius: 48px;
background: $pri;
display: flex;
align-items: center;
justify-content: center;
box-shadow: $shadow-md;
z-index: 10;
&:active {
background: $pri-d;
}
}
.fab-text {
font-size: var(--tk-font-hero);
color: #fff;
font-weight: bold;
}

View File

@@ -0,0 +1,171 @@
import { useState, useEffect } from 'react';
import { View, Text, Input, ScrollView } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import * as doctorApi from '@/services/doctor';
import Loading from '@/components/Loading';
import EmptyState from '@/components/EmptyState';
import { useElderClass } from '../../../hooks/useElderClass';
import './index.scss';
const TABS = [
{ key: '', label: '全部' },
{ key: 'draft', label: '草稿' },
{ key: 'completed', label: '已完成' },
{ key: 'reviewed', label: '已审核' },
];
const TYPE_MAP: Record<string, string> = { HD: 'HD', HDF: 'HDF', HF: 'HF' };
export default function DialysisList() {
const router = useRouter();
const patientId = router.params.patientId || '';
const modeClass = useElderClass();
const [searchPatient, setSearchPatient] = useState('');
const [currentPatientId, setCurrentPatientId] = useState(patientId);
const [activeTab, setActiveTab] = useState('');
const [records, setRecords] = useState<doctorApi.DialysisRecord[]>([]);
const [loading, setLoading] = useState(false);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1);
useEffect(() => {
if (currentPatientId) loadRecords(1);
}, [currentPatientId, activeTab]);
const loadRecords = async (p: number) => {
setLoading(true);
try {
const res = await doctorApi.listDialysisRecords(currentPatientId, { page: p, page_size: 20 });
setRecords(res.data || []);
setTotal(res.total || 0);
setPage(p);
} catch {
Taro.showToast({ title: '加载失败', icon: 'none' });
} finally {
setLoading(false);
}
};
const handleSearch = async () => {
if (!searchPatient.trim()) return;
setLoading(true);
try {
const res = await doctorApi.listPatients({ search: searchPatient.trim(), page: 1, page_size: 1 });
if (res.data && res.data.length > 0) {
setCurrentPatientId(res.data[0].id);
Taro.setNavigationBarTitle({ title: res.data[0].name + '的透析记录' });
} else {
Taro.showToast({ title: '未找到患者', icon: 'none' });
}
} catch {
Taro.showToast({ title: '搜索失败', icon: 'none' });
} finally {
setLoading(false);
}
};
const handleTab = (key: string) => {
setActiveTab(key);
setPage(1);
};
const filtered = activeTab ? records.filter((r) => r.status === activeTab) : records;
if (loading && records.length === 0) return <Loading />;
return (
<ScrollView scrollY className={`dialysis-page ${modeClass}`}>
{!patientId && (
<View className='search-bar'>
<Input
className='search-input'
placeholder='搜索患者姓名'
value={searchPatient}
onInput={(e) => setSearchPatient(e.detail.value)}
confirmType='search'
onConfirm={handleSearch}
/>
</View>
)}
<View className='tabs'>
{TABS.map((t) => (
<View
key={t.key}
className={`tab ${activeTab === t.key ? 'tab--active' : ''}`}
onClick={() => handleTab(t.key)}
>
<Text className='tab-text'>{t.label}</Text>
</View>
))}
</View>
{!currentPatientId ? (
<EmptyState text='请搜索并选择患者' />
) : filtered.length === 0 ? (
<EmptyState text='暂无透析记录' />
) : (
<View className='record-list'>
<View className='record-count'><Text> {total} </Text></View>
{filtered.map((r) => (
<View
key={r.id}
className='record-card'
onClick={() => Taro.navigateTo({
url: `/pages/doctor/dialysis/detail/index?id=${r.id}`,
})}
>
<View className='record-card__header'>
<Text className={`type-tag type-tag--${(r.dialysis_type || 'hd').toLowerCase()}`}>
{TYPE_MAP[r.dialysis_type] || r.dialysis_type}
</Text>
<Text className={`status-tag status-tag--${r.status}`}>
{r.status === 'draft' ? '草稿' : r.status === 'completed' ? '已完成' : '已审核'}
</Text>
</View>
<View className='record-card__body'>
<Text className='record-card__date'>{r.dialysis_date}</Text>
{r.dialysis_duration != null && (
<Text className='record-card__meta'> {r.dialysis_duration}</Text>
)}
{r.ultrafiltration_volume != null && (
<Text className='record-card__meta'> {r.ultrafiltration_volume}ml</Text>
)}
</View>
</View>
))}
{total > 20 && (
<View className='pagination'>
<View
className={`page-btn ${page <= 1 ? 'page-btn--disabled' : ''}`}
onClick={() => page > 1 && loadRecords(page - 1)}
>
<Text></Text>
</View>
<Text className='page-info'>{page} / {Math.ceil(total / 20)}</Text>
<View
className={`page-btn ${page * 20 >= total ? 'page-btn--disabled' : ''}`}
onClick={() => page * 20 < total && loadRecords(page + 1)}
>
<Text></Text>
</View>
</View>
)}
</View>
)}
<View
className='fab'
onClick={() => {
if (!currentPatientId) {
Taro.showToast({ title: '请先选择患者', icon: 'none' });
return;
}
Taro.navigateTo({ url: `/pages/doctor/dialysis/create/index?patientId=${currentPatientId}` });
}}
>
<Text className='fab-text'>+</Text>
</View>
</ScrollView>
);
}

View File

@@ -28,13 +28,13 @@
&__title {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 30px;
font-size: var(--tk-font-num);
font-weight: 700;
color: $tx;
}
&__status {
font-size: 24px;
font-size: var(--tk-font-h2);
padding: 6px 16px;
border-radius: $r;
font-weight: 500;
@@ -60,12 +60,12 @@
}
.info-label {
font-size: 22px;
font-size: var(--tk-font-body);
color: $tx3;
}
.info-value {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx;
font-weight: 500;
}
@@ -77,14 +77,14 @@
border-radius: $r;
&__label {
font-size: 22px;
font-size: var(--tk-font-body);
color: $tx2;
display: block;
margin-bottom: 8px;
}
&__text {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx;
line-height: 1.6;
}
@@ -99,14 +99,14 @@
}
&__date {
font-size: 22px;
font-size: var(--tk-font-body);
color: $tx3;
display: block;
margin-bottom: 8px;
}
&__text {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx;
display: block;
margin-bottom: 4px;
@@ -121,7 +121,7 @@
border-radius: $r;
margin-bottom: 24px;
color: $card;
font-size: 28px;
font-size: var(--tk-font-body-lg);
font-weight: 500;
}
@@ -130,7 +130,7 @@
}
.form-label {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx2;
font-weight: 500;
display: block;
@@ -143,7 +143,7 @@
background: $bd-l;
border-radius: $r;
padding: 16px 20px;
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx;
box-sizing: border-box;
line-height: 1.6;
@@ -154,7 +154,7 @@
padding: 16px 20px;
background: $bd-l;
border-radius: $r;
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx;
box-sizing: border-box;
}
@@ -171,7 +171,7 @@
}
&__text {
font-size: 28px;
font-size: var(--tk-font-body-lg);
color: $card;
font-weight: 600;
}
@@ -181,5 +181,5 @@
text-align: center;
padding: 80px 32px;
color: $tx3;
font-size: 28px;
font-size: var(--tk-font-body-lg);
}

View File

@@ -3,6 +3,7 @@ import { View, Text, Textarea, ScrollView } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import * as doctorApi from '@/services/doctor';
import Loading from '@/components/Loading';
import { useElderClass } from '../../../../hooks/useElderClass';
import './index.scss';
const STATUS_LABELS: Record<string, string> = {
@@ -16,6 +17,7 @@ const STATUS_LABELS: Record<string, string> = {
export default function FollowUpDetail() {
const router = useRouter();
const taskId = router.params.id || '';
const modeClass = useElderClass();
const [task, setTask] = useState<doctorApi.FollowUpTask | null>(null);
const [records, setRecords] = useState<doctorApi.FollowUpRecord[]>([]);
const [loading, setLoading] = useState(true);
@@ -87,12 +89,12 @@ export default function FollowUpDetail() {
const formatDate = (d: string) => new Date(d).toLocaleDateString('zh-CN');
if (loading) return <Loading />;
if (!task) return <View className='error-text'><Text></Text></View>;
if (!task) return <View className={`error-text ${modeClass}`}><Text></Text></View>;
const canSubmit = task.status === 'in_progress' || task.status === 'pending' || task.status === 'overdue';
return (
<ScrollView scrollY className='followup-detail'>
<ScrollView scrollY className={`followup-detail ${modeClass}`}>
<View className='section'>
<View className='task-header'>
<Text className='task-header__title'>访</Text>

View File

@@ -18,7 +18,7 @@
.tab {
display: inline-block;
padding: 24px 16px;
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx2;
position: relative;
flex-shrink: 0;
@@ -44,7 +44,7 @@
padding: 20px 28px;
text {
font-size: 24px;
font-size: var(--tk-font-h2);
color: $tx3;
}
}
@@ -75,19 +75,19 @@
&__type {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 28px;
font-size: var(--tk-font-body-lg);
font-weight: 600;
color: $tx;
}
&__status {
@include tag(transparent, $tx2);
font-size: 22px;
font-size: var(--tk-font-body);
font-weight: 500;
}
&__patient {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx2;
display: block;
margin-bottom: 8px;
@@ -99,7 +99,7 @@
}
&__date {
font-size: 24px;
font-size: var(--tk-font-h2);
color: $tx3;
}
}

View File

@@ -4,16 +4,10 @@ import Taro, { useRouter } from '@tarojs/taro';
import * as doctorApi from '@/services/doctor';
import Loading from '@/components/Loading';
import EmptyState from '@/components/EmptyState';
import { useElderClass } from '../../../hooks/useElderClass';
import { getStatusInlineStyle, getStatusLabel } from '@/utils/statusTag';
import './index.scss';
const STATUS_MAP: Record<string, { label: string; color: string }> = {
pending: { label: '待处理', color: '#f59e0b' },
in_progress: { label: '进行中', color: '#0891b2' },
completed: { label: '已完成', color: '#10b981' },
overdue: { label: '已逾期', color: '#ef4444' },
cancelled: { label: '已取消', color: '#94a3b8' },
};
const TABS = [
{ key: '', label: '全部' },
{ key: 'pending', label: '待处理' },
@@ -25,6 +19,7 @@ const TABS = [
export default function FollowUpList() {
const router = useRouter();
const patientId = router.params.patientId || '';
const modeClass = useElderClass();
const [tasks, setTasks] = useState<doctorApi.FollowUpTask[]>([]);
const [activeTab, setActiveTab] = useState('');
const [loading, setLoading] = useState(true);
@@ -69,7 +64,7 @@ export default function FollowUpList() {
if (loading && tasks.length === 0) return <Loading />;
return (
<ScrollView scrollY className='followup-page'>
<ScrollView scrollY className={`followup-page ${modeClass}`}>
<View className='tabs'>
{TABS.map((t) => (
<View
@@ -91,7 +86,6 @@ export default function FollowUpList() {
) : (
<View className='task-list'>
{tasks.map((task) => {
const st = STATUS_MAP[task.status] || { label: task.status, color: '#94a3b8' };
return (
<View
key={task.id}
@@ -100,8 +94,8 @@ export default function FollowUpList() {
>
<View className='task-card__header'>
<Text className='task-card__type'>{getTypeLabel(task.follow_up_type)}</Text>
<View className='task-card__status' style={`background: ${st.color}20; color: ${st.color}`}>
<Text>{st.label}</Text>
<View className='task-card__status' style={getStatusInlineStyle(task.status)}>
<Text>{getStatusLabel(task.status)}</Text>
</View>
</View>
<Text className='task-card__patient'>{task.patient_name || '未知患者'}</Text>

View File

@@ -13,19 +13,18 @@
&__title {
@include section-title;
font-size: 40px;
margin-bottom: 12px;
}
&__greeting {
font-size: 28px;
font-size: var(--tk-font-h2);
color: $tx2;
display: block;
margin-bottom: 8px;
}
&__date {
font-size: 24px;
font-size: var(--tk-font-h2);
color: $tx3;
}
@@ -34,34 +33,34 @@
align-items: center;
margin: 16px 24px;
padding: 16px 20px;
background: #FEF2F2;
background: $dan-l;
border-radius: $r;
border-left: 4px solid #EF4444;
border-left: 4px solid $dan;
}
&__alert-icon {
width: 36px;
height: 36px;
border-radius: 50%;
background: #EF4444;
background: $dan;
color: #fff;
text-align: center;
line-height: 36px;
font-weight: bold;
font-size: 22px;
font-size: var(--tk-font-body);
margin-right: 12px;
flex-shrink: 0;
}
&__alert-text {
flex: 1;
font-size: 26px;
color: #991B1B;
font-size: var(--tk-font-h1);
color: $dan;
}
&__alert-link {
font-size: 24px;
color: #EF4444;
font-size: var(--tk-font-h2);
color: $dan;
flex-shrink: 0;
}
@@ -70,11 +69,11 @@
}
&__search-input {
background: #F1F5F9;
background: $surface-alt;
border-radius: $r;
padding: 16px 20px;
font-size: 26px;
color: #94A3B8;
font-size: var(--tk-font-h1);
color: $tx3;
}
&__section {
@@ -113,14 +112,14 @@
background: $pri-l;
color: $pri;
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 28px;
font-size: var(--tk-font-body-lg);
font-weight: 700;
margin-bottom: 8px;
}
&__card-num {
@include serif-number;
font-size: 48px;
font-size: var(--tk-font-hero);
font-weight: 700;
color: $tx;
display: block;
@@ -128,7 +127,7 @@
}
&__card-label {
font-size: 24px;
font-size: var(--tk-font-h2);
color: $tx2;
}
@@ -145,7 +144,7 @@
&__logout {
color: $dan;
font-size: 28px;
font-size: var(--tk-font-h2);
padding: 16px 48px;
display: inline-block;
}
@@ -172,13 +171,34 @@
background: $acc-l;
color: $acc;
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 28px;
font-size: var(--tk-font-body-lg);
font-weight: 700;
}
&__icon-wrap {
position: relative;
display: inline-flex;
margin-bottom: 8px;
}
&__badge {
position: absolute;
top: -6px;
right: -12px;
min-width: 32px;
height: 32px;
line-height: 32px;
text-align: center;
background: $dan;
color: #fff;
font-size: var(--tk-font-body-sm);
font-weight: 700;
border-radius: $r-pill;
padding: 0 6px;
}
&__label {
font-size: 24px;
font-size: var(--tk-font-h2);
color: $tx2;
display: block;
}

View File

@@ -1,7 +1,8 @@
import { useState, useEffect } from 'react';
import { useState, useEffect, useMemo } from 'react';
import { View, Text, Input, ScrollView } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { useAuthStore } from '@/stores/auth';
import { useElderClass } from '../../hooks/useElderClass';
import * as doctorApi from '@/services/doctor';
import Loading from '@/components/Loading';
import './index.scss';
@@ -11,34 +12,67 @@ interface CardConfig {
label: string;
initial: string;
route: string;
roles?: string[];
}
const CARDS: CardConfig[] = [
const ALL_CARDS: CardConfig[] = [
{ key: 'total_patients', label: '我的患者', initial: '患', route: '/pages/doctor/patients/index' },
{ key: 'unread_messages', label: '未读消息', initial: '消', route: '/pages/doctor/consultation/index' },
{ key: 'pending_follow_ups', label: '待处理随访', initial: '随', route: '/pages/doctor/followup/index' },
{ key: 'today_consultations', label: '今日咨询', initial: '诊', route: '/pages/doctor/consultation/index' },
{ key: 'pending_follow_ups', label: '待处理随访', initial: '随', route: '/pages/doctor/followup/index', roles: ['doctor', 'nurse', 'health_manager'] },
{ key: 'today_consultations', label: '今日咨询', initial: '诊', route: '/pages/doctor/consultation/index', roles: ['doctor', 'health_manager'] },
];
const HEALTH_CARDS: CardConfig[] = [
{ key: 'pending_dialysis_review', label: '待审透析', initial: '', route: '/pages/doctor/patients/index' },
{ key: 'pending_lab_review', label: '待审化验', initial: '化', route: '/pages/doctor/report/index' },
const ALL_HEALTH_CARDS: CardConfig[] = [
{ key: 'pending_lab_review', label: '待审化验', initial: '', route: '/pages/doctor/report/index', roles: ['doctor'] },
{ key: 'today_appointments', label: '今日预约', initial: '约', route: '/pages/doctor/patients/index' },
];
const QUICK_ACTIONS = [
{ label: '化验审核', initial: '审', route: '/pages/doctor/report/index' },
{ label: '患者查询', initial: '查', route: '/pages/doctor/patients/index' },
{ label: '随访记录', initial: '随', route: '/pages/doctor/followup/index' },
{ label: '排班查看', initial: '排', route: '/pages/doctor/patients/index' },
interface QuickAction {
label: string;
initial: string;
route: string;
roles: string[];
}
const ALL_QUICK_ACTIONS: QuickAction[] = [
{ label: '化验审核', initial: '审', route: '/pages/doctor/report/index', roles: ['doctor'] },
{ label: '患者查询', initial: '查', route: '/pages/doctor/patients/index', roles: ['doctor', 'nurse', 'health_manager'] },
{ label: '随访记录', initial: '随', route: '/pages/doctor/followup/index', roles: ['doctor', 'nurse', 'health_manager'] },
{ label: '告警中心', initial: '警', route: '/pages/doctor/alerts/index', roles: ['doctor', 'nurse', 'health_manager'] },
{ label: '透析管理', initial: '透', route: '/pages/doctor/dialysis/index', roles: ['doctor'] },
{ label: '处方管理', initial: '方', route: '/pages/doctor/prescription/index', roles: ['doctor'] },
{ label: '行动收件箱', initial: '行', route: '/pages/doctor/action-inbox/index', roles: ['doctor', 'nurse', 'health_manager'] },
];
const ROLE_LABELS: Record<string, string> = {
doctor: '医生',
nurse: '护士',
health_manager: '健康管理师',
admin: '管理员',
operator: '运营',
};
export default function DoctorHome() {
const { user, logout } = useAuthStore();
const { user, logout, roles } = useAuthStore();
const modeClass = useElderClass();
const [dashboard, setDashboard] = useState<doctorApi.DoctorDashboard | null>(null);
const [alertCount, setAlertCount] = useState(0);
const [loading, setLoading] = useState(true);
const hasRole = (allowed: string[] | undefined) => {
if (!allowed) return true;
return roles.some((r) => r === 'admin' || allowed.includes(r));
};
const cards = useMemo(() => ALL_CARDS.filter((c) => hasRole(c.roles)), [roles]);
const healthCards = useMemo(() => ALL_HEALTH_CARDS.filter((c) => hasRole(c.roles)), [roles]);
const quickActions = useMemo(() => ALL_QUICK_ACTIONS.filter((a) => hasRole(a.roles)), [roles]);
const roleLabel = useMemo(() => {
const primary = roles.find((r) => r !== 'admin');
return primary ? (ROLE_LABELS[primary] || primary) : '医护';
}, [roles]);
useEffect(() => {
loadDashboard();
}, []);
@@ -73,11 +107,11 @@ export default function DoctorHome() {
if (loading) return <Loading />;
return (
<ScrollView scrollY className='doctor-home'>
<ScrollView scrollY className={`doctor-home ${modeClass}`}>
<View className='doctor-home__header'>
<Text className='doctor-home__title'></Text>
<Text className='doctor-home__greeting'>
{user?.display_name || user?.username || '医生'}
{user?.display_name || user?.username || roleLabel}
</Text>
<Text className='doctor-home__date'>
{new Date().toLocaleDateString('zh-CN', { month: 'long', day: 'numeric', weekday: 'long' })}
@@ -88,7 +122,7 @@ export default function DoctorHome() {
<View className='doctor-home__alert'>
<Text className='doctor-home__alert-icon'>!</Text>
<Text className='doctor-home__alert-text'>{alertCount} </Text>
<Text className='doctor-home__alert-link' onClick={() => Taro.navigateTo({ url: '/pages/doctor/patients/index' })}> </Text>
<Text className='doctor-home__alert-link' onClick={() => Taro.navigateTo({ url: '/pages/doctor/alerts/index' })}> </Text>
</View>
)}
@@ -103,7 +137,7 @@ export default function DoctorHome() {
<View className='doctor-home__section'>
<Text className='doctor-home__section-title'></Text>
<View className='doctor-home__grid'>
{CARDS.map((card) => (
{cards.map((card) => (
<View
key={card.key}
className='doctor-home__card'
@@ -117,10 +151,10 @@ export default function DoctorHome() {
</View>
</View>
<View className='doctor-home__section'>
{healthCards.length > 0 && (<View className='doctor-home__section'>
<Text className='doctor-home__section-title'></Text>
<View className='doctor-home__grid'>
{HEALTH_CARDS.map((card) => (
{healthCards.map((card) => (
<View
key={card.key}
className='doctor-home__card'
@@ -132,18 +166,23 @@ export default function DoctorHome() {
</View>
))}
</View>
</View>
</View>)}
<View className='doctor-home__section'>
<Text className='doctor-home__section-title'></Text>
<View className='doctor-home__quick-actions'>
{QUICK_ACTIONS.map((action) => (
{quickActions.map((action) => (
<View
key={action.route}
className='quick-action'
onClick={() => Taro.navigateTo({ url: action.route })}
>
<Text className='quick-action__initial'>{action.initial}</Text>
<View className='quick-action__icon-wrap'>
<Text className='quick-action__initial'>{action.initial}</Text>
{action.label === '告警中心' && alertCount > 0 && (
<Text className='quick-action__badge'>{alertCount > 99 ? '99+' : alertCount}</Text>
)}
</View>
<Text className='quick-action__label'>{action.label}</Text>
</View>
))}

View File

@@ -33,12 +33,12 @@
}
.info-label {
font-size: 22px;
font-size: var(--tk-font-body);
color: $tx3;
}
.info-value {
font-size: 28px;
font-size: var(--tk-font-body-lg);
color: $tx;
font-weight: 500;
}
@@ -51,7 +51,7 @@
}
.warning-label {
font-size: 22px;
font-size: var(--tk-font-body);
color: $wrn;
font-weight: 600;
display: block;
@@ -59,7 +59,7 @@
}
.warning-text {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $pri-d;
}
@@ -68,14 +68,14 @@
}
.info-block-label {
font-size: 22px;
font-size: var(--tk-font-body);
color: $tx3;
display: block;
margin-bottom: 8px;
}
.info-block-text {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx;
line-height: 1.6;
}
@@ -96,7 +96,7 @@
.vital-value {
@include serif-number;
font-size: 36px;
font-size: var(--tk-font-num-lg);
font-weight: 700;
color: $pri;
display: block;
@@ -104,7 +104,7 @@
}
.vital-label {
font-size: 22px;
font-size: var(--tk-font-body);
color: $tx2;
}
@@ -116,13 +116,13 @@
}
.stat-label {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx2;
}
.stat-value {
@include serif-number;
font-size: 26px;
font-size: var(--tk-font-h1);
font-weight: 600;
color: $tx;
@@ -151,18 +151,18 @@
}
&__type {
font-size: 26px;
font-size: var(--tk-font-h1);
font-weight: 500;
color: $tx;
}
&__date {
font-size: 24px;
font-size: var(--tk-font-h2);
color: $tx3;
}
&__abnormal {
font-size: 24px;
font-size: var(--tk-font-h2);
color: $dan;
font-weight: 500;
}
@@ -180,7 +180,7 @@
border-radius: $r;
background: $pri;
color: $card;
font-size: 26px;
font-size: var(--tk-font-h1);
font-weight: 500;
&:active {
@@ -196,5 +196,5 @@
text-align: center;
padding: 80px 32px;
color: $tx3;
font-size: 28px;
font-size: var(--tk-font-body-lg);
}

View File

@@ -3,11 +3,13 @@ import { View, Text, ScrollView } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import * as doctorApi from '@/services/doctor';
import Loading from '@/components/Loading';
import { useElderClass } from '../../../../hooks/useElderClass';
import './index.scss';
export default function PatientDetail() {
const router = useRouter();
const patientId = router.params.id || '';
const modeClass = useElderClass();
const [patient, setPatient] = useState<doctorApi.PatientDetail | null>(null);
const [summary, setSummary] = useState<doctorApi.HealthSummary | null>(null);
const [loading, setLoading] = useState(true);
@@ -40,10 +42,10 @@ export default function PatientDetail() {
};
if (loading) return <Loading />;
if (!patient) return <View className='error-text'><Text></Text></View>;
if (!patient) return <View className={`error-text ${modeClass}`}><Text></Text></View>;
return (
<ScrollView scrollY className='patient-detail'>
<ScrollView scrollY className={`patient-detail ${modeClass}`}>
{/* 基本信息 */}
<View className='section'>
<View className='section-header'>

View File

@@ -15,7 +15,7 @@
background: $card;
border-radius: $r;
padding: 20px 24px;
font-size: 28px;
font-size: var(--tk-font-body-lg);
width: 100%;
box-sizing: border-box;
box-shadow: $shadow-sm;
@@ -33,7 +33,7 @@
padding: 10px 24px;
border-radius: $r-pill;
background: $bd-l;
font-size: 24px;
font-size: var(--tk-font-h2);
color: $tx2;
margin-right: 16px;
@@ -47,7 +47,7 @@
margin-bottom: 16px;
text {
font-size: 24px;
font-size: var(--tk-font-h2);
color: $tx3;
}
}
@@ -75,14 +75,14 @@
}
&__name {
font-size: 30px;
font-size: var(--tk-font-num);
font-weight: 600;
color: $tx;
margin-right: 16px;
}
&__meta {
font-size: 24px;
font-size: var(--tk-font-h2);
color: $tx2;
}
@@ -112,7 +112,7 @@
background: $pri-l;
&__text {
font-size: 22px;
font-size: var(--tk-font-body);
}
}
@@ -124,7 +124,7 @@
margin-top: 32px;
&__btn {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $pri;
padding: 12px 24px;
@@ -134,7 +134,7 @@
}
&__info {
font-size: 24px;
font-size: var(--tk-font-h2);
color: $tx2;
}
}

View File

@@ -1,12 +1,14 @@
import { useState, useEffect } from 'react';
import { useState, useEffect, useRef } from 'react';
import { View, Text, Input, ScrollView } from '@tarojs/components';
import Taro from '@tarojs/taro';
import Taro, { usePullDownRefresh, useReachBottom } from '@tarojs/taro';
import * as doctorApi from '@/services/doctor';
import Loading from '@/components/Loading';
import EmptyState from '@/components/EmptyState';
import { useElderClass } from '../../../hooks/useElderClass';
import './index.scss';
export default function PatientList() {
const modeClass = useElderClass();
const [patients, setPatients] = useState<doctorApi.PatientItem[]>([]);
const [tags, setTags] = useState<doctorApi.PatientTag[]>([]);
const [activeTag, setActiveTag] = useState<string>('');
@@ -14,14 +16,15 @@ export default function PatientList() {
const [loading, setLoading] = useState(true);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1);
const loadingRef = useRef(false);
useEffect(() => {
loadTags();
}, []);
useEffect(() => {
loadPatients();
}, [page, activeTag]);
loadPatients(1, true);
}, [activeTag]);
const loadTags = async () => {
try {
@@ -30,32 +33,51 @@ export default function PatientList() {
} catch { /* ignore */ }
};
const loadPatients = async () => {
setLoading(true);
const loadPatients = async (pageNum: number, isRefresh = false) => {
if (loadingRef.current) return;
loadingRef.current = true;
if (isRefresh) setLoading(true);
try {
const res = await doctorApi.listPatients({
page,
page: pageNum,
page_size: 20,
search: search || undefined,
tag_id: activeTag || undefined,
});
setPatients(res.data || []);
const list = res.data || [];
if (isRefresh) {
setPatients(list);
} else {
setPatients((prev) => [...prev, ...list]);
}
setTotal(res.total || 0);
setPage(pageNum);
} catch {
Taro.showToast({ title: '加载失败', icon: 'none' });
} finally {
setLoading(false);
loadingRef.current = false;
}
};
usePullDownRefresh(() => {
loadPatients(1, true).finally(() => {
Taro.stopPullDownRefresh();
});
});
useReachBottom(() => {
if (!loading && patients.length < total) {
loadPatients(page + 1);
}
});
const handleSearch = () => {
setPage(1);
loadPatients();
loadPatients(1, true);
};
const handleTagFilter = (tagId: string) => {
setActiveTag(tagId === activeTag ? '' : tagId);
setPage(1);
};
const getGenderLabel = (gender?: string) => {
@@ -78,7 +100,7 @@ export default function PatientList() {
if (loading && patients.length === 0) return <Loading />;
return (
<ScrollView scrollY className='patient-list-page'>
<ScrollView scrollY className={`patient-list-page ${modeClass}`}>
<View className='search-bar'>
<Input
className='search-input'
@@ -154,23 +176,12 @@ export default function PatientList() {
</View>
)}
{total > 20 && (
<View className='pagination'>
<Text
className={`pagination__btn ${page <= 1 ? 'disabled' : ''}`}
onClick={() => page > 1 && setPage(page - 1)}
>
</Text>
<Text className='pagination__info'>{page} / {Math.ceil(total / 20)}</Text>
<Text
className={`pagination__btn ${page >= Math.ceil(total / 20) ? 'disabled' : ''}`}
onClick={() => page < Math.ceil(total / 20) && setPage(page + 1)}
>
</Text>
{!loading && patients.length >= total && total > 0 && (
<View style={{ textAlign: 'center', padding: '20px' }}>
<Text style={{ fontSize: '24px', color: '#78716C' }}></Text>
</View>
)}
{loading && patients.length > 0 && <Loading />}
</ScrollView>
);
}

View File

@@ -0,0 +1,93 @@
@import '../../../../styles/variables.scss';
@import '../../../../styles/mixins.scss';
.create-page {
min-height: 100vh;
background: $bg;
padding: 24px;
padding-bottom: 200px;
}
.section {
background: $card;
border-radius: $r;
padding: 24px;
margin-bottom: 16px;
box-shadow: $shadow-sm;
}
.section-title {
font-size: var(--tk-font-body-lg);
font-weight: bold;
color: $tx;
display: block;
margin-bottom: 16px;
}
.form-row {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16px 0;
border-bottom: 1px solid $bd-l;
&:last-child {
border-bottom: none;
}
}
.form-label {
font-size: var(--tk-font-h1);
color: $tx2;
flex-shrink: 0;
min-width: 140px;
}
.form-input {
flex: 1;
text-align: right;
font-size: var(--tk-font-h1);
color: $tx;
}
.form-value {
font-size: var(--tk-font-h1);
color: $tx;
&.placeholder {
color: $tx3;
}
}
.form-textarea {
width: 100%;
margin-top: 12px;
font-size: var(--tk-font-h1);
color: $tx;
min-height: 120px;
background: $bg;
border-radius: $r-sm;
padding: 16px;
}
.submit-btn {
background: $pri;
border-radius: $r-sm;
padding: 24px;
text-align: center;
margin-top: 24px;
&:active {
background: $pri-d;
}
&--disabled {
opacity: 0.5;
}
}
.submit-btn__text {
font-size: var(--tk-font-num);
font-weight: bold;
color: #fff;
}

View File

@@ -0,0 +1,198 @@
import { useState } from 'react';
import { View, Text, Input, Textarea, Picker, ScrollView } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import * as doctorApi from '@/services/doctor';
import Loading from '@/components/Loading';
import { useElderClass } from '../../../../hooks/useElderClass';
import './index.scss';
interface FormState {
dialyzer_model: string;
membrane_area: string;
dialysate_potassium: string;
dialysate_calcium: string;
dialysate_bicarbonate: string;
anticoagulation_type: string;
anticoagulation_dose: string;
target_ultrafiltration_ml: string;
target_dry_weight: string;
blood_flow_rate: string;
dialysate_flow_rate: string;
frequency_per_week: string;
duration_minutes: string;
vascular_access_type: string;
vascular_access_location: string;
effective_from: string;
effective_to: string;
notes: string;
}
const initialForm: FormState = {
dialyzer_model: '',
membrane_area: '',
dialysate_potassium: '',
dialysate_calcium: '',
dialysate_bicarbonate: '',
anticoagulation_type: '',
anticoagulation_dose: '',
target_ultrafiltration_ml: '',
target_dry_weight: '',
blood_flow_rate: '',
dialysate_flow_rate: '',
frequency_per_week: '',
duration_minutes: '',
vascular_access_type: '',
vascular_access_location: '',
effective_from: '',
effective_to: '',
notes: '',
};
export default function PrescriptionCreate() {
const router = useRouter();
const patientId = router.params.patientId || '';
const modeClass = useElderClass();
const [form, setForm] = useState<FormState>(initialForm);
const [submitting, setSubmitting] = useState(false);
const updateField = (key: keyof FormState, value: string) => {
setForm((prev) => ({ ...prev, [key]: value }));
};
const handleSubmit = async () => {
if (!patientId) {
Taro.showToast({ title: '缺少患者信息', icon: 'none' });
return;
}
setSubmitting(true);
const num = (v: string) => v ? Number(v) : undefined;
const payload = {
patient_id: patientId,
dialyzer_model: form.dialyzer_model || undefined,
membrane_area: num(form.membrane_area),
dialysate_potassium: num(form.dialysate_potassium),
dialysate_calcium: num(form.dialysate_calcium),
dialysate_bicarbonate: num(form.dialysate_bicarbonate),
anticoagulation_type: form.anticoagulation_type || undefined,
anticoagulation_dose: form.anticoagulation_dose || undefined,
target_ultrafiltration_ml: num(form.target_ultrafiltration_ml),
target_dry_weight: num(form.target_dry_weight),
blood_flow_rate: num(form.blood_flow_rate),
dialysate_flow_rate: num(form.dialysate_flow_rate),
frequency_per_week: num(form.frequency_per_week),
duration_minutes: num(form.duration_minutes),
vascular_access_type: form.vascular_access_type || undefined,
vascular_access_location: form.vascular_access_location || undefined,
effective_from: form.effective_from || undefined,
effective_to: form.effective_to || undefined,
notes: form.notes || undefined,
};
try {
await doctorApi.createDialysisPrescription(payload);
Taro.showToast({ title: '创建成功', icon: 'success' });
setTimeout(() => Taro.navigateBack(), 1000);
} catch {
Taro.showToast({ title: '创建失败', icon: 'none' });
} finally {
setSubmitting(false);
}
};
const InputField = ({ label, field, placeholder, type = 'digit' }: {
label: string; field: keyof FormState; placeholder: string; type?: string;
}) => (
<View className='form-row'>
<Text className='form-label'>{label}</Text>
<Input
className='form-input'
type={type as any}
placeholder={placeholder}
value={form[field]}
onInput={(e) => updateField(field, e.detail.value)}
/>
</View>
);
return (
<ScrollView scrollY className={`create-page ${modeClass}`}>
{/* 透析器 */}
<View className='section'>
<Text className='section-title'></Text>
<InputField label='透析器型号' field='dialyzer_model' placeholder='请输入型号' type='text' />
<InputField label='膜面积' field='membrane_area' placeholder='m²' />
</View>
{/* 透析液 */}
<View className='section'>
<Text className='section-title'></Text>
<InputField label='钾浓度' field='dialysate_potassium' placeholder='mmol/L' />
<InputField label='钙浓度' field='dialysate_calcium' placeholder='mmol/L' />
<InputField label='碳酸氢盐' field='dialysate_bicarbonate' placeholder='mmol/L' />
</View>
{/* 抗凝 */}
<View className='section'>
<Text className='section-title'></Text>
<InputField label='抗凝类型' field='anticoagulation_type' placeholder='请输入' type='text' />
<InputField label='抗凝剂量' field='anticoagulation_dose' placeholder='请输入' type='text' />
</View>
{/* 参数 */}
<View className='section'>
<Text className='section-title'></Text>
<InputField label='目标超滤量' field='target_ultrafiltration_ml' placeholder='ml' type='number' />
<InputField label='目标干体重' field='target_dry_weight' placeholder='kg' />
<InputField label='血流速' field='blood_flow_rate' placeholder='ml/min' type='number' />
<InputField label='透析液流量' field='dialysate_flow_rate' placeholder='ml/min' type='number' />
<InputField label='每周频次' field='frequency_per_week' placeholder='次/周' type='number' />
<InputField label='每次时长' field='duration_minutes' placeholder='分钟' type='number' />
</View>
{/* 血管通路 */}
<View className='section'>
<Text className='section-title'></Text>
<InputField label='通路类型' field='vascular_access_type' placeholder='请输入' type='text' />
<InputField label='通路位置' field='vascular_access_location' placeholder='请输入' type='text' />
</View>
{/* 生效日期 */}
<View className='section'>
<Text className='section-title'></Text>
<View className='form-row'>
<Text className='form-label'></Text>
<Picker mode='date' value={form.effective_from} onChange={(e) => updateField('effective_from', e.detail.value)}>
<Text className={`form-value ${!form.effective_from ? 'placeholder' : ''}`}>
{form.effective_from || '请选择'}
</Text>
</Picker>
</View>
<View className='form-row'>
<Text className='form-label'></Text>
<Picker mode='date' value={form.effective_to} onChange={(e) => updateField('effective_to', e.detail.value)}>
<Text className={`form-value ${!form.effective_to ? 'placeholder' : ''}`}>
{form.effective_to || '请选择'}
</Text>
</Picker>
</View>
</View>
{/* 备注 */}
<View className='section'>
<Text className='section-title'></Text>
<Textarea
className='form-textarea'
placeholder='请输入备注...'
value={form.notes}
onInput={(e) => updateField('notes', e.detail.value)}
maxlength={500}
/>
</View>
<View className={`submit-btn ${submitting ? 'submit-btn--disabled' : ''}`} onClick={handleSubmit}>
<Text className='submit-btn__text'>{submitting ? '提交中...' : '创建处方'}</Text>
</View>
</ScrollView>
);
}

View File

@@ -0,0 +1,137 @@
@import '../../../../styles/variables.scss';
@import '../../../../styles/mixins.scss';
.prescription-detail {
min-height: 100vh;
background: $bg;
padding: 24px;
padding-bottom: 200px;
}
.section {
background: $card;
border-radius: $r;
padding: 24px;
margin-bottom: 16px;
box-shadow: $shadow-sm;
}
.section-title {
font-size: var(--tk-font-body-lg);
font-weight: bold;
color: $tx;
display: block;
margin-bottom: 12px;
}
.rx-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 8px;
}
.rx-header__title {
font-size: var(--tk-font-num-lg);
font-weight: bold;
color: $tx;
}
.rx-header__status {
display: inline-block;
padding: 4px 12px;
border-radius: 8px;
font-size: var(--tk-font-body);
background: $bd-l;
color: $tx3;
&--active {
background: $acc-l;
color: $acc;
}
}
.rx-sub {
font-size: var(--tk-font-h1);
color: $tx2;
display: block;
font-variant-numeric: tabular-nums;
}
.detail-row {
display: flex;
justify-content: space-between;
padding: 10px 0;
border-bottom: 1px solid $bd-l;
&:last-child {
border-bottom: none;
}
}
.detail-label {
font-size: var(--tk-font-h1);
color: $tx2;
}
.detail-value {
font-size: var(--tk-font-h1);
color: $tx;
text-align: right;
flex: 1;
margin-left: 24px;
font-variant-numeric: tabular-nums;
}
.notes-text {
font-size: var(--tk-font-h1);
color: $tx;
line-height: 1.6;
}
.error-text {
text-align: center;
padding: 120px 0;
font-size: var(--tk-font-body-lg);
color: $tx3;
}
.actions {
display: flex;
flex-direction: column;
gap: 12px;
padding: 16px 0;
}
.action-btn {
border-radius: $r-sm;
padding: 20px;
text-align: center;
&--secondary {
background: $card;
border: 1px solid $bd;
.action-btn__text {
color: $pri;
}
}
&--danger {
background: $card;
border: 1px solid $dan;
.action-btn__text {
color: $dan;
}
}
&--disabled {
opacity: 0.5;
}
}
.action-btn__text {
font-size: var(--tk-font-body-lg);
font-weight: 500;
}

View File

@@ -0,0 +1,163 @@
import { useState, useEffect } from 'react';
import { View, Text, ScrollView } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import * as doctorApi from '@/services/doctor';
import Loading from '@/components/Loading';
import { useElderClass } from '../../../../hooks/useElderClass';
import './index.scss';
export default function PrescriptionDetail() {
const router = useRouter();
const id = router.params.id || '';
const modeClass = useElderClass();
const [rx, setRx] = useState<doctorApi.DialysisPrescription | null>(null);
const [loading, setLoading] = useState(true);
const [submitting, setSubmitting] = useState(false);
useEffect(() => {
if (id) loadRx();
}, [id]);
const loadRx = async () => {
setLoading(true);
try {
const data = await doctorApi.getDialysisPrescription(id);
setRx(data);
} catch {
Taro.showToast({ title: '加载失败', icon: 'none' });
} finally {
setLoading(false);
}
};
const handleDeactivate = async () => {
if (!rx) return;
const { confirm } = await Taro.showModal({
title: '确认停用',
content: '停用后该处方将不再生效,确定停用吗?',
});
if (!confirm) return;
setSubmitting(true);
try {
const updated = await doctorApi.updateDialysisPrescription(id, { status: 'inactive' }, rx.version);
setRx(updated);
Taro.showToast({ title: '已停用', icon: 'success' });
} catch {
Taro.showToast({ title: '操作失败', icon: 'none' });
} finally {
setSubmitting(false);
}
};
const handleDelete = async () => {
if (!rx) return;
const { confirm } = await Taro.showModal({
title: '确认删除',
content: '删除后不可恢复,确定要删除这条处方吗?',
});
if (!confirm) return;
setSubmitting(true);
try {
await doctorApi.deleteDialysisPrescription(id, rx.version);
Taro.showToast({ title: '已删除', icon: 'success' });
setTimeout(() => Taro.navigateBack(), 1000);
} catch {
Taro.showToast({ title: '删除失败', icon: 'none' });
setSubmitting(false);
}
};
const Row = ({ label, value, unit }: { label: string; value?: string | number | null; unit?: string }) => {
if (value == null) return null;
return (
<View className='detail-row'>
<Text className='detail-label'>{label}</Text>
<Text className='detail-value'>{value}{unit || ''}</Text>
</View>
);
};
if (loading) return <Loading />;
if (!rx) return <View className={`error-text ${modeClass}`}><Text></Text></View>;
return (
<ScrollView scrollY className={`prescription-detail ${modeClass}`}>
{/* 状态头部 */}
<View className='section'>
<View className='rx-header'>
<Text className='rx-header__title'>{rx.dialyzer_model || '透析处方'}</Text>
<Text className={`rx-header__status rx-header__status--${rx.status}`}>
{rx.status === 'active' ? '生效中' : rx.status === 'inactive' ? '已停用' : rx.status}
</Text>
</View>
{(rx.effective_from || rx.effective_to) && (
<Text className='rx-sub'>{rx.effective_from || '...'} ~ {rx.effective_to || '...'}</Text>
)}
</View>
{/* 基本参数 */}
<View className='section'>
<Text className='section-title'></Text>
<Row label='透析器型号' value={rx.dialyzer_model} />
<Row label='膜面积' value={rx.membrane_area != null ? `${rx.membrane_area}` : null} unit=' m²' />
<Row label='血流速' value={rx.blood_flow_rate} unit=' ml/min' />
<Row label='透析液流量' value={rx.dialysate_flow_rate} unit=' ml/min' />
<Row label='频率' value={rx.frequency_per_week != null ? `${rx.frequency_per_week} 次/周` : null} />
<Row label='每次时长' value={rx.duration_minutes} unit=' 分钟' />
</View>
{/* 透析液配比 */}
<View className='section'>
<Text className='section-title'></Text>
<Row label='钾浓度' value={rx.dialysate_potassium} unit=' mmol/L' />
<Row label='钙浓度' value={rx.dialysate_calcium} unit=' mmol/L' />
<Row label='碳酸氢盐' value={rx.dialysate_bicarbonate} unit=' mmol/L' />
</View>
{/* 抗凝方案 */}
<View className='section'>
<Text className='section-title'></Text>
<Row label='抗凝类型' value={rx.anticoagulation_type} />
<Row label='抗凝剂量' value={rx.anticoagulation_dose} />
</View>
{/* 血管通路 */}
{(rx.vascular_access_type || rx.vascular_access_location) && (
<View className='section'>
<Text className='section-title'></Text>
<Row label='通路类型' value={rx.vascular_access_type} />
<Row label='通路位置' value={rx.vascular_access_location} />
</View>
)}
{/* 超滤目标 */}
{(rx.target_ultrafiltration_ml != null || rx.target_dry_weight != null) && (
<View className='section'>
<Text className='section-title'></Text>
<Row label='目标超滤量' value={rx.target_ultrafiltration_ml} unit=' ml' />
<Row label='目标干体重' value={rx.target_dry_weight} unit=' kg' />
</View>
)}
{/* 备注 */}
{rx.notes && (
<View className='section'>
<Text className='section-title'></Text>
<Text className='notes-text'>{rx.notes}</Text>
</View>
)}
{/* 操作按钮 */}
<View className='actions'>
{rx.status === 'active' && (
<View className={`action-btn action-btn--secondary ${submitting ? 'action-btn--disabled' : ''}`} onClick={handleDeactivate}>
<Text className='action-btn__text'></Text>
</View>
)}
<View className='action-btn action-btn--danger' onClick={handleDelete}>
<Text className='action-btn__text'></Text>
</View>
</View>
</ScrollView>
);
}

View File

@@ -0,0 +1,176 @@
@import '../../../styles/variables.scss';
@import '../../../styles/mixins.scss';
.prescription-page {
min-height: 100vh;
background: $bg;
padding-bottom: 120px;
}
.search-bar {
padding: 16px 24px;
background: $card;
}
.search-input {
background: $bg;
border-radius: $r-sm;
padding: 16px 20px;
font-size: var(--tk-font-body-lg);
color: $tx;
}
.tabs {
display: flex;
padding: 0 24px;
background: $card;
border-bottom: 1px solid $bd-l;
}
.tab {
flex: 1;
text-align: center;
padding: 20px 0;
position: relative;
&--active {
.tab-text {
color: $pri;
font-weight: bold;
}
&::after {
content: '';
position: absolute;
bottom: 0;
left: 25%;
right: 25%;
height: 4px;
background: $pri;
border-radius: 2px;
}
}
}
.tab-text {
font-size: var(--tk-font-h1);
color: $tx2;
}
.prescription-list {
padding: 16px 24px;
}
.prescription-count {
font-size: var(--tk-font-h2);
color: $tx3;
padding: 8px 0 16px;
}
.prescription-card {
background: $card;
border-radius: $r;
padding: 24px;
margin-bottom: 16px;
box-shadow: $shadow-sm;
&:active {
box-shadow: $shadow-md;
}
}
.prescription-card__header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
}
.prescription-card__model {
font-size: var(--tk-font-body-lg);
font-weight: bold;
color: $tx;
}
.status-tag {
display: inline-block;
padding: 4px 12px;
border-radius: 8px;
font-size: var(--tk-font-body);
background: $bd-l;
color: $tx3;
&--active {
background: $acc-l;
color: $acc;
}
}
.prescription-card__body {
display: flex;
gap: 16px;
margin-bottom: 8px;
}
.prescription-card__meta {
font-size: var(--tk-font-h2);
color: $tx2;
font-variant-numeric: tabular-nums;
}
.prescription-card__date {
font-size: var(--tk-font-h2);
color: $tx3;
display: block;
font-variant-numeric: tabular-nums;
}
.pagination {
display: flex;
justify-content: center;
align-items: center;
padding: 16px 0;
gap: 24px;
}
.page-btn {
padding: 12px 24px;
background: $card;
border-radius: $r-sm;
font-size: var(--tk-font-h1);
color: $pri;
&--disabled {
opacity: 0.4;
}
}
.page-info {
font-size: var(--tk-font-h2);
color: $tx2;
}
.fab {
position: fixed;
right: 32px;
bottom: 120px;
width: 96px;
height: 96px;
border-radius: 48px;
background: $pri;
display: flex;
align-items: center;
justify-content: center;
box-shadow: $shadow-md;
z-index: 10;
&:active {
background: $pri-d;
}
}
.fab-text {
font-size: var(--tk-font-hero);
color: #fff;
font-weight: bold;
}

View File

@@ -0,0 +1,165 @@
import { useState, useEffect } from 'react';
import { View, Text, Input, ScrollView } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import * as doctorApi from '@/services/doctor';
import Loading from '@/components/Loading';
import EmptyState from '@/components/EmptyState';
import { useElderClass } from '../../../hooks/useElderClass';
import './index.scss';
const TABS = [
{ key: '', label: '全部' },
{ key: 'active', label: '生效中' },
{ key: 'inactive', label: '已停用' },
];
export default function PrescriptionList() {
const router = useRouter();
const patientId = router.params.patientId || '';
const modeClass = useElderClass();
const [searchPatient, setSearchPatient] = useState('');
const [currentPatientId, setCurrentPatientId] = useState(patientId);
const [activeTab, setActiveTab] = useState('');
const [prescriptions, setPrescriptions] = useState<doctorApi.DialysisPrescription[]>([]);
const [loading, setLoading] = useState(false);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1);
useEffect(() => {
loadData(1);
}, [currentPatientId, activeTab]);
const loadData = async (p: number) => {
setLoading(true);
try {
const res = await doctorApi.listDialysisPrescriptions({
patient_id: currentPatientId || undefined,
status: activeTab || undefined,
page: p,
page_size: 20,
});
setPrescriptions(res.data || []);
setTotal(res.total || 0);
setPage(p);
} catch {
Taro.showToast({ title: '加载失败', icon: 'none' });
} finally {
setLoading(false);
}
};
const handleSearch = async () => {
if (!searchPatient.trim()) return;
setLoading(true);
try {
const res = await doctorApi.listPatients({ search: searchPatient.trim(), page: 1, page_size: 1 });
if (res.data && res.data.length > 0) {
setCurrentPatientId(res.data[0].id);
} else {
Taro.showToast({ title: '未找到患者', icon: 'none' });
}
} catch {
Taro.showToast({ title: '搜索失败', icon: 'none' });
} finally {
setLoading(false);
}
};
if (loading && prescriptions.length === 0) return <Loading />;
return (
<ScrollView scrollY className={`prescription-page ${modeClass}`}>
{!patientId && (
<View className='search-bar'>
<Input
className='search-input'
placeholder='搜索患者姓名'
value={searchPatient}
onInput={(e) => setSearchPatient(e.detail.value)}
confirmType='search'
onConfirm={handleSearch}
/>
</View>
)}
<View className='tabs'>
{TABS.map((t) => (
<View
key={t.key}
className={`tab ${activeTab === t.key ? 'tab--active' : ''}`}
onClick={() => { setActiveTab(t.key); setPage(1); }}
>
<Text className='tab-text'>{t.label}</Text>
</View>
))}
</View>
{prescriptions.length === 0 ? (
<EmptyState text='暂无透析处方' />
) : (
<View className='prescription-list'>
<View className='prescription-count'><Text> {total} </Text></View>
{prescriptions.map((p) => (
<View
key={p.id}
className='prescription-card'
onClick={() => Taro.navigateTo({
url: `/pages/doctor/prescription/detail/index?id=${p.id}`,
})}
>
<View className='prescription-card__header'>
<Text className='prescription-card__model'>{p.dialyzer_model || '透析处方'}</Text>
<Text className={`status-tag status-tag--${p.status}`}>
{p.status === 'active' ? '生效中' : p.status === 'inactive' ? '已停用' : p.status}
</Text>
</View>
<View className='prescription-card__body'>
{p.frequency_per_week != null && (
<Text className='prescription-card__meta'>{p.frequency_per_week}/</Text>
)}
{p.duration_minutes != null && (
<Text className='prescription-card__meta'>{p.duration_minutes}</Text>
)}
</View>
{(p.effective_from || p.effective_to) && (
<Text className='prescription-card__date'>
{p.effective_from || '...'} ~ {p.effective_to || '...'}
</Text>
)}
</View>
))}
{total > 20 && (
<View className='pagination'>
<View
className={`page-btn ${page <= 1 ? 'page-btn--disabled' : ''}`}
onClick={() => page > 1 && loadData(page - 1)}
>
<Text></Text>
</View>
<Text className='page-info'>{page} / {Math.ceil(total / 20)}</Text>
<View
className={`page-btn ${page * 20 >= total ? 'page-btn--disabled' : ''}`}
onClick={() => page * 20 < total && loadData(page + 1)}
>
<Text></Text>
</View>
</View>
)}
</View>
)}
<View
className='fab'
onClick={() => {
if (!currentPatientId) {
Taro.showToast({ title: '请先选择患者', icon: 'none' });
return;
}
Taro.navigateTo({ url: `/pages/doctor/prescription/create/index?patientId=${currentPatientId}` });
}}
>
<Text className='fab-text'>+</Text>
</View>
</ScrollView>
);
}

View File

@@ -28,13 +28,13 @@
&__type {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 32px;
font-size: var(--tk-font-num);
font-weight: 700;
color: $tx;
}
&__status {
font-size: 24px;
font-size: var(--tk-font-h2);
padding: 6px 16px;
border-radius: $r;
font-weight: 500;
@@ -45,13 +45,13 @@
}
.report-date {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx2;
display: block;
}
.review-info {
font-size: 24px;
font-size: var(--tk-font-h2);
color: $acc;
display: block;
margin-top: 8px;
@@ -81,7 +81,7 @@
}
.indicator-cell {
font-size: 24px;
font-size: var(--tk-font-h2);
&--name {
flex: 2;
@@ -116,7 +116,7 @@
}
.indicator-row--header & {
font-size: 22px;
font-size: var(--tk-font-body);
color: $tx3;
font-weight: 400;
}
@@ -129,7 +129,7 @@
}
.notes-text {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx;
line-height: 1.6;
}
@@ -140,7 +140,7 @@
background: $bd-l;
border-radius: $r;
padding: 20px;
font-size: 26px;
font-size: var(--tk-font-h1);
color: $tx;
box-sizing: border-box;
line-height: 1.6;
@@ -158,7 +158,7 @@
}
&__text {
font-size: 28px;
font-size: var(--tk-font-body-lg);
color: $card;
font-weight: 600;
}
@@ -168,5 +168,5 @@
text-align: center;
padding: 80px 32px;
color: $tx3;
font-size: 28px;
font-size: var(--tk-font-body-lg);
}

View File

@@ -3,12 +3,14 @@ import { View, Text, Textarea, ScrollView } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import * as doctorApi from '@/services/doctor';
import Loading from '@/components/Loading';
import { useElderClass } from '../../../../hooks/useElderClass';
import './index.scss';
export default function ReportDetail() {
const router = useRouter();
const patientId = router.params.patientId || '';
const reportId = router.params.id || '';
const modeClass = useElderClass();
const [report, setReport] = useState<doctorApi.LabReportDetail | null>(null);
const [loading, setLoading] = useState(true);
const [doctorNotes, setDoctorNotes] = useState('');
@@ -51,10 +53,10 @@ export default function ReportDetail() {
const formatDate = (d: string) => new Date(d).toLocaleDateString('zh-CN');
if (loading) return <Loading />;
if (!report) return <View className='error-text'><Text></Text></View>;
if (!report) return <View className={`error-text ${modeClass}`}><Text></Text></View>;
return (
<ScrollView scrollY className='report-detail'>
<ScrollView scrollY className={`report-detail ${modeClass}`}>
{/* 基本信息 */}
<View className='section'>
<View className='report-header'>

View File

@@ -15,7 +15,7 @@
background: $card;
border-radius: $r;
padding: 20px 24px;
font-size: 28px;
font-size: var(--tk-font-body-lg);
width: 100%;
box-sizing: border-box;
box-shadow: $shadow-sm;
@@ -26,7 +26,7 @@
margin-bottom: 16px;
text {
font-size: 24px;
font-size: var(--tk-font-h2);
color: $tx3;
}
}
@@ -56,13 +56,13 @@
&__type {
font-family: 'Georgia', 'Times New Roman', serif;
font-size: 28px;
font-size: var(--tk-font-body-lg);
font-weight: 600;
color: $tx;
}
&__date {
font-size: 24px;
font-size: var(--tk-font-h2);
color: $tx3;
}
@@ -73,13 +73,13 @@
}
&__abnormal {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $dan;
font-weight: 600;
}
&__normal {
font-size: 26px;
font-size: var(--tk-font-h1);
color: $acc;
}

View File

@@ -4,11 +4,13 @@ import Taro, { useRouter } from '@tarojs/taro';
import * as doctorApi from '@/services/doctor';
import Loading from '@/components/Loading';
import EmptyState from '@/components/EmptyState';
import { useElderClass } from '../../../hooks/useElderClass';
import './index.scss';
export default function ReportList() {
const router = useRouter();
const patientId = router.params.patientId || '';
const modeClass = useElderClass();
const [searchPatient, setSearchPatient] = useState('');
const [currentPatientId, setCurrentPatientId] = useState(patientId);
const [reports, setReports] = useState<doctorApi.LabReportItem[]>([]);
@@ -55,7 +57,7 @@ export default function ReportList() {
if (loading && reports.length === 0) return <Loading />;
return (
<ScrollView scrollY className='report-page'>
<ScrollView scrollY className={`report-page ${modeClass}`}>
{!patientId && (
<View className='search-bar'>
<Input

Some files were not shown because too many files have changed in this diff Show More