55 Commits

Author SHA1 Message Date
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
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
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
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
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
a78ee2f154 fix(auth): Token 验证和撤销添加租户隔离 2026-05-06 10:21:07 +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
988f6cd6a5 fix(auth): JWT 中间件支持 query parameter token 回退
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
SSE/EventSource 无法设置自定义 Authorization 头,前端通过
?token=xxx 传参。中间件现在优先读 Authorization 头,回退到
URL query parameter,修复 SSE 连接永远 401 的问题。
2026-04-28 11:23:53 +08:00
iven
9dd6095e77 fix: P0/P1 安全与质量缺陷修复 — 10 项 QA 审查问题解决
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
P0 安全修复:
- tenant_rls: SQL 拼接改为参数化查询防止注入
- follow_up_service: UUID SQL 拼接改为参数化原生查询
- RLS 策略: 新迁移移除空字符串绕过条件
- SSE 消息推送: token 键名 'token' → 'access_token' 修复
- rate_limit: 登录端点 Redis 不可达时 fail-close

P1 质量修复:
- 小程序缓存清理: preservedKeys 补全认证键名
- 小程序 token 刷新: 失败时清除所有认证数据
- 小程序 401: redirectTo → reLaunch 兼容 tabBar
- 集成测试: 信号量限制并行数据库创建(4个)
- change_password: 乐观锁 version 硬编码 → 动态递增

测试: 516 全部通过 (含 153 集成测试)
2026-04-28 00:57:41 +08:00
iven
30f2452933 fix(core): 迁移修复 + 配置调整
- auth_state: 新增字段
- config/default.toml: 配置更新
- migration 078/082: 修复 SQL 语法
- state/main: 启动逻辑调整
2026-04-28 00:20:11 +08:00
iven
f58f1f73c5 test(health): 健康数据集成测试 — 8 个测试覆盖体征CRUD/化验报告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
fix(auth): WechatSessionResp mock 缺少 unionid 字段
2026-04-27 22:27:36 +08:00
iven
633bf8c62d feat(auth): data_scope 行级数据权限 — DataScope 枚举 + 中间件加载
- TenantContext 新增 permission_data_scopes: HashMap<String, DataScope>
- DataScope 枚举: All/SelfOnly/Department/DepartmentTree
- JWT 中间件查询 role_permissions.data_scope 填充到上下文
- rbac::get_data_scope() 供 service 层按权限获取数据范围
- 默认 All,完全向后兼容现有行为
2026-04-27 19:31:19 +08:00
iven
97bb592688 feat(core): build_event_payload 统一信封 — 28 处事件发布全部迁移
- erp-core 添加 build_event_payload(),自动注入 schema_version + occurred_at
- erp-health 12 个 service(25 处)、erp-auth(1 处)、erp-workflow(2 处)
  全部迁移到统一信封格式
2026-04-27 18:01:05 +08:00
iven
2519ad8fee feat(auth): 微信 session_key 迁移到 Redis — 内存降级兜底
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
session_key 从全局 HashMap 迁移到 Redis(SET key EX 300 / GETDEL),
Redis 不可用时自动降级到内存缓存,提升多实例部署安全性。
2026-04-27 13:05:25 +08:00
iven
b05b7c27a0 feat: 审计修复 Phase 6-7 — 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
Phase 6 功能补全:
- P1-3: 消息 SSE 实时推送端点 + 前端 EventSource 连接
- P1-6: ServiceTask HTTP 调用能力 (reqwest GET/POST)
- P1-7: user.deleted 事件处理 — 终止相关流程实例
- P1-8: 任务认领 (claim) 端点 + handler
- P1-9: 超时检查器发布 task.timeout 事件
- P1-15: 组织/部门名称唯一性校验 (create + update)
- P1-18: 消息群发 fan-out (role/department/all 批量投递)

Phase 7 P3-P4 收尾:
- PluginAdmin purge 按钮状态修复
- ChangePassword 最小 8 字符 + 新旧密码不同验证
- AuditLogViewer 用户名缓存 + 扩展资源类型
- InstanceMonitor 通过 definition 缓存解析 node_name
- NotificationPreferences DND 时间范围校验
2026-04-26 19:44:04 +08:00
iven
83fe89cbcd fix: 全系统审计问题修复 — 安全/数据完整性/功能缺陷/UX (Phase 1-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
Phase 1 安全热修复:
- P0-1: /uploads 文件服务添加 JWT 认证中间件(支持 header + query param)
- P0-2: analytics/batch 路由从 public 移到 protected_routes
- P0-3: plugin engine SQL 注入修复(format! → 参数化查询)
- P0-new: stats_service compute_avg_field 字段白名单 + FLOAT8 类型转换

Phase 2 数据完整性:
- P0-4: 组织删除级联检查(添加部门存在性校验)
- P0-5: 部门删除级联检查(添加岗位 + 用户存在性校验)
- P0-8: workflow on_tenant_deleted 实现 5 实体批量删除
- P0-7: 并行网关 race condition 修复(consumed → completed 原子转换)

Phase 3 P1 后端 Bug:
- P1-12: plugin host 表名消毒(使用 sanitize_identifier)
- P1-10: workflow deprecated 状态转换(published → deprecated)
- P1-11: workflow 更新验证条件(nodes/edges 任一变化即验证)
- P0-9: 小程序 .gitignore 添加 .env/.env.*/日志
- P1-19: 小程序加密密钥替换为 64 字符强密钥

Phase 4 消息模块:
- P1-5: 通知偏好 GET 路由 + handler
- P1-4: 消息模板 update/delete CRUD + version
- P2-8: mark_all_read SQL 添加 version + 1
- P2-7: markAsRead 改为乐观更新 + 失败回滚

Phase 5 前端修复:
- P2-9: 通知面板点击导航到 /messages
- P2-1: 随访任务患者名批量 ID 解析(替代 UUID 显示)
- P2-5: AppointmentList 分离 patient_id/doctor_id 分别调用 API
- P2-17: PluginMarket installed 字段修正(name → id)
- P3-3: 路由标题 fallback 改为模式匹配(支持 :id 动态路径)
- P2-15: workflow updateDefinition 添加 version 字段
- P3-9: Kanban 版本使用记录实际 version
- P2-21: secure-storage 生产环境无密钥时阻止存储
- P3-11: destroyOnHidden → destroyOnClose
- P3-13: PendingTasks 深色模式 Tag 颜色适配

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-26 19:16:23 +08:00
iven
a0b72b0f73 feat: Iteration 1 — 审计日志IP记录、文件上传、医护端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
Iteration 1 六项任务全部完成:

1. 审计日志IP记录 — task_local RequestInfo 自动注入 IP/user_agent
2. 文件上传服务 — multipart 上传 + ServeDir 静态文件服务
3. 医护端后端API — 医生工作台仪表盘 + 患者标签CRUD + 会话已读
4. 小程序角色切换 — 登录后根据角色跳转医护台/患者首页
5. 小程序安全加固 — secure-storage 开发模式警告
6. 讨论记录归档 — docs/discussions/
2026-04-26 13:13:25 +08:00
iven
945ccd64ba fix: 全面 QA 审计修复 — 安全加固/代码质量/跨平台一致性/测试覆盖
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 0 安全热修复 (CRITICAL):
- 外部化微信 appid/secret 到 ERP__WECHAT__APPID/SECRET 环境变量
- 正确连接 HealthCrypto 到 ERP__HEALTH__AES_KEY/HMAC_KEY 环境变量
- 外部化小程序加密密钥到 TARO_APP_ENCRYPTION_KEY 环境变量
- 移除小程序 auth store 中的敏感信息 console.log

Phase 1 安全加固:
- 微信自动注册 display_name 添加 sanitize 防止 XSS
- 测试数据库凭据改为从 TEST_DB_URL 环境变量读取

Phase 2 代码质量:
- 提取 useThemeMode hook 消除 22 处重复暗色模式检测
- 提取共享健康常量到 constants/health.ts
- 拆分 patient_service.rs 脱敏函数到 masking.rs
- 移除未使用的 i18next/react-i18next 依赖
- 移除未使用的 api/errors.ts 和 erp-auth/anyhow 依赖

Phase 3 测试覆盖:
- 新增 5 个患者模块集成测试 (CRUD/租户隔离/验证/软删除)

Phase 4 跨平台一致性:
- 统一小程序 Patient.birthday → birth_date 匹配后端
- 统一小程序 Appointment.time_slot → start_time/end_time 匹配后端

Phase 5 架构:
- 微信登录添加多租户 TODO 注释
- 更新 wiki/infrastructure.md 环境变量文档
2026-04-25 10:00:49 +08:00
iven
6776a82926 feat(auth): 微信手机号真实 AES 解密替换 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
- login 阶段缓存 session_key(内存 HashMap,5 分钟 TTL)
- bind_phone 用 AES-128-CBC + PKCS7 解密 encryptedData 获取真实手机号
- 新增 workspace 依赖:aes, cbc, hex, base64
- 移除硬编码 "13800000000" 占位逻辑
2026-04-24 12:56:12 +08:00
iven
6391a13467 fix(auth+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
MEDIUM:
- WechatLoginReq/WechatBindPhoneReq 添加 Validate 派生 + 字段校验规则
- handler 中调用 req.validate() 并 map_err 转换
- 新增 AuthError::DbError 变体,wechat_service 所有 DB 错误从 Validation 改为 DbError
- DbError 映射到 AppError::Internal,不再误导前端

LOW:
- fetch_session 改用 reqwest Client.query() 构建参数,自动 URL 编码
- app.tsx PropsWithChildren<any> 改为 Record<string, unknown>
- login handleGetPhone 回调 e: any 改为内联类型
- appointment/create 4 个事件回调 e: any 改为内联类型
- health/input catch (e: any) 改为 catch (e: unknown) + instanceof 守卫
- report/detail Object.entries 去掉 [string, any] 类型断言
- wechat_service 移除 decrypt_phone_placeholder 函数,内联占位注释
2026-04-24 08:16:01 +08:00
iven
ef6d76ef6c fix(miniprogram+auth): 二次审计修复 — 3 HIGH + 2 MEDIUM
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
HIGH:
- wechat_users 迁移补充 created_by/updated_by/version 标准字段
- Entity 同步更新,bind_phone 创建记录时填充新字段
- appointment create 移除 schedule_id 空字符串,改为可选
- appointment list 用 useRef 替代 useCallback 的 loading 依赖,消除 stale closure

MEDIUM:
- report 页 patientId 从顶层读取改为 useDidShow 内动态获取,就诊人切换后正确刷新
- profile/reports 同上修复
- profile/followups 移除 useDidShow 非法的第二参数
2026-04-24 08:05:58 +08:00
iven
ba132921cc feat(auth): 添加微信小程序登录支持
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
- 新增 wechat_users 表迁移和 SeaORM Entity
- 实现微信登录 Service(code→openid→绑定状态查询)
- 实现手机号绑定 Service(创建/关联 user + 签发 JWT)
- 添加公开路由 POST /auth/wechat/login 和 /auth/wechat/bind-phone
- 新增 WechatConfig 到 AppConfig(appid/secret 通过环境变量配置)
- 添加 reqwest 依赖用于调用微信 jscode2session API
2026-04-24 00:05:43 +08:00
iven
841766b168 fix(用户管理): 修复用户列表页面加载失败问题
修复用户列表页面加载失败导致测试超时的问题,确保页面元素正确渲染
2026-04-19 08:46:28 +08:00
iven
62eea3d20d feat(auth,plugin): Q3 行级数据权限 — user_departments 表 + JWT 注入 department_ids + data_scope 接线
- 新增 user_departments 关联表(migration + entity)
- JWT 中间件查询用户部门并注入 TenantContext.department_ids
- role_permission entity 添加 data_scope 字段
- data_handler 接线行级数据权限过滤(list/count/aggregate)
- DataScopeParams + build_scope_sql + merge_scope_condition 实现全链路
2026-04-17 21:42:40 +08:00
iven
6a44cbecf3 perf: Q3 N+1 查询优化 — user_service 和 plugin_service
- user_service::list() 循环内单查询改为 fetch_batch_user_role_resps 批量查询
- plugin_service::list() 循环内单查询改为 find_batch_plugin_entities 批量查询
- RoleResp 和 PluginEntityResp 添加 Clone derive
2026-04-17 19:30:12 +08:00
iven
7c14bf83ca feat(audit): Q2 Chunk 3 — 审计日志补全
- 登录成功/失败均写入审计日志(含 IP、User-Agent)
- 登出、密码修改添加审计日志
- 用户/角色 update 记录变更前后值(old_value/new_value)
- 插件数据 CRUD(create/update/delete)添加审计日志
- auth handler 提取 X-Forwarded-For/X-Real-IP/User-Agent
2026-04-17 19:21:43 +08:00
iven
080d2cb3d6 fix(security): Q2 Chunk 2 — 多租户安全加固 + 限流 fail-closed
- auth_service::refresh() 添加 tenant_id 校验
- user_service get_by_id/update/delete/assign_roles 改为数据库级 tenant_id 过滤
- 限流中间件改为 fail-closed:Redis 不可达时返回 429 而非放行
2026-04-17 17:45:59 +08:00
iven
39a12500e3 fix(security): Q2 Chunk 1 — 密钥外部化与启动强制检查
- default.toml 敏感值改为占位符,强制通过环境变量注入
- 启动时拒绝默认 JWT 密钥和数据库 URL
- 移除 super_admin_password 硬编码 fallback
- 移除 From<AppError> for AuthError 反向映射,5 处调用点改为显式 map_err
- .gitignore 添加 .test_token 和测试产物
2026-04-17 17:42:19 +08:00
iven
f4b1a06d53 feat(auth): JWT 中间件预留 department_ids 填充位置
当前 department_ids 为空列表,附带 TODO 注释说明
待 user_positions 关联表建立后补充查询逻辑。
2026-04-17 10:34:06 +08:00
iven
62f17d13ad feat(core): TenantContext 新增 department_ids 字段
为行级数据权限做准备,TenantContext 新增 department_ids 字段
存储用户所属部门 ID 列表。当前阶段 JWT 中间件填充为空列表,
待 user_positions 关联表建立后补充查询逻辑。
2026-04-17 10:33:28 +08:00
iven
ff352a4c24 feat(plugin): 集成 WASM 插件系统到主服务并修复链路问题
- 新增 erp-plugin crate:插件管理、WASM 运行时、动态表、数据 CRUD
- 新增前端插件管理页面(PluginAdmin/PluginCRUDPage)和 API 层
- 新增插件数据迁移(plugins/plugin_entities/plugin_event_subscriptions)
- 新增权限补充迁移(为已有租户补充 plugin.admin/plugin.list 权限)
- 修复 PluginAdmin 页面 InstallOutlined 图标不存在的崩溃问题
- 修复 settings 唯一索引迁移顺序错误(先去重再建索引)
- 更新 wiki 和 CLAUDE.md 反映插件系统集成状态
- 新增 dev.ps1 一键启动脚本
2026-04-15 23:32:02 +08:00
iven
7e8fabb095 feat(auth): add change password API and frontend page
Backend:
- Add ChangePasswordReq DTO with validation (current + new password)
- Add AuthService::change_password() method with credential verification,
  password rehash, and token revocation
- Add POST /api/v1/auth/change-password endpoint with utoipa annotation

Frontend:
- Add changePassword() API function in auth.ts
- Add ChangePassword.tsx page with form validation and confirmation
- Add "修改密码" tab in Settings page

After password change, all refresh tokens are revoked and the user
is redirected to the login page.
2026-04-15 01:32:18 +08:00
iven
d8a0ac7519 feat: implement on_tenant_created/deleted hooks and update ErpModule trait
- ErpModule trait hooks now accept db and event_bus parameters
- AuthModule.on_tenant_created: seeds default roles, permissions,
  and admin user for new tenants using existing seed_tenant_auth()
- AuthModule.on_tenant_deleted: soft-deletes all users for the tenant
- Updated all other modules (config, workflow, message) to match
  the new trait signature
2026-04-15 01:27:33 +08:00
iven
e44d6063be feat: add utoipa path annotations to all API handlers and wire OpenAPI spec
- Add #[utoipa::path] annotations to all 70+ handler functions across
  auth, config, workflow, and message modules
- Add IntoParams/ToSchema derives to Pagination, PaginatedResponse, ApiResponse
  in erp-core, and MessageQuery/TemplateQuery in erp-message
- Collect all module paths into OpenAPI spec via AuthApiDoc, ConfigApiDoc,
  WorkflowApiDoc, MessageApiDoc structs in erp-server main.rs
- Update openapi_spec handler to merge all module specs
- The /docs/openapi.json endpoint now returns complete API documentation
  with all endpoints, request/response schemas, and security requirements
2026-04-15 01:23:27 +08:00
iven
ee65b6e3c9 test: add 149 unit tests across core, auth, config, message crates
Test coverage increased from ~34 to 183 tests (zero failures):

- erp-core (21): version check, pagination, API response, error mapping
- erp-auth (39): org tree building, DTO validation, error conversion,
  password hashing, user model mapping
- erp-config (57): DTO validation, numbering reset logic, menu tree
  building, error conversion. Fixed BatchSaveMenusReq nested validation
- erp-message (50): DTO validation, template rendering, query defaults,
  error conversion
- erp-workflow (16): unchanged (parser + expression tests)

All tests are pure unit tests requiring no database.
2026-04-15 01:06:34 +08:00
iven
9568dd7875 chore: apply cargo fmt across workspace and update docs
- Run cargo fmt on all Rust crates for consistent formatting
- Update CLAUDE.md with WASM plugin commands and dev.ps1 instructions
- Update wiki: add WASM plugin architecture, rewrite dev environment docs
- Minor frontend cleanup (unused imports)
2026-04-15 00:49:20 +08:00
iven
3b41e73f82 fix: resolve E2E audit findings and add Phase C frontend pages
- Fix audit_log handler multi-tenant bug: use Extension<TenantContext>
  instead of hardcoded default_tenant_id
- Fix sendMessage route mismatch: frontend /messages/send → /messages
- Add POST /users/{id}/roles backend route for role assignment
- Add task.completed event payload: started_by + instance_id for
  notification delivery
- Add audit log viewer frontend page (AuditLogViewer.tsx)
- Add language management frontend page (LanguageManager.tsx)
- Add api/auditLogs.ts and api/languages.ts modules
2026-04-12 15:57:33 +08:00
iven
14f431efff feat: systematic functional audit — fix 18 issues across Phase A/B
Phase A (P1 production blockers):
- A1: Apply IP rate limiting to public routes (login/refresh)
- A2: Publish domain events for workflow instance state transitions
  (completed/suspended/resumed/terminated) via outbox pattern
- A3: Replace hardcoded nil UUID default tenant with dynamic DB lookup
- A4: Add GET /api/v1/audit-logs query endpoint with pagination
- A5: Enhance CORS wildcard warning for production environments

Phase B (P2 functional gaps):
- B1: Remove dead erp-common crate (zero references in codebase)
- B2: Refactor 5 settings pages to use typed API modules instead of
  direct client calls; create api/themes.ts; delete dead errors.ts
- B3: Add resume/suspend buttons to InstanceMonitor page
- B4: Remove unused EventHandler trait from erp-core
- B5: Handle task.completed events in message module (send notifications)
- B6: Wire TimeoutChecker as 60s background task
- B7: Auto-skip ServiceTask nodes instead of crashing the process
- B8: Remove empty register_routes() from ErpModule trait and modules
2026-04-12 15:22:28 +08:00
iven
685df5e458 feat(core): implement event outbox persistence
Add domain_events migration and SeaORM entity. Modify EventBus::publish
to persist events before broadcasting (best-effort: DB failure logs
warning but still broadcasts in-memory). Update all 19 publish call
sites across 4 crates to pass db reference.

Add outbox relay background task that polls pending events every 5s
and re-broadcasts them, ensuring no events are lost on server restart.
2026-04-12 00:10:49 +08:00
iven
db2cd24259 feat(core): add audit logging to all mutation operations
Create audit_log SeaORM entity and audit_service::record() helper.
Integrate audit recording into 35 mutation endpoints across all modules:
- erp-auth: user/role/organization/department/position CRUD (15 actions)
- erp-config: dictionary/menu/setting/numbering_rule CRUD (15 actions)
- erp-workflow: definition/instance/task operations (8 actions)
- erp-message: send/system/mark_read/delete (5 actions)

Uses fire-and-forget pattern — audit failures logged but non-blocking.
2026-04-11 23:48:45 +08:00
iven
5d6e1dc394 feat(core): implement optimistic locking across all entities
Add VersionMismatch error variant and check_version() helper to erp-core.
All 13 mutable entities now enforce version checking on update/delete:
- erp-auth: user, role, organization, department, position
- erp-config: dictionary, dictionary_item, menu, setting, numbering_rule
- erp-workflow: process_definition, process_instance, task
- erp-message: message, message_subscription

Update DTOs to expose version in responses and require version in update
requests. HTTP 409 Conflict returned on version mismatch.
2026-04-11 23:25:43 +08:00
iven
0d7d3af0a8 fix(auth): standardize permission codes to dot notation and add missing permissions
- Change all permission codes from colon (`:`) to dot (`.`) separator
  to match handler require_permission() calls consistently
- Add missing user.list, role.list, permission.list, organization.list,
  department.list, position.list permissions (handlers check for .list
  but seeds only had :read)
- Add missing message module permissions (message.list, message.send,
  message.template.list, message.template.create)
- Add missing setting.delete, numbering.delete permissions
- Fix workflow handlers: workflow: → workflow.
- Fix message handlers: message: → message.
- Update viewer role READ_PERM_INDICES for new permission list

This fixes a critical runtime bug where ALL permission checks in
erp-auth and erp-config handlers would return 403 Forbidden because
the seed data used colon separators but handlers checked for dots.
2026-04-11 14:30:47 +08:00
iven
97d3c9026b fix: resolve remaining clippy warnings and improve workflow frontend
- Collapse nested if-let in user_service.rs search filter
- Suppress dead_code warning on ApiDoc struct
- Refactor server routing: nest all routes under /api/v1 prefix
- Simplify health check route path
- Improve workflow ProcessDesigner with edit mode and loading states
- Update workflow pages with enhanced UX
- Add Phase 2 implementation plan document
2026-04-11 12:59:43 +08:00
iven
184034ff6b feat(config): add missing dictionary item CRUD, setting delete, and numbering delete routes
- Dictionary items: POST/PUT/DELETE endpoints under /config/dictionaries/{dict_id}/items
- Settings: DELETE /config/settings/{key}
- Numbering rules: DELETE /config/numbering-rules/{id}
- Fix workflow Entities: add deleted_at and version_field to process_definition,
  add standard fields to token and process_variable entities
- Update seed data for expanded permissions
2026-04-11 12:52:29 +08:00
iven
82986e988d docs: update progress to reflect Phase 1-6 completion
- Update CLAUDE.md architecture snapshot: all phases complete
- Update wiki/index.md: module descriptions and progress table
- All 6 phases of ERP platform base are now implemented

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-11 12:51:17 +08:00
iven
3a05523d23 fix: address Phase 1-2 audit findings
- CORS: replace permissive() with configurable whitelist (default.toml)
- Auth store: synchronously restore state at creation to eliminate
  flash-of-login-page on refresh
- MainLayout: menu highlight now tracks current route via useLocation
- Add extractErrorMessage() utility to reduce repeated error parsing
- Fix all clippy warnings across 4 crates (erp-auth, erp-config,
  erp-workflow, erp-message): remove unnecessary casts, use div_ceil,
  collapse nested ifs, reduce function arguments with DTOs
2026-04-11 12:36:34 +08:00
iven
91ecaa3ed7 feat(workflow): add workflow engine module (Phase 4)
Implement complete workflow engine with BPMN subset support:

Backend (erp-workflow crate):
- Token-driven execution engine with exclusive/parallel gateway support
- BPMN parser with flow graph validation
- Expression evaluator for conditional branching
- Process definition CRUD with draft/publish lifecycle
- Process instance management (start, suspend, terminate)
- Task service (pending, complete, delegate)
- PostgreSQL advisory locks for concurrent safety
- 5 database tables: process_definitions, process_instances,
  tokens, tasks, process_variables
- 13 API endpoints with RBAC protection
- Timeout checker framework (placeholder)

Frontend:
- Workflow page with 4 tabs (definitions, pending, completed, monitor)
- React Flow visual process designer (@xyflow/react)
- Process viewer with active node highlighting
- 3 API client modules for workflow endpoints
- Sidebar menu integration
2026-04-11 09:54:02 +08:00
iven
0baaf5f7ee feat(config): add system configuration module (Phase 3)
Implement the complete erp-config crate with:
- Data dictionaries (CRUD + items management)
- Dynamic menus (tree structure with role filtering)
- System settings (hierarchical: platform > tenant > org > user)
- Numbering rules (concurrency-safe via PostgreSQL advisory_lock)
- Theme and language configuration (via settings store)
- 6 database migrations (dictionaries, menus, settings, numbering_rules)
- Frontend Settings page with 5 tabs (dictionary, menu, numbering, settings, theme)

Refactor: move RBAC functions (require_permission) from erp-auth to erp-core
to avoid cross-module dependencies.

Add 20 new seed permissions for config module operations.
2026-04-11 08:09:19 +08:00
iven
8a012f6c6a feat(auth): add org/dept/position management, user page, and Phase 2 completion
Complete Phase 2 identity & authentication module:
- Organization CRUD with tree structure (parent_id + materialized path)
- Department CRUD nested under organizations with tree support
- Position CRUD nested under departments
- User management page with table, create/edit modal, role assignment
- Organization architecture page with 3-panel tree layout
- Frontend API layer for orgs/depts/positions
- Sidebar navigation updated with organization menu item
- Fix parse_ttl edge case for strings ending in 'd' (e.g. "invalid")
2026-04-11 04:00:32 +08:00
iven
6fd0288e7c feat(auth): add role/permission management (backend + frontend)
- RoleService: CRUD, assign_permissions, get_role_permissions
- PermissionService: list all tenant permissions
- Role handlers: 8 endpoints with RBAC permission checks
- Frontend Roles page: table, create/edit modal, permission assignment
- Frontend Roles API: full CRUD + permission operations
- Routes registered in AuthModule protected_routes
2026-04-11 03:46:54 +08:00