diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..77c8df8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +# Python +.venv/ +__pycache__/ +*.py[cod] +.pytest_cache/ + +# 本地数据库备份(仓库里已归档的历史备份不受影响) +data/*.bak +data/*.bak-* +data/exports/*.xlsx + +# 系统与编辑器 +.DS_Store diff --git a/.workbuddy/memory/2026-10-01.md b/.workbuddy/memory/2026-10-01.md new file mode 100644 index 0000000..5d8ce8b --- /dev/null +++ b/.workbuddy/memory/2026-10-01.md @@ -0,0 +1,47 @@ +# 2026-10-01 + +本轮目标(5 条):① 补表补代码做出**完整 RBAC** ② 修**跨季度财务统计** ③ 去掉冲突/不明确的交互 ④ 精简界面解释性文字 ⑤ 完整测试各模块。 +结果:83 个接口用例全绿(6.4s),8 个主菜单 + 全部子页签在浏览器实测无 console 报错、无横向溢出。 + +## ① RBAC 成体系(原来只有 `roles.menus` 一个 JSON 字段) + +- **新表**:`roles` / `role_menus`(授权矩阵,一行 = 一个菜单一个级别)/ `users` / `user_roles`(多角色)/ `user_sessions`(服务端 token)/ `audit_logs`(操作日志)。旧库用 `security.migrate_legacy_rbac()` 把 `roles.menus` JSON 迁进 `role_menus`,`users.menus` 迁进 `user_roles`。 +- **模型**:菜单 8 项 `MENUS`(board/projects/custom/focus/staff/intake/settings/rbac),级别 `ro` / `rw`,**表里没这行 = 看不到该菜单**;多角色取并集(`constants.merge_levels`,同菜单取更高级别)。 +- **两端同时管**:前端 `canR/canW/can` 过滤侧栏与写按钮;后端 `security.guard` 按 `SEGMENT_MENU`(路径首段 → 菜单)二次校验,**直接调接口绕不过去**。`/api/meta` 之类只要求登录。 +- **会话**:HttpOnly Cookie `unis_session`(`SESSION_DAYS=30`)。**只认 Cookie,不认自定义头**;退出/停用/改密/强制下线都是删 token → 立即失效。启动时 `purge_expired_sessions()` 清过期。 +- **防锁死**:`ensure_seed()` 保证系统里至少留一个 `rbac: rw` 的启用账号,没有就把「管理员」角色补给最早的用户;内置角色(管理员/部门成员/只读访客)禁止删除。 +- **界面**:新增「权限管理」四个子页签 —— 角色权限(授权矩阵)/ 用户 / 在线会话(可强制下线)/ 操作日志(按菜单+动作+时间过滤,可清空)。 +- **审计**:`app/audit.py` 统一记录写操作与登录行为(操作人/动作/菜单/接口/状态码/说明)。 +- **README 纠偏**:原文写「所有接口带 `X-Auth-Token`」「login 返回 `{token,user}`」「前端存 localStorage」,**与实现不符**,已改为 Cookie 事实。 + +## ② 跨季度财务统计:漏算「认不出季度」的项目 + +- **缺陷**:`finance.summary()` 的年度 KPI 只要求认得出**年份**,而年度任务表按**季度**分桶。像 `sign_date="2024/"`(库里确有 1 条:定制项目 id=6 郑州高新区…(AR城市云图),320000 元)这种「认得出年、认不出季」的行,**进了年度 KPI 却不进任何一季度** → 同屏「合计」比 KPI 少一笔(2024:50 个/669.93 万 vs 49 个/637.93 万)。验收侧同理(只有 `accept_year` 没有季度)。 +- **修法**:`finance.summary()` 新增 `sign_no_q` / `acc_no_q` → 输出 `kpi.sign_no_quarter` / `kpi.accept_no_quarter` 与 `annual.unscheduled`,**`annual.total` = 四个季度 + 未分季**(目标仍只累加四季)。前端只在 `unscheduled` 非 0 时才插一行「未分季」(目标/完成率显示 `—`),干净库不显示。 +- **不造假数据**:库里 `2024/` 原样保留(业务字面量不可改)。 +- **不变式**:**四季度 + 未分季 = 合计 = KPI 年度**(下单、验收两条口径都成立)。 +- **验证**:`tests/test_custom_finance.py` 加 2 例(脏数据计入年度并单列未分季 / 未分季为空不影响原合计);独立脚本跑 **2024~2027 × 12 个月 = 48 组**:季度归属正确、年度表不随所选月份漂移、合计/完成率/KPI 三者自洽。UI 实测 2024 显示未分季 1 个/32 万、合计 50 个/669.93 万;2026 无未分季行。 +- 口径唯一入口仍是 `app/finance.py`(`period_context` / `summary` / `read_annual_targets` / `is_placed` / `sign_period` / `accept_period`)。 + +## ③④ 交互冲突与界面冗余 + +- **人力资源花名册**:行内 3 个编辑控件(归属小组 / 人员归属 / 说明)与铅笔「编辑人员」弹窗**改同一批字段 = 两处入口打架**,还把「最近更新」列挤没(sticky 操作列遮挡,over=50)。→ **删掉行内控件与行内保存**,单元格改只读文本,统一走弹窗。复验 over=0 / overlap=0。 +- **权限矩阵**表格改 `tbl-tight`(左右内边距 8px)+ `.rbac-role{min-width:138px}`,「用户/操作」列不再被遮;角色名旁的「内置」标记与说明改成名称同行、说明另起行。 +- **设置页**数据库卡片改成两行事实:当前引擎 sqlite / 数据文件 `data/board.db`。 +- **删解释性长句**:更新录入两处 AI 预览页底部的「正文用你的原文,AI 只补…」整行删除;「没有取到当前周期的起止日期(刚更新过后端的话,请重启服务后刷新)」去掉括号里的碎碎念。 +- **保留**(判定为必要):删除确认里「请改用归档」的一行、直接写入/AI 整理的 radio 短注、登录页品牌语。 +- **术语统一**:模块③ 界面统一叫**定制项目**(原「定开项目」),README 里残留的 2 处「定开财务口径 / 定开财务」描述改为「定制项目」;`《定开项目.xlsx》` 是台账文件名,保留。 +- **宽台账横向滚动**(设计如此,不改):项目总览 17 列(over=622)、本周进展 16 列(over=478)都靠 `.tbl-wrap` 横向滚动,「操作」列 sticky 在右侧。实测滚到最右(scrollLeft=max)时最后一列「备注」与操作列**紧邻 gap=0**,不存在遮挡。 + +## ⑤ 测试与数据卫生 + +- `./.venv/bin/python -m pytest` → **83 passed**:`test_auth` / `test_rbac` / `test_custom_finance`(13) / `test_periods_projects` / `test_staff_focus_weekly` / `test_ai_export`;`conftest.py` 把 `DATABASE_URL` 指到临时库,**绝不碰 `data/board.db`**,每个用例重建表 + 重新补种。 +- 浏览器端逐个点 8 个主菜单与全部子页签:console 无报错,`pageOverflow=0`。 +- 清掉开发库里 **51 条脚本产生的会话**(Python-urllib / curl / testclient / UA 为空),只留 1 条真实浏览器会话,「在线会话」列表恢复可信。 +- 新增 `.gitignore`(`.venv/`、`__pycache__/`、`*.pyc`、`.pytest_cache/`、`data/*.bak*`、`.DS_Store`),并把误跟踪的 `app/**/__pycache__/*.pyc` 从索引里移除。 + +## 环境小抄(macOS) + +- 起服务:`run.sh`;健康检查 **`GET /health`**(不是 `/api/health`)。改后端要重启,改前端刷新即可。 +- 接口枚举:`/api` 是 Mount,得 `mount.app.openapi()["paths"]`,子 app 路径**不带 `/api` 前缀**。 +- 脚本登录:`http.cookiejar` + `POST /api/auth/login {username:admin,password:admin123}`,返回体是 user dict(**没有 token**),后续靠 Cookie。 diff --git a/.workbuddy/memory/MEMORY.md b/.workbuddy/memory/MEMORY.md index 4a9ac6f..8bb75f0 100644 --- a/.workbuddy/memory/MEMORY.md +++ b/.workbuddy/memory/MEMORY.md @@ -15,18 +15,20 @@ ## 关键结构 - `app/` 后端:`main.py`(入口,挂载 `/api` 子应用 + `/static`)、`models.py`、`schemas.py`、`constants.py`、`routers/{board,projects,custom,focus,weekly,staff,ai,export}.py`、`ai_parser.py`、`export.py`、`schema_patch.py`、`config.py`。 +- `app/finance.py`(定制项目财务口径**唯一入口**)、`app/audit.py`(操作日志写入)。 - `web/` 前端:`index.html` / `app.js` / `styles.css` / `icons.js`(零构建,no-cache + ETag)。 +- `tests/` + `pytest.ini` + `requirements-dev.txt`:接口级测试(83 例,`./.venv/bin/python -m pytest`),`conftest.py` 把库指到临时文件,**不碰 `data/board.db`**。 - `scripts/` 运维脚本:`init_db.py`、`import_excel.py`、`import_staff.py`、`migrate_custom.py`、`shift_year.py`、`fix_period_split.py`、`merge_project.py`、`add_entry_date.py`、**`import_custom_ledger.py`**(把《定开项目.xlsx》市场台账导入 `custom_projects`,支持 `--dry-run`/`--date`,按 项目ID→名称 匹配做 upsert + 变更比对)。 - `.workbuddy/memory/` 存每日工作日志(随仓库提交,2026-09-12 起)。 - `schema_patch.ensure_columns` 会在启动时自动给已有表补上模型里**新增的可空列**(`ALTER TABLE ... ADD COLUMN`),所以加字段只需改 `models.py`,不用写迁移脚本。 ## 业务模型 -四模块:① 工作看板(只读汇总 `/api/weekly`+`/api/focus`)② 项目管理(`projects`/`tasks`/`updates`)③ 定开项目(原「定制交付」,表 `custom_projects`/`custom_updates`)④ 每周重点工作(`weekly_focus`)。 -三支撑页:人力资源(`staff`,全系统负责人唯一来源)、更新录入、设置。 +四模块:① 工作看板(只读汇总 `/api/weekly`+`/api/focus`)② 项目管理(`projects`/`tasks`/`updates`)③ 定制项目(曾用名「定制交付」「定开项目」,表 `custom_projects`/`custom_updates`)④ 每周重点工作(`weekly_focus`)。 +四支撑页:人力资源(`staff`,全系统负责人唯一来源)、更新录入、设置、权限管理(`rbac`)。 ②③ 两套独立项目体系,共用一个花名册。 -### 定开项目的两套字段(2026-09-17 起) +### 定制项目的两套字段(2026-09-17 起) `custom_projects` 同时承载两套口径,**互不覆盖**: - **交付跟踪口径**(原有):`stage`(商务阶段)/`progress`/`revenue_amount`/`invoice_amount`/`received_amount`/`owner`(交付负责人,来自花名册) @@ -36,7 +38,7 @@ **`accept_date` vs `accept_date_real`**(2026-09-17 增):`accept_date` 存季度文本(Q1..Q4),只作展示;新增 **`accept_date_real`**(真实日期 YYYY-MM-DD)专门给「本月/本年验收」统计用。导入脚本会给「已验收 + 季度文本」的行补**当年季度末**占位(Q1→03-31…Q4→12-31),且**只在库中为空时补**,不覆盖界面手改的真日期。**统计口径(2026-09-20 定稿)**:下单看 `sign_date`(本季度/本年按日期归属);**验收看「验收时间」`accept_date`(季度文本 Q1~Q4)**——本季度验收 = `accept_date` 等于当前季度,本年验收 = 有验收时间(全部季度)。**不再用 `accept_date_real`**(它只作参考/展示,历史上有 4 条 Q3 行缺值,曾导致本季度验收少算)。 -明细表(`renderCustomList`)列顺序对齐 Excel 14 列 + 更新时间 + 操作;行内**只有「修改」**(详情靠点名称;归档按钮已按要求去掉)。**定开视图有 3 个 tab:项目明细 / 本周进展 / 年度任务**(`state.customTab`;原交付流水线 / 阶段看板 / 财务跟踪已下线)。列表在客户端按 关键字 + **项目归属** + 区域 + 状态 过滤。统计条 `.stat-row` 基于**全部已下单项目**(不随搜索/筛选变化):**已下单项目 / 合同额** + 本季度下单 + 本年新增下单 + 本季度验收 + 本年验收——**已下单 = 项目归属 ∈ {新签订单, 存量项目, 汇智直签}**(`isPlaced()` / `CUSTOM_PLACED`),**提前交付不计入下单**。「本周进展」tab(`renderCustomWeekly`)列出「更新时间」在本周(周一~周日)的项目,上方 3 张卡:**验收情况**(本周更新 ∩ 已验收)/ **本周新增项目**(按「下单时间」`sign_date` 在本周 ∩ 已下单或提前交付)/ **交付项目**(本周更新 ∩ 交付中+交付完成)。「年度任务」tab(`renderCustomAnnual`)按《年度任务.xlsx》出表:季度 + 计收目标(万元,前端常量 `CUSTOM_ANNUAL_TARGETS` = Q1 35/Q2 225/Q3 160/Q4 260)+ 回填列——**计收项目**(`accept_date` == Qn)/ **新增签单**(`isPlaced` 且 `sign_date` 在本年该季度),金额元→万元,完成率 = 计收金额 ÷ 目标。表格 `customTableHtml(rows)` 两个 tab 共用,在「项目状态」后新增**进度**列(`progress`,仅 状态=交付中 或 >0 时显示 `N%`)。项目名称搜索框**回车才查询**(`bindKeyword(id,{enter:true})`;cKeyword 定开 / pKeyword 项目已启用)。导出 Excel 列与明细表一致(15 列),跟随 归档/区域/状态/关键字 筛选。`openNewCustomDialog`(新建,更新录入页共用)字段同样对齐 Excel,提交时 `region` 由后端按 `office` 归一化(深圳→广东)。 +明细表(`renderCustomList`)列顺序对齐 Excel 14 列 + 更新时间 + 操作;行内**只有「修改」**(详情靠点名称;归档按钮已按要求去掉)。**定制项目视图有 3 个 tab:项目总览 / 本周进展 / 年度任务**(`#view-custom .ctab[data-ctab=list|weekly|annual]`)(`state.customTab`;原交付流水线 / 阶段看板 / 财务跟踪已下线)。列表在客户端按 关键字 + **项目归属** + 区域 + 状态 过滤。统计条 `.stat-row` 基于**全部已下单项目**(不随搜索/筛选变化):**已下单项目 / 合同额** + 本季度下单 + 本年新增下单 + 本季度验收 + 本年验收——**已下单 = 项目归属 ∈ {新签订单, 存量项目, 汇智直签}**(`isPlaced()` / `CUSTOM_PLACED`),**提前交付不计入下单**。「本周进展」tab(`renderCustomWeekly`)列出「更新时间」在本周(周一~周日)的项目,上方 3 张卡:**验收情况**(本周更新 ∩ 已验收)/ **本周新增项目**(按「下单时间」`sign_date` 在本周 ∩ 已下单或提前交付)/ **交付项目**(本周更新 ∩ 交付中+交付完成)。「年度任务」tab(`renderCustomAnnual`)按《年度任务.xlsx》出表:季度 + 计收目标(万元,前端常量 `CUSTOM_ANNUAL_TARGETS` = Q1 35/Q2 225/Q3 160/Q4 260)+ 回填列——**计收项目**(`accept_date` == Qn)/ **新增签单**(`isPlaced` 且 `sign_date` 在本年该季度),金额元→万元,完成率 = 计收金额 ÷ 目标。表格 `customTableHtml(rows)` 两个 tab 共用,在「项目状态」后新增**进度**列(`progress`,仅 状态=交付中 或 >0 时显示 `N%`)。项目名称搜索框**回车才查询**(`bindKeyword(id,{enter:true})`;cKeyword 定制 / pKeyword 自研已启用)。导出 Excel 列与明细表一致(15 列),跟随 归档/区域/状态/关键字 筛选。`openNewCustomDialog`(新建,更新录入页共用)字段同样对齐 Excel,提交时 `region` 由后端按 `office` 归一化(深圳→广东)。 **`update_date`(更新时间)的语义**:只在台账字段**确有变化**时才刷新(无变化不刷新)。 - **取值**:导入/初始 = 该行「下单时间」`sign_date`(2026-09-17 全量刷过);界面「修改 / 新建」提交后 = **提交时间** `YYYY-MM-DD HH:MM`(2026-09-18 起)。字段是 `String(16)`,正好放「YYYY-MM-DD HH:MM」。 @@ -45,14 +47,36 @@ 导入「市场责任人」等销售侧人名**不走花名册校验**,不要往 `staff` 里塞。 -## 登录与权限(2026-09-23 合并 main V 0.1.1 起) +## 登录与权限 / RBAC(2026-10-01 成体系) -- 全站需**登录**:未登录访问 `/api/*` 返回 **401**。默认管理员 **admin / admin123**(`app/config.py` 的 `ADMIN_PASSWORD` 默认值,可用 `.env` 覆盖);另有 `user`(部门成员)。 -- 权限模型:`roles.menus` 是 JSON(board/custom/focus/intake/projects/rbac/settings/staff,值 `rw` / `ro`);内置角色 管理员 / 部门成员 / 只读访客。代码:`app/security.py`(hashlib+hmac 手写,无新依赖)、`app/routers/auth.py`、`app/routers/rbac.py`;表 `users` / `roles` / `user_sessions`。 +- 全站需**登录**:未登录访问 `/api/*` 返回 **401**。默认管理员 **admin / admin123**(`app/config.py` 的 `ADMIN_PASSWORD`,可用 `.env` 覆盖);另有 `user`(部门成员)。 +- **三层模型**:`users` ←(`user_roles`)→ `roles` ←(`role_menus`)→ 菜单授权。`role_menus` 一行 = 一个菜单一个级别(`rw` 可编辑 / `ro` 只读),**表里没这行 = 看不到该菜单**;一个用户可挂多个角色,最终权限取**并集**(同菜单取更高级别,`constants.merge_levels` + `LEVEL_RANK`)。旧库由 `security.migrate_legacy_rbac()` 从 `roles.menus` / `users.menus` JSON 迁过来。`audit_logs` 记写操作与登录行为。 +- **两端同时管**:前端 `canR/canW/can` 过滤侧栏与写操作按钮;后端 `security.guard` 按 `SEGMENT_MENU`(接口路径首段 → 菜单)二次校验,直接调接口绕不过去。菜单 = `constants.MENUS` 八项:board / projects / custom / focus / staff / intake / settings / rbac。 +- **会话 = 服务端 token + HttpOnly Cookie `unis_session`**(`SESSION_DAYS=30`,启动时 `purge_expired_sessions()` 清过期)。**只认 Cookie,不认自定义头**;退出 / 停用 / 改密 / 强制下线都是删 token,立即失效。写脚本登录用 `http.cookiejar` + `POST /api/auth/login`,响应体是 user dict,**不含 token**。 +- **防锁死**:`ensure_seed()` 保证至少留一个 `rbac: rw` 的启用账号;内置角色(管理员 / 部门成员 / 只读访客)`is_builtin`,禁止删除。 +- **界面**:「权限管理」四个子页签 `#view-rbac .ctab[data-rbactab=roles|users|sessions|logs]`:角色权限(授权矩阵)/ 用户 / 在线会话(强制下线)/ 操作日志(菜单 + 动作 + 时间过滤,可清空)。 +- **密码**:pbkdf2(`hashlib` + `hmac` + `secrets`,标准库,**没有额外依赖**)。 -## 术语(2026-09-16 起) +## 定制项目财务口径(2026-10-01 定稿) -模块③ 的正式称呼是 **「定开项目」**(旧称「定制交付」),界面统一用「定开」:定开项目 / 定开项目明细 / 定开合同额 / 定开记录 / 定开动态 / 定开待计收。`categories` 表里也有一行分类叫「定开项目」。 +- **唯一入口 `app/finance.py`**:`period_context` / `summary` / `read_annual_targets` / `write_annual_targets` / `backfill` / `is_placed` / `sign_period` / `accept_period` / `accept_label`。路由与前端都不得自己算一遍。 +- **已下单** `is_placed` = `origin ∈ CUSTOM_PLACED_ORIGINS`(新签订单 / 存量项目 / 汇智直签);**提前交付不算下单**。 +- **下单归属**:`sign_period` = `parse_year_month(sign_date)` 再落到季度;**验收归属**:`accept_period` = (`accept_year`, `parse_quarter(accept_date)`),**刻意不看 `accept_date_real`**。 +- **年度目标**:`CUSTOM_ANNUAL_TARGETS_DEFAULT` = Q1 35 / Q2 225 / Q3 160 / Q4 260(万元),按年存 `Setting` 键 `custom_annual_targets:{年份}`。金额库内单位「元」,展示「万元」。 +- **未分季(2026-10-01 修)**:认得出年份但认不出季度的行(如 `sign_date="2024/"`)**必须计入年度**,否则同屏「合计」会比 KPI 少一笔。`summary()` 输出 `kpi.{sign,accept}_no_quarter` 与 `annual.unscheduled`,**`annual.total` = 四季度 + 未分季**(target 只累加四季)。前端仅在 `unscheduled` 非 0 时插一行「未分季」,目标/完成率显示 `—`。 +- **不变式**:**四季度 + 未分季 = 合计 = KPI 年度**(下单、验收两条口径都成立);年度表不随顶栏所选月份漂移(`current` 标记除外)。回归覆盖 4 年 × 12 月。 +- **脏数据留在库里**(如 `sign_date="2024/"` 的定制项目 id=6):不改业务字面量,靠口径容纳。 + +## 界面约定(2026-10-01) + +- **一处入口**:同一批字段只能有一个编辑入口。花名册的行内控件与「编辑人员」弹窗改同一批字段 → 已删行内控件,统一走弹窗。 +- **宽台账横向滚动是设计如此**:`.tbl-wrap{overflow-x:auto}`,「操作」列 sticky 在右。项目总览 17 列 / 本周进展 16 列都靠横向滚动,滚到最右时末列与操作列紧邻(gap=0),**不算遮挡**,别为了“消除溢出”去砍列。 +- **文案**:界面不放解释性长句;只保留删除确认里的「请改用归档」一行、直接写入/AI 整理的 radio 短注、登录页品牌语。 +- **表格紧凑**:列多时加 `tbl-tight`(左右内边距 8px)。 + +## 术语(2026-10-01 更新) + +模块③ 的界面称呼现在是 **「定制项目」**(`constants.MENUS` 里 `custom` 的标签),历史曾用名「定制交付」「定开项目」,界面与 README 已统一为「定制项目」。`categories` 表里仍有一行分类叫「定开项目」(业务数据,**不改**);`web/app.js` 里两处提到《定开项目.xlsx》的是台账文件名,保留。 **但这些字面量必须保留「定制」,改了会坏数据或逻辑**: - `"定制开发"` —— 历史 Excel 的项目容器名,是 `import_excel.py` / `migrate_custom.py` / `fix_period_split.py` / `add_entry_date.py` 里的匹配条件。 @@ -63,7 +87,8 @@ ## 约定 -- 当前开发分支:`develop-chezhiqi`(跟踪 `origin/develop-chezhiqi`;main 为发布线)。 +- 当前工作分支:`main`(`origin/develop-chezhiqi` 已并入,不再是开发线)。 +- 跑测试:`./.venv/bin/python -m pytest`(83 例,约 6.5s,用临时库)。前端语法自检:`node --check web/app.js`。 - 改代码后重启服务即可(未开 DEV 热加载)。 - 动数据库前先备份:`cp data/board.db data/board.db.bak`。 - 周期标签格式 `9月第1周`,可写 `2027年1月第1周` 显式指定年份。 diff --git a/README.md b/README.md index 8fe26a5..06897bb 100644 --- a/README.md +++ b/README.md @@ -7,11 +7,11 @@ | 模块 | 适用 | 关心什么 | 数据表 | |---|---|---|---| | **① 工作看板** | 每天进来的第一屏 | 三类工作本周期谁更新了、谁没动,点一条从一览看到详情 | 只读汇总(`/api/weekly` + `/api/focus`) | -| **② 项目管理** | NEX云桌面、AI Agent、智飞无人机平台、内部运营… | 长期重点项目的迭代执行、子任务进展、风险阻塞 | `projects` / `tasks` / `updates` | +| **② 自研产品** | NEX云桌面、AI Agent、智飞无人机平台、内部运营… | 长期重点项目的迭代执行、子任务进展、风险阻塞 | `projects` / `tasks` / `updates` | | **③ 定制项目** | 各省市客户定制子项目 | 商务阶段流转(签单→开发→交付→验收→计收)+ 按进度确认收入 | `custom_projects` / `custom_updates` | | **④ 每周重点工作** | 不值得单独建项目档案的短期活儿 | 一条就是一件事,面板里录,归在**录入周**这一周,跟到完成 | `weekly_focus` | -支撑页三个:**人力资源**(`staff`,全系统「负责人」的唯一来源)、**更新录入**(执行 / 交付记录的唯一写入口:粘贴原文 → AI 整理 → 确认写入)、**设置**(周期管理、AI 配置)。 +支撑页四个:**人力资源**(`staff`,全系统「负责人」的唯一来源)、**更新录入**(执行 / 交付记录的唯一写入口:粘贴原文 → AI 整理 → 确认写入)、**设置**(周期管理、AI 配置)、**权限管理**(角色 × 菜单授权、账号、在线会话、操作审计)。 ②③ 是**两套彼此独立的项目体系**(数据表也完全分开),共用一个**人力资源库**:项目与定制项目的「负责人」都从花名册里选,人员进出只维护一处。④ 的条目不是项目,不挂子任务与执行记录。① 只做汇总与跳转,自己不落数据。 @@ -201,13 +201,12 @@ ssh user@host 'cd /srv/unis_manager && ./deploy.sh up' | **左栏** | **三组**清单,顺序固定:① **本周工作重点**(列表,逾期的置顶)② **重点项目**(列表:`is_key` 的项目,另含本期补了执行记录的非重点项目,条目前用 ★ 区分)③ **定制项目**——**只给一个入口**「本周定制项目动态」,左栏不铺清单(100 多个项目会淹没看板),点开才在右栏列本周有动态的。组头显示条数与「几个已更新 / 几条逾期 / 本周动态几个」;每条带负责人、状态或阶段、本期摘要、风险条数,本期有记录的点亮标记 | | **右栏** | 点左栏任意一条即可联动。重点项目 → 本期执行记录 / 进度与状态(含子任务)/ 近 8 期趋势;**定制项目入口 → 本周动态总览**(顶部标签:本周新增 / 本周验收 / 有交付动态 / 合同额合计 / 本期计收,下面分「本周新增」「本周验收」「本周有变化」三段,每条带阶段、负责人、金额、本期计收与摘要),点某一条再下钻到该项目 → 交付环节五段条 / 财务跟踪四联卡 + 开票·回款行内输入 / 本期交付记录 / 更早的交付记录,改开票、回款、环节日期即时保存(改日期会自动推进商务阶段);每周重点工作 → 只读的说明与状态,要改点「修改」开抽屉 | | 工具栏 | 「负责人」筛选、「导出本周期记录」,提示里带本期项目数与定制动态数;顶栏可切周 / 月视图(月视图自动汇总该月所有周)。「列入全部在途」开关(`all_custom`)不在工具栏,挪到了右栏定制总览的头部 | -| 统计概览 | 页面最底部的折叠区(原「执行面板」,已不占主导航位):周期活跃度柱状图、分类环形图、状态分布、进度 Top10、低进度预警、风险清单,数据来自 `GET /api/stats`;加载失败也不影响看板主体 | 数据分两路:`GET /api/weekly?period_id=|year&month&owner=&all_custom=` 一次返回重点项目清单 + 定制项目清单 + 顶部 KPI(含 `custom_new` 本期新入库数、`custom_updated` 本期有交付记录数);**「本周工作重点」不在 `/api/weekly` 里**,前端并发取 `GET /api/focus` 后合并,分堆也在这一步判定(按条目的**录入周**:本周录入的 + 更早周次标了「延期」又没做完的结转条目)。 定制项目的口径:`/api/weekly` 返回**本期有交付记录**、**被标为重点**、**本周期新入库**(`is_new`:入库日期落在本周期首末日之内)、**本周期新下单**(`sign_date` 落在本周期)或**本周期已验收**(`update_date` 落在本周期且项目状态为「已验收」)的定制项目;右栏总览默认列「本周新增」「本周验收」「本周有变化」三段,其中**前两段与「定制项目 → 本周进展」的「新增项目 / 验收情况」口径完全一致**(前者按「下单时间」、后者按「更新时间 + 状态=已验收」),其余只在组头计数里出现,并在底部提示「另有 N 个在途定制项目本周没有动态」。勾选总览头部的「列入全部在途」后,后端补上处于在途阶段(商机 → 已验收)的项目,总览多出一段「其他在途项目」。头部几枚标签与「合同额合计」只加总**当前列出来的行**(同一项目同时落在两段时只算一次),勾与不勾数字会跟着清单变。 -### 2. 项目管理 +### 2. 自研产品(项目管理) 长期重点项目(`projects` + `tasks` + `updates`)。执行记录的写入逻辑没变,仍旧统一走「更新录入」。 @@ -215,15 +214,13 @@ ssh user@host 'cd /srv/unis_manager && ./deploy.sh up' |---|---| | **项目管理** | 表格展示分类、负责人、状态、进度、更新情况(标签只在详情抽屉里维护,列表不放,避免挤占名称列);**列表只读**,行内不放任何输入框和下拉,每行只有 **详情 / 修改 / 归档** 三个按钮(操作列吸附在表格右侧,横向滚动也不会被挤出可视区);负责人筛选下拉来自人力资源库;支持新建与「含归档」筛选。详情抽屉里的**周期反馈**可切「按周 / 按月」与「本周 · 近 4 周 · 近 12 周 · 全部」(按月为「本月 · 近 3 月 · 近 6 月 · 全部」),用 ‹ › 翻页看更早的周期,默认跟随顶栏选中的周期 | -> 「执行面板」不再单列模块,已折进工作看板底部的「统计概览」折叠区。 - #### 项目维护操作 | 操作 | 说明 | |---|---| -| **面板分区** | 抽屉用标准对话框式标题栏:**标题在左(下面一行副标题),基础信息的操作按钮成排在右,✕ 在最右**,按钮条嵌在标题栏里(不悬浮、不吸顶,滚动时跟着标题栏常驻)。详情档是「删除 · 归档/恢复 · 标记重点 · **修改**」,修改与新增档是「取消 · **保存/添加**」,主按钮永远在最右、危险动作在最左,按钮文字不再重复对象名(标题栏已经写了是哪个项目/条目)。附表的写入另放一处:**绿虚线 = 附表 · 更新记录**条仍留在它自己的附表标题下面,只有「+ 录一笔「某周期」执行记录 / 交付记录」,点它跳到「更新录入」并自动带上该项目与顶栏当前选中的周期。附表的写入统一走更新录入(粘贴原文 → AI 整理 → 确认写入),抽屉里不另做一套表单,避免两条路写出两份数据。基础信息的按钮在标题栏、附表的更新按钮在附表上方,两类按钮不在同一个位置混着放;编辑与新增档的报错信息显示在正文最上方;周期反馈上方的 按周/按月 + 本周/近 4 周/… 标成「查看范围(只读筛选)」,只翻看不改数据 | +| **面板分区** | 抽屉用标准对话框式标题栏:**标题在左(下面一行副标题),基础信息的操作按钮成排在右,✕ 在最右**,按钮条嵌在标题栏里(不悬浮、不吸顶,滚动时跟着标题栏常驻)。详情档是「删除 · 归档/恢复 · 标记重点 · **修改**」,修改与新增档是「取消 · **保存/添加**」,主按钮永远在最右、危险动作在最左,按钮文字不再重复对象名(标题栏已经写了是哪个项目/条目)。附表的写入只有一处入口:附表标题下的「添加执行记录」,它跳到「更新录入」并带上该项目与顶栏当前周期——抽屉里不另做一套基础信息之外的录入表单,避免两条路写出两份数据;改某一条已有记录用的是行内「修改」,走全站唯一的记录弹窗(`openUpdateDialog`,看板右栏与定制抽屉共用)。基础信息的按钮在标题栏、附表的更新按钮在附表上方,两类按钮不在同一个位置混着放;编辑与新增档的报错信息显示在正文最上方;周期反馈上方的 按周/按月 + 本周/近 4 周/… 标成「查看范围(只读筛选)」,只翻看不改数据 | | **改名** | 改名就是改基本信息:在详情面板点「修改」,表单第一行即项目名称(项目管理与定制项目同一套逻辑)。名称非空校验 + 重名检测,失败信息显示在面板正文最上方,不弹提示跑路 | -| **负责人与团队** | **多负责人只适用于重点项目**:重点项目可以指定**多个负责人**与**团队成员**,定制项目只有一个**交付负责人**(单人下拉)外加**团队成员**。人名一律从人力资源库下拉里选。**界面上负责人不分主次**:名单横向排开自动换行,每一位都带 × 可删(没有「主」标记、没有不给删的首行),「+ 添加负责人 / + 添加成员」跟在名单末尾。名单只在详情抽屉的「修改」档维护;只读处一律一排对等的小标签:重点项目的列表与详情把负责人摆成对等的一排,定制项目的列表与详情只显示一个交付负责人加团队成员标签。存储与统计口径不变:**重点项目 `owner` 字段仍是 `owners[0]`**(删掉第一位就由后一位顶上),看板、导出、人力负载与 KPI 按它归属,修改档的提示行写明了这点;重点项目**所有负责人都算命中**,定制项目按交付负责人命中;团队成员不参与该筛选 | +| **负责人与团队** | **多负责人只适用于重点项目**:重点项目可以指定**多个负责人**与**团队成员**,定制项目只有一个**交付负责人**(单人下拉)外加**团队成员**。人名一律从人力资源库下拉里选。**界面上负责人不分主次**:名单横向排开自动换行,每一位都带 × 可删(没有「主」标记、没有不给删的首行),「+ 添加负责人 / + 添加成员」跟在名单末尾。名单只在详情抽屉的「修改」档维护;只读处一律一排对等的小标签:重点项目的列表与详情把负责人摆成对等的一排,定制项目的列表与详情只显示一个交付负责人加团队成员标签。存储与统计口径不变:**重点项目 `owner` 字段仍是 `owners[0]`**(删掉第一位就由后一位顶上),看板、导出、人力负载与 KPI 按它归属;重点项目**所有负责人都算命中**,定制项目按交付负责人命中;团队成员不参与该筛选 | | **归档** | 项目从看板与列表默认视图中隐藏,数据完整保留;勾选「含归档」可查看,随时可恢复 | | **删除** | 高危操作:弹窗列出将连带删除的子任务数与执行记录数,并且必须**逐字输入项目名称**,「永久删除」按钮才会点亮。**删除后不可恢复**,仅想隐藏请用归档 | @@ -246,13 +243,16 @@ python scripts/merge_project.py --from "智空无人机平台" --to "智飞无 ### 3. 定制项目 -| 模块 | 说明 | +三个页签,都跟着顶栏周期走:**项目总览**(默认)· **本周进展** · **年度任务**。 +统计条与年度任务只认 `GET /api/custom/finance` 一个数据源,口径见「财务统计口径」。 + +| 页签 / 模块 | 说明 | |---|---| -| **交付流水线**(默认页签) | 卡头给「在库 N 个 · 重点 N 个 · 本期更新 N 个」,漏斗本身按环节给项目数与金额(页签上不再叠一条全局 KPI 带,金额与项目数按环节累计);「入库 → 签单 → 交付 → 验收 → 计收」五段漏斗,每段给项目数与金额;口径为**商务阶段 + 已录环节日期**取先到哪一步算哪一步(环节日期还没补全时由商务阶段兜底)。下方「卡点项目」列出最后一个**有日期**的环节停留超过 `CUSTOM_STEP_AGING_DAYS`(默认 45)天且尚未计收的项目,可一键「处理」跳到详情抽屉补录 | -| **阶段看板** | 按「商机 → 已签单 → 开发中 → 交付完成 → 已验收 → 已计收 → 暂停/异常」分列展示,卡片带金额、区域、开发进度、可确认收入;列头显示项目数与金额合计。卡片只是入口,点卡片开详情抽屉;卡上的 ★ 只读(重点标记在详情面板的基础信息区改),外层不做任何直接写入 | -| **财务跟踪** | 页签内一排 KPI:合同总额 / 按进度可确认收入 / 已计收 / 待计收 / 已开票 / 已回款 / 待开票 / 待回款(各带比例脚注);再往下是阶段金额分布、周期活跃度、按负责人与区域汇总、待回款排行。财务口径的汇总只在这一页出现,环节与账期一屏对齐,方便财务逐月对账 | -| **项目明细** | 表头一行给出当前列表的合同额 / 可确认 / 已计收 / 开票 / 回款合计;按入库时间倒序的**只读**总表:区域 / 负责人 / **入库 · 签单 · 交付 · 验收日期** / 阶段 / 合同额 / 进度 / 可确认 / 已计收 / **开票 / 回款**(金额列统一以「万」计)/ 备注;改数据点行尾「修改」 | -| **详情抽屉** | 分「详情 / 修改」两档:详情只读,修改才给表单(含项目名称、手动确认比例、**交付环节五个日期**、区域下拉、**开票与回款金额**)+ 收入确认卡 + 周期执行记录 + 阶段流转时间线。负责人从人力资源库里选。基础信息的动作在标题栏按钮条上(修改/保存,正文里标明不会动下面的交付记录),开票与回款金额跟着标题栏的「保存」一起提交;附表的绿虚线条(「+ 录一笔」跳更新录入 · 定制项目并带上项目与周期)留在附表标题下 | +| **项目总览** | 标题栏下一排统计条:已下单项目/合同额、本季度下单、本年新增下单、本季度验收、本年验收(金额按「万」显示,脚注项目数)。下面是按更新时间倒序的**只读**总表:项目名称 / 项目ID / 下单时间 / 项目归属 / 办事处 / 行业 / 市场下单人天 / 订单金额 / 市场责任人 / 项目状态 / 进度 / 验收时间 / 推动验收计划 / 风险值 / 更新时间;下单时间、订单金额、更新时间三列表头可点着排序。筛选只有关键字 + 归属 + 区域 + 项目状态 + 风险值。台账里认不出的写法(下单时间识别不了、已验收没填验收年度)在标题栏挂一枚提示标签,不挡事 | +| **本周进展** | 更新时间落在顶栏选中周期内的项目;统计条给「验收情况 / 新增项目 / 进行中项目」,其中新增与验收和工作看板右栏共用同一套口径(`customWeeklySections`),两处数字必然一致 | +| **年度任务** | 四个季度的计收目标(万元)与完成情况对照。完成额按「验收年度 + 验收季度」归集、下单按下单时间所在季度归集,跨年不会串;默认只读,点「编辑」才能改,改数字实时重算完成率与合计,保存走 `PUT /api/custom/annual-targets?year=` | +| **详情抽屉** | 分「详情 / 修改」两档:详情只读(基础信息 + 收入确认四联卡 + 开票 / 回款行内输入 + 交付记录 + 阶段流转时间线),修改才给表单(名称、手动确认比例、交付环节日期、区域、**验收年度 + 验收季度**成对填写、开票与回款金额)。交付负责人是单人下拉,从人力资源库里选;「添加交付记录」在交付记录区里,一个弹窗录本周期一条 | +| **归档** | 归档后不再出现在总览与统计中,历史周期记录完整保留,随时恢复 | ### 4. 每周重点工作 @@ -271,6 +271,12 @@ python scripts/merge_project.py --from "智空无人机平台" --to "智飞无 分堆口径(基准周 = 顶栏选中的那一周,一律按**录入周**算,和预计完成时间无关):录入周**等于**基准周 → **本周**;录入周**早于**基准周且「是否延期」打开且未完成 → **延期**(上周及更早没做完的活儿结转进来);状态为「已完成」→ **已完成**(交叉视图,条目仍留在自己那一周)。 「更早周次录入、没标延期又没完成」的条目不进当周视图,只在**全部**里查得到——所以每周收尾时,没做完的记得勾上「延期」,它才会结转进下周。库里不存「逾期」字段,延期是人工开关。 +### 5. 权限管理 + +`角色 × 菜单` 授权矩阵、账号与角色分配、在线会话、操作审计四个区块,一个页面四个页签。 +权限模型、内置角色与防锁死规则见「权限(RBAC)」,这里不重复。 +只有拿到 `rbac` 可编辑的账号能看到这个菜单。 + ### 人力资源库 侧栏「人力资源」,是全系统**负责人姓名的唯一来源**(`staff` 表)。 @@ -325,6 +331,33 @@ python scripts/add_entry_date.py --force # 全部重算 - 历史数据里若出现「内蒙古自治区」这类非规范写法,保存时会自动归一为「内蒙古」 - 早期从项目名推断的区域(`infer_region`)与标准列表口径一致,无需迁移 +## 权限(RBAC) + +侧栏每个菜单都是一个权限点,**授权 = 角色 × 菜单 × 级别**;账号不直接挂菜单,只挂角色。 + +| 概念 | 取值 | 说明 | +|---|---|---| +| 菜单 | `board` 工作看板 · `projects` 自研产品 · `custom` 定制项目 · `focus` 每周工作 · `staff` 人力资源 · `intake` 更新录入 · `settings` 设置 · `rbac` 权限管理 | 见 `constants.MENUS`,顺序即权限页里的列顺序 | +| 级别 | 空 = 看不到 / `ro` 只读 / `rw` 可编辑 | 没授权的菜单侧栏不出现,接口也进不去;`ro` 能看列表与详情,所有写接口一律 403 | + +- **多角色取并集、同级取高**:一个账号可挂多个角色,同一菜单只要有一个角色给了 `rw` 就是 `rw`(`constants.merge_levels`)。 +- **双端校验**:前端 `can()` / `canW()` 只负责把按钮藏起来,真正的门在接口上—— + 每个路由都挂了 `security` 的权限依赖,按路径首段映射菜单(`SEGMENT_MENU`), + 读请求要求 `ro`、写请求要求 `rw`;越权返回 403 并记一条 `audit_logs`(`action=deny`)。 + `/api/auth/*`、`/api/meta` 这类只要求登录,不看菜单,否则无法登录与自助改密。 +- **内置角色**:`管理员`(全部 `rw`)、`部门成员`(业务菜单 `rw`,设置与权限只读/无)、`只读访客`(除权限外全部 `ro`), + `is_builtin` 标记,不能删除。 +- **不会被锁死**:系统始终保证至少有一个「启用 + 权限管理可编辑」的账号; + 一个都没有时 `security.ensure_seed` 会把「管理员」角色补给最早的账号并在启动日志里提示。 +- **改权限即踢会话**:改角色授权 → 踢掉该角色下所有账号的会话;改/停账号 → 踢掉该账号的会话。 + 旧 token 不会继续带着旧权限跑。 +- **会话**:登录发 32 位随机 token,存 `user_sessions`(有效期 `SESSION_DAYS`,默认 30 天), + 只通过 `HttpOnly` Cookie `unis_session` 下发(JS 读不到,前端不存 token); + 权限管理页可查看全部在线会话并单独吊销。 +- **操作审计**:写操作与登录 / 登出 / 越权都落 `audit_logs`(谁、什么时间、哪个菜单、什么动作、返回码、IP), + 权限管理页可按菜单、动作、天数筛选。 +- 首个管理员账号来自 `.env` 的 `ADMIN_USERNAME` / `ADMIN_PASSWORD`(默认 `admin` / `admin123`,登录后请立刻改密码)。 + ## 界面设计语言 前端是零构建的原生 JS(`web/index.html` + `web/styles.css` + `web/app.js` + `web/icons.js`),设计口径固定如下,新增页面请沿用: @@ -357,6 +390,33 @@ python scripts/add_entry_date.py --force # 全部重算 导出的 xlsx 带表头样式、冻结首行、自动筛选,金额列按千分位格式;文件名含导出日期。 +## 财务统计口径 + +定制项目的金额统计全部收敛在 `app/finance.py`,页面、工作看板、导出都从它取数,**不存在第二套算法**。 + +| 口径 | 认定方式 | +|---|---| +| 已下单 | 只看项目归属:`origin ∈ {华智下单, 存量项目, 汇智直签}`;`提前交付` 不算下单 | +| 下单归属季度 / 年度 | `sign_date` 的 `YYYY-MM` 前缀;认不出年份的计入 `kpi.sign_unknown`,页面上提示补录 | +| 验收归属季度 / 年度 | **只认 `accept_year` + `accept_date`(Q1~Q4)**;`accept_date_real` 已停用,不再参与统计 | +| 未分季 | 认得出年份、认不出季度的行(`sign_date` 残缺成「2024/」、或只有 `accept_year` 没有 `accept_date`):计入年度,年度任务表里单列「未分季」一行 | +| 计收 | 累计看主档 `revenue_amount`;本周期新增看 `custom_updates.revenue_delta` 之和 | +| 金额单位 | 项目金额一律 **元**;年度计收目标一律 **万元**(`wanVal()` 录入时换算,接口按字段名区分) | + +- 统计范围跟顶栏周期走:`?period_id=` 看一周,`?year=&month=` 看一月,季度由月份自动归(`quarter_of_month`)。 + 跨季度、跨年度只以 `context.year` / `context.quarter` 为准,不会因为库里存在别的年份就串到别的季度去。 +- **年度计收目标**(`GET|PUT /api/custom/annual-targets?year=`):**存过就以库里为准**,某季度清空即 0; + 完全没配过的年份才回落到 `constants.CUSTOM_ANNUAL_TARGETS_DEFAULT`。目标值写非数字返回 400。 +- 验收年度与季度成对校验:只给其中一个 → 400,避免出现「有 Q3 没年份」这种没法归类的行。 +- **年度任务表的不变式**:`四个季度 + 未分季 = 合计 = KPI 年度`(下单、验收两条口径都成立)。 + 历史库里确实有「有年份没季度」的行,早期版本会让它们从季度表里静默消失, + 于是同一屏上「合计」比 KPI 年度少一笔;现在单列一行,既不丢数也不硬塞进某个季度。 + `annual.unscheduled` 给出笔数与金额,`kpi.sign_no_quarter` / `kpi.accept_no_quarter` 是计数。 +- **周期记录里的 `amount_delta` / `revenue_delta` 是增量,会同步落到项目主档**: + 新建记录 → 主档累加;修改记录 → 按新旧差额回补;删除记录 → 一并扣回。 + AI 写入时「parsed 给了 `amount` 绝对值就用绝对值,否则累加明细增量」,两条路只走一条,不会重复计。 +- 历史数据可疑时执行 `finance.backfill(db)`(幂等,可反复跑):按上面的口径重算验收年份与商务阶段。 + ## 收入确认口径 定制项目按**完工百分比法**确认收入: @@ -398,8 +458,14 @@ CustomProject(名称, 客户, 区域, 合同额, 阶段, 开发进度, 手动确 WeeklyFocus(工作内容, 说明, 录入周→Period, 预计完成时间, 执行状态, 是否延期, 结果反馈, 归档) Staff(姓名, 归属小组, 人员归属, 说明, 排序, 归档) # 花名册:所有「负责人 / 团队成员」下拉的唯一来源 -Category / Tag / Setting / ImportLog +Category / Tag / Setting(AI 配置、年度计收目标 custom_annual_targets:{年份}) / ImportLog(AI 整理留痕) LedgerItem(客户项目台账) # 只剩模型与 Excel 导入解析,界面无入口、接口已下线 + +# 权限(RBAC) +Role(名称, 说明, is_builtin) ── RoleMenu(菜单, 级别 ro|rw) # 授权矩阵:角色 × 菜单 +User(姓名, 账号, 口令散列+盐, 是否启用, 最近登录) ── UserRole(用户, 角色) # 多角色,权限取并集取高 +UserSession(token, 用户, 过期时间, IP, UA) # 会话,可按角色/账号吊销 +AuditLog(用户, 动作 create|update|delete|login|logout|deny, 菜单, 方法, 路径, 状态码, IP, 详情) ``` 原表映射关系: @@ -424,6 +490,19 @@ LedgerItem(客户项目台账) # 只剩模型与 Excel 导入解析,界面 - 阶段判定做了特殊处理:文本里同时出现「已计收」和「进度 60%」时判为**开发中**,计收金额由 `revenue_delta` 承载。 - 解析结果写入前始终提供**可编辑预览**,确认后才落库,并留痕到 `import_logs`。 +## 测试 + +```bash +./.venv/bin/pip install -r requirements-dev.txt -i https://pypi.tuna.tsinghua.edu.cn/simple +./.venv/bin/python -m pytest # 81 个用例,几秒钟跑完 +``` + +- 测试跑在临时库里:`tests/conftest.py` 在 import 业务模块之前就把 `DATABASE_URL` 指向临时文件,**不会碰 `data/board.db`**。 +- 每个用例重建表结构并重新补种内置角色与管理员,用例之间互不污染;`AI_API_KEY` 置空, + AI 相关用例走确定性的本地规则解析,不联网。 +- 覆盖范围:登录 / 口令 / 会话限流、RBAC 授权矩阵与越权与审计、周期与项目与执行记录、 + 定制项目财务口径(跨季度、跨年回归)、年度目标、花名册 / 每周重点 / 工作看板、AI 整理与六类 Excel 导出。 + ## 迁移到 MySQL 1. 安装驱动:`pip install pymysql cryptography` @@ -440,15 +519,21 @@ LedgerItem(客户项目台账) # 只剩模型与 Excel 导入解析,界面 ``` app/ main.py FastAPI 入口(API 挂载在 /api,静态页面在 /) - config.py 配置与 .env 加载(DATABASE_URL、AI 参数) + config.py 配置与 .env 加载(DATABASE_URL、AI 参数、SESSION_DAYS) db.py engine / Session(按 URL 自动适配方言) - models.py ORM 模型(项目 + 定制项目 + 每周重点工作 + 花名册) - constants.py 状态/阶段常量、收入确认比例、区域与阶段识别 + models.py ORM 模型(项目 + 定制项目 + 每周重点工作 + 花名册 + RBAC) + constants.py 状态/阶段常量、收入确认比例、区域与阶段识别、权限菜单目录 + security.py 口令散列、会话、权限解析与路由依赖(RBAC 的门) + audit.py 操作审计写入 + finance.py 定制项目财务口径唯一入口(下单/验收归属、年度目标、回填) + export.py xlsx 生成(表头样式、冻结、筛选、金额千分位) ai_parser.py LLM 解析 + 本地规则兜底(通用 / 定制两套) - routers/ board(周期/元数据/统计) · weekly(工作看板数据) · projects(项目管理) · - custom(定制项目) · focus(每周重点工作) · staff(人力) · ai · export -web/ index.html · styles.css · app.js(零依赖,无构建步骤) -scripts/ init_db.py · import_excel.py · migrate_custom.py · import_staff.py · add_entry_date.py · merge_project.py · shift_year.py + routers/ auth · rbac(角色/账号/会话/审计) · board(周期/元数据) · weekly(看板数据) · + projects · custom(定制项目 + 财务) · focus · staff · ai · export +web/ index.html · styles.css · app.js · icons.js(零依赖,无构建步骤) +tests/ pytest 接口测试(conftest 用临时库,绝不碰 data/board.db) +scripts/ init_db.py · import_excel.py · import_custom_ledger.py · migrate_custom.py · import_staff.py + add_entry_date.py · fix_period_split.py · merge_project.py · shift_year.py data/board.db SQLite 数据库 Dockerfile 运行镜像(依赖 + 代码,启动时自动补表/预置分类) docker-compose.yml 部署编排(./data 持久化、HOST_PORT、健康检查) @@ -458,52 +543,90 @@ deploy.sh 部署命令封装:up / update / restart / down / logs / ## API 速览 +鉴权走 **HttpOnly Cookie `unis_session`**(由 `/api/auth/login` 下发,只认 Cookie,不认自定义头); +除 `/api/auth/login` 与 `/health` 外,所有接口都要求已登录,否则 401。 +写操作(POST/PATCH/PUT/DELETE)额外要求对应菜单是 `rw`,越权返回 403 并留审计。 + ``` +# 登录与自助 +POST /api/auth/login {username,password} → 当前用户;会话 token 只写在 Set-Cookie 里 +POST /api/auth/logout 吊销当前会话 +GET /api/auth/me 当前账号 + 角色 + 菜单权限表(前端据此渲染侧栏) +PUT /api/auth/me 改自己的姓名 +POST /api/auth/password 改自己的密码(改完踢掉其它会话) + +# 权限管理 +GET /api/rbac/meta 菜单目录 + 级别字典 + 内置角色 +GET|POST /api/rbac/roles 角色清单(含授权矩阵)/ 新建角色 +PATCH|DELETE /api/rbac/roles/{id} 改名称、说明、menus({菜单: ro|rw});改授权会踢掉该角色的会话 +GET|POST /api/rbac/users 账号清单 / 新建账号(role_ids 分配角色) +PATCH|DELETE /api/rbac/users/{id} 改资料、启停、重设密码;停用即吊销会话 +POST /api/rbac/users/{id}/revoke 只吊销某个账号的全部会话 +GET /api/rbac/sessions 在线会话(用户、IP、UA、到期、token 摘要) +DELETE /api/rbac/sessions/{token} 吊销单个会话 +GET|DELETE /api/rbac/logs 操作审计 ?username=&menu=&action=&days=&limit= / DELETE 按 days 清理 + # 通用 -GET /api/meta 状态字典 / 优先级 / AI 配置状态 -GET /api/periods 周列表 + 按月聚合(含各周期记录数;today_id = 今天所在的周,顶栏默认落它) -POST /api/periods 新增周期(传 label 如「9月第1周」,年份自动接续) -DELETE /api/periods/{id} 删除空周期(有记录则拒绝) -GET /api/board?period_id=|year&month 周期汇总(页面主链路不走它,统计走 /api/stats) -GET /api/stats?period_id=|year&month -GET /api/weekly?period_id=|year&month&owner=&all_custom= 工作看板:重点项目 + 定制项目本周动态 + KPI - (custom_new 本期新入库 / custom_updated 本期有交付记录;行上带 is_new) - (左栏第一组「本周工作重点」前端另取 /api/focus 合并) -GET /api/projects (?archived=false|true|all) -POST /api/projects PATCH /api/projects/{id} DELETE /api/projects/{id} - (owners/members 传人名数组,整体替换:不传=不改,传 []=清空;owners[0] 回写 owner 列供归属统计,界面不再区分主次) -GET /api/categories POST /api/categories PATCH /api/categories/{id} DELETE /api/categories/{id} +GET /api/meta 状态字典 / 优先级 / 菜单 / AI 配置状态 +GET /api/periods 周列表 + 按月聚合(today_id = 今天所在的周,顶栏默认落它;没有会自动补建) +POST /api/periods 新增周期(传 label 如「9月第1周」,年份自动接续;重复提交返回已有的) +DELETE /api/periods/{id} 删除空周期(有记录则拒绝) +GET /api/weekly?period_id=|year&month&owner=&all_custom= + 工作看板:重点项目 + 定制项目本周动态 + KPI + (行上带 is_new / updated_this_period / idle_weeks / worst_status; + 非重点且本周无记录的默认不列出,all_custom=true 才列出在途定制; + 没有任何周期时返回全键 0 值骨架,前端不用兜底) +GET /api/projects (?archived=false|true|all&category_id=&is_key=&keyword=&owner=&period_id=|year&month) +POST /api/projects PATCH|DELETE /api/projects/{id} + (owners/members 传人名数组,整体替换:不传=不改,传 []=清空;owners[0] 回写 owner 列) +GET|POST /api/categories PATCH|DELETE /api/categories/{id} +GET|POST /api/tags DELETE /api/tags/{id} +POST /api/tasks 项目子任务 +GET /api/updates?project_id=&period_id=|year&month&limit= + 周期执行记录(月粒度含该月各周;范围内没有周期就返回空,不回落到最新周) +POST /api/updates 写入口校验:项目/周期必须存在、状态合法、正文与摘要不能都空 +PATCH|DELETE /api/updates/{id} # 定制项目 -GET /api/custom/meta 阶段字典 + 区域列表 + 交付环节(pipeline) + 卡点阈值(aging_days) -GET /api/custom/projects?stage=®ion=&keyword= -POST /api/custom/projects PATCH /api/custom/projects/{id} DELETE /api/custom/projects/{id} - (owner 是单个人名;members 传人名数组,整体替换:不传=不改,传 []=清空。不再接受 owners,多负责人只属于重点项目) -GET /api/custom/board?period_id=|year&month 阶段看板 -GET /api/custom/stats?period_id=|year&month 收入统计 -POST /api/custom/updates -POST /api/custom/ai/parse 粘贴文本 → 结构化预览 -POST /api/custom/ai/commit 确认写入 +GET /api/custom/meta 阶段字典 + 区域列表 + 交付环节(pipeline) + 卡点阈值(aging_days) +GET /api/custom/projects?stage=®ion=&keyword=&archived=&key_only=&owner= +POST /api/custom/projects PATCH|DELETE /api/custom/projects/{id} + (owner 是单个人名;members 传人名数组整体替换;不再接受 owners,多负责人只属于重点项目) +POST /api/custom/updates PATCH|DELETE /api/custom/updates/{id} + (amount_delta / revenue_delta 是增量,会自动累加/回补主档金额,见「财务统计口径」) +GET /api/custom/finance?period_id=|year&month + 财务汇总:context(年/月/季度区间) + kpi(下单、季度与年度验收、计收…) + 年度任务表 +GET|PUT /api/custom/annual-targets?year= 年度计收目标(万元)。存过就以库里为准,非数字返回 400 + +# AI 整理(两套体系各自独立;未配 Key 自动降级为本地规则解析) +POST /api/ai/parse 粘贴原文 → 结构化预览。**只读**:写了新项目名也不会建项目 +POST /api/ai/commit 确认写入:按 tasks 建子任务与执行记录(同名子任务复用),回写主档,留痕 import_logs +POST /api/custom/ai/parse 定制版预览(阶段/合同额/本期计收/本期明细) +POST /api/custom/ai/commit 定制版写入:按名称自动建档,绝对值优先、否则累加明细增量 # 每周重点工作 -GET /api/focus?archived=false|true|all&status=&keyword= 条目清单(period_id/period_label/sort_key 都是**录入周**,分堆由调用方判定) -POST /api/focus PATCH /api/focus/{id} DELETE /api/focus/{id} - 单条增改删;工作内容非空。period_id=录入周(前端传顶栏当前周, - 不传后端按今天所在的周补;due_date 只是目标日期,不改归属周) - 或直接给 period_id(必须存在);两者都不给 → 400 +GET /api/focus?archived=false|true|all&status=&keyword= + 条目清单(period_id / period_label 都是**录入周**,分堆由调用方判定) +POST /api/focus 工作内容非空;period_id=录入周(前端传顶栏当前周,不传按今天所在的周补) +PATCH|DELETE /api/focus/{id} 改 due_date 不会搬走归属周 # 人力资源库 -GET /api/staff?archived=false|true|all&group=&keyword= 花名册 + 各自工作量 + 花名册外负责人 + 小组/归属字典 -POST /api/staff PATCH /api/staff/{id} DELETE /api/staff/{id}(名下有项目时拒绝,离职请归档) +GET /api/staff?archived=false|true|all&group=&keyword= + 花名册 + 各自负载(在管/重点/定制数、定制合同额、待计收)+ 花名册外负责人 + 小组与归属字典 +POST /api/staff PATCH|DELETE /api/staff/{id} + (姓名与花名册重名返回 400;名下有项目时禁止直接删除,提示先归档,?force=true 才强制删; + 改名会把项目与定制项目上的负责人一起同步,返回值 synced 说明同步了几条) # 其他 -GET /api/settings PUT /api/settings +GET|PUT /api/settings AI 配置等(PUT 需要 settings 可编辑) -# 导出(均返回 xlsx) -GET /api/export/custom ?region=&stage=&keyword=&archived= -GET /api/export/custom-updates ?period_id=|year&month -GET /api/export/projects ?category_id=&keyword=&archived= -GET /api/export/staff ?archived=false|true|all -GET /api/export/focus ?archived=false|true|all&status=&keyword= -GET /api/export/updates ?period_id=|year&month&project_id= +# 导出(均返回 xlsx,筛选口径与页面对应) +GET /api/export/custom ?region=&origin=&status=&risk=&accept_plan=&keyword=&archived=false|true|all(末尾带合计行) +GET /api/export/custom-updates ?period_id=|year&month +GET /api/export/projects ?category_id=&keyword=&archived=false|true|all(默认 all) +GET /api/export/updates ?period_id=|year&month&project_id= +GET /api/export/staff ?archived=false|true|all +GET /api/export/focus ?archived=false|true|all&status=&keyword= + 导出与接口的差别:范围解析不出周期时导出给全量(让人把数据带走), + 接口则返回空(避免把「没数据」看成「全周期数据」) ``` diff --git a/app/__pycache__/__init__.cpython-313.pyc b/app/__pycache__/__init__.cpython-313.pyc deleted file mode 100644 index 178c3a9..0000000 Binary files a/app/__pycache__/__init__.cpython-313.pyc and /dev/null differ diff --git a/app/__pycache__/ai_parser.cpython-313.pyc b/app/__pycache__/ai_parser.cpython-313.pyc deleted file mode 100644 index 8c30824..0000000 Binary files a/app/__pycache__/ai_parser.cpython-313.pyc and /dev/null differ diff --git a/app/__pycache__/config.cpython-313.pyc b/app/__pycache__/config.cpython-313.pyc deleted file mode 100644 index 0a0cf21..0000000 Binary files a/app/__pycache__/config.cpython-313.pyc and /dev/null differ diff --git a/app/__pycache__/constants.cpython-313.pyc b/app/__pycache__/constants.cpython-313.pyc deleted file mode 100644 index 7d37c08..0000000 Binary files a/app/__pycache__/constants.cpython-313.pyc and /dev/null differ diff --git a/app/__pycache__/db.cpython-313.pyc b/app/__pycache__/db.cpython-313.pyc deleted file mode 100644 index b5623ad..0000000 Binary files a/app/__pycache__/db.cpython-313.pyc and /dev/null differ diff --git a/app/__pycache__/export.cpython-313.pyc b/app/__pycache__/export.cpython-313.pyc deleted file mode 100644 index 3070798..0000000 Binary files a/app/__pycache__/export.cpython-313.pyc and /dev/null differ diff --git a/app/__pycache__/main.cpython-313.pyc b/app/__pycache__/main.cpython-313.pyc deleted file mode 100644 index 8c1b9e9..0000000 Binary files a/app/__pycache__/main.cpython-313.pyc and /dev/null differ diff --git a/app/__pycache__/models.cpython-313.pyc b/app/__pycache__/models.cpython-313.pyc deleted file mode 100644 index f42c98b..0000000 Binary files a/app/__pycache__/models.cpython-313.pyc and /dev/null differ diff --git a/app/__pycache__/schema_patch.cpython-313.pyc b/app/__pycache__/schema_patch.cpython-313.pyc deleted file mode 100644 index e697d73..0000000 Binary files a/app/__pycache__/schema_patch.cpython-313.pyc and /dev/null differ diff --git a/app/__pycache__/schemas.cpython-312.pyc b/app/__pycache__/schemas.cpython-312.pyc deleted file mode 100644 index 9d6c575..0000000 Binary files a/app/__pycache__/schemas.cpython-312.pyc and /dev/null differ diff --git a/app/__pycache__/schemas.cpython-313.pyc b/app/__pycache__/schemas.cpython-313.pyc deleted file mode 100644 index 8e0694c..0000000 Binary files a/app/__pycache__/schemas.cpython-313.pyc and /dev/null differ diff --git a/app/__pycache__/security.cpython-313.pyc b/app/__pycache__/security.cpython-313.pyc deleted file mode 100644 index 07d3c57..0000000 Binary files a/app/__pycache__/security.cpython-313.pyc and /dev/null differ diff --git a/app/audit.py b/app/audit.py new file mode 100644 index 0000000..cfdb10e --- /dev/null +++ b/app/audit.py @@ -0,0 +1,118 @@ +"""操作审计:谁在什么时候改了哪个菜单的数据,成功还是被拒。 + +写入口只有一个:`/api` 子应用上的 HTTP 中间件。它在每个请求结束后落一行, +所以 401/403(越权尝试)和 4xx/5xx(失败的写操作)同样留痕。 +只记写操作 + 登录/退出,GET 不落库,避免日志被列表刷新刷爆。 +业务代码可以用 `audit.note(request, "……")` 补一句说明,日志的「说明」列直接可读。 +""" +from __future__ import annotations + +from datetime import timedelta + +from fastapi import Request +from sqlalchemy.orm import Session + +from .db import SessionLocal +from .models import AuditLog, now + +# 命中这些路径前缀的 GET 也要留痕(登录相关) +TRACKED_GETS = () +# 方法 → 动作 +METHOD_ACTION = {"POST": "create", "PUT": "update", "PATCH": "update", "DELETE": "delete"} +# 特殊动作:路径以这些结尾时按语义记,不套 method 默认值 +SPECIAL_ACTION = { + "/api/auth/login": "login", + "/api/auth/logout": "logout", + "/api/auth/password": "password", +} +KEEP_DAYS = 180 # 日志保留天数,启动时清一次 + + +def client_ip(request: Request) -> str | None: + fwd = request.headers.get("x-forwarded-for") + if fwd: + return fwd.split(",")[0].strip()[:64] + return request.client.host[:64] if request.client else None + + +def action_for(path: str, method: str) -> str | None: + """返回 None 表示这个请求不进审计。""" + clean = path.rstrip("/") + if clean in SPECIAL_ACTION: + return SPECIAL_ACTION[clean] + if method in METHOD_ACTION: + return METHOD_ACTION[method] + if clean.endswith("/revoke") or clean.endswith("/purge"): + return "revoke" + return None + + +def note(request: Request, text: str | None = None, *, username: str | None = None) -> None: + """业务代码给审计日志留一句人话说明;落库由中间件完成。 + + `username` 只在拿不到登录用户时用得上(比如密码输错,操作人记的是被尝试的账号)。 + """ + try: + if text: + request.state.audit_detail = text[:255] + if username: + request.state.audit_username = username[:64] + except Exception: # 审计说明是锦上添花,不能带崩业务 + pass + + +def write(db: Session, *, user, request: Request, status: int, action: str, + menu: str | None = None, detail: str | None = None, + username: str | None = None) -> None: + db.add(AuditLog( + user_id=getattr(user, "id", None), + username=username or getattr(user, "username", None), + action=action, + menu=menu, + method=request.method, + path=request.url.path[:255], + status=status, + ip=client_ip(request), + detail=detail[:255] if detail else None, + )) + db.commit() + + +def prune(db: Session, keep_days: int = KEEP_DAYS) -> int: + q = db.query(AuditLog).filter(AuditLog.created_at < now() - timedelta(days=keep_days)) + n = q.count() + if n: + q.delete(synchronize_session=False) + db.commit() + return n + + +def audit_middleware_factory(): + """给 /api 子应用用的中间件:写完响应后补一条审计。""" + + async def audit(request: Request, call_next): + from .security import resolve_rule # 避免循环导入 + + action = action_for(request.url.path, request.method) + response = await call_next(request) + if action is None: + return response + path = request.url.path.rstrip("/") + rule = resolve_rule(path, request.method) + menu = rule[0] if rule else None + state = getattr(request, "state", None) + user = getattr(state, "user", None) + actor = getattr(state, "audit_username", None) + detail = getattr(state, "audit_detail", None) + if response.status_code >= 400: + detail = f"{detail};" if detail else "" + detail += f"HTTP {response.status_code}" + try: + with SessionLocal() as db: + write(db, user=user, request=request, status=response.status_code, + action=action, menu=menu, detail=detail, username=actor) + except Exception: # 审计绝不能把业务请求带崩 + pass + return response + + return audit diff --git a/app/constants.py b/app/constants.py index 201e856..f864191 100644 --- a/app/constants.py +++ b/app/constants.py @@ -36,6 +36,42 @@ LEDGER_CATEGORIES = [ "异常项目", ] +# -------------------------------------------------------------------------- +# 权限菜单目录(前后端共用:键是权限标识,顺序即权限管理页里的展示顺序) +# rw = 可编辑(含新增/修改/删除/导出写入口) +# ro = 只读(能看列表与详情,所有写接口一律 403) +# 没有这个菜单 = 侧栏看不到、接口也进不去 +# -------------------------------------------------------------------------- +MENUS = [ + ("board", "工作看板"), + ("projects", "自研产品"), + ("custom", "定制项目"), + ("focus", "每周工作"), + ("staff", "人力资源"), + ("intake", "更新录入"), + ("settings", "设置"), + ("rbac", "权限管理"), +] +MENU_KEYS = [k for k, _ in MENUS] +MENU_LABELS = dict(MENUS) +LEVELS = ("ro", "rw") +LEVEL_LABELS = {"rw": "可编辑", "ro": "只读", "": "无权限"} +# 多角色并集时比大小用 +LEVEL_RANK = {"": 0, "ro": 1, "rw": 2} + + +def merge_levels(*maps: dict) -> dict: + """把多张菜单权限表合成一张:同一菜单取更高级别。""" + out: dict[str, str] = {} + for m in maps: + for menu, level in (m or {}).items(): + if menu not in MENU_LABELS: + continue + if LEVEL_RANK.get(level, 0) > LEVEL_RANK.get(out.get(menu, ""), 0): + out[menu] = level + return out + + # -------------------------------------------------------------------------- # 定制项目(交付制,与平台产品类项目分开管理) # (code, 名称, 颜色, 收入确认基准比例) @@ -59,13 +95,20 @@ CUSTOM_STAGE_CODES = [c for c, _, _, _ in CUSTOM_STAGES] CUSTOM_STAGE_ORDER = {c: i for i, (c, _, _, _) in enumerate(CUSTOM_STAGES)} -def custom_revenue_ratio(stage: str, progress: float | None, manual_ratio=None) -> float: - """按阶段 + 开发进度计算收入确认比例(0~1)。""" +def custom_revenue_ratio(stage: str, progress: float | None, manual_ratio=None, + project_status: str | None = None) -> float: + """按阶段 + 开发进度计算收入确认比例(0~1)。 + + 手动比例 manual_ratio 优先;其次「退单」一律按 0 计(阶段虽落到 closed, + 但退单没有收入,不能让已关闭项目的基准比例把金额算进来)。 + """ if manual_ratio is not None: try: return max(0.0, min(1.0, float(manual_ratio))) except (TypeError, ValueError): pass + if (project_status or "").strip() == CUSTOM_NO_REVENUE_STATUS and manual_ratio is None: + return 0.0 base = CUSTOM_STAGE_MAP.get(stage, ("", "#94a3b8", 0.0))[2] if stage == "developing": p = float(progress or 0) @@ -405,3 +448,84 @@ def normalize_staff_affiliation(value: str | None) -> str | None: if a in v: return a return v + + +# -------------------------------------------------------------------------- +# 定制项目:项目状态(台账口径)→ 商务阶段(内部推导,不再单独维护) +# 界面上只有「项目状态」可编辑,商务阶段(含收入确认比例)由它推导, +# 避免出现两套状态互相打架。 +# -------------------------------------------------------------------------- +CUSTOM_STATUSES = ["待开发", "进行中", "交付完成", "已验收", "退单"] +CUSTOM_STATUS_STAGE = { + "待开发": "signed", + "进行中": "developing", + "交付完成": "delivered", + "已验收": "accepted", + "退单": "closed", +} +# 反向:AI 录入等只认阶段的入口,写回项目状态 +CUSTOM_STAGE_STATUS = { + "signed": "待开发", "developing": "进行中", "delivered": "交付完成", + "accepted": "已验收", "revenue": "已验收", "closed": "退单", + "paused": "进行中", "lead": "待开发", +} +# 退单不确认收入(阶段落到 closed,但比例按 0 处理) +CUSTOM_NO_REVENUE_STATUS = "退单" + +# 项目归属:前三项算「已下单」,提前交付是下单前状态 +CUSTOM_ORIGINS = ["华智下单", "存量项目", "汇智直签", "提前交付"] +CUSTOM_PLACED_ORIGINS = ("华智下单", "存量项目", "汇智直签") + +# 行业 / 风险值:台账里的下拉取值,前端一律从 /custom/meta 取,不再各写一份 +CUSTOM_INDUSTRIES = ["安平", "政府", "企业", "教育", "交通", "医疗", "高速", "行业", "其他"] +CUSTOM_RISKS = ["1.高风险", "2.低风险"] + + +def derive_stage(project_status: str | None, fallback: str | None = None) -> str: + """按项目状态推导商务阶段;状态没填时保留原阶段。""" + return CUSTOM_STATUS_STAGE.get((project_status or "").strip(), fallback or "signed") + + +# -------------------------------------------------------------------------- +# 年 / 季度:财务统计的时间归属只在这里判定一次(前端不再自己算季度) +# -------------------------------------------------------------------------- +def quarter_of_month(month: int) -> int: + """月份 1~12 → 季度 1~4。""" + return (int(month) - 1) // 3 + 1 + + +def parse_quarter(text) -> int | None: + """「Q3」/「q3」→ 3;其他写法一律不认(验收季度在界面上是下拉选项,脏文本不认才不会串统计)。""" + s = str(text or "").strip().upper() + if len(s) == 2 and s[0] == "Q" and s[1] in "1234": + return int(s[1]) + return None + + +def parse_year_month(text) -> tuple[int, int] | None: + """从「下单时间」这类可能带脏文本的字段里取 (年, 月);取不到月份时月份为 0。 + + 认:2026-03-31 / 2026/3/31 / 2026-3 / 2026年3月 / 2026年 / 2026。 + 「2024年3月前」这种能识别出 2024 年 3 月(前缀匹配),只用于年份归属。 + """ + import re + + s = str(text or "").strip() + if not s: + return None + m = re.search(r"(20\d{2})\s*[-/年.]\s*(\d{1,2})", s) + if m: + year, month = int(m.group(1)), int(m.group(2)) + return (year, month) if 1 <= month <= 12 else (year, 0) + m = re.search(r"(20\d{2})", s) + return (int(m.group(1)), 0) if m else None + + +def quarter_end(year: int, quarter: int) -> str: + """季度末日期(YYYY-MM-DD),用于按季度派生验收日期。""" + import calendar + import datetime + + last_month = int(quarter) * 3 + day = calendar.monthrange(int(year), last_month)[1] + return datetime.date(int(year), last_month, day).isoformat() diff --git a/app/finance.py b/app/finance.py new file mode 100644 index 0000000..6b09114 --- /dev/null +++ b/app/finance.py @@ -0,0 +1,264 @@ +"""定开项目财务口径:时间归属 + 季度 / 年度统计 + 年度计收目标。 + +历史数据有三个坑,统一在这里处理,前端只消费结果: + · `accept_date` 只写季度(Q1~Q4)没有年份,跨年就混在一起(2025Q3 和 2026Q3 + 都算「Q3」)→ 新增 `accept_year`,启动时按真实验收日期回填一次; + · `accept_date_real` 是当年导入脚本按「季度末」补的占位日期,不能当统计依据 → 停用; + · `sign_date` 存过自由文本(「2024年3月前」)→ 能识别出年份的才进年/季度口径。 + +统计周期以顶栏选中的周期为准:`period_id`(周)或 `year+month`(月), +由后端换算成所属「年份 + 季度」,切到历史周期看到的就还是那一年的数。 +""" +from __future__ import annotations + +import json +from datetime import date + +from sqlalchemy.orm import Session + +from .constants import ( + CUSTOM_ANNUAL_TARGETS_DEFAULT, + CUSTOM_PLACED_ORIGINS, + derive_stage, + parse_quarter, + parse_year_month, + quarter_end, + quarter_of_month, +) +from .models import CustomProject, Period, Setting, now + +__all__ = [ + "period_context", "accept_period", "sign_period", "accept_label", "is_placed", + "summary", "read_annual_targets", "write_annual_targets", "backfill", +] + + +# ---------------------------------------------------------------- 统计上下文 +def period_context(db: Session, period_id: int | None = None, + year: int | None = None, month: int | None = None) -> dict: + """把顶栏选中的周期换算成「年份 + 季度」,没选就取今天所在的年月。""" + label = "" + if period_id: + per = db.get(Period, period_id) + if per is not None: + year, month = per.year, per.month + label = per.full_label + if not year or not month: + today = date.today() + year = int(year) if year else today.year + month = int(month) if month else today.month + month = min(12, max(1, int(month))) + year = int(year) + q = quarter_of_month(month) + return { + "period_id": period_id, + "year": year, + "month": month, + "quarter": q, + "label": label or f"{year}年{month}月", + "quarter_label": f"{year}年Q{q}", + "quarter_start": f"{year}-{(q - 1) * 3 + 1:02d}-01", + "quarter_end": quarter_end(year, q), + } + + +# ---------------------------------------------------------------- 时间归属 +def is_placed(cp: CustomProject) -> bool: + """已下单 = 项目归属属于「华智下单 / 存量项目 / 汇智直签」。""" + return (cp.origin or "").strip() in CUSTOM_PLACED_ORIGINS + + +def sign_period(cp: CustomProject) -> tuple[int | None, int | None]: + """下单时间 → (年份, 季度);文本认不出年份时返回 (None, None)。""" + ym = parse_year_month(cp.sign_date) + if not ym: + return None, None + year, month = ym + return year, quarter_of_month(month) if month else None + + +def accept_period(cp: CustomProject) -> tuple[int | None, int | None]: + """验收时间 → (年份, 季度)。年份只认 `accept_year`(缺年度就按「未定」不计入任何年份)。 + + 刻意不看 `accept_date_real`:那是导入脚本按季度末补的占位日期, + 用它兜底会把「没填验收时间」的项目算进某一年,清掉年度也清不掉。 + 老数据的一次性补齐在 `backfill()` 里做。 + """ + return (cp.accept_year or None), parse_quarter(cp.accept_date) + + +def accept_label(cp: CustomProject) -> str: + """界面上的验收时间:「2026Q3」;缺什么显示什么,全空返回空串。""" + year, q = accept_period(cp) + if year and q: + return f"{year}Q{q}" + if q: + return f"Q{q}" + return str(year) if year else "" + + +# ---------------------------------------------------------------- 年度计收目标 +ANNUAL_TARGETS_PREFIX = "custom_annual_targets" + + +def _targets_key(year: int) -> str: + return f"{ANNUAL_TARGETS_PREFIX}:{year}" + + +def read_annual_targets(db: Session, year: int) -> dict[str, float]: + """按年取四个季度的计收目标(万元);没配过的年份用默认值。""" + row = db.get(Setting, _targets_key(year)) + # 没配过的年份用默认值;配过就以库里为准——在界面上清空某一季,读回来就得是 0 + saved = None + if row and row.value: + try: + parsed = json.loads(row.value) + saved = parsed if isinstance(parsed, dict) else None + except (TypeError, ValueError): + saved = None + if saved is None: + saved = {str(q): v for q, v in CUSTOM_ANNUAL_TARGETS_DEFAULT.items()} + targets: dict[str, float] = {} + for q in (1, 2, 3, 4): + v = saved.get(str(q)) + try: + targets[str(q)] = 0.0 if v in (None, "") else round(float(v), 2) + except (TypeError, ValueError): + targets[str(q)] = 0.0 + return targets + + +def write_annual_targets(db: Session, year: int, targets: dict) -> dict[str, float]: + clean: dict[str, float] = {} + for q in (1, 2, 3, 4): + v = (targets or {}).get(str(q)) + if v is None or v == "": + clean[str(q)] = 0.0 + continue + try: + clean[str(q)] = round(float(v), 2) + except (TypeError, ValueError): + raise ValueError(f"Q{q} 目标值不是数字") + value = json.dumps(clean, ensure_ascii=False) + row = db.get(Setting, _targets_key(year)) + if row: + row.value = value + else: + db.add(Setting(key=_targets_key(year), value=value)) + db.commit() + return clean + + +# ---------------------------------------------------------------- 统计 +def _sum(rows) -> float: + return round(sum(float(r.amount or 0) for r in rows), 2) + + +def summary(db: Session, ctx: dict) -> dict: + """定开财务汇总:KPI(当前季度 / 年度)+ 年度任务表(该年四个季度 + 未分季)。 + + 金额单位一律「元」,展示层再折算万元;目标值是「万元」。 + 「未分季」= 认得出年份、认不出季度(`sign_date` 只有「2024/」这类残缺值、 + 或只有 `accept_year` 没有 `accept_date`)的项目:它们计入年度, + 但不属于任何一季度,所以单列一行,保证「四季度 + 未分季 = 合计 = KPI 年度」。 + """ + year, q = ctx["year"], ctx["quarter"] + rows = db.query(CustomProject).filter(CustomProject.archived.is_(False)).all() + placed = [r for r in rows if is_placed(r)] + + def signed(yy, qq): + return [r for r in placed + if (sy := sign_period(r))[0] == yy and (qq is None or sy[1] == qq)] + + def accepted(yy, qq): + return [r for r in rows + if (ap := accept_period(r))[0] == yy and (qq is None or ap[1] == qq)] + + def kpi(items): + return {"count": len(items), "amount": _sum(items)} + + sign_q, sign_y = signed(year, q), signed(year, None) + acc_q, acc_y = accepted(year, q), accepted(year, None) + # 数据质量:识别不出下单年份 / 缺验收年份的项目,页面上给计数,不静默漏算 + sign_unknown = [r for r in placed if sign_period(r)[0] is None] + acc_no_year = [r for r in rows if accept_period(r)[1] and not accept_period(r)[0]] + # 有年份、无季度:计入年度,不进任何一季度 + sign_no_q = [r for r in placed if (sy := sign_period(r))[0] == year and sy[1] is None] + acc_no_q = [r for r in rows if (ap := accept_period(r))[0] == year and ap[1] is None] + + targets = read_annual_targets(db, year) + quarters = [] + for i in (1, 2, 3, 4): + acc, sgn = accepted(year, i), signed(year, i) + target = targets[str(i)] + amount = _sum(acc) + quarters.append({ + "q": i, + "target": target, # 万元 + "acc_count": len(acc), "acc_amount": amount, # 元 + "sign_count": len(sgn), "sign_amount": _sum(sgn), + "rate": round(amount / 10000 / target, 4) if target else None, + "current": i == q, + }) + return { + "context": ctx, + "kpi": { + "placed": kpi(placed), + "sign_quarter": kpi(sign_q), + "sign_year": kpi(sign_y), + "accept_quarter": kpi(acc_q), + "accept_year": kpi(acc_y), + "sign_unknown": len(sign_unknown), + "accept_no_year": len(acc_no_year), + "sign_no_quarter": len(sign_no_q), + "accept_no_quarter": len(acc_no_q), + }, + "annual": { + "year": year, + "targets": targets, + "quarters": quarters, + "unscheduled": { + "acc_count": len(acc_no_q), "acc_amount": _sum(acc_no_q), + "sign_count": len(sign_no_q), "sign_amount": _sum(sign_no_q), + }, + "total": { + "target": round(sum(t["target"] for t in quarters), 2), + "acc_count": sum(t["acc_count"] for t in quarters) + len(acc_no_q), + "acc_amount": round(sum(t["acc_amount"] for t in quarters) + _sum(acc_no_q), 2), + "sign_count": sum(t["sign_count"] for t in quarters) + len(sign_no_q), + "sign_amount": round(sum(t["sign_amount"] for t in quarters) + _sum(sign_no_q), 2), + }, + }, + "generated_at": now().isoformat(timespec="seconds"), + } + + +# ---------------------------------------------------------------- 老库回填 +def backfill(db: Session) -> list[str]: + """幂等回填:验收年份 + 由项目状态推导商务阶段。只在缺值 / 不一致时写。""" + notes: list[str] = [] + rows = db.query(CustomProject).all() + # 台账按年维护,缺年份的老行按库里出现过的最晚验收年份补(不随「今天」漂移) + known = [ym[0] for r in rows + if (ym := parse_year_month(r.accept_date_real)) and parse_quarter(r.accept_date)] + fallback = max(known) if known else None + years = stages = 0 + for r in rows: + if r.accept_year is None and parse_quarter(r.accept_date): + ym = parse_year_month(r.accept_date_real) + r.accept_year = ym[0] if ym else fallback + if r.accept_year: + years += 1 + status = (r.project_status or "").strip() + if status: + want = derive_stage(status, r.stage) + if r.stage != want: + r.stage = want + stages += 1 + if years or stages: + db.commit() + if years: + notes.append(f"已补齐定制项目验收年份 {years} 条") + if stages: + notes.append(f"已按项目状态推导商务阶段 {stages} 条") + return notes diff --git a/app/main.py b/app/main.py index 75c4fc8..f79b109 100644 --- a/app/main.py +++ b/app/main.py @@ -7,7 +7,7 @@ from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse from fastapi.staticfiles import StaticFiles -from . import config, security +from . import audit, config, finance, security from .db import Base, SessionLocal, engine from .routers import ai, auth, board, custom, export, focus, projects, rbac, staff, weekly from .schema_patch import ensure_columns @@ -17,10 +17,17 @@ _patch = ensure_columns(engine, Base.metadata) if _patch: print(f"[ok] 已补齐数据库字段:{', '.join(_patch)}") -# 内置角色 + 管理员账号(只在缺失时补,不会覆盖已改过的密码/权限) +# 权限模型升级(旧库的 roles.menus / users.role_id → role_menus / user_roles)+ 内置角色与管理员 +for _note in security.migrate_legacy_rbac(engine): + print(f"[ok] {_note}") with SessionLocal() as _db: for _note in security.ensure_seed(_db): print(f"[ok] {_note}") + security.purge_expired_sessions(_db) + audit.prune(_db) + # 定开财务口径回填(验收年份 / 由项目状态推导阶段),幂等 + for _note in finance.backfill(_db): + print(f"[ok] {_note}") # 每次进程启动换一个值;热加载重启后前端据此自动刷新 BOOT_ID = uuid.uuid4().hex @@ -36,6 +43,7 @@ app.add_middleware( # 所有 /api 接口先过 RBAC 总闸(登录 + 菜单权限),登录接口自身除外 api = FastAPI(title="DMS管理平台 API", dependencies=[Depends(security.guard)]) +api.middleware("http")(audit.audit_middleware_factory()) api.include_router(board.router, prefix="", tags=["board"]) api.include_router(projects.router, prefix="", tags=["projects"]) api.include_router(ai.router, prefix="", tags=["ai"]) diff --git a/app/models.py b/app/models.py index 74e95b1..7222ef1 100644 --- a/app/models.py +++ b/app/models.py @@ -22,6 +22,7 @@ from sqlalchemy import ( ) from sqlalchemy.orm import Mapped, mapped_column, relationship +from .constants import LEVEL_RANK, merge_levels from .db import Base @@ -208,6 +209,11 @@ class Period(Base): updates: Mapped[list["Update"]] = relationship(back_populates="period") + @property + def full_label(self) -> str: + """「2026年10月第2周」:label 只有「10月第2周」,跨年展示一律用这个。""" + return f"{self.year}年{self.month}月" + (f"第{self.week}周" if self.week else "") + def to_dict(self): return { "id": self.id, @@ -219,7 +225,7 @@ class Period(Base): "start_date": self.start_date, "end_date": self.end_date, "sort_key": self.sort_key, - "full_label": f"{self.year}年{self.month}月" + (f"第{self.week}周" if self.week else ""), + "full_label": self.full_label, } @@ -436,9 +442,11 @@ class CustomProject(Base, TimestampMixin): update_date: Mapped[str | None] = mapped_column( String(16), nullable=True, index=True ) # 更新时间 YYYY-MM-DD:该行数据最后一次变动的日期,用于按周查看变化 + # 验收年份:accept_date 只有季度(Q1~Q4),跨统计年度时必须靠它区分 2025Q3 与 2026Q3 + accept_year: Mapped[int | None] = mapped_column(Integer, nullable=True, index=True) accept_date_real: Mapped[str | None] = mapped_column( String(16), nullable=True, index=True - ) # 验收日期 YYYY-MM-DD(真实日期):与 accept_date(季度文本)区分,用于「本月/本年验收」统计 + ) # 已停用:早期导入脚本按季度末补的占位日期。验收时间统一看 accept_year + accept_date updates: Mapped[list["CustomUpdate"]] = relationship( back_populates="project", cascade="all, delete-orphan" @@ -446,8 +454,11 @@ class CustomProject(Base, TimestampMixin): def to_dict(self, with_revenue: bool = True): from .constants import custom_revenue_ratio + from .finance import accept_label - ratio = custom_revenue_ratio(self.stage, self.progress, self.manual_ratio) + ratio = custom_revenue_ratio( + self.stage, self.progress, self.manual_ratio, self.project_status + ) data = { "id": self.id, "name": self.name, @@ -484,6 +495,8 @@ class CustomProject(Base, TimestampMixin): "risk_level": self.risk_level, "update_date": self.update_date, "accept_date_real": self.accept_date_real, + "accept_year": self.accept_year, + "accept_label": accept_label(self), "update_count": len(self.updates), "updated_at": self.updated_at.isoformat(timespec="seconds") if self.updated_at else None, } @@ -620,29 +633,26 @@ class ImportLog(Base): # ---------------------------------------------------------------------- 权限 +# 三层模型:用户 ←(多对多)→ 角色 ←(一对多)→ 菜单授权 +# user_roles :一个用户可以挂多个角色,权限取并集(同一菜单取更高级别) +# role_menus :角色的菜单授权矩阵,一行 = 一个菜单一个级别(rw / ro) +# audit_logs :写操作与登录行为的审计流水 class Role(Base, TimestampMixin): - """角色 = 一组功能菜单权限。 - - menus 存 JSON 文本:{"board":"rw","projects":"ro"}, - 键是菜单标识(见 security.MENUS),值 rw=可编辑 / ro=只读;没有这个键就是看不到该菜单。 - """ + """角色 = 一组菜单授权(rw 可编辑 / ro 只读 / 没有这一行就是看不到)。""" __tablename__ = "roles" id: Mapped[int] = mapped_column(Integer, primary_key=True) name: Mapped[str] = mapped_column(String(64), unique=True, nullable=False) description: Mapped[str | None] = mapped_column(String(255), nullable=True) - menus: Mapped[str | None] = mapped_column(Text, nullable=True) is_builtin: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False) + grants: Mapped[list["RoleMenu"]] = relationship( + back_populates="role", cascade="all, delete-orphan", lazy="selectin" + ) + def menu_map(self) -> dict: - if not self.menus: - return {} - try: - data = json.loads(self.menus) - except ValueError: - return {} - return data if isinstance(data, dict) else {} + return {g.menu: g.level for g in self.grants if g.level} def to_dict(self): return { @@ -655,8 +665,27 @@ class Role(Base, TimestampMixin): } +class RoleMenu(Base): + """角色对某个菜单的授权级别。级别只有 rw / ro,表里没有这一行就是无权限。""" + + __tablename__ = "role_menus" + + role_id: Mapped[int] = mapped_column( + Integer, ForeignKey("roles.id", ondelete="CASCADE"), primary_key=True + ) + menu: Mapped[str] = mapped_column(String(32), primary_key=True) + level: Mapped[str] = mapped_column(String(8), nullable=False) + created_at: Mapped[datetime] = mapped_column(DateTime, default=now, nullable=False) + + role: Mapped["Role"] = relationship(back_populates="grants") + + class User(Base, TimestampMixin): - """登录用户。密码只存 pbkdf2 派生值 + 盐,不存明文。""" + """登录用户。密码只存 pbkdf2 派生值 + 盐,不存明文。 + + 角色是多对多:`user.roles`。`menus` 是所有角色授权的并集, + 同一个菜单被多个角色命中时取更高级别(rw > ro)。 + """ __tablename__ = "users" @@ -665,23 +694,28 @@ class User(Base, TimestampMixin): username: Mapped[str] = mapped_column(String(64), unique=True, nullable=False) password_hash: Mapped[str] = mapped_column(String(128), nullable=False) password_salt: Mapped[str] = mapped_column(String(64), nullable=False) - role_id: Mapped[int | None] = mapped_column(Integer, ForeignKey("roles.id", ondelete="SET NULL"), nullable=True) active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False) last_login_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True) - role: Mapped[Role | None] = relationship("Role", lazy="joined") + roles: Mapped[list["Role"]] = relationship( + "Role", secondary="user_roles", lazy="selectin", order_by="Role.id" + ) @property def menus(self) -> dict: - return self.role.menu_map() if self.role else {} + return merge_levels(*[r.menu_map() for r in self.roles]) + + @property + def role_names(self) -> list[str]: + return [r.name for r in self.roles] def to_dict(self): return { "id": self.id, "name": self.name, "username": self.username, - "role_id": self.role_id, - "role_name": self.role.name if self.role else None, + "role_ids": [r.id for r in self.roles], + "role_names": self.role_names, "menus": self.menus, "active": self.active, "last_login_at": self.last_login_at.isoformat(timespec="seconds") if self.last_login_at else None, @@ -689,8 +723,22 @@ class User(Base, TimestampMixin): } +class UserRole(Base): + """用户与角色的关联(多角色)。""" + + __tablename__ = "user_roles" + + user_id: Mapped[int] = mapped_column( + Integer, ForeignKey("users.id", ondelete="CASCADE"), primary_key=True + ) + role_id: Mapped[int] = mapped_column( + Integer, ForeignKey("roles.id", ondelete="CASCADE"), primary_key=True + ) + created_at: Mapped[datetime] = mapped_column(DateTime, default=now, nullable=False) + + class UserSession(Base): - """登录会话。退出登录 / 禁用用户时删掉对应 token 即可立即失效。""" + """登录会话。退出登录 / 禁用用户 / 改密时删掉对应 token 即可立即失效。""" __tablename__ = "user_sessions" @@ -698,3 +746,46 @@ class UserSession(Base): user_id: Mapped[int] = mapped_column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=now, nullable=False) expires_at: Mapped[datetime] = mapped_column(DateTime, nullable=False) + ip: Mapped[str | None] = mapped_column(String(64), nullable=True) + user_agent: Mapped[str | None] = mapped_column(String(128), nullable=True) + + def to_dict(self): + return { + "token_hint": self.token[:6] + "…", + "created_at": self.created_at.isoformat(timespec="seconds") if self.created_at else None, + "expires_at": self.expires_at.isoformat(timespec="seconds") if self.expires_at else None, + "ip": self.ip, + "user_agent": self.user_agent, + } + + +class AuditLog(Base): + """操作审计:所有写操作 + 登录/退出,成功失败都留痕。""" + + __tablename__ = "audit_logs" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + user_id: Mapped[int | None] = mapped_column(Integer, nullable=True, index=True) + username: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True) + action: Mapped[str] = mapped_column(String(16), nullable=False, index=True) # create/update/delete/login/logout/deny + menu: Mapped[str | None] = mapped_column(String(32), nullable=True, index=True) + method: Mapped[str] = mapped_column(String(8), nullable=False) + path: Mapped[str] = mapped_column(String(255), nullable=False) + status: Mapped[int] = mapped_column(Integer, nullable=False) + ip: Mapped[str | None] = mapped_column(String(64), nullable=True) + detail: Mapped[str | None] = mapped_column(String(255), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=now, nullable=False, index=True) + + def to_dict(self): + return { + "id": self.id, + "user_id": self.user_id, + "username": self.username, + "action": self.action, + "menu": self.menu, + "method": self.method, + "path": self.path, + "status": self.status, + "detail": self.detail, + "created_at": self.created_at.isoformat(timespec="seconds") if self.created_at else None, + } diff --git a/app/routers/__pycache__/__init__.cpython-313.pyc b/app/routers/__pycache__/__init__.cpython-313.pyc deleted file mode 100644 index 8561a91..0000000 Binary files a/app/routers/__pycache__/__init__.cpython-313.pyc and /dev/null differ diff --git a/app/routers/__pycache__/ai.cpython-313.pyc b/app/routers/__pycache__/ai.cpython-313.pyc deleted file mode 100644 index f0a31ae..0000000 Binary files a/app/routers/__pycache__/ai.cpython-313.pyc and /dev/null differ diff --git a/app/routers/__pycache__/auth.cpython-313.pyc b/app/routers/__pycache__/auth.cpython-313.pyc deleted file mode 100644 index 0e3f8da..0000000 Binary files a/app/routers/__pycache__/auth.cpython-313.pyc and /dev/null differ diff --git a/app/routers/__pycache__/board.cpython-313.pyc b/app/routers/__pycache__/board.cpython-313.pyc deleted file mode 100644 index 3e1626c..0000000 Binary files a/app/routers/__pycache__/board.cpython-313.pyc and /dev/null differ diff --git a/app/routers/__pycache__/custom.cpython-313.pyc b/app/routers/__pycache__/custom.cpython-313.pyc deleted file mode 100644 index b156750..0000000 Binary files a/app/routers/__pycache__/custom.cpython-313.pyc and /dev/null differ diff --git a/app/routers/__pycache__/export.cpython-313.pyc b/app/routers/__pycache__/export.cpython-313.pyc deleted file mode 100644 index 257e635..0000000 Binary files a/app/routers/__pycache__/export.cpython-313.pyc and /dev/null differ diff --git a/app/routers/__pycache__/focus.cpython-312.pyc b/app/routers/__pycache__/focus.cpython-312.pyc deleted file mode 100644 index 0e98439..0000000 Binary files a/app/routers/__pycache__/focus.cpython-312.pyc and /dev/null differ diff --git a/app/routers/__pycache__/focus.cpython-313.pyc b/app/routers/__pycache__/focus.cpython-313.pyc deleted file mode 100644 index a620997..0000000 Binary files a/app/routers/__pycache__/focus.cpython-313.pyc and /dev/null differ diff --git a/app/routers/__pycache__/projects.cpython-313.pyc b/app/routers/__pycache__/projects.cpython-313.pyc deleted file mode 100644 index ccb5928..0000000 Binary files a/app/routers/__pycache__/projects.cpython-313.pyc and /dev/null differ diff --git a/app/routers/__pycache__/rbac.cpython-313.pyc b/app/routers/__pycache__/rbac.cpython-313.pyc deleted file mode 100644 index 197afcb..0000000 Binary files a/app/routers/__pycache__/rbac.cpython-313.pyc and /dev/null differ diff --git a/app/routers/__pycache__/staff.cpython-313.pyc b/app/routers/__pycache__/staff.cpython-313.pyc deleted file mode 100644 index 0773610..0000000 Binary files a/app/routers/__pycache__/staff.cpython-313.pyc and /dev/null differ diff --git a/app/routers/__pycache__/weekly.cpython-313.pyc b/app/routers/__pycache__/weekly.cpython-313.pyc deleted file mode 100644 index 7eba175..0000000 Binary files a/app/routers/__pycache__/weekly.cpython-313.pyc and /dev/null differ diff --git a/app/routers/ai.py b/app/routers/ai.py index b555b8a..dde97f0 100644 --- a/app/routers/ai.py +++ b/app/routers/ai.py @@ -13,7 +13,9 @@ from ..schemas import AICommitIn, AIParseIn router = APIRouter() -def _resolve_project(db: Session, project_id: int | None, project_name: str | None) -> Project | None: +def _resolve_project(db: Session, project_id: int | None, project_name: str | None, + *, create: bool = False) -> Project | None: + """按 id 或名称取项目。只有确认写入时才允许按名称新建,预览整理不碰库。""" if project_id: p = db.get(Project, project_id) if not p: @@ -21,7 +23,7 @@ def _resolve_project(db: Session, project_id: int | None, project_name: str | No return p if project_name: p = db.query(Project).filter(Project.name == project_name).one_or_none() - if not p: + if not p and create: p = Project(name=project_name) db.add(p) db.flush() @@ -31,8 +33,11 @@ def _resolve_project(db: Session, project_id: int | None, project_name: str | No @router.post("/ai/parse") def ai_parse(payload: AIParseIn, db: Session = Depends(get_db)): + """整理预览:只读。写了新项目名也不会建项目,确认写入时才建。""" project = _resolve_project(db, payload.project_id, payload.project_name) period = db.get(Period, payload.period_id) if payload.period_id else None + if payload.period_id and not period: + raise HTTPException(404, "周期不存在") parsed, mode, error = ai_parser.parse( payload.raw_text, @@ -55,7 +60,7 @@ def ai_parse(payload: AIParseIn, db: Session = Depends(get_db)): @router.post("/ai/commit") def ai_commit(payload: AICommitIn, db: Session = Depends(get_db)): - project = _resolve_project(db, payload.project_id, payload.project_name) + project = _resolve_project(db, payload.project_id, payload.project_name, create=True) if not project: raise HTTPException(400, "缺少项目信息") period = db.get(Period, payload.period_id) @@ -136,9 +141,3 @@ def ai_commit(payload: AICommitIn, db: Session = Depends(get_db)): "project": project.to_dict(), "created": [u.to_dict() for u in created], } - - -@router.get("/ai/logs") -def ai_logs(limit: int = 20, db: Session = Depends(get_db)): - rows = db.query(ImportLog).order_by(ImportLog.id.desc()).limit(limit).all() - return [r.to_dict() for r in rows] diff --git a/app/routers/auth.py b/app/routers/auth.py index 4b6bae0..6242353 100644 --- a/app/routers/auth.py +++ b/app/routers/auth.py @@ -1,25 +1,68 @@ -"""登录 / 退出 / 当前用户 / 用户自己的设置(昵称、密码)。""" +"""登录 / 退出 / 当前用户 / 自己的设置(昵称、密码)。 + +登录失败按「账号 + IP」限流:连错 5 次锁 5 分钟,成功一次即清零。 +进程内计数,重启即复位——防的是脚本撞库,不追求分布式精确。 +""" from __future__ import annotations +import time +from collections import defaultdict, deque + from fastapi import APIRouter, Depends, HTTPException, Request, Response from sqlalchemy.orm import Session -from .. import config, security +from .. import audit, config, security from ..db import get_db from ..models import User from ..schemas import LoginIn, PasswordIn, ProfileIn router = APIRouter() +MAX_FAILS = 5 +LOCK_SECONDS = 300 +_failures: dict[str, deque] = defaultdict(deque) + + +def _throttle_key(request: Request, username: str) -> str: + return f"{audit.client_ip(request) or '?'}|{username}" + + +def _check_lock(key: str) -> None: + now = time.time() + hits = _failures[key] + while hits and now - hits[0] > LOCK_SECONDS: + hits.popleft() + if len(hits) >= MAX_FAILS: + wait = int(LOCK_SECONDS - (now - hits[0])) + 1 + raise HTTPException(status_code=429, detail=f"密码连续输错 {MAX_FAILS} 次,请 {wait} 秒后再试") + + +def _mark_fail(key: str) -> None: + _failures[key].append(time.time()) + + +def _clear_fail(key: str) -> None: + _failures.pop(key, None) + @router.post("/auth/login") -def login(body: LoginIn, response: Response, db: Session = Depends(get_db)): - user = db.query(User).filter(User.username == (body.username or "").strip()).one_or_none() +def login(body: LoginIn, request: Request, response: Response, db: Session = Depends(get_db)): + username = (body.username or "").strip() + key = _throttle_key(request, username) + _check_lock(key) + user = db.query(User).filter(User.username == username).one_or_none() if user is None or not security.verify_password(body.password or "", user.password_hash, user.password_salt): + _mark_fail(key) + audit.note(request, f"登录失败:{username}", username=username or None) raise HTTPException(status_code=401, detail="用户名或密码不正确") if not user.active: + audit.note(request, f"账号已停用:{username}", username=username or None) raise HTTPException(status_code=403, detail="该账号已被停用,请联系管理员") - token = security.start_session(db, user) + _clear_fail(key) + token = security.start_session( + db, user, ip=audit.client_ip(request), user_agent=request.headers.get("user-agent") + ) + request.state.user = user response.set_cookie( security.SESSION_COOKIE, token, max_age=config.SESSION_DAYS * 86400, @@ -32,6 +75,7 @@ def login(body: LoginIn, response: Response, db: Session = Depends(get_db)): def logout(request: Request, response: Response, db: Session = Depends(get_db)): token = request.cookies.get(security.SESSION_COOKIE) if token: + request.state.user = security.user_from_token(db, token) db.query(security.UserSession).filter(security.UserSession.token == token).delete() db.commit() response.delete_cookie(security.SESSION_COOKIE, path="/") @@ -61,12 +105,11 @@ def change_password(body: PasswordIn, request: Request, response: Response, new = (body.new_password or "").strip() if len(new) < 6: raise HTTPException(status_code=400, detail="新密码至少 6 位") + if new == (body.old_password or ""): + raise HTTPException(status_code=400, detail="新密码不能与原密码相同") user.password_hash, user.password_salt = security.hash_password(new) + audit.note(request, "修改自己的密码") # 改密后其余设备全部下线,只保留当前这次登录 keep = request.cookies.get(security.SESSION_COOKIE) - query = db.query(security.UserSession).filter(security.UserSession.user_id == user.id) - if keep: - query = query.filter(security.UserSession.token != keep) - query.delete(synchronize_session=False) - db.commit() + security.revoke_all(db, user.id, keep_token=keep) return {"ok": True} diff --git a/app/routers/board.py b/app/routers/board.py index 95ed04d..fdc984f 100644 --- a/app/routers/board.py +++ b/app/routers/board.py @@ -1,10 +1,9 @@ from __future__ import annotations -from collections import defaultdict from datetime import date from typing import Iterable -from fastapi import APIRouter, Depends, HTTPException, Query +from fastapi import APIRouter, Depends, HTTPException from pydantic import BaseModel from sqlalchemy import func from sqlalchemy.orm import Session @@ -12,7 +11,7 @@ from sqlalchemy.orm import Session from .. import constants from ..constants import parse_period_label from ..db import get_db -from ..models import Period, Project, Task, Update +from ..models import Period, Project, Update router = APIRouter() @@ -204,292 +203,3 @@ def meta(db: Session = Depends(get_db)): "has_key": bool((s.get("ai_api_key") or "").strip()), }, } - - -# ---------------------------------------------------------------- 看板 -@router.get("/board") -def board( - period_id: int | None = None, - year: int | None = None, - month: int | None = None, - category_id: int | None = None, - key_only: bool = False, - keyword: str | None = None, - idle: str = Query("key", pattern="^(none|key|all)$"), - db: Session = Depends(get_db), -): - period_ids = resolve_period_ids(db, period_id, year, month) - if not period_ids: - return {"period_ids": [], "periods": [], "rows": [], "stats": None} - - periods = ( - db.query(Period).filter(Period.id.in_(period_ids)).order_by(Period.sort_key).all() - ) - - q = db.query(Project).filter(Project.archived.is_(False)) - if category_id: - q = q.filter(Project.category_id == category_id) - if key_only: - q = q.filter(Project.is_key.is_(True)) - if keyword: - q = q.filter(Project.name.contains(keyword)) - projects = q.order_by(Project.is_key.desc(), Project.sort_order, Project.id).all() - - ups = ( - db.query(Update) - .filter(Update.period_id.in_(period_ids)) - .order_by(Update.id) - .all() - ) - by_project: dict[int, list[Update]] = defaultdict(list) - for u in ups: - by_project[u.project_id].append(u) - - tasks = ( - db.query(Task) - .filter(Task.project_id.in_([p.id for p in projects])) - .order_by(Task.sort_order, Task.id) - .all() - ) - tasks_by_project: dict[int, list[Task]] = defaultdict(list) - for t in tasks: - tasks_by_project[t.project_id].append(t) - - rows = [] - for p in projects: - items = by_project.get(p.id, []) - if not items: - if idle == "none" or (idle == "key" and not p.is_key): - continue - - task_cards = [] - used_task_ids = set() - for t in tasks_by_project.get(p.id, []): - t_ups = [u for u in items if u.task_id == t.id] - for u in t_ups: - used_task_ids.add(u.id) - task_cards.append( - { - "task": t.to_dict(), - "updates": [u.to_dict() for u in t_ups], - } - ) - other_ups = [u for u in items if u.id not in used_task_ids] - - progresses = [u.progress for u in items if u.progress is not None] - if progresses: - progress, progress_known = round(max(progresses), 1), True - else: - progress, progress_known = round(p.progress or 0, 1), bool(items) - status = worst_status([u.status for u in items]) if items else p.status - - rows.append( - { - "project": p.to_dict(), - "progress": progress, - "progress_known": progress_known, - "status": status, - "update_count": len(items), - "summary": next((u.summary for u in items if u.summary), None) - or (items[-1].content or "")[:80] - if items - else None, - "has_update": bool(items), - "risks": [u.risk for u in items if u.risk], - "task_cards": task_cards, - "other_updates": [u.to_dict() for u in other_ups], - "updates": [u.to_dict() for u in items], - } - ) - - rows.sort( - key=lambda r: ( - not r["project"]["is_key"], - r["status"] != "blocked", - r["status"] != "at_risk", - not r["has_update"], - -(r["progress"] or 0), - ) - ) - - return { - "period_ids": period_ids, - "periods": [p.to_dict() for p in periods], - "rows": rows, - "stats": _quick_stats(db, period_ids, rows), - } - - -def _quick_stats(db: Session, period_ids: list[int], rows: list[dict]) -> dict: - updates = db.query(Update).filter(Update.period_id.in_(period_ids)).all() - by_status: dict[str, int] = defaultdict(int) - for u in updates: - by_status[u.status] += 1 - active = [r for r in rows if r["has_update"]] - progresses = [r["progress"] for r in active if r["progress"]] - return { - "project_total": len(rows), - "project_active": len(active), - "project_idle": len(rows) - len(active), - "key_total": sum(1 for r in rows if r["project"]["is_key"]), - "key_updated": sum(1 for r in active if r["project"]["is_key"]), - "update_count": len(updates), - "avg_progress": round(sum(progresses) / len(progresses), 1) if progresses else 0, - "status_counts": {k: by_status.get(k, 0) for k, _, _ in constants.STATUSES}, - } - - -# ---------------------------------------------------------------- 统计面板 -@router.get("/stats") -def stats( - period_id: int | None = None, - year: int | None = None, - month: int | None = None, - db: Session = Depends(get_db), -): - period_ids = resolve_period_ids(db, period_id, year, month) - periods = ( - db.query(Period).filter(Period.id.in_(period_ids)).order_by(Period.sort_key).all() - if period_ids - else [] - ) - scope_label = ( - "、".join(p.label for p in periods[:3]) + ("…" if len(periods) > 3 else "") - if periods - else (f"{year}年{month}月" if year and month else "—") - ) - - updates = ( - db.query(Update).filter(Update.period_id.in_(period_ids)).all() if period_ids else [] - ) - projects = db.query(Project).filter(Project.archived.is_(False)).all() - - # 全量:每个周期的更新量 / 覆盖项目数 / 平均进度(趋势图) - trend_rows = ( - db.query( - Period.id, - Period.label, - Period.sort_key, - Period.year, - Period.month, - Period.week, - func.count(Update.id), - ) - .outerjoin(Update, Update.period_id == Period.id) - .group_by(Period.id) - .order_by(Period.sort_key) - .all() - ) - trend = [ - { - "period_id": r[0], - "label": r[1], - "sort_key": r[2], - "year": r[3], - "month": r[4], - "week": r[5], - "update_count": r[6], - } - for r in trend_rows - ] - - # 分类分布 - cat_counter: dict[int, int] = defaultdict(int) - for p in projects: - cat_counter[p.category_id or 0] += 1 - cat_names = {} - for p in projects: - if p.category_id: - cat_names[p.category_id] = (p.category.name, p.category.color) - category_dist = [] - for cid, cnt in sorted(cat_counter.items(), key=lambda x: -x[1]): - name, color = cat_names.get(cid, ("未分类", "#94a3b8")) - category_dist.append({"id": cid, "name": name, "color": color, "count": cnt}) - - # 状态分布(本周期) - status_dist = [] - for code, name, color in constants.STATUSES: - status_dist.append( - { - "code": code, - "name": name, - "color": color, - "count": sum(1 for u in updates if u.status == code), - } - ) - - # 风险清单 - risks = [ - u.to_dict(with_project=True) - for u in updates - if u.status in constants.NEGATIVE_STATUS or (u.risk or "").strip() - ] - - # 重点工作未更新 - updated_ids = {u.project_id for u in updates} - idle_key = [ - p.to_dict() for p in projects if p.is_key and p.id not in updated_ids - ] - - # 进度排行 - prog_rows = [] - for p in projects: - p_ups = [u for u in updates if u.project_id == p.id] - prs = [u.progress for u in p_ups if u.progress is not None] - prog = max(prs) if prs else p.progress - prog_rows.append( - { - "id": p.id, - "name": p.name, - "progress": round(prog or 0, 1), - "is_key": p.is_key, - "status": worst_status([u.status for u in p_ups]) if p_ups else p.status, - "color": (p.category.color if p.category else "#2563eb"), - "estimated": not prs, - } - ) - prog_rows.sort(key=lambda x: (-x["progress"], x["name"])) - top_progress = [r for r in prog_rows if r["id"] in updated_ids][:10] or prog_rows[:10] - low_progress = [ - r - for r in prog_rows - if r["progress"] < 30 and r["status"] not in ("done",) and r["id"] in updated_ids - ][:8] - - recent = ( - db.query(Update) - .filter(Update.period_id.in_(period_ids)) - .order_by(Update.id.desc()) - .limit(10) - .all() - if period_ids - else [] - ) - - covered_prog = [p["progress"] for p in prog_rows if p["id"] in updated_ids] - return { - "scope_label": scope_label, - "period_ids": period_ids, - "kpi": { - "project_total": len(projects), - "key_total": sum(1 for p in projects if p.is_key), - "update_count": len(updates), - "covered_projects": len(updated_ids), - "risk_count": len(risks), - # 风险 / 阻塞分开计数:at_risk=风险、blocked=阻塞 - "at_risk_count": sum(1 for u in updates if u.status == "at_risk"), - "blocked_count": sum(1 for u in updates if u.status == "blocked"), - # 平均进度只统计本周期有更新的项目,避免历史一次性事项拉低数值 - "avg_progress": round(sum(covered_prog) / len(covered_prog), 1) - if covered_prog - else 0, - }, - "trend": trend[-14:], - "category_dist": category_dist, - "status_dist": status_dist, - "risks": risks, - "idle_key": idle_key, - "top_progress": top_progress, - "low_progress": low_progress, - "recent_updates": [u.to_dict(with_project=True) for u in recent], - } diff --git a/app/routers/custom.py b/app/routers/custom.py index f0c39e4..c35f3e6 100644 --- a/app/routers/custom.py +++ b/app/routers/custom.py @@ -1,31 +1,38 @@ """定制项目 API(独立于通用项目体系)。 -关注:商务阶段流转 与 按进度确认收入。 +三条口径要记住: + · **项目状态**(待开发/进行中/交付完成/已验收/退单)是界面上唯一可编辑的状态, + 商务阶段 `stage`(含收入确认比例)由它推导,不再单独维护; + · 财务统计(下单 / 验收按年按季度)统一走 `app/finance.py`,本文件不自己算季度; + · 周期记录里的 `amount_delta`(本期新增下单)与 `revenue_delta`(本期新增计收) + 都是增量:写入时累加进项目台账,改了就按差额回补,删了就扣回。 """ from __future__ import annotations import json -from collections import defaultdict -from datetime import date, datetime, timedelta +from datetime import date, datetime from fastapi import APIRouter, Depends, HTTPException, Query from pydantic import BaseModel -from sqlalchemy import func from sqlalchemy.orm import Session -from .. import ai_parser +from .. import ai_parser, finance from ..constants import ( - CUSTOM_ANNUAL_TARGETS_DEFAULT, + CUSTOM_INDUSTRIES, + CUSTOM_ORIGINS, CUSTOM_PIPELINE, - CUSTOM_STAGES, - CUSTOM_STAGE_MAP, - CUSTOM_STAGE_ORDER, + CUSTOM_STAGE_STATUS, + CUSTOM_STATUSES, CUSTOM_STEP_AGING_DAYS, - custom_revenue_ratio, + CUSTOM_PLACED_ORIGINS, + CUSTOM_RISKS, + CUSTOM_STAGES, + derive_stage, normalize_region, + parse_quarter, ) from ..db import get_db -from ..models import CustomProject, CustomUpdate, ImportLog, Period, Setting, set_people +from ..models import CustomProject, CustomUpdate, ImportLog, Period, set_people from .board import resolve_period_ids router = APIRouter() @@ -61,7 +68,7 @@ class CustomProjectIn(BaseModel): project_status: str | None = None accept_plan: str | None = None risk_level: str | None = None - accept_date_real: str | None = None # 验收日期(真实日期,区别于 accept_date 季度文本) + accept_year: int | None = None # 验收年度(accept_date 只有季度,跨年靠它区分) class CustomParseIn(BaseModel): @@ -82,24 +89,37 @@ class CustomCommitIn(BaseModel): model: str | None = None -def _ratio(cp: CustomProject) -> float: - return custom_revenue_ratio(cp.stage, cp.progress, cp.manual_ratio) +def _sync_stage(cp: CustomProject, stage_hint: str | None = None) -> None: + """把项目状态翻译成商务阶段(唯一的写入口,别处不要再直接改 stage)。 + + 只给了阶段、没给状态的入口(AI 录入 / 老接口)先反推出状态,保证台账上只有一个状态字段。 + """ + status = (cp.project_status or "").strip() + if not status and stage_hint: + status = CUSTOM_STAGE_STATUS.get(stage_hint, "") + cp.project_status = status or None + if status and status not in CUSTOM_STATUSES: + raise HTTPException(400, f"项目状态「{status}」不在取值范围内") + cp.stage = derive_stage(status, cp.stage) -# 环节日期字段 → 该环节对应的阶段 -_STEP_DATE_STAGE = {field: stage for _k, _n, field, stage, _c in CUSTOM_PIPELINE} +def _sync_accept(cp: CustomProject, payload: dict) -> None: + """验收时间 = 年度 + 季度 一对,要填就两个都填,清空就一起清空。 - -def _advance_stage(cp: CustomProject, payload: dict): - """补录了某个环节的日期,就把商务阶段推进到那一环(只进不退,暂停/关闭不动)。""" - if cp.stage in ("paused", "closed"): + 只留季度没年度正是「跨季度统计串年」的根源,所以宁可报错也不猜年份。 + """ + if "accept_date" not in payload and "accept_year" not in payload: return - target = cp.stage - for field, stage in _STEP_DATE_STAGE.items(): - if field in payload and str(payload.get(field) or "").strip(): - if CUSTOM_STAGE_ORDER.get(stage, 0) > CUSTOM_STAGE_ORDER.get(target, 0): - target = stage - cp.stage = target + quarter = parse_quarter(cp.accept_date) + if not quarter: + if cp.accept_year: + raise HTTPException(400, "验收时间要填完整:选了年度就别留季度为空") + cp.accept_date = None + cp.accept_year = None + return + cp.accept_date = f"Q{quarter}" + if not cp.accept_year: + raise HTTPException(400, "验收时间要填完整:请先选验收年度") def _entry_key(cp: CustomProject) -> str: @@ -122,11 +142,16 @@ def _sort_by_update(projects): return sorted(projects, key=key, reverse=True) -def _week_range(today: date | None = None) -> tuple[date, date]: - """当前自然周(周一~周日)。""" - t = today or date.today() - start = t - timedelta(days=t.weekday()) - return start, start + timedelta(days=6) +def _add_delta(cp: CustomProject, field: str, delta) -> None: + """本期新增量累加进项目台账(下单金额 / 计收金额同一套口径)。""" + if delta: + setattr(cp, field, max(0.0, float(getattr(cp, field) or 0.0) + float(delta))) + + +def _rebase_delta(cp: CustomProject, field: str, prev, new) -> None: + """把「本期新增量」改成另一个值:主档按差额回补,保证台账始终等于各期之和。""" + if prev or new: + setattr(cp, field, max(0.0, float(getattr(cp, field) or 0.0) - float(prev or 0) + float(new or 0))) def _unique_name(db: Session, name: str, exclude_id: int | None = None): @@ -138,67 +163,28 @@ def _unique_name(db: Session, name: str, exclude_id: int | None = None): raise HTTPException(400, f"已存在同名定制项目「{name}」,请换个名称") -# ---------------------------------------------------------------- 元信息 # ---------------------------------------------------------------- 年度计收目标 -# 目标值按「年 + 季度」存在 settings 里(一页一套),没配过就用《年度任务.xlsx》的默认值。 -ANNUAL_TARGETS_PREFIX = "custom_annual_targets" - - -def _annual_targets_key(year: int) -> str: - return f"{ANNUAL_TARGETS_PREFIX}:{year}" - - -def read_annual_targets(db: Session, year: int) -> dict[str, float]: - row = db.get(Setting, _annual_targets_key(year)) - targets = dict(CUSTOM_ANNUAL_TARGETS_DEFAULT) - if row and row.value: - try: - saved = json.loads(row.value) - except (TypeError, ValueError): - saved = {} - for q in (1, 2, 3, 4): - v = saved.get(str(q)) - if v is not None and v != "": - try: - targets[q] = float(v) - except (TypeError, ValueError): - pass - return {str(q): targets[q] for q in (1, 2, 3, 4)} +# 目标值按「年」存在 settings 里(一年一套),读写口径都在 finance 里。 class AnnualTargetsIn(BaseModel): year: int - targets: dict[str, float | None] + targets: dict # 值交给 finance 校验:非数字要报「Q几 目标值不是数字」,不是 422 @router.get("/custom/annual-targets") def get_annual_targets(year: int | None = None, db: Session = Depends(get_db)): y = year or date.today().year - return {"year": y, "targets": read_annual_targets(db, y)} + return {"year": y, "targets": finance.read_annual_targets(db, y)} @router.put("/custom/annual-targets") def put_annual_targets(payload: AnnualTargetsIn, db: Session = Depends(get_db)): - y = payload.year - targets = dict(CUSTOM_ANNUAL_TARGETS_DEFAULT) - for q in (1, 2, 3, 4): - v = payload.targets.get(str(q)) - if v is None or v == "": - targets[q] = 0.0 - continue - try: - targets[q] = float(v) - except (TypeError, ValueError): - raise HTTPException(400, f"Q{q} 目标值不是数字") - value = json.dumps({str(q): targets[q] for q in (1, 2, 3, 4)}, ensure_ascii=False) - key = _annual_targets_key(y) - row = db.get(Setting, key) - if row: - row.value = value - else: - db.add(Setting(key=key, value=value)) - db.commit() - return {"year": y, "targets": {str(q): targets[q] for q in (1, 2, 3, 4)}} + try: + targets = finance.write_annual_targets(db, payload.year, payload.targets) + except ValueError as exc: + raise HTTPException(400, str(exc)) + return {"year": payload.year, "targets": targets} @router.get("/custom/meta") @@ -229,8 +215,13 @@ def custom_meta(db: Session = Depends(get_db)): for k, n, f, st, col in CUSTOM_PIPELINE ], "aging_days": CUSTOM_STEP_AGING_DAYS, - # 年度计收目标(万元):默认取《年度任务.xlsx》,页面改过则以库里的值为准 - "annual_targets": {"year": date.today().year, "targets": read_annual_targets(db, date.today().year)}, + # 下拉选项的唯一来源:前端不再各写一份,避免前后端取值不一致 + "statuses": CUSTOM_STATUSES, + "origins": CUSTOM_ORIGINS, + # 「已下单」的归属取值:财务口径与前端「已下单」筛选共用同一份 + "placed_origins": list(CUSTOM_PLACED_ORIGINS), + "industries": CUSTOM_INDUSTRIES, + "risks": CUSTOM_RISKS, } @@ -281,6 +272,8 @@ def create_custom_project(payload: CustomProjectIn, db: Session = Depends(get_db _unique_name(db, name) cp = CustomProject(**data, source="manual") set_people(cp, None, payload.members) + _sync_stage(cp, stage_hint=payload.stage) + _sync_accept(cp, {"accept_date": cp.accept_date, "accept_year": cp.accept_year}) db.add(cp) db.commit() db.refresh(cp) @@ -321,14 +314,15 @@ def patch_custom_project(cid: int, payload: dict, db: Session = Depends(get_db)) cp = db.get(CustomProject, cid) if not cp: raise HTTPException(404, "定制项目不存在") + # 商务阶段 stage 不在白名单里:它由 project_status 推导,接口层面改不了 allowed = ( - "name", "customer", "region", "amount", "stage", "progress", "manual_ratio", + "name", "customer", "region", "amount", "progress", "manual_ratio", "revenue_amount", "invoice_amount", "received_amount", "owner", - "entry_date", "sign_date", "deliver_date", "accept_date", "revenue_date", - "remark", "is_key", "archived", "period_id", + "entry_date", "sign_date", "deliver_date", "accept_date", "accept_year", + "revenue_date", "remark", "is_key", "archived", "period_id", # 市场/销售侧台账字段 "origin", "project_code", "office", "industry", "man_days", - "market_owner", "project_status", "accept_plan", "risk_level", "accept_date_real", + "market_owner", "project_status", "accept_plan", "risk_level", ) payload = payload or {} if "name" in payload: @@ -348,7 +342,8 @@ def patch_custom_project(cid: int, payload: dict, db: Session = Depends(get_db)) setattr(cp, k, v) # 团队成员:名单型字段,整体替换(不传即不改);负责人只有单人,走上面的 owner set_people(cp, None, payload.get("members")) - _advance_stage(cp, payload) + _sync_stage(cp) + _sync_accept(cp, payload) # 「更新时间」= 本次提交时间:台账字段有变化时刷新,便于按周查看最新改动 if changed: cp.update_date = datetime.now().strftime("%Y-%m-%d %H:%M") @@ -369,250 +364,43 @@ def delete_custom_project(cid: int, db: Session = Depends(get_db)): return {"ok": True, "name": name, "deleted_updates": n_upd} -# ---------------------------------------------------------------- 按周删除 -def _week_filtered(db: Session): - """本周(周一~周日)有「更新时间」的定制项目。""" - start, end = _week_range() - rows = ( - db.query(CustomProject) - .filter( - CustomProject.update_date.isnot(None), - CustomProject.update_date >= start.isoformat(), - CustomProject.update_date <= end.isoformat(), - ) - .all() - ) - return start, end, rows - - -@router.get("/custom/weekly-preview") -def weekly_preview(db: Session = Depends(get_db)): - """本周有更新的项目清单(供「删除本周更新」二次确认)。""" - start, end, rows = _week_filtered(db) - return { - "start": start.isoformat(), - "end": end.isoformat(), - "count": len(rows), - "amount": round(sum(r.amount or 0 for r in rows), 2), - "names": [r.name for r in rows[:60]], - } - - -@router.post("/custom/purge-week") -def purge_week(db: Session = Depends(get_db)): - """删除本周(周一~周日)更新的定制项目,连带其记录。破坏性操作,前端须二次确认。""" - start, end, rows = _week_filtered(db) - names = [r.name for r in rows] - for r in rows: - db.delete(r) # custom_updates 走 relationship cascade="all, delete-orphan" - db.commit() - return { - "deleted": len(names), - "start": start.isoformat(), - "end": end.isoformat(), - "names": names, - } - - -# ---------------------------------------------------------------- 阶段看板 -@router.get("/custom/board") -def custom_board( +# ---------------------------------------------------------------- 财务统计 +@router.get("/custom/finance") +def custom_finance( period_id: int | None = None, year: int | None = None, month: int | None = None, - region: str | None = None, - keyword: str | None = None, db: Session = Depends(get_db), ): - period_ids = resolve_period_ids(db, period_id, year, month) - periods = ( - db.query(Period).filter(Period.id.in_(period_ids)).order_by(Period.sort_key).all() - if period_ids - else [] - ) + """定开财务汇总:KPI + 年度任务表。 - q = db.query(CustomProject).filter(CustomProject.archived.is_(False)) - if region: - q = q.filter(CustomProject.region == region) - if keyword: - q = q.filter(CustomProject.name.contains(keyword)) - projects = _sort_by_entry(q.all()) - - # 本期有记录的项目 - ups = ( - db.query(CustomUpdate) - .filter(CustomUpdate.period_id.in_(period_ids)) - .all() - if period_ids - else [] - ) - by_project: dict[int, list[CustomUpdate]] = defaultdict(list) - for u in ups: - by_project[u.custom_project_id].append(u) - updated_ids = set(by_project.keys()) - - columns = [] - for code, name, color, _base in CUSTOM_STAGES: - bucket = _sort_by_entry([c for c in projects if c.stage == code]) - columns.append( - { - "code": code, - "name": name, - "color": color, - "count": len(bucket), - "amount": round(sum(c.amount or 0 for c in bucket), 2), - "projects": [c.to_dict() for c in bucket], - "updated_count": sum(1 for c in bucket if c.id in updated_ids), - } - ) - - return { - "period_ids": period_ids, - "periods": [p.to_dict() for p in periods], - "columns": columns, - "updated_ids": sorted(updated_ids), - } - - -# ---------------------------------------------------------------- 收入统计 -@router.get("/custom/stats") -def custom_stats( - period_id: int | None = None, - year: int | None = None, - month: int | None = None, - region: str | None = None, - keyword: str | None = None, - archived: str = Query("false", pattern="^(true|false|all)$"), - db: Session = Depends(get_db), -): - period_ids = resolve_period_ids(db, period_id, year, month) - periods = ( - db.query(Period).filter(Period.id.in_(period_ids)).order_by(Period.sort_key).all() - if period_ids - else [] - ) - scope_label = ( - "、".join(p.label for p in periods[:3]) + ("…" if len(periods) > 3 else "") - if periods - else (f"{year}年{month}月" if year and month else "—") - ) - - pq = db.query(CustomProject) - if archived == "false": - pq = pq.filter(CustomProject.archived.is_(False)) - elif archived == "true": - pq = pq.filter(CustomProject.archived.is_(True)) - if region: - pq = pq.filter(CustomProject.region == region) - if keyword: - pq = pq.filter(CustomProject.name.contains(keyword)) - projects = pq.all() - - amount_total = sum(c.amount or 0 for c in projects) - revenue_total = sum(c.revenue_amount or 0 for c in projects) - confirmed_total = sum((c.amount or 0) * _ratio(c) for c in projects) - invoice_total = sum(c.invoice_amount or 0 for c in projects) - received_total = sum(c.received_amount or 0 for c in projects) - - # 按阶段 - stage_agg: dict[str, dict] = { - c: {"code": c, "name": n, "color": col, "count": 0, "amount": 0.0, "confirmed": 0.0} - for c, n, col, _ in CUSTOM_STAGES - } - for c in projects: - agg = stage_agg.setdefault( - c.stage, - {"code": c.stage, "name": c.stage, "color": "#94a3b8", "count": 0, "amount": 0.0, "confirmed": 0.0}, - ) - agg["count"] += 1 - agg["amount"] += c.amount or 0 - agg["confirmed"] += (c.amount or 0) * _ratio(c) - - # 按区域 - region_agg: dict[str, dict] = defaultdict(lambda: {"count": 0, "amount": 0.0, "confirmed": 0.0, "revenue": 0.0}) - for c in projects: - r = region_agg[c.region or "未标注"] - r["count"] += 1 - r["amount"] += c.amount or 0 - r["confirmed"] += (c.amount or 0) * _ratio(c) - r["revenue"] += c.revenue_amount or 0 - - by_region = [ - {"name": k, **{kk: round(vv, 2) for kk, vv in v.items() if kk != "count"}, "count": v["count"]} - for k, v in sorted(region_agg.items(), key=lambda x: -x[1]["amount"]) - ] - - # 各周期:更新项目数 / 新增计收 - trend_rows = ( - db.query( - Period.id, Period.label, Period.sort_key, Period.year, Period.month, Period.week, - func.count(CustomUpdate.id), - ) - .outerjoin(CustomUpdate, CustomUpdate.period_id == Period.id) - .group_by(Period.id) - .order_by(Period.sort_key) - .all() - ) - trend = [ - { - "period_id": r[0], "label": r[1], "sort_key": r[2], "year": r[3], - "month": r[4], "week": r[5], "update_count": r[6], - } - for r in trend_rows - ] - - ups_in_scope = ( - db.query(CustomUpdate).filter(CustomUpdate.period_id.in_(period_ids)).all() if period_ids else [] - ) - period_revenue = sum(u.revenue_delta or 0 for u in ups_in_scope) - period_amount = sum(u.amount_delta or 0 for u in ups_in_scope) - - top = sorted(projects, key=lambda c: -(c.amount or 0))[:12] - recently_stage_changed = sorted( - [c for c in projects if c.period_id in period_ids], - key=lambda c: CUSTOM_STAGE_ORDER.get(c.stage, 99), - )[:10] - - return { - "scope_label": scope_label, - "period_ids": period_ids, - "kpi": { - "project_count": len(projects), - "key_count": sum(1 for c in projects if c.is_key), - "amount_total": round(amount_total, 2), - "revenue_total": round(revenue_total, 2), - "confirmed_total": round(confirmed_total, 2), - "pending_total": round(max(0.0, confirmed_total - revenue_total), 2), - "progress_rate": round(confirmed_total / amount_total * 100, 1) if amount_total else 0, - "revenue_rate": round(revenue_total / amount_total * 100, 1) if amount_total else 0, - "invoice_total": round(invoice_total, 2), - "received_total": round(received_total, 2), - "pending_invoice": round(max(0.0, amount_total - invoice_total), 2), - "pending_received": round(max(0.0, amount_total - received_total), 2), - "received_rate": round(received_total / amount_total * 100, 1) if amount_total else 0, - "period_revenue": round(period_revenue, 2), - "period_amount": round(period_amount, 2), - "period_updated": len({u.custom_project_id for u in ups_in_scope}), - }, - "by_stage": [stage_agg[c] for c, _, _, _ in CUSTOM_STAGES if stage_agg[c]["count"]], - "by_region": by_region, - "trend": trend[-14:], - "top_projects": [c.to_dict() for c in top], - "recent_changes": [c.to_dict() for c in recently_stage_changed], - "recent_updates": [u.to_dict() for u in sorted(ups_in_scope, key=lambda x: -x.id)[:10]], - } + 统计周期跟着顶栏走(period_id = 周,year+month = 月,都不传 = 今天), + 年份 / 季度由后端判定,前端只负责摆数字,切到历史周期也只看那一年。 + """ + ctx = finance.period_context(db, period_id=period_id, year=year, month=month) + return finance.summary(db, ctx) # ---------------------------------------------------------------- 执行记录 @router.post("/custom/updates") def create_custom_update(payload: dict, db: Session = Depends(get_db)): - cp = db.get(CustomProject, payload.get("custom_project_id")) + payload = payload or {} + cid, pid = payload.get("custom_project_id"), payload.get("period_id") + cp = db.get(CustomProject, cid) if cid else None if not cp: raise HTTPException(404, "定制项目不存在") + if not pid or not db.get(Period, pid): + raise HTTPException(400, "请选择记录所属周期") + # 先把项目状态 / 进度按本次记录更新,再取推导出的阶段存进记录,历史轨迹才对得上 + if payload.get("project_status") is not None: + cp.project_status = (payload["project_status"] or "").strip() or None + if payload.get("progress") is not None: + cp.progress = float(payload["progress"]) + _sync_stage(cp, stage_hint=payload.get("stage")) u = CustomUpdate( custom_project_id=payload["custom_project_id"], period_id=payload["period_id"], - stage=payload.get("stage") or cp.stage, + stage=cp.stage, content=payload.get("content"), summary=payload.get("summary"), progress=payload.get("progress"), @@ -626,12 +414,8 @@ def create_custom_update(payload: dict, db: Session = Depends(get_db)): model=payload.get("model"), ) db.add(u) - if payload.get("progress") is not None: - cp.progress = float(payload["progress"]) - if payload.get("stage"): - cp.stage = payload["stage"] - if payload.get("revenue_delta"): - cp.revenue_amount = (cp.revenue_amount or 0) + float(payload["revenue_delta"]) + _add_delta(cp, "amount", payload.get("amount_delta")) + _add_delta(cp, "revenue_amount", payload.get("revenue_delta")) cp.period_id = payload["period_id"] db.commit() db.refresh(u) @@ -642,14 +426,15 @@ def create_custom_update(payload: dict, db: Session = Depends(get_db)): def patch_custom_update(uid: int, payload: dict, db: Session = Depends(get_db)): """修改单条定制周期记录。 - 金额/计收是「本期新增量」,改了要按差额回补项目累计值;进度与阶段直接覆盖项目档案。 + 金额/计收是「本期新增量」,改了要按差额回补项目累计值;进度与项目状态覆盖项目档案 + (商务阶段跟着项目状态走,不单独改)。 """ u = db.get(CustomUpdate, uid) if not u: raise HTTPException(404, "记录不存在") cp = db.get(CustomProject, u.custom_project_id) - prev_revenue = u.revenue_delta or 0.0 - for k in ("content", "summary", "risk", "next_step", "owner", "stage"): + prev_revenue, prev_amount = u.revenue_delta or 0.0, u.amount_delta or 0.0 + for k in ("content", "summary", "risk", "next_step", "owner"): if k in payload: setattr(u, k, payload[k] or None) for k in ("progress", "amount_delta", "revenue_delta"): @@ -659,14 +444,21 @@ def patch_custom_update(uid: int, payload: dict, db: Session = Depends(get_db)): if "period_id" in payload: if not payload["period_id"]: raise HTTPException(400, "周期不能为空") + if not db.get(Period, int(payload["period_id"])): + raise HTTPException(404, "周期不存在,请重新选择周期") u.period_id = int(payload["period_id"]) if payload.get("progress") is not None and cp: cp.progress = float(payload["progress"]) - if payload.get("stage") and cp: - cp.stage = payload["stage"] - # 「本期新增计收」是增量:改了就按差额回补项目累计计收,保持台账对得上 + if cp and ("project_status" in payload or payload.get("stage")): + if "project_status" in payload: + cp.project_status = (payload["project_status"] or "").strip() or None + _sync_stage(cp, stage_hint=payload.get("stage")) + u.stage = cp.stage # 记录里的阶段与档案保持一致 + # 「本期新增」都是增量:改了就按差额回补主档,保持台账与各期记录对得上 if cp and "revenue_delta" in payload: - cp.revenue_amount = max(0.0, (cp.revenue_amount or 0.0) - prev_revenue + (u.revenue_delta or 0.0)) + _rebase_delta(cp, "revenue_amount", prev_revenue, u.revenue_delta) + if cp and "amount_delta" in payload: + _rebase_delta(cp, "amount", prev_amount, u.amount_delta) db.commit() db.refresh(u) return u.to_dict() @@ -677,10 +469,11 @@ def delete_custom_update(uid: int, db: Session = Depends(get_db)): u = db.get(CustomUpdate, uid) if not u: raise HTTPException(404, "记录不存在") - # 「本期新增计收」是加进项目累计值的增量,删记录要一并扣回,否则台账对不上 + # 「本期新增」是加进项目累计值的增量,删记录要一并扣回,否则台账对不上 cp = db.get(CustomProject, u.custom_project_id) - if cp and u.revenue_delta: - cp.revenue_amount = max(0.0, (cp.revenue_amount or 0.0) - float(u.revenue_delta)) + if cp: + _rebase_delta(cp, "revenue_amount", u.revenue_delta, 0) + _rebase_delta(cp, "amount", u.amount_delta, 0) db.delete(u) db.commit() return {"ok": True} @@ -764,17 +557,20 @@ def custom_ai_commit(payload: CustomCommitIn, db: Session = Depends(get_db)): db.add(u) created.append(u) - # 回写项目主档 - if p.get("stage"): - cp.stage = p["stage"] + # 回写项目主档:AI 识别出的是阶段,落到台账上写的是项目状态 + _sync_stage(cp, stage_hint=p.get("stage")) if p.get("progress") is not None: cp.progress = float(p["progress"]) + add_amount = sum(float(it.get("amount_delta") or 0) for it in items) + add_revenue = sum(float(it.get("revenue_delta") or 0) for it in items) if p.get("amount") is not None: cp.amount = float(p["amount"]) + elif add_amount: + cp.amount = max(0.0, float(cp.amount or 0.0) + add_amount) if p.get("revenue_amount") is not None: cp.revenue_amount = float(p["revenue_amount"]) - elif p.get("revenue_delta"): - cp.revenue_amount = (cp.revenue_amount or 0) + float(p["revenue_delta"]) + elif add_revenue: + cp.revenue_amount = max(0.0, float(cp.revenue_amount or 0.0) + add_revenue) if p.get("summary"): cp.remark = p["summary"] cp.period_id = period.id diff --git a/app/routers/export.py b/app/routers/export.py index 088a7f4..d111f3b 100644 --- a/app/routers/export.py +++ b/app/routers/export.py @@ -1,6 +1,6 @@ """数据导出(Excel / xlsx)。 -提供四类导出,均可带上页面当前的筛选条件: +提供六类导出,均可带上页面当前的筛选条件: - /export/custom 定制项目明细 - /export/custom-updates 定制项目周期记录 - /export/projects 常规项目管理 @@ -14,6 +14,7 @@ from fastapi import APIRouter, Depends, Query from fastapi.responses import Response from sqlalchemy.orm import Session +from .. import finance from ..constants import CUSTOM_STAGE_MAP, STATUS_MAP from ..db import get_db from ..export import build_xlsx, xlsx_response @@ -93,7 +94,7 @@ def export_custom( c.amount if c.amount is not None else "", c.market_owner or "", c.project_status or "", - c.accept_date or "", + finance.accept_label(c), c.accept_plan or "", c.risk_level or "", (c.remark or "").replace("\n", " "), diff --git a/app/routers/focus.py b/app/routers/focus.py index 4d78a12..a42be46 100644 --- a/app/routers/focus.py +++ b/app/routers/focus.py @@ -146,4 +146,4 @@ def delete_focus(fid: int, db: Session = Depends(get_db)): content = item.content db.delete(item) db.commit() - return {"id": fid, "content": content} + return {"ok": True, "id": fid, "content": content} # 与其它删除接口保持一致 diff --git a/app/routers/projects.py b/app/routers/projects.py index 5cebb72..1f78dd3 100644 --- a/app/routers/projects.py +++ b/app/routers/projects.py @@ -18,6 +18,7 @@ from ..models import ( people_like, set_people, ) +from .. import constants from ..schemas import ( CategoryIn, ProjectIn, @@ -317,14 +318,20 @@ def delete_tag(tid: int, db: Session = Depends(get_db)): def list_updates( project_id: int | None = None, period_id: int | None = None, + year: int | None = None, + month: int | None = None, limit: int = Query(50, le=500), db: Session = Depends(get_db), ): + """执行记录。周期口径与项目清单一致:period_id 或 year+month(月粒度含该月各周)。""" q = db.query(Update) if project_id: q = q.filter(Update.project_id == project_id) - if period_id: - q = q.filter(Update.period_id == period_id) + if period_id or (year and month): + ids = resolve_period_ids(db, period_id, year, month) + if not ids: # 该周期/该月还没有任何周 + return [] + q = q.filter(Update.period_id.in_(ids)) rows = q.order_by(Update.id.desc()).limit(limit).all() return [u.to_dict(with_project=True) for u in rows] @@ -344,9 +351,13 @@ def create_update(payload: UpdateIn, db: Session = Depends(get_db)): db.add(t) db.flush() data["task_id"] = t.id + p = _require_project(db, payload.project_id) + _require_period(db, payload.period_id) + _check_status(payload.status) + if not (payload.content or "").strip() and not (payload.summary or "").strip(): + raise HTTPException(400, "请填写执行情况内容") u = Update(**data) db.add(u) - p = db.get(Project, payload.project_id) if p and data.get("progress") is not None: p.progress = float(data["progress"]) db.commit() @@ -354,6 +365,25 @@ def create_update(payload: UpdateIn, db: Session = Depends(get_db)): return u.to_dict() +def _require_project(db: Session, pid: int) -> Project: + p = db.get(Project, pid) + if not p: + raise HTTPException(404, "项目不存在") + return p + + +def _require_period(db: Session, period_id: int) -> Period: + p = db.get(Period, period_id) + if not p: + raise HTTPException(404, "周期不存在,请重新选择周期") + return p + + +def _check_status(status: str | None): + if status and status not in constants.STATUS_CODES: + raise HTTPException(400, "状态不认识:" + status) + + @router.patch("/updates/{uid}") def patch_update(uid: int, payload: UpdatePatch, db: Session = Depends(get_db)): """修改单条执行记录;改了进度就同步项目档案,与新建时的口径一致。""" @@ -373,8 +403,11 @@ def patch_update(uid: int, payload: UpdatePatch, db: Session = Depends(get_db)): db.add(t) db.flush() data["task_id"] = t.id - if "period_id" in data and not data["period_id"]: - raise HTTPException(400, "周期不能为空") + if "period_id" in data: + if not data["period_id"]: + raise HTTPException(400, "周期不能为空") + _require_period(db, data["period_id"]) + _check_status(data.get("status")) for k, v in data.items(): setattr(u, k, v) if data.get("progress") is not None: @@ -398,7 +431,18 @@ def delete_update(uid: int, db: Session = Depends(get_db)): @router.post("/tasks") def create_task(payload: dict, db: Session = Depends(get_db)): - t = Task(project_id=payload["project_id"], name=payload["name"]) + """新增子任务。同名子任务直接复用,避免任务列表里出现重复条目。""" + pid = payload.get("project_id") + project = db.get(Project, pid) if pid else None + if project is None: + raise HTTPException(404, "项目不存在") + name = str(payload.get("name") or "").strip() + if not name: + raise HTTPException(400, "子任务名称不能为空") + existed = db.query(Task).filter(Task.project_id == project.id, Task.name == name).one_or_none() + if existed: + return existed.to_dict() + t = Task(project_id=project.id, name=name) db.add(t) db.commit() db.refresh(t) diff --git a/app/routers/rbac.py b/app/routers/rbac.py index eaba248..5ebdb44 100644 --- a/app/routers/rbac.py +++ b/app/routers/rbac.py @@ -1,57 +1,138 @@ -"""权限管理:角色(菜单权限矩阵)与用户(分配角色 / 启停 / 重置密码)。 +"""权限管理:角色(菜单授权矩阵)、用户(挂角色 / 启停 / 重置密码)、在线会话、操作日志。 -只有拿到「权限管理」菜单授权的用户能进(写操作还要 rw),由 security.guard 拦。 +进入这一页需要「权限管理」授权,写操作还要 rw,由 security.guard 拦。 +两条自我保护规则: + · 内置「管理员」角色永远保留权限管理授权,也删不掉; + · 不让最后一个可管理权限的账号被停用 / 删除 / 降权。 """ from __future__ import annotations -from fastapi import APIRouter, Depends, HTTPException +from fastapi import APIRouter, Depends, HTTPException, Query, Request from sqlalchemy.orm import Session -from .. import security +from .. import audit, security +from ..constants import LEVELS, LEVEL_RANK, MENU_KEYS, MENU_LABELS, LEVEL_LABELS, merge_levels from ..db import get_db -from ..models import Role, User +from ..models import AuditLog, Role, RoleMenu, User, UserRole, UserSession from ..schemas import RoleIn, RolePatch, UserIn, UserPatch router = APIRouter() +ADMIN_ROLE = "管理员" + +def _role_menus(db: Session, role_id: int) -> dict[str, str]: + return {g.menu: g.level for g in db.query(RoleMenu).filter(RoleMenu.role_id == role_id).all()} + + +def _set_role_menus(db: Session, role: Role, menus: dict) -> None: + """整体替换角色的菜单授权(矩阵里改一格也是整行覆盖)。""" + clean = security.normalize_menus(menus) + if role.is_builtin and role.name == ADMIN_ROLE: + clean["rbac"] = "rw" # 管理员不能被自己关在门外 + # 逐条 ORM 删除后再插:批量 delete() 会把旧对象留在 identity map 里, + # 主键相同时 SQLAlchemy 会告警,甚至让随后的读取拿到改之前的旧级别 + for row in db.query(RoleMenu).filter(RoleMenu.role_id == role.id).all(): + db.delete(row) + db.flush() + for menu, level in clean.items(): + db.add(RoleMenu(role_id=role.id, menu=menu, level=level)) + db.commit() + + +def _set_user_roles(db: Session, user: User, role_ids: list[int]) -> None: + ids = sorted({int(r) for r in role_ids if r}) + for rid in ids: + if db.get(Role, rid) is None: + raise HTTPException(status_code=400, detail="角色不存在") + # 同 _set_role_menus:先 ORM 删除再插入,避免主键冲突的旧对象残留在 identity map + for row in db.query(UserRole).filter(UserRole.user_id == user.id).all(): + db.delete(row) + db.flush() + for rid in ids: + db.add(UserRole(user_id=user.id, role_id=rid)) + db.commit() + + +def _menus_of_role_ids(db: Session, role_ids) -> dict[str, str]: + """预判:这几个角色挂上去之后用户会拿到什么权限(用于改角色前的自我保护判断)。""" + maps = [] + for rid in {int(r) for r in role_ids if r}: + role = db.get(Role, rid) + if role is not None: + maps.append(_role_menus(db, role.id)) + return merge_levels(*maps) + + +def _rbac_managers(db: Session, exclude_id: int | None = None) -> int: + """还有几个可用账号拥有「权限管理 · 可编辑」。""" + n = 0 + for u in db.query(User).filter(User.active.is_(True)).all(): + if exclude_id is not None and u.id == exclude_id: + continue + if u.menus.get("rbac") == "rw": + n += 1 + return n + + +def _effective_role_ids(user: User, role_ids) -> list[int]: + """没传角色 = 保持原样;传了 = 整体替换。""" + return [int(r) for r in role_ids] if role_ids is not None else [r.id for r in user.roles] + + +# ---------------------------------------------------------------------- 元信息 @router.get("/rbac/meta") def meta(): return { - "menus": [{"key": k, "label": v} for k, v in security.MENUS], - "levels": [{"value": "rw", "label": "可编辑"}, {"value": "ro", "label": "只读"}, - {"value": "", "label": "无权限"}], + "menus": [{"key": k, "label": v} for k, v in + [(k, MENU_LABELS[k]) for k in MENU_KEYS]], + "levels": [{"value": v, "label": LEVEL_LABELS[v]} for v in ("rw", "ro", "")], + "actions": [ + {"value": "create", "label": "新增"}, + {"value": "update", "label": "修改"}, + {"value": "delete", "label": "删除"}, + {"value": "login", "label": "登录"}, + {"value": "logout", "label": "退出"}, + {"value": "password", "label": "改密码"}, + {"value": "revoke", "label": "下线"}, + ], } # ---------------------------------------------------------------------- 角色 @router.get("/rbac/roles") def list_roles(db: Session = Depends(get_db)): - roles = db.query(Role).order_by(Role.id).all() + users = db.query(User).all() + counts: dict[int, int] = {} + for u in users: + for r in u.roles: + counts[r.id] = counts.get(r.id, 0) + 1 out = [] - for r in roles: + for r in db.query(Role).order_by(Role.id).all(): d = r.to_dict() - d["user_count"] = db.query(User).filter(User.role_id == r.id).count() + d["user_count"] = counts.get(r.id, 0) out.append(d) return out @router.post("/rbac/roles") -def create_role(body: RoleIn, db: Session = Depends(get_db)): +def create_role(body: RoleIn, request: Request, db: Session = Depends(get_db)): name = (body.name or "").strip() if not name: raise HTTPException(status_code=400, detail="角色名不能为空") if db.query(Role).filter(Role.name == name).count(): raise HTTPException(status_code=400, detail=f"角色「{name}」已存在") role = Role(name=name[:64], description=(body.description or "").strip() or None, - menus=security.menus_json(body.menus)) + is_builtin=False) db.add(role) db.commit() + _set_role_menus(db, role, body.menus) + audit.note(request, f"新建角色「{role.name}」") return role.to_dict() @router.patch("/rbac/roles/{rid}") -def update_role(rid: int, body: RolePatch, db: Session = Depends(get_db)): +def update_role(rid: int, body: RolePatch, request: Request, db: Session = Depends(get_db)): role = db.get(Role, rid) if role is None: raise HTTPException(status_code=404, detail="角色不存在") @@ -59,42 +140,68 @@ def update_role(rid: int, body: RolePatch, db: Session = Depends(get_db)): name = body.name.strip() if not name: raise HTTPException(status_code=400, detail="角色名不能为空") - dup = db.query(Role).filter(Role.name == name, Role.id != rid).count() - if dup: + if db.query(Role).filter(Role.name == name, Role.id != rid).count(): raise HTTPException(status_code=400, detail=f"角色「{name}」已存在") + if role.is_builtin and role.name == ADMIN_ROLE and name != ADMIN_ROLE: + raise HTTPException(status_code=400, detail="内置「管理员」角色不能改名") role.name = name[:64] if body.description is not None: role.description = body.description.strip() or None - if body.menus is not None: - role.menus = security.menus_json(body.menus) db.commit() + if body.menus is not None: + before = _role_menus(db, rid) + _set_role_menus(db, role, body.menus) + db.expire(role) + if before != _role_menus(db, rid): + _kick_role_users(db, rid) # 权限变了,让他们重新登录取新权限 + audit.note(request, f"调整角色「{role.name}」的菜单授权,已下线该角色下的用户") + else: + audit.note(request, f"修改角色「{role.name}」") + else: + audit.note(request, f"修改角色「{role.name}」") return role.to_dict() +def _kick_role_users(db: Session, rid: int) -> None: + for uid in [u.id for u in db.query(User).all() + if any(r.id == rid for r in u.roles)]: + security.revoke_all(db, uid) + + @router.delete("/rbac/roles/{rid}") -def delete_role(rid: int, me: User = Depends(security.current_user), db: Session = Depends(get_db)): +def delete_role(rid: int, request: Request, me: User = Depends(security.current_user), + db: Session = Depends(get_db)): role = db.get(Role, rid) if role is None: raise HTTPException(status_code=404, detail="角色不存在") if role.is_builtin: - raise HTTPException(status_code=400, detail="内置角色不能删除,可以改它的菜单权限") - if me.role_id == rid: + raise HTTPException(status_code=400, detail="内置角色不能删除,可以改它的菜单授权") + if any(r.id == rid for r in me.roles): raise HTTPException(status_code=400, detail="不能删除自己正在使用的角色") - if db.query(User).filter(User.role_id == rid).count(): + if db.query(UserRole).filter(UserRole.role_id == rid).count(): raise HTTPException(status_code=400, detail="该角色下还有用户,请先给他们换角色") - db.delete(role) + db.delete(role) # Role.grants 是 delete-orphan,菜单授权行跟着一起删 db.commit() + audit.note(request, f"删除角色「{role.name}」") return {"ok": True} # ---------------------------------------------------------------------- 用户 @router.get("/rbac/users") def list_users(db: Session = Depends(get_db)): - return [u.to_dict() for u in db.query(User).order_by(User.id).all()] + online = {} + for s in db.query(UserSession).all(): + online[s.user_id] = online.get(s.user_id, 0) + 1 + out = [] + for u in db.query(User).order_by(User.id).all(): + d = u.to_dict() + d["online"] = online.get(u.id, 0) + out.append(d) + return out @router.post("/rbac/users") -def create_user(body: UserIn, db: Session = Depends(get_db)): +def create_user(body: UserIn, request: Request, db: Session = Depends(get_db)): name = (body.name or "").strip() username = (body.username or "").strip() password = (body.password or "").strip() @@ -104,58 +211,183 @@ def create_user(body: UserIn, db: Session = Depends(get_db)): raise HTTPException(status_code=400, detail="初始密码至少 6 位") if db.query(User).filter(User.username == username).count(): raise HTTPException(status_code=400, detail=f"登录账号「{username}」已存在") + role_ids = body.role_ids or _default_role_ids(db) + if not role_ids: + raise HTTPException(status_code=400, detail="至少要给账号挂一个角色") pw_hash, salt = security.hash_password(password) - user = User(name=name[:64], username=username[:64], password_hash=pw_hash, password_salt=salt, - role_id=body.role_id, active=bool(body.active)) + user = User(name=name[:64], username=username[:64], password_hash=pw_hash, + password_salt=salt, active=bool(body.active)) db.add(user) db.commit() + _set_user_roles(db, user, role_ids) + audit.note(request, f"新建账号 {user.username}({user.name})") return user.to_dict() +def _default_role_ids(db: Session) -> list[int]: + role = db.query(Role).filter(Role.name == "部门成员").one_or_none() + return [role.id] if role else [] + + @router.patch("/rbac/users/{uid}") -def update_user(uid: int, body: UserPatch, me: User = Depends(security.current_user), - db: Session = Depends(get_db)): +def update_user(uid: int, body: UserPatch, request: Request, + me: User = Depends(security.current_user), db: Session = Depends(get_db)): user = db.get(User, uid) if user is None: raise HTTPException(status_code=404, detail="用户不存在") + + # 先把所有校验跑完再落库:否则角色/密码改了一半时后面报 400,库里已经是新值了 + name = None if body.name is not None: name = body.name.strip() if not name: raise HTTPException(status_code=400, detail="姓名不能为空") + new_ids: list[int] | None = None + if body.role_ids is not None: + ids = _effective_role_ids(user, body.role_ids) + if sorted(ids) != sorted(r.id for r in user.roles): + if user.id == me.id: + raise HTTPException(status_code=400, detail="不能修改自己的角色") + after = _menus_of_role_ids(db, ids) + if user.menus.get("rbac") == "rw" and after.get("rbac") != "rw" \ + and not _rbac_managers(db, exclude_id=user.id): + raise HTTPException(status_code=400, detail="系统里要保留一个可管理权限的账号") + new_ids = ids + password = (body.password or "").strip() + if password and len(password) < 6: + raise HTTPException(status_code=400, detail="新密码至少 6 位") + if body.active is not None and user.id == me.id and not body.active: + raise HTTPException(status_code=400, detail="不能停用自己的账号") + if body.active is False and user.menus.get("rbac") == "rw" \ + and not _rbac_managers(db, exclude_id=user.id): + raise HTTPException(status_code=400, detail="系统里要保留一个可管理权限的账号") + + changed_role = False + if name: user.name = name[:64] - if body.role_id is not None and body.role_id != user.role_id: - if db.get(Role, body.role_id) is None: - raise HTTPException(status_code=400, detail="角色不存在") - if user.id == me.id: - raise HTTPException(status_code=400, detail="不能修改自己的角色") - user.role_id = body.role_id - security.revoke_all(db, user.id) # 权限变了,强制重新登录 - if body.password is not None and body.password.strip(): - if len(body.password.strip()) < 6: - raise HTTPException(status_code=400, detail="新密码至少 6 位") - user.password_hash, user.password_salt = security.hash_password(body.password.strip()) - security.revoke_all(db, user.id) + if new_ids is not None: + _set_user_roles(db, user, new_ids) + changed_role = True + if password: + user.password_hash, user.password_salt = security.hash_password(password) + security.revoke_all(db, user.id) # 改密即下线,旧 token 立即失效 if body.active is not None: - if user.id == me.id and not body.active: - raise HTTPException(status_code=400, detail="不能停用自己的账号") user.active = bool(body.active) if not user.active: security.revoke_all(db, user.id) db.commit() + if changed_role: + security.revoke_all(db, user.id) # 权限变了,强制重新登录 + db.expire(user) + what = [] + if name: + what.append("改名") + if new_ids is not None: + what.append("改角色") + if password: + what.append("重置密码") + if body.active is not None: + what.append("启用" if body.active else "停用") + audit.note(request, f"修改账号 {user.username}" + (f":{'、'.join(what)}" if what else "")) return user.to_dict() @router.delete("/rbac/users/{uid}") -def delete_user(uid: int, me: User = Depends(security.current_user), db: Session = Depends(get_db)): +def delete_user(uid: int, request: Request, me: User = Depends(security.current_user), + db: Session = Depends(get_db)): user = db.get(User, uid) if user is None: raise HTTPException(status_code=404, detail="用户不存在") if user.id == me.id: raise HTTPException(status_code=400, detail="不能删除自己,可以换一个角色或让别人删") - remaining = db.query(User).filter(User.active.is_(True), User.id != uid).count() - if not remaining: + username = user.username + if not db.query(User).filter(User.active.is_(True), User.id != uid).count(): raise HTTPException(status_code=400, detail="至少要保留一个可用账号") + if user.active and user.menus.get("rbac") == "rw" and not _rbac_managers(db, exclude_id=user.id): + raise HTTPException(status_code=400, detail="系统里要保留一个可管理权限的账号") security.revoke_all(db, user.id) - db.delete(user) + db.delete(user) # user_roles 是 secondary 关联,删用户时 SQLAlchemy 自己会清 db.commit() + audit.note(request, f"删除账号 {username}") return {"ok": True} + + +@router.post("/rbac/users/{uid}/revoke") +def revoke_user_sessions(uid: int, request: Request, db: Session = Depends(get_db)): + user = db.get(User, uid) + if user is None: + raise HTTPException(status_code=404, detail="用户不存在") + security.revoke_all(db, uid) + audit.note(request, f"强制下线 {user.username}") + return {"ok": True, "revoked": True} + + +# ---------------------------------------------------------------------- 在线会话 +@router.get("/rbac/sessions") +def list_sessions(db: Session = Depends(get_db)): + users = {u.id: u for u in db.query(User).all()} + out = [] + for s in db.query(UserSession).order_by(UserSession.created_at.desc()).all(): + u = users.get(s.user_id) + if u is None: + continue + d = s.to_dict() + d["token"] = s.token # 下线要用真实 token,列表里只展示 token_hint + d.update({"user_id": u.id, "name": u.name, "username": u.username}) + out.append(d) + return out + + +@router.delete("/rbac/sessions/{token}") +def revoke_session(token: str, request: Request, db: Session = Depends(get_db)): + sess = db.get(UserSession, token) + if sess is None: + raise HTTPException(status_code=404, detail="会话不存在或已失效") + target = db.get(User, sess.user_id) + db.delete(sess) + db.commit() + audit.note(request, f"下线一个登录会话:{target.username if target else '已删除的账号'}") + return {"ok": True} + + +# ---------------------------------------------------------------------- 操作日志 +@router.get("/rbac/logs") +def list_logs( + username: str | None = None, + menu: str | None = None, + action: str | None = None, + days: int = Query(30, ge=1, le=365), + limit: int = Query(200, ge=1, le=1000), + offset: int = Query(0, ge=0), + db: Session = Depends(get_db), +): + from datetime import timedelta + + from ..models import now as _now + + q = db.query(AuditLog).filter(AuditLog.created_at >= _now() - timedelta(days=days)) + if username: + q = q.filter(AuditLog.username == username) + if menu: + q = q.filter(AuditLog.menu == menu) + if action: + q = q.filter(AuditLog.action == action) + total = q.count() + rows = q.order_by(AuditLog.id.desc()).offset(offset).limit(limit).all() + return {"total": total, "items": [r.to_dict() for r in rows]} + + +@router.delete("/rbac/logs") +def clear_logs(days: int = Query(0, ge=0), db: Session = Depends(get_db)): + """清空操作日志;days > 0 时只清 N 天以前的。""" + from datetime import timedelta + + from ..models import now as _now + + q = db.query(AuditLog) + if days > 0: + q = q.filter(AuditLog.created_at < _now() - timedelta(days=days)) + n = q.count() + q.delete(synchronize_session=False) + db.commit() + return {"ok": True, "deleted": n} diff --git a/app/routers/weekly.py b/app/routers/weekly.py index 78e1766..4f481cb 100644 --- a/app/routers/weekly.py +++ b/app/routers/weekly.py @@ -22,6 +22,16 @@ from .board import resolve_period_ids, worst_status router = APIRouter() +def empty_kpi() -> dict: + """空周期的 KPI 骨架:键与统计结果保持一致,前端不用防 undefined。""" + return { + "key_total": 0, "key_updated": 0, "key_idle": 0, "project_listed": 0, + "update_count": 0, "custom_total": 0, "custom_new": 0, "custom_updated": 0, + "custom_amount": 0.0, "amount_delta": 0.0, "revenue_delta": 0.0, + "risk_count": 0, "at_risk_count": 0, "blocked_count": 0, + } + + @router.get("/weekly") def weekly( period_id: int | None = None, @@ -33,7 +43,8 @@ def weekly( ): period_ids = resolve_period_ids(db, period_id, year, month) if not period_ids: - return {"periods": [], "projects": [], "custom": [], "kpi": {}} + # 选中的年月还没有任何一周:给同样的结构 + 全 0 指标,而不是空对象 + return {"periods": [], "projects": [], "custom": [], "kpi": empty_kpi()} periods = db.query(Period).filter(Period.id.in_(period_ids)).order_by(Period.sort_key).all() scope_sort = max(p.sort_key for p in periods) @@ -186,6 +197,7 @@ def weekly( at_risk = sum(1 for r in project_rows for u in r["updates"] if u["status"] == "at_risk") blocked = sum(1 for r in project_rows for u in r["updates"] if u["status"] == "blocked") kpi = { + **empty_kpi(), "key_total": key_all, "key_updated": sum(1 for r in project_rows if r["is_key"] and r["has_update"]), "key_idle": sum(1 for r in project_rows if r["is_key"] and not r["has_update"]), @@ -201,6 +213,7 @@ def weekly( "at_risk_count": at_risk, "blocked_count": blocked, } + assert set(kpi) == set(empty_kpi()) # 两种返回结构的键必须一致 return { "periods": [p.to_dict() for p in periods], "projects": project_rows, diff --git a/app/schemas.py b/app/schemas.py index 14487eb..a1d8a01 100644 --- a/app/schemas.py +++ b/app/schemas.py @@ -173,12 +173,12 @@ class UserIn(BaseModel): name: str username: str password: str - role_id: int | None = None + role_ids: list[int] = Field(default_factory=list) # 可挂多个角色,权限取并集 active: bool = True class UserPatch(BaseModel): name: str | None = None - role_id: int | None = None + role_ids: list[int] | None = None # 不传即不改;传空数组即清空(该用户将没有任何权限) active: bool | None = None password: str | None = None # 管理员重置密码,不需要旧密码 diff --git a/app/security.py b/app/security.py index 7327af6..715e91a 100644 --- a/app/security.py +++ b/app/security.py @@ -1,10 +1,14 @@ """登录与权限(RBAC)。 -角色 = 一组功能菜单权限(rw 可编辑 / ro 只读 / 没配就是看不到),用户挂一个角色。 -菜单权限同时管两端: - · 前端按 /auth/me 返回的 menus 过滤侧边栏菜单、隐藏写操作按钮; - · 后端用 guard 依赖按「请求路径 -> 菜单」做二次校验,直接调接口也绕不过去。 -会话是服务端 token(HttpOnly Cookie),退出登录 / 禁用用户时删 token 立即失效。 +三层模型:**用户 ←(多对多)→ 角色 ←(一对多)→ 菜单授权** + · `role_menus` 存授权矩阵:一行 = 一个菜单一个级别,`rw` 可编辑 / `ro` 只读, + 表里没有这一行就是看不到该菜单; + · 一个用户可以挂多个角色,最终权限取并集(同一菜单取更高级别); + · 菜单权限同时管两端:前端按 `/auth/me` 返回的 menus 过滤侧栏与写操作按钮, + 后端 `guard` 按「请求路径 → 菜单 → 级别」二次校验,直接调接口也绕不过去; + · 所有写操作与登录行为写进 `audit_logs`,在「权限管理 → 操作日志」里查。 + +会话是服务端 token(HttpOnly Cookie),退出登录 / 停用 / 改密 / 强制下线都是删 token,立即失效。 密码只存 pbkdf2 派生值,用标准库,不引额外依赖。 """ from __future__ import annotations @@ -16,36 +20,36 @@ import secrets from datetime import datetime, timedelta from fastapi import Depends, HTTPException, Request +from sqlalchemy import inspect, text from sqlalchemy.orm import Session from . import config +from .constants import ( + LEVEL_LABELS, + LEVEL_RANK, + LEVELS, + MENUS, + MENU_KEYS, + MENU_LABELS, + merge_levels, +) from .db import get_db -from .models import Role, User, UserSession, now +from .models import Role, RoleMenu, User, UserRole, UserSession, now SESSION_COOKIE = "unis_session" PBKDF2_ROUNDS = 120_000 -# 功能菜单:键是前后端共用的权限标识,顺序即权限管理页里的展示顺序 -MENUS = [ - ("board", "工作看板"), - ("projects", "自研产品"), - ("custom", "定制项目"), - ("focus", "每周工作"), - ("staff", "人力资源"), - ("intake", "更新录入"), - ("settings", "设置"), - ("rbac", "权限管理"), +__all__ = [ + "MENUS", "MENU_KEYS", "MENU_LABELS", "LEVELS", "LEVEL_LABELS", + "SESSION_COOKIE", "normalize_menus", "menus_json", "hash_password", "verify_password", + "start_session", "revoke_all", "user_from_token", "current_user", "guard", + "resolve_rule", "ensure_seed", "migrate_legacy_rbac", "level_of", ] -MENU_KEYS = [k for k, _ in MENUS] -MENU_LABELS = dict(MENUS) -LEVELS = ("ro", "rw") # 接口路径首段 -> 菜单。没列出来的(/meta 等)只要求登录,不看菜单。 SEGMENT_MENU = { "focus": "focus", "weekly": "board", - "board": "board", - "stats": "board", "projects": "projects", "categories": "projects", "tags": "projects", @@ -69,11 +73,12 @@ EXPORT_MENU = { } +# ------------------------------------------------------------------ 权限表 def normalize_menus(raw) -> dict: """清洗前端传来的权限表:只留已知菜单 + 合法级别。""" out: dict[str, str] = {} for key, value in (raw or {}).items(): - if key in MENU_KEYS and value in LEVELS: + if key in MENU_LABELS and value in LEVELS: out[key] = value return out @@ -82,36 +87,62 @@ def menus_json(menus: dict) -> str: return json.dumps(normalize_menus(menus), ensure_ascii=False, sort_keys=True) +def level_of(user: User | None, menu: str) -> str: + if user is None: + return "" + return user.menus.get(menu, "") + + # ------------------------------------------------------------------ 密码 def hash_password(password: str) -> tuple[str, str]: salt = secrets.token_hex(16) - digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), bytes.fromhex(salt), PBKDF2_ROUNDS) + digest = hashlib.pbkdf2_hmac("sha256", password.encode(), bytes.fromhex(salt), PBKDF2_ROUNDS) return digest.hex(), salt def verify_password(password: str, password_hash: str, salt: str) -> bool: try: - digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), bytes.fromhex(salt), PBKDF2_ROUNDS) + digest = hashlib.pbkdf2_hmac( + "sha256", (password or "").encode(), bytes.fromhex(salt), PBKDF2_ROUNDS + ) except ValueError: return False return hmac.compare_digest(digest.hex(), password_hash) # ------------------------------------------------------------------ 会话 -def start_session(db: Session, user: User) -> str: +def _clip(value: str | None, size: int) -> str | None: + return value[:size] if value else None + + +def start_session(db: Session, user: User, ip: str | None = None, + user_agent: str | None = None) -> str: token = secrets.token_urlsafe(32) db.add(UserSession(token=token, user_id=user.id, - expires_at=now() + timedelta(days=config.SESSION_DAYS))) + expires_at=now() + timedelta(days=config.SESSION_DAYS), + ip=_clip(ip, 64), user_agent=_clip(user_agent, 128))) user.last_login_at = now() db.commit() return token -def revoke_all(db: Session, user_id: int) -> None: - db.query(UserSession).filter(UserSession.user_id == user_id).delete(synchronize_session=False) +def revoke_all(db: Session, user_id: int, keep_token: str | None = None) -> None: + q = db.query(UserSession).filter(UserSession.user_id == user_id) + if keep_token: + q = q.filter(UserSession.token != keep_token) + q.delete(synchronize_session=False) db.commit() +def purge_expired_sessions(db: Session) -> int: + q = db.query(UserSession).filter(UserSession.expires_at < now()) + n = q.count() + if n: + q.delete(synchronize_session=False) + db.commit() + return n + + def user_from_token(db: Session, token: str | None) -> User | None: if not token: return None @@ -124,6 +155,100 @@ def user_from_token(db: Session, token: str | None) -> User | None: return user +# ------------------------------------------------------------------ 旧库升级 +def migrate_legacy_rbac(engine) -> list[str]: + """把旧版的 roles.menus(JSON) / users.role_id 迁到 role_menus / user_roles。 + + 幂等:目标表里已经有数据就跳过。老库升级后第一次启动自动完成。 + """ + notes: list[str] = [] + insp = inspect(engine) + tables = set(insp.get_table_names()) + if "roles" not in tables or "users" not in tables: + return notes + with engine.begin() as conn: + cols = {c["name"] for c in insp.get_columns("roles")} + if "menus" in cols and "role_menus" in tables: + filled = conn.execute(text("SELECT COUNT(*) FROM role_menus")).scalar() or 0 + if not filled: + rows = conn.execute(text("SELECT id, menus FROM roles")).all() + moved = 0 + for rid, raw in rows: + if not raw: + continue + try: + data = json.loads(raw) + except ValueError: + continue + for menu, level in normalize_menus(data).items(): + conn.execute( + text("INSERT INTO role_menus(role_id, menu, level, created_at) " + "VALUES(:r,:m,:l,:c)"), + {"r": rid, "m": menu, "l": level, "c": now()}, + ) + moved += 1 + if moved: + notes.append(f"角色菜单授权已迁到 role_menus({moved} 条)") + if "role_id" in {c["name"] for c in insp.get_columns("users")} and "user_roles" in tables: + filled = conn.execute(text("SELECT COUNT(*) FROM user_roles")).scalar() or 0 + if not filled: + rows = conn.execute( + text("SELECT id, role_id FROM users WHERE role_id IS NOT NULL") + ).all() + for uid, rid in rows: + conn.execute( + text("INSERT INTO user_roles(user_id, role_id, created_at) VALUES(:u,:r,:c)"), + {"u": uid, "r": rid, "c": now()}, + ) + if rows: + notes.append(f"用户角色已迁到 user_roles({len(rows)} 条)") + return notes + + +# ------------------------------------------------------------------ 内置数据 +BUILTIN_ROLES = [ + ("管理员", "全部菜单可编辑,含设置与权限管理", {k: "rw" for k in MENU_KEYS}, True), + ("部门成员", "业务菜单可编辑,不能改设置与权限", + {k: "rw" for k in MENU_KEYS if k not in ("settings", "rbac")}, True), + ("只读访客", "只能查看,不能修改任何数据", + {k: "ro" for k in MENU_KEYS if k != "rbac"}, True), +] + + +def ensure_seed(db: Session) -> list[str]: + """首次启动(或升级后)补内置角色与管理员账号,返回新建的提示项。""" + notes: list[str] = [] + for name, desc, menus, builtin in BUILTIN_ROLES: + role = db.query(Role).filter(Role.name == name).one_or_none() + if role is None: + role = Role(name=name, description=desc, is_builtin=builtin) + db.add(role) + db.flush() + notes.append(f"已创建内置角色「{name}」") + if not db.query(RoleMenu).filter(RoleMenu.role_id == role.id).count(): + for menu, level in normalize_menus(menus).items(): + db.add(RoleMenu(role_id=role.id, menu=menu, level=level)) + admin_role = db.query(Role).filter(Role.name == "管理员").one() + if not db.query(User).count(): + pw_hash, salt = hash_password(config.ADMIN_PASSWORD) + user = User(name=config.ADMIN_USERNAME, username=config.ADMIN_USERNAME, + password_hash=pw_hash, password_salt=salt, active=True) + db.add(user) + db.flush() + db.add(UserRole(user_id=user.id, role_id=admin_role.id)) + notes.append(f"已创建管理员账号 {config.ADMIN_USERNAME}(请尽快在用户设置里改密码)") + else: + # 保证系统里至少有一个能管权限的账号,不会出现把自己锁在门外的情况 + guarded = [u for u in db.query(User).filter(User.active.is_(True)).all() + if u.menus.get("rbac") == "rw"] + if not guarded: + first = db.query(User).order_by(User.id).first() + db.add(UserRole(user_id=first.id, role_id=admin_role.id)) + notes.append(f"已把「管理员」角色补给 {first.username},避免没人能管权限") + db.commit() + return notes + + # ------------------------------------------------------------------ 依赖 READ_METHODS = ("GET", "HEAD", "OPTIONS") @@ -145,51 +270,21 @@ def resolve_rule(path: str, method: str): return menu, method not in READ_METHODS -def ensure_seed(db: Session) -> list[str]: - """首次启动(或升级后)补内置角色与管理员账号,返回新建的提示项。""" - notes: list[str] = [] - presets = [ - ("管理员", "全部菜单可编辑,含设置与权限管理", - {k: "rw" for k in MENU_KEYS}, True), - ("部门成员", "业务菜单可编辑,不能改设置与权限", - {k: "rw" for k in MENU_KEYS if k not in ("settings", "rbac")}, True), - ("只读访客", "只能查看,不能修改任何数据", - {k: "ro" for k in MENU_KEYS if k != "rbac"}, True), - ] - role_map: dict[str, Role] = {r.name: r for r in db.query(Role).all()} - for name, desc, menus, builtin in presets: - role = role_map.get(name) - if role is None: - role = Role(name=name, description=desc, menus=menus_json(menus), is_builtin=builtin) - db.add(role) - db.flush() - role_map[name] = role - notes.append(f"已创建内置角色「{name}」") - if not db.query(User).count(): - pw_hash, salt = hash_password(config.ADMIN_PASSWORD) - db.add(User(name=config.ADMIN_USERNAME, username=config.ADMIN_USERNAME, - password_hash=pw_hash, password_salt=salt, - role_id=role_map["管理员"].id, active=True)) - db.commit() - notes.append(f"已创建管理员账号 {config.ADMIN_USERNAME}(请尽快在用户设置里改密码)") - db.commit() - return notes - - def guard(request: Request, db: Session = Depends(get_db)) -> User | None: """挂在 /api 子应用上的总闸:先验登录,再按菜单权限放行。""" path = request.url.path if path.rstrip("/") == "/api/auth/login": return None user = user_from_token(db, request.cookies.get(SESSION_COOKIE)) + request.state.user = user if user is None: raise HTTPException(status_code=401, detail="登录已失效,请重新登录") if path.startswith("/api/rbac/"): # 权限管理自身必须显式授权,普通用户即使能读别的菜单也不能碰 if "rbac" not in user.menus: - raise HTTPException(status_code=403, detail="没有「权限管理」的访问权限") + raise HTTPException(status_code=403, detail=f"没有「{MENU_LABELS['rbac']}」的访问权限") if request.method not in READ_METHODS and user.menus.get("rbac") != "rw": - raise HTTPException(status_code=403, detail="「权限管理」是只读权限,不能修改") + raise HTTPException(status_code=403, detail=f"「{MENU_LABELS['rbac']}」是只读权限,不能修改") return user rule = resolve_rule(path, request.method) if rule is None: @@ -207,4 +302,14 @@ def current_user(request: Request, db: Session = Depends(get_db)) -> User: user = user_from_token(db, request.cookies.get(SESSION_COOKIE)) if user is None: raise HTTPException(status_code=401, detail="请先登录") + request.state.user = user return user + + +def require_level(menu: str, level: str = "rw"): + """给个别高危接口用的显式授权依赖(除菜单写权限外还要求指定菜单可编辑)。""" + def dep(user: User = Depends(current_user)) -> User: + if LEVEL_RANK.get(user.menus.get(menu, ""), 0) < LEVEL_RANK.get(level, 0): + raise HTTPException(status_code=403, detail=f"需要「{MENU_LABELS.get(menu, menu)}」的可编辑权限") + return user + return dep diff --git a/data/.DS_Store b/data/.DS_Store deleted file mode 100644 index bfd61a5..0000000 Binary files a/data/.DS_Store and /dev/null differ diff --git a/data/board.db b/data/board.db index 7675868..80d27de 100644 Binary files a/data/board.db and b/data/board.db differ diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..eeb9d41 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +testpaths = tests +addopts = -q diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..b22aa0d --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,6 @@ +# 开发 / 测试依赖 +# ./.venv/bin/pip install -r requirements-dev.txt -i https://pypi.tuna.tsinghua.edu.cn/simple +# ./.venv/bin/python -m pytest -q +pytest>=8.0 +httpx>=0.27 +openpyxl>=3.1 diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..24a8dab --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,174 @@ +"""接口测试公共夹具。 + +两条硬规矩: + 1. **绝不碰 data/board.db**:在 import 业务模块之前把 DATABASE_URL 指到临时库里 + (`app.db` 在 import 时建 engine,`app.main` 在 import 时建表 + 补内置角色,晚一步就来不及了); + 2. **每个用例一个干净库**:清表重建 + 重新补种内置角色/管理员,用例之间不互相污染 + (权限类用例会故意停用账号、改角色,没有隔离就没法稳定断言)。 +""" +from __future__ import annotations + +import os +import sys +import tempfile +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient + +ROOT = Path(__file__).resolve().parent.parent +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +_TMP_DIR = tempfile.mkdtemp(prefix="unis-dms-test-") +os.environ["DATABASE_URL"] = f"sqlite:///{_TMP_DIR}/test.db" +os.environ["ADMIN_USERNAME"] = "admin" +os.environ["ADMIN_PASSWORD"] = "admin123" +os.environ["AI_API_KEY"] = "" # 不配 Key:/ai 走本地规则解析,测试不联网 + +from app import security # noqa: E402 +from app.db import Base, SessionLocal, engine # noqa: E402 +from app.main import app # noqa: E402 +from app.routers import auth as auth_router # noqa: E402 + +ADMIN_USER = "admin" +ADMIN_PASS = "admin123" +DEFAULT_PW = "pw123456" + + +@pytest.fixture(autouse=True) +def clean_db(): + """每个用例重建表结构 + 补种内置数据,并清掉登录失败计数(限流是进程内的)。""" + Base.metadata.drop_all(bind=engine) + Base.metadata.create_all(bind=engine) + engine.dispose() # 丢掉连接池里的旧连接,避免 SQLite 结构缓存 + with SessionLocal() as db: + security.ensure_seed(db) + auth_router._failures.clear() + yield + + +@pytest.fixture() +def client(clean_db): + """未登录的裸客户端。""" + with TestClient(app) as c: + yield c + + +@pytest.fixture() +def db(clean_db): + """直接操作数据库(造脏数据、绕开接口校验用)。""" + with SessionLocal() as s: + yield s + + +class Harness: + """一组顺手的小工具:建角色/建账号/登录/造业务数据,测试里只写断言。""" + + def __init__(self): + self.app = app + self.anon = TestClient(app) + self.admin = self.login(ADMIN_USER, ADMIN_PASS) + + # ------------------------------------------------------------- 账号 + def login(self, username: str, password: str | None = None) -> TestClient: + # 内置管理员用 seed 密码,其它测试账号统一用默认初始密码 + password = password or (ADMIN_PASS if username == ADMIN_USER else DEFAULT_PW) + c = TestClient(self.app) + r = c.post("/api/auth/login", json={"username": username, "password": password}) + assert r.status_code == 200, f"登录失败 {username}: {r.status_code} {r.text}" + return c + + def roles(self) -> dict[str, dict]: + return {x["name"]: x for x in self.admin.get("/api/rbac/roles").json()} + + def role(self, name: str, menus: dict | None = None, **kw) -> dict: + body = {"name": name, "menus": menus or {}} + body.update(kw) + r = self.admin.post("/api/rbac/roles", json=body) + assert r.status_code == 200, r.text + return r.json() + + def user(self, username: str, *, name: str | None = None, password: str = DEFAULT_PW, + menus: dict | None = None, role_ids: list[int] | None = None, + active: bool = True) -> dict: + """建账号。给了 menus 就先建一个同名角色挂上去;不给角色则走后端默认「部门成员」。""" + ids = role_ids + if menus is not None: + ids = [self.role(f"角色-{username}", menus)["id"]] + body = {"name": name or username, "username": username, "password": password, + "active": active} + if ids is not None: + body["role_ids"] = ids + r = self.admin.post("/api/rbac/users", json=body) + assert r.status_code == 200, r.text + return r.json() + + def user_client(self, username: str, **kw) -> TestClient: + """建账号并登录,直接返回带会话的客户端。""" + password = kw.get("password", DEFAULT_PW) + self.user(username, password=password, **{k: v for k, v in kw.items() if k != "password"}) + return self.login(username, password) + + # ------------------------------------------------------------- 周期 + def periods(self) -> dict: + r = self.admin.get("/api/periods") + assert r.status_code == 200, r.text + return r.json() + + def period(self, year: int, month: int, week: int = 1) -> dict: + r = self.admin.post("/api/periods", json={"year": year, "month": month, "week": week}) + assert r.status_code == 200, r.text + return r.json()["period"] + + @property + def today_period_id(self) -> int: + data = self.periods() + pid = data["today_id"] + assert pid, "今天所在的周应当自动建出来" + return pid + + # ------------------------------------------------------------- 业务数据 + def project(self, name: str, **kw) -> dict: + r = self.admin.post("/api/projects", json={"name": name, **kw}) + assert r.status_code == 200, r.text + return r.json() + + def category(self, name: str, **kw) -> dict: + r = self.admin.post("/api/categories", json={"name": name, **kw}) + assert r.status_code == 200, r.text + return r.json() + + def custom(self, name: str, **kw) -> dict: + r = self.admin.post("/api/custom/projects", json={"name": name, **kw}) + assert r.status_code == 200, r.text + return r.json() + + def custom_update(self, custom_project_id: int, period_id: int, **kw) -> dict: + r = self.admin.post("/api/custom/updates", + json={"custom_project_id": custom_project_id, + "period_id": period_id, **kw}) + assert r.status_code == 200, r.text + return r.json() + + def update(self, project_id: int, period_id: int, **kw) -> dict: + body = {"project_id": project_id, "period_id": period_id, + "content": kw.pop("content", "推进中"), **kw} + r = self.admin.post("/api/updates", json=body) + assert r.status_code == 200, r.text + return r.json() + + def staff(self, name: str, **kw) -> dict: + r = self.admin.post("/api/staff", json={"name": name, **kw}) + assert r.status_code == 200, r.text + return r.json() + + def focus(self, content: str, **kw) -> dict: + r = self.admin.post("/api/focus", json={"content": content, **kw}) + assert r.status_code == 200, r.text + return r.json() + + +@pytest.fixture() +def h(clean_db) -> Harness: + return Harness() diff --git a/tests/test_ai_export.py b/tests/test_ai_export.py new file mode 100644 index 0000000..f44bd9c --- /dev/null +++ b/tests/test_ai_export.py @@ -0,0 +1,364 @@ +"""AI 整理与 Excel 导出的接口测试。 + +AI 一律走本地规则解析(conftest 把 AI_API_KEY 置空),断言的都是确定性行为,不联网。 +导出只验三件事:能下载、文件确实是 xlsx、表头与筛选口径跟页面一致。 +""" +from __future__ import annotations + +import io + +from openpyxl import load_workbook + +from app.db import SessionLocal +from app.models import CustomProject, CustomUpdate, ImportLog, Task, Update + +RAW = """1、需求评审完成 +2、开发进度 60% +3、接口联调延期,等待对方提供文档 +下一步:完成联调 +""" + +CUSTOM_RAW = """1、合同金额 150,000 元,开发进度 60% +2、已计收 50,000 +""" + + +# ---------------------------------------------------------------- 小工具 +def _parse(h, **kw): + return h.admin.post("/api/ai/parse", json={"raw_text": RAW, "use_ai": False, **kw}) + + +def _commit(h, **kw): + body = {"raw_text": RAW, "mode": "rule", "parsed": {}} + body.update(kw) + return h.admin.post("/api/ai/commit", json=body) + + +def _sheet(resp): + """把响应当 xlsx 打开,返回 (工作表名, 全部行)。""" + assert resp.status_code == 200, resp.text + assert "spreadsheetml.sheet" in resp.headers["content-type"], resp.headers + assert resp.content[:4] == b"PK\x03\x04" # xlsx 就是 zip 包 + wb = load_workbook(io.BytesIO(resp.content)) + rows = [list(r) for r in wb.active.iter_rows(values_only=True)] + # build_xlsx 固定前两行是标题 + 导出时间,第 3 行才是表头 + assert rows[1][0] and str(rows[1][0]).startswith("导出时间"), rows[:2] + return wb.active.title, rows + + +# ================================================================== 常规项目:AI 整理 +def test_规则解析出摘要状态风险与子任务(h): + r = _parse(h) + assert r.status_code == 200, r.text + data = r.json() + assert data["mode"] == "rule" and data["error"] is None + assert "未配置大模型" in (data["warning"] or "") # 没配 Key 要说清楚现在用的是本地规则 + + p = data["parsed"] + assert set(p) == {"summary", "progress", "status", "risks", "next_steps", "tasks"} + assert p["summary"] == "需求评审完成" + assert p["progress"] == 60 # 取原文里出现的百分比 + assert p["status"] == "at_risk" # 子任务里有延期 → 整体按最差状态报 + assert p["risks"] and "延期" in p["risks"][0] + assert p["next_steps"] and "下一步" in p["next_steps"][0] + assert [t["status"] for t in p["tasks"]] == ["done", "in_progress", "at_risk"] + assert all(t["content"] and t["name"] for t in p["tasks"]) + + +def test_预览是只动的整理不会顺手建项目(h): + r = _parse(h, project_name="只想预览的项目") + assert r.status_code == 200, r.text + assert r.json()["project"] is None # 预览不认得这个名字 + names = [x["name"] for x in h.admin.get("/api/projects").json()] + assert "只想预览的项目" not in names # 也不许偷偷建出来 + + p = h.project("已有项目") + r = _parse(h, project_name=p["name"]) + assert r.json()["project"]["id"] == p["id"] # 同名能认出来 + assert r.json()["period"] is None + + +def test_预览校验项目与周期是否存在(h): + r = _parse(h, project_id=987654) + assert r.status_code == 404 and "项目" in r.json()["detail"] + r = _parse(h, period_id=987654) + assert r.status_code == 404 and "周期" in r.json()["detail"] + r = _parse(h, period_id=h.today_period_id) + assert r.status_code == 200 and r.json()["period"]["id"] == h.today_period_id + + +def test_确认写入按子任务落库并复用同名子任务(h): + p = h.project("AI落地项目") + period = h.today_period_id + parsed = { + "summary": "三条进展", "progress": 60, "status": "at_risk", + "risks": ["文档延期"], "next_steps": ["完成联调"], + "tasks": [ + {"name": "开发", "content": "开发完成 60%", "progress": 60, "status": "in_progress"}, + {"name": "联调", "content": "等对方文档", "progress": 0, "status": "at_risk", "risk": "文档未到"}, + ], + } + r = _commit(h, project_id=p["id"], period_id=period, parsed=parsed) + assert r.status_code == 200, r.text + out = r.json() + assert out["ok"] and len(out["created"]) == 2 + by_task = {u["task_name"]: u for u in out["created"]} + assert set(by_task) == {"开发", "联调"} + assert by_task["开发"]["risk"] == "文档延期" # 整体风险落在第一条上 + assert by_task["开发"]["next_step"] == "完成联调" + assert by_task["联调"]["risk"] == "文档未到" # 子任务自己的风险优先 + assert all(u["period_id"] == period for u in out["created"]) + + # 主档回写,时间线也按这一周聚合出来 + detail = h.admin.get(f"/api/projects/{p['id']}").json() + assert detail["project"]["progress"] == 60 and detail["project"]["status"] == "at_risk" + assert [t["status"] for t in detail["timeline"]] == ["at_risk"] + assert len(detail["timeline"][0]["updates"]) == 2 + + # 同名子任务复用,不重复建;新记录追加不覆盖旧的 + r2 = _commit(h, project_id=p["id"], period_id=period, + parsed={"tasks": [{"name": "开发", "content": "又推进了一点"}]}) + assert r2.status_code == 200 and len(r2.json()["created"]) == 1 + with SessionLocal() as s: + assert s.query(Task).filter(Task.project_id == p["id"]).count() == 2 + assert s.query(Update).filter(Update.project_id == p["id"]).count() == 3 + assert s.query(ImportLog).filter(ImportLog.project_id == p["id"]).count() == 2 + + +def test_确认写入没有子任务时只落一条(h): + p = h.project("单条AI项目") + r = _commit(h, project_name=p["name"], period_id=h.today_period_id, + mode="ai", model="deepseek-chat", + parsed={"summary": "整体推进", "progress": 40, "status": "in_progress", + "risks": ["人手不足", "接口不稳"], "next_steps": ["补齐测试"], "tasks": []}) + assert r.status_code == 200, r.text + created = r.json()["created"] + assert len(created) == 1 + u = created[0] + assert u["content"] == RAW # 原文整段留档 + assert u["risk"] == "人手不足;接口不稳" + assert u["next_step"] == "补齐测试" + assert u["source"] == "ai" and u["model"] == "deepseek-chat" + assert len(h.admin.get("/api/projects").json()) == 1 # 按同名找到已有项目,没有新建 + + with SessionLocal() as s: + log = s.query(ImportLog).one() + assert log.mode == "ai" and log.model == "deepseek-chat" + assert log.raw_input == RAW and "整体推进" in log.parsed_json + + +def test_确认写入缺少项目或周期会报错(h): + r = _commit(h, period_id=h.today_period_id, parsed={}) + assert r.status_code == 400 and "项目" in r.json()["detail"] + + p = h.project("要有周期") + r = _commit(h, project_id=p["id"], period_id=987654, parsed={}) + assert r.status_code == 404 and "周期" in r.json()["detail"] + + +# ================================================================== 定制项目:AI 整理 +def _custom_parse(h, **kw): + return h.admin.post("/api/custom/ai/parse", + json={"raw_text": CUSTOM_RAW, "use_ai": False, **kw}) + + +def test_定制规则解析出阶段金额与本期计收(h): + r = _custom_parse(h) + assert r.status_code == 200, r.text + data = r.json() + assert data["mode"] == "rule" and "未配置大模型" in (data["warning"] or "") + p = data["parsed"] + assert p["stage"] == "developing" # 有「开发进度 60%」→ 在制,不算验收 + assert p["progress"] == 60 + assert p["amount"] == 150000.0 # 「金额 150,000 元」 + assert p["revenue_amount"] is None # 没写累计计收就别编 + assert p["revenue_delta"] == 50000.0 # 「已计收 50,000」算本期新增 + assert len(p["updates"]) == 2 + assert p["updates"][1]["revenue_delta"] == 50000.0 + assert p["summary"].startswith("合同金额") + + +def test_定制预览校验项目是否存在(h): + r = _custom_parse(h, custom_project_id=987654) + assert r.status_code == 404 and "定制项目" in r.json()["detail"] + + c = h.custom("预览用的定制单", stage="developing") + r = _custom_parse(h, custom_project_id=c["id"], period_id=h.today_period_id) + assert r.status_code == 200 + assert r.json()["project"]["id"] == c["id"] + assert r.json()["period"]["id"] == h.today_period_id + + +def test_定制确认写入自动建档并按口径记账(h): + period = h.today_period_id + r = h.admin.post("/api/custom/ai/commit", json={ + "raw_text": CUSTOM_RAW, "project_name": "AI新建的定制单", "mode": "rule", "period_id": period, + "parsed": {"stage": "developing", "progress": 60, "amount": 150000, "summary": "开发中", + "updates": [{"content": "开发进度 60%", "progress": 60, + "stage": "developing", "revenue_delta": 50000}]}, + }) + assert r.status_code == 200, r.text + out = r.json() + cp = out["project"] + assert cp["name"] == "AI新建的定制单" and len(out["created"]) == 1 + assert cp["amount"] == 150000.0 # parsed.amount 是绝对值,直接落主档 + assert cp["revenue_amount"] == 50000.0 # 计收走增量累加 + assert cp["progress"] == 60 and cp["stage"] == "developing" + assert cp["remark"] == "开发中" and cp["period_id"] == period + assert out["created"][0]["amount_delta"] is None + + # 第二条记录只给增量:主档在现有金额上累加,不覆盖 + r2 = h.admin.post("/api/custom/ai/commit", json={ + "raw_text": "追加下单", "custom_project_id": cp["id"], "mode": "rule", "period_id": period, + "parsed": {"updates": [{"content": "追加下单", "amount_delta": 30000}]}, + }) + assert r2.status_code == 200, r2.text + cp2 = r2.json()["project"] + assert cp2["amount"] == 180000.0 and cp2["revenue_amount"] == 50000.0 + assert cp2["id"] == cp["id"] + + with SessionLocal() as s: + assert s.query(CustomUpdate).filter(CustomUpdate.custom_project_id == cp["id"]).count() == 2 + logs = s.query(ImportLog).all() + assert len(logs) == 2 and all(l.project_id is None for l in logs) + assert str(cp["id"]) in logs[0].parsed_json + + +def test_定制确认写入缺少项目或周期会报错(h): + r = h.admin.post("/api/custom/ai/commit", + json={"raw_text": "随便写点", "period_id": h.today_period_id, "parsed": {}}) + assert r.status_code == 400 and "项目" in r.json()["detail"] + + r = h.admin.post("/api/custom/ai/commit", + json={"raw_text": "随便写点", "project_name": "临时建的项目", + "period_id": 987654, "parsed": {}}) + assert r.status_code == 404 and "周期" in r.json()["detail"] + names = [x["name"] for x in h.admin.get("/api/custom/projects", + params={"archived": "all"}).json()] + assert "临时建的项目" not in names # 报错就什么都不留 + + +# ================================================================== 导出 +def _seed(h): + """每类数据各来一条,导出用例共用。""" + period = h.today_period_id + p = h.project("导出-常规项目", is_key=True, owners=["张三"]) + h.update(p["id"], period, content="推进中", status="at_risk", risk="等客户确认") + # 主档金额不预先填,全靠周期记录里的增量累加出来(这才是页面上的录入口径) + c = h.custom("导出-定制单", origin="华智下单", man_days=12, + sign_date="2026-01-05", accept_date="Q1", accept_year=2026, + project_status="进行中", region="华东", owner="张三") + h.custom_update(c["id"], period, content="开发中", progress=50, + amount_delta=120000, revenue_delta=20000) + h.staff("张三", group="AI产品组", affiliation="汇智") + h.focus("导出-重点事项", due_date="2026-10-09", delayed=True, status="in_progress") + return period + + +def test_六类导出都是可用的xlsx(h): + _seed(h) + checks = { + "/api/export/custom": (["项目归属", "订单金额(元)", "验收时间"], "定制项目明细"), + "/api/export/custom-updates": (["周期", "本期新增下单(元)", "本期新增计收(元)"], "定制项目记录"), + "/api/export/projects": (["项目名称", "执行记录数", "最近更新周期"], "项目管理"), + "/api/export/updates": (["周期", "执行情况", "状态"], "周期执行记录"), + "/api/export/staff": (["姓名", "定制合同额(元)", "定制待计收(元)"], "人力资源库"), + "/api/export/focus": (["工作内容", "录入周", "是否延期"], "每周重点工作"), + } + for url, (cols, sheet) in checks.items(): + name, rows = _sheet(h.admin.get(url)) + assert name == sheet, url + header = [c for c in rows[2] if c] + for col in cols: + assert col in header, f"{url} 表头缺 {col}:{header}" + assert len(rows) > 3, f"{url} 没有数据行:{rows}" + + # 内容抽查:验收时间、状态中文、负载金额都对得上 + _, rows = _sheet(h.admin.get("/api/export/custom")) + row = next(r for r in rows[3:] if r[1] == "导出-定制单") + assert row[0] == "华智下单" and row[7] == 120000 and row[10] == "2026Q1" + _, rows = _sheet(h.admin.get("/api/export/updates")) + row = next(r for r in rows[3:] if r[1] == "导出-常规项目") + assert row[5] == "风险" and row[8] == "手工" + _, rows = _sheet(h.admin.get("/api/export/staff")) + row = next(r for r in rows[3:] if r[1] == "张三") + assert row[4] == 1 and row[7] == 120000 and row[8] == 100000 + _, rows = _sheet(h.admin.get("/api/export/focus")) + row = next(r for r in rows[3:] if r[1] == "导出-重点事项") + assert row[5] == "进行中" and row[6] == "是" and row[3] == "2026-10-09" + + +def test_定制导出带合计行并跟随筛选(h): + _seed(h) + other = h.custom("导出-另一单", origin="汇智直签", amount=30000, sign_date="2026-02-02", + region="华南", project_status="已验收") + + _, rows = _sheet(h.admin.get("/api/export/custom")) + total = rows[-1] + assert total[0] == "合计" and total[1] == "2 个项目" + assert total[6] == 12 and total[7] == 150000 # 人天合计、金额合计 + assert len(rows) == 3 + 2 + 2 # 两行抬头 + 表头 + 两条数据 + 空行 + 合计 + + _, rows = _sheet(h.admin.get("/api/export/custom", params={"keyword": "另一单"})) + assert rows[-1][1] == "1 个项目" and rows[3][1] == "导出-另一单" + + _, rows = _sheet(h.admin.get("/api/export/custom", params={"origin": "华智下单"})) + assert rows[-1][1] == "1 个项目" + + h.admin.patch(f"/api/custom/projects/{other['id']}", json={"archived": True}) + _, rows = _sheet(h.admin.get("/api/export/custom")) + assert rows[-1][1] == "1 个项目" # 归档的默认不导 + _, rows = _sheet(h.admin.get("/api/export/custom", params={"archived": "all"})) + assert rows[-1][1] == "2 个项目" + _, rows = _sheet(h.admin.get("/api/export/custom", params={"archived": "true"})) + assert rows[-1][1] == "1 个项目" and rows[3][1] == "导出-另一单" + + +def test_执行记录导出按顶栏周期筛选(h): + p = h.project("周期导出") + w1, w2 = h.period(2026, 3, 1), h.period(2026, 3, 2) + w3 = h.period(2026, 4, 1) + h.update(p["id"], w1["id"], content="三月第一周") + h.update(p["id"], w2["id"], content="三月第二周") + h.update(p["id"], w3["id"], content="四月第一周") + + _, rows = _sheet(h.admin.get("/api/export/updates", params={"period_id": w1["id"]})) + assert [r[3] for r in rows[3:]] == ["三月第一周"] + + _, rows = _sheet(h.admin.get("/api/export/updates", params={"year": 2026, "month": 3})) + assert [r[3] for r in rows[3:]] == ["三月第一周", "三月第二周"] # 按月 = 当月所有周 + + _, rows = _sheet(h.admin.get("/api/export/updates")) + assert [r[3] for r in rows[3:]] == ["四月第一周"] # 不给条件 = 最新一周 + + # 认不出的周期不给空表,而是导出全量:导出是让人把数据带走的,不做隐式裁剪 + _, rows = _sheet(h.admin.get("/api/export/updates", params={"period_id": 987654})) + assert len(rows) == 3 + 3 + + # 定制周期记录同理 + c = h.custom("定制导出单") + h.custom_update(c["id"], w1["id"], content="定开三月", amount_delta=1000, revenue_delta=200) + h.custom_update(c["id"], w3["id"], content="定开四月") + _, rows = _sheet(h.admin.get("/api/export/custom-updates", params={"year": 2026, "month": 3})) + assert [r[4] for r in rows[3:]] == ["定开三月"] + _, rows = _sheet(h.admin.get("/api/export/custom-updates", params={"period_id": 987654})) + assert [r[4] for r in rows[3:]] == ["定开三月", "定开四月"] + assert rows[3][6] == 1000 and rows[3][7] == 200 + + +def test_项目导出含归档开关与统计列(h): + _seed(h) + archived = h.project("导出-已归档项目", archived=True) + + _, rows = _sheet(h.admin.get("/api/export/projects")) + names = [r[0] for r in rows[3:]] + assert "导出-常规项目" in names and "导出-已归档项目" in names # 默认 all:整库留档 + row = next(r for r in rows[3:] if r[0] == "导出-常规项目") + assert row[3] == "进行中" and row[5] == "是" and row[9] == 1 + assert row[10] and "第" in row[10] # 最近更新周期写了周次 + + _, rows = _sheet(h.admin.get("/api/export/projects", params={"archived": "false"})) + names = [r[0] for r in rows[3:]] + assert "导出-已归档项目" not in names + _, rows = _sheet(h.admin.get("/api/export/projects", params={"keyword": "归档"})) + assert [r[0] for r in rows[3:]] == ["导出-已归档项目"] diff --git a/tests/test_auth.py b/tests/test_auth.py new file mode 100644 index 0000000..fb5245c --- /dev/null +++ b/tests/test_auth.py @@ -0,0 +1,122 @@ +"""登录 / 会话 / 个人设置。""" +from __future__ import annotations + +from fastapi.testclient import TestClient + +from app.main import app + + +def test_未登录时业务接口一律401(client): + for path in ("/api/projects", "/api/custom/projects", "/api/staff", "/api/focus", + "/api/rbac/users", "/api/settings", "/api/export/custom"): + r = client.get(path) + assert r.status_code == 401, (path, r.status_code, r.text) + assert client.post("/api/projects", json={"name": "越权新建"}).status_code == 401 + + +def test_登录只认cookie不认body(client): + r = client.post("/api/auth/login", json={"username": "admin", "password": "admin123"}) + assert r.status_code == 200 + body = r.json() + assert body["username"] == "admin" and "password_hash" not in body + assert body["menus"]["rbac"] == "rw" # 内置管理员:全菜单可编辑 + assert body["role_names"] == ["管理员"] + assert body["last_login_at"] + assert "unis_session" in r.cookies # 会话是 HttpOnly Cookie + # 会话只在这台客户端上有效:另开一个不带 cookie 的客户端照样 401 + assert TestClient(app).get("/api/auth/me").status_code == 401 + + +def test_登录失败只给笼统提示(h): + r = h.anon.post("/api/auth/login", json={"username": "admin", "password": "错的"}) + assert r.status_code == 401 + assert r.json()["detail"] == "用户名或密码不正确" # 不暴露账号是否存在 + r2 = h.anon.post("/api/auth/login", json={"username": "查无此人", "password": "x123456"}) + assert r2.status_code == 401 and r2.json()["detail"] == "用户名或密码不正确" + + +def test_连续输错五次后锁定该账号(h): + for i in range(5): + r = h.anon.post("/api/auth/login", json={"username": "admin", "password": f"错{i}"}) + assert r.status_code == 401, i + r = h.anon.post("/api/auth/login", json={"username": "admin", "password": "admin123"}) + assert r.status_code == 429 # 锁定期内连正确密码也不给过 + assert "秒后再试" in r.json()["detail"] + # 限流按「IP + 账号」计,别人的账号不受影响 + h.user("other_ok", menus={"board": "ro"}) + assert h.login("other_ok").get("/api/auth/me").status_code == 200 + + +def test_成功登录会清零失败计数(h): + for _ in range(4): + assert h.anon.post("/api/auth/login", json={"username": "admin", "password": "错"}).status_code == 401 + assert h.anon.post("/api/auth/login", json={"username": "admin", "password": "admin123"}).status_code == 200 + for _ in range(4): + assert h.anon.post("/api/auth/login", json={"username": "admin", "password": "错"}).status_code == 401 + assert h.anon.post("/api/auth/login", json={"username": "admin", "password": "admin123"}).status_code == 200 + + +def test_停用账号既拦登录也断已有会话(h): + u = h.user("sleepy", menus={"board": "ro"}) + c = h.login("sleepy") + assert c.get("/api/auth/me").status_code == 200 + assert h.admin.patch(f"/api/rbac/users/{u['id']}", json={"active": False}).status_code == 200 + assert c.get("/api/auth/me").status_code == 401 # 现有 token 立刻失效 + r = h.anon.post("/api/auth/login", json={"username": "sleepy", "password": "pw123456"}) + assert r.status_code == 403 and "停用" in r.json()["detail"] + # 重新启用后能正常登录 + h.admin.patch(f"/api/rbac/users/{u['id']}", json={"active": True}) + assert h.login("sleepy").get("/api/auth/me").status_code == 200 + + +def test_改密后其他设备下线(h): + h.user("multi_dev", menus={"board": "ro"}) + c1 = h.login("multi_dev") + c2 = h.login("multi_dev") + assert c1.get("/api/auth/me").status_code == c2.get("/api/auth/me").status_code == 200 + r = c1.post("/api/auth/password", json={"old_password": "pw123456", "new_password": "newpass8"}) + assert r.status_code == 200, r.text + assert c1.get("/api/auth/me").status_code == 200 # 当前这次登录保留 + assert c2.get("/api/auth/me").status_code == 401 # 其余设备全部下线 + assert h.anon.post("/api/auth/login", json={"username": "multi_dev", + "password": "pw123456"}).status_code == 401 + assert h.login("multi_dev", "newpass8").get("/api/auth/me").status_code == 200 + + +def test_改密的三条前置校验(h): + h.user("pw_rule", menus={"board": "ro"}) + c = h.login("pw_rule") + cases = [ + ({"old_password": "不对的", "new_password": "whatever1"}, "原密码不正确"), + ({"old_password": "pw123456", "new_password": "123"}, "至少 6 位"), + ({"old_password": "pw123456", "new_password": "pw123456"}, "不能与原密码相同"), + ] + for body, expect in cases: + r = c.post("/api/auth/password", json=body) + assert r.status_code == 400, body + assert expect in r.json()["detail"], body + + +def test_退出登录后token失效(h): + h.user("bye", menus={"board": "ro"}) + c = h.login("bye") + assert c.post("/api/auth/logout").json() == {"ok": True} + assert c.get("/api/auth/me").status_code == 401 + + +def test_改昵称只能改自己(h): + h.user("nick", menus={"board": "ro"}) + c = h.login("nick") + assert c.put("/api/auth/me", json={"name": "新昵称"}).json()["name"] == "新昵称" + assert c.put("/api/auth/me", json={"name": " "}).status_code == 400 + # 昵称之外的字段改不动 + r = c.put("/api/auth/me", json={"name": "再改一次", "username": "hacked", "active": False}) + assert r.json()["username"] == "nick" and r.json()["active"] is True + + +def test_强制下线会踢掉全部会话(h): + u = h.user("kickme", menus={"board": "ro"}) + c = h.login("kickme") + assert c.get("/api/auth/me").status_code == 200 + assert h.admin.post(f"/api/rbac/users/{u['id']}/revoke").json()["revoked"] is True + assert c.get("/api/auth/me").status_code == 401 diff --git a/tests/test_custom_finance.py b/tests/test_custom_finance.py new file mode 100644 index 0000000..899781f --- /dev/null +++ b/tests/test_custom_finance.py @@ -0,0 +1,276 @@ +"""定开财务口径:跨季度 / 跨年度统计、年度计收目标、验收时间与增量金额的联动。 + +这一组用例是「跨季度统计有问题」的回归防线: +金额一律「元」,年度目标一律「万元」,验收归属只认 accept_year + accept_date。 +""" +from __future__ import annotations + +from datetime import date + +from app import constants, finance + + +def _ledger(h): + """一套故意跨年份、带脏数据的定开台账。""" + rows = {} + rows["甲"] = h.custom("甲-2025下单2026验收", origin="华智下单", amount=100000, + sign_date="2025-11-20", accept_date="Q1", accept_year=2026) + rows["乙"] = h.custom("乙-2026下单2026验收", origin="华智下单", amount=200000, + sign_date="2026-01-10", accept_date="Q3", accept_year=2026) + rows["丙"] = h.custom("丙-非下单归属", origin="提前交付", amount=50000, + sign_date="2026-02-01", accept_date="Q3", accept_year=2026) + rows["丁"] = h.custom("丁-脏下单时间", origin="华智下单", amount=80000, sign_date="2024年3月前") + rows["戊"] = h.custom("戊-无下单时间", origin="华智下单", amount=60000) + rows["己"] = h.custom("己-缺验收年度", amount=70000) + return rows + + +def _finance(h, **params): + r = h.admin.get("/api/custom/finance", params=params) + assert r.status_code == 200, r.text + return r.json() + + +# ------------------------------------------------------------------ 跨季度 / 跨年度 +def test_统计按选中年月的季度归集(h): + rows = _ledger(h) + # 只有季度没有年度的历史脏行:直接改库造出来,接口层是拦着的 + from app.models import CustomProject + from app.db import SessionLocal + with SessionLocal() as s: + s.get(CustomProject, rows["己"]["id"]).accept_date = "Q2" + s.commit() + + d = _finance(h, year=2026, month=1) + ctx = d["context"] + assert (ctx["year"], ctx["month"], ctx["quarter"]) == (2026, 1, 1) + assert ctx["quarter_label"] == "2026年Q1" + assert ctx["quarter_start"] == "2026-01-01" and ctx["quarter_end"] == "2026-03-31" + + k = d["kpi"] + # 已下单只看项目归属:提前交付不算,四单共 44 万 + assert k["placed"] == {"count": 4, "amount": 440000.0} + # 2026Q1 下单的只有乙;2026 年全年下单也只有乙 + assert k["sign_quarter"] == {"count": 1, "amount": 200000.0} + assert k["sign_year"] == {"count": 1, "amount": 200000.0} + # 验收:甲是 2026Q1,乙丙是 2026Q3;本季度只算甲,全年算三笔 + assert k["accept_quarter"] == {"count": 1, "amount": 100000.0} + assert k["accept_year"] == {"count": 3, "amount": 350000.0} + # 数据质量提示:认不出下单年份的 1 笔(戊),只有季度没有年度的 1 笔(己) + assert k["sign_unknown"] == 1 and k["accept_no_year"] == 1 + + +def test_切到历史周期只看那一年(h): + _ledger(h) + y2025 = _finance(h, year=2025, month=12) + assert (y2025["context"]["year"], y2025["context"]["quarter"]) == (2025, 4) + # 甲 2025-11 下单 → 落在 2025Q4;它的验收在 2026,不能串回 2025 + assert y2025["kpi"]["sign_quarter"] == {"count": 1, "amount": 100000.0} + assert y2025["kpi"]["sign_year"] == {"count": 1, "amount": 100000.0} + assert y2025["kpi"]["accept_quarter"] == {"count": 0, "amount": 0.0} + assert y2025["kpi"]["accept_year"] == {"count": 0, "amount": 0.0} + + # 脏文本「2024年3月前」按 2024Q1 统计,不因为脏就整笔丢掉 + y2024 = _finance(h, year=2024, month=2) + assert y2024["kpi"]["sign_quarter"] == {"count": 1, "amount": 80000.0} + assert y2024["kpi"]["sign_year"] == {"count": 1, "amount": 80000.0} + + # 顶栏选周:周期换算出来的年月季度与月视图一致 + week = h.period(2025, 12, 1) + byweek = _finance(h, period_id=week["id"]) + assert byweek["context"]["label"] == week["full_label"] + assert byweek["context"]["quarter_label"] == y2025["context"]["quarter_label"] + assert byweek["kpi"] == y2025["kpi"] + + +def test_认不出季度的项目计入年度并单列未分季(h): + """回归:有年份、认不出季度(「2024/」这种残缺值)的项目曾从季度表里静默消失, + 导致同一屏上「年度任务合计」比 KPI 年度少一笔。""" + from app.db import SessionLocal + from app.models import CustomProject + + h.custom("庚-下单只有年份", origin="华智下单", amount=320000, sign_date="2024/") + acc = h.custom("辛-验收只有年度", origin="华智下单", amount=150000, sign_date="2024-02-18") + with SessionLocal() as s: # 接口拦着「只填年度不填季度」,直接造脏行 + s.get(CustomProject, acc["id"]).accept_year = 2024 + s.commit() + + d = _finance(h, year=2024, month=5) + k, a = d["kpi"], d["annual"] + q1, q2, q3, q4 = a["quarters"] + uns = a["unscheduled"] + + # 都不在任何季度里,但都算进 2024 年度 + assert (q1["sign_count"], q2["sign_count"], q3["sign_count"], q4["sign_count"]) == (1, 0, 0, 0) + assert (q1["acc_count"], q2["acc_count"], q3["acc_count"], q4["acc_count"]) == (0, 0, 0, 0) + assert uns["sign_count"] == 1 and uns["sign_amount"] == 320000.0 + assert uns["acc_count"] == 1 and uns["acc_amount"] == 150000.0 + assert k["sign_no_quarter"] == 1 and k["accept_no_quarter"] == 1 + + # 核心不变式:四季度 + 未分季 = 合计 = KPI 年度 + t = a["total"] + assert t["sign_count"] == sum(x["sign_count"] for x in a["quarters"]) + uns["sign_count"] + assert t["sign_amount"] == k["sign_year"]["amount"] == 470000.0 + assert t["acc_count"] == sum(x["acc_count"] for x in a["quarters"]) + uns["acc_count"] == 1 + assert t["acc_amount"] == k["accept_year"]["amount"] == 150000.0 + # 目标只按四个季度累加,未分季不占目标、也不折算完成率 + assert t["target"] == sum(x["target"] for x in a["quarters"]) + + +def test_未分季为空时不影响原有合计(h): + """干净台账下未分季计数为 0,合计仍等于四个季度之和(不引入新的偏差)。""" + _ledger(h) + a = _finance(h, year=2026, month=8)["annual"] + uns, t = a["unscheduled"], a["total"] + assert uns == {"acc_count": 0, "acc_amount": 0.0, "sign_count": 0, "sign_amount": 0.0} + assert t["acc_count"] == sum(x["acc_count"] for x in a["quarters"]) + assert t["sign_amount"] == round(sum(x["sign_amount"] for x in a["quarters"]), 2) + + +def test_顶栏周期换算成季度(db): + from app.db import SessionLocal + + with SessionLocal() as s: + ctx = finance.period_context(s, year=2026, month=11) + assert (ctx["year"], ctx["quarter"]) == (2026, 4) + assert ctx["label"] == "2026年11月" + assert ctx["quarter_start"] == "2026-10-01" and ctx["quarter_end"] == "2026-12-31" + # 选中的周期不存在时按年月兜底,不会报错也不会算错年份 + assert finance.period_context(s, period_id=424242, year=2025, month=2)["quarter"] == 1 + assert finance.period_context(s)["year"] == date.today().year + assert constants.quarter_of_month(1) == 1 and constants.quarter_of_month(12) == 4 + assert constants.quarter_end(2026, 1) == "2026-03-31" + assert constants.quarter_end(2024, 1) == "2024-03-31" # 闰年也认得 + + +# ------------------------------------------------------------------ 年度计收目标 +def test_年度目标保存后读回来一模一样(h): + _ledger(h) + r = h.admin.put("/api/custom/annual-targets", + json={"year": 2026, "targets": {"1": 10, "2": 0, "3": 20, "4": None}}) + assert r.status_code == 200, r.text + saved = {"1": 10.0, "2": 0.0, "3": 20.0, "4": 0.0} + assert r.json()["targets"] == saved + assert h.admin.get("/api/custom/annual-targets", params={"year": 2026}).json()["targets"] == saved + + annual = _finance(h, year=2026, month=1)["annual"] + assert annual["year"] == 2026 and annual["targets"] == saved + q1, q2, q3, q4 = annual["quarters"] + assert q1 == {**q1, "acc_count": 1, "acc_amount": 100000.0, "rate": 1.0, "current": True} + assert q2["target"] == 0.0 and q2["rate"] is None # 没设目标就不折算完成率 + assert (q3["acc_count"], q3["acc_amount"], q3["rate"]) == (2, 250000.0, 1.25) + assert q4["current"] is False + assert annual["total"]["target"] == 30.0 + assert annual["total"]["acc_count"] == 3 and annual["total"]["acc_amount"] == 350000.0 + assert annual["total"]["sign_count"] == 1 and annual["total"]["sign_amount"] == 200000.0 + + +def test_没配过的年份用默认目标(h): + defaults = {str(q): v for q, v in constants.CUSTOM_ANNUAL_TARGETS_DEFAULT.items()} + assert h.admin.get("/api/custom/annual-targets", params={"year": 2030}).json()["targets"] == defaults + assert h.admin.get("/api/custom/annual-targets").json()["year"] == __import__("datetime").date.today().year + + +def test_目标值不是数字要报错(h): + r = h.admin.put("/api/custom/annual-targets", json={"year": 2026, "targets": {"2": "十万"}}) + assert r.status_code == 400 and "Q2" in r.json()["detail"] + + +# ------------------------------------------------------------------ 台账字段口径 +def test_验收时间必须年度季度一起填(h): + cp = h.custom("验收时间校验", amount=1000) + assert cp["accept_label"] == "" + cid = cp["id"] + patch = lambda body: h.admin.patch(f"/api/custom/projects/{cid}", json=body) + + assert "验收年度" in patch({"accept_date": "Q2"}).json()["detail"] + assert patch({"accept_date": "Q2"}).status_code == 400 + assert "别留季度为空" in patch({"accept_year": 2027, "accept_date": ""}).json()["detail"] + + ok = patch({"accept_date": "q2", "accept_year": 2027}).json() # 大小写不敏感,存成 Q2 + assert (ok["accept_date"], ok["accept_year"], ok["accept_label"]) == ("Q2", 2027, "2027Q2") + cleared = patch({"accept_date": None, "accept_year": None}).json() # 要清就一起清 + assert cleared["accept_date"] is None and cleared["accept_year"] is None + assert cleared["accept_label"] == "" + + +def test_项目状态是唯一状态字段(h): + cp = h.custom("阶段推导", project_status="退单", amount=100000) + assert cp["stage"] == "closed" + assert cp["confirmed_amount"] == 0.0 # 退单不确认收入 + accepted = h.admin.patch(f"/api/custom/projects/{cp['id']}", + json={"project_status": "已验收"}).json() + assert accepted["stage"] == "accepted" + # 商务阶段不再是可写字段:传了也不生效,避免出现两套状态 + ignored = h.admin.patch(f"/api/custom/projects/{cp['id']}", json={"stage": "lead"}).json() + assert ignored["stage"] == "accepted" + assert h.admin.patch(f"/api/custom/projects/{cp['id']}", + json={"project_status": "随便写"}).status_code == 400 + assert h.admin.post("/api/custom/projects", json={"name": "阶段推导"}).status_code == 400 + assert h.admin.post("/api/custom/projects", json={"name": " "}).status_code == 400 + assert h.admin.patch("/api/custom/projects/424242", json={"name": "x"}).status_code == 404 + + +def test_周期记录的新增量与台账同步(h): + pid = h.today_period_id + cp = h.custom("增量联动", amount=100000, revenue_amount=20000) + cur = lambda: h.admin.get(f"/api/custom/projects/{cp['id']}").json()["project"] + + u = h.custom_update(cp["id"], pid, content="本月新增下单与计收", + amount_delta=50000, revenue_delta=30000) + assert (u["amount_delta"], u["revenue_delta"]) == (50000.0, 30000.0) + assert (cur()["amount"], cur()["revenue_amount"]) == (150000.0, 50000.0) + + h.admin.patch(f"/api/custom/updates/{u['id']}", json={"revenue_delta": 10000}) + assert (cur()["amount"], cur()["revenue_amount"]) == (150000.0, 30000.0) # 按差额回补 + + assert h.admin.patch(f"/api/custom/updates/{u['id']}", json={"period_id": None}).status_code == 400 + assert h.admin.patch(f"/api/custom/updates/{u['id']}", json={"period_id": 424242}).status_code == 404 + h.admin.delete(f"/api/custom/updates/{u['id']}") + assert (cur()["amount"], cur()["revenue_amount"]) == (100000.0, 20000.0) # 删记录一并扣回 + + assert h.admin.patch("/api/custom/updates/424242", json={"content": "x"}).status_code == 404 + assert h.admin.delete("/api/custom/updates/424242").status_code == 404 + assert h.admin.post("/api/custom/updates", json={"content": "没有项目"}).status_code == 404 + assert h.admin.post("/api/custom/updates", + json={"custom_project_id": cp["id"], "content": "没有周期"}).status_code == 400 + + +# ------------------------------------------------------------------ 老库回填 +def test_回填补齐验收年份与商务阶段(h, db): + from app.models import CustomProject + + cp = h.custom("待回填", accept_date=None) + other = h.custom("待改阶段", project_status="待开发") + db.expire_all() + row = db.get(CustomProject, cp["id"]) + row.accept_date, row.accept_date_real, row.accept_year = "Q3", "2024-09-30", None + db.get(CustomProject, other["id"]).stage = "signed" # 状态与阶段对不上 + db.commit() + + notes = finance.backfill(db) + db.expire_all() + assert db.get(CustomProject, cp["id"]).accept_year == 2024 + assert db.get(CustomProject, other["id"]).stage == "signed" # 待开发本来就是 signed + assert any("验收年份" in n for n in notes) + + db.get(CustomProject, other["id"]).project_status = "已验收" + db.commit() + assert any("商务阶段" in n for n in finance.backfill(db)) + db.expire_all() + assert db.get(CustomProject, other["id"]).stage == "accepted" + assert finance.backfill(db) == [] # 再跑一次不再改任何东西 + + +def test_时间解析只认能进统计的写法(): + assert constants.parse_quarter("Q3") == 3 and constants.parse_quarter("q3") == 3 + assert constants.parse_quarter("三季度") is None and constants.parse_quarter("") is None + assert constants.parse_year_month("2026-03-31") == (2026, 3) + assert constants.parse_year_month("2026年3月") == (2026, 3) + assert constants.parse_year_month("2024年3月前") == (2024, 3) + assert constants.parse_year_month("2026") == (2026, 0) + assert constants.parse_year_month("待定") is None and constants.parse_year_month(None) is None + assert constants.derive_stage("已验收") == "accepted" + assert constants.derive_stage("", "developing") == "developing" + assert constants.merge_levels({"board": "ro"}, {"board": "rw", "rbac": "ro"}) == { + "board": "rw", "rbac": "ro"} diff --git a/tests/test_periods_projects.py b/tests/test_periods_projects.py new file mode 100644 index 0000000..ab4ff6e --- /dev/null +++ b/tests/test_periods_projects.py @@ -0,0 +1,194 @@ +"""周期、元信息、常规项目 / 分类 / 标签 / 执行记录 / 设置。""" +from __future__ import annotations + +from app import constants + + +# ------------------------------------------------------------------ 周期 +def test_周期列表会自动补出今天所在的周(h): + data = h.periods() + assert data["weeks"] and data["today_id"] + today = [w for w in data["weeks"] if w["id"] == data["today_id"]][0] + y, m, w = constants.week_of_date(__import__("datetime").date.today()) + assert (today["year"], today["month"], today["week"]) == (y, m, w) + sorts = [x["sort_key"] for x in data["weeks"]] + assert sorts == sorted(sorts) # 顶栏按时间正序 + assert all(x["first_day"] <= x["last_day"] for x in data["weeks"]) + month_keys = {(x["year"], x["month"]) for x in data["months"]} + assert (y, m) in month_keys + assert sum(x["week_count"] for x in data["months"]) == len(data["weeks"]) + + +def test_新建周期会按标签推年份并跨年(h): + base = h.periods()["today_id"] + latest = [w for w in h.periods()["weeks"] if w["id"] == base][0] + r = h.admin.post("/api/periods", json={"label": "12月第1周"}) + assert r.status_code == 200 + p = r.json()["period"] + # 12 月不早于当前月份 → 仍然是今年 + assert p["year"] == latest["year"] and (p["month"], p["week"]) == (12, 1) + assert p["sort_key"] == p["year"] * 10000 + 1201 + # 同一个周期不会重复建 + again = h.admin.post("/api/periods", json={"label": "12月第1周"}).json() + assert again["created"] is False and again["period"]["id"] == p["id"] + # 再补 1 月:月份比最新周期小,说明跨年,年份 +1 + p2 = h.admin.post("/api/periods", json={"label": "1月第1周"}).json()["period"] + assert p2["year"] == latest["year"] + 1 and p2["sort_key"] > p["sort_key"] + # 标签里写了年份就按写的算 + p3 = h.admin.post("/api/periods", json={"label": f"{latest['year'] - 1}年3月第2周"}).json()["period"] + assert p3["year"] == latest["year"] - 1 and p3["week"] == 2 + + +def test_新建周期的入参校验(h): + assert h.admin.post("/api/periods", json={}).status_code == 400 + assert h.admin.post("/api/periods", json={"label": "随便写点什么"}).status_code == 400 + p = h.period(2027, 5, 3) + assert (p["year"], p["month"], p["week"], p["sort_key"]) == (2027, 5, 3, 20270503) + + +def test_有记录的周期不能删(h): + pid = h.today_period_id + p = h.project("要被记录的周期项目") + h.update(p["id"], pid, content="本周推进") + r = h.admin.delete(f"/api/periods/{pid}") + assert r.status_code == 400 and "执行记录" in r.json()["detail"] + empty = h.period(2030, 1, 1) + assert h.admin.delete(f"/api/periods/{empty['id']}").json() == {"ok": True} + assert h.admin.delete("/api/periods/424242").status_code == 404 + + +def test_元信息给状态优先级和AI状态(h): + meta = h.admin.get("/api/meta").json() + assert [x["code"] for x in meta["statuses"]] == [c for c, _, _ in constants.STATUSES] + assert [x["code"] for x in meta["priorities"]] == [c for c, _, _ in constants.PRIORITIES] + assert meta["ai"]["enabled"] is False # 没配 Key:走本地规则 + assert meta["ai"]["has_key"] is False + + +# ------------------------------------------------------------------ 分类 / 标签 +def test_分类增删改(h): + c = h.category("研发平台", color="#123456") + assert c["color"] == "#123456" + assert h.admin.post("/api/categories", json={"name": "研发平台"}).status_code == 400 + up = h.admin.patch(f"/api/categories/{c['id']}", json={"name": "研发中台", "color": "#000"}) + assert up.json()["name"] == "研发中台" + assert h.admin.delete(f"/api/categories/{c['id']}").status_code == 200 + assert h.admin.patch(f"/api/categories/{c['id']}", json={"name": "x"}).status_code == 404 + assert h.admin.delete("/api/categories/424242").status_code == 404 + + +def test_标签重复提交返回同一个(h): + t = h.admin.post("/api/tags", json={"name": "重点"}).json() + again = h.admin.post("/api/tags", json={"name": "重点"}).json() + assert t["id"] == again["id"] + assert h.admin.delete(f"/api/tags/{t['id']}").json() == {"ok": True} + assert h.admin.delete("/api/tags/424242").status_code == 404 + + +# ------------------------------------------------------------------ 项目 +def test_项目字段与人员标签的写入(h): + cat = h.category("交付项目") + p = h.project("智慧园区", category_id=cat["id"], owners=["张三", "李四"], + members=["王五", "赵六"], tags=["新客户", "重点"], is_key=True, + progress=35, priority="p1", description="备注说明") + assert p["owner"] == "张三" and p["owners"] == ["张三", "李四"] # 第一位是主负责人 + assert p["members"] == ["王五", "赵六"] + assert {t["name"] for t in p["tags"]} == {"新客户", "重点"} + assert p["category"]["name"] == "交付项目" and p["is_key"] and p["progress"] == 35 + # 标签是自动创建的,不用先建 + assert {t["name"] for t in h.admin.get("/api/tags").json()} >= {"新客户", "重点"} + # 换负责人名单是整体替换 + up = h.admin.patch(f"/api/projects/{p['id']}", json={"owners": ["李四"], "tags": []}) + assert up.json()["owner"] == "李四" and up.json()["owners"] == ["李四"] and up.json()["tags"] == [] + + +def test_项目的重名与空名保护(h): + h.project("同名项目") + assert h.admin.post("/api/projects", json={"name": "同名项目"}).status_code == 400 + p = h.project("另一个项目") + assert h.admin.patch(f"/api/projects/{p['id']}", json={"name": "同名项目"}).status_code == 400 + assert h.admin.patch(f"/api/projects/{p['id']}", json={"name": " "}).status_code == 400 + assert h.admin.patch("/api/projects/424242", json={"name": "不存在"}).status_code == 404 + assert h.admin.get("/api/projects/424242").status_code == 404 + assert h.admin.delete("/api/projects/424242").status_code == 404 + + +def test_项目列表的筛选与本周期状态(h): + pid = h.today_period_id + cat = h.category("筛选专用") + a = h.project("甲项目", category_id=cat["id"], owners=["陈明"], is_key=True) + b = h.project("乙项目", owners=["刘芳"]) + h.update(b["id"], pid, content="乙本周有记录") + rows = {x["name"]: x for x in h.admin.get("/api/projects").json()} + assert rows["甲项目"]["updated_this_period"] is False and rows["甲项目"]["idle_weeks"] is None + assert rows["乙项目"]["updated_this_period"] is True and rows["乙项目"]["update_count"] == 1 + assert rows["甲项目"]["task_count"] == 0 + assert {x["id"] for x in h.admin.get("/api/projects", params={"is_key": True}).json()} == {a["id"]} + assert {x["id"] for x in h.admin.get("/api/projects", params={"keyword": "甲"}).json()} == {a["id"]} + assert {x["id"] for x in h.admin.get("/api/projects", params={"category_id": cat["id"]}).json()} == {a["id"]} + assert {x["id"] for x in h.admin.get("/api/projects", params={"owner": "陈明"}).json()} == {a["id"]} + # 归档后默认看不到,archived=true 才出现 + h.admin.patch(f"/api/projects/{a['id']}", json={"archived": True}) + assert a["id"] not in {x["id"] for x in h.admin.get("/api/projects").json()} + assert a["id"] in {x["id"] for x in h.admin.get("/api/projects", params={"archived": "true"}).json()} + assert a["id"] in {x["id"] for x in h.admin.get("/api/projects", params={"archived": "all"}).json()} + assert b["id"] in {x["id"] for x in h.admin.get("/api/projects", params={"owner": "刘芳"}).json()} + + +def test_按周与按月都能取到本周期数据(h): + week = h.period(2028, 3, 2) + p = h.project("跨月记录") + h.update(p["id"], week["id"], content="2028年3月第2周") + # 项目清单始终给全量,周期范围只决定「本周期是否更新 / 隔了几周没更新」 + rows = h.admin.get("/api/projects", params={"period_id": week["id"]}).json() + assert [x["name"] for x in rows] == ["跨月记录"] and rows[0]["updated_this_period"] is True + rows = h.admin.get("/api/projects", params={"year": 2028, "month": 3}).json() + assert rows and rows[0]["updated_this_period"] is True + assert rows[0]["idle_weeks"] == 0 + # 该年月还没有任何周期 → 清单照旧返回,只是都算「本周期没更新」 + rows = h.admin.get("/api/projects", params={"year": 2027, "month": 1}).json() + assert [x["name"] for x in rows] == ["跨月记录"] and rows[0]["updated_this_period"] is False + assert h.admin.get("/api/updates", params={"period_id": week["id"]}).json()[0]["content"] == "2028年3月第2周" + assert h.admin.get("/api/updates", params={"year": 2028, "month": 3}).json() != [] + assert h.admin.get("/api/updates", params={"year": 2026, "month": 1}).json() == [] + + +def test_执行记录的增改删(h): + pid = h.today_period_id + p = h.project("记录演练") + task = h.admin.post("/api/tasks", json={"project_id": p["id"], "name": "接口联调"}).json() + assert h.admin.post("/api/tasks", json={"project_id": p["id"], "name": "接口联调"}).json()["id"] == task["id"] + assert h.admin.post("/api/tasks", json={"name": "接口联调"}).status_code == 404 + assert h.admin.post("/api/tasks", json={"project_id": p["id"], "name": " "}).status_code == 400 + u = h.update(p["id"], pid, task_id=task["id"], content="联调过半", progress=60, + status="at_risk", risk="等待接口文档", next_step="约对方对齐", owner="张三") + assert u["content"] == "联调过半" and u["status"] == "at_risk" and u["task_id"] == task["id"] + assert u["period_label"] or u["period_id"] == pid + up = h.admin.patch(f"/api/updates/{u['id']}", json={"progress": 80, "status": "in_progress"}) + assert up.json()["progress"] == 80 and up.json()["status"] == "in_progress" + assert up.json()["content"] == "联调过半" # 没提交的字段保持原值 + assert h.admin.patch(f"/api/updates/{u['id']}", json={"period_id": None}).status_code == 400 + assert h.admin.patch("/api/updates/424242", json={"progress": 1}).status_code == 404 + detail = h.admin.get(f"/api/projects/{p['id']}").json() + assert detail["tasks"] and detail["updates"] + assert h.admin.delete(f"/api/updates/{u['id']}").status_code == 200 + assert h.admin.get("/api/updates", params={"project_id": p["id"]}).json() == [] + assert h.admin.delete(f"/api/updates/{u['id']}").status_code == 404 + + +def test_删除项目会带走它的记录(h): + pid = h.today_period_id + p = h.project("用完就删") + h.update(p["id"], pid, content="临时记录") + assert h.admin.delete(f"/api/projects/{p['id']}").status_code == 200 + assert h.admin.get("/api/updates", params={"project_id": p["id"]}).json() == [] + + +def test_设置只认AI相关的键(h): + r = h.admin.put("/api/settings", json={"values": {"ai_model": "glm-4", "ai_api_key": "sk-x", + "ai_temperature": "0.5", "偷改的键": "1"}}) + assert r.json() == {"ok": True} + s = h.admin.get("/api/settings").json() + assert s["ai_model"] == "glm-4" and s["ai_api_key"] == "sk-x" and s["ai_temperature"] == "0.5" + assert "偷改的键" not in s + assert h.admin.get("/api/meta").json()["ai"]["has_key"] is True # 配了 Key 就显示已配置 diff --git a/tests/test_rbac.py b/tests/test_rbac.py new file mode 100644 index 0000000..5e0b35f --- /dev/null +++ b/tests/test_rbac.py @@ -0,0 +1,340 @@ +"""RBAC:菜单授权矩阵、多角色并集、后端总闸、自我保护、会话与审计。""" +from __future__ import annotations + +from app import security +from app.db import SessionLocal +from app.models import Role, RoleMenu, User, UserRole + + +# ------------------------------------------------------------------ 元信息 +def test_权限元信息给全前端要的三样(h): + meta = h.admin.get("/api/rbac/meta").json() + assert [m["key"] for m in meta["menus"]] == [ + "board", "projects", "custom", "focus", "staff", "intake", "settings", "rbac"] + assert all(m["label"] for m in meta["menus"]) + assert [lv["value"] for lv in meta["levels"]] == ["rw", "ro", ""] + assert {a["value"] for a in meta["actions"]} == { + "create", "update", "delete", "login", "logout", "password", "revoke"} + + +def test_内置角色与管理员账号自动就位(h): + roles = h.roles() + assert set(roles) == {"管理员", "部门成员", "只读访客"} + assert all(r["is_builtin"] for r in roles.values()) + assert roles["管理员"]["menus"]["rbac"] == "rw" + # 部门成员:业务菜单可编辑,设置与权限管理一律没有 + assert roles["部门成员"]["menus"]["custom"] == "rw" + assert "settings" not in roles["部门成员"]["menus"] and "rbac" not in roles["部门成员"]["menus"] + assert all(v == "ro" for k, v in roles["只读访客"]["menus"].items() if k != "rbac") + assert "rbac" not in roles["只读访客"]["menus"] + assert h.admin.get("/api/auth/me").json()["username"] == "admin" + + +# ------------------------------------------------------------------ 后端总闸 +def test_没授权的菜单读不到也改不了(h): + c = h.user_client("only_board", menus={"board": "rw"}) + assert c.get("/api/weekly").status_code == 200 + for path in ("/api/projects", "/api/custom/finance", "/api/staff", "/api/focus", "/api/settings"): + assert c.get(path).status_code == 403, path + assert c.post("/api/projects", json={"name": "越权"}).status_code == 403 + assert c.get("/api/rbac/users").status_code == 403 # 权限管理必须显式授权 + + +def test_只读能看不能改(h): + c = h.user_client("readonly", menus={"custom": "ro", "projects": "ro"}) + assert c.get("/api/custom/projects").status_code == 200 + assert c.get("/api/projects").status_code == 200 + assert c.post("/api/custom/projects", json={"name": "只读新建"}).status_code == 403 + assert c.patch("/api/custom/projects/1", json={"amount": 1}).status_code == 403 + assert "只读" in c.post("/api/custom/projects", json={"name": "x"}).json()["detail"] + + +def test_导出接口跟着对应页面的权限(h): + viewer = h.user_client("viewer", menus={"custom": "ro", "focus": "ro"}) + assert viewer.get("/api/export/custom").status_code == 200 + assert viewer.get("/api/export/focus").status_code == 200 + assert viewer.get("/api/export/projects").status_code == 403 + writer = h.user_client("writer", menus={"projects": "rw"}) + assert writer.get("/api/export/projects").status_code == 200 + assert writer.get("/api/export/custom").status_code == 403 + + +def test_周期列表人人可读但只有设置页可改(h): + member = h.user_client("member_a") # 部门成员:没有 settings + assert member.get("/api/periods").status_code == 200 + assert member.post("/api/periods", json={"label": "1月第1周"}).status_code == 403 + assert member.get("/api/settings").status_code == 403 + assert h.admin.post("/api/periods", json={"label": "1月第1周"}).status_code == 200 + + +def test_录入页权限管住AI接口(h): + no_intake = h.user_client("no_intake", menus={"board": "rw"}) + assert no_intake.post("/api/ai/parse", json={"raw_text": "干了点活"}).status_code == 403 + assert no_intake.post("/api/custom/ai/parse", json={"raw_text": "干了点活"}).status_code == 403 + intake = h.user_client("intake_guy", menus={"intake": "rw"}) + assert intake.post("/api/ai/parse", json={"raw_text": "完成了接口"}).status_code == 200 + ro_intake = h.user_client("intake_ro", menus={"intake": "ro"}) + assert ro_intake.post("/api/ai/parse", json={"raw_text": "x"}).status_code == 403 + + +def test_一个角色被清空权限后该用户什么都干不了(h): + c = h.user_client("nobody", menus={"board": "rw"}) + assert c.get("/api/weekly").status_code == 200 + role = h.roles()["角色-nobody"] + h.admin.patch(f"/api/rbac/roles/{role['id']}", json={"menus": {}}) + assert c.get("/api/auth/me").status_code == 401 # 改授权后强制重新登录 + fresh = h.login("nobody") + # 登录本身还是通的(前端要靠 /auth/me 判断并给出「请联系管理员」的提示),但业务接口全关 + me = fresh.get("/api/auth/me") + assert me.status_code == 200 and me.json()["menus"] == {} + for path in ("/api/weekly", "/api/projects", "/api/custom/finance", "/api/rbac/users"): + assert fresh.get(path).status_code == 403, path + + +# ------------------------------------------------------------------ 多角色并集 +def test_多角色取并集同一菜单取更高级别(h): + r_board_ro = h.role("只看看", {"board": "ro", "projects": "ro"})["id"] + r_board_rw = h.role("能改看板", {"board": "rw"})["id"] + r_custom = h.role("只管定制", {"custom": "rw"})["id"] + u = h.user("multi_role", role_ids=[r_board_ro, r_board_rw, r_custom]) + assert sorted(u["role_ids"]) == sorted([r_board_ro, r_board_rw, r_custom]) + assert set(u["role_names"]) == {"只看看", "能改看板", "只管定制"} + menus = u["menus"] + assert menus["board"] == "rw" and menus["projects"] == "ro" and menus["custom"] == "rw" + assert "staff" not in menus + c = h.login("multi_role") + assert c.get("/api/weekly").status_code == 200 + assert c.post("/api/custom/projects", json={"name": "定制能写"}).status_code == 200 + assert c.post("/api/projects", json={"name": "项目不能写"}).status_code == 403 + assert c.get("/api/staff").status_code == 403 + + +# ------------------------------------------------------------------ 角色管理 +def test_角色增删改的基本规则(h): + r = h.role("报表岗", {"board": "ro", "custom": "ro"}, description="只看数") + assert r["menus"] == {"board": "ro", "custom": "ro"} and r["is_builtin"] is False + assert h.admin.post("/api/rbac/roles", json={"name": "报表岗"}).status_code == 400 + assert h.admin.post("/api/rbac/roles", json={"name": " "}).status_code == 400 + # 未知菜单 / 非法级别一律丢掉,前端传什么都不怕 + r2 = h.role("脏权限", {"board": "rw", "不存在的菜单": "rw", "custom": "读写", "staff": "admin"}) + assert r2["menus"] == {"board": "rw"} + up = h.admin.patch(f"/api/rbac/roles/{r['id']}", + json={"name": "报表查看", "description": "", "menus": {"board": "rw"}}) + assert up.status_code == 200 and up.json()["name"] == "报表查看" + assert up.json()["description"] is None and up.json()["menus"] == {"board": "rw"} + assert h.admin.patch(f"/api/rbac/roles/{r['id']}", json={"name": " "}).status_code == 400 + assert h.admin.patch("/api/rbac/roles/99999", json={"name": "x"}).status_code == 404 + assert h.admin.delete(f"/api/rbac/roles/{r['id']}").json() == {"ok": True} + assert h.admin.delete("/api/rbac/roles/99999").status_code == 404 + + +def test_角色改名不能撞已有的名字(h): + h.role("先建的", {"board": "ro"}) + r2 = h.role("后建的", {"board": "ro"}) + r = h.admin.patch(f"/api/rbac/roles/{r2['id']}", json={"name": "先建的"}) + assert r.status_code == 400 and "已存在" in r.json()["detail"] + + +def test_内置角色的三道锁(h): + builtin = h.roles()["管理员"] + assert h.admin.delete(f"/api/rbac/roles/{builtin['id']}").status_code == 400 + assert h.admin.patch(f"/api/rbac/roles/{builtin['id']}", json={"name": "超级管理员"}).status_code == 400 + # 想把管理员的「权限管理」授权去掉?会被强行留一份,杜绝把自己锁在门外 + r = h.admin.patch(f"/api/rbac/roles/{builtin['id']}", json={"menus": {"board": "rw"}}) + assert r.status_code == 200 + assert r.json()["menus"] == {"board": "rw", "rbac": "rw"} + # 改授权会把这个角色下的用户一并踢下线——管理员改自己的角色也不例外,得重新登录 + assert h.admin.get("/api/auth/me").status_code == 401 + h.admin = h.login("admin") + assert h.admin.get("/api/auth/me").json()["menus"]["board"] == "rw" + # 另外两个内置角色可以改授权,但不能删 + member = h.roles()["部门成员"] + assert h.admin.delete(f"/api/rbac/roles/{member['id']}").status_code == 400 + assert h.admin.patch(f"/api/rbac/roles/{member['id']}", json={"menus": {"board": "ro"}}).status_code == 200 + assert h.roles()["部门成员"]["menus"] == {"board": "ro"} + # 还原内置授权,免得影响同一次运行里的其它断言 + with SessionLocal() as db: + db.query(RoleMenu).filter(RoleMenu.role_id == member["id"]).delete(synchronize_session=False) + for menu, level in security.BUILTIN_ROLES[1][2].items(): + db.add(RoleMenu(role_id=member["id"], menu=menu, level=level)) + db.commit() + + +def test_正在使用的角色不能删(h): + r = h.role("临时岗", {"board": "ro"}) + h.user("temp_user", role_ids=[r["id"]]) + res = h.admin.delete(f"/api/rbac/roles/{r['id']}") + assert res.status_code == 400 and "还有用户" in res.json()["detail"] + # 自己正在用的角色也不能删(管理员角色就是 admin 正在用的) + assert h.admin.delete(f"/api/rbac/roles/{h.roles()['管理员']['id']}").status_code == 400 + assert "内置角色" in h.admin.delete(f"/api/rbac/roles/{h.roles()['管理员']['id']}").json()["detail"] + + +# ------------------------------------------------------------------ 用户管理 +def test_建账号的校验(h): + h.user("dup_user", menus={"board": "ro"}) + assert h.admin.post("/api/rbac/users", json={"name": "重名", "username": "dup_user", + "password": "pw123456"}).status_code == 400 + assert h.admin.post("/api/rbac/users", json={"name": "", "username": "no_name", + "password": "pw123456"}).status_code == 400 + assert h.admin.post("/api/rbac/users", json={"name": "短密码", "username": "short_pw", + "password": "123"}).status_code == 400 + assert h.admin.post("/api/rbac/users", json={"name": "没这个角色", "username": "ghost_role", + "password": "pw123456", + "role_ids": [424242]}).status_code == 400 + # 不指定角色 → 默认给「部门成员」,避免建出一个进不了门的账号 + d = h.user("default_role") + assert d["role_names"] == ["部门成员"] + + +def test_用户列表字段与在线状态(h): + h.user("online_one", menus={"board": "ro"}) + h.login("online_one") # 制造一个在线会话 + users = {u["username"]: u for u in h.admin.get("/api/rbac/users").json()} + u = users["online_one"] + assert u["online"] >= 1 and u["active"] is True + assert u["menus"] == {"board": "ro"} and len(u["role_ids"]) == 1 + assert "password_hash" not in u and "role_id" not in u + + +def test_改名改权限会踢掉该账号的会话(h): + u = h.user("revoke_me", menus={"board": "rw"}) + c = h.login("revoke_me") + assert c.get("/api/weekly").status_code == 200 + r = h.role("换个岗位", {"custom": "rw"}) + assert h.admin.patch(f"/api/rbac/users/{u['id']}", json={"role_ids": [r["id"]]}).status_code == 200 + assert c.get("/api/weekly").status_code == 401 # 权限变了必须重新登录 + fresh = h.login("revoke_me") + assert fresh.get("/api/weekly").status_code == 403 + assert fresh.get("/api/custom/projects").status_code == 200 + + +def test_管理员重置密码不需要旧密码但会下线对方(h): + u = h.user("reset_pw", menus={"board": "ro"}) + c = h.login("reset_pw") + assert h.admin.patch(f"/api/rbac/users/{u['id']}", json={"password": "brandnew1"}).status_code == 200 + assert c.get("/api/auth/me").status_code == 401 + assert h.anon.post("/api/auth/login", json={"username": "reset_pw", + "password": "pw123456"}).status_code == 401 + assert h.login("reset_pw", "brandnew1").get("/api/auth/me").status_code == 200 + assert h.admin.patch(f"/api/rbac/users/{u['id']}", json={"password": "1"}).status_code == 400 + + +def test_不能动自己(h): + me = h.admin.get("/api/auth/me").json() + member_role = h.roles()["部门成员"]["id"] + r1 = h.admin.patch(f"/api/rbac/users/{me['id']}", json={"role_ids": [member_role]}) + assert r1.status_code == 400 and "自己的角色" in r1.json()["detail"] + r2 = h.admin.patch(f"/api/rbac/users/{me['id']}", json={"active": False}) + assert r2.status_code == 400 and "停用" in r2.json()["detail"] + r3 = h.admin.delete(f"/api/rbac/users/{me['id']}") + assert r3.status_code == 400 and "删除自己" in r3.json()["detail"] + # 但改自己的昵称是允许的 + assert h.admin.put("/api/auth/me", json={"name": "系统管理员"}).json()["name"] == "系统管理员" + + +def test_删除账号会连带清掉会话与角色关联(h): + u = h.user("drop_me", menus={"board": "ro"}) + c = h.login("drop_me") + assert h.admin.delete(f"/api/rbac/users/{u['id']}").json() == {"ok": True} + assert c.get("/api/auth/me").status_code == 401 + assert u["id"] not in {x["id"] for x in h.admin.get("/api/rbac/users").json()} + assert h.admin.delete("/api/rbac/users/424242").status_code == 404 + + +def test_没人能管权限时启动补种会自动补一个管理员(db): + """防锁死兜底:最后一个可管理账号丢了,ensure_seed 会把管理员角色补给最早的账号。""" + with SessionLocal() as s: + member = s.query(Role).filter(Role.name == "部门成员").one() + admin_role = s.query(Role).filter(Role.name == "管理员").one() + victim = s.query(User).filter(User.username == "admin").one() + s.query(UserRole).filter(UserRole.user_id == victim.id).delete() + s.add(UserRole(user_id=victim.id, role_id=member.id)) + s.commit() + assert victim.menus.get("rbac") is None + notes = security.ensure_seed(s) + assert any("管理员" in n for n in notes), notes + s.expire_all() + assert s.get(User, victim.id).menus["rbac"] == "rw" + assert admin_role is not None + + +# ------------------------------------------------------------------ 会话 +def test_会话列表能看得到并能逐个下线(h): + u = h.user("sess_one", menus={"board": "ro"}) + h.login("sess_one") + sessions = h.admin.get("/api/rbac/sessions").json() + mine = [s for s in sessions if s["user_id"] == u["id"]] + assert len(mine) == 1 + s = mine[0] + assert s["username"] == "sess_one" and s["token"] + # 列表只展示打码后的 token_hint,但下线要用完整 token + assert s["token"].startswith(s["token_hint"].rstrip("…")) and "…" in s["token_hint"] + assert s["expires_at"] and s["created_at"] + assert h.admin.delete(f"/api/rbac/sessions/{s['token']}").json() == {"ok": True} + assert [x for x in h.admin.get("/api/rbac/sessions").json() if x["user_id"] == u["id"]] == [] + assert h.admin.delete("/api/rbac/sessions/不存在的token").status_code == 404 + + +def test_下线自己的会话等于自己退出(h): + tokens = {s["username"]: s["token"] for s in h.admin.get("/api/rbac/sessions").json()} + assert h.admin.delete(f"/api/rbac/sessions/{tokens['admin']}").status_code == 200 + assert h.admin.get("/api/auth/me").status_code == 401 + + +# ------------------------------------------------------------------ 审计 +def test_写操作与越权尝试都留痕并能筛选(h): + r = h.role("审计岗", {"board": "ro"}) + u = h.user("audit_user", role_ids=[r["id"]]) + # 角色下还有人 → 删不掉,这次失败的尝试同样进日志 + assert h.admin.delete(f"/api/rbac/roles/{r['id']}").status_code == 400 + h.admin.delete(f"/api/rbac/users/{u['id']}") + assert h.admin.delete(f"/api/rbac/roles/{r['id']}").status_code == 200 + logs = h.admin.get("/api/rbac/logs", params={"menu": "rbac", "limit": 100}).json() + assert logs["total"] >= 3 + actions = {x["action"] for x in logs["items"]} + assert {"create", "delete"} <= actions + details = ";".join(x["detail"] or "" for x in logs["items"]) + assert "新建角色「审计岗」" in details and "删除角色「审计岗」" in details + assert all(x["username"] == "admin" for x in logs["items"]) + # 被拒的那次删除也留了痕,说明里带上了状态码 + denied_role = [x for x in logs["items"] if x["status"] == 400] + assert denied_role and "HTTP 400" in denied_role[0]["detail"] + # 越权尝试同样进日志,并带上被拒的说明 + h.user("bad_try", menus={"board": "ro"}) + c = h.login("bad_try") + assert c.post("/api/projects", json={"name": "越权"}).status_code == 403 + denied = h.admin.get("/api/rbac/logs", + params={"username": "bad_try", "action": "create"}).json() + assert denied["total"] == 1 + assert denied["items"][0]["status"] == 403 and "HTTP 403" in denied["items"][0]["detail"] + assert denied["items"][0]["menu"] == "projects" and denied["items"][0]["action"] == "create" + # 失败的登录也按被尝试的账号记一笔 + h.anon.post("/api/auth/login", json={"username": "bad_try", "password": "错的答案"}) + by_action = h.admin.get("/api/rbac/logs", params={"action": "login"}).json() + assert any(x["status"] == 401 and "登录失败" in (x["detail"] or "") for x in by_action["items"]) + # 筛选参数与分页 + assert h.admin.get("/api/rbac/logs", params={"action": "revoke"}).json()["total"] == 0 + page1 = h.admin.get("/api/rbac/logs", params={"limit": 1, "offset": 0}).json() + page2 = h.admin.get("/api/rbac/logs", params={"limit": 1, "offset": 1}).json() + assert page1["total"] == page2["total"] and page1["items"][0]["id"] != page2["items"][0]["id"] + assert h.admin.get("/api/rbac/logs", params={"days": 0}).status_code == 422 + + +def test_清空日志(h): + h.role("要被记一笔", {"board": "ro"}) + assert h.admin.get("/api/rbac/logs").json()["total"] >= 1 + assert h.admin.delete("/api/rbac/logs", params={"days": 0}).json()["deleted"] >= 1 + # 清空动作本身也会被记一笔,剩下的只应有一条「删除 /api/rbac/logs」 + rest = h.admin.get("/api/rbac/logs").json()["items"] + assert all(x["path"] == "/api/rbac/logs" for x in rest), rest + + +def test_敏感写操作的说明文字可读(h): + u = h.user("note_user", menus={"board": "ro"}) + h.admin.patch(f"/api/rbac/users/{u['id']}", json={"name": "改名了", "active": False}) + h.admin.post(f"/api/rbac/users/{u['id']}/revoke") + items = h.admin.get("/api/rbac/logs", params={"limit": 50}).json()["items"] + joined = ";".join(x["detail"] or "" for x in items) + assert "修改账号 note_user:改名、停用" in joined + assert "强制下线 note_user" in joined diff --git a/tests/test_staff_focus_weekly.py b/tests/test_staff_focus_weekly.py new file mode 100644 index 0000000..0e19f82 --- /dev/null +++ b/tests/test_staff_focus_weekly.py @@ -0,0 +1,197 @@ +"""人力库(花名册 / 负载)、每周重点工作、周视图汇总。""" +from __future__ import annotations + +from app import constants + + +def _row(h, name): + rows = [x for x in h.admin.get("/api/staff").json()["items"] if x["name"] == name] + assert rows, f"花名册里找不到 {name}" + return rows[0] + + +# ------------------------------------------------------------------ 人力库 +def test_花名册的增删改查(h): + a = h.staff("陈明", group="Nex产品组", affiliation="汇智", note="接口负责人") + assert (a["group"], a["affiliation"], a["note"]) == ("Nex产品组", "汇智", "接口负责人") + assert a["sort_order"] == 1 # 不给序号就排在最后 + assert h.staff("李雷", group="AI项目组", affiliation="云数科技")["group"] == "AI产品组" + assert _row(h, "李雷")["affiliation"] == "云数" # 历史写法归一到标准口径 + + assert h.admin.post("/api/staff", json={"name": "陈明"}).status_code == 400 + assert h.admin.post("/api/staff", json={"name": " "}).status_code == 400 + assert h.admin.patch("/api/staff/424242", json={"note": "x"}).status_code == 404 + assert h.admin.delete("/api/staff/424242").status_code == 404 + + upd = h.admin.patch(f"/api/staff/{a['id']}", json={"note": "换成项目负责人", "偷改": 1}).json() + assert upd["synced"] == {"projects": 0, "custom_projects": 0} + assert upd["staff"]["note"] == "换成项目负责人" and "偷改" not in upd["staff"] + assert h.admin.patch(f"/api/staff/{a['id']}", json={"name": "李雷"}).status_code == 400 + assert h.admin.patch(f"/api/staff/{a['id']}", json={"name": " "}).status_code == 400 + + # 归档后默认列表看不到,但名字仍占着,不能新建同名 + h.admin.patch(f"/api/staff/{a['id']}", json={"archived": True}) + assert "陈明" not in [x["name"] for x in h.admin.get("/api/staff").json()["items"]] + assert "陈明" in [x["name"] for x in h.admin.get("/api/staff", params={"archived": "true"}).json()["items"]] + assert h.admin.post("/api/staff", json={"name": "陈明"}).status_code == 400 + # 关键字命中姓名或备注;小组筛选按标准口径 + assert [x["name"] for x in h.admin.get("/api/staff", params={"archived": "all", "keyword": "负责人"}).json()["items"]] == ["陈明"] + assert [x["name"] for x in h.admin.get("/api/staff", params={"keyword": "李雷"}).json()["items"]] == ["李雷"] + assert [x["name"] for x in h.admin.get("/api/staff", params={"group": "AI产品组"}).json()["items"]] == ["李雷"] + + +def test_负载统计与删除保护(h): + s = h.staff("王芳", group="定制产品组") + p = h.project("园区项目", owners=["王芳"], is_key=True) + cp = h.custom("定制甲", owner="王芳", amount=100000, revenue_amount=40000) + h.project("别人的项目", owners=["赵四"], members=["王芳"]) + row = _row(h, "王芳") + assert (row["project_count"], row["key_project_count"]) == (1, 1) + assert row["custom_count"] == 1 + assert (row["custom_amount"], row["custom_pending"]) == (100000.0, 60000.0) + assert row["last_update"] is None # 名下项目还没有任何执行记录 + + data = h.admin.get("/api/staff").json() + assert data["summary"]["total"] == 1 and data["summary"]["with_project"] == 1 + assert {"name": "定制产品组", "count": 1} in data["summary"]["groups"] + assert {"name": "未填写", "count": 1} in data["summary"]["affiliations"] + assert data["summary"]["outside"] == [{"name": "赵四", "project_count": 1, "custom_count": 0}] + assert data["dict"]["groups"] and data["dict"]["affiliations"] + + # 有执行记录之后,负载上能看到最近一次动静在哪一周 + pid = h.today_period_id + h.update(p["id"], pid, content="本周推进") + assert _row(h, "王芳")["last_update"] == h.periods()["weeks"][-1]["full_label"] + + # 名下有在管项目:默认不给删,提示归档;确认要删才删 + r = h.admin.delete(f"/api/staff/{s['id']}") + assert r.status_code == 400 and "归档" in r.json()["detail"] + assert h.admin.delete(f"/api/staff/{s['id']}?force=true").json()["ok"] is True + assert h.admin.get("/api/projects").json() and h.admin.get("/api/custom/projects").json() + + # 改名要把名下项目的负责人一并带过去,否则负载和记录会认不出人 + q = h.staff("旧名字") + mine = h.project("要跟着改名的项目", owners=["旧名字"], other_owners=["旧名字"]) + patched = h.admin.patch(f"/api/staff/{q['id']}", json={"name": "新名字"}).json() + assert patched["synced"] == {"projects": 1, "custom_projects": 0} + fresh = h.admin.get(f"/api/projects/{mine['id']}").json()["project"] + assert fresh["owner"] == "新名字" and "旧名字" not in fresh["owners"] + assert cp["id"] + + +# ------------------------------------------------------------------ 每周重点工作 +def test_重点工作按录入周归属(h): + today = h.periods()["today_id"] + item = h.focus("整理三季度复盘") + assert item["period_id"] == today # 不传周期就按今天所在的周 + assert item["status"] == "not_started" and item["delayed"] is False + + assert h.admin.post("/api/focus", json={"content": " "}).status_code == 400 + assert h.admin.post("/api/focus", json={"content": "x", "status": "起飞了"}).status_code == 400 + assert h.admin.post("/api/focus", json={"content": "x", "period_id": 424242}).status_code == 400 + bad = h.admin.post("/api/focus", json={"content": "x", "due_date": "下周五"}) + assert bad.status_code == 400 and "YYYY-MM-DD" in bad.json()["detail"] + + week = h.period(2028, 3, 2) + other = h.focus("明年这时候干", period_id=week["id"], due_date="2028-03-20", detail="说明") + assert other["period_id"] == week["id"] and other["due_date"] == "2028-03-20" + # 改预计完成时间不会把条目搬去别的周 + moved = h.admin.patch(f"/api/focus/{other['id']}", json={"due_date": "2026-01-05"}).json() + assert moved["due_date"] == "2026-01-05" and moved["period_id"] == week["id"] + assert h.admin.patch(f"/api/focus/{other['id']}", json={"due_date": ""}).json()["due_date"] is None + done = h.admin.patch(f"/api/focus/{other['id']}", + json={"status": "done", "result": "已完成", "delayed": True}).json() + assert (done["status"], done["result"], done["delayed"]) == ("done", "已完成", True) + assert h.admin.patch(f"/api/focus/{other['id']}", json={"status": "不认识"}).status_code == 400 + assert h.admin.patch(f"/api/focus/{other['id']}", json={"content": ""}).status_code == 400 + assert h.admin.patch("/api/focus/424242", json={"status": "done"}).status_code == 404 + + rows = h.admin.get("/api/focus").json() + assert [x["id"] for x in rows] == [other["id"], item["id"]] # 新录入在前 + assert [x["id"] for x in h.admin.get("/api/focus", params={"status": "done"}).json()] == [other["id"]] + assert [x["id"] for x in h.admin.get("/api/focus", params={"keyword": "复盘"}).json()] == [item["id"]] + assert [x["id"] for x in h.admin.get("/api/focus", params={"keyword": "说明"}).json()] == [other["id"]] + h.admin.patch(f"/api/focus/{item['id']}", json={"archived": True}) + assert item["id"] not in [x["id"] for x in h.admin.get("/api/focus").json()] + assert item["id"] in [x["id"] for x in h.admin.get("/api/focus", params={"archived": "true"}).json()] + assert h.admin.delete(f"/api/focus/{item['id']}").json()["ok"] is True + assert h.admin.delete("/api/focus/424242").status_code == 404 + + +# ------------------------------------------------------------------ 周视图 +def test_周视图把两条线的动态合在一起(h): + week = h.period(2028, 3, 2) + key = h.project("重点项目", owners=["王芳"], is_key=True) + quiet = h.project("沉默的重点项目", is_key=True) + h.update(key["id"], week["id"], content="接口联调过半", progress=60, + status="at_risk", risk="等对方给文档", next_step="周三对齐") + h.update(key["id"], week["id"], content="出现阻塞", status="blocked") + # 入库/下单时间取本周第一天,确保「本周新增」判定落在选中的这一周里 + week_first = constants.period_first_day(2028, 3, 2) + busy = h.custom("本周有动静的定制", owner="王芳", amount=100000, + entry_date=week_first, sign_date=week_first) + idle = h.custom("躺着不动的定制", amount=200000) + h.custom_update(busy["id"], week["id"], content="完成部署", progress=80, + amount_delta=50000, revenue_delta=20000, risk="验收时间待定") + + d = h.admin.get("/api/weekly", params={"period_id": week["id"]}).json() + assert [x["id"] for x in d["periods"]] == [week["id"]] + projects = {x["name"]: x for x in d["projects"]} + assert set(projects) == {"重点项目", "沉默的重点项目"} # 非重点又没动静的不占版面 + assert projects["重点项目"]["has_update"] and projects["重点项目"]["update_count"] == 2 + assert projects["重点项目"]["progress"] == 60.0 + assert projects["重点项目"]["progress_source"] == "本周期" + assert projects["重点项目"]["risks"] == ["等对方给文档"] + assert projects["重点项目"]["status"] == "blocked" # 多条记录取最坏状态 + assert projects["沉默的重点项目"]["has_update"] is False + assert projects["沉默的重点项目"]["progress_source"] == "项目档案" + + # 定制这一线:本周有动静 / 本周新增 / 重点才占版面,躺着不动的默认不出现 + custom = {x["name"]: x for x in d["custom"]} + assert set(custom) == {"本周有动静的定制"} + assert custom["本周有动静的定制"]["is_new"] is True # 入库时间落在本周 + assert custom["本周有动静的定制"]["period_amount_delta"] == 50000.0 + assert custom["本周有动静的定制"]["period_revenue_delta"] == 20000.0 + + k = d["kpi"] + assert (k["key_total"], k["key_updated"], k["key_idle"]) == (2, 1, 1) + assert (k["update_count"], k["custom_new"], k["custom_updated"]) == (2, 1, 1) + assert k["amount_delta"] == 50000.0 and k["revenue_delta"] == 20000.0 + assert k["risk_count"] == 2 and k["at_risk_count"] == 1 and k["blocked_count"] == 1 + + # 按人筛选只看他名下的活儿 + byowner = h.admin.get("/api/weekly", params={"period_id": week["id"], "owner": "王芳"}).json() + assert [x["name"] for x in byowner["projects"]] == ["重点项目"] + assert [x["name"] for x in byowner["custom"]] == ["本周有动静的定制"] + # 月视图:该月各周合并统计,跨周的记录也算进来 + monthly = h.admin.get("/api/weekly", params={"year": 2028, "month": 3}).json() + assert monthly["kpi"]["update_count"] == 2 and monthly["periods"][0]["id"] == week["id"] + # all_custom:在途的定制项目全部列出来,没动静的也盯一眼 + everything = h.admin.get("/api/weekly", params={"period_id": week["id"], "all_custom": True}).json() + assert {x["name"] for x in everything["custom"]} == {"本周有动静的定制", "躺着不动的定制"} + assert {x["name"]: x["is_new"] for x in everything["custom"]}["躺着不动的定制"] is False + assert everything["kpi"]["custom_total"] == 2 + + +def test_周视图的没更新周数(h): + w1 = h.period(2028, 3, 1) + w2 = h.period(2028, 3, 2) + w3 = h.period(2028, 3, 3) + p = h.project("看更新节奏", is_key=True) + h.update(p["id"], w1["id"], content="第一周更新过一次") + rows = {x["name"]: x for x in h.admin.get("/api/weekly", params={"period_id": w3["id"]}).json()["projects"]} + assert rows["看更新节奏"]["idle_weeks"] == 2 and rows["看更新节奏"]["has_update"] is False + rows = {x["name"]: x for x in h.admin.get("/api/weekly", params={"period_id": w2["id"]}).json()["projects"]} + assert rows["看更新节奏"]["idle_weeks"] == 1 + assert rows["看更新节奏"]["last_update"] == "2028年3月第1周" + + +def test_选中的年月还没有周期时给空骨架(h): + h.project("空视图") + d = h.admin.get("/api/weekly", params={"year": 2031, "month": 6}).json() + assert d["periods"] == [] and d["projects"] == [] and d["custom"] == [] + assert set(d["kpi"]) == {"key_total", "key_updated", "key_idle", "project_listed", + "update_count", "custom_total", "custom_new", "custom_updated", + "custom_amount", "amount_delta", "revenue_delta", + "risk_count", "at_risk_count", "blocked_count"} + assert all(not v for v in d["kpi"].values()) diff --git a/web/app.js b/web/app.js index 78d2bd4..6f6bec5 100644 --- a/web/app.js +++ b/web/app.js @@ -17,14 +17,13 @@ meta: null, periods: null, categories: [], - board: null, - stats: null, projects: [], drawerProject: null, // 详情抽屉:周期反馈的显示粒度 / 范围 / 往前翻页偏移 dw: { group: "week", range: 2, back: 0 }, // 定制项目 customMeta: null, + finance: null, // /custom/finance 汇总:统计条与年度任务的唯一数据源 // 定制:项目明细 / 本周进展 两个 tab(原交付流水线 / 阶段看板 / 财务跟踪已下线) customTab: "list", customAnnualEdit: false, // 年度任务:默认查看模式,点「编辑」才可改 @@ -43,7 +42,6 @@ intakeType: "general", // 更新录入的两种方式:direct = 直接写入(原样存 1 条);ai = AI 整理(补结构化字段,也只存 1 条) intakeMode: "direct", - intakePeriodId: null, drawerCustom: null, // 周看板(左栏总览 + 右栏详情) weekly: null, @@ -55,6 +53,9 @@ focusRows: [], focusFilter: "week", focusArchived: false, + // 权限管理:当前 tab / 操作日志筛选 + rbacTab: "roles", + rbacLog: { username: "", menu: "", action: "", days: 30 }, // 人力资源库 staff: [], staffDict: { groups: [], affiliations: [] }, @@ -177,7 +178,7 @@ $("#sideUser").innerHTML = `
@@ -969,7 +1004,7 @@
本期交付记录(${row.updates.length})
${row.updates.length ? row.updates.map((x) => updateItem(x, "custom")).join("") - : `
本周期没有交付记录。
`} + : `
本周期没有交付记录
`}
${hist.length ? ` @@ -989,7 +1024,7 @@ if (add) add.addEventListener("click", () => openUpdateDialog({ kind: row.kind, periodId: state.weekId, projectId: row.id, customProjectId: row.id, - status: row.status, stage: row.stage, + status: row.status, customStatus: row.project_status, }) ); bindUpdateOps(box, row.updates); @@ -1040,13 +1075,14 @@ const { added, accepted, listed } = customWeeklySections(data.custom, scopeRange()); // 高风险取全部在档项目:/weekly 的 custom 只有本期有动态的,取全量才不会漏 // 只列「统计周期所在季度」要推动验收的高风险项目(按推动验收计划 Q1~Q4) - const riskQ = "Q" + scopeQuarter(); + const ctx = (state.finance || {}).context || {}; + const riskQ = "Q" + (ctx.quarter || (Math.floor(new Date().getMonth() / 3) + 1)); const risky = (state.customAll || data.custom) .filter((r) => isHighRisk(r) && String(r.accept_plan || "").trim().toUpperCase() === riskQ) .sort((a, b) => Number(b.amount || 0) - Number(a.amount || 0)); // 合计只算列出来的行(同一项目可能同时出现在新增与验收两段,这里按 id 去重),免得数字对不上清单 const sum = listed.reduce((a, r) => a + Number(r.amount || 0), 0); - const sec = (title, sub, list, tag, o) => ` + const sec = (title, list, tag, o) => `
${title}
${list.length ? list.map((r) => weeklyCustomRow(r, tag(r), o)).join("") @@ -1068,11 +1104,11 @@
- ${sec("本周新增", "下单时间落在本周期(已下单 / 提前交付)", added, + ${sec("本周新增", added, (r) => `${esc(String(r.sign_date || "").slice(0, 10) || "本期下单")}`)} - ${sec("本周验收", "更新时间落在本周期且状态为已验收", accepted, + ${sec("本周验收", accepted, (r) => `${esc(String(r.update_date || "").slice(0, 10) || "本期验收")}`)} - ${sec("高风险项目(推动验收计划 " + riskQ + ")", "风险值为高风险且推动验收计划落在统计周期所在季度", risky, + ${sec("高风险项目(推动验收计划 " + riskQ + ")", risky, (r) => (r.project_status ? `${esc(r.project_status)}` : ""), { province: true, owner: false, empty: riskQ + " 没有推动验收的高风险项目" })}`; } @@ -1123,19 +1159,14 @@ const host = $("#view-board"); host.innerHTML = `
加载中…
`; if (!state.customMeta) state.customMeta = await api("/custom/meta"); - const [data, focusRows, customAll] = await Promise.all([ + const [data, focusRows, customAll, fin] = await Promise.all([ api("/weekly" + scopeQuery()), api("/focus" + focusQuery(["archived=false"])), - // 「本季度验收」与「定制项目 · 项目总览」同一口径:严格按「验收时间」(Q1~Q4 季度文本) api("/custom/projects?archived=false"), + api("/custom/finance" + finQuery()), ]); - const now = new Date(); - const qYear = now.getFullYear(), qNo = Math.floor(now.getMonth() / 3) + 1; - const qOf = (s) => { const t = String(s || "").trim().toUpperCase(); return /^Q[1-4]$/.test(t) ? t : ""; }; - // 与「定制项目 · 项目总览」同一口径:严格按「验收时间」(Q1~Q4 季度文本),没填的不计入 - const accQuarter = customAll.filter((p) => qOf(p.accept_date) === "Q" + qNo); - const accQuarterAmount = accQuarter.reduce((a, p) => a + Number(p.amount || 0), 0); - const accYearCount = customAll.filter((p) => qOf(p.accept_date)).length; + state.finance = fin; + const FC = fin.context, FK = fin.kpi; state.weekly = data; state.customAll = customAll; // 右栏「高风险项目」用全量台账 state.focusRows = focusRows; @@ -1161,7 +1192,7 @@
${Ico.badge("star")}
重点项目
${k.key_total}
本期已更新 ${k.key_updated}
${Ico.badge("list-checks")}
本周重点工作
${focus.week.length}
延期 ${focus.overdue.length} 条 · 已完成 ${focus.done.length} 条
${Ico.badge("activity")}
执行记录
${k.update_count}
在办项目 ${k.project_listed} 个
-
${Ico.badge("wallet")}
截止验收(${qYear}年Q${qNo})
${fen(accQuarterAmount)} 万
${accQuarter.length} 个项目 · 本年验收 ${accYearCount} 个
+
${Ico.badge("wallet")}
截止验收(${esc(FC.quarter_label)})
${fen(FK.accept_quarter.amount)} 万
${FK.accept_quarter.count} 个项目 · ${FC.year} 年验收 ${FK.accept_year.count} 个
${Ico.badge("alert")}
工作风险 / 阻塞
${k.at_risk_count} / ${k.blocked_count}
`; @@ -1481,13 +1512,13 @@
基本信息
-
+
${esc(entryWeek)}
-
+
`; $("#drawerBody").innerHTML = @@ -1772,20 +1803,53 @@ let keywordFocus = false; - /** 定制「项目归属」取值:前三项视为「已下单」,提前交付为下单前状态 */ - const CUSTOM_ORIGINS = ["华智下单", "存量项目", "汇智直签", "提前交付"]; - const CUSTOM_PLACED = ["华智下单", "存量项目", "汇智直签"]; - const isPlaced = (p) => CUSTOM_PLACED.indexOf(p.origin) >= 0; + /** 定制台账的下拉取值一律取 /custom/meta(后端是唯一来源),前端不再各写一份。 + * meta 没取到时用台账口径兜底,保证离线/异常时下拉不至于空。 */ + const CM_DEFAULTS = { + statuses: ["待开发", "进行中", "交付完成", "已验收", "退单"], + origins: ["华智下单", "存量项目", "汇智直签", "提前交付"], + placed_origins: ["华智下单", "存量项目", "汇智直签"], + industries: [], + risks: ["1.高风险", "2.低风险"], + }; + const cmOptions = (key) => { + const m = state.customMeta || {}; + return (m[key] && m[key].length) ? m[key] : CM_DEFAULTS[key]; + }; + /** 下拉 option:当前值不在标准取值里(历史脏数据)时补一项,避免一改就把原值清掉 */ + function optionHtml(list, sel) { + const l = (list || []).slice(); + if (sel && l.indexOf(sel) < 0) l.push(sel); + return l.map((v) => ``).join(""); + } + const isPlaced = (p) => cmOptions("placed_origins").indexOf(p.origin) >= 0; + + /** 验收年度下拉:验收时间只有季度,跨年靠它判定,跟季度成对填写 */ + function yearSelectHtml(id, value) { + const cur = Number(value) || 0; + const now = new Date().getFullYear(); + const list = []; + for (let y = now + 1; y >= now - 6; y--) list.push(y); + if (cur && list.indexOf(cur) < 0) list.unshift(cur); + return ``; + } async function renderCustom() { saveUI(); const host = $("#view-custom"); host.innerHTML = `
加载中…
`; if (!state.customMeta) state.customMeta = await api("/custom/meta"); - // 一次性取「全部定制项目」(不带搜索/筛选条件): - // 列表在本地按关键字/区域/状态筛选,而统计条始终基于全部数据。 - const allRows = await api("/custom/projects?archived=" + state.customArchived); + // 一次性取「全部定制项目」(不带搜索/筛选条件):列表在本地按关键字/区域/状态筛选; + // 财务口径由 /custom/finance 给出,跟着顶栏统计周期走,不随列表筛选变化。 + const [allRows, fin] = await Promise.all([ + api("/custom/projects?archived=" + state.customArchived), + api("/custom/finance" + finQuery()), + ]); state.customRows = allRows; + state.finance = fin; // 区域筛选:用规范名称、按大区分组,只列出实际有项目的区域 const usedSet = {}; @@ -1806,14 +1870,11 @@ ``; } - const STATUS_OPTIONS = ["已验收", "待开发", "交付完成", "进行中", "退单"]; - const statusFilterHtml = `` + - STATUS_OPTIONS.map((s) => ``).join(""); - const originFilterHtml = `` + - CUSTOM_ORIGINS.map((o) => ``).join(""); - const RISK_OPTIONS = ["1.高风险", "2.低风险"]; - const riskFilterHtml = `` + - RISK_OPTIONS.map((r) => ``).join(""); + const filterHtml = (label, list, cur) => `` + + list.map((v) => ``).join(""); + const statusFilterHtml = filterHtml("全部状态", cmOptions("statuses"), state.customStatus); + const originFilterHtml = filterHtml("全部归属", cmOptions("origins"), state.customOrigin); + const riskFilterHtml = filterHtml("全部风险值", cmOptions("risks"), state.customRisk); const isList = state.customTab !== "weekly" && state.customTab !== "annual"; // 三个 tab 是卡片外的页签,选中项和下方卡片连成一体;header 面板只放筛选器和功能按钮 @@ -1822,7 +1883,7 @@ .join("") + ``; const head = { tools: isList ? ` - ${keywordInputHtml("cKeyword", "搜索项目名称…(回车查询)", 200)} + ${keywordInputHtml("cKeyword", "搜索项目名称…", 200)} @@ -1833,7 +1894,7 @@ host.innerHTML = tabs + ( state.customTab === "weekly" ? renderCustomWeekly(allRows, head) - : state.customTab === "annual" ? renderCustomAnnual(allRows, head) + : state.customTab === "annual" ? renderCustomAnnual(head) : renderCustomList(allRows, head)); host.querySelectorAll("[data-ctab]").forEach((b) => @@ -1888,45 +1949,28 @@ const pageRows = pagedRows(view, "custom", [state.customTab, state.keyword, state.customOrigin, state.customRegion, state.customStatus, state.customRisk, state.customArchived]); - // ---- 统计条:基于「全部已下单项目」,不随搜索 / 筛选变化 ---- - const placed = allRows.filter(isPlaced); // 已下单 = 华智下单 / 存量项目 / 汇智直签 - const today = new Date(); - const Y = today.getFullYear(); - const M = today.getMonth() + 1; - const Q = Math.floor((M - 1) / 3) + 1; // 当前季度 1~4 - const sum = (arr, f) => arr.reduce((a, p) => a + Number(p[f] || 0), 0); - // 取日期里的「年-月」;像「2024年3月前」这种文本不参与季度/年度判定 - const ymOf = (d) => { - const s = String(d || ""); - return /^\d{4}-\d{2}/.test(s) ? { y: Number(s.slice(0, 4)), m: Number(s.slice(5, 7)) } : null; - }; - const inYear = (d) => { const t = ymOf(d); return !!t && t.y === Y; }; - const inQuarter = (d) => { const t = ymOf(d); return !!t && t.y === Y && Math.floor((t.m - 1) / 3) + 1 === Q; }; - - const signedQuarter = placed.filter((p) => inQuarter(p.sign_date)); - const signedYear = placed.filter((p) => inYear(p.sign_date)); - // 验收:严格按「验收时间」(accept_date,季度文本 Q1~Q4) —— 没填验收时间的不计入; - // 本季度 = 验收时间等于当前季度;本年 = 有验收时间(全部季度)。 - const qOf = (s) => { const t = String(s || "").trim().toUpperCase(); return /^Q[1-4]$/.test(t) ? t : ""; }; - const thisQ = "Q" + Q; - const accRows = allRows.filter((p) => qOf(p.accept_date)); - const accQuarter = accRows.filter((p) => qOf(p.accept_date) === thisQ); - const accYear = accRows; - - const stat = (label, count, amount, accent, icon) => - `
${Ico.badge(icon)}
${label}
${fen(amount)} 万
${count} 个项目
`; - + // ---- 统计条:口径全部来自 /custom/finance,跟着顶栏统计周期走,不随搜索 / 筛选变化 ---- + const C = (state.finance || {}).context || {}; + const K = (state.finance || {}).kpi || {}; + const stat = (label, box, accent, icon) => + `
${Ico.badge(icon)}
${label}
${fen((box || {}).amount)} 万
${(box || {}).count || 0} 个项目
`; const statBar = `
- ${stat("已下单项目 / 合同额", placed.length, sum(placed, "amount"), "accent-blue", "wallet")} - ${stat(`本季度下单(${Y}年Q${Q})`, signedQuarter.length, sum(signedQuarter, "amount"), "accent-violet", "trending-up")} - ${stat(`本年新增下单(${Y}年)`, signedYear.length, sum(signedYear, "amount"), "accent-violet", "trending-up")} - ${stat(`本季度验收(${Y}年Q${Q})`, accQuarter.length, sum(accQuarter, "amount"), "accent-amber", "receipt")} - ${stat(`本年验收项目(${Y}年)`, accYear.length, sum(accYear, "amount"), "accent-amber", "receipt")} + ${stat("已下单项目 / 合同额", K.placed, "accent-blue", "wallet")} + ${stat("本季度下单(" + esc(C.quarter_label || "—") + ")", K.sign_quarter, "accent-violet", "trending-up")} + ${stat("本年新增下单(" + (C.year || "—") + "年)", K.sign_year, "accent-violet", "trending-up")} + ${stat("本季度验收(" + esc(C.quarter_label || "—") + ")", K.accept_quarter, "accent-amber", "receipt")} + ${stat("本年验收(" + (C.year || "—") + "年)", K.accept_year, "accent-amber", "receipt")}
`; + // 台账里下单时间 / 验收时间填了系统认不出的写法时,在标题栏挂一个不挡事的提示 + const dirty = []; + if (K.sign_unknown) dirty.push(K.sign_unknown + " 个项目下单时间无法识别"); + if (K.accept_no_year) dirty.push(K.accept_no_year + " 个已验收项目未填验收年度"); + const dirtyTag = dirty.length + ? `${dirty.join(" · ")}` : ""; return `
- ${cardHead({ tools: hdr.tools })} + ${cardHead({ tools: hdr.tools + dirtyTag })} ${statBar} ${view.length ? customTableHtml(pageRows) : `
${state.keyword ? "没有匹配「" + esc(state.keyword) + "」的定制项目" : "当前筛选条件下没有定制项目"}
`} ${pagerBar("custom", view.length)} @@ -1938,7 +1982,7 @@ const ops = withOps !== false; const s = state.customSort || { key: "update_date", dir: "desc" }; const sth = (label, k, cls) => - `${label}${s.key === k ? (s.dir === "asc" ? " ▲" : " ▼") : ""}`; + `${label}${s.key === k ? (s.dir === "asc" ? " ▲" : " ▼") : ""}`; return `
@@ -2022,7 +2066,7 @@ function renderCustomWeekly(allRows, hdr) { hdr = hdr || {}; const sc = scopeRange(); - if (!sc) return `
没有取到当前周期的起止日期(刚更新过后端的话,请重启服务后刷新)
`; + if (!sc) return `
没有取到当前周期的起止日期
`; const start = sc.start, end = sc.end; const dayOf = (v) => String(v || "").slice(0, 10); const inScope = (v) => { const s = dayOf(v); return !!s && s >= start && s <= end; }; @@ -2055,85 +2099,74 @@ `; } - /** 年度任务:季度计收目标(可在页面上改,存后端)+ 按「验收时间 / 下单时间」回填的完成数据 */ - function renderCustomAnnual(allRows, hdr) { + /** 年度任务:四季度的计收目标(万元,可在页面编辑)+ 后端回填的完成数据。 + * 完成数据按「验收年度 + 验收季度」归集,跨年不会串;下单列按下单时间所在季度归集。 */ + function renderCustomAnnual(hdr) { hdr = hdr || {}; - const meta = annualTargetMeta(); - const Y = meta.year; - const saved = meta.targets; - const qOf = (s) => { const t = String(s || "").trim().toUpperCase(); return /^Q[1-4]$/.test(t) ? t : ""; }; - const signQ = (d) => { - const s = String(d || ""); - if (!/^\d{4}-\d{2}/.test(s) || Number(s.slice(0, 4)) !== Y) return 0; - return Math.floor((Number(s.slice(5, 7)) - 1) / 3) + 1; - }; - const sumW = (arr) => arr.reduce((a, p) => a + Number(p.amount || 0), 0) / 10000; // 元 → 万元 - const fmt = (v) => v.toLocaleString("zh-CN", { maximumFractionDigits: 2 }); - const rate = (target, acc) => (!target ? "—" : ((acc / target) * 100).toFixed(1) + "%"); - const targetOf = (q) => Number(saved[String(q)] || 0); - - const rows = [1, 2, 3, 4].map((q) => { - const acc = allRows.filter((p) => qOf(p.accept_date) === "Q" + q); // 计收:验收项目 - const sign = allRows.filter((p) => isPlaced(p) && signQ(p.sign_date) === q); // 签单:下单项目(已下单) - const accAmt = sumW(acc); - return { q, target: targetOf(q), accN: acc.length, accAmt, signN: sign.length, signAmt: sumW(sign) }; - }); - const tot = rows.reduce((a, r) => ({ - target: a.target + r.target, accN: a.accN + r.accN, accAmt: a.accAmt + r.accAmt, - signN: a.signN + r.signN, signAmt: a.signAmt + r.signAmt, - }), { target: 0, accN: 0, accAmt: 0, signN: 0, signAmt: 0 }); - + const a = (state.finance || {}).annual || {}; + const year = a.year || new Date().getFullYear(); + const quarters = a.quarters || []; const editing = !!state.customAnnualEdit; + const fmt = (v) => Number(v || 0).toLocaleString("zh-CN", { maximumFractionDigits: 2 }); + const toWan = (v) => fmt(Number(v || 0) / 10000); // 后端存元,表头是万元 + const rate = (target, acc) => (!target ? "—" : ((Number(acc || 0) / 10000 / target) * 100).toFixed(1) + "%"); + const tr = (r) => ` - - + + - - - - - + + + + + `; + const t = a.total || {}; + const u = a.unscheduled || {}; // 有年份、认不出季度的项目,计入年度但不进任何一季度 + const uRow = (!u.acc_count && !u.sign_count) ? "" : ` + + + + + + + + + `; return `
${cardHead({ tools: canW("custom") ? `` : "" })}
Q${r.q}Q${r.q}${r.current ? ` 本季度` : ""} ${editing - ? `` + ? `` : fmt(r.target)}${r.accN}${fmt(r.accAmt)}${rate(r.target, r.accAmt)}${r.signN}${fmt(r.signAmt)}${r.acc_count}${toWan(r.acc_amount)}${rate(r.target, r.acc_amount)}${r.sign_count}${toWan(r.sign_amount)}
未分季—${u.acc_count || 0}${toWan(u.acc_amount)}—${u.sign_count || 0}${toWan(u.sign_amount)}
- + - + - ${rows.map(tr).join("")} + ${quarters.map(tr).join("")} + ${uRow} - - - - - - + + + + + +
季度(${Y}年)季度(${year}年) 计收目标(万元) 计收项目数量 计收项目金额(万元) 计收完成率 新增签单项目数量新增签单项目数量金额(万元)新增签单项目金额(万元)
合计${fmt(tot.target)}${tot.accN}${fmt(tot.accAmt)}${rate(tot.target, tot.accAmt)}${tot.signN}${fmt(tot.signAmt)}${fmt(t.target)}${t.acc_count || 0}${toWan(t.acc_amount)}${rate(t.target, t.acc_amount)}${t.sign_count || 0}${toWan(t.sign_amount)}
-
`; } - /** 年度计收目标(万元):后端存一年一套,没配过时返回《年度任务.xlsx》的默认值 */ - function annualTargetMeta() { - const a = (state.customMeta && state.customMeta.annual_targets) || {}; - return { year: a.year || new Date().getFullYear(), targets: a.targets || {} }; - } - /** 年度目标:默认只读,点「编辑」进入编辑模式(按钮变「保存」),改数字实时重算完成率与合计 */ function bindAnnualTargets(host) { const btn = host.querySelector("#atSave"); @@ -2142,33 +2175,38 @@ btn.addEventListener("click", () => { state.customAnnualEdit = true; renderCustom(); }); return; } - const meta = annualTargetMeta(); - const save = btn; + const annual = ((state.finance || {}).annual) || {}; + const quarters = annual.quarters || []; const inputs = Array.prototype.slice.call(host.querySelectorAll("[data-at]")); - const fmt = (v) => v.toLocaleString("zh-CN", { maximumFractionDigits: 2 }); + const fmt = (v) => Number(v || 0).toLocaleString("zh-CN", { maximumFractionDigits: 2 }); const valOf = (q) => { const el = inputs.filter((i) => i.dataset.at === String(q))[0]; return el ? Number(el.value) || 0 : 0; }; - const rate = (target, acc) => (!target ? "—" : ((acc / target) * 100).toFixed(1) + "%"); + const unschAcc = Number(((annual.unscheduled || {}).acc_amount) || 0); + const accOf = (q) => (q === 0 + ? quarters.reduce((x, r) => x + (Number(r.acc_amount) || 0), 0) + unschAcc + : (quarters.filter((r) => r.q === q)[0] || {}).acc_amount) || 0; const recalc = () => { - const total = [1, 2, 3, 4].reduce((a, q) => a + valOf(q), 0); + const total = [1, 2, 3, 4].reduce((x, q) => x + valOf(q), 0); host.querySelectorAll("[data-ate]").forEach((cell) => { const q = Number(cell.dataset.ate); const target = q === 0 ? total : valOf(q); - cell.textContent = rate(target, Number(cell.dataset.acc) || 0); + cell.textContent = !target ? "—" : ((accOf(q) / 10000 / target) * 100).toFixed(1) + "%"; }); - host.querySelector("[data-att]").textContent = fmt(total); + const cell = host.querySelector("[data-att]"); + if (cell) cell.textContent = fmt(total); }; inputs.forEach((i) => i.addEventListener("input", recalc)); - save.addEventListener("click", async () => { + btn.addEventListener("click", async () => { const targets = {}; inputs.forEach((i) => { targets[i.dataset.at] = Number(i.value) || 0; }); - save.disabled = true; + btn.disabled = true; try { - state.customMeta.annual_targets = await put("/custom/annual-targets", { year: meta.year, targets: targets }); + await put("/custom/annual-targets", { year: annual.year, targets: targets }); + state.finance = null; // 目标变了,重新取一次财务汇总 } catch (e) { - save.disabled = false; + btn.disabled = false; toast("保存失败:" + e.message); return; } @@ -2220,20 +2258,16 @@ String(today.getMonth() + 1).padStart(2, "0") + "-" + String(today.getDate()).padStart(2, "0"); - // 选项直接对齐《定开项目.xlsx》台账字段取值 - const opts = (list, sel) => - list.map((v) => ``).join(""); - const originOpts = opts(CUSTOM_ORIGINS, "华智下单"); - const industryOpts = opts(["安平", "政府", "企业", "教育", "交通", "医疗", "高速", "行业", "其他"], ""); - const statusOpts = opts(["待开发", "进行中", "交付完成", "已验收", "退单"], "待开发"); - const riskOpts = opts(["1.高风险", "2.低风险"], "2.低风险"); + const originOpts = optionHtml(cmOptions("origins"), "华智下单"); + const industryOpts = optionHtml(cmOptions("industries"), ""); + const statusOpts = optionHtml(cmOptions("statuses"), "待开发"); + const riskOpts = optionHtml(cmOptions("risks"), "2.低风险"); const numVal = (sel) => ($(sel).value === "" ? null : Number($(sel).value)); const txtVal = (sel) => $(sel).value.trim() || null; openModal( `

数据库

${esc(health.db)}
-
- 默认使用 SQLite(data/board.db),无需安装任何服务。

- 迁移到 MySQL:
- 1. 安装驱动:pip install pymysql cryptography
- 2. 在 .env 中设置:
- DATABASE_URL=mysql+pymysql://user:pwd@host:3306/unis_board?charset=utf8mb4
- 3. 重启服务,表结构自动创建;再用 - python scripts/import_excel.py --reset 重新灌数即可。

- 数据访问层全部走 SQLAlchemy,无原生 SQL,切换方言不需要改业务代码。 -
+
data/board.db
@@ -3027,7 +3013,7 @@ ${pagedRows(weeks, "periods").map((w) => ` - ${esc(w.full_label)} (原标签:${esc(w.label)}) + ${esc(w.full_label)} ${w.update_count || 0} ${w.custom_update_count || 0} ${rw ? `` : ""} @@ -3050,7 +3036,9 @@ const id = Number(b.dataset.delperiod); const row = b.closest("tr"); const name = row.querySelector("b").textContent; - if (!confirm(`确认删除周期「${name}」?`)) return; + const ok = await confirmDialog({ title: "删除周期", danger: true, okText: "确认删除", + body: `

确认删除周期 ${esc(name)}?该周期下已没有记录。

` }); + if (!ok) return; try { await del("/periods/" + id); toast("已删除周期 " + name); @@ -3115,7 +3103,7 @@ ${peopleEditorHtml("dwOwners", "负责人", p.owners, { add: "负责人" })} ${peopleEditorHtml("dwMembers", "团队成员", p.members, { add: "成员" })}
%
-
+
` : `
项目信息
@@ -3176,7 +3164,6 @@ const gotoIntake = () => { state.intakeType = "general"; state.intakeMode = "direct"; - state.intakePeriodId = state.weekId; intakeProjectId = pid; closeDrawer(); setView("intake"); @@ -3332,7 +3319,6 @@
- ${isNew ? "" : `
改姓名会把名下项目的负责人一并改过来,历史记录不会断。
`} ` @@ -3370,8 +3356,7 @@ danger: true, okText: "确认删除", body: `

确认从花名册删除 ${esc(m.name)}?

-
删除后这个人不再出现在「负责人」下拉里。 - 若他名下还有在管项目,接口会拒绝删除 —— 离职人员请用归档,历史数据完整保留。
`, +
名下还有在管项目时不能删除,离职人员请改用归档。
`, }); if (!ok) return; try { @@ -3432,7 +3417,7 @@ `; const pageRows = pagedRows(d.items, "staff", [state.keyword, state.staffArchived, state.staffGroup]); - const table = ` + const table = `
@@ -3446,15 +3431,9 @@ : `${esc(m.name)}`} ${m.archived ? `已归档` : ""} - - - + + + @@ -3517,55 +3496,66 @@ host.querySelectorAll("[data-outside]").forEach((b) => b.addEventListener("click", () => openStaffDialog({ name: b.dataset.outside })) ); - const roStaff = !canW("staff"); - host.querySelectorAll("tr[data-sid]").forEach((tr) => { - const id = Number(tr.dataset.sid); - tr.querySelectorAll("[data-sf]").forEach((inp) => { - if (roStaff) { inp.disabled = true; return; } - inp.addEventListener("change", async () => { - const f = inp.dataset.sf; - try { - await patch("/staff/" + id, { [f]: inp.value || null }); - toast("已保存"); - await afterWrite(); - } catch (e) { toast("保存失败:" + e.message); } - }); - }); - }); } /* ------------------------------------------------------ 权限管理(RBAC) */ - /** 角色 = 一张「菜单 × 能改/只读」矩阵;用户挂一个角色。下拉改完即存,后端立刻生效。 */ + const RBAC_TABS = [["roles", "角色权限"], ["users", "用户"], ["sessions", "在线会话"], ["logs", "操作日志"]]; + + /** 角色权限矩阵 / 用户挂角色 / 在线会话 / 操作日志,四个 tab 共用一次 meta+roles+users 请求。 */ async function renderRbac() { const host = $("#view-rbac"); host.innerHTML = `
加载中…
`; + const tab = state.rbacTab || "roles"; const [meta, roles, users] = await Promise.all([ api("/rbac/meta"), api("/rbac/roles"), api("/rbac/users"), ]); const rw = canW("rbac"); - const menus = meta.menus; const save = async (fn) => { try { await fn(); } catch (e) { toast("保存失败:" + e.message); } await renderRbac(); }; + let sessions = [], logs = { total: 0, items: [] }; + if (tab === "sessions") sessions = await api("/rbac/sessions"); + if (tab === "logs") logs = await api("/rbac/logs" + rbacLogQuery()); + const tabs = `
` + RBAC_TABS.map(([k, label]) => + ``).join("") + `
`; + const pages = { + roles: rbacRolesPage(meta, roles, rw), + users: rbacUsersPage(users, rw), + sessions: rbacSessionsPage(sessions, rw), + logs: rbacLogsPage(meta, logs, rw), + }; + host.innerHTML = tabs + (pages[tab] || pages.roles); + + host.querySelectorAll("[data-rbactab]").forEach((b) => + b.addEventListener("click", () => { state.rbacTab = b.dataset.rbactab; renderRbac(); }) + ); + bindPager(host, renderRbac); + if (tab === "roles") bindRbacRoles(host, roles, rw, save); + else if (tab === "users") bindRbacUsers(host, users, roles, rw, save); + else if (tab === "sessions") bindRbacSessions(host, rw, save); + else bindRbacLogs(host, save); + } + + /* ---- tab 1:角色 × 菜单 权限矩阵(改一格提交整行,后端立刻生效) ---- */ + function rbacRolesPage(meta, roles, rw) { const levelCell = (role, m) => { const cur = (role.menus || {})[m.key] || ""; return ``; }; - const rolePage = pagedRows(roles, "rbacRole"); - const roleTable = `
姓名归属小组人员归属说明 在管项目定制项目定制合同额${esc(m.group || "—")}${esc(m.affiliation || "—")}${nl2br(m.note) || "—"} ${m.project_count ? `${m.project_count}${m.key_project_count ? ` ${starMark(true, false, "重点项目")}${m.key_project_count}` : ""}` : "—"} ${m.custom_count} ${m.custom_amount ? fen(m.custom_amount) + " 万" : "—"}
+ const table = `
- ${menus.map((m) => ``).join("")} + ${meta.menus.map((m) => ``).join("")} ${rw ? `` : ""} - ${rolePage.map((r) => ` - - ${menus.map((m) => levelCell(r, m)).join("")} + ${pagedRows(roles, "rbacRole").map((r) => ` + + ${meta.menus.map((m) => levelCell(r, m)).join("")} ${rw ? `` : ""} `).join("")}
角色 / 说明${esc(m.label)}${esc(m.label)}用户操作
${esc(r.name)}${r.is_builtin ? ` 内置` : ""}${r.description ? `${esc(r.description)}` : ""}
${esc(r.name)}${r.is_builtin ? ` 内置` : ""}${r.description ? `${esc(r.description)}` : ""}${r.user_count} @@ -3573,52 +3563,18 @@
`; + return listCard({ + title: "角色权限", count: roles.length, rows: roles, table: table, empty: "还没有角色", + pager: pagerBar("rbacRole", roles.length), + tools: rw ? `` : "", + }); + } - const roleOpts = (sel) => roles.map((r) => - ``).join(""); - const userPage = pagedRows(users, "rbacUser"); - const userTable = ` - - - ${rw ? `` : ""} - - ${userPage.map((u) => { - const self = u.id === state.me.id; - return ` - - - - - - ${rw ? `` : ""} - `; - }).join("")} -
姓名登录账号角色可用菜单最近登录操作
${esc(u.name)}${self ? ` 我自己` : ""}${u.active ? "" : ` 已停用`}${esc(u.username)}${u.menus ? Object.keys(u.menus).length : 0}${esc(u.last_login_at ? u.last_login_at.replace("T", " ").slice(0, 16) : "从未登录")} - - ${self ? "" : ` - - `} -
`; - - host.innerHTML = - listCard({ - title: "角色权限", count: roles.length, rows: roles, table: roleTable, empty: "还没有角色", - pager: pagerBar("rbacRole", roles.length), - tools: rw ? `` : "", - }) + - `
` + - listCard({ - title: "用户", count: users.length, rows: users, table: userTable, empty: "还没有用户", - pager: pagerBar("rbacUser", users.length), - tools: rw ? `` : "", - }); - - bindPager(host, renderRbac); - // ---- 权限矩阵:一个角色的整行一起提交 ---- + function bindRbacRoles(host, roles, rw, save) { host.querySelectorAll("[data-rmenu]").forEach((sel) => sel.addEventListener("change", () => { const rid = Number(sel.dataset.rmenu); - const mine = state.me.role_id === rid; + const mine = (state.me.role_ids || []).indexOf(rid) >= 0; const next = {}; sel.closest("tr").querySelectorAll("[data-rmenu]").forEach((x) => { if (x.value) next[x.dataset.menu] = x.value; }); save(() => patch("/rbac/roles/" + rid, { menus: next })).then(() => { @@ -3639,19 +3595,60 @@ if (ok) save(() => del("/rbac/roles/" + r.id)); }) ); + } - // ---- 用户 ---- + /* ---- tab 2:用户(可挂多个角色,权限取并集) ---- */ + function rbacUsersPage(users, rw) { + const table = ` + + + + ${rw ? `` : ""} + + ${pagedRows(users, "rbacUser").map((u) => { + const self = u.id === state.me.id; + return ` + + + + + + + ${rw ? `` : ""} + `; + }).join("")} +
姓名登录账号角色可用菜单在线最近登录操作
${esc(u.name)}${self ? ` 我自己` : ""}${u.active ? "" : ` 已停用`}${esc(u.username)}${(u.role_names || []).length ? (u.role_names || []).map((n) => `${esc(n)}`).join(" ") : `未分配`}${u.menus ? Object.keys(u.menus).length : 0}${u.online || 0}${esc(u.last_login_at ? u.last_login_at.replace("T", " ").slice(0, 16) : "从未登录")} + + + + ${self ? "" : ` + + `} +
`; + return listCard({ + title: "用户", count: users.length, rows: users, table: table, empty: "还没有用户", + pager: pagerBar("rbacUser", users.length), + tools: rw ? `` : "", + }); + } + + function bindRbacUsers(host, users, roles, rw, save) { + const find = (id) => users.find((x) => x.id === Number(id)); const bnu = $("#btnNewUser"); if (bnu) bnu.addEventListener("click", () => openUserDialog(null, roles)); - host.querySelectorAll("[data-urole]").forEach((sel) => - sel.addEventListener("change", () => - save(() => patch("/rbac/users/" + Number(sel.dataset.urole), { role_id: Number(sel.value) })) - ) + host.querySelectorAll("[data-uedit]").forEach((b) => + b.addEventListener("click", () => openUserDialog(find(b.dataset.uedit), roles)) ); host.querySelectorAll("[data-upw]").forEach((b) => - b.addEventListener("click", () => - openPasswordReset(users.find((x) => x.id === Number(b.dataset.upw))) - ) + b.addEventListener("click", () => openPasswordReset(find(b.dataset.upw))) + ); + host.querySelectorAll("[data-urevoke]").forEach((b) => + b.addEventListener("click", async () => { + const u = find(b.dataset.urevoke); + const ok = await confirmDialog({ title: "强制下线", okText: "确认下线", + body: `

下线 ${esc(u.name)}(${esc(u.username)})的所有登录?该账号需要重新登录。

` }); + if (ok) save(() => post("/rbac/users/" + u.id + "/revoke", {})); + }) ); host.querySelectorAll("[data-uactive]").forEach((b) => b.addEventListener("click", () => { @@ -3661,7 +3658,7 @@ ); host.querySelectorAll("[data-udel]").forEach((b) => b.addEventListener("click", async () => { - const u = users.find((x) => x.id === Number(b.dataset.udel)); + const u = find(b.dataset.udel); const ok = await confirmDialog({ title: "删除用户", danger: true, okText: "确认删除", body: `

确认删除用户 ${esc(u.name)}(${esc(u.username)})?该账号会立即下线。

` }); if (ok) save(() => del("/rbac/users/" + u.id)); @@ -3669,7 +3666,105 @@ ); } - /** 角色只影响「能看哪些菜单」,名称说明在这里改,菜单授权在矩阵里勾 */ + /* ---- tab 3:在线会话 ---- */ + function rbacSessionsPage(sessions, rw) { + const table = ` + + + ${rw ? `` : ""} + + ${pagedRows(sessions, "rbacSession").map((x) => ` + + + + + + + ${rw ? `` : ""} + `).join("")} +
用户登录账号登录时间有效期至来源客户端操作
${esc(x.name)}${esc(x.username)}${esc((x.created_at || "").replace("T", " ").slice(0, 16))}${esc((x.expires_at || "").replace("T", " ").slice(0, 16))}${esc(x.ip || "—")}${esc(x.user_agent || "—")}
`; + return listCard({ + title: "在线会话", count: sessions.length, rows: sessions, table: table, + empty: "当前没有有效登录", pager: pagerBar("rbacSession", sessions.length), + }); + } + + function bindRbacSessions(host, rw, save) { + if (!rw) return; + host.querySelectorAll("[data-kick]").forEach((b) => + b.addEventListener("click", () => save(() => del("/rbac/sessions/" + encodeURIComponent(b.dataset.kick)))) + ); + } + + /* ---- tab 4:操作日志 ---- */ + function rbacLogQuery() { + const f = state.rbacLog; + const p = ["days=" + f.days, "limit=200"]; + if (f.username) p.push("username=" + encodeURIComponent(f.username)); + if (f.menu) p.push("menu=" + encodeURIComponent(f.menu)); + if (f.action) p.push("action=" + encodeURIComponent(f.action)); + return "?" + p.join("&"); + } + + function rbacLogsPage(meta, data, rw) { + const f = state.rbacLog; + const sel = (id, label, options, cur) => `${label}`; + const menus = [{ value: "", label: "全部菜单" }].concat(meta.menus.map((m) => ({ value: m.key, label: m.label }))); + const actions = [{ value: "", label: "全部动作" }].concat(meta.actions.map((a) => ({ value: a.value, label: a.label }))); + const days = [1, 7, 30, 90].map((d) => ({ value: d, label: d + " 天内" })); + const items = data.items || []; + const label = (a) => ((meta.actions || []).filter((x) => x.value === a)[0] || {}).label || a || "—"; + const table = ` + + + + ${pagedRows(items, "rbacLog").map((x) => ` + + + + + + + + `).join("")} +
时间操作人动作菜单接口状态说明
${esc((x.created_at || "").replace("T", " ").slice(0, 19))}${esc(x.username || "—")}${esc(label(x.action))}${esc(((meta.menus || []).filter((m) => m.key === x.menu)[0] || {}).label || x.menu || "—")}${esc((x.method || "") + " " + (x.path || ""))}${x.status}${esc(x.detail || "—")}
`; + return listCard({ + title: "操作日志", count: data.total, rows: items, table: table, empty: "这个时间段没有操作记录", + pager: pagerBar("rbacLog", items.length), + tools: `` + + sel("lgMenu", "", menus, f.menu) + sel("lgAction", "", actions, f.action) + sel("lgDays", "", days, f.days) + + (rw ? `` : ""), + }); + } + + function bindRbacLogs(host, save) { + const f = state.rbacLog; + const input = $("#lgUser"); + if (input) { + input.addEventListener("keydown", (e) => { + if (e.key !== "Enter") return; + e.preventDefault(); + f.username = input.value.trim(); renderRbac(); + }); + input.addEventListener("search", () => { f.username = input.value.trim(); renderRbac(); }); + } + const bindSel = (id, key, cast) => { + const el = $("#" + id); + if (el) el.addEventListener("change", () => { f[key] = cast ? cast(el.value) : el.value; renderRbac(); }); + }; + bindSel("lgMenu", "menu"); + bindSel("lgAction", "action"); + bindSel("lgDays", "days", Number); + const cl = $("#lgClear"); + if (cl) cl.addEventListener("click", async () => { + const ok = await confirmDialog({ title: "清空操作日志", danger: true, okText: "确认清空", + body: `

将删除全部操作日志,删除后无法恢复。

` }); + if (ok) save(() => del("/rbac/logs")); + }); + } + function openRoleDialog(role) { const isNew = !role; openModal( @@ -3677,7 +3772,7 @@ ` @@ -3705,19 +3800,23 @@
-
+
${ + roles.map((r) => ``).join("") + }
+ ${!isNew && u.id === state.me.id ? `
不能修改自己的角色
` : ""} ${isNew ? `
` : ""}
-
换角色会强制该账号重新登录,权限立即按新角色生效。
` ); + const roleIds = () => $$("[data-urole]").filter((c) => c.checked).map((c) => Number(c.dataset.urole)); $("#mOk").addEventListener("click", async () => { const name = $("#usName").value.trim(); if (!name) return modalError("请填写姓名"); + if (!roleIds().length) return modalError("至少要挂一个角色"); const btn = $("#mOk"); btn.disabled = true; try { @@ -3725,9 +3824,11 @@ const username = $("#usUser").value.trim(); const password = $("#usPass").value.trim(); if (!username) return void (btn.disabled = false, modalError("请填写登录账号")); - await post("/rbac/users", { name: name, username: username, password: password, role_id: Number($("#usRole").value), active: true }); + await post("/rbac/users", { + name: name, username: username, password: password, active: true, role_ids: roleIds(), + }); } else { - await patch("/rbac/users/" + u.id, { name: name }); + await patch("/rbac/users/" + u.id, { name: name, role_ids: roleIds() }); } closeModal(); toast(isNew ? `已新建用户「${name}」` : "已保存"); @@ -3742,7 +3843,7 @@ ` @@ -3763,11 +3864,17 @@ state.categories = await api("/categories"); } + // 顶栏控件按视图给:周期选择器只对按周/月统计的页面有意义,搜索框对设置/权限/录入没有作用 + const PERIOD_VIEWS = ["board", "projects", "custom", "focus", "intake"]; + const SEARCH_VIEWS = ["board", "projects", "custom", "focus", "staff"]; + function setView(view) { if (!can(view)) view = firstAllowedView(); if (!view) { hostNoPermission(); return; } state.view = view; saveUI(); + document.querySelector(".period-bar").classList.toggle("hidden", PERIOD_VIEWS.indexOf(view) < 0); + $("#globalSearch").classList.toggle("hidden", SEARCH_VIEWS.indexOf(view) < 0); $$("#nav .nav-item").forEach((b) => b.classList.toggle("active", b.dataset.view === view)); $$(".view").forEach((v) => v.classList.add("hidden")); $("#view-" + view).classList.remove("hidden"); diff --git a/web/index.html b/web/index.html index c9aadc3..c92d838 100644 --- a/web/index.html +++ b/web/index.html @@ -92,15 +92,7 @@
DMS管理平台软件开发部
-
-

进展、风险、计收
一张看板看完

- -
-
数据留在本部门服务器,仅限内部使用
+

进展、风险、计收
一张看板看完

@@ -112,7 +104,6 @@ -
忘记密码或需要开通账号,请联系管理员
diff --git a/web/styles.css b/web/styles.css index 642d977..4f9b954 100644 --- a/web/styles.css +++ b/web/styles.css @@ -241,9 +241,13 @@ button:focus-visible, input:focus-visible, select:focus-visible, textarea:focus- /* ---------------- 权限管理 ---------------- */ .rbac-menu-th { font-size: 11px !important; white-space: nowrap; } -.rbac-role { min-width: 168px; } -.rbac-role b { display: block; font-size: 13px; } +.rbac-role { min-width: 138px; } +/* 权限矩阵列多,收紧内边距,避免 1280 宽时操作列盖住「用户」列 */ +.tbl-tight th, .tbl-tight td { padding-left: 8px; padding-right: 8px; } +.rbac-role b { font-size: 13px; } .rbac-role span { font-size: 11px; color: var(--muted); } +.rbac-role .desc { display: block; margin-top: 3px; } +.staff-note { max-width: 190px; font-size: 12px; color: var(--muted); } .tag-mini.builtin { background: #eef2ff; color: #4f46e5; } /* ---------------- main ---------------- */ @@ -734,3 +738,10 @@ table.tbl td.col-ops .btn.sm { padding: 0 7px; } /* 操作列按钮收紧,避 /* 主导航分组标题(业务模块 / 支撑功能) */ .nav-label { font-size: 11px; color: var(--muted); letter-spacing: .6px; padding: 14px 10px 4px; } + +/* 角色多选(用户弹窗) */ +.check-row { display: flex; flex-wrap: wrap; gap: 8px 14px; padding: 4px 0; } +.check { display: inline-flex; align-items: center; gap: 6px; font-size: 13px; color: var(--text); cursor: pointer; } +.check input { width: 15px; height: 15px; accent-color: var(--primary); cursor: pointer; } +.check input:disabled { cursor: not-allowed; } +.check input:disabled + * { color: var(--muted); }