init
parent
0e6f0ae14d
commit
8260c5a2af
|
|
@ -0,0 +1,3 @@
|
|||
# 默认忽略的文件
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="JAVA_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$" />
|
||||
<orderEntry type="jdk" jdkName="Python 3.11" jdkType="Python SDK" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<inspection_tool class="PyUnresolvedReferencesInspection" enabled="true" level="WARNING" enabled_by_default="true">
|
||||
<option name="ignoredIdentifiers">
|
||||
<list>
|
||||
<option value="pythonStudy.day10_inherit.exercise03.GraphicManager.__graphics" />
|
||||
</list>
|
||||
</option>
|
||||
</inspection_tool>
|
||||
</profile>
|
||||
</component>
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Black">
|
||||
<option name="sdkName" value="Python 3.11" />
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11" project-jdk-type="Python SDK" />
|
||||
</project>
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/fourcal-pms.iml" filepath="$PROJECT_DIR$/.idea/fourcal-pms.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
304
README.md
304
README.md
|
|
@ -1,2 +1,304 @@
|
|||
# fourcal-pms
|
||||
# 四算项目管理系统(fourcal-pms)
|
||||
|
||||
老四算系统(Spring Boot 1.5 + JPA + Activiti 6 + FreeMarker)的重构版。
|
||||
|
||||
- **后端**:Python 3.11 · FastAPI · SQLAlchemy 2.0 · MySQL 8
|
||||
- **前端**:Vue 3 · TypeScript · Vite 5 · Tailwind · Pinia(组件体系对齐 sub2api)
|
||||
- **范围**:项目立项(概算)、项目预算、审批流程;配套流程配置、角色权限、
|
||||
**数据权限(支持多套自定义配置)**、菜单权限、系统账号、组织架构
|
||||
- **统一身份**:预留 Hub 同步通道(参照 unisoa 的做法,`[hub]` 开关控制)
|
||||
|
||||
## 快速开始
|
||||
|
||||
```bash
|
||||
# 1) 后端(端口 8383)
|
||||
cd backend
|
||||
pip install -r requirements.txt
|
||||
python3 run.py # 首次启动自动建库建表并种基础数据
|
||||
|
||||
# 2) 前端(端口 5383,/api 代理到 127.0.0.1:8383)
|
||||
cd frontend
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
打开 http://localhost:5383 ,用 `localadmin` / `admin123` 登录。这是本系统唯一的本地账号
|
||||
(首次登录后请立即改口令):由 seed 维护,每次启动都补,`scripts/clean_demo_data.py` 也
|
||||
留着它,清库或重建库都不会把它清没;口令只在本系统校验,从不拿去问统一身份,所以登录页
|
||||
上验证码那一行可以不填。名字刻意不叫 `admin`——那个名字留给统一身份里真叫 admin 的人,
|
||||
否则同步过来只能落成 `admin_hubNNN` 这种别扭的号。想再留第二把本地门,填
|
||||
`[seed] emergency_account` / `emergency_password`;生产上口令留空(seed 随机生成,只在
|
||||
启动日志里打印一次)或用 `PMS_SEED_ADMIN_PASSWORD` 注入,别落进仓库。
|
||||
|
||||
演示账号 `zhangsan` / `lisi` / `wangwu` 同一口令,分别对应业务、项目负责人、财务三种角色,
|
||||
用来验数据权限和审批流转最方便,但只有 `[seed] demo_data = true` 时才种。它们也是本地账号,
|
||||
真要按 README 验数据权限,得把这三个名字填进 `hub.local_only_accounts`,否则会被 Hub 一句
|
||||
"账号或密码错误"挡在门外。
|
||||
|
||||
登录页也收统一身份账号:直接输 Hub 的账号口令(带 Hub 下发的验证码)就能登,
|
||||
口令归谁验由 `hub.login_mode` 定,见「统一身份」一节。
|
||||
|
||||
## 验证
|
||||
|
||||
```bash
|
||||
cd backend && python3 -m pytest tests -q # 294 passed, 13 skipped
|
||||
cd backend && python3 scripts/gen_schema.py --check # 建表脚本是否跟模型走样了
|
||||
cd backend && python3 scripts/clean_demo_data.py # 干跑:看看库里积了多少演示/测试数据
|
||||
cd frontend && npx vue-tsc --noEmit && npm run build
|
||||
```
|
||||
|
||||
## 配置分档
|
||||
|
||||
同一个包要在本机、测试机、生产机上跑,三套库三套密钥。办法是给配置文件分档:
|
||||
|
||||
```
|
||||
config.toml 各环境公共基础值(端口、口令策略、Hub 节奏、上传…;计算口径不在这里)
|
||||
config.dev.toml 开发/测试档差异(测试库地址口令、JWT 密钥、CORS、种子数据)
|
||||
config.prod.toml 生产档差异(生产库账号、监听地址、落盘路径;密钥一律留空)
|
||||
```
|
||||
|
||||
```bash
|
||||
python3 run.py # 默认 dev,读 config.dev.toml
|
||||
PMS_ENV=prod python3 run.py # 生产档
|
||||
PMS_CONFIG=/path/x.toml python3 run.py # 只认这一个文件,分档一概不看
|
||||
```
|
||||
|
||||
- 读两档时做**深合并**:档位文件只写跟公共值不一样的键,没写的沿用。
|
||||
- 优先级:**环境变量 `PMS_*` > `config.<档位>.toml` > `config.toml` > 内置默认值**,
|
||||
例如 `PMS_DB_HOST`、`PMS_DB_PASSWORD`、`PMS_JWT_SECRET`、`PMS_HUB_DIRECTORY_KEY`。
|
||||
- 默认档位是 `dev`,**不会因为漏设 `PMS_ENV` 而误连生产库**。
|
||||
- 生产把 `auto_create_schema` 设为 `false`,建表交 DBA,用 `sql/schema.sql`。
|
||||
- 密钥不进仓库:`config.prod.toml` 里库口令、`jwt_secret`、Hub 两把 key 一律留空,
|
||||
由 `PMS_*` 环境变量注入;`config.dev.toml` 带的是测试库口令,仓库转公共之前记得挪走。
|
||||
|
||||
数据库:开发库 `fourcal_pms_dev`(本系统自己的库)。
|
||||
老库 `unis_fourcal_dev` 作为 `legacy` 数据源**只读**挂载,导数与对账用它,不会写入一个字节。
|
||||
|
||||
## 目录
|
||||
|
||||
```
|
||||
backend/
|
||||
config.toml / config.dev.toml / config.prod.toml
|
||||
run.py 启动入口(uvicorn,reload 仅 dev)
|
||||
app/
|
||||
config.py 分档配置 + 深合并 + 环境变量覆盖
|
||||
db.py / security.py / envelope.py / deps.py / seed.py / main.py
|
||||
dicts.py 数据字典:代码枚举 + 库内维护,一份取值喂到前端
|
||||
models/ org · permission · project · finance · approval · dictionary(40 张表)
|
||||
api/ auth · org · system · dicts · projects · finance · approvals(108 个路由)
|
||||
service/
|
||||
permissions.py 权限码与菜单树构建
|
||||
data_scope.py 数据权限引擎(策略表 → SQL 谓词)
|
||||
biz.py 版本、明细行、计算快照、投影回写
|
||||
org_sync.py / hub_api.py 统一身份同步
|
||||
calc/ money · tax · profit · fund_plan · validate · mapping · engine
|
||||
approval/ candidates · flow · engine
|
||||
tests/ test_calc(口径)+ test_api_flow(主链路)
|
||||
scripts/migrate_legacy.py 老库只读导入
|
||||
scripts/clean_demo_data.py 开发库清回初始状态(默认干跑,删前自动备份,可回放)
|
||||
sql/schema.sql 生产建表脚本
|
||||
|
||||
frontend/src/
|
||||
api/ http.ts(信封拆解 + 令牌静默续期)· index.ts · types.ts
|
||||
stores/ auth(登录态与权限视图)· dicts(数据字典缓存)· ui · toast
|
||||
composables/ useAsync · usePagedQuery · useDict(下拉框取字典)
|
||||
router/ 路由与守卫;菜单由后端下发,前端不抄权限表
|
||||
components/
|
||||
common/ DataTable · Select · DictSelect · BaseDialog · ToastHost · Skeleton …(对齐 sub2api)
|
||||
layout/ AppLayout · AppSidebar · AppHeader · TablePageLayout
|
||||
project/ ProjectShell · SectionRail · LineEditor · SummaryStrip ·
|
||||
ProfitLadder · FundPlanTable · ValidationPanel · ApprovalTimeline
|
||||
approval/ InstanceDetailDrawer
|
||||
views/ 工作台 · 项目 · 审批中心 · 组织 · 系统管理(含「数据字典」维护页)
|
||||
|
||||
docs/
|
||||
前端布局方案.md 使用方视角的布局设计(含双层页签的前后对比)
|
||||
数据权限设计.md 策略模型、求值顺序、字段级权限
|
||||
审批流程设计.md 去 Activiti 后的流程模型与流转语义
|
||||
计算口径.md 价税、利润阶梯、资金计划、校验规则、已知老口径差异
|
||||
```
|
||||
|
||||
## 接口约定
|
||||
|
||||
**响应信封**
|
||||
|
||||
```jsonc
|
||||
// 成功
|
||||
{ "ok": true, "data": { ... } }
|
||||
// 失败
|
||||
{ "ok": false,
|
||||
"error": { "code": "validation_failed", "message": "送审前还有 2 项校验没有通过",
|
||||
"detail": { "issues": [ ... ] }, "traceId": "ac366c13a9744451" } }
|
||||
```
|
||||
|
||||
- 金额**全程字符串**,前端不 `Number().toFixed()` 大额数字(超过 2^53 会静默丢精度)。
|
||||
- 比率是**百分数本身**(13 表示 13%);可能无定义的比率返回 `{value, defined, reason}`。
|
||||
- `wrapper` 键用驼峰(`contractAmount`、`pageNo`);明细行字段用下划线(`include_amount`),
|
||||
与数据库列一一对应,导数时不用换算。
|
||||
- 每个响应带 `X-Trace-Id`,前端 Toast 会显示 `traceId`,报错能直接贴给运维查日志。
|
||||
|
||||
**主要分组**
|
||||
|
||||
| 前缀 | 内容 |
|
||||
| --- | --- |
|
||||
| `/api/health` | 健康检查(含数据库连通、当前档位与口径版本) |
|
||||
| `/api/v1/bootstrap` | 一次拿全:环境、数据字典、菜单树、权限码、字段脱敏配置 |
|
||||
| `/api/v1/auth` | 登录、刷新、改口令、登出 |
|
||||
| `/api/v1/org` | 部门树、账号、岗位、`accounts/options`(人员选择器)、`accounts/{id}/roles`(给人员配角色)、`accounts/roles/batch`(批量分配:按勾选或按当前筛选圈人,追加/移除/覆盖,一次上限 500 人)、Hub 同步 |
|
||||
| `/api/v1/projects` | 项目 CRUD、软删除与回收站恢复、彻底删除、阶段流转、成员与可见角色 |
|
||||
| `/api/v1/finance/{module}` | 概算/预算:版本、明细行、试算、快照、校验、送审 |
|
||||
| `/api/v1/approvals` | 待办/已办/我发起/监控、办理、撤回、退回、转办、加签、流程配置 |
|
||||
| `/api/v1/system` | 角色、数据权限策略与试算解释、权限树、业务参数、计算口径 |
|
||||
| `/api/v1/system/operation-logs` | 审计查询:写操作日志(含明细与筛选项)、`login-logs` 登录日志 |
|
||||
| `/api/v1/dicts` | 数据字典:前端按下拉框编码取值(只要求登录) |
|
||||
| `/api/v1/system/dicts` | 数据字典维护:字典与取值的增删改、启停、排序、恢复默认 |
|
||||
|
||||
**明细行的三种写法**
|
||||
|
||||
```
|
||||
POST /finance/budget/projects/{id}/lines/{lineKey} body { "data": {...} } 单行新增/更新
|
||||
PUT /finance/budget/projects/{id}/lines/{lineKey} body { "rows": [...] } 整段替换(前端批量保存用这个)
|
||||
DELETE /finance/budget/projects/{id}/lines/{lineKey}/{lineId}
|
||||
```
|
||||
|
||||
`PUT` 是**整段替换**语义:一次提交这一段的全部行。每次落库都触发一次重算,
|
||||
重算结果写入 `calc_snapshot`,并把关键指标投影回 `project` 主表。
|
||||
|
||||
## 设计上的几个决定
|
||||
|
||||
1. **`biz_revision` 取代老系统的 `_temp` 影子表。** 概算/预算的每一版都是一行 `biz_revision`,
|
||||
所有明细行带 `revision_id`。送审冻结的是版本号,不是复制一份表。
|
||||
2. **计算快照是唯一事实。** `calc_snapshot.payload_json` 存完整结果,
|
||||
`project` 表上的利润列只是投影,由 `biz.apply_projection` 写入。对账看快照,不看主表。
|
||||
3. **审批去 Activiti。** 流程定义/节点/实例/待办/流水五张表,与业务同库同事务。
|
||||
"这单现在谁在审"变成一次查询。
|
||||
4. **数据权限是策略表,不是角色上的一个字段。** 5 种主体 × 10 种范围 × allow/deny × 可嵌套
|
||||
条件树,能表达"同一个人不同列表不同范围"。详见《数据权限设计》。
|
||||
5. **口径可配置并带版本号。** 老系统写死的 2.8% 管理费率、10% 差旅限额、价内税公式、
|
||||
零分母行为都是 `system_config` 里 `calc.` 开头的业务参数,在「系统 → 计算口径」页面上改、
|
||||
保存即生效,双跑对账时切回老口径复现,`version` 随快照留痕。配置文件里一条计算规则都不留。
|
||||
6. **下拉框取值统一进数据字典。** 以前一份枚举写三处:model 的 ``LABELS``、接口里现拼
|
||||
的 ``[{value,label}]``、前端视图里的常量数组——项目类型就因此对不上(接口叫"工程集成类",
|
||||
列表页写"系统集成"),采购明细的产品归属还给过内核根本不认的编码,选了不报错、钱也不投影。
|
||||
现在 ``dict_type`` / ``dict_item`` 是运行期唯一来源:随 ``/bootstrap`` 下发,页面用
|
||||
``DictSelect`` 按编码取值;「系统 → 数据字典」能改名、排序、停用、加自定义字典,保存即生效。
|
||||
代码那份 LABELS 退成兜底与护栏——内置取值不许改也不许删(业务代码按它判分支),
|
||||
只在界面上提供"恢复默认"。**字典管候选项和展示名,不管校验**:能不能送审、走哪条分支
|
||||
仍然看代码常量,否则改个名字就能把状态机改出洞。
|
||||
7. **前端砍掉了双层页签。** 明细表从"页签"降级成"目录",计算结果常驻右手边。
|
||||
详见《前端布局方案》。
|
||||
|
||||
## 数据迁移
|
||||
|
||||
老四算(`unis_fourcal_dev`,93 张表 / 828 个项目)用 `backend/scripts/migrate_legacy.py` 导进新库。
|
||||
这个脚本有三条不可商量的前提:**老库只读**(连接一开就 `START TRANSACTION READ ONLY`,脚本里只发
|
||||
SELECT)、**默认干跑**(不加 `--apply` 一律回滚)、**不保留老库主键**(新库自己发号,老 id→新 id
|
||||
走内存映射;直接搬会和 seed 出来的 admin、演示项目撞号,撞了是静默覆盖,比报错更糟)。
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
python3 scripts/migrate_legacy.py # 干跑,先看报告
|
||||
python3 scripts/migrate_legacy.py --apply --steps org,user,role # 只导人头,先验证头寸
|
||||
python3 scripts/migrate_legacy.py --apply --limit-projects 50 # 前 50 个项目试水
|
||||
python3 scripts/migrate_legacy.py --apply # 全量
|
||||
```
|
||||
|
||||
步骤顺序固定为 `org → role → positions → user → flow → project → estimate → budget → visible`,
|
||||
`--steps` 只挑要做哪几步,不会打乱依赖顺序。干跑一次约 3~5 分钟(按项目逐张拉明细,远库往返占大头)。
|
||||
|
||||
老库有几处口径和新系统不一样,脚本**显式换算并在报告里计数**,不静默改数:
|
||||
|
||||
| 项目 | 老库 | 新系统 |
|
||||
| --- | --- | --- |
|
||||
| 税率 `tax_rate` | 小数 `0.13` | 百分数 `13`(只放大 `(0,1]`) |
|
||||
| 利润率 `*_margin` | **本来就是百分数** `12.15` | 原样搬运,**不乘 100** |
|
||||
| 采购类别 `category` | `procurement_type` 的 id 字符串 `"8"` | 中文名 + 产品归属编码 `huazhi` |
|
||||
| 日期 `pay_time` 等 | `datetime` / 空 | DATE 列,空给 NULL(DATE 写 `''` 报 1292) |
|
||||
| 布尔 `is_deleted` | `bit(1)`,回来是 `b'\x00'` | `bool(b'\x00')` 是 True,按非零字节判 |
|
||||
|
||||
这两条口径都是实测钉住的,不是猜的:利润率 `1578.60 / 12990 = 12.15` 与 `margin=12.15` 对得上,
|
||||
而库里确实有 `0.03` 这种利润率——那是 `0.03%`,早期版本一个 `-1 < v < 1` 的启发式把它放大成了 `3%`。
|
||||
对应的回归测试在 `tests/test_migrate_legacy.py`。
|
||||
|
||||
**在途审批和审批历史都不迁。** 老流程实例在 Activiti 里,硬迁过来只能造出一堆来路不明的待办;
|
||||
切流前把在途单子清干净,新送审一律走新流程。已经走完的历史审批想看的话,源数据在老库
|
||||
`act_hi_procinst`(2,040 条)/ `act_hi_taskinst`(9,341 条)/ `act_hi_comment`(17,419 条),
|
||||
需要单独做成 `approval_record` 流水跟新流程解耦——这得先定历史流水在新界面里怎么摆,
|
||||
脚本里没有开关,别去猜 `--with-history`。
|
||||
|
||||
报告里 `需要你确认的` 那几条是真要人跟的:老流程候选人只有角色能自动对上(`candidate_users` 是老库
|
||||
用户 id,要按新账号重新指定);老库没有垫资年利率字段,按 `--advance-rate` 统一赋值后要逐个核对;
|
||||
约一成采购明细的类别落在四个产品归属之外("外购产品""外购服务"这类),`product_category` 只能留空。
|
||||
导入完成后到项目里点一次「重新试算」,让计算快照和投影按新口径重算。
|
||||
|
||||
字符串超过新库列宽时脚本会**截断并计数**(报告里 `截断:表.列` 那几行),列宽从模型元数据现读。
|
||||
触发了就说明列宽该跟老库对齐——比如 `pay_way` 老库存的是合同付款条款、实测 136 字,新列就从 64
|
||||
放到了 255。放着不管等于默认丢数据。
|
||||
|
||||
生产建表脚本 `backend/sql/schema.sql` 由模型编译,别手改:
|
||||
|
||||
```bash
|
||||
cd backend && python3 scripts/gen_schema.py # 改完模型重新生成
|
||||
cd backend && python3 scripts/gen_schema.py --check # 只比对,可挂 CI
|
||||
```
|
||||
|
||||
## 统一身份(账号组织同步 + 免登)
|
||||
|
||||
按 dsh-hub 对接契约实现,口径与 unisoa 一致:**hub 是人员与组织的唯一权威源,本系统只读消费,
|
||||
不回写、不另建一套人**。免登只走一次性票据;登录页那个口令框默认也归 Hub 判,
|
||||
本系统不自建第二套口令。
|
||||
|
||||
```toml
|
||||
[hub]
|
||||
enabled = true
|
||||
base_url = "https://hub.oa.unissense.tech"
|
||||
directory_key = "" # X-Directory-Key:拉组织与人员
|
||||
app_code = "" # 免登应用编码,用于校验票据受众
|
||||
integration_key = "" # X-Integration-Key:校验票据
|
||||
login_mode = "hub" # 口令校验口径:hub / hybrid / local / sso
|
||||
```
|
||||
|
||||
- **两把密钥互不通用**:目录密钥换不了身份,应用密钥读不到目录。同步页把它们分开显示,
|
||||
因为配错最常见的表现是"同步下来是空的",合并成一个"凭据已配置"会把排查方向带偏。
|
||||
- 接口路径写死在 `HubConfig` 里(目录 `/api/v1/auth/directory`、增量 `…/changes`、验票
|
||||
`/api/v1/auth/tickets/verify`,加上登录页要问的 `/auth/captcha`、`/auth/login` 和补主键用的
|
||||
`/api/v1/auth/me`),不做成可配项:路径是契约的一部分,配错一个斜杠就会
|
||||
静默同步到空目录,然后按"hub 里没人了"把本地账号全停用。
|
||||
- **两条节奏**:增量按 `changes_interval_seconds`(建议 45 秒)蹭游标,全量按
|
||||
`sync_interval_minutes`(默认每日)校对。全量必须留着,因为人员资料微调不产生变更事件。
|
||||
游标只在整批成功后推进;游标落后于对端最早流水、或收到只带 id 的组织事件时,自动退回全量。
|
||||
- `login_mode` 决定登录页那个口令框收谁的账号、口令归谁验:`hub`(默认,只问统一身份,
|
||||
连不上当场回"统一身份暂不可用")/ `hybrid`(连不上才退回本地口令)/ `local`(只用本地口令)/
|
||||
`sso`(口令登录整个关掉,页面只留"前往统一门户")。逐档差别见文档 §1.1。
|
||||
- **Hub 账号在这里没有本地口令**。`_verify` 里不存在"Hub 连不上就当本地账号放行"的兜底——那会让
|
||||
停用与离职下线在故障期间集体失效;Hub 说"密码不对"也不会再拿库里的旧哈希兜第二层,被拒
|
||||
同样不去累加本地锁定计数。逃生门是 `break_glass_login`,只放行 `source=local` 的本地账号:
|
||||
内置超管(默认就叫 `localadmin`)永远在列,`local_only_accounts` 点名的账号也算;把它设成
|
||||
`false` 就是彻底只认免登。
|
||||
- 免登的身份映射只认 `sub`(`accounts.hub_user_id`),不按姓名或邮箱合并账号。只有口令那条路
|
||||
允许按账号名认领一条同名本地账号——本人当场报了账号名、又过了 Hub 的口令校验;认领只补空的
|
||||
主键,已经绑着别人主键就回 `account_identity_conflict`,不建影子账号放人进来。
|
||||
- **免登的落地地址(Hub 的 `launch_url`)填后端回调** `/api/v1/auth/sso/callback`:票据只在
|
||||
"浏览器 → 本系统 → Hub" 这一趟里出现,前端脚本、浏览历史与 Referer 都拿不到它。后端验完票
|
||||
只 302 回 `/sso`,地址上带的是一条 60 秒即失效、只能用一次、还绑着 HttpOnly Cookie 的短码。
|
||||
要抄的完整地址在 `/org/hub-sync` 页与 `GET /api/v1/auth/hub/status` 的 `sso.callbackUrl`。
|
||||
|
||||
联调与排障看 `/org/hub-sync`:两条密钥状态、门户落地地址、两条节奏、当前游标、最近一次同步
|
||||
的四态与错误原文。落法、一次性短码、`state` 两层校验,以及**与 unisoa 哪几处有意不同**,
|
||||
见 [docs/统一身份登录.md](/Users/kangwenjing/Downloads/project/fourcal-pms/docs/统一身份登录.md)。
|
||||
|
||||
## 部署
|
||||
|
||||
```bash
|
||||
# 生产
|
||||
cd backend # 先填 config.prod.toml:库账号、监听地址、落盘路径
|
||||
chmod 600 config.prod.toml # 里面密钥一律留空,改用 PMS_* 环境变量注入
|
||||
export PMS_ENV=prod
|
||||
python3 run.py # 或用 gunicorn/uvicorn 多 worker 起
|
||||
|
||||
# 前端
|
||||
cd frontend && npm run build # 产物在 dist/,同域反向代理到 /api
|
||||
```
|
||||
|
||||
Nginx 关键两条:`/api` 反代到后端 8383;`dist` 静态资源交给前端路由做 `try_files` 回落 `index.html`。
|
||||
生产同域部署时 CORS 可以留空。
|
||||
|
|
|
|||
|
|
@ -0,0 +1,9 @@
|
|||
__pycache__/
|
||||
*.py[cod]
|
||||
.pytest_cache/
|
||||
.venv/
|
||||
venv/
|
||||
|
||||
# 上传的附件、运行日志,以及 clean_demo_data.py 写出的库备份(内含整表数据,别进仓库)
|
||||
storage/
|
||||
logs/
|
||||
|
|
@ -0,0 +1 @@
|
|||
"""HTTP 接口。"""
|
||||
|
|
@ -0,0 +1,528 @@
|
|||
"""审批:待办/已办/我发起的、审批动作、流程配置。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from .. import dicts as dict_store
|
||||
from ..deps import DbSession, PrincipalOf, assert_project_visible
|
||||
from ..envelope import conflict, forbidden, not_found, ok, page
|
||||
from ..models import (
|
||||
Action,
|
||||
ApprovalDelegate,
|
||||
ApprovalFlow,
|
||||
ApprovalInstance,
|
||||
ApprovalNode,
|
||||
ApprovalRecord,
|
||||
ApprovalTask,
|
||||
FlowStatus,
|
||||
InstanceStatus,
|
||||
NodeType,
|
||||
Revision,
|
||||
RevisionStatus,
|
||||
SignType,
|
||||
TaskStatus,
|
||||
)
|
||||
from ..service.approval import engine as approval_engine
|
||||
from ..service.approval import flow as flow_service
|
||||
|
||||
router = APIRouter(prefix="/approvals", tags=["approvals"])
|
||||
|
||||
#: 流程设计器里可以手工摆的节点类型(发起节点由系统生成,不给选)
|
||||
_CONFIGURABLE_NODE_TYPES = {NodeType.APPROVE, NodeType.CC, NodeType.CONDITION, NodeType.END}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 工作台
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/todo")
|
||||
def todo(db: DbSession, current: PrincipalOf, module: str = "",
|
||||
pageNo: int = Query(1, ge=1), pageSize: int = Query(20, ge=1, le=200)) -> dict[str, Any]:
|
||||
statement = (
|
||||
select(ApprovalTask, ApprovalInstance)
|
||||
.join(ApprovalInstance, ApprovalInstance.id == ApprovalTask.instance_id)
|
||||
.where(ApprovalTask.assignee_id == current.account.id,
|
||||
ApprovalTask.status == TaskStatus.PENDING,
|
||||
ApprovalInstance.status == InstanceStatus.REVIEWING)
|
||||
)
|
||||
if module:
|
||||
statement = statement.where(ApprovalInstance.business_module == module)
|
||||
total = db.execute(select(func.count()).select_from(statement.subquery())).scalar() or 0
|
||||
rows = db.execute(statement.order_by(ApprovalTask.id.desc())
|
||||
.offset((pageNo - 1) * pageSize).limit(pageSize)).all()
|
||||
return page([
|
||||
{
|
||||
"taskId": task.id, "instanceId": instance.id,
|
||||
"businessModule": instance.business_module,
|
||||
"businessModuleLabel": dict_store.label(db, "businessModule", instance.business_module),
|
||||
"projectId": instance.project_id, "projectName": instance.project_name,
|
||||
"revisionId": instance.revision_id, "snapshotId": instance.snapshot_id,
|
||||
"nodeName": task.node_name, "signType": task.sign_type,
|
||||
"signTypeLabel": dict_store.label(db, "signType", task.sign_type),
|
||||
"submitterName": instance.submitter_name,
|
||||
"submittedAt": instance.submitted_at.isoformat(sep=" ", timespec="seconds"),
|
||||
"dueAt": task.due_at.isoformat(sep=" ", timespec="seconds") if task.due_at else "",
|
||||
}
|
||||
for task, instance in rows
|
||||
], total, pageNo, pageSize)
|
||||
|
||||
|
||||
@router.get("/done")
|
||||
def done(db: DbSession, current: PrincipalOf, module: str = "",
|
||||
pageNo: int = Query(1, ge=1), pageSize: int = Query(20, ge=1, le=200)) -> dict[str, Any]:
|
||||
statement = (
|
||||
select(ApprovalTask, ApprovalInstance)
|
||||
.join(ApprovalInstance, ApprovalInstance.id == ApprovalTask.instance_id)
|
||||
.where(ApprovalTask.assignee_id == current.account.id,
|
||||
ApprovalTask.status.in_([TaskStatus.DONE, TaskStatus.TRANSFERRED]))
|
||||
)
|
||||
if module:
|
||||
statement = statement.where(ApprovalInstance.business_module == module)
|
||||
total = db.execute(select(func.count()).select_from(statement.subquery())).scalar() or 0
|
||||
rows = db.execute(statement.order_by(ApprovalTask.acted_at.desc())
|
||||
.offset((pageNo - 1) * pageSize).limit(pageSize)).all()
|
||||
return page([
|
||||
{
|
||||
"taskId": task.id, "instanceId": instance.id,
|
||||
"businessModuleLabel": dict_store.label(db, "businessModule", instance.business_module),
|
||||
"projectId": instance.project_id, "projectName": instance.project_name,
|
||||
"snapshotId": instance.snapshot_id,
|
||||
"nodeName": task.node_name, "action": task.action,
|
||||
"actionLabel": dict_store.label(db, "approvalAction", task.action, task.action),
|
||||
"comment": task.comment,
|
||||
"instanceStatus": instance.status,
|
||||
"instanceStatusLabel": dict_store.label(db, "instanceStatus", instance.status),
|
||||
"actedAt": task.acted_at.isoformat(sep=" ", timespec="seconds") if task.acted_at else "",
|
||||
}
|
||||
for task, instance in rows
|
||||
], total, pageNo, pageSize)
|
||||
|
||||
|
||||
@router.get("/created")
|
||||
def created(db: DbSession, current: PrincipalOf, module: str = "", status: str = "",
|
||||
pageNo: int = Query(1, ge=1), pageSize: int = Query(20, ge=1, le=200)) -> dict[str, Any]:
|
||||
statement = select(ApprovalInstance).where(ApprovalInstance.submitter_id == current.account.id)
|
||||
if module:
|
||||
statement = statement.where(ApprovalInstance.business_module == module)
|
||||
if status:
|
||||
statement = statement.where(ApprovalInstance.status == status)
|
||||
total = db.execute(select(func.count()).select_from(statement.subquery())).scalar() or 0
|
||||
rows = db.execute(statement.order_by(ApprovalInstance.id.desc())
|
||||
.offset((pageNo - 1) * pageSize).limit(pageSize)).scalars().all()
|
||||
return page([_instance_view(db, row) for row in rows], total, pageNo, pageSize)
|
||||
|
||||
|
||||
@router.get("/monitor")
|
||||
def monitor(db: DbSession, current: PrincipalOf, module: str = "", status: str = "",
|
||||
keyword: str = "", pageNo: int = Query(1, ge=1),
|
||||
pageSize: int = Query(20, ge=1, le=200)) -> dict[str, Any]:
|
||||
if not current.permission.can("approval:monitor:view"):
|
||||
raise forbidden("缺少权限:approval:monitor:view")
|
||||
statement = select(ApprovalInstance)
|
||||
if module:
|
||||
statement = statement.where(ApprovalInstance.business_module == module)
|
||||
if status:
|
||||
statement = statement.where(ApprovalInstance.status == status)
|
||||
if keyword:
|
||||
statement = statement.where(ApprovalInstance.project_name.like(f"%{keyword}%"))
|
||||
total = db.execute(select(func.count()).select_from(statement.subquery())).scalar() or 0
|
||||
rows = db.execute(statement.order_by(ApprovalInstance.id.desc())
|
||||
.offset((pageNo - 1) * pageSize).limit(pageSize)).scalars().all()
|
||||
return page([_instance_view(db, row) for row in rows], total, pageNo, pageSize)
|
||||
|
||||
|
||||
def _instance_view(db: Session, row: ApprovalInstance) -> dict[str, Any]:
|
||||
return {
|
||||
"id": row.id, "flowName": row.flow_name,
|
||||
"businessModule": row.business_module,
|
||||
"businessModuleLabel": dict_store.label(db, "businessModule", row.business_module),
|
||||
"projectId": row.project_id, "projectName": row.project_name,
|
||||
"revisionId": row.revision_id, "snapshotId": row.snapshot_id,
|
||||
"status": row.status, "statusLabel": dict_store.label(db, "instanceStatus", row.status),
|
||||
"currentNode": row.current_node_name,
|
||||
"submitterName": row.submitter_name,
|
||||
"submittedAt": row.submitted_at.isoformat(sep=" ", timespec="seconds"),
|
||||
"finishedAt": row.finished_at.isoformat(sep=" ", timespec="seconds") if row.finished_at else "",
|
||||
}
|
||||
|
||||
|
||||
@router.get("/instances/{instance_id}")
|
||||
def instance_detail(instance_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
instance = db.get(ApprovalInstance, instance_id)
|
||||
if instance is None:
|
||||
raise not_found("审批实例不存在")
|
||||
assert_project_visible(db, current, instance.project_id, module=instance.business_module)
|
||||
|
||||
tasks = db.execute(select(ApprovalTask).where(ApprovalTask.instance_id == instance_id)
|
||||
.order_by(ApprovalTask.id)).scalars().all()
|
||||
records = db.execute(select(ApprovalRecord).where(ApprovalRecord.instance_id == instance_id)
|
||||
.order_by(ApprovalRecord.id)).scalars().all()
|
||||
revision = db.get(Revision, instance.revision_id) if instance.revision_id else None
|
||||
my_tasks = [task.id for task in tasks
|
||||
if task.assignee_id == current.account.id and task.status == TaskStatus.PENDING]
|
||||
|
||||
return ok({
|
||||
"instance": _instance_view(db, instance),
|
||||
"canWithdraw": (instance.status == InstanceStatus.REVIEWING
|
||||
and instance.submitter_id == current.account.id),
|
||||
"myTaskIds": my_tasks,
|
||||
"revision": {
|
||||
"id": revision.id, "version": revision.version, "status": revision.status,
|
||||
"statusLabel": dict_store.label(db, "revisionStatus", revision.status),
|
||||
} if revision else None,
|
||||
"tasks": [{
|
||||
"id": task.id, "nodeName": task.node_name, "assigneeName": task.assignee_name,
|
||||
"status": task.status, "action": task.action,
|
||||
"statusLabel": dict_store.label(db, "taskStatus", task.status),
|
||||
"actionLabel": dict_store.label(db, "approvalAction", task.action), "comment": task.comment,
|
||||
"signType": task.sign_type,
|
||||
"signTypeLabel": dict_store.label(db, "signType", task.sign_type),
|
||||
"orderInNode": task.order_in_node,
|
||||
"dueAt": task.due_at.isoformat(sep=" ", timespec="seconds") if task.due_at else "",
|
||||
"actedAt": task.acted_at.isoformat(sep=" ", timespec="seconds") if task.acted_at else "",
|
||||
} for task in tasks],
|
||||
"records": [{
|
||||
"id": row.id, "nodeName": row.node_name, "action": row.action,
|
||||
"actionLabel": row.action_label, "operatorName": row.operator_name,
|
||||
"targetNames": row.target_names, "comment": row.comment,
|
||||
"rollbackToNode": row.rollback_to_node,
|
||||
"createdAt": row.created_at.isoformat(sep=" ", timespec="seconds"),
|
||||
} for row in records],
|
||||
})
|
||||
|
||||
|
||||
class ActBody(BaseModel):
|
||||
action: str = Field(min_length=1, max_length=24)
|
||||
comment: str = ""
|
||||
targetIds: list[int] = Field(default_factory=list)
|
||||
rollbackTo: str = ""
|
||||
|
||||
|
||||
@router.post("/tasks/{task_id}/act")
|
||||
def act(task_id: int, body: ActBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
task = db.get(ApprovalTask, task_id)
|
||||
if task is None:
|
||||
raise not_found("待办不存在")
|
||||
instance = approval_engine.act(
|
||||
db, task=task, actor=current.account, action=body.action,
|
||||
comment=body.comment, target_ids=body.targetIds, rollback_to=body.rollbackTo,
|
||||
)
|
||||
db.commit()
|
||||
return ok({"instance": _instance_view(db, instance)})
|
||||
|
||||
|
||||
class WithdrawBody(BaseModel):
|
||||
comment: str = ""
|
||||
|
||||
|
||||
@router.post("/instances/{instance_id}/withdraw")
|
||||
def withdraw(instance_id: int, body: WithdrawBody, *, db: DbSession,
|
||||
current: PrincipalOf) -> dict[str, Any]:
|
||||
instance = db.get(ApprovalInstance, instance_id)
|
||||
if instance is None:
|
||||
raise not_found("审批实例不存在")
|
||||
approval_engine.withdraw(db, instance=instance, actor=current.account, comment=body.comment)
|
||||
db.commit()
|
||||
return ok({"instance": _instance_view(db, instance)})
|
||||
|
||||
|
||||
@router.get("/instances/{instance_id}/rollback-targets")
|
||||
def rollback_targets(instance_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
"""退回到哪些节点可选,由后端算,前端不猜。"""
|
||||
instance = db.get(ApprovalInstance, instance_id)
|
||||
if instance is None:
|
||||
raise not_found("审批实例不存在")
|
||||
completed = set(json.loads(instance.runtime_json or "{}").get("completed", []))
|
||||
nodes = flow_service.ordered_nodes(db.get(ApprovalFlow, instance.flow_id))
|
||||
current_node = next((node for node in nodes if node.node_key == instance.current_node_key), None)
|
||||
allowed = set(json.loads(current_node.rollback_keys_json or "[]")) if current_node else set()
|
||||
out = [{"value": "initiator", "label": "退回发起人修改"}]
|
||||
for node in nodes:
|
||||
if node.node_type != NodeType.APPROVE or node.node_key not in completed:
|
||||
continue
|
||||
if allowed and node.node_key not in allowed:
|
||||
continue
|
||||
out.append({"value": node.node_key, "label": f"退回到「{node.name}」"})
|
||||
return ok(out)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 流程配置
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class NodeBody(BaseModel):
|
||||
nodeKey: str = Field(min_length=1, max_length=64)
|
||||
name: str = Field(min_length=1, max_length=128)
|
||||
nodeType: str = NodeType.APPROVE
|
||||
orderNumber: int = 100
|
||||
signType: str = SignType.ANY
|
||||
candidates: list[dict[str, Any]] = Field(default_factory=list)
|
||||
emptyStrategy: str = "admin"
|
||||
condition: str = ""
|
||||
nextNodeKey: str = ""
|
||||
rejectTo: str = "end"
|
||||
rollbackKeys: list[str] = Field(default_factory=list)
|
||||
commentRequired: bool = False
|
||||
rejectCommentRequired: bool = True
|
||||
timeoutHours: int = 0
|
||||
timeoutAction: str = "none"
|
||||
enabled: bool = True
|
||||
remark: str = ""
|
||||
|
||||
|
||||
class FlowBody(BaseModel):
|
||||
key: str = Field(min_length=1, max_length=64)
|
||||
name: str = Field(min_length=1, max_length=128)
|
||||
businessModule: str
|
||||
status: str = FlowStatus.DRAFT
|
||||
matchExpressions: list[str] = Field(default_factory=list)
|
||||
priority: int = 100
|
||||
allowSelfSelect: bool = False
|
||||
autoSkipDuplicate: bool = True
|
||||
remark: str = ""
|
||||
nodes: list[NodeBody] = Field(default_factory=list)
|
||||
|
||||
|
||||
@router.get("/flows")
|
||||
def list_flows(db: DbSession, current: PrincipalOf, module: str = "") -> dict[str, Any]:
|
||||
if not current.permission.can_any(("approval:flow:view", "approval:flow:edit")):
|
||||
raise forbidden("缺少权限:approval:flow:view")
|
||||
statement = select(ApprovalFlow).where(ApprovalFlow.is_deleted.is_(False))
|
||||
if module:
|
||||
statement = statement.where(ApprovalFlow.business_module == module)
|
||||
rows = db.execute(statement.order_by(ApprovalFlow.business_module, ApprovalFlow.priority,
|
||||
ApprovalFlow.id.desc())).scalars().all()
|
||||
return ok([{
|
||||
"id": row.id, "key": row.key, "name": row.name,
|
||||
"businessModule": row.business_module,
|
||||
"businessModuleLabel": dict_store.label(db, "businessModule", row.business_module),
|
||||
"version": row.version, "status": row.status, "priority": row.priority,
|
||||
"matchExpressions": _match_expressions(row.match_json),
|
||||
"allowSelfSelect": row.allow_self_select, "autoSkipDuplicate": row.auto_skip_duplicate,
|
||||
"remark": row.remark, "nodeCount": len(flow_service.ordered_nodes(row)),
|
||||
} for row in rows])
|
||||
|
||||
|
||||
def _match_expressions(raw: str) -> list[str]:
|
||||
if not (raw or "").strip():
|
||||
return []
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
return [raw]
|
||||
if isinstance(data, dict):
|
||||
return [str(item) for item in (data.get("expressions") or [])]
|
||||
return [str(item) for item in data] if isinstance(data, list) else []
|
||||
|
||||
|
||||
@router.get("/flows/options")
|
||||
def flow_options(db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
if not current.permission.can_any(("approval:flow:view", "approval:flow:edit")):
|
||||
raise forbidden("缺少权限:approval:flow:view")
|
||||
from ..models import PermRole, Position
|
||||
|
||||
return ok({
|
||||
# 这几组下拉值一律现取字典。前端已经改成直接读字典(DictSelect),这里保留同样的
|
||||
# 键只是给还在用这条接口的老调用方兜底——取值和名字都来自同一份,不会对不上。
|
||||
"modules": dict_store.options(db, "businessModule"),
|
||||
"nodeTypes": [row for row in dict_store.options(db, "nodeType")
|
||||
if row["value"] in _CONFIGURABLE_NODE_TYPES],
|
||||
"signTypes": dict_store.options(db, "signType"),
|
||||
"candidateTypes": dict_store.options(db, "candidateType"),
|
||||
"emptyStrategies": dict_store.options(db, "emptyStrategy"),
|
||||
"timeoutActions": dict_store.options(db, "timeoutAction"),
|
||||
"roles": [{"id": row.id, "name": row.name} for row in
|
||||
db.execute(select(PermRole).where(PermRole.is_deleted.is_(False))).scalars().all()],
|
||||
"positions": [{"id": row.id, "name": row.name} for row in
|
||||
db.execute(select(Position).where(Position.is_deleted.is_(False))).scalars().all()],
|
||||
"conditionFields": ["contract_amount", "contribution_profit_rate", "project_type",
|
||||
"underwritten_mode", "income_total", "org_unit_id", "submitter_id"],
|
||||
})
|
||||
|
||||
|
||||
@router.get("/flows/{flow_id}")
|
||||
def get_flow(flow_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
if not current.permission.can_any(("approval:flow:view", "approval:flow:edit")):
|
||||
raise forbidden("缺少权限:approval:flow:view")
|
||||
flow = db.get(ApprovalFlow, flow_id)
|
||||
if flow is None or flow.is_deleted:
|
||||
raise not_found("流程不存在")
|
||||
return ok({
|
||||
"flow": {
|
||||
"id": flow.id, "key": flow.key, "name": flow.name,
|
||||
"businessModule": flow.business_module, "version": flow.version, "status": flow.status,
|
||||
"matchExpressions": _match_expressions(flow.match_json), "priority": flow.priority,
|
||||
"allowSelfSelect": flow.allow_self_select, "autoSkipDuplicate": flow.auto_skip_duplicate,
|
||||
"remark": flow.remark,
|
||||
},
|
||||
"nodes": [_node_view(node) for node in flow_service.ordered_nodes(flow)],
|
||||
"errors": flow_service.definition_errors(flow),
|
||||
})
|
||||
|
||||
|
||||
def _node_view(node: ApprovalNode) -> dict[str, Any]:
|
||||
return {
|
||||
"id": node.id, "nodeKey": node.node_key, "name": node.name, "nodeType": node.node_type,
|
||||
"orderNumber": node.order_number, "signType": node.sign_type,
|
||||
"candidates": _loads(node.candidates_json, []),
|
||||
"emptyStrategy": node.empty_strategy, "condition": node.condition_json,
|
||||
"nextNodeKey": node.next_node_key, "rejectTo": node.reject_to,
|
||||
"rollbackKeys": _loads(node.rollback_keys_json, []),
|
||||
"commentRequired": node.comment_required, "rejectCommentRequired": node.reject_comment_required,
|
||||
"timeoutHours": node.timeout_hours, "timeoutAction": node.timeout_action,
|
||||
"enabled": node.enabled, "remark": node.remark,
|
||||
}
|
||||
|
||||
|
||||
def _loads(raw: str, default: Any) -> Any:
|
||||
try:
|
||||
return json.loads(raw or "null")
|
||||
except json.JSONDecodeError:
|
||||
return default
|
||||
|
||||
|
||||
@router.post("/flows")
|
||||
def create_flow(body: FlowBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
if not current.permission.can("approval:flow:edit"):
|
||||
raise forbidden("缺少权限:approval:flow:edit")
|
||||
flow = ApprovalFlow(
|
||||
key=body.key, name=body.name, business_module=body.businessModule,
|
||||
status=FlowStatus.DRAFT, # 新建一律是草稿,必须显式发布
|
||||
match_json=json.dumps({"expressions": body.matchExpressions}, ensure_ascii=False),
|
||||
priority=body.priority, allow_self_select=body.allowSelfSelect,
|
||||
auto_skip_duplicate=body.autoSkipDuplicate, remark=body.remark,
|
||||
)
|
||||
db.add(flow)
|
||||
db.flush()
|
||||
_replace_nodes(db, flow, body.nodes)
|
||||
db.commit()
|
||||
return ok({"id": flow.id})
|
||||
|
||||
|
||||
def _replace_nodes(db, flow: ApprovalFlow, nodes: list[NodeBody]) -> None:
|
||||
for node in list(flow.nodes):
|
||||
db.delete(node)
|
||||
db.flush()
|
||||
for item in nodes:
|
||||
db.add(ApprovalNode(
|
||||
flow_id=flow.id, node_key=item.nodeKey, name=item.name, node_type=item.nodeType,
|
||||
order_number=item.orderNumber, sign_type=item.signType,
|
||||
candidates_json=json.dumps(item.candidates, ensure_ascii=False),
|
||||
empty_strategy=item.emptyStrategy, condition_json=item.condition,
|
||||
next_node_key=item.nextNodeKey, reject_to=item.rejectTo,
|
||||
rollback_keys_json=json.dumps(item.rollbackKeys),
|
||||
comment_required=item.commentRequired, reject_comment_required=item.rejectCommentRequired,
|
||||
timeout_hours=item.timeoutHours, timeout_action=item.timeoutAction,
|
||||
enabled=item.enabled, remark=item.remark,
|
||||
))
|
||||
db.flush()
|
||||
|
||||
|
||||
@router.put("/flows/{flow_id}")
|
||||
def update_flow(flow_id: int, body: FlowBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
if not current.permission.can("approval:flow:edit"):
|
||||
raise forbidden("缺少权限:approval:flow:edit")
|
||||
flow = db.get(ApprovalFlow, flow_id)
|
||||
if flow is None or flow.is_deleted:
|
||||
raise not_found("流程不存在")
|
||||
if flow.status == FlowStatus.PUBLISHED and body.status != FlowStatus.OFFLINE:
|
||||
raise conflict("published_locked",
|
||||
"已发布的流程不能直接改。请先下线,或复制成新版本再发布,"
|
||||
"否则正在跑的审批会突然换规则。")
|
||||
flow.name = body.name
|
||||
flow.business_module = body.businessModule
|
||||
flow.match_json = json.dumps({"expressions": body.matchExpressions}, ensure_ascii=False)
|
||||
flow.priority = body.priority
|
||||
flow.allow_self_select = body.allowSelfSelect
|
||||
flow.auto_skip_duplicate = body.autoSkipDuplicate
|
||||
flow.remark = body.remark
|
||||
_replace_nodes(db, flow, body.nodes)
|
||||
db.commit()
|
||||
return ok({"id": flow.id, "errors": flow_service.definition_errors(flow)})
|
||||
|
||||
|
||||
@router.post("/flows/{flow_id}/publish")
|
||||
def publish_flow(flow_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
if not current.permission.can("approval:flow:publish"):
|
||||
raise forbidden("缺少权限:approval:flow:publish")
|
||||
flow = db.get(ApprovalFlow, flow_id)
|
||||
if flow is None or flow.is_deleted:
|
||||
raise not_found("流程不存在")
|
||||
errors = flow_service.definition_errors(flow)
|
||||
if errors:
|
||||
raise conflict("definition_invalid", "流程定义有问题,不能发布", {"errors": errors})
|
||||
# 同一模块同一时刻只有一条已发布流程会被匹配到,但允许配多条不同条件的
|
||||
flow.status = FlowStatus.PUBLISHED
|
||||
flow.version = flow.version + 1
|
||||
db.commit()
|
||||
return ok({"id": flow.id, "version": flow.version})
|
||||
|
||||
|
||||
@router.post("/flows/{flow_id}/offline")
|
||||
def offline_flow(flow_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
if not current.permission.can("approval:flow:publish"):
|
||||
raise forbidden("缺少权限:approval:flow:publish")
|
||||
flow = db.get(ApprovalFlow, flow_id)
|
||||
if flow is None or flow.is_deleted:
|
||||
raise not_found("流程不存在")
|
||||
running = db.execute(
|
||||
select(func.count(ApprovalInstance.id)).where(ApprovalInstance.flow_id == flow_id,
|
||||
ApprovalInstance.status == InstanceStatus.REVIEWING)
|
||||
).scalar() or 0
|
||||
flow.status = FlowStatus.OFFLINE
|
||||
db.commit()
|
||||
return ok({"id": flow.id, "runningInstances": running})
|
||||
|
||||
|
||||
@router.get("/delegates")
|
||||
def list_delegates(db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
rows = db.execute(select(ApprovalDelegate).where(
|
||||
ApprovalDelegate.from_id == current.account.id,
|
||||
ApprovalDelegate.is_deleted.is_(False)).order_by(ApprovalDelegate.id.desc())).scalars().all()
|
||||
return ok([{
|
||||
"id": row.id, "toId": row.to_id, "toName": row.to_name,
|
||||
"modules": _loads(row.modules_json, []),
|
||||
"validFrom": row.valid_from.isoformat(sep=" ", timespec="minutes") if row.valid_from else "",
|
||||
"validTo": row.valid_to.isoformat(sep=" ", timespec="minutes") if row.valid_to else "",
|
||||
"enabled": row.enabled, "reason": row.reason,
|
||||
} for row in rows])
|
||||
|
||||
|
||||
class DelegateBody(BaseModel):
|
||||
toId: int
|
||||
modules: list[str] = Field(default_factory=list)
|
||||
validFrom: str = ""
|
||||
validTo: str = ""
|
||||
reason: str = ""
|
||||
|
||||
|
||||
@router.post("/delegates")
|
||||
def create_delegate(body: DelegateBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
from datetime import datetime
|
||||
|
||||
from ..models import Account
|
||||
|
||||
target = db.get(Account, body.toId)
|
||||
if target is None or target.is_deleted:
|
||||
raise not_found("接手人不存在")
|
||||
row = ApprovalDelegate(
|
||||
from_id=current.account.id, from_name=current.account.display_name,
|
||||
to_id=target.id, to_name=target.display_name or target.account,
|
||||
modules_json=json.dumps(body.modules), enabled=True, reason=body.reason,
|
||||
)
|
||||
if body.validFrom:
|
||||
row.valid_from = datetime.fromisoformat(body.validFrom)
|
||||
if body.validTo:
|
||||
row.valid_to = datetime.fromisoformat(body.validTo)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
return ok({"id": row.id})
|
||||
|
|
@ -0,0 +1,202 @@
|
|||
"""审计查询:操作日志与登录日志。
|
||||
|
||||
日志由 :mod:`app.service.audit` 中间件负责写,这里只负责让人查得动:按人、按动作、
|
||||
按对象、按时间窗,失败的操作单列。审计页的存在本身就是这套机制的一半——记了没人看
|
||||
的日志等于没记。
|
||||
|
||||
口径上有两条要说清楚:
|
||||
|
||||
* 审计不做数据权限过滤。它是"谁动了系统"的账,按 ``system:audit:view`` 这一个权限码
|
||||
放行;给它套项目数据范围,等于让被审计的人自己决定别人能看到他什么。
|
||||
* 明细里的请求体是脱敏后存的(口令/令牌/验证码在写入时就被抹成 ``***``),
|
||||
上传类请求只留字节数,不留内容。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
from sqlalchemy import func, or_, select
|
||||
|
||||
from ..deps import DbSession, PrincipalOf
|
||||
from ..envelope import forbidden, not_found, ok, page
|
||||
from ..models import LoginLog, OperationLog
|
||||
from ..service.audit import action_label
|
||||
|
||||
router = APIRouter(prefix="/system", tags=["audit"])
|
||||
|
||||
#: 一次最多翻多少天。审计表只增不删,不设上限的话一个全表扫能把库拖住。
|
||||
MAX_WINDOW_DAYS = 366
|
||||
|
||||
|
||||
def _need(current: PrincipalOf) -> None:
|
||||
if not current.permission.can("system:audit:view"):
|
||||
raise forbidden("缺少权限:system:audit:view")
|
||||
|
||||
|
||||
def _detail(row: OperationLog) -> dict[str, Any]:
|
||||
if not row.detail_json:
|
||||
return {}
|
||||
try:
|
||||
parsed = json.loads(row.detail_json)
|
||||
except ValueError:
|
||||
return {"_raw": row.detail_json[:2000]}
|
||||
return parsed if isinstance(parsed, dict) else {"_raw": parsed}
|
||||
|
||||
|
||||
def _window(days: int, from_date: str, to_date: str) -> tuple[datetime, datetime | None]:
|
||||
def parse(value: str) -> datetime | None:
|
||||
try:
|
||||
return datetime.fromisoformat(value.strip()[:10])
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
start = parse(from_date) or (datetime.now() - timedelta(days=max(1, min(days, MAX_WINDOW_DAYS))))
|
||||
end = parse(to_date)
|
||||
if end:
|
||||
end = end + timedelta(days=1) # 闭区间:填 2026-10-13 要把 13 号整天算进来
|
||||
return start, end
|
||||
|
||||
|
||||
@router.get("/operation-logs")
|
||||
def operation_logs(
|
||||
db: DbSession,
|
||||
current: PrincipalOf,
|
||||
keyword: str = "",
|
||||
accountName: str = "",
|
||||
action: str = "",
|
||||
objectType: str = "",
|
||||
days: int = Query(30, ge=1, le=MAX_WINDOW_DAYS),
|
||||
fromDate: str = "",
|
||||
toDate: str = "",
|
||||
onlyFailures: bool = False,
|
||||
pageNo: int = Query(1, ge=1),
|
||||
pageSize: int = Query(20, ge=1, le=200),
|
||||
) -> dict[str, Any]:
|
||||
_need(current)
|
||||
start, end = _window(days, fromDate, toDate)
|
||||
|
||||
statement = select(OperationLog).where(OperationLog.created_at >= start)
|
||||
if end:
|
||||
statement = statement.where(OperationLog.created_at < end)
|
||||
if accountName:
|
||||
statement = statement.where(OperationLog.account_name.like(f"%{accountName.strip()}%"))
|
||||
if action:
|
||||
statement = statement.where(OperationLog.action == action)
|
||||
if objectType:
|
||||
statement = statement.where(OperationLog.object_type == objectType)
|
||||
if keyword:
|
||||
like = f"%{keyword.strip()}%"
|
||||
statement = statement.where(or_(
|
||||
OperationLog.object_name.like(like), OperationLog.object_id.like(like),
|
||||
OperationLog.account_name.like(like), OperationLog.detail_json.like(like),
|
||||
))
|
||||
|
||||
total = db.execute(select(func.count()).select_from(statement.subquery())).scalar() or 0
|
||||
rows = db.execute(statement.order_by(OperationLog.id.desc())
|
||||
.offset((pageNo - 1) * pageSize).limit(pageSize)).scalars().all()
|
||||
|
||||
items = []
|
||||
for row in rows:
|
||||
detail = _detail(row)
|
||||
error = detail.get("error") if isinstance(detail.get("error"), dict) else {}
|
||||
items.append({
|
||||
"id": row.id,
|
||||
"accountName": row.account_name,
|
||||
"action": row.action,
|
||||
"actionLabel": action_label(row.action),
|
||||
"objectType": row.object_type,
|
||||
"objectId": row.object_id,
|
||||
"objectName": row.object_name,
|
||||
"ip": row.ip,
|
||||
"createdAt": row.created_at.isoformat(sep=" ", timespec="seconds") if row.created_at else "",
|
||||
"method": detail.get("method", ""),
|
||||
"path": detail.get("path", ""),
|
||||
"status": detail.get("status", 0),
|
||||
"ok": bool(detail.get("ok", True)),
|
||||
"durationMs": detail.get("durationMs", 0),
|
||||
"errorCode": error.get("code", ""),
|
||||
"errorMessage": error.get("message", ""),
|
||||
"traceId": error.get("traceId", ""),
|
||||
})
|
||||
result = page(items, total, pageNo, pageSize)
|
||||
result["data"]["window"] = {
|
||||
"from": start.isoformat(timespec="seconds"),
|
||||
"to": end.isoformat(timespec="seconds") if end else "",
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/operation-logs/options")
|
||||
def operation_log_options(db: DbSession, current: PrincipalOf,
|
||||
days: int = Query(90, ge=1, le=MAX_WINDOW_DAYS)) -> dict[str, Any]:
|
||||
"""筛选下拉的取值:只用这段时间里真出现过的动作与对象,不摆一长串用不上的选项。"""
|
||||
_need(current)
|
||||
start = datetime.now() - timedelta(days=days)
|
||||
actions = db.execute(
|
||||
select(OperationLog.action, func.count(OperationLog.id))
|
||||
.where(OperationLog.created_at >= start)
|
||||
.group_by(OperationLog.action).order_by(func.count(OperationLog.id).desc())
|
||||
).all()
|
||||
objects = db.execute(
|
||||
select(OperationLog.object_type, func.count(OperationLog.id))
|
||||
.where(OperationLog.created_at >= start, OperationLog.object_type != "")
|
||||
.group_by(OperationLog.object_type).order_by(func.count(OperationLog.id).desc())
|
||||
).all()
|
||||
return ok({
|
||||
"actions": [{"value": value, "label": action_label(value), "count": count}
|
||||
for value, count in actions],
|
||||
"objectTypes": [{"value": value or "", "label": value or "未标注", "count": count}
|
||||
for value, count in objects],
|
||||
})
|
||||
|
||||
|
||||
@router.get("/operation-logs/{log_id}")
|
||||
def operation_log_detail(log_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
"""单条明细:把脱敏后的请求体、参数、错误与业务补充原样给出。"""
|
||||
_need(current)
|
||||
row = db.get(OperationLog, log_id)
|
||||
if row is None:
|
||||
raise not_found("没有这条操作日志")
|
||||
detail = _detail(row)
|
||||
return ok({
|
||||
"id": row.id, "accountId": row.account_id, "accountName": row.account_name,
|
||||
"action": row.action, "actionLabel": action_label(row.action),
|
||||
"objectType": row.object_type, "objectId": row.object_id, "objectName": row.object_name,
|
||||
"ip": row.ip,
|
||||
"createdAt": row.created_at.isoformat(sep=" ", timespec="seconds") if row.created_at else "",
|
||||
"detail": detail,
|
||||
})
|
||||
|
||||
|
||||
@router.get("/login-logs")
|
||||
def login_logs(
|
||||
db: DbSession,
|
||||
current: PrincipalOf,
|
||||
keyword: str = "",
|
||||
onlyFailed: bool = False,
|
||||
days: int = Query(30, ge=1, le=MAX_WINDOW_DAYS),
|
||||
pageNo: int = Query(1, ge=1),
|
||||
pageSize: int = Query(20, ge=1, le=200),
|
||||
) -> dict[str, Any]:
|
||||
"""登录审计。审计"谁进过系统"这件事靠 ``login_log``,操作日志管的是进来之后改了什么。"""
|
||||
_need(current)
|
||||
start = datetime.now() - timedelta(days=days)
|
||||
statement = select(LoginLog).where(LoginLog.created_at >= start)
|
||||
if onlyFailed:
|
||||
statement = statement.where(LoginLog.success.is_(False))
|
||||
if keyword:
|
||||
like = f"%{keyword.strip()}%"
|
||||
statement = statement.where(or_(LoginLog.account.like(like), LoginLog.ip.like(like),
|
||||
LoginLog.reason.like(like)))
|
||||
total = db.execute(select(func.count()).select_from(statement.subquery())).scalar() or 0
|
||||
rows = db.execute(statement.order_by(LoginLog.id.desc())
|
||||
.offset((pageNo - 1) * pageSize).limit(pageSize)).scalars().all()
|
||||
return page([{
|
||||
"id": row.id, "account": row.account, "success": bool(row.success), "reason": row.reason,
|
||||
"ip": row.ip, "userAgent": row.user_agent, "mode": row.mode,
|
||||
"createdAt": row.created_at.isoformat(sep=" ", timespec="seconds") if row.created_at else "",
|
||||
} for row in rows], total, pageNo, pageSize)
|
||||
|
|
@ -0,0 +1,765 @@
|
|||
"""登录、令牌、免登与"我"的信息。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Query, Request, Response
|
||||
from fastapi.responses import RedirectResponse
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..config import settings
|
||||
from ..deps import CurrentUser, DbSession, PrincipalOf, client_ip
|
||||
from ..envelope import ApiError, ok
|
||||
from ..models import (Account, AccountIdentity, AccountSource, LoginLog, OperationLog,
|
||||
OrgUnit, Status)
|
||||
from ..security import (
|
||||
TokenError,
|
||||
decode_token,
|
||||
hash_password,
|
||||
issue_tokens,
|
||||
password_policy_error,
|
||||
verify_password,
|
||||
)
|
||||
from ..service import hub_api, org_sync, permissions, sso_handoff, sso_state
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
|
||||
class LoginBody(BaseModel):
|
||||
account: str = Field(min_length=1, max_length=190)
|
||||
password: str = Field(min_length=1, max_length=200)
|
||||
#: Hub 开着且它要验证码时才有值;没要就留空,别把空串当"验证码错误"送过去。
|
||||
captchaId: str = ""
|
||||
captchaAnswer: str = ""
|
||||
|
||||
|
||||
class RefreshBody(BaseModel):
|
||||
refreshToken: str
|
||||
|
||||
|
||||
class PasswordBody(BaseModel):
|
||||
oldPassword: str = ""
|
||||
newPassword: str = Field(min_length=1, max_length=200)
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
def login(body: LoginBody, request: Request, db: DbSession) -> dict[str, Any]:
|
||||
"""账号口令登录。界面上只有一个账号口令框,归谁验由 ``[hub].login_mode`` 决定。
|
||||
|
||||
统一身份开着的时候,这个框收的就是 Hub 账号:口令由 Hub 判定,本系统只把结果换成
|
||||
自己的会话,口令明文既不落库也不写日志。返回值里的 ``via`` 说清这次是走哪条路进来
|
||||
的(``hub`` / ``local``),登录日志与前端提示都照着它讲。
|
||||
"""
|
||||
account, via, detail = _authenticate(db, body, request)
|
||||
# 审计里的 mode 与返回给前端的 via 同源:都回答"口令归谁判的"
|
||||
judged = "hub" if via == "hub" else "password"
|
||||
if not Status.is_active(account.status):
|
||||
_log(db, account.id, account.account, False, Status.label(account.status), request,
|
||||
mode=judged)
|
||||
db.commit()
|
||||
raise ApiError("disabled", f"账号已{Status.label(account.status)},请联系管理员", http_status=403)
|
||||
|
||||
return ok({**_issue_session(db, request, account, detail=detail, mode=judged), "via": via})
|
||||
|
||||
|
||||
def _authenticate(db: Session, body: LoginBody,
|
||||
request: Request) -> tuple[Account, str, str]:
|
||||
"""返回 ``(本地账号, 认证方式, 登录日志说明)``。
|
||||
|
||||
判定顺序照 unisoa 那套口径来,两条不能让步的:
|
||||
|
||||
* **应急账号先走本地**。内置超管永远在 ``local_only_accounts`` 里,Hub 密钥配错、
|
||||
目录同步没跑、Hub 整个停机的时候还得进得去门改配置,否则就只能改库了。
|
||||
* **Hub 说"不对"就是不对**。被拒之后绝不拿库里那个旧哈希再兜一层——那样 Hub 上的
|
||||
停用、离职下线、改口令会在故障期集体失效。只有"压根没问到"(连不上、超时)才谈
|
||||
得上 ``login_mode = "hybrid"`` 那条回落。
|
||||
"""
|
||||
hub = settings.hub
|
||||
name = body.account.strip()
|
||||
if hub.hub_password_login and name.lower() not in hub.local_only_account_set:
|
||||
try:
|
||||
principal = hub_api.login_with_password(name, body.password,
|
||||
captcha_id=body.captchaId.strip(),
|
||||
captcha_answer=body.captchaAnswer.strip())
|
||||
except hub_api.HubRejected as exc:
|
||||
# 故意不去动 login_failed_count:那是本地口令的锁定计数,让 Hub 的失败去
|
||||
# 累加它,等于给外面开一条"把管理员锁在自己系统外面"的免费通道。
|
||||
_log(db, None, name, False, f"统一身份拒绝:{exc.message}", request, mode="hub")
|
||||
db.commit()
|
||||
if exc.needs_captcha:
|
||||
raise ApiError("captcha_required", exc.message or "验证码不正确或已失效",
|
||||
http_status=401) from exc
|
||||
raise ApiError("bad_credentials", exc.message or "账号或口令不正确",
|
||||
http_status=401) from exc
|
||||
except hub_api.HubError as exc:
|
||||
if hub.mode != "hybrid":
|
||||
raise ApiError("hub_unavailable",
|
||||
f"{exc};本档口令只认统一身份,可改用统一门户免登",
|
||||
http_status=503) from exc
|
||||
logger.warning("统一身份不可用,退回本地口令校验 %s:%s", name, exc)
|
||||
else:
|
||||
account = _account_from_hub(db, principal, name, request)
|
||||
sub = str(principal.get("sub") or "").strip()
|
||||
return account, "hub", f"统一身份口令校验通过(sub={sub or '-'})"
|
||||
|
||||
return _local_login(db, name, body.password, request), "local", ""
|
||||
|
||||
|
||||
def _local_login(db: Session, name: str, password: str, request: Request) -> Account:
|
||||
"""本地口令那条路:查号、锁定、验哈希、记失败次数。"""
|
||||
account = db.execute(
|
||||
select(Account).where(Account.account == name, Account.is_deleted.is_(False))
|
||||
).scalars().first()
|
||||
|
||||
if account is None:
|
||||
_log(db, None, name, False, "账号不存在", request)
|
||||
raise ApiError("bad_credentials", "账号或口令不正确", http_status=401)
|
||||
if account.locked_until and account.locked_until > datetime.now():
|
||||
minutes = max(1, int((account.locked_until - datetime.now()).total_seconds() // 60) + 1)
|
||||
raise ApiError("locked", f"账号已锁定,请 {minutes} 分钟后再试", http_status=429)
|
||||
|
||||
if not _verify(db, account, password):
|
||||
_fail(db, account, request)
|
||||
raise ApiError("bad_credentials", "账号或口令不正确", http_status=401)
|
||||
return account
|
||||
|
||||
|
||||
def _issue_session(db: Session, request: Request, account: Account, *,
|
||||
detail: str, mode: str = "password") -> dict[str, Any]:
|
||||
"""登录成功后公共的那一段:记登录日志、落最近登录信息、发令牌、拼权限。
|
||||
|
||||
口令登录、免登票据、免登短码三条入口都必须走这里,否则很容易出现"免登进来的
|
||||
人没记登录日志"或者"免登没清失败计数,被上一次口令输错连坐锁定"这类偏差。
|
||||
"""
|
||||
account.login_failed_count = 0
|
||||
account.locked_until = None
|
||||
account.last_login_at = datetime.now()
|
||||
account.last_login_ip = _client_ip(request)
|
||||
tokens = issue_tokens(account.id, account.account)
|
||||
context = permissions.build_context(db, account)
|
||||
_log(db, account.id, account.account, True, detail, request, mode=mode)
|
||||
db.commit()
|
||||
return {
|
||||
**tokens,
|
||||
"user": profile_payload(db, account),
|
||||
"permissions": sorted(context.codes) or (["*"] if context.is_system_admin else []),
|
||||
"roles": [{"id": role.id, "code": role.code, "name": role.name} for role in context.roles],
|
||||
}
|
||||
|
||||
|
||||
def _verify(db: Session, account: Account, password: str) -> bool:
|
||||
"""本地口令校验:只管本系统自己存的那份哈希。
|
||||
|
||||
Hub 账号的口令不归这里管——那是 :func:`_authenticate` 拿去问统一身份的事,本系统
|
||||
库里给 Hub 账号存的哈希(同步建的号甚至是空串)不构成任何凭据。所以这里没有任何
|
||||
"Hub 连不上就当本地账号放行"的兜底:那样做等于让 Hub 的停用与离职下线在故障期间
|
||||
集体失效,是最坏情况下最不该发生的事。
|
||||
|
||||
Hub 整体不可用时的逃生门是 ``[hub].break_glass_login``,它只放行 ``source=local``
|
||||
的账号(内置超管),不给任何 Hub 账号开后门;想留更宽的退路请显式改
|
||||
``[hub].login_mode = "hybrid"``。
|
||||
"""
|
||||
if account.source == AccountSource.HUB:
|
||||
return False
|
||||
# login_mode = "sso" 时口令这条路整个关掉,连逃生门也不留
|
||||
if not settings.hub.local_password_login_allowed:
|
||||
return False
|
||||
if settings.hub.enabled and not settings.hub.break_glass_login:
|
||||
return False
|
||||
return verify_password(password, account.password_hash)
|
||||
|
||||
|
||||
|
||||
def _fail(db, account: Account, request: Request) -> None:
|
||||
limit = settings.security.login_max_errors
|
||||
account.login_failed_count = (account.login_failed_count or 0) + 1
|
||||
if limit and account.login_failed_count >= limit:
|
||||
account.locked_until = datetime.now() + timedelta(minutes=settings.security.login_lock_minutes)
|
||||
account.login_failed_count = 0
|
||||
_log(db, account.id, account.account, False, "口令不正确", request)
|
||||
db.commit()
|
||||
|
||||
|
||||
def _log(db, account_id: int | None, account: str, success: bool, reason: str, request: Request,
|
||||
*, mode: str = "password") -> None:
|
||||
"""记一条登录审计。
|
||||
|
||||
``mode`` 说的是"这次是谁判的":``password`` 本地口令、``hub`` 统一身份口令、
|
||||
``sso`` 统一门户免登。排查时"这个人到底是怎么进来的"全靠这一列,不能都糊成默认值。
|
||||
"""
|
||||
db.add(LoginLog(
|
||||
account=account, account_id=account_id, success=success, reason=reason,
|
||||
ip=_client_ip(request), user_agent=request.headers.get("User-Agent", "")[:500],
|
||||
mode=mode,
|
||||
))
|
||||
db.flush()
|
||||
|
||||
|
||||
# 取访客 IP 的口径统一在 deps.client_ip,这里只留一个短别名
|
||||
_client_ip = client_ip
|
||||
|
||||
|
||||
@router.get("/captcha")
|
||||
def login_captcha() -> dict[str, Any]:
|
||||
"""登录页验证码:口令要拿去问 Hub 时才需要,Hub 那侧确实是算术题 SVG。
|
||||
|
||||
``required=false`` 有两种含义——本系统压根不问 Hub(``login_mode`` 是 local/sso 或
|
||||
Hub 没开),以及问不到验证码(这一种带 ``warning``)。后者不挡登录:真需要验证码时
|
||||
Hub 会当场拒,接口回 ``captcha_required``,前端那时再取一张并把框亮出来。
|
||||
"""
|
||||
if not settings.hub.hub_password_login:
|
||||
return ok({"required": False, "captchaId": "", "image": "", "question": ""})
|
||||
try:
|
||||
payload = hub_api.fetch_captcha()
|
||||
except hub_api.HubError as exc:
|
||||
logger.warning("取登录验证码失败:%s", exc)
|
||||
return ok({"required": False, "captchaId": "", "image": "", "question": "",
|
||||
"warning": str(exc)})
|
||||
return ok({"required": True, **payload})
|
||||
|
||||
|
||||
@router.post("/refresh")
|
||||
def refresh(body: RefreshBody, db: DbSession) -> dict[str, Any]:
|
||||
try:
|
||||
payload = decode_token(body.refreshToken, expect="refresh")
|
||||
except TokenError as exc:
|
||||
raise ApiError("invalid_token", str(exc), http_status=401) from exc
|
||||
account = db.get(Account, int(payload.get("sub") or 0))
|
||||
if account is None or account.is_deleted or not Status.is_active(account.status):
|
||||
raise ApiError("invalid_token", "账号不可用,请重新登录", http_status=401)
|
||||
if account.password_updated_at:
|
||||
issued_at = payload.get("iat") or 0
|
||||
if account.password_updated_at.timestamp() > float(issued_at):
|
||||
raise ApiError("invalid_token", "口令已修改,请重新登录", http_status=401)
|
||||
return ok(issue_tokens(account.id, account.account))
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
def me(db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
context = current.permission
|
||||
return ok({
|
||||
"user": profile_payload(db, current.account),
|
||||
"permissions": ["*"] if context.is_system_admin else sorted(context.codes),
|
||||
"roles": [{"id": role.id, "code": role.code, "name": role.name} for role in context.roles],
|
||||
"menus": permissions.menu_tree(db, context),
|
||||
"fieldMasks": context.field_masks,
|
||||
})
|
||||
|
||||
|
||||
@router.get("/menus")
|
||||
def menus(db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
return ok(permissions.menu_tree(db, current.permission))
|
||||
|
||||
|
||||
@router.put("/password")
|
||||
def change_password(body: PasswordBody, db: DbSession, account: CurrentUser) -> dict[str, Any]:
|
||||
if account.source == "hub" and settings.hub.enabled:
|
||||
raise ApiError("hub_account", "统一身份账号的口令请到统一身份平台修改")
|
||||
if account.password_hash and not verify_password(body.oldPassword, account.password_hash):
|
||||
raise ApiError("bad_password", "原口令不正确")
|
||||
problem = password_policy_error(body.newPassword)
|
||||
if problem:
|
||||
raise ApiError("weak_password", problem)
|
||||
account.password_hash = hash_password(body.newPassword)
|
||||
account.password_updated_at = datetime.now()
|
||||
db.add(OperationLog(account_id=account.id, account_name=account.display_name,
|
||||
action="change_password", object_type="account", object_id=str(account.id)))
|
||||
db.commit()
|
||||
return ok({"changed": True})
|
||||
|
||||
|
||||
@router.post("/logout")
|
||||
def logout(account: CurrentUser) -> dict[str, Any]:
|
||||
# 无状态令牌:前端删掉本地令牌即可。真正的即时吊销靠改口令/停用账号。
|
||||
return ok({"loggedOut": True})
|
||||
|
||||
|
||||
@router.get("/sso/status")
|
||||
def sso_status(request: Request) -> dict[str, Any]:
|
||||
"""前端据此决定登录页长什么样、"前往统一门户"该把人送去哪。
|
||||
|
||||
``localPasswordAllowed=false`` 时登录页要撤掉口令表单,只留"从统一门户进入":
|
||||
跳转链接只能由门户签发(``POST /auth/apps/{code}/launch`` 要用户在 Hub 的登录态),
|
||||
本系统自己造不出这张票,所以这里不给 authorizeUrl,只给状态与门户地址。
|
||||
|
||||
``callbackUrl`` 是管理员要去 Hub 后台登记的那一条,随请求地址现算,换部署不用改代码。
|
||||
"""
|
||||
return ok({
|
||||
"enabled": settings.hub.sso_configured,
|
||||
"hubEnabled": settings.hub.enabled,
|
||||
"passwordLoginAllowed": settings.hub.password_login_allowed,
|
||||
"hubPasswordLogin": settings.hub.hub_password_login,
|
||||
"localPasswordAllowed": settings.hub.local_password_login_allowed,
|
||||
"loginMode": settings.hub.mode,
|
||||
"hubBaseUrl": settings.hub.base_url if settings.hub.enabled else "",
|
||||
"portalUrl": settings.hub.portal_base_url if settings.hub.enabled else "",
|
||||
"appCode": settings.hub.app_code,
|
||||
"missing": _sso_missing(),
|
||||
**sso_handoff.advertised_urls(request),
|
||||
**sso_handoff.view(),
|
||||
})
|
||||
|
||||
|
||||
def _sso_missing() -> list[str]:
|
||||
"""免登三件套缺哪几项,直接点名;对接文档说"配不齐就等于没开"。"""
|
||||
missing: list[str] = []
|
||||
if not settings.hub.enabled:
|
||||
missing.append("hub.enabled")
|
||||
if not settings.hub.base_url:
|
||||
missing.append("hub.base_url")
|
||||
if not settings.hub.app_code:
|
||||
missing.append("hub.app_code")
|
||||
if not settings.hub.integration_key:
|
||||
missing.append("hub.integration_key")
|
||||
return missing
|
||||
|
||||
|
||||
@router.post("/sso/state")
|
||||
def sso_begin(request: Request, response: Response) -> dict[str, Any]:
|
||||
"""发起免登:写一条随机 ``state`` 到 HttpOnly Cookie,把 state 与门户地址给前端。
|
||||
|
||||
前端拿到 state 后把用户送回统一门户,用户在门户里点本系统卡片,Hub 带着 ``ticket``
|
||||
(以及它收到的 ``state``)把浏览器跳回来。文档要求 state 由下游服务端生成并保管、
|
||||
落地时精确比对,用来挡会话固定与票据注入——所以值放服务端下发的 HttpOnly Cookie,
|
||||
不放 localStorage、不放地址栏,见 :mod:`app.service.sso_state`。
|
||||
"""
|
||||
missing = _sso_missing()
|
||||
if missing:
|
||||
raise ApiError("sso_disabled", f"统一门户免登未启用,缺少:{'、'.join(missing)}",
|
||||
http_status=400)
|
||||
value = sso_state.issue_state(response, secure=sso_state.is_https(request))
|
||||
return ok({
|
||||
"state": value,
|
||||
"portalUrl": settings.hub.portal_base_url,
|
||||
"appCode": settings.hub.app_code,
|
||||
"ttlSeconds": sso_state.STATE_TTL_SECONDS,
|
||||
})
|
||||
|
||||
|
||||
class TicketBody(BaseModel):
|
||||
ticket: str = ""
|
||||
state: str = ""
|
||||
|
||||
|
||||
class ExchangeBody(BaseModel):
|
||||
code: str = ""
|
||||
|
||||
|
||||
#: 免登失败的稳定原因码。回调 302 回落地页时只透传这一批,表外的一律收进
|
||||
#: ``sso_failed``,免得后端的中文句子绕过前端语言包直接上界面。
|
||||
LANDING_REASONS = frozenset({
|
||||
"sso_disabled",
|
||||
"ticket_missing",
|
||||
"ticket_invalid",
|
||||
"ticket_expired",
|
||||
"ticket_audience_mismatch",
|
||||
"user_inactive",
|
||||
"sso_state_rejected",
|
||||
"hub_key_rejected",
|
||||
"hub_app_forbidden",
|
||||
"hub_app_not_found",
|
||||
"hub_no_subject",
|
||||
"hub_unavailable",
|
||||
"account_disabled",
|
||||
"account_not_provisioned",
|
||||
})
|
||||
|
||||
#: 落地地址上带着一性次短码,不能被浏览器或中间代理缓存了重复使用
|
||||
_NO_STORE = {"Cache-Control": "no-store", "Pragma": "no-cache"}
|
||||
|
||||
logger = logging.getLogger("pms.hub")
|
||||
|
||||
|
||||
@router.post("/sso/ticket")
|
||||
def sso_ticket_login(body: TicketBody, request: Request, response: Response,
|
||||
db: DbSession) -> dict[str, Any]:
|
||||
"""免登落地换本地会话(前端落地页口径):``ticket`` -> Hub 校验 -> 发本地令牌。
|
||||
|
||||
票据由浏览器交给前端、再由前端 POST 回来,判定全在 :func:`_person_from_ticket`,
|
||||
与后端回调 ``GET /auth/sso/callback`` 走的是同一套。Hub 上把 ``launch_url`` 填成
|
||||
前端路由时才用这条路;填的是后端回调就该走 ``POST /auth/sso/exchange``。
|
||||
"""
|
||||
account, detail = _person_from_ticket(db, request, response,
|
||||
ticket=body.ticket, state=body.state)
|
||||
return ok({**_issue_session(db, request, account, detail=detail, mode="sso"), "via": "hub"})
|
||||
|
||||
|
||||
@router.get("/sso/callback")
|
||||
def sso_callback(
|
||||
db: DbSession,
|
||||
request: Request,
|
||||
ticket: str = Query("", description="统一门户跳转带来的一次性票据"),
|
||||
state: str = Query("", description="发起跳转时本系统发出、门户原样带回的 state"),
|
||||
redirect: str = Query("", description="免登成功后要去的站内路径"),
|
||||
) -> RedirectResponse:
|
||||
"""免登回调(后端落地口径):Hub 把浏览器 302 到这里,本系统当场验票。
|
||||
|
||||
Hub 上 ``launch_url`` / ``redirect_uris`` 填本路径(或别名 ``/sso/hub``)时,票据只在
|
||||
"浏览器 -> 本系统 -> Hub" 这一趟里出现,前端 JS、浏览历史、代理日志与 Referer 都拿不到
|
||||
它。验完 302 到 ``/sso#code=…``,前端再调 ``POST /auth/sso/exchange`` 换会话。
|
||||
"""
|
||||
return _landing(db, request, ticket=ticket, state=state, redirect=redirect)
|
||||
|
||||
|
||||
@router.post("/sso/exchange")
|
||||
def sso_exchange(body: ExchangeBody, request: Request, response: Response,
|
||||
db: DbSession) -> dict[str, Any]:
|
||||
"""用回调发出的一次性短码换本地会话(配 ``GET /auth/sso/callback`` 使用)。
|
||||
|
||||
短码必须配着回调当场下发的那条 HttpOnly Cookie 一起交回来,两者缺一律按失效处理;
|
||||
用掉即作废,第二次来就是"回门户重新点一次"。出参形状与 ``POST /auth/sso/ticket``
|
||||
一致,多带一个 ``redirect``:回调时带进来的站内路径,前端据此决定进哪一页。
|
||||
"""
|
||||
account, row = sso_handoff.redeem(db, request, response, body.code)
|
||||
if not Status.is_active(account.status):
|
||||
# 回调与兑换之间只有几十秒,但停用确实可能发生在这里,不能拿旧身份换会话
|
||||
raise ApiError("account_disabled",
|
||||
f"账号已{Status.label(account.status)},请联系管理员", http_status=403)
|
||||
session = _issue_session(db, request, account, detail=row.detail or "统一门户免登进入",
|
||||
mode="sso")
|
||||
return ok({**session, "via": "hub", "redirect": sso_handoff.redirect_target(row)})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 回调地址的别名:Hub 上填 /sso/hub 也接得住
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: 不带 ``/api/v1`` 前缀的回调别名。对接地带里管理员最常照对接指南的举例把 ``launch_url``
|
||||
#: 写成 ``https://<本系统>/sso/hub``,那一处如果没有后端路由就只剩一张空白页,
|
||||
#: 还得让人回头改 Hub 上的配置。生产同域反代把这一条也转给后端即可。
|
||||
sso_alias_router = APIRouter(tags=["auth"])
|
||||
|
||||
|
||||
@sso_alias_router.get(sso_handoff.ALIAS_PATH, include_in_schema=False)
|
||||
def sso_callback_alias(
|
||||
db: DbSession,
|
||||
request: Request,
|
||||
ticket: str = Query("", description="统一门户跳转带来的一次性票据"),
|
||||
state: str = Query("", description="发起跳转时本系统发出、门户原样带回的 state"),
|
||||
redirect: str = Query("", description="免登成功后要去的站内路径"),
|
||||
) -> RedirectResponse:
|
||||
"""``/sso/hub`` 与 ``GET /api/v1/auth/sso/callback`` 是同一个入口的两种写法。"""
|
||||
return _landing(db, request, ticket=ticket, state=state, redirect=redirect)
|
||||
|
||||
|
||||
def _landing(db: Session, request: Request, *, ticket: str, state: str,
|
||||
redirect: str) -> RedirectResponse:
|
||||
"""统一门户 302 落到后端:验票认人,再用一条一次性短码把人送进前端。
|
||||
|
||||
这是浏览器整页跳转过来的入口,出错不能回 JSON(用户只会看到一屏
|
||||
``{"ok": false, ...}``),一律 302 回落地页并带上稳定原因码,由前端翻成本地化文案。
|
||||
票据原值既不进 302 地址,也不写日志;本地令牌同样不上地址栏,上来的是
|
||||
:mod:`app.service.sso_handoff` 那条 60 秒即失效、只能用一次、还绑着 HttpOnly Cookie
|
||||
的短码。
|
||||
"""
|
||||
scratch = Response()
|
||||
try:
|
||||
account, detail = _person_from_ticket(db, request, scratch,
|
||||
ticket=ticket, state=state)
|
||||
except ApiError as exc:
|
||||
logger.warning("免登回调被拒(%s),来源 %s", exc.code, _client_ip(request))
|
||||
return _redirect(sso_handoff.landing_url(error=_landing_reason(exc.code)), scratch)
|
||||
code, bind = sso_handoff.issue(db, account=account, detail=detail,
|
||||
redirect=sso_handoff.safe_path(redirect))
|
||||
response = _redirect(sso_handoff.landing_url(code=code), scratch)
|
||||
sso_handoff.attach_cookie(response, bind, secure=sso_state.is_https(request))
|
||||
logger.info("统一门户免登回调落地:%s -> 一次性短码", account.account)
|
||||
return response
|
||||
|
||||
|
||||
def _landing_reason(reason: str) -> str:
|
||||
"""回调失败时能写进 302 地址的原因码:表外的一律收进 ``sso_failed``。"""
|
||||
return reason if reason in LANDING_REASONS else "sso_failed"
|
||||
|
||||
|
||||
def _redirect(location: str, scratch: Response | None = None) -> RedirectResponse:
|
||||
"""发一条不缓存的 302,顺带把校验 ``state`` 时用掉的那条 Cookie 一起带出去。"""
|
||||
response = RedirectResponse(location, status_code=302, headers=_NO_STORE)
|
||||
if scratch is not None:
|
||||
sso_state.forward_cookies(scratch, response)
|
||||
return response
|
||||
|
||||
|
||||
def _person_from_ticket(db: Session, request: Request, response: Response, *,
|
||||
ticket: str, state: str) -> tuple[Account, str]:
|
||||
"""免登票据 -> 本地账号。前端落地页与后端回调两条路共用这一段判定。
|
||||
|
||||
成了给出 ``(本地账号, 登录日志说明)``,任何一环不对都抛 :class:`ApiError`,``code``
|
||||
是给前端与日志用的稳定码。几条来自对接文档的硬规定,这里逐条对上:
|
||||
|
||||
* 票据只在这一次服务端调用里消费,**不重试**(超时也无法判断 Hub 是否已消费);
|
||||
票据原值不写日志、不进异常文本;
|
||||
* ``state`` 比两层:浏览器 Cookie 一层,票据校验响应回传的那层再比一次;
|
||||
* 受众(``app_code``)与 ``expires_at`` 由 :mod:`app.service.hub_api` 二次校验;
|
||||
* ``user_inactive`` 就把本地账号一并停用,绝不"回落到旧会话";
|
||||
* 只按 ``sub`` 建映射,``account`` 只是展示与认领线索。
|
||||
"""
|
||||
missing = _sso_missing()
|
||||
if missing:
|
||||
raise ApiError("sso_disabled", "统一门户免登未启用,请联系管理员检查 Hub 站点地址、"
|
||||
"应用编码与免登应用密钥", http_status=400)
|
||||
value = (ticket or "").strip()
|
||||
if not value:
|
||||
raise ApiError("ticket_missing", "缺少免登票据,请回到统一门户重新点击本系统",
|
||||
http_status=400)
|
||||
|
||||
check = sso_state.check_state(request, response, state)
|
||||
allowed, why = check.verdict(settings.hub.sso_state_required)
|
||||
if not allowed:
|
||||
logger.warning("免登被拒:state 校验未通过(%s),来源 %s", why, _client_ip(request))
|
||||
raise ApiError("sso_state_rejected", f"免登校验未通过:{why}", http_status=401)
|
||||
|
||||
try:
|
||||
identity = hub_api.verify_ticket(value, app_code=settings.hub.app_code or None)
|
||||
except hub_api.TicketRejected as exc:
|
||||
# 登录日志只记 reason 与 Hub 的错误码,票据原值一个字都不落
|
||||
_log(db, None, f"hub:{exc.reason}", False, exc.message, request, mode="sso")
|
||||
db.commit()
|
||||
if exc.reason == "user_inactive":
|
||||
_retire_local_session(db, exc.data)
|
||||
logger.warning("免登票据校验未通过(reason=%s code=%s),来源 %s",
|
||||
exc.reason, exc.code or "-", _client_ip(request))
|
||||
raise ApiError(exc.reason, exc.message,
|
||||
http_status=403 if exc.reason == "user_inactive" else 401) from exc
|
||||
|
||||
# 票据回传的 state 必须与这一趟交回来的 state 是同一条:Cookie 那一层只证明
|
||||
# "地址栏里的 state 是本系统发出去的",这一层才证明"Hub 签的这张票本来就是开给
|
||||
# 这个 state 的"。少了它,别人就能拿自己的票据配我们的 state,把人登成他自己。
|
||||
echoed = str(identity.get("state") or "").strip()
|
||||
given = (state or "").strip()
|
||||
if echoed != given and (echoed or settings.hub.sso_state_required):
|
||||
logger.warning("免登被拒:票据回传的 state 与%s的 state 不一致,来源 %s",
|
||||
"本系统发出" if given else "地址栏", _client_ip(request))
|
||||
raise ApiError("sso_state_rejected",
|
||||
"免登校验未通过:票据与本次跳转不是同一次发起,请回到统一门户重新点击",
|
||||
http_status=401)
|
||||
|
||||
sub = str(identity.get("sub") or "").strip()
|
||||
account = _account_by_sub(db, sub)
|
||||
if account is None:
|
||||
account = _bind_hub_principal(db, sub, identity)
|
||||
|
||||
if account is None:
|
||||
_log(db, None, sub, False, "免登被拒:无法建立账号映射", request, mode="sso")
|
||||
db.commit()
|
||||
raise ApiError("account_not_provisioned", "这个统一身份账号在本系统里还没有映射,"
|
||||
"请联系管理员或先做一次组织人员同步", http_status=403)
|
||||
if not Status.is_active(account.status):
|
||||
_log(db, account.id, account.account, False, "免登被拒:账号不可用", request, mode="sso")
|
||||
db.commit()
|
||||
raise ApiError("account_disabled",
|
||||
f"账号已{Status.label(account.status)},请联系管理员", http_status=403)
|
||||
|
||||
logger.info("统一门户免登校验通过:%s(sub=%s)", account.account, sub)
|
||||
return account, (
|
||||
f"统一门户免登进入(app={identity.get('app_code') or settings.hub.app_code},sub={sub})"
|
||||
)
|
||||
|
||||
|
||||
def _account_from_hub(db: Session, principal: dict[str, Any], submitted: str,
|
||||
request: Request) -> Account:
|
||||
"""统一身份认了这个账号 -> 本地账号:先按 Hub 主键,其次按账号,都没有就当场建号。
|
||||
|
||||
与免登那条路共用 :func:`_bind_hub_principal` -> ``org_sync._sync_people`` 那套建号
|
||||
规则,两条路各写一份"同名撞号怎么办"迟早对不上。多出来的一步是按账号认领:这条路
|
||||
是本人亲自在本系统页面上报了账号名并过了 Hub 的口令校验,把还没绑过主键的同名本地
|
||||
账号认下来是安全的;免登那条路不行,票据里只有 ``sub``,账号名只是 Hub 顺带下发的
|
||||
展示值,拿它认人等于允许别人用票据把自己登成别人。
|
||||
"""
|
||||
sub = str(principal.get("sub") or "").strip()
|
||||
if not sub and principal.get("access_token"):
|
||||
# 极少数部署登录响应里不带用户主键,拿刚拿到的令牌问一次 /auth/me 补上;
|
||||
# 问不到就退回账号名那条路,别把已经验过口令的人挡在门外。
|
||||
sub = _sub_from_access_token(str(principal["access_token"]))
|
||||
|
||||
account = _account_by_sub(db, sub)
|
||||
if account is None:
|
||||
account, refused = _claim_hub_account_by_name(db, sub, principal, submitted)
|
||||
if refused:
|
||||
_log(db, None, submitted or sub, False, "统一身份校验通过,但账号主键与别人冲突", request,
|
||||
mode="hub")
|
||||
db.commit()
|
||||
raise ApiError("account_identity_conflict",
|
||||
"这个账号名在本系统里已经绑定了另一个统一身份主键,"
|
||||
"请联系管理员核对后再登录", http_status=403)
|
||||
if account is None:
|
||||
account = _bind_hub_principal(db, sub, principal)
|
||||
if account is None:
|
||||
_log(db, None, submitted or sub, False, "统一身份校验通过,但无法建立账号映射", request,
|
||||
mode="hub")
|
||||
db.commit()
|
||||
raise ApiError("account_not_provisioned",
|
||||
"统一身份已经认了这个账号,但本系统还没有它的映射:"
|
||||
"请先在「统一身份同步」跑一次人员同步,或联系管理员建号",
|
||||
http_status=403)
|
||||
|
||||
_adopt_hub_identity(db, account, sub, principal)
|
||||
return account
|
||||
|
||||
|
||||
def _sub_from_access_token(token: str) -> str:
|
||||
"""用登录拿到的令牌问一次 ``/auth/me``,只为把用户主键补全。"""
|
||||
try:
|
||||
me = hub_api.fetch_me(token)
|
||||
except hub_api.HubError as exc:
|
||||
logger.warning("统一身份登录响应没有主键,问 /auth/me 也没问到:%s", exc)
|
||||
return ""
|
||||
for key in ("user_id", "id", "sub"):
|
||||
value = me.get(key)
|
||||
if value not in (None, ""):
|
||||
return str(value).strip()
|
||||
return ""
|
||||
|
||||
|
||||
def _claim_hub_account_by_name(db: Session, sub: str, principal: dict[str, Any],
|
||||
submitted: str) -> tuple[Account | None, bool]:
|
||||
"""按账号名认领本地已有账号,返回 ``(账号, 是否因主键冲突而拒)``。
|
||||
|
||||
主键只补空、不覆盖:把一个已经绑着别人主键的行改过来,等于把两个人的权限、待办、
|
||||
流程历史并成一条,所以这里直接拒,也不再往下走建号那条路——悄悄建一条
|
||||
``xxx_hubNNN`` 的影子账号放人进来,是更难被发现的一种并号。
|
||||
"""
|
||||
wanted = [name for name in (str(principal.get("account") or "").strip(), submitted) if name]
|
||||
for name in dict.fromkeys(wanted):
|
||||
account = db.execute(
|
||||
select(Account).where(Account.account == name, Account.is_deleted.is_(False))
|
||||
).scalars().first()
|
||||
if account is None:
|
||||
continue
|
||||
if account.hub_user_id and sub.isdigit() and account.hub_user_id != int(sub):
|
||||
logger.warning("账号 %s 本地绑的是 Hub 主键 %s,本次登录却是 %s,不认领",
|
||||
account.account, account.hub_user_id, sub)
|
||||
return None, True
|
||||
logger.info("统一身份登录认领本地账号 %s(sub=%s)", account.account, sub or "-")
|
||||
return account, False
|
||||
return None, False
|
||||
|
||||
|
||||
def _adopt_hub_identity(db: Session, account: Account, sub: str,
|
||||
principal: dict[str, Any]) -> None:
|
||||
"""本人刚在统一身份验过口令,这一行从这次登录起交给 Hub 口径。
|
||||
|
||||
只补空、不改名、不动状态:账号改名要连着审批岗位、共享名单一起搬,那是同步的活;
|
||||
状态由同步与免登停用那条路管,这里把停用的人"救活"是最坏的一种体贴。
|
||||
"""
|
||||
changed = False
|
||||
if sub.isdigit() and not account.hub_user_id:
|
||||
account.hub_user_id = int(sub)
|
||||
changed = True
|
||||
elif sub.isdigit() and account.hub_user_id != int(sub):
|
||||
logger.warning("账号 %s 本地绑的是 Hub 主键 %s,本次登录却是 %s,保持不动,请人工核对",
|
||||
account.account, account.hub_user_id, sub)
|
||||
if account.source != AccountSource.HUB:
|
||||
account.source = AccountSource.HUB
|
||||
changed = True
|
||||
if changed:
|
||||
db.flush()
|
||||
|
||||
|
||||
def _account_by_sub(db: Session, sub: str) -> Account | None:
|
||||
"""按 Hub 主键(票据里的 ``sub``)找本地账号——文档规定只以 ``sub`` 建映射。"""
|
||||
if not sub.isdigit():
|
||||
return None
|
||||
return db.execute(
|
||||
select(Account).where(Account.hub_user_id == int(sub), Account.is_deleted.is_(False))
|
||||
).scalars().first()
|
||||
|
||||
|
||||
def _retire_local_session(db: Session, data: dict[str, Any]) -> None:
|
||||
"""Hub 说这个人停用了:本地账号就地停用,绝不"回落到旧会话"。
|
||||
|
||||
本系统的访问令牌是无状态 JWT,不存服务端会话,所以这里能做的是把账号停用——
|
||||
``deps.current_account`` 每个请求都会重新查状态,停用即刻生效,旧令牌立刻没用。
|
||||
"""
|
||||
account = _account_by_sub(db, str((data or {}).get("sub") or "").strip())
|
||||
if account is None or account.status == Status.DISABLED:
|
||||
return
|
||||
account.status = Status.DISABLED
|
||||
db.commit()
|
||||
logger.info("统一门户已停用 %s,本地账号同步置为停用", account.account)
|
||||
|
||||
|
||||
def _bind_hub_principal(db: Session, sub: str, principal: dict[str, Any]) -> Account | None:
|
||||
"""首次免登时按 ``sub`` 建账号。
|
||||
|
||||
文档写死"只以 sub 建立映射,禁止用 display_name 或 email 自动合并账号",所以这里
|
||||
不看姓名、不看邮箱;本地已经占着同名账号的人也不抢,走 org_sync 那套加后缀新建的
|
||||
规则,保持两条路径行为一致。
|
||||
"""
|
||||
from ..service.org_sync import SyncStats, _sync_people # 复用同一段建号规则
|
||||
|
||||
if not sub.isdigit():
|
||||
return None
|
||||
status = principal.get("status")
|
||||
node = {
|
||||
"user_id": int(sub),
|
||||
"account": str(principal.get("account") or "").strip(),
|
||||
"display_name": str(principal.get("display_name") or "").strip(),
|
||||
"email": str(principal.get("email") or "").strip(),
|
||||
# 对端没带状态就按启用建号(刚从统一身份验过口令的人当然是活的);带了就照它写,
|
||||
# 免得顺带认领到一行时把一个停用的人在这里悄悄救活。
|
||||
"status": 1 if status is None else Status.normalize(status),
|
||||
}
|
||||
if not node["account"]:
|
||||
return None
|
||||
_sync_people(db, [node], {}, SyncStats())
|
||||
db.flush()
|
||||
return db.execute(
|
||||
select(Account).where(Account.hub_user_id == node["user_id"])
|
||||
).scalars().first()
|
||||
|
||||
|
||||
@router.get("/hub/status")
|
||||
def hub_status(request: Request, db: DbSession) -> dict[str, Any]:
|
||||
"""同步与免登的运行态。
|
||||
|
||||
``sso`` 这一段是给人抄进 Hub 后台的:缺哪几项、回调地址是哪一条、落地页在哪。
|
||||
对接文档里"配不齐就等于没开"最坑人的地方就是它不报错,只是安静地不生效。
|
||||
"""
|
||||
payload = org_sync.status_payload(db)
|
||||
payload["sso"] = {
|
||||
"enabled": settings.hub.sso_configured,
|
||||
"missing": _sso_missing(),
|
||||
"appCode": settings.hub.app_code,
|
||||
"portalUrl": settings.hub.portal_base_url,
|
||||
"stateRequired": settings.hub.sso_state_required,
|
||||
**sso_handoff.view(),
|
||||
**sso_handoff.advertised_urls(request),
|
||||
}
|
||||
return ok(payload)
|
||||
|
||||
|
||||
def profile_payload(db, account: Account) -> dict[str, Any]:
|
||||
identity = db.execute(
|
||||
select(AccountIdentity, OrgUnit.name)
|
||||
.join(OrgUnit, OrgUnit.id == AccountIdentity.org_unit_id)
|
||||
.where(AccountIdentity.account_id == account.id)
|
||||
.order_by(AccountIdentity.is_default.desc())
|
||||
.limit(1)
|
||||
).first()
|
||||
return {
|
||||
"id": account.id,
|
||||
"account": account.account,
|
||||
"displayName": account.display_name or account.account,
|
||||
"empCode": account.emp_code,
|
||||
"email": account.email,
|
||||
"telephone": account.telephone,
|
||||
"avatarUrl": account.avatar_url,
|
||||
"orgUnitId": account.org_unit_id,
|
||||
"orgUnitName": account.org_unit_name,
|
||||
"identityOrgName": identity[1] if identity else account.org_unit_name,
|
||||
"positionId": account.position_id,
|
||||
"positionName": account.position.name if account.position else "",
|
||||
"isSystemAdmin": account.is_system_admin,
|
||||
"source": account.source,
|
||||
"sourceLabel": "统一身份" if account.source == "hub" else "本地",
|
||||
"status": account.status,
|
||||
"statusLabel": Status.label(account.status),
|
||||
"lastLoginAt": account.last_login_at.isoformat(sep=" ", timespec="seconds") if account.last_login_at else "",
|
||||
"workLocation": account.work_location,
|
||||
}
|
||||
|
|
@ -0,0 +1,398 @@
|
|||
"""预算控制:立项基线 vs 预算现值、超支拦截规则、成本台账与仪表盘。
|
||||
|
||||
一句话口径:**基线是立项审批通过那一刻的数**,之后不论预算怎么改,基线都不动。
|
||||
只有立项本身重新送审并批准,基线才跟着换版。这条是整个模块的地基——基线如果跟着
|
||||
预算走,编制预算的人就能自己把拦截线抬上去,那还拦什么。
|
||||
|
||||
"预算执行实时对比 / 超支拦截"里真正的"执行"需要**实际成本**(合同收付款、总账凭证),
|
||||
那两块数据源还没接(见 docs/模块规划.md)。当前这一层比的是"预算 vs 立项批准",
|
||||
它是实际成本接进来之后第二层对比的对照物,不是它的替身。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import func, or_, select
|
||||
|
||||
from ..deps import DbSession, PrincipalOf
|
||||
from ..envelope import bad_request, forbidden, ok
|
||||
from ..models import (
|
||||
ApprovalInstance,
|
||||
ApprovalTask,
|
||||
CalcSnapshot,
|
||||
InstanceStatus,
|
||||
Project,
|
||||
Revision,
|
||||
RevisionModule,
|
||||
RevisionStatus,
|
||||
SystemConfig,
|
||||
TaskStatus,
|
||||
)
|
||||
from ..service import biz
|
||||
from ..service.calc.money import ZERO, money_str, to_dec
|
||||
|
||||
router = APIRouter(prefix="/control", tags=["control"])
|
||||
|
||||
CODE_VIEW = "budget:control:view"
|
||||
CODE_EDIT = "budget:control:edit"
|
||||
|
||||
#: 状态色:ok 正常 / near 接近阈值 / over 已超 / none 没有基线
|
||||
STATUS_LABELS = {"none": "无基线", "ok": "未超", "near": "接近阈值", "over": "已超基线",
|
||||
"noBudget": "未编预算"}
|
||||
|
||||
|
||||
def _t(value: datetime | None) -> str:
|
||||
return value.isoformat(sep=" ", timespec="seconds") if value else ""
|
||||
|
||||
|
||||
def _ratio(current, baseline) -> str:
|
||||
base = to_dec(baseline)
|
||||
if base <= 0:
|
||||
return ""
|
||||
return f"{(to_dec(current) / base - 1) * 100:.2f}"
|
||||
|
||||
|
||||
def _status(current, baseline, rate: float) -> str:
|
||||
base = to_dec(baseline)
|
||||
if base <= 0:
|
||||
return "none"
|
||||
value = to_dec(current)
|
||||
if value > base * (1 + rate / 100):
|
||||
return "over"
|
||||
if rate > 0 and value > base * (1 + max(rate - 2, rate * 0.6) / 100):
|
||||
return "near"
|
||||
return "ok"
|
||||
|
||||
|
||||
@router.get("/rules")
|
||||
def get_rules(db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
if not current.permission.can_any((CODE_VIEW, CODE_EDIT)):
|
||||
raise forbidden(f"缺少权限:{CODE_VIEW}")
|
||||
rate, action = biz.budget_control_settings(db)
|
||||
return ok({
|
||||
"rate": f"{rate}",
|
||||
"action": action,
|
||||
"actionLabels": {"block": "拦截送审", "warn": "仅告警"},
|
||||
"baselineNote": "基线取立项审批通过那一版的口径,重新批准立项才会换基线",
|
||||
})
|
||||
|
||||
|
||||
class RulesBody(BaseModel):
|
||||
rate: str = ""
|
||||
action: str = ""
|
||||
|
||||
|
||||
@router.put("/rules")
|
||||
def update_rules(body: RulesBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
if not current.permission.can(CODE_EDIT):
|
||||
raise forbidden(f"缺少权限:{CODE_EDIT}")
|
||||
if body.action and body.action not in ("block", "warn"):
|
||||
raise bad_request("bad_action", "动作只能是 block 或 warn")
|
||||
rate = to_dec(body.rate or 0)
|
||||
if rate < 0 or rate > 100:
|
||||
raise bad_request("bad_rate", "阈值要落在 0~100 之间(0 表示不检查)")
|
||||
wanted = {biz.BUDGET_CONTROL_RATE_CODE: f"{rate}", biz.BUDGET_CONTROL_ACTION_CODE: body.action}
|
||||
rows = {row.code: row for row in db.execute(
|
||||
select(SystemConfig).where(SystemConfig.code.in_(list(wanted)))).scalars().all()}
|
||||
for code, value in wanted.items():
|
||||
if value == "":
|
||||
continue
|
||||
row = rows.get(code)
|
||||
if row is None:
|
||||
db.add(SystemConfig(code=code, name=code, value=value, value_type="number",
|
||||
group="budget", editable=True, remark="预算控制参数"))
|
||||
else:
|
||||
row.value = value
|
||||
db.commit()
|
||||
rate_now, action_now = biz.budget_control_settings(db)
|
||||
return ok({"rate": f"{rate_now}", "action": action_now})
|
||||
|
||||
|
||||
@router.get("/compare")
|
||||
def compare(db: DbSession, current: PrincipalOf, keyword: str = "", status: str = "",
|
||||
onlyMine: bool = False, pageNo: int = 1, pageSize: int = Query(20, ge=1, le=100)
|
||||
) -> dict[str, Any]:
|
||||
"""预算 vs 立项基线。给「预算执行对比」页与仪表盘共用。"""
|
||||
if not current.permission.can(CODE_VIEW):
|
||||
raise forbidden(f"缺少权限:{CODE_VIEW}")
|
||||
from ..service.data_scope import evaluate
|
||||
|
||||
decision = evaluate(db, "project", current.scope)
|
||||
statement = select(Project).where(Project.is_deleted.is_(False))
|
||||
statement = decision.apply_to(statement)
|
||||
if keyword:
|
||||
like = f"%{keyword}%"
|
||||
statement = statement.where(or_(Project.name.like(like), Project.project_no.like(like),
|
||||
Project.customer.like(like)))
|
||||
if onlyMine:
|
||||
from ..models import ProjectMember
|
||||
|
||||
statement = statement.where(or_(
|
||||
Project.creator_id == current.account.id,
|
||||
Project.principal_id == current.account.id,
|
||||
Project.id.in_(select(ProjectMember.project_id).where(
|
||||
ProjectMember.account_id == current.account.id)),
|
||||
))
|
||||
projects = db.execute(statement.order_by(Project.updated_at.desc())).scalars().all()
|
||||
rate, action = biz.budget_control_settings(db)
|
||||
rate_value = float(rate or 0)
|
||||
|
||||
budget_heads = _latest_revisions(db, [row.id for row in projects], RevisionModule.BUDGET)
|
||||
items: list[dict[str, Any]] = []
|
||||
for project in projects:
|
||||
budget = budget_heads.get(project.id)
|
||||
baseline = biz.initiation_baseline(db, project.id)
|
||||
current_values = _budget_totals(db, budget)
|
||||
row_state = _status(current_values.get("contractAmount"), baseline.get("contractAmount"),
|
||||
rate_value) if budget else "noBudget"
|
||||
purchase_state = _status(current_values.get("purchaseAmount"), baseline.get("purchaseInclude"),
|
||||
rate_value) if budget else "noBudget"
|
||||
worst = _worst(row_state, purchase_state)
|
||||
items.append({
|
||||
"id": project.id, "name": project.name, "projectNo": project.project_no,
|
||||
"orgUnitName": project.org_unit_name, "principal": project.principal,
|
||||
"budgetStatus": budget.status if budget else "",
|
||||
"budgetVersion": budget.version if budget else 0,
|
||||
"initiationApprovedAt": baseline.get("approvedAt", ""),
|
||||
"initiationVersion": baseline.get("version", 0),
|
||||
"baseline": {
|
||||
"contractAmount": money_str(baseline.get("contractAmount")),
|
||||
"purchaseAmount": money_str(baseline.get("purchaseInclude")),
|
||||
"grossProfit": money_str(baseline.get("grossProfit")),
|
||||
},
|
||||
"budget": {
|
||||
"contractAmount": money_str(current_values.get("contractAmount")),
|
||||
"purchaseAmount": money_str(current_values.get("purchaseAmount")),
|
||||
"grossProfit": money_str(current_values.get("grossProfit")),
|
||||
},
|
||||
"diff": {
|
||||
"contractRate": _ratio(current_values.get("contractAmount"),
|
||||
baseline.get("contractAmount")),
|
||||
"purchaseRate": _ratio(current_values.get("purchaseAmount"),
|
||||
baseline.get("purchaseInclude")),
|
||||
},
|
||||
"status": worst,
|
||||
"statusLabel": STATUS_LABELS.get(worst, worst),
|
||||
})
|
||||
|
||||
if status:
|
||||
items = [item for item in items if item["status"] == status]
|
||||
# 已超基线的排最前:这一页是给人来处理超支的,不是给人看报表的
|
||||
order = {"over": 0, "near": 1, "noBudget": 2, "ok": 3, "none": 4}
|
||||
items.sort(key=lambda item: (order.get(item["status"], 9), item["projectNo"] or item["name"]))
|
||||
total = len(items)
|
||||
start = (max(pageNo, 1) - 1) * pageSize
|
||||
counts: dict[str, int] = {}
|
||||
for item in items:
|
||||
counts[item["status"]] = counts.get(item["status"], 0) + 1
|
||||
return ok({
|
||||
"items": items[start:start + pageSize], "total": total, "pageNo": pageNo,
|
||||
"pageSize": pageSize,
|
||||
"summary": {"rate": f"{rate}", "action": action, "counts": counts,
|
||||
"checked": len(projects)},
|
||||
"scope": decision.to_dict(),
|
||||
})
|
||||
|
||||
|
||||
def _worst(*statuses: str) -> str:
|
||||
order = ["over", "near", "noBudget", "none", "ok"]
|
||||
for candidate in order:
|
||||
if candidate in statuses:
|
||||
return candidate
|
||||
return "ok"
|
||||
|
||||
|
||||
def _latest_revisions(db, project_ids: list[int], module: str) -> dict[int, Revision]:
|
||||
if not project_ids:
|
||||
return {}
|
||||
rows = db.execute(
|
||||
select(Revision).where(Revision.project_id.in_(project_ids), Revision.module == module,
|
||||
Revision.is_deleted.is_(False)).order_by(Revision.version.desc())
|
||||
).scalars().all()
|
||||
out: dict[int, Revision] = {}
|
||||
for row in rows:
|
||||
out.setdefault(row.project_id, row)
|
||||
return out
|
||||
|
||||
|
||||
def _budget_totals(db, budget: Revision | None) -> dict[str, Any]:
|
||||
"""预算侧现值:读那一版最近的计算快照,不在这儿重算第二遍。"""
|
||||
empty = {"contractAmount": ZERO, "purchaseAmount": ZERO, "grossProfit": ZERO}
|
||||
if budget is None:
|
||||
return empty
|
||||
snapshot = None
|
||||
if budget.snapshot_id:
|
||||
snapshot = db.get(CalcSnapshot, budget.snapshot_id)
|
||||
if snapshot is None:
|
||||
snapshot = db.execute(
|
||||
select(CalcSnapshot).where(CalcSnapshot.revision_id == budget.id)
|
||||
.order_by(CalcSnapshot.id.desc()).limit(1)
|
||||
).scalars().first()
|
||||
payload = biz.snapshot_payload(snapshot)
|
||||
if not payload:
|
||||
return empty
|
||||
profit = payload.get("profit") or {}
|
||||
groups = payload.get("groups") or {}
|
||||
purchase_include = sum((to_dec((bucket or {}).get("include"))
|
||||
for bucket in (groups.get("purchase") or {}).values()), ZERO)
|
||||
return {
|
||||
"contractAmount": to_dec(payload.get("contract_amount") or profit.get("income_total")),
|
||||
"purchaseAmount": purchase_include,
|
||||
"grossProfit": to_dec(profit.get("gross_b")),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/cost-ledger")
|
||||
def cost_ledger(db: DbSession, current: PrincipalOf, keyword: str = "",
|
||||
pageNo: int = 1, pageSize: int = 20) -> dict[str, Any]:
|
||||
"""项目成本台账:每个项目最新预算版本的收入、采购、管理费、毛利。
|
||||
|
||||
数据只从计算快照读,跟工作台、审批看的是同一份口径,不在这里重算。
|
||||
"""
|
||||
if not current.permission.can(CODE_VIEW):
|
||||
raise forbidden(f"缺少权限:{CODE_VIEW}")
|
||||
from ..service.data_scope import evaluate
|
||||
|
||||
decision = evaluate(db, "project", current.scope)
|
||||
statement = select(Project).where(Project.is_deleted.is_(False))
|
||||
statement = decision.apply_to(statement)
|
||||
if keyword:
|
||||
like = f"%{keyword}%"
|
||||
statement = statement.where(or_(Project.name.like(like), Project.project_no.like(like)))
|
||||
total = db.execute(select(func.count()).select_from(statement.subquery())).scalar() or 0
|
||||
rows = db.execute(statement.order_by(Project.contract_amount.desc())
|
||||
.offset((max(pageNo, 1) - 1) * pageSize).limit(pageSize)).scalars().all()
|
||||
heads = _latest_revisions(db, [row.id for row in rows], RevisionModule.BUDGET)
|
||||
|
||||
items = []
|
||||
for project in rows:
|
||||
budget = heads.get(project.id)
|
||||
payload = {}
|
||||
if budget is not None:
|
||||
snapshot = db.get(CalcSnapshot, budget.snapshot_id) if budget.snapshot_id else None
|
||||
payload = biz.snapshot_payload(snapshot)
|
||||
profit = payload.get("profit") or {}
|
||||
manage = payload.get("manage") or {}
|
||||
fund = payload.get("fund_plan") or {}
|
||||
items.append({
|
||||
"id": project.id, "name": project.name, "projectNo": project.project_no,
|
||||
"principal": project.principal, "orgUnitName": project.org_unit_name,
|
||||
"budgetVersion": budget.version if budget else 0,
|
||||
"budgetStatus": budget.status if budget else "",
|
||||
"incomeTotal": money_str(profit.get("income_total")),
|
||||
"purchaseTotal": money_str(profit.get("purchase_total")),
|
||||
"manageTotal": money_str(manage.get("total")),
|
||||
"grossProfit": money_str(profit.get("gross_b")),
|
||||
"grossProfitRate": _rate_text(profit.get("gross_b_rate")),
|
||||
"contributionRate": _rate_text(profit.get("contribution_rate")),
|
||||
"advancePeak": money_str(fund.get("peak_value")),
|
||||
"capitalInterest": money_str(fund.get("interest_total")),
|
||||
"snapshotAt": _t(budget.updated_at) if budget else "",
|
||||
})
|
||||
return ok({"items": items, "total": total, "pageNo": pageNo, "pageSize": pageSize,
|
||||
"scope": decision.to_dict()})
|
||||
|
||||
|
||||
def _rate_text(block: Any) -> str:
|
||||
if not isinstance(block, dict):
|
||||
return ""
|
||||
if block.get("defined") is False:
|
||||
return "未定义"
|
||||
value = block.get("value")
|
||||
return "" if value is None else f"{value}"
|
||||
|
||||
|
||||
@router.get("/dashboard")
|
||||
def dashboard(db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
"""仪表盘:立项漏斗 + 预算覆盖 + 超基线数 + 我的待办。
|
||||
|
||||
刻意只数"能数得准的":合同额、毛利、垫资这些来自计算快照,立项/预算状态来自
|
||||
版本表。实际支出(预算执行率)要等合同收付款与总账接进来,这里不猜。
|
||||
"""
|
||||
if not current.permission.can(CODE_VIEW):
|
||||
raise forbidden(f"缺少权限:{CODE_VIEW}")
|
||||
from ..service.data_scope import evaluate
|
||||
from ..models import ProjectStage
|
||||
|
||||
decision = evaluate(db, "project", current.scope)
|
||||
base = decision.apply_to(select(Project.id).where(Project.is_deleted.is_(False)))
|
||||
project_ids = [row[0] for row in db.execute(base).all()]
|
||||
|
||||
def count_by(module: str, statuses: tuple[str, ...] = ()) -> int:
|
||||
statement = select(func.count(Revision.id)).where(
|
||||
Revision.module == module, Revision.is_deleted.is_(False),
|
||||
Revision.project_id.in_(project_ids or [-1]))
|
||||
if statuses:
|
||||
statement = statement.where(Revision.status.in_(statuses))
|
||||
return db.execute(statement).scalar() or 0
|
||||
|
||||
approved_projects = db.execute(
|
||||
select(func.count(func.distinct(Revision.project_id))).where(
|
||||
Revision.module == RevisionModule.ESTIMATE,
|
||||
Revision.status == RevisionStatus.APPROVED,
|
||||
Revision.is_deleted.is_(False),
|
||||
Revision.project_id.in_(project_ids or [-1]))
|
||||
).scalar() or 0
|
||||
budget_projects = db.execute(
|
||||
select(func.count(func.distinct(Revision.project_id))).where(
|
||||
Revision.module == RevisionModule.BUDGET, Revision.is_deleted.is_(False),
|
||||
Revision.project_id.in_(project_ids or [-1]))
|
||||
).scalar() or 0
|
||||
totals = db.execute(
|
||||
select(func.coalesce(func.sum(Project.contract_amount), 0),
|
||||
func.coalesce(func.sum(Project.gross_profit), 0),
|
||||
func.coalesce(func.sum(Project.advance_peak_value), 0))
|
||||
.where(Project.id.in_(project_ids or [-1]), Project.is_deleted.is_(False))
|
||||
).one()
|
||||
|
||||
compare_page = compare(db, current, status="over", pageNo=1, pageSize=10)
|
||||
over = compare_page["data"]
|
||||
|
||||
todo = 0
|
||||
if _has_todo_permission(current):
|
||||
todo = db.execute(
|
||||
select(func.count(ApprovalTask.id))
|
||||
.join(ApprovalInstance, ApprovalTask.instance_id == ApprovalInstance.id)
|
||||
.where(ApprovalTask.assignee_id == current.account.id,
|
||||
ApprovalTask.status == TaskStatus.PENDING,
|
||||
ApprovalInstance.status == InstanceStatus.REVIEWING)
|
||||
).scalar() or 0
|
||||
|
||||
stages = db.execute(
|
||||
select(Project.stage, func.count(Project.id))
|
||||
.where(Project.id.in_(project_ids or [-1]), Project.is_deleted.is_(False))
|
||||
.group_by(Project.stage)
|
||||
).all()
|
||||
|
||||
return ok({
|
||||
"projects": len(project_ids),
|
||||
"initiation": {
|
||||
"reviewing": count_by(RevisionModule.ESTIMATE, (RevisionStatus.REVIEWING,)),
|
||||
"approved": int(approved_projects),
|
||||
"approvedRate": f"{(approved_projects / len(project_ids) * 100):.1f}" if project_ids else "0",
|
||||
},
|
||||
"budget": {
|
||||
"draft": count_by(RevisionModule.BUDGET, (RevisionStatus.DRAFT,)),
|
||||
"reviewing": count_by(RevisionModule.BUDGET, (RevisionStatus.REVIEWING,)),
|
||||
"approved": count_by(RevisionModule.BUDGET, (RevisionStatus.APPROVED,)),
|
||||
"covered": int(budget_projects),
|
||||
"coverageRate": f"{(budget_projects / approved_projects * 100):.1f}" if approved_projects else "0",
|
||||
},
|
||||
"amounts": {
|
||||
"contractTotal": money_str(totals[0]), "grossProfitTotal": money_str(totals[1]),
|
||||
"advancePeakTotal": money_str(totals[2]),
|
||||
},
|
||||
"overBudget": {"total": over["total"], "items": over["items"]},
|
||||
"todo": int(todo),
|
||||
"stageFlow": [{"stage": stage, "label": ProjectStage.LABELS.get(stage, str(stage)),
|
||||
"count": count} for stage, count in sorted(stages)],
|
||||
"scope": decision.to_dict(),
|
||||
})
|
||||
|
||||
|
||||
def _has_todo_permission(current: PrincipalOf) -> bool:
|
||||
return current.permission.can_any(("workbench:todo", "approval:monitor:view"))
|
||||
|
|
@ -0,0 +1,307 @@
|
|||
"""数据字典接口:前端取值的读接口 + 「系统 → 数据字典」的维护接口。
|
||||
|
||||
读写分开挂在不同前缀下:``/dicts`` 只要求登录(任何页面都要拉取值),
|
||||
``/system/dicts`` 要 ``system:dict:view`` / ``system:dict:edit``。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from .. import dicts as store
|
||||
from ..deps import DbSession, PrincipalOf
|
||||
from ..envelope import conflict, forbidden, not_found, ok
|
||||
from ..models import DictItem, DictSource, DictType, DictValueType
|
||||
|
||||
router = APIRouter(prefix="/dicts", tags=["dicts"])
|
||||
admin = APIRouter(prefix="/system/dicts", tags=["system"])
|
||||
|
||||
#: 字典编码要能当 JS 属性名用(bootstrap 里直接 enums.projectStage),
|
||||
#: 所以钉成 camelCase;一旦建了就别再改,前端是按它取值的。
|
||||
CODE_RE = re.compile(r"^[a-z][A-Za-z0-9]{1,63}$")
|
||||
|
||||
|
||||
def _need(db, current: PrincipalOf, code: str) -> None:
|
||||
if not current.permission.can(code):
|
||||
raise forbidden(f"缺少权限:{code}")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 读:给前端下拉框
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("")
|
||||
def dict_data(db: DbSession, current: PrincipalOf, types: str = "") -> dict[str, Any]:
|
||||
"""按需取几类字典的取值;``types`` 留空给全量。
|
||||
|
||||
全量已经随 ``/bootstrap`` 下发过一次,这条是给懒加载和自定义字典用的,
|
||||
所以只要登录就能读——下拉框取值不是敏感信息,权限管的是能不能改。
|
||||
"""
|
||||
codes = [code for code in (part.strip() for part in types.split(",")) if code]
|
||||
return ok(store.export(db, codes or None))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 维护:字典类型
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _type_view(row: DictType, total: int, usable: int) -> dict[str, Any]:
|
||||
return {
|
||||
"id": row.id, "code": row.code, "name": row.name, "group": row.group,
|
||||
"valueType": row.value_type, "source": row.source,
|
||||
"sourceLabel": DictSource.LABELS.get(row.source, row.source),
|
||||
"builtin": row.source == DictSource.SYSTEM,
|
||||
# TINYINT 存布尔,直接回给前端是 1/0,Toggle 组件要的是真布尔
|
||||
"enabled": bool(row.enabled), "remark": row.remark,
|
||||
"itemCount": total, "enabledCount": usable,
|
||||
"codeDefined": row.code in store.SPECS,
|
||||
}
|
||||
|
||||
|
||||
@admin.get("")
|
||||
def list_types(db: DbSession, current: PrincipalOf, keyword: str = "",
|
||||
group: str = "") -> dict[str, Any]:
|
||||
_need(db, current, "system:dict:view")
|
||||
statement = select(DictType).where(DictType.is_deleted.is_(False))
|
||||
if group:
|
||||
statement = statement.where(DictType.group == group)
|
||||
if keyword:
|
||||
like = f"%{keyword}%"
|
||||
statement = statement.where(DictType.name.like(like) | DictType.code.like(like))
|
||||
rows = db.execute(statement.order_by(DictType.group, DictType.id)).scalars().all()
|
||||
|
||||
counts = dict(db.execute(
|
||||
select(DictItem.dict_type_id, func.count())
|
||||
.where(DictItem.is_deleted.is_(False)).group_by(DictItem.dict_type_id)).all())
|
||||
enabled_counts = dict(db.execute(
|
||||
select(DictItem.dict_type_id, func.count())
|
||||
.where(DictItem.is_deleted.is_(False), DictItem.enabled.is_(True))
|
||||
.group_by(DictItem.dict_type_id)).all())
|
||||
return ok([_type_view(row, counts.get(row.id, 0), enabled_counts.get(row.id, 0))
|
||||
for row in rows])
|
||||
|
||||
|
||||
@admin.get("/groups")
|
||||
def list_groups(db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
"""维护页的分组筛选。代码字典自带分组,自建字典自己填,这里按库里的去重。"""
|
||||
_need(db, current, "system:dict:view")
|
||||
rows = db.execute(select(DictType.group).where(DictType.is_deleted.is_(False))
|
||||
.distinct()).scalars().all()
|
||||
return ok(sorted({row or "common" for row in rows}))
|
||||
|
||||
|
||||
class DictTypeBody(BaseModel):
|
||||
code: str = Field(min_length=1, max_length=64)
|
||||
name: str = Field(min_length=1, max_length=128)
|
||||
group: str = "common"
|
||||
valueType: str = DictValueType.STRING
|
||||
enabled: bool = True
|
||||
remark: str = ""
|
||||
|
||||
|
||||
@admin.post("")
|
||||
def create_type(body: DictTypeBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_need(db, current, "system:dict:edit")
|
||||
code = body.code.strip()
|
||||
if not CODE_RE.match(code):
|
||||
raise conflict("invalid_code", "字典编码只能用 camelCase 字母数字,且以字母开头")
|
||||
if code in store.SPECS:
|
||||
raise conflict("reserved_code", f"{code} 是代码内置字典,换一个编码或到列表里改它")
|
||||
if db.execute(select(DictType).where(DictType.code == code)).scalars().first():
|
||||
raise conflict("duplicated_code", "字典编码已存在")
|
||||
if body.valueType not in DictValueType.LABELS:
|
||||
raise conflict("invalid_value_type", "取值类型只能是文本或整数")
|
||||
|
||||
row = DictType(code=code, name=body.name.strip(), group=(body.group or "common").strip(),
|
||||
value_type=body.valueType, source=DictSource.CUSTOM,
|
||||
enabled=body.enabled, remark=body.remark)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
store.invalidate()
|
||||
return ok({"id": row.id})
|
||||
|
||||
|
||||
@admin.put("/{type_id}")
|
||||
def update_type(type_id: int, body: DictTypeBody, db: DbSession,
|
||||
current: PrincipalOf) -> dict[str, Any]:
|
||||
_need(db, current, "system:dict:edit")
|
||||
row = db.get(DictType, type_id)
|
||||
if row is None or row.is_deleted:
|
||||
raise not_found("字典不存在")
|
||||
if row.source == DictSource.SYSTEM:
|
||||
# 内置字典的编码与取值类型是代码契约的一部分:前端按编码取值、按类型换算,
|
||||
# 改了就对不上,所以只让改名字、分组、说明和启停。
|
||||
if body.valueType != row.value_type:
|
||||
raise conflict("builtin_type", "代码内置字典的取值类型不能改")
|
||||
elif body.code.strip() != row.code:
|
||||
raise conflict("immutable_code", "字典编码已被前端引用,不能改")
|
||||
if body.valueType not in DictValueType.LABELS:
|
||||
raise conflict("invalid_value_type", "取值类型只能是文本或整数")
|
||||
|
||||
row.name = body.name.strip()
|
||||
row.group = (body.group or "common").strip()
|
||||
row.enabled = body.enabled
|
||||
row.remark = body.remark
|
||||
db.commit()
|
||||
store.invalidate()
|
||||
return ok({"id": row.id})
|
||||
|
||||
|
||||
@admin.delete("/{type_id}")
|
||||
def delete_type(type_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_need(db, current, "system:dict:edit")
|
||||
row = db.get(DictType, type_id)
|
||||
if row is None or row.is_deleted:
|
||||
raise not_found("字典不存在")
|
||||
if row.source == DictSource.SYSTEM:
|
||||
raise conflict("builtin_type", "代码内置字典不能删除;整类不想用可以停用")
|
||||
row.is_deleted = True
|
||||
for item in db.execute(select(DictItem).where(DictItem.dict_type_id == row.id,
|
||||
DictItem.is_deleted.is_(False))
|
||||
).scalars().all():
|
||||
item.is_deleted = True
|
||||
db.commit()
|
||||
store.invalidate()
|
||||
return ok({"deleted": True})
|
||||
|
||||
|
||||
@admin.post("/{code}/reset")
|
||||
def reset_type(code: str, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
"""把代码内置字典恢复成代码定义:改名改乱了、误停了几项,一键回来。"""
|
||||
_need(db, current, "system:dict:edit")
|
||||
try:
|
||||
count = store.reset_items(db, code)
|
||||
except ValueError as exc:
|
||||
raise conflict("not_builtin", str(exc)) from None
|
||||
db.commit()
|
||||
store.invalidate() # 提交后再失效,免得把提交前的快照重新装回缓存
|
||||
return ok({"code": code, "count": count})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 维护:字典条目
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@admin.get("/{code}/items")
|
||||
def list_items(code: str, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_need(db, current, "system:dict:view")
|
||||
rows = store.items(db, code, include_disabled=True)
|
||||
spec = store.SPECS.get(code)
|
||||
return ok({
|
||||
"code": code,
|
||||
"defined": spec is not None,
|
||||
"codeValues": [str(value) for value, _ in spec.items] if spec else [],
|
||||
"items": rows,
|
||||
})
|
||||
|
||||
|
||||
class DictItemBody(BaseModel):
|
||||
#: 整数型字典的前端会把 3 原样传上来,这里收 str|int,落库前统一折成字符串;
|
||||
#: 空值由 :func:`normalize_value` 挡,min_length 对整数用不上
|
||||
value: str | int
|
||||
label: str = Field(min_length=1, max_length=128)
|
||||
sort: int = 100
|
||||
enabled: bool = True
|
||||
tag: str = ""
|
||||
remark: str = ""
|
||||
|
||||
|
||||
def _type_or_404(db: DbSession, code: str) -> DictType:
|
||||
row = db.execute(select(DictType).where(DictType.code == code,
|
||||
DictType.is_deleted.is_(False))
|
||||
).scalars().first()
|
||||
if row is None:
|
||||
raise not_found("字典不存在")
|
||||
return row
|
||||
|
||||
|
||||
@admin.post("/{code}/items")
|
||||
def create_item(code: str, body: DictItemBody, db: DbSession,
|
||||
current: PrincipalOf) -> dict[str, Any]:
|
||||
_need(db, current, "system:dict:edit")
|
||||
parent = _type_or_404(db, code)
|
||||
value = _normalized(parent, body.value)
|
||||
if db.execute(select(DictItem).where(DictItem.dict_type_id == parent.id,
|
||||
DictItem.value == value,
|
||||
DictItem.is_deleted.is_(False))
|
||||
).scalars().first():
|
||||
raise conflict("duplicated_value", f"取值 {value} 已存在")
|
||||
row = DictItem(dict_type_id=parent.id, value=value, label=body.label.strip(),
|
||||
sort=body.sort, enabled=body.enabled, tag=body.tag.strip(),
|
||||
builtin=False, remark=body.remark)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
store.invalidate()
|
||||
return ok({"id": row.id})
|
||||
|
||||
|
||||
@admin.put("/items/{item_id}")
|
||||
def update_item(item_id: int, body: DictItemBody, db: DbSession,
|
||||
current: PrincipalOf) -> dict[str, Any]:
|
||||
_need(db, current, "system:dict:edit")
|
||||
row = db.get(DictItem, item_id)
|
||||
if row is None or row.is_deleted:
|
||||
raise not_found("字典项不存在")
|
||||
parent = db.get(DictType, row.dict_type_id)
|
||||
if parent is None:
|
||||
raise not_found("字典不存在")
|
||||
|
||||
value = row.value
|
||||
if str(body.value).strip() != row.value:
|
||||
if row.builtin:
|
||||
raise conflict("builtin_item",
|
||||
"代码内置取值不能改,业务代码按它判分支;要改名字请改「显示名称」")
|
||||
value = _normalized(parent, body.value)
|
||||
clash = db.execute(select(DictItem).where(
|
||||
DictItem.dict_type_id == parent.id, DictItem.value == value,
|
||||
DictItem.is_deleted.is_(False), DictItem.id != row.id)).scalars().first()
|
||||
if clash:
|
||||
raise conflict("duplicated_value", f"取值 {value} 已存在")
|
||||
|
||||
row.value, row.label, row.sort = value, body.label.strip(), body.sort
|
||||
row.enabled, row.tag, row.remark = body.enabled, body.tag.strip(), body.remark
|
||||
db.commit()
|
||||
store.invalidate()
|
||||
return ok({"id": row.id})
|
||||
|
||||
|
||||
@admin.delete("/items/{item_id}")
|
||||
def delete_item(item_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_need(db, current, "system:dict:edit")
|
||||
row = db.get(DictItem, item_id)
|
||||
if row is None or row.is_deleted:
|
||||
raise not_found("字典项不存在")
|
||||
if row.builtin:
|
||||
raise conflict("builtin_item", "代码内置取值不能删除,从下拉框里摘掉请改用「停用」")
|
||||
row.is_deleted = True
|
||||
db.commit()
|
||||
store.invalidate()
|
||||
return ok({"deleted": True})
|
||||
|
||||
|
||||
@admin.post("/items/{item_id}/toggle")
|
||||
def toggle_item(item_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
"""界面上那枚开关走这条:只翻启停,不用把整份表单提交一遍。"""
|
||||
_need(db, current, "system:dict:edit")
|
||||
row = db.get(DictItem, item_id)
|
||||
if row is None or row.is_deleted:
|
||||
raise not_found("字典项不存在")
|
||||
row.enabled = not row.enabled
|
||||
db.commit()
|
||||
store.invalidate()
|
||||
return ok({"id": row.id, "enabled": bool(row.enabled)})
|
||||
|
||||
|
||||
def _normalized(parent: DictType, value: str) -> str:
|
||||
try:
|
||||
return store.normalize_value(parent.value_type, value)
|
||||
except ValueError as exc:
|
||||
raise conflict("invalid_value", str(exc)) from None
|
||||
|
|
@ -0,0 +1,548 @@
|
|||
"""项目立项与项目预算:版本、明细、计算预览、送审。
|
||||
|
||||
路由形状固定成 ``/finance/{module}/projects/{project_id}/...``,立项与预算共用一套代码,
|
||||
两个模块只是换了 ``module`` 参数——这正好反映了两者共用同一个利润内核的事实。
|
||||
内部编码仍叫 ``estimate``:它是 ``biz_revision.module``、审批流程的 ``business_module``
|
||||
与数据权限模块键的取值,改这个字符串要连着改库里的历史数据,换来的只是少一个词;
|
||||
界面上则统一叫**项目立项**,不再出现"概算"。
|
||||
|
||||
两道闸口在这里:
|
||||
1. 立项送审前必须把立项表的必填项填完(``submit`` 里的 ``initiation_missing_fields``)。
|
||||
2. 预算侧"第一次生成版本"必须立项已批准——拦在 ``biz.get_or_create_revision`` 里,
|
||||
本文件另外提供显式的 ``generate`` 接口,界面上点「生成预算」才调它。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .. import dicts as dict_store
|
||||
from ..deps import DbSession, PrincipalOf, assert_project_visible
|
||||
from ..envelope import bad_request, conflict, forbidden, not_found, ok
|
||||
from ..models import (
|
||||
Account,
|
||||
CalcSnapshot,
|
||||
Project,
|
||||
ProjectStage,
|
||||
Revision,
|
||||
RevisionModule,
|
||||
RevisionStatus,
|
||||
to_decimal,
|
||||
)
|
||||
from ..service import biz
|
||||
from ..service.approval import engine as approval_engine
|
||||
|
||||
router = APIRouter(prefix="/finance", tags=["finance"])
|
||||
|
||||
MODULES = {RevisionModule.ESTIMATE: "项目立项", RevisionModule.BUDGET: "项目预算"}
|
||||
|
||||
LINE_KEYS = {
|
||||
"income", "cost", "other",
|
||||
"income_plan", "purchase", "pay_plan", "manage", "other_cost", "fund_month",
|
||||
}
|
||||
|
||||
|
||||
class LineBody(BaseModel):
|
||||
data: dict[str, Any]
|
||||
|
||||
|
||||
class LinesBody(BaseModel):
|
||||
rows: list[dict[str, Any]] = Field(default_factory=list)
|
||||
|
||||
|
||||
class SubmitBody(BaseModel):
|
||||
comment: str = ""
|
||||
selfSelected: dict[str, list[int]] = Field(default_factory=dict)
|
||||
|
||||
|
||||
class InitiationBody(BaseModel):
|
||||
"""立项表(= 项目信息表)的一次保存。``None`` 表示这一栏没提交,不是"清空"。"""
|
||||
|
||||
name: str | None = None
|
||||
projectNo: str | None = None
|
||||
type: int | None = None
|
||||
underwrittenMode: int | None = None
|
||||
certainty: int | None = None
|
||||
industryScene: int | None = None
|
||||
industrySceneDesc: str | None = None
|
||||
customer: str | None = None
|
||||
terminalCustomer: str | None = None
|
||||
valueRisk: str | None = None
|
||||
principalId: int | None = None
|
||||
contractTime: str | None = None
|
||||
bidsTime: str | None = None
|
||||
isSecond: int | None = None
|
||||
isHuizhiBid: int | None = None
|
||||
calculationCollection: str | None = None
|
||||
stage: int | None = None
|
||||
saleStage: int | None = None
|
||||
stageRemark: str | None = None
|
||||
planStart: str | None = None
|
||||
planEnd: str | None = None
|
||||
contractAmount: str | None = None
|
||||
grossProfit: str | None = None
|
||||
grossProfitRate: str | None = None
|
||||
huizhiAmount: str | None = None
|
||||
huazhiAmount: str | None = None
|
||||
h3cAmount: str | None = None
|
||||
otherProductAmount: str | None = None
|
||||
advanceInterestRate: str | None = None
|
||||
header: dict[str, Any] | None = None
|
||||
|
||||
|
||||
def _module_or_404(module: str) -> str:
|
||||
if module not in MODULES:
|
||||
raise not_found(f"未知的业务模块:{module}")
|
||||
return module
|
||||
|
||||
|
||||
def _permission(module: str, action: str) -> str:
|
||||
return f"project:{module}:{action}"
|
||||
|
||||
|
||||
def _revision_context(db, current: PrincipalOf, project_id: int, module: str, *,
|
||||
write: bool = False) -> tuple[Project, Revision]:
|
||||
project = assert_project_visible(db, current, project_id, module=module)
|
||||
action = "edit" if write else "view"
|
||||
if not current.permission.can(_permission(module, action)):
|
||||
raise forbidden(f"缺少权限:{_permission(module, action)}")
|
||||
revision = biz.get_or_create_revision(db, project_id, module, current.account)
|
||||
return project, revision
|
||||
|
||||
|
||||
@router.get("/{module}/projects/{project_id}/revision")
|
||||
def get_revision(module: str, project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
"""一个版本的完整视图:明细 + 最新快照 + 审批状态 + 立项表。页面首屏只要这一个请求。"""
|
||||
_module_or_404(module)
|
||||
project, revision = _revision_context(db, current, project_id, module)
|
||||
lines = biz.revision_lines(db, revision)
|
||||
snapshot = biz.current_snapshot(db, revision)
|
||||
payload = biz.snapshot_payload(snapshot)
|
||||
|
||||
versions = db.execute(
|
||||
select(Revision).where(Revision.project_id == project_id, Revision.module == module,
|
||||
Revision.is_deleted.is_(False)).order_by(Revision.version.desc())
|
||||
).scalars().all()
|
||||
|
||||
return ok({
|
||||
"module": module,
|
||||
"moduleLabel": MODULES[module],
|
||||
"project": {"id": project.id, "name": project.name, "projectNo": project.project_no,
|
||||
"stage": project.stage, "stageLabel": project.stage_label,
|
||||
"advanceInterestRate": f"{project.advance_interest_rate}"},
|
||||
"initiation": _initiation_view(db, project, revision, module),
|
||||
"revision": _revision_view(db, revision),
|
||||
"versions": [_revision_view(db, row) for row in versions],
|
||||
"lines": {key: [biz.serialize_line(row) for row in rows] for key, rows in lines.items()},
|
||||
"snapshot": {
|
||||
"id": snapshot.id if snapshot else None,
|
||||
"calcVersion": snapshot.calc_version if snapshot else "",
|
||||
"createdAt": snapshot.created_at.isoformat(sep=" ", timespec="seconds") if snapshot else "",
|
||||
"payload": payload,
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 立项表:一张能存草稿的项目信息表
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: 立项表上要让前端读到、也能写回的列
|
||||
INITIATION_FIELDS = (
|
||||
"project_no", "name", "type", "underwritten_mode", "certainty", "industry_scene",
|
||||
"industry_scene_desc", "customer", "terminal_customer", "value_risk", "principal",
|
||||
"principal_id", "contract_time", "bids_time", "is_second", "is_huizhi_bid",
|
||||
"calculation_collection", "stage", "sale_stage", "stage_remark", "plan_start", "plan_end",
|
||||
"contract_amount", "gross_profit", "gross_profit_rate", "huizhi_amount", "huazhi_amount",
|
||||
"h3c_amount", "other_product_amount", "advance_interest_rate", "org_unit_name",
|
||||
)
|
||||
|
||||
#: 日期列:回给前端一律折成 YYYY-MM-DD,带 T00:00:00 的字符串日期输入框回填不进去
|
||||
DATE_FIELDS = ("contract_time", "bids_time", "plan_start", "plan_end")
|
||||
|
||||
#: 表头里允许前端写的键(合同名称、解决方案协同…),别的键只读
|
||||
HEADER_FIELDS = ("contract_name", "resolve_plan_synergy", "income_detail_attr",
|
||||
"cost_detail_attr", "remark")
|
||||
|
||||
|
||||
def _initiation_view(db: Session, project: Project, revision: Revision, module: str) -> dict[str, Any]:
|
||||
data: dict[str, Any] = {}
|
||||
for column in INITIATION_FIELDS:
|
||||
value = getattr(project, column, None)
|
||||
if column in DATE_FIELDS:
|
||||
data[column] = value.date().isoformat() if isinstance(value, datetime) else (
|
||||
value.isoformat() if hasattr(value, "isoformat") else "")
|
||||
elif isinstance(value, Decimal):
|
||||
data[column] = f"{value}"
|
||||
else:
|
||||
data[column] = value if value is not None else ""
|
||||
data.update({
|
||||
"id": project.id,
|
||||
"orgUnitId": project.org_unit_id,
|
||||
"typeLabel": dict_store.label(db, "projectType", project.type, ""),
|
||||
"underwrittenModeLabel": dict_store.label(db, "underwrittenMode", project.underwritten_mode, ""),
|
||||
"certaintyLabel": dict_store.label(db, "certainty", project.certainty, ""),
|
||||
"industrySceneLabel": dict_store.label(db, "industryScene", project.industry_scene, ""),
|
||||
"saleStageLabel": dict_store.label(db, "saleStage", project.sale_stage, "未填写"),
|
||||
"stageLabel": project.stage_label,
|
||||
"isSecondLabel": dict_store.label(db, "yesNo", project.is_second, ""),
|
||||
"isHuizhiBidLabel": dict_store.label(db, "yesNo", project.is_huizhi_bid, ""),
|
||||
"source": project.source,
|
||||
# 送审前要拦的必填项:草稿不拦,界面上用它把缺的栏标出来
|
||||
"missingRequired": biz.initiation_missing_fields(project)
|
||||
if module == RevisionModule.ESTIMATE else [],
|
||||
# 有测算明细时这几个金额由计算投影覆盖,表单里就该显示成"跟着测算走"
|
||||
"amountDrivenByLines": bool(revision.snapshot_id),
|
||||
"header": biz.header_of(revision),
|
||||
})
|
||||
return data
|
||||
|
||||
|
||||
def _parse_date(column: str, text: str):
|
||||
from .projects import _date, _datetime
|
||||
|
||||
if not text:
|
||||
return None
|
||||
if column in ("contract_time", "bids_time"):
|
||||
return _datetime(text)
|
||||
return _date(text)
|
||||
|
||||
|
||||
@router.get("/{module}/projects/{project_id}/initiation")
|
||||
def get_initiation(module: str, project_id: int, db: DbSession,
|
||||
current: PrincipalOf) -> dict[str, Any]:
|
||||
_module_or_404(module)
|
||||
project, revision = _revision_context(db, current, project_id, module)
|
||||
return ok({"initiation": _initiation_view(db, project, revision, module),
|
||||
"state": biz.initiation_state(db, project_id)})
|
||||
|
||||
|
||||
@router.put("/{module}/projects/{project_id}/initiation")
|
||||
def save_initiation(module: str, project_id: int, body: InitiationBody, db: DbSession,
|
||||
current: PrincipalOf) -> dict[str, Any]:
|
||||
"""保存立项表(项目信息)。
|
||||
|
||||
这条接口**只保存、不送审**,也不卡必填:立项表就是一张能反复存草稿的表,
|
||||
"录到一半"是常态。必填在 ``submit`` 里统一校验。
|
||||
"""
|
||||
_module_or_404(module)
|
||||
project, revision = _revision_context(db, current, project_id, module, write=True)
|
||||
for text, column in (
|
||||
(body.name, "name"), (body.customer, "customer"), (body.terminalCustomer, "terminal_customer"),
|
||||
(body.valueRisk, "value_risk"), (body.calculationCollection, "calculation_collection"),
|
||||
(body.stageRemark, "stage_remark"), (body.industrySceneDesc, "industry_scene_desc"),
|
||||
(body.projectNo, "project_no"),
|
||||
):
|
||||
if text is not None:
|
||||
setattr(project, column, text if column == "name" else text.strip())
|
||||
for value, column in (
|
||||
(body.type, "type"), (body.underwrittenMode, "underwritten_mode"), (body.certainty, "certainty"),
|
||||
(body.industryScene, "industry_scene"), (body.isSecond, "is_second"),
|
||||
(body.isHuizhiBid, "is_huizhi_bid"), (body.saleStage, "sale_stage"),
|
||||
(body.principalId, "principal_id"),
|
||||
):
|
||||
if value is not None:
|
||||
setattr(project, column, value)
|
||||
if body.stage in ProjectStage.LABELS:
|
||||
project.stage = body.stage
|
||||
for text, column in (
|
||||
(body.contractTime, "contract_time"), (body.bidsTime, "bids_time"),
|
||||
(body.planStart, "plan_start"), (body.planEnd, "plan_end"),
|
||||
):
|
||||
if text is not None:
|
||||
setattr(project, column, _parse_date(column, text))
|
||||
for text, column in (
|
||||
(body.contractAmount, "contract_amount"), (body.grossProfit, "gross_profit"),
|
||||
(body.grossProfitRate, "gross_profit_rate"), (body.huizhiAmount, "huizhi_amount"),
|
||||
(body.huazhiAmount, "huazhi_amount"), (body.h3cAmount, "h3c_amount"),
|
||||
(body.otherProductAmount, "other_product_amount"),
|
||||
(body.advanceInterestRate, "advance_interest_rate"),
|
||||
):
|
||||
if text not in (None, ""):
|
||||
setattr(project, column, to_decimal(text))
|
||||
if body.principalId:
|
||||
owner = db.get(Account, body.principalId)
|
||||
if owner is not None:
|
||||
project.principal = owner.display_name or owner.account
|
||||
biz.sync_owner_member(db, project)
|
||||
if body.header:
|
||||
biz.save_header(revision, body.header)
|
||||
db.commit()
|
||||
return ok({"initiation": _initiation_view(db, project, revision, module)})
|
||||
|
||||
|
||||
@router.post("/budget/projects/{project_id}/generate")
|
||||
def generate_budget(project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
"""立项批准后,按批准那一版生成预算草稿版本。
|
||||
|
||||
这是"预算数据从哪来"的唯一入口:界面上点「按立项生成预算」才调它,
|
||||
工作台不会偷偷替人建版本。
|
||||
"""
|
||||
project = assert_project_visible(db, current, project_id, module=RevisionModule.BUDGET)
|
||||
if not current.permission.can("project:budget:edit"):
|
||||
raise forbidden("缺少权限:project:budget:edit")
|
||||
result = biz.generate_budget_from_initiation(db, project, current.account)
|
||||
db.commit()
|
||||
return ok({
|
||||
"revision": _revision_view(db, result["revision"]),
|
||||
"copied": result["copied"],
|
||||
"skippedOtherLines": result["skippedOtherLines"],
|
||||
"note": result["note"],
|
||||
})
|
||||
|
||||
|
||||
@router.get("/{module}/projects/{project_id}/gate")
|
||||
def gate(module: str, project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
"""给列表页与按钮用的一句回答:这个项目现在能不能编预算、进展到哪一步。"""
|
||||
_module_or_404(module)
|
||||
assert_project_visible(db, current, project_id, module=module)
|
||||
return ok(biz.initiation_state(db, project_id))
|
||||
|
||||
|
||||
def _revision_view(db: Session, row: Revision) -> dict[str, Any]:
|
||||
return {
|
||||
"id": row.id, "version": row.version, "status": row.status,
|
||||
"statusLabel": dict_store.label(db, "revisionStatus", row.status, row.status),
|
||||
"editable": row.status in RevisionStatus.EDITABLE,
|
||||
"title": row.title, "basedOnId": row.based_on_id, "snapshotId": row.snapshot_id,
|
||||
"calcVersion": row.calc_version, "creatorName": row.creator_name,
|
||||
"header": biz.header_of(row),
|
||||
"submittedAt": row.submitted_at.isoformat(sep=" ", timespec="seconds") if row.submitted_at else "",
|
||||
"decidedAt": row.decided_at.isoformat(sep=" ", timespec="seconds") if row.decided_at else "",
|
||||
"createdAt": row.created_at.isoformat(sep=" ", timespec="seconds"),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{module}/projects/{project_id}/versions/{revision_id}")
|
||||
def get_version(module: str, project_id: int, revision_id: int, db: DbSession,
|
||||
current: PrincipalOf) -> dict[str, Any]:
|
||||
"""翻历史版本:只读,用来对照"上一版和这一版差在哪"。"""
|
||||
_module_or_404(module)
|
||||
assert_project_visible(db, current, project_id, module=module)
|
||||
revision = db.get(Revision, revision_id)
|
||||
if revision is None or revision.project_id != project_id or revision.module != module:
|
||||
raise not_found("版本不存在")
|
||||
lines = biz.revision_lines(db, revision)
|
||||
return ok({
|
||||
"revision": _revision_view(db, revision),
|
||||
"lines": {key: [biz.serialize_line(row) for row in rows] for key, rows in lines.items()},
|
||||
"snapshot": biz.snapshot_payload(biz.current_snapshot(db, revision)),
|
||||
})
|
||||
|
||||
|
||||
@router.post("/{module}/projects/{project_id}/lines/{line_key}")
|
||||
def upsert_line(module: str, project_id: int, line_key: str, body: LineBody,
|
||||
db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_module_or_404(module)
|
||||
_assert_line_key(line_key)
|
||||
project, revision = _revision_context(db, current, project_id, module, write=True)
|
||||
row = biz.upsert_line(db, revision, f"{module}.{line_key}", body.data, current.account)
|
||||
snapshot = biz.current_snapshot(db, revision)
|
||||
db.commit()
|
||||
return ok({"line": biz.serialize_line(row),
|
||||
"snapshot": biz.snapshot_payload(snapshot),
|
||||
"revision": _revision_view(db, revision)})
|
||||
|
||||
|
||||
@router.put("/{module}/projects/{project_id}/lines/{line_key}")
|
||||
def replace_lines(module: str, project_id: int, line_key: str, body: LinesBody,
|
||||
db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_module_or_404(module)
|
||||
_assert_line_key(line_key)
|
||||
project, revision = _revision_context(db, current, project_id, module, write=True)
|
||||
removed = biz.replace_lines(db, revision, f"{module}.{line_key}", body.rows, current.account)
|
||||
snapshot = biz.current_snapshot(db, revision)
|
||||
db.commit()
|
||||
return ok({"removed": removed, "snapshot": biz.snapshot_payload(snapshot),
|
||||
"revision": _revision_view(db, revision)})
|
||||
|
||||
|
||||
def _assert_line_key(line_key: str) -> None:
|
||||
if line_key not in LINE_KEYS:
|
||||
raise not_found(f"未知的明细类型:{line_key}")
|
||||
|
||||
|
||||
@router.delete("/{module}/projects/{project_id}/lines/{line_key}/{line_id}")
|
||||
def delete_line(module: str, project_id: int, line_key: str, line_id: int,
|
||||
db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_module_or_404(module)
|
||||
_assert_line_key(line_key)
|
||||
project, revision = _revision_context(db, current, project_id, module, write=True)
|
||||
biz.delete_line(db, revision, f"{module}.{line_key}", line_id, current.account)
|
||||
snapshot = biz.current_snapshot(db, revision)
|
||||
db.commit()
|
||||
return ok({"deleted": True, "snapshot": biz.snapshot_payload(snapshot)})
|
||||
|
||||
|
||||
@router.post("/{module}/projects/{project_id}/calculate")
|
||||
def calculate(module: str, project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
"""计算预览。前端字段变化时调它,浏览器不自己算(``TO-BE-REACT-002``)。"""
|
||||
_module_or_404(module)
|
||||
project, revision = _revision_context(db, current, project_id, module)
|
||||
snapshot = biz.recompute(db, revision, current.account, trigger="preview",
|
||||
persist_projection=revision.status == RevisionStatus.DRAFT)
|
||||
db.commit()
|
||||
return ok(biz.snapshot_payload(snapshot))
|
||||
|
||||
|
||||
@router.get("/{module}/projects/{project_id}/snapshots")
|
||||
def list_snapshots(module: str, project_id: int, db: DbSession, current: PrincipalOf,
|
||||
revisionId: int | None = None, limit: int = Query(20, ge=1, le=100)) -> dict[str, Any]:
|
||||
_module_or_404(module)
|
||||
assert_project_visible(db, current, project_id, module=module)
|
||||
statement = select(CalcSnapshot).where(CalcSnapshot.project_id == project_id,
|
||||
CalcSnapshot.module == module)
|
||||
if revisionId:
|
||||
statement = statement.where(CalcSnapshot.revision_id == revisionId)
|
||||
rows = db.execute(statement.order_by(CalcSnapshot.id.desc()).limit(limit)).scalars().all()
|
||||
return ok([{"id": row.id, "revisionId": row.revision_id, "calcVersion": row.calc_version,
|
||||
"trigger": row.trigger, "accountName": row.account_name,
|
||||
"createdAt": row.created_at.isoformat(sep=" ", timespec="seconds")} for row in rows])
|
||||
|
||||
|
||||
@router.get("/{module}/snapshots/{snapshot_id}")
|
||||
def get_snapshot(module: str, snapshot_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
"""审批页与对账页读快照的入口:给一个 id,拿到当时那份完整结果。"""
|
||||
_module_or_404(module)
|
||||
snapshot = db.get(CalcSnapshot, snapshot_id)
|
||||
if snapshot is None or snapshot.module != module:
|
||||
raise not_found("快照不存在")
|
||||
assert_project_visible(db, current, snapshot.project_id, module=module)
|
||||
return ok({"id": snapshot.id, "calcVersion": snapshot.calc_version, "trigger": snapshot.trigger,
|
||||
"payload": biz.snapshot_payload(snapshot),
|
||||
"createdAt": snapshot.created_at.isoformat(sep=" ", timespec="seconds")})
|
||||
|
||||
|
||||
@router.post("/{module}/projects/{project_id}/submit")
|
||||
def submit(module: str, project_id: int, body: SubmitBody, db: DbSession,
|
||||
current: PrincipalOf) -> dict[str, Any]:
|
||||
"""送审:卡必填 -> 强制重算 -> 冻结 -> 起流程。"""
|
||||
_module_or_404(module)
|
||||
project, revision = _revision_context(db, current, project_id, module, write=True)
|
||||
if revision.status == RevisionStatus.REVIEWING:
|
||||
raise conflict("already_reviewing", "该版本已经在审批中")
|
||||
|
||||
# 立项送审先卡立项表必填:截图里那十来栏全是必填,缺一项就退回去,
|
||||
# 别让审批人批一张连客户都没填的立项单。预算侧不卡——那是立项的表。
|
||||
if module == RevisionModule.ESTIMATE:
|
||||
missing = biz.initiation_missing_fields(project)
|
||||
if missing:
|
||||
raise bad_request(
|
||||
"initiation_incomplete",
|
||||
f"立项表还有 {len(missing)} 项必填没填完",
|
||||
{"issues": [{"field": item["field"],
|
||||
"message": f"立项表必填项「{item['label']}」还没填"} for item in missing]},
|
||||
)
|
||||
|
||||
snapshot = biz.recompute(db, revision, current.account, trigger="submit")
|
||||
payload = biz.snapshot_payload(snapshot)
|
||||
validation = payload.get("validation") or {}
|
||||
blocking = validation.get("errors") or []
|
||||
if blocking:
|
||||
# 校验不通过就把结构化错误原样抛回去,前端能在对应段落上标红
|
||||
raise bad_request("validation_failed", "送审前还有 "
|
||||
f"{len(blocking)} 项校验没有通过", {"issues": blocking})
|
||||
|
||||
# 冻结送审时刻的关键数据:审批人看的永远是这一份,之后改草稿不影响在途审批
|
||||
revision.freeze_json = json.dumps({
|
||||
"submittedProjectName": project.name,
|
||||
"contractAmount": payload.get("contract_amount"),
|
||||
"profit": payload.get("profit"),
|
||||
"calcVersion": payload.get("calc_version"),
|
||||
}, ensure_ascii=False)
|
||||
|
||||
instance = approval_engine.submit(
|
||||
db,
|
||||
module=module,
|
||||
project=project,
|
||||
revision=revision,
|
||||
snapshot_id=snapshot.id,
|
||||
submitter=current.account,
|
||||
variables={
|
||||
"contract_amount": float(_num(payload.get("contract_amount"))),
|
||||
"contribution_profit_rate": float(_num(
|
||||
((payload.get("profit") or {}).get("contribution_rate") or {}).get("value") or 0)),
|
||||
"income_total": float(_num((payload.get("profit") or {}).get("income_total"))),
|
||||
},
|
||||
comment=body.comment,
|
||||
self_selected=body.selfSelected or None,
|
||||
)
|
||||
|
||||
if module == RevisionModule.BUDGET:
|
||||
biz.set_project_stage(db, project, ProjectStage.S3_BUDGET, current.account, "提交预算审批")
|
||||
db.commit()
|
||||
return ok({
|
||||
"instanceId": instance.id,
|
||||
"status": instance.status,
|
||||
"currentNode": instance.current_node_name,
|
||||
"revision": _revision_view(db, revision),
|
||||
})
|
||||
|
||||
|
||||
def _num(value: Any) -> Any:
|
||||
try:
|
||||
return float(str(value or 0))
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
|
||||
|
||||
@router.post("/{module}/projects/{project_id}/new-version")
|
||||
def new_version(module: str, project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
"""显式基于最新版开新版本(已通过之后再改就走这里)。"""
|
||||
_module_or_404(module)
|
||||
project, _existing = _revision_context(db, current, project_id, module, write=True)
|
||||
latest = db.execute(
|
||||
select(Revision).where(Revision.project_id == project_id, Revision.module == module,
|
||||
Revision.is_deleted.is_(False)).order_by(Revision.version.desc()).limit(1)
|
||||
).scalars().first()
|
||||
if latest is None or latest.status not in RevisionStatus.EFFECTIVE:
|
||||
raise conflict("no_base", "只有已批准的版本才能派生新版本;草稿直接编辑即可")
|
||||
revision = biz.get_or_create_revision(db, project_id, module, current.account)
|
||||
biz.recompute(db, revision, current.account, trigger="edit")
|
||||
db.commit()
|
||||
return ok({"revision": _revision_view(db, revision)})
|
||||
|
||||
|
||||
@router.get("/{module}/projects/{project_id}/approval")
|
||||
def approval_of(module: str, project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
"""项目详情里的"审核记录":按模块取最近若干次审批实例与流水。"""
|
||||
_module_or_404(module)
|
||||
assert_project_visible(db, current, project_id, module=module)
|
||||
from ..models import ApprovalInstance, ApprovalRecord
|
||||
|
||||
instances = db.execute(
|
||||
select(ApprovalInstance).where(ApprovalInstance.project_id == project_id,
|
||||
ApprovalInstance.business_module == module)
|
||||
.order_by(ApprovalInstance.id.desc()).limit(10)
|
||||
).scalars().all()
|
||||
if not instances:
|
||||
return ok({"instances": [], "records": []})
|
||||
|
||||
ids = [row.id for row in instances]
|
||||
records = db.execute(
|
||||
select(ApprovalRecord).where(ApprovalRecord.instance_id.in_(ids)).order_by(ApprovalRecord.id)
|
||||
).scalars().all()
|
||||
return ok({
|
||||
"instances": [{
|
||||
"id": row.id, "status": row.status, "flowName": row.flow_name,
|
||||
"submitterName": row.submitter_name, "currentNode": row.current_node_name,
|
||||
"revisionId": row.revision_id, "snapshotId": row.snapshot_id,
|
||||
"submittedAt": row.submitted_at.isoformat(sep=" ", timespec="seconds"),
|
||||
"finishedAt": row.finished_at.isoformat(sep=" ", timespec="seconds") if row.finished_at else "",
|
||||
} for row in instances],
|
||||
"records": [{
|
||||
"id": row.id, "instanceId": row.instance_id, "nodeName": row.node_name,
|
||||
"action": row.action, "actionLabel": row.action_label,
|
||||
"operatorName": row.operator_name, "targetNames": row.target_names,
|
||||
"comment": row.comment, "rollbackToNode": row.rollback_to_node,
|
||||
"createdAt": row.created_at.isoformat(sep=" ", timespec="seconds"),
|
||||
} for row in records],
|
||||
})
|
||||
|
|
@ -0,0 +1,694 @@
|
|||
"""组织架构与系统账号。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import delete, func, or_, select
|
||||
|
||||
from ..deps import DbSession, PrincipalOf
|
||||
from ..envelope import conflict, forbidden, not_found, ok, page
|
||||
from ..models import (
|
||||
Account,
|
||||
AccountIdentity,
|
||||
AccountSource,
|
||||
OrgUnit,
|
||||
PermAccountRole,
|
||||
PermRole,
|
||||
Position,
|
||||
Status,
|
||||
)
|
||||
from ..security import hash_password, password_policy_error
|
||||
from ..service.org_sync import sync_all, sync_changes
|
||||
|
||||
router = APIRouter(prefix="/org", tags=["org"])
|
||||
|
||||
|
||||
class UnitBody(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=255)
|
||||
code: str = ""
|
||||
shortName: str = ""
|
||||
parentId: int | None = None
|
||||
managerId: int | None = None
|
||||
orderNumber: int = 0
|
||||
status: int = Status.ACTIVE
|
||||
remark: str = ""
|
||||
|
||||
|
||||
class PositionBody(BaseModel):
|
||||
code: str = Field(min_length=1, max_length=64)
|
||||
name: str = Field(min_length=1, max_length=128)
|
||||
rank: int = 100
|
||||
orderNumber: int = 0
|
||||
enabled: bool = True
|
||||
remark: str = ""
|
||||
|
||||
|
||||
class AccountBody(BaseModel):
|
||||
account: str = Field(min_length=1, max_length=190)
|
||||
displayName: str = ""
|
||||
password: str = ""
|
||||
empCode: str = ""
|
||||
telephone: str = ""
|
||||
email: str = ""
|
||||
orgUnitId: int | None = None
|
||||
positionId: int | None = None
|
||||
leaderId: int | None = None
|
||||
status: int = Status.ACTIVE
|
||||
#: None 表示"这次不动它"。编辑弹窗少传一个字段就把超管降成普通人,是没人能接受的
|
||||
isSystemAdmin: bool | None = None
|
||||
roleIds: list[int] = Field(default_factory=list)
|
||||
workLocation: str = ""
|
||||
remark: str = ""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 组织
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/units")
|
||||
def unit_tree(db: DbSession, keyword: str = "", includeDisabled: bool = False) -> dict[str, Any]:
|
||||
statement = select(OrgUnit).where(OrgUnit.is_deleted.is_(False))
|
||||
if keyword:
|
||||
statement = statement.where(or_(OrgUnit.name.like(f"%{keyword}%"), OrgUnit.code.like(f"%{keyword}%")))
|
||||
if not includeDisabled:
|
||||
statement = statement.where(OrgUnit.status == Status.ACTIVE)
|
||||
units = db.execute(statement.order_by(OrgUnit.order_number, OrgUnit.id)).scalars().all()
|
||||
|
||||
manager_ids = {unit.manager_id for unit in units if unit.manager_id}
|
||||
names = {}
|
||||
if manager_ids:
|
||||
names = dict(db.execute(
|
||||
select(Account.id, Account.display_name).where(Account.id.in_(manager_ids))
|
||||
).all())
|
||||
counts = dict(db.execute(
|
||||
select(Account.org_unit_id, func.count(Account.id)).where(Account.is_deleted.is_(False))
|
||||
.group_by(Account.org_unit_id)
|
||||
).all())
|
||||
|
||||
nodes = {
|
||||
unit.id: {
|
||||
"id": unit.id, "name": unit.name, "code": unit.code, "shortName": unit.short_name,
|
||||
"parentId": unit.parent_id, "level": unit.level, "path": unit.path,
|
||||
"status": unit.status, "statusLabel": Status.label(unit.status),
|
||||
"managerId": unit.manager_id, "managerName": names.get(unit.manager_id, ""),
|
||||
"orderNumber": unit.order_number, "isHub": unit.is_hub,
|
||||
"userCount": counts.get(unit.id, 0), "children": [],
|
||||
}
|
||||
for unit in units
|
||||
}
|
||||
roots: list[dict[str, Any]] = []
|
||||
for node in nodes.values():
|
||||
parent = nodes.get(node["parentId"]) if node["parentId"] else None
|
||||
(parent["children"] if parent else roots).append(node)
|
||||
return ok(roots)
|
||||
|
||||
|
||||
@router.post("/units")
|
||||
def create_unit(body: UnitBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
if not current.permission.can("org:unit:edit"):
|
||||
raise forbidden("缺少权限:org:unit:edit")
|
||||
unit = OrgUnit(
|
||||
name=body.name, code=body.code, short_name=body.shortName, parent_id=body.parentId,
|
||||
manager_id=body.managerId, order_number=body.orderNumber, status=body.status, remark=body.remark,
|
||||
)
|
||||
db.add(unit)
|
||||
db.flush()
|
||||
_recompute_path(db, unit)
|
||||
db.commit()
|
||||
return ok({"id": unit.id})
|
||||
|
||||
|
||||
@router.put("/units/{unit_id}")
|
||||
def update_unit(unit_id: int, body: UnitBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
if not current.permission.can("org:unit:edit"):
|
||||
raise forbidden("缺少权限:org:unit:edit")
|
||||
unit = db.get(OrgUnit, unit_id)
|
||||
if unit is None or unit.is_deleted:
|
||||
raise not_found("部门不存在")
|
||||
# Hub 接管的部门:名称/编码/状态/上级由同步说了算,本地只让改负责人、简称与排序
|
||||
if not unit.is_hub:
|
||||
unit.name = body.name
|
||||
unit.code = body.code
|
||||
unit.status = body.status
|
||||
unit.parent_id = body.parentId
|
||||
unit.short_name = body.shortName
|
||||
unit.manager_id = body.managerId
|
||||
unit.order_number = body.orderNumber
|
||||
unit.remark = body.remark
|
||||
_recompute_path(db, unit)
|
||||
db.commit()
|
||||
return ok({"id": unit.id})
|
||||
|
||||
|
||||
@router.delete("/units/{unit_id}")
|
||||
def delete_unit(unit_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
if not current.permission.can("org:unit:edit"):
|
||||
raise forbidden("缺少权限:org:unit:edit")
|
||||
unit = db.get(OrgUnit, unit_id)
|
||||
if unit is None or unit.is_deleted:
|
||||
raise not_found("部门不存在")
|
||||
if unit.is_hub:
|
||||
raise conflict("hub_managed", "该部门由统一身份接管,请到统一身份平台调整")
|
||||
if unit.children:
|
||||
raise conflict("has_children", "请先删除下级部门")
|
||||
headcount = db.execute(
|
||||
select(func.count(Account.id)).where(Account.org_unit_id == unit_id, Account.is_deleted.is_(False))
|
||||
).scalar() or 0
|
||||
if headcount:
|
||||
raise conflict("has_accounts", f"部门下还有 {headcount} 个账号")
|
||||
unit.is_deleted = True
|
||||
db.commit()
|
||||
return ok({"deleted": True})
|
||||
|
||||
|
||||
def _recompute_path(db, unit: OrgUnit) -> None:
|
||||
"""重算本节点及以下所有节点的路径与层级。"""
|
||||
units = {item.id: item for item in db.execute(select(OrgUnit).where(OrgUnit.is_deleted.is_(False))).scalars().all()}
|
||||
|
||||
def path_of(target: OrgUnit, depth: int = 0) -> tuple[str, int]:
|
||||
if depth > 32:
|
||||
return f"/{target.id}/", 1
|
||||
parent = units.get(target.parent_id) if target.parent_id else None
|
||||
if parent is None or parent.id == target.id:
|
||||
return f"/{target.id}/", 1
|
||||
parent_path, parent_level = path_of(parent, depth + 1)
|
||||
return f"{parent_path}{target.id}/", parent_level + 1
|
||||
|
||||
affected = db.execute(
|
||||
select(OrgUnit).where(OrgUnit.id.in_(list(units.keys())))
|
||||
).scalars().all()
|
||||
for item in affected:
|
||||
item.path, item.level = path_of(item)
|
||||
db.flush()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 岗位
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/positions")
|
||||
def list_positions(db: DbSession) -> dict[str, Any]:
|
||||
rows = db.execute(select(Position).where(Position.is_deleted.is_(False))
|
||||
.order_by(Position.rank, Position.order_number, Position.id)).scalars().all()
|
||||
return ok([{"id": row.id, "code": row.code, "name": row.name, "rank": row.rank,
|
||||
"orderNumber": row.order_number, "enabled": row.enabled, "remark": row.remark} for row in rows])
|
||||
|
||||
|
||||
@router.post("/positions")
|
||||
def create_position(body: PositionBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
if not current.permission.can("org:position:edit"):
|
||||
raise forbidden("缺少权限:org:position:edit")
|
||||
if db.execute(select(Position).where(Position.code == body.code)).scalars().first():
|
||||
raise conflict("duplicated_code", "岗位编码已存在")
|
||||
row = Position(code=body.code, name=body.name, rank=body.rank, order_number=body.orderNumber,
|
||||
enabled=body.enabled, remark=body.remark)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
return ok({"id": row.id})
|
||||
|
||||
|
||||
@router.put("/positions/{position_id}")
|
||||
def update_position(position_id: int, body: PositionBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
if not current.permission.can("org:position:edit"):
|
||||
raise forbidden("缺少权限:org:position:edit")
|
||||
row = db.get(Position, position_id)
|
||||
if row is None or row.is_deleted:
|
||||
raise not_found("岗位不存在")
|
||||
row.name, row.rank, row.order_number, row.enabled, row.remark = (
|
||||
body.name, body.rank, body.orderNumber, body.enabled, body.remark)
|
||||
db.commit()
|
||||
return ok({"id": row.id})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 账号
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/accounts")
|
||||
def list_accounts(
|
||||
db: DbSession,
|
||||
current: PrincipalOf,
|
||||
keyword: str = "",
|
||||
orgUnitId: int | None = None,
|
||||
includeChildren: bool = True,
|
||||
positionId: int | None = None,
|
||||
roleId: int | None = None,
|
||||
status: int | None = None,
|
||||
source: str = "",
|
||||
unassigned: bool = False,
|
||||
pageNo: int = Query(1, ge=1),
|
||||
pageSize: int = Query(20, ge=1, le=200),
|
||||
) -> dict[str, Any]:
|
||||
if not current.permission.can_any(("org:person:view", "org:person:edit")):
|
||||
raise forbidden("缺少权限:org:person:view")
|
||||
|
||||
statement = _account_filters(
|
||||
db, keyword=keyword, orgUnitId=orgUnitId, includeChildren=includeChildren,
|
||||
positionId=positionId, roleId=roleId, status=status, source=source, unassigned=unassigned)
|
||||
total = db.execute(select(func.count()).select_from(statement.subquery())).scalar() or 0
|
||||
rows = db.execute(statement.order_by(Account.org_unit_id, Account.id)
|
||||
.offset((pageNo - 1) * pageSize).limit(pageSize)).scalars().all()
|
||||
|
||||
roles_by_account = _roles_by_account(db, [row.id for row in rows])
|
||||
positions = dict(db.execute(select(Position.id, Position.name)).all())
|
||||
items = [_account_view(row, roles_by_account.get(row.id, []), positions) for row in rows]
|
||||
return page(items, total, pageNo, pageSize)
|
||||
|
||||
|
||||
def _account_filters(db, *, cols: tuple = (Account,), keyword: str = "",
|
||||
orgUnitId: int | None = None,
|
||||
includeChildren: bool = True, positionId: int | None = None,
|
||||
roleId: int | None = None, status: int | None = None,
|
||||
source: str = "", unassigned: bool = False):
|
||||
"""账号列表的筛选口径。
|
||||
|
||||
抽出来是因为「批量分配角色」要能按"当前筛选结果"圈人:列表里看到 98 个未分配,
|
||||
批量就该作用在这 98 个人身上,两处各写一遍筛选迟早会算出两个数。
|
||||
"""
|
||||
statement = select(*cols).where(Account.is_deleted.is_(False))
|
||||
if keyword:
|
||||
like = f"%{keyword}%"
|
||||
statement = statement.where(or_(Account.account.like(like), Account.display_name.like(like),
|
||||
Account.emp_code.like(like), Account.telephone.like(like)))
|
||||
if orgUnitId:
|
||||
from ..service.data_scope import descendant_unit_ids
|
||||
|
||||
ids = descendant_unit_ids(db, [orgUnitId]) if includeChildren else [orgUnitId]
|
||||
# 兼岗的人也要出现在部门下面,所以按身份表判定,而不是只看主部门
|
||||
statement = statement.where(
|
||||
Account.id.in_(select(AccountIdentity.account_id).where(AccountIdentity.org_unit_id.in_(ids)))
|
||||
)
|
||||
if positionId:
|
||||
statement = statement.where(Account.position_id == positionId)
|
||||
if roleId:
|
||||
statement = statement.where(Account.id.in_(
|
||||
select(PermAccountRole.account_id).where(PermAccountRole.role_id == roleId)))
|
||||
if unassigned:
|
||||
# 同步刚跑完时最容易用:一整批人挂进来、一个角色都没有,得先把他们挑出来
|
||||
statement = statement.where(
|
||||
~Account.id.in_(select(PermAccountRole.account_id).join(
|
||||
PermRole, PermRole.id == PermAccountRole.role_id).where(
|
||||
PermRole.is_deleted.is_(False))))
|
||||
if status is not None:
|
||||
statement = statement.where(Account.status == status)
|
||||
if source:
|
||||
statement = statement.where(Account.source == source)
|
||||
return statement
|
||||
|
||||
|
||||
def _roles_by_account(db, account_ids: list[int]) -> dict[int, list[dict[str, Any]]]:
|
||||
if not account_ids:
|
||||
return {}
|
||||
rows = db.execute(
|
||||
select(PermAccountRole.account_id, PermRole.id, PermRole.name, PermRole.code)
|
||||
.join(PermRole, PermRole.id == PermAccountRole.role_id)
|
||||
.where(PermAccountRole.account_id.in_(account_ids), PermRole.is_deleted.is_(False))
|
||||
).all()
|
||||
out: dict[int, list[dict[str, Any]]] = {}
|
||||
for account_id, role_id, role_name, role_code in rows:
|
||||
out.setdefault(account_id, []).append({"id": role_id, "name": role_name, "code": role_code})
|
||||
return out
|
||||
|
||||
|
||||
def _account_view(row: Account, roles: list[dict[str, Any]], positions: dict[int, str]) -> dict[str, Any]:
|
||||
return {
|
||||
"id": row.id, "account": row.account, "displayName": row.display_name or row.account,
|
||||
"empCode": row.emp_code, "email": row.email, "telephone": row.telephone,
|
||||
"orgUnitId": row.org_unit_id, "orgUnitName": row.org_unit_name,
|
||||
"positionId": row.position_id, "positionName": positions.get(row.position_id or 0, ""),
|
||||
"leaderId": row.leader_id, "status": row.status, "statusLabel": Status.label(row.status),
|
||||
"source": row.source, "sourceLabel": AccountSource.label(row.source),
|
||||
"isSystemAdmin": row.is_system_admin, "roles": roles,
|
||||
"workLocation": row.work_location, "remark": row.remark,
|
||||
"lastLoginAt": row.last_login_at.isoformat(sep=" ", timespec="seconds") if row.last_login_at else "",
|
||||
"canLoginLocally": bool(row.password_hash),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/accounts/options")
|
||||
def account_options(db: DbSession, current: PrincipalOf, keyword: str = "") -> dict[str, Any]:
|
||||
"""人员选择器用的精简列表:只要 id + 姓名,不分页。
|
||||
|
||||
之前三处选择器都拿 pageSize=300 去请求分页接口,一是撞 le=200 直接 422,
|
||||
二是人多的时候会静默截断,选不到靠后的人。必须在 /accounts/{account_id}
|
||||
之前声明,否则 "options" 会被当成 account_id。
|
||||
"""
|
||||
allowed = (
|
||||
"org:person:view", "org:person:edit",
|
||||
"workbench:delegates", "system:datapermission:edit", "approval:flow:edit",
|
||||
)
|
||||
if not current.permission.can_any(allowed):
|
||||
raise forbidden("缺少权限:org:person:view")
|
||||
# org_unit_name 是关系推导出来的属性,不是列,所以这里显式 join 出来
|
||||
statement = (
|
||||
select(Account.id, Account.account, Account.display_name,
|
||||
OrgUnit.name.label("org_unit_name"))
|
||||
.outerjoin(OrgUnit, OrgUnit.id == Account.org_unit_id)
|
||||
.where(Account.is_deleted.is_(False), Account.status == Status.ACTIVE)
|
||||
.order_by(Account.org_unit_id, Account.id)
|
||||
.limit(2000)
|
||||
)
|
||||
if keyword:
|
||||
like = f"%{keyword}%"
|
||||
statement = statement.where(or_(Account.account.like(like), Account.display_name.like(like)))
|
||||
return ok([
|
||||
{"id": row.id, "account": row.account,
|
||||
"displayName": row.display_name or row.account, "orgUnitName": row.org_unit_name}
|
||||
for row in db.execute(statement).all()
|
||||
])
|
||||
|
||||
|
||||
@router.get("/accounts/role-options")
|
||||
def account_role_options(db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
"""给人挂角色时要的候选角色清单。
|
||||
|
||||
单独开一条而不复用 ``/system/roles``:能管人(``org:person:view``)就该看得见能给人
|
||||
挂哪几个角色,这是配人的下限;看得见的应该是"这个角色叫什么、有多少人挂着",
|
||||
至于角色里具体勾了哪些权限点,那才归 ``system:role:view`` 管。
|
||||
顺手把成员数带上,界面能一眼看出哪些角色还没人用。
|
||||
"""
|
||||
if not current.permission.can_any(("org:person:view", "org:person:edit")):
|
||||
raise forbidden("缺少权限:org:person:view")
|
||||
rows = db.execute(select(PermRole).where(PermRole.is_deleted.is_(False))
|
||||
.order_by(PermRole.order_number, PermRole.id)).scalars().all()
|
||||
counts = dict(db.execute(
|
||||
select(PermAccountRole.role_id, func.count())
|
||||
.where(PermAccountRole.role_id.in_([row.id for row in rows] or [0]))
|
||||
.group_by(PermAccountRole.role_id)).all()) if rows else {}
|
||||
return ok([{
|
||||
"id": row.id, "code": row.code, "name": row.name, "builtin": bool(row.builtin),
|
||||
# 停用的角色也带回来,但带着标记:界面据此只让人摘、不让人新挂
|
||||
"enabled": bool(row.enabled), "remark": row.remark,
|
||||
"memberCount": counts.get(row.id, 0),
|
||||
} for row in rows])
|
||||
|
||||
|
||||
@router.get("/accounts/{account_id}")
|
||||
def get_account(account_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
if not current.permission.can_any(("org:person:view", "org:person:edit")):
|
||||
raise forbidden("缺少权限:org:person:view")
|
||||
row = db.get(Account, account_id)
|
||||
if row is None or row.is_deleted:
|
||||
raise not_found("账号不存在")
|
||||
roles = _roles_by_account(db, [account_id]).get(account_id, [])
|
||||
positions = dict(db.execute(select(Position.id, Position.name)).all())
|
||||
identities = db.execute(
|
||||
select(AccountIdentity, OrgUnit.name, Position.name)
|
||||
.join(OrgUnit, OrgUnit.id == AccountIdentity.org_unit_id)
|
||||
.outerjoin(Position, Position.id == AccountIdentity.position_id)
|
||||
.where(AccountIdentity.account_id == account_id)
|
||||
).all()
|
||||
data = _account_view(row, roles, positions)
|
||||
data["identities"] = [
|
||||
{"id": identity.id, "orgUnitId": identity.org_unit_id, "orgUnitName": org_name,
|
||||
"positionName": position_name or "", "isDefault": identity.is_default, "kind": identity.kind}
|
||||
for identity, org_name, position_name in identities
|
||||
]
|
||||
return ok(data)
|
||||
|
||||
|
||||
@router.post("/accounts")
|
||||
def create_account(body: AccountBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
if not current.permission.can("org:person:edit"):
|
||||
raise forbidden("缺少权限:org:person:edit")
|
||||
if db.execute(select(Account).where(Account.account == body.account,
|
||||
Account.is_deleted.is_(False))).scalars().first():
|
||||
raise conflict("duplicated_account", "登录账号已存在")
|
||||
password = body.password or ""
|
||||
if password:
|
||||
problem = password_policy_error(password)
|
||||
if problem:
|
||||
raise forbidden(problem)
|
||||
row = Account(
|
||||
account=body.account, display_name=body.displayName or body.account,
|
||||
password_hash=hash_password(password) if password else "",
|
||||
emp_code=body.empCode, telephone=body.telephone, email=body.email,
|
||||
org_unit_id=body.orgUnitId, position_id=body.positionId, leader_id=body.leaderId,
|
||||
status=body.status, is_system_admin=bool(body.isSystemAdmin), work_location=body.workLocation,
|
||||
remark=body.remark, source=AccountSource.LOCAL,
|
||||
)
|
||||
db.add(row)
|
||||
db.flush()
|
||||
_sync_roles(db, row.id, body.roleIds)
|
||||
_sync_identities(db, row.id, body.orgUnitId)
|
||||
db.commit()
|
||||
return ok({"id": row.id, "hasPassword": bool(password)})
|
||||
|
||||
|
||||
@router.put("/accounts/{account_id}")
|
||||
def update_account(account_id: int, body: AccountBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
if not current.permission.can("org:person:edit"):
|
||||
raise forbidden("缺少权限:org:person:edit")
|
||||
row = db.get(Account, account_id)
|
||||
if row is None or row.is_deleted:
|
||||
raise not_found("账号不存在")
|
||||
if row.is_hub and (body.orgUnitId or 0) not in (0, row.org_unit_id):
|
||||
raise conflict("hub_managed", "统一身份账号的部门由同步维护,本地不能改")
|
||||
if body.isSystemAdmin is not None and bool(body.isSystemAdmin) != bool(row.is_system_admin):
|
||||
if not current.permission.is_system_admin:
|
||||
raise forbidden("只有系统管理员能授予或收回「系统管理员」标记")
|
||||
if not body.isSystemAdmin and _remaining_system_admins(db, exclude_id=row.id) == 0:
|
||||
raise conflict("last_admin", "至少要保留一个系统管理员,否则没人再进得了系统管理")
|
||||
if body.password:
|
||||
problem = password_policy_error(body.password)
|
||||
if problem:
|
||||
raise forbidden(problem)
|
||||
row.password_hash = hash_password(body.password)
|
||||
row.password_updated_at = datetime.now()
|
||||
row.display_name = body.displayName or row.display_name
|
||||
row.emp_code, row.telephone, row.email = body.empCode, body.telephone, body.email
|
||||
row.position_id, row.leader_id = body.positionId, body.leaderId
|
||||
if body.isSystemAdmin is not None:
|
||||
row.is_system_admin = bool(body.isSystemAdmin)
|
||||
row.work_location, row.remark = body.workLocation, body.remark
|
||||
if not row.is_hub:
|
||||
row.org_unit_id = body.orgUnitId
|
||||
row.status = body.status
|
||||
_sync_roles(db, row.id, body.roleIds)
|
||||
_sync_identities(db, row.id, row.org_unit_id)
|
||||
db.commit()
|
||||
return ok({"id": row.id})
|
||||
|
||||
|
||||
class AccountRoleBody(BaseModel):
|
||||
roleIds: list[int] = Field(default_factory=list)
|
||||
|
||||
|
||||
@router.put("/accounts/{account_id}/roles")
|
||||
def set_account_roles(account_id: int, body: AccountRoleBody, db: DbSession,
|
||||
current: PrincipalOf) -> dict[str, Any]:
|
||||
"""只换角色,别动档案。
|
||||
|
||||
统一身份同步过来的人,姓名部门口令都归 Hub,本地要给他开权限,动的本来就只有角色;
|
||||
为这件事把整份档案表单填一遍既难用,也很容易顺手把 Hub 管的字段带歪。
|
||||
"""
|
||||
if not current.permission.can("org:person:edit"):
|
||||
raise forbidden("缺少权限:org:person:edit")
|
||||
row = db.get(Account, account_id)
|
||||
if row is None or row.is_deleted:
|
||||
raise not_found("账号不存在")
|
||||
|
||||
wanted = list(dict.fromkeys(int(item) for item in body.roleIds or []))
|
||||
existing = set(db.execute(select(PermAccountRole.role_id).where(
|
||||
PermAccountRole.account_id == row.id)).scalars().all())
|
||||
if wanted:
|
||||
found = {item.id: item for item in db.execute(
|
||||
select(PermRole).where(PermRole.id.in_(wanted),
|
||||
PermRole.is_deleted.is_(False))).scalars()}
|
||||
unknown = [item for item in wanted if item not in found]
|
||||
if unknown:
|
||||
raise conflict("unknown_role", f"角色不存在:{unknown}")
|
||||
# 停用的角色不许新挂,但原本就挂着、这次只是照样留着的不算新挂
|
||||
disabled = [found[item].name for item in wanted
|
||||
if item not in existing and not found[item].enabled]
|
||||
if disabled:
|
||||
raise conflict("role_disabled", "角色已停用,先启用再分配:" + "、".join(disabled))
|
||||
|
||||
_sync_roles(db, row.id, wanted)
|
||||
db.commit()
|
||||
return ok({"id": row.id,
|
||||
"roles": _roles_by_account(db, [row.id]).get(row.id, [])})
|
||||
|
||||
|
||||
#: 一次批量最多动多少人。批量是把双刃剑:一个手滑的筛选能把全公司的角色改掉。
|
||||
BATCH_LIMIT = 500
|
||||
|
||||
|
||||
class AccountRoleTargetBody(BaseModel):
|
||||
"""批量分配的目标人群之二:照抄账号列表的筛选条件圈人。"""
|
||||
|
||||
keyword: str = ""
|
||||
orgUnitId: int | None = None
|
||||
includeChildren: bool = True
|
||||
positionId: int | None = None
|
||||
roleId: int | None = None
|
||||
status: int | None = None
|
||||
source: str = ""
|
||||
unassigned: bool = False
|
||||
|
||||
|
||||
class BatchRoleBody(BaseModel):
|
||||
accountIds: list[int] = Field(default_factory=list)
|
||||
target: AccountRoleTargetBody | None = None
|
||||
#: append=在各自原有的基础上加;remove=只摘这几个角色;replace=整份换成这些(空数组=清空)
|
||||
mode: str = "append"
|
||||
roleIds: list[int] = Field(default_factory=list)
|
||||
|
||||
|
||||
@router.post("/accounts/roles/batch")
|
||||
def batch_assign_roles(body: BatchRoleBody, db: DbSession,
|
||||
current: PrincipalOf) -> dict[str, Any]:
|
||||
"""一批人一起改角色。
|
||||
|
||||
统一身份一次同步进来上百人,一个个点开分配不现实:要么勾几页,要么直接按
|
||||
当前筛选结果整批处理("只看未分配角色" + 追加一个角色,就是同步后的第一步)。
|
||||
"""
|
||||
if not current.permission.can("org:person:edit"):
|
||||
raise forbidden("缺少权限:org:person:edit")
|
||||
if bool(body.accountIds) == bool(body.target):
|
||||
raise conflict("pick_target", "要么点名(accountIds),要么按筛选条件(target)圈人,只能选一种")
|
||||
if body.mode not in ("append", "remove", "replace"):
|
||||
raise conflict("invalid_mode", "分配方式只能是追加、移除或覆盖")
|
||||
if body.mode in ("append", "remove") and not body.roleIds:
|
||||
# 覆盖 + 空列表是"清空",那是一句有意义的话;追加和移除空列表只是客户端漏传
|
||||
raise conflict("empty_roles", "要" + ("追加" if body.mode == "append" else "移除")
|
||||
+ "哪几个角色?想清空就把方式换成「覆盖」并且一个都不选")
|
||||
|
||||
if body.target is not None:
|
||||
account_ids = list(db.execute(
|
||||
_account_filters(db, cols=(Account.id,), **body.target.model_dump())).scalars().all())
|
||||
else:
|
||||
account_ids = list(dict.fromkeys(int(item) for item in body.accountIds))
|
||||
found = set(db.execute(select(Account.id).where(
|
||||
Account.id.in_(account_ids), Account.is_deleted.is_(False))).scalars().all())
|
||||
unknown = [item for item in account_ids if item not in found]
|
||||
if unknown:
|
||||
raise conflict("unknown_account", f"账号不存在:{unknown[:5]}")
|
||||
if not account_ids:
|
||||
raise conflict("empty_target", "这批人里一个都没有,先换个筛选条件")
|
||||
if len(account_ids) > BATCH_LIMIT:
|
||||
raise conflict("too_many", f"一次最多处理 {BATCH_LIMIT} 人,这次圈到 {len(account_ids)} 人")
|
||||
|
||||
wanted = set(int(item) for item in body.roleIds or [])
|
||||
if wanted:
|
||||
found_roles = {row.id: row for row in db.execute(select(PermRole).where(
|
||||
PermRole.id.in_(wanted), PermRole.is_deleted.is_(False))).scalars()}
|
||||
missing = [item for item in wanted if item not in found_roles]
|
||||
if missing:
|
||||
raise conflict("unknown_role", f"角色不存在:{missing}")
|
||||
# 停用的角色不许整批新挂;移除一个停用角色是清理,照样让做
|
||||
if body.mode in ("append", "replace"):
|
||||
disabled = [found_roles[item].name for item in wanted if not found_roles[item].enabled]
|
||||
if disabled:
|
||||
raise conflict("role_disabled", "角色已停用,先启用再分配:" + "、".join(disabled))
|
||||
|
||||
existing: dict[int, set[int]] = {account_id: set() for account_id in account_ids}
|
||||
for account_id, role_id in db.execute(select(PermAccountRole.account_id, PermAccountRole.role_id)
|
||||
.where(PermAccountRole.account_id.in_(account_ids))).all():
|
||||
existing.setdefault(account_id, set()).add(role_id)
|
||||
|
||||
to_add: dict[int, list[int]] = {}
|
||||
to_remove: dict[int, list[int]] = {}
|
||||
affected = 0
|
||||
for account_id in account_ids:
|
||||
before = existing.get(account_id, set())
|
||||
if body.mode == "append":
|
||||
after = before | wanted
|
||||
elif body.mode == "remove":
|
||||
after = before - wanted
|
||||
else:
|
||||
after = set(wanted)
|
||||
if after == before:
|
||||
continue
|
||||
affected += 1
|
||||
for role_id in before - after:
|
||||
to_remove.setdefault(role_id, []).append(account_id)
|
||||
for role_id in after - before:
|
||||
to_add.setdefault(role_id, []).append(account_id)
|
||||
|
||||
for role_id, targets in to_remove.items():
|
||||
db.execute(delete(PermAccountRole).where(
|
||||
PermAccountRole.role_id == role_id, PermAccountRole.account_id.in_(targets)))
|
||||
for role_id, targets in to_add.items():
|
||||
db.add_all([PermAccountRole(account_id=account_id, role_id=role_id) for account_id in targets])
|
||||
db.commit()
|
||||
return ok({"accounts": len(account_ids), "affected": affected,
|
||||
"added": sum(len(items) for items in to_add.values()),
|
||||
"removed": sum(len(items) for items in to_remove.values())})
|
||||
|
||||
|
||||
def _remaining_system_admins(db, exclude_id: int | None = None) -> int:
|
||||
"""还剩几个能进系统管理的账号(``exclude_id`` 用来把正在被改的那个先摘出去)。"""
|
||||
statement = select(func.count()).select_from(Account).where(
|
||||
Account.is_deleted.is_(False), Account.is_system_admin.is_(True),
|
||||
Account.status == Status.ACTIVE)
|
||||
if exclude_id:
|
||||
statement = statement.where(Account.id != exclude_id)
|
||||
return db.execute(statement).scalar() or 0
|
||||
|
||||
|
||||
def _sync_roles(db, account_id: int, role_ids: list[int]) -> None:
|
||||
existing = set(db.execute(
|
||||
select(PermAccountRole.role_id).where(PermAccountRole.account_id == account_id)
|
||||
).scalars().all())
|
||||
wanted = set(role_ids or [])
|
||||
for role_id in existing - wanted:
|
||||
for row in db.execute(select(PermAccountRole).where(
|
||||
PermAccountRole.account_id == account_id, PermAccountRole.role_id == role_id)).scalars():
|
||||
db.delete(row)
|
||||
for role_id in wanted - existing:
|
||||
db.add(PermAccountRole(account_id=account_id, role_id=role_id))
|
||||
db.flush()
|
||||
|
||||
|
||||
def _sync_identities(db, account_id: int, org_unit_id: int | None) -> None:
|
||||
if not org_unit_id:
|
||||
return
|
||||
exists = db.execute(select(AccountIdentity).where(
|
||||
AccountIdentity.account_id == account_id, AccountIdentity.org_unit_id == org_unit_id
|
||||
)).scalars().first()
|
||||
if exists:
|
||||
return
|
||||
total = db.execute(select(func.count(AccountIdentity.id)).where(
|
||||
AccountIdentity.account_id == account_id)).scalar() or 0
|
||||
db.add(AccountIdentity(account_id=account_id, org_unit_id=org_unit_id, is_default=total == 0))
|
||||
db.flush()
|
||||
|
||||
|
||||
@router.post("/hub/sync")
|
||||
def trigger_sync(db: DbSession, current: PrincipalOf, mode: str = "full") -> dict[str, Any]:
|
||||
"""手动触发一次统一身份同步。``mode=full`` 全量镜像,``mode=changes`` 只蹭游标。
|
||||
|
||||
默认全量:手动点按钮的人要的是"把现在Hub里的样子搬过来",增量只补事件,
|
||||
补不了那些压根没发事件的变化(人员资料调整就不发)。界面上的"立即同步"走全量,
|
||||
增量留给定时任务。
|
||||
"""
|
||||
if not current.permission.can("org:sync:run"):
|
||||
raise forbidden("缺少权限:org:sync:run")
|
||||
from ..service.org_sync import serialize
|
||||
|
||||
if mode == "changes":
|
||||
run = sync_changes(db, trigger="manual")
|
||||
else:
|
||||
run = sync_all(db, trigger="manual")
|
||||
db.commit()
|
||||
return ok(serialize(run))
|
||||
|
||||
|
||||
@router.get("/hub/sync/changes")
|
||||
def poll_changes(db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
"""手动拉一次增量。给没开定时轮询的环境(开发档)留个手动手。"""
|
||||
if not current.permission.can("org:sync:run"):
|
||||
raise forbidden("缺少权限:org:sync:run")
|
||||
from ..service.org_sync import serialize
|
||||
|
||||
run = sync_changes(db, trigger="manual")
|
||||
db.commit()
|
||||
return ok(serialize(run))
|
||||
|
|
@ -0,0 +1,617 @@
|
|||
"""项目计划:阶段推进板、里程碑、WBS 分解。
|
||||
|
||||
这三样从前都不存在——项目上只有一个 ``stage`` 整数和一段"当前进度描述",于是
|
||||
"这个项目走到哪了"只能靠人写小作文。现在拆成三层各管一件事:
|
||||
|
||||
* **阶段**(``project.stage``):公司统一口径的 S0..S8,一次只能在一个阶段上,推进留流水。
|
||||
* **里程碑**:这个项目上要盯的几个日子,可以有多个,可逾期。
|
||||
* **WBS**:怎么把活拆开、谁做、做到几成,一棵树。
|
||||
|
||||
阶段板 :func:`stage_board` 刻意不新造一张"阶段表":口径仍然只有一份(``ProjectStage``),
|
||||
板子只是把项目按 stage 摊开看,避免又长出一个会和 ``stage`` 漂移的字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from .. import dicts as dict_store
|
||||
from ..deps import DbSession, PrincipalOf, assert_project_visible
|
||||
from ..envelope import conflict, forbidden, not_found, ok
|
||||
from ..models import (
|
||||
Account,
|
||||
MilestoneStatus,
|
||||
Project,
|
||||
ProjectMilestone,
|
||||
ProjectStage,
|
||||
ProjectStageEvent,
|
||||
ProjectStageLog,
|
||||
WbsTask,
|
||||
WbsTaskStatus,
|
||||
to_decimal,
|
||||
)
|
||||
from ..service import biz
|
||||
from ..service.calc.money import money_str
|
||||
|
||||
router = APIRouter(prefix="/plan", tags=["plan"])
|
||||
|
||||
WRITE_CODES = {
|
||||
"milestone": "project:milestone:edit",
|
||||
"wbs": "project:wbs:edit",
|
||||
"stage": "project:stage:edit",
|
||||
}
|
||||
|
||||
|
||||
def _t(value: datetime | None) -> str:
|
||||
return value.isoformat(sep=" ", timespec="seconds") if value else ""
|
||||
|
||||
|
||||
def _d(value: date | None) -> str:
|
||||
return value.isoformat() if value else ""
|
||||
|
||||
|
||||
def _today() -> date:
|
||||
return date.today()
|
||||
|
||||
|
||||
def _require(current: PrincipalOf, kind: str, write: bool = True) -> None:
|
||||
code = WRITE_CODES[kind] if write else f"{WRITE_CODES[kind][:-5]}:view"
|
||||
if not current.permission.can(code):
|
||||
raise forbidden(f"缺少权限:{code}")
|
||||
|
||||
|
||||
def _account_name(db, account_id: int | None, fallback: str = "") -> str:
|
||||
if not account_id:
|
||||
return fallback
|
||||
account = db.get(Account, account_id)
|
||||
if account is None:
|
||||
return fallback
|
||||
return account.display_name or account.account or fallback
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 阶段板
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/stage-board")
|
||||
def stage_board(db: DbSession, current: PrincipalOf, onlyMine: bool = False) -> dict[str, Any]:
|
||||
"""按项目阶段摊开的项目看板:每个阶段多少个项目、哪些项目。
|
||||
|
||||
数据权限和 :func:`app.api.projects.list_projects` 完全同一条 :func:`evaluate`,
|
||||
所以不会出现"列表看不见的项目在看板上数得出来"。
|
||||
"""
|
||||
from ..service.data_scope import evaluate
|
||||
|
||||
_require(current, "stage", write=False)
|
||||
decision = evaluate(db, "project", current.scope)
|
||||
statement = select(Project).where(Project.is_deleted.is_(False))
|
||||
statement = decision.apply_to(statement)
|
||||
if onlyMine:
|
||||
from sqlalchemy import or_
|
||||
from ..models import ProjectMember
|
||||
|
||||
statement = statement.where(or_(
|
||||
Project.creator_id == current.account.id,
|
||||
Project.principal_id == current.account.id,
|
||||
Project.id.in_(select(ProjectMember.project_id).where(
|
||||
ProjectMember.account_id == current.account.id)),
|
||||
))
|
||||
rows = db.execute(statement.order_by(Project.stage, Project.updated_at.desc())).scalars().all()
|
||||
|
||||
buckets: dict[int, list[dict[str, Any]]] = {}
|
||||
for row in rows:
|
||||
buckets.setdefault(int(row.stage or 0), []).append({
|
||||
"id": row.id, "name": row.name, "projectNo": row.project_no,
|
||||
"principal": row.principal, "orgUnitName": row.org_unit_name,
|
||||
"contractAmount": money_str(row.contract_amount),
|
||||
"updatedAt": _t(row.updated_at), "stageRemark": row.stage_remark,
|
||||
})
|
||||
stages = [{
|
||||
"stage": stage,
|
||||
"stageLabel": dict_store.label(db, "projectStage", stage, ProjectStage.LABELS[stage]),
|
||||
"count": len(buckets.get(stage, [])),
|
||||
"items": buckets.get(stage, [])[:50],
|
||||
} for stage in ProjectStage.LABELS]
|
||||
return ok({"stages": stages, "scope": decision.to_dict(), "total": len(rows)})
|
||||
|
||||
|
||||
class StageAdvanceBody(BaseModel):
|
||||
stage: int
|
||||
remark: str = ""
|
||||
|
||||
|
||||
@router.post("/projects/{project_id}/stage")
|
||||
def advance_stage(project_id: int, body: StageAdvanceBody, db: DbSession,
|
||||
current: PrincipalOf) -> dict[str, Any]:
|
||||
"""推进阶段。写 ``project.stage`` 与流水,和 ``POST /projects/{id}/stage`` 同一套落库。"""
|
||||
_require(current, "stage")
|
||||
project = assert_project_visible(db, current, project_id)
|
||||
if body.stage not in ProjectStage.LABELS:
|
||||
raise conflict("unknown_stage", f"未知的项目阶段:{body.stage}")
|
||||
pending = db.execute(
|
||||
select(func.count(ProjectStageEvent.id)).where(
|
||||
ProjectStageEvent.project_id == project_id,
|
||||
ProjectStageEvent.stage == project.stage,
|
||||
ProjectStageEvent.done.is_(False),
|
||||
)
|
||||
).scalar() or 0
|
||||
if pending:
|
||||
raise conflict("stage_items_open",
|
||||
f"当前阶段还有 {pending} 项检查项没勾完,先勾完或把它删掉再推进")
|
||||
biz.set_project_stage(db, project, body.stage, current.account, body.remark)
|
||||
db.commit()
|
||||
return ok({"stage": body.stage,
|
||||
"stageLabel": dict_store.label(db, "projectStage", body.stage,
|
||||
ProjectStage.LABELS[body.stage])})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 阶段检查项
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class StageItemBody(BaseModel):
|
||||
stage: int | None = None
|
||||
name: str = Field(default="", max_length=255)
|
||||
done: bool | None = None
|
||||
ownerName: str = ""
|
||||
dueDate: str = ""
|
||||
remark: str = ""
|
||||
sort: int | None = None
|
||||
|
||||
|
||||
def _stage_item_view(db, row: ProjectStageEvent) -> dict[str, Any]:
|
||||
return {"id": row.id, "stage": row.stage,
|
||||
"stageLabel": dict_store.label(db, "projectStage", row.stage, str(row.stage)),
|
||||
"name": row.name, "done": bool(row.done), "ownerName": row.owner_name,
|
||||
"dueDate": _d(row.due_date), "remark": row.remark, "sort": row.sort}
|
||||
|
||||
|
||||
@router.get("/projects/{project_id}/stage-items")
|
||||
def list_stage_items(project_id: int, db: DbSession, current: PrincipalOf,
|
||||
stage: int | None = None) -> dict[str, Any]:
|
||||
_require(current, "stage", write=False)
|
||||
assert_project_visible(db, current, project_id)
|
||||
statement = select(ProjectStageEvent).where(ProjectStageEvent.project_id == project_id)
|
||||
if stage is not None:
|
||||
statement = statement.where(ProjectStageEvent.stage == stage)
|
||||
rows = db.execute(statement.order_by(ProjectStageEvent.sort, ProjectStageEvent.id)
|
||||
).scalars().all()
|
||||
return ok([_stage_item_view(db, row) for row in rows])
|
||||
|
||||
|
||||
@router.post("/projects/{project_id}/stage-items")
|
||||
def create_stage_item(project_id: int, body: StageItemBody, db: DbSession,
|
||||
current: PrincipalOf) -> dict[str, Any]:
|
||||
_require(current, "stage")
|
||||
project = assert_project_visible(db, current, project_id)
|
||||
if not body.name.strip():
|
||||
raise conflict("name_required", "检查项名称不能为空")
|
||||
row = ProjectStageEvent(
|
||||
project_id=project_id,
|
||||
stage=body.stage if body.stage in ProjectStage.LABELS else project.stage,
|
||||
name=body.name.strip(), owner_name=_account_name(db, None, body.ownerName),
|
||||
due_date=_date(body.dueDate), remark=body.remark,
|
||||
sort=body.sort if body.sort is not None else 100,
|
||||
)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
return ok({"id": row.id})
|
||||
|
||||
|
||||
@router.put("/stage-items/{item_id}")
|
||||
def update_stage_item(item_id: int, body: StageItemBody, db: DbSession,
|
||||
current: PrincipalOf) -> dict[str, Any]:
|
||||
_require(current, "stage")
|
||||
row = db.get(ProjectStageEvent, item_id)
|
||||
if row is None:
|
||||
raise not_found("检查项不存在")
|
||||
assert_project_visible(db, current, row.project_id)
|
||||
if body.stage in ProjectStage.LABELS:
|
||||
row.stage = body.stage
|
||||
if body.name.strip():
|
||||
row.name = body.name.strip()
|
||||
if body.done is not None:
|
||||
row.done = body.done
|
||||
if body.ownerName:
|
||||
row.owner_name = body.ownerName
|
||||
if body.dueDate is not None:
|
||||
row.due_date = _date(body.dueDate)
|
||||
if body.remark:
|
||||
row.remark = body.remark
|
||||
if body.sort is not None:
|
||||
row.sort = body.sort
|
||||
db.commit()
|
||||
return ok(_stage_item_view(db, row))
|
||||
|
||||
|
||||
@router.delete("/stage-items/{item_id}")
|
||||
def delete_stage_item(item_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_require(current, "stage")
|
||||
row = db.get(ProjectStageEvent, item_id)
|
||||
if row is None:
|
||||
raise not_found("检查项不存在")
|
||||
assert_project_visible(db, current, row.project_id)
|
||||
db.delete(row)
|
||||
db.commit()
|
||||
return ok({"deleted": True})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 里程碑
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class MilestoneBody(BaseModel):
|
||||
name: str = Field(default="", max_length=255)
|
||||
stage: int | None = None
|
||||
planDate: str = ""
|
||||
actualDate: str = ""
|
||||
ownerId: int | None = None
|
||||
amount: str = ""
|
||||
receivePoint: str = ""
|
||||
status: str = ""
|
||||
remark: str = ""
|
||||
sort: int | None = None
|
||||
|
||||
|
||||
def _date(value: str | None) -> date | None:
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
return date.fromisoformat(value.strip()[:10])
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _milestone_view(db, row: ProjectMilestone) -> dict[str, Any]:
|
||||
status = row.status
|
||||
if status != MilestoneStatus.DONE and row.plan_date and row.plan_date < _today():
|
||||
status = MilestoneStatus.OVERDUE
|
||||
return {
|
||||
"id": row.id, "projectId": row.project_id, "name": row.name,
|
||||
"stage": row.stage,
|
||||
"stageLabel": dict_store.label(db, "projectStage", row.stage, "") if row.stage else "",
|
||||
"planDate": _d(row.plan_date), "actualDate": _d(row.actual_date),
|
||||
"ownerId": row.owner_id, "ownerName": row.owner_name,
|
||||
"amount": money_str(row.amount), "receivePoint": row.receive_point,
|
||||
"status": status,
|
||||
"statusLabel": dict_store.label(db, "milestoneStatus", status,
|
||||
MilestoneStatus.LABELS.get(status, status)),
|
||||
"overdue": status == MilestoneStatus.OVERDUE,
|
||||
"remark": row.remark, "sort": row.sort, "createdAt": _t(row.created_at),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/projects/{project_id}/milestones")
|
||||
def list_milestones(project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_require(current, "milestone", write=False)
|
||||
assert_project_visible(db, current, project_id)
|
||||
rows = db.execute(
|
||||
select(ProjectMilestone)
|
||||
.where(ProjectMilestone.project_id == project_id, ProjectMilestone.is_deleted.is_(False))
|
||||
.order_by(ProjectMilestone.plan_date.is_(None), ProjectMilestone.plan_date, ProjectMilestone.sort)
|
||||
).scalars().all()
|
||||
items = [_milestone_view(db, row) for row in rows]
|
||||
return ok({
|
||||
"items": items,
|
||||
"summary": {
|
||||
"total": len(items),
|
||||
"done": sum(1 for item in items if item["status"] == MilestoneStatus.DONE),
|
||||
"overdue": sum(1 for item in items if item["overdue"]),
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@router.get("/milestones")
|
||||
def list_all_milestones(db: DbSession, current: PrincipalOf, keyword: str = "",
|
||||
status: str = "", pageNo: int = 1, pageSize: int = 50) -> dict[str, Any]:
|
||||
"""跨项目的里程碑台账:逾期在前、按计划日期排。"""
|
||||
from sqlalchemy import or_
|
||||
|
||||
from ..service.data_scope import evaluate
|
||||
|
||||
_require(current, "milestone", write=False)
|
||||
visible = evaluate(db, "project", current.scope).apply_to(
|
||||
select(Project.id).where(Project.is_deleted.is_(False)))
|
||||
visible_ids = [row[0] for row in db.execute(visible).all()]
|
||||
if not visible_ids:
|
||||
return ok({"items": [], "total": 0})
|
||||
|
||||
statement = select(ProjectMilestone).where(
|
||||
ProjectMilestone.project_id.in_(visible_ids), ProjectMilestone.is_deleted.is_(False))
|
||||
if keyword:
|
||||
like = f"%{keyword}%"
|
||||
statement = statement.where(or_(ProjectMilestone.name.like(like),
|
||||
ProjectMilestone.receive_point.like(like)))
|
||||
rows = db.execute(statement.order_by(ProjectMilestone.plan_date.is_(None),
|
||||
ProjectMilestone.plan_date)).scalars().all()
|
||||
projects = dict(db.execute(select(Project.id, Project.name, Project.project_no)
|
||||
.where(Project.id.in_(visible_ids))).all())
|
||||
items = []
|
||||
for row in rows:
|
||||
item = _milestone_view(db, row)
|
||||
name_no = projects.get(row.project_id, ("", ""))
|
||||
item["projectName"], item["projectNo"] = name_no[0], name_no[1]
|
||||
items.append(item)
|
||||
if status == "overdue":
|
||||
items = [item for item in items if item["overdue"]]
|
||||
elif status == "open":
|
||||
items = [item for item in items if item["status"] != MilestoneStatus.DONE]
|
||||
# 逾期顶到最前:跨项目台账上真正要人动手的就是这几条
|
||||
items.sort(key=lambda item: (not item["overdue"], item["planDate"] or "9999-12-31"))
|
||||
start = (max(pageNo, 1) - 1) * pageSize
|
||||
return ok({"items": items[start:start + pageSize], "total": len(items)})
|
||||
|
||||
|
||||
@router.post("/projects/{project_id}/milestones")
|
||||
def create_milestone(project_id: int, body: MilestoneBody, db: DbSession,
|
||||
current: PrincipalOf) -> dict[str, Any]:
|
||||
_require(current, "milestone")
|
||||
assert_project_visible(db, current, project_id)
|
||||
if not body.name.strip():
|
||||
raise conflict("name_required", "里程碑名称不能为空")
|
||||
row = ProjectMilestone(
|
||||
project_id=project_id, name=body.name.strip(), stage=body.stage,
|
||||
plan_date=_date(body.planDate), actual_date=_date(body.actualDate),
|
||||
owner_id=body.ownerId, owner_name=_account_name(db, body.ownerId),
|
||||
amount=to_decimal(body.amount or 0), receive_point=body.receivePoint,
|
||||
status=body.status if body.status in MilestoneStatus.LABELS else MilestoneStatus.PENDING,
|
||||
remark=body.remark, sort=body.sort if body.sort is not None else 100,
|
||||
)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
return ok({"id": row.id})
|
||||
|
||||
|
||||
@router.put("/milestones/{milestone_id}")
|
||||
def update_milestone(milestone_id: int, body: MilestoneBody, db: DbSession,
|
||||
current: PrincipalOf) -> dict[str, Any]:
|
||||
_require(current, "milestone")
|
||||
row = db.get(ProjectMilestone, milestone_id)
|
||||
if row is None or row.is_deleted:
|
||||
raise not_found("里程碑不存在")
|
||||
assert_project_visible(db, current, row.project_id)
|
||||
if body.name.strip():
|
||||
row.name = body.name.strip()
|
||||
if body.stage is not None:
|
||||
row.stage = body.stage
|
||||
if body.planDate is not None and body.planDate != "":
|
||||
row.plan_date = _date(body.planDate)
|
||||
if body.actualDate is not None and body.actualDate != "":
|
||||
row.actual_date = _date(body.actualDate)
|
||||
if body.ownerId is not None:
|
||||
row.owner_id = body.ownerId
|
||||
row.owner_name = _account_name(db, body.ownerId)
|
||||
if body.amount != "":
|
||||
row.amount = to_decimal(body.amount or 0)
|
||||
if body.receivePoint is not None:
|
||||
row.receive_point = body.receivePoint
|
||||
if body.status in MilestoneStatus.LABELS:
|
||||
row.status = body.status
|
||||
# 勾成已完成却没写日期时补今天,否则台账上"已完成但没有完成时间"没法复盘
|
||||
if body.status == MilestoneStatus.DONE and row.actual_date is None:
|
||||
row.actual_date = _today()
|
||||
if body.remark is not None:
|
||||
row.remark = body.remark
|
||||
if body.sort is not None:
|
||||
row.sort = body.sort
|
||||
db.commit()
|
||||
return ok(_milestone_view(db, row))
|
||||
|
||||
|
||||
@router.delete("/milestones/{milestone_id}")
|
||||
def delete_milestone(milestone_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_require(current, "milestone")
|
||||
row = db.get(ProjectMilestone, milestone_id)
|
||||
if row is None or row.is_deleted:
|
||||
raise not_found("里程碑不存在")
|
||||
assert_project_visible(db, current, row.project_id)
|
||||
row.is_deleted = True
|
||||
db.commit()
|
||||
return ok({"deleted": True})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# WBS
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class WbsBody(BaseModel):
|
||||
name: str = Field(default="", max_length=255)
|
||||
parentId: int | None = None
|
||||
milestoneId: int | None = None
|
||||
ownerId: int | None = None
|
||||
planStart: str = ""
|
||||
planEnd: str = ""
|
||||
actualStart: str = ""
|
||||
actualEnd: str = ""
|
||||
weight: str = ""
|
||||
progress: int | None = None
|
||||
status: str = ""
|
||||
budgetAmount: str = ""
|
||||
actualAmount: str = ""
|
||||
remark: str = ""
|
||||
|
||||
|
||||
def _wbs_code(db, parent: WbsTask | None, sibling_index: int) -> str:
|
||||
if parent is None:
|
||||
return str(sibling_index)
|
||||
return f"{parent.code or '1'}.{sibling_index}"
|
||||
|
||||
|
||||
def _wbs_view(row: WbsTask, rollup: dict[int, dict[str, Any]] | None = None) -> dict[str, Any]:
|
||||
data = {
|
||||
"id": row.id, "projectId": row.project_id, "parentId": row.parent_id,
|
||||
"code": row.code, "name": row.name, "level": row.level, "path": row.path,
|
||||
"milestoneId": row.milestone_id, "ownerId": row.owner_id, "ownerName": row.owner_name,
|
||||
"planStart": _d(row.plan_start), "planEnd": _d(row.plan_end),
|
||||
"actualStart": _d(row.actual_start), "actualEnd": _d(row.actual_end),
|
||||
"weight": f"{row.weight}", "progress": row.progress, "status": row.status,
|
||||
"statusLabel": WbsTaskStatus.LABELS.get(row.status, row.status),
|
||||
"budgetAmount": money_str(row.budget_amount), "actualAmount": money_str(row.actual_amount),
|
||||
"remark": row.remark, "sort": row.sort,
|
||||
}
|
||||
data.update((rollup or {}).get(row.id, {}))
|
||||
return data
|
||||
|
||||
|
||||
def _rollup(rows: list[WbsTask]) -> dict[int, dict[str, Any]]:
|
||||
"""子树汇总:进度按权重加权、金额直接相加、完成数数叶子。
|
||||
|
||||
只存一份"自身进度",汇总读时算——存两份迟早会有一份没人更新,那比没有更难看。
|
||||
"""
|
||||
children: dict[int | None, list[WbsTask]] = {}
|
||||
for row in rows:
|
||||
children.setdefault(row.parent_id, []).append(row)
|
||||
|
||||
def descendants(task_id: int) -> list[WbsTask]:
|
||||
out: list[WbsTask] = []
|
||||
for child in children.get(task_id, []):
|
||||
out.append(child)
|
||||
out.extend(descendants(child.id))
|
||||
return out
|
||||
|
||||
out: dict[int, dict[str, Any]] = {}
|
||||
for row in rows:
|
||||
subtree = descendants(row.id)
|
||||
if subtree:
|
||||
weights = [to_decimal(child.weight or 1) for child in subtree]
|
||||
total_weight = sum(weights) or to_decimal(1)
|
||||
progress = sum((to_decimal(child.progress) * weight
|
||||
for child, weight in zip(subtree, weights)), to_decimal(0)) / total_weight
|
||||
else:
|
||||
progress = to_decimal(row.progress)
|
||||
out[row.id] = {
|
||||
"rollupProgress": f"{progress:.1f}",
|
||||
"childCount": len(children.get(row.id, [])),
|
||||
"descendantCount": len(subtree),
|
||||
"budgetRollup": money_str(sum((child.budget_amount for child in subtree),
|
||||
to_decimal(0)) + row.budget_amount),
|
||||
"actualRollup": money_str(sum((child.actual_amount for child in subtree),
|
||||
to_decimal(0)) + row.actual_amount),
|
||||
"doneCount": sum(1 for child in subtree if child.status == WbsTaskStatus.DONE),
|
||||
"isLeaf": not children.get(row.id),
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/projects/{project_id}/wbs")
|
||||
def list_wbs(project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_require(current, "wbs", write=False)
|
||||
assert_project_visible(db, current, project_id)
|
||||
rows = db.execute(
|
||||
select(WbsTask).where(WbsTask.project_id == project_id, WbsTask.is_deleted.is_(False))
|
||||
.order_by(WbsTask.path, WbsTask.sort, WbsTask.id)
|
||||
).scalars().all()
|
||||
rollup = _rollup(list(rows))
|
||||
items = [_wbs_view(row, rollup) for row in rows]
|
||||
tops = [item for item in items if not item["parentId"]]
|
||||
summary = {
|
||||
"tasks": len(items),
|
||||
"done": sum(1 for item in items if item["status"] == WbsTaskStatus.DONE),
|
||||
"blocked": sum(1 for item in items if item["status"] == WbsTaskStatus.BLOCKED),
|
||||
"budget": money_str(sum((row.budget_amount for row in rows), to_decimal(0))),
|
||||
"actual": money_str(sum((row.actual_amount for row in rows), to_decimal(0))),
|
||||
"progress": tops[0]["rollupProgress"] if tops and len(tops) == 1 else
|
||||
(f"{sum(float(item['rollupProgress']) for item in tops) / len(tops):.1f}" if tops else "0.0"),
|
||||
}
|
||||
return ok({"items": items, "summary": summary})
|
||||
|
||||
|
||||
@router.post("/projects/{project_id}/wbs")
|
||||
def create_wbs(project_id: int, body: WbsBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_require(current, "wbs")
|
||||
assert_project_visible(db, current, project_id)
|
||||
if not body.name.strip():
|
||||
raise conflict("name_required", "任务名称不能为空")
|
||||
parent: WbsTask | None = None
|
||||
if body.parentId:
|
||||
parent = db.get(WbsTask, body.parentId)
|
||||
if parent is None or parent.project_id != project_id:
|
||||
raise not_found("父任务不存在")
|
||||
siblings = db.execute(
|
||||
select(func.count(WbsTask.id)).where(
|
||||
WbsTask.project_id == project_id, WbsTask.is_deleted.is_(False),
|
||||
WbsTask.parent_id == (parent.id if parent else None))
|
||||
).scalar() or 0
|
||||
row = WbsTask(
|
||||
project_id=project_id, parent_id=parent.id if parent else None,
|
||||
level=(parent.level + 1) if parent else 1,
|
||||
code=_wbs_code(db, parent, int(siblings) + 1),
|
||||
name=body.name.strip(), milestone_id=body.milestoneId,
|
||||
owner_id=body.ownerId, owner_name=_account_name(db, body.ownerId),
|
||||
plan_start=_date(body.planStart), plan_end=_date(body.planEnd),
|
||||
actual_start=_date(body.actualStart), actual_end=_date(body.actualEnd),
|
||||
weight=to_decimal(body.weight or 1), progress=body.progress or 0,
|
||||
status=body.status if body.status in WbsTaskStatus.LABELS else WbsTaskStatus.NOT_STARTED,
|
||||
budget_amount=to_decimal(body.budgetAmount or 0),
|
||||
actual_amount=to_decimal(body.actualAmount or 0),
|
||||
remark=body.remark, sort=(int(siblings) + 1) * 10,
|
||||
)
|
||||
db.add(row)
|
||||
db.flush()
|
||||
row.path = f"{parent.path if parent else '/'}{row.id}/"
|
||||
db.commit()
|
||||
return ok({"id": row.id, "code": row.code, "path": row.path})
|
||||
|
||||
|
||||
@router.put("/wbs/{task_id}")
|
||||
def update_wbs(task_id: int, body: WbsBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_require(current, "wbs")
|
||||
row = db.get(WbsTask, task_id)
|
||||
if row is None or row.is_deleted:
|
||||
raise not_found("任务不存在")
|
||||
assert_project_visible(db, current, row.project_id)
|
||||
if body.name.strip():
|
||||
row.name = body.name.strip()
|
||||
if body.milestoneId is not None:
|
||||
row.milestone_id = body.milestoneId
|
||||
if body.ownerId is not None:
|
||||
row.owner_id = body.ownerId
|
||||
row.owner_name = _account_name(db, body.ownerId)
|
||||
for text, column in ((body.planStart, "plan_start"), (body.planEnd, "plan_end"),
|
||||
(body.actualStart, "actual_start"), (body.actualEnd, "actual_end")):
|
||||
if text:
|
||||
setattr(row, column, _date(text))
|
||||
if body.weight:
|
||||
row.weight = to_decimal(body.weight)
|
||||
if body.progress is not None:
|
||||
row.progress = max(0, min(100, int(body.progress)))
|
||||
if row.progress >= 100 and body.status not in WbsTaskStatus.LABELS:
|
||||
row.status = WbsTaskStatus.DONE
|
||||
if body.status in WbsTaskStatus.LABELS:
|
||||
row.status = body.status
|
||||
if body.budgetAmount != "":
|
||||
row.budget_amount = to_decimal(body.budgetAmount or 0)
|
||||
if body.actualAmount != "":
|
||||
row.actual_amount = to_decimal(body.actualAmount or 0)
|
||||
if body.remark is not None:
|
||||
row.remark = body.remark
|
||||
db.commit()
|
||||
return ok(_wbs_view(row))
|
||||
|
||||
|
||||
@router.delete("/wbs/{task_id}")
|
||||
def delete_wbs(task_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
"""删任务连同子树一起软删:留一堆父节点已没了的孤儿子在树上,界面上没法摆。"""
|
||||
_require(current, "wbs")
|
||||
row = db.get(WbsTask, task_id)
|
||||
if row is None or row.is_deleted:
|
||||
raise not_found("任务不存在")
|
||||
assert_project_visible(db, current, row.project_id)
|
||||
subtree = db.execute(
|
||||
select(WbsTask).where(WbsTask.project_id == row.project_id,
|
||||
WbsTask.is_deleted.is_(False),
|
||||
WbsTask.path.like(f"{row.path}%"))
|
||||
).scalars().all()
|
||||
for item in subtree:
|
||||
item.is_deleted = True
|
||||
db.commit()
|
||||
return ok({"deleted": True, "count": len(subtree)})
|
||||
|
|
@ -0,0 +1,904 @@
|
|||
"""项目主档:列表、详情、创建、成员、阶段、删除与恢复。
|
||||
|
||||
列表一律先过数据权限再分页,计数也用同一个条件,否则会出现"总数 500 但只列得出来 3 条"。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Query, Request
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import func, or_, select
|
||||
|
||||
from .. import dicts as dict_store
|
||||
from ..deps import DbSession, Principal, PrincipalOf, assert_project_visible
|
||||
from ..envelope import conflict, forbidden, not_found, ok, page
|
||||
from ..models import (
|
||||
Account,
|
||||
ApprovalInstance,
|
||||
ApprovalRecord,
|
||||
Attachment,
|
||||
BudgetFundMonth,
|
||||
BudgetIncomeLine,
|
||||
BudgetIncomePlanLine,
|
||||
BudgetManageLine,
|
||||
BudgetOtherCostLine,
|
||||
BudgetPayPlanLine,
|
||||
BudgetPurchaseLine,
|
||||
CalcSnapshot,
|
||||
EstimateCostLine,
|
||||
EstimateIncomeLine,
|
||||
EstimateOtherLine,
|
||||
InstanceStatus,
|
||||
Project,
|
||||
ProjectMember,
|
||||
ProjectMemberRole,
|
||||
ProjectSource,
|
||||
ProjectStage,
|
||||
ProjectStageLog,
|
||||
SaleStage,
|
||||
ProjectVisibleRole,
|
||||
Revision,
|
||||
RevisionModule,
|
||||
RevisionStatus,
|
||||
to_decimal,
|
||||
)
|
||||
from ..service import audit, biz
|
||||
from ..service.calc.money import money_str
|
||||
|
||||
router = APIRouter(prefix="/projects", tags=["projects"])
|
||||
|
||||
|
||||
class ProjectBody(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=1000)
|
||||
otherName: str = ""
|
||||
type: int = 0
|
||||
projectNo: str = ""
|
||||
customer: str = ""
|
||||
terminalCustomer: str = ""
|
||||
planStart: str = ""
|
||||
planEnd: str = ""
|
||||
contractTime: str = ""
|
||||
bidsTime: str = ""
|
||||
underwrittenMode: int | None = None
|
||||
cooperateType: int | None = None
|
||||
collaborator: str = ""
|
||||
certainty: int | None = None
|
||||
isSecond: int | None = None
|
||||
isHuizhiBid: int | None = None
|
||||
saleStage: int | None = None
|
||||
stage: int | None = None
|
||||
signType: int | None = None
|
||||
resolvePlan: int | None = None
|
||||
industryScene: int = 0
|
||||
industrySceneDesc: str = ""
|
||||
principalId: int | None = None
|
||||
mainContractCollectionTerms: str = ""
|
||||
mainContractResolvePlan: str = ""
|
||||
calculationCollection: str = ""
|
||||
valueRisk: str = ""
|
||||
advanceInterestRate: str = ""
|
||||
stageRemark: str = ""
|
||||
nextPlan: str = ""
|
||||
memberIds: list[int] = Field(default_factory=list)
|
||||
# 立项表上可以直接录入的金额。录了测算明细之后,这几个数改由计算投影覆盖
|
||||
# (见 biz.apply_projection:有明细行才投影),手填值只在没明细时生效。
|
||||
contractAmount: str = ""
|
||||
grossProfit: str = ""
|
||||
grossProfitRate: str = ""
|
||||
huizhiAmount: str = ""
|
||||
huazhiAmount: str = ""
|
||||
h3cAmount: str = ""
|
||||
otherProductAmount: str = ""
|
||||
|
||||
|
||||
class MemberBody(BaseModel):
|
||||
accountIds: list[int] = Field(default_factory=list)
|
||||
memberRole: str = ProjectMemberRole.PARTICIPANT
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_projects(
|
||||
db: DbSession,
|
||||
current: PrincipalOf,
|
||||
keyword: str = "",
|
||||
type: int | None = None,
|
||||
stage: int | None = None,
|
||||
orgUnitId: int | None = None,
|
||||
underwrittenMode: int | None = None,
|
||||
initiationStatus: str = "",
|
||||
onlyMine: bool = False,
|
||||
deletedOnly: bool = False,
|
||||
pageNo: int = Query(1, ge=1),
|
||||
pageSize: int = Query(20, ge=1, le=200),
|
||||
orderBy: str = "-updated_at",
|
||||
) -> dict[str, Any]:
|
||||
if not current.permission.can_any(("project:project:view", "project:project:edit")):
|
||||
raise forbidden("缺少权限:project:project:view")
|
||||
|
||||
from ..service.data_scope import descendant_unit_ids, evaluate
|
||||
|
||||
# deletedOnly 是回收站:同一个数据权限条件,只把"有效/已删除"这一维翻过来,
|
||||
# 不能因为换了个视图就让人看到别人删掉的项目。
|
||||
statement = select(Project).where(
|
||||
Project.is_deleted.is_(True) if deletedOnly else Project.is_deleted.is_(False)
|
||||
)
|
||||
decision = evaluate(db, "project", current.scope)
|
||||
statement = decision.apply_to(statement)
|
||||
|
||||
if keyword:
|
||||
like = f"%{keyword}%"
|
||||
statement = statement.where(or_(Project.name.like(like), Project.project_no.like(like),
|
||||
Project.customer.like(like), Project.other_name.like(like)))
|
||||
if type is not None:
|
||||
statement = statement.where(Project.type == type)
|
||||
if stage is not None:
|
||||
statement = statement.where(Project.stage == stage)
|
||||
if orgUnitId:
|
||||
statement = statement.where(Project.org_unit_id.in_(descendant_unit_ids(db, [orgUnitId])))
|
||||
if underwrittenMode is not None:
|
||||
statement = statement.where(Project.underwritten_mode == underwrittenMode)
|
||||
if onlyMine:
|
||||
statement = statement.where(or_(
|
||||
Project.creator_id == current.account.id,
|
||||
Project.principal_id == current.account.id,
|
||||
Project.id.in_(select(ProjectMember.project_id).where(
|
||||
ProjectMember.account_id == current.account.id)),
|
||||
))
|
||||
if initiationStatus:
|
||||
# 两个模块列表共用这一条查询:立项列表看全部,预算列表看 approved。
|
||||
# "none" 是还没建过立项版本的项目——老系统迁过来的八百多个项目就是这么一大片,
|
||||
# 新系统里它们算"还没立项",得能在界面上筛出来。
|
||||
wanted = [item.strip() for item in initiationStatus.split(",") if item.strip()]
|
||||
if "none" in wanted:
|
||||
statement = statement.where(Project.id.notin_(
|
||||
select(Revision.project_id).where(Revision.module == RevisionModule.ESTIMATE,
|
||||
Revision.is_deleted.is_(False))))
|
||||
else:
|
||||
statement = statement.where(Project.id.in_(
|
||||
select(Revision.project_id).where(
|
||||
Revision.module == RevisionModule.ESTIMATE,
|
||||
Revision.is_deleted.is_(False),
|
||||
Revision.status.in_([item for item in wanted if item != "none"]))))
|
||||
|
||||
total = db.execute(select(func.count()).select_from(statement.subquery())).scalar() or 0
|
||||
order_column = _order_column(orderBy)
|
||||
rows = db.execute(statement.order_by(order_column).offset((pageNo - 1) * pageSize).limit(pageSize)
|
||||
).scalars().all()
|
||||
states = _initiation_states(db, [row.id for row in rows])
|
||||
result = page([_project_view(db, row, states.get(row.id)) for row in rows], total, pageNo, pageSize)
|
||||
# 把"你看到的是哪个范围"一起返回,用户不用猜为什么少了几条
|
||||
result["data"]["scope"] = decision.to_dict()
|
||||
return result
|
||||
|
||||
|
||||
def _order_column(order_by: str):
|
||||
mapping = {
|
||||
"updated_at": Project.updated_at, "created_at": Project.created_at,
|
||||
"contract_amount": Project.contract_amount, "project_no": Project.project_no,
|
||||
"contribution_profit_rate": Project.contribution_profit_rate,
|
||||
}
|
||||
descending = order_by.startswith("-")
|
||||
column = mapping.get(order_by.lstrip("-"), Project.updated_at)
|
||||
return column.desc() if descending else column.asc()
|
||||
|
||||
|
||||
def _s(value: Any) -> str:
|
||||
return money_str(value)
|
||||
|
||||
|
||||
def _t(value: datetime | None) -> str:
|
||||
return value.isoformat(sep=" ", timespec="seconds") if value else ""
|
||||
|
||||
|
||||
def _initiation_states(db, project_ids: list[int]) -> dict[int, dict[str, Any]]:
|
||||
"""一次把这一页项目的立项状态捞回来。
|
||||
|
||||
逐行走 :func:`biz.initiation_state` 会变成每行两条 SQL,一页 20 行就是 40 条查询;
|
||||
这里改成一条:把这一页项目的立项版本全捞出来,在内存里挑"最近一版"与"最近通过版"。
|
||||
"""
|
||||
if not project_ids:
|
||||
return {}
|
||||
rows = db.execute(
|
||||
select(Revision.project_id, Revision.id, Revision.version, Revision.status,
|
||||
Revision.decided_at)
|
||||
.where(Revision.project_id.in_(project_ids), Revision.module == RevisionModule.ESTIMATE,
|
||||
Revision.is_deleted.is_(False))
|
||||
.order_by(Revision.version.desc())
|
||||
).all()
|
||||
latest: dict[int, tuple] = {}
|
||||
approved: dict[int, tuple] = {}
|
||||
for row in rows:
|
||||
latest.setdefault(row.project_id, row)
|
||||
if row.status == RevisionStatus.APPROVED:
|
||||
approved.setdefault(row.project_id, row)
|
||||
out: dict[int, dict[str, Any]] = {}
|
||||
for project_id in project_ids:
|
||||
head, passed = latest.get(project_id), approved.get(project_id)
|
||||
out[project_id] = {
|
||||
"status": head.status if head else "",
|
||||
"statusLabel": dict_store.label(db, "revisionStatus", head.status, head.status) if head else "未立项",
|
||||
"version": head.version if head else 0,
|
||||
"revisionId": head.id if head else None,
|
||||
"approvedVersion": passed.version if passed else 0,
|
||||
"approvedRevisionId": passed.id if passed else None,
|
||||
"approvedAt": _t(passed.decided_at) if passed else "",
|
||||
"budgetReady": passed is not None,
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
def _project_view(db, row: Project, initiation: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
return {
|
||||
"id": row.id, "projectNo": row.project_no, "name": row.name, "otherName": row.other_name,
|
||||
"type": row.type, "stage": row.stage, "stageLabel": row.stage_label,
|
||||
"customer": row.customer, "terminalCustomer": row.terminal_customer,
|
||||
"orgUnitId": row.org_unit_id, "orgUnitName": row.org_unit_name,
|
||||
"creatorId": row.creator_id, "creatorName": row.creator_name,
|
||||
"principal": row.principal, "principalId": row.principal_id,
|
||||
"underwrittenMode": row.underwritten_mode,
|
||||
"contractAmount": _s(row.contract_amount),
|
||||
"grossProfitA": _s(row.gross_profit_a), "grossProfitARate": _s(row.gross_profit_a_rate),
|
||||
"grossProfit": _s(row.gross_profit), "grossProfitRate": _s(row.gross_profit_rate),
|
||||
"contributionProfit": _s(row.contribution_profit),
|
||||
"contributionProfitRate": _s(row.contribution_profit_rate),
|
||||
"advancePeakAmount": _s(row.advance_peak_value),
|
||||
"advancePeakMonth": row.advance_peak_month,
|
||||
"advanceInterestAmount": _s(row.advance_interest_amount),
|
||||
"calcVersion": row.calc_version,
|
||||
"source": row.source,
|
||||
"sourceLabel": ProjectSource.LABELS.get(row.source, row.source),
|
||||
"saleStage": row.sale_stage,
|
||||
"saleStageLabel": dict_store.label(db, "saleStage", row.sale_stage, "未填写"),
|
||||
"isHuizhiBid": row.is_huizhi_bid,
|
||||
"certainty": row.certainty,
|
||||
"certaintyLabel": dict_store.label(db, "certainty", row.certainty, ""),
|
||||
"industrySceneLabel": dict_store.label(db, "industryScene", row.industry_scene, ""),
|
||||
"initiation": initiation or {},
|
||||
"createdAt": _t(row.created_at), "updatedAt": _t(row.updated_at),
|
||||
"deletedAt": _t(row.deleted_at), "deletedByName": row.deleted_by_name,
|
||||
"deleteReason": row.delete_reason,
|
||||
}
|
||||
|
||||
|
||||
def _project_detail(db, row: Project, initiation: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
data = _project_view(db, row, initiation)
|
||||
data.update({
|
||||
"planStart": row.plan_start.isoformat() if row.plan_start else "",
|
||||
"planEnd": row.plan_end.isoformat() if row.plan_end else "",
|
||||
"contractTime": _t(row.contract_time), "bidsTime": _t(row.bids_time),
|
||||
"cooperateType": row.cooperate_type, "collaborator": row.collaborator,
|
||||
"collaboratorAttachment": row.collaborator_attachment,
|
||||
"certainty": row.certainty, "isSecond": row.is_second, "signType": row.sign_type,
|
||||
"isHuizhiBid": row.is_huizhi_bid,
|
||||
"saleStage": row.sale_stage,
|
||||
"saleStageLabel": dict_store.label(db, "saleStage", row.sale_stage, "未填写"),
|
||||
"certaintyLabel": dict_store.label(db, "certainty", row.certainty, ""),
|
||||
"isSecondLabel": dict_store.label(db, "yesNo", row.is_second, ""),
|
||||
"isHuizhiBidLabel": dict_store.label(db, "yesNo", row.is_huizhi_bid, ""),
|
||||
"industrySceneLabel": dict_store.label(db, "industryScene", row.industry_scene, ""),
|
||||
"grossProfit": _s(row.gross_profit), "grossProfitRate": _s(row.gross_profit_rate),
|
||||
"resolvePlan": row.resolve_plan, "industryScene": row.industry_scene,
|
||||
"industrySceneDesc": row.industry_scene_desc,
|
||||
"mainContractCollectionTerms": row.main_contract_collection_terms,
|
||||
"mainContractResolvePlan": row.main_contract_resolve_plan,
|
||||
"calculationCollection": row.calculation_collection, "valueRisk": row.value_risk,
|
||||
"stageRemark": row.stage_remark, "nextPlan": row.next_plan,
|
||||
"advanceInterestRate": _s(row.advance_interest_rate),
|
||||
"advancePlanTotal": _s(row.advance_plan_total),
|
||||
"huazhiAmount": _s(row.huazhi_amount), "huizhiAmount": _s(row.huizhi_amount),
|
||||
"h3cAmount": _s(row.h3c_amount), "otherProductAmount": _s(row.other_product_amount),
|
||||
"calcSnapshotId": row.calc_snapshot_id, "calcAt": _t(row.calc_at),
|
||||
})
|
||||
return data
|
||||
|
||||
|
||||
@router.get("/options")
|
||||
def project_options(db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
"""项目类型/阶段/垫资模式这些枚举统一从数据字典取,前后端都不再自己抄一份。"""
|
||||
return ok({
|
||||
"types": dict_store.options(db, "projectType"),
|
||||
"stages": dict_store.options(db, "projectStage"),
|
||||
"underwrittenModes": dict_store.options(db, "underwrittenMode"),
|
||||
"memberRoles": dict_store.options(db, "projectMemberRole"),
|
||||
"certainties": dict_store.options(db, "certainty"),
|
||||
"industryScenes": dict_store.options(db, "industryScene"),
|
||||
"saleStages": dict_store.options(db, "saleStage"),
|
||||
"yesNo": dict_store.options(db, "yesNo"),
|
||||
})
|
||||
|
||||
|
||||
@router.post("")
|
||||
def create_project(body: ProjectBody, request: Request, db: DbSession,
|
||||
current: PrincipalOf) -> dict[str, Any]:
|
||||
if not current.permission.can("project:project:create"):
|
||||
raise forbidden("缺少权限:project:project:create")
|
||||
account = current.account
|
||||
unit = account.org_unit
|
||||
project = Project(
|
||||
name=body.name, other_name=body.otherName, type=body.type or 0,
|
||||
project_no=body.projectNo.strip() or next_project_no(db),
|
||||
creator_id=account.id, creator_name=account.display_name or account.account,
|
||||
org_unit_id=account.org_unit_id, org_unit_name=unit.name if unit else "",
|
||||
stage=body.stage if body.stage in ProjectStage.LABELS else ProjectStage.S0_INITIATION,
|
||||
customer=body.customer, terminal_customer=body.terminalCustomer,
|
||||
plan_start=_date(body.planStart), plan_end=_date(body.planEnd),
|
||||
contract_time=_datetime(body.contractTime), bids_time=_datetime(body.bidsTime),
|
||||
underwritten_mode=body.underwrittenMode, cooperate_type=body.cooperateType,
|
||||
collaborator=body.collaborator, certainty=body.certainty, is_second=body.isSecond,
|
||||
is_huizhi_bid=body.isHuizhiBid, sale_stage=body.saleStage
|
||||
if body.saleStage is not None else SaleStage.UNSET,
|
||||
sign_type=body.signType, resolve_plan=body.resolvePlan,
|
||||
industry_scene=body.industryScene or 0, industry_scene_desc=body.industrySceneDesc,
|
||||
principal_id=body.principalId or account.id,
|
||||
main_contract_collection_terms=body.mainContractCollectionTerms,
|
||||
main_contract_resolve_plan=body.mainContractResolvePlan,
|
||||
calculation_collection=body.calculationCollection, value_risk=body.valueRisk,
|
||||
advance_interest_rate=to_decimal(body.advanceInterestRate),
|
||||
stage_remark=body.stageRemark, next_plan=body.nextPlan,
|
||||
source=ProjectSource.LOCAL,
|
||||
)
|
||||
_apply_manual_amounts(project, body)
|
||||
# 负责人没点名就是创建人:姓名与账号一起落,别只留 principal_id。
|
||||
# 只留 id 会让主档上那一列一直是空串,立项表的"项目负责人"必填就永远卡着,
|
||||
# 列表页那列也是空的。
|
||||
if not project.principal and project.principal_id:
|
||||
owner = account if project.principal_id == account.id else db.get(Account, project.principal_id)
|
||||
project.principal = (owner.display_name or owner.account) if owner else ""
|
||||
db.add(project)
|
||||
db.flush()
|
||||
# 负责人没点名就是创建人:姓名与账号一起落,别只留 principal_id——
|
||||
# 主档那列空着,立项表的"项目负责人"必填就永远卡着,列表页这一列也是空的。
|
||||
if project.principal_id and not project.principal:
|
||||
owner = account if project.principal_id == account.id else db.get(Account, project.principal_id)
|
||||
if owner is not None:
|
||||
project.principal = owner.display_name or owner.account
|
||||
|
||||
# 负责人先落成员表(sync_owner_member 内部会去重),创建人只有在不是负责人时才另记一条,
|
||||
# 否则同一个人会被插两次,撞上 uk_project_member 唯一键。
|
||||
biz.sync_owner_member(db, project)
|
||||
member_ids = {account.id} | set(body.memberIds or [])
|
||||
if project.principal_id:
|
||||
member_ids.add(project.principal_id)
|
||||
existing_members = {project.principal_id} if project.principal_id else set()
|
||||
for account_id in member_ids:
|
||||
if account_id in existing_members:
|
||||
continue
|
||||
target = account if account_id == account.id else db.get(Account, account_id)
|
||||
if target is None or target.is_deleted:
|
||||
continue
|
||||
db.add(ProjectMember(project_id=project.id, account_id=account_id,
|
||||
account_name=target.display_name or target.account,
|
||||
member_role=ProjectMemberRole.PARTICIPANT))
|
||||
existing_members.add(account_id)
|
||||
db.add(ProjectStageLog(project_id=project.id, stage=project.stage, stage_label=project.stage_label,
|
||||
account_id=account.id, account_name=account.display_name or account.account,
|
||||
remark="创建项目"))
|
||||
db.commit()
|
||||
audit.enrich(request, object_name=project.name, projectNo=project.project_no)
|
||||
return ok({"id": project.id})
|
||||
|
||||
|
||||
def next_project_no(db) -> str:
|
||||
"""生成项目编号:``前缀 + 年份 + 当年四位流水``(例:FS26-0007)。
|
||||
|
||||
立项表上这一栏写的是"保存后默认提供",所以编号得在保存那一刻就有,不能指望
|
||||
事后再补。取当年已有最大流水 +1,不锁表:两个人同时建项目撞上同一个号的概率
|
||||
极低,真撞了 ``uk_project_no``……库里并没有这个唯一键,所以这里只做一次存在性
|
||||
重试,比加表锁合适。
|
||||
"""
|
||||
from ..models import SystemConfig
|
||||
|
||||
prefix = (db.execute(select(SystemConfig.value).where(
|
||||
SystemConfig.code == "project.no_prefix")).scalars().first() or "FS").strip() or "FS"
|
||||
year = datetime.now().year
|
||||
head = f"{prefix}{year % 100:02d}-"
|
||||
like = f"{head}%"
|
||||
numbers = [int(no[len(head):]) for (no,) in db.execute(
|
||||
select(Project.project_no).where(Project.project_no.like(like))
|
||||
) if no[len(head):].isdigit()]
|
||||
candidate_index = (max(numbers) + 1) if numbers else 1
|
||||
existing = {row[0] for row in db.execute(
|
||||
select(Project.project_no).where(Project.project_no.like(like))).all()}
|
||||
while f"{head}{candidate_index:04d}" in existing:
|
||||
candidate_index += 1
|
||||
return f"{head}{candidate_index:04d}"
|
||||
|
||||
|
||||
def _apply_manual_amounts(project: Project, body: "ProjectBody") -> None:
|
||||
"""立项表上手填的那几个金额。空串表示"这一栏没动",不是"清零"。"""
|
||||
pairs = (
|
||||
(body.contractAmount, "contract_amount"), (body.grossProfit, "gross_profit"),
|
||||
(body.grossProfitRate, "gross_profit_rate"), (body.huizhiAmount, "huizhi_amount"),
|
||||
(body.huazhiAmount, "huazhi_amount"), (body.h3cAmount, "h3c_amount"),
|
||||
(body.otherProductAmount, "other_product_amount"),
|
||||
)
|
||||
for text, column in pairs:
|
||||
if text not in (None, ""):
|
||||
setattr(project, column, to_decimal(text))
|
||||
|
||||
|
||||
def _date(value: str | None) -> date | None:
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
text = value.strip()
|
||||
if len(text) == 7: # 日期选择器可能只给到月(YYYY-MM),补成当月 1 号
|
||||
text += "-01"
|
||||
return date.fromisoformat(text[:10])
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _datetime(value: str | None) -> datetime | None:
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
return datetime.fromisoformat(value.strip().replace("Z", ""))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
@router.get("/{project_id}")
|
||||
def get_project(project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
project = assert_project_visible(db, current, project_id)
|
||||
members = db.execute(select(ProjectMember).where(ProjectMember.project_id == project_id)
|
||||
.order_by(ProjectMember.id)).scalars().all()
|
||||
stage_logs = db.execute(select(ProjectStageLog).where(ProjectStageLog.project_id == project_id)
|
||||
.order_by(ProjectStageLog.id.desc())).scalars().all()
|
||||
data = _project_detail(db, project, biz.initiation_state(db, project_id))
|
||||
data["members"] = [{"id": row.id, "accountId": row.account_id, "accountName": row.account_name,
|
||||
"memberRole": row.member_role,
|
||||
"memberRoleLabel": dict_store.label(
|
||||
db, "projectMemberRole", row.member_role, row.member_role)}
|
||||
for row in members]
|
||||
data["stageLogs"] = [{"id": row.id, "stage": row.stage, "stageLabel": row.stage_label,
|
||||
"accountName": row.account_name, "remark": row.remark,
|
||||
"createdAt": _t(row.created_at)} for row in stage_logs]
|
||||
return ok(data)
|
||||
|
||||
|
||||
@router.put("/{project_id}")
|
||||
def update_project(project_id: int, body: ProjectBody, request: Request, db: DbSession,
|
||||
current: PrincipalOf) -> dict[str, Any]:
|
||||
project = assert_project_visible(db, current, project_id)
|
||||
if not current.permission.can("project:project:edit"):
|
||||
raise forbidden("缺少权限:project:project:edit")
|
||||
_assert_project_owner(current, project, "修改项目信息")
|
||||
|
||||
project.name = body.name
|
||||
project.other_name = body.otherName
|
||||
project.type = body.type or project.type
|
||||
project.project_no = body.projectNo
|
||||
project.customer = body.customer
|
||||
project.terminal_customer = body.terminalCustomer
|
||||
project.plan_start = _date(body.planStart)
|
||||
project.plan_end = _date(body.planEnd)
|
||||
project.contract_time = _datetime(body.contractTime)
|
||||
project.bids_time = _datetime(body.bidsTime)
|
||||
project.underwritten_mode = body.underwrittenMode
|
||||
project.cooperate_type = body.cooperateType
|
||||
project.collaborator = body.collaborator
|
||||
project.certainty = body.certainty
|
||||
project.is_second = body.isSecond
|
||||
project.is_huizhi_bid = body.isHuizhiBid
|
||||
if body.saleStage is not None:
|
||||
project.sale_stage = body.saleStage
|
||||
if body.stage in ProjectStage.LABELS:
|
||||
project.stage = body.stage
|
||||
project.sign_type = body.signType
|
||||
project.resolve_plan = body.resolvePlan
|
||||
project.industry_scene = body.industryScene or 0
|
||||
project.industry_scene_desc = body.industrySceneDesc
|
||||
project.main_contract_collection_terms = body.mainContractCollectionTerms
|
||||
project.main_contract_resolve_plan = body.mainContractResolvePlan
|
||||
project.calculation_collection = body.calculationCollection
|
||||
project.value_risk = body.valueRisk
|
||||
project.advance_interest_rate = to_decimal(body.advanceInterestRate)
|
||||
project.stage_remark = body.stageRemark
|
||||
project.next_plan = body.nextPlan
|
||||
_apply_manual_amounts(project, body)
|
||||
if body.principalId:
|
||||
project.principal_id = body.principalId
|
||||
owner = db.get(Account, body.principalId)
|
||||
project.principal = (owner.display_name or owner.account) if owner else project.principal
|
||||
biz.sync_owner_member(db, project)
|
||||
db.commit()
|
||||
audit.enrich(request, object_name=project.name, projectNo=project.project_no)
|
||||
return ok({"id": project.id})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 删除与恢复:软删除,回收站走同一条数据权限
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: 合同期及其之后的阶段。删掉这一档的项目要额外提醒一句——合同、结算都挂在上面,
|
||||
#: 而"项目丢失"(S9) 虽然编号更靠后,恰恰是最该允许清掉的那类,所以不在这个名单里。
|
||||
LATE_STAGES = (ProjectStage.S5_CONTRACT, ProjectStage.S6_DELIVERY,
|
||||
ProjectStage.S7_SETTLEMENT, ProjectStage.S8_FINAL)
|
||||
|
||||
|
||||
class DeleteBody(BaseModel):
|
||||
reason: str = Field(default="", max_length=500)
|
||||
|
||||
|
||||
def _assert_project_owner(current: Principal, project: Project, action: str) -> None:
|
||||
"""主档级改动(改、删、恢复)的归属判定:系统管理员,或创建人、项目负责人。
|
||||
|
||||
数据权限管"看得见",这条管"动得了"——财务能看全公司项目,不等于能把别人的项目删掉。
|
||||
"""
|
||||
if not (current.permission.is_system_admin or project.creator_id == current.account.id
|
||||
or project.principal_id == current.account.id):
|
||||
raise forbidden(f"只有创建人或项目负责人可以{action}")
|
||||
|
||||
|
||||
def _count(db, statement) -> int:
|
||||
return db.execute(statement).scalar() or 0
|
||||
|
||||
|
||||
def _delete_report(db, project: Project) -> dict[str, Any]:
|
||||
"""删除前的影响面清单。
|
||||
|
||||
只有**审批还在流转**这一条真挡删除:实例活着、待办挂在别人名下,项目一消失,
|
||||
那些人手里就剩一条点不开的待办。已通过的版本、附件、历史审批都只是"连带藏起来",
|
||||
恢复即全部回来,所以只列出来让人看清楚,不拦。
|
||||
"""
|
||||
revision_statuses = db.execute(
|
||||
select(Revision.status).where(Revision.project_id == project.id,
|
||||
Revision.is_deleted.is_(False))
|
||||
).scalars().all()
|
||||
approved = sum(1 for status in revision_statuses if status == RevisionStatus.APPROVED)
|
||||
reviewing = _count(db, select(func.count(ApprovalInstance.id)).where(
|
||||
ApprovalInstance.project_id == project.id,
|
||||
ApprovalInstance.status == InstanceStatus.REVIEWING))
|
||||
instances = _count(db, select(func.count(ApprovalInstance.id)).where(
|
||||
ApprovalInstance.project_id == project.id))
|
||||
attachments = _count(db, select(func.count(Attachment.id)).where(
|
||||
Attachment.object_id == project.id, Attachment.is_deleted.is_(False)))
|
||||
members = _count(db, select(func.count(ProjectMember.id)).where(
|
||||
ProjectMember.project_id == project.id))
|
||||
|
||||
blockers: list[dict[str, str]] = []
|
||||
warnings: list[dict[str, str]] = []
|
||||
if reviewing:
|
||||
blockers.append({
|
||||
"code": "approval_in_progress",
|
||||
"message": f"有 {reviewing} 个审批正在流转,请先撤回送审或等审批出结果",
|
||||
})
|
||||
if approved:
|
||||
warnings.append({
|
||||
"code": "has_approved_revision",
|
||||
"message": f"已有 {approved} 个审批通过的版本,删除后这些口径在列表里查不到",
|
||||
})
|
||||
if project.stage in LATE_STAGES:
|
||||
warnings.append({
|
||||
"code": "late_stage",
|
||||
"message": f"项目已进入「{project.stage_label}」,删除前请确认合同与结算已经了结",
|
||||
})
|
||||
if attachments:
|
||||
warnings.append({"code": "has_attachment",
|
||||
"message": f"项目还挂着 {attachments} 个附件"})
|
||||
if instances and not reviewing:
|
||||
warnings.append({"code": "has_approval_history",
|
||||
"message": f"有 {instances} 条历史审批记录"})
|
||||
|
||||
return {
|
||||
"projectName": project.name, "projectNo": project.project_no,
|
||||
"stage": project.stage, "stageLabel": project.stage_label,
|
||||
"deletable": not blockers, "blockers": blockers, "warnings": warnings,
|
||||
"stats": {
|
||||
"members": members, "attachments": attachments,
|
||||
"revisions": len(revision_statuses), "approvedRevisions": approved,
|
||||
"approvalInstances": instances, "reviewingInstances": reviewing,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{project_id}/delete-check")
|
||||
def check_project_deletion(project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
"""删除确认框要显示的东西:能不能删、牵连多少。前端不自己猜规则。"""
|
||||
project = assert_project_visible(db, current, project_id)
|
||||
_assert_project_owner(current, project, "删除项目")
|
||||
return ok(_delete_report(db, project))
|
||||
|
||||
|
||||
@router.delete("/{project_id}")
|
||||
def delete_project(project_id: int, request: Request, db: DbSession, current: PrincipalOf,
|
||||
body: DeleteBody | None = None) -> dict[str, Any]:
|
||||
"""软删除。项目连同概算、预算、成员、附件一起从业务视图里消失,数据一行不少。"""
|
||||
project = assert_project_visible(db, current, project_id)
|
||||
if not current.permission.can("project:project:delete"):
|
||||
raise forbidden("缺少权限:project:project:delete")
|
||||
_assert_project_owner(current, project, "删除项目")
|
||||
report = _delete_report(db, project)
|
||||
if report["blockers"]:
|
||||
first = report["blockers"][0]
|
||||
raise conflict(first["code"], first["message"])
|
||||
|
||||
reason = (body.reason.strip() if body else "")[:500]
|
||||
project.is_deleted = True
|
||||
project.deleted_at = datetime.now()
|
||||
project.deleted_by_id = current.account.id
|
||||
project.deleted_by_name = current.account.display_name or current.account.account
|
||||
project.delete_reason = reason
|
||||
# 审计行由中间件统一写;这里只补"为什么删"和业务口径,不另开一条。
|
||||
audit.enrich(request, action="delete", object_name=project.name, reason=reason,
|
||||
stage=project.stage, stageLabel=project.stage_label,
|
||||
projectNo=project.project_no, stats=report["stats"])
|
||||
db.commit()
|
||||
return ok({"deleted": True, "id": project.id, "deletedAt": _t(project.deleted_at)})
|
||||
|
||||
|
||||
@router.post("/{project_id}/restore")
|
||||
def restore_project(project_id: int, request: Request, db: DbSession,
|
||||
current: PrincipalOf) -> dict[str, Any]:
|
||||
"""回收站里捞回来。删除留痕一并清掉,别拿上一次的原因冒充这一次的。"""
|
||||
project = assert_project_visible(db, current, project_id, allow_deleted=True)
|
||||
if not project.is_deleted:
|
||||
raise conflict("not_deleted", "这个项目没有被删除")
|
||||
if not current.permission.can("project:project:delete"):
|
||||
raise forbidden("缺少权限:project:project:delete")
|
||||
_assert_project_owner(current, project, "恢复项目")
|
||||
|
||||
previous_reason = project.delete_reason
|
||||
project.is_deleted = False
|
||||
project.deleted_at = None
|
||||
project.deleted_by_id = None
|
||||
project.deleted_by_name = ""
|
||||
project.delete_reason = ""
|
||||
audit.enrich(request, action="restore", object_name=project.name,
|
||||
previousDeleteReason=previous_reason)
|
||||
db.commit()
|
||||
return ok({"restored": True, "id": project.id})
|
||||
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 彻底删除:把回收站里的项目连同业务数据一起销毁,不可恢复
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: 销毁顺序(叶子在前)与界面上的说法。不依赖 MySQL 的外键级联:级联是这台库的配置,
|
||||
#: 不是这套代码的约束,写清楚每张表既能在任何后端删干净,也能把"删了多少"讲明白。
|
||||
PURGE_PLAN: tuple[tuple[str, tuple[type, ...]], ...] = (
|
||||
("概算明细", (EstimateIncomeLine, EstimateCostLine, EstimateOtherLine)),
|
||||
("预算明细", (BudgetIncomeLine, BudgetIncomePlanLine, BudgetPurchaseLine,
|
||||
BudgetPayPlanLine, BudgetManageLine, BudgetOtherCostLine, BudgetFundMonth)),
|
||||
("计算快照", (CalcSnapshot,)),
|
||||
("概算/预算版本", (Revision,)),
|
||||
("项目成员", (ProjectMember,)),
|
||||
("可见角色授权", (ProjectVisibleRole,)),
|
||||
("阶段流水", (ProjectStageLog,)),
|
||||
)
|
||||
|
||||
#: 附件是按 (object_type, object_id) 挂的多态表,只认项目这一族的挂法;
|
||||
#: 回收站/项目页能列出来的附件,和这里要销毁的附件,必须是同一批。
|
||||
PROJECT_ATTACHMENT_TYPES = ("project", "estimate", "budget", "settlement", "final")
|
||||
|
||||
|
||||
class PurgeBody(BaseModel):
|
||||
confirmName: str = Field(default="", max_length=1000)
|
||||
|
||||
|
||||
def _purge_counts(db, project: Project) -> dict[str, int]:
|
||||
"""数一遍销毁会带走多少行;附件按项目的挂点算。"""
|
||||
counts = {label: 0 for label, _ in PURGE_PLAN}
|
||||
for label, models in PURGE_PLAN:
|
||||
for model in models:
|
||||
counts[label] += _count(db, select(func.count(model.id)).where(
|
||||
model.project_id == project.id))
|
||||
counts["审批记录"] = _count(db, select(func.count(ApprovalRecord.id)).where(
|
||||
ApprovalRecord.project_id == project.id))
|
||||
counts["附件"] = _count(db, select(func.count(Attachment.id)).where(
|
||||
Attachment.object_id == project.id,
|
||||
Attachment.object_type.in_(PROJECT_ATTACHMENT_TYPES)))
|
||||
return counts
|
||||
|
||||
|
||||
def _purge_blockers(db, project: Project) -> list[dict[str, str]]:
|
||||
blockers: list[dict[str, str]] = []
|
||||
if not project.is_deleted:
|
||||
blockers.append({
|
||||
"code": "not_in_bin",
|
||||
"message": "只能销毁回收站里的项目,请先删除再彻底删除",
|
||||
})
|
||||
instances = _count(db, select(func.count(ApprovalInstance.id)).where(
|
||||
ApprovalInstance.project_id == project.id))
|
||||
records = _count(db, select(func.count(ApprovalRecord.id)).where(
|
||||
ApprovalRecord.project_id == project.id))
|
||||
if instances or records:
|
||||
# 审批留痕是合规资产:谁批的、什么时候批的、按什么数批的。项目可以作废,
|
||||
# 这条链不能跟着销毁,否则审计就断在"曾经有个项目批过 800 万但查不到了"。
|
||||
blockers.append({
|
||||
"code": "has_approval_history",
|
||||
"message": f"项目留有审批痕迹({instances} 个实例 / {records} 条记录),"
|
||||
"按审计要求不能物理销毁,请保留在回收站",
|
||||
})
|
||||
return blockers
|
||||
|
||||
|
||||
def _assert_project_purgable(db, current: Principal, project: Project) -> list[dict[str, str]]:
|
||||
if not current.permission.can("project:project:purge"):
|
||||
raise forbidden("缺少权限:project:project:purge")
|
||||
_assert_project_owner(current, project, "彻底删除项目")
|
||||
blockers = _purge_blockers(db, project)
|
||||
if blockers:
|
||||
first = blockers[0]
|
||||
raise conflict(first["code"], first["message"])
|
||||
return blockers
|
||||
|
||||
|
||||
@router.get("/{project_id}/purge-check")
|
||||
def check_project_purge(project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
"""彻底删除前把"会毁掉什么"和要回敲的确认词一起给出去。"""
|
||||
project = assert_project_visible(db, current, project_id, allow_deleted=True)
|
||||
if not current.permission.can("project:project:purge"):
|
||||
raise forbidden("缺少权限:project:project:purge")
|
||||
_assert_project_owner(current, project, "彻底删除项目")
|
||||
blockers = _purge_blockers(db, project)
|
||||
return ok({
|
||||
"projectName": project.name, "projectNo": project.project_no,
|
||||
"deletedAt": _t(project.deleted_at), "deletedByName": project.deleted_by_name,
|
||||
"deletable": not blockers, "blockers": blockers,
|
||||
"confirmName": project.project_no or project.name,
|
||||
"counts": _purge_counts(db, project),
|
||||
})
|
||||
|
||||
|
||||
@router.delete("/{project_id}/purge")
|
||||
def purge_project(project_id: int, request: Request, db: DbSession, current: PrincipalOf,
|
||||
body: PurgeBody | None = None) -> dict[str, Any]:
|
||||
"""物理销毁。执行完只剩审计行,业务数据一行不剩,没有回头路。"""
|
||||
project = assert_project_visible(db, current, project_id, allow_deleted=True)
|
||||
_assert_project_purgable(db, current, project)
|
||||
wanted = (project.project_no or project.name).strip()
|
||||
if (body.confirmName if body else "").strip() != wanted:
|
||||
raise conflict("confirm_mismatch", f"请输入项目编号「{wanted}」确认销毁")
|
||||
|
||||
# 销毁之前先把现场留进审计:这条日志是这件事在这个世界上剩下的唯一痕迹。
|
||||
counts = _purge_counts(db, project)
|
||||
snapshot = {
|
||||
"projectNo": project.project_no, "name": project.name, "stage": project.stage,
|
||||
"stageLabel": project.stage_label, "creatorName": project.creator_name,
|
||||
"orgUnitName": project.org_unit_name, "principal": project.principal,
|
||||
"contractAmount": money_str(project.contract_amount),
|
||||
"deletedAt": _t(project.deleted_at), "deletedByName": project.deleted_by_name,
|
||||
"deleteReason": project.delete_reason, "destroyed": counts,
|
||||
}
|
||||
|
||||
for _, models in PURGE_PLAN:
|
||||
for model in models:
|
||||
db.query(model).filter(model.project_id == project.id).delete(
|
||||
synchronize_session=False)
|
||||
db.query(Attachment).filter(
|
||||
Attachment.object_id == project.id,
|
||||
Attachment.object_type.in_(PROJECT_ATTACHMENT_TYPES)).delete(synchronize_session=False)
|
||||
db.query(Project).filter(Project.id == project.id).delete(synchronize_session=False)
|
||||
audit.enrich(request, action="purge", object_name=snapshot["name"], **snapshot)
|
||||
db.commit()
|
||||
return ok({"purged": True, "id": project_id, "destroyed": counts})
|
||||
|
||||
class StageBody(BaseModel):
|
||||
stage: int
|
||||
remark: str = ""
|
||||
|
||||
|
||||
@router.post("/{project_id}/stage")
|
||||
def change_stage(project_id: int, body: StageBody, request: Request, *, db: DbSession,
|
||||
current: PrincipalOf) -> dict[str, Any]:
|
||||
stage = body.stage
|
||||
project = assert_project_visible(db, current, project_id)
|
||||
if not current.permission.can("project:project:edit"):
|
||||
raise forbidden("缺少权限:project:project:edit")
|
||||
if stage not in ProjectStage.LABELS:
|
||||
raise conflict("unknown_stage", f"未知的项目阶段:{stage}")
|
||||
biz.set_project_stage(db, project, stage, current.account, body.remark)
|
||||
audit.enrich(request, object_name=project.name, stage=stage,
|
||||
stageLabel=project.stage_label, remark=body.remark)
|
||||
db.commit()
|
||||
return ok({"stage": stage,
|
||||
"stageLabel": dict_store.label(db, "projectStage", stage,
|
||||
ProjectStage.LABELS[stage])})
|
||||
|
||||
|
||||
@router.get("/{project_id}/members")
|
||||
def list_members(project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
assert_project_visible(db, current, project_id)
|
||||
rows = db.execute(select(ProjectMember).where(ProjectMember.project_id == project_id)
|
||||
.order_by(ProjectMember.id)).scalars().all()
|
||||
return ok([{"id": row.id, "accountId": row.account_id, "accountName": row.account_name,
|
||||
"memberRole": row.member_role,
|
||||
"memberRoleLabel": dict_store.label(
|
||||
db, "projectMemberRole", row.member_role, row.member_role)}
|
||||
for row in rows])
|
||||
|
||||
|
||||
@router.post("/{project_id}/members")
|
||||
def add_members(project_id: int, body: MemberBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
assert_project_visible(db, current, project_id)
|
||||
if not current.permission.can("project:project:edit"):
|
||||
raise forbidden("缺少权限:project:project:edit")
|
||||
existing = set(db.execute(select(ProjectMember.account_id).where(
|
||||
ProjectMember.project_id == project_id)).scalars().all())
|
||||
added = 0
|
||||
for account_id in body.accountIds or []:
|
||||
if account_id in existing:
|
||||
continue
|
||||
target = db.get(Account, account_id)
|
||||
if target is None or target.is_deleted:
|
||||
continue
|
||||
db.add(ProjectMember(project_id=project_id, account_id=account_id,
|
||||
account_name=target.display_name or target.account,
|
||||
member_role=body.memberRole))
|
||||
added += 1
|
||||
db.commit()
|
||||
return ok({"added": added, "projectId": project_id})
|
||||
|
||||
|
||||
@router.delete("/{project_id}/members/{account_id}")
|
||||
def remove_member(project_id: int, account_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
assert_project_visible(db, current, project_id)
|
||||
if not current.permission.can("project:project:edit"):
|
||||
raise forbidden("缺少权限:project:project:edit")
|
||||
row = db.execute(select(ProjectMember).where(
|
||||
ProjectMember.project_id == project_id, ProjectMember.account_id == account_id
|
||||
)).scalars().first()
|
||||
if row is None:
|
||||
raise not_found("该成员不在项目里")
|
||||
if row.member_role == ProjectMemberRole.OWNER:
|
||||
raise conflict("owner_protected", "项目负责人不能移除,请先移交项目负责人")
|
||||
db.delete(row)
|
||||
db.commit()
|
||||
return ok({"deleted": True})
|
||||
|
||||
|
||||
@router.get("/{project_id}/visible-roles")
|
||||
def list_visible_roles(project_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
assert_project_visible(db, current, project_id)
|
||||
from ..models import PermRole
|
||||
|
||||
rows = db.execute(select(ProjectVisibleRole).where(
|
||||
ProjectVisibleRole.project_id == project_id)).scalars().all()
|
||||
roles = dict(db.execute(select(PermRole.id, PermRole.name)).all())
|
||||
return ok([{"id": row.id, "roleId": row.role_id, "roleName": roles.get(row.role_id, "")} for row in rows])
|
||||
|
||||
|
||||
class VisibleRoleBody(BaseModel):
|
||||
roleIds: list[int] = Field(default_factory=list)
|
||||
|
||||
|
||||
@router.put("/{project_id}/visible-roles")
|
||||
def set_visible_roles(project_id: int, body: VisibleRoleBody, db: DbSession,
|
||||
current: PrincipalOf) -> dict[str, Any]:
|
||||
"""逐项目的"哪些角色能看这个项目",兼容老 project_visible 的 type=1。"""
|
||||
assert_project_visible(db, current, project_id)
|
||||
if not current.permission.can("project:project:edit"):
|
||||
raise forbidden("缺少权限:project:project:edit")
|
||||
existing = set(db.execute(select(ProjectVisibleRole.role_id).where(
|
||||
ProjectVisibleRole.project_id == project_id)).scalars().all())
|
||||
wanted = set(body.roleIds or [])
|
||||
for role_id in existing - wanted:
|
||||
for row in db.execute(select(ProjectVisibleRole).where(
|
||||
ProjectVisibleRole.project_id == project_id,
|
||||
ProjectVisibleRole.role_id == role_id)).scalars():
|
||||
db.delete(row)
|
||||
for role_id in wanted - existing:
|
||||
db.add(ProjectVisibleRole(project_id=project_id, role_id=role_id))
|
||||
db.commit()
|
||||
return ok({"count": len(wanted)})
|
||||
|
||||
|
||||
@router.get("/{project_id}/attachments")
|
||||
def list_attachments(project_id: int, db: DbSession, current: PrincipalOf,
|
||||
objectType: str = "") -> dict[str, Any]:
|
||||
assert_project_visible(db, current, project_id)
|
||||
statement = select(Attachment).where(Attachment.object_id == project_id,
|
||||
Attachment.is_deleted.is_(False))
|
||||
if objectType:
|
||||
statement = statement.where(Attachment.object_type == objectType)
|
||||
rows = db.execute(statement.order_by(Attachment.id.desc())).scalars().all()
|
||||
return ok([{"id": row.id, "objectType": row.object_type, "objectId": row.object_id,
|
||||
"field": row.field, "fileName": row.file_name, "url": row.url, "size": row.size,
|
||||
"ext": row.ext, "uploaderName": row.uploader_name,
|
||||
"createdAt": _t(row.created_at)} for row in rows])
|
||||
|
|
@ -0,0 +1,538 @@
|
|||
"""角色权限、菜单权限、数据权限、字段权限与业务参数。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .. import dicts as dict_store
|
||||
from ..config import settings
|
||||
from ..deps import DbSession, PrincipalOf
|
||||
from ..envelope import conflict, forbidden, not_found, ok
|
||||
from ..models import (
|
||||
Effect,
|
||||
FieldScope,
|
||||
PermDataPolicy,
|
||||
PermKind,
|
||||
PermNode,
|
||||
PermRole,
|
||||
ScopeType,
|
||||
SubjectType,
|
||||
SystemConfig,
|
||||
)
|
||||
from ..service import data_scope, permissions
|
||||
from ..service.calc import engine as calc_engine
|
||||
from ..service.calc import rules as calc_rules
|
||||
from ..service.biz import apply_sys_config
|
||||
|
||||
router = APIRouter(prefix="/system", tags=["system"])
|
||||
|
||||
logger = logging.getLogger("pms.api.system")
|
||||
|
||||
|
||||
def _need(db, current: PrincipalOf, code: str) -> None:
|
||||
if not current.permission.can(code):
|
||||
raise forbidden(f"缺少权限:{code}")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 菜单 / 权限目录
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/permissions/catalog")
|
||||
def catalog(db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_need(db, current, "system:permission:view")
|
||||
return ok({
|
||||
"nodes": permissions.permission_catalog(db),
|
||||
"kinds": list(PermKind.ALL),
|
||||
"modules": data_scope.registered_modules(),
|
||||
})
|
||||
|
||||
|
||||
class NodeBody(BaseModel):
|
||||
code: str = Field(min_length=1, max_length=128)
|
||||
name: str = Field(min_length=1, max_length=128)
|
||||
kind: str = PermKind.MENU
|
||||
parentId: int = 0
|
||||
path: str = ""
|
||||
icon: str = ""
|
||||
module: str = ""
|
||||
sort: int = 100
|
||||
visible: bool = True
|
||||
enabled: bool = True
|
||||
remark: str = ""
|
||||
|
||||
|
||||
@router.post("/permissions/nodes")
|
||||
def create_node(body: NodeBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_need(db, current, "system:permission:edit")
|
||||
if db.execute(select(PermNode).where(PermNode.code == body.code)).scalars().first():
|
||||
raise conflict("duplicated_code", "权限码已存在")
|
||||
node = PermNode(code=body.code, name=body.name, kind=body.kind, parent_id=body.parentId,
|
||||
path=body.path, icon=body.icon, module=body.module, sort=body.sort,
|
||||
visible=body.visible, enabled=body.enabled, remark=body.remark)
|
||||
db.add(node)
|
||||
db.commit()
|
||||
return ok({"id": node.id})
|
||||
|
||||
|
||||
@router.put("/permissions/nodes/{node_id}")
|
||||
def update_node(node_id: int, body: NodeBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_need(db, current, "system:permission:edit")
|
||||
node = db.get(PermNode, node_id)
|
||||
if node is None or node.is_deleted:
|
||||
raise not_found("权限节点不存在")
|
||||
for attr, value in (("name", body.name), ("kind", body.kind), ("parent_id", body.parentId),
|
||||
("path", body.path), ("icon", body.icon), ("module", body.module),
|
||||
("sort", body.sort), ("visible", body.visible), ("enabled", body.enabled),
|
||||
("remark", body.remark)):
|
||||
setattr(node, attr, value)
|
||||
db.commit()
|
||||
return ok({"id": node.id})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 角色
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class RoleBody(BaseModel):
|
||||
code: str = Field(min_length=1, max_length=64)
|
||||
name: str = Field(min_length=1, max_length=128)
|
||||
enabled: bool = True
|
||||
orderNumber: int = 100
|
||||
remark: str = ""
|
||||
|
||||
|
||||
@router.get("/roles")
|
||||
def list_roles(db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_need(db, current, "system:role:view")
|
||||
rows = db.execute(select(PermRole).where(PermRole.is_deleted.is_(False))
|
||||
.order_by(PermRole.order_number, PermRole.id)).scalars().all()
|
||||
return ok([{
|
||||
"id": row.id, "code": row.code, "name": row.name, "builtin": row.builtin,
|
||||
"enabled": row.enabled, "orderNumber": row.order_number, "remark": row.remark,
|
||||
"permissionCount": len(permissions.role_permission_ids(db, row.id)),
|
||||
} for row in rows])
|
||||
|
||||
|
||||
@router.post("/roles")
|
||||
def create_role(body: RoleBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_need(db, current, "system:role:edit")
|
||||
if db.execute(select(PermRole).where(PermRole.code == body.code)).scalars().first():
|
||||
raise conflict("duplicated_code", "角色编码已存在")
|
||||
role = PermRole(code=body.code, name=body.name, enabled=body.enabled,
|
||||
order_number=body.orderNumber, remark=body.remark)
|
||||
db.add(role)
|
||||
db.commit()
|
||||
return ok({"id": role.id})
|
||||
|
||||
|
||||
@router.put("/roles/{role_id}")
|
||||
def update_role(role_id: int, body: RoleBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_need(db, current, "system:role:edit")
|
||||
role = db.get(PermRole, role_id)
|
||||
if role is None or role.is_deleted:
|
||||
raise not_found("角色不存在")
|
||||
role.name, role.enabled, role.order_number, role.remark = (
|
||||
body.name, body.enabled, body.orderNumber, body.remark)
|
||||
db.commit()
|
||||
return ok({"id": role.id})
|
||||
|
||||
|
||||
@router.delete("/roles/{role_id}")
|
||||
def delete_role(role_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_need(db, current, "system:role:edit")
|
||||
role = db.get(PermRole, role_id)
|
||||
if role is None or role.is_deleted:
|
||||
raise not_found("角色不存在")
|
||||
if role.builtin:
|
||||
raise conflict("builtin_role", "内置角色不能删除")
|
||||
role.is_deleted = True
|
||||
db.commit()
|
||||
return ok({"deleted": True})
|
||||
|
||||
|
||||
@router.get("/roles/{role_id}/permissions")
|
||||
def role_permissions(role_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_need(db, current, "system:role:view")
|
||||
return ok({"nodeIds": permissions.role_permission_ids(db, role_id)})
|
||||
|
||||
|
||||
class NodeIdsBody(BaseModel):
|
||||
nodeIds: list[int] = Field(default_factory=list)
|
||||
|
||||
|
||||
@router.put("/roles/{role_id}/permissions")
|
||||
def set_role_permissions(role_id: int, body: NodeIdsBody, db: DbSession,
|
||||
current: PrincipalOf) -> dict[str, Any]:
|
||||
_need(db, current, "system:role:edit")
|
||||
if db.get(PermRole, role_id) is None:
|
||||
raise not_found("角色不存在")
|
||||
count = permissions.set_role_permissions(db, role_id, body.nodeIds)
|
||||
db.commit()
|
||||
return ok({"count": count})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 数据权限策略
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class PolicyBody(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=128)
|
||||
module: str = Field(min_length=1, max_length=64)
|
||||
subjectType: str = SubjectType.ROLE
|
||||
subjectId: int = 0
|
||||
effect: str = Effect.ALLOW
|
||||
scopeType: str = ScopeType.SELF
|
||||
targetIds: list[int] = Field(default_factory=list)
|
||||
includeChildren: bool = True
|
||||
conditions: dict[str, Any] | None = None
|
||||
priority: int = 100
|
||||
enabled: bool = True
|
||||
validFrom: str = ""
|
||||
validTo: str = ""
|
||||
remark: str = ""
|
||||
|
||||
|
||||
@router.get("/data-policies")
|
||||
def list_policies(db: DbSession, current: PrincipalOf, module: str = "") -> dict[str, Any]:
|
||||
_need(db, current, "system:datapermission:view")
|
||||
statement = select(PermDataPolicy).where(PermDataPolicy.is_deleted.is_(False))
|
||||
if module:
|
||||
statement = statement.where(PermDataPolicy.module == module)
|
||||
rows = db.execute(statement.order_by(PermDataPolicy.module, PermDataPolicy.priority,
|
||||
PermDataPolicy.id)).scalars().all()
|
||||
return ok([_policy_view(db, row) for row in rows])
|
||||
|
||||
|
||||
def _policy_view(db: Session, row: PermDataPolicy) -> dict[str, Any]:
|
||||
labels = {item["module"]: item["label"] for item in data_scope.registered_modules()}
|
||||
# covers 是这条策略真正管到哪几个模块:族代表一条管全族,成员模块上配的只管自己。
|
||||
# 界面上不写清楚,管理员就会以为"某某 - budget"只管预算那一页。
|
||||
covers = [{"module": key, "label": labels.get(key, key)}
|
||||
for key in data_scope.policy_covers(row.module)]
|
||||
return {
|
||||
"id": row.id, "name": row.name, "module": row.module, "covers": covers,
|
||||
"subjectType": row.subject_type, "subjectId": row.subject_id,
|
||||
"effect": row.effect, "scopeType": row.scope_type,
|
||||
"scopeLabel": dict_store.label(db, "scopeType", row.scope_type,
|
||||
ScopeType.label(row.scope_type)),
|
||||
"targetIds": _loads(row.target_ids_json, []),
|
||||
"includeChildren": row.include_children,
|
||||
"conditions": _loads(row.conditions_json, None),
|
||||
"priority": row.priority, "enabled": row.enabled,
|
||||
"validFrom": row.valid_from, "validTo": row.valid_to, "remark": row.remark,
|
||||
}
|
||||
|
||||
|
||||
def _loads(raw: str, default: Any) -> Any:
|
||||
if not (raw or "").strip():
|
||||
return default
|
||||
try:
|
||||
return json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
return default
|
||||
|
||||
|
||||
@router.post("/data-policies")
|
||||
def create_policy(body: PolicyBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_need(db, current, "system:datapermission:edit")
|
||||
_validate_policy(body)
|
||||
row = PermDataPolicy(
|
||||
name=body.name, module=body.module, subject_type=body.subjectType, subject_id=body.subjectId,
|
||||
effect=body.effect, scope_type=body.scopeType,
|
||||
target_ids_json=json.dumps(body.targetIds), include_children=body.includeChildren,
|
||||
conditions_json=json.dumps(body.conditions, ensure_ascii=False) if body.conditions else "",
|
||||
priority=body.priority, enabled=body.enabled, valid_from=body.validFrom,
|
||||
valid_to=body.validTo, remark=body.remark,
|
||||
)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
return ok({"id": row.id})
|
||||
|
||||
|
||||
@router.put("/data-policies/{policy_id}")
|
||||
def update_policy(policy_id: int, body: PolicyBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_need(db, current, "system:datapermission:edit")
|
||||
row = db.get(PermDataPolicy, policy_id)
|
||||
if row is None or row.is_deleted:
|
||||
raise not_found("策略不存在")
|
||||
_validate_policy(body)
|
||||
row.name, row.module, row.subject_type, row.subject_id = body.name, body.module, body.subjectType, body.subjectId
|
||||
row.effect, row.scope_type = body.effect, body.scopeType
|
||||
row.target_ids_json = json.dumps(body.targetIds)
|
||||
row.include_children = body.includeChildren
|
||||
row.conditions_json = json.dumps(body.conditions, ensure_ascii=False) if body.conditions else ""
|
||||
row.priority, row.enabled = body.priority, body.enabled
|
||||
row.valid_from, row.valid_to = body.validFrom, body.validTo
|
||||
row.remark = body.remark
|
||||
db.commit()
|
||||
return ok({"id": row.id})
|
||||
|
||||
|
||||
@router.delete("/data-policies/{policy_id}")
|
||||
def delete_policy(policy_id: int, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_need(db, current, "system:datapermission:edit")
|
||||
row = db.get(PermDataPolicy, policy_id)
|
||||
if row is None or row.is_deleted:
|
||||
raise not_found("策略不存在")
|
||||
row.is_deleted = True
|
||||
db.commit()
|
||||
return ok({"deleted": True})
|
||||
|
||||
|
||||
def _validate_policy(body: PolicyBody) -> None:
|
||||
if body.module not in {item["module"] for item in data_scope.registered_modules()}:
|
||||
raise conflict("unknown_module", f"未知的业务模块:{body.module}")
|
||||
if body.scopeType not in ScopeType.ALL_TYPES:
|
||||
raise conflict("unknown_scope", f"未知的数据范围:{body.scopeType}")
|
||||
if body.subjectType not in SubjectType.ALL_TYPES:
|
||||
raise conflict("unknown_subject", f"未知的主体类型:{body.subjectType}")
|
||||
if body.subjectType != SubjectType.ALL and not body.subjectId:
|
||||
raise conflict("subject_required", "除了「所有人」以外都必须选择具体主体")
|
||||
if body.scopeType in (ScopeType.ORG_LIST, ScopeType.ACCOUNT_LIST) and not body.targetIds:
|
||||
raise conflict("target_required", "「指定部门/指定人员」范围必须选择具体对象")
|
||||
if body.conditions:
|
||||
unknown = _unknown_fields(body.module, body.conditions)
|
||||
if unknown:
|
||||
raise conflict("unknown_condition_field",
|
||||
"自定义条件里用了不支持的字段:" + "、".join(sorted(unknown)))
|
||||
|
||||
|
||||
def _unknown_fields(module: str, tree: dict[str, Any], found: set[str] | None = None) -> set[str]:
|
||||
spec = data_scope.spec_for(module)
|
||||
allowed = set(spec.filterable.keys()) if spec else set()
|
||||
unknown: set[str] = set()
|
||||
for item in tree.get("items") or []:
|
||||
unknown |= _unknown_fields(module, item)
|
||||
field_name = tree.get("field")
|
||||
if field_name and field_name not in allowed:
|
||||
unknown.add(str(field_name))
|
||||
return unknown
|
||||
|
||||
|
||||
@router.get("/data-policies/options")
|
||||
def policy_options(db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
"""前端配置页要用的下拉数据,一次给全,省得配一条策略发五次请求。"""
|
||||
_need(db, current, "system:datapermission:view")
|
||||
specs = []
|
||||
for item in data_scope.registered_modules():
|
||||
spec = data_scope.spec_for(item["module"])
|
||||
specs.append({
|
||||
**item,
|
||||
"filterable": sorted(spec.filterable.keys()) if spec else [],
|
||||
"numeric": list(spec.numeric) if spec else [],
|
||||
"covers": data_scope.policy_covers(item["module"]),
|
||||
})
|
||||
return ok({
|
||||
"modules": specs,
|
||||
# 这几组下拉值改从数据字典取:以前这里、权限模型里、前端各留一份中文名,
|
||||
# 改一处漏两处("按人员/按账号"就是那么对不上的)。
|
||||
"scopeTypes": dict_store.options(db, "scopeType"),
|
||||
"subjectTypes": dict_store.options(db, "subjectType"),
|
||||
"effects": dict_store.options(db, "effect"),
|
||||
"operators": dict_store.options(db, "dataOperator"),
|
||||
"dynamicValues": dict_store.options(db, "dynamicValue"),
|
||||
"roles": [{"id": row.id, "name": row.name} for row in
|
||||
db.execute(select(PermRole).where(PermRole.is_deleted.is_(False))).scalars().all()],
|
||||
})
|
||||
|
||||
|
||||
class ExplainBody(BaseModel):
|
||||
accountId: int
|
||||
module: str
|
||||
|
||||
|
||||
@router.post("/data-policies/explain")
|
||||
def explain(body: ExplainBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
""""我以这个人的身份打开这个模块会看到什么",配置完当场能验证。"""
|
||||
_need(db, current, "system:datapermission:view")
|
||||
from ..models import Account
|
||||
|
||||
account = db.get(Account, body.accountId)
|
||||
if account is None or account.is_deleted:
|
||||
raise not_found("账号不存在")
|
||||
return ok(data_scope.explain(db, body.module, account))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 字段权限
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class FieldScopeBody(BaseModel):
|
||||
module: str
|
||||
field: str
|
||||
roleId: int
|
||||
mode: str = "hidden"
|
||||
|
||||
|
||||
@router.get("/field-scopes")
|
||||
def list_field_scopes(db: DbSession, current: PrincipalOf, module: str = "") -> dict[str, Any]:
|
||||
_need(db, current, "system:datapermission:view")
|
||||
statement = select(FieldScope).where(FieldScope.role_id.in_(
|
||||
select(PermRole.id).where(PermRole.is_deleted.is_(False))))
|
||||
if module:
|
||||
statement = statement.where(FieldScope.module == module)
|
||||
rows = db.execute(statement.order_by(FieldScope.module, FieldScope.field)).scalars().all()
|
||||
roles = dict(db.execute(select(PermRole.id, PermRole.name)).all())
|
||||
return ok([{"id": row.id, "module": row.module, "field": row.field, "roleId": row.role_id,
|
||||
"roleName": roles.get(row.role_id, ""), "mode": row.mode} for row in rows])
|
||||
|
||||
|
||||
@router.post("/field-scopes")
|
||||
def set_field_scope(body: FieldScopeBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_need(db, current, "system:datapermission:edit")
|
||||
existing = db.execute(select(FieldScope).where(
|
||||
FieldScope.module == body.module, FieldScope.field == body.field,
|
||||
FieldScope.role_id == body.roleId)).scalars().first()
|
||||
if existing:
|
||||
existing.mode = body.mode
|
||||
else:
|
||||
db.add(FieldScope(module=body.module, field=body.field, role_id=body.roleId, mode=body.mode))
|
||||
db.commit()
|
||||
return ok({"saved": True})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 业务参数
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/configs")
|
||||
def list_configs(db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_need(db, current, "system:config:view")
|
||||
rows = db.execute(select(SystemConfig).order_by(SystemConfig.group, SystemConfig.id)).scalars().all()
|
||||
return ok([{"id": row.id, "code": row.code, "name": row.name, "value": row.value,
|
||||
"valueType": row.value_type, "group": row.group, "editable": row.editable,
|
||||
"remark": row.remark} for row in rows])
|
||||
|
||||
|
||||
class ConfigBody(BaseModel):
|
||||
value: str
|
||||
|
||||
|
||||
@router.put("/configs/{code}")
|
||||
def update_config(code: str, body: ConfigBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
_need(db, current, "system:config:edit")
|
||||
if calc_rules.is_rule_code(code):
|
||||
# 计算口径有专门的入口:那边按取值范围逐条校验、整套一起提交,
|
||||
# 权限也是独立的(能改业务参数不等于能改财务口径)。
|
||||
raise conflict("use_calc_rules", "计算口径请在「系统 → 计算口径」页面修改")
|
||||
row = db.execute(select(SystemConfig).where(SystemConfig.code == code)).scalars().first()
|
||||
if row is None:
|
||||
raise not_found("参数不存在")
|
||||
if not row.editable:
|
||||
raise conflict("not_editable", "该参数不允许在界面上修改")
|
||||
row.value = body.value
|
||||
db.commit()
|
||||
apply_sys_config(db)
|
||||
return ok({"code": code, "value": row.value})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 计算口径(system_config 里 group=calc / calc.* 那一批)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/calc-rules")
|
||||
def get_calc_rules(db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
"""口径清单:每条的当前生效值、默认值、库里的原样、取值范围与规则说明。
|
||||
|
||||
页面照着这份渲染(枚举给下拉、开关给拨把、数字给步进框),不在前端抄一份常量表——
|
||||
前端那份和内核那份迟早对不上,而对不上的是算钱的口径。
|
||||
"""
|
||||
_need(db, current, "system:calcrule:view")
|
||||
return ok(calc_rules.view(db))
|
||||
|
||||
|
||||
class CalcRulesBody(BaseModel):
|
||||
#: {"calc.money_scale": "2", ...};只提交改过的条也行
|
||||
values: dict[str, str] = Field(default_factory=dict)
|
||||
|
||||
|
||||
@router.put("/calc-rules")
|
||||
def put_calc_rules(body: CalcRulesBody, db: DbSession, current: PrincipalOf) -> dict[str, Any]:
|
||||
"""整页保存:先全部校验,有任何一条不合法就一条都不写。
|
||||
|
||||
一次改口径通常是成套改(比如同时调管理费率并升版本号),写一半比全不写危险得多。
|
||||
"""
|
||||
_need(db, current, "system:calcrule:edit")
|
||||
if not body.values:
|
||||
raise conflict("empty", "没有要保存的口径")
|
||||
|
||||
normalized: dict[str, str] = {}
|
||||
problems: list[str] = []
|
||||
for code, raw in body.values.items():
|
||||
spec = calc_rules.spec_for(code)
|
||||
if spec is None:
|
||||
problems.append(f"{code}:不是计算口径参数")
|
||||
continue
|
||||
try:
|
||||
normalized[code] = calc_rules.normalize(spec, raw)
|
||||
except ValueError as exc:
|
||||
problems.append(f"{spec.name}:{exc}")
|
||||
if problems:
|
||||
raise conflict("invalid_value", ";".join(problems))
|
||||
|
||||
rows = {row.code: row for row in
|
||||
db.execute(select(SystemConfig).where(
|
||||
SystemConfig.code.in_(list(normalized)))).scalars().all()}
|
||||
for code, value in normalized.items():
|
||||
row = rows.get(code)
|
||||
if row is None:
|
||||
# 老库还没补过参数:按默认值补一行再写,页面不必为此区分"新增"和"修改"
|
||||
spec = calc_rules.spec_for(code)
|
||||
row = SystemConfig(code=code, name=spec.name, value=spec.default_text,
|
||||
value_type=spec.value_type, group=calc_rules.RULE_GROUP,
|
||||
editable=True, remark=spec.remark)
|
||||
db.add(row)
|
||||
rows[code] = row
|
||||
row.value = value
|
||||
db.commit()
|
||||
|
||||
apply_sys_config(db)
|
||||
logger.info("计算口径已更新:%s(操作人 %s)", calc_rules.describe(),
|
||||
current.account.account)
|
||||
return ok(calc_rules.view(db))
|
||||
|
||||
|
||||
@router.get("/info")
|
||||
def system_info() -> dict[str, Any]:
|
||||
"""前端"关于"与排障要看的东西:档位、口径版本、能力开关。"""
|
||||
return ok({
|
||||
"env": settings.env,
|
||||
"calcVersion": calc_engine.calc_version(),
|
||||
"configFiles": settings.files,
|
||||
"hubEnabled": settings.hub.enabled,
|
||||
"ssoEnabled": settings.hub.sso_configured,
|
||||
# 登录页据此决定表单长什么样:passwordLoginAllowed 管"账号口令框还留不留"
|
||||
# (Hub 开着也要留,那框收的是统一身份账号),hubPasswordLogin 管"要不要摆验证码",
|
||||
# localPasswordAllowed 管"本地自建账号的口令还认不认"(只影响提示语)。
|
||||
"passwordLoginAllowed": settings.hub.password_login_allowed,
|
||||
"hubPasswordLogin": settings.hub.hub_password_login,
|
||||
"localPasswordAllowed": settings.hub.local_password_login_allowed,
|
||||
"loginMode": settings.hub.mode,
|
||||
# 口径的生效值,内核读到的就是这几个数(详情页汇总条与关于页共用)
|
||||
"companyManageFeeRate": calc_rules.RULES.company_manage_fee_rate,
|
||||
"travelBusinessLimitRate": calc_rules.RULES.travel_business_limit_rate,
|
||||
"contributionRateAction": calc_rules.RULES.contribution_rate_action,
|
||||
"calcRulesChanged": calc_rules.changed_count(),
|
||||
"production": settings.is_production,
|
||||
"warnings": settings_warnings(),
|
||||
})
|
||||
|
||||
|
||||
def settings_warnings() -> list[str]:
|
||||
from ..config import warnings as prod_warnings
|
||||
|
||||
return prod_warnings(settings)
|
||||
|
|
@ -0,0 +1,526 @@
|
|||
"""配置读取:只管引导项(连库、监听、密钥、Hub 节奏)。
|
||||
|
||||
一份代码,多套环境
|
||||
==================
|
||||
|
||||
同一个包要在自己机器上跑、在测试机上跑、在生产上跑,三套库三套密钥。办法是给配置
|
||||
文件分档,用环境变量 ``PMS_ENV`` 说一声现在跑在哪一档:
|
||||
|
||||
* 本机开发:什么都不用设,``PMS_ENV`` 默认就是 ``dev``,读到的是测试那一份;
|
||||
* 换一档:``PMS_ENV=prod python run.py``(写全名 ``production`` 也认);
|
||||
* 只认一个文件:``PMS_CONFIG=/path/to/x.toml``,**此时只读它**,分档文件一概不看。
|
||||
|
||||
每一档读两个文件,后面那份逐段盖在前面那份上面(深合并:只覆盖写到的键,没写的沿用):
|
||||
|
||||
1. ``config.toml`` —— 各环境公共的基础值;
|
||||
2. ``config.<环境名>.toml`` —— 这一档自己的差异(库地址账号、密钥、开关)。
|
||||
|
||||
取值优先级(高的赢):**环境变量 ``PMS_*``** > ``config.<环境>.toml`` >
|
||||
``config.toml`` > 代码里的默认值。于是密钥既能写文件(chmod 600),也能由容器注入。
|
||||
|
||||
生产档(``prod`` / ``production`` / ``staging`` / ``gray``)启动时还要过一轮上线体检:
|
||||
空密钥、没关的演示数据、空的数据库口令都会在日志里点名(:func:`warnings`)。
|
||||
|
||||
**计算口径不在这里。** 舍入位数、价税口径、利润各层扣什么、各类限额比例与动作,全是
|
||||
``system_config`` 表里 ``calc.`` 开头的业务参数,在「系统 → 计算口径」页面上改,保存即生效;
|
||||
默认值与校验规则见 :mod:`app.service.calc.rules`。业务口径混进配置文件的话,调一个费率要
|
||||
排队等运维重启,而重启期间跑出来的快照算哪套口径没人说得清。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from dataclasses import dataclass, field, fields
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import quote_plus
|
||||
|
||||
logger = logging.getLogger("pms.config")
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
|
||||
try: # Python 3.11+ 自带;低版本装 tomli
|
||||
import tomllib as _tomllib
|
||||
except ModuleNotFoundError: # pragma: no cover
|
||||
try:
|
||||
import tomli as _tomllib # type: ignore[no-redef]
|
||||
except ModuleNotFoundError:
|
||||
_tomllib = None # type: ignore[assignment]
|
||||
|
||||
#: 没设 ``PMS_ENV`` 时算哪一档。默认测试档:不会因为漏设而误连生产库
|
||||
DEFAULT_ENV = "dev"
|
||||
#: 决定读哪一档配置文件的环境变量,按顺序取第一个有值的
|
||||
ENV_VARS = ("PMS_ENV", "PMS_PROFILE")
|
||||
#: 只认一个文件的环境变量:设了它就完全不看分档文件
|
||||
CONFIG_FILE_VAR = "PMS_CONFIG"
|
||||
#: 环境名的常见写法归一化:``PMS_ENV=production`` 与 ``PMS_ENV=prod`` 是同一档
|
||||
ENV_ALIASES = {
|
||||
"dev": "dev",
|
||||
"develop": "dev",
|
||||
"development": "dev",
|
||||
"local": "dev",
|
||||
"test": "dev",
|
||||
"prod": "prod",
|
||||
"production": "prod",
|
||||
"pro": "prod",
|
||||
"staging": "staging",
|
||||
"gray": "gray",
|
||||
}
|
||||
#: 这些档位算"上线",要过生产体检
|
||||
PRODUCTION_ENVS = ("prod", "production", "staging", "gray")
|
||||
|
||||
#: 环境变量 -> (段, 键) 的映射表;容器与 CI 注入密钥就靠它
|
||||
ENV_OVERRIDES: dict[str, tuple[str, str]] = {
|
||||
"PMS_DB_HOST": ("database", "host"),
|
||||
"PMS_DB_PORT": ("database", "port"),
|
||||
"PMS_DB_USER": ("database", "user"),
|
||||
"PMS_DB_PASSWORD": ("database", "password"),
|
||||
"PMS_DB_NAME": ("database", "name"),
|
||||
"PMS_AUTO_CREATE_SCHEMA": ("database", "auto_create_schema"),
|
||||
"PMS_LEGACY_HOST": ("legacy", "host"),
|
||||
"PMS_LEGACY_PORT": ("legacy", "port"),
|
||||
"PMS_LEGACY_USER": ("legacy", "user"),
|
||||
"PMS_LEGACY_PASSWORD": ("legacy", "password"),
|
||||
"PMS_LEGACY_NAME": ("legacy", "name"),
|
||||
"PMS_LEGACY_ENABLED": ("legacy", "enabled"),
|
||||
"PMS_HOST": ("server", "host"),
|
||||
"PMS_PORT": ("server", "port"),
|
||||
"PMS_JWT_SECRET": ("security", "jwt_secret"),
|
||||
"PMS_SEED_DEMO": ("seed", "demo_data"),
|
||||
"PMS_SEED_ADMIN_ACCOUNT": ("seed", "admin_account"),
|
||||
"PMS_SEED_ADMIN_PASSWORD": ("seed", "admin_password"),
|
||||
"PMS_SEED_EMERGENCY_ACCOUNT": ("seed", "emergency_account"),
|
||||
"PMS_SEED_EMERGENCY_PASSWORD": ("seed", "emergency_password"),
|
||||
"PMS_HUB_ENABLED": ("hub", "enabled"),
|
||||
"PMS_HUB_BASE_URL": ("hub", "base_url"),
|
||||
"PMS_HUB_DIRECTORY_KEY": ("hub", "directory_key"),
|
||||
"PMS_HUB_APP_CODE": ("hub", "app_code"),
|
||||
"PMS_HUB_INTEGRATION_KEY": ("hub", "integration_key"),
|
||||
"PMS_HUB_PORTAL_URL": ("hub", "portal_url"),
|
||||
"PMS_HUB_SSO_STATE_REQUIRED": ("hub", "sso_state_required"),
|
||||
"PMS_HUB_BREAK_GLASS_LOGIN": ("hub", "break_glass_login"),
|
||||
"PMS_HUB_LOGIN_MODE": ("hub", "login_mode"),
|
||||
"PMS_HUB_LOCAL_ONLY_ACCOUNTS": ("hub", "local_only_accounts"),
|
||||
"PMS_UPLOAD_PATH": ("upload", "path"),
|
||||
"PMS_LOG_LEVEL": ("log", "level"),
|
||||
}
|
||||
|
||||
|
||||
def resolve_env(raw: str | None) -> str:
|
||||
"""把 ``PMS_ENV`` 的原始写法折成规范档位名。"""
|
||||
if not raw:
|
||||
return DEFAULT_ENV
|
||||
return ENV_ALIASES.get(raw.strip().lower(), raw.strip().lower() or DEFAULT_ENV)
|
||||
|
||||
|
||||
def current_env() -> str:
|
||||
for name in ENV_VARS:
|
||||
value = os.environ.get(name)
|
||||
if value:
|
||||
return resolve_env(value)
|
||||
# 档位开关也可以写在 config.toml 的 [env] name 里(Docker 里不想传环境变量时用)
|
||||
base = _read_toml(BASE_DIR / "config.toml") or {}
|
||||
section = base.get("env") or {}
|
||||
return resolve_env(str(section.get("name") or "")) or DEFAULT_ENV
|
||||
|
||||
|
||||
def _read_toml(path: Path) -> dict[str, Any] | None:
|
||||
if not path.is_file() or _tomllib is None:
|
||||
return None
|
||||
try:
|
||||
with path.open("rb") as handle:
|
||||
return _tomllib.load(handle)
|
||||
except Exception as exc: # 配置文件写坏了也要能起来,只是要吵一声
|
||||
logger.error("配置文件 %s 解析失败,已忽略:%s", path, exc)
|
||||
return None
|
||||
|
||||
|
||||
def _deep_merge(base: dict[str, Any], overlay: dict[str, Any]) -> dict[str, Any]:
|
||||
"""只覆盖写到的键,没写的沿用;段落递归合并。"""
|
||||
out = dict(base)
|
||||
for key, value in overlay.items():
|
||||
if isinstance(value, dict) and isinstance(out.get(key), dict):
|
||||
out[key] = _deep_merge(out[key], value)
|
||||
else:
|
||||
out[key] = value
|
||||
return out
|
||||
|
||||
|
||||
def load_raw() -> tuple[dict[str, Any], list[Path]]:
|
||||
"""按档位拼出原始配置字典,并说清楚到底读了哪几个文件。"""
|
||||
only = os.environ.get(CONFIG_FILE_VAR)
|
||||
if only:
|
||||
return (_read_toml(Path(only)) or {}), [Path(only)]
|
||||
|
||||
merged: dict[str, Any] = {}
|
||||
used: list[Path] = []
|
||||
for candidate in (BASE_DIR / "config.toml",):
|
||||
data = _read_toml(candidate)
|
||||
if data:
|
||||
merged = _deep_merge(merged, data)
|
||||
used.append(candidate)
|
||||
|
||||
env_name = current_env()
|
||||
scoped = _read_toml(BASE_DIR / f"config.{env_name}.toml")
|
||||
if scoped:
|
||||
merged = _deep_merge(merged, scoped)
|
||||
used.append(BASE_DIR / f"config.{env_name}.toml")
|
||||
elif env_name not in (DEFAULT_ENV,):
|
||||
logger.warning("档位 %s 没有 config.%s.toml,只用 config.toml 与默认值", env_name, env_name)
|
||||
|
||||
merged = _deep_merge(merged, _env_overlay())
|
||||
merged.setdefault("_meta", {})["env"] = env_name
|
||||
merged["_meta"]["files"] = [str(p) for p in used]
|
||||
return merged, used
|
||||
|
||||
|
||||
def _env_overlay() -> dict[str, Any]:
|
||||
overlay: dict[str, Any] = {}
|
||||
for name, (section, key) in ENV_OVERRIDES.items():
|
||||
value = os.environ.get(name)
|
||||
if value is None or value == "":
|
||||
continue
|
||||
overlay.setdefault(section, {})[key] = value
|
||||
return overlay
|
||||
|
||||
|
||||
def _coerce(value: Any, target: Any) -> Any:
|
||||
"""配置文件与环境变量都是字符串进来,按默认值的类型折一下。"""
|
||||
if isinstance(target, bool):
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
return str(value).strip().lower() in ("1", "true", "yes", "on")
|
||||
if isinstance(target, int) and not isinstance(target, bool):
|
||||
try:
|
||||
return int(str(value).strip())
|
||||
except (TypeError, ValueError):
|
||||
logger.warning("配置项期望整数但拿到 %r,改用默认值 %r", value, target)
|
||||
return target
|
||||
if isinstance(target, float):
|
||||
try:
|
||||
return float(str(value).strip())
|
||||
except (TypeError, ValueError):
|
||||
return target
|
||||
if isinstance(target, list):
|
||||
if isinstance(value, list):
|
||||
return value
|
||||
return [item.strip() for item in str(value).split(",") if item.strip()]
|
||||
return value
|
||||
|
||||
|
||||
def _fill(instance: Any, data: dict[str, Any]) -> Any:
|
||||
for f in fields(instance):
|
||||
if f.name not in data:
|
||||
continue
|
||||
default = getattr(instance, f.name)
|
||||
setattr(instance, f.name, _coerce(data[f.name], default))
|
||||
return instance
|
||||
|
||||
|
||||
@dataclass
|
||||
class DatabaseConfig:
|
||||
"""引导配置:连上库之前就得知道,改了必须重启。"""
|
||||
|
||||
host: str = "127.0.0.1"
|
||||
port: int = 3306
|
||||
user: str = "root"
|
||||
password: str = ""
|
||||
name: str = "fourcal_pms_dev"
|
||||
auto_create_schema: bool = True
|
||||
echo_sql: bool = False
|
||||
pool_size: int = 10
|
||||
max_overflow: int = 30
|
||||
|
||||
@property
|
||||
def url(self) -> str:
|
||||
return (
|
||||
f"mysql+pymysql://{self.user}:{quote_plus(self.password)}"
|
||||
f"@{self.host}:{self.port}/{self.name}"
|
||||
"?charset=utf8mb4"
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class LegacyConfig:
|
||||
"""老四算库(只读):迁移脚本与双跑对账用。"""
|
||||
|
||||
enabled: bool = False
|
||||
host: str = "127.0.0.1"
|
||||
port: int = 3306
|
||||
user: str = ""
|
||||
password: str = ""
|
||||
name: str = "unis_fourcal"
|
||||
|
||||
@property
|
||||
def url(self) -> str:
|
||||
return (
|
||||
f"mysql+pymysql://{self.user}:{quote_plus(self.password)}"
|
||||
f"@{self.host}:{self.port}/{self.name}"
|
||||
"?charset=utf8mb4"
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ServerConfig:
|
||||
host: str = "0.0.0.0"
|
||||
port: int = 8383
|
||||
cors_origins: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class SecurityConfig:
|
||||
jwt_secret: str = ""
|
||||
jwt_algorithm: str = "HS256"
|
||||
access_token_ttl: int = 28_800
|
||||
refresh_token_ttl: int = 604_800
|
||||
password_min_length: int = 8
|
||||
login_max_errors: int = 5
|
||||
login_lock_minutes: int = 30
|
||||
|
||||
|
||||
#: 账号口令的四种校验口径,逐项说明见 :attr:`HubConfig.login_mode`
|
||||
LOGIN_MODES = ("hub", "hybrid", "local", "sso")
|
||||
|
||||
|
||||
@dataclass
|
||||
class HubConfig:
|
||||
"""统一身份(Hub):账号组织同步与免登,口径与 unisoa 一致。"""
|
||||
|
||||
enabled: bool = False
|
||||
base_url: str = ""
|
||||
directory_key: str = ""
|
||||
app_code: str = ""
|
||||
integration_key: str = ""
|
||||
# 三个接口路径按 dsh-hub 对接文档写死在这里,不再做成可配项:路径是契约的一部分,
|
||||
# 让运维能改只会让"配错一个斜杠、同步静默拿到空数组"这种事变得查不出来。
|
||||
directory_path: str = "/api/v1/auth/directory"
|
||||
changes_path: str = "/api/v1/auth/directory/changes"
|
||||
ticket_verify_path: str = "/api/v1/auth/tickets/verify"
|
||||
# 登录页直接输账号口令时要问 Hub 的两条:验证码下发与口令校验。
|
||||
captcha_path: str = "/auth/captcha"
|
||||
login_path: str = "/auth/login"
|
||||
# 登录响应没带用户主键时补问一次的那条。
|
||||
me_path: str = "/api/v1/auth/me"
|
||||
# 全量目录的花名册上限,接口默认 2000;truncated=true 时必须提高上限重拉。
|
||||
directory_member_limit: int = 5000
|
||||
changes_limit: int = 500
|
||||
# 登录页上那两次调用(取验证码、验口令)的超时。跟同步的 60 秒分开:同步慢一点无所谓,
|
||||
# 登录转圈超过十几秒人就以为死了,hybrid 档还要等这一趟超时才回落本地口令。
|
||||
login_timeout: int = 10
|
||||
# 增量轮询间隔(文档建议 30~60 秒)与全量校对间隔(文档要求每日一次)。
|
||||
changes_interval_seconds: int = 45
|
||||
sync_interval_minutes: int = 60 * 24
|
||||
sync_timeout: int = 60
|
||||
missing_account_action: str = "disable"
|
||||
missing_org_action: str = "disable"
|
||||
# Hub 停用/不可达时,仍允许本地账号用口令登录(只放行 source=local 的账号)。
|
||||
break_glass_login: bool = True
|
||||
# 账号口令的校验口径(对齐 unisoa 的 hub_login_mode):
|
||||
# hub —— 默认。口令只问统一身份,本地口令只剩逃生门那批账号可用;Hub 连不上
|
||||
# 就当场回"统一身份暂不可用",绝不"连不上就当本地账号放行"。
|
||||
# hybrid —— 先问统一身份;它连不上时退回本地口令校验。它明确说"密码不对"仍然
|
||||
# 算被拒,不兜第二层,否则 Hub 的停用与改口令在故障期集体失效。
|
||||
# local —— 不问统一身份,只用本地口令(目录同步与免登照旧)。
|
||||
# sso —— 口令登录整个关掉,登录页只留"前往统一门户"。
|
||||
login_mode: str = "hub"
|
||||
# 这些账号永远只用本地口令,不去问 Hub(逗号分隔,大小写不敏感)。内置超管
|
||||
# ([seed] admin_account)始终在列,不必写在这里——那是 Hub 配错时唯一能保证
|
||||
# 还进得去门的账号。本地自建、又想像以前那样用口令登的账号加到这里。
|
||||
local_only_accounts: str = ""
|
||||
# 统一门户首页:免登失败或本地口令关闭时把人送回哪里。留空用 base_url。
|
||||
portal_url: str = ""
|
||||
# 严格档:连"门户压根没带回 state"(直点卡片那条路)也拒。默认关,
|
||||
# 开了就必须保证发起跳转这一趟一定经过本系统,否则没人进得来。
|
||||
sso_state_required: bool = False
|
||||
|
||||
@property
|
||||
def portal_base_url(self) -> str:
|
||||
"""把人送回统一门户时用的地址。``portal_url`` 没填就退回 Hub 站点地址。"""
|
||||
return (self.portal_url or self.base_url).rstrip("/")
|
||||
|
||||
@property
|
||||
def configured(self) -> bool:
|
||||
"""能不能拉目录(X-Directory-Key 一条通道)。"""
|
||||
return bool(self.enabled and self.base_url and self.directory_key)
|
||||
|
||||
@property
|
||||
def sso_configured(self) -> bool:
|
||||
"""能不能免登(X-Integration-Key 是另一条通道,密钥互不通用)。"""
|
||||
return bool(self.enabled and self.base_url and self.app_code and self.integration_key)
|
||||
|
||||
@property
|
||||
def mode(self) -> str:
|
||||
"""``login_mode`` 的归一化值;写错的一律按 ``hub`` 那档(最不容易出事)处理。"""
|
||||
value = (self.login_mode or "").strip().lower()
|
||||
return value if value in LOGIN_MODES else "hub"
|
||||
|
||||
@property
|
||||
def hub_password_login(self) -> bool:
|
||||
"""账号口令要不要拿去问统一身份;登录页据此决定要不要摆验证码。"""
|
||||
return bool(self.enabled) and self.mode in ("hub", "hybrid")
|
||||
|
||||
@property
|
||||
def password_login_allowed(self) -> bool:
|
||||
"""登录页要不要留账号口令框。
|
||||
|
||||
Hub 模式下这个框收的是统一身份账号,不是本系统口令,所以 Hub 开着也得留着——
|
||||
撤掉它就只剩"去门户点卡片"一条路,想在登录页直接输账号口令验一下都办不到。
|
||||
"""
|
||||
return self.mode != "sso"
|
||||
|
||||
@property
|
||||
def local_only_account_set(self) -> frozenset[str]:
|
||||
"""不去问 Hub、直接用本地口令的账号集合;两个内置账号永远在列。
|
||||
|
||||
内置的是 :attr:`SeedConfig.admin_account`(超管)与
|
||||
:attr:`SeedConfig.emergency_account`(应急管理员)——它们本来就没有统一身份对应,
|
||||
写不写进 ``local_only_accounts`` 都该走本地口令。代价是:万一 Hub 上真有个叫
|
||||
``admin`` / ``localadmin`` 的人,他在本系统只能靠免登进来,口令这条路是关着的。
|
||||
"""
|
||||
names = {part.strip().lower()
|
||||
for part in (self.local_only_accounts or "").split(",") if part.strip()}
|
||||
seed = getattr(settings, "seed", None)
|
||||
for name in (getattr(seed, "admin_account", ""), getattr(seed, "emergency_account", "")):
|
||||
key = str(name or "").strip().lower()
|
||||
if key:
|
||||
names.add(key)
|
||||
return frozenset(names)
|
||||
|
||||
@property
|
||||
def local_password_login_allowed(self) -> bool:
|
||||
"""本地口令这条路还通不通(只管本系统自建的账号,Hub 账号从来不在讨论范围内)。
|
||||
|
||||
对接文档 §1.4 要求下游撤掉自己的账号口令登录:人在 Hub 那边,本系统再留一条
|
||||
口令入口,等于同一批人两套凭据、两套锁定策略。所以 Hub 开起来之后本地口令只
|
||||
留给逃生门([[hub]].break_glass_login)和 local_only_accounts 那批账号;
|
||||
``login_mode = "hybrid"`` 时它还兼任"Hub 连不上"的退路。
|
||||
"""
|
||||
if self.mode == "sso":
|
||||
return False
|
||||
if self.mode == "local" or not self.enabled:
|
||||
return True
|
||||
return self.break_glass_login
|
||||
|
||||
|
||||
@dataclass
|
||||
class ApprovalConfig:
|
||||
"""审批运行时参数。"""
|
||||
|
||||
# 超时催办 / 自动通过的扫描间隔。以前这个间隔是从 hub.sync_interval_minutes
|
||||
# 借的,两件事八竿子打不着:Hub 全量校对按文档调成一天一次之后,审批超时就变成
|
||||
# 一天才处理一回,节点到期 23 小时59分都不会有人被催。
|
||||
timeout_sweep_minutes: int = 10
|
||||
|
||||
|
||||
@dataclass
|
||||
class SeedConfig:
|
||||
demo_data: bool = True
|
||||
admin_account: str = "admin"
|
||||
admin_password: str = ""
|
||||
# 第二把本地门(可选):与内置超管同样的权限,但账号名另起一个,留给"Hub 密钥配错、
|
||||
# 应用没登记、门都进不去"的时候用。口令只在本系统校验,永远不拿去问统一身份。
|
||||
# 默认关着——内置超管本身就是一个本地账号,多数部署只要那一个;把它命名成和
|
||||
# ``admin_account`` 一样的名字,等于只有一把门。
|
||||
emergency_account: str = ""
|
||||
emergency_password: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class UploadConfig:
|
||||
path: str = "./storage/uploads"
|
||||
max_size_mb: int = 50
|
||||
allowed_ext: list[str] = field(
|
||||
default_factory=lambda: [
|
||||
"pdf", "doc", "docx", "xls", "xlsx", "png", "jpg", "jpeg", "zip", "rar",
|
||||
]
|
||||
)
|
||||
|
||||
@property
|
||||
def directory(self) -> Path:
|
||||
return Path(self.path)
|
||||
|
||||
|
||||
@dataclass
|
||||
class LogConfig:
|
||||
level: str = "INFO"
|
||||
dir: str = "./logs"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Settings:
|
||||
env: str = DEFAULT_ENV
|
||||
files: list[str] = field(default_factory=list)
|
||||
server: ServerConfig = field(default_factory=ServerConfig)
|
||||
database: DatabaseConfig = field(default_factory=DatabaseConfig)
|
||||
legacy: LegacyConfig = field(default_factory=LegacyConfig)
|
||||
security: SecurityConfig = field(default_factory=SecurityConfig)
|
||||
hub: HubConfig = field(default_factory=HubConfig)
|
||||
approval: ApprovalConfig = field(default_factory=ApprovalConfig)
|
||||
seed: SeedConfig = field(default_factory=SeedConfig)
|
||||
upload: UploadConfig = field(default_factory=UploadConfig)
|
||||
log: LogConfig = field(default_factory=LogConfig)
|
||||
|
||||
@property
|
||||
def is_production(self) -> bool:
|
||||
return self.env in PRODUCTION_ENVS
|
||||
|
||||
|
||||
def load_settings() -> Settings:
|
||||
raw, used = load_raw()
|
||||
meta = raw.get("_meta") or {}
|
||||
settings = Settings(env=str(meta.get("env") or DEFAULT_ENV), files=[str(p) for p in used])
|
||||
mapping = {
|
||||
"server": settings.server,
|
||||
"database": settings.database,
|
||||
"legacy": settings.legacy,
|
||||
"security": settings.security,
|
||||
"hub": settings.hub,
|
||||
"seed": settings.seed,
|
||||
"upload": settings.upload,
|
||||
"log": settings.log,
|
||||
}
|
||||
for section, instance in mapping.items():
|
||||
data = raw.get(section)
|
||||
if isinstance(data, dict):
|
||||
_fill(instance, data)
|
||||
return settings
|
||||
|
||||
|
||||
def warnings(settings: Settings) -> list[str]:
|
||||
"""上线体检:把生产上会出事配置项一次性点名。"""
|
||||
problems: list[str] = []
|
||||
if not settings.is_production:
|
||||
return problems
|
||||
if not settings.security.jwt_secret:
|
||||
problems.append("生产档没有配置 security.jwt_secret,登录令牌无法签发")
|
||||
if not settings.database.password:
|
||||
problems.append("生产档数据库口令为空")
|
||||
if settings.seed.demo_data:
|
||||
problems.append("生产档仍然打开了 seed.demo_data,会写入演示数据")
|
||||
if settings.database.auto_create_schema:
|
||||
problems.append("生产档打开了 database.auto_create_schema,建议改由 DBA 执行 sql/schema.sql")
|
||||
if settings.legacy.enabled and not settings.legacy.user:
|
||||
problems.append("生产档打开了 legacy 但没有配置只读账号")
|
||||
if settings.hub.enabled:
|
||||
# 这几条都会导致"同步静默拿到空目录",然后按 hub 里没人把本地账号整批停用,
|
||||
# 属于必须在上线前点名的那类配置。
|
||||
if not settings.hub.base_url:
|
||||
problems.append("生产档打开了 hub 但没有 base_url")
|
||||
elif not settings.hub.base_url.startswith("https://"):
|
||||
problems.append("生产档 hub.base_url 不是 HTTPS,票据与密钥会走明文")
|
||||
if not settings.hub.directory_key:
|
||||
problems.append("生产档打开了 hub 但没有 directory_key,组织与人员拉不进来")
|
||||
if bool(settings.hub.app_code) != bool(settings.hub.integration_key):
|
||||
problems.append("生产档 hub 免登只配了一半(app_code 与 integration_key 要同时有)")
|
||||
if settings.hub.directory_member_limit < 2000:
|
||||
problems.append("hub.directory_member_limit 低于接口默认值 2000,人多的时候会直接报截断")
|
||||
elif settings.hub.directory_member_limit > 5000:
|
||||
# 客户端会把它收进 1-5000 再发出去(越界 Hub 直接 400),写大了不报错,
|
||||
# 但也不会有任何效果,照样在截断那一步停下来。
|
||||
problems.append("hub.directory_member_limit 超过接口上限 5000,实际按 5000 生效")
|
||||
return problems
|
||||
|
||||
|
||||
settings = load_settings()
|
||||
logger.info("四算 PMS 档位=%s 配置文件=%s", settings.env, ", ".join(settings.files) or "(仅默认值)")
|
||||
|
|
@ -0,0 +1,178 @@
|
|||
"""数据库会话与建库建表。
|
||||
|
||||
生产上 ``database.auto_create_schema=false`` 时这里什么都不做,建表交 DBA 跑
|
||||
``sql/schema.sql``;开发/测试档默认打开,改了模型重启就生效,省去手工同步。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
|
||||
import pymysql
|
||||
from sqlalchemy import create_engine, inspect, text
|
||||
from sqlalchemy.engine import Engine
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from .config import settings
|
||||
from .models import Base
|
||||
|
||||
logger = logging.getLogger("pms.db")
|
||||
|
||||
engine: Engine | None = None
|
||||
SessionLocal: sessionmaker[Session] | None = None
|
||||
|
||||
#: 老系统留下的连接保活:容器里空闲连接常被中间设备掐断
|
||||
POOL_PARAMETERS = {"pool_pre_ping": True, "pool_recycle": 1800}
|
||||
|
||||
|
||||
def get_engine() -> Engine:
|
||||
global engine
|
||||
if engine is None:
|
||||
engine = create_engine(
|
||||
settings.database.url,
|
||||
echo=settings.database.echo_sql,
|
||||
pool_size=settings.database.pool_size,
|
||||
max_overflow=settings.database.max_overflow,
|
||||
**POOL_PARAMETERS,
|
||||
)
|
||||
return engine
|
||||
|
||||
|
||||
def get_session() -> Iterator[Session]:
|
||||
"""FastAPI 依赖用。"""
|
||||
session = SessionFactory()()
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def SessionFactory() -> sessionmaker[Session]:
|
||||
global SessionLocal
|
||||
if SessionLocal is None:
|
||||
SessionLocal = sessionmaker(bind=get_engine(), autoflush=False, expire_on_commit=False)
|
||||
return SessionLocal
|
||||
|
||||
|
||||
@contextmanager
|
||||
def session_scope() -> Iterator[Session]:
|
||||
"""脚本与定时任务用:正常提交、异常回滚。"""
|
||||
session = SessionFactory()()
|
||||
try:
|
||||
yield session
|
||||
session.commit()
|
||||
except Exception:
|
||||
session.rollback()
|
||||
raise
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def ensure_database() -> None:
|
||||
"""库不存在就建一个。只有引导配置能做这件事——连不上库就没地方读配置。"""
|
||||
config = settings.database
|
||||
if config.name.startswith("information_schema"):
|
||||
return
|
||||
connection = pymysql.connect(
|
||||
host=config.host,
|
||||
port=config.port,
|
||||
user=config.user,
|
||||
password=config.password,
|
||||
connect_timeout=10,
|
||||
charset="utf8mb4",
|
||||
autocommit=True,
|
||||
)
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute(
|
||||
f"CREATE DATABASE IF NOT EXISTS `{config.name}` "
|
||||
"DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"
|
||||
)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def create_all() -> None:
|
||||
"""建表 + 给已存在的表补新增列。
|
||||
|
||||
只做"加法":补列、补索引,永不删列改类型。删东西必须走 SQL 脚本,否则一次误改
|
||||
配置就能把生产数据洗掉。
|
||||
"""
|
||||
target = get_engine()
|
||||
Base.metadata.create_all(target)
|
||||
added = _add_missing_columns(target)
|
||||
if added:
|
||||
logger.info("已补齐 %d 个新增列:%s", len(added), "、".join(added[:12]))
|
||||
|
||||
|
||||
def _add_missing_columns(target: Engine) -> list[str]:
|
||||
inspector = inspect(target)
|
||||
existing_tables = set(inspector.get_table_names())
|
||||
added: list[str] = []
|
||||
with target.begin() as connection:
|
||||
for table in Base.metadata.sorted_tables:
|
||||
if table.name not in existing_tables:
|
||||
continue # create_all 刚建过,列一定是全的
|
||||
present = {column["name"] for column in inspector.get_columns(table.name)}
|
||||
for column in table.columns:
|
||||
if column.name in present:
|
||||
continue
|
||||
column_type = column.type.compile(target.dialect)
|
||||
piece = f"ALTER TABLE `{table.name}` ADD COLUMN `{column.name}` {column_type}"
|
||||
if not column.nullable:
|
||||
default = _literal_default(column)
|
||||
if default is None:
|
||||
piece += " NULL"
|
||||
elif _large_type_needs_expression_default(column_type):
|
||||
# MySQL 8:BLOB/TEXT/JSON/GEOMETRY 不接受字面量默认值,
|
||||
# 只能写成表达式默认值 DEFAULT (''),否则整条 ADD COLUMN 直接报错。
|
||||
piece += f" NOT NULL DEFAULT ({default})"
|
||||
else:
|
||||
piece += f" NOT NULL DEFAULT {default}"
|
||||
connection.execute(text(piece))
|
||||
added.append(f"{table.name}.{column.name}")
|
||||
return added
|
||||
|
||||
|
||||
#: MySQL 里这几类大字段不能带字面量默认值(1101),得用括号包起来的表达式默认值
|
||||
_LARGE_TYPE_PREFIXES = ("tinytext", "text", "mediumtext", "longtext",
|
||||
"tinyblob", "blob", "mediumblob", "longblob",
|
||||
"json", "geometry")
|
||||
|
||||
|
||||
def _large_type_needs_expression_default(column_type: str) -> bool:
|
||||
return column_type.lower().startswith(_LARGE_TYPE_PREFIXES)
|
||||
|
||||
|
||||
def _literal_default(column: object) -> str | None:
|
||||
server_default = getattr(column, "server_default", None)
|
||||
if server_default is not None and getattr(server_default, "arg", None):
|
||||
return str(server_default.arg)
|
||||
default = getattr(column, "default", None)
|
||||
if default is not None and default.is_scalar:
|
||||
value = default.arg
|
||||
if isinstance(value, bool):
|
||||
return "1" if value else "0"
|
||||
if isinstance(value, (int, float)):
|
||||
return str(value)
|
||||
return "'" + str(value).replace("'", "''") + "'"
|
||||
return None
|
||||
|
||||
|
||||
def legacy_engine() -> Engine | None:
|
||||
"""老四算库的只读连接。迁移与对账用,没配就返回 None。"""
|
||||
if not settings.legacy.enabled:
|
||||
return None
|
||||
return create_engine(settings.legacy.url, pool_pre_ping=True, **{})
|
||||
|
||||
|
||||
def ping() -> bool:
|
||||
try:
|
||||
with get_engine().connect() as connection:
|
||||
connection.execute(text("SELECT 1"))
|
||||
return True
|
||||
except Exception as exc: # pragma: no cover - 取决于环境
|
||||
logger.warning("数据库不可用:%s", exc)
|
||||
return False
|
||||
|
|
@ -0,0 +1,144 @@
|
|||
"""FastAPI 依赖:登录态、权限判定、数据范围。
|
||||
|
||||
接口鉴权只认权限码,因此加新页面不用改网关配置,删权限也不用改代码。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Depends, Request
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .db import get_session
|
||||
from .envelope import forbidden, unauthorized
|
||||
from .models import Account, Project, Status
|
||||
from .security import TokenError, decode_token
|
||||
from .service import data_scope, permissions
|
||||
|
||||
DbSession = Annotated[Session, Depends(get_session)]
|
||||
|
||||
|
||||
def client_ip(request: Request) -> str:
|
||||
"""访客 IP。过了反代以后 ``request.client`` 只会是代理的地址,先认 ``X-Forwarded-For``。
|
||||
|
||||
登录日志、审计、免登失败告警都要用它定位是谁在试,所以放在这里共用一份,
|
||||
不在每个 API 模块里各抄一遍——抄多了迟早有一处忘了认反向代理头。
|
||||
"""
|
||||
forwarded = request.headers.get("X-Forwarded-For")
|
||||
if forwarded:
|
||||
return forwarded.split(",")[0].strip()
|
||||
return request.client.host if request.client else ""
|
||||
|
||||
|
||||
def _bearer(request: Request) -> str:
|
||||
header = request.headers.get("Authorization") or ""
|
||||
if header.lower().startswith("bearer "):
|
||||
return header[7:].strip()
|
||||
token = request.cookies.get("pms_token") or request.query_params.get("token") or ""
|
||||
return token.strip()
|
||||
|
||||
|
||||
def current_account(db: DbSession, request: Request) -> Account:
|
||||
token = _bearer(request)
|
||||
if not token:
|
||||
raise unauthorized("请先登录")
|
||||
try:
|
||||
payload = decode_token(token)
|
||||
except TokenError as exc:
|
||||
raise unauthorized(str(exc)) from exc
|
||||
|
||||
account = db.get(Account, int(payload.get("sub") or 0))
|
||||
if account is None or account.is_deleted:
|
||||
raise unauthorized("账号不存在或已被删除")
|
||||
if not Status.is_active(account.status):
|
||||
raise unauthorized(f"账号已{Status.label(account.status)},请联系管理员")
|
||||
|
||||
request.state.account = account
|
||||
return account
|
||||
|
||||
|
||||
CurrentUser = Annotated[Account, Depends(current_account)]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Principal:
|
||||
"""当前人的"账号 + 授权视图 + 数据范围上下文",一个依赖搞定三层鉴权所需的东西。"""
|
||||
|
||||
account: Account
|
||||
permission: permissions.PermissionContext
|
||||
scope: data_scope.ScopeContext
|
||||
|
||||
|
||||
def principal(db: DbSession, account: CurrentUser) -> Principal:
|
||||
cached: Principal | None = getattr(db, "_pms_principal", None)
|
||||
if cached is not None and cached.account.id == account.id:
|
||||
return cached
|
||||
built = Principal(
|
||||
account=account,
|
||||
permission=permissions.build_context(db, account),
|
||||
scope=data_scope.build_scope_context(db, account),
|
||||
)
|
||||
try:
|
||||
db._pms_principal = built # type: ignore[attr-defined]
|
||||
except Exception: # pragma: no cover - 极少数 Session 实现不允许挂属性
|
||||
pass
|
||||
return built
|
||||
|
||||
|
||||
PrincipalOf = Annotated[Principal, Depends(principal)]
|
||||
|
||||
|
||||
def require(code: str, *also: str):
|
||||
"""接口级权限。``@require("project:budget:edit")``。"""
|
||||
wanted = (code, *also)
|
||||
|
||||
def dependency(current: PrincipalOf) -> Principal:
|
||||
if not current.permission.can_any(wanted):
|
||||
raise forbidden(f"缺少权限:{' 或 '.join(wanted)}")
|
||||
return current
|
||||
|
||||
return Depends(dependency)
|
||||
|
||||
|
||||
def data_filter(module: str):
|
||||
"""把某模块的数据权限条件注到查询上。"""
|
||||
|
||||
def dependency(db: DbSession, current: PrincipalOf) -> data_scope.ScopeDecision:
|
||||
return data_scope.evaluate(db, module, current.scope)
|
||||
|
||||
return Depends(dependency)
|
||||
|
||||
|
||||
def scope_of(db: Session, current: Principal, module: str) -> data_scope.ScopeDecision:
|
||||
return data_scope.evaluate(db, module, current.scope)
|
||||
|
||||
|
||||
def assert_project_visible(db: Session, current: Principal, project_id: int,
|
||||
module: str = "project", *,
|
||||
allow_deleted: bool = False) -> Project:
|
||||
"""单个对象的越权检查。
|
||||
|
||||
列表过滤挡不住"直接猜 ID 调详情"这条路,所以每个按 id 取项目的接口都要过这里。
|
||||
判定方式和列表完全一致(同一份 :func:`data_scope.evaluate`),不会出现
|
||||
"列表看不见但详情打得开"。
|
||||
|
||||
``allow_deleted=True`` 只给回收站用(删除确认与恢复):软删除的项目对业务接口
|
||||
一律当作不存在,但对"把它救回来"这两条接口必须还得看得见。
|
||||
"""
|
||||
from .envelope import not_found
|
||||
|
||||
project = db.get(Project, project_id)
|
||||
if project is None or (project.is_deleted and not allow_deleted):
|
||||
raise not_found("项目不存在")
|
||||
|
||||
decision = data_scope.evaluate(db, module, current.scope)
|
||||
if decision.unlimited:
|
||||
return project
|
||||
|
||||
statement = decision.apply_to(select(Project.id).where(Project.id == project_id))
|
||||
if db.execute(statement).first() is None:
|
||||
raise forbidden("没有该项目的数据权限")
|
||||
return project
|
||||
|
|
@ -0,0 +1,457 @@
|
|||
"""数据字典服务:代码枚举 + 库内维护,一份取值喂到前端。
|
||||
|
||||
单一事实来源本来是 model 里的 ``LABELS``,但"能在界面上改一改取值"这件事代码给不了——
|
||||
加一个客户等级、把一个阶段名从"S3-预算评估"改成"S3-预算评审"都得发版。所以现在分两层:
|
||||
|
||||
* **代码层**(本文件的 :data:`SPECS`):业务分支依赖的枚举,启动时同步进 ``dict_type``
|
||||
/ ``dict_item``,标成 ``source=system``。代码永远是这份的兜底:库是空的、表还没建、
|
||||
字典被误删,读到的仍是代码里的取值,系统不会因为字典没种好就白屏。
|
||||
* **库内层**(``dict_type`` / ``dict_item``):运行期的事实来源。「系统 → 数据字典」
|
||||
改的就是这一层,改完立刻生效,还能建代码里根本没有的自定义字典。
|
||||
|
||||
读取走进程内缓存(下拉框取值是典型读多写少),写接口改完调 :func:`invalidate`。
|
||||
多进程部署时其他 worker 最长滞后 :data:`CACHE_TTL_SECONDS`,改完在界面上刷新一下即可。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Iterable, Mapping
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .models import (
|
||||
AccountSource,
|
||||
Action,
|
||||
BusinessModule,
|
||||
CandidateType,
|
||||
Certainty,
|
||||
CostType,
|
||||
DictItem,
|
||||
DictSource,
|
||||
DictType,
|
||||
DictValueType,
|
||||
Effect,
|
||||
FlowStatus,
|
||||
IncomeType,
|
||||
InstanceStatus,
|
||||
IndustryScene,
|
||||
MilestoneStatus,
|
||||
NodeType,
|
||||
OtherCostBucket,
|
||||
ProductCategory,
|
||||
PermKind,
|
||||
ProjectMemberRole,
|
||||
ProjectMilestone,
|
||||
ProjectSource,
|
||||
ProjectStage,
|
||||
ProjectType,
|
||||
PurchaseType,
|
||||
RevisionStatus,
|
||||
SaleStage,
|
||||
ScopeType,
|
||||
SignType,
|
||||
Status,
|
||||
SubjectType,
|
||||
TaskStatus,
|
||||
UnderwrittenMode,
|
||||
WbsTaskStatus,
|
||||
YesNo,
|
||||
)
|
||||
|
||||
#: 进程内缓存的存活时间(秒)。写接口会当场失效,这个值只兜多进程部署的跨进程延迟。
|
||||
CACHE_TTL_SECONDS = 60
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DictSpec:
|
||||
"""代码里定义的一份字典。"""
|
||||
|
||||
code: str
|
||||
name: str
|
||||
group: str
|
||||
items: tuple[tuple[Any, str], ...]
|
||||
value_type: str = DictValueType.STRING
|
||||
remark: str = ""
|
||||
#: value -> 状态色,只为让前端徽章有地方取色;留空由前端自己判
|
||||
tags: Mapping[Any, str] = field(default_factory=dict)
|
||||
|
||||
def options(self) -> list[dict[str, Any]]:
|
||||
return [{"value": value, "label": label} for value, label in self.items]
|
||||
|
||||
|
||||
def _numbered(labels: Mapping[Any, str]) -> tuple[str, tuple[tuple[Any, str], ...]]:
|
||||
"""整数键的 LABELS:按值排序,返回 (取值类型, 条目)。"""
|
||||
items = list(labels.items())
|
||||
if all(isinstance(key, int) for key, _ in items):
|
||||
items.sort(key=lambda kv: kv[0])
|
||||
return DictValueType.INT, tuple(items)
|
||||
return DictValueType.STRING, tuple(items)
|
||||
|
||||
|
||||
def _enum(code: str, name: str, group: str, labels: Mapping[Any, str], *,
|
||||
remark: str = "", tags: Mapping[Any, str] | None = None) -> DictSpec:
|
||||
value_type, items = _numbered(labels)
|
||||
return DictSpec(code=code, name=name, group=group, items=items,
|
||||
value_type=value_type, remark=remark, tags=tags or {})
|
||||
|
||||
|
||||
#: 审批里"状态色"的推荐值,与前端 StatusBadge 那份默认色一致;界面上可以改。
|
||||
_STATUS_TAGS = {
|
||||
"draft": "gray", "reviewing": "warning", "pending": "warning", "approved": "success",
|
||||
"done": "success", "rejected": "danger", "withdrawn": "gray", "canceled": "gray",
|
||||
"skipped": "gray", "transferred": "info", "published": "success", "offline": "gray",
|
||||
}
|
||||
|
||||
|
||||
def _specs() -> dict[str, DictSpec]:
|
||||
specs = [
|
||||
# 项目
|
||||
_enum("projectType", "项目类型", "项目", ProjectType.LABELS),
|
||||
_enum("projectStage", "项目阶段", "项目", ProjectStage.LABELS),
|
||||
_enum("underwrittenMode", "垫资模式", "项目", UnderwrittenMode.LABELS),
|
||||
_enum("projectMemberRole", "项目成员种类", "项目", ProjectMemberRole.LABELS),
|
||||
_enum("certainty", "项目把握度", "项目", Certainty.LABELS),
|
||||
_enum("industryScene", "行业场景应用", "项目", IndustryScene.LABELS,
|
||||
remark="取值沿用老四算 project.industry_scene 的实际分布;0 表示老数据只填了描述"),
|
||||
_enum("saleStage", "公司销售阶段", "项目", SaleStage.LABELS,
|
||||
remark="老库这一列没有注释,档位名是可改的初始值;分支与迁移只认编码"),
|
||||
_enum("yesNo", "是/否", "项目", YesNo.LABELS,
|
||||
remark="是否二次合作、是否汇智中标这类下拉框;0 与 -1 都显示为未填"),
|
||||
_enum("milestoneStatus", "里程碑状态", "项目", MilestoneStatus.LABELS,
|
||||
remark="已逾期由系统按计划日期现算,不落库"),
|
||||
_enum("wbsTaskStatus", "WBS 任务状态", "项目", WbsTaskStatus.LABELS),
|
||||
# 明细分类
|
||||
_enum("incomeType", "收入明细类别", "立项预算", IncomeType.LABELS),
|
||||
_enum("purchaseType", "采购明细类别", "立项预算", PurchaseType.LABELS),
|
||||
_enum("costType", "成本明细类别", "立项预算", CostType.LABELS),
|
||||
_enum("revisionStatus", "版本状态", "立项预算", RevisionStatus.LABELS,
|
||||
tags=_STATUS_TAGS),
|
||||
_enum("productCategory", "产品归属", "立项预算", ProductCategory.LABELS,
|
||||
remark="取值决定金额投影到项目主档的哪一列,改动前先和财务确认"),
|
||||
_enum("otherCostBucket", "费用归属", "立项预算", OtherCostBucket.LABELS,
|
||||
remark="计算器按这一列决定费用进利润公式的哪一层"),
|
||||
# 组织
|
||||
_enum("accountStatus", "账号状态", "组织", Status.LABELS,
|
||||
remark="组织与账号共用;Hub 导出的 status 也是这套数字"),
|
||||
_enum("accountSource", "账号来源", "组织", AccountSource.LABELS),
|
||||
# 权限
|
||||
_enum("permKind", "权限节点类型", "权限", PermKind.LABELS),
|
||||
_enum("effect", "数据策略效果", "权限", Effect.LABELS),
|
||||
_enum("scopeType", "数据范围", "权限", ScopeType.LABELS),
|
||||
_enum("subjectType", "策略主体类型", "权限", SubjectType.LABELS),
|
||||
_enum("dataOperator", "数据条件运算符", "权限", {
|
||||
"eq": "等于", "ne": "不等于", "gt": "大于", "gte": "大于等于",
|
||||
"lt": "小于", "lte": "小于等于", "in": "属于", "not_in": "不属于",
|
||||
"contains": "包含", "not_contains": "不包含",
|
||||
"is_null": "为空", "is_not_null": "不为空",
|
||||
}),
|
||||
_enum("logicOp", "条件组合方式", "权限", {"and": "全部满足 (and)", "or": "任一满足 (or)"}),
|
||||
_enum("dynamicValue", "动态取值", "权限", {
|
||||
"$account_id": "当前登录人",
|
||||
"$org_unit_ids": "当前人所在部门",
|
||||
"$org_unit_ids_with_children": "当前人所在部门及下级",
|
||||
}),
|
||||
# 审批
|
||||
_enum("businessModule", "审批业务模块", "审批", BusinessModule.LABELS),
|
||||
_enum("flowStatus", "流程状态", "审批", FlowStatus.LABELS, tags=_STATUS_TAGS),
|
||||
_enum("nodeType", "流程节点类型", "审批", NodeType.LABELS),
|
||||
_enum("signType", "多人办理方式", "审批", SignType.LABELS),
|
||||
_enum("candidateType", "候选人来源", "审批", CandidateType.LABELS),
|
||||
_enum("emptyStrategy", "找不到审批人时", "审批", {
|
||||
"error": "报错并阻止送审", "skip": "跳过该节点", "admin": "转给系统管理员",
|
||||
}),
|
||||
_enum("timeoutAction", "审批超时处理", "审批", {
|
||||
"none": "不处理", "remind": "自动催办", "auto_approve": "自动通过",
|
||||
}),
|
||||
_enum("instanceStatus", "审批实例状态", "审批", InstanceStatus.LABELS,
|
||||
tags=_STATUS_TAGS),
|
||||
_enum("taskStatus", "审批待办状态", "审批", TaskStatus.LABELS, tags=_STATUS_TAGS),
|
||||
_enum("approvalAction", "审批动作", "审批", Action.LABELS),
|
||||
]
|
||||
return {spec.code: spec for spec in specs}
|
||||
|
||||
|
||||
#: 代码内置字典清单;:func:`sync` 按这份补齐库里的字典,界面上删不掉的也是这份。
|
||||
SPECS: dict[str, DictSpec] = _specs()
|
||||
|
||||
_LOCK = threading.RLock()
|
||||
#: 两份缓存:下拉框只看在用的条目,取显示名时停用的也算(历史数据还得显示名字)。
|
||||
_CACHE: dict[str, dict[str, Any]] = {
|
||||
"options": {"at": 0.0, "data": {}},
|
||||
"labels": {"at": 0.0, "data": {}},
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 纯代码层(不碰库,建库前的兜底)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def code_options() -> dict[str, list[dict[str, Any]]]:
|
||||
return {code: spec.options() for code, spec in SPECS.items()}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 缓存
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def invalidate() -> None:
|
||||
"""让缓存作废;所有写接口都要调,否则界面改完取值看不到变化。"""
|
||||
with _LOCK:
|
||||
for bucket in _CACHE.values():
|
||||
bucket["at"] = 0.0
|
||||
bucket["data"] = {}
|
||||
|
||||
|
||||
def _coerce(value_type: str, raw: str) -> Any:
|
||||
if value_type == DictValueType.INT:
|
||||
try:
|
||||
return int(raw)
|
||||
except (TypeError, ValueError):
|
||||
# 界面上手滑填了非数字:宁可原样下发也别让整份字典读不出来
|
||||
return raw
|
||||
return raw
|
||||
|
||||
|
||||
def _load(db: Session) -> dict[str, list[dict[str, Any]]]:
|
||||
"""一次把全部字典读进内存。字典表只有几百行,逐类查不如一把捞。"""
|
||||
types = db.execute(
|
||||
select(DictType).where(DictType.is_deleted.is_(False)).order_by(DictType.id)
|
||||
).scalars().all()
|
||||
if not types:
|
||||
return code_options()
|
||||
|
||||
rows = db.execute(
|
||||
select(DictItem, DictType)
|
||||
.join(DictType, DictType.id == DictItem.dict_type_id)
|
||||
.where(DictItem.is_deleted.is_(False), DictItem.enabled.is_(True),
|
||||
DictType.enabled.is_(True))
|
||||
.order_by(DictItem.dict_type_id, DictItem.sort, DictItem.id)
|
||||
).all()
|
||||
grouped: dict[str, list[dict[str, Any]]] = {row.code: [] for row in types if not row.enabled}
|
||||
for item, parent in rows:
|
||||
option: dict[str, Any] = {
|
||||
"value": _coerce(parent.value_type, item.value), "label": item.label}
|
||||
if item.tag:
|
||||
option["tag"] = item.tag
|
||||
if item.remark:
|
||||
option["remark"] = item.remark
|
||||
grouped.setdefault(parent.code, []).append(option)
|
||||
|
||||
for code, spec in SPECS.items(): # 库里还没有这一类时退回代码取值
|
||||
grouped.setdefault(code, spec.options())
|
||||
return grouped
|
||||
|
||||
|
||||
def _cached(db: Session) -> dict[str, list[dict[str, Any]]]:
|
||||
return _memo("options", db, _load)
|
||||
|
||||
|
||||
def _memo(name: str, db: Session, loader: Any) -> dict[str, list[dict[str, Any]]]:
|
||||
bucket = _CACHE[name]
|
||||
now = time.monotonic()
|
||||
with _LOCK:
|
||||
fresh = now - bucket["at"] < CACHE_TTL_SECONDS and bucket["data"]
|
||||
data = bucket["data"] if fresh else loader(db)
|
||||
if not fresh:
|
||||
bucket.update(at=now, data=data)
|
||||
return data
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 读接口
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def build(db: Session | None = None) -> dict[str, list[dict[str, Any]]]:
|
||||
"""前端 ``/bootstrap`` 要的整份字典。
|
||||
|
||||
不传库就退化成代码取值:建库之前、健康检查这类路径都要能应答。
|
||||
"""
|
||||
if db is None:
|
||||
return code_options()
|
||||
return dict(_cached(db))
|
||||
|
||||
|
||||
def options(db: Session, code: str, *, include_disabled: bool = False) -> list[dict[str, Any]]:
|
||||
"""某个字典的取值。``include_disabled`` 时直查库,维护页要用停用的那些。"""
|
||||
if not include_disabled:
|
||||
return list(_cached(db).get(code) or [])
|
||||
return items(db, code, include_disabled=True)
|
||||
|
||||
|
||||
def items(db: Session, code: str, *, include_disabled: bool = False) -> list[dict[str, Any]]:
|
||||
"""维护页视角的条目(带 id、排序、启停),不走缓存。"""
|
||||
row = db.execute(select(DictType).where(DictType.code == code,
|
||||
DictType.is_deleted.is_(False))).scalars().first()
|
||||
if row is None:
|
||||
spec = SPECS.get(code)
|
||||
return [{"id": None, "value": str(value), "label": label, "sort": index * 10 + 10,
|
||||
"enabled": True, "tag": spec.tags.get(value, ""), "builtin": True,
|
||||
"remark": ""}
|
||||
for index, (value, label) in enumerate(spec.items)] if spec else []
|
||||
statement = (select(DictItem).where(DictItem.dict_type_id == row.id,
|
||||
DictItem.is_deleted.is_(False))
|
||||
.order_by(DictItem.sort, DictItem.id))
|
||||
rows = db.execute(statement).scalars().all()
|
||||
return [{"id": item.id, "value": _coerce(row.value_type, item.value),
|
||||
"label": item.label, "sort": item.sort, "enabled": bool(item.enabled),
|
||||
"tag": item.tag, "builtin": bool(item.builtin), "remark": item.remark}
|
||||
for item in rows if include_disabled or item.enabled]
|
||||
|
||||
|
||||
def label_from_code(code: str, value: Any, default: str = "") -> str:
|
||||
"""代码取值 → 显示名,不碰库。给签名里拿不到 Session 的小工具函数用。"""
|
||||
if value is None or value == "":
|
||||
return default
|
||||
spec = SPECS.get(code)
|
||||
if spec:
|
||||
for item_value, item_label in spec.items:
|
||||
if item_value == value or str(item_value) == str(value):
|
||||
return item_label
|
||||
return default
|
||||
|
||||
|
||||
def label(db: Session, code: str, value: Any, default: str = "") -> str:
|
||||
"""取显示名。库里没有这一项就退回代码里的名字,取不到再退回调用方给的兜底。
|
||||
|
||||
读路径上给接口用(列表页那几列 ``xxxLabel``),所以字典停用的条目也要能查出名字——
|
||||
停用只是从下拉框里摘掉,不代表历史数据上的值不该显示。
|
||||
"""
|
||||
if value is None or value == "":
|
||||
return default
|
||||
for row in _all_with_disabled(db).get(code, []):
|
||||
if row["value"] == value or str(row["value"]) == str(value):
|
||||
return row["label"]
|
||||
spec = SPECS.get(code)
|
||||
if spec:
|
||||
for item_value, item_label in spec.items:
|
||||
if item_value == value or str(item_value) == str(value):
|
||||
return item_label
|
||||
return default
|
||||
|
||||
|
||||
def _all_with_disabled(db: Session) -> dict[str, list[dict[str, Any]]]:
|
||||
return _memo("labels", db, _load_labels)
|
||||
|
||||
|
||||
def _load_labels(db: Session) -> dict[str, list[dict[str, Any]]]:
|
||||
rows = db.execute(
|
||||
select(DictItem, DictType)
|
||||
.join(DictType, DictType.id == DictItem.dict_type_id)
|
||||
.where(DictItem.is_deleted.is_(False))
|
||||
.order_by(DictItem.dict_type_id, DictItem.sort, DictItem.id)
|
||||
).all()
|
||||
grouped: dict[str, list[dict[str, Any]]] = {}
|
||||
for item, parent in rows:
|
||||
grouped.setdefault(parent.code, []).append(
|
||||
{"value": _coerce(parent.value_type, item.value), "label": item.label})
|
||||
for code, spec in SPECS.items():
|
||||
grouped.setdefault(code, [{"value": value, "label": lab} for value, lab in spec.items])
|
||||
return grouped
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 写接口(维护页与 seed 共用)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def sync(db: Session) -> dict[str, int]:
|
||||
"""把代码字典同步进库:缺的补上,已有的不动。
|
||||
|
||||
刻意不覆盖已有条目——界面上改过的名字被一次重启冲掉,比名字对不上更难查。
|
||||
想把某类字典恢复成代码取值,用维护页的「恢复默认」。
|
||||
"""
|
||||
created_types = created_items = 0
|
||||
types = {row.code: row for row in
|
||||
db.execute(select(DictType)).scalars().all()}
|
||||
for code, spec in SPECS.items():
|
||||
parent = types.get(code)
|
||||
if parent is None:
|
||||
parent = DictType(code=code, name=spec.name, group=spec.group,
|
||||
value_type=spec.value_type, source=DictSource.SYSTEM,
|
||||
enabled=True, remark=spec.remark)
|
||||
db.add(parent)
|
||||
db.flush()
|
||||
types[code] = parent
|
||||
created_types += 1
|
||||
elif parent.source != DictSource.SYSTEM:
|
||||
# 有人先手工建了同名编码:认下来,但别把它改造成系统字典,
|
||||
# 否则"恢复默认"会往一份自定义取值里灌代码枚举。
|
||||
continue
|
||||
|
||||
existing = {row.value for row in
|
||||
db.execute(select(DictItem).where(DictItem.dict_type_id == parent.id)
|
||||
).scalars().all()}
|
||||
for index, (value, label_text) in enumerate(spec.items):
|
||||
raw = str(value)
|
||||
if raw in existing:
|
||||
continue
|
||||
db.add(DictItem(dict_type_id=parent.id, value=raw, label=label_text,
|
||||
sort=index * 10 + 10, enabled=True,
|
||||
tag=spec.tags.get(value, ""), builtin=True, remark=""))
|
||||
created_items += 1
|
||||
db.flush()
|
||||
invalidate()
|
||||
return {"types": created_types, "items": created_items}
|
||||
|
||||
|
||||
def reset_items(db: Session, code: str) -> int:
|
||||
"""把某个代码字典的取值恢复成代码定义(改名回来、误停的恢复)。"""
|
||||
spec = SPECS.get(code)
|
||||
if spec is None:
|
||||
raise ValueError(f"{code} 不是代码内置字典,没有默认值可恢复")
|
||||
parent = db.execute(select(DictType).where(DictType.code == code,
|
||||
DictType.is_deleted.is_(False))).scalars().first()
|
||||
if parent is None:
|
||||
sync(db)
|
||||
return 0
|
||||
rows = db.execute(select(DictItem).where(DictItem.dict_type_id == parent.id)
|
||||
.order_by(DictItem.id)).scalars().all()
|
||||
by_value = {row.value: row for row in rows}
|
||||
for index, (value, label_text) in enumerate(spec.items):
|
||||
row = by_value.get(str(value))
|
||||
if row is None:
|
||||
db.add(DictItem(dict_type_id=parent.id, value=str(value), label=label_text,
|
||||
sort=index * 10 + 10, enabled=True,
|
||||
tag=spec.tags.get(value, ""), builtin=True, remark=""))
|
||||
continue
|
||||
row.label, row.sort, row.enabled, row.is_deleted = label_text, index * 10 + 10, True, False
|
||||
row.tag = spec.tags.get(value, "")
|
||||
count = len(spec.items)
|
||||
for row in rows:
|
||||
if row.value not in {str(value) for value, _ in spec.items}:
|
||||
row.is_deleted = True
|
||||
db.flush()
|
||||
invalidate()
|
||||
return count
|
||||
|
||||
|
||||
def normalize_value(value_type: str, value: Any) -> str:
|
||||
"""把界面传来的取值折成库里存的字符串。整数型字典不接受非数字。"""
|
||||
text = str(value).strip()
|
||||
if value_type == DictValueType.INT:
|
||||
try:
|
||||
return str(int(text))
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError(f"该字典的取值类型是整数,{value!r} 不是整数") from None
|
||||
if not text:
|
||||
raise ValueError("取值不能为空")
|
||||
return text
|
||||
|
||||
|
||||
def export(db: Session, codes: Iterable[str] | None = None) -> dict[str, list[dict[str, Any]]]:
|
||||
"""按需取几类字典(前端懒加载用)。
|
||||
|
||||
点名了但系统里确实没有的编码不出现在结果里——前端把"缺键"当成"这份字典不存在",
|
||||
比回一串空数组更好判断(空数组也可能是整类停用)。
|
||||
"""
|
||||
data = _cached(db)
|
||||
if codes is None:
|
||||
return dict(data)
|
||||
return {code: list(data[code]) for code in codes if code in data}
|
||||
|
|
@ -0,0 +1,165 @@
|
|||
"""统一响应包装与错误模型。
|
||||
|
||||
前端只需要认一种形状:``{"ok": true, "data": ...}`` / ``{"ok": false, "error": {...}}``。
|
||||
错误对象里固定带 ``code``(机器读)、``message``(人读)、``detail``(表单级字段错误)
|
||||
和 ``traceId``(排障用),因此 422 校验、业务异常、未捕获异常在前端走同一段代码。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from typing import Any, Generic, TypeVar
|
||||
|
||||
from fastapi import FastAPI, Request, status
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
logger = logging.getLogger("pms.api")
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class ErrorBody(BaseModel):
|
||||
code: str
|
||||
message: str
|
||||
detail: Any | None = None
|
||||
|
||||
|
||||
class ApiResponse(BaseModel, Generic[T]):
|
||||
ok: bool = True
|
||||
data: T | None = None
|
||||
error: ErrorBody | None = None
|
||||
|
||||
|
||||
class PageMeta(BaseModel):
|
||||
total: int = 0
|
||||
page: int = 1
|
||||
page_size: int = Field(default=20, alias="pageSize")
|
||||
|
||||
model_config = {"populate_by_name": True}
|
||||
|
||||
|
||||
class PageData(BaseModel, Generic[T]):
|
||||
items: list[T] = Field(default_factory=list)
|
||||
meta: PageMeta
|
||||
|
||||
|
||||
def ok(data: Any = None) -> dict[str, Any]:
|
||||
return {"ok": True, "data": data}
|
||||
|
||||
|
||||
def page(items: list[Any], total: int, page_no: int, page_size: int) -> dict[str, Any]:
|
||||
return {
|
||||
"ok": True,
|
||||
"data": {
|
||||
"items": items,
|
||||
"meta": {"total": total, "page": page_no, "pageSize": page_size},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
"""业务异常。抛这个,中间件会翻成人话并带上 traceId。"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
code: str,
|
||||
message: str,
|
||||
*,
|
||||
http_status: int = status.HTTP_400_BAD_REQUEST,
|
||||
detail: Any = None,
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.http_status = http_status
|
||||
self.detail = detail
|
||||
|
||||
|
||||
def not_found(message: str = "记录不存在") -> ApiError:
|
||||
return ApiError("not_found", message, http_status=status.HTTP_404_NOT_FOUND)
|
||||
|
||||
|
||||
def forbidden(message: str = "没有权限执行该操作") -> ApiError:
|
||||
return ApiError("forbidden", message, http_status=status.HTTP_403_FORBIDDEN)
|
||||
|
||||
|
||||
def unauthorized(message: str = "登录状态已失效,请重新登录") -> ApiError:
|
||||
return ApiError("unauthorized", message, http_status=status.HTTP_401_UNAUTHORIZED)
|
||||
|
||||
|
||||
def bad_request(code: str, message: str, detail: Any = None) -> ApiError:
|
||||
"""请求本身没问题,但业务规则不让做:用 400,别和 409 的状态冲突混用。"""
|
||||
return ApiError(code, message, http_status=status.HTTP_400_BAD_REQUEST, detail=detail)
|
||||
|
||||
|
||||
def conflict(code: str, message: str, detail: Any = None) -> ApiError:
|
||||
return ApiError(code, message, http_status=status.HTTP_409_CONFLICT, detail=detail)
|
||||
|
||||
|
||||
def trace_id(request: Request) -> str:
|
||||
return getattr(request.state, "trace_id", "")
|
||||
|
||||
|
||||
def install_handlers(app: FastAPI) -> None:
|
||||
"""挂上异常处理与 traceId。"""
|
||||
|
||||
@app.middleware("http")
|
||||
async def attach_trace(request: Request, call_next): # pragma: no cover - 由框架调用
|
||||
request.state.trace_id = request.headers.get("X-Trace-Id") or uuid.uuid4().hex[:16]
|
||||
response = await call_next(request)
|
||||
response.headers["X-Trace-Id"] = request.state.trace_id
|
||||
return response
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
async def handle_api_error(request: Request, exc: ApiError) -> JSONResponse:
|
||||
return JSONResponse(
|
||||
status_code=exc.http_status,
|
||||
content={
|
||||
"ok": False,
|
||||
"error": {
|
||||
"code": exc.code,
|
||||
"message": exc.message,
|
||||
"detail": exc.detail,
|
||||
"traceId": trace_id(request),
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def handle_validation(request: Request, exc: RequestValidationError) -> JSONResponse:
|
||||
fields: dict[str, str] = {}
|
||||
for item in exc.errors():
|
||||
location = ".".join(str(part) for part in item.get("loc", ()) if part != "body")
|
||||
fields[location or "body"] = item.get("msg", "格式不正确")
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
content={
|
||||
"ok": False,
|
||||
"error": {
|
||||
"code": "validation_failed",
|
||||
"message": "提交的表单有 "
|
||||
f"{len(fields)} 处不符合要求",
|
||||
"detail": {"fields": fields},
|
||||
"traceId": trace_id(request),
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def handle_unexpected(request: Request, exc: Exception) -> JSONResponse: # pragma: no cover
|
||||
logger.exception("未处理异常 traceId=%s path=%s", trace_id(request), request.url.path)
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
content={
|
||||
"ok": False,
|
||||
"error": {
|
||||
"code": "internal_error",
|
||||
"message": "服务器内部错误,请把 traceId 发给管理员",
|
||||
"detail": None,
|
||||
"traceId": trace_id(request),
|
||||
},
|
||||
},
|
||||
)
|
||||
|
|
@ -0,0 +1,253 @@
|
|||
"""FastAPI 应用装配。
|
||||
|
||||
路由全部挂在 ``/api/v1`` 下,前端开发服务器通过 Vite 代理访问,生产走同域反向代理,
|
||||
因此两边都不需要配 CORS 白名单(本地开发例外,白名单来自配置文件)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Any
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from . import dicts
|
||||
from .api import approvals, audit as audit_api, auth, control, dicts as dicts_api, finance, org, plan, projects, system
|
||||
from .config import settings
|
||||
from .config import warnings as prod_warnings
|
||||
from .db import create_all, ensure_database, ping
|
||||
from .deps import DbSession
|
||||
from .models import Account, Status
|
||||
from .envelope import install_handlers, ok
|
||||
from .seed import seed_all
|
||||
from .service import audit as audit_log
|
||||
from .service.calc import engine as calc_engine
|
||||
from .service.calc import rules as calc_rules
|
||||
|
||||
logging.basicConfig(
|
||||
level=getattr(logging, (settings.log.level or "INFO").upper(), logging.INFO),
|
||||
format="%(asctime)s %(levelname)-5s %(name)s | %(message)s",
|
||||
)
|
||||
logger = logging.getLogger("pms.app")
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_app: FastAPI):
|
||||
_bootstrap()
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
lifespan=lifespan,
|
||||
title="四算项目管理系统",
|
||||
version="1.0.0",
|
||||
description="项目立项(概算)、项目预算与审批流程",
|
||||
docs_url="/api/docs",
|
||||
openapi_url="/api/openapi.json",
|
||||
)
|
||||
|
||||
install_handlers(app)
|
||||
|
||||
if settings.server.cors_origins:
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=settings.server.cors_origins,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# 写操作审计挂在最后加入(= 最外层),这样它看到的是最终状态码:过了 CORS、过了
|
||||
# traceId、也过了业务异常处理,"这次到底改成没有"才记得准。详见 service/audit.py。
|
||||
audit_log.install(app)
|
||||
|
||||
API = "/api/v1"
|
||||
app.include_router(auth.router, prefix=API)
|
||||
app.include_router(org.router, prefix=API)
|
||||
app.include_router(system.router, prefix=API)
|
||||
app.include_router(audit_api.router, prefix=API)
|
||||
app.include_router(projects.router, prefix=API)
|
||||
app.include_router(finance.router, prefix=API)
|
||||
app.include_router(plan.router, prefix=API)
|
||||
app.include_router(control.router, prefix=API)
|
||||
app.include_router(approvals.router, prefix=API)
|
||||
|
||||
# 字典的两个入口都在 /api/v1 下:/dicts 给页面取下拉值,/system/dicts 是维护页
|
||||
app.include_router(dicts_api.router, prefix=API)
|
||||
app.include_router(dicts_api.admin, prefix=API)
|
||||
|
||||
|
||||
#: 免登回调的短别名(``/sso/hub``)。Hub 上习惯把 launch_url 写成这一条,
|
||||
#: 同域反代把它转给后端即可;规范地址仍是 ``/api/v1/auth/sso/callback``。
|
||||
app.include_router(auth.sso_alias_router)
|
||||
|
||||
|
||||
@app.get("/api/health")
|
||||
def health() -> dict[str, Any]:
|
||||
"""存活 + 就绪:给容器编排和负载均衡用。"""
|
||||
database_ok = ping()
|
||||
payload = {
|
||||
"ok": database_ok,
|
||||
"status": "ready" if database_ok else "degraded",
|
||||
"env": settings.env,
|
||||
"database": settings.database.name if database_ok else "unavailable",
|
||||
"calcVersion": calc_engine.calc_version(),
|
||||
"hub": {"enabled": settings.hub.enabled, "configured": settings.hub.configured},
|
||||
}
|
||||
return JSONResponse(status_code=200 if database_ok else 503, content=payload)
|
||||
|
||||
|
||||
@app.get(f"{API}/bootstrap")
|
||||
def bootstrap(request: Request, db: DbSession) -> dict[str, Any]:
|
||||
"""前端启动时拉一次:运行档位、口径版本、数据字典、当前人的权限。
|
||||
|
||||
带了令牌就顺手把"这个人能看什么"一起返回,SPA 少一次往返、少一处加载竞态;
|
||||
没带令牌也照常返回枚举与告警,登录页要用。
|
||||
"""
|
||||
from .api.auth import profile_payload
|
||||
from .security import TokenError, decode_token
|
||||
from .service import permissions
|
||||
|
||||
payload: dict[str, Any] = {
|
||||
"env": settings.env,
|
||||
"calcVersion": calc_engine.calc_version(),
|
||||
"production": settings.is_production,
|
||||
"warnings": prod_warnings(settings),
|
||||
"hubEnabled": settings.hub.enabled,
|
||||
"ssoEnabled": settings.hub.sso_configured,
|
||||
# 登录页这三开关:口令框留不留、口令归不归统一身份验(决定要不要摆验证码)、
|
||||
# 本地自建账号的口令还认不认(只影响提示语)。口径与 GET /auth/sso/status 一致。
|
||||
"passwordLoginAllowed": settings.hub.password_login_allowed,
|
||||
"hubPasswordLogin": settings.hub.hub_password_login,
|
||||
"localPasswordAllowed": settings.hub.local_password_login_allowed,
|
||||
"loginMode": settings.hub.mode,
|
||||
"enums": dicts.build(db),
|
||||
"user": None,
|
||||
"permissions": [],
|
||||
"roles": [],
|
||||
"menus": [],
|
||||
"fieldMasks": {},
|
||||
}
|
||||
header = request.headers.get("Authorization") or ""
|
||||
token = header[7:].strip() if header.lower().startswith("bearer ") else ""
|
||||
if token:
|
||||
try:
|
||||
account_id = int(decode_token(token, expect="access").get("sub") or 0)
|
||||
except (TokenError, TypeError, ValueError):
|
||||
account_id = 0
|
||||
account = db.get(Account, account_id) if account_id else None
|
||||
if account is not None and not account.is_deleted and Status.is_active(account.status):
|
||||
context = permissions.build_context(db, account)
|
||||
payload.update({
|
||||
"user": profile_payload(db, account),
|
||||
"permissions": ["*"] if context.is_system_admin else sorted(context.codes),
|
||||
"roles": [{"id": role.id, "code": role.code, "name": role.name}
|
||||
for role in context.roles],
|
||||
"menus": permissions.menu_tree(db, context),
|
||||
"fieldMasks": context.field_masks,
|
||||
})
|
||||
return ok(payload)
|
||||
|
||||
|
||||
def _timeout_sweep_loop() -> None:
|
||||
"""审批超时轮询,间隔走 ``[approval].timeout_sweep_minutes``。"""
|
||||
interval = max(60, (settings.approval.timeout_sweep_minutes or 0) * 60)
|
||||
if settings.approval.timeout_sweep_minutes <= 0:
|
||||
return
|
||||
while True:
|
||||
time.sleep(interval)
|
||||
try:
|
||||
from .db import session_scope
|
||||
from .service.approval.engine import sweep_timeouts
|
||||
|
||||
with session_scope() as session:
|
||||
result = sweep_timeouts(session)
|
||||
if result["reminded"] or result["auto_approved"]:
|
||||
logger.info("审批超时处理:催办 %s 条,自动通过 %s 条",
|
||||
result["reminded"], result["auto_approved"])
|
||||
except Exception as exc: # 后台线程绝不能把进程带崩
|
||||
logger.warning("审批超时轮询失败:%s", exc)
|
||||
|
||||
|
||||
def _hub_sync_loop() -> None:
|
||||
"""统一身份定时任务,两条节奏各走各的。
|
||||
|
||||
文档 §6.3 把同步定成三件事:首次全量、固定周期轮增量(30~60 秒)、每日一次全量校对。
|
||||
增量和全量的代价差着两个数量级,不能共用一个间隔,所以这里拆成两个计时器共用一个
|
||||
线程:增量按 ``changes_interval_seconds`` 蹭游标,全量按 ``sync_interval_minutes``
|
||||
兜住"事件没发、写失败、父子关系变了"这三种增量永远补不到的情况。
|
||||
"""
|
||||
changes_interval = max(0, settings.hub.changes_interval_seconds or 0)
|
||||
full_interval = max(0, (settings.hub.sync_interval_minutes or 0) * 60)
|
||||
if not settings.hub.configured or (changes_interval <= 0 and full_interval <= 0):
|
||||
return
|
||||
|
||||
from .db import session_scope
|
||||
from .service.org_sync import local_cursor, sync_all, sync_changes
|
||||
|
||||
tick = min(x for x in (changes_interval or None, full_interval or None) if x) or 60
|
||||
since_changes = 0
|
||||
since_full = 0
|
||||
while True:
|
||||
time.sleep(tick)
|
||||
since_changes += tick
|
||||
since_full += tick
|
||||
|
||||
want_full = full_interval > 0 and since_full >= full_interval
|
||||
# 本地还没有游标就说明从没成功全量过,先补一次全量再说增量。
|
||||
if not want_full:
|
||||
try:
|
||||
with session_scope() as session:
|
||||
want_full = local_cursor(session) <= 0
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("读取目录游标失败:%s", exc)
|
||||
|
||||
try:
|
||||
if want_full:
|
||||
since_full = 0
|
||||
since_changes = 0
|
||||
with session_scope() as session:
|
||||
run = sync_all(session, trigger="scheduled")
|
||||
logger.info("统一身份全量校对:%s(部门 +%s/改%s,账号 +%s/改%s)",
|
||||
run.status, run.org_created, run.org_updated,
|
||||
run.account_created, run.account_updated)
|
||||
elif changes_interval > 0 and since_changes >= changes_interval:
|
||||
since_changes = 0
|
||||
with session_scope() as session:
|
||||
run = sync_changes(session, trigger="scheduled")
|
||||
if run.account_total or run.status != "success":
|
||||
logger.info("统一身份增量同步:%s 处理 %s 条,游标 %s",
|
||||
run.status, run.account_total, run.cursor_after)
|
||||
except Exception as exc: # 后台线程绝不能把进程带崩
|
||||
logger.warning("统一身份定时同步失败:%s", exc)
|
||||
|
||||
|
||||
def _bootstrap() -> None:
|
||||
logger.info("四算 PMS 启动:档位=%s", settings.env)
|
||||
for message in prod_warnings(settings):
|
||||
logger.warning("上线体检:%s", message)
|
||||
|
||||
if settings.database.auto_create_schema:
|
||||
ensure_database()
|
||||
create_all()
|
||||
counts = seed_all()
|
||||
logger.info("基础数据就绪:%s", counts)
|
||||
|
||||
from .db import session_scope
|
||||
|
||||
# 口径在库里,不在配置文件里:建表补完参数就把生效值读进内核,
|
||||
# 免得第一个请求赶在 seed 之前跑,用的是代码默认值却盖着界面上的版本号。
|
||||
with session_scope() as session:
|
||||
calc_rules.reload(session)
|
||||
logger.info("计算口径 %s:%s", calc_engine.calc_version(), calc_rules.describe(
|
||||
[spec.attr for spec in calc_rules.RULE_SPECS if spec.attr != "version"]))
|
||||
|
||||
if not threading.main_thread().is_alive(): # pragma: no cover - 防御
|
||||
return
|
||||
threading.Thread(target=_timeout_sweep_loop, daemon=True, name="approval-timeout").start()
|
||||
if settings.hub.enabled and settings.hub.configured:
|
||||
threading.Thread(target=_hub_sync_loop, daemon=True, name="hub-sync").start()
|
||||
|
|
@ -0,0 +1,127 @@
|
|||
"""所有 ORM 模型集中导出,建表与 Alembic 式自检都看这个包。"""
|
||||
|
||||
from .base import Base, SoftDeleteMixin, TimestampMixin, money, percent, to_decimal
|
||||
from .org import (
|
||||
Account,
|
||||
AccountIdentity,
|
||||
AccountSource,
|
||||
HubSyncRun,
|
||||
LoginLog,
|
||||
OperationLog,
|
||||
OrgUnit,
|
||||
Position,
|
||||
SsoHandoff,
|
||||
Status,
|
||||
)
|
||||
from .permission import (
|
||||
FALLBACK_SCOPE,
|
||||
Effect,
|
||||
FieldScope,
|
||||
PermAccountRole,
|
||||
PermDataPolicy,
|
||||
PermKind,
|
||||
PermNode,
|
||||
PermRole,
|
||||
PermRoleNode,
|
||||
ScopeType,
|
||||
SubjectType,
|
||||
)
|
||||
from .project import (
|
||||
Attachment,
|
||||
Project,
|
||||
ProjectMember,
|
||||
ProjectMemberRole,
|
||||
ProjectStage,
|
||||
ProjectStageLog,
|
||||
ProjectType,
|
||||
ProjectVisibleRole,
|
||||
SystemConfig,
|
||||
UnderwrittenMode,
|
||||
)
|
||||
from .project import (
|
||||
Certainty,
|
||||
IndustryScene,
|
||||
MilestoneStatus,
|
||||
ProjectMilestone,
|
||||
ProjectSource,
|
||||
ProjectStageEvent,
|
||||
SaleStage,
|
||||
WbsTask,
|
||||
WbsTaskStatus,
|
||||
YesNo,
|
||||
)
|
||||
from .finance import (
|
||||
BudgetFundMonth,
|
||||
BudgetIncomeLine,
|
||||
BudgetIncomePlanLine,
|
||||
BudgetManageLine,
|
||||
BudgetOtherCostLine,
|
||||
BudgetPayPlanLine,
|
||||
BudgetPurchaseLine,
|
||||
CalcSnapshot,
|
||||
CostFeeGroup,
|
||||
CostType,
|
||||
EstimateCostLine,
|
||||
EstimateIncomeLine,
|
||||
EstimateOtherLine,
|
||||
EstimateManageType,
|
||||
IncomeType,
|
||||
ManageItemCode,
|
||||
OtherCostBucket,
|
||||
ProductCategory,
|
||||
PurchaseType,
|
||||
Revision,
|
||||
RevisionModule,
|
||||
RevisionStatus,
|
||||
)
|
||||
from .dictionary import DictItem, DictSource, DictType, DictValueType
|
||||
from .approval import (
|
||||
Action,
|
||||
ApprovalDelegate,
|
||||
ApprovalFlow,
|
||||
ApprovalInstance,
|
||||
ApprovalNode,
|
||||
ApprovalRecord,
|
||||
ApprovalTask,
|
||||
BusinessModule,
|
||||
CandidateType,
|
||||
FlowStatus,
|
||||
InstanceStatus,
|
||||
NodeType,
|
||||
SignType,
|
||||
TaskStatus,
|
||||
)
|
||||
|
||||
#: 建表顺序无关紧要(SQLAlchemy 会拓扑排序),列在这里方便自检脚本比对
|
||||
ALL_MODELS = (
|
||||
OrgUnit, Position, Account, AccountIdentity, HubSyncRun, SsoHandoff, LoginLog, OperationLog,
|
||||
PermNode, PermRole, PermAccountRole, PermRoleNode, PermDataPolicy, FieldScope,
|
||||
DictType, DictItem,
|
||||
Project, ProjectMember, ProjectVisibleRole, ProjectStageLog, Attachment, SystemConfig,
|
||||
ProjectMilestone, WbsTask, ProjectStageEvent,
|
||||
Revision, CalcSnapshot,
|
||||
EstimateIncomeLine, EstimateCostLine, EstimateOtherLine,
|
||||
BudgetIncomeLine, BudgetIncomePlanLine, BudgetPurchaseLine, BudgetPayPlanLine,
|
||||
BudgetManageLine, BudgetFundMonth, BudgetOtherCostLine,
|
||||
ApprovalFlow, ApprovalNode, ApprovalInstance, ApprovalTask, ApprovalRecord, ApprovalDelegate,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"Base", "ALL_MODELS", "Status", "AccountSource", "OrgUnit", "Position", "Account",
|
||||
"AccountIdentity", "HubSyncRun", "SsoHandoff", "LoginLog", "OperationLog",
|
||||
"PermKind", "PermNode", "PermRole", "PermAccountRole", "PermRoleNode", "PermDataPolicy",
|
||||
"FieldScope", "ScopeType", "SubjectType", "Effect", "FALLBACK_SCOPE",
|
||||
"DictType", "DictItem", "DictSource", "DictValueType",
|
||||
"ProjectType", "ProjectStage", "UnderwrittenMode", "Project", "ProjectMember",
|
||||
"ProjectMemberRole", "ProjectVisibleRole", "ProjectStageLog", "Attachment", "SystemConfig",
|
||||
"Certainty", "YesNo", "IndustryScene", "SaleStage", "ProjectSource",
|
||||
"ProjectMilestone", "MilestoneStatus", "WbsTask", "WbsTaskStatus", "ProjectStageEvent",
|
||||
"Revision", "RevisionModule", "RevisionStatus", "CalcSnapshot",
|
||||
"IncomeType", "PurchaseType", "CostFeeGroup", "CostType", "EstimateManageType",
|
||||
"ManageItemCode", "ProductCategory", "OtherCostBucket", "EstimateIncomeLine", "EstimateCostLine", "EstimateOtherLine",
|
||||
"BudgetIncomeLine", "BudgetIncomePlanLine", "BudgetPurchaseLine", "BudgetPayPlanLine",
|
||||
"BudgetManageLine", "BudgetFundMonth", "BudgetOtherCostLine",
|
||||
"BusinessModule", "NodeType", "SignType", "CandidateType", "FlowStatus", "InstanceStatus",
|
||||
"Action", "TaskStatus", "ApprovalFlow", "ApprovalNode", "ApprovalInstance", "ApprovalTask",
|
||||
"ApprovalRecord", "ApprovalDelegate", "money", "percent", "to_decimal",
|
||||
]
|
||||
|
|
@ -0,0 +1,351 @@
|
|||
"""审批流程。
|
||||
|
||||
替换掉 Activiti 6。理由写在 docs/审批流程设计.md,一句话概括:老系统里 BPMN 图
|
||||
(activiti-editor 那一万多个静态文件)和 ``act_task_def`` 表其实是两套并行的节点定义,
|
||||
真正决定审批人的是后者(``candidate_users`` / ``candidate_roles`` / ``candidate_types``
|
||||
三个逗号分隔的 varchar(4000)),图只用来画着看。既然图不产生行为,就把它去掉,把
|
||||
节点定义做成一张正经的、能在界面上配的配置表。
|
||||
|
||||
保留的老语义:或签(单实例)、会签(多实例)、退回指定节点、审批意见、会签单附件、
|
||||
按角色/按人员/按类型找候选人。新增:条件分支、依次审批、加签、转办、委托、抄送、
|
||||
超时提醒、同一审批人自动跳过。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import ForeignKey, Index, Integer, String, Text, UniqueConstraint, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from .base import Base, SoftDeleteMixin, TimestampMixin, timestamp_col, u_bigint, u_tinyint
|
||||
|
||||
|
||||
class BusinessModule:
|
||||
"""可走审批的业务对象。"""
|
||||
|
||||
ESTIMATE = "estimate" # 项目立项(概算)
|
||||
BUDGET = "budget" # 项目预算
|
||||
SETTLEMENT = "settlement" # 结算
|
||||
FINAL = "final" # 决算
|
||||
SALE_CONTRACT = "sale_contract"
|
||||
PURCHASE_CONTRACT = "purchase_contract"
|
||||
|
||||
LABELS = {
|
||||
ESTIMATE: "项目立项(概算)", BUDGET: "项目预算", SETTLEMENT: "月度结算",
|
||||
FINAL: "项目决算", SALE_CONTRACT: "销售合同", PURCHASE_CONTRACT: "业务采购合同",
|
||||
}
|
||||
|
||||
|
||||
class NodeType:
|
||||
START = "start" # 发起
|
||||
APPROVE = "approve" # 审批
|
||||
CC = "cc" # 抄送(不阻塞)
|
||||
CONDITION = "condition" # 条件分支(自动判定,不产生待办)
|
||||
END = "end"
|
||||
|
||||
LABELS = {START: "发起", APPROVE: "审批", CC: "抄送",
|
||||
CONDITION: "条件分支", END: "结束"}
|
||||
|
||||
|
||||
class SignType:
|
||||
"""多人节点的空签方式。老系统 ``act_task_def.task_type`` 0/1 对应前两种。"""
|
||||
|
||||
ANY = "any" # 或签:任一人处理即通过
|
||||
ALL = "all" # 会签:全部通过才通过
|
||||
ORDER = "order" # 依次审批:按候选人顺序,任一人驳回即驳回
|
||||
|
||||
LABELS = {ANY: "或签(任一人)", ALL: "会签(全部)", ORDER: "依次审批"}
|
||||
|
||||
|
||||
class CandidateType:
|
||||
"""候选人来源。对应老 ``candidate_types``,但拆成结构化配置。"""
|
||||
|
||||
FIXED = "fixed" # 固定人员
|
||||
ROLE = "role" # 角色下的所有人
|
||||
POSITION = "position" # 岗位下的所有人
|
||||
ORG_MANAGER = "org_manager" # 发起人所在部门负责人
|
||||
ORG_MANAGER_CHAIN = "org_manager_chain" # 沿组织树向上 N 级
|
||||
DIRECT_LEADER = "direct_leader" # 发起人直属上级
|
||||
PROJECT_OWNER = "project_owner" # 项目负责人
|
||||
PREVIOUS_ASSIGNEE = "previous" # 上一节点的实际审批人
|
||||
FORM_FIELD = "form_field" # 从送审数据里取某个字段
|
||||
EXPRESSION = "expression" # 表达式(受控白名单,见 service/approval/resolve.py)
|
||||
|
||||
ALL = (FIXED, ROLE, POSITION, ORG_MANAGER, ORG_MANAGER_CHAIN, DIRECT_LEADER,
|
||||
PROJECT_OWNER, PREVIOUS_ASSIGNEE, FORM_FIELD, EXPRESSION)
|
||||
|
||||
LABELS = {
|
||||
FIXED: "指定人员", ROLE: "按角色", POSITION: "按岗位",
|
||||
ORG_MANAGER: "本部门负责人", ORG_MANAGER_CHAIN: "逐级向上负责人",
|
||||
DIRECT_LEADER: "直属上级", PROJECT_OWNER: "项目负责人",
|
||||
PREVIOUS_ASSIGNEE: "上一节点审批人", FORM_FIELD: "表单字段", EXPRESSION: "表达式",
|
||||
}
|
||||
|
||||
|
||||
class FlowStatus:
|
||||
DRAFT = "draft"
|
||||
PUBLISHED = "published"
|
||||
OFFLINE = "offline"
|
||||
|
||||
LABELS = {DRAFT: "草稿", PUBLISHED: "已发布", OFFLINE: "已下线"}
|
||||
|
||||
|
||||
class InstanceStatus:
|
||||
REVIEWING = "reviewing"
|
||||
APPROVED = "approved"
|
||||
REJECTED = "rejected"
|
||||
WITHDRAWN = "withdrawn"
|
||||
CANCELED = "canceled"
|
||||
|
||||
LABELS = {REVIEWING: "审批中", APPROVED: "已通过", REJECTED: "已驳回",
|
||||
WITHDRAWN: "已撤回", CANCELED: "已作废"}
|
||||
|
||||
|
||||
class Action:
|
||||
"""审批动作。对应老 ``project_task_record.task_status`` 0/1/2。"""
|
||||
|
||||
SUBMIT = "submit"
|
||||
APPROVE = "approve"
|
||||
REJECT = "reject"
|
||||
ROLLBACK = "rollback" # 退回指定节点
|
||||
WITHDRAW = "withdraw"
|
||||
TRANSFER = "transfer" # 转办
|
||||
ADD_SIGN = "add_sign" # 加签
|
||||
CC = "cc"
|
||||
REMIND = "remind"
|
||||
AUTO_SKIP = "auto_skip" # 同一审批人自动跳过
|
||||
TIMEOUT = "timeout"
|
||||
|
||||
LABELS = {
|
||||
SUBMIT: "提交审批", APPROVE: "审批通过", REJECT: "审批不通过", ROLLBACK: "退回修改",
|
||||
WITHDRAW: "撤回", TRANSFER: "转办", ADD_SIGN: "加签", CC: "抄送", REMIND: "催办",
|
||||
AUTO_SKIP: "自动跳过", TIMEOUT: "超时处理",
|
||||
}
|
||||
|
||||
|
||||
class TaskStatus:
|
||||
PENDING = "pending"
|
||||
DONE = "done"
|
||||
SKIPPED = "skipped"
|
||||
TRANSFERRED = "transferred"
|
||||
CANCELED = "canceled"
|
||||
|
||||
LABELS = {
|
||||
PENDING: "待办理",
|
||||
DONE: "已办理",
|
||||
SKIPPED: "自动跳过",
|
||||
TRANSFERRED: "已转办",
|
||||
CANCELED: "已作废",
|
||||
}
|
||||
|
||||
|
||||
class ApprovalFlow(Base, TimestampMixin, SoftDeleteMixin):
|
||||
"""流程定义。
|
||||
|
||||
一个业务模块可以按项目类型、金额区间配多条流程,匹配规则见
|
||||
:func:`app.service.approval.flow.match_flow`:先按 ``business_module``,再用
|
||||
``match_json`` 里的条件(项目类型、金额阈值、垫资模式…)挑最具体的一条。
|
||||
"""
|
||||
|
||||
__tablename__ = "approval_flow"
|
||||
__table_args__ = (
|
||||
Index("idx_approval_flow_module", "business_module", "status"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
key: Mapped[str] = mapped_column(String(64), nullable=False, comment="流程标识")
|
||||
name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
business_module: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
version: Mapped[int] = mapped_column(Integer, default=1, server_default="1", nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(16), default=FlowStatus.DRAFT, nullable=False)
|
||||
# 匹配条件(项目类型/金额区间/垫资模式等),空表示默认流程
|
||||
match_json: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||
# 同一模块多条已发布流程时的先后,数字小者优先
|
||||
priority: Mapped[int] = mapped_column(Integer, default=100, server_default="100", nullable=False)
|
||||
# 允许发起人自选首个节点审批人
|
||||
allow_self_select: Mapped[bool] = mapped_column(u_tinyint(), default=False, server_default="0", nullable=False)
|
||||
# 同一审批人连续出现时自动通过(老系统没有,实际业务几乎总要)
|
||||
auto_skip_duplicate: Mapped[bool] = mapped_column(u_tinyint(), default=True, server_default="1", nullable=False)
|
||||
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False)
|
||||
|
||||
nodes: Mapped[list["ApprovalNode"]] = relationship(
|
||||
back_populates="flow", cascade="all, delete-orphan", order_by="ApprovalNode.order_number",
|
||||
lazy="selectin",
|
||||
)
|
||||
|
||||
|
||||
class ApprovalNode(Base, SoftDeleteMixin):
|
||||
"""流程节点。"""
|
||||
|
||||
__tablename__ = "approval_node"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("flow_id", "node_key", name="uk_approval_node_key"),
|
||||
Index("idx_approval_node_flow", "flow_id", "order_number"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
flow_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("approval_flow.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
node_key: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
node_type: Mapped[str] = mapped_column(String(16), default=NodeType.APPROVE, nullable=False)
|
||||
order_number: Mapped[int] = mapped_column(Integer, default=100, server_default="100", nullable=False)
|
||||
sign_type: Mapped[str] = mapped_column(String(16), default=SignType.ANY, nullable=False)
|
||||
# 候选人配置:[{"type":"role","ids":[3]},{"type":"org_manager"}]
|
||||
candidates_json: Mapped[str] = mapped_column(Text, default="[]", nullable=False)
|
||||
# 找不到候选人时的兜底:error(报错阻塞)/ skip(跳过节点)/ admin(转给系统管理员)
|
||||
empty_strategy: Mapped[str] = mapped_column(String(16), default="admin", server_default="admin", nullable=False)
|
||||
# 条件分支:满足才进入本节点,空表示无条件
|
||||
condition_json: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||
# 通过后去向:next(默认下一个 order)或指定 node_key
|
||||
next_node_key: Mapped[str] = mapped_column(String(64), default="", nullable=False)
|
||||
# 驳回后的去向:end(直接结束为驳回)/ initiator(退回发起人在本节点重提)/ 指定 node_key
|
||||
reject_to: Mapped[str] = mapped_column(String(64), default="end", nullable=False)
|
||||
# 允许退回到的节点集合,空表示允许退回发起人
|
||||
rollback_keys_json: Mapped[str] = mapped_column(Text, default="[]", nullable=False)
|
||||
# 审批意见是否必填;驳回时是否必填
|
||||
comment_required: Mapped[bool] = mapped_column(u_tinyint(), default=False, server_default="0", nullable=False)
|
||||
reject_comment_required: Mapped[bool] = mapped_column(u_tinyint(), default=True, server_default="1", nullable=False)
|
||||
# 限时(小时),0 表示不限;超时触发 remind / auto_approve / none
|
||||
timeout_hours: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
|
||||
timeout_action: Mapped[str] = mapped_column(String(16), default="none", server_default="none", nullable=False)
|
||||
enabled: Mapped[bool] = mapped_column(u_tinyint(), default=True, server_default="1", nullable=False)
|
||||
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False)
|
||||
|
||||
flow: Mapped["ApprovalFlow"] = relationship(back_populates="nodes")
|
||||
|
||||
|
||||
class ApprovalInstance(Base):
|
||||
"""一次审批实例:某个业务对象的某一次送审。
|
||||
|
||||
老系统靠 ``project_instance_relation``( Activiti 流程实例 id 字符串)反向关联,
|
||||
业务侧要显示"当前谁在审"还得去查 ``act_ru_task``。这里直接存业务外键与当前节点,
|
||||
列表页一次查询就够。
|
||||
"""
|
||||
|
||||
__tablename__ = "approval_instance"
|
||||
__table_args__ = (
|
||||
Index("idx_approval_instance_biz", "business_module", "revision_id"),
|
||||
Index("idx_approval_instance_project", "project_id", "status"),
|
||||
Index("idx_approval_instance_submitter", "submitter_id", "status"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
flow_id: Mapped[int] = mapped_column(u_bigint(), nullable=False)
|
||||
flow_key: Mapped[str] = mapped_column(String(64), default="", nullable=False)
|
||||
flow_name: Mapped[str] = mapped_column(String(128), default="", nullable=False)
|
||||
flow_version: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
|
||||
business_module: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
project_id: Mapped[int] = mapped_column(u_bigint(), nullable=False, index=True)
|
||||
project_name: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||
# 送审的业务版本(概算/预算的 revision_id),审批看的就是这一版
|
||||
revision_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True)
|
||||
snapshot_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(16), default=InstanceStatus.REVIEWING, nullable=False)
|
||||
# 当前停留的节点(会签可能有多个待办人,但节点是同一个)
|
||||
current_node_key: Mapped[str] = mapped_column(String(64), default="", nullable=False)
|
||||
current_node_name: Mapped[str] = mapped_column(String(128), default="", nullable=False)
|
||||
submitter_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("accounts.id", ondelete="RESTRICT"), nullable=False)
|
||||
submitter_name: Mapped[str] = mapped_column(String(100), default="", nullable=False)
|
||||
submitter_org_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True)
|
||||
# 送审时冻结的判定数据(金额、项目类型…),流程条件与追溯都读它
|
||||
variables_json: Mapped[str] = mapped_column(Text, default="{}", nullable=False)
|
||||
# 流程走到哪一步的运行时数据(已完成的节点、依次审批游标等)
|
||||
runtime_json: Mapped[str] = mapped_column(Text, default="{}", nullable=False)
|
||||
submitted_at: Mapped[datetime] = mapped_column(
|
||||
timestamp_col(), default=datetime.now, server_default=text("CURRENT_TIMESTAMP(3)"), nullable=False)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True)
|
||||
# 退回后重新提交时指向被退回去的那次实例,保留完整链路
|
||||
previous_instance_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True)
|
||||
|
||||
|
||||
class ApprovalTask(Base):
|
||||
"""待办任务。一个人在某节点上的一个待办。"""
|
||||
|
||||
__tablename__ = "approval_task"
|
||||
__table_args__ = (
|
||||
Index("idx_approval_task_assignee", "assignee_id", "status"),
|
||||
Index("idx_approval_task_instance", "instance_id", "status"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
instance_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("approval_instance.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
node_key: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
node_name: Mapped[str] = mapped_column(String(128), default="", nullable=False)
|
||||
sign_type: Mapped[str] = mapped_column(String(16), default=SignType.ANY, nullable=False)
|
||||
assignee_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("accounts.id", ondelete="RESTRICT"), nullable=False, index=True)
|
||||
assignee_name: Mapped[str] = mapped_column(String(100), default="", nullable=False)
|
||||
# 因为是"委托人"而收到任务的人(转办/委托留痕)
|
||||
origin_assignee_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(16), default=TaskStatus.PENDING, nullable=False)
|
||||
order_in_node: Mapped[int] = mapped_column(Integer, default=100, server_default="100", nullable=False,
|
||||
comment="依次审批时的顺序号")
|
||||
due_at: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True)
|
||||
acted_at: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True)
|
||||
action: Mapped[str] = mapped_column(String(16), default="", nullable=False)
|
||||
comment: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
timestamp_col(), default=datetime.now, server_default=text("CURRENT_TIMESTAMP(3)"), nullable=False)
|
||||
|
||||
|
||||
class ApprovalRecord(Base):
|
||||
"""审批流水(老 ``project_task_record``)。前端"项目审核记录"页签直接读它。"""
|
||||
|
||||
__tablename__ = "approval_record"
|
||||
__table_args__ = (
|
||||
Index("idx_approval_record_instance", "instance_id", "id"),
|
||||
Index("idx_approval_record_project", "project_id", "id"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
instance_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("approval_instance.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
project_id: Mapped[int] = mapped_column(u_bigint(), nullable=False, index=True)
|
||||
business_module: Mapped[str] = mapped_column(String(32), default="", nullable=False)
|
||||
node_key: Mapped[str] = mapped_column(String(64), default="", nullable=False)
|
||||
node_name: Mapped[str] = mapped_column(String(128), default="", nullable=False)
|
||||
action: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
action_label: Mapped[str] = mapped_column(String(32), default="", nullable=False)
|
||||
operator_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True)
|
||||
operator_name: Mapped[str] = mapped_column(String(100), default="", nullable=False)
|
||||
# 被处理人(转办/加签的目标)
|
||||
target_names: Mapped[str] = mapped_column(String(1000), default="", nullable=False)
|
||||
comment: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||
# 退回信息与老表的 rollback_record_id/rollback_desc 对应
|
||||
rollback_to_node: Mapped[str] = mapped_column(String(64), default="", nullable=False)
|
||||
rollback_record_id: Mapped[int] = mapped_column(u_bigint(), default=0, server_default="0", nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
timestamp_col(), default=datetime.now, server_default=text("CURRENT_TIMESTAMP(3)"), nullable=False)
|
||||
|
||||
|
||||
class ApprovalDelegate(Base, TimestampMixin, SoftDeleteMixin):
|
||||
"""委托:某人在一段时间内把待办自动转给他人。"""
|
||||
|
||||
__tablename__ = "approval_delegate"
|
||||
__table_args__ = (
|
||||
Index("idx_approval_delegate_from", "from_id", "enabled"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
from_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("accounts.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
from_name: Mapped[str] = mapped_column(String(100), default="", nullable=False)
|
||||
to_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("accounts.id", ondelete="CASCADE"), nullable=False)
|
||||
to_name: Mapped[str] = mapped_column(String(100), default="", nullable=False)
|
||||
# 只对某些业务模块生效,空表示全部
|
||||
modules_json: Mapped[str] = mapped_column(Text, default="[]", nullable=False)
|
||||
valid_from: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True)
|
||||
valid_to: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True)
|
||||
enabled: Mapped[bool] = mapped_column(u_tinyint(), default=True, server_default="1", nullable=False)
|
||||
reason: Mapped[str] = mapped_column(String(500), default="", nullable=False)
|
||||
|
|
@ -0,0 +1,99 @@
|
|||
"""ORM 基类与几个跨模块复用的小工具。
|
||||
|
||||
列类型工厂集中在这里,是为了让"同一套模型在 MySQL 上拿到最贴合的列类型"这件事只写一次:
|
||||
主键统一无符号 BIGINT、时间统一 DATETIME(3)、金额统一 DECIMAL,避免各模块各写一套
|
||||
导致同一张表在两套代码里对不上。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from decimal import Decimal, InvalidOperation
|
||||
|
||||
from sqlalchemy import BigInteger, Date, DateTime, Numeric, func
|
||||
from sqlalchemy.dialects.mysql import BIGINT, DATETIME, TINYINT
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
"""所有表的基类。"""
|
||||
|
||||
|
||||
def timestamp_col():
|
||||
"""DATETIME(3);非 MySQL 方言退回普通 DATETIME。"""
|
||||
return DateTime().with_variant(DATETIME(fsp=3), "mysql")
|
||||
|
||||
|
||||
def date_col():
|
||||
"""DATE:项目计划起止这类"精确到月/日但没有时刻"的列。"""
|
||||
return Date()
|
||||
|
||||
|
||||
def u_bigint():
|
||||
"""无符号 BIGINT:主键与外键统一用它,避免有符号/无符号混用让索引失效。"""
|
||||
return BigInteger().with_variant(BIGINT(unsigned=True), "mysql")
|
||||
|
||||
|
||||
def u_tinyint():
|
||||
return TINYINT(unsigned=True)
|
||||
|
||||
|
||||
def money(precision: int = 18, scale: int = 4):
|
||||
"""金额列。
|
||||
|
||||
库里保留 4 位小数而不是 2 位:老系统明细单价是 5 位、含税总额是 4 位,只存 2 位
|
||||
会在重算时对不上账。展示层再按 :mod:`app.service.calc` 的口径舍入到 2 位。
|
||||
"""
|
||||
return Numeric(precision, scale)
|
||||
|
||||
|
||||
def percent(scale: int = 6):
|
||||
"""比率列(百分数本身,13 表示 13%)。
|
||||
|
||||
宽度给到 18 而不是 10:比率都是"金额 ÷ 金额 × 100"算出来的,分子分母都是
|
||||
DECIMAL(18,4),分母一小(老库里就有 contract_amount = 1.00 的试算项目)结果就能
|
||||
冲出 ±9999。DECIMAL(10,6) 遇到这种值不是报错就是截断——重算写入时抛 1264,
|
||||
导数时整条项目插不进去。列宽换 4 个字节,比丢数或炸库便宜。
|
||||
"""
|
||||
return Numeric(18, scale)
|
||||
|
||||
|
||||
class TimestampMixin:
|
||||
"""创建/更新时间,交给数据库兜底,避免应用时钟不一致。"""
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
timestamp_col(),
|
||||
default=datetime.now,
|
||||
server_default=func.current_timestamp(3),
|
||||
nullable=False,
|
||||
comment="创建时间",
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
timestamp_col(),
|
||||
default=datetime.now,
|
||||
onupdate=datetime.now,
|
||||
server_default=func.current_timestamp(3),
|
||||
nullable=False,
|
||||
comment="最后更新时间",
|
||||
)
|
||||
|
||||
|
||||
class SoftDeleteMixin:
|
||||
"""软删除。老系统几乎每张表都有 is_deleted,这里统一成一个布尔位。"""
|
||||
|
||||
is_deleted: Mapped[bool] = mapped_column(
|
||||
u_tinyint(), default=False, server_default="0", nullable=False, index=True,
|
||||
comment="软删除 0=有效 1=已删除",
|
||||
)
|
||||
|
||||
|
||||
def to_decimal(value: object) -> Decimal:
|
||||
"""把数据库/JSON 回来的杂七杂八类型折成 Decimal,None 视作 0。"""
|
||||
if value is None or value == "":
|
||||
return Decimal("0")
|
||||
if isinstance(value, Decimal):
|
||||
return value
|
||||
try:
|
||||
return Decimal(str(value))
|
||||
except (InvalidOperation, ValueError):
|
||||
return Decimal("0")
|
||||
|
|
@ -0,0 +1,103 @@
|
|||
"""数据字典:下拉框取值的唯一存放处。
|
||||
|
||||
系统里的下拉框原本分三处写死:model 里的 ``LABELS``、API 里临时拼的
|
||||
``[{"value": …, "label": …}]``、前端视图里的常量数组。三处各写一份的结局是
|
||||
对不上——项目类型在 model 里是"工程集成类/设备集成类/战略合作类",前端列表页
|
||||
自己抄成了"系统集成/软件开发/运维服务",谁都没报错,只是两边各说各话。
|
||||
|
||||
这一张表把取值收到库里,界面上(系统 → 数据字典)就能改:
|
||||
|
||||
* **``source=system``(代码字典)**:取值来自 :mod:`app.dicts` 里的代码枚举,
|
||||
启动时同步进来。业务代码按 ``value`` 判分支,所以 **value 与 code 不许改**,
|
||||
能改的只有显示名、排序、启停、配色;删掉的条目相当于隐藏,代码读到未知值仍会
|
||||
退回代码里的名字,不会渲染成空白。
|
||||
* **``source=custom``(自建字典)**:完全由界面维护,随便加删。新增一个"客户等级"
|
||||
这类下拉框不必再发版。
|
||||
|
||||
字典是**展示与候选项**的事实来源,不是**校验**的事实来源:能不能送审、走哪条分支
|
||||
仍然看代码里的常量,否则改个名字就能把状态机改出洞。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import ForeignKey, Index, Integer, String, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from .base import Base, SoftDeleteMixin, TimestampMixin, u_bigint, u_tinyint
|
||||
|
||||
|
||||
class DictSource:
|
||||
"""字典来源。"""
|
||||
|
||||
SYSTEM = "system" # 代码枚举同步进来的,value 不可改
|
||||
CUSTOM = "custom" # 界面上自建的
|
||||
|
||||
LABELS = {SYSTEM: "代码内置", CUSTOM: "自定义"}
|
||||
|
||||
|
||||
class DictValueType:
|
||||
"""``value`` 列的存储类型。
|
||||
|
||||
取值一律存字符串,读的时候按这个键还原成 int——项目阶段、账号状态这些列在库里
|
||||
是数字,前端 Select 也是按数字比对的,混成字符串会出现"选了但选不上"的毛病。
|
||||
"""
|
||||
|
||||
STRING = "string"
|
||||
INT = "int"
|
||||
|
||||
LABELS = {STRING: "文本", INT: "整数"}
|
||||
|
||||
|
||||
class DictType(Base, TimestampMixin, SoftDeleteMixin):
|
||||
"""字典类型:一个下拉框对应一条。"""
|
||||
|
||||
__tablename__ = "dict_type"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("code", name="uk_dict_type_code"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
code: Mapped[str] = mapped_column(
|
||||
String(64), nullable=False, comment="字典编码,前后端按它取值(camelCase)")
|
||||
name: Mapped[str] = mapped_column(String(128), nullable=False, comment="显示名称")
|
||||
group: Mapped[str] = mapped_column(String(64), default="common", server_default="common",
|
||||
nullable=False, index=True, comment="维护页里的分组")
|
||||
value_type: Mapped[str] = mapped_column(
|
||||
String(8), default=DictValueType.STRING, server_default=DictValueType.STRING,
|
||||
nullable=False, comment="取值类型 string/int,决定下发时要不要转成数字")
|
||||
source: Mapped[str] = mapped_column(
|
||||
String(16), default=DictSource.CUSTOM, server_default=DictSource.CUSTOM, nullable=False,
|
||||
comment="system=代码枚举同步,value 不可改;custom=界面自建")
|
||||
enabled: Mapped[bool] = mapped_column(u_tinyint(), default=True, server_default="1",
|
||||
nullable=False, comment="停用后下拉框取到空列表")
|
||||
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False)
|
||||
|
||||
|
||||
class DictItem(Base, TimestampMixin, SoftDeleteMixin):
|
||||
"""字典条目:下拉框里的一个选项。"""
|
||||
|
||||
__tablename__ = "dict_item"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("dict_type_id", "value", name="uk_dict_item_type_value"),
|
||||
Index("idx_dict_item_type_sort", "dict_type_id", "sort"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
dict_type_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("dict_type.id", ondelete="CASCADE"), nullable=False,
|
||||
comment="所属字典类型")
|
||||
value: Mapped[str] = mapped_column(String(128), nullable=False, comment="存给后端的值")
|
||||
label: Mapped[str] = mapped_column(String(128), nullable=False, comment="给人看的名字")
|
||||
sort: Mapped[int] = mapped_column(Integer, default=100, server_default="100", nullable=False,
|
||||
comment="越小越靠前")
|
||||
enabled: Mapped[bool] = mapped_column(u_tinyint(), default=True, server_default="1",
|
||||
nullable=False, comment="停用即从下拉框里摘掉,历史数据不受影响")
|
||||
tag: Mapped[str] = mapped_column(
|
||||
String(16), default="", server_default="", nullable=False,
|
||||
comment="状态色(success/warning/danger/info/gray),给 StatusBadge 用")
|
||||
builtin: Mapped[bool] = mapped_column(u_tinyint(), default=False, server_default="0",
|
||||
nullable=False, comment="代码枚举同步来的条目,value 不可改")
|
||||
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False,
|
||||
comment="备注,界面上以下拉提示语展示")
|
||||
|
|
@ -0,0 +1,548 @@
|
|||
"""概算、预算与它们的版本(草稿/送审/批准)。
|
||||
|
||||
对应重构范围内的两个模块:**项目立项(概算)信息** 与 **项目预算信息**。
|
||||
|
||||
为什么要引入 Revision
|
||||
=====================
|
||||
|
||||
老系统给每张预算明细表都配了一份 ``*_temp`` 影子表(收入、采购、收款计划、付款计划、
|
||||
项目管理、资金计划六对十二张表),"草稿"就是写 temp,"提交"就是整表搬到正式表。
|
||||
于是任何一次读取都要先判断"这个用户在读草稿还是读正式版",跨表统计(利润、资金计划)
|
||||
在两套表上算出来的结果还不一样。
|
||||
|
||||
这里改成一张 ``biz_revision``:一个版本一行,明细行用 ``revision_id`` 挂过去。
|
||||
好处是草稿与正式版走完全相同的查询与计算代码,只是 ``status`` 不同;也天然支持
|
||||
"驳回后改出新版本、老版本仍可追溯"。
|
||||
|
||||
计算快照
|
||||
========
|
||||
|
||||
``TO-BE-EST-001`` / ``TO-BE-BUD-SSOT-001`` 要求"原始输入 + 计算结果快照 + 规则版本",
|
||||
所以明细行只存人工输入与必要的回退值,所有派生金额(不含税、税额、分类合计、利润、
|
||||
资金计划余额、垫资、还款、利息)一律落在 ``calc_snapshot.payload_json``,并记录
|
||||
``calc_version``。审批看的就是这份快照,事后重算对不上也能立刻发现。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
|
||||
from sqlalchemy import ForeignKey, Index, Integer, String, Text, UniqueConstraint, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from .base import Base, SoftDeleteMixin, date_col, money, percent, timestamp_col, u_bigint, u_tinyint
|
||||
|
||||
|
||||
class IncomeType:
|
||||
"""收入分类(老 ``project_estimate_income.type`` / 明细 type)。"""
|
||||
|
||||
DEVICE = 1 # 设备类
|
||||
ENGINEERING = 2 # 工程类
|
||||
SERVICE = 3 # 服务类
|
||||
|
||||
LABELS = {DEVICE: "设备类", ENGINEERING: "工程类", SERVICE: "服务类"}
|
||||
ALL = (DEVICE, ENGINEERING, SERVICE)
|
||||
|
||||
|
||||
class PurchaseType:
|
||||
"""采购成本分类。"""
|
||||
|
||||
DEVICE = 1 # 设备
|
||||
CONSTRUCTION = 2 # 施工
|
||||
SERVICE = 3 # 服务
|
||||
OTHER = 4 # 其他
|
||||
|
||||
LABELS = {DEVICE: "设备", CONSTRUCTION: "施工", SERVICE: "服务", OTHER: "其他"}
|
||||
ALL = (DEVICE, CONSTRUCTION, SERVICE, OTHER)
|
||||
|
||||
|
||||
class CostFeeGroup:
|
||||
"""成本大类(老 ``project_budget_cost.fee``)。"""
|
||||
|
||||
PURCHASE = 1 # 采购成本
|
||||
PROJECT_MANAGE = 2 # 项目管理成本
|
||||
OTHER = 3 # 其他
|
||||
|
||||
|
||||
class CostType:
|
||||
"""成本汇总行的分类(老 ``project_*_cost.type``,1..6)。"""
|
||||
|
||||
DEVICE = 1
|
||||
CONSTRUCTION = 2
|
||||
SERVICE = 3
|
||||
OTHER = 4
|
||||
PROJECT_MANAGE = 5
|
||||
OTHER_OTHER = 6
|
||||
|
||||
LABELS = {DEVICE: "设备", CONSTRUCTION: "施工", SERVICE: "服务", OTHER: "其他",
|
||||
PROJECT_MANAGE: "项目管理成本", OTHER_OTHER: "其他其他"}
|
||||
|
||||
|
||||
class ProductCategory:
|
||||
"""采购明细的产品归属(BUD-COST-002 的四个桶)。
|
||||
|
||||
这几个编码同时是 :data:`app.service.calc.mapping.PRODUCT_CATEGORY_TO_FIELD` 的键,
|
||||
也就是项目主档上那四列产品金额的归属。前端曾经自己抄过一份
|
||||
(``integration`` / ``other``),后果是选了那两个归属的采购额永远投影不到
|
||||
``project.huazhi_amount`` 这些列上——不报错,只是数对不上。所以取值只认这一份,
|
||||
``tests/test_dict.py`` 里钉了一条"字典与内核映射表取值一致"的断言。
|
||||
"""
|
||||
|
||||
HUIZHI = "huizhi"
|
||||
HUAZHI = "huazhi"
|
||||
H3C = "h3c"
|
||||
ZIGUANG_OTHER = "ziguang_other"
|
||||
|
||||
LABELS = {HUIZHI: "汇智产品", HUAZHI: "华智产品", H3C: "华三产品",
|
||||
ZIGUANG_OTHER: "紫光其他产品"}
|
||||
|
||||
|
||||
class OtherCostBucket:
|
||||
"""概算"管理与财务费用"行属于利润公式的哪一层。
|
||||
|
||||
计算器按 ``bucket`` 取数(见 ``engine.estimate_payload``),列注释里那四个编码
|
||||
就是全部合法值;前端那份多出来的 ``finance_cost`` 谁都不读,选了等于没录。
|
||||
"""
|
||||
|
||||
PROJECT_MANAGE = "project_manage"
|
||||
OTHER_COST = "other_cost"
|
||||
CAPITAL_INTEREST = "capital_interest"
|
||||
COMPANY_MANAGE = "company_manage"
|
||||
|
||||
LABELS = {PROJECT_MANAGE: "项目管理费用", OTHER_COST: "其他成本",
|
||||
CAPITAL_INTEREST: "资金占用成本", COMPANY_MANAGE: "公司管理费用"}
|
||||
|
||||
|
||||
class EstimateManageType:
|
||||
"""概算"管理与财务费用"行的分类(老 ``project_estimate_cost_manage.type``)。"""
|
||||
|
||||
CAPITAL = 1 # 资金占用成本
|
||||
COMPANY_MANAGE = 2 # 公司管理费用
|
||||
|
||||
|
||||
class RevisionStatus:
|
||||
"""版本状态。"""
|
||||
|
||||
DRAFT = "draft"
|
||||
REVIEWING = "reviewing"
|
||||
APPROVED = "approved"
|
||||
REJECTED = "rejected"
|
||||
WITHDRAWN = "withdrawn"
|
||||
|
||||
LABELS = {DRAFT: "草稿", REVIEWING: "审批中", APPROVED: "已通过",
|
||||
REJECTED: "已驳回", WITHDRAWN: "已撤回"}
|
||||
|
||||
#: 可以改明细的状态
|
||||
EDITABLE = (DRAFT, REJECTED, WITHDRAWN)
|
||||
#: 已经生效过、可以当作"上一版"引用的状态
|
||||
EFFECTIVE = (APPROVED,)
|
||||
|
||||
|
||||
class RevisionModule:
|
||||
ESTIMATE = "estimate"
|
||||
BUDGET = "budget"
|
||||
|
||||
|
||||
class Revision(Base, SoftDeleteMixin):
|
||||
"""一次概算/预算的版本(草稿或已送审)。
|
||||
|
||||
``freeze_json`` 是送审那一刻把项目主档与关键指标冻结下来的 JSON。审批人看到的是
|
||||
送审时的口径,即使发起人之后改了项目名也不会跟着变——老系统把五十多列平铺到
|
||||
``project_budget`` 上就是为了这件事,这里用一个 JSON 冻结块顶替那五十多列。
|
||||
"""
|
||||
|
||||
__tablename__ = "biz_revision"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("module", "project_id", "version", name="uk_biz_revision_version"),
|
||||
Index("idx_biz_revision_project", "project_id", "status"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
module: Mapped[str] = mapped_column(String(16), nullable=False, comment="estimate/budget")
|
||||
project_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("project.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
version: Mapped[int] = mapped_column(Integer, default=1, server_default="1", nullable=False)
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(16), default=RevisionStatus.DRAFT, nullable=False, index=True)
|
||||
title: Mapped[str] = mapped_column(String(255), default="", nullable=False, comment="版本说明")
|
||||
# 从哪一版派生出来的(驳回后改新版用)
|
||||
based_on_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True)
|
||||
snapshot_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True, comment="最近一次计算快照")
|
||||
calc_version: Mapped[str] = mapped_column(String(32), default="", nullable=False)
|
||||
freeze_json: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||
creator_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("accounts.id", ondelete="RESTRICT"), nullable=False)
|
||||
creator_name: Mapped[str] = mapped_column(String(100), default="", nullable=False)
|
||||
submitted_at: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True)
|
||||
decided_at: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True)
|
||||
# 表头:老系统把"合同名称""解决方案协同""收入/采购明细附件"平铺在 project_budget 上,
|
||||
# 这些既不是明细行也不该进冻结块(冻结块是送审那一刻的口径,表头是录入过程中的草稿),
|
||||
# 所以单独一个 JSON 列,随版本走。
|
||||
# 用 VARCHAR(2000) 而不是 Text:MySQL 不给 TEXT 列在 ALTER 时带默认值
|
||||
# (1101 BLOB/TEXT can't have a default value),而开发档启动是"补列"式的,
|
||||
# 用 Text 会让老库升不上来。表头就几个名字与一个协同标记,两千字够用。
|
||||
header_json: Mapped[str] = mapped_column(String(2000), default="", server_default="",
|
||||
nullable=False,
|
||||
comment="表头字段 JSON:合同名称、解决方案协同、附件名")
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
timestamp_col(), default=datetime.now, server_default=text("CURRENT_TIMESTAMP(3)"), nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
timestamp_col(), default=datetime.now, onupdate=datetime.now,
|
||||
server_default=text("CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)"), nullable=False)
|
||||
|
||||
|
||||
class CalcSnapshot(Base):
|
||||
"""一次计算的完整结果。审批、导出、对账都读它,不再各自算第二遍。"""
|
||||
|
||||
__tablename__ = "calc_snapshot"
|
||||
__table_args__ = (
|
||||
Index("idx_calc_snapshot_revision", "module", "revision_id", "id"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
module: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
project_id: Mapped[int] = mapped_column(u_bigint(), nullable=False, index=True)
|
||||
revision_id: Mapped[int] = mapped_column(u_bigint(), nullable=False, index=True)
|
||||
calc_version: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
# 触发来源:edit(改明细)/ preview(前端预览)/ submit(送审)/ approval(审批落库)
|
||||
trigger: Mapped[str] = mapped_column(String(16), default="edit", nullable=False)
|
||||
payload_json: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
# 校验结果(限额、勾稽)也一起存,审批人要看得到当时的告警
|
||||
validation_json: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||
account_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True)
|
||||
account_name: Mapped[str] = mapped_column(String(100), default="", nullable=False)
|
||||
trace_id: Mapped[str] = mapped_column(String(64), default="", nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
timestamp_col(), default=datetime.now, server_default=text("CURRENT_TIMESTAMP(3)"), nullable=False)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 概算:明细行
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class EstimateIncomeLine(Base):
|
||||
"""概算收入行。老概算只存分类汇总(一类一行),这里存到明细,满足 TO-BE-EST-001。"""
|
||||
|
||||
__tablename__ = "estimate_income_line"
|
||||
__table_args__ = (
|
||||
Index("idx_estimate_income_revision", "revision_id", "income_type"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
revision_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("biz_revision.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
project_id: Mapped[int] = mapped_column(u_bigint(), nullable=False, index=True)
|
||||
income_type: Mapped[int] = mapped_column(Integer, nullable=False, comment="1设备 2工程 3服务")
|
||||
name: Mapped[str] = mapped_column(String(255), default="", nullable=False, comment="收入项名称")
|
||||
# 人工输入:含税金额(或 数量×单价 二选一,允许只填含税总额)
|
||||
include_amount: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False,
|
||||
comment="含税金额")
|
||||
tax_rate: Mapped[Decimal] = mapped_column(percent(), default=Decimal("0"), nullable=False,
|
||||
comment="税率百分数,13 表示 13%")
|
||||
qty: Mapped[Decimal] = mapped_column(money(18, 4), default=Decimal("0"), nullable=False)
|
||||
unit_price: Mapped[Decimal] = mapped_column(money(20, 5), default=Decimal("0"), nullable=False)
|
||||
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False)
|
||||
sort: Mapped[int] = mapped_column(Integer, default=100, server_default="100", nullable=False)
|
||||
|
||||
|
||||
class EstimateCostLine(Base):
|
||||
"""概算采购成本行。"""
|
||||
|
||||
__tablename__ = "estimate_cost_line"
|
||||
__table_args__ = (
|
||||
Index("idx_estimate_cost_revision", "revision_id", "purchase_type"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
revision_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("biz_revision.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
project_id: Mapped[int] = mapped_column(u_bigint(), nullable=False, index=True)
|
||||
purchase_type: Mapped[int] = mapped_column(Integer, nullable=False, comment="1设备 2施工 3服务 4其他")
|
||||
name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
|
||||
include_amount: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False)
|
||||
tax_rate: Mapped[Decimal] = mapped_column(percent(), default=Decimal("0"), nullable=False)
|
||||
qty: Mapped[Decimal] = mapped_column(money(18, 4), default=Decimal("0"), nullable=False)
|
||||
unit_price: Mapped[Decimal] = mapped_column(money(20, 5), default=Decimal("0"), nullable=False)
|
||||
# 产品归属,用于汇智/华智/华三/紫光其他四项的聚合(BUD-COST-002)
|
||||
product_category: Mapped[str] = mapped_column(String(64), default="", nullable=False)
|
||||
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False)
|
||||
sort: Mapped[int] = mapped_column(Integer, default=100, server_default="100", nullable=False)
|
||||
|
||||
|
||||
class EstimateOtherLine(Base):
|
||||
"""概算的"其他成本 / 项目管理费用 / 资金占用 / 公司管理费用"行。
|
||||
|
||||
老系统把这几项散在 ``project_estimate_cost_manage``(只有两类)与项目管理成本表里,
|
||||
利润公式里到底是哪几项参与全靠读 getter 猜。这里显式一张表,用 ``bucket`` 说明它
|
||||
属于利润公式的哪一层,计算器照 bucket 取数,不再猜。
|
||||
"""
|
||||
|
||||
__tablename__ = "estimate_other_line"
|
||||
__table_args__ = (
|
||||
Index("idx_estimate_other_revision", "revision_id", "bucket"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
revision_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("biz_revision.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
project_id: Mapped[int] = mapped_column(u_bigint(), nullable=False, index=True)
|
||||
bucket: Mapped[str] = mapped_column(
|
||||
String(32), nullable=False,
|
||||
comment="other_cost/project_manage/capital_interest/company_manage")
|
||||
name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
|
||||
exclude_amount: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False,
|
||||
comment="不含税金额")
|
||||
manual: Mapped[bool] = mapped_column(u_tinyint(), default=True, server_default="1", nullable=False,
|
||||
comment="人工估算还是系统派生(TO-BE-EST-001)")
|
||||
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False)
|
||||
sort: Mapped[int] = mapped_column(Integer, default=100, server_default="100", nullable=False)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 预算:明细行。截图里"项目预算信息"下的八个页签,一一对应下面这些表
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class BudgetIncomeLine(Base):
|
||||
"""收入明细表。"""
|
||||
|
||||
__tablename__ = "budget_income_line"
|
||||
__table_args__ = (
|
||||
Index("idx_budget_income_revision", "revision_id", "income_type"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
revision_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("biz_revision.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
project_id: Mapped[int] = mapped_column(u_bigint(), nullable=False, index=True)
|
||||
income_type: Mapped[int] = mapped_column(Integer, nullable=False, comment="1设备 2工程 3服务")
|
||||
name: Mapped[str] = mapped_column(String(255), default="", nullable=False, comment="产品名称")
|
||||
spec: Mapped[str] = mapped_column(String(255), default="", nullable=False, comment="规格型号")
|
||||
param: Mapped[str] = mapped_column(Text, default="", nullable=False, comment="参数")
|
||||
unit: Mapped[str] = mapped_column(String(64), default="", nullable=False, comment="单位")
|
||||
qty: Mapped[Decimal] = mapped_column(money(18, 4), default=Decimal("0"), nullable=False, comment="数量")
|
||||
unit_price: Mapped[Decimal] = mapped_column(money(20, 5), default=Decimal("0"), nullable=False, comment="单价")
|
||||
# 允许人工直接指定含税总额,且以它为准(TAX-001;DECISION-AMT-001 待业务签字)
|
||||
include_amount: Mapped[Decimal | None] = mapped_column(money(), nullable=True,
|
||||
comment="人工含税总额;为空时用 数量×单价")
|
||||
tax_rate: Mapped[Decimal] = mapped_column(percent(), default=Decimal("0"), nullable=False)
|
||||
expiration_date: Mapped[str] = mapped_column(String(32), default="", nullable=False)
|
||||
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False)
|
||||
sort: Mapped[int] = mapped_column(Integer, default=100, server_default="100", nullable=False)
|
||||
|
||||
|
||||
class BudgetIncomePlanLine(Base):
|
||||
"""收款计划表。"""
|
||||
|
||||
__tablename__ = "budget_income_plan_line"
|
||||
__table_args__ = (
|
||||
Index("idx_budget_income_plan_revision", "revision_id"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
revision_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("biz_revision.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
project_id: Mapped[int] = mapped_column(u_bigint(), nullable=False, index=True)
|
||||
receive_point: Mapped[str] = mapped_column(String(255), default="", nullable=False, comment="收款节点")
|
||||
receive_date: Mapped[date | None] = mapped_column(date_col(), nullable=True, comment="收款时间")
|
||||
amount: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False, comment="收款金额")
|
||||
# 保证金收款参与资金计划(PLAN-001),所以要能标出来
|
||||
is_earnest: Mapped[bool] = mapped_column(u_tinyint(), default=False, server_default="0", nullable=False)
|
||||
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False)
|
||||
sort: Mapped[int] = mapped_column(Integer, default=100, server_default="100", nullable=False)
|
||||
|
||||
|
||||
class BudgetPurchaseLine(Base):
|
||||
"""采购成本明细表。"""
|
||||
|
||||
__tablename__ = "budget_purchase_line"
|
||||
__table_args__ = (
|
||||
Index("idx_budget_purchase_revision", "revision_id", "purchase_type"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
revision_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("biz_revision.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
project_id: Mapped[int] = mapped_column(u_bigint(), nullable=False, index=True)
|
||||
purchase_type: Mapped[int] = mapped_column(Integer, nullable=False, comment="1设备 2施工 3服务 4其他")
|
||||
category: Mapped[str] = mapped_column(String(128), default="", nullable=False, comment="类别")
|
||||
# 产品归属:老代码同时兼容"分类 ID 字符串"和"中文分类名"(BUD-COST-002),
|
||||
# 这里只留编码,中文由字典表给。
|
||||
product_category: Mapped[str] = mapped_column(String(64), default="", nullable=False,
|
||||
comment="汇智/华智/华三/紫光其他的编码")
|
||||
name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
|
||||
unit: Mapped[str] = mapped_column(String(64), default="", nullable=False)
|
||||
qty: Mapped[Decimal] = mapped_column(money(18, 4), default=Decimal("0"), nullable=False)
|
||||
unit_price: Mapped[Decimal] = mapped_column(money(20, 5), default=Decimal("0"), nullable=False)
|
||||
include_amount: Mapped[Decimal | None] = mapped_column(money(), nullable=True)
|
||||
tax_rate: Mapped[Decimal] = mapped_column(percent(), default=Decimal("0"), nullable=False)
|
||||
contract_party: Mapped[str] = mapped_column(String(255), default="", nullable=False, comment="签约方")
|
||||
is_underwritten: Mapped[bool] = mapped_column(u_tinyint(), default=False, server_default="0", nullable=False,
|
||||
comment="是否垫资")
|
||||
underwritten_amount: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False,
|
||||
comment="预估垫资金额")
|
||||
pay_date: Mapped[date | None] = mapped_column(date_col(), nullable=True, comment="支出时间")
|
||||
pay_amount: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False, comment="支出金额")
|
||||
pay_way: Mapped[str] = mapped_column(String(255), default="", nullable=False,
|
||||
comment="付款方式;老库这列塞的是合同付款条款,实测最长 136 字")
|
||||
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False)
|
||||
sort: Mapped[int] = mapped_column(Integer, default=100, server_default="100", nullable=False)
|
||||
|
||||
|
||||
class BudgetPayPlanLine(Base):
|
||||
"""付款计划表。"""
|
||||
|
||||
__tablename__ = "budget_pay_plan_line"
|
||||
__table_args__ = (
|
||||
Index("idx_budget_pay_plan_revision", "revision_id"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
revision_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("biz_revision.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
project_id: Mapped[int] = mapped_column(u_bigint(), nullable=False, index=True)
|
||||
pay_point: Mapped[str] = mapped_column(String(255), default="", nullable=False, comment="付款节点")
|
||||
pay_date: Mapped[date | None] = mapped_column(date_col(), nullable=True)
|
||||
# 采购成本项目:决定这笔付款落到资金计划的哪一列(PLAN-001 / PLAN-VAL-001)
|
||||
purchase_type: Mapped[int | None] = mapped_column(Integer, nullable=True, comment="1设备 2施工 3服务 4其他")
|
||||
amount: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False)
|
||||
supplier: Mapped[str] = mapped_column(String(255), default="", nullable=False, comment="供应商")
|
||||
is_earnest: Mapped[bool] = mapped_column(u_tinyint(), default=False, server_default="0", nullable=False,
|
||||
comment="保证金付款")
|
||||
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False)
|
||||
sort: Mapped[int] = mapped_column(Integer, default=100, server_default="100", nullable=False)
|
||||
|
||||
|
||||
class ManageItemCode:
|
||||
"""项目管理费用里"差旅费/业务费"的稳定编码。
|
||||
|
||||
``BUD-VAL-001`` 的老实现是用 ``type == 2 且 name 为 "4" 或 "5"`` 认这两项费用,
|
||||
页面上加一个选项就会悄悄失效。这里改成稳定编码 + 显式标记 ``counts_to_travel_limit``。
|
||||
"""
|
||||
|
||||
LABOR = "labor" # 人工
|
||||
TRAVEL = "travel" # 人员差旅费(计入 10% 限额)
|
||||
BUSINESS = "business" # 业务费用(计入 10% 限额)
|
||||
BIZ_ACCEPT = "biz_acceptance" # 商务及专项验收费
|
||||
OFFICE = "office" # 办公费用
|
||||
HQ_SUPPORT = "hq_support" # 总部支撑人力费用
|
||||
OTHER = "other"
|
||||
|
||||
TRAVEL_LIMIT_CODES = (TRAVEL, BUSINESS)
|
||||
|
||||
|
||||
class BudgetManageLine(Base):
|
||||
"""项目管理费用表。"""
|
||||
|
||||
__tablename__ = "budget_manage_line"
|
||||
__table_args__ = (
|
||||
Index("idx_budget_manage_revision", "revision_id", "manage_type"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
revision_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("biz_revision.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
project_id: Mapped[int] = mapped_column(u_bigint(), nullable=False, index=True)
|
||||
manage_type: Mapped[int] = mapped_column(Integer, default=1, nullable=False, comment="1人工 2业务费用 3其他")
|
||||
item_code: Mapped[str] = mapped_column(String(64), default=ManageItemCode.OTHER, nullable=False)
|
||||
item_name: Mapped[str] = mapped_column(String(255), default="", nullable=False, comment="名称")
|
||||
detail: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||
unit: Mapped[str] = mapped_column(String(64), default="", nullable=False)
|
||||
# 数量允许小数:RISK-BUD-PM-001 里前端 parseInt 会截断
|
||||
qty: Mapped[Decimal] = mapped_column(money(18, 4), default=Decimal("0"), nullable=False)
|
||||
unit_price: Mapped[Decimal] = mapped_column(money(20, 5), default=Decimal("0"), nullable=False)
|
||||
total: Mapped[Decimal | None] = mapped_column(money(), nullable=True, comment="人工总额;为空用 数量×单价")
|
||||
predict_method: Mapped[str] = mapped_column(String(255), default="", nullable=False, comment="预估计算方法")
|
||||
predict_why: Mapped[str] = mapped_column(String(255), default="", nullable=False, comment="预估依据")
|
||||
pay_date: Mapped[date | None] = mapped_column(date_col(), nullable=True)
|
||||
pay_amount: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False)
|
||||
# 固定项(老系统 fourcal.fixedprojectmanagedetails 配的那批)不可删
|
||||
deletable: Mapped[bool] = mapped_column(u_tinyint(), default=True, server_default="1", nullable=False)
|
||||
counts_to_travel_limit: Mapped[bool] = mapped_column(
|
||||
u_tinyint(), default=False, server_default="0", nullable=False, comment="是否计入差旅/业务费 10% 限额")
|
||||
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False)
|
||||
sort: Mapped[int] = mapped_column(Integer, default=100, server_default="100", nullable=False)
|
||||
|
||||
|
||||
class BudgetFundMonth(Base):
|
||||
"""资金计划表:一个月一行。
|
||||
|
||||
只存人工输入(各类支出、收款、保证金、年利率快照)。总支出、总收入、余额、垫资、
|
||||
还款、利息全部由 :func:`app.service.calc.fund_plan.calculate` 按月份顺序整条重算
|
||||
(``TO-BE-PLAN-001``),根除 ``RISK-PLAN-DERIVED-001``:付款计划一变就整条重算,
|
||||
而不是只覆盖四列。
|
||||
"""
|
||||
|
||||
__tablename__ = "budget_fund_month"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("revision_id", "month", name="uk_budget_fund_month"),
|
||||
Index("idx_budget_fund_month_project", "project_id", "month"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
revision_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("biz_revision.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
project_id: Mapped[int] = mapped_column(u_bigint(), nullable=False, index=True)
|
||||
month: Mapped[str] = mapped_column(String(8), nullable=False, comment="YYYY-MM")
|
||||
|
||||
# --- 人工输入 -------------------------------------------------------------
|
||||
device_cost: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False, comment="设备支出")
|
||||
construction_cost: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False, comment="施工支出")
|
||||
service_cost: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False, comment="服务支出")
|
||||
other_cost: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False, comment="其他支出")
|
||||
manage_cost: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False, comment="项目管理支出")
|
||||
earnest_cost: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False, comment="保证金支出")
|
||||
sale_income: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False, comment="销售收款")
|
||||
earnest_income: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False, comment="保证金收入")
|
||||
interest_rate: Mapped[Decimal] = mapped_column(percent(), default=Decimal("0"), nullable=False,
|
||||
comment="当月使用的年利率快照")
|
||||
opening_balance: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False,
|
||||
comment="期初余额,首月一般为 0")
|
||||
# 该行金额是手工覆盖的还是由付款/收款计划汇总来的
|
||||
manual_override: Mapped[bool] = mapped_column(u_tinyint(), default=False, server_default="0", nullable=False)
|
||||
|
||||
# --- 派生:由计算器写入,禁止其它代码改 -----------------------------------
|
||||
total_cost: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False)
|
||||
total_income: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False)
|
||||
balance: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False, comment="月末资金余额")
|
||||
underwritten_plan: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False, comment="垫资计划")
|
||||
repayment_plan: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False, comment="还款计划")
|
||||
capital_interest: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False, comment="资金利息")
|
||||
calc_version: Mapped[str] = mapped_column(String(32), default="", nullable=False)
|
||||
|
||||
|
||||
class BudgetOtherCostLine(Base):
|
||||
"""其他成本行。
|
||||
|
||||
``BUD-OTHER-001`` 的老实现是"其他成本不在预算明细里,而是去冗余汇总表读 type=6",
|
||||
于是它既不能被编辑也无法追溯。这里给它一张正经的明细表,是否参与毛利由业务口径
|
||||
配置决定(``DECISION-BUD-PROFIT-001``)。
|
||||
"""
|
||||
|
||||
__tablename__ = "budget_other_cost_line"
|
||||
__table_args__ = (
|
||||
Index("idx_budget_other_cost_revision", "revision_id"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
revision_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("biz_revision.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
project_id: Mapped[int] = mapped_column(u_bigint(), nullable=False, index=True)
|
||||
name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
|
||||
exclude_amount: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False)
|
||||
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False)
|
||||
sort: Mapped[int] = mapped_column(Integer, default=100, server_default="100", nullable=False)
|
||||
|
|
@ -0,0 +1,392 @@
|
|||
"""组织架构与系统账号。
|
||||
|
||||
口径与 unisoa 的「账户、组织同步与统一身份验证」保持一致,这样同一套 Hub 导出接口
|
||||
两个系统都能吃:
|
||||
|
||||
* ``OrgUnit.hub_org_id`` / ``Account.hub_user_id`` 是"这条记录是不是统一身份的、
|
||||
是其中哪一个"的唯一依据,本地自建的一律为 NULL;
|
||||
* ``Account.source`` 区分本地账号与同步账号,**同步永远不碰本地账号**,避免夜间同步
|
||||
把管理员改掉;
|
||||
* 部门负责人存人员主键而不是名字或 DN:组织同步会改名、挪部门,而"谁是这个部门的
|
||||
负责人"要跟着人走,解析审批人时再换成对方当前身份。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import ForeignKey, Index, Integer, String, Text, UniqueConstraint, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from .base import Base, SoftDeleteMixin, TimestampMixin, timestamp_col, u_bigint, u_tinyint
|
||||
|
||||
|
||||
class Status:
|
||||
"""组织与账号共用的状态口径,和 Hub 导出的 status 同一套数字。
|
||||
|
||||
``1`` 是启用,其余值(停用/待审核/已拒绝)本地一律按不可用处理,读代码时不用换算。
|
||||
"""
|
||||
|
||||
DISABLED = 0
|
||||
ACTIVE = 1
|
||||
PENDING = 2
|
||||
REJECTED = 3
|
||||
|
||||
LABELS = {DISABLED: "已停用", ACTIVE: "正常", PENDING: "待审核", REJECTED: "已拒绝"}
|
||||
|
||||
@classmethod
|
||||
def label(cls, value: object) -> str:
|
||||
return cls.LABELS.get(int(value or 0), "未知")
|
||||
|
||||
@classmethod
|
||||
def is_active(cls, value: object) -> bool:
|
||||
return int(value or 0) == cls.ACTIVE
|
||||
|
||||
@classmethod
|
||||
def normalize(cls, value: object) -> int:
|
||||
"""外部(Hub)状态折成本地取值:只认 1=启用,其余一律停用。"""
|
||||
return cls.ACTIVE if int(value or 0) == cls.ACTIVE else cls.DISABLED
|
||||
|
||||
|
||||
class AccountSource:
|
||||
"""``accounts.source``:账号是谁建的,决定同步能不能动它。"""
|
||||
|
||||
LOCAL = "local"
|
||||
HUB = "hub"
|
||||
|
||||
LABELS = {LOCAL: "本地", HUB: "统一身份"}
|
||||
|
||||
@classmethod
|
||||
def label(cls, value: str) -> str:
|
||||
return cls.LABELS.get(value or cls.LOCAL, value or cls.LOCAL)
|
||||
|
||||
|
||||
class OrgUnit(Base, TimestampMixin, SoftDeleteMixin):
|
||||
"""组织/部门树。
|
||||
|
||||
``path`` 存的是 ``/1/5/23/`` 这样的祖先链,数据权限里"本部门及下级"就靠它做前缀
|
||||
匹配,比递归查询快得多;``level`` 与 ``order_number`` 供左树右表的排序与缩进用。
|
||||
"""
|
||||
|
||||
__tablename__ = "org_unit"
|
||||
__table_args__ = (
|
||||
# 一个 Hub 组织只能落地成本地一个部门:撞两个就等于组织树裂开,必须唯一。
|
||||
# NULL 不参与唯一性,所以本地自建部门不受影响。
|
||||
Index("uq_org_unit_hub_org_id", "hub_org_id", unique=True),
|
||||
Index("idx_org_unit_parent", "parent_id"),
|
||||
# path 是 VARCHAR(1024),utf8mb4 下全列索引会超过 3072 字节上限,取前 255 字符
|
||||
Index("idx_org_unit_path", "path", mysql_length=255),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
name: Mapped[str] = mapped_column(String(255), nullable=False, comment="部门名称")
|
||||
code: Mapped[str] = mapped_column(
|
||||
String(190), default="", server_default="", nullable=False, index=True,
|
||||
comment="组织编码(Hub 的 code),本地自建可留空",
|
||||
)
|
||||
short_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
|
||||
parent_id: Mapped[int | None] = mapped_column(
|
||||
u_bigint(), ForeignKey("org_unit.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
# 祖先链,形如 /1/5/;根节点为 /。同步与数据权限都读它。
|
||||
path: Mapped[str] = mapped_column(String(1024), default="/", nullable=False)
|
||||
level: Mapped[int] = mapped_column(Integer, default=1, server_default="1", nullable=False)
|
||||
order_number: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
|
||||
status: Mapped[int] = mapped_column(
|
||||
u_tinyint(), default=Status.ACTIVE, server_default="1", nullable=False,
|
||||
comment="1=正常 0=停用 2=待审核 3=已拒绝",
|
||||
)
|
||||
hub_org_id: Mapped[int | None] = mapped_column(
|
||||
u_bigint(), nullable=True, comment="Hub 组织主键;非空时 Hub 侧接管名称/编码/状态/上级"
|
||||
)
|
||||
# 部门负责人:存人员主键而不是 DN,理由见模块 docstring。不加外键,避免
|
||||
# accounts.org_unit_id 与它形成双向外键环,让建表脚本绕圈子。
|
||||
manager_id: Mapped[int | None] = mapped_column(
|
||||
u_bigint(), nullable=True, index=True, comment="部门负责人的 accounts.id"
|
||||
)
|
||||
# 同步接管范围:Hub 侧只接管这几个键,其余(负责人、排序、说明)永远归本地。
|
||||
synced_at: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True)
|
||||
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False)
|
||||
|
||||
parent: Mapped["OrgUnit | None"] = relationship(
|
||||
"OrgUnit", remote_side=[id], back_populates="children", foreign_keys=[parent_id]
|
||||
)
|
||||
children: Mapped[list["OrgUnit"]] = relationship(
|
||||
"OrgUnit", back_populates="parent", foreign_keys=[parent_id]
|
||||
)
|
||||
|
||||
@property
|
||||
def is_active(self) -> bool:
|
||||
return Status.is_active(self.status)
|
||||
|
||||
@property
|
||||
def is_hub(self) -> bool:
|
||||
return self.hub_org_id is not None
|
||||
|
||||
|
||||
class Position(Base, TimestampMixin, SoftDeleteMixin):
|
||||
"""职位/岗位。
|
||||
|
||||
老系统用 ``sys_role.level``(1 执行董事、2 财务总监…)同时兼职级和审批人来源,
|
||||
一个字段两套语义;这里把岗位拆出来,审批人解析可以用「按岗位找人」。
|
||||
"""
|
||||
|
||||
__tablename__ = "org_position"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("code", name="uk_org_position_code"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
code: Mapped[str] = mapped_column(String(64), nullable=False, comment="岗位编码,流程按它解析审批人")
|
||||
name: Mapped[str] = mapped_column(String(128), nullable=False, comment="岗位名称")
|
||||
rank: Mapped[int] = mapped_column(Integer, default=100, server_default="100", nullable=False,
|
||||
comment="岗位级别,数字越小级别越高,用于『升级到上级审批』")
|
||||
order_number: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
|
||||
enabled: Mapped[bool] = mapped_column(u_tinyint(), default=True, server_default="1", nullable=False)
|
||||
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False)
|
||||
|
||||
|
||||
class Account(Base, SoftDeleteMixin):
|
||||
"""系统账号(登录人)。
|
||||
|
||||
一个自然人只有一条 ``accounts``;他挂在哪个部门、以什么身份审批,走
|
||||
``AccountIdentity``,因为现实中存在"一个人同时在两个部门审批"的情况。
|
||||
"""
|
||||
|
||||
__tablename__ = "accounts"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("account", name="uk_accounts_account"),
|
||||
Index("idx_accounts_email", "email"),
|
||||
Index("idx_accounts_status", "status"),
|
||||
Index("idx_accounts_org", "org_unit_id"),
|
||||
# Hub 的 user_id 是同步账号的唯一身份:账号能被别人注册走、姓名会改,
|
||||
# 只有它从头到尾指向同一个人。
|
||||
Index("uq_accounts_hub_user_id", "hub_user_id", unique=True),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
account: Mapped[str] = mapped_column(String(190), nullable=False, comment="登录账号")
|
||||
password_hash: Mapped[str] = mapped_column(String(255), nullable=False, default="")
|
||||
display_name: Mapped[str] = mapped_column(String(100), default="", server_default="", nullable=False,
|
||||
comment="姓名")
|
||||
emp_code: Mapped[str] = mapped_column(String(64), default="", server_default="", nullable=False,
|
||||
index=True, comment="工号")
|
||||
telephone: Mapped[str] = mapped_column(String(30), default="", server_default="", nullable=False)
|
||||
email: Mapped[str] = mapped_column(String(190), default="", server_default="", nullable=False)
|
||||
avatar_url: Mapped[str] = mapped_column(String(500), default="", server_default="", nullable=False)
|
||||
org_unit_id: Mapped[int | None] = mapped_column(
|
||||
u_bigint(), ForeignKey("org_unit.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
position_id: Mapped[int | None] = mapped_column(
|
||||
u_bigint(), ForeignKey("org_position.id", ondelete="SET NULL"), nullable=True, index=True
|
||||
)
|
||||
# 直属上级:「发起人上级审批」最常用的口径;没设置时解析退回所在部门负责人。
|
||||
leader_id: Mapped[int | None] = mapped_column(
|
||||
u_bigint(), ForeignKey("accounts.id", ondelete="SET NULL"), nullable=True, index=True
|
||||
)
|
||||
# 是否系统管理员:只决定"能不能进系统管理",业务权限一律走角色,不用它开后门。
|
||||
is_system_admin: Mapped[bool] = mapped_column(
|
||||
u_tinyint(), default=False, server_default="0", nullable=False
|
||||
)
|
||||
status: Mapped[int] = mapped_column(
|
||||
u_tinyint(), default=Status.ACTIVE, server_default="1", nullable=False,
|
||||
comment="1=正常 0=停用 2=待审核 3=已拒绝",
|
||||
)
|
||||
# --- 统一身份(Hub)镜像字段:来源、Hub 主键、最后一次同步时间 -------------
|
||||
source: Mapped[str] = mapped_column(
|
||||
String(16), default=AccountSource.LOCAL, server_default=AccountSource.LOCAL, nullable=False,
|
||||
comment="local=本地建号 hub=统一身份同步",
|
||||
)
|
||||
hub_user_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True)
|
||||
hub_synced_at: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True)
|
||||
# 登录安全:连续失败锁号,替代老系统的 login_error_count/locked/locked_date 三兄弟
|
||||
login_failed_count: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
|
||||
locked_until: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True)
|
||||
last_login_at: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True)
|
||||
last_login_ip: Mapped[str] = mapped_column(String(64), default="", nullable=False)
|
||||
password_updated_at: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True)
|
||||
work_location: Mapped[str] = mapped_column(String(255), default="", nullable=False)
|
||||
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False, comment="账号说明")
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
timestamp_col(), default=datetime.now,
|
||||
server_default=text("CURRENT_TIMESTAMP(3)"), nullable=False,
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
timestamp_col(), default=datetime.now, onupdate=datetime.now,
|
||||
server_default=text("CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)"), nullable=False,
|
||||
)
|
||||
|
||||
org_unit: Mapped["OrgUnit | None"] = relationship("OrgUnit", foreign_keys=[org_unit_id])
|
||||
position: Mapped["Position | None"] = relationship("Position", foreign_keys=[position_id])
|
||||
leader: Mapped["Account | None"] = relationship(
|
||||
"Account", remote_side=[id], foreign_keys=[leader_id]
|
||||
)
|
||||
identities: Mapped[list["AccountIdentity"]] = relationship(
|
||||
"AccountIdentity", back_populates="account", cascade="all, delete-orphan"
|
||||
)
|
||||
|
||||
@property
|
||||
def can_login(self) -> bool:
|
||||
return Status.is_active(self.status)
|
||||
|
||||
@property
|
||||
def is_hub(self) -> bool:
|
||||
return self.source == AccountSource.HUB
|
||||
|
||||
@property
|
||||
def org_unit_name(self) -> str:
|
||||
return self.org_unit.name if self.org_unit else ""
|
||||
|
||||
|
||||
class AccountIdentity(Base, TimestampMixin):
|
||||
"""一个人在系统里的"身份":某人以某部门成员的身份参与业务与审批。
|
||||
|
||||
兼岗、跨部门审批、借调都靠它表达。``is_default`` 的那个人是默认身份,用于
|
||||
列表上"所属部门"这一列以及数据权限的默认口径。
|
||||
"""
|
||||
|
||||
__tablename__ = "account_identity"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("account_id", "org_unit_id", name="uk_account_identity"),
|
||||
Index("idx_account_identity_unit", "org_unit_id"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
account_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("accounts.id", ondelete="CASCADE"), nullable=False, index=True
|
||||
)
|
||||
org_unit_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("org_unit.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
position_id: Mapped[int | None] = mapped_column(
|
||||
u_bigint(), ForeignKey("org_position.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
is_default: Mapped[bool] = mapped_column(
|
||||
u_tinyint(), default=False, server_default="0", nullable=False, comment="是否默认身份"
|
||||
)
|
||||
# 主岗/兼岗:数据权限里"本人及下属部门"要区分这两者,兼岗一般不给下级数据。
|
||||
kind: Mapped[str] = mapped_column(
|
||||
String(16), default="primary", server_default="primary", nullable=False,
|
||||
comment="primary=主岗 concurrent=兼岗",
|
||||
)
|
||||
|
||||
account: Mapped["Account"] = relationship("Account", back_populates="identities")
|
||||
org_unit: Mapped["OrgUnit"] = relationship("OrgUnit")
|
||||
|
||||
|
||||
class HubSyncRun(Base):
|
||||
"""一次统一身份同步的流水,界面上的"同步历史"读这张表。"""
|
||||
|
||||
__tablename__ = "hub_sync_run"
|
||||
__table_args__ = (
|
||||
Index("idx_hub_sync_run_started", "started_at"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
trigger: Mapped[str] = mapped_column(String(16), default="manual", nullable=False,
|
||||
comment="manual=手动 scheduled=定时")
|
||||
status: Mapped[str] = mapped_column(String(16), default="running", nullable=False,
|
||||
comment="running/success/partial/failed")
|
||||
started_at: Mapped[datetime] = mapped_column(timestamp_col(), nullable=False)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True)
|
||||
org_total: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
|
||||
org_created: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
|
||||
org_updated: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
|
||||
org_disabled: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
|
||||
account_total: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
|
||||
account_created: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
|
||||
account_updated: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
|
||||
account_disabled: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False)
|
||||
skipped_local: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False,
|
||||
comment="因为是本地账号而没动的条数")
|
||||
# 增量同步后的目录游标。全量那次记的是"拉完再取一次 changes 的 newest_seq",
|
||||
# 之后每次增量只在整批成功时才往前推,中途失败保持原游标重来。
|
||||
cursor_after: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False,
|
||||
comment="本次同步后的目录游标;0=不是增量批次")
|
||||
# 逐步落盘,失败时能看出停在哪一步
|
||||
steps_json: Mapped[str] = mapped_column(Text, default="[]", nullable=False)
|
||||
error: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||
|
||||
|
||||
class LoginLog(Base):
|
||||
"""登录审计。"""
|
||||
|
||||
__tablename__ = "login_log"
|
||||
__table_args__ = (
|
||||
Index("idx_login_log_account", "account", "created_at"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
account: Mapped[str] = mapped_column(String(190), default="", nullable=False)
|
||||
account_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True)
|
||||
success: Mapped[bool] = mapped_column(u_tinyint(), default=False, nullable=False)
|
||||
reason: Mapped[str] = mapped_column(String(255), default="", nullable=False)
|
||||
ip: Mapped[str] = mapped_column(String(64), default="", nullable=False)
|
||||
user_agent: Mapped[str] = mapped_column(String(500), default="", nullable=False)
|
||||
mode: Mapped[str] = mapped_column(String(16), default="password", nullable=False,
|
||||
comment="password=口令 hub=统一身份 sso=免登")
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
timestamp_col(), default=datetime.now, server_default=text("CURRENT_TIMESTAMP(3)"), nullable=False
|
||||
)
|
||||
|
||||
|
||||
class OperationLog(Base):
|
||||
"""写操作审计:谁在什么时候改了哪个对象的哪个字段。"""
|
||||
|
||||
__tablename__ = "operation_log"
|
||||
__table_args__ = (
|
||||
Index("idx_operation_log_object", "object_type", "object_id"),
|
||||
Index("idx_operation_log_created", "created_at"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
account_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True, index=True)
|
||||
account_name: Mapped[str] = mapped_column(String(100), default="", nullable=False)
|
||||
action: Mapped[str] = mapped_column(String(64), nullable=False, comment="create/update/delete/approve…")
|
||||
object_type: Mapped[str] = mapped_column(String(64), default="", nullable=False)
|
||||
object_id: Mapped[str] = mapped_column(String(64), default="", nullable=False)
|
||||
object_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
|
||||
detail_json: Mapped[str] = mapped_column(Text, default="", nullable=False, comment="字段级变更前后值")
|
||||
ip: Mapped[str] = mapped_column(String(64), default="", nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
timestamp_col(), default=datetime.now, server_default=text("CURRENT_TIMESTAMP(3)"), nullable=False
|
||||
)
|
||||
|
||||
|
||||
class SsoHandoff(Base):
|
||||
"""后端免登回调发给浏览器的一次性短码。
|
||||
|
||||
回调(``GET /api/v1/auth/sso/callback``)验完票不能直接把本地令牌拼在 302 的地址上
|
||||
——那等于把会话钥匙写进浏览历史、代理日志和 Referer。于是中间垫一条短码:库里只存
|
||||
它的哈希与"兑换串"的哈希,60 秒失效、只能用一次,兑换还必须配着回调当场下发的
|
||||
HttpOnly Cookie,两半都在别人手里就兑不出会话。口径与 unisoa 的 ``oa_sso_handoff`` 一致。
|
||||
"""
|
||||
|
||||
__tablename__ = "sso_handoff"
|
||||
__table_args__ = (
|
||||
Index("idx_sso_handoff_expires", "expires_at"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
code_hash: Mapped[str] = mapped_column(
|
||||
String(64), nullable=False, unique=True, comment="短码 SHA-256,明文只在 302 的片段里出现过一次"
|
||||
)
|
||||
bind_hash: Mapped[str] = mapped_column(
|
||||
String(64), nullable=False, comment="HttpOnly 兑换串的 SHA-256,缺它这条短码就是废纸"
|
||||
)
|
||||
account_id: Mapped[int] = mapped_column(u_bigint(), nullable=False, comment="验票认出来的本地账号")
|
||||
redirect: Mapped[str] = mapped_column(String(255), default="", nullable=False, comment="免登进去要落到哪一页")
|
||||
detail: Mapped[str] = mapped_column(String(255), default="", nullable=False, comment="写进登录日志的说明")
|
||||
expires_at: Mapped[datetime] = mapped_column(timestamp_col(), nullable=False)
|
||||
used_at: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
timestamp_col(), default=datetime.now, server_default=text("CURRENT_TIMESTAMP(3)"), nullable=False
|
||||
)
|
||||
|
|
@ -0,0 +1,276 @@
|
|||
"""菜单权限、角色权限与数据权限。
|
||||
|
||||
三件事分开建模,是因为它们的变更频率和负责人根本不同:
|
||||
|
||||
* **菜单/操作权限**(``perm_node`` + ``perm_role_node``)决定"能看见哪些菜单、能点哪些按钮、
|
||||
能调哪些接口",一份权限码同时管这三层,避免菜单藏了但接口还通;
|
||||
* **角色**(``perm_role``)是授权的单位,人可以有多个角色,权限取并集;
|
||||
* **数据权限**(``perm_data_policy``)单独一张策略表而不是在角色上挂一个 scope 字段,
|
||||
因为现实需求是"同一个人,在项目列表上看全公司,在结算列表上只看本部门,
|
||||
在预算列表上看本部门及下级但金额超过 500 万要藏掉"——按模块各配一条,
|
||||
还要能按角色/人/部门三种主体下发,并且支持自定义条件。详见 docs/数据权限设计.md。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import ForeignKey, Index, Integer, String, Text, UniqueConstraint, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from .base import Base, SoftDeleteMixin, TimestampMixin, u_bigint, u_tinyint
|
||||
|
||||
#: 没有任何数据权限策略命中时的兜底范围,避免把人彻底锁在系统外
|
||||
FALLBACK_SCOPE = "self"
|
||||
|
||||
|
||||
class PermKind:
|
||||
"""权限节点类型。"""
|
||||
|
||||
MENU = "menu" # 菜单节点(会出现在左侧导航里)
|
||||
GROUP = "group" # 纯分组,不跳转
|
||||
ACTION = "action" # 按钮/接口级操作
|
||||
DATA = "data" # "数据范围"开关(界面上勾"可看全公司"这类)
|
||||
|
||||
ALL = (MENU, GROUP, ACTION, DATA)
|
||||
|
||||
LABELS = {MENU: "菜单", GROUP: "分组", ACTION: "操作", DATA: "数据范围"}
|
||||
|
||||
|
||||
class PermNode(Base, SoftDeleteMixin):
|
||||
"""权限目录树:菜单 + 操作 + 数据开关,一个 code 打天下。
|
||||
|
||||
``code`` 是稳定标识(如 ``project:budget:approve``),前端按钮与后端接口都按它鉴权;
|
||||
``path``/``icon`` 只在 ``kind=menu`` 时有意义,前端路由直接照它生成。
|
||||
"""
|
||||
|
||||
__tablename__ = "perm_node"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("code", name="uk_perm_node_code"),
|
||||
Index("idx_perm_node_parent", "parent_id"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
code: Mapped[str] = mapped_column(String(128), nullable=False, comment="权限码,前后端共用")
|
||||
name: Mapped[str] = mapped_column(String(128), nullable=False, comment="显示名称")
|
||||
kind: Mapped[str] = mapped_column(String(16), default=PermKind.MENU, nullable=False)
|
||||
parent_id: Mapped[int] = mapped_column(u_bigint(), default=0, server_default="0", nullable=False)
|
||||
path: Mapped[str] = mapped_column(String(255), default="", nullable=False, comment="前端路由")
|
||||
icon: Mapped[str] = mapped_column(String(64), default="", nullable=False)
|
||||
module: Mapped[str] = mapped_column(String(64), default="", nullable=False, index=True,
|
||||
comment="所属业务模块,数据权限按它匹配")
|
||||
sort: Mapped[int] = mapped_column(Integer, default=100, server_default="100", nullable=False)
|
||||
visible: Mapped[bool] = mapped_column(u_tinyint(), default=True, server_default="1", nullable=False,
|
||||
comment="菜单是否显示(隐藏但仍可授权时用)")
|
||||
enabled: Mapped[bool] = mapped_column(u_tinyint(), default=True, server_default="1", nullable=False)
|
||||
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False)
|
||||
created_at: Mapped[str] = mapped_column(
|
||||
String(32), default="", server_default=text("''"), nullable=False
|
||||
)
|
||||
|
||||
|
||||
class PermRole(Base, TimestampMixin, SoftDeleteMixin):
|
||||
"""角色。
|
||||
|
||||
老系统用 ``sys_role.level``(1 执行董事、2 财务总监…)把"岗位级别"和"审批身份"
|
||||
混在一起,改一个动两边;这里角色只负责授权,审批人解析走岗位与专门的候选人策略。
|
||||
"""
|
||||
|
||||
__tablename__ = "perm_role"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("code", name="uk_perm_role_code"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
# 内置角色不允许删除,避免把自己锁在系统外
|
||||
builtin: Mapped[bool] = mapped_column(u_tinyint(), default=False, server_default="0", nullable=False)
|
||||
enabled: Mapped[bool] = mapped_column(u_tinyint(), default=True, server_default="1", nullable=False)
|
||||
order_number: Mapped[int] = mapped_column(Integer, default=100, server_default="100", nullable=False)
|
||||
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False)
|
||||
|
||||
|
||||
class PermAccountRole(Base):
|
||||
"""人-角色。多角色取权限并集、数据权限并集。"""
|
||||
|
||||
__tablename__ = "perm_account_role"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("account_id", "role_id", name="uk_perm_account_role"),
|
||||
Index("idx_perm_account_role_role", "role_id"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
account_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("accounts.id", ondelete="CASCADE"), nullable=False, index=True
|
||||
)
|
||||
role_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("perm_role.id", ondelete="CASCADE"), nullable=False, index=True
|
||||
)
|
||||
|
||||
|
||||
class PermRoleNode(Base):
|
||||
"""角色-权限码。"""
|
||||
|
||||
__tablename__ = "perm_role_node"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("role_id", "node_id", name="uk_perm_role_node"),
|
||||
Index("idx_perm_role_node_node", "node_id"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
role_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("perm_role.id", ondelete="CASCADE"), nullable=False, index=True
|
||||
)
|
||||
node_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("perm_node.id", ondelete="CASCADE"), nullable=False, index=True
|
||||
)
|
||||
|
||||
|
||||
class ScopeType:
|
||||
"""数据范围类型。
|
||||
|
||||
刻意做得比"self/unit/all"三种多:老系统里既有"按角色和人员配置项目可见性"
|
||||
(``project_visible`` 表),也有"按部门"、还有"我参与的",几种口径在同一系统里
|
||||
长期共存,所以这里全部保留成可组合的范围类型,而不是逼业务二选一。
|
||||
"""
|
||||
|
||||
ALL = "all" # 全部数据
|
||||
SELF = "self" # 仅本人创建/负责
|
||||
UNIT = "unit" # 本部门
|
||||
UNIT_AND_BELOW = "unit_and_below" # 本部门及下级部门
|
||||
ORG_LIST = "org_list" # 指定的若干部门(可含/不含下级)
|
||||
IDENTITY_UNITS = "identity_units" # 本人全部身份所在部门(兼岗也算)
|
||||
PARTICIPANT = "participant" # 我参与的(成员/协作/被抄送)
|
||||
ACCOUNT_LIST = "account_list" # 指定的若干人
|
||||
DEPT_OF_RECORD = "dept_of_record" # 按数据行上的部门字段判定(默认口径)
|
||||
CUSTOM = "custom" # 只用自定义条件,不限定主体范围
|
||||
|
||||
ALL_TYPES = (
|
||||
ALL, SELF, UNIT, UNIT_AND_BELOW, ORG_LIST,
|
||||
IDENTITY_UNITS, PARTICIPANT, ACCOUNT_LIST, DEPT_OF_RECORD, CUSTOM,
|
||||
)
|
||||
|
||||
#: 用于"取并集时谁更宽"的比较;只影响提示与冲突检查,不改变语义
|
||||
RANK = {
|
||||
SELF: 0,
|
||||
PARTICIPANT: 1,
|
||||
UNIT: 2,
|
||||
IDENTITY_UNITS: 2,
|
||||
UNIT_AND_BELOW: 3,
|
||||
ORG_LIST: 3,
|
||||
ACCOUNT_LIST: 2,
|
||||
CUSTOM: 2,
|
||||
DEPT_OF_RECORD: 2,
|
||||
ALL: 9,
|
||||
}
|
||||
|
||||
LABELS = {
|
||||
ALL: "全部数据",
|
||||
SELF: "仅本人",
|
||||
UNIT: "本部门",
|
||||
UNIT_AND_BELOW: "本部门及下级",
|
||||
ORG_LIST: "指定部门",
|
||||
IDENTITY_UNITS: "本人所属部门(含兼岗)",
|
||||
PARTICIPANT: "我参与的",
|
||||
ACCOUNT_LIST: "指定人员",
|
||||
DEPT_OF_RECORD: "按数据归属部门",
|
||||
CUSTOM: "仅自定义条件",
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def label(cls, value: str) -> str:
|
||||
return cls.LABELS.get(value, value)
|
||||
|
||||
|
||||
class SubjectType:
|
||||
"""数据权限策略挂在谁身上。"""
|
||||
|
||||
ALL = "all" # 所有人
|
||||
ROLE = "role"
|
||||
ACCOUNT = "account"
|
||||
ORG_UNIT = "org_unit" # 挂在部门上:这个部门里的人都吃这条
|
||||
POSITION = "position"
|
||||
|
||||
ALL_TYPES = (ALL, ROLE, ACCOUNT, ORG_UNIT, POSITION)
|
||||
|
||||
LABELS = {ALL: "所有人", ROLE: "按角色", ACCOUNT: "按账号",
|
||||
ORG_UNIT: "按部门", POSITION: "按岗位"}
|
||||
|
||||
|
||||
class Effect:
|
||||
ALLOW = "allow"
|
||||
DENY = "deny"
|
||||
|
||||
LABELS = {ALLOW: "允许", DENY: "排除"}
|
||||
|
||||
|
||||
class FieldScope(Base):
|
||||
"""字段级权限:某些列对某些角色隐藏(如成本单价、供应商名称)。"""
|
||||
|
||||
__tablename__ = "perm_field_scope"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("module", "field", "role_id", name="uk_perm_field_scope"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
module: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
||||
field: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
role_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("perm_role.id", ondelete="CASCADE"), nullable=False, index=True
|
||||
)
|
||||
mode: Mapped[str] = mapped_column(
|
||||
String(16), default="hidden", server_default="hidden", nullable=False,
|
||||
comment="hidden=不返回 masked=打码 readonly=只读",
|
||||
)
|
||||
|
||||
|
||||
class PermDataPolicy(Base, TimestampMixin, SoftDeleteMixin):
|
||||
"""一条数据权限策略。
|
||||
|
||||
求值方式(见 ``app.service.data_scope``):
|
||||
|
||||
1. 找出所有命中当前人的策略(主体 = 全部 / 我的任一角色 / 我本人 / 我任一部门 /
|
||||
我的任一岗位,且模块对得上);
|
||||
2. 每条 allow 策略 = ``范围谓词 AND 自定义条件``,多条之间取 **OR**;
|
||||
3. 每条 deny 策略同样算出谓词,多条之间取 OR,最后 **AND NOT** 掉;
|
||||
4. 一条 allow 都没命中时用兜底范围 ``self``,不会把人锁死。
|
||||
|
||||
``conditions_json`` 是一棵可嵌套的条件树,因此能表达"金额≥500 万 且(状态=通过 或
|
||||
部门∈{财务…})"这类自定义规则,而不必为每种组合加代码。
|
||||
"""
|
||||
|
||||
__tablename__ = "perm_data_policy"
|
||||
__table_args__ = (
|
||||
Index("idx_perm_data_policy_module", "module", "enabled"),
|
||||
Index("idx_perm_data_policy_subject", "subject_type", "subject_id"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
module: Mapped[str] = mapped_column(
|
||||
String(64), nullable=False, comment="业务模块:project/estimate/budget/settlement/final/approval"
|
||||
)
|
||||
subject_type: Mapped[str] = mapped_column(String(16), default=SubjectType.ROLE, nullable=False)
|
||||
subject_id: Mapped[int] = mapped_column(u_bigint(), default=0, server_default="0", nullable=False)
|
||||
effect: Mapped[str] = mapped_column(String(8), default=Effect.ALLOW, nullable=False)
|
||||
scope_type: Mapped[str] = mapped_column(String(32), default=ScopeType.SELF, nullable=False)
|
||||
# scope_type=org_list/account_list 时用的 id 列表,JSON 数组
|
||||
target_ids_json: Mapped[str] = mapped_column(Text, default="[]", nullable=False)
|
||||
# 是否把指定部门的下级也算进来
|
||||
include_children: Mapped[bool] = mapped_column(
|
||||
u_tinyint(), default=True, server_default="1", nullable=False
|
||||
)
|
||||
# 自定义条件树:{"op":"and","items":[{"field":..,"op":..,"value":..}]}
|
||||
conditions_json: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||
# 同一模块内多条策略的评估顺序;deny 先于 allow 生效,priority 只影响同种效果内部的顺序
|
||||
priority: Mapped[int] = mapped_column(Integer, default=100, server_default="100", nullable=False)
|
||||
enabled: Mapped[bool] = mapped_column(u_tinyint(), default=True, server_default="1", nullable=False)
|
||||
# 临时策略:到期自动失效,用于"项目交接期间临时授权"
|
||||
valid_from: Mapped[str] = mapped_column(String(32), default="", nullable=False)
|
||||
valid_to: Mapped[str] = mapped_column(String(32), default="", nullable=False)
|
||||
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False)
|
||||
|
|
@ -0,0 +1,547 @@
|
|||
"""项目主档与项目成员。
|
||||
|
||||
相对老库 ``project`` 表做了三处结构性调整,其余字段尽量同名,方便迁移与对账:
|
||||
|
||||
1. **拆掉"编码列 + 描述列"成对冗余**。老表里 ``underwritten_mode`` /
|
||||
``underwritten_mode_str``、``certainty`` / ``certainty_str`` 等有七八对,两边会漂移,
|
||||
而且描述是中文写死的。这里只留编码,描述由 :mod:`app.enums` 统一给出。
|
||||
2. **利润类冗余字段不再当事实来源**。``gross_profit`` 等仍然保留,但明确标注为
|
||||
"投影",只能由 :mod:`app.service.calc` 重算写入,读取一律走计算快照
|
||||
(``RISK-BUD-SSOT-001`` 的根治办法)。
|
||||
3. **审批状态从四个平铺列改成按流程对象存**(``approval_instance``),项目上只留一个
|
||||
当前阶段与当前待办人,避免"概算已通过但状态列还是待审"这类不同步。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
|
||||
from sqlalchemy import ForeignKey, Index, Integer, String, Text, UniqueConstraint, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from .base import Base, SoftDeleteMixin, date_col, money, percent, timestamp_col, u_bigint, u_tinyint
|
||||
|
||||
|
||||
class ProjectType:
|
||||
"""项目类型(老 ``project.type``)。
|
||||
|
||||
名字以前只散在两处:接口里拼一遍、前端列表页自己再抄一遍(抄成了
|
||||
"系统集成/软件开发/运维服务")。现在统一挂 LABELS,由 :mod:`app.dicts`
|
||||
同步进「系统 → 数据字典」,界面上改名不用再发版。
|
||||
"""
|
||||
|
||||
ENGINEERING = 1 # 工程集成类
|
||||
EQUIPMENT = 2 # 设备集成类
|
||||
STRATEGIC = 3 # 战略合作类
|
||||
|
||||
LABELS = {ENGINEERING: "工程集成类", EQUIPMENT: "设备集成类", STRATEGIC: "战略合作类"}
|
||||
|
||||
|
||||
class ProjectStage:
|
||||
"""项目阶段。老系统 ``stage`` 的取值原样保留,历史数据能直接对上。"""
|
||||
|
||||
S0_INITIATION = 0 # S0-项目立项
|
||||
S1_RESEARCH = 1
|
||||
S2_DESIGN = 2
|
||||
S3_BUDGET = 3 # S3-预算评估
|
||||
S4_BID = 4
|
||||
S5_CONTRACT = 5
|
||||
S6_DELIVERY = 6
|
||||
S7_SETTLEMENT = 7
|
||||
S8_FINAL = 8
|
||||
L_LOST = 9 # L-项目丢失
|
||||
|
||||
#: 老代码与迁移脚本按这个名字写了很久,留个别名,别再为了改名去动调用点
|
||||
S0_ESTIMATE = 0
|
||||
|
||||
LABELS = {
|
||||
S0_INITIATION: "S0-项目立项", S1_RESEARCH: "S1-项目调研", S2_DESIGN: "S2-方案设计",
|
||||
S3_BUDGET: "S3-预算评估", S4_BID: "S4-招标期", S5_CONTRACT: "S5-合同期",
|
||||
S6_DELIVERY: "S6-交付期", S7_SETTLEMENT: "S7-结算期", S8_FINAL: "S8-决算期",
|
||||
L_LOST: "L-项目丢失",
|
||||
}
|
||||
|
||||
|
||||
class UnderwrittenMode:
|
||||
"""垫资模式(老 ``underwritten_mode``)。"""
|
||||
|
||||
A = 1 # A类-不垫资(战略合作)
|
||||
B = 2 # B类-不垫资(背靠背)
|
||||
C = 3 # C类-垫资(账期覆盖)
|
||||
D = 4 # D类-垫资(账期不覆盖)
|
||||
|
||||
LABELS = {A: "A类-不垫资(战略合作)", B: "B类-不垫资(背靠背)",
|
||||
C: "C类-垫资(账期覆盖)", D: "D类-垫资(账期不覆盖)"}
|
||||
|
||||
|
||||
class Certainty:
|
||||
"""项目把握度(老 ``certainty``,立项表上的下拉框)。
|
||||
|
||||
取值与名字是从老库 ``project.certainty`` 的实际分布 + 立项表截图对出来的:
|
||||
库里只有 1/2/3 三种,没见过的编码一概不加。
|
||||
"""
|
||||
|
||||
A = 1
|
||||
B = 2
|
||||
C = 3
|
||||
|
||||
LABELS = {A: "A:项目成功率80%-100%", B: "B:项目成功率50%-80%", C: "C:项目成功率30%-50%"}
|
||||
|
||||
|
||||
class YesNo:
|
||||
"""是/否类字段(老库把"没填"存成 0 或 -1,这里原样留着,历史数据才显示得出名字)。"""
|
||||
|
||||
UNSET = 0
|
||||
YES = 1
|
||||
NO = 2
|
||||
LEGACY_UNKNOWN = -1
|
||||
|
||||
LABELS = {YES: "是", NO: "否", UNSET: "未填", LEGACY_UNKNOWN: "未填"}
|
||||
|
||||
|
||||
class IndustryScene:
|
||||
"""行业场景应用(老 ``industry_scene``)。
|
||||
|
||||
名字逐条对过老库 ``project.industry_scene`` 与 ``industry_scenario`` 的描述列,
|
||||
两边一致的才收进来;``0`` 是老数据里"只写了描述、没选场景"的那一批。
|
||||
"""
|
||||
|
||||
LABELS = {
|
||||
1: "信息安全", 2: "政府", 3: "公安", 4: "企业", 5: "教育", 6: "交通", 7: "医疗",
|
||||
8: "电力能源", 9: "运营商", 10: "金融", 11: "专网", 12: "其他", 13: "互联网", 14: "银行",
|
||||
}
|
||||
|
||||
|
||||
class SaleStage:
|
||||
"""公司销售阶段(老 ``sale_stage``)。
|
||||
|
||||
老库这一列没有注释,取值 -1..10 是从数据里数出来的;档位名字在老系统的
|
||||
库里找不到出处,只从立项表截图确认了 S0-商机线索 与 S2-项目报备 两档。
|
||||
所以这份取值当**可在「系统 → 数据字典」改名的初始值**看待:编码是稳定的
|
||||
(送审分支与迁移都按编码走),名字由业务定。
|
||||
"""
|
||||
|
||||
UNSET = -1
|
||||
LEAD = 0 # S0-商机线索
|
||||
INTENT = 1
|
||||
REPORTED = 2 # S2-项目报备
|
||||
PROPOSAL = 3
|
||||
NEGOTIATION = 4
|
||||
WON = 5
|
||||
SIGNED = 6
|
||||
DELIVERY = 7
|
||||
RECEIPT = 8
|
||||
CLOSED = 9
|
||||
OTHER = 10
|
||||
|
||||
LABELS = {
|
||||
UNSET: "未填写", LEAD: "S0-商机线索", INTENT: "S1-意向沟通", REPORTED: "S2-项目报备",
|
||||
PROPOSAL: "S3-方案报价", NEGOTIATION: "S4-商务谈判", WON: "S5-中标",
|
||||
SIGNED: "S6-合同签订", DELIVERY: "S7-项目交付", RECEIPT: "S8-回款完结",
|
||||
CLOSED: "S9-项目关闭", OTHER: "S10-其他",
|
||||
}
|
||||
|
||||
|
||||
class ProjectSource:
|
||||
"""项目从哪来。清理脚本靠这一列决定"演示/测试数据删、迁移数据留"。
|
||||
|
||||
没有这列之前,清库脚本只能整表清 ``project``,于是每清一次演示数据就得把
|
||||
``migrate_legacy.py`` 导进来的八百多个真实项目一起冲掉——那是最贵的一种误删。
|
||||
"""
|
||||
|
||||
LOCAL = "local" # 界面上建的(含 pytest 造的测试数据)
|
||||
LEGACY = "legacy" # scripts/migrate_legacy.py 从老四算导入
|
||||
|
||||
LABELS = {LOCAL: "本系统创建", LEGACY: "老系统迁移"}
|
||||
|
||||
|
||||
class Project(Base, SoftDeleteMixin):
|
||||
"""项目主档。"""
|
||||
|
||||
__tablename__ = "project"
|
||||
__table_args__ = (
|
||||
Index("idx_project_creator", "creator_id"),
|
||||
Index("idx_project_org", "org_unit_id"),
|
||||
Index("idx_project_stage", "stage"),
|
||||
Index("idx_project_no", "project_no"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
project_no: Mapped[str] = mapped_column(String(64), default="", nullable=False, comment="项目编号")
|
||||
name: Mapped[str] = mapped_column(Text, nullable=False, comment="项目名称")
|
||||
other_name: Mapped[str] = mapped_column(String(255), default="", nullable=False, comment="项目简称")
|
||||
type: Mapped[int] = mapped_column(Integer, default=0, nullable=False, comment="项目类型")
|
||||
|
||||
# --- 归属:数据权限的主要依据 ---------------------------------------------
|
||||
creator_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("accounts.id", ondelete="RESTRICT"), nullable=False
|
||||
)
|
||||
creator_name: Mapped[str] = mapped_column(String(100), default="", nullable=False)
|
||||
# 归属部门:老系统取"创建者的部门",但人员会调动,历史项目跟着人跑掉。
|
||||
# 这里在创建时固化,之后只在显式"项目移交"时改动,数据权限按它算。
|
||||
org_unit_id: Mapped[int | None] = mapped_column(
|
||||
u_bigint(), ForeignKey("org_unit.id", ondelete="SET NULL"), nullable=True
|
||||
)
|
||||
org_unit_name: Mapped[str] = mapped_column(String(255), default="", nullable=False)
|
||||
principal: Mapped[str] = mapped_column(String(100), default="", nullable=False, comment="项目负责人姓名")
|
||||
principal_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True, comment="项目负责人账号")
|
||||
|
||||
# --- 生命周期 -------------------------------------------------------------
|
||||
stage: Mapped[int] = mapped_column(Integer, default=ProjectStage.S0_ESTIMATE, nullable=False)
|
||||
stage_remark: Mapped[str] = mapped_column(Text, default="", nullable=False, comment="当前进度描述")
|
||||
next_plan: Mapped[str] = mapped_column(Text, default="", nullable=False, comment="下一步计划")
|
||||
|
||||
# --- 客户与合同要素 -------------------------------------------------------
|
||||
customer: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||
terminal_customer: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||
plan_start: Mapped[date | None] = mapped_column(
|
||||
date_col(), nullable=True, comment="计划开始(精确到月)")
|
||||
plan_end: Mapped[date | None] = mapped_column(
|
||||
date_col(), nullable=True, comment="计划结束(精确到月)")
|
||||
contract_time: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True)
|
||||
bids_time: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True)
|
||||
|
||||
underwritten_mode: Mapped[int | None] = mapped_column(Integer, nullable=True, comment="垫资模式")
|
||||
cooperate_type: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
collaborator: Mapped[str] = mapped_column(String(255), default="", nullable=False, comment="合作对象")
|
||||
collaborator_attachment: Mapped[str] = mapped_column(String(500), default="", nullable=False)
|
||||
certainty: Mapped[int | None] = mapped_column(Integer, nullable=True, comment="项目把握度")
|
||||
is_second: Mapped[int | None] = mapped_column(Integer, nullable=True, comment="是否二次合作")
|
||||
is_huizhi_bid: Mapped[int | None] = mapped_column(Integer, nullable=True, comment="是否汇智中标")
|
||||
sign_type: Mapped[int | None] = mapped_column(Integer, nullable=True, comment="签单方式")
|
||||
resolve_plan: Mapped[int | None] = mapped_column(Integer, nullable=True, comment="解决方案")
|
||||
industry_scene: Mapped[int] = mapped_column(Integer, default=0, nullable=False, comment="行业场景")
|
||||
industry_scene_desc: Mapped[str] = mapped_column(String(255), default="", nullable=False)
|
||||
# 公司销售阶段:老库 project.sale_stage 同名列。从前迁移把它丢了,
|
||||
# 立项表上这一栏是必填的,再丢一次就得让人重新录八百个项目。
|
||||
sale_stage: Mapped[int] = mapped_column(Integer, default=SaleStage.UNSET, nullable=False,
|
||||
comment="公司销售阶段")
|
||||
source: Mapped[str] = mapped_column(String(16), default=ProjectSource.LOCAL, nullable=False,
|
||||
comment="数据来源 local/legacy")
|
||||
|
||||
main_contract_collection_terms: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||
main_contract_resolve_plan: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||
calculation_collection: Mapped[str] = mapped_column(Text, default="", nullable=False, comment="计收计划")
|
||||
value_risk: Mapped[str] = mapped_column(Text, default="", nullable=False, comment="价值及风险")
|
||||
|
||||
# --- 产品金额构成 ---------------------------------------------------------
|
||||
huazhi_amount: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False)
|
||||
huizhi_amount: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False)
|
||||
h3c_amount: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False)
|
||||
other_product_amount: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False)
|
||||
|
||||
# --- 计算投影:只由 calc 服务写,禁止业务代码直接改 -----------------------
|
||||
contract_amount: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False)
|
||||
gross_profit_a: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False)
|
||||
gross_profit_a_rate: Mapped[Decimal] = mapped_column(percent(), default=Decimal("0"), nullable=False)
|
||||
gross_profit: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False)
|
||||
gross_profit_rate: Mapped[Decimal] = mapped_column(percent(), default=Decimal("0"), nullable=False)
|
||||
contribution_profit: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False)
|
||||
contribution_profit_rate: Mapped[Decimal] = mapped_column(percent(), default=Decimal("0"), nullable=False)
|
||||
advance_peak_amount: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False)
|
||||
advance_interest_amount: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False)
|
||||
advance_interest_rate: Mapped[Decimal] = mapped_column(percent(), default=Decimal("0"), nullable=False,
|
||||
comment="垫资年利率")
|
||||
# 口径见 RISK-PLAN-STAT-001:老系统字段名叫"峰值金额"但算的是各月垫资之和。
|
||||
# 这里明确改名并保留旧列语义,新列 give_peak_month/give_peak_value 给真实峰值。
|
||||
advance_plan_total: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False,
|
||||
comment="各月垫资计划之和(老'峰值金额'的真实含义)")
|
||||
advance_peak_month: Mapped[str] = mapped_column(String(16), default="", nullable=False,
|
||||
comment="单月垫资最大值所在月份")
|
||||
advance_peak_value: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False,
|
||||
comment="单月垫资最大值")
|
||||
calc_version: Mapped[str] = mapped_column(String(32), default="", nullable=False, comment="投影所属计算规则版本")
|
||||
calc_snapshot_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True, comment="投影来源快照")
|
||||
calc_at: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True)
|
||||
|
||||
# --- 软删除留痕 -----------------------------------------------------------
|
||||
# 光有一个 is_deleted 位,回收站就答不出"谁在什么时候、因为什么删的"。项目是财务
|
||||
# 口径的载体,误删之后总得有人把它捞回来并交代来历,所以这几列跟着标记一起写;
|
||||
# 恢复时清空,不拿上一次的删除信息冒充这一次的。
|
||||
deleted_at: Mapped[datetime | None] = mapped_column(timestamp_col(), nullable=True, comment="删除时间")
|
||||
deleted_by_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True, comment="删除人账号")
|
||||
deleted_by_name: Mapped[str] = mapped_column(String(100), default="", nullable=False, comment="删除人姓名")
|
||||
delete_reason: Mapped[str] = mapped_column(String(500), default="", nullable=False, comment="删除原因")
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
timestamp_col(), default=datetime.now, server_default=text("CURRENT_TIMESTAMP(3)"), nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
timestamp_col(), default=datetime.now, onupdate=datetime.now,
|
||||
server_default=text("CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)"), nullable=False)
|
||||
|
||||
members: Mapped[list["ProjectMember"]] = relationship(
|
||||
back_populates="project", cascade="all, delete-orphan", lazy="selectin"
|
||||
)
|
||||
|
||||
@property
|
||||
def stage_label(self) -> str:
|
||||
return ProjectStage.LABELS.get(self.stage, "未知")
|
||||
|
||||
|
||||
class ProjectMemberRole:
|
||||
"""项目成员种类。数据权限的"我参与的"就是按这张表判定。"""
|
||||
|
||||
OWNER = "owner" # 项目负责人
|
||||
PARTICIPANT = "participant"
|
||||
COLLABORATOR = "collaborator" # 协作/支撑
|
||||
VIEWER = "viewer" # 单独授权可见的人
|
||||
|
||||
ALL = (OWNER, PARTICIPANT, COLLABORATOR, VIEWER)
|
||||
|
||||
LABELS = {OWNER: "项目负责人", PARTICIPANT: "参与人",
|
||||
COLLABORATOR: "协作支撑", VIEWER: "仅可见"}
|
||||
|
||||
|
||||
class ProjectMember(Base):
|
||||
"""项目成员(含老 ``project_visible`` 里 type=2 的"按人员授权可见")。"""
|
||||
|
||||
__tablename__ = "project_member"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("project_id", "account_id", name="uk_project_member"),
|
||||
Index("idx_project_member_account", "account_id", "member_role"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
project_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("project.id", ondelete="CASCADE"), nullable=False, index=True
|
||||
)
|
||||
account_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("accounts.id", ondelete="CASCADE"), nullable=False
|
||||
)
|
||||
account_name: Mapped[str] = mapped_column(String(100), default="", nullable=False)
|
||||
member_role: Mapped[str] = mapped_column(
|
||||
String(24), default=ProjectMemberRole.PARTICIPANT, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
timestamp_col(), default=datetime.now, server_default=text("CURRENT_TIMESTAMP(3)"), nullable=False)
|
||||
|
||||
project: Mapped["Project"] = relationship(back_populates="members")
|
||||
|
||||
|
||||
class ProjectVisibleRole(Base):
|
||||
"""按角色授权项目可见(老 ``project_visible`` type=1)。
|
||||
|
||||
保留它是因为业务上确有"整个财务部都能看所有项目"这种整批授权;日常更推荐直接在
|
||||
数据权限里配策略,这里留着兼容老数据的逐项目授权。
|
||||
"""
|
||||
|
||||
__tablename__ = "project_visible_role"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("project_id", "role_id", name="uk_project_visible_role"),
|
||||
Index("idx_project_visible_role", "role_id"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
project_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("project.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
role_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("perm_role.id", ondelete="CASCADE"), nullable=False)
|
||||
|
||||
|
||||
class ProjectStageLog(Base):
|
||||
"""阶段变更流水,项目详情"基本信息"页的时间线用它。"""
|
||||
|
||||
__tablename__ = "project_stage_log"
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
project_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("project.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
stage: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
stage_label: Mapped[str] = mapped_column(String(64), default="", nullable=False)
|
||||
account_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True)
|
||||
account_name: Mapped[str] = mapped_column(String(100), default="", nullable=False)
|
||||
remark: Mapped[str] = mapped_column(String(2000), default="", nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
timestamp_col(), default=datetime.now, server_default=text("CURRENT_TIMESTAMP(3)"), nullable=False)
|
||||
|
||||
|
||||
class Attachment(Base, SoftDeleteMixin):
|
||||
"""附件。老系统把附件路径平铺在业务表上(cost_detail_attr 等),一列一路径,
|
||||
改一次留不住历史;这里统一成一张表,业务侧用 (object_type, object_id) 挂。"""
|
||||
|
||||
__tablename__ = "attachment"
|
||||
__table_args__ = (
|
||||
Index("idx_attachment_object", "object_type", "object_id"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
object_type: Mapped[str] = mapped_column(String(64), nullable=False,
|
||||
comment="estimate/budget/contract/approval…")
|
||||
object_id: Mapped[int] = mapped_column(u_bigint(), default=0, server_default="0", nullable=False)
|
||||
field: Mapped[str] = mapped_column(String(64), default="", nullable=False, comment="挂在哪个字段上")
|
||||
file_name: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
stored_name: Mapped[str] = mapped_column(String(500), default="", nullable=False)
|
||||
url: Mapped[str] = mapped_column(String(1000), default="", nullable=False)
|
||||
size: Mapped[int] = mapped_column(u_bigint(), default=0, server_default="0", nullable=False)
|
||||
ext: Mapped[str] = mapped_column(String(16), default="", nullable=False)
|
||||
uploader_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True)
|
||||
uploader_name: Mapped[str] = mapped_column(String(100), default="", nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
timestamp_col(), default=datetime.now, server_default=text("CURRENT_TIMESTAMP(3)"), nullable=False)
|
||||
|
||||
|
||||
class SystemConfig(Base):
|
||||
"""业务参数(利润率阈值、固定项目管理费用项等)。
|
||||
|
||||
老系统 ``sys_config`` 只有 code/name/value 三列且没有类型,读出来全是字符串。这里
|
||||
加 value_type 与分组,界面上按组渲染表单,代码里按类型取值。
|
||||
"""
|
||||
|
||||
__tablename__ = "system_config"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("code", name="uk_system_config_code"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
code: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
value: Mapped[str] = mapped_column(Text, default="", nullable=False)
|
||||
value_type: Mapped[str] = mapped_column(String(16), default="string", nullable=False,
|
||||
comment="string/number/bool/json")
|
||||
group: Mapped[str] = mapped_column(String(64), default="common", nullable=False, index=True)
|
||||
editable: Mapped[bool] = mapped_column(u_tinyint(), default=True, server_default="1", nullable=False)
|
||||
remark: Mapped[str] = mapped_column(String(500), default="", nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
timestamp_col(), default=datetime.now, onupdate=datetime.now,
|
||||
server_default=text("CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)"), nullable=False)
|
||||
|
||||
|
||||
class MilestoneStatus:
|
||||
"""里程碑状态。``overdue`` 不入库,读的时候按"计划日期已过且未完成"现算,
|
||||
否则每天凌晨没人跑任务,逾期就永远显示不出来。"""
|
||||
|
||||
PENDING = "pending"
|
||||
DONE = "done"
|
||||
OVERDUE = "overdue"
|
||||
|
||||
LABELS = {PENDING: "未完成", DONE: "已完成", OVERDUE: "已逾期"}
|
||||
|
||||
|
||||
class ProjectMilestone(Base, SoftDeleteMixin):
|
||||
"""项目里程碑:立项批准后要盯的那几个节点(招标、签约、到货、初验…)。
|
||||
|
||||
``receive_point`` 与预算收款计划的"收款节点"同名,是为了让"这个里程碑完成了该收钱"
|
||||
这件事有个对得上的锚点;先不做自动关联,把字段留对,比事后按名字猜强。
|
||||
"""
|
||||
|
||||
__tablename__ = "project_milestone"
|
||||
__table_args__ = (
|
||||
Index("idx_milestone_project", "project_id", "plan_date"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
project_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("project.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
name: Mapped[str] = mapped_column(String(255), nullable=False, comment="里程碑名称")
|
||||
stage: Mapped[int | None] = mapped_column(Integer, nullable=True, comment="挂在哪个项目阶段")
|
||||
plan_date: Mapped[date | None] = mapped_column(date_col(), nullable=True, comment="计划完成日期")
|
||||
actual_date: Mapped[date | None] = mapped_column(date_col(), nullable=True, comment="实际完成日期")
|
||||
owner_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True)
|
||||
owner_name: Mapped[str] = mapped_column(String(100), default="", nullable=False)
|
||||
amount: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False,
|
||||
comment="该节点对应的合同金额")
|
||||
receive_point: Mapped[str] = mapped_column(String(255), default="", nullable=False,
|
||||
comment="对应预算收款计划的收款节点")
|
||||
status: Mapped[str] = mapped_column(String(16), default=MilestoneStatus.PENDING, nullable=False)
|
||||
remark: Mapped[str] = mapped_column(String(1000), default="", nullable=False)
|
||||
sort: Mapped[int] = mapped_column(Integer, default=100, server_default="100", nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
timestamp_col(), default=datetime.now, server_default=text("CURRENT_TIMESTAMP(3)"), nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
timestamp_col(), default=datetime.now, onupdate=datetime.now,
|
||||
server_default=text("CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)"), nullable=False)
|
||||
|
||||
|
||||
class WbsTaskStatus:
|
||||
"""WBS 任务状态。"""
|
||||
|
||||
NOT_STARTED = "not_started"
|
||||
IN_PROGRESS = "in_progress"
|
||||
DONE = "done"
|
||||
BLOCKED = "blocked"
|
||||
|
||||
LABELS = {NOT_STARTED: "未开始", IN_PROGRESS: "进行中", DONE: "已完成", BLOCKED: "受阻"}
|
||||
|
||||
|
||||
class WbsTask(Base, SoftDeleteMixin):
|
||||
"""WBS 分解结构:一棵挂在项目上的任务树。
|
||||
|
||||
用 ``parent_id`` + ``path`` 两条腿:``parent_id`` 给外键与移动子树用,
|
||||
``path``(``/1/8/19/``)让"取整棵子树"和"按层级排序"退化成一次 LIKE 与一次 ORDER BY,
|
||||
不用在应用里递归。``rollup`` 读时算:进度 = 子任务按权重加权,
|
||||
存一份就要负责把它算对,那是第三份会漂移的进度。
|
||||
"""
|
||||
|
||||
__tablename__ = "wbs_task"
|
||||
__table_args__ = (
|
||||
Index("idx_wbs_task_project", "project_id", "path"),
|
||||
Index("idx_wbs_task_parent", "parent_id"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
project_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("project.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
parent_id: Mapped[int | None] = mapped_column(
|
||||
u_bigint(), ForeignKey("wbs_task.id", ondelete="CASCADE"), nullable=True)
|
||||
path: Mapped[str] = mapped_column(String(500), default="/", nullable=False, comment="物化路径")
|
||||
level: Mapped[int] = mapped_column(Integer, default=1, server_default="1", nullable=False)
|
||||
code: Mapped[str] = mapped_column(String(32), default="", nullable=False, comment="WBS 编码 1.2.3")
|
||||
name: Mapped[str] = mapped_column(String(255), nullable=False, comment="任务名称")
|
||||
milestone_id: Mapped[int | None] = mapped_column(
|
||||
u_bigint(), ForeignKey("project_milestone.id", ondelete="SET NULL"), nullable=True,
|
||||
comment="归属的里程碑")
|
||||
owner_id: Mapped[int | None] = mapped_column(u_bigint(), nullable=True)
|
||||
owner_name: Mapped[str] = mapped_column(String(100), default="", nullable=False)
|
||||
plan_start: Mapped[date | None] = mapped_column(date_col(), nullable=True)
|
||||
plan_end: Mapped[date | None] = mapped_column(date_col(), nullable=True)
|
||||
actual_start: Mapped[date | None] = mapped_column(date_col(), nullable=True)
|
||||
actual_end: Mapped[date | None] = mapped_column(date_col(), nullable=True)
|
||||
weight: Mapped[Decimal] = mapped_column(money(10, 2), default=Decimal("1"), nullable=False,
|
||||
comment="父子进度加权的权重")
|
||||
progress: Mapped[int] = mapped_column(Integer, default=0, server_default="0", nullable=False,
|
||||
comment="自身进度 0-100")
|
||||
status: Mapped[str] = mapped_column(String(16), default=WbsTaskStatus.NOT_STARTED, nullable=False)
|
||||
budget_amount: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False,
|
||||
comment="任务预算(预算科目编制的落点)")
|
||||
actual_amount: Mapped[Decimal] = mapped_column(money(), default=Decimal("0"), nullable=False,
|
||||
comment="任务实际发生(实际成本归集的落点)")
|
||||
remark: Mapped[str] = mapped_column(String(1000), default="", nullable=False)
|
||||
sort: Mapped[int] = mapped_column(Integer, default=100, server_default="100", nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
timestamp_col(), default=datetime.now, server_default=text("CURRENT_TIMESTAMP(3)"), nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
timestamp_col(), default=datetime.now, onupdate=datetime.now,
|
||||
server_default=text("CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)"), nullable=False)
|
||||
|
||||
|
||||
class ProjectStageEvent(Base):
|
||||
"""阶段内的检查项/交付物清单(阶段推进时的"这几件事做完了吗")。
|
||||
|
||||
只做"记录",不做工作流:真要卡流程应该走审批引擎,别在阶段表里再长一套状态机。
|
||||
"""
|
||||
|
||||
__tablename__ = "project_stage_item"
|
||||
__table_args__ = (
|
||||
Index("idx_stage_item_project", "project_id", "stage"),
|
||||
{"mysql_charset": "utf8mb4", "mysql_collate": "utf8mb4_unicode_ci"},
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(u_bigint(), primary_key=True, autoincrement=True)
|
||||
project_id: Mapped[int] = mapped_column(
|
||||
u_bigint(), ForeignKey("project.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
stage: Mapped[int] = mapped_column(Integer, nullable=False, comment="所属项目阶段")
|
||||
name: Mapped[str] = mapped_column(String(255), nullable=False, comment="检查项/交付物")
|
||||
done: Mapped[bool] = mapped_column(u_tinyint(), default=False, server_default="0", nullable=False)
|
||||
owner_name: Mapped[str] = mapped_column(String(100), default="", nullable=False)
|
||||
due_date: Mapped[date | None] = mapped_column(date_col(), nullable=True)
|
||||
remark: Mapped[str] = mapped_column(String(1000), default="", nullable=False)
|
||||
sort: Mapped[int] = mapped_column(Integer, default=100, server_default="100", nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
timestamp_col(), default=datetime.now, server_default=text("CURRENT_TIMESTAMP(3)"), nullable=False)
|
||||
|
|
@ -0,0 +1,153 @@
|
|||
"""口令散列与登录令牌。
|
||||
|
||||
老系统用 ``MD5(密码 + salt)``(``DESCrypto`` / ``Utils`` 里那套),并且 salt 和口令
|
||||
分开存两列。这里换 bcrypt,代价是每次校验几十毫秒,但对登录这种低频操作完全值得。
|
||||
|
||||
令牌用 JWT 而不是老系统那种"Redis 里存一个随机串":本系统要能在多实例下横向扩容,
|
||||
也要让前端能离线判过期。撤销靠 ``accounts.password_updated_at`` 与刷新令牌表,
|
||||
见 :func:`issue_tokens`。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
import bcrypt
|
||||
from jose import JWTError, jwt
|
||||
|
||||
from .config import settings
|
||||
|
||||
_BCRYPT_MAX_BYTES = 72 # bcrypt 只看前 72 字节,超长口令先截断,避免"两种口令都能登"
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return bcrypt.hashpw(_encode(password), bcrypt.gensalt()).decode("utf-8")
|
||||
|
||||
|
||||
def verify_password(password: str, password_hash: str) -> bool:
|
||||
if not password_hash:
|
||||
return False
|
||||
try:
|
||||
return bcrypt.checkpw(_encode(password), password_hash.encode("utf-8"))
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
def _encode(password: str) -> bytes:
|
||||
return password.encode("utf-8")[:_BCRYPT_MAX_BYTES]
|
||||
|
||||
|
||||
def random_password(length: int = 14) -> str:
|
||||
return secrets.token_urlsafe(length)
|
||||
|
||||
|
||||
class TokenError(Exception):
|
||||
"""令牌无效、过期或已撤销。"""
|
||||
|
||||
|
||||
def issue_tokens(
|
||||
account_id: int,
|
||||
account: str,
|
||||
*,
|
||||
identity_id: int | None = None,
|
||||
extra: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""签发访问令牌 + 刷新令牌。"""
|
||||
now = datetime.now()
|
||||
access_payload: dict[str, Any] = {
|
||||
"sub": str(account_id),
|
||||
"account": account,
|
||||
"typ": "access",
|
||||
"iat": int(now.timestamp()),
|
||||
"exp": int((now + timedelta(seconds=settings.security.access_token_ttl)).timestamp()),
|
||||
}
|
||||
if identity_id:
|
||||
access_payload["identity"] = identity_id
|
||||
if extra:
|
||||
access_payload.update(extra)
|
||||
|
||||
refresh_payload = {
|
||||
"sub": str(account_id),
|
||||
"account": account,
|
||||
"typ": "refresh",
|
||||
"jti": secrets.token_hex(12),
|
||||
"iat": int(now.timestamp()),
|
||||
"exp": int((now + timedelta(seconds=settings.security.refresh_token_ttl)).timestamp()),
|
||||
}
|
||||
algorithm = settings.security.jwt_algorithm
|
||||
# 出参用驼峰,和全站 wrapper 一致;这里的键名一旦改动,前端登录会静默失效
|
||||
return {
|
||||
"accessToken": jwt.encode(access_payload, _secret(), algorithm=algorithm),
|
||||
"refreshToken": jwt.encode(refresh_payload, _secret(), algorithm=algorithm),
|
||||
"tokenType": "bearer",
|
||||
"expiresIn": settings.security.access_token_ttl,
|
||||
}
|
||||
|
||||
|
||||
def decode_token(token: str, *, expect: str = "access") -> dict[str, Any]:
|
||||
try:
|
||||
payload = jwt.decode(token, _secret(), algorithms=[settings.security.jwt_algorithm])
|
||||
except JWTError as exc:
|
||||
raise TokenError(f"令牌无效或已过期:{exc}") from exc
|
||||
if payload.get("typ") != expect:
|
||||
raise TokenError("令牌类型不正确")
|
||||
return payload
|
||||
|
||||
|
||||
def refresh_token_ttl() -> int:
|
||||
return settings.security.refresh_token_ttl
|
||||
|
||||
|
||||
def access_token_ttl() -> int:
|
||||
return settings.security.access_token_ttl
|
||||
|
||||
|
||||
def _secret() -> str:
|
||||
secret = settings.security.jwt_secret
|
||||
if not secret:
|
||||
# 生产档漏配密钥时绝不能退化成"随便签一个能用的",直接拒绝签发
|
||||
raise TokenError("服务端未配置 security.jwt_secret,无法签发登录令牌")
|
||||
return secret
|
||||
|
||||
|
||||
def signing_secret() -> str:
|
||||
"""非 JWT 的东西(免登 state、一次性短码)也用这把密钥签/哈希。
|
||||
|
||||
集中在这里只有一个原因:密钥漏配时宁可抛错,也不能退化成"随便找个串签一下"——
|
||||
那种情况下签出来的 state 谁都能造,免登的防注入就白做了。
|
||||
"""
|
||||
return _secret()
|
||||
|
||||
|
||||
def hash_token(value: str) -> str:
|
||||
"""令牌类字符串的哈希口径。库里只存这个,明文丢了也还原不出可用凭据。"""
|
||||
return hashlib.sha256((value or "").encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def sign(value: str) -> str:
|
||||
"""给短字符串签名(免登 state 的 Cookie 值用),常数时间比对靠 :func:`verify_signature`。"""
|
||||
return hmac.new(signing_secret().encode("utf-8"), value.encode("utf-8"), hashlib.sha256).hexdigest()[:32]
|
||||
|
||||
|
||||
def verify_signature(value: str, signature: str) -> bool:
|
||||
return hmac.compare_digest(sign(value), (signature or "").strip())
|
||||
|
||||
|
||||
def password_policy_error(password: str) -> str | None:
|
||||
"""口令强度:长度 + 至少两类字符。返回 None 表示合格。"""
|
||||
minimum = settings.security.password_min_length
|
||||
if len(password) < minimum:
|
||||
return f"口令长度不得少于 {minimum} 位"
|
||||
kinds = sum([
|
||||
any(char.islower() for char in password),
|
||||
any(char.isupper() for char in password),
|
||||
any(char.isdigit() for char in password),
|
||||
any(not char.isalnum() for char in password),
|
||||
])
|
||||
if kinds < 2:
|
||||
return "口令需包含小写字母、大写字母、数字、符号中的至少两类"
|
||||
return None
|
||||
|
|
@ -0,0 +1,731 @@
|
|||
"""首次启动时种下的基础数据。
|
||||
|
||||
种的东西分两类,只有第二类受 ``seed.demo_data`` 控制:
|
||||
|
||||
1. **跑不起来的最低要求**:权限目录、内置角色、超管账号、默认审批流程、业务参数。
|
||||
这些没有就等于系统空转,任何档位都要种。
|
||||
2. **演示数据**:示例组织、示例项目。只有 ``demo_data=true`` 才种,生产绝不开。
|
||||
|
||||
种的动作全部是"库里没有才插",重复启动不会产生第二份,也不会覆盖你在界面上改过的东西。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .config import settings
|
||||
from .service import data_scope
|
||||
from .db import SessionFactory
|
||||
from .models import (
|
||||
Account,
|
||||
AccountIdentity,
|
||||
AccountSource,
|
||||
ApprovalFlow,
|
||||
ApprovalNode,
|
||||
OrgUnit,
|
||||
PermAccountRole,
|
||||
PermDataPolicy,
|
||||
PermNode,
|
||||
PermRole,
|
||||
PermRoleNode,
|
||||
Position,
|
||||
ScopeType,
|
||||
Status,
|
||||
SubjectType,
|
||||
SystemConfig,
|
||||
)
|
||||
from . import dicts as dict_store
|
||||
from .security import hash_password, random_password
|
||||
from .service.approval import flow as flow_service
|
||||
from .service.calc import rules as calc_rules
|
||||
|
||||
logger = logging.getLogger("pms.seed")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 权限目录:一个 code 同时管菜单、按钮、接口
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# (code, name, kind, path, icon, module, children)
|
||||
CATALOG: list[tuple[str, str, str, str, str, str, list[Any]]] = [
|
||||
("workbench", "工作台", "menu", "/workbench", "gauge", "", [
|
||||
("workbench:todo", "我的待办", "menu", "/workbench/todo", "inbox", "approval", []),
|
||||
("workbench:done", "我的已办", "menu", "/workbench/done", "check-circle", "approval", []),
|
||||
("workbench:created", "我发起的", "menu", "/workbench/created", "send", "approval", []),
|
||||
("workbench:delegates", "审批委托", "menu", "/workbench/delegates", "user-switch", "approval", []),
|
||||
]),
|
||||
("project", "项目管理", "menu", "/projects", "folder", "project", [
|
||||
("project:project:view", "项目列表", "menu", "/projects", "list", "project", [
|
||||
("project:project:create", "新建项目", "action", "", "", "project", []),
|
||||
("project:project:edit", "编辑项目", "action", "", "", "project", []),
|
||||
("project:project:delete", "删除项目", "action", "", "", "project", []),
|
||||
# 销毁与删除分开授权:删除可恢复,销毁不可恢复,默认只给系统管理员。
|
||||
("project:project:purge", "彻底删除项目", "action", "", "", "project", []),
|
||||
("project:project:export", "导出项目", "action", "", "", "project", []),
|
||||
]),
|
||||
# 立项是独立模块,不再是项目详情里的一个页签:它有自己的列表、表单和审批流,
|
||||
# 审批通过之后项目预算那一侧才允许生成数据(见 biz.assert_initiation_approved)。
|
||||
("project:estimate:view", "项目立项", "menu", "/initiations", "target", "estimate", [
|
||||
("project:estimate:edit", "填报立项", "action", "", "", "estimate", []),
|
||||
("project:estimate:submit", "提交立项审批", "action", "", "", "estimate", []),
|
||||
]),
|
||||
("project:stage:view", "项目阶段", "menu", "/project-stages", "route", "project", [
|
||||
("project:stage:edit", "推进阶段", "action", "", "", "project", []),
|
||||
]),
|
||||
("project:milestone:view", "项目里程碑", "menu", "/milestones", "star", "project", [
|
||||
("project:milestone:edit", "维护里程碑", "action", "", "", "project", []),
|
||||
]),
|
||||
("project:wbs:view", "WBS 分解", "menu", "/wbs", "listChecks", "project", [
|
||||
("project:wbs:edit", "维护 WBS", "action", "", "", "project", []),
|
||||
]),
|
||||
("project:member:edit", "项目成员与可见性", "action", "", "", "project", []),
|
||||
]),
|
||||
# —— 预算模块:编制 → 执行对比 → 超支拦截。从前预算只是项目详情里的一个页签,
|
||||
# 和立项挤在同一个菜单项下面,"谁能编预算、谁能看执行对比"没法分开授权。
|
||||
("budget", "预算模块", "menu", "/budgets", "fileSpreadsheet", "budget", [
|
||||
("project:budget:view", "预算编制", "menu", "/budgets", "list", "budget", [
|
||||
("project:budget:edit", "编辑预算", "action", "", "", "budget", []),
|
||||
("project:budget:submit", "提交预算审批", "action", "", "", "budget", []),
|
||||
]),
|
||||
("budget:control:view", "预算执行对比", "menu", "/budget-control", "barChart", "budget", [
|
||||
("budget:control:edit", "维护超支拦截规则", "action", "", "", "budget", []),
|
||||
]),
|
||||
]),
|
||||
("approval", "审批中心", "menu", "/approvals", "git-pull-request", "approval", [
|
||||
("approval:monitor:view", "流程监控", "menu", "/approvals/monitor", "activity", "approval", []),
|
||||
("approval:flow:view", "流程配置", "menu", "/approvals/flows", "workflow", "", [
|
||||
("approval:flow:edit", "编辑流程", "action", "", "", "", []),
|
||||
("approval:flow:publish", "发布/下线流程", "action", "", "", "", []),
|
||||
]),
|
||||
]),
|
||||
("org", "组织与人员", "menu", "/org", "network", "", [
|
||||
("org:unit", "组织架构", "menu", "/org/units", "git-branch", "", [
|
||||
("org:unit:edit", "维护部门", "action", "", "", "", []),
|
||||
]),
|
||||
("org:person", "系统账号", "menu", "/org/accounts", "users", "", [
|
||||
("org:person:view", "查看账号", "action", "", "", "", []),
|
||||
("org:person:edit", "维护账号", "action", "", "", "", []),
|
||||
]),
|
||||
("org:position", "岗位", "menu", "/org/positions", "briefcase", "", [
|
||||
("org:position:edit", "维护岗位", "action", "", "", "", []),
|
||||
]),
|
||||
("org:sync:run", "统一身份同步", "menu", "/org/hub-sync", "refresh-cw", "", []),
|
||||
]),
|
||||
("system", "系统管理", "menu", "/system", "settings", "", [
|
||||
("system:role:view", "角色与权限", "menu", "/system/roles", "shield", "", [
|
||||
("system:role:edit", "维护角色", "action", "", "", "", []),
|
||||
]),
|
||||
("system:datapermission:view", "数据权限", "menu", "/system/data-permission", "lock", "", [
|
||||
("system:datapermission:edit", "维护数据权限", "action", "", "", "", []),
|
||||
]),
|
||||
("system:permission:view", "菜单与权限码", "menu", "/system/permissions", "key", "", [
|
||||
("system:permission:edit", "维护权限码", "action", "", "", "", []),
|
||||
]),
|
||||
("system:config:view", "业务参数", "menu", "/system/configs", "sliders", "", [
|
||||
("system:config:edit", "修改参数", "action", "", "", "", []),
|
||||
]),
|
||||
("system:calcrule:view", "计算口径", "menu", "/system/calc-rules", "sigma", "", [
|
||||
("system:calcrule:edit", "修改计算口径", "action", "", "", "", []),
|
||||
]),
|
||||
("system:dict:view", "数据字典", "menu", "/system/dicts", "tag", "", [
|
||||
("system:dict:edit", "维护字典", "action", "", "", "", []),
|
||||
]),
|
||||
("system:audit:view", "操作日志", "menu", "/system/operation-logs", "clock", "", []),
|
||||
]),
|
||||
]
|
||||
|
||||
ROLES: list[dict[str, Any]] = [
|
||||
{"code": "super_admin", "name": "超级管理员", "builtin": True, "order": 0,
|
||||
"remark": "系统内置,拥有全部菜单与全部数据", "codes": ["*"], "scope": ScopeType.ALL},
|
||||
{"code": "project_owner", "name": "项目负责人", "builtin": True, "order": 10,
|
||||
"remark": "本人创建或负责的项目全流程", "scope": ScopeType.PARTICIPANT,
|
||||
"codes": ["workbench", "workbench:todo", "workbench:done", "workbench:created",
|
||||
"workbench:delegates", "project", "project:project:view", "project:project:create",
|
||||
"project:project:edit", "project:project:delete", "project:project:export",
|
||||
"project:estimate:view",
|
||||
"project:estimate:edit", "project:estimate:submit", "project:budget:view",
|
||||
"project:budget:edit", "project:budget:submit", "project:member:edit",
|
||||
"project:stage:view", "project:stage:edit",
|
||||
"project:milestone:view", "project:milestone:edit",
|
||||
"project:wbs:view", "project:wbs:edit",
|
||||
"budget", "budget:control:view"]},
|
||||
{"code": "business", "name": "商务/市场", "builtin": True, "order": 20,
|
||||
"remark": "本部门项目的立项与预算填报", "scope": ScopeType.UNIT_AND_BELOW,
|
||||
"codes": ["workbench", "workbench:todo", "workbench:done", "workbench:created",
|
||||
"project", "project:project:view", "project:project:create", "project:project:edit",
|
||||
"project:project:delete", "project:estimate:view", "project:estimate:edit", "project:estimate:submit",
|
||||
"project:budget:view", "project:budget:edit", "project:budget:submit",
|
||||
"project:stage:view", "project:stage:edit",
|
||||
"project:milestone:view", "project:milestone:edit",
|
||||
"project:wbs:view", "project:wbs:edit",
|
||||
"budget", "budget:control:view"]},
|
||||
{"code": "finance", "name": "财务", "builtin": True, "order": 30,
|
||||
"remark": "查看全部项目的预算与成本,负责预算审批", "scope": ScopeType.ALL,
|
||||
"codes": ["workbench", "workbench:todo", "workbench:done", "workbench:created",
|
||||
"project", "project:project:view", "project:project:export",
|
||||
"project:estimate:view", "project:budget:view", "project:budget:edit",
|
||||
"budget", "budget:control:view", "budget:control:edit",
|
||||
"project:stage:view", "project:milestone:view", "project:wbs:view",
|
||||
"approval", "approval:monitor:view"]},
|
||||
{"code": "leader", "name": "公司领导", "builtin": True, "order": 40,
|
||||
"remark": "全公司项目概览与流程监控", "scope": ScopeType.ALL,
|
||||
"codes": ["workbench", "workbench:todo", "workbench:done", "workbench:created",
|
||||
"project", "project:project:view", "project:project:export",
|
||||
"project:estimate:view", "project:budget:view",
|
||||
"budget", "budget:control:view",
|
||||
"project:stage:view", "project:milestone:view", "project:wbs:view",
|
||||
"approval", "approval:monitor:view"]},
|
||||
]
|
||||
|
||||
CONFIGS: list[tuple[str, str, str, str, str, str]] = [
|
||||
("budget.contribution_rate_threshold", "贡献利润率阈值(%)", "0", "number", "budget",
|
||||
"低于该阈值时按计算口径里的「贡献利润率不达标时」决定拦截还是仅告警;0 表示不检查"),
|
||||
# 计算口径(含公司管理费用率、差旅业务费限额比例)不在这里,见
|
||||
# app/service/calc/rules.py:默认值与校验规则只在那一份定义里写一次。
|
||||
("project.fixed_manage_items", "固定项目管理费用项",
|
||||
"总部支撑人力费用|人员差旅费|业务费用|商务及专项验收费用|办公费用", "string", "project",
|
||||
"新建预算时自动带入且不可删除的费用项(替代老系统 fourcal.fixedprojectmanagedetails)"),
|
||||
("project.no_prefix", "项目编号前缀", "FS", "string", "project",
|
||||
"立项保存时没填编号就用它生成:前缀 + 年份 + 当年流水号"),
|
||||
# —— 预算控制(超支拦截)。基线取**立项审批通过那一刻**的口径,不按版本滚动上移,
|
||||
# 否则每改一次预算就把基线抬高一次,拦截线跟着被编预算的人走,等于没有拦截。
|
||||
("budget.over_initiation_rate", "预算超立项基线阈值(%)", "5", "number", "budget",
|
||||
"预算的合同额或采购额超过立项批准值这个比例时触发下面的动作;0 表示不检查"),
|
||||
("budget.over_initiation_action", "超基线时的动作", "block", "string", "budget",
|
||||
"block 拦截送审 / warn 只在送审前告警"),
|
||||
]
|
||||
|
||||
|
||||
def seed_all() -> dict[str, int]:
|
||||
with SessionFactory()() as db:
|
||||
created_nodes, new_codes = _seed_nodes(db)
|
||||
# 先补新节点,再做改名/挪父:升级项认的是"还等于老默认值",新种的行本来就是新值,
|
||||
# 顺序反过来也不会出错,但补完再改能一次看清这次版本动了哪些菜单。
|
||||
renamed = _upgrade_catalog(db) + _upgrade_dicts(db) + _upgrade_flows(db)
|
||||
counts = {
|
||||
"nodes": created_nodes,
|
||||
"upgraded": renamed,
|
||||
"roles": _seed_roles(db, new_codes),
|
||||
"configs": _seed_configs(db),
|
||||
"dicts": _seed_dicts(db),
|
||||
"flows": _seed_flows(db),
|
||||
}
|
||||
counts["admin"] = _seed_admin(db)
|
||||
counts["emergency"] = _seed_emergency_admin(db)
|
||||
if settings.seed.demo_data:
|
||||
counts.update(_seed_demo(db))
|
||||
db.commit()
|
||||
return counts
|
||||
|
||||
|
||||
def _seed_dicts(db: Session) -> int:
|
||||
"""把代码里的枚举同步成库里的字典。
|
||||
|
||||
只补缺、不覆盖:界面上改过的取值名不能被一次重启冲回去。想恢复代码默认值,
|
||||
去「系统 → 数据字典」按类点「恢复默认」。
|
||||
"""
|
||||
counts = dict_store.sync(db)
|
||||
return counts["types"] + counts["items"]
|
||||
|
||||
|
||||
def _seed_nodes(db: Session) -> tuple[int, set[str]]:
|
||||
"""种权限目录,并把**这次新建的** code 一起带出去给角色补种用(见 :func:`_seed_roles`)。"""
|
||||
created = 0
|
||||
new_codes: set[str] = set()
|
||||
|
||||
def walk(items: list[Any], parent_id: int, sort_base: int) -> None:
|
||||
nonlocal created
|
||||
for index, (code, name, kind, path, icon, module, children) in enumerate(items):
|
||||
existing = db.execute(select(PermNode).where(PermNode.code == code)).scalars().first()
|
||||
if existing is None:
|
||||
db.add(PermNode(code=code, name=name, kind=kind, parent_id=parent_id, path=path,
|
||||
icon=icon, module=module, sort=sort_base + index * 10))
|
||||
db.flush()
|
||||
created += 1
|
||||
new_codes.add(code)
|
||||
node_id = db.execute(select(PermNode.id).where(PermNode.code == code)).scalar()
|
||||
else:
|
||||
node_id = existing.id
|
||||
if children:
|
||||
walk(children, node_id, 1)
|
||||
|
||||
walk(CATALOG, 0, 1)
|
||||
return created, new_codes
|
||||
|
||||
|
||||
def _seed_roles(db: Session, new_codes: set[str] | None = None) -> int:
|
||||
node_ids = dict(db.execute(select(PermNode.code, PermNode.id)).all())
|
||||
created = 0
|
||||
for spec in ROLES:
|
||||
role = db.execute(select(PermRole).where(PermRole.code == spec["code"])).scalars().first()
|
||||
if role is None:
|
||||
role = PermRole(code=spec["code"], name=spec["name"], builtin=True,
|
||||
order_number=spec["order"], remark=spec["remark"])
|
||||
db.add(role)
|
||||
db.flush()
|
||||
created += 1
|
||||
# 默认数据口径每次启动都校准。它从前排在"这个角色有没有权限节点"的判断后面,
|
||||
# 角色一旦配好权限节点就再也进不来,于是"多一个模块"这类补种永远落不了地:
|
||||
# 内置角色"公司领导"就是在这里少了预算那条,一进预算列表掉进 self 兜底。
|
||||
_seed_role_scope(db, role, spec["scope"])
|
||||
if db.execute(select(func.count(PermRoleNode.id)).where(PermRoleNode.role_id == role.id)
|
||||
).scalar():
|
||||
_grant_new_codes(db, role, spec["codes"], new_codes or set())
|
||||
continue
|
||||
codes = spec["codes"]
|
||||
wanted = "*" in codes
|
||||
for code, node_id in node_ids.items():
|
||||
if wanted or code in codes:
|
||||
db.add(PermRoleNode(role_id=role.id, node_id=node_id))
|
||||
db.flush()
|
||||
return created
|
||||
|
||||
|
||||
def _grant_new_codes(db: Session, role: PermRole, codes: list[str], new_codes: set[str]) -> None:
|
||||
"""给已经配好权限的内置角色补上**本次新增**的权限码。
|
||||
|
||||
``_seed_roles`` 平时"角色一旦有权限节点就不再插手",为的是不覆盖管理员在界面上
|
||||
调过的授权;代价是新加的码永远落不到老库的角色上——"能改不能删"就是这么来的。
|
||||
这里只认本次新建的码:管理员从前主动摘掉的权限不会被这次补回来,内置角色的默认
|
||||
授权又能跟着版本一起长。自定义角色一概不动,那是管理员自己的东西。
|
||||
"""
|
||||
if "*" in codes or not new_codes:
|
||||
return
|
||||
wanted = set(codes) & new_codes
|
||||
if not wanted:
|
||||
return
|
||||
node_ids = dict(db.execute(
|
||||
select(PermNode.code, PermNode.id).where(PermNode.code.in_(wanted))
|
||||
).all())
|
||||
linked = set(db.execute(
|
||||
select(PermNode.code).join(PermRoleNode, PermRoleNode.node_id == PermNode.id)
|
||||
.where(PermRoleNode.role_id == role.id)
|
||||
).scalars().all())
|
||||
for code in wanted - linked:
|
||||
if code in node_ids:
|
||||
db.add(PermRoleNode(role_id=role.id, node_id=node_ids[code]))
|
||||
db.flush()
|
||||
|
||||
|
||||
#: 内置角色的默认数据口径挂在哪个模块上。概算/预算/结算/决算与它在 ``data_scope`` 里
|
||||
#: 属于同一个口径组,一条策略就管住整族,不需要挨个模块再抄一遍。
|
||||
SCOPE_ROOT_MODULE = "project"
|
||||
|
||||
|
||||
def _seed_role_scope(db: Session, role: PermRole, scope: str) -> None:
|
||||
"""给内置角色配**一条**默认数据权限策略,并把从前按模块铺开的重复行收掉。
|
||||
|
||||
一条就够:这一族查的是同一张 Project 表、同一套归属列,族策略管的就是整族。
|
||||
按模块各种一条的写法除了让授权页每个角色长出三四张一模一样的卡片,只剩一个坏处——
|
||||
它随时可能像"公司领导"那样漏掉某个模块,而漏掉的那一侧是静默按 ``self`` 兜底的。
|
||||
"""
|
||||
family = data_scope.policy_covers(SCOPE_ROOT_MODULE)
|
||||
rows = db.execute(
|
||||
select(PermDataPolicy).where(
|
||||
PermDataPolicy.subject_type == SubjectType.ROLE,
|
||||
PermDataPolicy.subject_id == role.id,
|
||||
PermDataPolicy.module.in_(family),
|
||||
PermDataPolicy.is_deleted.is_(False),
|
||||
)
|
||||
).scalars().all()
|
||||
default = next((row for row in rows if row.module == SCOPE_ROOT_MODULE), None)
|
||||
if default is None and not rows:
|
||||
# 整族一条都没有才补默认口径;管理员自己配过就别替他改主意
|
||||
default = PermDataPolicy(
|
||||
name=f"{role.name} · 项目数据", module=SCOPE_ROOT_MODULE,
|
||||
subject_type=SubjectType.ROLE, subject_id=role.id, scope_type=scope,
|
||||
remark="内置角色默认口径(seed),管项目列表及其概算/预算/结算/决算",
|
||||
)
|
||||
db.add(default)
|
||||
db.flush()
|
||||
if default is not None:
|
||||
# 老命名把模块键("超级管理员 - project")直接写进了授权页。只认那一字不差的
|
||||
# 老格式,管理员自己改过的名字一律不动。
|
||||
if default.name == f"{role.name} - {SCOPE_ROOT_MODULE}":
|
||||
default.name = f"{role.name} · 项目数据"
|
||||
default.remark = default.remark or "内置角色默认口径(seed),管项目列表及其概算/预算/结算/决算"
|
||||
_retire_identical_member_policies(db, rows, default)
|
||||
db.flush()
|
||||
|
||||
|
||||
def _retire_identical_member_policies(db: Session, rows: list[PermDataPolicy],
|
||||
keep: PermDataPolicy) -> None:
|
||||
"""把"与族策略逐字段相同、只差 ``module``"的成员模块策略软删掉。
|
||||
|
||||
判定刻意收到逐字段相等:内容不一样的那条是管理员真的想让某个模块宽窄不同,
|
||||
留着,它按"专属策略优先"继续生效;一模一样的几条只是同一个口径抄了三遍。
|
||||
"""
|
||||
def signature(row: PermDataPolicy) -> tuple:
|
||||
return (row.effect, row.scope_type, row.target_ids_json,
|
||||
bool(row.include_children), (row.conditions_json or "").strip(),
|
||||
row.priority, row.valid_from, row.valid_to, bool(row.enabled))
|
||||
|
||||
target = signature(keep)
|
||||
for row in rows:
|
||||
if row.id != keep.id and not row.is_deleted and signature(row) == target:
|
||||
row.is_deleted = True
|
||||
row.remark = f"与「{keep.name}」内容相同,已并入族策略"
|
||||
db.flush()
|
||||
|
||||
|
||||
def _seed_configs(db: Session) -> int:
|
||||
created = _merge_legacy_configs(db)
|
||||
rows = list(CONFIGS) + calc_rules.seed_rows()
|
||||
for code, name, value, value_type, group, remark in rows:
|
||||
if db.execute(select(SystemConfig).where(SystemConfig.code == code)).scalars().first():
|
||||
continue
|
||||
db.add(SystemConfig(code=code, name=name, value=value, value_type=value_type,
|
||||
group=group, remark=remark))
|
||||
created += 1
|
||||
db.flush()
|
||||
return created
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 菜单目录升级:老库里那几行菜单要跟着版本改名/换地址/挪父子,不能只靠"缺了就补"
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: ``code -> 要改成的值``,并且**只在当前值还等于下面这份老默认值时才改**。
|
||||
#: 管理员在「系统 → 菜单与权限码」上自己改过的名字与地址一概不动——那是他们的决定,
|
||||
#: 一次重启就冲回去是最招人恨的那种升级。
|
||||
CATALOG_UPGRADES: dict[str, dict[str, tuple[str, str]]] = {
|
||||
"project:estimate:view": {
|
||||
"name": ("项目立项(概算)", "项目立项"),
|
||||
"path": ("/projects/:id/estimate", "/initiations"),
|
||||
"icon": ("clipboard", "target"),
|
||||
},
|
||||
"project:estimate:edit": {"name": ("编辑概算", "填报立项")},
|
||||
"project:estimate:submit": {"name": ("提交概算审批", "提交立项审批")},
|
||||
"project:budget:view": {
|
||||
"name": ("项目预算", "预算编制"),
|
||||
"path": ("/projects/:id/budget", "/budgets"),
|
||||
},
|
||||
}
|
||||
|
||||
#: 需要换父亲的节点:``code -> (老父 code, 新父 code)``。同样只在"还挂在老父亲下面"时挪。
|
||||
CATALOG_REPARENT: dict[str, tuple[str, str]] = {
|
||||
"project:budget:view": ("project", "budget"),
|
||||
}
|
||||
|
||||
#: 字典的同类升级:``(表, 定位条件, 列, 老值, 新值)``。
|
||||
#: 菜单名与字典名是两套东西——菜单在 ``perm_node``,下拉框取值在 ``dict_*``,
|
||||
#: 只改一边就会出现"菜单叫立项、下拉框还写概算立项"这种半吊子改名。
|
||||
DICT_UPGRADES: list[dict[str, str]] = [
|
||||
{"type": "projectStage", "value": "0", "label": "S0-概算立项", "to_label": "S0-项目立项"},
|
||||
]
|
||||
|
||||
#: 字典分组的改名(``dict_type.group``),按老分组名整批改。
|
||||
DICT_GROUP_UPGRADES: dict[str, str] = {"概算预算": "立项预算"}
|
||||
|
||||
#: 内置审批流程模板的改名(只认老默认名,管理员改过就不动)。
|
||||
FLOW_NAME_UPGRADES: dict[str, tuple[str, str]] = {
|
||||
"estimate_default": ("项目立项(概算)审批", "项目立项审批"),
|
||||
}
|
||||
|
||||
|
||||
def _upgrade_catalog(db: Session) -> int:
|
||||
"""按 :data:`CATALOG_UPGRADES` / :data:`CATALOG_REPARENT` 改那几行菜单。"""
|
||||
changed = 0
|
||||
nodes = {row.code: row for row in db.execute(select(PermNode)).scalars().all()}
|
||||
for code, fields in CATALOG_UPGRADES.items():
|
||||
node = nodes.get(code)
|
||||
if node is None:
|
||||
continue
|
||||
for column, (old_value, new_value) in fields.items():
|
||||
current = getattr(node, column) or ""
|
||||
if current == old_value and old_value != new_value:
|
||||
setattr(node, column, new_value)
|
||||
changed += 1
|
||||
for code, (old_parent, new_parent) in CATALOG_REPARENT.items():
|
||||
node, parent_old, parent_new = nodes.get(code), nodes.get(old_parent), nodes.get(new_parent)
|
||||
if node and parent_old and parent_new and node.parent_id == parent_old.id:
|
||||
node.parent_id = parent_new.id
|
||||
changed += 1
|
||||
db.flush()
|
||||
return changed
|
||||
|
||||
|
||||
def _upgrade_dicts(db: Session) -> int:
|
||||
"""把字典里那几个"系统里不再叫概算"的取值名与分组名换掉。
|
||||
|
||||
``dicts.sync`` 刻意只补不覆盖,所以改名必须单独走这一趟;判定同样是
|
||||
"当前名字还等于老默认值"才改。
|
||||
"""
|
||||
from .models import DictItem, DictType
|
||||
|
||||
changed = 0
|
||||
types = {row.code: row for row in db.execute(select(DictType)).scalars().all()}
|
||||
for old_group, new_group in DICT_GROUP_UPGRADES.items():
|
||||
for row in types.values():
|
||||
if row.group == old_group:
|
||||
row.group = new_group
|
||||
changed += 1
|
||||
for spec in DICT_UPGRADES:
|
||||
parent = types.get(spec["type"])
|
||||
if parent is None or spec["label"] == spec["to_label"]:
|
||||
continue
|
||||
row = db.execute(
|
||||
select(DictItem).where(DictItem.dict_type_id == parent.id,
|
||||
DictItem.value == spec["value"])
|
||||
).scalars().first()
|
||||
if row is not None and row.label == spec["label"]:
|
||||
row.label = spec["to_label"]
|
||||
changed += 1
|
||||
db.flush()
|
||||
if changed:
|
||||
dict_store.invalidate()
|
||||
return changed
|
||||
|
||||
|
||||
def _upgrade_flows(db: Session) -> int:
|
||||
changed = 0
|
||||
for key, (old_name, new_name) in FLOW_NAME_UPGRADES.items():
|
||||
flow = db.execute(select(ApprovalFlow).where(ApprovalFlow.key == key)).scalars().first()
|
||||
if flow is not None and flow.name == old_name:
|
||||
flow.name = new_name
|
||||
changed += 1
|
||||
db.flush()
|
||||
return changed
|
||||
|
||||
|
||||
def _merge_legacy_configs(db: Session) -> int:
|
||||
"""把两条"界面上有、内核从没读过"的重复参数并进 ``calc.*``,然后删掉老的。
|
||||
|
||||
老库里 ``finance.company_manage_fee_rate`` 与 ``budget.travel_business_limit_rate``
|
||||
跟 ``[calc]`` 里的同名规则是一回事,但内核读的是配置文件,界面上改了从不生效。
|
||||
口径整体搬进数据库之后两者只能留一个:留 ``calc.*``,并承认人在界面上存过的值——
|
||||
那本来就是他想让系统用的数。被丢弃的旧值一律写日志,不静默。
|
||||
"""
|
||||
created = 0
|
||||
by_code = {row.code: row for row in db.execute(
|
||||
select(SystemConfig).where(
|
||||
SystemConfig.code.in_([*calc_rules.LEGACY_CODE_ALIASES,
|
||||
*calc_rules.LEGACY_CODE_ALIASES.values()]))).scalars().all()}
|
||||
for legacy_code, target_code in calc_rules.LEGACY_CODE_ALIASES.items():
|
||||
legacy = by_code.get(legacy_code)
|
||||
if legacy is None:
|
||||
continue
|
||||
target = by_code.get(target_code)
|
||||
spec = calc_rules.spec_for(target_code)
|
||||
if target is None:
|
||||
target = SystemConfig(code=target_code, name=spec.name, value=spec.default_text,
|
||||
value_type=spec.value_type, group=calc_rules.RULE_GROUP,
|
||||
editable=True, remark=spec.remark)
|
||||
db.add(target)
|
||||
db.flush()
|
||||
created += 1
|
||||
try:
|
||||
carried = calc_rules.normalize(spec, legacy.value)
|
||||
except ValueError as exc:
|
||||
logger.warning("旧参数 %s 的取值 %r 不合法(%s),合并到 %s 时改用默认 %s",
|
||||
legacy_code, legacy.value, exc, target_code, spec.default_text)
|
||||
carried = spec.default_text
|
||||
if carried == spec.default_text:
|
||||
pass # 旧参数从没被改过,没什么可搬的
|
||||
elif target.value == spec.default_text:
|
||||
target.value = carried
|
||||
logger.info("计算口径 %s 沿用界面上已存的值 %s(原参数 %s 已合并删除)",
|
||||
target_code, carried, legacy_code)
|
||||
else:
|
||||
# 两边都被改过:以新编码上的值为准(口径页上改的那次更晚、也才是内核真正读的),
|
||||
# 但绝不静默丢数——把两条值都写进日志,对不上时能翻出来。
|
||||
logger.warning("计算口径 %s 已是 %s,旧参数 %s 的 %s 不覆盖它;旧参数已删除",
|
||||
target_code, target.value, legacy_code, carried)
|
||||
db.delete(legacy)
|
||||
return created
|
||||
|
||||
|
||||
def _ensure_super_role(db: Session, account: Account) -> None:
|
||||
"""把 ``super_admin`` 角色补回给内置账号(已经挂着就不动)。
|
||||
|
||||
``scripts/clean_demo_data.py`` 是整表清 ``perm_account_role`` 的:账号留着、角色没了。
|
||||
靠 ``is_system_admin`` 权限仍然是全量,但"这个人属于什么角色"在界面、审计和登录返回里
|
||||
都空一块,也看不出 seed 到底跑没跑过。清理脚本与 seed 谁先跑,这个口径都不该破。
|
||||
"""
|
||||
role = db.execute(select(PermRole).where(PermRole.code == "super_admin")).scalars().first()
|
||||
if role is None:
|
||||
return
|
||||
linked = db.execute(
|
||||
select(PermAccountRole).where(PermAccountRole.account_id == account.id,
|
||||
PermAccountRole.role_id == role.id)
|
||||
).scalars().first()
|
||||
if linked is None:
|
||||
db.add(PermAccountRole(account_id=account.id, role_id=role.id))
|
||||
db.flush()
|
||||
|
||||
|
||||
def _seed_admin(db: Session) -> int:
|
||||
account_name = settings.seed.admin_account or "admin"
|
||||
account = db.execute(select(Account).where(Account.account == account_name)).scalars().first()
|
||||
created = account is None
|
||||
if created:
|
||||
password = settings.seed.admin_password or random_password()
|
||||
account = Account(
|
||||
account=account_name,
|
||||
display_name="系统管理员",
|
||||
password_hash=hash_password(password),
|
||||
is_system_admin=True,
|
||||
source=AccountSource.LOCAL,
|
||||
status=Status.ACTIVE,
|
||||
remark="内置超级管理员",
|
||||
)
|
||||
db.add(account)
|
||||
db.flush()
|
||||
_ensure_super_role(db, account)
|
||||
if created and not settings.seed.admin_password:
|
||||
# 没配置文件里给口令时,随机生成并打印一次,界面上第一次登录后应立即修改
|
||||
logger.warning("已创建超级管理员 %s,初始口令(只显示这一次):%s", account_name, password)
|
||||
elif created:
|
||||
logger.info("已创建超级管理员 %s", account_name)
|
||||
return 1 if created else 0
|
||||
|
||||
|
||||
def _seed_emergency_admin(db: Session) -> int:
|
||||
"""本地应急管理员:Hub 配错、应用没登记、整体不可达时的那条独立入口。
|
||||
|
||||
权限与内置超管一样(``is_system_admin`` 等于全量 ``*``),区别只在账号名:超管那个
|
||||
名字常常要让给统一身份里的真人(unisoa 就是这么处理的),应急入口得有个不会被
|
||||
Hub 认领的名字。这条必须留在 seed 里而不是"手动建一个"——清库脚本和重建库都会把它
|
||||
抹掉,而恰恰是清完库进不去门的那一刻最需要它。
|
||||
"""
|
||||
account_name = (settings.seed.emergency_account or "").strip()
|
||||
if not account_name or account_name == (settings.seed.admin_account or "admin"):
|
||||
return 0
|
||||
account = db.execute(select(Account).where(Account.account == account_name)).scalars().first()
|
||||
created = account is None
|
||||
if created:
|
||||
password = settings.seed.emergency_password or random_password()
|
||||
account = Account(
|
||||
account=account_name,
|
||||
display_name="应急管理员",
|
||||
password_hash=hash_password(password),
|
||||
is_system_admin=True,
|
||||
source=AccountSource.LOCAL,
|
||||
status=Status.ACTIVE,
|
||||
remark="本地应急入口:Hub 配错或整体不可达时用,口令只在本系统校验",
|
||||
)
|
||||
db.add(account)
|
||||
db.flush()
|
||||
_ensure_super_role(db, account)
|
||||
if created and not settings.seed.emergency_password:
|
||||
# 没配口令就随机生成,只在启动日志里出现一次,第一次登录后立即改掉
|
||||
logger.warning("已创建应急管理员 %s,初始口令(只显示这一次):%s", account_name, password)
|
||||
elif created:
|
||||
logger.info("已创建应急管理员 %s", account_name)
|
||||
return 1 if created else 0
|
||||
|
||||
|
||||
FLOW_TEMPLATES = [
|
||||
{
|
||||
"key": "estimate_default", "name": "项目立项(概算)审批", "module": "estimate",
|
||||
"nodes": [
|
||||
("dept_leader", "部门负责人审批", "org_manager", "any", 10),
|
||||
("finance", "财务审核", "role:finance", "any", 20),
|
||||
],
|
||||
},
|
||||
{
|
||||
"key": "budget_default", "name": "项目预算审批", "module": "budget",
|
||||
"nodes": [
|
||||
("dept_leader", "部门负责人审批", "org_manager", "any", 10),
|
||||
("finance", "财务审核", "role:finance", "any", 20),
|
||||
("leader", "分管领导审批", "org_manager_chain:2", "any", 30),
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def _seed_flows(db: Session) -> int:
|
||||
created = 0
|
||||
role_ids = dict(db.execute(select(PermRole.code, PermRole.id)).all())
|
||||
for template in FLOW_TEMPLATES:
|
||||
if db.execute(select(ApprovalFlow).where(ApprovalFlow.key == template["key"])).scalars().first():
|
||||
continue
|
||||
flow = ApprovalFlow(key=template["key"], name=template["name"],
|
||||
business_module=template["module"], status="draft",
|
||||
remark="系统内置模板,请按需调整节点与审批人后发布")
|
||||
db.add(flow)
|
||||
db.flush()
|
||||
for node_key, name, candidate, sign, order in template["nodes"]:
|
||||
db.add(ApprovalNode(
|
||||
flow_id=flow.id, node_key=node_key, name=name, node_type="approve",
|
||||
order_number=order, sign_type=sign,
|
||||
candidates_json=_candidates(candidate, role_ids),
|
||||
empty_strategy="admin", reject_to="initiator",
|
||||
))
|
||||
db.flush()
|
||||
if not flow_service.definition_errors(flow):
|
||||
flow.status = "published"
|
||||
created += 1
|
||||
db.flush()
|
||||
return created
|
||||
|
||||
|
||||
def _candidates(spec: str, role_ids: dict[str, int]) -> str:
|
||||
import json
|
||||
|
||||
kind, _, value = spec.partition(":")
|
||||
if kind == "role":
|
||||
return json.dumps([{"type": "role", "ids": [role_ids.get(value, 0)]}])
|
||||
if kind == "org_manager_chain":
|
||||
return json.dumps([{"type": "org_manager_chain", "levels": int(value or 1)}])
|
||||
return json.dumps([{"type": kind}])
|
||||
|
||||
|
||||
def _seed_demo(db: Session) -> dict[str, int]:
|
||||
"""演示组织与账号。生产档不会走到这里。"""
|
||||
if db.execute(select(func.count(OrgUnit.id))).scalar():
|
||||
return {"demo": 0}
|
||||
root = OrgUnit(name="紫光数字经济科技园项目部", code="root", status=Status.ACTIVE)
|
||||
db.add(root)
|
||||
db.flush()
|
||||
root.path, root.level = f"/{root.id}/", 1
|
||||
children = []
|
||||
for name, code in (("市场部", "biz"), ("工程管理部", "eng"), ("财务部", "fin")):
|
||||
unit = OrgUnit(name=name, code=code, parent_id=root.id, status=Status.ACTIVE)
|
||||
db.add(unit)
|
||||
db.flush()
|
||||
unit.path, unit.level = f"{root.path}{unit.id}/", 2
|
||||
children.append(unit)
|
||||
|
||||
positions = []
|
||||
for code, name, rank in (("manager", "部门负责人", 10), ("engineer", "工程师", 60),
|
||||
("accountant", "会计", 60), ("sales", "商务", 60)):
|
||||
row = Position(code=code, name=name, rank=rank)
|
||||
db.add(row)
|
||||
positions.append(row)
|
||||
db.flush()
|
||||
|
||||
admin = db.execute(select(Account).where(Account.account == (settings.seed.admin_account or "admin"))
|
||||
).scalars().first()
|
||||
roles = dict(db.execute(select(PermRole.code, PermRole.id)).all())
|
||||
password = settings.seed.admin_password or "Demo@12345"
|
||||
for index, (account_name, display, unit, position_code, role_code) in enumerate([
|
||||
("zhangsan", "张三", children[0], "sales", "business"),
|
||||
("lisi", "李四", children[1], "engineer", "project_owner"),
|
||||
("wangwu", "王五", children[2], "accountant", "finance"),
|
||||
]):
|
||||
person = Account(account=account_name, display_name=display,
|
||||
password_hash=hash_password(password), org_unit_id=unit.id,
|
||||
source=AccountSource.LOCAL, status=Status.ACTIVE,
|
||||
leader_id=admin.id if admin else None,
|
||||
position_id=next((p.id for p in positions if p.code == position_code), None))
|
||||
db.add(person)
|
||||
db.flush()
|
||||
db.add(AccountIdentity(account_id=person.id, org_unit_id=unit.id, is_default=True))
|
||||
role_id = roles.get(role_code)
|
||||
if role_id:
|
||||
db.add(PermAccountRole(account_id=person.id, role_id=role_id))
|
||||
if admin:
|
||||
admin.org_unit_id = root.id
|
||||
db.add(AccountIdentity(account_id=admin.id, org_unit_id=root.id, is_default=True))
|
||||
for unit, person_name in ((children[0], "zhangsan"), (children[1], "lisi"), (children[2], "wangwu")):
|
||||
person = db.execute(select(Account).where(Account.account == person_name)).scalars().first()
|
||||
if person:
|
||||
unit.manager_id = person.id
|
||||
db.flush()
|
||||
logger.info("已种入演示组织与账号(初始口令与配置中的超管口令一致)")
|
||||
return {"demo": 1}
|
||||
|
|
@ -0,0 +1 @@
|
|||
"""服务层。"""
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
"""审批:候选人解析、流程匹配、流转状态机。"""
|
||||
|
||||
from . import candidates, engine, flow # noqa: F401
|
||||
|
||||
__all__ = ["candidates", "engine", "flow"]
|
||||
|
|
@ -0,0 +1,269 @@
|
|||
"""审批人解析:把节点上的候选人配置翻成具体的人。
|
||||
|
||||
老系统的 ``act_task_def`` 用三个逗号分隔字符串(``candidate_users`` /
|
||||
``candidate_roles`` / ``candidate_types``)表达同一件事,还要靠 ``ActCandidateTypeEnum``
|
||||
去猜第三列里写的是什么。这里换成 JSON 数组,每项一个来源,可以多来源并存(例如
|
||||
"财务角色 或 指定的两个人")。
|
||||
|
||||
找不到人时的处理必须显式配置(节点的 ``empty_strategy``):报错卡住、跳过节点、
|
||||
还是转给系统管理员。老系统没有这个开关,节点解析为空时流程会静静卡死,
|
||||
业务方只能找运维查库。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ...models import (
|
||||
Account,
|
||||
AccountIdentity,
|
||||
ApprovalNode,
|
||||
CandidateType,
|
||||
OrgUnit,
|
||||
PermAccountRole,
|
||||
Position,
|
||||
Project,
|
||||
Status,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Resolved:
|
||||
accounts: list[Account] = field(default_factory=list)
|
||||
notes: list[str] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def ids(self) -> list[int]:
|
||||
return [item.id for item in self.accounts]
|
||||
|
||||
@property
|
||||
def names(self) -> list[str]:
|
||||
return [item.display_name or item.account for item in self.accounts]
|
||||
|
||||
|
||||
def parse_config(raw: str) -> list[dict[str, Any]]:
|
||||
try:
|
||||
data = json.loads(raw or "[]")
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
if isinstance(data, dict):
|
||||
return [data]
|
||||
return [item for item in data if isinstance(item, dict)]
|
||||
|
||||
|
||||
def resolve(
|
||||
db: Session,
|
||||
node: ApprovalNode,
|
||||
*,
|
||||
submitter_id: int,
|
||||
project: Project | None = None,
|
||||
variables: dict[str, Any] | None = None,
|
||||
previous_assignees: list[int] | None = None,
|
||||
) -> Resolved:
|
||||
"""按节点配置找人,去重、剔除停用账号、按岗位级别排序。"""
|
||||
variables = variables or {}
|
||||
collected: dict[int, Account] = {}
|
||||
notes: list[str] = []
|
||||
|
||||
for item in parse_config(node.candidates_json):
|
||||
kind = str(item.get("type") or "")
|
||||
found = _resolve_one(db, kind, item, submitter_id=submitter_id, project=project,
|
||||
variables=variables, previous_assignees=previous_assignees or [], notes=notes)
|
||||
for account in found:
|
||||
collected[account.id] = account
|
||||
|
||||
# 委托人:某人休假期间把待办整体交给别人
|
||||
collected = _apply_delegates(db, collected, notes)
|
||||
|
||||
if not collected:
|
||||
return Resolved([], notes)
|
||||
|
||||
ordered = sorted(collected.values(), key=lambda item: (item.display_name or "", item.id))
|
||||
return Resolved(ordered, notes)
|
||||
|
||||
|
||||
def _resolve_one(
|
||||
db: Session,
|
||||
kind: str,
|
||||
config: dict[str, Any],
|
||||
*,
|
||||
submitter_id: int,
|
||||
project: Project | None,
|
||||
variables: dict[str, Any],
|
||||
previous_assignees: list[int],
|
||||
notes: list[str],
|
||||
) -> list[Account]:
|
||||
if kind == CandidateType.FIXED:
|
||||
return _active(db, _ids(config))
|
||||
if kind == CandidateType.ROLE:
|
||||
rows = db.execute(
|
||||
select(Account).join(PermAccountRole, PermAccountRole.account_id == Account.id)
|
||||
.where(PermAccountRole.role_id.in_(_ids(config)), Account.is_deleted.is_(False),
|
||||
Account.status == Status.ACTIVE)
|
||||
.distinct()
|
||||
).scalars().all()
|
||||
return list(rows)
|
||||
if kind == CandidateType.POSITION:
|
||||
return _active_ids(db, select(Account.id).where(Account.position_id.in_(_ids(config))))
|
||||
if kind == CandidateType.ORG_MANAGER:
|
||||
unit_id = _submitter_unit_id(db, submitter_id)
|
||||
unit = db.get(OrgUnit, unit_id) if unit_id else None
|
||||
if unit is None or not unit.manager_id:
|
||||
notes.append(f"节点「{node_or(config)}」找不到部门负责人")
|
||||
return []
|
||||
return _active(db, [unit.manager_id])
|
||||
if kind == CandidateType.ORG_MANAGER_CHAIN:
|
||||
levels = int(config.get("levels") or 1)
|
||||
return _managers_upwards(db, submitter_id, levels)
|
||||
if kind == CandidateType.DIRECT_LEADER:
|
||||
account = db.get(Account, submitter_id)
|
||||
if account is None or not account.leader_id:
|
||||
notes.append("发起人没有配置直属上级")
|
||||
return []
|
||||
return _active(db, [account.leader_id])
|
||||
if kind == CandidateType.PROJECT_OWNER:
|
||||
if project is None or not project.principal_id:
|
||||
notes.append("项目没有负责人")
|
||||
return []
|
||||
return _active(db, [project.principal_id])
|
||||
if kind == CandidateType.PREVIOUS_ASSIGNEE:
|
||||
return _active(db, previous_assignees)
|
||||
if kind == CandidateType.FORM_FIELD:
|
||||
key = str(config.get("field") or "")
|
||||
value = variables.get(key)
|
||||
ids = value if isinstance(value, list) else ([value] if value else [])
|
||||
return _active(db, [int(item) for item in ids if str(item).strip().isdigit()])
|
||||
if kind == CandidateType.EXPRESSION:
|
||||
return _from_expression(db, config, submitter_id=submitter_id, project=project,
|
||||
variables=variables, notes=notes)
|
||||
notes.append(f"未知的候选人来源类型:{kind or '(空)'}")
|
||||
return []
|
||||
|
||||
|
||||
def node_or(config: dict[str, Any]) -> str:
|
||||
return str(config.get("node") or "当前")
|
||||
|
||||
|
||||
def _from_expression(
|
||||
db: Session,
|
||||
config: dict[str, Any],
|
||||
*,
|
||||
submitter_id: int,
|
||||
project: Project | None,
|
||||
variables: dict[str, Any],
|
||||
notes: list[str],
|
||||
) -> list[Account]:
|
||||
"""表达式来源。刻意不做 eval,只支持有限的几种"按变量找人"。
|
||||
|
||||
``{"type":"expression","if":"contract_amount>=5000000","then_type":"role","then_ids":[3]}``
|
||||
这类规则用条件 + 转发的组合就能覆盖,比让流程管理员写 Python 表达式安全得多。
|
||||
"""
|
||||
from .flow import evaluate_simple_condition
|
||||
|
||||
condition = str(config.get("if") or "")
|
||||
if condition and not evaluate_simple_condition(condition, variables):
|
||||
return []
|
||||
forwarded = dict(config)
|
||||
forwarded["type"] = str(config.get("then_type") or "")
|
||||
forwarded["ids"] = config.get("then_ids") or []
|
||||
return _resolve_one(db, forwarded["type"], forwarded, submitter_id=submitter_id, project=project,
|
||||
variables=variables, previous_assignees=[], notes=notes)
|
||||
|
||||
|
||||
def _managers_upwards(db: Session, submitter_id: int, levels: int) -> list[Account]:
|
||||
"""沿组织树向上取 ``levels`` 级负责人,跳过空级但计入层级消耗。"""
|
||||
unit_id = _submitter_unit_id(db, submitter_id)
|
||||
picked: list[int] = []
|
||||
seen: set[int] = set()
|
||||
remaining = max(levels, 1)
|
||||
while unit_id and unit_id not in seen and remaining > 0:
|
||||
seen.add(unit_id)
|
||||
unit = db.get(OrgUnit, unit_id)
|
||||
if unit is None:
|
||||
break
|
||||
if unit.manager_id:
|
||||
picked.append(unit.manager_id)
|
||||
unit_id = unit.parent_id
|
||||
remaining -= 1
|
||||
return _active(db, picked)
|
||||
|
||||
|
||||
def _submitter_unit_id(db: Session, account_id: int) -> int | None:
|
||||
row = db.execute(
|
||||
select(AccountIdentity.org_unit_id)
|
||||
.where(AccountIdentity.account_id == account_id)
|
||||
.order_by(AccountIdentity.is_default.desc(), AccountIdentity.id)
|
||||
).scalars().first()
|
||||
if row:
|
||||
return row
|
||||
account = db.get(Account, account_id)
|
||||
return account.org_unit_id if account else None
|
||||
|
||||
|
||||
def _apply_delegates(db: Session, collected: dict[int, Account], notes: list[str]) -> dict[int, Account]:
|
||||
from datetime import datetime
|
||||
|
||||
from ...models import ApprovalDelegate
|
||||
|
||||
if not collected:
|
||||
return collected
|
||||
now = datetime.now()
|
||||
rows = db.execute(
|
||||
select(ApprovalDelegate).where(
|
||||
ApprovalDelegate.from_id.in_(list(collected.keys())),
|
||||
ApprovalDelegate.enabled.is_(True),
|
||||
ApprovalDelegate.is_deleted.is_(False),
|
||||
)
|
||||
).scalars().all()
|
||||
replacements: dict[int, int] = {}
|
||||
for row in rows:
|
||||
if row.valid_from and row.valid_from > now:
|
||||
continue
|
||||
if row.valid_to and row.valid_to < now:
|
||||
continue
|
||||
replacements[row.from_id] = row.to_id
|
||||
if not replacements:
|
||||
return collected
|
||||
|
||||
out = dict(collected)
|
||||
targets = _active(db, list(set(replacements.values())))
|
||||
by_id = {item.id: item for item in targets}
|
||||
for source, target in replacements.items():
|
||||
account = out.pop(source, None)
|
||||
replacement = by_id.get(target)
|
||||
if account and replacement:
|
||||
notes.append(f"{account.display_name or account.account} 的待办已委托给 "
|
||||
f"{replacement.display_name or replacement.account}")
|
||||
out[replacement.id] = replacement
|
||||
elif account:
|
||||
out[source] = account # 委托人失效就回到本人,不能把待办弄丢
|
||||
return out
|
||||
|
||||
|
||||
def _active(db: Session, ids: list[int]) -> list[Account]:
|
||||
ids = [int(item) for item in ids or [] if str(item).strip().isdigit()]
|
||||
if not ids:
|
||||
return []
|
||||
rows = db.execute(
|
||||
select(Account).where(Account.id.in_(ids), Account.is_deleted.is_(False),
|
||||
Account.status == Status.ACTIVE)
|
||||
).scalars().all()
|
||||
order = {account_id: index for index, account_id in enumerate(ids)}
|
||||
return sorted(rows, key=lambda item: order.get(item.id, 999))
|
||||
|
||||
|
||||
def _active_ids(db: Session, statement: Any) -> list[Account]:
|
||||
ids = list(db.execute(statement).scalars().all())
|
||||
return _active(db, ids)
|
||||
|
||||
|
||||
def _ids(config: dict[str, Any]) -> list[int]:
|
||||
raw = config.get("ids") or config.get("id") or []
|
||||
if isinstance(raw, (str, int)):
|
||||
raw = [raw]
|
||||
return [int(item) for item in raw if str(item).strip().isdigit()]
|
||||
|
|
@ -0,0 +1,643 @@
|
|||
"""审批流转状态机。
|
||||
|
||||
覆盖老系统的或签/会签/退回/审批意见,并补上业务上一直接受不了但老系统没有的行为:
|
||||
依次审批、加签、转办、撤回、同一审批人自动跳过、超时提醒。
|
||||
|
||||
一条铁律:**审批看的是送审时冻结的那一版数据**(``revision_id`` + ``snapshot_id``),
|
||||
发起人之后怎么改草稿都不影响正在跑的审批。老系统靠"提交时把 temp 表搬到正式表"
|
||||
间接实现了这件事,但代价是草稿和正式共用一套表名、两套查询。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select, update
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ...envelope import ApiError
|
||||
from ...models import (
|
||||
Action,
|
||||
ApprovalFlow,
|
||||
ApprovalInstance,
|
||||
ApprovalNode,
|
||||
ApprovalRecord,
|
||||
ApprovalTask,
|
||||
FlowStatus,
|
||||
InstanceStatus,
|
||||
NodeType,
|
||||
Project,
|
||||
Revision,
|
||||
RevisionStatus,
|
||||
SignType,
|
||||
TaskStatus,
|
||||
)
|
||||
from . import candidates as candidate_resolver
|
||||
from .flow import match_flow, node_condition_passes, ordered_nodes
|
||||
|
||||
|
||||
class ApprovalError(ApiError):
|
||||
def __init__(self, code: str, message: str) -> None:
|
||||
super().__init__(code, message, http_status=400)
|
||||
|
||||
|
||||
def submit(
|
||||
db: Session,
|
||||
*,
|
||||
module: str,
|
||||
project: Project,
|
||||
revision: Revision,
|
||||
snapshot_id: int | None,
|
||||
submitter: Any,
|
||||
variables: dict[str, Any] | None = None,
|
||||
comment: str = "",
|
||||
previous_instance_id: int | None = None,
|
||||
self_selected: dict[str, list[int]] | None = None,
|
||||
) -> ApprovalInstance:
|
||||
"""发起一次审批。找不到匹配流程时直接报错,不允许"静默通过"。"""
|
||||
payload = dict(variables or {})
|
||||
payload.setdefault("project_id", project.id)
|
||||
payload.setdefault("project_type", project.type)
|
||||
payload.setdefault("underwritten_mode", project.underwritten_mode)
|
||||
payload.setdefault("submitter_id", submitter.id)
|
||||
payload.setdefault("org_unit_id", project.org_unit_id or submitter.org_unit_id)
|
||||
|
||||
flow = match_flow(db, module, payload)
|
||||
if flow is None:
|
||||
raise ApprovalError(
|
||||
"flow_not_matched",
|
||||
"没有找到匹配的审批流程,请联系管理员在「审批流程配置」中为该业务发布一条流程",
|
||||
)
|
||||
if flow.status != FlowStatus.PUBLISHED:
|
||||
raise ApprovalError("flow_not_published", f"流程「{flow.name}」尚未发布")
|
||||
|
||||
nodes = ordered_nodes(flow)
|
||||
if not nodes:
|
||||
raise ApprovalError("flow_empty", f"流程「{flow.name}」没有可用节点")
|
||||
|
||||
instance = ApprovalInstance(
|
||||
flow_id=flow.id,
|
||||
flow_key=flow.key,
|
||||
flow_name=flow.name,
|
||||
flow_version=flow.version,
|
||||
business_module=module,
|
||||
project_id=project.id,
|
||||
project_name=project.name,
|
||||
revision_id=revision.id,
|
||||
snapshot_id=snapshot_id,
|
||||
status=InstanceStatus.REVIEWING,
|
||||
submitter_id=submitter.id,
|
||||
submitter_name=submitter.display_name or submitter.account,
|
||||
submitter_org_id=submitter.org_unit_id,
|
||||
variables_json=json.dumps(payload, ensure_ascii=False),
|
||||
runtime_json=json.dumps({"completed": [], "selected": self_selected or {}}),
|
||||
previous_instance_id=previous_instance_id,
|
||||
)
|
||||
db.add(instance)
|
||||
db.flush()
|
||||
|
||||
_record(db, instance, node_key="", node_name="", action=Action.SUBMIT,
|
||||
operator=submitter, comment=comment)
|
||||
|
||||
revision.status = RevisionStatus.REVIEWING
|
||||
revision.submitted_at = datetime.now()
|
||||
|
||||
_advance(db, instance, submitter.id, start_from_order=-1)
|
||||
db.flush()
|
||||
return instance
|
||||
|
||||
|
||||
def pending_tasks(db: Session, account_id: int, *, module: str | None = None) -> list[ApprovalTask]:
|
||||
statement = (
|
||||
select(ApprovalTask)
|
||||
.join(ApprovalInstance, ApprovalInstance.id == ApprovalTask.instance_id)
|
||||
.where(ApprovalTask.assignee_id == account_id, ApprovalTask.status == TaskStatus.PENDING,
|
||||
ApprovalInstance.status == InstanceStatus.REVIEWING)
|
||||
)
|
||||
if module:
|
||||
statement = statement.where(ApprovalInstance.business_module == module)
|
||||
return list(db.execute(statement.order_by(ApprovalTask.id.desc())).scalars().all())
|
||||
|
||||
|
||||
def act(
|
||||
db: Session,
|
||||
*,
|
||||
task: ApprovalTask,
|
||||
actor: Any,
|
||||
action: str,
|
||||
comment: str = "",
|
||||
target_ids: list[int] | None = None,
|
||||
rollback_to: str = "",
|
||||
) -> ApprovalInstance:
|
||||
"""处理一条待办。"""
|
||||
instance = db.get(ApprovalInstance, task.instance_id)
|
||||
if instance is None:
|
||||
raise ApprovalError("instance_missing", "审批实例不存在")
|
||||
if instance.status != InstanceStatus.REVIEWING:
|
||||
raise ApprovalError("instance_closed", "该审批已经结束,无法再操作")
|
||||
if task.status != TaskStatus.PENDING:
|
||||
raise ApprovalError("task_handled", "这条待办已经被处理过了")
|
||||
if task.assignee_id != actor.id:
|
||||
raise ApprovalError("not_assignee", "这条待办不属于你")
|
||||
|
||||
node = _node_of(db, instance, task.node_key)
|
||||
if action in (Action.REJECT, Action.ROLLBACK) and node.reject_comment_required and not comment.strip():
|
||||
raise ApprovalError("comment_required", "审批不通过时必须填写审批意见")
|
||||
if action == Action.APPROVE and node.comment_required and not comment.strip():
|
||||
raise ApprovalError("comment_required", "该节点要求填写审批意见")
|
||||
|
||||
if action == Action.APPROVE:
|
||||
return _approve(db, instance, task, node, actor, comment)
|
||||
if action == Action.REJECT:
|
||||
return _reject(db, instance, task, node, actor, comment)
|
||||
if action == Action.ROLLBACK:
|
||||
return _rollback(db, instance, task, node, actor, comment, rollback_to)
|
||||
if action == Action.TRANSFER:
|
||||
return _transfer(db, instance, task, node, actor, comment, target_ids or [])
|
||||
if action == Action.ADD_SIGN:
|
||||
return _add_sign(db, instance, task, node, actor, comment, target_ids or [])
|
||||
if action == Action.REMIND:
|
||||
_record(db, instance, node_key=node.node_key, node_name=node.name, action=Action.REMIND,
|
||||
operator=actor, comment=comment, target_names=_names(db, [task.assignee_id]))
|
||||
db.flush()
|
||||
return instance
|
||||
raise ApprovalError("unsupported_action", f"不支持的审批动作:{action}")
|
||||
|
||||
|
||||
def withdraw(db: Session, *, instance: ApprovalInstance, actor: Any, comment: str = "") -> ApprovalInstance:
|
||||
"""撤回:只有还没任何人处理过时才允许,避免把已经表过态的审批抹掉。"""
|
||||
if instance.status != InstanceStatus.REVIEWING:
|
||||
raise ApprovalError("instance_closed", "审批已结束,无法撤回")
|
||||
if instance.submitter_id != actor.id:
|
||||
raise ApprovalError("not_submitter", "只有发起人可以撤回")
|
||||
acted = db.execute(
|
||||
select(ApprovalTask.id).where(
|
||||
ApprovalTask.instance_id == instance.id,
|
||||
ApprovalTask.status.in_([TaskStatus.DONE, TaskStatus.TRANSFERRED]),
|
||||
).limit(1)
|
||||
).scalar()
|
||||
if acted:
|
||||
raise ApprovalError("already_handled", "已有人处理,不能撤回,请联系当前审批人退回")
|
||||
|
||||
_cancel_pending(db, instance.id)
|
||||
instance.status = InstanceStatus.WITHDRAWN
|
||||
instance.finished_at = datetime.now()
|
||||
_record(db, instance, node_key=instance.current_node_key, node_name=instance.current_node_name,
|
||||
action=Action.WITHDRAW, operator=actor, comment=comment)
|
||||
_release_revision(db, instance, RevisionStatus.WITHDRAWN)
|
||||
db.flush()
|
||||
return instance
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 内部:节点推进
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _approve(db: Session, instance: ApprovalInstance, task: ApprovalTask, node: ApprovalNode,
|
||||
actor: Any, comment: str) -> ApprovalInstance:
|
||||
task.status = TaskStatus.DONE
|
||||
task.action = Action.APPROVE
|
||||
task.comment = comment
|
||||
task.acted_at = datetime.now()
|
||||
_record(db, instance, node_key=node.node_key, node_name=node.name, action=Action.APPROVE,
|
||||
operator=actor, comment=comment)
|
||||
|
||||
runtime = _runtime(instance)
|
||||
if actor is not None:
|
||||
runtime["completed_assignees"] = sorted(
|
||||
set(runtime.get("completed_assignees", [])) | {int(actor.id)}
|
||||
)
|
||||
|
||||
if node.sign_type == SignType.ANY:
|
||||
_cancel_siblings(db, instance.id, node.node_key, keep_id=task.id)
|
||||
return _finish_node(db, instance, node, runtime)
|
||||
|
||||
remaining = db.execute(
|
||||
select(ApprovalTask.id).where(
|
||||
ApprovalTask.instance_id == instance.id,
|
||||
ApprovalTask.node_key == node.node_key,
|
||||
ApprovalTask.status == TaskStatus.PENDING,
|
||||
)
|
||||
).scalars().all()
|
||||
|
||||
if remaining:
|
||||
_save_runtime(instance, runtime)
|
||||
db.flush()
|
||||
return instance
|
||||
return _finish_node(db, instance, node, runtime)
|
||||
|
||||
|
||||
def _finish_node(db: Session, instance: ApprovalInstance, node: ApprovalNode,
|
||||
runtime: dict[str, Any]) -> ApprovalInstance:
|
||||
"""节点通过后的去向:显式 next 优先,否则按 order 往后走。"""
|
||||
completed = set(runtime.get("completed", []))
|
||||
completed.add(node.node_key)
|
||||
runtime["completed"] = sorted(completed)
|
||||
runtime["completed_assignees"] = runtime.get("completed_assignees", [])
|
||||
_save_runtime(instance, runtime)
|
||||
|
||||
nodes = ordered_nodes(db.get(ApprovalFlow, instance.flow_id))
|
||||
if node.next_node_key:
|
||||
target = next((item for item in nodes if item.node_key == node.next_node_key), None)
|
||||
if target is None:
|
||||
raise ApprovalError("flow_broken", f"节点「{node.name}」的去向不存在")
|
||||
order_before = target.order_number - 1
|
||||
else:
|
||||
order_before = node.order_number
|
||||
|
||||
return _advance(db, instance, instance.submitter_id, start_from_order=order_before,
|
||||
skip_keys=completed)
|
||||
|
||||
|
||||
def _advance(db: Session, instance: ApprovalInstance, submitter_id: int, *, start_from_order: int,
|
||||
skip_keys: set[str] | None = None) -> ApprovalInstance:
|
||||
"""从 ``start_from_order`` 之后找第一个需要人处理的节点并派任务。
|
||||
|
||||
条件不成立的节点直接跳过并留痕;抄送节点只记流水不阻塞。
|
||||
"""
|
||||
flow = db.get(ApprovalFlow, instance.flow_id)
|
||||
nodes = ordered_nodes(flow)
|
||||
variables = json.loads(instance.variables_json or "{}")
|
||||
runtime = _runtime(instance)
|
||||
skip_keys = set(skip_keys or runtime.get("completed", []))
|
||||
project = db.get(Project, instance.project_id)
|
||||
|
||||
for node in nodes:
|
||||
if node.order_number <= start_from_order:
|
||||
continue
|
||||
if node.node_type == NodeType.END:
|
||||
break
|
||||
if node.node_key in skip_keys:
|
||||
continue
|
||||
if not node_condition_passes(node, variables):
|
||||
_record(db, instance, node_key=node.node_key, node_name=node.name, action=Action.AUTO_SKIP,
|
||||
operator_id=submitter_id, operator_name="系统", comment="条件不满足,自动跳过该节点")
|
||||
continue
|
||||
if node.node_type == NodeType.CC:
|
||||
_record(db, instance, node_key=node.node_key, node_name=node.name, action=Action.CC,
|
||||
operator_id=submitter_id, operator_name="系统", comment="抄送")
|
||||
continue
|
||||
|
||||
resolved = candidate_resolver.resolve(
|
||||
db, node,
|
||||
submitter_id=submitter_id,
|
||||
project=project,
|
||||
variables=variables,
|
||||
previous_assignees=runtime.get("completed_assignees", []),
|
||||
)
|
||||
picked = resolved.ids
|
||||
selected = (runtime.get("selected") or {}).get(node.node_key)
|
||||
if selected:
|
||||
allowed = set(selected)
|
||||
picked = [item for item in picked if item in allowed] or list(allowed)
|
||||
|
||||
if flow.auto_skip_duplicate and picked:
|
||||
already = set(runtime.get("completed_assignees", []))
|
||||
overlapping = [item for item in picked if item in already]
|
||||
if overlapping and len(overlapping) == len(picked) and node.sign_type != SignType.ALL:
|
||||
_record(db, instance, node_key=node.node_key, node_name=node.name, action=Action.AUTO_SKIP,
|
||||
operator_id=submitter_id, operator_name="系统",
|
||||
comment="审批人与前序节点相同,自动跳过:" + "、".join(resolved.names))
|
||||
skip_keys.add(node.node_key)
|
||||
continue
|
||||
picked = [item for item in picked if item not in already] or picked
|
||||
|
||||
if not picked:
|
||||
if node.empty_strategy == "skip":
|
||||
_record(db, instance, node_key=node.node_key, node_name=node.name, action=Action.AUTO_SKIP,
|
||||
operator_id=submitter_id, operator_name="系统",
|
||||
comment="未解析到审批人,按节点配置跳过" + (";" + ";".join(resolved.notes) if resolved.notes else ""))
|
||||
continue
|
||||
if node.empty_strategy == "admin":
|
||||
admin = _fallback_admin(db)
|
||||
if admin:
|
||||
picked = [admin.id]
|
||||
# 必须把兜底人放回 resolved,否则 _create_tasks 取不到姓名,
|
||||
# 待办列表和流程详情上会显示成"未指派"
|
||||
if admin not in resolved.accounts:
|
||||
resolved.accounts.append(admin)
|
||||
resolved.notes.append(f"已转交系统管理员 {admin.display_name or admin.account}")
|
||||
if not picked:
|
||||
raise ApprovalError(
|
||||
"no_candidate",
|
||||
f"节点「{node.name}」没有找到审批人"
|
||||
+ (":" + ";".join(resolved.notes) if resolved.notes else ""),
|
||||
)
|
||||
|
||||
instance.current_node_key = node.node_key
|
||||
instance.current_node_name = node.name
|
||||
created = _create_tasks(db, instance, node, resolved, picked, submitter_id)
|
||||
if created == 0:
|
||||
skip_keys.add(node.node_key)
|
||||
continue
|
||||
runtime["completed"] = sorted(set(runtime.get("completed", [])))
|
||||
_save_runtime(instance, runtime)
|
||||
db.flush()
|
||||
return instance
|
||||
|
||||
return _finish(db, instance, InstanceStatus.APPROVED)
|
||||
|
||||
|
||||
def _create_tasks(db: Session, instance: ApprovalInstance, node: ApprovalNode,
|
||||
resolved: candidate_resolver.Resolved, picked: list[int], submitter_id: int) -> int:
|
||||
"""按空签方式建待办。依次审批只建第一个人。"""
|
||||
names = {account.id: (account.display_name or account.account) for account in resolved.accounts}
|
||||
due = datetime.now() + timedelta(hours=node.timeout_hours) if node.timeout_hours else None
|
||||
if node.sign_type == SignType.ORDER:
|
||||
first = picked[0]
|
||||
db.add(ApprovalTask(
|
||||
instance_id=instance.id, node_key=node.node_key, node_name=node.name,
|
||||
sign_type=node.sign_type, assignee_id=first, assignee_name=names.get(first, ""),
|
||||
order_in_node=1, due_at=due,
|
||||
))
|
||||
runtime = _runtime(instance)
|
||||
runtime["order_cursor"] = {node.node_key: 1, **runtime.get("order_cursor", {})}
|
||||
runtime["order_queue"] = {node.node_key: picked, **runtime.get("order_queue", {})}
|
||||
_save_runtime(instance, runtime)
|
||||
return 1
|
||||
|
||||
for index, account_id in enumerate(picked):
|
||||
db.add(ApprovalTask(
|
||||
instance_id=instance.id, node_key=node.node_key, node_name=node.name,
|
||||
sign_type=node.sign_type, assignee_id=account_id, assignee_name=names.get(account_id, ""),
|
||||
order_in_node=(index + 1) * 10, due_at=due,
|
||||
))
|
||||
return len(picked)
|
||||
|
||||
|
||||
def _reject(db: Session, instance: ApprovalInstance, task: ApprovalTask, node: ApprovalNode,
|
||||
actor: Any, comment: str) -> ApprovalInstance:
|
||||
task.status = TaskStatus.DONE
|
||||
task.action = Action.REJECT
|
||||
task.comment = comment
|
||||
task.acted_at = datetime.now()
|
||||
_cancel_siblings(db, instance.id, node.node_key, keep_id=task.id)
|
||||
_record(db, instance, node_key=node.node_key, node_name=node.name, action=Action.REJECT,
|
||||
operator=actor, comment=comment)
|
||||
|
||||
if node.reject_to in ("", "end"):
|
||||
return _finish(db, instance, InstanceStatus.REJECTED)
|
||||
if node.reject_to == "initiator":
|
||||
_cancel_pending(db, instance.id)
|
||||
return _finish(db, instance, InstanceStatus.REJECTED, returned_to_initiator=True)
|
||||
return _move_back_to(db, instance, node.reject_to, actor, comment)
|
||||
|
||||
|
||||
def _rollback(db: Session, instance: ApprovalInstance, task: ApprovalTask, node: ApprovalNode,
|
||||
actor: Any, comment: str, target: str) -> ApprovalInstance:
|
||||
"""退回到指定节点。允许的目标由节点的 ``rollback_keys_json`` 白名单控制。"""
|
||||
allowed = json.loads(node.rollback_keys_json or "[]")
|
||||
if target in ("", "initiator"):
|
||||
task.status = TaskStatus.DONE
|
||||
task.action = Action.ROLLBACK
|
||||
task.comment = comment
|
||||
task.acted_at = datetime.now()
|
||||
_cancel_pending(db, instance.id)
|
||||
_record(db, instance, node_key=node.node_key, node_name=node.name, action=Action.ROLLBACK,
|
||||
operator=actor, comment=comment, rollback_to="initiator")
|
||||
return _finish(db, instance, InstanceStatus.REJECTED, returned_to_initiator=True)
|
||||
if allowed and target not in allowed:
|
||||
raise ApprovalError("rollback_forbidden", "该节点不允许退回到所选节点")
|
||||
|
||||
task.status = TaskStatus.DONE
|
||||
task.action = Action.ROLLBACK
|
||||
task.comment = comment
|
||||
task.acted_at = datetime.now()
|
||||
_record(db, instance, node_key=node.node_key, node_name=node.name, action=Action.ROLLBACK,
|
||||
operator=actor, comment=comment, rollback_to=target)
|
||||
return _move_back_to(db, instance, target, actor, comment)
|
||||
|
||||
|
||||
def _move_back_to(db: Session, instance: ApprovalInstance, target_key: str, actor: Any,
|
||||
comment: str) -> ApprovalInstance:
|
||||
"""把流程拉回更早的节点:清掉那之后的完成记录与待办。"""
|
||||
flow = db.get(ApprovalFlow, instance.flow_id)
|
||||
nodes = ordered_nodes(flow)
|
||||
target = next((item for item in nodes if item.node_key == target_key), None)
|
||||
if target is None:
|
||||
raise ApprovalError("flow_broken", f"退回去向 {target_key} 不存在")
|
||||
|
||||
_cancel_pending(db, instance.id)
|
||||
runtime = _runtime(instance)
|
||||
runtime["completed"] = [key for key in runtime.get("completed", [])
|
||||
if _order_of(nodes, key) < target.order_number]
|
||||
_save_runtime(instance, runtime)
|
||||
return _advance(db, instance, instance.submitter_id, start_from_order=target.order_number - 1)
|
||||
|
||||
|
||||
def _transfer(db: Session, instance: ApprovalInstance, task: ApprovalTask, node: ApprovalNode,
|
||||
actor: Any, comment: str, target_ids: list[int]) -> ApprovalInstance:
|
||||
if not target_ids:
|
||||
raise ApprovalError("target_required", "转办必须指定接手人")
|
||||
from ...models import Account
|
||||
|
||||
targets = db.execute(
|
||||
select(Account).where(Account.id.in_(target_ids), Account.is_deleted.is_(False))
|
||||
).scalars().all()
|
||||
if not targets:
|
||||
raise ApprovalError("target_missing", "转办目标不存在或已停用")
|
||||
|
||||
task.status = TaskStatus.TRANSFERRED
|
||||
task.action = Action.TRANSFER
|
||||
task.comment = comment
|
||||
task.acted_at = datetime.now()
|
||||
for account in targets:
|
||||
db.add(ApprovalTask(
|
||||
instance_id=instance.id, node_key=node.node_key, node_name=node.name,
|
||||
sign_type=node.sign_type, assignee_id=account.id,
|
||||
assignee_name=account.display_name or account.account,
|
||||
origin_assignee_id=actor.id, order_in_node=task.order_in_node, due_at=task.due_at,
|
||||
))
|
||||
_record(db, instance, node_key=node.node_key, node_name=node.name, action=Action.TRANSFER,
|
||||
operator=actor, comment=comment,
|
||||
target_names="、".join(a.display_name or a.account for a in targets))
|
||||
db.flush()
|
||||
return instance
|
||||
|
||||
|
||||
def _add_sign(db: Session, instance: ApprovalInstance, task: ApprovalTask, node: ApprovalNode,
|
||||
actor: Any, comment: str, target_ids: list[int]) -> ApprovalInstance:
|
||||
"""加签:被加签人也要处理,加签人自己的那条待办保留。"""
|
||||
if not target_ids:
|
||||
raise ApprovalError("target_required", "加签必须指定人员")
|
||||
from ...models import Account
|
||||
|
||||
targets = db.execute(
|
||||
select(Account).where(Account.id.in_(target_ids), Account.is_deleted.is_(False))
|
||||
).scalars().all()
|
||||
if not targets:
|
||||
raise ApprovalError("target_missing", "加签目标不存在或已停用")
|
||||
existing = set(db.execute(
|
||||
select(ApprovalTask.assignee_id).where(
|
||||
ApprovalTask.instance_id == instance.id,
|
||||
ApprovalTask.node_key == node.node_key,
|
||||
ApprovalTask.status == TaskStatus.PENDING,
|
||||
)
|
||||
).scalars().all())
|
||||
for account in targets:
|
||||
if account.id in existing:
|
||||
continue
|
||||
db.add(ApprovalTask(
|
||||
instance_id=instance.id, node_key=node.node_key, node_name=node.name,
|
||||
sign_type=SignType.ALL, assignee_id=account.id,
|
||||
assignee_name=account.display_name or account.account,
|
||||
origin_assignee_id=actor.id, order_in_node=5,
|
||||
))
|
||||
_record(db, instance, node_key=node.node_key, node_name=node.name, action=Action.ADD_SIGN,
|
||||
operator=actor, comment=comment,
|
||||
target_names="、".join(a.display_name or a.account for a in targets))
|
||||
db.flush()
|
||||
return instance
|
||||
|
||||
|
||||
def _finish(db: Session, instance: ApprovalInstance, status: str,
|
||||
*, returned_to_initiator: bool = False) -> ApprovalInstance:
|
||||
instance.status = status
|
||||
instance.finished_at = datetime.now()
|
||||
if status == InstanceStatus.APPROVED:
|
||||
instance.current_node_key = ""
|
||||
instance.current_node_name = "结束"
|
||||
_release_revision(db, instance, RevisionStatus.APPROVED)
|
||||
elif returned_to_initiator:
|
||||
instance.current_node_name = "已退回发起人"
|
||||
_release_revision(db, instance, RevisionStatus.REJECTED)
|
||||
else:
|
||||
_release_revision(db, instance, RevisionStatus.REJECTED)
|
||||
runtime = _runtime(instance)
|
||||
runtime["returned_to_initiator"] = returned_to_initiator
|
||||
_save_runtime(instance, runtime)
|
||||
db.flush()
|
||||
return instance
|
||||
|
||||
|
||||
def _release_revision(db: Session, instance: ApprovalInstance, status: str) -> None:
|
||||
if not instance.revision_id:
|
||||
return
|
||||
revision = db.get(Revision, instance.revision_id)
|
||||
if revision is None:
|
||||
return
|
||||
revision.status = status
|
||||
revision.decided_at = datetime.now()
|
||||
|
||||
|
||||
def sweep_timeouts(db: Session, *, now: datetime | None = None) -> dict[str, int]:
|
||||
"""定时任务:超时提醒或自动通过。"""
|
||||
now = now or datetime.now()
|
||||
tasks = db.execute(
|
||||
select(ApprovalTask).where(
|
||||
ApprovalTask.status == TaskStatus.PENDING,
|
||||
ApprovalTask.due_at.isnot(None),
|
||||
ApprovalTask.due_at < now,
|
||||
)
|
||||
).scalars().all()
|
||||
reminded = auto = 0
|
||||
for task in tasks:
|
||||
instance = db.get(ApprovalInstance, task.instance_id)
|
||||
if instance is None or instance.status != InstanceStatus.REVIEWING:
|
||||
continue
|
||||
node = _node_of(db, instance, task.node_key)
|
||||
if node.timeout_action == "remind":
|
||||
_record(db, instance, node_key=node.node_key, node_name=node.name, action=Action.TIMEOUT,
|
||||
operator_id=None, operator_name="系统", comment=f"{task.assignee_name} 超时未处理,已催办")
|
||||
reminded += 1
|
||||
elif node.timeout_action == "auto_approve":
|
||||
_approve(db, instance, task, node, None, "超时自动通过")
|
||||
auto += 1
|
||||
db.flush()
|
||||
return {"reminded": reminded, "auto_approved": auto}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 小工具
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _order_of(nodes: list[ApprovalNode], key: str) -> int:
|
||||
for node in nodes:
|
||||
if node.node_key == key:
|
||||
return node.order_number
|
||||
return 0
|
||||
|
||||
|
||||
def _node_of(db: Session, instance: ApprovalInstance, node_key: str) -> ApprovalNode:
|
||||
node = db.execute(
|
||||
select(ApprovalNode).where(ApprovalNode.flow_id == instance.flow_id, ApprovalNode.node_key == node_key)
|
||||
).scalars().first()
|
||||
if node is None:
|
||||
raise ApprovalError("flow_broken", f"流程节点 {node_key} 已被删除,请联系管理员")
|
||||
return node
|
||||
|
||||
|
||||
def _runtime(instance: ApprovalInstance) -> dict[str, Any]:
|
||||
try:
|
||||
data = json.loads(instance.runtime_json or "{}")
|
||||
except json.JSONDecodeError:
|
||||
return {}
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def _save_runtime(instance: ApprovalInstance, runtime: dict[str, Any]) -> None:
|
||||
instance.runtime_json = json.dumps(runtime, ensure_ascii=False)
|
||||
|
||||
|
||||
def _cancel_siblings(db: Session, instance_id: int, node_key: str, *, keep_id: int) -> None:
|
||||
db.execute(
|
||||
update(ApprovalTask)
|
||||
.where(ApprovalTask.instance_id == instance_id, ApprovalTask.node_key == node_key,
|
||||
ApprovalTask.status == TaskStatus.PENDING, ApprovalTask.id != keep_id)
|
||||
.values(status=TaskStatus.SKIPPED, acted_at=datetime.now())
|
||||
)
|
||||
|
||||
|
||||
def _cancel_pending(db: Session, instance_id: int) -> None:
|
||||
db.execute(
|
||||
update(ApprovalTask)
|
||||
.where(ApprovalTask.instance_id == instance_id, ApprovalTask.status == TaskStatus.PENDING)
|
||||
.values(status=TaskStatus.CANCELED, acted_at=datetime.now())
|
||||
)
|
||||
|
||||
|
||||
def _fallback_admin(db: Session):
|
||||
from ...models import Account, Status
|
||||
|
||||
return db.execute(
|
||||
select(Account).where(Account.is_system_admin.is_(True), Account.is_deleted.is_(False),
|
||||
Account.status == Status.ACTIVE).order_by(Account.id).limit(1)
|
||||
).scalars().first()
|
||||
|
||||
|
||||
def _names(db: Session, ids: list[int]) -> str:
|
||||
from ...models import Account
|
||||
|
||||
if not ids:
|
||||
return ""
|
||||
rows = db.execute(select(Account.display_name, Account.account).where(Account.id.in_(ids))).all()
|
||||
return "、".join(name or account for name, account in rows)
|
||||
|
||||
|
||||
def _record(db: Session, instance: ApprovalInstance, *, node_key: str, node_name: str, action: str,
|
||||
operator: Any = None, operator_id: int | None = None, operator_name: str = "",
|
||||
comment: str = "", target_names: str = "", rollback_to: str = "") -> int:
|
||||
if operator is not None:
|
||||
operator_id = getattr(operator, "id", operator_id)
|
||||
operator_name = getattr(operator, "display_name", None) or operator_name or ""
|
||||
record = ApprovalRecord(
|
||||
instance_id=instance.id,
|
||||
project_id=instance.project_id,
|
||||
business_module=instance.business_module,
|
||||
node_key=node_key,
|
||||
node_name=node_name,
|
||||
action=action,
|
||||
action_label=Action.LABELS.get(action, action),
|
||||
operator_id=operator_id,
|
||||
operator_name=operator_name,
|
||||
target_names=target_names,
|
||||
comment=comment,
|
||||
rollback_to_node=rollback_to,
|
||||
)
|
||||
db.add(record)
|
||||
db.flush()
|
||||
return record.id
|
||||
|
|
@ -0,0 +1,177 @@
|
|||
"""流程匹配与定义校验。
|
||||
|
||||
一个业务模块常常要按项目类型、金额区间走不同流程(老系统是靠 ``ActProjectTypeEnum``
|
||||
和硬编码的项目类型分支实现的)。这里改成"已发布流程 + 匹配条件 + 优先级",新增一条
|
||||
分支不用改代码。
|
||||
|
||||
条件表达式刻意用受限语法(``字段 运算符 值``,多个用 and/or 串起来),不 eval:
|
||||
流程管理员写的东西会进数据库并被执行,任何能写表达式的口子都是攻击面。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ...models import ApprovalFlow, ApprovalNode, FlowStatus, NodeType
|
||||
|
||||
_CONDITION_PATTERN = re.compile(
|
||||
r"^\s*(?P<field>[A-Za-z_][A-Za-z0-9_.]*)\s*(?P<op>>=|<=|==|!=|>|<|in|contains)\s*(?P<value>.+?)\s*$"
|
||||
)
|
||||
|
||||
def evaluate_simple_condition(expression: str, variables: dict[str, Any]) -> bool:
|
||||
"""``contract_amount>=5000000 and type in [1,2]`` 这样的合取/析取式。"""
|
||||
text = (expression or "").strip()
|
||||
if not text:
|
||||
return True
|
||||
|
||||
for connector, all_or_any in ((" or ", False), (" and ", True)):
|
||||
parts = [part.strip() for part in text.split(connector) if part.strip()]
|
||||
if len(parts) > 1:
|
||||
results = [evaluate_simple_condition(part, variables) for part in parts]
|
||||
return all(results) if all_or_any else any(results)
|
||||
|
||||
match = _CONDITION_PATTERN.match(text)
|
||||
if not match:
|
||||
return False
|
||||
field_name = match.group("field")
|
||||
operator = match.group("op")
|
||||
raw_value = match.group("value")
|
||||
left = _lookup(variables, field_name)
|
||||
right = _parse_literal(raw_value)
|
||||
|
||||
if operator == "in":
|
||||
return left in (right if isinstance(right, (list, tuple, set)) else [right])
|
||||
if operator == "contains":
|
||||
return str(right) in str(left or "")
|
||||
if operator in (">", "<", ">=", "<="):
|
||||
try:
|
||||
left_number, right_number = float(left or 0), float(right if not isinstance(right, bool) else int(right))
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
return {">": left_number > right_number, "<": left_number < right_number,
|
||||
">=": left_number >= right_number, "<=": left_number <= right_number}[operator]
|
||||
if operator == "!=":
|
||||
return str(left) != str(right)
|
||||
return str(left) == str(right)
|
||||
|
||||
|
||||
def _lookup(variables: dict[str, Any], dotted: str) -> Any:
|
||||
current: Any = variables
|
||||
for part in dotted.split("."):
|
||||
if isinstance(current, dict):
|
||||
current = current.get(part)
|
||||
else:
|
||||
return None
|
||||
return current
|
||||
|
||||
|
||||
def _parse_literal(raw: str) -> Any:
|
||||
text = raw.strip()
|
||||
if text.startswith("[") and text.endswith("]"):
|
||||
try:
|
||||
return json.loads(text)
|
||||
except json.JSONDecodeError:
|
||||
return [item.strip().strip("'\"") for item in text[1:-1].split(",") if item.strip()]
|
||||
if text.lower() in ("true", "false"):
|
||||
return text.lower() == "true"
|
||||
if (text.startswith('"') and text.endswith('"')) or (text.startswith("'") and text.endswith("'")):
|
||||
return text[1:-1]
|
||||
try:
|
||||
return float(text) if "." in text else int(text)
|
||||
except ValueError:
|
||||
return text
|
||||
|
||||
|
||||
def match_flow(db: Session, module: str, variables: dict[str, Any]) -> ApprovalFlow | None:
|
||||
"""挑一条最合适的已发布流程。
|
||||
|
||||
先按 ``priority`` 小的优先,其次按"匹配条件写得更多"的优先——没有显式条件的那条
|
||||
是兜底默认流程,永远排最后。
|
||||
"""
|
||||
flows = db.execute(
|
||||
select(ApprovalFlow).where(
|
||||
ApprovalFlow.business_module == module,
|
||||
ApprovalFlow.status == FlowStatus.PUBLISHED,
|
||||
ApprovalFlow.is_deleted.is_(False),
|
||||
).order_by(ApprovalFlow.priority, ApprovalFlow.id.desc())
|
||||
).scalars().all()
|
||||
|
||||
candidates: list[tuple[int, int, ApprovalFlow]] = []
|
||||
for flow in flows:
|
||||
conditions = _conditions(flow.match_json)
|
||||
if not conditions:
|
||||
candidates.append((2, flow.priority, flow)) # 默认流程
|
||||
continue
|
||||
if all(evaluate_simple_condition(expression, variables) for expression in conditions):
|
||||
candidates.append((0 if len(conditions) > 1 else 1, flow.priority, flow))
|
||||
|
||||
if not candidates:
|
||||
return None
|
||||
candidates.sort(key=lambda item: (item[0], item[1], -item[2].id))
|
||||
return candidates[0][2]
|
||||
|
||||
|
||||
def _conditions(raw: str) -> list[str]:
|
||||
if not (raw or "").strip():
|
||||
return []
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
return [raw]
|
||||
if isinstance(data, str):
|
||||
return [data]
|
||||
if isinstance(data, dict):
|
||||
expressions = data.get("expressions") or []
|
||||
return [str(item) for item in expressions if str(item).strip()]
|
||||
return [str(item) for item in data if str(item).strip()]
|
||||
|
||||
|
||||
def node_condition_passes(node: ApprovalNode, variables: dict[str, Any]) -> bool:
|
||||
from ...models import NodeType as _NodeType
|
||||
|
||||
if node.node_type == _NodeType.CONDITION:
|
||||
# 条件节点自身就是判定:通过 condition_json 决定流程是否继续走它后面的分支
|
||||
return evaluate_simple_condition(node.condition_json, variables)
|
||||
return evaluate_simple_condition(node.condition_json, variables)
|
||||
|
||||
|
||||
def ordered_nodes(flow: ApprovalFlow) -> list[ApprovalNode]:
|
||||
return sorted(
|
||||
[node for node in flow.nodes if node.enabled and not node.is_deleted],
|
||||
key=lambda node: (node.order_number, node.id),
|
||||
)
|
||||
|
||||
|
||||
def definition_errors(flow: ApprovalFlow) -> list[str]:
|
||||
"""发布前自检:把"发出去才发现流程不通"挡在发布这一步。"""
|
||||
nodes = ordered_nodes(flow)
|
||||
errors: list[str] = []
|
||||
if not nodes:
|
||||
return ["流程没有任何节点"]
|
||||
if not any(node.node_type == NodeType.APPROVE for node in nodes):
|
||||
errors.append("流程至少要有一个审批节点")
|
||||
|
||||
keys = [node.node_key for node in nodes]
|
||||
if len(keys) != len(set(keys)):
|
||||
errors.append("存在重复的节点标识")
|
||||
|
||||
known = set(keys)
|
||||
for node in nodes:
|
||||
if node.next_node_key and node.next_node_key not in known:
|
||||
errors.append(f"节点「{node.name}」的去向 {node.next_node_key} 不存在")
|
||||
if node.reject_to not in ("end", "initiator") and node.reject_to not in known:
|
||||
errors.append(f"节点「{node.name}」的驳回去向 {node.reject_to} 不存在")
|
||||
for target in json.loads(node.rollback_keys_json or "[]"):
|
||||
if target not in known:
|
||||
errors.append(f"节点「{node.name}」允许退回的 {target} 不存在")
|
||||
from .candidates import parse_config
|
||||
|
||||
for item in parse_config(node.candidates_json):
|
||||
if not item.get("type"):
|
||||
errors.append(f"节点「{node.name}」有缺少 type 的候选人配置")
|
||||
return errors
|
||||
|
|
@ -0,0 +1,431 @@
|
|||
"""写操作审计:所有改数据的请求都留一条 ``operation_log``。
|
||||
|
||||
老系统的审计是"谁想起来谁写一行",结果就是出了事查不到人:接口上百条,只有零星几条
|
||||
接口记得记日志,格式还各写各的。这里把审计挪到 ASGI 中间件,**按方法判定而不是按接口
|
||||
判定**——POST/PUT/PATCH/DELETE 一律留痕,新加接口不需要记得挂什么东西,漏不掉。
|
||||
|
||||
三条口径:
|
||||
|
||||
1. **一次操作一条**。接口想补充业务语义(项目名、删除原因、影响面)用 :func:`enrich`
|
||||
挂到 ``request.state`` 上,由中间件并到同一行里,不另开一条。
|
||||
2. **口令这类东西绝不入库**。请求体里命中敏感字样的键统一替换成 ``***``,整段还带
|
||||
长度上限;上传类请求(multipart)只记元信息,不碰内容。
|
||||
3. **审计失败不影响业务**。日志写在响应出去之后,异常只打警告,绝不把一次已经成功的
|
||||
保存变成 500。
|
||||
|
||||
登录/免登/改口令不在这条链路里:前两者有自己的 ``login_log`` 与 ``sso_handoff``,改口令
|
||||
在接口里写了一条动作更明确的 ``operation_log``;三条路径的请求体都是要防着的东西,
|
||||
混进来除了多存一份敏感数据没别的好处。
|
||||
|
||||
审计页上的**对象名**由这里按 ``object_type`` 反查一次(见 ``NAME_LOOKUPS``),不要求每个
|
||||
接口自己记得报名字——接口会一个个新增,靠人记的规矩一定会漏。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
||||
|
||||
from ..db import SessionFactory
|
||||
from ..models import OperationLog
|
||||
|
||||
logger = logging.getLogger("pms.audit")
|
||||
|
||||
MUTATING_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"})
|
||||
|
||||
#: 不审计的路径。登录/免登/改口令有自己的日志,且请求体是要防着的东西。
|
||||
SKIP_PREFIXES = ("/api/health", "/api/docs", "/api/openapi.json")
|
||||
SKIP_PATHS = ("/api/v1/auth/login", "/api/v1/auth/password")
|
||||
SKIP_SUBTREES = ("/api/v1/auth/sso",)
|
||||
|
||||
#: 请求体只截这么多字节进日志;再长的(整表批量保存)留个长度就够定位了。
|
||||
BODY_LIMIT = 4096
|
||||
#: 命中这些字样的键一律抹掉,别把口令、令牌、验证码存进审计表。刻意不收 "code"/"key"
|
||||
#: 这种宽泛字样——部门编码、岗位编码、字典编码都是审计要看的,被糊掉等于白记。
|
||||
SENSITIVE_HINTS = ("password", "passwd", "token", "secret", "captcha", "credential",
|
||||
"authorization", "ticket")
|
||||
|
||||
#: 路径尾巴上是这些词时,动作按词记,不按 HTTP 方法猜。
|
||||
VERB_TAILS = {
|
||||
"submit": "submit", "withdraw": "withdraw", "approve": "approve", "reject": "reject",
|
||||
"rollback": "rollback", "transfer": "transfer", "add-sign": "add_sign", "act": "act",
|
||||
"remind": "remind", "publish": "publish", "offline": "offline", "restore": "restore",
|
||||
"purge": "purge", "reset": "reset", "toggle": "toggle", "sync": "sync",
|
||||
"calculate": "calculate", "new-version": "new_version", "logout": "logout",
|
||||
"exchange": "sso_exchange", "run": "run", "stage": "stage",
|
||||
}
|
||||
|
||||
METHOD_ACTIONS = {"POST": "create", "PUT": "update", "PATCH": "update", "DELETE": "delete"}
|
||||
|
||||
#: 路径段 → (对象类型, 记 id 用的路径参数名)。深的那段优先,外层那段进 detail。
|
||||
SEGMENT_OBJECT: dict[str, tuple[str, str]] = {
|
||||
"projects": ("project", "project_id"),
|
||||
"members": ("project_member", "account_id"),
|
||||
"visible-roles": ("project_visible_role", "role_id"),
|
||||
"attachments": ("attachment", "attachment_id"),
|
||||
"units": ("org_unit", "unit_id"),
|
||||
"positions": ("position", "position_id"),
|
||||
"accounts": ("account", "id"),
|
||||
"roles": ("perm_role", "role_id"),
|
||||
"permissions": ("perm_node", "node_id"),
|
||||
"nodes": ("perm_node", "node_id"),
|
||||
"data-policies": ("perm_data_policy", "policy_id"),
|
||||
"field-scopes": ("field_scope", "scope_id"),
|
||||
"configs": ("system_config", "code"),
|
||||
"calc-rules": ("calc_rule", ""),
|
||||
"dicts": ("dict_type", "dict_id"),
|
||||
"items": ("dict_item", "item_id"),
|
||||
"flows": ("approval_flow", "flow_id"),
|
||||
"delegates": ("approval_delegate", ""),
|
||||
"instances": ("approval_instance", "instance_id"),
|
||||
"tasks": ("approval_task", "task_id"),
|
||||
"versions": ("biz_revision", "revision_id"),
|
||||
"snapshots": ("calc_snapshot", "snapshot_id"),
|
||||
"lines": ("biz_line", "line_id"),
|
||||
"stage": ("project_stage", ""),
|
||||
"finance": ("biz_revision", "project_id"),
|
||||
"approvals": ("approval", ""),
|
||||
}
|
||||
|
||||
#: 审计页要显示"改的是哪个东西",按对象类型回查一次显示名列。查不到就留空,
|
||||
#: 对象 id 与请求体都还在,不影响定位。
|
||||
NAME_LOOKUPS: dict[str, tuple[str, str]] = {
|
||||
"project": ("Project", "name"),
|
||||
"project_member": ("Account", "display_name"),
|
||||
"org_unit": ("OrgUnit", "name"),
|
||||
"position": ("Position", "name"),
|
||||
"account": ("Account", "display_name"),
|
||||
"perm_role": ("PermRole", "name"),
|
||||
"perm_node": ("PermNode", "name"),
|
||||
"perm_data_policy": ("PermDataPolicy", "name"),
|
||||
"system_config": ("SystemConfig", "name"),
|
||||
"dict_type": ("DictType", "name"),
|
||||
"approval_flow": ("ApprovalFlow", "name"),
|
||||
"approval_instance": ("ApprovalInstance", "project_name"),
|
||||
}
|
||||
|
||||
|
||||
ACTION_LABELS = {
|
||||
"create": "新增", "update": "修改", "delete": "删除", "purge": "彻底删除",
|
||||
"restore": "恢复", "submit": "提交送审", "withdraw": "撤回送审", "approve": "审批通过",
|
||||
"reject": "审批不通过", "rollback": "退回修改", "transfer": "转办", "add_sign": "加签",
|
||||
"act": "办理审批", "remind": "催办", "publish": "发布流程", "offline": "下线流程",
|
||||
"reset": "恢复默认", "toggle": "启停", "sync": "同步", "calculate": "试算",
|
||||
"new_version": "新建版本", "logout": "登出", "sso_exchange": "免登换会话", "run": "执行",
|
||||
"stage": "推进阶段", "delete_check": "删除前检查",
|
||||
"change_password": "修改口令", "unknown": "操作",
|
||||
}
|
||||
|
||||
|
||||
def action_label(action: str) -> str:
|
||||
return ACTION_LABELS.get(action, action or "操作")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 接口侧的业务补充
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def enrich(request: Any, *, action: str = "", object_type: str = "", object_id: Any = None,
|
||||
object_name: str = "", **detail: Any) -> None:
|
||||
"""给这次请求的审计行补业务语义;由中间件在响应之后合并成一行。
|
||||
|
||||
``request`` 传 FastAPI 的 ``Request``,没有的话传 ``request.state`` 所在的那个对象——
|
||||
只认 ``state``,因此 ASGI 中间件重建出来的 ``Request`` 也能读到这里写的东西。
|
||||
"""
|
||||
state = getattr(request, "state", request)
|
||||
bag: dict[str, Any] = getattr(state, "audit", None) or {}
|
||||
if action:
|
||||
bag["action"] = action
|
||||
if object_type:
|
||||
bag["object_type"] = object_type
|
||||
if object_id is not None:
|
||||
bag["object_id"] = str(object_id)
|
||||
if object_name:
|
||||
bag["object_name"] = object_name[:255]
|
||||
if detail:
|
||||
bag.setdefault("detail", {}).update(detail)
|
||||
try:
|
||||
state.audit = bag
|
||||
except Exception: # pragma: no cover - 极少数 state 实现不允许挂属性
|
||||
pass
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 路径 → 对象
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _is_param(segment: str) -> bool:
|
||||
return segment.startswith("{") and segment.endswith("}")
|
||||
|
||||
|
||||
def resolve_object(route_path: str, path_params: dict[str, Any]) -> tuple[str, str, str, str]:
|
||||
"""从路由模板里折出 (对象类型, 对象 id, 父类型, 父 id)。
|
||||
|
||||
取**最深**一段能对上 id 的作为主体:删成员记的是那个成员,不是项目;项目 id 仍然
|
||||
进 detail,查的时候按项目也能捞出来。
|
||||
"""
|
||||
segments = [s for s in route_path.split("/") if s][2:] # 去掉 api/v1
|
||||
found: list[tuple[str, str]] = []
|
||||
for segment in segments:
|
||||
if _is_param(segment):
|
||||
continue
|
||||
mapped = SEGMENT_OBJECT.get(segment)
|
||||
if not mapped:
|
||||
continue
|
||||
object_type, param = mapped
|
||||
value = path_params.get(param) if param else None
|
||||
found.append((object_type, "" if value is None else str(value)))
|
||||
if not found:
|
||||
return "", "", "", ""
|
||||
deepest = next((item for item in reversed(found) if item[1]), found[-1])
|
||||
outer = found[0]
|
||||
if outer[0] == deepest[0]:
|
||||
return deepest[0], deepest[1], "", ""
|
||||
return deepest[0], deepest[1], outer[0], outer[1]
|
||||
|
||||
|
||||
def resolve_action(method: str, route_path: str) -> str:
|
||||
tail = [s for s in route_path.split("/") if s][-1]
|
||||
if not _is_param(tail):
|
||||
verb = VERB_TAILS.get(tail)
|
||||
if verb:
|
||||
return verb
|
||||
return METHOD_ACTIONS.get(method, "unknown")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 请求体脱敏
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _sensitive(key: str) -> bool:
|
||||
lowered = key.lower().replace("_", "")
|
||||
return any(hint in lowered for hint in SENSITIVE_HINTS)
|
||||
|
||||
|
||||
def redact(value: Any, *, depth: int = 0) -> Any:
|
||||
"""递归脱敏。列表/字典原样折,命中敏感字样的键换成 ``***``。"""
|
||||
if depth > 6:
|
||||
return "…"
|
||||
if isinstance(value, dict):
|
||||
return {(k if isinstance(k, str) else str(k)):
|
||||
("***" if isinstance(k, str) and _sensitive(k) else redact(v, depth=depth + 1))
|
||||
for k, v in list(value.items())[:120]}
|
||||
if isinstance(value, list):
|
||||
folded = [redact(item, depth=depth + 1) for item in value[:60]]
|
||||
if len(value) > 60:
|
||||
folded.append(f"…共 {len(value)} 条")
|
||||
return folded
|
||||
if isinstance(value, (str, int, float, bool)) or value is None:
|
||||
if isinstance(value, str) and len(value) > 500:
|
||||
return value[:500] + f"…共 {len(value)} 字"
|
||||
return value
|
||||
return str(value)[:500]
|
||||
|
||||
|
||||
def _body_for_log(content_type: str, raw: bytes) -> Any:
|
||||
if not raw:
|
||||
return None
|
||||
length = len(raw)
|
||||
text = raw[:BODY_LIMIT].decode("utf-8", "replace")
|
||||
if content_type.startswith("multipart/"):
|
||||
return {"_upload": True, "bytes": length}
|
||||
try:
|
||||
return redact(json.loads(text))
|
||||
except ValueError:
|
||||
return {"_raw": text[:BODY_LIMIT] + (f"…共 {length} 字节" if length > BODY_LIMIT else "")}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 中间件
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class AuditMiddleware:
|
||||
"""原生 ASGI 中间件:只观察,不改请求也不改响应。
|
||||
|
||||
没用 ``BaseHTTPMiddleware`` 是因为要在不吃掉请求体的前提下看到同一段 body——
|
||||
在这里套一层 ``receive``,消息照样原样往下传,接口读到的字节一个不少。
|
||||
"""
|
||||
|
||||
def __init__(self, app: ASGIApp) -> None:
|
||||
self.app = app
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
path = scope.get("path", "")
|
||||
method = scope.get("method", "")
|
||||
if (scope.get("type") != "http" or method not in MUTATING_METHODS
|
||||
or path.startswith(SKIP_PREFIXES) or path in SKIP_PATHS
|
||||
or path.startswith(SKIP_SUBTREES)):
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
chunks: list[bytes] = []
|
||||
seen = 0
|
||||
|
||||
async def watching_receive() -> Message:
|
||||
nonlocal seen
|
||||
message = await receive()
|
||||
if message.get("type") == "http.request":
|
||||
piece = message.get("body", b"") or b""
|
||||
if seen < BODY_LIMIT * 2:
|
||||
chunks.append(piece)
|
||||
seen += len(piece)
|
||||
return message
|
||||
|
||||
outcome: dict[str, Any] = {"status": 0, "body": b""}
|
||||
|
||||
async def watching_send(message: Message) -> None:
|
||||
kind = message.get("type")
|
||||
if kind == "http.response.start":
|
||||
outcome["status"] = message.get("status", 0)
|
||||
elif kind == "http.response.body" and len(outcome["body"]) < 2048:
|
||||
# 响应体只在内存里截一小段,不整段留下:失败的要写出"为什么没改成",
|
||||
# 新增成功的要拿 data.id ——本系统所有创建接口都回 ok({"id": N}),
|
||||
# 认这一条约定,新建出来的对象 id 就不用每个接口自己报一遍。
|
||||
outcome["body"] += message.get("body", b"") or b""
|
||||
await send(message)
|
||||
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
await self.app(scope, watching_receive, watching_send)
|
||||
finally:
|
||||
raw = b"".join(chunks)
|
||||
elapsed = round((time.perf_counter() - started) * 1000, 1)
|
||||
try:
|
||||
await run_in_threadpool(self._record, scope, raw, outcome, elapsed)
|
||||
except Exception as exc: # pragma: no cover - 审计绝不能带崩业务
|
||||
logger.warning("写审计日志失败 %s %s:%s", method, path, exc)
|
||||
|
||||
# -- 落库 ---------------------------------------------------------------
|
||||
|
||||
def _record(self, scope: Scope, raw: bytes, outcome: dict[str, Any], elapsed: float) -> None:
|
||||
status = int(outcome.get("status") or 0)
|
||||
from starlette.requests import Request
|
||||
|
||||
request = Request(scope)
|
||||
route = scope.get("route")
|
||||
route_path = getattr(route, "path_format", None) or getattr(route, "path", "") or scope.get("path", "")
|
||||
path_params = dict(scope.get("path_params") or {})
|
||||
payload = _parse_json(outcome.get("body") or b"")
|
||||
state = getattr(request, "state", None)
|
||||
bag: dict[str, Any] = getattr(state, "audit", None) or {}
|
||||
account = getattr(state, "account", None)
|
||||
|
||||
object_type, object_id, parent_type, parent_id = resolve_object(route_path, path_params)
|
||||
action = bag.get("action") or resolve_action(scope.get("method", ""), route_path)
|
||||
if bag.get("object_type"):
|
||||
object_type = bag["object_type"]
|
||||
object_id = bag.get("object_id", object_id)
|
||||
|
||||
query = dict(request.query_params)
|
||||
detail: dict[str, Any] = {
|
||||
"method": scope.get("method", ""),
|
||||
"path": scope.get("path", ""),
|
||||
"route": route_path,
|
||||
"status": status,
|
||||
"ok": status < 400,
|
||||
"durationMs": elapsed,
|
||||
}
|
||||
if query:
|
||||
detail["query"] = redact(query)
|
||||
if path_params:
|
||||
detail["params"] = redact(path_params)
|
||||
body = _body_for_log(request.headers.get("content-type", ""), raw)
|
||||
if body is not None:
|
||||
detail["body"] = body
|
||||
error = bag.get("error") or _error_from_response(payload)
|
||||
if error:
|
||||
detail["error"] = error
|
||||
if not object_id and action == "create":
|
||||
object_id = _created_id(payload)
|
||||
if parent_type:
|
||||
detail["parentType"], detail["parentId"] = parent_type, parent_id
|
||||
detail.update(bag.get("detail") or {})
|
||||
|
||||
if not bag.get("object_name"):
|
||||
object_name_hint = _lookup_name(object_type, object_id)
|
||||
else:
|
||||
object_name_hint = bag["object_name"]
|
||||
|
||||
with SessionFactory()() as session:
|
||||
session.add(OperationLog(
|
||||
account_id=getattr(account, "id", None),
|
||||
account_name=(getattr(account, "display_name", "") or getattr(account, "account", "")
|
||||
or bag.get("account_name", ""))[:100],
|
||||
action=action[:64],
|
||||
object_type=(object_type or (route_path.split("/")[2] if route_path.count("/") > 2 else ""))[:64],
|
||||
object_id=(object_id or bag.get("object_id") or "")[:64],
|
||||
object_name=str(object_name_hint or "")[:255],
|
||||
detail_json=json.dumps(detail, ensure_ascii=False, default=str),
|
||||
ip=(request.headers.get("X-Forwarded-For", "").split(",")[0].strip()
|
||||
or (request.client.host if request.client else ""))[:64],
|
||||
))
|
||||
session.commit()
|
||||
|
||||
|
||||
def _lookup_name(object_type: str, object_id: str) -> str:
|
||||
"""按对象类型把显示名捞出来。捞不到不算错,审计页留空也比编一个强。"""
|
||||
from .. import models
|
||||
|
||||
spec = NAME_LOOKUPS.get(object_type)
|
||||
if not spec or not (object_id or "").isdigit():
|
||||
return ""
|
||||
model = getattr(models, spec[0], None)
|
||||
if model is None:
|
||||
return ""
|
||||
try:
|
||||
with SessionFactory()() as session:
|
||||
row = session.get(model, int(object_id))
|
||||
except Exception: # pragma: no cover - 对象已被同一次操作删掉
|
||||
return ""
|
||||
if row is None:
|
||||
return ""
|
||||
value = getattr(row, spec[1], "")
|
||||
if spec[1] == "display_name":
|
||||
value = value or getattr(row, "account", "")
|
||||
return str(value or "")
|
||||
|
||||
|
||||
def install(app: Any) -> None:
|
||||
"""把审计中间件挂到应用最外层(后加的在外层,能看到路由已经跑完的结果)。"""
|
||||
app.add_middleware(AuditMiddleware)
|
||||
|
||||
|
||||
def _parse_json(raw: bytes) -> dict[str, Any]:
|
||||
if not raw:
|
||||
return {}
|
||||
try:
|
||||
payload = json.loads(raw.decode("utf-8", "replace"))
|
||||
except ValueError:
|
||||
return {}
|
||||
return payload if isinstance(payload, dict) else {}
|
||||
|
||||
|
||||
def _created_id(payload: dict[str, Any]) -> str:
|
||||
"""新增接口回的那条 ``{"ok": true, "data": {"id": N}}``。"""
|
||||
data = payload.get("data")
|
||||
if isinstance(data, dict) and data.get("id") is not None:
|
||||
return str(data["id"])[:64]
|
||||
return ""
|
||||
|
||||
|
||||
def _error_from_response(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""从统一响应包里挑出要进审计的那几个字段,别的大段 detail 不存。"""
|
||||
error = payload.get("error")
|
||||
if not isinstance(error, dict):
|
||||
return {}
|
||||
folded = {"code": str(error.get("code", ""))[:64], "message": str(error.get("message", ""))[:500]}
|
||||
if error.get("traceId"):
|
||||
folded["traceId"] = str(error["traceId"])[:64]
|
||||
detail = error.get("detail")
|
||||
if detail:
|
||||
folded["detail"] = redact(detail)
|
||||
return folded
|
||||
|
|
@ -0,0 +1,836 @@
|
|||
"""项目 / 概算 / 预算的业务编排。
|
||||
|
||||
设计上的三个决定:
|
||||
|
||||
1. **明细的写与算绑在一起**。任何一次明细改动都顺手重算并落一份快照,因此库里永远
|
||||
不存在"明细是新的、汇总是旧的"这种中间态(``RISK-BUD-SSOT-001`` 的根治)。
|
||||
2. **送审前强制重算并冻结**。快照 id 写进审批实例,审批人看到的数字与发起人屏幕上
|
||||
的完全一致,事后也能复查。
|
||||
3. **写回 ``project`` 的只有投影列**,并且带上 ``calc_version``,一眼能看出这条投影
|
||||
是哪套口径算的。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .. import dicts as dict_store
|
||||
from ..envelope import ApiError, conflict, not_found
|
||||
from ..models import (
|
||||
Account,
|
||||
BudgetFundMonth,
|
||||
BudgetIncomeLine,
|
||||
BudgetIncomePlanLine,
|
||||
BudgetManageLine,
|
||||
BudgetOtherCostLine,
|
||||
BudgetPayPlanLine,
|
||||
BudgetPurchaseLine,
|
||||
CalcSnapshot,
|
||||
EstimateCostLine,
|
||||
EstimateIncomeLine,
|
||||
EstimateOtherLine,
|
||||
ManageItemCode,
|
||||
Project,
|
||||
ProjectMember,
|
||||
ProjectMemberRole,
|
||||
ProjectStageLog,
|
||||
Revision,
|
||||
RevisionModule,
|
||||
RevisionStatus,
|
||||
SystemConfig,
|
||||
to_decimal,
|
||||
)
|
||||
from ..models.project import Attachment
|
||||
from ..service.calc import engine as calc_engine
|
||||
from ..service.calc import rules as calc_rules
|
||||
from ..service.calc import validate as calc_validate
|
||||
from ..service.calc.money import ZERO, money_str, to_dec
|
||||
|
||||
LINE_MODELS = {
|
||||
"estimate.income": (EstimateIncomeLine, RevisionModule.ESTIMATE),
|
||||
"estimate.cost": (EstimateCostLine, RevisionModule.ESTIMATE),
|
||||
"estimate.other": (EstimateOtherLine, RevisionModule.ESTIMATE),
|
||||
"budget.income": (BudgetIncomeLine, RevisionModule.BUDGET),
|
||||
"budget.income_plan": (BudgetIncomePlanLine, RevisionModule.BUDGET),
|
||||
"budget.purchase": (BudgetPurchaseLine, RevisionModule.BUDGET),
|
||||
"budget.pay_plan": (BudgetPayPlanLine, RevisionModule.BUDGET),
|
||||
"budget.manage": (BudgetManageLine, RevisionModule.BUDGET),
|
||||
"budget.other_cost": (BudgetOtherCostLine, RevisionModule.BUDGET),
|
||||
"budget.fund_month": (BudgetFundMonth, RevisionModule.BUDGET),
|
||||
}
|
||||
|
||||
|
||||
class BizError(ApiError):
|
||||
def __init__(self, code: str, message: str) -> None:
|
||||
super().__init__(code, message, http_status=400)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 立项:状态、必填校验、预算闸口、生成预算
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: 立项表上的必填项(截图里每一条都带红星)。这里只校验"能不能送审",
|
||||
#: **不校验能不能保存**——草稿就是给人半成品状态的,卡必填等于不让人存盘。
|
||||
INITIATION_REQUIRED_FIELDS: tuple[tuple[str, str, str], ...] = (
|
||||
("name", "项目名称", "text"),
|
||||
("type", "项目类型", "dict"),
|
||||
("underwritten_mode", "垫资模式", "dict"),
|
||||
("certainty", "项目把握度", "dict"),
|
||||
("industry_scene", "行业场景应用", "dict"),
|
||||
("customer", "客户名称", "text"),
|
||||
("terminal_customer", "最终用户名称", "text"),
|
||||
("value_risk", "价值及风险", "text"),
|
||||
("principal", "项目负责人", "text"),
|
||||
("contract_time", "预计合同签订时间", "date"),
|
||||
("bids_time", "项目计划招标时间", "date"),
|
||||
("is_second", "是否二次合作", "dict"),
|
||||
("is_huizhi_bid", "是否汇智中标", "dict"),
|
||||
("calculation_collection", "计收计划", "text"),
|
||||
("stage", "项目阶段", "dict"),
|
||||
("sale_stage", "公司销售阶段", "dict"),
|
||||
("stage_remark", "当前进度描述", "text"),
|
||||
)
|
||||
|
||||
#: 金额类:没有测算明细时允许手填,有测算明细时由计算投影覆盖,所以只做告警不拦送审。
|
||||
INITIATION_AMOUNT_FIELDS: tuple[tuple[str, str], ...] = (
|
||||
("contract_amount", "合同金额"),
|
||||
("gross_profit", "项目毛利"),
|
||||
)
|
||||
|
||||
|
||||
def initiation_missing_fields(project: Project) -> list[dict[str, str]]:
|
||||
"""立项送审前的必填清单,返回 ``[{field, label}]``。"""
|
||||
missing: list[dict[str, str]] = []
|
||||
for field_name, label, _kind in INITIATION_REQUIRED_FIELDS:
|
||||
value = getattr(project, field_name, None)
|
||||
if field_name == "industry_scene":
|
||||
# 0 是老数据"只写了描述没选场景",有描述就算填过
|
||||
if not value and not (project.industry_scene_desc or "").strip():
|
||||
missing.append({"field": field_name, "label": label})
|
||||
continue
|
||||
if field_name == "sale_stage":
|
||||
if value is None or int(value or 0) < 0:
|
||||
missing.append({"field": field_name, "label": label})
|
||||
continue
|
||||
if value is None or (isinstance(value, str) and not value.strip()):
|
||||
missing.append({"field": field_name, "label": label})
|
||||
return missing
|
||||
|
||||
|
||||
def latest_initiation(db: Session, project_id: int) -> Revision | None:
|
||||
"""最近一版立项(不带 status 过滤),列表页要显示"立项到哪一步了"。"""
|
||||
return db.execute(
|
||||
select(Revision)
|
||||
.where(Revision.project_id == project_id, Revision.module == RevisionModule.ESTIMATE,
|
||||
Revision.is_deleted.is_(False))
|
||||
.order_by(Revision.version.desc())
|
||||
.limit(1)
|
||||
).scalars().first()
|
||||
|
||||
|
||||
def approved_initiation(db: Session, project_id: int) -> Revision | None:
|
||||
"""最近一版**审批通过**的立项。预算那一侧只认这一版。"""
|
||||
return db.execute(
|
||||
select(Revision)
|
||||
.where(Revision.project_id == project_id, Revision.module == RevisionModule.ESTIMATE,
|
||||
Revision.status == RevisionStatus.APPROVED, Revision.is_deleted.is_(False))
|
||||
.order_by(Revision.version.desc())
|
||||
.limit(1)
|
||||
).scalars().first()
|
||||
|
||||
|
||||
def initiation_state(db: Session, project_id: int) -> dict[str, Any]:
|
||||
"""立项进度的一站式答案:状态、版本、通过时间、预算是否已解锁。
|
||||
|
||||
前端两个列表页与预算工作台都要这个判断,写在一处才不会各猜各的。
|
||||
"""
|
||||
latest = latest_initiation(db, project_id)
|
||||
approved = approved_initiation(db, project_id)
|
||||
return {
|
||||
"status": latest.status if latest else "",
|
||||
"version": latest.version if latest else 0,
|
||||
"revisionId": latest.id if latest else None,
|
||||
"approvedVersion": approved.version if approved else 0,
|
||||
"approvedRevisionId": approved.id if approved else None,
|
||||
"approvedAt": approved.decided_at.isoformat(sep=" ", timespec="seconds")
|
||||
if approved and approved.decided_at else "",
|
||||
"budgetReady": approved is not None,
|
||||
}
|
||||
|
||||
|
||||
def assert_initiation_approved(db: Session, project_id: int) -> Revision:
|
||||
"""预算闸口:立项没批下来,预算模块不给生成任何数据。
|
||||
|
||||
拦在**取版本**这一步(而不是只拦"送审"),是因为工作台一进来就会
|
||||
``get_or_create_revision`` 悄悄建一条草稿版本;不在这儿挡住,未批准的立项
|
||||
也会在库里长出没人签批的预算版本,后面那些数到底算不算数就没人说得清了。
|
||||
"""
|
||||
approved = approved_initiation(db, project_id)
|
||||
if approved is None:
|
||||
state = initiation_state(db, project_id)
|
||||
reason = {
|
||||
"": "还没有立项记录",
|
||||
RevisionStatus.DRAFT: f"立项 v{state['version']} 还是草稿",
|
||||
RevisionStatus.REVIEWING: f"立项 v{state['version']} 正在审批中",
|
||||
RevisionStatus.REJECTED: f"立项 v{state['version']} 已被驳回",
|
||||
RevisionStatus.WITHDRAWN: f"立项 v{state['version']} 已撤回",
|
||||
}.get(state["status"], "立项尚未审批通过")
|
||||
raise conflict("initiation_not_approved",
|
||||
f"项目预算需要立项审批通过后才能编制:{reason}")
|
||||
return approved
|
||||
|
||||
|
||||
def initiation_baseline(db: Session, project_id: int) -> dict[str, Any]:
|
||||
"""立项批准那一刻的口径,作为预算控制的基线。
|
||||
|
||||
优先读那一版自己的计算快照(有完整的分类合计),快照没了再退回送审冻结块。
|
||||
"""
|
||||
approved = approved_initiation(db, project_id)
|
||||
if approved is None:
|
||||
return {}
|
||||
payload = snapshot_payload(current_snapshot(db, approved))
|
||||
if not payload:
|
||||
try:
|
||||
payload = json.loads(approved.freeze_json or "{}")
|
||||
except json.JSONDecodeError:
|
||||
payload = {}
|
||||
profit = payload.get("profit") or {}
|
||||
groups = payload.get("groups") or {}
|
||||
|
||||
def group_total(group: str, key: str) -> Decimal:
|
||||
return sum((to_dec((buckets or {}).get(key)) for buckets in (groups.get(group) or {}).values()),
|
||||
ZERO)
|
||||
|
||||
return {
|
||||
"revisionId": approved.id,
|
||||
"version": approved.version,
|
||||
"approvedAt": approved.decided_at.isoformat(sep=" ", timespec="seconds")
|
||||
if approved.decided_at else "",
|
||||
"calcVersion": approved.calc_version,
|
||||
"contractAmount": to_dec(payload.get("contract_amount") or profit.get("income_total")
|
||||
or approved_project_amount(payload)),
|
||||
"incomeExclude": group_total("income", "exclude"),
|
||||
"purchaseInclude": group_total("purchase", "include"),
|
||||
"purchaseExclude": group_total("purchase", "exclude"),
|
||||
"grossProfit": to_dec(profit.get("gross_b")),
|
||||
"contributionRate": _rate(profit.get("contribution_rate")),
|
||||
}
|
||||
|
||||
|
||||
def approved_project_amount(payload: dict[str, Any]) -> str:
|
||||
"""冻结块里存的是 ``contractAmount``,快照里没有 contract_amount 时的退路。"""
|
||||
return str((payload or {}).get("contractAmount") or "0")
|
||||
|
||||
|
||||
def _rate(block: Any) -> Decimal:
|
||||
value = (block or {}).get("value") if isinstance(block, dict) else block
|
||||
return to_dec(value)
|
||||
|
||||
|
||||
#: 立项 → 预算的行级搬运规则:源段 -> (目标段, 字段映射)
|
||||
GENERATE_LINE_MAP: dict[str, tuple[str, dict[str, str]]] = {
|
||||
"income": ("income", {}),
|
||||
"cost": ("purchase", {}),
|
||||
}
|
||||
|
||||
#: 概算的"管理与财务费用"按 bucket 分流:项目管理费进预算的项目管理费用表,
|
||||
#: 其他成本进其他成本表;资金占用与公司管理费用**故意不搬**——预算侧这两项分别由
|
||||
#: 资金计划(按月算利息)和计算口径(公司管理费用率)派生,搬过去就是算两遍。
|
||||
GENERATE_BUCKET_MAP = {
|
||||
"project_manage": "manage",
|
||||
"other_cost": "other_cost",
|
||||
}
|
||||
GENERATE_SKIP_BUCKETS = ("capital_interest", "company_manage")
|
||||
|
||||
|
||||
def generate_budget_from_initiation(db: Session, project: Project, actor: Account) -> dict[str, Any]:
|
||||
"""立项批准后,按批准那一版生成预算草稿。
|
||||
|
||||
只在这张项目**还没有任何预算版本**时自动调用(工作台/列表页的"生成预算"按钮)。
|
||||
已经编过预算的项目要走「基于本版新建」显式开新版本,不能一点按钮就把人改了两天的
|
||||
草稿覆盖掉。
|
||||
"""
|
||||
approved = assert_initiation_approved(db, project.id)
|
||||
existing = db.execute(
|
||||
select(func.count(Revision.id)).where(Revision.project_id == project.id,
|
||||
Revision.module == RevisionModule.BUDGET,
|
||||
Revision.is_deleted.is_(False))
|
||||
).scalar() or 0
|
||||
if existing:
|
||||
raise conflict("budget_exists",
|
||||
f"这个项目已经有 {existing} 个预算版本,请在预算工作台用「基于本版新建」开新版")
|
||||
|
||||
budget = get_or_create_revision(db, project.id, RevisionModule.BUDGET, actor)
|
||||
budget.title = f"由立项 v{approved.version} 生成"
|
||||
budget.based_on_id = approved.id
|
||||
|
||||
source = revision_lines(db, approved)
|
||||
counts: dict[str, int] = {}
|
||||
for line_key in ("income", "cost"):
|
||||
target_key, _ = GENERATE_LINE_MAP[line_key]
|
||||
rows = source.get(line_key, [])
|
||||
counts[target_key] = _copy_section(db, approved, budget, line_key, target_key, rows)
|
||||
manage_rows: list[Any] = []
|
||||
other_rows: list[Any] = []
|
||||
skipped = 0
|
||||
for row in source.get("other", []):
|
||||
target = GENERATE_BUCKET_MAP.get(row.bucket)
|
||||
if target == "manage":
|
||||
manage_rows.append(row)
|
||||
elif target == "other_cost":
|
||||
other_rows.append(row)
|
||||
else:
|
||||
skipped += 1
|
||||
counts["manage"] = _copy_other_section(db, budget, "manage", manage_rows)
|
||||
counts["other_cost"] = _copy_other_section(db, budget, "other_cost", other_rows)
|
||||
|
||||
recompute(db, budget, actor, trigger="edit")
|
||||
db.flush()
|
||||
return {
|
||||
"revision": budget,
|
||||
"copied": counts,
|
||||
"skippedOtherLines": skipped,
|
||||
"note": "资金占用成本与公司管理费用不搬运:预算侧分别由资金计划与计算口径派生",
|
||||
}
|
||||
|
||||
|
||||
def _copy_section(db: Session, source: Revision, target: Revision,
|
||||
source_key: str, target_key: str, rows: list[Any]) -> int:
|
||||
"""把一段明细搬到预算侧,同名的字段照搬,预算独有的字段留空。"""
|
||||
source_model = LINE_MODELS[f"estimate.{source_key}"][0]
|
||||
target_model = LINE_MODELS[f"budget.{target_key}"][0]
|
||||
shared = set(LINE_FIELDS[f"estimate.{source_key}"]) & set(LINE_FIELDS[f"budget.{target_key}"])
|
||||
for row in rows:
|
||||
clone = target_model(project_id=target.project_id, revision_id=target.id)
|
||||
for field_name in shared:
|
||||
setattr(clone, field_name, getattr(row, field_name, None))
|
||||
db.add(clone)
|
||||
db.flush()
|
||||
return len(rows)
|
||||
|
||||
|
||||
def _copy_other_section(db: Session, target: Revision, target_key: str, rows: list[Any]) -> int:
|
||||
"""概算的不含税费用行 -> 预算的项目管理费用 / 其他成本。"""
|
||||
if not rows:
|
||||
return 0
|
||||
model = LINE_MODELS[f"budget.{target_key}"][0]
|
||||
for row in rows:
|
||||
clone = model(project_id=target.project_id, revision_id=target.id)
|
||||
clone.name = row.name
|
||||
clone.remark = row.remark or ""
|
||||
clone.sort = getattr(row, "sort", 100) or 100
|
||||
if target_key == "manage":
|
||||
clone.manage_type = 3 # 3 = 其他(老编码)
|
||||
clone.item_code = ManageItemCode.OTHER
|
||||
clone.item_name = row.name
|
||||
clone.total = row.exclude_amount
|
||||
clone.predict_method = "由立项测算带入"
|
||||
clone.deletable = True
|
||||
else:
|
||||
clone.exclude_amount = row.exclude_amount
|
||||
db.add(clone)
|
||||
db.flush()
|
||||
return len(rows)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 阈值与计算口径注入
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def apply_sys_config(db: Session) -> dict[str, str]:
|
||||
"""把系统参数表灌进计算内核:阈值 + ``calc.*`` 口径。
|
||||
|
||||
每次计算前都要走这一趟。口径存的是库而不是配置文件,多进程部署时别的 worker
|
||||
看不见这次保存,只有算之前重新读一遍,才能保证快照里的数字和快照里的版本号
|
||||
说的是同一套口径。
|
||||
"""
|
||||
rows = db.execute(select(SystemConfig)).scalars().all()
|
||||
values = {row.code: str(row.value) for row in rows}
|
||||
calc_validate.set_thresholds(values)
|
||||
calc_rules.apply(values)
|
||||
return values
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Revision
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def get_or_create_revision(db: Session, project_id: int, module: str, actor: Account) -> Revision:
|
||||
"""取当前可编辑的版本;没有就开一个 1 版。
|
||||
|
||||
已批准之后再进来编辑,会基于最新版开新版本(``based_on_id`` 指过去),老版本
|
||||
原样留着当历史,界面上"版本"页签能翻。
|
||||
"""
|
||||
editable = db.execute(
|
||||
select(Revision)
|
||||
.where(
|
||||
Revision.project_id == project_id,
|
||||
Revision.module == module,
|
||||
Revision.status.in_(RevisionStatus.EDITABLE),
|
||||
Revision.is_deleted.is_(False),
|
||||
)
|
||||
.order_by(Revision.version.desc())
|
||||
.limit(1)
|
||||
).scalars().first()
|
||||
if editable is not None:
|
||||
return editable
|
||||
|
||||
latest = db.execute(
|
||||
select(Revision)
|
||||
.where(Revision.project_id == project_id, Revision.module == module, Revision.is_deleted.is_(False))
|
||||
.order_by(Revision.version.desc())
|
||||
.limit(1)
|
||||
).scalars().first()
|
||||
|
||||
# 预算第一次开版本 = "生成预算数据",这一步必须立项已批准。已经存在的预算版本照旧
|
||||
# 能看能改:立项后来又改出个新草稿,不该把已经在跑的预算一起锁死。
|
||||
if latest is None and module == RevisionModule.BUDGET:
|
||||
assert_initiation_approved(db, project_id)
|
||||
|
||||
revision = Revision(
|
||||
module=module,
|
||||
project_id=project_id,
|
||||
version=(latest.version + 1) if latest else 1,
|
||||
status=RevisionStatus.DRAFT,
|
||||
based_on_id=latest.id if latest else None,
|
||||
creator_id=actor.id,
|
||||
creator_name=actor.display_name or actor.account,
|
||||
)
|
||||
db.add(revision)
|
||||
db.flush()
|
||||
if latest is not None:
|
||||
_copy_lines(db, latest, revision)
|
||||
return revision
|
||||
|
||||
|
||||
LINE_FIELDS = {
|
||||
"estimate.income": ("income_type", "name", "include_amount", "tax_rate", "qty", "unit_price", "remark", "sort"),
|
||||
"estimate.cost": ("purchase_type", "name", "include_amount", "tax_rate", "qty", "unit_price",
|
||||
"product_category", "remark", "sort"),
|
||||
"estimate.other": ("bucket", "name", "exclude_amount", "manual", "remark", "sort"),
|
||||
"budget.income": ("income_type", "name", "spec", "param", "unit", "qty", "unit_price",
|
||||
"include_amount", "tax_rate", "expiration_date", "remark", "sort"),
|
||||
"budget.income_plan": ("receive_point", "receive_date", "amount", "is_earnest", "remark", "sort"),
|
||||
"budget.purchase": ("purchase_type", "category", "product_category", "name", "unit", "qty", "unit_price",
|
||||
"include_amount", "tax_rate", "contract_party", "is_underwritten", "underwritten_amount",
|
||||
"pay_date", "pay_amount", "pay_way", "remark", "sort"),
|
||||
"budget.pay_plan": ("pay_point", "pay_date", "purchase_type", "amount", "supplier", "is_earnest",
|
||||
"remark", "sort"),
|
||||
"budget.manage": ("manage_type", "item_code", "item_name", "detail", "unit", "qty", "unit_price", "total",
|
||||
"predict_method", "predict_why", "pay_date", "pay_amount", "deletable",
|
||||
"counts_to_travel_limit", "remark", "sort"),
|
||||
"budget.other_cost": ("name", "exclude_amount", "remark", "sort"),
|
||||
"budget.fund_month": ("month", "device_cost", "construction_cost", "service_cost", "other_cost",
|
||||
"manage_cost", "earnest_cost", "sale_income", "earnest_income", "interest_rate",
|
||||
"opening_balance", "manual_override"),
|
||||
}
|
||||
|
||||
|
||||
def _copy_lines(db: Session, source: Revision, target: Revision) -> None:
|
||||
"""新版本继承上一版明细。"""
|
||||
for key, (model, module) in LINE_MODELS.items():
|
||||
if module != source.module:
|
||||
continue
|
||||
rows = db.execute(select(model).where(model.revision_id == source.id)).scalars().all()
|
||||
for row in rows:
|
||||
clone = model(project_id=target.project_id, revision_id=target.id)
|
||||
for field_name in LINE_FIELDS[key]:
|
||||
setattr(clone, field_name, getattr(row, field_name))
|
||||
db.add(clone)
|
||||
db.flush()
|
||||
|
||||
|
||||
def revision_lines(db: Session, revision: Revision) -> dict[str, list[Any]]:
|
||||
out: dict[str, list[Any]] = {}
|
||||
for key, (model, module) in LINE_MODELS.items():
|
||||
if module != revision.module:
|
||||
continue
|
||||
rows = db.execute(
|
||||
select(model).where(model.revision_id == revision.id).order_by(
|
||||
getattr(model, "sort", model.id), model.id
|
||||
)
|
||||
).scalars().all()
|
||||
out[key.split(".", 1)[1]] = list(rows)
|
||||
return out
|
||||
|
||||
|
||||
def upsert_line(db: Session, revision: Revision, line_key: str, payload: dict[str, Any],
|
||||
actor: Account) -> Any:
|
||||
model, module = _model_of(line_key)
|
||||
if module != revision.module:
|
||||
raise BizError("module_mismatch", f"{line_key} 不属于{module}模块")
|
||||
_assert_editable(db, revision)
|
||||
|
||||
fields = LINE_FIELDS[line_key]
|
||||
line_id = payload.get("id")
|
||||
if line_id:
|
||||
row = db.get(model, int(line_id))
|
||||
if row is None or row.revision_id != revision.id:
|
||||
raise not_found("明细行不存在")
|
||||
else:
|
||||
row = model(revision_id=revision.id, project_id=revision.project_id)
|
||||
db.add(row)
|
||||
|
||||
for field_name in fields:
|
||||
if field_name not in payload:
|
||||
continue
|
||||
value = payload[field_name]
|
||||
setattr(row, field_name, _coerce(row, field_name, value))
|
||||
db.flush()
|
||||
recompute(db, revision, actor, trigger="edit")
|
||||
return row
|
||||
|
||||
|
||||
def delete_line(db: Session, revision: Revision, line_key: str, line_id: int, actor: Account) -> None:
|
||||
model, module = _model_of(line_key)
|
||||
if module != revision.module:
|
||||
raise BizError("module_mismatch", f"{line_key} 不属于{module}模块")
|
||||
_assert_editable(db, revision)
|
||||
row = db.get(model, line_id)
|
||||
if row is None or row.revision_id != revision.id:
|
||||
raise not_found("明细行不存在")
|
||||
if line_key == "budget.manage" and not getattr(row, "deletable", True):
|
||||
raise conflict("line_locked", "固定费用项不允许删除,可以改金额或备注")
|
||||
db.delete(row)
|
||||
db.flush()
|
||||
recompute(db, revision, actor, trigger="edit")
|
||||
|
||||
|
||||
def replace_lines(db: Session, revision: Revision, line_key: str, rows: list[dict[str, Any]],
|
||||
actor: Account) -> int:
|
||||
"""整表覆盖式保存(页面上"批量编辑后一次保存"的用法)。"""
|
||||
model, module = _model_of(line_key)
|
||||
if module != revision.module:
|
||||
raise BizError("module_mismatch", f"{line_key} 不属于{module}模块")
|
||||
_assert_editable(db, revision)
|
||||
keep_ids = {int(item["id"]) for item in rows if item.get("id")}
|
||||
existing = db.execute(select(model).where(model.revision_id == revision.id)).scalars().all()
|
||||
removed = 0
|
||||
for row in existing:
|
||||
if row.id in keep_ids:
|
||||
continue
|
||||
if line_key == "budget.manage" and not getattr(row, "deletable", True):
|
||||
continue # 固定项不能被批量保存顺手删掉
|
||||
db.delete(row)
|
||||
removed += 1
|
||||
db.flush()
|
||||
for item in rows:
|
||||
upsert_line(db, revision, line_key, item, actor)
|
||||
return removed
|
||||
|
||||
|
||||
def _model_of(line_key: str):
|
||||
if line_key not in LINE_MODELS:
|
||||
raise BizError("unknown_line", f"未知的明细类型:{line_key}")
|
||||
return LINE_MODELS[line_key]
|
||||
|
||||
|
||||
def _assert_editable(db: Session, revision: Revision) -> None:
|
||||
if revision.status not in RevisionStatus.EDITABLE:
|
||||
raise conflict(
|
||||
"revision_locked",
|
||||
f"当前版本处于「{dict_store.label(db, 'revisionStatus', revision.status, revision.status)}」,不能修改。"
|
||||
"请先撤回或等待审批结束。",
|
||||
)
|
||||
|
||||
|
||||
def _coerce(row: Any, field_name: str, value: Any) -> Any:
|
||||
column = getattr(type(row), field_name, None)
|
||||
target = getattr(column, "type", None)
|
||||
text = target.__class__.__name__.lower() if target is not None else ""
|
||||
if value in ("", None) and text not in ("numeric",):
|
||||
return None if text in ("datetime", "date") else ("" if text == "string" or "varchar" in text or "text" in text else value)
|
||||
if "numeric" in text:
|
||||
return None if value is None or value == "" else to_decimal(value)
|
||||
if text == "date" and isinstance(value, str) and value:
|
||||
return date.fromisoformat(value[:10])
|
||||
if text == "datetime" and isinstance(value, str) and value:
|
||||
return datetime.fromisoformat(value.replace("Z", ""))
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
return value
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 计算
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def recompute(db: Session, revision: Revision, actor: Account | None, *, trigger: str = "edit",
|
||||
persist_projection: bool = True) -> CalcSnapshot:
|
||||
"""重算并落快照;顺手把投影写回项目。"""
|
||||
apply_sys_config(db)
|
||||
project = db.get(Project, revision.project_id)
|
||||
if project is None:
|
||||
raise not_found("项目不存在")
|
||||
|
||||
lines = revision_lines(db, revision)
|
||||
if revision.module == RevisionModule.ESTIMATE:
|
||||
payload = calc_engine.estimate_payload(
|
||||
income_lines=lines.get("income", []),
|
||||
cost_lines=lines.get("cost", []),
|
||||
other_lines=lines.get("other", []),
|
||||
)
|
||||
validation = payload.get("validation") or {"passed": True, "errors": [], "warnings": []}
|
||||
payload["validation"] = validation
|
||||
else:
|
||||
payload = calc_engine.budget_payload(
|
||||
income_lines=lines.get("income", []),
|
||||
purchase_lines=lines.get("purchase", []),
|
||||
manage_lines=lines.get("manage", []),
|
||||
other_cost_lines=lines.get("other_cost", []),
|
||||
pay_plan_lines=lines.get("pay_plan", []),
|
||||
income_plan_lines=lines.get("income_plan", []),
|
||||
fund_months=lines.get("fund_month", []),
|
||||
annual_rate=to_dec(project.advance_interest_rate),
|
||||
plan_start=_month_of(project.plan_start),
|
||||
plan_end=_month_of(project.plan_end),
|
||||
)
|
||||
_persist_fund_derived(db, revision, payload)
|
||||
if revision.status in RevisionStatus.EDITABLE:
|
||||
apply_budget_control(db, project, payload)
|
||||
|
||||
snapshot = CalcSnapshot(
|
||||
module=revision.module,
|
||||
project_id=revision.project_id,
|
||||
revision_id=revision.id,
|
||||
calc_version=payload.get("calc_version") or calc_engine.calc_version(),
|
||||
trigger=trigger,
|
||||
payload_json=json.dumps(payload, ensure_ascii=False),
|
||||
validation_json=json.dumps(payload.get("validation") or {}, ensure_ascii=False),
|
||||
account_id=actor.id if actor else None,
|
||||
account_name=(actor.display_name or actor.account) if actor else "",
|
||||
)
|
||||
db.add(snapshot)
|
||||
db.flush()
|
||||
|
||||
revision.snapshot_id = snapshot.id
|
||||
revision.calc_version = snapshot.calc_version
|
||||
|
||||
if persist_projection:
|
||||
apply_projection(db, project, payload, snapshot.id)
|
||||
return snapshot
|
||||
|
||||
|
||||
#: 预算控制读的两个业务参数(在「系统 → 业务参数」里改,保存即生效)
|
||||
BUDGET_CONTROL_RATE_CODE = "budget.over_initiation_rate"
|
||||
BUDGET_CONTROL_ACTION_CODE = "budget.over_initiation_action"
|
||||
|
||||
#: 比的两项:预算的合同额/采购额 vs 立项批准那一刻的同一口径
|
||||
BUDGET_CONTROL_METRICS: tuple[tuple[str, str, str, str], ...] = (
|
||||
("contract_amount", "contractAmount", "合同额", "预算收入明细含税合计超出立项批准值"),
|
||||
("purchase", "purchaseInclude", "采购成本", "预算采购成本含税合计超出立项批准值"),
|
||||
)
|
||||
|
||||
|
||||
def budget_control_settings(db: Session) -> tuple[Decimal, str]:
|
||||
rows = dict(db.execute(select(SystemConfig.code, SystemConfig.value)).all())
|
||||
rate = to_dec(rows.get(BUDGET_CONTROL_RATE_CODE) or 0)
|
||||
action = (rows.get(BUDGET_CONTROL_ACTION_CODE) or "block").strip().lower()
|
||||
return (rate if rate > 0 else ZERO, "warn" if action == "warn" else "block")
|
||||
|
||||
|
||||
def apply_budget_control(db: Session, project: Project, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""把"预算超立项基线"写进这次计算的校验报告。
|
||||
|
||||
写成 ``errors`` 就等于拦住送审(送审只看 ``validation.errors``),写成
|
||||
``warnings`` 只在送审前提示一句——动作是哪一种由业务参数定,不写死在代码里。
|
||||
基线缺失(立项没批或快照丢了)时不加任何一条:宁可不拦,也不拿一个凭空的
|
||||
0 当基线,那会把所有预算都拦死。
|
||||
"""
|
||||
rate, action = budget_control_settings(db)
|
||||
baseline = initiation_baseline(db, project.id)
|
||||
report = payload.setdefault("validation", {"passed": True, "errors": [], "warnings": []})
|
||||
report["budget_control"] = {"rate": f"{rate}", "action": action,
|
||||
"baseline": baseline, "items": []}
|
||||
if not baseline or rate <= 0:
|
||||
return report
|
||||
|
||||
profit = payload.get("profit") or {}
|
||||
groups = payload.get("groups") or {}
|
||||
current = {
|
||||
"contract_amount": to_dec(payload.get("contract_amount") or profit.get("income_total")),
|
||||
"purchase": sum((to_dec((b or {}).get("include")) for b in (groups.get("purchase") or {}).values()),
|
||||
ZERO),
|
||||
}
|
||||
allowed = (Decimal("100") + rate) / Decimal("100")
|
||||
for key, baseline_key, label, message in BUDGET_CONTROL_METRICS:
|
||||
limit = to_dec(baseline.get(baseline_key)) * allowed
|
||||
value = current.get(key, ZERO)
|
||||
if limit <= 0 or value <= limit:
|
||||
continue
|
||||
over = (value / to_dec(baseline.get(baseline_key)) - Decimal("1")) * Decimal("100") if to_dec(baseline.get(baseline_key)) > 0 else ZERO
|
||||
item = {
|
||||
"code": f"over_initiation_{key}",
|
||||
"metric": label,
|
||||
"baseline": money_str(baseline.get(baseline_key)),
|
||||
"current": money_str(value),
|
||||
"limit": money_str(limit),
|
||||
"over_rate": f"{over:.2f}",
|
||||
}
|
||||
report["budget_control"]["items"].append(item)
|
||||
entry = {"field": "budget.control",
|
||||
"message": f"{message}:基线 {money_str(baseline.get(baseline_key))},"
|
||||
f"允许到 {money_str(limit)}(+{rate}%),当前 {money_str(value)}",
|
||||
"level": action}
|
||||
(report["errors"] if action == "block" else report["warnings"]).append(entry)
|
||||
report["passed"] = not report["errors"]
|
||||
return report
|
||||
|
||||
|
||||
def header_of(revision: Revision) -> dict[str, Any]:
|
||||
"""预算/立项表头字段(合同名称、解决方案协同…),存在版本上。"""
|
||||
try:
|
||||
data = json.loads(revision.header_json or "{}")
|
||||
except json.JSONDecodeError:
|
||||
return {}
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def save_header(revision: Revision, values: dict[str, Any]) -> dict[str, Any]:
|
||||
merged = header_of(revision)
|
||||
merged.update({k: v for k, v in values.items() if k in BUDGET_HEADER_FIELDS})
|
||||
revision.header_json = json.dumps(merged, ensure_ascii=False)
|
||||
return merged
|
||||
|
||||
|
||||
#: 表头允许前端写的键,别的键(比如基线)只读,别让页面把冻结口径改花
|
||||
BUDGET_HEADER_FIELDS = ("contract_name", "resolve_plan_synergy", "income_detail_attr",
|
||||
"cost_detail_attr", "remark")
|
||||
|
||||
|
||||
def _payload_line_count(payload: dict[str, Any]) -> int:
|
||||
groups = (payload or {}).get("groups") or {}
|
||||
return sum(int((bucket or {}).get("count") or 0)
|
||||
for buckets in groups.values() for bucket in buckets.values())
|
||||
|
||||
|
||||
def apply_projection(db: Session, project: Project, payload: dict[str, Any], snapshot_id: int) -> None:
|
||||
"""把快照里的关键指标写回项目主档(明确标注为投影)。
|
||||
|
||||
一条例外:**这次计算一行明细都没有就不投影**。立项表上的合同金额、毛利、
|
||||
产品金额允许先手填(截图里那几栏就是录入框),而"还没录明细"时算出来的
|
||||
合同额必然是 0——照写下去等于把人刚填的数擦成零,还是静默擦的。
|
||||
"""
|
||||
if _payload_line_count(payload):
|
||||
for field_name, value in calc_engine.project_projection(payload).items():
|
||||
if field_name == "calc_version":
|
||||
continue
|
||||
if hasattr(project, field_name):
|
||||
setattr(project, field_name, value)
|
||||
project.calc_version = payload.get("calc_version") or calc_engine.calc_version()
|
||||
project.calc_snapshot_id = snapshot_id
|
||||
project.calc_at = datetime.now()
|
||||
|
||||
|
||||
def _persist_fund_derived(db: Session, revision: Revision, payload: dict[str, Any]) -> None:
|
||||
"""把重算出来的派生列写回 ``budget_fund_month``。
|
||||
|
||||
注意只写派生列:人工输入列一律不动,这样"资金计划表"页面上填的东西不会被覆盖,
|
||||
和 ``TO-BE-PLAN-001`` 的要求一致。
|
||||
"""
|
||||
months = {item["month"]: item for item in (payload.get("fund_plan") or {}).get("months", [])}
|
||||
rows = db.execute(select(BudgetFundMonth).where(BudgetFundMonth.revision_id == revision.id)).scalars().all()
|
||||
for row in rows:
|
||||
derived = months.get(row.month)
|
||||
if derived is None:
|
||||
continue
|
||||
row.total_cost = to_dec(derived["total_cost"])
|
||||
row.total_income = to_dec(derived["total_income"])
|
||||
row.balance = to_dec(derived["balance"])
|
||||
row.underwritten_plan = to_dec(derived["underwritten_plan"])
|
||||
row.repayment_plan = to_dec(derived["repayment_plan"])
|
||||
row.capital_interest = to_dec(derived["capital_interest"])
|
||||
row.calc_version = payload.get("calc_version") or calc_engine.calc_version()
|
||||
db.flush()
|
||||
|
||||
|
||||
def snapshot_payload(snapshot: CalcSnapshot | None) -> dict[str, Any]:
|
||||
if snapshot is None:
|
||||
return {}
|
||||
try:
|
||||
return json.loads(snapshot.payload_json or "{}")
|
||||
except json.JSONDecodeError:
|
||||
return {}
|
||||
|
||||
|
||||
def current_snapshot(db: Session, revision: Revision) -> CalcSnapshot | None:
|
||||
if revision.snapshot_id:
|
||||
snapshot = db.get(CalcSnapshot, revision.snapshot_id)
|
||||
if snapshot is not None:
|
||||
return snapshot
|
||||
return db.execute(
|
||||
select(CalcSnapshot)
|
||||
.where(CalcSnapshot.revision_id == revision.id)
|
||||
.order_by(CalcSnapshot.id.desc())
|
||||
.limit(1)
|
||||
).scalars().first()
|
||||
|
||||
|
||||
def serialize_line(row: Any) -> dict[str, Any]:
|
||||
"""明细行转 JSON。金额一律字符串,避免 JS 浮点。"""
|
||||
out: dict[str, Any] = {"id": row.id}
|
||||
for key, value in row.__dict__.items():
|
||||
if key.startswith("_"):
|
||||
continue
|
||||
out[key] = _json_value(value)
|
||||
return out
|
||||
|
||||
|
||||
def _json_value(value: Any) -> Any:
|
||||
if isinstance(value, Decimal):
|
||||
return f"{value:.4f}".rstrip("0").rstrip(".") if value != value.to_integral_value() else f"{value:.2f}"
|
||||
if isinstance(value, datetime):
|
||||
return value.isoformat(sep=" ", timespec="seconds")
|
||||
if isinstance(value, date):
|
||||
return value.isoformat()
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
return value
|
||||
|
||||
|
||||
def _month_of(value: date | datetime | None) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
return value.strftime("%Y-%m")
|
||||
|
||||
|
||||
def set_project_stage(db: Session, project: Project, stage: int, actor: Account, remark: str = "") -> None:
|
||||
if project.stage == stage:
|
||||
return
|
||||
project.stage = stage
|
||||
db.add(ProjectStageLog(
|
||||
project_id=project.id, stage=stage,
|
||||
stage_label=dict_store.label(db, "projectStage", stage, str(stage)),
|
||||
account_id=actor.id, account_name=actor.display_name or actor.account, remark=remark,
|
||||
))
|
||||
db.flush()
|
||||
|
||||
|
||||
def sync_owner_member(db: Session, project: Project) -> None:
|
||||
"""保证"项目负责人"一定在成员表里,否则数据权限的"我参与的"会漏掉他。"""
|
||||
if not project.principal_id:
|
||||
return
|
||||
exists = db.execute(
|
||||
select(ProjectMember.id).where(
|
||||
ProjectMember.project_id == project.id,
|
||||
ProjectMember.account_id == project.principal_id,
|
||||
)
|
||||
).scalar()
|
||||
if exists:
|
||||
return
|
||||
account = db.get(Account, project.principal_id)
|
||||
db.add(ProjectMember(
|
||||
project_id=project.id, account_id=project.principal_id,
|
||||
account_name=(account.display_name if account else project.principal) or "",
|
||||
member_role=ProjectMemberRole.OWNER,
|
||||
))
|
||||
db.flush()
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
"""计算内核。所有金额、税率、利润、资金计划的唯一实现。
|
||||
|
||||
* :mod:`~app.service.calc.rules` —— 口径参数(系统参数表里,界面上改)
|
||||
* :mod:`~app.service.calc.money` —— 舍入口径
|
||||
* :mod:`~app.service.calc.tax` —— 价内税 ``TAX-001`` / ``TAX-002``
|
||||
* :mod:`~app.service.calc.profit` —— 利润阶梯
|
||||
* :mod:`~app.service.calc.fund_plan` —— 月度资金计划
|
||||
* :mod:`~app.service.calc.validate` —— 结果校验
|
||||
* :mod:`~app.service.calc.engine` —— 编排成快照
|
||||
"""
|
||||
|
||||
from . import engine, fund_plan, money, profit, rules, tax, validate # noqa: F401
|
||||
|
||||
__all__ = ["engine", "fund_plan", "money", "profit", "rules", "tax", "validate"]
|
||||
|
|
@ -0,0 +1,447 @@
|
|||
"""把明细行算成一份完整快照。
|
||||
|
||||
这是唯一的计算入口:概算、预算、审批、导出、预览都调这里,算完落成
|
||||
``calc_snapshot`` 并把投影写回 ``project``(``TO-BE-ARCH-001`` / ``TO-BE-ARCH-003``)。
|
||||
|
||||
输出 JSON 的形状就是前端"预算信息"页签要显示的结构,因此前端不需要再算一遍。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from decimal import Decimal
|
||||
from functools import partial
|
||||
from typing import Any, Iterable, Sequence
|
||||
|
||||
from . import fund_plan, profit, tax, validate
|
||||
from .mapping import INCOME_TYPE_TO_KEY, PRODUCT_CATEGORY_TO_FIELD, PURCHASE_TYPE_TO_KEY
|
||||
from .money import ZERO, money_str, round_money, to_dec
|
||||
from .rules import RULES
|
||||
|
||||
|
||||
def calc_version() -> str:
|
||||
"""当前生效的计算口径版本。界面上能改,所以每次取都现读,不在导入时抄一份。"""
|
||||
return RULES.version
|
||||
|
||||
|
||||
@dataclass
|
||||
class Line:
|
||||
"""从 ORM 行折出来的通用输入,避免计算器依赖 SQLAlchemy 对象。"""
|
||||
|
||||
income_type: int = 0
|
||||
purchase_type: int = 0
|
||||
include_amount: Decimal = ZERO
|
||||
qty: Decimal = ZERO
|
||||
unit_price: Decimal = ZERO
|
||||
tax_rate: Decimal = ZERO
|
||||
exclude_amount: Decimal = ZERO
|
||||
total: Decimal | None = None
|
||||
item_code: str = ""
|
||||
counts_to_travel_limit: bool = False
|
||||
product_category: str = ""
|
||||
bucket: str = ""
|
||||
manual: bool = True
|
||||
purchase_type_extra: int = 0
|
||||
is_earnest: bool = False
|
||||
raw: dict[str, Any] | None = None
|
||||
|
||||
|
||||
def _as_line(row: Any) -> Line:
|
||||
"""ORM 行或 dict 都能吃。"""
|
||||
get = partial(_value_of, row)
|
||||
return Line(
|
||||
income_type=int(get("income_type") or 0),
|
||||
purchase_type=int(get("purchase_type") or 0),
|
||||
include_amount=get("include_amount"),
|
||||
qty=to_dec(get("qty")),
|
||||
unit_price=to_dec(get("unit_price")),
|
||||
tax_rate=to_dec(get("tax_rate")),
|
||||
exclude_amount=to_dec(get("exclude_amount")),
|
||||
total=get("total"),
|
||||
item_code=str(get("item_code") or ""),
|
||||
counts_to_travel_limit=bool(get("counts_to_travel_limit") or False),
|
||||
product_category=str(get("product_category") or ""),
|
||||
bucket=str(get("bucket") or ""),
|
||||
manual=bool(get("manual") if get("manual") is not None else True),
|
||||
is_earnest=bool(get("is_earnest") or False),
|
||||
raw=row if isinstance(row, dict) else None,
|
||||
)
|
||||
|
||||
|
||||
def _price_tax_total(lines: Sequence[Line], *, exclude_of_manual_line: bool = False) -> dict[str, Any]:
|
||||
"""按"人工含税优先 → 数量×单价 → 价内税拆分"汇总一组明细。"""
|
||||
results = [tax.line(item.include_amount, item.qty, item.unit_price, item.tax_rate) for item in lines]
|
||||
include = sum((item.include for item in results), ZERO)
|
||||
exclude = sum((item.exclude for item in results), ZERO)
|
||||
tax_total = sum((item.tax for item in results), ZERO)
|
||||
return {
|
||||
"count": len(results),
|
||||
"include": money_str(round_money(include)),
|
||||
"exclude": money_str(round_money(exclude)),
|
||||
"tax": money_str(round_money(tax_total)),
|
||||
"_include": round_money(include),
|
||||
"_exclude": round_money(exclude),
|
||||
}
|
||||
|
||||
|
||||
def group_income(lines: Iterable[Line]) -> dict[str, dict[str, Any]]:
|
||||
"""收入按 设备/工程/服务 三类汇总(``BUD-INC-001``)。"""
|
||||
buckets: dict[str, list[Line]] = {key: [] for key in INCOME_TYPE_TO_KEY.values()}
|
||||
for row in lines:
|
||||
key = INCOME_TYPE_TO_KEY.get(int(row.income_type or 0))
|
||||
if key:
|
||||
buckets[key].append(row)
|
||||
return {key: _price_tax_total(items) for key, items in buckets.items()}
|
||||
|
||||
|
||||
def group_purchase(lines: Iterable[Line]) -> dict[str, dict[str, Any]]:
|
||||
"""采购按 设备/施工/服务/其他 四类汇总(``BUD-COST-001``)。"""
|
||||
buckets: dict[str, list[Line]] = {key: [] for key in PURCHASE_TYPE_TO_KEY.values()}
|
||||
for row in lines:
|
||||
key = PURCHASE_TYPE_TO_KEY.get(int(row.purchase_type or 0))
|
||||
if key:
|
||||
buckets[key].append(row)
|
||||
return {key: _price_tax_total(items) for key, items in buckets.items()}
|
||||
|
||||
|
||||
def group_product_category(lines: Iterable[Line]) -> dict[str, str]:
|
||||
"""按产品归属聚合到汇智/华智/华三/紫光其他(``BUD-COST-002``)。"""
|
||||
totals: dict[str, Decimal] = {field: ZERO for field in PRODUCT_CATEGORY_TO_FIELD.values()}
|
||||
for row in lines:
|
||||
field = PRODUCT_CATEGORY_TO_FIELD.get(row.product_category)
|
||||
if not field:
|
||||
continue
|
||||
totals[field] += to_dec(row.include_amount) or round_money(to_dec(row.qty) * to_dec(row.unit_price))
|
||||
return {field: money_str(round_money(value)) for field, value in totals.items()}
|
||||
|
||||
|
||||
def manage_total(lines: Sequence[Line]) -> tuple[Decimal, Decimal]:
|
||||
"""项目管理费用总额,以及其中计入差旅/业务费限额的部分(``BUD-VAL-001`` 的左值)。
|
||||
|
||||
``BUD-PM-001``:人工总额优先,否则 数量×单价;项目管理成本视为不含税。
|
||||
"""
|
||||
total = ZERO
|
||||
travel = ZERO
|
||||
for row in lines:
|
||||
if row.total is not None and str(row.total).strip() != "":
|
||||
value = round_money(row.total)
|
||||
else:
|
||||
value = round_money(to_dec(row.qty) * to_dec(row.unit_price))
|
||||
total += value
|
||||
if row.counts_to_travel_limit:
|
||||
travel += value
|
||||
return round_money(total), round_money(travel)
|
||||
|
||||
|
||||
def other_lines_total(lines: Sequence[Line], bucket: str) -> Decimal:
|
||||
return round_money(sum((to_dec(row.exclude_amount) for row in lines if row.bucket == bucket), ZERO))
|
||||
|
||||
|
||||
def company_manage_manual(lines: Sequence[Line]) -> Decimal | None:
|
||||
"""概算里人工填的公司管理费用;没有人工行就返回 None 让利润层按费率派生。"""
|
||||
for row in lines:
|
||||
if row.bucket == "company_manage" and row.manual:
|
||||
return to_dec(row.exclude_amount)
|
||||
return None
|
||||
|
||||
|
||||
def estimate_payload(
|
||||
*,
|
||||
income_lines: Sequence[Any],
|
||||
cost_lines: Sequence[Any],
|
||||
other_lines: Sequence[Any],
|
||||
) -> dict[str, Any]:
|
||||
"""概算快照。与预算共用同一个利润内核(``EST-003`` 说明老系统就是这么复用的)。"""
|
||||
incomes = [_as_line(row) for row in income_lines]
|
||||
purchases = [_as_line(row) for row in cost_lines]
|
||||
others = [_as_line(row) for row in other_lines]
|
||||
|
||||
income_group = group_income(incomes)
|
||||
purchase_group = group_purchase(purchases)
|
||||
manage, travel = manage_total([row for row in others if row.bucket == "project_manage"])
|
||||
other_cost = other_lines_total(others, "other_cost")
|
||||
finance = other_lines_total(others, "capital_interest")
|
||||
|
||||
result = profit.calculate(
|
||||
profit.ProfitInput(
|
||||
income_device=_ex(income_group, "device"),
|
||||
income_engineering=_ex(income_group, "engineering"),
|
||||
income_service=_ex(income_group, "service"),
|
||||
purchase_device=_ex(purchase_group, "device"),
|
||||
purchase_construction=_ex(purchase_group, "construction"),
|
||||
purchase_service=_ex(purchase_group, "service"),
|
||||
purchase_other=_ex(purchase_group, "other"),
|
||||
project_manage=manage,
|
||||
other_cost=other_cost,
|
||||
finance_cost=finance,
|
||||
company_manage=company_manage_manual(others),
|
||||
)
|
||||
)
|
||||
return {
|
||||
"calc_version": calc_version(),
|
||||
"groups": {
|
||||
"income": {k: _public(v) for k, v in income_group.items()},
|
||||
"purchase": {k: _public(v) for k, v in purchase_group.items()},
|
||||
},
|
||||
"product_amounts": group_product_category(purchases),
|
||||
"manage": {"total": money_str(manage), "travel_business": money_str(travel)},
|
||||
"other_cost": money_str(other_cost),
|
||||
"finance_cost": money_str(finance),
|
||||
"profit": result.to_dict(),
|
||||
}
|
||||
|
||||
|
||||
def budget_payload(
|
||||
*,
|
||||
income_lines: Sequence[Any],
|
||||
purchase_lines: Sequence[Any],
|
||||
manage_lines: Sequence[Any],
|
||||
other_cost_lines: Sequence[Any] = (),
|
||||
pay_plan_lines: Sequence[Any] = (),
|
||||
income_plan_lines: Sequence[Any] = (),
|
||||
fund_months: Sequence[Any] = (),
|
||||
annual_rate: Decimal = ZERO,
|
||||
plan_start: str = "",
|
||||
plan_end: str = "",
|
||||
income_tax: Decimal = ZERO,
|
||||
) -> dict[str, Any]:
|
||||
"""预算快照:八个页签要显示的东西一次算完。"""
|
||||
incomes = [_as_line(row) for row in income_lines]
|
||||
purchases = [_as_line(row) for row in purchase_lines]
|
||||
manages = [_as_line(row) for row in manage_lines]
|
||||
other_costs = [_as_line(row) for row in other_cost_lines]
|
||||
|
||||
income_group = group_income(incomes)
|
||||
purchase_group = group_purchase(purchases)
|
||||
manage_sum, travel_business = manage_total(manages)
|
||||
other_cost = round_money(sum((to_dec(row.exclude_amount) for row in other_costs), ZERO))
|
||||
|
||||
# 资金计划:没录入月份时按收付款计划自动推导(TO-BE-PLAN-001 的"付款计划变了就整条重算")
|
||||
months = [_as_fund_month(row, annual_rate) for row in fund_months]
|
||||
if not months:
|
||||
derived = fund_plan.derive_months(
|
||||
[_plan_dict(row, "pay") for row in pay_plan_lines],
|
||||
[_plan_dict(row, "receive") for row in income_plan_lines],
|
||||
[_manage_dict(row) for row in manage_lines],
|
||||
months=[],
|
||||
annual_rate=to_dec(annual_rate),
|
||||
)
|
||||
months = derived
|
||||
|
||||
plan = fund_plan.calculate(months)
|
||||
|
||||
result = profit.calculate(
|
||||
profit.ProfitInput(
|
||||
income_device=_ex(income_group, "device"),
|
||||
income_engineering=_ex(income_group, "engineering"),
|
||||
income_service=_ex(income_group, "service"),
|
||||
purchase_device=_ex(purchase_group, "device"),
|
||||
purchase_construction=_ex(purchase_group, "construction"),
|
||||
purchase_service=_ex(purchase_group, "service"),
|
||||
purchase_other=_ex(purchase_group, "other"),
|
||||
project_manage=manage_sum,
|
||||
other_cost=other_cost,
|
||||
finance_cost=plan.finance_cost,
|
||||
company_manage=None,
|
||||
income_tax=to_dec(income_tax),
|
||||
)
|
||||
)
|
||||
|
||||
report = validate.ValidationReport()
|
||||
v = build_validations(
|
||||
report,
|
||||
result=result,
|
||||
manage_total=manage_sum,
|
||||
travel_business=travel_business,
|
||||
purchase_group=purchase_group,
|
||||
pay_plan_lines=pay_plan_lines,
|
||||
plan=plan,
|
||||
other_cost=other_cost,
|
||||
income_group=income_group,
|
||||
income_plan_lines=income_plan_lines,
|
||||
months=[m.month for m in plan.months],
|
||||
plan_start=plan_start,
|
||||
plan_end=plan_end,
|
||||
)
|
||||
|
||||
return {
|
||||
"calc_version": calc_version(),
|
||||
"groups": {
|
||||
"income": {k: _public(x) for k, x in income_group.items()},
|
||||
"purchase": {k: _public(x) for k, x in purchase_group.items()},
|
||||
},
|
||||
"product_amounts": group_product_category(purchases),
|
||||
"manage": {"total": money_str(manage_sum), "travel_business": money_str(travel_business)},
|
||||
"other_cost": money_str(other_cost),
|
||||
"contract_amount": _include_all(income_group),
|
||||
"fund_plan": plan.to_dict(),
|
||||
"profit": result.to_dict(),
|
||||
"validation": v.to_dict(),
|
||||
}
|
||||
|
||||
|
||||
def build_validations(
|
||||
report: validate.ValidationReport,
|
||||
*,
|
||||
result: profit.ProfitResult,
|
||||
manage_total: Decimal,
|
||||
travel_business: Decimal,
|
||||
purchase_group: dict[str, dict[str, Any]],
|
||||
pay_plan_lines: Sequence[Any],
|
||||
plan: fund_plan.FundPlanResult,
|
||||
other_cost: Decimal,
|
||||
income_group: dict[str, dict[str, Any]],
|
||||
income_plan_lines: Sequence[Any] = (),
|
||||
months: Sequence[str],
|
||||
plan_start: str,
|
||||
plan_end: str,
|
||||
) -> validate.ValidationReport:
|
||||
"""跑一遍所有结果校验。"""
|
||||
validate.check_travel_limit(report, result.gross_a, manage_total, travel_business)
|
||||
validate.check_contribution_rate(report, result.contribution_rate)
|
||||
|
||||
pay_by_type: dict[int, Decimal] = {}
|
||||
for row in pay_plan_lines or []:
|
||||
if _flag_of(row, "is_earnest"):
|
||||
continue
|
||||
code = int(_value_of(row, "purchase_type") or 0)
|
||||
pay_by_type[code] = pay_by_type.get(code, ZERO) + _amount_of(row)
|
||||
purchase_by_type = {
|
||||
1: _inc(purchase_group, "device"),
|
||||
2: _inc(purchase_group, "construction"),
|
||||
3: _inc(purchase_group, "service"),
|
||||
4: _inc(purchase_group, "other"),
|
||||
}
|
||||
# 只有真的录了付款计划才做勾稽,否则一进来就满屏报错,业务不会认这个体验
|
||||
if pay_by_type:
|
||||
validate.check_pay_plan_reconciles(report, pay_by_type, purchase_by_type)
|
||||
|
||||
purchase_include_total = round_money(sum(purchase_by_type.values()))
|
||||
earnest_cost_total = round_money(sum(
|
||||
_amount_of(row) for row in (pay_plan_lines or []) if _flag_of(row, "is_earnest")
|
||||
))
|
||||
earnest_income_total = round_money(sum(
|
||||
_amount_of(row) for row in (income_plan_lines or []) if _flag_of(row, "is_earnest")
|
||||
))
|
||||
validate.check_fund_plan_totals(
|
||||
report,
|
||||
fund_cost_total=plan.total_cost,
|
||||
fund_income_total=plan.total_income,
|
||||
purchase_include_total=purchase_include_total,
|
||||
earnest_cost_total=earnest_cost_total,
|
||||
manage_total=manage_total,
|
||||
income_include_total=_include_all_decimal(income_group),
|
||||
earnest_income_total=earnest_income_total,
|
||||
)
|
||||
validate.check_fund_months(report, list(months), plan_start, plan_end)
|
||||
return report
|
||||
|
||||
|
||||
def _as_fund_month(row: Any, annual_rate: Decimal) -> fund_plan.FundMonthInput:
|
||||
get = partial(_value_of, row)
|
||||
return fund_plan.FundMonthInput(
|
||||
month=str(get("month") or ""),
|
||||
device_cost=to_dec(get("device_cost")),
|
||||
construction_cost=to_dec(get("construction_cost")),
|
||||
service_cost=to_dec(get("service_cost")),
|
||||
other_cost=to_dec(get("other_cost")),
|
||||
manage_cost=to_dec(get("manage_cost")),
|
||||
earnest_cost=to_dec(get("earnest_cost")),
|
||||
sale_income=to_dec(get("sale_income")),
|
||||
earnest_income=to_dec(get("earnest_income")),
|
||||
interest_rate=to_dec(get("interest_rate")) or to_dec(annual_rate),
|
||||
opening_balance=to_dec(get("opening_balance")),
|
||||
)
|
||||
|
||||
|
||||
def _plan_dict(row: Any, kind: str) -> dict[str, Any]:
|
||||
get = partial(_value_of, row)
|
||||
# 收款计划用 receive_date、付款计划用 pay_date,老库里两张表字段名不同;
|
||||
# 两边都接受任一种写法,迁移与前端两种 payload 都能喂进来。
|
||||
pay_at = get("pay_date") or get("pay_time")
|
||||
receive_at = get("receive_date") or get("receive_time") or pay_at
|
||||
return {
|
||||
"pay_date": pay_at,
|
||||
"receive_date": receive_at,
|
||||
"amount": get("amount"),
|
||||
"purchase_type": get("purchase_type"),
|
||||
"is_earnest": get("is_earnest"),
|
||||
}
|
||||
|
||||
|
||||
def _value_of(row: Any, key: str, default: Any = None) -> Any:
|
||||
"""ORM 行与 dict 通吃的取值。"""
|
||||
if isinstance(row, dict):
|
||||
return row.get(key, default)
|
||||
return getattr(row, key, default)
|
||||
|
||||
|
||||
def _amount_of(row: Any) -> Decimal:
|
||||
return to_dec(_value_of(row, "amount"))
|
||||
|
||||
|
||||
def _flag_of(row: Any, key: str) -> bool:
|
||||
return bool(_value_of(row, key) or False)
|
||||
|
||||
|
||||
def _manage_dict(row: Any) -> dict[str, Any]:
|
||||
"""项目管理费用行 -> 资金计划输入。没录支出时间时退回按总额计。"""
|
||||
return {
|
||||
"pay_date": _value_of(row, "pay_date") or _value_of(row, "pay_time"),
|
||||
"pay_amount": _value_of(row, "pay_amount") or _value_of(row, "total"),
|
||||
"total": _value_of(row, "total"),
|
||||
}
|
||||
|
||||
|
||||
def _public(block: dict[str, Any]) -> dict[str, Any]:
|
||||
"""去掉内部键,只留对外字段。"""
|
||||
return {k: v for k, v in block.items() if not k.startswith("_")}
|
||||
|
||||
|
||||
def _ex(groups: dict[str, dict[str, Any]], key: str) -> Decimal:
|
||||
return to_dec(groups.get(key, {}).get("_exclude"))
|
||||
|
||||
|
||||
def _inc(groups: dict[str, dict[str, Any]], key: str) -> Decimal:
|
||||
return to_dec(groups.get(key, {}).get("_include"))
|
||||
|
||||
|
||||
def _include_all(groups: dict[str, dict[str, Any]]) -> str:
|
||||
return money_str(_include_all_decimal(groups))
|
||||
|
||||
|
||||
def _include_all_decimal(groups: dict[str, dict[str, Any]]) -> Decimal:
|
||||
return round_money(sum((_inc(groups, key) for key in INCOME_TYPE_TO_KEY.values()), ZERO))
|
||||
|
||||
|
||||
def project_projection(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""从快照抽出要写回 ``project`` 的投影列。"""
|
||||
profit_block = payload.get("profit") or {}
|
||||
fund = payload.get("fund_plan") or {}
|
||||
products = payload.get("product_amounts") or {}
|
||||
|
||||
def dec(value: object) -> Decimal:
|
||||
return to_dec(value)
|
||||
|
||||
rate = lambda key: _rate_of(profit_block, key) # noqa: E731
|
||||
return {
|
||||
"contract_amount": dec(payload.get("contract_amount") or profit_block.get("income_total")),
|
||||
"gross_profit_a": dec(profit_block.get("gross_a")),
|
||||
"gross_profit_a_rate": rate("gross_a_rate"),
|
||||
"gross_profit": dec(profit_block.get("gross_b")),
|
||||
"gross_profit_rate": rate("gross_b_rate"),
|
||||
"contribution_profit": dec(profit_block.get("contribution")),
|
||||
"contribution_profit_rate": rate("contribution_rate"),
|
||||
"advance_plan_total": dec(fund.get("underwritten_total")),
|
||||
"advance_interest_amount": dec(fund.get("interest_total")),
|
||||
"advance_peak_month": str(fund.get("peak_month") or ""),
|
||||
"advance_peak_value": dec(fund.get("peak_value")),
|
||||
"calc_version": payload.get("calc_version") or calc_version(),
|
||||
**{key: dec(value) for key, value in products.items()},
|
||||
}
|
||||
|
||||
|
||||
def _rate_of(profit_block: dict[str, Any], key: str) -> Decimal:
|
||||
block = profit_block.get(key) or {}
|
||||
value = block.get("value")
|
||||
return to_dec(value) if value is not None else ZERO
|
||||
|
|
@ -0,0 +1,260 @@
|
|||
"""月度资金计划:``PLAN-001`` / ``PLAN-ADV-001`` / ``PLAN-REPAY-001`` / ``PLAN-INT-001``。
|
||||
|
||||
三条硬性规则(对应文档的 TO-BE-PLAN-001 / RISK-PLAN-DERIVED-001):
|
||||
|
||||
1. 只把人工输入当事实,所有派生列(总支出、总收入、余额、垫资、还款、利息)由这里
|
||||
按月份顺序**整条**重算,绝不允许"付款计划变了就顺手覆盖四列";
|
||||
2. 月份顺序由 ``month``(YYYY-MM)字典序决定,缺月不补,但会给出校验告警;
|
||||
3. 一次调用同时产出汇总(垫资合计、真实峰值、利息合计),项目主档上的冗余指标只能
|
||||
从这份结果里取。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from decimal import Decimal
|
||||
|
||||
from .money import HUNDRED, ZERO, money_str, round_money, to_dec
|
||||
|
||||
|
||||
@dataclass
|
||||
class FundMonthInput:
|
||||
"""一个月的人工输入。"""
|
||||
|
||||
month: str
|
||||
device_cost: Decimal = ZERO
|
||||
construction_cost: Decimal = ZERO
|
||||
service_cost: Decimal = ZERO
|
||||
other_cost: Decimal = ZERO
|
||||
manage_cost: Decimal = ZERO
|
||||
earnest_cost: Decimal = ZERO
|
||||
sale_income: Decimal = ZERO
|
||||
earnest_income: Decimal = ZERO
|
||||
interest_rate: Decimal = ZERO # 年利率百分数
|
||||
opening_balance: Decimal = ZERO # 期初余额,首月一般 0
|
||||
|
||||
|
||||
@dataclass
|
||||
class FundMonthResult:
|
||||
month: str
|
||||
device_cost: Decimal = ZERO
|
||||
construction_cost: Decimal = ZERO
|
||||
service_cost: Decimal = ZERO
|
||||
other_cost: Decimal = ZERO
|
||||
manage_cost: Decimal = ZERO
|
||||
earnest_cost: Decimal = ZERO
|
||||
sale_income: Decimal = ZERO
|
||||
earnest_income: Decimal = ZERO
|
||||
total_cost: Decimal = ZERO
|
||||
total_income: Decimal = ZERO
|
||||
opening_balance: Decimal = ZERO
|
||||
balance: Decimal = ZERO
|
||||
underwritten_plan: Decimal = ZERO
|
||||
repayment_plan: Decimal = ZERO
|
||||
capital_interest: Decimal = ZERO
|
||||
interest_rate: Decimal = ZERO
|
||||
|
||||
def to_dict(self) -> dict[str, object]:
|
||||
return {key: money_str(value) if not isinstance(value, str) else value
|
||||
for key, value in self.__dict__.items()}
|
||||
|
||||
|
||||
@dataclass
|
||||
class FundPlanResult:
|
||||
months: list[FundMonthResult] = field(default_factory=list)
|
||||
total_cost: Decimal = ZERO
|
||||
total_income: Decimal = ZERO
|
||||
final_balance: Decimal = ZERO
|
||||
underwritten_total: Decimal = ZERO
|
||||
repayment_total: Decimal = ZERO
|
||||
interest_total: Decimal = ZERO
|
||||
peak_month: str = ""
|
||||
peak_value: Decimal = ZERO
|
||||
finance_cost: Decimal = ZERO # = interest_total,喂给利润阶梯的 F
|
||||
|
||||
def to_dict(self) -> dict[str, object]:
|
||||
return {
|
||||
"months": [m.to_dict() for m in self.months],
|
||||
"total_cost": money_str(self.total_cost),
|
||||
"total_income": money_str(self.total_income),
|
||||
"final_balance": money_str(self.final_balance),
|
||||
"underwritten_total": money_str(self.underwritten_total),
|
||||
"repayment_total": money_str(self.repayment_total),
|
||||
"interest_total": money_str(self.interest_total),
|
||||
# RISK-PLAN-STAT-001:老系统把"各月垫资之和"叫峰值金额。这里两个都给,
|
||||
# underwritten_total 复现老口径,peak_* 是名实相符的真实峰值。
|
||||
"peak_month": self.peak_month,
|
||||
"peak_value": money_str(self.peak_value),
|
||||
}
|
||||
|
||||
|
||||
def month_total_cost(row: FundMonthInput) -> Decimal:
|
||||
"""``PLAN-001``:六类支出相加。"""
|
||||
return round_money(
|
||||
to_dec(row.device_cost) + to_dec(row.construction_cost) + to_dec(row.service_cost)
|
||||
+ to_dec(row.other_cost) + to_dec(row.manage_cost) + to_dec(row.earnest_cost)
|
||||
)
|
||||
|
||||
|
||||
def month_total_income(row: FundMonthInput) -> Decimal:
|
||||
return round_money(to_dec(row.sale_income) + to_dec(row.earnest_income))
|
||||
|
||||
|
||||
def underwritten_plan(income: Decimal, expense: Decimal, prev_balance: Decimal) -> Decimal:
|
||||
"""``PLAN-ADV-001``:本月垫资。
|
||||
|
||||
收入够支出就不垫;上月已经是负余额时只补当月缺口(老算法如此,注释里也写了
|
||||
"简化表达需谨慎"),这里原样保留,不做"一次补齐历史负余额"的臆测改动。
|
||||
"""
|
||||
income, expense, prev = round_money(income), round_money(expense), round_money(prev_balance)
|
||||
if income >= expense:
|
||||
return ZERO
|
||||
gap = expense - income
|
||||
if prev < ZERO:
|
||||
return round_money(gap)
|
||||
if ZERO <= prev <= gap:
|
||||
return round_money(gap - prev)
|
||||
return ZERO
|
||||
|
||||
|
||||
def repayment_plan(income: Decimal, expense: Decimal, prev_balance: Decimal) -> Decimal:
|
||||
"""``PLAN-REPAY-001``:本月还款,最多把历史负余额还到 0。"""
|
||||
income, expense, prev = round_money(income), round_money(expense), round_money(prev_balance)
|
||||
if income <= expense:
|
||||
return ZERO
|
||||
if prev >= ZERO:
|
||||
return ZERO
|
||||
return round_money(min(income - expense, -prev))
|
||||
|
||||
|
||||
def capital_interest(balance: Decimal, annual_rate_percent: Decimal) -> Decimal:
|
||||
"""``PLAN-INT-001``:月息 = max(0, −月末余额 × 年利率/100/12)。
|
||||
|
||||
``RISK-PLAN-INT-001`` 指出这个口径用的是月末余额,没有日均余额和计息天数;是否
|
||||
符合财务要求属于待确认事项,这里保持口径不变,只把公式集中到一处。
|
||||
"""
|
||||
balance = round_money(balance)
|
||||
if balance >= ZERO:
|
||||
return ZERO
|
||||
rate = to_dec(annual_rate_percent)
|
||||
if rate == ZERO:
|
||||
return ZERO
|
||||
monthly = rate / HUNDRED / Decimal("12")
|
||||
raw = -balance * monthly
|
||||
if raw <= ZERO:
|
||||
return ZERO
|
||||
return round_money(raw)
|
||||
|
||||
|
||||
def calculate(rows: list[FundMonthInput]) -> FundPlanResult:
|
||||
"""按月份顺序整条重算。"""
|
||||
result = FundPlanResult()
|
||||
ordered = sorted(rows, key=lambda item: item.month)
|
||||
previous_balance = ZERO
|
||||
peak_value = ZERO
|
||||
peak_month = ""
|
||||
|
||||
for index, row in enumerate(ordered):
|
||||
expense = month_total_cost(row)
|
||||
income = month_total_income(row)
|
||||
# 首月的"上月余额"取期初余额;后续月份用上月月末余额
|
||||
opening = to_dec(row.opening_balance) if index == 0 else previous_balance
|
||||
underwritten = underwritten_plan(income, expense, opening)
|
||||
repayment = repayment_plan(income, expense, opening)
|
||||
# PLAN-001:余额只由收支与上月余额决定。垫资/还款是并列的说明性列,
|
||||
# 不参与余额推导——把它们加进余额会把同一笔现金算两次。
|
||||
balance = round_money(income - expense + opening)
|
||||
interest = capital_interest(balance, row.interest_rate)
|
||||
|
||||
month_result = FundMonthResult(
|
||||
month=row.month,
|
||||
device_cost=round_money(row.device_cost),
|
||||
construction_cost=round_money(row.construction_cost),
|
||||
service_cost=round_money(row.service_cost),
|
||||
other_cost=round_money(row.other_cost),
|
||||
manage_cost=round_money(row.manage_cost),
|
||||
earnest_cost=round_money(row.earnest_cost),
|
||||
sale_income=round_money(row.sale_income),
|
||||
earnest_income=round_money(row.earnest_income),
|
||||
total_cost=expense,
|
||||
total_income=income,
|
||||
opening_balance=round_money(opening),
|
||||
balance=balance,
|
||||
underwritten_plan=underwritten,
|
||||
repayment_plan=repayment,
|
||||
capital_interest=interest,
|
||||
interest_rate=to_dec(row.interest_rate),
|
||||
)
|
||||
result.months.append(month_result)
|
||||
|
||||
result.total_cost = round_money(result.total_cost + expense)
|
||||
result.total_income = round_money(result.total_income + income)
|
||||
result.underwritten_total = round_money(result.underwritten_total + underwritten)
|
||||
result.repayment_total = round_money(result.repayment_total + repayment)
|
||||
result.interest_total = round_money(result.interest_total + interest)
|
||||
if underwritten > peak_value:
|
||||
peak_value, peak_month = underwritten, row.month
|
||||
previous_balance = balance
|
||||
|
||||
result.final_balance = previous_balance
|
||||
result.peak_value = peak_value
|
||||
result.peak_month = peak_month
|
||||
result.finance_cost = result.interest_total
|
||||
return result
|
||||
|
||||
|
||||
def derive_months(
|
||||
pay_plans: list[dict],
|
||||
income_plans: list[dict],
|
||||
manage_lines: list[dict],
|
||||
months: list[str],
|
||||
annual_rate: Decimal,
|
||||
) -> list[FundMonthInput]:
|
||||
"""从付款计划/收款计划/项目管理费用汇总出每月输入。
|
||||
|
||||
``PLAN-001`` 的输入来源就是这三处;用户在资金计划页手工改过的月份保留人工值
|
||||
(由调用方决定传不传进来覆盖)。
|
||||
"""
|
||||
bucket: dict[str, FundMonthInput] = {m: FundMonthInput(month=m, interest_rate=to_dec(annual_rate)) for m in months}
|
||||
|
||||
def slot(month: str | None) -> FundMonthInput | None:
|
||||
if not month:
|
||||
return None
|
||||
key = str(month)[:7]
|
||||
if key not in bucket:
|
||||
bucket[key] = FundMonthInput(month=key, interest_rate=to_dec(annual_rate))
|
||||
return bucket[key]
|
||||
|
||||
# 采购付款:按采购分类落到对应列;保证金单独一列
|
||||
from .mapping import PAY_PROJECT_TO_COLUMN
|
||||
|
||||
for plan in pay_plans or []:
|
||||
target = slot(plan.get("pay_date") or plan.get("pay_time"))
|
||||
if target is None:
|
||||
continue
|
||||
amount = to_dec(plan.get("amount"))
|
||||
if plan.get("is_earnest"):
|
||||
target.earnest_cost = round_money(target.earnest_cost + amount)
|
||||
continue
|
||||
column = PAY_PROJECT_TO_COLUMN.get(int(plan.get("purchase_type") or 0))
|
||||
if column:
|
||||
setattr(target, column, round_money(getattr(target, column) + amount))
|
||||
|
||||
for plan in income_plans or []:
|
||||
target = slot(plan.get("receive_date") or plan.get("receive_time"))
|
||||
if target is None:
|
||||
continue
|
||||
amount = to_dec(plan.get("amount"))
|
||||
if plan.get("is_earnest"):
|
||||
target.earnest_income = round_money(target.earnest_income + amount)
|
||||
else:
|
||||
target.sale_income = round_money(target.sale_income + amount)
|
||||
|
||||
for line in manage_lines or []:
|
||||
target = slot(line.get("pay_date") or line.get("pay_time"))
|
||||
if target is None:
|
||||
continue
|
||||
amount = to_dec(line.get("pay_amount")) or to_dec(line.get("total"))
|
||||
target.manage_cost = round_money(target.manage_cost + amount)
|
||||
|
||||
return list(bucket.values())
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
"""老分类码到新列名的映射,集中一处,避免散在各服务的 if/else。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
#: 采购分类 -> 资金计划里的支出列(PLAN-001 的六类支出)
|
||||
PAY_PROJECT_TO_COLUMN = {
|
||||
1: "device_cost", # 设备
|
||||
2: "construction_cost", # 施工
|
||||
3: "service_cost", # 服务
|
||||
4: "other_cost", # 其他
|
||||
}
|
||||
|
||||
#: 收入分类 -> 汇总键
|
||||
INCOME_TYPE_TO_KEY = {1: "device", 2: "engineering", 3: "service"}
|
||||
|
||||
#: 采购分类 -> 汇总键
|
||||
PURCHASE_TYPE_TO_KEY = {1: "device", 2: "construction", 3: "service", 4: "other"}
|
||||
|
||||
#: 老 project_budget_cost.type 的六个汇总位
|
||||
COST_TYPE_TO_KEY = {
|
||||
1: "device", 2: "construction", 3: "service", 4: "other",
|
||||
5: "project_manage", 6: "other_other",
|
||||
}
|
||||
|
||||
#: 产品归属编码 -> 项目主档上的金额列(BUD-COST-002)
|
||||
PRODUCT_CATEGORY_TO_FIELD = {
|
||||
"huizhi": "huizhi_amount",
|
||||
"huazhi": "huazhi_amount",
|
||||
"h3c": "h3c_amount",
|
||||
"ziguang_other": "other_product_amount",
|
||||
}
|
||||
|
||||
#: 老库 procurement_type 字典(id -> 中文名)。
|
||||
#: project_budget_cost_detail.category 存的是这张表的 id(写成字符串,"8"/"12"/"17"…),
|
||||
#: 少数老行直接存了中文名,所以迁移时两种都要认。
|
||||
#: 这里留一份是为了老库不可达时也能解释历史数据;真正导数时脚本会现查老库的表,以库里的为准。
|
||||
LEGACY_PROCUREMENT_TYPES = {
|
||||
8: "华智产品",
|
||||
9: "紫光其他产品",
|
||||
10: "华智服务",
|
||||
11: "紫光其他服务",
|
||||
12: "外购产品",
|
||||
13: "外购工程",
|
||||
14: "外购服务",
|
||||
15: "其他产品",
|
||||
16: "汇智产品",
|
||||
17: "华三产品",
|
||||
}
|
||||
|
||||
#: 老数据里可能出现的中文分类名,迁移时折成上面的编码
|
||||
LEGACY_CATEGORY_ALIASES = {
|
||||
"汇智产品": "huizhi",
|
||||
"华智产品": "huazhi",
|
||||
"华三产品": "h3c",
|
||||
"紫光其他": "ziguang_other",
|
||||
"紫光其他产品": "ziguang_other",
|
||||
# 老字典里"华智服务 / 紫光其他服务"是独立条目,但项目主档只有四个产品归属列
|
||||
# (huazhi / huizhi / h3c / other_product),按品牌归到同一桶。
|
||||
"华智服务": "huazhi",
|
||||
"紫光其他服务": "ziguang_other",
|
||||
}
|
||||
|
|
@ -0,0 +1,164 @@
|
|||
"""十进制金额与比率的基础设施。
|
||||
|
||||
老系统最大的坑之一就是"同一个指标在 Java、浏览器、Excel 三个地方各舍入一次"
|
||||
(``RISK-EXPORT-001``)。这里把舍入收成一个地方:所有计算器只能用本模块的函数,
|
||||
位数与进位方式来自 :mod:`app.service.calc.rules`(界面上可改),因此口径可追溯、可版本化。
|
||||
|
||||
约定
|
||||
====
|
||||
|
||||
* 金额一律 ``Decimal``,绝不用 ``float``;JSON 输出用字符串,避免 JS 精度问题。
|
||||
* 比率用"百分数本身"(13 表示 13%),与数据库列、前端展示保持同一口径。
|
||||
* 中间除法保留 ``rate_scale`` 位(默认 4),最终展示保留 ``money_scale`` 位(默认 2)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import (
|
||||
ROUND_CEILING,
|
||||
ROUND_DOWN,
|
||||
ROUND_FLOOR,
|
||||
ROUND_HALF_DOWN,
|
||||
ROUND_HALF_EVEN,
|
||||
ROUND_HALF_UP,
|
||||
ROUND_UP,
|
||||
Decimal,
|
||||
InvalidOperation,
|
||||
getcontext,
|
||||
)
|
||||
|
||||
from .rules import RULES
|
||||
|
||||
# 财务计算用不到 28 位以上,但留足余量避免中间除法溢出
|
||||
getcontext().prec = 34
|
||||
|
||||
ZERO = Decimal("0")
|
||||
ONE = Decimal("1")
|
||||
HUNDRED = Decimal("100")
|
||||
|
||||
_ROUNDING_MODES = {
|
||||
"HALF_UP": ROUND_HALF_UP,
|
||||
"HALF_DOWN": ROUND_HALF_DOWN,
|
||||
"HALF_EVEN": ROUND_HALF_EVEN,
|
||||
"UP": ROUND_UP,
|
||||
"DOWN": ROUND_DOWN,
|
||||
"FLOOR": ROUND_FLOOR,
|
||||
"CEILING": ROUND_CEILING,
|
||||
}
|
||||
|
||||
|
||||
def quantize_exponent(scale: int) -> Decimal:
|
||||
return Decimal(1).scaleb(-scale)
|
||||
|
||||
|
||||
def rounding_mode(name: str | None = None) -> int:
|
||||
return _ROUNDING_MODES.get((name or RULES.rounding or "HALF_UP").upper(), ROUND_HALF_UP)
|
||||
|
||||
|
||||
def to_dec(value: object) -> Decimal:
|
||||
"""杂七杂八的输入折成 Decimal;空值当 0,脏数据不炸。"""
|
||||
if value is None or value == "":
|
||||
return ZERO
|
||||
if isinstance(value, Decimal):
|
||||
return value
|
||||
if isinstance(value, bool): # bool 是 int 子类,先挡掉,别让 True 变成 1 元
|
||||
return Decimal("1") if value else ZERO
|
||||
try:
|
||||
return Decimal(str(value))
|
||||
except (InvalidOperation, ValueError):
|
||||
return ZERO
|
||||
|
||||
|
||||
def round_money(value: object, scale: int | None = None) -> Decimal:
|
||||
"""按全局口径把金额舍到分。"""
|
||||
scale = RULES.money_scale if scale is None else scale
|
||||
return to_dec(value).quantize(quantize_exponent(scale), rounding=rounding_mode())
|
||||
|
||||
|
||||
def round_rate(value: object) -> Decimal:
|
||||
"""比率中间除法保留位数(对应老代码里散落的"除法保留 4 位")。"""
|
||||
return to_dec(value).quantize(quantize_exponent(RULES.rate_scale), rounding=rounding_mode())
|
||||
|
||||
|
||||
def round_percent(value: object) -> Decimal:
|
||||
"""百分比结果保留位数(对应老 ``ROUND_HALF_UP`` 到 2 位)。"""
|
||||
return to_dec(value).quantize(quantize_exponent(RULES.percent_scale), rounding=rounding_mode())
|
||||
|
||||
|
||||
class Ratio:
|
||||
"""一次除法的结果,可能"未定义"。
|
||||
|
||||
老系统利润率在零分母时一会儿返回 0、一会儿返回"利润×100"、一会儿把分母换成 1
|
||||
(``BUD-PROFIT-002`` / ``RISK-SET-RATE-001`` / ``FINAL-RATE-001``)。这里明确成
|
||||
对象:要么有值,要么带原因,前端与导出都只能表达"未定义"而不是假装是 0。
|
||||
"""
|
||||
|
||||
__slots__ = ("value", "reason", "numerator", "denominator")
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
value: Decimal | None,
|
||||
reason: str = "",
|
||||
numerator: Decimal = ZERO,
|
||||
denominator: Decimal = ZERO,
|
||||
) -> None:
|
||||
self.value = value
|
||||
self.reason = reason
|
||||
self.numerator = numerator
|
||||
self.denominator = denominator
|
||||
|
||||
@property
|
||||
def defined(self) -> bool:
|
||||
return self.value is not None
|
||||
|
||||
def or_zero(self) -> Decimal:
|
||||
return self.value if self.value is not None else ZERO
|
||||
|
||||
def to_dict(self) -> dict[str, object]:
|
||||
return {
|
||||
"value": money_str(self.value) if self.value is not None else None,
|
||||
"defined": self.defined,
|
||||
"reason": self.reason or None,
|
||||
"numerator": money_str(self.numerator),
|
||||
"denominator": money_str(self.denominator),
|
||||
}
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover - 调试辅助
|
||||
return f"Ratio(value={self.value}, reason={self.reason!r})"
|
||||
|
||||
|
||||
def ratio(numerator: object, denominator: object, *, scale: int | None = None) -> Ratio:
|
||||
"""``numerator / denominator * 100``,并处理零分母。
|
||||
|
||||
零分母行为由 ``calc.zero_denominator`` 决定:``undefined``(默认,推荐)返回未定义
|
||||
并带原因;``zero`` 返回 0,用于与老系统逐月对账的过渡期。
|
||||
"""
|
||||
num, den = to_dec(numerator), to_dec(denominator)
|
||||
if den == ZERO:
|
||||
if RULES.zero_denominator == "zero":
|
||||
return Ratio(ZERO, "zero_denominator_treated_as_zero", num, den)
|
||||
return Ratio(None, "zero_denominator", num, den)
|
||||
value = (num / den) * HUNDRED
|
||||
scale = RULES.percent_scale if scale is None else scale
|
||||
return Ratio(value.quantize(quantize_exponent(scale), rounding=rounding_mode()), "", num, den)
|
||||
|
||||
|
||||
def money_str(value: object) -> str:
|
||||
"""金额转字符串给 JSON:十进制、去掉无意义的尾随零但保留两位。"""
|
||||
dec = to_dec(value)
|
||||
return f"{dec:.{RULES.money_scale}f}"
|
||||
|
||||
|
||||
def sum_money(values: object) -> Decimal:
|
||||
"""先按明细舍入、再求和(``TAX-002`` 的"每条明细先保留 2 位再分类求和")。"""
|
||||
total = ZERO
|
||||
for item in values or ():
|
||||
total += round_money(item)
|
||||
return total
|
||||
|
||||
|
||||
def safe_div(numerator: object, denominator: object) -> Decimal | None:
|
||||
den = to_dec(denominator)
|
||||
if den == ZERO:
|
||||
return None
|
||||
return round_rate(to_dec(numerator) / den)
|
||||
|
|
@ -0,0 +1,154 @@
|
|||
"""利润阶梯:``BUD-PROFIT-001`` / ``BUD-PROFIT-002`` 与推荐口径 ``DECISION-BUD-PROFIT-001``。
|
||||
|
||||
术语固定下来,代码与页面都不再造新词:
|
||||
|
||||
=========================== ==========================================
|
||||
指标 公式
|
||||
=========================== ==========================================
|
||||
不含税收入总额 R 各类收入不含税之和
|
||||
采购成本总额 P 设备+施工+服务+其他 四类采购(不含税)
|
||||
采购毛利 A R − P
|
||||
项目毛利 B A − 项目管理费用 M − 其他成本 O − 财务费用 F
|
||||
贡献利润 B − 公司管理费用 C
|
||||
净利润 贡献利润 − 所得税
|
||||
=========================== ==========================================
|
||||
|
||||
三个 ``profit_*_in_gross`` 开关决定 B 层扣哪些项,默认全扣(推荐口径)。把
|
||||
``profit_other_cost_in_gross`` 关掉就精确复现老后端(``RISK-BUD-PROFIT-001`` 里
|
||||
"后端没扣其他成本"的那一套),双跑对账可以直接比。
|
||||
|
||||
公司管理费用过去写死在 ``BudgetBean`` 的 getter 里返回"收入×2.8%",导致页面上改了
|
||||
不生效(``RISK-BUD-CM-001``)。这里改成:人工填了就用人填的,没填才按
|
||||
``calc.company_manage_fee_rate`` 派生,并在快照里标明这一项是人工还是派生。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from decimal import Decimal
|
||||
|
||||
from .rules import RULES
|
||||
from .money import HUNDRED, ZERO, Ratio, money_str, ratio, round_money, to_dec
|
||||
|
||||
|
||||
@dataclass
|
||||
class ProfitInput:
|
||||
"""利润计算的人工输入(都是不含税金额)。"""
|
||||
|
||||
income_device: Decimal = ZERO
|
||||
income_engineering: Decimal = ZERO
|
||||
income_service: Decimal = ZERO
|
||||
purchase_device: Decimal = ZERO
|
||||
purchase_construction: Decimal = ZERO
|
||||
purchase_service: Decimal = ZERO
|
||||
purchase_other: Decimal = ZERO
|
||||
project_manage: Decimal = ZERO # M 项目管理费用
|
||||
other_cost: Decimal = ZERO # O 其他成本
|
||||
finance_cost: Decimal = ZERO # F 财务费用(= 各月资金利息之和)
|
||||
company_manage: Decimal | None = None # C 人工值;None 表示按费率派生
|
||||
income_tax: Decimal = ZERO # 所得税,可选
|
||||
|
||||
@property
|
||||
def income_total(self) -> Decimal:
|
||||
return round_money(self.income_device + self.income_engineering + self.income_service)
|
||||
|
||||
@property
|
||||
def purchase_total(self) -> Decimal:
|
||||
return round_money(
|
||||
self.purchase_device + self.purchase_construction + self.purchase_service + self.purchase_other
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ProfitResult:
|
||||
"""利润计算结果,含每一层的金额与比率。"""
|
||||
|
||||
income_total: Decimal = ZERO
|
||||
purchase_total: Decimal = ZERO
|
||||
gross_a: Decimal = ZERO
|
||||
gross_a_rate: Ratio = field(default_factory=lambda: Ratio(None, "unset"))
|
||||
project_manage: Decimal = ZERO
|
||||
other_cost: Decimal = ZERO
|
||||
finance_cost: Decimal = ZERO
|
||||
company_manage: Decimal = ZERO
|
||||
company_manage_source: str = "derived"
|
||||
gross_b: Decimal = ZERO
|
||||
gross_b_rate: Ratio = field(default_factory=lambda: Ratio(None, "unset"))
|
||||
contribution: Decimal = ZERO
|
||||
contribution_rate: Ratio = field(default_factory=lambda: Ratio(None, "unset"))
|
||||
income_tax: Decimal = ZERO
|
||||
net_profit: Decimal = ZERO
|
||||
net_profit_rate: Ratio = field(default_factory=lambda: Ratio(None, "unset"))
|
||||
|
||||
def to_dict(self) -> dict[str, object]:
|
||||
return {
|
||||
"income_total": money_str(self.income_total),
|
||||
"purchase_total": money_str(self.purchase_total),
|
||||
"gross_a": money_str(self.gross_a),
|
||||
"gross_a_rate": self.gross_a_rate.to_dict(),
|
||||
"project_manage": money_str(self.project_manage),
|
||||
"other_cost": money_str(self.other_cost),
|
||||
"finance_cost": money_str(self.finance_cost),
|
||||
"company_manage": money_str(self.company_manage),
|
||||
"company_manage_source": self.company_manage_source,
|
||||
"gross_b": money_str(self.gross_b),
|
||||
"gross_b_rate": self.gross_b_rate.to_dict(),
|
||||
"contribution": money_str(self.contribution),
|
||||
"contribution_rate": self.contribution_rate.to_dict(),
|
||||
"income_tax": money_str(self.income_tax),
|
||||
"net_profit": money_str(self.net_profit),
|
||||
"net_profit_rate": self.net_profit_rate.to_dict(),
|
||||
}
|
||||
|
||||
|
||||
def company_manage_fee(income_exclude_total: object, manual: object | None) -> tuple[Decimal, str]:
|
||||
"""公司管理费用 C。人工填了就用人工的(修掉 ``RISK-BUD-CM-001``),否则按费率派生。"""
|
||||
if manual is not None and str(manual).strip() != "":
|
||||
return round_money(manual), "manual"
|
||||
rate = to_dec(RULES.company_manage_fee_rate)
|
||||
return round_money(to_dec(income_exclude_total) * rate / HUNDRED), "derived"
|
||||
|
||||
|
||||
def calculate(data: ProfitInput) -> ProfitResult:
|
||||
"""按可配置的成本集合算出整条利润阶梯。"""
|
||||
income = data.income_total
|
||||
purchase = data.purchase_total
|
||||
|
||||
gross_a = round_money(income - purchase)
|
||||
|
||||
manage = round_money(data.project_manage)
|
||||
other = round_money(data.other_cost)
|
||||
finance = round_money(data.finance_cost)
|
||||
|
||||
gross_b = gross_a
|
||||
if RULES.profit_manage_cost_in_gross:
|
||||
gross_b -= manage
|
||||
if RULES.profit_other_cost_in_gross:
|
||||
gross_b -= other
|
||||
if RULES.profit_finance_cost_in_gross:
|
||||
gross_b -= finance
|
||||
gross_b = round_money(gross_b)
|
||||
|
||||
company, company_source = company_manage_fee(income, data.company_manage)
|
||||
contribution = round_money(gross_b - company)
|
||||
income_tax = round_money(data.income_tax)
|
||||
net = round_money(contribution - income_tax)
|
||||
|
||||
return ProfitResult(
|
||||
income_total=income,
|
||||
purchase_total=purchase,
|
||||
gross_a=gross_a,
|
||||
gross_a_rate=ratio(gross_a, income),
|
||||
project_manage=manage,
|
||||
other_cost=other,
|
||||
finance_cost=finance,
|
||||
company_manage=company,
|
||||
company_manage_source=company_source,
|
||||
gross_b=gross_b,
|
||||
gross_b_rate=ratio(gross_b, income),
|
||||
contribution=contribution,
|
||||
contribution_rate=ratio(contribution, income),
|
||||
income_tax=income_tax,
|
||||
net_profit=net,
|
||||
net_profit_rate=ratio(net, income),
|
||||
)
|
||||
|
|
@ -0,0 +1,420 @@
|
|||
"""计算口径的运行态:规则存在系统参数表里,界面上改,代码里读。
|
||||
|
||||
这些规则过去写在 ``config.toml`` 的 ``[calc]`` 段:想把公司管理费率调 0.2 个百分点,
|
||||
得登机器改文件、重启后端,还得祈祷没人正在跑试算。现在它们落在 ``system_config``
|
||||
(``group='calc'``),在「系统 → 计算口径」页面上改,保存即生效,配置文件里一个字都不留。
|
||||
|
||||
三条规矩:
|
||||
|
||||
* **默认值只写一次**::class:`CalcRules` 的字段默认值就是推荐口径。建库时按它把
|
||||
``system_config`` 补齐,页面上的"恢复默认"也回到它,不存在第二份抄来的数字。
|
||||
* **脏值进不来**:枚举取值、数字区间、位数是不是整数都在 :func:`normalize` 里挡,
|
||||
保存不成功就回中文原因,绝不会把 ``HALF_UP`` 静默存成 ``halfup`` 再静默回落。
|
||||
* **读取口只有一个**:``from .rules import RULES`` 之后写 ``RULES.money_scale``。
|
||||
:func:`apply` 是原地改字段、不换新对象,所以各处 ``from .rules import RULES``
|
||||
拿到的一直是同一个对象,界面上存完下一次试算就是新口径。
|
||||
|
||||
多进程部署(``uvicorn --workers 2``)时另一个 worker 看不见这次保存,所以每次试算前
|
||||
:func:`app.service.biz.apply_sys_config` 都会按库里的值重新灌一遍——快照里的口径
|
||||
永远跟这一次计算开始时库里的值一致。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass, fields
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any, Iterable, Iterator, Mapping
|
||||
|
||||
logger = logging.getLogger("pms.calc.rules")
|
||||
|
||||
#: system_config.group 里属于计算口径的那一批
|
||||
RULE_GROUP = "calc"
|
||||
#: 参数编码的统一前缀(calc.money_scale 这种)
|
||||
CODE_PREFIX = "calc."
|
||||
#: 历史上界面上有、但内核没读过的重复参数:值搬进 calc.* 之后删掉,别再留两处
|
||||
LEGACY_CODE_ALIASES = {
|
||||
"finance.company_manage_fee_rate": "calc.company_manage_fee_rate",
|
||||
"budget.travel_business_limit_rate": "calc.travel_business_limit_rate",
|
||||
}
|
||||
|
||||
BOOL_TRUE = ("1", "true", "yes", "on")
|
||||
BOOL_FALSE = ("0", "false", "no", "off")
|
||||
|
||||
|
||||
@dataclass
|
||||
class CalcRules:
|
||||
"""一次计算用到的全部口径参数。默认值 = 推荐口径(docs/计算口径.md)。"""
|
||||
|
||||
version: str = "2026.10"
|
||||
money_scale: int = 2
|
||||
rate_scale: int = 4
|
||||
percent_scale: int = 2
|
||||
rounding: str = "HALF_UP"
|
||||
zero_denominator: str = "undefined"
|
||||
company_manage_fee_rate: float = 2.8
|
||||
travel_business_limit_rate: float = 10.0
|
||||
contribution_rate_action: str = "warn"
|
||||
# 价内税:True(默认,TO-BE)先算不含税、税额=含税-不含税,保证 含税额=不含税+税额 分毫不差;
|
||||
# False 回到老公式 税额=含税×r/(1+r)(TAX-002),双跑对账时用。
|
||||
tax_from_complement: bool = True
|
||||
# True 回到老口径:税率参与公式前先舍到 2 位(RISK-TAX-001),默认关闭。
|
||||
tax_rate_pre_round: bool = False
|
||||
# 利润各层的成本集合(DECISION-BUD-PROFIT-001)。默认按推荐口径:
|
||||
# 项目毛利 = 采购毛利 - 项目管理费用 - 其他成本 - 财务费用
|
||||
profit_manage_cost_in_gross: bool = True
|
||||
profit_other_cost_in_gross: bool = True
|
||||
profit_finance_cost_in_gross: bool = True
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Choice:
|
||||
value: str
|
||||
label: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RuleSpec:
|
||||
"""一条规则在界面上的长相 + 校验它所需要的全部信息。
|
||||
|
||||
``attr`` 是 :class:`CalcRules` 上的字段名,参数编码由它拼出来(``calc.<attr>``),
|
||||
所以 seed、页面、校验三处看到的是同一份定义,不会各写一份常量表。
|
||||
"""
|
||||
|
||||
attr: str
|
||||
name: str
|
||||
section: str
|
||||
kind: str # int / decimal / bool / enum / string
|
||||
remark: str = ""
|
||||
unit: str = ""
|
||||
choices: tuple[Choice, ...] = ()
|
||||
minimum: float | None = None
|
||||
maximum: float | None = None
|
||||
step: str = ""
|
||||
|
||||
@property
|
||||
def code(self) -> str:
|
||||
return f"{CODE_PREFIX}{self.attr}"
|
||||
|
||||
@property
|
||||
def value_type(self) -> str:
|
||||
return "number" if self.kind in ("int", "decimal") else ("bool" if self.kind == "bool" else "string")
|
||||
|
||||
@property
|
||||
def default(self) -> Any:
|
||||
return getattr(CalcRules(), self.attr)
|
||||
|
||||
@property
|
||||
def default_text(self) -> str:
|
||||
return format_value(self, self.default)
|
||||
|
||||
|
||||
#: 页面按段落渲染,顺序就是这里排的顺序
|
||||
RULE_SECTIONS: tuple[tuple[str, str, str], ...] = (
|
||||
("scale", "舍入与位数", "金额、比率保留几位,遇到零分母怎么办"),
|
||||
("tax", "价税分离", "TAX-001 / TAX-002 与双跑对账用的两个历史口径"),
|
||||
("profit", "利润阶梯", "各层扣哪些成本,以及没人工填写时按什么费率派生"),
|
||||
("validate", "校验阈值", "BUD-VAL-001 / BUD-VAL-002 用的比例与动作"),
|
||||
)
|
||||
|
||||
RULE_SPECS: tuple[RuleSpec, ...] = (
|
||||
RuleSpec(
|
||||
"version", "计算口径版本", "scale", "string",
|
||||
remark="写进每一次计算快照与项目的 calc_version。生产上改上面任何一条都必须同时升这一项,"
|
||||
"否则同一项目会出现「数字变了但版本号没变」。",
|
||||
),
|
||||
RuleSpec("money_scale", "金额保留位数", "scale", "int", unit="位", minimum=0, maximum=12,
|
||||
remark="所有金额舍入的小数位(round_money)。老系统 Java / 浏览器 / Excel 各舍一次,"
|
||||
"这里只舍一处。", step="1"),
|
||||
RuleSpec("rate_scale", "比率中间除法保留位数", "scale", "int", unit="位", minimum=1, maximum=12,
|
||||
remark="中间除法保留的位数,对应老代码里散落的「除法保留 4 位」。", step="1"),
|
||||
RuleSpec("percent_scale", "百分比结果保留位数", "scale", "int", unit="位", minimum=0, maximum=12,
|
||||
remark="利润率这类百分比结果保留的位数(利润 / 收入 × 100)。", step="1"),
|
||||
RuleSpec(
|
||||
"rounding", "舍入方式", "scale", "enum",
|
||||
choices=(Choice("HALF_UP", "四舍五入(HALF_UP)"), Choice("HALF_DOWN", "五舍六入(HALF_DOWN)"),
|
||||
Choice("HALF_EVEN", "银行家舍入(HALF_EVEN)"), Choice("UP", "远离零进位(UP)"),
|
||||
Choice("DOWN", "截断(DOWN)"), Choice("FLOOR", "向下取整(FLOOR)"),
|
||||
Choice("CEILING", "向上取整(CEILING)")),
|
||||
remark="所有舍入统一用它。老系统是 HALF_UP,换别的口径要在版本号上留痕。",
|
||||
),
|
||||
RuleSpec(
|
||||
"zero_denominator", "零分母的利润率", "scale", "enum",
|
||||
choices=(Choice("undefined", "返回未定义并带原因(推荐)"), Choice("zero", "返回 0(老系统口径)")),
|
||||
remark="收入为 0 时利润率怎么算。老系统一会儿返回 0、一会儿返回「利润×100」、"
|
||||
"一会儿把分母换成 1(BUD-PROFIT-002 / RISK-SET-RATE-001 / FINAL-RATE-001);"
|
||||
"zero 只在逐月对账的过渡期用。",
|
||||
),
|
||||
RuleSpec(
|
||||
"tax_from_complement", "税额取补数", "tax", "bool",
|
||||
remark="开:税额 = 含税额 − 不含税额,保证三项相加正好等于含税额(推荐)。"
|
||||
"关:回到老公式 税额 = 含税 × r/(1+r)(RISK-TAX-002),双跑对账期间用。",
|
||||
),
|
||||
RuleSpec(
|
||||
"tax_rate_pre_round", "税率先舍到 2 位", "tax", "bool",
|
||||
remark="开:税率进入公式前先舍到 2 位(RISK-TAX-001),高精度税率会先丢精度。默认关。",
|
||||
),
|
||||
RuleSpec(
|
||||
"profit_manage_cost_in_gross", "项目毛利扣项目管理费用", "profit", "bool",
|
||||
remark="DECISION-BUD-PROFIT-001:项目毛利 B = 采购毛利 A − 项目管理费用 M − 其他成本 O − 财务费用 F。"
|
||||
"关掉就是从 B 里少扣一项,只用于复现老口径。",
|
||||
),
|
||||
RuleSpec(
|
||||
"profit_other_cost_in_gross", "项目毛利扣其他成本", "profit", "bool",
|
||||
remark="关掉它就精确复现老后端「没扣其他成本」的那一套(RISK-BUD-PROFIT-001),"
|
||||
"双跑对账可以直接比。",
|
||||
),
|
||||
RuleSpec(
|
||||
"profit_finance_cost_in_gross", "项目毛利扣财务费用", "profit", "bool",
|
||||
remark="关掉就是从项目毛利里少扣财务费用,只用于复现老口径。",
|
||||
),
|
||||
RuleSpec(
|
||||
"company_manage_fee_rate", "公司管理费用率", "profit", "decimal", unit="%",
|
||||
minimum=0, maximum=100, step="0.1",
|
||||
remark="没有人工填写公司管理费用时按这个费率派生(收入不含税 × 费率)。老系统把它写死在 "
|
||||
"BudgetBean 的 getter 里返回 2.8%,页面上改了不生效(RISK-BUD-CM-001)。",
|
||||
),
|
||||
RuleSpec(
|
||||
"travel_business_limit_rate", "差旅及业务费限额比例", "validate", "decimal", unit="%",
|
||||
minimum=0, maximum=100, step="0.1",
|
||||
remark="BUD-VAL-001:差旅费 + 业务费 ≤ [毛利A −(项目管理费用总额 − 差旅业务费)] × 该比例。",
|
||||
),
|
||||
RuleSpec(
|
||||
"contribution_rate_action", "贡献利润率不达标时", "validate", "enum",
|
||||
choices=(Choice("block", "拦截送审"), Choice("warn", "仅告警"), Choice("none", "不检查")),
|
||||
remark="BUD-VAL-002 的动作。阈值在「业务参数」页的 budget.contribution_rate_threshold,"
|
||||
"填 0 表示不检查;老系统这段校验是被注释掉的,实际从不生效。",
|
||||
),
|
||||
)
|
||||
|
||||
SPECS_BY_ATTR: dict[str, RuleSpec] = {spec.attr: spec for spec in RULE_SPECS}
|
||||
SPECS_BY_CODE: dict[str, RuleSpec] = {spec.code: spec for spec in RULE_SPECS}
|
||||
RULE_CODES: tuple[str, ...] = tuple(spec.code for spec in RULE_SPECS)
|
||||
|
||||
#: 当前生效的口径。整个进程只有这一个对象,apply() 原地改它。
|
||||
RULES = CalcRules()
|
||||
#: 每条规则当前的来源:config(库里的值)/ default(代码默认值)
|
||||
SOURCES: dict[str, str] = {spec.attr: "default" for spec in RULE_SPECS}
|
||||
|
||||
|
||||
def format_value(spec: RuleSpec, value: Any) -> str:
|
||||
"""字段值 -> 存进 system_config / 给前端的字符串。
|
||||
|
||||
浮点走 :class:`~decimal.Decimal` 而不是 ``%g``:``%g`` 只留 6 位有效数字,
|
||||
会把 12.345678 悄悄印成 12.3457,而这是要显示给财务看的"当前生效值"。
|
||||
"""
|
||||
if isinstance(value, bool):
|
||||
return "true" if value else "false"
|
||||
if isinstance(value, float):
|
||||
return f"{Decimal(str(value)).normalize():f}"
|
||||
return str(value)
|
||||
|
||||
|
||||
def spec_for(code: str) -> RuleSpec | None:
|
||||
return SPECS_BY_CODE.get((code or "").strip())
|
||||
|
||||
|
||||
def normalize(spec: RuleSpec, raw: object) -> str:
|
||||
"""把界面上填的东西折成规范字符串;不合法直接 ValueError(中文,能直接回给用户)。
|
||||
|
||||
这里严格,:func:`apply` 宽松:库里躺着一条脏值不该让整条计算链崩掉,
|
||||
但人在界面上存一条脏值必须当场被怼回去。
|
||||
"""
|
||||
text = str(raw).strip() if raw is not None else ""
|
||||
if spec.kind == "bool":
|
||||
lowered = text.lower()
|
||||
if lowered in BOOL_TRUE:
|
||||
return "true"
|
||||
if lowered in BOOL_FALSE:
|
||||
return "false"
|
||||
raise ValueError(f"{spec.name}只能是「是」或「否」")
|
||||
if spec.kind == "int":
|
||||
try:
|
||||
number = int(text)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError(f"{spec.name}必须是整数") from None
|
||||
_check_range(spec, number)
|
||||
return str(number)
|
||||
if spec.kind == "decimal":
|
||||
try:
|
||||
number = Decimal(text)
|
||||
except (InvalidOperation, ValueError, TypeError):
|
||||
raise ValueError(f"{spec.name}必须是数字") from None
|
||||
if not number.is_finite():
|
||||
raise ValueError(f"{spec.name}必须是有限数字")
|
||||
_check_range(spec, number)
|
||||
return f"{number.normalize():f}"
|
||||
if spec.kind == "enum":
|
||||
allowed = {choice.value.lower(): choice.value for choice in spec.choices}
|
||||
if text.lower() not in allowed:
|
||||
raise ValueError(f"{spec.name}只能是:{' / '.join(c.value for c in spec.choices)}")
|
||||
return allowed[text.lower()]
|
||||
if not text:
|
||||
raise ValueError(f"{spec.name}不能为空")
|
||||
if len(text) > 64:
|
||||
raise ValueError(f"{spec.name}过长(最多 64 个字符)")
|
||||
return text
|
||||
|
||||
|
||||
def _check_range(spec: RuleSpec, number: Decimal | int) -> None:
|
||||
if spec.minimum is not None and number < Decimal(str(spec.minimum)):
|
||||
raise ValueError(f"{spec.name}不能小于 {spec.minimum:g}")
|
||||
if spec.maximum is not None and number > Decimal(str(spec.maximum)):
|
||||
raise ValueError(f"{spec.name}不能大于 {spec.maximum:g}")
|
||||
|
||||
|
||||
def parse(spec: RuleSpec, text: str) -> Any:
|
||||
"""规范字符串 -> 字段值。"""
|
||||
if spec.kind == "bool":
|
||||
return text.lower() in BOOL_TRUE
|
||||
if spec.kind == "int":
|
||||
return int(text)
|
||||
if spec.kind == "decimal":
|
||||
return float(Decimal(text))
|
||||
return text
|
||||
|
||||
|
||||
def apply(values: Mapping[str, object]) -> CalcRules:
|
||||
"""把 system_config 里的原始值灌进 :data:`RULES`(原地改,不换新对象)。
|
||||
|
||||
认不出来或校验不过的键跳过并留一条 warning——库里躺着脏值时口径退回默认,
|
||||
但绝不停掉试算。
|
||||
"""
|
||||
for spec in RULE_SPECS:
|
||||
if spec.code not in values:
|
||||
SOURCES[spec.attr] = "default"
|
||||
continue
|
||||
raw = values[spec.code]
|
||||
try:
|
||||
text = normalize(spec, raw)
|
||||
except ValueError as exc:
|
||||
SOURCES[spec.attr] = "default"
|
||||
setattr(RULES, spec.attr, spec.default)
|
||||
logger.warning("计算口径 %s 的取值 %r 不合法(%s),本条退回默认 %s",
|
||||
spec.code, raw, exc, spec.default_text)
|
||||
continue
|
||||
setattr(RULES, spec.attr, parse(spec, text))
|
||||
SOURCES[spec.attr] = "config"
|
||||
return RULES
|
||||
|
||||
|
||||
def reset_to_defaults() -> CalcRules:
|
||||
"""退回代码默认口径(库连不上时的兜底,也是单用例之间的清场)。"""
|
||||
defaults = CalcRules()
|
||||
for f in fields(RULES):
|
||||
setattr(RULES, f.name, getattr(defaults, f.name))
|
||||
for spec in RULE_SPECS:
|
||||
SOURCES[spec.attr] = "default"
|
||||
return RULES
|
||||
|
||||
|
||||
def reload(db: Any) -> CalcRules:
|
||||
"""从库里把口径读回来。``db`` 是一个 SQLAlchemy Session。"""
|
||||
return apply(read(db))
|
||||
|
||||
|
||||
def read(db: Any) -> dict[str, str]:
|
||||
"""读回 ``{参数编码: 原始字符串}``;一条都没有时返回空字典(口径退回默认)。"""
|
||||
from sqlalchemy import select
|
||||
|
||||
from ...models import SystemConfig # 延迟导入:计算内核平时不碰 ORM
|
||||
|
||||
rows = db.execute(select(SystemConfig).where(SystemConfig.code.in_(RULE_CODES))).scalars().all()
|
||||
return {row.code: str(row.value) for row in rows}
|
||||
|
||||
|
||||
def seed_rows() -> list[tuple[str, str, str, str, str, str]]:
|
||||
"""给 seed 用的参数行,形状跟 ``seed.CONFIGS`` 一致。"""
|
||||
return [(spec.code, spec.name, spec.default_text, spec.value_type, RULE_GROUP, spec.remark)
|
||||
for spec in RULE_SPECS]
|
||||
|
||||
|
||||
def is_rule_code(code: str) -> bool:
|
||||
return spec_for(code) is not None
|
||||
|
||||
|
||||
def changed_count() -> int:
|
||||
"""有多少条口径被改成跟推荐口径不一样。页面和启动日志都要这句实话。"""
|
||||
return sum(1 for spec in RULE_SPECS
|
||||
if SOURCES[spec.attr] == "config"
|
||||
and format_value(spec, getattr(RULES, spec.attr)) != spec.default_text)
|
||||
|
||||
|
||||
def view(db: Any) -> dict[str, Any]:
|
||||
"""页面要的一切:段落、每条的当前值 / 默认值 / 库里存的原样。
|
||||
|
||||
进来先 reload 一次——另一个 worker 刚存过、或 DBA 直接改了库,页面都得说实话。
|
||||
"""
|
||||
stored = read(db)
|
||||
apply(stored)
|
||||
sections: list[dict[str, Any]] = []
|
||||
for key, title, hint in RULE_SECTIONS:
|
||||
items = []
|
||||
for spec in RULE_SPECS:
|
||||
if spec.section != key:
|
||||
continue
|
||||
effective = format_value(spec, getattr(RULES, spec.attr))
|
||||
items.append({
|
||||
"code": spec.code,
|
||||
"key": spec.attr,
|
||||
"name": spec.name,
|
||||
"kind": spec.kind,
|
||||
"valueType": spec.value_type,
|
||||
"unit": spec.unit,
|
||||
"step": spec.step or ("1" if spec.kind == "int" else "0.01"),
|
||||
"min": spec.minimum,
|
||||
"max": spec.maximum,
|
||||
"choices": [{"value": choice.value, "label": choice.label} for choice in spec.choices],
|
||||
"remark": spec.remark,
|
||||
"value": effective,
|
||||
"default": spec.default_text,
|
||||
"stored": stored.get(spec.code, spec.default_text),
|
||||
"configured": spec.code in stored,
|
||||
# 库里存的原样跟生效值不一样 = 存进了非法值被退回默认,页面上得看得出来
|
||||
"normalized": spec.code in stored and stored[spec.code] != effective,
|
||||
})
|
||||
sections.append({"key": key, "title": title, "hint": hint, "rules": items})
|
||||
return {
|
||||
"group": RULE_GROUP,
|
||||
"version": RULES.version,
|
||||
"sections": sections,
|
||||
# 库里改过、而且跟推荐口径不一样的条数:页面据此提示"当前不是默认口径"
|
||||
"changed": changed_count(),
|
||||
"seeded": sum(1 for code in RULE_CODES if code in stored),
|
||||
}
|
||||
|
||||
|
||||
@contextmanager
|
||||
def override(**values: object) -> Iterator[CalcRules]:
|
||||
"""临时改口径,退出时还原。给用例和双跑对账脚本用,别在业务代码里调。
|
||||
|
||||
``with override(profit_other_cost_in_gross=False):`` 这种写法不用自己记 original。
|
||||
"""
|
||||
unknown = sorted(key for key in values if key not in SPECS_BY_ATTR)
|
||||
if unknown:
|
||||
raise KeyError(f"没有这条计算口径:{'、'.join(unknown)}")
|
||||
spec_by_attr = SPECS_BY_ATTR
|
||||
before = {attr: getattr(RULES, attr) for attr in values}
|
||||
before_source = {attr: SOURCES.get(attr, "default") for attr in values}
|
||||
try:
|
||||
for attr, raw in values.items():
|
||||
spec = spec_by_attr[attr]
|
||||
setattr(RULES, attr, parse(spec, normalize(spec, raw)))
|
||||
SOURCES[attr] = "override"
|
||||
yield RULES
|
||||
finally:
|
||||
for attr, value in before.items():
|
||||
setattr(RULES, attr, value)
|
||||
SOURCES[attr] = before_source[attr]
|
||||
|
||||
|
||||
def as_dict() -> dict[str, Any]:
|
||||
"""当前生效口径的扁平字典(诊断与日志用)。"""
|
||||
return {spec.attr: getattr(RULES, spec.attr) for spec in RULE_SPECS}
|
||||
|
||||
|
||||
def describe(values: Iterable[str] | None = None) -> str:
|
||||
"""一行话把口径说清楚,启动日志与快照留痕用。"""
|
||||
wanted = list(values or ()) or [spec.attr for spec in RULE_SPECS]
|
||||
return " ".join(f"{attr}={getattr(RULES, attr)}" for attr in wanted)
|
||||
|
|
@ -0,0 +1,108 @@
|
|||
"""价税计算:``TAX-001`` / ``TAX-002``。
|
||||
|
||||
老系统同一行明细的税额在 Java 与浏览器里算法不同(``RISK-TAX-002``:含税 113、税率 13%
|
||||
时浏览器算出 14.69 而不是 13),保存前后页面显示不一样。这里只有一份实现,前端一律
|
||||
调"计算预览"接口取数(``TO-BE-REACT-002``)。
|
||||
|
||||
两个可开关的历史口径:
|
||||
|
||||
* ``calc.tax_from_complement``(系统参数,界面可改)—— 默认开。开启时税额取"含税 − 不含税"的补数,保证
|
||||
``含税额 == 不含税额 + 税额`` 分毫不差;关闭则回到 ``TAX-002`` 原式 ``I·r/(1+r)``,
|
||||
它和不含税额相加可能差一分,只在双跑对账时打开。
|
||||
* ``calc.tax_rate_pre_round`` —— 默认关。开启时先把税率舍到 2 位再用(``RISK-TAX-001``)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from decimal import Decimal
|
||||
|
||||
from .rules import RULES
|
||||
from .money import ONE, ZERO, round_money, to_dec
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TaxAmount:
|
||||
"""一行明细的价税结果。"""
|
||||
|
||||
include: Decimal # 含税
|
||||
exclude: Decimal # 不含税
|
||||
tax: Decimal # 税额
|
||||
rate: Decimal # 税率百分数
|
||||
source: str = "" # manual / product,说明含税金额是人工填的还是数量×单价来的
|
||||
|
||||
def to_dict(self) -> dict[str, object]:
|
||||
from .money import money_str
|
||||
|
||||
return {
|
||||
"include": money_str(self.include),
|
||||
"exclude": money_str(self.exclude),
|
||||
"tax": money_str(self.tax),
|
||||
"rate": f"{self.rate}",
|
||||
"source": self.source or None,
|
||||
}
|
||||
|
||||
|
||||
def resolve_include(
|
||||
include_amount: object | None,
|
||||
qty: object | None,
|
||||
unit_price: object | None,
|
||||
) -> tuple[Decimal, str]:
|
||||
"""``TAX-001``:优先用人工含税总额,否则退回 数量 × 单价。
|
||||
|
||||
老代码在"单价有值、数量为空"时会直接乘法炸出 NPE(``TAX-006``)。这里数量为空
|
||||
按 0 处理,交给上层校验器去报"必填",计算器本身不炸。
|
||||
"""
|
||||
manual = to_dec(include_amount)
|
||||
derived = round_money(to_dec(unit_price) * to_dec(qty))
|
||||
# 明细表存的是 NOT NULL 列,"没填"落到库里就是 0.00。0 不能当成"人工填了 0",
|
||||
# 否则凡是走数量×单价的行都会被抹成 0,且与 budget 侧的汇总口径分叉。
|
||||
if manual != ZERO:
|
||||
return round_money(manual), "manual"
|
||||
if derived != ZERO:
|
||||
return derived, "product"
|
||||
return round_money(manual), "manual"
|
||||
|
||||
|
||||
def split(include: object, rate_percent: object) -> TaxAmount:
|
||||
"""``TAX-002``:价内税拆分。
|
||||
|
||||
``r = taxRate / 100``;``E = I / (1 + r)``;``T = I − E``(或老口径 ``I·r/(1+r)``)。
|
||||
税率为空/0 时不含税等于含税、税额为 0。
|
||||
"""
|
||||
amount = round_money(include)
|
||||
rate = to_dec(rate_percent)
|
||||
if rate == ZERO:
|
||||
return TaxAmount(amount, amount, ZERO, rate)
|
||||
|
||||
r = rate / Decimal("100")
|
||||
if RULES.tax_rate_pre_round:
|
||||
r = round_money(r)
|
||||
|
||||
denominator = ONE + r
|
||||
exclude = round_money(amount / denominator)
|
||||
if RULES.tax_from_complement:
|
||||
tax = round_money(amount - exclude)
|
||||
else:
|
||||
tax = round_money(amount * r / denominator)
|
||||
return TaxAmount(amount, exclude, tax, rate)
|
||||
|
||||
|
||||
def line(
|
||||
include_amount: object | None,
|
||||
qty: object | None,
|
||||
unit_price: object | None,
|
||||
rate_percent: object,
|
||||
) -> TaxAmount:
|
||||
"""一行明细:先定含税金额(TAX-001),再拆价税(TAX-002)。"""
|
||||
amount, source = resolve_include(include_amount, qty, unit_price)
|
||||
result = split(amount, rate_percent)
|
||||
return TaxAmount(result.include, result.exclude, result.tax, result.rate, source)
|
||||
|
||||
|
||||
def total(tax_amounts: list[TaxAmount]) -> TaxAmount:
|
||||
"""多行合计。明细已各自舍入,这里只做加法(``TAX-008`` 的多行尾差策略)。"""
|
||||
include = sum((item.include for item in tax_amounts), ZERO)
|
||||
exclude = sum((item.exclude for item in tax_amounts), ZERO)
|
||||
tax = sum((item.tax for item in tax_amounts), ZERO)
|
||||
return TaxAmount(round_money(include), round_money(exclude), round_money(tax), ZERO, "total")
|
||||
|
|
@ -0,0 +1,241 @@
|
|||
"""结果校验:把只存在于浏览器里的约束搬到后端。
|
||||
|
||||
``RISK-BUD-VAL-001`` 写得很明白——差旅费/业务费 10% 限额、付款勾稽这些"关键校验"
|
||||
全在前端,调接口或换个页面入口就能绕过。这里成为唯一实现,前端展示同样结论但不再是
|
||||
把关者(``TO-BE-BACKEND-CALC-007``:输入校验与结果校验分开)。
|
||||
|
||||
每条规则都带稳定编号,前端提示、审计日志、测试用例引用同一个号。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import field as dc_field
|
||||
from decimal import Decimal
|
||||
|
||||
from .rules import RULES
|
||||
from .money import ZERO, money_str, to_dec
|
||||
|
||||
SEVERITY_ERROR = "error"
|
||||
SEVERITY_WARNING = "warning"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Issue:
|
||||
rule_id: str
|
||||
severity: str
|
||||
message: str
|
||||
field: str = ""
|
||||
detail: dict[str, object] = dc_field(default_factory=dict)
|
||||
|
||||
def to_dict(self) -> dict[str, object]:
|
||||
return {
|
||||
"ruleId": self.rule_id,
|
||||
"severity": self.severity,
|
||||
"message": self.message,
|
||||
"field": self.field or None,
|
||||
"detail": self.detail or None,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class ValidationReport:
|
||||
issues: list[Issue] = dc_field(default_factory=list)
|
||||
|
||||
@property
|
||||
def errors(self) -> list[Issue]:
|
||||
return [item for item in self.issues if item.severity == SEVERITY_ERROR]
|
||||
|
||||
@property
|
||||
def warnings(self) -> list[Issue]:
|
||||
return [item for item in self.issues if item.severity == SEVERITY_WARNING]
|
||||
|
||||
@property
|
||||
def passed(self) -> bool:
|
||||
return not self.errors
|
||||
|
||||
def add(self, rule_id: str, severity: str, message: str, field: str = "", **detail: object) -> None:
|
||||
self.issues.append(Issue(rule_id, severity, message, field, detail))
|
||||
|
||||
def error(self, rule_id: str, message: str, field: str = "", **detail: object) -> None:
|
||||
self.add(rule_id, SEVERITY_ERROR, message, field, **detail)
|
||||
|
||||
def warning(self, rule_id: str, message: str, field: str = "", **detail: object) -> None:
|
||||
self.add(rule_id, SEVERITY_WARNING, message, field, **detail)
|
||||
|
||||
def merge(self, other: "ValidationReport") -> None:
|
||||
self.issues.extend(other.issues)
|
||||
|
||||
def to_dict(self) -> dict[str, object]:
|
||||
return {
|
||||
"passed": self.passed,
|
||||
"errors": [i.to_dict() for i in self.errors],
|
||||
"warnings": [i.to_dict() for i in self.warnings],
|
||||
}
|
||||
|
||||
|
||||
def check_required(report: ValidationReport, rows: list[dict], *, label: str, fields: list[str]) -> None:
|
||||
"""输入校验:明细行必填项。``TAX-06`` 那类 NPE 从此变成明确的校验错误。"""
|
||||
for index, row in enumerate(rows, start=1):
|
||||
missing = [name for name in fields if str(row.get(name) or "").strip() == ""]
|
||||
if missing:
|
||||
report.error(
|
||||
"INPUT-REQUIRED",
|
||||
f"{label}第 {index} 行缺少必填项:{'、'.join(missing)}",
|
||||
field=f"{label}#{index}",
|
||||
rows_index=index,
|
||||
missing=missing,
|
||||
)
|
||||
|
||||
|
||||
def check_travel_limit(
|
||||
report: ValidationReport,
|
||||
gross_a: Decimal,
|
||||
manage_total: Decimal,
|
||||
travel_and_business: Decimal,
|
||||
) -> None:
|
||||
"""``BUD-VAL-001``:差旅费 + 业务费 ≤ [毛利 A − (项目管理费用总额 − 差旅费 − 业务费)] × 比例。"""
|
||||
rate = to_dec(RULES.travel_business_limit_rate)
|
||||
travel = to_dec(travel_and_business)
|
||||
allowed = (to_dec(gross_a) - (to_dec(manage_total) - travel)) * rate / Decimal("100")
|
||||
if travel > allowed:
|
||||
report.error(
|
||||
"BUD-VAL-001",
|
||||
"项目管理费用中差旅费与业务费合计 "
|
||||
f"{money_str(travel)} 超出限额 {money_str(allowed)}"
|
||||
f"(限额=[毛利A −(项目管理费用总额 − 差旅业务费)]×{rate}%)",
|
||||
field="budget.manage_lines",
|
||||
travel=money_str(travel),
|
||||
allowed=money_str(allowed),
|
||||
gross_a=money_str(gross_a),
|
||||
manage_total=money_str(manage_total),
|
||||
)
|
||||
|
||||
|
||||
def check_contribution_rate(report: ValidationReport, contribution_rate: object) -> None:
|
||||
"""``BUD-VAL-002``:贡献利润率阈值。老系统这个校验被注释掉了,实际不生效。
|
||||
|
||||
动作由系统参数 ``calc.contribution_rate_action`` 决定:``block`` 阻止送审,``warn`` 只告警
|
||||
(默认,等业务确认后再收紧),``none`` 完全不检查。
|
||||
"""
|
||||
action = RULES.contribution_rate_action
|
||||
if action == "none":
|
||||
return
|
||||
from .money import Ratio
|
||||
|
||||
value = contribution_rate
|
||||
if isinstance(value, Ratio):
|
||||
if not value.defined:
|
||||
report.warning("BUD-VAL-002", "贡献利润率无法计算(不含税收入为 0),送审前请确认", "profit.contribution_rate")
|
||||
return
|
||||
value = value.value
|
||||
threshold_key = "budget.contribution_rate_threshold"
|
||||
threshold = to_dec(THRESHOLD_REGISTRY.get(threshold_key, "0"))
|
||||
if threshold == ZERO:
|
||||
return
|
||||
if to_dec(value) < threshold:
|
||||
message = f"项目贡献利润率 {money_str(value)}% 低于配置阈值 {money_str(threshold)}%"
|
||||
if action == "block":
|
||||
report.error("BUD-VAL-002", message, "profit.contribution_rate", value=money_str(value), threshold=money_str(threshold))
|
||||
else:
|
||||
report.warning("BUD-VAL-002", message, "profit.contribution_rate", value=money_str(value), threshold=money_str(threshold))
|
||||
|
||||
|
||||
#: 阈值这类"业务随时要改"的数字放在系统配置里,由服务层在计算前灌进来。
|
||||
THRESHOLD_REGISTRY: dict[str, str] = {}
|
||||
|
||||
|
||||
def set_thresholds(values: dict[str, object]) -> None:
|
||||
THRESHOLD_REGISTRY.clear()
|
||||
THRESHOLD_REGISTRY.update({str(k): str(v) for k, v in (values or {}).items()})
|
||||
|
||||
|
||||
def check_pay_plan_reconciles(
|
||||
report: ValidationReport,
|
||||
pay_by_type: dict[int, Decimal],
|
||||
purchase_by_type: dict[int, Decimal],
|
||||
) -> None:
|
||||
"""``PLAN-VAL-001``:付款计划四类含税合计分别等于采购明细对应分类含税金额。"""
|
||||
from .mapping import PURCHASE_TYPE_TO_KEY
|
||||
|
||||
labels = {1: "设备", 2: "施工", 3: "服务", 4: "其他"}
|
||||
for code, label in labels.items():
|
||||
paid = to_dec(pay_by_type.get(code))
|
||||
purchased = to_dec(purchase_by_type.get(code))
|
||||
if paid != purchased:
|
||||
report.error(
|
||||
"PLAN-VAL-001",
|
||||
f"{label}类付款计划合计 {money_str(paid)} 与采购成本明细含税 {money_str(purchased)} 不一致",
|
||||
field="budget.pay_plan",
|
||||
purchase_type=code,
|
||||
paid=money_str(paid),
|
||||
purchased=money_str(purchased),
|
||||
)
|
||||
|
||||
|
||||
def check_fund_plan_totals(
|
||||
report: ValidationReport,
|
||||
*,
|
||||
fund_cost_total: Decimal,
|
||||
fund_income_total: Decimal,
|
||||
purchase_include_total: Decimal,
|
||||
earnest_cost_total: Decimal,
|
||||
manage_total: Decimal,
|
||||
income_include_total: Decimal,
|
||||
earnest_income_total: Decimal,
|
||||
) -> None:
|
||||
"""``PLAN-VAL-002``:资金计划收付总额与明细勾稽。"""
|
||||
expected_cost = to_dec(purchase_include_total) + to_dec(earnest_cost_total) + to_dec(manage_total)
|
||||
if to_dec(fund_cost_total) != expected_cost:
|
||||
report.error(
|
||||
"PLAN-VAL-002",
|
||||
f"资金计划支出合计 {money_str(fund_cost_total)} 应等于"
|
||||
f"采购含税 {money_str(purchase_include_total)} + 保证金 {money_str(earnest_cost_total)}"
|
||||
f" + 项目管理费用 {money_str(manage_total)} = {money_str(expected_cost)}",
|
||||
field="budget.fund_months",
|
||||
fund_total=money_str(fund_cost_total),
|
||||
expected=money_str(expected_cost),
|
||||
)
|
||||
expected_income = to_dec(income_include_total) + to_dec(earnest_income_total)
|
||||
if to_dec(fund_income_total) != expected_income:
|
||||
report.error(
|
||||
"PLAN-VAL-002",
|
||||
f"资金计划收款合计 {money_str(fund_income_total)} 应等于"
|
||||
f"收入含税 {money_str(income_include_total)} + 保证金收款 {money_str(earnest_income_total)}"
|
||||
f" = {money_str(expected_income)}",
|
||||
field="budget.fund_months",
|
||||
fund_total=money_str(fund_income_total),
|
||||
expected=money_str(expected_income),
|
||||
)
|
||||
|
||||
|
||||
def check_fund_months(report: ValidationReport, months: list[str], plan_start: str, plan_end: str) -> None:
|
||||
"""``PLAN-VAL-003``:月份不得重复,起止月必须存在。"""
|
||||
seen: set[str] = set()
|
||||
for month in months:
|
||||
if month in seen:
|
||||
report.error("PLAN-VAL-003", f"资金计划月份 {month} 重复", "budget.fund_months", month=month)
|
||||
seen.add(month)
|
||||
for boundary, label in ((plan_start, "开始"), (plan_end, "结束")):
|
||||
if boundary and boundary not in seen:
|
||||
report.error(
|
||||
"PLAN-VAL-003",
|
||||
f"资金计划缺少项目{label}月 {boundary}",
|
||||
"budget.fund_months",
|
||||
missing=boundary,
|
||||
)
|
||||
|
||||
|
||||
def check_tax_inputs(report: ValidationReport, rows: list[dict], *, label: str) -> None:
|
||||
"""``TAX-06``/``TAX-07``:税率范围与高精度税率提示。"""
|
||||
for index, row in enumerate(rows, start=1):
|
||||
raw = row.get("tax_rate")
|
||||
if raw is None or str(raw).strip() == "":
|
||||
continue
|
||||
rate = to_dec(raw)
|
||||
if rate < ZERO or rate > Decimal("100"):
|
||||
report.error("INPUT-TAX-RANGE", f"{label}第 {index} 行税率 {raw} 不在 0~100 之间",
|
||||
field=f"{label}#{index}", row_index=index)
|
||||
elif rate != rate.quantize(Decimal("1")):
|
||||
report.warning("TAX-07", f"{label}第 {index} 行税率 {raw} 含小数,请确认是否为录入误差",
|
||||
field=f"{label}#{index}", row_index=index)
|
||||
|
|
@ -0,0 +1,493 @@
|
|||
"""数据权限引擎。
|
||||
|
||||
需求是"同一个人,在项目列表看全公司、在结算列表只看本部门、在预算列表看本部门及下级
|
||||
但把大额项目藏掉"。所以不能只在角色上挂一个 scope 字段,要做成可组合的策略:
|
||||
|
||||
求值顺序
|
||||
========
|
||||
|
||||
1. **粗筛主体**:命中"全部人 / 我的任一角色 / 我本人 / 我任一部门 / 我任一岗位"的策略;
|
||||
2. **allow 之间取并集**:每条 = ``范围谓词 AND 自定义条件``,多条 OR;
|
||||
3. **deny 取并集后整体排除**:``AND NOT (deny1 OR deny2 ...)``;
|
||||
4. **一条 allow 都没命中**时退回兜底范围 ``self``,不把人锁死;
|
||||
5. 系统管理员直接返回"不加限制"。
|
||||
|
||||
范围谓词怎么落到列上,由 :class:`ModuleSpec` 声明,模块注册一次就够,业务查询只要
|
||||
``session.query(...).where(*scope_conditions)``,看不到任何权限细节。
|
||||
|
||||
自定义条件用 JSON 条件树而不是拼 SQL 字符串:字段名要过白名单,值走绑定参数,
|
||||
这样"自定义"不会变成注入入口。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Callable
|
||||
|
||||
from sqlalchemy import and_, false, or_, select, true
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import (
|
||||
FALLBACK_SCOPE,
|
||||
Account,
|
||||
AccountIdentity,
|
||||
Effect,
|
||||
OrgUnit,
|
||||
PermDataPolicy,
|
||||
Project,
|
||||
ProjectMember,
|
||||
ScopeType,
|
||||
)
|
||||
from . import permissions
|
||||
|
||||
|
||||
@dataclass
|
||||
class ModuleSpec:
|
||||
"""一个业务模块怎么接数据权限。"""
|
||||
|
||||
module: str
|
||||
label: str
|
||||
entity: Any
|
||||
org_column: str = "org_unit_id" # 数据归属部门列
|
||||
owner_column: str = "creator_id" # 数据归属人列
|
||||
# 口径组的族代表:留空表示这个模块自己就是一个口径。概算/预算/结算/决算填 "project",
|
||||
# 意思是"这一族共用挂在 project 上的那条策略",见 :func:`_policies_for_module`。
|
||||
family: str = ""
|
||||
# 需要 join 才能判定的范围(如"我参与的"),返回一个 EXISTS 子句
|
||||
participant_predicate: Callable[[int], Any] | None = None
|
||||
# 允许出现在自定义条件里的字段白名单:对外的名字 -> 实体属性
|
||||
filterable: dict[str, str] = field(default_factory=dict)
|
||||
# 金额类字段,条件里按数值比
|
||||
numeric: tuple[str, ...] = ()
|
||||
|
||||
|
||||
#: 字段名 -> 操作符 -> 生成 SQL 表达式
|
||||
OPERATORS = {
|
||||
"eq": lambda column, value: column == value,
|
||||
"ne": lambda column, value: column != value,
|
||||
"gt": lambda column, value: column > value,
|
||||
"gte": lambda column, value: column >= value,
|
||||
"lt": lambda column, value: column < value,
|
||||
"lte": lambda column, value: column <= value,
|
||||
"in": lambda column, value: column.in_(value if isinstance(value, (list, tuple)) else [value]),
|
||||
"not_in": lambda column, value: column.not_in(value if isinstance(value, (list, tuple)) else [value]),
|
||||
"contains": lambda column, value: column.like(f"%{value}%"),
|
||||
"not_contains": lambda column, value: ~column.like(f"%{value}%"),
|
||||
"is_null": lambda column, value: column.is_(None),
|
||||
"is_not_null": lambda column, value: column.isnot(None),
|
||||
}
|
||||
|
||||
#: 条件树里的动态变量,运行期换成当前人的上下文
|
||||
DYNAMIC_VALUES = ("$account_id", "$org_unit_ids", "$org_unit_ids_with_children", "$account_name")
|
||||
|
||||
|
||||
_REGISTRY: dict[str, ModuleSpec] = {}
|
||||
|
||||
|
||||
def register(spec: ModuleSpec) -> ModuleSpec:
|
||||
_REGISTRY[spec.module] = spec
|
||||
return spec
|
||||
|
||||
|
||||
def spec_for(module: str) -> ModuleSpec | None:
|
||||
return _REGISTRY.get(module)
|
||||
|
||||
|
||||
def registered_modules() -> list[dict[str, str]]:
|
||||
return [{"module": item.module, "label": item.label, "family": item.family}
|
||||
for item in _REGISTRY.values()]
|
||||
|
||||
|
||||
def policy_covers(module: str) -> list[str]:
|
||||
"""在 ``module`` 上配一条策略,实际管到哪几个模块。
|
||||
|
||||
族代表上的策略是整族的默认口径;成员模块上配的策略只管它自己。界面靠这句话说明
|
||||
一条策略的作用面,省得管理员以为"超级管理员 - budget"只管预算那一页。
|
||||
"""
|
||||
spec = spec_for(module)
|
||||
if spec is None or (spec.family and spec.family != module):
|
||||
return [module]
|
||||
return [item.module for item in _REGISTRY.values()
|
||||
if item.module == module or item.family == module]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 模块注册
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _project_participant(account_id: int):
|
||||
"""EXISTS (SELECT 1 FROM project_member ...):数据权限的"我参与的"。"""
|
||||
return (
|
||||
select(ProjectMember.id)
|
||||
.where(ProjectMember.project_id == Project.id, ProjectMember.account_id == account_id)
|
||||
.exists()
|
||||
)
|
||||
|
||||
|
||||
#: 项目这一族(项目列表 + 概算/预算/结算/决算)查的是同一张 Project 表、同一套归属列,
|
||||
#: 条件白名单也必须是同一份。白名单不一致时族策略会出事:在 project 上写好的条件换到
|
||||
#: 预算那一侧,会因为字段不在白名单里被 :func:`_condition_tree` 静默丢掉,于是同一条策略
|
||||
#: 在项目列表收着、在预算列表放开——那是最没人查得出来的放宽。
|
||||
_PROJECT_FILTERABLE = {
|
||||
"name": "name",
|
||||
"project_no": "project_no",
|
||||
"type": "type",
|
||||
"stage": "stage",
|
||||
"customer": "customer",
|
||||
"org_unit_id": "org_unit_id",
|
||||
"creator_id": "creator_id",
|
||||
"principal_id": "principal_id",
|
||||
"underwritten_mode": "underwritten_mode",
|
||||
"contract_amount": "contract_amount",
|
||||
"contribution_profit_rate": "contribution_profit_rate",
|
||||
"created_at": "created_at",
|
||||
}
|
||||
_PROJECT_NUMERIC = ("contract_amount", "contribution_profit_rate", "gross_profit")
|
||||
|
||||
register(ModuleSpec(
|
||||
module="project",
|
||||
label="项目列表",
|
||||
entity=Project,
|
||||
org_column="org_unit_id",
|
||||
owner_column="creator_id",
|
||||
participant_predicate=_project_participant,
|
||||
filterable=dict(_PROJECT_FILTERABLE),
|
||||
numeric=_PROJECT_NUMERIC,
|
||||
))
|
||||
|
||||
# 概算/预算/结算/决算都挂在项目上,数据权限直接沿用项目那套归属:
|
||||
# 能看到项目,才能看到它下面的各版本。这样不会出现"列表看得见、详情 403"。
|
||||
# 口径既然相同,这四个成员模块就不需要各自一条策略:族策略管的就是它们。从前那种
|
||||
# "每个模块种一条一模一样的"只会长出三五条重复授权,还会种漏——内置角色"公司领导"
|
||||
# 就漏了预算那条,他一进预算列表直接掉进 self 兜底。
|
||||
for _alias, _label in (("estimate", "项目立项(概算)"), ("budget", "项目预算"),
|
||||
("settlement", "月度结算"), ("final", "项目决算")):
|
||||
register(ModuleSpec(
|
||||
module=_alias,
|
||||
label=_label,
|
||||
entity=Project,
|
||||
org_column="org_unit_id",
|
||||
owner_column="creator_id",
|
||||
participant_predicate=_project_participant,
|
||||
family="project",
|
||||
filterable=dict(_PROJECT_FILTERABLE),
|
||||
numeric=_PROJECT_NUMERIC,
|
||||
))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 上下文
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class ScopeContext:
|
||||
account: Account
|
||||
role_ids: list[int]
|
||||
org_unit_ids: list[int] # 本人全部身份所在部门
|
||||
position_ids: list[int]
|
||||
primary_org_id: int | None
|
||||
org_unit_ids_with_children: list[int] = field(default_factory=list)
|
||||
_db: Any = None # 供条件树里展开部门下级用,不参与序列化
|
||||
|
||||
|
||||
def build_scope_context(db: Session, account: Account) -> ScopeContext:
|
||||
identities = db.execute(
|
||||
select(AccountIdentity).where(AccountIdentity.account_id == account.id)
|
||||
).scalars().all()
|
||||
org_ids = sorted({row.org_unit_id for row in identities}) or ([account.org_unit_id] if account.org_unit_id else [])
|
||||
position_ids = sorted({row.position_id for row in identities if row.position_id})
|
||||
if account.position_id and account.position_id not in position_ids:
|
||||
position_ids.append(account.position_id)
|
||||
primary = account.org_unit_id
|
||||
if identities:
|
||||
default_row = next((row for row in identities if row.is_default), identities[0])
|
||||
primary = primary or default_row.org_unit_id
|
||||
return ScopeContext(
|
||||
account=account,
|
||||
role_ids=[role.id for role in permissions.account_roles(db, account.id)],
|
||||
org_unit_ids=org_ids,
|
||||
position_ids=position_ids,
|
||||
primary_org_id=primary,
|
||||
org_unit_ids_with_children=descendant_unit_ids(db, org_ids),
|
||||
)
|
||||
|
||||
|
||||
def _context_with_db(db: Session, context: ScopeContext) -> ScopeContext:
|
||||
context._db = db
|
||||
return context
|
||||
|
||||
|
||||
def _descendant_prefix(unit: OrgUnit) -> str:
|
||||
"""把部门路径收成"能安全当 LIKE 前缀"的形状:一定以 ``/`` 开头、也以 ``/`` 结尾。
|
||||
|
||||
两个真实的坑,都朝越权那边倒:
|
||||
|
||||
* ``org_unit.path`` 的列默认值是 ``"/"``(脚本直插、没跑过路径重算的部门就是这个值),
|
||||
拿它当前缀等于 ``LIKE '/%'``,整棵组织树都算"我的下级",本部门及下级当场变成全部数据;
|
||||
* 少写结尾斜杠的路径(``/1/2``)会把同级的 ``20/21/…29`` 一起前缀匹配进来。
|
||||
|
||||
所以宁可按 ``/{id}/`` 兜底:宁可少给几部门,不能多给一整棵树。
|
||||
"""
|
||||
path = (unit.path or "").strip().rstrip("/")
|
||||
return f"{path}/" if path and path != "/" else f"/{unit.id}/"
|
||||
|
||||
|
||||
def descendant_unit_ids(db: Session, unit_ids: list[int]) -> list[int]:
|
||||
"""按 ``org_unit.path`` 前缀匹配取自身 + 全部下级。
|
||||
|
||||
用 path 前缀而不是递归 CTE:组织树很深时递归查询每页都要跑一遍,前缀索引一次扫完。
|
||||
"""
|
||||
if not unit_ids:
|
||||
return []
|
||||
units = db.execute(select(OrgUnit).where(OrgUnit.id.in_(unit_ids))).scalars().all()
|
||||
prefixes = [_descendant_prefix(unit) for unit in units]
|
||||
rows = db.execute(
|
||||
select(OrgUnit.id).where(
|
||||
or_(OrgUnit.id.in_(unit_ids), *[OrgUnit.path.like(f"{prefix}%") for prefix in prefixes])
|
||||
)
|
||||
).scalars().all()
|
||||
return sorted(set(rows))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 谓词构造
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class ScopeDecision:
|
||||
"""一次数据权限求值的结果,带人类可读的说明,界面上要能告诉用户"你为什么看不到"。"""
|
||||
|
||||
def __init__(self, condition: Any, summary: list[str], *, unlimited: bool = False) -> None:
|
||||
self.condition = condition
|
||||
self.summary = summary
|
||||
self.unlimited = unlimited
|
||||
|
||||
def apply_to(self, query: Any) -> Any:
|
||||
return query if self.unlimited or self.condition is None else query.where(self.condition)
|
||||
|
||||
def describe(self) -> str:
|
||||
return ";".join(self.summary) if self.summary else "全部数据"
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {"unlimited": self.unlimited, "description": self.describe()}
|
||||
|
||||
|
||||
def evaluate(db: Session, module: str, context: ScopeContext) -> ScopeDecision:
|
||||
_context_with_db(db, context)
|
||||
spec = spec_for(module)
|
||||
if spec is None:
|
||||
# 没注册的模块一律不给看,而不是放行——漏注册应当是个 bug,不能变成越权
|
||||
return ScopeDecision(false(), [f"模块 {module} 未登记数据权限,默认拒绝"])
|
||||
|
||||
if context.account.is_system_admin:
|
||||
return ScopeDecision(None, [], unlimited=True)
|
||||
|
||||
policies = permissions.data_policies_for(
|
||||
db, context.account.id, context.role_ids, context.org_unit_ids, context.position_ids
|
||||
)
|
||||
module_policies, inherited = _policies_for_module(policies, spec, module)
|
||||
|
||||
allows: list[Any] = []
|
||||
denies: list[Any] = []
|
||||
summary: list[str] = []
|
||||
|
||||
if inherited:
|
||||
summary.append(f"沿用「{spec_for(spec.family).label}」的口径")
|
||||
|
||||
for policy in module_policies:
|
||||
condition = _policy_condition(db, spec, policy, context)
|
||||
if condition is None:
|
||||
continue
|
||||
if policy.effect == Effect.DENY:
|
||||
denies.append(condition)
|
||||
summary.append(f"排除:{policy.name}")
|
||||
else:
|
||||
allows.append(condition)
|
||||
summary.append(f"{policy.name}({ScopeType.label(policy.scope_type)})")
|
||||
|
||||
entity = spec.entity
|
||||
|
||||
if any(_is_unlimited(item) for item in module_policies if item.effect == Effect.ALLOW):
|
||||
# 有"全部数据"的 allow 且没有任何 deny 时,等价于不加限制
|
||||
if not denies:
|
||||
return ScopeDecision(None, summary, unlimited=True)
|
||||
|
||||
if not allows:
|
||||
fallback = _scope_predicate(None, spec, FALLBACK_SCOPE, [], context, entity)
|
||||
condition = fallback if fallback is not None else false()
|
||||
summary.append(f"未配置生效策略,按默认范围「{ScopeType.label(FALLBACK_SCOPE)}」")
|
||||
else:
|
||||
condition = allows[0] if len(allows) == 1 else or_(*allows)
|
||||
|
||||
if denies:
|
||||
condition = and_(condition, ~or_(*denies)) if condition is not None else ~or_(*denies)
|
||||
|
||||
if condition is None:
|
||||
return ScopeDecision(None, summary, unlimited=True)
|
||||
return ScopeDecision(condition, summary)
|
||||
|
||||
|
||||
def _policies_for_module(policies: list[PermDataPolicy], spec: ModuleSpec,
|
||||
module: str) -> tuple[list[PermDataPolicy], bool]:
|
||||
"""这次查询该用哪几条策略,返回 ``(策略, 是否沿用族口径)``。
|
||||
|
||||
规则只有一句:**本模块的专属策略优先,一条都没有才回落到族策略**。是"优先"不是
|
||||
"并集"——项目上配了全部数据、预算想收窄成本部门,单独配一条预算策略就得真的收窄,
|
||||
不能被项目那条族策略又撑回去。族内各模块的归属列与条件白名单完全一致,同一条族策略
|
||||
在族内任何模块上编译出来的谓词都一样。
|
||||
"""
|
||||
own = [item for item in policies if item.module == module and _in_valid_window(item)]
|
||||
if own or not spec.family or spec.family == module:
|
||||
return own, False
|
||||
inherited = [item for item in policies
|
||||
if item.module == spec.family and _in_valid_window(item)]
|
||||
return inherited, bool(inherited)
|
||||
|
||||
|
||||
def _is_unlimited(policy: PermDataPolicy) -> bool:
|
||||
return policy.scope_type == ScopeType.ALL and not (policy.conditions_json or "").strip()
|
||||
|
||||
|
||||
def _in_valid_window(policy: PermDataPolicy) -> bool:
|
||||
from datetime import date
|
||||
|
||||
today = date.today().isoformat()
|
||||
if policy.valid_from and policy.valid_from > today:
|
||||
return False
|
||||
if policy.valid_to and policy.valid_to < today:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _policy_condition(db: Session | None, spec: ModuleSpec, policy: PermDataPolicy,
|
||||
context: ScopeContext) -> Any:
|
||||
entity = spec.entity
|
||||
target_ids = _json_list(policy.target_ids_json)
|
||||
scope = _scope_predicate(db, spec, policy.scope_type, target_ids, context, entity,
|
||||
include_children=policy.include_children)
|
||||
condition = None if scope is None else true()
|
||||
if scope is not None:
|
||||
condition = scope
|
||||
tree = _json_dict(policy.conditions_json)
|
||||
if tree:
|
||||
node = _condition_tree(spec, tree, context)
|
||||
condition = and_(condition, node) if condition is not None else node
|
||||
if condition is None:
|
||||
# CUSTOM 且没写条件、或 ALL:视为不加范围限制
|
||||
return None
|
||||
return condition
|
||||
|
||||
|
||||
def _scope_predicate(
|
||||
db: Session | None,
|
||||
spec: ModuleSpec,
|
||||
scope_type: str,
|
||||
target_ids: list[int],
|
||||
context: ScopeContext,
|
||||
entity: Any,
|
||||
*,
|
||||
include_children: bool = True,
|
||||
) -> Any:
|
||||
"""把范围类型翻成 SQL。返回 None 表示"这一层不加限制"。"""
|
||||
org_column = getattr(entity, spec.org_column, None)
|
||||
owner_column = getattr(entity, spec.owner_column, None)
|
||||
|
||||
if scope_type == ScopeType.ALL:
|
||||
return None
|
||||
if scope_type == ScopeType.SELF:
|
||||
return owner_column == context.account.id
|
||||
if scope_type == ScopeType.UNIT:
|
||||
ids = context.org_unit_ids or ([-1])
|
||||
return org_column.in_(ids)
|
||||
if scope_type == ScopeType.UNIT_AND_BELOW:
|
||||
ids = context.org_unit_ids_with_children or [-1]
|
||||
return org_column.in_(ids)
|
||||
if scope_type == ScopeType.IDENTITY_UNITS:
|
||||
return org_column.in_(context.org_unit_ids or [-1])
|
||||
if scope_type == ScopeType.ORG_LIST:
|
||||
ids = target_ids
|
||||
if include_children and db is not None:
|
||||
ids = descendant_unit_ids(db, target_ids)
|
||||
return org_column.in_(ids or [-1])
|
||||
if scope_type == ScopeType.ACCOUNT_LIST:
|
||||
return owner_column.in_(target_ids or [-1])
|
||||
if scope_type == ScopeType.PARTICIPANT:
|
||||
predicate = spec.participant_predicate(context.account.id) if spec.participant_predicate else None
|
||||
mine = owner_column == context.account.id
|
||||
return or_(mine, predicate) if predicate is not None else mine
|
||||
if scope_type == ScopeType.DEPT_OF_RECORD:
|
||||
ids = context.org_unit_ids_with_children or [-1]
|
||||
return org_column.in_(ids)
|
||||
if scope_type == ScopeType.CUSTOM:
|
||||
return None
|
||||
return owner_column == context.account.id
|
||||
|
||||
|
||||
def _condition_tree(spec: ModuleSpec, tree: dict[str, Any], context: ScopeContext) -> Any:
|
||||
op = str(tree.get("op") or "and").lower()
|
||||
if op in ("and", "or"):
|
||||
children = [_condition_tree(spec, item, context) for item in tree.get("items") or []]
|
||||
children = [item for item in children if item is not None]
|
||||
if not children:
|
||||
return None
|
||||
return and_(*children) if op == "and" else or_(*children)
|
||||
|
||||
field_name = str(tree.get("field") or "")
|
||||
attribute = spec.filterable.get(field_name)
|
||||
if not attribute:
|
||||
# 白名单外的字段直接忽略这一条,不报错也不放宽
|
||||
return None
|
||||
column = getattr(spec.entity, attribute)
|
||||
operator = str(tree.get("operator") or "eq").lower()
|
||||
builder = OPERATORS.get(operator)
|
||||
if builder is None:
|
||||
return None
|
||||
value = _resolve_value(tree.get("value"), context)
|
||||
if field_name in spec.numeric and isinstance(value, str):
|
||||
try:
|
||||
value = float(value)
|
||||
except ValueError:
|
||||
return None
|
||||
return builder(column, value)
|
||||
|
||||
|
||||
def _resolve_value(value: Any, context: ScopeContext) -> Any:
|
||||
if isinstance(value, str) and value in DYNAMIC_VALUES:
|
||||
if value == "$account_id":
|
||||
return context.account.id
|
||||
if value == "$account_name":
|
||||
return context.account.display_name
|
||||
if value == "$org_unit_ids":
|
||||
return context.org_unit_ids or [-1]
|
||||
if value == "$org_unit_ids_with_children":
|
||||
return context.org_unit_ids_with_children or [-1]
|
||||
if isinstance(value, list):
|
||||
return [_resolve_value(item, context) for item in value]
|
||||
return value
|
||||
|
||||
|
||||
def _json_list(raw: str) -> list[int]:
|
||||
try:
|
||||
data = json.loads(raw or "[]")
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
return [int(item) for item in data if str(item).strip().isdigit()]
|
||||
|
||||
|
||||
def _json_dict(raw: str) -> dict[str, Any]:
|
||||
if not (raw or "").strip():
|
||||
return {}
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
return {}
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def explain(db: Session, module: str, account: Account) -> dict[str, Any]:
|
||||
"""给管理界面用:"如果以这个人的身份打开这个模块,会看到什么范围"。"""
|
||||
context = build_scope_context(db, account)
|
||||
return evaluate(db, module, context).to_dict()
|
||||
|
|
@ -0,0 +1,547 @@
|
|||
"""统一身份(dsh-hub)的 HTTP 客户端。
|
||||
|
||||
契约依据是 unisoa 仓库里的《dsh-hub 统一门户 第三方系统对接指南》,接口路径、字段名、
|
||||
鉴权头都以那份文档为准。四条最容易踩的:
|
||||
|
||||
1. **两条密钥通道互不通用**。目录用 ``X-Directory-Key``,票据校验用
|
||||
``X-Integration-Key``。目录密钥拿去换身份会被 401 挡回来。
|
||||
2. **响应信封成功恒为 HTTP 200 + ``code == "200"``(字符串)**。判成功只认 ``code``,
|
||||
不要拿 ``message`` 的中文文案做判断,也不要只看 HTTP 状态。
|
||||
3. **票据失败也是 HTTP 200**,由 ``data.active=false`` + ``reason`` 表达。
|
||||
按 ``active`` 分支,不是按状态码。
|
||||
4. **票据是一次性的,禁止自动重试**。校验入口"先查询、立即删除",删除发生在受众与
|
||||
有效期判定之前,所以超时后无法判断 Hub 是否已经消费过,只能丢弃让用户重新发起跳转。
|
||||
|
||||
免登只走票据:本系统不再自己认人,也不保留 OAuth2 授权码那套(Hub 没有那两个端点)。
|
||||
|
||||
登录页上的账号口令走第三条通道:``GET /auth/captcha`` + ``POST /auth/login``,不要密钥
|
||||
(那两条密钥通道是服务端到服务端的),判定全在 Hub,本系统只负责把结果换成自己的会话。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
from ..config import settings
|
||||
|
||||
|
||||
class HubError(Exception):
|
||||
"""目录或身份接口不可用(网络、密钥、信封非成功码)。"""
|
||||
|
||||
|
||||
class TicketRejected(Exception):
|
||||
"""票据没换到身份。
|
||||
|
||||
``reason`` 用 Hub 的原词,前端按词给不同提示;``retryable`` 恒为 False——
|
||||
票据一次性,任何形式的自动重试都会把用户坑进 ticket_invalid。
|
||||
"""
|
||||
|
||||
def __init__(self, reason: str, message: str, *, code: str = "",
|
||||
data: dict[str, Any] | None = None) -> None:
|
||||
super().__init__(message)
|
||||
self.reason = reason
|
||||
self.message = message
|
||||
#: Hub 侧的错误码原值(``401001`` 这类),只在日志里出现
|
||||
self.code = code
|
||||
#: 校验没通过时 Hub 回的那一段。票据失败也是 HTTP 200 + ``active:false``,
|
||||
#: 里面偶尔还带着 ``sub``,调用方靠它才知道"该把本地哪个账号停用"。
|
||||
self.data = data or {}
|
||||
|
||||
@property
|
||||
def retryable(self) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
class HubRejected(Exception):
|
||||
"""Hub 看懂了这次登录请求并且明确说不行:账号、口令或验证码不对。
|
||||
|
||||
与 :class:`HubError` 的区别就是这条不能当回落本地口令的理由——Hub 已经替这个人
|
||||
表过态了,再拿库里那个旧哈希兜一层,等于让 Hub 侧的停用与改口令当场失效。
|
||||
``needs_captcha`` 为真时登录页要换一张验证码再让人试。
|
||||
"""
|
||||
|
||||
def __init__(self, message: str, *, code: str = "", needs_captcha: bool = False) -> None:
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
self.code = code
|
||||
self.needs_captcha = needs_captcha
|
||||
|
||||
|
||||
#: Hub 明说"验证码这一项不对"的几种写法(裸 error 名与信封码各一套)。
|
||||
CAPTCHA_ERROR_SLUGS = frozenset({"invalid_captcha", "captcha_invalid", "captcha_expired"})
|
||||
CAPTCHA_ERROR_CODES = frozenset({"400002", "400101"})
|
||||
#: Hub 已经看懂并表态的几种错误码,按被拒处理,不算"服务不可用"。
|
||||
REJECT_CODES = frozenset({"400001", "401001", "403001", "422001"})
|
||||
#: 服务自己出问题,与用户填了什么无关。
|
||||
UNAVAILABLE_CODES = frozenset({"500001"})
|
||||
|
||||
# 文档 §4.3 的 reason 原词 -> 给人看的话
|
||||
TICKET_MESSAGES = {
|
||||
"ticket_invalid": "登录票据无效或已被使用,请回到统一门户重新点击进入",
|
||||
"ticket_audience_mismatch": "这张票据不是发给本系统的,检查 hub.app_code 与密钥是否配对",
|
||||
"ticket_expired": "登录票据已过期,请回到统一门户重新点击进入",
|
||||
"user_inactive": "统一身份里这个账号已停用或不存在",
|
||||
}
|
||||
|
||||
|
||||
#: 票据校验这一步会被 Hub 直接拒掉的三种情况(对接指南第 9 节错误码表)。
|
||||
#: 一律糊成"密钥不对"的话,运维只能挨个试;照表翻成三句能照着查的话,
|
||||
#: 接口 reason 也跟着分开——这一条与 unisoa 的 ``hub.ticket_reject`` 同一套口径。
|
||||
REJECT_HINTS = {
|
||||
"401001": "免登应用密钥不对、应用已被停用,或旧密钥过了宽限期",
|
||||
"403001": "免登应用编码与密钥不属于同一个应用,或应用已被停用",
|
||||
"404001": "Hub 上没有这个应用编码(大小写不敏感),核对 hub.app_code",
|
||||
}
|
||||
REJECT_REASONS = {
|
||||
"401001": "hub_key_rejected",
|
||||
"403001": "hub_app_forbidden",
|
||||
"404001": "hub_app_not_found",
|
||||
}
|
||||
|
||||
|
||||
def ticket_reject(code: str, status_code: int = 200) -> tuple[str, str]:
|
||||
"""Hub 的拒绝 -> ``(该查什么, 接口 reason)``。
|
||||
|
||||
错误码认不出来时退回按 HTTP 状态猜(401/403/404 是 Hub 网关吃掉信封的那几种部署),
|
||||
再猜不出来就只说"门户拒了这次校验",绝不把猜测写成结论。
|
||||
"""
|
||||
key = str(code or "").strip()
|
||||
if key in REJECT_HINTS:
|
||||
return REJECT_HINTS[key], REJECT_REASONS[key]
|
||||
if status_code == 401:
|
||||
return REJECT_HINTS["401001"], REJECT_REASONS["401001"]
|
||||
if status_code == 403:
|
||||
return REJECT_HINTS["403001"], REJECT_REASONS["403001"]
|
||||
if status_code == 404:
|
||||
return REJECT_HINTS["404001"], REJECT_REASONS["404001"]
|
||||
return "统一门户拒绝了这次票据校验", "hub_key_rejected"
|
||||
|
||||
|
||||
def _error_code(payload: object) -> str:
|
||||
"""从响应体里抠出 Hub 的错误码;响应体可能根本不是 JSON。"""
|
||||
if isinstance(payload, dict):
|
||||
return str(payload.get("code") or "").strip()
|
||||
return ""
|
||||
|
||||
|
||||
def _base_url() -> str:
|
||||
url = (settings.hub.base_url or "").rstrip("/")
|
||||
if not url:
|
||||
raise HubError("未配置 hub.base_url")
|
||||
# 文档允许 http:// 前缀,仅用于本地联调;生产必须 HTTPS。
|
||||
return url if url.startswith(("http://", "https://")) else f"http://{url}"
|
||||
|
||||
|
||||
def _timeout() -> int:
|
||||
return int(settings.hub.sync_timeout or 60)
|
||||
|
||||
|
||||
def _unwrap(payload: Any, *, what: str) -> dict[str, Any]:
|
||||
"""拆 ``{"code":"200","data":{...},"message":"..."}`` 信封。
|
||||
|
||||
兼容裸对象返回(本地假 Hub / 老版本),但那种情况下 code 缺失按失败处理会更安全,
|
||||
所以只有整体就是个 dict 且没有 code 键时才当成 data 本身。
|
||||
"""
|
||||
if not isinstance(payload, dict):
|
||||
raise HubError(f"{what}返回的不是 JSON 对象")
|
||||
code = payload.get("code")
|
||||
if code is None:
|
||||
return payload
|
||||
if str(code) != "200":
|
||||
raise HubError(f"{what}失败 code={code} message={str(payload.get('message'))[:160]}")
|
||||
data = payload.get("data")
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def _get_json(url: str, headers: dict[str, str], params: dict[str, Any], *, what: str,
|
||||
directory: bool = False) -> Any:
|
||||
try:
|
||||
response = httpx.get(url, headers=headers, params=params, timeout=_timeout())
|
||||
except httpx.HTTPError as exc:
|
||||
raise HubError(f"连接统一身份失败:{exc}") from exc
|
||||
if response.status_code >= 400:
|
||||
if directory:
|
||||
# 目录通道的 401 与免登的 401 不是一回事,各翻各的排查方向
|
||||
raise _directory_error(what, response.status_code, response.text)
|
||||
raise HubError(f"{what}返回 {response.status_code}:{response.text[:200]}")
|
||||
try:
|
||||
return response.json()
|
||||
except ValueError as exc:
|
||||
raise HubError(f"{what}返回的不是 JSON") from exc
|
||||
|
||||
|
||||
def _try_json(text: str) -> object:
|
||||
"""尽力把响应体读成 JSON,读不出来就当没有——错误码只是用来挑提示语。"""
|
||||
import json
|
||||
|
||||
try:
|
||||
return json.loads(text or "")
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
#: 目录接口花名册上限的取值区间(指南 §6.1:越界或非数字直接 400 400001,且这条接口没有分页)。
|
||||
MEMBER_LIMIT_MIN = 1
|
||||
MEMBER_LIMIT_MAX = 5000
|
||||
|
||||
#: 目录通道(``X-Directory-Key``)被挡时的排查口径。**"免登进得去、目录拉不动"几乎都栽在
|
||||
#: 这一条上**:Hub 在目录通道上复用了免登那套错误码和"集成密钥无效"的文案(指南 §6.1、§9),
|
||||
#: 照字面去查免登密钥一定查不出来——目录密钥是 Hub 服务端环境变量 ``HUB_DIRECTORY_KEYS`` 里
|
||||
#: 登记的条目(格式 ``标签:密钥``,逗号并列多条),不跟免登应用密钥共用,也没有管理界面、
|
||||
#: 不能在线轮换,改了只能重启。
|
||||
DIRECTORY_HINTS = {
|
||||
401: "目录密钥没被统一身份认账(401001)。目录通道认的是 Hub 服务端 HUB_DIRECTORY_KEYS "
|
||||
"里登记的那几把,与免登用的应用密钥互不通用,免登能登进来不代表目录拉得动——"
|
||||
"请让 Hub 管理员把 hub.directory_key 这一串加进 HUB_DIRECTORY_KEYS(改完要重启)",
|
||||
403: "统一身份拒了这次目录调用(403001):目录密钥所属应用被停用,或它与调用范围不匹配",
|
||||
404: "统一身份上没有这个目录接口(404001):多半是部署前缀或网关与对接文档不一致,"
|
||||
"核对 hub.directory_path",
|
||||
400: "目录接口拒了这次的查询参数(400001):member_limit 取值 1-5000,布尔参数只认 true/false",
|
||||
}
|
||||
|
||||
|
||||
def _directory_error(what: str, status_code: int, body: str) -> HubError:
|
||||
"""目录通道(全量与增量)的失败 -> 一句能照着查的话。
|
||||
|
||||
Hub 原样回的是"集成密钥无效",这句在目录通道上的实际意思是"目录密钥不认识",
|
||||
但运维照着它只会去查免登密钥,一查就是半天。原始状态码、错误码和响应体都留在
|
||||
后半句里,排查要用的信息一个字都不丢。
|
||||
"""
|
||||
code = _error_code(_try_json(body))
|
||||
hint = DIRECTORY_HINTS.get(int(status_code)) or "统一身份的目录接口不可用"
|
||||
suffix = f" {code}" if code else ""
|
||||
return HubError(f"{what}失败:{hint}(Hub 返回 {status_code}{suffix}:"
|
||||
f"{(body or '').strip()[:180]})")
|
||||
|
||||
|
||||
def _member_limit() -> int:
|
||||
"""把配置里的花名册上限收进接口允许的 1-5000。
|
||||
|
||||
配大了不就地报错,而是按上限发出去,让 Hub 用 ``truncated`` 说"人不止这些"——那种情况
|
||||
会被 :func:`fetch_directory` 判成拒绝对账,比拿一个查不出所以然的 400 好定位。
|
||||
"""
|
||||
try:
|
||||
value = int(settings.hub.directory_member_limit)
|
||||
except (TypeError, ValueError):
|
||||
return MEMBER_LIMIT_MAX
|
||||
return max(MEMBER_LIMIT_MIN, min(MEMBER_LIMIT_MAX, value))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 目录:全量 + 增量
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def fetch_directory() -> dict[str, Any]:
|
||||
"""拉全量目录,返回 ``{organizations, users, truncated, permission_version}``。
|
||||
|
||||
固定带 ``include_disabled=true&include_disabled_users=true``。文档 §6.4 说得很明白:
|
||||
默认导出会整棵裁掉"父组织停用"下面那些状态仍为启用的子树,镜像场景不带上这两个参数
|
||||
就会**静默少一批组织和人**——少掉的还是层级最深的那些,最难发现。
|
||||
"""
|
||||
if not settings.hub.configured:
|
||||
raise HubError("统一身份未启用或未配置目录密钥")
|
||||
limit = _member_limit()
|
||||
params = {
|
||||
"tree": "false",
|
||||
"include_disabled": "true",
|
||||
"include_disabled_users": "true",
|
||||
"member_limit": limit,
|
||||
}
|
||||
payload = _get_json(
|
||||
f"{_base_url()}{settings.hub.directory_path}",
|
||||
{"X-Directory-Key": settings.hub.directory_key, "Accept": "application/json"},
|
||||
params, what="目录全量", directory=True,
|
||||
)
|
||||
data = _unwrap(payload, what="目录全量")
|
||||
organizations = data.get("organizations")
|
||||
users = data.get("users")
|
||||
if not isinstance(organizations, list) or not isinstance(users, list):
|
||||
# 空集合契约上输出 [],缺键说明对端不是我们认的目录接口,宁可比报错也不要把
|
||||
# "接口换形状"当成"Hub 里一个人都没有"——那会把本地所有人停用。
|
||||
raise HubError("目录全量返回缺少 organizations / users 列表,拒绝据此改本地数据")
|
||||
truncated = bool(data.get("truncated"))
|
||||
if truncated:
|
||||
# 到了接口上限还截断,就不是改配置能解决的了,别让人对着一个调不动的键反复试
|
||||
next_step = (
|
||||
f"接口上限就是 {MEMBER_LIMIT_MAX} 且这一接口没有分页,得请 Hub 侧放宽上限或拆分应用"
|
||||
if limit >= MEMBER_LIMIT_MAX
|
||||
else f"请调大 hub.directory_member_limit(接口上限 {MEMBER_LIMIT_MAX})后重跑"
|
||||
)
|
||||
raise HubError(
|
||||
f"目录全量被 member_limit={limit} 截断,只同步一部分人比同步失败更糟;{next_step}"
|
||||
)
|
||||
return {
|
||||
"organizations": organizations,
|
||||
"users": users,
|
||||
"total_users": data.get("total_users") or 0,
|
||||
"returned_users": data.get("returned_users") or len(users),
|
||||
"permission_version": data.get("permission_version"),
|
||||
}
|
||||
|
||||
|
||||
def fetch_changes(since: int, limit: int | None = None) -> dict[str, Any]:
|
||||
"""拉一次增量变更流。
|
||||
|
||||
``since`` 是排他游标;调用方自己决定何时提交游标——文档要求同一批循环拉到
|
||||
``has_more=false`` 才允许推进,中途失败必须从老游标重来。
|
||||
"""
|
||||
if not settings.hub.configured:
|
||||
raise HubError("统一身份未启用或未配置目录密钥")
|
||||
params = {"since": int(max(0, since)), "limit": int(limit or settings.hub.changes_limit)}
|
||||
payload = _get_json(
|
||||
f"{_base_url()}{settings.hub.changes_path}",
|
||||
{"X-Directory-Key": settings.hub.directory_key, "Accept": "application/json"},
|
||||
params, what="目录增量", directory=True,
|
||||
)
|
||||
data = _unwrap(payload, what="目录增量")
|
||||
changes = data.get("changes")
|
||||
if not isinstance(changes, list):
|
||||
raise HubError("目录增量返回缺少 changes 列表")
|
||||
return {
|
||||
"cursor": int(data.get("cursor") if data.get("cursor") is not None else since),
|
||||
"oldest_seq": int(data.get("oldest_seq") or 0),
|
||||
"newest_seq": int(data.get("newest_seq") or 0),
|
||||
"has_more": bool(data.get("has_more")),
|
||||
"changes": changes,
|
||||
# since 落在 oldest_seq 之后说明中间流水已被裁剪,靠增量补不回来。
|
||||
# 这里只如实报出来,"退回全量"由 org_sync 决定,客户端不越权替它做。
|
||||
"behind": bool(data.get("oldest_seq")) and int(since) < int(data.get("oldest_seq")),
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 免登:一次性票据换身份
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def verify_ticket(ticket: str, app_code: str | None = None) -> dict[str, Any]:
|
||||
"""用门户跳转带来的一次性票据换身份,成功返回 Hub 的 data。
|
||||
|
||||
最小可用字段是 ``sub`` / ``account`` / ``display_name``;角色 Hub 不下发,本系统自持。
|
||||
``app_code`` 只有拿 HUB_DIRECTORY_KEYS 里的 bootstrap 密钥时才必填,日常不传。
|
||||
"""
|
||||
value = (ticket or "").strip()
|
||||
if not value:
|
||||
raise TicketRejected("ticket_invalid", "缺少登录票据")
|
||||
if not (settings.hub.enabled and settings.hub.base_url):
|
||||
raise TicketRejected("ticket_invalid", "统一身份未启用,无法校验登录票据")
|
||||
|
||||
headers = {"X-Integration-Key": settings.hub.integration_key, "Content-Type": "application/json"}
|
||||
if not settings.hub.integration_key:
|
||||
# 文档 §4.5:既无 X-Integration-Key 也无 app_code 时 Hub 返回 401;
|
||||
# 本地先挡掉,省一次无谓往返,也把"密钥没配"和"票据无效"区分开。
|
||||
raise TicketRejected("ticket_invalid", "未配置 hub.integration_key,无法校验登录票据")
|
||||
|
||||
body: dict[str, Any] = {"ticket": value}
|
||||
if app_code:
|
||||
body["app_code"] = app_code
|
||||
|
||||
# 这里刻意不包任何重试:票据"先查询、立即删除",重试必然 ticket_invalid。
|
||||
try:
|
||||
response = httpx.post(f"{_base_url()}{settings.hub.ticket_verify_path}",
|
||||
headers=headers, json=body, timeout=_timeout())
|
||||
except httpx.HTTPError as exc:
|
||||
raise TicketRejected("hub_unavailable",
|
||||
"统一身份暂时连不上,请回到门户重新点击进入(票据不会自动重试)") from exc
|
||||
|
||||
if response.status_code >= 400:
|
||||
# 密钥/应用层面的错误(401001 / 403001 / 404001):这是配置问题不是用户问题,
|
||||
# 提示里要点名该查哪一项,但绝不把密钥本身带出去。
|
||||
hint, reason = ticket_reject(_error_code(_try_json(response.text)), response.status_code)
|
||||
raise TicketRejected(reason, f"统一门户拒绝了本次免登校验:{hint}",
|
||||
code=_error_code(_try_json(response.text)))
|
||||
|
||||
try:
|
||||
payload = response.json()
|
||||
except ValueError as exc:
|
||||
raise TicketRejected("hub_unavailable", "统一身份返回的不是 JSON") from exc
|
||||
|
||||
if _error_code(payload) in REJECT_REASONS:
|
||||
# 有些部署把网关错误码放进 200 的信封里,走的是同一条口径
|
||||
hint, reason = ticket_reject(_error_code(payload))
|
||||
raise TicketRejected(reason, f"统一门户拒绝了本次免登校验:{hint}",
|
||||
code=_error_code(payload))
|
||||
|
||||
try:
|
||||
data = _unwrap(payload, what="票据校验")
|
||||
except HubError as exc:
|
||||
# 信封不是成功码:这是 Hub 那边出问题,不是这张票据的问题
|
||||
raise TicketRejected("hub_unavailable", str(exc)) from exc
|
||||
if not data.get("active"):
|
||||
reason = str(data.get("reason") or "ticket_invalid")
|
||||
raise TicketRejected(reason,
|
||||
TICKET_MESSAGES.get(reason, f"登录票据校验失败:{reason}"),
|
||||
data=data)
|
||||
|
||||
_assert_not_expired(data.get("expires_at"))
|
||||
_assert_audience(data.get("app_code"))
|
||||
|
||||
sub = str(data.get("sub") or "").strip()
|
||||
if not sub:
|
||||
raise TicketRejected("hub_no_subject", "统一身份没有返回 sub,无法建立身份映射")
|
||||
return data
|
||||
|
||||
|
||||
def _assert_not_expired(expires_at: Any) -> None:
|
||||
"""文档要求下游对 ``expires_at`` 做二次校验(时钟以 NTP 校准)。
|
||||
|
||||
票据本身 30 秒就过期,网络抖一下也可能落地即失效;与其放一个已失效的身份进来,
|
||||
不如明确拒绝并让用户重新点一次。
|
||||
"""
|
||||
raw = str(expires_at or "").strip()
|
||||
if not raw:
|
||||
return
|
||||
try:
|
||||
moment = datetime.fromisoformat(raw.replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
return
|
||||
if moment.tzinfo is None:
|
||||
moment = moment.replace(tzinfo=timezone.utc)
|
||||
if moment <= datetime.now(timezone.utc):
|
||||
raise TicketRejected("ticket_expired",
|
||||
TICKET_MESSAGES["ticket_expired"])
|
||||
|
||||
|
||||
def _assert_audience(ticket_app_code: Any) -> None:
|
||||
"""防串号:票据属于哪个应用要跟自己比对,密钥配错应用时靠这一步兜住。"""
|
||||
mine = (settings.hub.app_code or "").strip()
|
||||
theirs = str(ticket_app_code or "").strip()
|
||||
if mine and theirs and mine != theirs:
|
||||
raise TicketRejected("ticket_audience_mismatch",
|
||||
TICKET_MESSAGES["ticket_audience_mismatch"])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 登录页:验证码下发 + 账号口令校验
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_CAPTCHA_IMAGE_KEYS = ("image", "image_base64", "img", "captcha_image", "base64", "data")
|
||||
_CAPTCHA_TEXT_KEYS = ("question", "text", "challenge", "expression", "content", "prompt")
|
||||
|
||||
|
||||
def _captcha_view(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""把 Hub 的验证码响应整形成前端好画的形状,原始字段一并带回。
|
||||
|
||||
hubtest 回的是 ``{"id": "...", "image": "data:image/svg+xml;base64,..."}``,
|
||||
题目是 ``8 + 2 = ?`` 这种算术题;别的部署可能回 ``captcha_id``、也可能把题目
|
||||
直接写成文本,所以这里两侧的叫法都认。
|
||||
"""
|
||||
captcha_id = str(payload.get("captcha_id") or payload.get("id") or payload.get("key") or "")
|
||||
image = ""
|
||||
for key in _CAPTCHA_IMAGE_KEYS:
|
||||
value = payload.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
image = value.strip()
|
||||
break
|
||||
question = ""
|
||||
for key in _CAPTCHA_TEXT_KEYS:
|
||||
value = payload.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
question = value.strip()
|
||||
break
|
||||
return {"captchaId": captcha_id, "image": image, "question": question, "raw": payload}
|
||||
|
||||
|
||||
def _login_error(response: httpx.Response) -> Exception:
|
||||
"""把 Hub 登录接口的失败分成两类:被拒(用户填错了)与不可用(对端出问题)。
|
||||
|
||||
分成两类是因为后面要走的路完全不同:被拒就得如实告诉用户并换验证码,不可用才谈得上
|
||||
``login_mode = "hybrid"`` 那条回落。混成一类要么把"密码不对"说成"服务不可用",
|
||||
要么在 Hub 已经判定口令错误的情况下又拿本地旧哈希放人进去。
|
||||
"""
|
||||
payload = _try_json(response.text)
|
||||
body = payload if isinstance(payload, dict) else {}
|
||||
code = _error_code(body)
|
||||
slug = str(body.get("error") or "").strip().lower()
|
||||
message = str(body.get("message") or "").strip()
|
||||
status = int(response.status_code)
|
||||
|
||||
if status >= 500 or code in UNAVAILABLE_CODES:
|
||||
return HubError(message or "统一身份暂时不可用,请稍后再试")
|
||||
if status == 404:
|
||||
# 路径配错 / 对端没开这个接口:这是部署问题,跟用户填什么无关。
|
||||
return HubError("统一身份没有提供账号口令登录接口(或路径不对),请联系管理员")
|
||||
needs_captcha = ("验证码" in message) or slug in CAPTCHA_ERROR_SLUGS or code in CAPTCHA_ERROR_CODES
|
||||
if status in (400, 401, 403, 422) or code in REJECT_CODES or slug:
|
||||
# 裸 error 口径(hubtest 就是这样):{"error":"invalid_credentials","message":"账号或密码错误"}
|
||||
return HubRejected(message or f"统一身份拒绝了这次登录(HTTP {status})",
|
||||
code=code or slug, needs_captcha=needs_captcha)
|
||||
return HubError(message or f"统一身份返回了无法解析的内容(HTTP {status})")
|
||||
|
||||
|
||||
def fetch_captcha() -> dict[str, Any]:
|
||||
"""取一张登录验证码。
|
||||
|
||||
验证码不是一次性的口令,但也别在后台缓存:Hub 那边按 ``id`` 存答案,答错或超时都作废,
|
||||
登录页每次刷新都重新拿一张最省事。Hub 回的是裸 JSON(没有 ``code`` 信封),
|
||||
:func:`_unwrap` 对这种形状原样放行。
|
||||
"""
|
||||
payload = _get_json(f"{_base_url()}{settings.hub.captcha_path}",
|
||||
{"Accept": "application/json"}, {}, what="登录验证码")
|
||||
return _captcha_view(payload if isinstance(payload, dict) else {})
|
||||
|
||||
|
||||
def login_with_password(account: str, password: str, *, captcha_id: str = "",
|
||||
captcha_answer: str = "") -> dict[str, Any]:
|
||||
"""拿登录页提交的账号口令问一次统一身份,认了才返回身份。
|
||||
|
||||
口令明文只在"浏览器 -> 本系统后端 -> Hub"这一趟里出现,本系统既不落库也不写日志;
|
||||
认下来之后换的是本系统自己的令牌,Hub 那个 access_token 不在本地会话里留存。
|
||||
|
||||
没填验证码时刻意不把它塞进请求体:部分部署关掉了验证码,带一个空串过去会被当成
|
||||
"验证码错误",白拒一次。口令错就是 :class:`HubRejected`,对端挂了才是
|
||||
:class:`HubError`,两条路的处置见 :func:`_login_error`。
|
||||
"""
|
||||
name = (account or "").strip()
|
||||
if not name or not password:
|
||||
raise HubRejected("账号与口令都要填")
|
||||
body: dict[str, Any] = {"account": name, "password": password}
|
||||
if captcha_id:
|
||||
body["captcha_id"] = captcha_id
|
||||
if captcha_answer:
|
||||
body["captcha_answer"] = captcha_answer
|
||||
|
||||
try:
|
||||
response = httpx.post(f"{_base_url()}{settings.hub.login_path}",
|
||||
headers={"Content-Type": "application/json",
|
||||
"Accept": "application/json"},
|
||||
json=body, timeout=float(settings.hub.login_timeout))
|
||||
except httpx.HTTPError as exc:
|
||||
raise HubError(f"连接统一身份失败:{exc}") from exc
|
||||
|
||||
if response.status_code >= 400:
|
||||
raise _login_error(response)
|
||||
|
||||
try:
|
||||
payload = response.json()
|
||||
except ValueError as exc:
|
||||
raise HubError("统一身份登录接口返回的不是 JSON") from exc
|
||||
|
||||
data = _unwrap(payload, what="统一身份登录")
|
||||
# 令牌可能直接放在 data 上,也可能套一层 tokens,两种部署都见过。
|
||||
tokens = data.get("tokens") if isinstance(data.get("tokens"), dict) else data
|
||||
user = data.get("user") if isinstance(data.get("user"), dict) else {}
|
||||
access_token = str(tokens.get("access_token") or data.get("access_token") or "")
|
||||
if not access_token:
|
||||
# 没拿到令牌就说明这次登录其实没成,宁可报"服务不可用"也不放行。
|
||||
raise HubError("统一身份没有返回登录令牌,无法确认这次登录")
|
||||
|
||||
sub = ""
|
||||
for candidate in (user.get("user_id"), user.get("id"), data.get("user_id"), data.get("sub")):
|
||||
if candidate not in (None, ""):
|
||||
sub = str(candidate).strip()
|
||||
break
|
||||
return {
|
||||
"sub": sub,
|
||||
"account": str(user.get("account") or data.get("account") or name).strip(),
|
||||
"display_name": str(user.get("display_name") or user.get("name")
|
||||
or data.get("display_name") or data.get("name") or "").strip(),
|
||||
"email": str(user.get("email") or data.get("email") or "").strip(),
|
||||
"status": user.get("status", data.get("status")),
|
||||
"access_token": access_token,
|
||||
"raw": data,
|
||||
}
|
||||
|
|
@ -0,0 +1,607 @@
|
|||
"""把统一身份的组织与人同步进本地。
|
||||
|
||||
三条硬规则,跟 unisoa 一致:
|
||||
|
||||
1. **只认主键,不认名字**。组织靠 ``hub_org_id``、人靠 ``hub_user_id`` 对上号;账号名
|
||||
和姓名都会在 Hub 侧改,靠名字对号迟早对到别人身上。
|
||||
2. **本地账号永远不动**。``source=local`` 的账号(含内置超管)同步不碰,避免夜间同步
|
||||
把管理员改没。
|
||||
3. **Hub 侧消失的一律停用而不是删除**。审批记录、项目创建人要一直指得到人,物理删除
|
||||
会让历史数据失去解释。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..config import settings
|
||||
from ..models import Account, AccountIdentity, AccountSource, HubSyncRun, OrgUnit, Status
|
||||
from . import hub_api
|
||||
|
||||
|
||||
@dataclass
|
||||
class SyncStats:
|
||||
org_total: int = 0
|
||||
# "必须退回全量"的信号走这个独立字段,不混进 errors:errors 会被拼进
|
||||
# hub_sync_run.error 直接显示到界面上,内部前缀漏出去很难看也很难懂。
|
||||
escalate: str = ""
|
||||
org_created: int = 0
|
||||
org_updated: int = 0
|
||||
org_disabled: int = 0
|
||||
account_total: int = 0
|
||||
account_created: int = 0
|
||||
account_updated: int = 0
|
||||
account_disabled: int = 0
|
||||
skipped_local: int = 0
|
||||
steps: list[dict[str, Any]] = field(default_factory=list)
|
||||
errors: list[str] = field(default_factory=list)
|
||||
|
||||
def step(self, name: str, **detail: Any) -> None:
|
||||
self.steps.append({"name": name, "at": datetime.now().isoformat(timespec="seconds"), **detail})
|
||||
|
||||
|
||||
def sync_all(db: Session, *, trigger: str = "manual") -> HubSyncRun:
|
||||
"""跑一次完整同步,结果写 ``hub_sync_run``。"""
|
||||
run = HubSyncRun(trigger=trigger, status="running", started_at=datetime.now())
|
||||
db.add(run)
|
||||
db.flush()
|
||||
|
||||
stats = SyncStats()
|
||||
cursor = 0
|
||||
try:
|
||||
directory = hub_api.fetch_directory()
|
||||
organizations = directory["organizations"]
|
||||
users = directory["users"]
|
||||
stats.step("fetch", organizations=len(organizations), users=len(users),
|
||||
totalUsers=directory["total_users"])
|
||||
org_map = _sync_units(db, organizations, stats)
|
||||
stats.step("units", created=stats.org_created, updated=stats.org_updated)
|
||||
_sync_people(db, users, org_map, stats)
|
||||
stats.step("people", created=stats.account_created, updated=stats.account_updated)
|
||||
if settings.hub.missing_org_action == "disable":
|
||||
_disable_missing_units(db, organizations, stats)
|
||||
if settings.hub.missing_account_action == "disable":
|
||||
_disable_missing_accounts(db, users, stats)
|
||||
_refresh_paths(db)
|
||||
# 文档 §6.3:全量落地后记一次游标边界,之后的增量从这里接着走。
|
||||
# 这一步失败不影响全量结果本身,单独记一笔,别把整次同步判成失败。
|
||||
cursor = _cursor_boundary(stats)
|
||||
status = "partial" if stats.errors else "success"
|
||||
except hub_api.HubError as exc:
|
||||
stats.errors.append(str(exc))
|
||||
status = "failed"
|
||||
|
||||
run.status = status
|
||||
run.finished_at = datetime.now()
|
||||
run.org_total, run.org_created, run.org_updated, run.org_disabled = (
|
||||
stats.org_total, stats.org_created, stats.org_updated, stats.org_disabled)
|
||||
run.account_total, run.account_created, run.account_updated, run.account_disabled = (
|
||||
stats.account_total, stats.account_created, stats.account_updated, stats.account_disabled)
|
||||
run.skipped_local = stats.skipped_local
|
||||
run.cursor_after = cursor
|
||||
run.steps_json = json.dumps(stats.steps, ensure_ascii=False)
|
||||
run.error = ";".join(stats.errors)
|
||||
db.flush()
|
||||
return run
|
||||
|
||||
|
||||
def _cursor_boundary(stats: SyncStats) -> int:
|
||||
"""拉一次增量只为拿 newest_seq,作为下一次增量的起点。"""
|
||||
try:
|
||||
return int(hub_api.fetch_changes(0, limit=1)["newest_seq"])
|
||||
except hub_api.HubError as exc:
|
||||
stats.errors.append(f"全量已落地但没拿到游标边界,下次仍会走全量:{exc}")
|
||||
return 0
|
||||
|
||||
|
||||
def local_cursor(db: Session) -> int:
|
||||
"""本地已同步到的目录游标。没有增量批次就返回 0(表示只能走全量)。"""
|
||||
return int(
|
||||
db.execute(
|
||||
select(HubSyncRun.cursor_after)
|
||||
.where(HubSyncRun.status.in_(("success", "partial")),
|
||||
HubSyncRun.cursor_after > 0)
|
||||
.order_by(HubSyncRun.id.desc())
|
||||
.limit(1)
|
||||
).scalars().first()
|
||||
or 0
|
||||
)
|
||||
|
||||
|
||||
def sync_changes(db: Session, *, trigger: str = "scheduled", max_batches: int = 20) -> HubSyncRun:
|
||||
"""按游标拉一次增量并幂等应用,结果写 ``hub_sync_run``。
|
||||
|
||||
游标只在"整批都成功"之后才推进:文档要求同一批循环拉到 ``has_more=false`` 才允许提交,
|
||||
中途失败必须从老游标重来,否则会永久漏掉中间那些事件。
|
||||
|
||||
两种情况直接升级成全量重跑,不硬扛:
|
||||
|
||||
* ``since`` 落到 ``oldest_seq`` 之前 —— 中间流水已被裁剪,增量补不回来;
|
||||
* 收到"只带 id 和 status / parent_id"的组织事件 —— 文档 §6.4 明说这类 payload 不带
|
||||
``path``、组织停用也不会给子孙逐个发事件,禁止靠它推导父子关系。硬套批量同步函数
|
||||
会因为 payload 里没有 ``name`` 而把好好的部门名刷成"组织 12"。
|
||||
"""
|
||||
cursor = local_cursor(db)
|
||||
run = HubSyncRun(trigger=trigger, status="running", started_at=datetime.now())
|
||||
db.add(run)
|
||||
db.flush()
|
||||
|
||||
stats = SyncStats()
|
||||
stats.step("cursor", since=cursor)
|
||||
escalate_reason = ""
|
||||
if cursor <= 0:
|
||||
escalate_reason = "本地还没有游标(从未成功同步过),只能走全量"
|
||||
else:
|
||||
since = cursor
|
||||
batches = 0
|
||||
batches_ok = 0
|
||||
applied = 0
|
||||
try:
|
||||
while batches < max_batches:
|
||||
batches += 1
|
||||
batch = hub_api.fetch_changes(since)
|
||||
batches_ok += 1
|
||||
if batch["behind"]:
|
||||
escalate_reason = (
|
||||
f"本地游标 {since} 已落后于 Hub 侧最早流水 {batch['oldest_seq']},"
|
||||
"中间事件被裁剪,退回全量重建"
|
||||
)
|
||||
break
|
||||
org_structure_changed = False
|
||||
for change in batch["changes"]:
|
||||
if _apply_change(db, change, stats=stats) == "escalate":
|
||||
break # 单条错误只记账,不中断整批;升级信号由 stats 里的标记带出去
|
||||
applied += 1
|
||||
if str(change.get("entity") or "").lower() == "organization":
|
||||
org_structure_changed = True
|
||||
if org_structure_changed:
|
||||
# path / level 是按 parent_id 全量重算的,一批一次就够,别一条一算。
|
||||
_refresh_paths(db)
|
||||
org_structure_changed = False
|
||||
since = batch["cursor"]
|
||||
stats.step("batch", seq=since, changes=len(batch["changes"]),
|
||||
hasMore=batch["has_more"])
|
||||
if outcome_stopped(stats) or not batch["has_more"]:
|
||||
break
|
||||
except hub_api.HubError as exc:
|
||||
stats.errors.append(str(exc))
|
||||
|
||||
if not escalate_reason and stats.escalate:
|
||||
escalate_reason = stats.escalate
|
||||
|
||||
if escalate_reason:
|
||||
stats.step("escalate", reason=escalate_reason)
|
||||
run.status = "skipped"
|
||||
run.error = escalate_reason
|
||||
run.cursor_after = 0
|
||||
run.finished_at = datetime.now()
|
||||
run.steps_json = json.dumps(stats.steps, ensure_ascii=False)
|
||||
db.flush()
|
||||
full = sync_all(db, trigger=f"{trigger}+full")
|
||||
# 升级前后的过程记录要接在一起,才能在"同步历史"里看清是先退回再全量的。
|
||||
# 这里不能直接 json.loads(run.steps_json):列默认值是 Python 侧给的,
|
||||
# 一个刚 new 出来还没 flush 的 HubSyncRun 上它就是 None,直接抛 TypeError。
|
||||
full.steps_json = json.dumps(_steps_of(run) + _steps_of(full), ensure_ascii=False)
|
||||
db.flush()
|
||||
return full
|
||||
|
||||
# 一批都没拉成功 = 这次同步压根没发生,报 partial 会把"对端挂了"粉饰成"同步好了大部分"。
|
||||
# 只有先落了几批、后面才断的,才算 partial。
|
||||
if batches_ok == 0:
|
||||
run.status = "failed"
|
||||
else:
|
||||
run.status = "partial" if stats.errors else "success"
|
||||
run.finished_at = datetime.now()
|
||||
run.cursor_after = since
|
||||
run.account_total = applied
|
||||
run.account_updated = stats.account_updated
|
||||
run.account_created = stats.account_created
|
||||
run.account_disabled = stats.account_disabled
|
||||
run.org_updated = stats.org_updated
|
||||
run.org_created = stats.org_created
|
||||
run.org_disabled = stats.org_disabled
|
||||
run.steps_json = json.dumps(stats.steps, ensure_ascii=False)
|
||||
run.error = ";".join(stats.errors)
|
||||
db.flush()
|
||||
return run
|
||||
|
||||
|
||||
def outcome_stopped(stats: SyncStats) -> bool:
|
||||
"""批内出现"必须退回全量"的信号时,停止继续消费增量。"""
|
||||
return bool(stats.escalate)
|
||||
|
||||
|
||||
def _apply_change(db: Session, change: dict[str, Any], *, stats: SyncStats) -> str:
|
||||
"""应用一条目录变更。返回 ``ok`` / ``escalate``。
|
||||
|
||||
``data`` 的键名随来源变化(``source=hub`` 用 ``id``,``source=wecom`` 用
|
||||
``organization_id`` / ``user_id``),先按 entity 分支再取值。
|
||||
"""
|
||||
entity = str(change.get("entity") or "").strip().lower()
|
||||
op = str(change.get("op") or "").strip().lower()
|
||||
payload = change.get("data") if isinstance(change.get("data"), dict) else {}
|
||||
seq = change.get("seq")
|
||||
|
||||
if entity == "organization":
|
||||
hub_id = _node_id(payload) or (int(change["entity_id"])
|
||||
if str(change.get("entity_id") or "").isdigit() else None)
|
||||
if hub_id is None:
|
||||
stats.errors.append(f"变更 seq={seq} 是组织但取不到主键,忽略")
|
||||
return "ok"
|
||||
if op == "delete":
|
||||
unit = _hub_unit(db, hub_id)
|
||||
if unit is not None:
|
||||
unit.is_deleted = True
|
||||
unit.status = Status.DISABLED
|
||||
stats.org_disabled += 1
|
||||
return "ok"
|
||||
if not str(payload.get("name") or "").strip():
|
||||
# 只带 id + status / parent_id 的部分 payload:按文档必须重拉全量。
|
||||
stats.escalate = (f"seq={seq} 的组织事件只给了 id 与状态,按契约不能靠它推导层级")
|
||||
return "escalate"
|
||||
_sync_units(db, [payload], stats)
|
||||
_refresh_paths(db)
|
||||
return "ok"
|
||||
|
||||
if entity == "user":
|
||||
hub_id = _person_id(payload) or (int(change["entity_id"])
|
||||
if str(change.get("entity_id") or "").isdigit() else None)
|
||||
if hub_id is None:
|
||||
stats.errors.append(f"变更 seq={seq} 是人员但取不到主键,忽略")
|
||||
return "ok"
|
||||
account = _hub_account(db, hub_id)
|
||||
if op == "delete":
|
||||
if account is not None:
|
||||
# 软删除:审批记录和项目创建人要一直指得到人。
|
||||
account.status = Status.DISABLED
|
||||
account.is_deleted = True
|
||||
stats.account_disabled += 1
|
||||
return "ok"
|
||||
has_identity = str(payload.get("account") or "").strip() and \
|
||||
str(payload.get("display_name") or "").strip()
|
||||
if account is None and not has_identity:
|
||||
stats.escalate = (f"seq={seq} 的新人员事件字段不全,本地没有对应账号,需全量补建")
|
||||
return "escalate"
|
||||
if account is None:
|
||||
_sync_people(db, [payload], _hub_org_map(db), stats)
|
||||
return "ok"
|
||||
# 已有账号:payload 里给了什么就更新什么,没给的一律不动。
|
||||
if "organization_id" in payload or "org_id" in payload:
|
||||
unit = _hub_org_map(db).get(_person_org_id(payload) or -1)
|
||||
if unit is not None and account.org_unit_id != unit.id:
|
||||
account.org_unit_id = unit.id
|
||||
stats.account_updated += 1
|
||||
if "status" in payload:
|
||||
status = Status.normalize(payload.get("status", 1))
|
||||
if account.status != status:
|
||||
account.status = status
|
||||
stats.account_updated += 1
|
||||
if str(payload.get("display_name") or "").strip():
|
||||
display = str(payload["display_name"]).strip()
|
||||
if account.display_name != display:
|
||||
account.display_name = display
|
||||
stats.account_updated += 1
|
||||
if str(payload.get("email") or "").strip():
|
||||
account.email = str(payload["email"]).strip()
|
||||
account.hub_synced_at = datetime.now()
|
||||
return "ok"
|
||||
|
||||
stats.errors.append(f"变更 seq={seq} 的 entity={entity!r} 不认识,忽略")
|
||||
return "ok"
|
||||
|
||||
|
||||
def _hub_unit(db: Session, hub_org_id: int) -> OrgUnit | None:
|
||||
return db.execute(select(OrgUnit).where(OrgUnit.hub_org_id == hub_org_id)).scalars().first()
|
||||
|
||||
|
||||
def _hub_account(db: Session, hub_user_id: int) -> Account | None:
|
||||
return db.execute(
|
||||
select(Account).where(Account.hub_user_id == hub_user_id)
|
||||
).scalars().first()
|
||||
|
||||
|
||||
def _hub_org_map(db: Session) -> dict[int, OrgUnit]:
|
||||
return {
|
||||
unit.hub_org_id: unit
|
||||
for unit in db.execute(select(OrgUnit).where(OrgUnit.hub_org_id.isnot(None))).scalars().all()
|
||||
}
|
||||
|
||||
|
||||
|
||||
def _node_id(node: dict[str, Any]) -> int | None:
|
||||
for key in ("organization_id", "org_id", "id", "deptId", "dept_id"):
|
||||
value = node.get(key)
|
||||
if value is not None and str(value).strip().isdigit():
|
||||
return int(value)
|
||||
return None
|
||||
|
||||
|
||||
def _node_parent_id(node: dict[str, Any]) -> int | None:
|
||||
for key in ("parent_id", "parentId", "parent"):
|
||||
value = node.get(key)
|
||||
if value is not None and str(value).strip().isdigit() and int(value) > 0:
|
||||
return int(value)
|
||||
return None
|
||||
|
||||
|
||||
def _tree_nodes(organizations: list[dict[str, Any]], stats: SyncStats) -> list[dict[str, Any]]:
|
||||
"""把 Hub 返回的组织摊平成"父先子后"的有序列表。
|
||||
|
||||
Hub 可能返回一棵嵌套树,也可能是扁平数组,两种都要能吃;同时挡一下环形父子,
|
||||
否则后面的 path 计算会无限递归。
|
||||
"""
|
||||
flat: list[dict[str, Any]] = []
|
||||
|
||||
def walk(node: Any) -> None:
|
||||
if not isinstance(node, dict):
|
||||
return
|
||||
children = node.get("children") or node.get("child") or []
|
||||
shallow = {key: value for key, value in node.items() if key not in ("children", "child")}
|
||||
flat.append(shallow)
|
||||
if isinstance(children, list):
|
||||
for child in children:
|
||||
walk(child)
|
||||
|
||||
for item in organizations or []:
|
||||
walk(item)
|
||||
|
||||
stats.org_total = len(flat)
|
||||
ordered: list[dict[str, Any]] = []
|
||||
placed: set[int] = set()
|
||||
pending = list(flat)
|
||||
guard = 0
|
||||
while pending and guard < 50:
|
||||
guard += 1
|
||||
remaining: list[dict[str, Any]] = []
|
||||
for node in pending:
|
||||
key = _node_id(node)
|
||||
parent = _node_parent_id(node)
|
||||
if key is None:
|
||||
continue
|
||||
if parent is None or parent in placed:
|
||||
ordered.append(node)
|
||||
placed.add(key)
|
||||
else:
|
||||
remaining.append(node)
|
||||
if len(remaining) == len(pending): # 环形或父缺失,剩下的直接按原序补上
|
||||
ordered.extend(remaining)
|
||||
break
|
||||
pending = remaining
|
||||
return ordered
|
||||
|
||||
|
||||
def _sync_units(db: Session, organizations: list[dict[str, Any]], stats: SyncStats) -> dict[int, OrgUnit]:
|
||||
existing = {
|
||||
unit.hub_org_id: unit
|
||||
for unit in db.execute(select(OrgUnit).where(OrgUnit.hub_org_id.isnot(None))).scalars().all()
|
||||
}
|
||||
mapping: dict[int, OrgUnit] = {}
|
||||
for node in _tree_nodes(organizations, stats):
|
||||
hub_id = _node_id(node)
|
||||
if hub_id is None:
|
||||
continue
|
||||
name = str(node.get("name") or node.get("departName") or "").strip() or f"组织 {hub_id}"
|
||||
code = str(node.get("code") or node.get("orgCode") or "").strip()
|
||||
status = Status.normalize(node.get("status", 1))
|
||||
parent_unit = mapping.get(_node_parent_id(node) or -1)
|
||||
|
||||
unit = existing.get(hub_id)
|
||||
if unit is None:
|
||||
unit = OrgUnit(name=name, code=code, hub_org_id=hub_id, status=status,
|
||||
parent_id=parent_unit.id if parent_unit else None)
|
||||
db.add(unit)
|
||||
db.flush()
|
||||
stats.org_created += 1
|
||||
else:
|
||||
if unit.name != name:
|
||||
unit.name = name
|
||||
if code and unit.code != code:
|
||||
unit.code = code
|
||||
unit.status = status
|
||||
parent_id = parent_unit.id if parent_unit else None
|
||||
if unit.parent_id != parent_id:
|
||||
unit.parent_id = parent_id
|
||||
stats.org_updated += 1
|
||||
unit.short_name = str(node.get("short_name") or node.get("shortName") or unit.short_name or "")
|
||||
unit.order_number = int(node.get("order_number") or node.get("sort") or unit.order_number or 0)
|
||||
unit.hub_synced_at = datetime.now()
|
||||
unit.is_deleted = False
|
||||
mapping[hub_id] = unit
|
||||
db.flush()
|
||||
return mapping
|
||||
|
||||
|
||||
def _person_id(node: dict[str, Any]) -> int | None:
|
||||
for key in ("user_id", "userId", "id", "personId"):
|
||||
value = node.get(key)
|
||||
if value is not None and str(value).strip().isdigit():
|
||||
return int(value)
|
||||
return None
|
||||
|
||||
|
||||
def _person_org_id(node: dict[str, Any]) -> int | None:
|
||||
for key in ("organization_id", "org_id", "organizationId", "deptId", "dept_id"):
|
||||
value = node.get(key)
|
||||
if value is not None and str(value).strip().isdigit():
|
||||
return int(value)
|
||||
return None
|
||||
|
||||
|
||||
def _sync_people(db: Session, users: list[dict[str, Any]], org_map: dict[int, OrgUnit],
|
||||
stats: SyncStats) -> None:
|
||||
existing = {
|
||||
account.hub_user_id: account
|
||||
for account in db.execute(
|
||||
select(Account).where(Account.hub_user_id.isnot(None))
|
||||
).scalars().all()
|
||||
}
|
||||
stats.account_total = len(users or [])
|
||||
|
||||
for node in users or []:
|
||||
hub_id = _person_id(node)
|
||||
if hub_id is None:
|
||||
continue
|
||||
account_name = str(node.get("account") or node.get("username") or node.get("userName") or "").strip()
|
||||
display = str(node.get("display_name") or node.get("name") or node.get("realName") or "").strip()
|
||||
unit = org_map.get(_person_org_id(node) or -1)
|
||||
status = Status.normalize(node.get("status", 1))
|
||||
|
||||
account = existing.get(hub_id)
|
||||
created = False
|
||||
if account is None:
|
||||
if not account_name:
|
||||
stats.errors.append(f"Hub 用户 {hub_id} 没有账号名,已跳过")
|
||||
continue
|
||||
taken = db.execute(select(Account).where(Account.account == account_name)).scalars().first()
|
||||
if taken is not None and taken.source != AccountSource.HUB:
|
||||
# 本地已经有人用了这个账号名:不抢,改名后新建,避免把本地人的号夺走
|
||||
account_name = f"{account_name}_hub{hub_id}"
|
||||
stats.skipped_local += 1
|
||||
if taken is not None and taken.source == AccountSource.HUB:
|
||||
account = taken # 之前建的 hub 账号还没回填 hub_user_id,认领它而不是再建一个
|
||||
else:
|
||||
account = Account(account=account_name, password_hash="",
|
||||
source=AccountSource.HUB, hub_user_id=hub_id)
|
||||
created = True
|
||||
stats.account_created += 1
|
||||
db.add(account)
|
||||
db.flush()
|
||||
else:
|
||||
if account.display_name != display and display:
|
||||
account.display_name = display
|
||||
if unit is not None and account.org_unit_id != unit.id:
|
||||
account.org_unit_id = unit.id
|
||||
account.status = status
|
||||
stats.account_updated += 1
|
||||
|
||||
account.hub_user_id = hub_id
|
||||
account.source = AccountSource.HUB
|
||||
account.hub_synced_at = datetime.now()
|
||||
account.display_name = display or account.display_name
|
||||
account.emp_code = str(node.get("emp_code") or node.get("empCode") or account.emp_code or "")
|
||||
account.telephone = str(node.get("telephone") or node.get("mobile") or account.telephone or "")
|
||||
account.email = str(node.get("email") or node.get("company_email") or account.email or "")
|
||||
if unit is not None:
|
||||
account.org_unit_id = unit.id
|
||||
account.is_deleted = False
|
||||
db.flush()
|
||||
|
||||
_ensure_identity(db, account, unit, stats)
|
||||
|
||||
db.flush()
|
||||
|
||||
|
||||
def _ensure_identity(db: Session, account: Account, unit: OrgUnit | None, stats: SyncStats) -> None:
|
||||
if unit is None:
|
||||
return
|
||||
existing = db.execute(
|
||||
select(AccountIdentity).where(
|
||||
AccountIdentity.account_id == account.id, AccountIdentity.org_unit_id == unit.id
|
||||
)
|
||||
).scalars().first()
|
||||
if existing is None:
|
||||
others = db.execute(
|
||||
select(AccountIdentity.id).where(AccountIdentity.account_id == account.id)
|
||||
).scalars().all()
|
||||
db.add(AccountIdentity(account_id=account.id, org_unit_id=unit.id, is_default=not list(others)))
|
||||
db.flush()
|
||||
|
||||
|
||||
def _disable_missing_units(db: Session, organizations: list[dict[str, Any]], stats: SyncStats) -> None:
|
||||
seen = {_node_id(node) for node in _tree_nodes(organizations, SyncStats())}
|
||||
seen.discard(None)
|
||||
rows = db.execute(select(OrgUnit).where(OrgUnit.hub_org_id.isnot(None),
|
||||
OrgUnit.is_deleted.is_(False))).scalars().all()
|
||||
for unit in rows:
|
||||
if unit.hub_org_id not in seen and unit.is_active:
|
||||
unit.status = Status.DISABLED
|
||||
stats.org_disabled += 1
|
||||
|
||||
|
||||
def _disable_missing_accounts(db: Session, users: list[dict[str, Any]], stats: SyncStats) -> None:
|
||||
seen = {_person_id(node) for node in (users or [])}
|
||||
seen.discard(None)
|
||||
rows = db.execute(
|
||||
select(Account).where(Account.source == AccountSource.HUB, Account.is_deleted.is_(False))
|
||||
).scalars().all()
|
||||
for account in rows:
|
||||
if account.hub_user_id not in seen and account.status == Status.ACTIVE:
|
||||
account.status = Status.DISABLED
|
||||
stats.account_disabled += 1
|
||||
|
||||
|
||||
def _refresh_paths(db: Session) -> None:
|
||||
"""重算 ``org_unit.path`` 与层级。同步改过 parent_id 之后必须跑一次。"""
|
||||
units = {unit.id: unit for unit in db.execute(select(OrgUnit)).scalars().all()}
|
||||
for unit in units.values():
|
||||
chain: list[int] = []
|
||||
cursor: OrgUnit | None = unit
|
||||
guard = 0
|
||||
while cursor is not None and guard < 32:
|
||||
if cursor.id in chain: # 环形父子,截断
|
||||
break
|
||||
chain.append(cursor.id)
|
||||
cursor = units.get(cursor.parent_id) if cursor.parent_id else None
|
||||
guard += 1
|
||||
unit.path = "/" + "/".join(str(item) for item in reversed(chain)) + "/"
|
||||
unit.level = len(chain)
|
||||
parent = units.get(unit.parent_id) if unit.parent_id else None
|
||||
if parent and parent.path:
|
||||
unit.path = parent.path + f"{unit.id}/"
|
||||
unit.level = parent.level + 1
|
||||
db.flush()
|
||||
|
||||
|
||||
def _steps_of(run: HubSyncRun) -> list[Any]:
|
||||
"""读 run.steps_json,容忍 None 与脏数据。"""
|
||||
raw = getattr(run, "steps_json", None)
|
||||
if not raw:
|
||||
return []
|
||||
try:
|
||||
loaded = json.loads(raw)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return []
|
||||
return loaded if isinstance(loaded, list) else []
|
||||
|
||||
|
||||
def serialize(run: HubSyncRun) -> dict[str, Any]:
|
||||
data = {
|
||||
"id": run.id,
|
||||
"trigger": run.trigger,
|
||||
"status": run.status,
|
||||
"startedAt": run.started_at.isoformat(sep=" ", timespec="seconds") if run.started_at else "",
|
||||
"finishedAt": run.finished_at.isoformat(sep=" ", timespec="seconds") if run.finished_at else "",
|
||||
"orgTotal": run.org_total, "orgCreated": run.org_created,
|
||||
"orgUpdated": run.org_updated, "orgDisabled": run.org_disabled,
|
||||
"accountTotal": run.account_total, "accountCreated": run.account_created,
|
||||
"accountUpdated": run.account_updated, "accountDisabled": run.account_disabled,
|
||||
"skippedLocal": run.skipped_local,
|
||||
"cursorAfter": run.cursor_after,
|
||||
"error": run.error,
|
||||
}
|
||||
data["steps"] = _steps_of(run)
|
||||
return data
|
||||
|
||||
|
||||
def status_payload(db: Session) -> dict[str, Any]:
|
||||
latest = db.execute(select(HubSyncRun).order_by(HubSyncRun.id.desc()).limit(1)).scalars().first()
|
||||
return {
|
||||
"enabled": settings.hub.enabled,
|
||||
"configured": settings.hub.configured,
|
||||
"ssoConfigured": settings.hub.sso_configured,
|
||||
"baseUrl": settings.hub.base_url,
|
||||
"syncIntervalMinutes": settings.hub.sync_interval_minutes,
|
||||
"changesIntervalSeconds": settings.hub.changes_interval_seconds,
|
||||
# 本地游标。0 表示"从没成功全量过",下一次定时任务会先补全量而不是空跑增量。
|
||||
"cursor": local_cursor(db),
|
||||
"autoSyncActive": bool(settings.hub.configured
|
||||
and (settings.hub.changes_interval_seconds > 0
|
||||
or settings.hub.sync_interval_minutes > 0)),
|
||||
"latest": serialize(latest) if latest else None,
|
||||
}
|
||||
|
|
@ -0,0 +1,265 @@
|
|||
"""角色解析、菜单树与权限判定。
|
||||
|
||||
一份权限码同时管三层:菜单可见性、按钮可用性、接口放行。老系统 ``sys_permission``
|
||||
的 ``url`` 与 ``permission`` 是两个独立字段,菜单按 url 过滤、接口按 permission 过滤,
|
||||
两边靠人工保持一致,实际线上出现过"菜单藏了但直接敲 URL 还能进"的情况。这里只认
|
||||
``code``,接口声明需要什么码就查什么码。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Iterable
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import Account, PermAccountRole, PermDataPolicy, PermNode, PermRole, PermRoleNode
|
||||
|
||||
ALL = "*"
|
||||
|
||||
|
||||
@dataclass
|
||||
class RoleView:
|
||||
id: int
|
||||
code: str
|
||||
name: str
|
||||
builtin: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class PermissionContext:
|
||||
"""一个人登录后的全部授权视图,随令牌缓存。"""
|
||||
|
||||
account_id: int
|
||||
roles: list[RoleView] = field(default_factory=list)
|
||||
codes: frozenset[str] = frozenset()
|
||||
is_system_admin: bool = False
|
||||
field_masks: dict[str, dict[str, str]] = field(default_factory=dict)
|
||||
|
||||
def can(self, code: str) -> bool:
|
||||
return self.is_system_admin or ALL in self.codes or code in self.codes
|
||||
|
||||
def can_any(self, codes: Iterable[str]) -> bool:
|
||||
wanted = set(codes)
|
||||
return self.is_system_admin or ALL in self.codes or bool(wanted & self.codes)
|
||||
|
||||
def can_all(self, codes: Iterable[str]) -> bool:
|
||||
if self.is_system_admin or ALL in self.codes:
|
||||
return True
|
||||
return wanted_subset(self.codes, codes)
|
||||
|
||||
|
||||
def wanted_subset(codes: frozenset[str], wanted: Iterable[str]) -> bool:
|
||||
return set(wanted).issubset(codes)
|
||||
|
||||
|
||||
def account_roles(db: Session, account_id: int) -> list[RoleView]:
|
||||
rows = db.execute(
|
||||
select(PermRole)
|
||||
.join(PermAccountRole, PermAccountRole.role_id == PermRole.id)
|
||||
.where(
|
||||
PermAccountRole.account_id == account_id,
|
||||
PermRole.enabled.is_(True),
|
||||
PermRole.is_deleted.is_(False),
|
||||
)
|
||||
.order_by(PermRole.order_number, PermRole.id)
|
||||
).scalars().all()
|
||||
return [RoleView(role.id, role.code, role.name, role.builtin) for role in rows]
|
||||
|
||||
|
||||
def permission_codes(db: Session, role_ids: list[int]) -> frozenset[str]:
|
||||
if not role_ids:
|
||||
return frozenset()
|
||||
rows = db.execute(
|
||||
select(PermNode.code)
|
||||
.join(PermRoleNode, PermRoleNode.node_id == PermNode.id)
|
||||
.where(
|
||||
PermRoleNode.role_id.in_(role_ids),
|
||||
PermNode.enabled.is_(True),
|
||||
PermNode.is_deleted.is_(False),
|
||||
)
|
||||
.distinct()
|
||||
).scalars().all()
|
||||
return frozenset(rows)
|
||||
|
||||
|
||||
def build_context(db: Session, account: Account) -> PermissionContext:
|
||||
roles = account_roles(db, account.id)
|
||||
codes = permission_codes(db, [role.id for role in roles])
|
||||
return PermissionContext(
|
||||
account_id=account.id,
|
||||
roles=roles,
|
||||
codes=codes,
|
||||
is_system_admin=bool(account.is_system_admin),
|
||||
field_masks=field_masks(db, [role.id for role in roles]),
|
||||
)
|
||||
|
||||
|
||||
def field_masks(db: Session, role_ids: list[int]) -> dict[str, dict[str, str]]:
|
||||
"""字段级权限:多角色取最宽松的一种(hidden < masked < readonly < 可见)。"""
|
||||
from ..models import FieldScope
|
||||
|
||||
if not role_ids:
|
||||
return {}
|
||||
rank = {"hidden": 0, "masked": 1, "readonly": 2}
|
||||
best: dict[tuple[str, str], int] = {}
|
||||
rows = db.execute(
|
||||
select(FieldScope).where(FieldScope.role_id.in_(role_ids))
|
||||
).scalars().all()
|
||||
for row in rows:
|
||||
key = (row.module, row.field)
|
||||
best[key] = max(best.get(key, 99), rank.get(row.mode, 0))
|
||||
out: dict[str, dict[str, str]] = {}
|
||||
inverse = {value: key for key, value in rank.items()}
|
||||
for (module, field_name), level in best.items():
|
||||
out.setdefault(module, {})[field_name] = inverse.get(level, "hidden")
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 菜单树
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def menu_tree(db: Session, context: PermissionContext) -> list[dict[str, Any]]:
|
||||
"""按权限过滤后的菜单树。父节点只要有任何一个可见子节点就保留。"""
|
||||
nodes = db.execute(
|
||||
select(PermNode)
|
||||
.where(
|
||||
PermNode.kind.in_(("menu", "group")),
|
||||
PermNode.enabled.is_(True),
|
||||
PermNode.visible.is_(True),
|
||||
PermNode.is_deleted.is_(False),
|
||||
)
|
||||
.order_by(PermNode.sort, PermNode.id)
|
||||
).scalars().all()
|
||||
|
||||
by_id: dict[int, dict[str, Any]] = {}
|
||||
for node in nodes:
|
||||
by_id[node.id] = {
|
||||
"id": node.id,
|
||||
"code": node.code,
|
||||
"name": node.name,
|
||||
"path": node.path,
|
||||
"icon": node.icon,
|
||||
"kind": node.kind,
|
||||
"module": node.module,
|
||||
"parentId": node.parent_id,
|
||||
"children": [],
|
||||
"allowed": context.can(node.code),
|
||||
}
|
||||
|
||||
roots: list[dict[str, Any]] = []
|
||||
for node in by_id.values():
|
||||
parent = by_id.get(node["parentId"])
|
||||
if parent is not None:
|
||||
parent["children"].append(node)
|
||||
else:
|
||||
roots.append(node)
|
||||
|
||||
return [prune(root) for root in roots if prune(root) is not None]
|
||||
|
||||
|
||||
def prune(node: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""自底向上剪枝:没权限的叶子去掉,子全被剪光的分组也去掉。"""
|
||||
kept_children = [child for child in (prune(item) for item in node["children"]) if child]
|
||||
if kept_children:
|
||||
node["children"] = kept_children
|
||||
return node
|
||||
if node["allowed"]:
|
||||
node["children"] = []
|
||||
return node
|
||||
return None
|
||||
|
||||
|
||||
def permission_catalog(db: Session) -> list[dict[str, Any]]:
|
||||
"""授权矩阵用的全量目录(含按钮级),不做权限过滤。
|
||||
|
||||
返回成树,前端矩阵就能直接渲染;勾选父节点要不要联动子节点,
|
||||
交给界面决定,后端不预设这个策略。
|
||||
"""
|
||||
rows = db.execute(
|
||||
select(PermNode).where(PermNode.is_deleted.is_(False)).order_by(PermNode.sort, PermNode.id)
|
||||
).scalars().all()
|
||||
nodes = {
|
||||
row.id: {
|
||||
"id": row.id,
|
||||
"code": row.code,
|
||||
"name": row.name,
|
||||
"kind": row.kind,
|
||||
"parentId": row.parent_id,
|
||||
"module": row.module,
|
||||
"path": row.path,
|
||||
"icon": row.icon,
|
||||
"sort": row.sort,
|
||||
"enabled": row.enabled,
|
||||
"children": [],
|
||||
}
|
||||
for row in rows
|
||||
}
|
||||
roots: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
node = nodes[row.id]
|
||||
parent = nodes.get(row.parent_id)
|
||||
(parent["children"] if parent else roots).append(node)
|
||||
return roots
|
||||
|
||||
|
||||
def role_permission_ids(db: Session, role_id: int) -> list[int]:
|
||||
return list(
|
||||
db.execute(
|
||||
select(PermRoleNode.node_id).where(PermRoleNode.role_id == role_id)
|
||||
).scalars().all()
|
||||
)
|
||||
|
||||
|
||||
def set_role_permissions(db: Session, role_id: int, node_ids: list[int]) -> int:
|
||||
from ..models import PermRoleNode as Link
|
||||
|
||||
existing = set(role_permission_ids(db, role_id))
|
||||
wanted = set(node_ids)
|
||||
for node_id in existing - wanted:
|
||||
row = db.execute(
|
||||
select(Link).where(Link.role_id == role_id, Link.node_id == node_id)
|
||||
).scalar_one_or_none()
|
||||
if row:
|
||||
db.delete(row)
|
||||
for node_id in wanted - existing:
|
||||
db.add(Link(role_id=role_id, node_id=node_id))
|
||||
db.flush()
|
||||
return len(wanted)
|
||||
|
||||
|
||||
def data_policies_for(db: Session, account_id: int, role_ids: list[int], org_unit_ids: list[int],
|
||||
position_ids: list[int]) -> list[PermDataPolicy]:
|
||||
"""捞出所有命中这个人的数据权限策略(含"挂在他所在部门/岗位上"的)。
|
||||
|
||||
这里只按主体粗筛,效果与模块过滤留给 :mod:`app.service.data_scope`,这样主体
|
||||
解析只写一遍。
|
||||
"""
|
||||
from ..models import Effect, SubjectType
|
||||
|
||||
conditions = [
|
||||
(PermDataPolicy.subject_type == SubjectType.ALL),
|
||||
]
|
||||
if role_ids:
|
||||
conditions.append((PermDataPolicy.subject_type == SubjectType.ROLE) & PermDataPolicy.subject_id.in_(role_ids))
|
||||
conditions.append((PermDataPolicy.subject_type == SubjectType.ACCOUNT) & (PermDataPolicy.subject_id == account_id))
|
||||
if org_unit_ids:
|
||||
conditions.append((PermDataPolicy.subject_type == SubjectType.ORG_UNIT) & PermDataPolicy.subject_id.in_(org_unit_ids))
|
||||
if position_ids:
|
||||
conditions.append((PermDataPolicy.subject_type == SubjectType.POSITION) & PermDataPolicy.subject_id.in_(position_ids))
|
||||
|
||||
from sqlalchemy import or_
|
||||
|
||||
rows = db.execute(
|
||||
select(PermDataPolicy)
|
||||
.where(
|
||||
PermDataPolicy.is_deleted.is_(False),
|
||||
PermDataPolicy.enabled.is_(True),
|
||||
or_(*conditions),
|
||||
)
|
||||
.order_by(PermDataPolicy.effect, PermDataPolicy.priority, PermDataPolicy.id)
|
||||
).scalars().all()
|
||||
return [row for row in rows if row.effect in (Effect.ALLOW, Effect.DENY)]
|
||||
|
|
@ -0,0 +1,232 @@
|
|||
"""后端免登回调与前端之间的那一手交接:一条只许用一次的短码。
|
||||
|
||||
对接指南把票据落点写成"携带 ticket 落到下游页面",于是老口径只能让浏览器先把票据交给
|
||||
JS、再由前端 POST 回来。本模块支持另一种落法:门户 302 直接落到后端
|
||||
(``GET /api/v1/auth/sso/callback``),票据只在这一次服务端调用里出现,浏览器从此看不到
|
||||
它。可后端也不能把本地令牌拼在 302 的地址上——那等于把会话钥匙写进浏览历史、代理日志
|
||||
和 Referer。于是中间垫一条一次性短码:
|
||||
|
||||
后端验完票 -> 发 code(60 秒、用一次、绑一条 HttpOnly Cookie)-> 302 /sso#code=…
|
||||
前端拿 code + Cookie -> POST /auth/sso/exchange -> 本地会话
|
||||
|
||||
三件事保证这条短码丢了也不出事:库里只存它的哈希;地址上带的是片段(``#``)而不是查询
|
||||
串,浏览器不会把它发给任何第三方;兑换必须同时带上回调当场下发的 HttpOnly Cookie,
|
||||
前端脚本读不到那条 Cookie,别人也就没法在自己浏览器里兑走别人的会话。
|
||||
口径与 unisoa 的 ``sso_handoff`` 一致。
|
||||
|
||||
``redirect``(免登进去要落到哪一页)只认站内路径,``//host`` 与 ``/\\host`` 一律丢掉。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hmac
|
||||
import logging
|
||||
import re
|
||||
import secrets
|
||||
from datetime import datetime, timedelta
|
||||
from urllib.parse import quote
|
||||
|
||||
from fastapi import Request
|
||||
from fastapi.responses import Response
|
||||
from sqlalchemy import delete, select, update
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .. import models, security
|
||||
|
||||
logger = logging.getLogger("pms.hub")
|
||||
|
||||
#: 后端回调的规范地址:Hub 上 ``launch_url`` / ``redirect_uris`` 就填这一条
|
||||
CALLBACK_PATH = "/api/v1/auth/sso/callback"
|
||||
#: 好抄的别名路径,与对接指南里 ``launch_url`` 的举例写法对齐
|
||||
ALIAS_PATH = "/sso/hub"
|
||||
#: 前端落地页;回调成功与失败都 302 到这里
|
||||
LANDING_PATH = "/sso"
|
||||
|
||||
#: 兑换串的 Cookie 名。HttpOnly + SameSite=Lax:前端读不到,同站请求照常带。
|
||||
COOKIE_NAME = "pms_sso_handoff"
|
||||
#: 一条短码的存活秒数。302 + 首屏加载用完,多留一点给慢吞吞的浏览器。
|
||||
CODE_TTL_SECONDS = 60
|
||||
#: 过期短码在库里再留多久供排障,之后随下一次发放顺手清掉
|
||||
GC_KEEP_SECONDS = 3600
|
||||
|
||||
#: 兑换失败统一回这一个 reason:短码不存在、用过、过期、Cookie 对不上一律糊成同一个,
|
||||
#: 免得这个接口变成"这条短码到底存不存在"的探针;真实原因只写日志。
|
||||
REASON_INVALID = "handoff_invalid"
|
||||
|
||||
#: 只当 Host / X-Forwarded-Host 的形状校验(主机名 + 可选端口)
|
||||
_HOST_RE = re.compile(r"[A-Za-z0-9.\-]+(?::\d{1,5})?")
|
||||
|
||||
|
||||
def safe_path(value: object) -> str:
|
||||
"""只放行站内路径,其余一律当没填(前端拿到空值自己挑兜底页)。"""
|
||||
raw = str(value or "").strip()
|
||||
if not raw or len(raw) > 255:
|
||||
return ""
|
||||
# ``//host`` 与 ``/\\host`` 浏览器会当成另一台主机,带 scheme 的更是直接出站
|
||||
if not raw.startswith("/") or raw.startswith(("//", "/\\")) or "://" in raw:
|
||||
return ""
|
||||
return raw
|
||||
|
||||
|
||||
def landing_url(*, code: str = "", error: str = "", redirect: str = "") -> str:
|
||||
"""拼 302 的目标地址:成功把短码放进片段,失败把原因码放进查询串。
|
||||
|
||||
只用相对地址:Hub 登记的回调地址是"浏览器实际访问的那台"(开发期是 Vite 代理口),
|
||||
拼绝对地址就得去猜站点根,猜错了 302 会把人送到别的端口上去。
|
||||
"""
|
||||
query = f"?error={quote(error, safe='')}" if error else ""
|
||||
target = f"{LANDING_PATH}{query}"
|
||||
if redirect:
|
||||
target += f"?redirect={quote(redirect, safe='')}" if not query else f"&redirect={quote(redirect, safe='')}"
|
||||
if code:
|
||||
# 放在 # 后面:不进服务端访问日志,也不跟着 Referer 出站
|
||||
target += f"#code={quote(code, safe='')}"
|
||||
return target
|
||||
|
||||
|
||||
def issue(db: Session, *, account: models.Account, detail: str = "",
|
||||
redirect: str = "") -> tuple[str, str]:
|
||||
"""发一条短码,返回 ``(短码明文, 兑换串明文)``。
|
||||
|
||||
短码拼进 302 的片段,兑换串写进 HttpOnly Cookie,两边各拿一半;库里只存两个哈希,
|
||||
所以这趟之后数据库里没有任何能还原会话凭据的东西。
|
||||
"""
|
||||
code = secrets.token_urlsafe(32)
|
||||
bind = secrets.token_urlsafe(24)
|
||||
now = datetime.now()
|
||||
db.add(models.SsoHandoff(
|
||||
code_hash=security.hash_token(code),
|
||||
bind_hash=security.hash_token(bind),
|
||||
account_id=account.id,
|
||||
redirect=safe_path(redirect),
|
||||
detail=(detail or "统一门户免登进入")[:255],
|
||||
expires_at=now + timedelta(seconds=CODE_TTL_SECONDS),
|
||||
))
|
||||
db.commit()
|
||||
_collect(db, now)
|
||||
return code, bind
|
||||
|
||||
|
||||
def attach_cookie(response: Response, bind: str, *, secure: bool = False) -> None:
|
||||
"""把兑换串写进回调响应。
|
||||
|
||||
回调接口直接返回 302,FastAPI 不会替它合并注入的 ``Response`` 参数,所以 Cookie只能
|
||||
写在这条响应上;``secure`` 跟着协议走,理由见 :func:`sso_state.is_https`。
|
||||
"""
|
||||
response.set_cookie(
|
||||
COOKIE_NAME, bind, max_age=CODE_TTL_SECONDS, path="/",
|
||||
httponly=True, samesite="lax", secure=secure,
|
||||
)
|
||||
|
||||
|
||||
def redeem(db: Session, request: Request, response: Response, code: str
|
||||
) -> tuple[models.Account, models.SsoHandoff]:
|
||||
"""兑换短码 -> ``(本地账号, 这行短码)``。
|
||||
|
||||
无论成功失败 Cookie 都用掉;失败对外只给一个笼统原因(免得这里变成"某条短码存在吗"
|
||||
的探针),真实原因只进日志。
|
||||
"""
|
||||
from ..deps import client_ip # 延迟导入:deps 会拉起 service 层,别在模块期绕成环
|
||||
|
||||
value = str(code or "").strip()
|
||||
bind = str(request.cookies.get(COOKIE_NAME) or "").strip()
|
||||
response.delete_cookie(COOKIE_NAME, path="/")
|
||||
problem = ""
|
||||
row: models.SsoHandoff | None = None
|
||||
if not value or not bind:
|
||||
# 没带短码或没带 Cookie:换了浏览器、Cookie 被拦、页面被人手工拼过
|
||||
problem = "absent"
|
||||
else:
|
||||
row = db.execute(
|
||||
select(models.SsoHandoff).where(models.SsoHandoff.code_hash == security.hash_token(value))
|
||||
).scalars().first()
|
||||
if row is None:
|
||||
problem = "unknown"
|
||||
elif row.used_at is not None:
|
||||
problem = "used"
|
||||
elif row.expires_at <= datetime.now():
|
||||
problem = "expired"
|
||||
elif not hmac.compare_digest(str(row.bind_hash or ""), security.hash_token(bind)):
|
||||
problem = "unbound"
|
||||
if problem:
|
||||
logger.warning("免登短码兑换被拒(%s),来源 %s", problem, client_ip(request))
|
||||
raise _invalid()
|
||||
assert row is not None
|
||||
# 到这儿才算真用掉:并发下只有一条请求能改到这一行,另一条只能被拒
|
||||
consumed = db.execute(
|
||||
update(models.SsoHandoff)
|
||||
.where(
|
||||
models.SsoHandoff.id == row.id,
|
||||
models.SsoHandoff.used_at.is_(None),
|
||||
models.SsoHandoff.expires_at > datetime.now(),
|
||||
)
|
||||
.values(used_at=datetime.now())
|
||||
)
|
||||
db.commit()
|
||||
if consumed.rowcount != 1:
|
||||
logger.warning("免登短码兑换被拒(consumed),来源 %s", client_ip(request))
|
||||
raise _invalid()
|
||||
account = db.get(models.Account, int(row.account_id))
|
||||
if account is None or account.is_deleted:
|
||||
# 回调之后、兑换之前这个人被删了:当作免登失效,让人回门户重来
|
||||
logger.warning("免登短码指向的账号 %s 已不存在,来源 %s", row.account_id, client_ip(request))
|
||||
raise _invalid()
|
||||
return account, row
|
||||
|
||||
|
||||
def redirect_target(row: models.SsoHandoff) -> str:
|
||||
"""兑换成功后该去哪一页(空串交给前端决定兜底页)。"""
|
||||
return safe_path(row.redirect)
|
||||
|
||||
|
||||
def advertised_urls(request: Request) -> dict[str, str]:
|
||||
"""把回调地址拼成管理员能直接抄进 Hub 后台的完整 URL。
|
||||
|
||||
站点根取当前这一次请求的地址(过了反代就认 ``X-Forwarded-Proto/Host``),**只作界面
|
||||
抄写参考**:它不参与任何校验,反代头写歪了顶多是显示的地址不对。
|
||||
"""
|
||||
proto = str(request.headers.get("x-forwarded-proto") or "").split(",")[0].strip().lower()
|
||||
if proto not in ("http", "https"):
|
||||
proto = str(request.url.scheme or "http").lower()
|
||||
host = str(request.headers.get("x-forwarded-host") or "").split(",")[0].strip()
|
||||
if not host:
|
||||
host = str(request.headers.get("host") or "").strip()
|
||||
# Host 头是客户端说了算,只允许主机名与端口这种形状,别把别的字符拼进界面
|
||||
if not _HOST_RE.fullmatch(host):
|
||||
host = str(request.url.netloc)
|
||||
root = f"{proto}://{host}".rstrip("/")
|
||||
return {
|
||||
"callbackUrl": root + CALLBACK_PATH,
|
||||
"aliasUrl": root + ALIAS_PATH,
|
||||
"landingUrl": root + LANDING_PATH,
|
||||
}
|
||||
|
||||
|
||||
def view() -> dict[str, object]:
|
||||
"""给状态接口/界面上的"该去 Hub 填哪个地址"用,不含任何密钥。"""
|
||||
return {
|
||||
"callbackPath": CALLBACK_PATH,
|
||||
"aliasPath": ALIAS_PATH,
|
||||
"landingPath": LANDING_PATH,
|
||||
"cookieName": COOKIE_NAME,
|
||||
"codeTtlSeconds": CODE_TTL_SECONDS,
|
||||
}
|
||||
|
||||
|
||||
def _invalid():
|
||||
from ..envelope import ApiError # 同上,避免模块期依赖
|
||||
|
||||
return ApiError(REASON_INVALID, "免登跳转已经失效,请回到统一门户重新点击本系统",
|
||||
http_status=401)
|
||||
|
||||
|
||||
def _collect(db: Session, now: datetime) -> None:
|
||||
"""顺手清掉过期已久的短码:这表只有几列,但没人清就会一直长。"""
|
||||
try:
|
||||
db.execute(delete(models.SsoHandoff).where(
|
||||
models.SsoHandoff.expires_at < now - timedelta(seconds=GC_KEEP_SECONDS)
|
||||
))
|
||||
db.commit()
|
||||
except Exception: # noqa: BLE001 清表失败不该把一次正常免登弄失败
|
||||
db.rollback()
|
||||
logger.debug("清理过期免登短码失败", exc_info=True)
|
||||
|
|
@ -0,0 +1,166 @@
|
|||
"""免登跳转的 ``state``:本系统服务端生成,存在浏览器一条 HttpOnly Cookie 里。
|
||||
|
||||
对接指南第 5 节与第 10 节自查清单要求:``state`` 由**下游服务端**生成并保管,落地时
|
||||
与票据校验响应里回传的 ``state`` 精确比对,用来挡会话固定与"别人把票据塞给你"。
|
||||
"服务端一侧"排除了浏览器能自己读写的地方,所以早先把 state 签成 JWT 交给前端
|
||||
sessionStorage 的写法并不算数——那份值前端脚本读得到,也能被人提前造好。这里改放
|
||||
HttpOnly Cookie:前端拿不到明文,只能在落地后把地址栏里 Hub 原样带回来的 ``state``
|
||||
交回来,由后端与 Cookie 里的值做常数时间比对。口径与 unisoa 的 ``sso_state`` 一致。
|
||||
|
||||
两条链路都要走得通,于是按 ``[hub].sso_state_required`` 分两档:
|
||||
|
||||
* **从本系统发起**:先调 ``POST /auth/sso/state`` 写 Cookie 再跳门户,落地时 Cookie 一定在;
|
||||
只要落地带回了 ``state``,就必须与 Cookie 里那条对上,对不上直接拒。
|
||||
* **从 Hub 门户直接点卡片**:门户压根不知道被发过哪个 state,落地要么没 Cookie
|
||||
(隔了一小时才点、换了浏览器),要么 Cookie 在而地址栏没带回 state。宽松档(默认)
|
||||
这两种都放行,但**带回了 state 就必须对上**——放宽的只是"这一趟压根没有可比的东西",
|
||||
比对本身从来不跳过;严格档(``sso_state_required=true``)两种一律拒。
|
||||
|
||||
Cookie 是一次性的:不管校验结果如何都立刻清掉,免得同一条 state 被反复消费。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
|
||||
from fastapi import Request
|
||||
from fastapi.responses import Response
|
||||
|
||||
from .. import security
|
||||
from ..config import settings
|
||||
|
||||
#: 存 state 的 Cookie 名。HttpOnly + SameSite=Lax:脚本读不到,同站请求照常带。
|
||||
COOKIE_NAME = "pms_sso_state"
|
||||
#: 一条 state 的存活秒数。跳门户 → 点卡片 → 落地换会话,十分钟够用。
|
||||
STATE_TTL_SECONDS = 600
|
||||
|
||||
#: 校验结论,写进日志与接口 reason,排障时一眼看出是哪一步没对上
|
||||
MATCHED = "matched"
|
||||
MISSING = "missing"
|
||||
#: 本系统发过 state,落地却没带回 state(门户直点卡片就是这个样子)
|
||||
NOT_RETURNED = "not_returned"
|
||||
EXPIRED = "expired"
|
||||
TAMPERED = "tampered"
|
||||
MISMATCH = "mismatch"
|
||||
|
||||
REASONS = {
|
||||
MATCHED: "state 与本系统发出的一致",
|
||||
MISSING: "浏览器里没有本系统发出的 state(不是从本系统发起的免登)",
|
||||
NOT_RETURNED: "本系统发出过 state,但落地没带回 state(统一门户直点卡片就是这种)",
|
||||
EXPIRED: "state 已过期,请重新发起免登",
|
||||
TAMPERED: "state 签名不对,按被篡改处理",
|
||||
MISMATCH: "落地带回来的 state 与本系统发出的不一致",
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StateCheck:
|
||||
"""一次 state 校验的结论。``verdict`` 才结合配置决定放不放行。"""
|
||||
|
||||
code: str
|
||||
had_cookie: bool
|
||||
|
||||
@property
|
||||
def matched(self) -> bool:
|
||||
return self.code == MATCHED
|
||||
|
||||
@property
|
||||
def detail(self) -> str:
|
||||
return REASONS.get(self.code, self.code)
|
||||
|
||||
def verdict(self, required: bool) -> tuple[bool, str]:
|
||||
"""结合"必须校验 state"这一档决定放不放行,并给出一句话说明。"""
|
||||
if self.matched:
|
||||
return True, self.detail
|
||||
if self.code in (MISSING, NOT_RETURNED) and not required:
|
||||
return True, f"{self.detail};未开启强制校验,本次按门户直跳放行"
|
||||
return False, self.detail
|
||||
|
||||
|
||||
def is_https(request: Request) -> bool:
|
||||
"""这次请求走没走 HTTPS:直连看 scheme,过了反代看 ``X-Forwarded-Proto``。
|
||||
|
||||
Cookie 的 ``Secure`` 位要跟着它走。在 HTTP 部署上打开这一位,浏览器会直接把 Cookie
|
||||
丢掉,症状是"免登永远说没发过 state",非常难查。
|
||||
"""
|
||||
forwarded = str(request.headers.get("x-forwarded-proto") or "").split(",")[0].strip().lower()
|
||||
if forwarded:
|
||||
return forwarded == "https"
|
||||
return str(request.url.scheme or "").lower() == "https"
|
||||
|
||||
|
||||
def issue_state(response: Response, *, secure: bool = False) -> str:
|
||||
"""生成一条 state,写进 HttpOnly Cookie,把明文返回给前端拼进跳转地址。"""
|
||||
state = secrets.token_urlsafe(24)
|
||||
raw = f"{state}.{int(time.time())}"
|
||||
response.set_cookie(
|
||||
COOKIE_NAME,
|
||||
f"{raw}.{security.sign(raw)}",
|
||||
max_age=STATE_TTL_SECONDS,
|
||||
path="/",
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
secure=secure,
|
||||
)
|
||||
return state
|
||||
|
||||
|
||||
def clear_state(response: Response) -> None:
|
||||
response.delete_cookie(COOKIE_NAME, path="/")
|
||||
|
||||
|
||||
def forward_cookies(source: Response, target: Response) -> None:
|
||||
"""把临时 ``Response`` 上攒下的 ``Set-Cookie`` 搬到真正要发出去的响应上。
|
||||
|
||||
FastAPI 只在接口返回"可序列化数据"时才把注入的 ``Response`` 合并进最终响应;接口
|
||||
直接返回一个 ``Response``(免登回调返回的就是 302)时它原样发出,注入参数上写的
|
||||
Cookie 就此丢掉。而 state 无论校验结果如何都要当场用掉,所以这一趟自己搬。
|
||||
"""
|
||||
target.raw_headers.extend(source.raw_headers)
|
||||
|
||||
|
||||
def _parse(cookie: str) -> tuple[str, str]:
|
||||
"""拆 Cookie,返回 ``(state, 结论)``;结论是 ``""``(合法)/ ``expired`` / ``tampered``。"""
|
||||
parts = cookie.strip().split(".")
|
||||
if len(parts) != 3:
|
||||
return "", TAMPERED
|
||||
state, stamp, signature = parts
|
||||
if not security.verify_signature(f"{state}.{stamp}", signature):
|
||||
return "", TAMPERED
|
||||
try:
|
||||
issued_at = int(stamp)
|
||||
except ValueError:
|
||||
return "", TAMPERED
|
||||
if time.time() - issued_at > STATE_TTL_SECONDS:
|
||||
return "", EXPIRED
|
||||
return state, ""
|
||||
|
||||
|
||||
def check_state(request: Request, response: Response, submitted: str) -> StateCheck:
|
||||
"""比对落地带回的 ``state`` 与 Cookie 里那条,无论结果如何都把 Cookie 用掉。"""
|
||||
cookie = str(request.cookies.get(COOKIE_NAME) or "").strip()
|
||||
clear_state(response)
|
||||
if not cookie:
|
||||
return StateCheck(code=MISSING, had_cookie=False)
|
||||
expected, problem = _parse(cookie)
|
||||
if problem:
|
||||
return StateCheck(code=problem, had_cookie=True)
|
||||
if not submitted:
|
||||
# 发过 state,可 Hub 那一趟没往落地地址上拼 state。门户直点卡片是对接文档里的
|
||||
# 主路径,不能因为它不带 state 就把人锁在门外;带回来了才必须对上,见下一条。
|
||||
return StateCheck(code=NOT_RETURNED, had_cookie=True)
|
||||
if not secrets.compare_digest(expected, submitted.strip()):
|
||||
return StateCheck(code=MISMATCH, had_cookie=True)
|
||||
return StateCheck(code=MATCHED, had_cookie=True)
|
||||
|
||||
|
||||
def view() -> dict[str, object]:
|
||||
"""给状态接口用的一组说明,不含任何密钥。"""
|
||||
return {
|
||||
"cookieName": COOKIE_NAME,
|
||||
"ttlSeconds": STATE_TTL_SECONDS,
|
||||
# 严格档开了以后"门户直点卡片"也会被拒,界面上必须能看出现在处在哪一档
|
||||
"required": settings.hub.sso_state_required,
|
||||
}
|
||||
|
|
@ -0,0 +1,70 @@
|
|||
# 四算 PMS 后端配置 · 开发/测试档(PMS_ENV 没设时读这一份)
|
||||
#
|
||||
# 叠在 config.toml 上面,只写跟公共值不一样的键,其余沿用那边。
|
||||
# 生产上不用管这个文件:export PMS_ENV=prod 之后读的是 config.prod.toml。
|
||||
#
|
||||
# 本文件带测试库口令和 hubtest 联调密钥,别提交到公共仓库,
|
||||
# 也别照着改生产——换环境一律用 PMS_* 环境变量注入。
|
||||
|
||||
# 本系统自己的开发库。老四算库 unis_fourcal_dev 一个字节都不改,只挂只读
|
||||
[database]
|
||||
host = "10.100.51.227"
|
||||
port = 30306
|
||||
user = "root"
|
||||
password = "unis@123"
|
||||
name = "fourcal_pms_dev"
|
||||
auto_create_schema = true # 启动时自动建库建表补列(生产交 DBA 时改 false)
|
||||
|
||||
# 老系统数据源:只读,供 scripts/migrate_legacy.py 与双跑对账报表使用
|
||||
[legacy]
|
||||
enabled = true
|
||||
host = "10.100.51.227"
|
||||
port = 30306
|
||||
user = "root"
|
||||
password = "unis@123"
|
||||
name = "unis_fourcal_dev"
|
||||
|
||||
# 前端开发服务器地址,供 CORS 白名单使用
|
||||
[server]
|
||||
cors_origins = [
|
||||
"http://localhost:5383", "http://127.0.0.1:5383",
|
||||
"http://localhost:5273", "http://127.0.0.1:5273",
|
||||
]
|
||||
|
||||
# 本机专用随机密钥,与 config.prod.toml 那把不同
|
||||
[security]
|
||||
jwt_secret = "dev-only-2k6PmS-f0uRc4l-JWt-s3cr3t-8f2c1a7e9b4d6053"
|
||||
|
||||
# 首次启动种的数据:只在库里没有对应记录时生效
|
||||
[seed]
|
||||
# 演示组织与张三李四王五已用 scripts/clean_demo_data.py 清掉,这里跟着关掉:
|
||||
# seed 的判断是"org_unit 是空表就种一份",留着 true 下次重启又长回来。
|
||||
# 要演示数据就改回 true 再重启一次后端。
|
||||
demo_data = false
|
||||
# 本系统只留这一个本地账号:口令只在本系统校验,从不问统一身份,seed 每次启动都补,
|
||||
# scripts/clean_demo_data.py 也会留着它。名字刻意不叫 admin——那个名字留给统一身份里
|
||||
# 真叫 admin 的人,否则同步过来只能建成 admin_hubNNN 这种别扭的号(unisoa 同样处理)。
|
||||
admin_account = "localadmin"
|
||||
admin_password = "admin123" # 只适合开发机;首次登录后请立即改
|
||||
|
||||
|
||||
# 统一身份(hubtest)联调档。hubtest 上已把本系统注册成应用 pms:
|
||||
# directory_key -> 拉组织与人员(X-Directory-Key)
|
||||
# integration_key -> 免登票据校验(X-Integration-Key),Hub 回显的 app_code 就是 pms
|
||||
# 换环境请用 PMS_HUB_* 环境变量注入,别把生产密钥写进仓库。
|
||||
[hub]
|
||||
enabled = true
|
||||
base_url = "http://hubtest.oa.unissense.tech"
|
||||
# 两把密钥互不通用,别串:填错 Hub 回 401 401001「集成密钥无效」,
|
||||
# 拿目录密钥去换票据回 403001「密钥与应用的对应关系不正确」
|
||||
directory_key = "6ca995bac55dee72e93a1f04e2e2f6cb370bb2d875bc4b3dcccc318df44ccdea" # X-Directory-Key:拉组织与人员
|
||||
integration_key = "6ca995bac55dee72e93a1f04e2e2f6cb370bb2d875bc4b3dcccc318df44ccdea" # X-Integration-Key:免登票据校验
|
||||
app_code = "pms" # 免登应用编码,Hub 回显的就是这一条
|
||||
# 开发机别后台狂轮询,同步只在「统一身份同步」页手点
|
||||
changes_interval_seconds = 0
|
||||
sync_interval_minutes = 0
|
||||
# 这些账号永远只用本地口令,不去问 Hub(内置超管 admin 无需写,代码里始终在列):
|
||||
|
||||
|
||||
[log]
|
||||
level = "DEBUG"
|
||||
|
|
@ -0,0 +1,83 @@
|
|||
# 四算 PMS 后端配置 · 生产档(export PMS_ENV=prod 后生效)
|
||||
#
|
||||
# 叠在 config.toml 上面,只写跟公共值不一样的键。填好之后 chmod 600 本文件。
|
||||
# 不想落到文件里的口令密钥,用环境变量注入,优先级高于本文件:
|
||||
# PMS_DB_PASSWORD · PMS_LEGACY_PASSWORD · PMS_JWT_SECRET
|
||||
# PMS_HUB_DIRECTORY_KEY · PMS_HUB_INTEGRATION_KEY · PMS_HUB_APP_CODE
|
||||
#
|
||||
# 生产档启动时会过一轮上线体检:空密钥、空库口令、没关的演示数据、
|
||||
# 非 HTTPS 的 Hub 地址,都会在日志里点名。
|
||||
|
||||
# 生产不要用 root,给最小权限账号;建表交 DBA
|
||||
[database]
|
||||
host = "127.0.0.1" # PMS_DB_HOST
|
||||
port = 3306 # PMS_DB_PORT
|
||||
user = "fourcal_pms" # PMS_DB_USER
|
||||
password = "" # PMS_DB_PASSWORD
|
||||
name = "fourcal_pms_pro" # PMS_DB_NAME
|
||||
auto_create_schema = false # 生产建表交 DBA,执行 sql/schema.sql
|
||||
pool_size = 20
|
||||
max_overflow = 60
|
||||
|
||||
# 老四算库:只读,上线双跑对账期间打开,对账结束改 false
|
||||
[legacy]
|
||||
enabled = true
|
||||
host = "127.0.0.1"
|
||||
port = 3306
|
||||
user = "fourcal_readonly" # 老库只读账号
|
||||
password = "" # PMS_LEGACY_PASSWORD
|
||||
name = "unis_fourcal"
|
||||
|
||||
# 生产只监听本机,由 Nginx 把 /api 反代过来;同域部署 CORS 留空
|
||||
[server]
|
||||
host = "127.0.0.1"
|
||||
port = 8383
|
||||
|
||||
# 必须填:48 字节以上的随机串,例如 openssl rand -hex 48
|
||||
[security]
|
||||
jwt_secret = "" # PMS_JWT_SECRET
|
||||
|
||||
# 生产绝不种演示数据。超管口令留空即首次启动打印一次性初始口令
|
||||
[seed]
|
||||
demo_data = false
|
||||
# 本系统唯一的本地账号,口令只在本系统校验,从不问统一身份。名字不叫 admin 是把它让给
|
||||
# 统一身份里真叫 admin 的人。口令别写进仓库:留空时 seed 随机生成、只在启动日志里打印
|
||||
# 一次,或用 PMS_SEED_ADMIN_PASSWORD 注入。
|
||||
admin_account = "localadmin"
|
||||
admin_password = ""
|
||||
# 想再留第二把本地门才填这两项;与 admin_account 同名或留空就是只有一把
|
||||
emergency_account = ""
|
||||
emergency_password = ""
|
||||
|
||||
# 生产 Hub:地址必须 HTTPS,两把密钥都从环境变量注入,不落文件
|
||||
[hub]
|
||||
enabled = true # PMS_HUB_ENABLED
|
||||
base_url = "https://hub.oa.unissense.tech"
|
||||
# 两把密钥互不通用,也不写进文件:拿免登密钥去拉目录,Hub 回 401 401001「集成密钥无效」;
|
||||
# 拿目录密钥去换票据,回 403001「密钥与应用的对应关系不正确」。hubtest 那两把在 dev 档里。
|
||||
directory_key = "" # PMS_HUB_DIRECTORY_KEY(X-Directory-Key,拉组织与人员)
|
||||
app_code = "pms" # PMS_HUB_APP_CODE(免登应用编码)
|
||||
integration_key = "" # PMS_HUB_INTEGRATION_KEY(X-Integration-Key,与上面不通用)
|
||||
# 统一门户另有前端地址时才填这一项,留空退回 base_url
|
||||
portal_url = "" # PMS_HUB_PORTAL_URL
|
||||
changes_interval_seconds = 45 # 增量轮询
|
||||
sync_interval_minutes = 1440 # 每日一次全量校对,兜住事件缺失
|
||||
# 逃生门先留着:Hub 整体挂掉时还得能登进来处理审批超时。
|
||||
# 安全口径要求彻底关掉本地口令的话,改成 false
|
||||
break_glass_login = true
|
||||
# 这些账号的口令只在本系统校验,绝不拿去问 Hub。内置超管([seed] admin_account)
|
||||
# 代码里始终在列,这里放的是额外点名的应急账号;账号本身用 scripts 或页面建,
|
||||
# 口令由部署方设并按需改,不要写进仓库。名字对不上就是空转,多写一个不报错。
|
||||
local_only_accounts = "localadmin"
|
||||
# 严格档:门户直点卡片(不带 state)也会被拒。先和门户确认再开
|
||||
sso_state_required = false
|
||||
|
||||
# Hub 后台登记本系统时,落地地址(launch_url / redirect_uris)填这一条:
|
||||
# https://<本系统>/api/v1/auth/sso/callback 别名 /sso/hub
|
||||
# 完整地址连域名一起看 GET /api/v1/auth/hub/status 的 sso.callbackUrl。
|
||||
|
||||
[upload]
|
||||
path = "/home/data/fourcal-pms/uploads" # PMS_UPLOAD_PATH
|
||||
|
||||
[log]
|
||||
dir = "/home/data/fourcal-pms/logs"
|
||||
|
|
@ -0,0 +1,94 @@
|
|||
# 四算 PMS 后端配置 · 各环境公共基础值
|
||||
#
|
||||
# 有效配置 = 本文件 + 档位文件深合并(只覆盖档位文件里写到的键,没写的沿用这里):
|
||||
# config.dev.toml 开发/测试档,PMS_ENV 没设时读这一份
|
||||
# config.prod.toml 生产档,PMS_ENV=prod 时读这一份
|
||||
#
|
||||
# python run.py 默认 dev 档
|
||||
# PMS_ENV=prod python run.py 生产档(写全名 production 也认)
|
||||
# PMS_CONFIG=/path/to/x.toml 只认这一个文件,档位文件一概不读
|
||||
#
|
||||
# 优先级:环境变量 PMS_* > 档位文件 > 本文件 > app/config.py 里的内置默认值。
|
||||
# 库地址与口令、JWT 密钥、Hub 的密钥和站点地址、种子数据都跟环境走,
|
||||
# 只写在档位文件里(或用环境变量注入),本文件一个密钥都不放。
|
||||
|
||||
# 兜底档位:没设 PMS_ENV 时算哪一档。留 dev,不会因为漏设而误连生产库
|
||||
[env]
|
||||
name = "dev"
|
||||
|
||||
# 引导配置:服务监听,改完要重启
|
||||
[server]
|
||||
host = "0.0.0.0"
|
||||
port = 8383
|
||||
cors_origins = [] # CORS 白名单;同域反向代理留空,本机前端地址在 dev 档里
|
||||
|
||||
# 引导配置:登录令牌签名,改完要重启(换密钥 = 已登录会话全部失效)
|
||||
# jwt_secret 各环境必须不同,写在档位文件里,测试签出的令牌到生产上验不过才是对的
|
||||
[security]
|
||||
jwt_algorithm = "HS256"
|
||||
access_token_ttl = 28800 # 访问令牌有效期(秒),默认 8 小时
|
||||
refresh_token_ttl = 604800 # 刷新令牌有效期(秒),默认 7 天
|
||||
password_min_length = 8
|
||||
login_max_errors = 5 # 连续登录失败多少次锁号
|
||||
login_lock_minutes = 30 # 锁号时长(分钟)
|
||||
|
||||
# 这里没有 [calc]:计算口径不在配置文件里。
|
||||
# 舍入位数与进位方式、零分母行为、价内税两个历史开关、利润各层扣哪些成本、
|
||||
# 公司管理费用率、差旅业务费限额比例、贡献利润率不达标时的动作——全部是
|
||||
# system_config 表里 calc. 开头的业务参数,登录后在「系统 → 计算口径」页面上改,
|
||||
# 保存即生效(下一次试算就是新口径),不用重启,也不用登机器。
|
||||
# 推荐值、取值范围与规则号见 app/service/calc/rules.py 与 docs/计算口径.md;
|
||||
# 改之前先过业务确认,并且把 calc.version 一起升上去,不然项目上会出现
|
||||
# "数字变了但快照里的口径版本号没变",那是最难查的一种对不上。
|
||||
|
||||
# 统一身份(Hub):账号与组织架构同步、单点登录。对接口径与 unisoa 一致,
|
||||
# 细节见 docs/统一身份登录.md。契约见 dsh-hub《第三方系统对接指南》:目录走
|
||||
# directory_key(X-Directory-Key),免登走 integration_key(X-Integration-Key),
|
||||
# 两把密钥互不通用;接口路径写在 HubConfig 里当常量,不在这里配,
|
||||
# 免得配错一个斜杠就静默同步到空目录。站点地址与两把密钥在档位文件里。
|
||||
[hub]
|
||||
enabled = false # 总闸:false 时只用本地账号口令登录
|
||||
directory_member_limit = 5000 # 全量花名册上限;接口返回 truncated 会直接报错而不是静默少人
|
||||
changes_limit = 500 # 增量单批条数,接口上限 500
|
||||
changes_interval_seconds = 45 # 增量轮询间隔(文档建议 30~60 秒);0 = 只在页面上手动同步
|
||||
sync_interval_minutes = 1440 # 全量校对间隔,文档要求每日一次;0 = 只在页面上手动同步
|
||||
sync_timeout = 60 # 单次拉取超时(秒)
|
||||
missing_account_action = "disable" # Hub 侧账号已消失:disable 停用(推荐)/ skip 不动
|
||||
missing_org_action = "disable" # Hub 侧组织已消失:同上
|
||||
|
||||
# 口令校验口径:hub 口令只问统一身份,Hub 连不上就当场回"统一身份暂不可用",
|
||||
# 绝不"连不上就当本地账号放行";hybrid 在 Hub 连不上时退回本地口令校验;
|
||||
# local 不问统一身份,只用本地口令;sso 口令登录整个关掉,登录页只留"前往统一门户"
|
||||
login_mode = "hub"
|
||||
# 这些账号永远只用本地口令,不去问 Hub(逗号分隔,大小写不敏感)。内置超管
|
||||
# (seed.admin_account)始终在列,不必写在这里——那是 Hub 配错时唯一能保证
|
||||
# 还进得去门的账号
|
||||
local_only_accounts = ""
|
||||
# Hub 停用或整体不可达时,仍允许 source=local 的账号(内置超管)用口令登进来救火。
|
||||
# 设成 false 就是彻底只认免登;任何情况下都不会给 Hub 账号留口令后门
|
||||
break_glass_login = true
|
||||
# 严格档:连"门户直点卡片、压根没带回 state"也拒。开了之后每次免登都必须先从
|
||||
# 本系统登录页跳出去,否则没人进得来,没跟门户确认之前别打开
|
||||
sso_state_required = false
|
||||
|
||||
# 免登要在 Hub 后台把本系统登记成应用,落地地址(launch_url / redirect_uris)填
|
||||
# 后端回调这一条,票据就不会进浏览器:
|
||||
# http(s)://<本系统>/api/v1/auth/sso/callback 别名 /sso/hub
|
||||
# 后端验完票只 302 回前端落地页 /sso,地址上带的是一条 60 秒即失效、只能用一次、
|
||||
# 还绑着 HttpOnly Cookie 的短码。该填哪一条本系统会自己算,看
|
||||
# GET /api/v1/auth/hub/status 的 sso.callbackUrl,免登状态页也摆着同一份。
|
||||
|
||||
# 审批运行时
|
||||
[approval]
|
||||
timeout_sweep_minutes = 10 # 超时催办/自动通过的扫描间隔;0 = 不自动扫(有人操作时顺带处理)
|
||||
|
||||
# 附件上传:走本地磁盘,生产可换对象存储
|
||||
[upload]
|
||||
path = "./storage/uploads"
|
||||
max_size_mb = 50
|
||||
allowed_ext = ["pdf", "doc", "docx", "xls", "xlsx", "png", "jpg", "jpeg", "zip", "rar"]
|
||||
|
||||
# 日志
|
||||
[log]
|
||||
level = "INFO"
|
||||
dir = "./logs"
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
fastapi>=0.115
|
||||
uvicorn[standard]>=0.29
|
||||
SQLAlchemy>=2.0
|
||||
PyMySQL>=1.1
|
||||
cryptography>=42.0
|
||||
pydantic>=2.7
|
||||
python-jose[cryptography]>=3.3
|
||||
bcrypt>=4.0
|
||||
python-multipart>=0.0.9
|
||||
httpx>=0.27
|
||||
openpyxl>=3.1
|
||||
pytest>=8.0
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
"""四算 PMS 后端入口。
|
||||
|
||||
python run.py # 默认 dev 档(config.dev.toml)
|
||||
PMS_ENV=prod python run.py # 生产档(config.prod.toml)
|
||||
"""
|
||||
import os
|
||||
|
||||
import uvicorn
|
||||
|
||||
from app.config import settings
|
||||
|
||||
if __name__ == "__main__":
|
||||
uvicorn.run(
|
||||
"app.main:app",
|
||||
host=os.environ.get("PMS_HOST", settings.server.host),
|
||||
port=int(os.environ.get("PMS_PORT", settings.server.port)),
|
||||
reload=os.environ.get("PMS_RELOAD", "1") == "1",
|
||||
)
|
||||
|
|
@ -0,0 +1,493 @@
|
|||
#!/usr/bin/env python3
|
||||
"""把库清回"刚建完表 + seed 基础数据"的样子:演示数据、界面造的示例单据、
|
||||
pytest 跑出来的垃圾,一次扫干净。
|
||||
|
||||
先分清两样东西
|
||||
==============
|
||||
|
||||
**留下的**(系统基础数据,没有就等于系统空转,seed 也随时能补回来):
|
||||
|
||||
perm_node / perm_role / perm_role_node / perm_field_scope / perm_data_policy
|
||||
system_config
|
||||
approval_flow / approval_node
|
||||
accounts 里只留 seed 会补回来的两个账号:内置超管(``[seed] admin_account``)
|
||||
与本地应急管理员(``[seed] emergency_account``,默认 ``localadmin``)
|
||||
|
||||
**清掉的**(都可再生:组织与人点一次「全量同步」就回来,单据本来就是要重造的):
|
||||
|
||||
组织岗位 org_unit / org_position
|
||||
账号关系 accounts(超管之外)/ account_identity / perm_account_role / approval_delegate
|
||||
项目单据 project / project_member / project_stage_log / project_visible_role
|
||||
biz_revision / estimate_*_line / budget_*_line / calc_snapshot / attachment
|
||||
审批运行时 approval_instance / approval_record / approval_task
|
||||
流水日志 login_log / operation_log / hub_sync_run / sso_handoff
|
||||
|
||||
怎么保证删得回来
|
||||
================
|
||||
|
||||
* **默认干跑**:不加 ``--apply`` 只报每张表要删多少行,一行都不动。
|
||||
* **删之前先备份**:被删的每一行都写成 INSERT 落到
|
||||
``storage/backups/clean-<时间>-<库名>.sql``,事后想留哪张表就回放那一段;
|
||||
``--no-backup`` 才跳过。
|
||||
* **生产档拒绝执行**:``PMS_ENV=prod`` 时直接退出,非要删得再加
|
||||
``--i-know-this-is-production``。
|
||||
* 表清单是写死的,但会跟模型比对:模型里多出一张既不在"留"也不在"删"名单里的表,
|
||||
脚本当场报错,不会悄悄留一堆孤儿行。
|
||||
|
||||
python3 scripts/clean_demo_data.py # 先看要删什么
|
||||
python3 scripts/clean_demo_data.py --apply # 备份 + 真删
|
||||
python3 scripts/clean_demo_data.py --restore <备份文件> # 先看要回什么
|
||||
python3 scripts/clean_demo_data.py --restore <备份文件> --apply # 真回放
|
||||
|
||||
回放走脚本自己,不依赖 ``mysql`` 客户端(本机就没装);备份文件是标准 INSERT,
|
||||
拿去 ``mysql 库名 < 备份文件`` 也一样能吃。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from sqlalchemy import func, select # noqa: E402
|
||||
|
||||
import app.models # noqa: F401,E402 (触发模型注册)
|
||||
from app.config import settings # noqa: E402
|
||||
from app.db import Base, SessionFactory # noqa: E402
|
||||
|
||||
#: 留下的表:系统基础数据,清掉等于把权限目录和业务参数一起扔了。
|
||||
#: ``dict_type`` / ``dict_item`` 在这儿是因为它们是 seed 每次启动都同步的"代码字典"
|
||||
#: (``seed._seed_dicts`` → ``app.dicts.sync``):清掉不出问题,但下次启动又会长回来,
|
||||
#: 白清一趟;界面上自建的 ``source=custom`` 条目算配置不算测试数据,跟着一起留。
|
||||
KEEP_TABLES = (
|
||||
"perm_node",
|
||||
"perm_role",
|
||||
"perm_role_node",
|
||||
"perm_field_scope",
|
||||
"perm_data_policy",
|
||||
"system_config",
|
||||
"approval_flow",
|
||||
"approval_node",
|
||||
"dict_type",
|
||||
"dict_item",
|
||||
)
|
||||
|
||||
#: 清掉的表,顺序就是删除顺序:先子表后父表,外键才不会拦着
|
||||
CLEAR_TABLES = (
|
||||
# 审批运行时(引用账号、流程实例)
|
||||
"approval_record",
|
||||
"approval_task",
|
||||
"approval_instance",
|
||||
"approval_delegate",
|
||||
# 项目与单据(引用账号、项目、版本)
|
||||
"budget_fund_month",
|
||||
"budget_income_line",
|
||||
"budget_income_plan_line",
|
||||
"budget_manage_line",
|
||||
"budget_other_cost_line",
|
||||
"budget_pay_plan_line",
|
||||
"budget_purchase_line",
|
||||
"estimate_cost_line",
|
||||
"estimate_income_line",
|
||||
"estimate_other_line",
|
||||
"biz_revision",
|
||||
"project_member",
|
||||
"project_stage_log",
|
||||
"project_visible_role",
|
||||
"attachment",
|
||||
"calc_snapshot",
|
||||
"project",
|
||||
# 账号与关系(引用组织、岗位)
|
||||
"perm_account_role",
|
||||
"account_identity",
|
||||
"sso_handoff",
|
||||
"accounts",
|
||||
# 组织岗位与流水
|
||||
"org_unit",
|
||||
"org_position",
|
||||
"hub_sync_run",
|
||||
"login_log",
|
||||
"operation_log",
|
||||
)
|
||||
|
||||
#: 这几张表虽然要清,但只清 seed 账号之外的行——超管与应急管理员不能一起删掉
|
||||
CLEAR_ALL_BUT_SEED = ("accounts",)
|
||||
|
||||
#: KEEP_TABLES 里的行并不全是"seed 补得回来的基础数据":``migrate_legacy.py``
|
||||
#: 会往 ``perm_role`` / ``approval_flow`` 里插"由老四算导入"的角色和流程,
|
||||
#: code / key 一律带 ``legacy_`` 前缀。整表留着就等于把上一次迁移的结果当成基础数据
|
||||
#: 留了下来——清完库再导一次,同 key 直接"已导入"跳过,改都改不动。
|
||||
#: 所以认这个前缀,把导入件当演示数据清掉,seed 那几行照旧留。
|
||||
KEEP_DROP_IMPORTED = {
|
||||
"perm_role": ("code", "legacy_"),
|
||||
"approval_flow": ("key", "legacy_"),
|
||||
}
|
||||
|
||||
#: 跟着父表连坐的子表:自己没有任何"我是导入的"标记,只能按外键跟着删
|
||||
KEEP_DROP_IMPORTED_CHILDREN = {
|
||||
"approval_node": ("approval_flow", "flow_id"),
|
||||
}
|
||||
|
||||
|
||||
def _protected_accounts() -> tuple[str, ...]:
|
||||
"""seed 随时会补回来、所以清理时必须留着的那几个账号。
|
||||
|
||||
以前只留超管,结果清一次演示数据就把应急管理员一起删了:它不属于"演示数据",
|
||||
要等下次启动 seed 才回来,而清库的人往往正卡在"进不去门"上——那段时间最需要它。
|
||||
"""
|
||||
names = [settings.seed.admin_account or "admin",
|
||||
(settings.seed.emergency_account or "").strip()]
|
||||
keep: list[str] = []
|
||||
for name in names:
|
||||
if name and name not in keep:
|
||||
keep.append(name)
|
||||
return tuple(keep)
|
||||
|
||||
|
||||
def _imported_ids(session) -> dict[str, list[int]]:
|
||||
"""KEEP 表里"由迁移脚本导入"的行 id,按表分组。"""
|
||||
from sqlalchemy import select
|
||||
|
||||
out: dict[str, list[int]] = {}
|
||||
# .scalars() 不是风格问题:少了它取回来的是 (id,) 元组,
|
||||
# 拿元组去 IN 匹配不到任何行,删起来就是"报 0 行、什么也没删"的静默失败
|
||||
for name, (column, prefix) in KEEP_DROP_IMPORTED.items():
|
||||
table = Base.metadata.tables[name]
|
||||
out[name] = list(session.scalars(
|
||||
select(table.c.id).where(table.c[column].like(f"{prefix}%", escape="\\"))))
|
||||
for name, (parent, fk) in KEEP_DROP_IMPORTED_CHILDREN.items():
|
||||
table = Base.metadata.tables[name]
|
||||
parent_ids = out.get(parent) or [-1]
|
||||
rows = list(session.scalars(select(table.c.id).where(table.c[fk].in_(parent_ids))))
|
||||
if rows:
|
||||
out.setdefault(name, [])
|
||||
out[name] += rows
|
||||
return {name: ids for name, ids in out.items() if ids}
|
||||
|
||||
|
||||
def _literal(value: object) -> str:
|
||||
"""把取出来的值写成 SQL 字面量,够把备份文件直接 mysql 进去就行。"""
|
||||
if value is None:
|
||||
return "NULL"
|
||||
if isinstance(value, bool):
|
||||
return "1" if value else "0"
|
||||
if isinstance(value, (int, Decimal)):
|
||||
return str(value)
|
||||
if isinstance(value, datetime):
|
||||
return f"'{value.isoformat(sep=' ')}'"
|
||||
if isinstance(value, date):
|
||||
return f"'{value.isoformat()}'"
|
||||
if isinstance(value, (bytes, bytearray)):
|
||||
return f"_binary 0x{value.hex()}"
|
||||
text = str(value)
|
||||
escaped = (text.replace("\\", "\\\\").replace("'", "\\'")
|
||||
.replace("\n", "\\n").replace("\r", "\\r"))
|
||||
return f"'{escaped}'"
|
||||
|
||||
|
||||
def _rows_to_inserts(table, rows: list[dict], batch: int = 200) -> list[str]:
|
||||
if not rows:
|
||||
return []
|
||||
cols = ", ".join(f"`{c}`" for c in rows[0])
|
||||
out = []
|
||||
for start in range(0, len(rows), batch):
|
||||
values = ",\n ".join(
|
||||
"(" + ", ".join(_literal(row[table.c[c].name]) for c in rows[0]) + ")"
|
||||
for row in rows[start:start + batch]
|
||||
)
|
||||
out.append(f"INSERT INTO `{table.name}` ({cols}) VALUES\n {values};")
|
||||
return out
|
||||
|
||||
|
||||
def split_statements(sql: str) -> list[str]:
|
||||
"""按 MySQL 的规矩切语句:引号里、反引号里、注释里的分号都不算结束。
|
||||
|
||||
不能拿 ``split(";")`` 糊弄——``login_log.user_agent`` 里全是
|
||||
``Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)`` 这种带分号的值,
|
||||
硬切出来的半截 INSERT 会把回放带到沟里。
|
||||
"""
|
||||
statements: list[str] = []
|
||||
buf: list[str] = []
|
||||
quote = None # 当前字符串引号:单引号或双引号
|
||||
in_backtick = False
|
||||
i, n = 0, len(sql)
|
||||
while i < n:
|
||||
ch = sql[i]
|
||||
if quote is not None:
|
||||
if ch == "\\" and i + 1 < n: # 反斜杠转义,连下一个字符一起吃掉
|
||||
buf.append(ch)
|
||||
buf.append(sql[i + 1])
|
||||
i += 2
|
||||
continue
|
||||
if ch == quote:
|
||||
if i + 1 < n and sql[i + 1] == quote: # '' 这种双写转义
|
||||
buf.append(ch)
|
||||
buf.append(sql[i + 1])
|
||||
i += 2
|
||||
continue
|
||||
quote = None
|
||||
buf.append(ch)
|
||||
i += 1
|
||||
continue
|
||||
if in_backtick:
|
||||
buf.append(ch)
|
||||
if ch == "`":
|
||||
in_backtick = False
|
||||
i += 1
|
||||
continue
|
||||
if ch in ("'", '"'):
|
||||
quote = ch
|
||||
buf.append(ch)
|
||||
i += 1
|
||||
continue
|
||||
if ch == "`":
|
||||
in_backtick = True
|
||||
buf.append(ch)
|
||||
i += 1
|
||||
continue
|
||||
if ch == "#" or sql.startswith("--", i) or sql.startswith("/*", i):
|
||||
end = sql.find("\n", i) if ch in "#-" else sql.find("*/", i)
|
||||
if ch == "/" and sql.startswith("/*", i):
|
||||
i = (end + 2) if end != -1 else n
|
||||
else:
|
||||
i = end if end != -1 else n
|
||||
continue
|
||||
if ch == ";":
|
||||
statement = "".join(buf).strip()
|
||||
if statement:
|
||||
statements.append(statement)
|
||||
buf = []
|
||||
i += 1
|
||||
continue
|
||||
buf.append(ch)
|
||||
i += 1
|
||||
tail = "".join(buf).strip()
|
||||
if tail:
|
||||
statements.append(tail)
|
||||
return statements
|
||||
|
||||
|
||||
def _restore(path: Path, apply: bool) -> int:
|
||||
if not path.is_file():
|
||||
print(f"备份文件不存在:{path}")
|
||||
return 2
|
||||
statements = split_statements(path.read_text(encoding="utf-8"))
|
||||
kinds: dict[str, int] = {}
|
||||
for stmt in statements:
|
||||
head = stmt.split(None, 1)[0].upper()
|
||||
table = stmt.split("`")[1] if "`" in stmt else ""
|
||||
kinds[f"{head} {table}".strip()] = kinds.get(f"{head} {table}".strip(), 0) + (
|
||||
stmt.count("),") + 1 if head == "INSERT" else 1)
|
||||
print(f"备份文件 = {path}")
|
||||
summary = ",".join(f"{k} x{v}" for k, v in kinds.items())
|
||||
print(f" 语句 {len(statements)} 条:{summary}")
|
||||
if not apply:
|
||||
print("\n干跑:只解析了备份,一行都没写。确认无误再加 --apply。")
|
||||
return 0
|
||||
with SessionFactory()() as session:
|
||||
# 用 exec_driver_sql 而不是 text():备份里的数据长得像绑参(Hub 报错原文里的
|
||||
# "data":null、LIKE 'wecom-%'),交给 SQLAlchemy 解析会被当成 :参数 或 % 格式符。
|
||||
for stmt in statements:
|
||||
session.exec_driver_sql(stmt)
|
||||
session.commit()
|
||||
print("回放完成。下面这张表现场的行数应该都回来了:")
|
||||
with SessionFactory()() as session:
|
||||
imported = _imported_ids(session)
|
||||
for name in list(KEEP_DROP_IMPORTED) + list(KEEP_DROP_IMPORTED_CHILDREN):
|
||||
ids = imported.get(name)
|
||||
if not ids:
|
||||
continue
|
||||
table = Base.metadata.tables[name]
|
||||
rows = list(session.execute(table.select().where(table.c.id.in_(ids))))
|
||||
keys = [c.name for c in table.columns]
|
||||
data = [dict(zip(keys, row)) for row in rows]
|
||||
lines.append(f"-- {name}: {len(data)} 行(迁移导入,非 seed)")
|
||||
lines.extend(_rows_to_inserts(table, data))
|
||||
lines.append("")
|
||||
for name in reversed(CLEAR_TABLES):
|
||||
table = Base.metadata.tables[name]
|
||||
n = session.execute(select(func.count()).select_from(table)).scalar() or 0
|
||||
if n:
|
||||
print(f" {name:24s} {n}")
|
||||
return 0
|
||||
|
||||
|
||||
def _classified_or_die() -> None:
|
||||
known = set(KEEP_TABLES) | set(CLEAR_TABLES)
|
||||
all_tables = set(Base.metadata.tables)
|
||||
missing = sorted(all_tables - known)
|
||||
if missing:
|
||||
raise SystemExit(
|
||||
"模型里出现了没归过类的表:" + ", ".join(missing)
|
||||
+ "\n请先决定它算基础数据(进 KEEP_TABLES)还是算演示数据(进 CLEAR_TABLES)再跑。"
|
||||
)
|
||||
|
||||
|
||||
def _counts(session, protected: tuple[str, ...]) -> dict[str, int]:
|
||||
from sqlalchemy import func, select
|
||||
|
||||
out = {}
|
||||
for name in CLEAR_TABLES:
|
||||
table = Base.metadata.tables[name]
|
||||
total = session.execute(select(func.count()).select_from(table)).scalar() or 0
|
||||
if name in CLEAR_ALL_BUT_SEED:
|
||||
keep = session.execute(
|
||||
select(func.count()).select_from(table)
|
||||
.where(table.c.account.in_(protected))
|
||||
).scalar() or 0
|
||||
total -= keep
|
||||
out[name] = total
|
||||
for name, ids in _imported_ids(session).items():
|
||||
out[name] = len(ids)
|
||||
return out
|
||||
|
||||
|
||||
def _backup_dir() -> Path:
|
||||
path = Path("./storage/backups")
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def _write_backup(session, protected: tuple[str, ...]) -> Path:
|
||||
"""把要被删的每一行导成 INSERT,按"先父表后子表"的顺序写,回放时省心得得多。"""
|
||||
path = _backup_dir() / (
|
||||
f"clean-{datetime.now():%Y%m%d-%H%M%S}-{settings.database.name}.sql"
|
||||
)
|
||||
lines = [
|
||||
"-- 四算 PMS 清理前的备份:可直接 mysql 回放",
|
||||
f"-- 库 = {settings.database.name}@{settings.database.host}:{settings.database.port}"
|
||||
f" 档位 = {settings.env}",
|
||||
f"-- 生成 = {datetime.now():%Y-%m-%d %H:%M:%S} 由 scripts/clean_demo_data.py 写出",
|
||||
"-- 回放前先确认库是空的或至少不撞主键:",
|
||||
"-- mysql -h HOST -P PORT USER 库名 < 本文件",
|
||||
"",
|
||||
"SET NAMES utf8mb4;",
|
||||
"SET FOREIGN_KEY_CHECKS=0;",
|
||||
"",
|
||||
]
|
||||
for name in reversed(CLEAR_TABLES):
|
||||
table = Base.metadata.tables[name]
|
||||
rows = list(session.execute(table.select()))
|
||||
keys = [c.name for c in table.columns]
|
||||
data = [dict(zip(keys, row)) for row in rows]
|
||||
if name in CLEAR_ALL_BUT_SEED:
|
||||
data = [row for row in data if row["account"] not in protected]
|
||||
if not data:
|
||||
continue
|
||||
lines.append(f"-- {name}: {len(data)} 行")
|
||||
lines.extend(_rows_to_inserts(table, data))
|
||||
lines.append("")
|
||||
lines.extend(["SET FOREIGN_KEY_CHECKS=1;", ""])
|
||||
path.write_text("\n".join(lines), encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def _wipe(session, protected: tuple[str, ...]) -> dict[str, int]:
|
||||
from sqlalchemy import bindparam, text
|
||||
|
||||
# 自引用先拆掉:一条 DELETE 里同时删父亲和下属,InnoDB 会按行的先后拦外键,
|
||||
# 干脆先把 leader_id 与组织岗位指针清空,删起来就没有先后顺序的讲究。
|
||||
session.execute(text("UPDATE accounts SET leader_id = NULL WHERE leader_id IS NOT NULL"))
|
||||
session.execute(
|
||||
text("UPDATE accounts SET org_unit_id = NULL, position_id = NULL "
|
||||
"WHERE account IN :names").bindparams(bindparam("names", expanding=True)),
|
||||
{"names": list(protected)},
|
||||
)
|
||||
done = {}
|
||||
for name in CLEAR_TABLES:
|
||||
table = Base.metadata.tables[name]
|
||||
if name in CLEAR_ALL_BUT_SEED:
|
||||
result = session.execute(table.delete().where(table.c.account.notin_(protected)))
|
||||
else:
|
||||
result = session.execute(table.delete())
|
||||
done[name] = result.rowcount or 0
|
||||
|
||||
# KEEP 表里的迁移导入件最后删:业务行此时已经清光,perm_role_node /
|
||||
# project_visible_role 这些引用方不会再拦外键。
|
||||
# 顺序是先子表(approval_node)再父表(approval_flow)。
|
||||
imported = _imported_ids(session)
|
||||
for name in list(KEEP_DROP_IMPORTED_CHILDREN) + list(KEEP_DROP_IMPORTED):
|
||||
ids = imported.get(name)
|
||||
if not ids:
|
||||
continue
|
||||
table = Base.metadata.tables[name]
|
||||
done[name] = session.execute(
|
||||
table.delete().where(table.c.id.in_(ids))).rowcount or 0
|
||||
return done
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="清掉演示数据,回到刚初始化完的库")
|
||||
parser.add_argument("--apply", action="store_true", help="真的删;不加只干跑报数")
|
||||
parser.add_argument("--no-backup", action="store_true", help="跳过备份(不建议)")
|
||||
parser.add_argument("--restore", metavar="备份文件", help="把某次清理的备份回放进当前库")
|
||||
parser.add_argument("--i-know-this-is-production", action="store_true",
|
||||
help="明知是生产档还要删/回放(默认生产档拒绝执行)")
|
||||
args = parser.parse_args()
|
||||
|
||||
_classified_or_die()
|
||||
protected = _protected_accounts()
|
||||
|
||||
if args.restore:
|
||||
print(f"库 = {settings.database.name}@{settings.database.host}:{settings.database.port}"
|
||||
f" 档位 = {settings.env}")
|
||||
return _restore(Path(args.restore), args.apply)
|
||||
|
||||
if settings.is_production and not args.i_know_this_is_production:
|
||||
print(f"档位 {settings.env} 算上线环境,本脚本默认不碰。"
|
||||
"\n真要删再加 --i-know-this-is-production。")
|
||||
return 2
|
||||
|
||||
print(f"库 = {settings.database.name}@{settings.database.host}:{settings.database.port}"
|
||||
f" 档位 = {settings.env} 保留账号 = {', '.join(protected)}")
|
||||
print(f"保留的表 = {', '.join(KEEP_TABLES)}")
|
||||
|
||||
with SessionFactory()() as session:
|
||||
plan = _counts(session, protected)
|
||||
total = sum(plan.values())
|
||||
print("\n=== 要删的行 ===")
|
||||
for name, n in plan.items():
|
||||
if n:
|
||||
print(f" {name:24s} {n}")
|
||||
print(f" {'合计':22s} {total}")
|
||||
if not total:
|
||||
print("\n库已经是干净的,没东西要删。")
|
||||
return 0
|
||||
if not args.apply:
|
||||
print("\n干跑:什么都没动。确认无误再加 --apply。")
|
||||
return 0
|
||||
|
||||
if args.no_backup:
|
||||
print("\n按要求跳过备份——删完就没了。")
|
||||
else:
|
||||
path = _write_backup(session, protected)
|
||||
print(f"\n备份已写出:{path}({path.stat().st_size // 1024} KB)")
|
||||
|
||||
deleted = _wipe(session, protected)
|
||||
session.commit()
|
||||
print("\n=== 实际删除 ===")
|
||||
for name, n in deleted.items():
|
||||
if n:
|
||||
print(f" {name:24s} {n}")
|
||||
|
||||
after = _counts(session, protected)
|
||||
from sqlalchemy import func, select
|
||||
left = {t.name: session.execute(select(func.count()).select_from(t)).scalar() or 0
|
||||
for t in (Base.metadata.tables[n] for n in KEEP_TABLES)}
|
||||
left["accounts"] = session.execute(
|
||||
select(func.count()).select_from(Base.metadata.tables["accounts"])).scalar() or 0
|
||||
print("\n=== 清完之后 ===")
|
||||
print(f" 演示与业务数据残留 = {sum(after.values())}")
|
||||
print(f" 留下的 seed 账号 = {left['accounts']}(应为 {len(protected)}:"
|
||||
f"{'、'.join(protected)})")
|
||||
print(" 留下的基础数据 = " + ", ".join(f"{k}:{v}" for k, v in left.items() if v))
|
||||
print("\n组织与人要回来:统一身份同步页点一次全量同步即可。")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
|
|
@ -0,0 +1,145 @@
|
|||
#!/usr/bin/env python3
|
||||
"""由 SQLAlchemy 元数据生成 backend/sql/schema.sql(生产建库脚本)。
|
||||
|
||||
生产档把 auto_create_schema 关掉,建表交 DBA,跑的就是这份文件。既然不能手写,
|
||||
就不能靠"谁记得手动重新生成"来保证它和模型一致——所以这里既当生成器,也当校验器:
|
||||
|
||||
python3 scripts/gen_schema.py # 重新生成 sql/schema.sql
|
||||
python3 scripts/gen_schema.py --check # 只比对,不一致退出码 1(可挂 CI)
|
||||
|
||||
改完 app/models 记得重新生成,别手改 sql/schema.sql。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from sqlalchemy.dialects import mysql # noqa: E402
|
||||
from sqlalchemy.schema import CreateIndex, CreateTable # noqa: E402
|
||||
|
||||
import app.models # noqa: F401,E402 (触发模型注册)
|
||||
from app.models.base import Base # noqa: E402
|
||||
|
||||
OUT_PATH = Path(__file__).resolve().parents[1] / "sql" / "schema.sql"
|
||||
|
||||
# SQLAlchemy 编译 CreateTable 时已经带上了 CHARSET/COLLATE,这里只补 ENGINE,
|
||||
# 并把闭合括号后面的那一串选项统一成一种写法,免得两份 charset 打架
|
||||
# (MySQL 会把 "utf8mb4_unicode_ciCHARSET=utf8mb4" 当成一个非法 collation 名)。
|
||||
TABLE_OPTIONS = "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
|
||||
CLOSE_PAREN = re.compile(r"\n\)\s*[^\n]*$")
|
||||
LINE = "-- " + "=" * 72
|
||||
THIN = "-- " + "-" * 72
|
||||
|
||||
HEADER = f"""{LINE}
|
||||
-- 四算项目管理系统(fourcal-pms)生产建表脚本
|
||||
-- {THIN[3:]}
|
||||
-- 生成方式:backend/scripts/gen_schema.py 由 SQLAlchemy 元数据编译
|
||||
-- (CreateTable / CreateIndex + mysql dialect),因此这份 DDL 与
|
||||
-- backend/app/models 里的模型定义一一对应,不会手写走样。
|
||||
-- 改了模型请重新生成,不要手改本文件:
|
||||
-- python3 backend/scripts/gen_schema.py
|
||||
-- 比对是否走样(可挂 CI):
|
||||
-- python3 backend/scripts/gen_schema.py --check
|
||||
--
|
||||
-- 已验证:在 MySQL 8 上建空库逐条执行全部语句通过(脚本末尾有校验查询)。
|
||||
--
|
||||
-- 什么时候用:生产环境把 config.prod.toml 的 auto_create_schema 设为 false,
|
||||
-- 建表交 DBA,就跑这个文件。开发档(auto_create_schema=true)不需要它。
|
||||
--
|
||||
-- 用法:
|
||||
-- mysql -h <host> -P <port> -u <user> -p < backend/sql/schema.sql
|
||||
-- 或先自己建库再执行本文件(下面 CREATE DATABASE 默认注释掉,
|
||||
-- 避免 DBA 用高权限账号跑脚本时误建库)。
|
||||
--
|
||||
-- 注意
|
||||
-- 1. 本文件只建表,不种数据。基础数据(权限节点、角色、超管、演示流程)
|
||||
-- 由后端首次启动时的 seed 流程写入,只在库里没有对应记录时生效。
|
||||
-- 2. 老四算库 unis_fourcal_dev 不在本文件范围内,它是只读数据源,
|
||||
-- 导数用 scripts/migrate_legacy.py。
|
||||
-- 3. 字符集统一 utf8mb4 / utf8mb4_unicode_ci,金额列一律 DECIMAL,
|
||||
-- 不要用 FLOAT/DOUBLE,也不要用 VARCHAR 存金额。
|
||||
{LINE}
|
||||
"""
|
||||
|
||||
|
||||
def compile_ddl() -> tuple[list[str], list[str]]:
|
||||
"""返回 (建表语句, 建索引语句),顺序按外键依赖排好。"""
|
||||
dialect = mysql.dialect()
|
||||
tables: list[str] = []
|
||||
for table in Base.metadata.sorted_tables:
|
||||
ddl = str(CreateTable(table).compile(dialect=dialect)).strip().rstrip(";")
|
||||
tables.append(f"{CLOSE_PAREN.sub(chr(10) + ')', ddl, count=1)}{TABLE_OPTIONS};")
|
||||
|
||||
indexes: list[str] = []
|
||||
for table in Base.metadata.sorted_tables:
|
||||
for index in sorted(table.indexes, key=lambda item: item.name or ""):
|
||||
indexes.append(
|
||||
str(CreateIndex(index).compile(dialect=dialect)).rstrip().rstrip(";") + ";"
|
||||
)
|
||||
return tables, indexes
|
||||
|
||||
|
||||
def render() -> str:
|
||||
tables, indexes = compile_ddl()
|
||||
parts = [HEADER, ""]
|
||||
parts += [
|
||||
"-- CREATE DATABASE IF NOT EXISTS `fourcal_pms`",
|
||||
"-- DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;",
|
||||
"-- USE `fourcal_pms`;",
|
||||
"",
|
||||
"SET NAMES utf8mb4;",
|
||||
"SET FOREIGN_KEY_CHECKS = 0;",
|
||||
"",
|
||||
THIN,
|
||||
f"-- 建表({len(tables)} 张,按依赖顺序)",
|
||||
THIN,
|
||||
"",
|
||||
]
|
||||
for ddl in tables:
|
||||
parts += [ddl, ""]
|
||||
parts += [THIN, f"-- 索引({len(indexes)} 条)", THIN, ""]
|
||||
parts += [f"{ddl};" if not ddl.endswith(";") else ddl for ddl in indexes]
|
||||
parts += [
|
||||
"",
|
||||
"SET FOREIGN_KEY_CHECKS = 1;",
|
||||
"",
|
||||
LINE,
|
||||
f"-- 完。共 {len(tables)} 张表、{len(indexes)} 条索引语句。",
|
||||
"-- 建完可以抽查一条确认口径:",
|
||||
"-- SHOW CREATE TABLE project\\G",
|
||||
"-- SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE();",
|
||||
LINE,
|
||||
"",
|
||||
]
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="生成/校验生产建表脚本")
|
||||
parser.add_argument("--check", action="store_true",
|
||||
help="只比对现有 sql/schema.sql,不写文件")
|
||||
opts = parser.parse_args(argv)
|
||||
|
||||
content = render()
|
||||
tables, indexes = compile_ddl()
|
||||
|
||||
if opts.check:
|
||||
current = OUT_PATH.read_text(encoding="utf-8") if OUT_PATH.exists() else ""
|
||||
if current == content:
|
||||
print(f"schema.sql 与模型一致({len(tables)} 张表 / {len(indexes)} 条索引)")
|
||||
return 0
|
||||
print("schema.sql 已走样,请重新运行:python3 scripts/gen_schema.py", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
OUT_PATH.write_text(content, encoding="utf-8")
|
||||
print(f"已生成 {OUT_PATH}({len(tables)} 张表 / {len(indexes)} 条索引)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,926 @@
|
|||
-- ========================================================================
|
||||
-- 四算项目管理系统(fourcal-pms)生产建表脚本
|
||||
-- ------------------------------------------------------------------------
|
||||
-- 生成方式:backend/scripts/gen_schema.py 由 SQLAlchemy 元数据编译
|
||||
-- (CreateTable / CreateIndex + mysql dialect),因此这份 DDL 与
|
||||
-- backend/app/models 里的模型定义一一对应,不会手写走样。
|
||||
-- 改了模型请重新生成,不要手改本文件:
|
||||
-- python3 backend/scripts/gen_schema.py
|
||||
-- 比对是否走样(可挂 CI):
|
||||
-- python3 backend/scripts/gen_schema.py --check
|
||||
--
|
||||
-- 已验证:在 MySQL 8 上建空库逐条执行全部语句通过(脚本末尾有校验查询)。
|
||||
--
|
||||
-- 什么时候用:生产环境把 config.prod.toml 的 auto_create_schema 设为 false,
|
||||
-- 建表交 DBA,就跑这个文件。开发档(auto_create_schema=true)不需要它。
|
||||
--
|
||||
-- 用法:
|
||||
-- mysql -h <host> -P <port> -u <user> -p < backend/sql/schema.sql
|
||||
-- 或先自己建库再执行本文件(下面 CREATE DATABASE 默认注释掉,
|
||||
-- 避免 DBA 用高权限账号跑脚本时误建库)。
|
||||
--
|
||||
-- 注意
|
||||
-- 1. 本文件只建表,不种数据。基础数据(权限节点、角色、超管、演示流程)
|
||||
-- 由后端首次启动时的 seed 流程写入,只在库里没有对应记录时生效。
|
||||
-- 2. 老四算库 unis_fourcal_dev 不在本文件范围内,它是只读数据源,
|
||||
-- 导数用 scripts/migrate_legacy.py。
|
||||
-- 3. 字符集统一 utf8mb4 / utf8mb4_unicode_ci,金额列一律 DECIMAL,
|
||||
-- 不要用 FLOAT/DOUBLE,也不要用 VARCHAR 存金额。
|
||||
-- ========================================================================
|
||||
|
||||
|
||||
-- CREATE DATABASE IF NOT EXISTS `fourcal_pms`
|
||||
-- DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
-- USE `fourcal_pms`;
|
||||
|
||||
SET NAMES utf8mb4;
|
||||
SET FOREIGN_KEY_CHECKS = 0;
|
||||
|
||||
-- ------------------------------------------------------------------------
|
||||
-- 建表(40 张,按依赖顺序)
|
||||
-- ------------------------------------------------------------------------
|
||||
|
||||
CREATE TABLE approval_flow (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`key` VARCHAR(64) NOT NULL COMMENT '流程标识',
|
||||
name VARCHAR(128) NOT NULL,
|
||||
business_module VARCHAR(32) NOT NULL,
|
||||
version INTEGER NOT NULL DEFAULT '1',
|
||||
status VARCHAR(16) NOT NULL,
|
||||
match_json TEXT NOT NULL,
|
||||
priority INTEGER NOT NULL DEFAULT '100',
|
||||
allow_self_select TINYINT UNSIGNED NOT NULL DEFAULT '0',
|
||||
auto_skip_duplicate TINYINT UNSIGNED NOT NULL DEFAULT '1',
|
||||
remark VARCHAR(500) NOT NULL,
|
||||
created_at DATETIME(3) NOT NULL COMMENT '创建时间' DEFAULT CURRENT_TIMESTAMP(3),
|
||||
updated_at DATETIME(3) NOT NULL COMMENT '最后更新时间' DEFAULT CURRENT_TIMESTAMP(3),
|
||||
is_deleted TINYINT UNSIGNED NOT NULL COMMENT '软删除 0=有效 1=已删除' DEFAULT '0',
|
||||
PRIMARY KEY (id)
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE attachment (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
object_type VARCHAR(64) NOT NULL COMMENT 'estimate/budget/contract/approval…',
|
||||
object_id BIGINT UNSIGNED NOT NULL DEFAULT '0',
|
||||
field VARCHAR(64) NOT NULL COMMENT '挂在哪个字段上',
|
||||
file_name VARCHAR(500) NOT NULL,
|
||||
stored_name VARCHAR(500) NOT NULL,
|
||||
url VARCHAR(1000) NOT NULL,
|
||||
size BIGINT UNSIGNED NOT NULL DEFAULT '0',
|
||||
ext VARCHAR(16) NOT NULL,
|
||||
uploader_id BIGINT UNSIGNED,
|
||||
uploader_name VARCHAR(100) NOT NULL,
|
||||
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
is_deleted TINYINT UNSIGNED NOT NULL COMMENT '软删除 0=有效 1=已删除' DEFAULT '0',
|
||||
PRIMARY KEY (id)
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE calc_snapshot (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
module VARCHAR(16) NOT NULL,
|
||||
project_id BIGINT UNSIGNED NOT NULL,
|
||||
revision_id BIGINT UNSIGNED NOT NULL,
|
||||
calc_version VARCHAR(32) NOT NULL,
|
||||
`trigger` VARCHAR(16) NOT NULL,
|
||||
payload_json TEXT NOT NULL,
|
||||
validation_json TEXT NOT NULL,
|
||||
account_id BIGINT UNSIGNED,
|
||||
account_name VARCHAR(100) NOT NULL,
|
||||
trace_id VARCHAR(64) NOT NULL,
|
||||
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (id)
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE dict_type (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
code VARCHAR(64) NOT NULL COMMENT '字典编码,前后端按它取值(camelCase)',
|
||||
name VARCHAR(128) NOT NULL COMMENT '显示名称',
|
||||
`group` VARCHAR(64) NOT NULL COMMENT '维护页里的分组' DEFAULT 'common',
|
||||
value_type VARCHAR(8) NOT NULL COMMENT '取值类型 string/int,决定下发时要不要转成数字' DEFAULT 'string',
|
||||
source VARCHAR(16) NOT NULL COMMENT 'system=代码枚举同步,value 不可改;custom=界面自建' DEFAULT 'custom',
|
||||
enabled TINYINT UNSIGNED NOT NULL COMMENT '停用后下拉框取到空列表' DEFAULT '1',
|
||||
remark VARCHAR(500) NOT NULL,
|
||||
created_at DATETIME(3) NOT NULL COMMENT '创建时间' DEFAULT CURRENT_TIMESTAMP(3),
|
||||
updated_at DATETIME(3) NOT NULL COMMENT '最后更新时间' DEFAULT CURRENT_TIMESTAMP(3),
|
||||
is_deleted TINYINT UNSIGNED NOT NULL COMMENT '软删除 0=有效 1=已删除' DEFAULT '0',
|
||||
PRIMARY KEY (id),
|
||||
CONSTRAINT uk_dict_type_code UNIQUE (code)
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE hub_sync_run (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
`trigger` VARCHAR(16) NOT NULL COMMENT 'manual=手动 scheduled=定时',
|
||||
status VARCHAR(16) NOT NULL COMMENT 'running/success/partial/failed',
|
||||
started_at DATETIME(3) NOT NULL,
|
||||
finished_at DATETIME(3),
|
||||
org_total INTEGER NOT NULL DEFAULT '0',
|
||||
org_created INTEGER NOT NULL DEFAULT '0',
|
||||
org_updated INTEGER NOT NULL DEFAULT '0',
|
||||
org_disabled INTEGER NOT NULL DEFAULT '0',
|
||||
account_total INTEGER NOT NULL DEFAULT '0',
|
||||
account_created INTEGER NOT NULL DEFAULT '0',
|
||||
account_updated INTEGER NOT NULL DEFAULT '0',
|
||||
account_disabled INTEGER NOT NULL DEFAULT '0',
|
||||
skipped_local INTEGER NOT NULL COMMENT '因为是本地账号而没动的条数' DEFAULT '0',
|
||||
cursor_after INTEGER NOT NULL COMMENT '本次同步后的目录游标;0=不是增量批次' DEFAULT '0',
|
||||
steps_json TEXT NOT NULL,
|
||||
error TEXT NOT NULL,
|
||||
PRIMARY KEY (id)
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE login_log (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
account VARCHAR(190) NOT NULL,
|
||||
account_id BIGINT UNSIGNED,
|
||||
success TINYINT UNSIGNED NOT NULL,
|
||||
reason VARCHAR(255) NOT NULL,
|
||||
ip VARCHAR(64) NOT NULL,
|
||||
user_agent VARCHAR(500) NOT NULL,
|
||||
mode VARCHAR(16) NOT NULL COMMENT 'password=口令 hub=统一身份 sso=免登',
|
||||
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (id)
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE operation_log (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
account_id BIGINT UNSIGNED,
|
||||
account_name VARCHAR(100) NOT NULL,
|
||||
action VARCHAR(64) NOT NULL COMMENT 'create/update/delete/approve…',
|
||||
object_type VARCHAR(64) NOT NULL,
|
||||
object_id VARCHAR(64) NOT NULL,
|
||||
object_name VARCHAR(255) NOT NULL,
|
||||
detail_json TEXT NOT NULL COMMENT '字段级变更前后值',
|
||||
ip VARCHAR(64) NOT NULL,
|
||||
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (id)
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE org_position (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
code VARCHAR(64) NOT NULL COMMENT '岗位编码,流程按它解析审批人',
|
||||
name VARCHAR(128) NOT NULL COMMENT '岗位名称',
|
||||
`rank` INTEGER NOT NULL COMMENT '岗位级别,数字越小级别越高,用于『升级到上级审批』' DEFAULT '100',
|
||||
order_number INTEGER NOT NULL DEFAULT '0',
|
||||
enabled TINYINT UNSIGNED NOT NULL DEFAULT '1',
|
||||
remark VARCHAR(500) NOT NULL,
|
||||
created_at DATETIME(3) NOT NULL COMMENT '创建时间' DEFAULT CURRENT_TIMESTAMP(3),
|
||||
updated_at DATETIME(3) NOT NULL COMMENT '最后更新时间' DEFAULT CURRENT_TIMESTAMP(3),
|
||||
is_deleted TINYINT UNSIGNED NOT NULL COMMENT '软删除 0=有效 1=已删除' DEFAULT '0',
|
||||
PRIMARY KEY (id),
|
||||
CONSTRAINT uk_org_position_code UNIQUE (code)
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE org_unit (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
name VARCHAR(255) NOT NULL COMMENT '部门名称',
|
||||
code VARCHAR(190) NOT NULL COMMENT '组织编码(Hub 的 code),本地自建可留空' DEFAULT '',
|
||||
short_name VARCHAR(255) NOT NULL,
|
||||
parent_id BIGINT UNSIGNED,
|
||||
path VARCHAR(1024) NOT NULL,
|
||||
level INTEGER NOT NULL DEFAULT '1',
|
||||
order_number INTEGER NOT NULL DEFAULT '0',
|
||||
status TINYINT UNSIGNED NOT NULL COMMENT '1=正常 0=停用 2=待审核 3=已拒绝' DEFAULT '1',
|
||||
hub_org_id BIGINT UNSIGNED COMMENT 'Hub 组织主键;非空时 Hub 侧接管名称/编码/状态/上级',
|
||||
manager_id BIGINT UNSIGNED COMMENT '部门负责人的 accounts.id',
|
||||
synced_at DATETIME(3),
|
||||
remark VARCHAR(500) NOT NULL,
|
||||
created_at DATETIME(3) NOT NULL COMMENT '创建时间' DEFAULT CURRENT_TIMESTAMP(3),
|
||||
updated_at DATETIME(3) NOT NULL COMMENT '最后更新时间' DEFAULT CURRENT_TIMESTAMP(3),
|
||||
is_deleted TINYINT UNSIGNED NOT NULL COMMENT '软删除 0=有效 1=已删除' DEFAULT '0',
|
||||
PRIMARY KEY (id),
|
||||
FOREIGN KEY(parent_id) REFERENCES org_unit (id) ON DELETE SET NULL
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE perm_data_policy (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
name VARCHAR(128) NOT NULL,
|
||||
module VARCHAR(64) NOT NULL COMMENT '业务模块:project/estimate/budget/settlement/final/approval',
|
||||
subject_type VARCHAR(16) NOT NULL,
|
||||
subject_id BIGINT UNSIGNED NOT NULL DEFAULT '0',
|
||||
effect VARCHAR(8) NOT NULL,
|
||||
scope_type VARCHAR(32) NOT NULL,
|
||||
target_ids_json TEXT NOT NULL,
|
||||
include_children TINYINT UNSIGNED NOT NULL DEFAULT '1',
|
||||
conditions_json TEXT NOT NULL,
|
||||
priority INTEGER NOT NULL DEFAULT '100',
|
||||
enabled TINYINT UNSIGNED NOT NULL DEFAULT '1',
|
||||
valid_from VARCHAR(32) NOT NULL,
|
||||
valid_to VARCHAR(32) NOT NULL,
|
||||
remark VARCHAR(500) NOT NULL,
|
||||
created_at DATETIME(3) NOT NULL COMMENT '创建时间' DEFAULT CURRENT_TIMESTAMP(3),
|
||||
updated_at DATETIME(3) NOT NULL COMMENT '最后更新时间' DEFAULT CURRENT_TIMESTAMP(3),
|
||||
is_deleted TINYINT UNSIGNED NOT NULL COMMENT '软删除 0=有效 1=已删除' DEFAULT '0',
|
||||
PRIMARY KEY (id)
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE perm_node (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
code VARCHAR(128) NOT NULL COMMENT '权限码,前后端共用',
|
||||
name VARCHAR(128) NOT NULL COMMENT '显示名称',
|
||||
kind VARCHAR(16) NOT NULL,
|
||||
parent_id BIGINT UNSIGNED NOT NULL DEFAULT '0',
|
||||
path VARCHAR(255) NOT NULL COMMENT '前端路由',
|
||||
icon VARCHAR(64) NOT NULL,
|
||||
module VARCHAR(64) NOT NULL COMMENT '所属业务模块,数据权限按它匹配',
|
||||
sort INTEGER NOT NULL DEFAULT '100',
|
||||
visible TINYINT UNSIGNED NOT NULL COMMENT '菜单是否显示(隐藏但仍可授权时用)' DEFAULT '1',
|
||||
enabled TINYINT UNSIGNED NOT NULL DEFAULT '1',
|
||||
remark VARCHAR(500) NOT NULL,
|
||||
created_at VARCHAR(32) NOT NULL DEFAULT '',
|
||||
is_deleted TINYINT UNSIGNED NOT NULL COMMENT '软删除 0=有效 1=已删除' DEFAULT '0',
|
||||
PRIMARY KEY (id),
|
||||
CONSTRAINT uk_perm_node_code UNIQUE (code)
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE perm_role (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
code VARCHAR(64) NOT NULL,
|
||||
name VARCHAR(128) NOT NULL,
|
||||
builtin TINYINT UNSIGNED NOT NULL DEFAULT '0',
|
||||
enabled TINYINT UNSIGNED NOT NULL DEFAULT '1',
|
||||
order_number INTEGER NOT NULL DEFAULT '100',
|
||||
remark VARCHAR(500) NOT NULL,
|
||||
created_at DATETIME(3) NOT NULL COMMENT '创建时间' DEFAULT CURRENT_TIMESTAMP(3),
|
||||
updated_at DATETIME(3) NOT NULL COMMENT '最后更新时间' DEFAULT CURRENT_TIMESTAMP(3),
|
||||
is_deleted TINYINT UNSIGNED NOT NULL COMMENT '软删除 0=有效 1=已删除' DEFAULT '0',
|
||||
PRIMARY KEY (id),
|
||||
CONSTRAINT uk_perm_role_code UNIQUE (code)
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE sso_handoff (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
code_hash VARCHAR(64) NOT NULL COMMENT '短码 SHA-256,明文只在 302 的片段里出现过一次',
|
||||
bind_hash VARCHAR(64) NOT NULL COMMENT 'HttpOnly 兑换串的 SHA-256,缺它这条短码就是废纸',
|
||||
account_id BIGINT UNSIGNED NOT NULL COMMENT '验票认出来的本地账号',
|
||||
redirect VARCHAR(255) NOT NULL COMMENT '免登进去要落到哪一页',
|
||||
detail VARCHAR(255) NOT NULL COMMENT '写进登录日志的说明',
|
||||
expires_at DATETIME(3) NOT NULL,
|
||||
used_at DATETIME(3),
|
||||
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE (code_hash)
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE system_config (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
code VARCHAR(128) NOT NULL,
|
||||
name VARCHAR(128) NOT NULL,
|
||||
value TEXT NOT NULL,
|
||||
value_type VARCHAR(16) NOT NULL COMMENT 'string/number/bool/json',
|
||||
`group` VARCHAR(64) NOT NULL,
|
||||
editable TINYINT UNSIGNED NOT NULL DEFAULT '1',
|
||||
remark VARCHAR(500) NOT NULL,
|
||||
updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (id),
|
||||
CONSTRAINT uk_system_config_code UNIQUE (code)
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE accounts (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
account VARCHAR(190) NOT NULL COMMENT '登录账号',
|
||||
password_hash VARCHAR(255) NOT NULL,
|
||||
display_name VARCHAR(100) NOT NULL COMMENT '姓名' DEFAULT '',
|
||||
emp_code VARCHAR(64) NOT NULL COMMENT '工号' DEFAULT '',
|
||||
telephone VARCHAR(30) NOT NULL DEFAULT '',
|
||||
email VARCHAR(190) NOT NULL DEFAULT '',
|
||||
avatar_url VARCHAR(500) NOT NULL DEFAULT '',
|
||||
org_unit_id BIGINT UNSIGNED,
|
||||
position_id BIGINT UNSIGNED,
|
||||
leader_id BIGINT UNSIGNED,
|
||||
is_system_admin TINYINT UNSIGNED NOT NULL DEFAULT '0',
|
||||
status TINYINT UNSIGNED NOT NULL COMMENT '1=正常 0=停用 2=待审核 3=已拒绝' DEFAULT '1',
|
||||
source VARCHAR(16) NOT NULL COMMENT 'local=本地建号 hub=统一身份同步' DEFAULT 'local',
|
||||
hub_user_id BIGINT UNSIGNED,
|
||||
hub_synced_at DATETIME(3),
|
||||
login_failed_count INTEGER NOT NULL DEFAULT '0',
|
||||
locked_until DATETIME(3),
|
||||
last_login_at DATETIME(3),
|
||||
last_login_ip VARCHAR(64) NOT NULL,
|
||||
password_updated_at DATETIME(3),
|
||||
work_location VARCHAR(255) NOT NULL,
|
||||
remark VARCHAR(500) NOT NULL COMMENT '账号说明',
|
||||
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
|
||||
is_deleted TINYINT UNSIGNED NOT NULL COMMENT '软删除 0=有效 1=已删除' DEFAULT '0',
|
||||
PRIMARY KEY (id),
|
||||
CONSTRAINT uk_accounts_account UNIQUE (account),
|
||||
FOREIGN KEY(org_unit_id) REFERENCES org_unit (id) ON DELETE SET NULL,
|
||||
FOREIGN KEY(position_id) REFERENCES org_position (id) ON DELETE SET NULL,
|
||||
FOREIGN KEY(leader_id) REFERENCES accounts (id) ON DELETE SET NULL
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE approval_node (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
flow_id BIGINT UNSIGNED NOT NULL,
|
||||
node_key VARCHAR(64) NOT NULL,
|
||||
name VARCHAR(128) NOT NULL,
|
||||
node_type VARCHAR(16) NOT NULL,
|
||||
order_number INTEGER NOT NULL DEFAULT '100',
|
||||
sign_type VARCHAR(16) NOT NULL,
|
||||
candidates_json TEXT NOT NULL,
|
||||
empty_strategy VARCHAR(16) NOT NULL DEFAULT 'admin',
|
||||
condition_json TEXT NOT NULL,
|
||||
next_node_key VARCHAR(64) NOT NULL,
|
||||
reject_to VARCHAR(64) NOT NULL,
|
||||
rollback_keys_json TEXT NOT NULL,
|
||||
comment_required TINYINT UNSIGNED NOT NULL DEFAULT '0',
|
||||
reject_comment_required TINYINT UNSIGNED NOT NULL DEFAULT '1',
|
||||
timeout_hours INTEGER NOT NULL DEFAULT '0',
|
||||
timeout_action VARCHAR(16) NOT NULL DEFAULT 'none',
|
||||
enabled TINYINT UNSIGNED NOT NULL DEFAULT '1',
|
||||
remark VARCHAR(500) NOT NULL,
|
||||
is_deleted TINYINT UNSIGNED NOT NULL COMMENT '软删除 0=有效 1=已删除' DEFAULT '0',
|
||||
PRIMARY KEY (id),
|
||||
CONSTRAINT uk_approval_node_key UNIQUE (flow_id, node_key),
|
||||
FOREIGN KEY(flow_id) REFERENCES approval_flow (id) ON DELETE CASCADE
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE dict_item (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
dict_type_id BIGINT UNSIGNED NOT NULL COMMENT '所属字典类型',
|
||||
value VARCHAR(128) NOT NULL COMMENT '存给后端的值',
|
||||
label VARCHAR(128) NOT NULL COMMENT '给人看的名字',
|
||||
sort INTEGER NOT NULL COMMENT '越小越靠前' DEFAULT '100',
|
||||
enabled TINYINT UNSIGNED NOT NULL COMMENT '停用即从下拉框里摘掉,历史数据不受影响' DEFAULT '1',
|
||||
tag VARCHAR(16) NOT NULL COMMENT '状态色(success/warning/danger/info/gray),给 StatusBadge 用' DEFAULT '',
|
||||
builtin TINYINT UNSIGNED NOT NULL COMMENT '代码枚举同步来的条目,value 不可改' DEFAULT '0',
|
||||
remark VARCHAR(500) NOT NULL COMMENT '备注,界面上以下拉提示语展示',
|
||||
created_at DATETIME(3) NOT NULL COMMENT '创建时间' DEFAULT CURRENT_TIMESTAMP(3),
|
||||
updated_at DATETIME(3) NOT NULL COMMENT '最后更新时间' DEFAULT CURRENT_TIMESTAMP(3),
|
||||
is_deleted TINYINT UNSIGNED NOT NULL COMMENT '软删除 0=有效 1=已删除' DEFAULT '0',
|
||||
PRIMARY KEY (id),
|
||||
CONSTRAINT uk_dict_item_type_value UNIQUE (dict_type_id, value),
|
||||
FOREIGN KEY(dict_type_id) REFERENCES dict_type (id) ON DELETE CASCADE
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE perm_field_scope (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
module VARCHAR(64) NOT NULL,
|
||||
field VARCHAR(64) NOT NULL,
|
||||
role_id BIGINT UNSIGNED NOT NULL,
|
||||
mode VARCHAR(16) NOT NULL COMMENT 'hidden=不返回 masked=打码 readonly=只读' DEFAULT 'hidden',
|
||||
PRIMARY KEY (id),
|
||||
CONSTRAINT uk_perm_field_scope UNIQUE (module, field, role_id),
|
||||
FOREIGN KEY(role_id) REFERENCES perm_role (id) ON DELETE CASCADE
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE perm_role_node (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
role_id BIGINT UNSIGNED NOT NULL,
|
||||
node_id BIGINT UNSIGNED NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
CONSTRAINT uk_perm_role_node UNIQUE (role_id, node_id),
|
||||
FOREIGN KEY(role_id) REFERENCES perm_role (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(node_id) REFERENCES perm_node (id) ON DELETE CASCADE
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE account_identity (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
account_id BIGINT UNSIGNED NOT NULL,
|
||||
org_unit_id BIGINT UNSIGNED NOT NULL,
|
||||
position_id BIGINT UNSIGNED,
|
||||
is_default TINYINT UNSIGNED NOT NULL COMMENT '是否默认身份' DEFAULT '0',
|
||||
kind VARCHAR(16) NOT NULL COMMENT 'primary=主岗 concurrent=兼岗' DEFAULT 'primary',
|
||||
created_at DATETIME(3) NOT NULL COMMENT '创建时间' DEFAULT CURRENT_TIMESTAMP(3),
|
||||
updated_at DATETIME(3) NOT NULL COMMENT '最后更新时间' DEFAULT CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (id),
|
||||
CONSTRAINT uk_account_identity UNIQUE (account_id, org_unit_id),
|
||||
FOREIGN KEY(account_id) REFERENCES accounts (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(org_unit_id) REFERENCES org_unit (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(position_id) REFERENCES org_position (id) ON DELETE SET NULL
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE approval_delegate (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
from_id BIGINT UNSIGNED NOT NULL,
|
||||
from_name VARCHAR(100) NOT NULL,
|
||||
to_id BIGINT UNSIGNED NOT NULL,
|
||||
to_name VARCHAR(100) NOT NULL,
|
||||
modules_json TEXT NOT NULL,
|
||||
valid_from DATETIME(3),
|
||||
valid_to DATETIME(3),
|
||||
enabled TINYINT UNSIGNED NOT NULL DEFAULT '1',
|
||||
reason VARCHAR(500) NOT NULL,
|
||||
created_at DATETIME(3) NOT NULL COMMENT '创建时间' DEFAULT CURRENT_TIMESTAMP(3),
|
||||
updated_at DATETIME(3) NOT NULL COMMENT '最后更新时间' DEFAULT CURRENT_TIMESTAMP(3),
|
||||
is_deleted TINYINT UNSIGNED NOT NULL COMMENT '软删除 0=有效 1=已删除' DEFAULT '0',
|
||||
PRIMARY KEY (id),
|
||||
FOREIGN KEY(from_id) REFERENCES accounts (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(to_id) REFERENCES accounts (id) ON DELETE CASCADE
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE approval_instance (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
flow_id BIGINT UNSIGNED NOT NULL,
|
||||
flow_key VARCHAR(64) NOT NULL,
|
||||
flow_name VARCHAR(128) NOT NULL,
|
||||
flow_version INTEGER NOT NULL,
|
||||
business_module VARCHAR(32) NOT NULL,
|
||||
project_id BIGINT UNSIGNED NOT NULL,
|
||||
project_name TEXT NOT NULL,
|
||||
revision_id BIGINT UNSIGNED,
|
||||
snapshot_id BIGINT UNSIGNED,
|
||||
status VARCHAR(16) NOT NULL,
|
||||
current_node_key VARCHAR(64) NOT NULL,
|
||||
current_node_name VARCHAR(128) NOT NULL,
|
||||
submitter_id BIGINT UNSIGNED NOT NULL,
|
||||
submitter_name VARCHAR(100) NOT NULL,
|
||||
submitter_org_id BIGINT UNSIGNED,
|
||||
variables_json TEXT NOT NULL,
|
||||
runtime_json TEXT NOT NULL,
|
||||
submitted_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
finished_at DATETIME(3),
|
||||
previous_instance_id BIGINT UNSIGNED,
|
||||
PRIMARY KEY (id),
|
||||
FOREIGN KEY(submitter_id) REFERENCES accounts (id) ON DELETE RESTRICT
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE perm_account_role (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
account_id BIGINT UNSIGNED NOT NULL,
|
||||
role_id BIGINT UNSIGNED NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
CONSTRAINT uk_perm_account_role UNIQUE (account_id, role_id),
|
||||
FOREIGN KEY(account_id) REFERENCES accounts (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(role_id) REFERENCES perm_role (id) ON DELETE CASCADE
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE project (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
project_no VARCHAR(64) NOT NULL COMMENT '项目编号',
|
||||
name TEXT NOT NULL COMMENT '项目名称',
|
||||
other_name VARCHAR(255) NOT NULL COMMENT '项目简称',
|
||||
type INTEGER NOT NULL COMMENT '项目类型',
|
||||
creator_id BIGINT UNSIGNED NOT NULL,
|
||||
creator_name VARCHAR(100) NOT NULL,
|
||||
org_unit_id BIGINT UNSIGNED,
|
||||
org_unit_name VARCHAR(255) NOT NULL,
|
||||
principal VARCHAR(100) NOT NULL COMMENT '项目负责人姓名',
|
||||
principal_id BIGINT UNSIGNED COMMENT '项目负责人账号',
|
||||
stage INTEGER NOT NULL,
|
||||
stage_remark TEXT NOT NULL COMMENT '当前进度描述',
|
||||
next_plan TEXT NOT NULL COMMENT '下一步计划',
|
||||
customer TEXT NOT NULL,
|
||||
terminal_customer TEXT NOT NULL,
|
||||
plan_start DATE COMMENT '计划开始(精确到月)',
|
||||
plan_end DATE COMMENT '计划结束(精确到月)',
|
||||
contract_time DATETIME(3),
|
||||
bids_time DATETIME(3),
|
||||
underwritten_mode INTEGER COMMENT '垫资模式',
|
||||
cooperate_type INTEGER,
|
||||
collaborator VARCHAR(255) NOT NULL COMMENT '合作对象',
|
||||
collaborator_attachment VARCHAR(500) NOT NULL,
|
||||
certainty INTEGER COMMENT '项目把握度',
|
||||
is_second INTEGER COMMENT '是否二次合作',
|
||||
sign_type INTEGER COMMENT '签单方式',
|
||||
resolve_plan INTEGER COMMENT '解决方案',
|
||||
industry_scene INTEGER NOT NULL COMMENT '行业场景',
|
||||
industry_scene_desc VARCHAR(255) NOT NULL,
|
||||
main_contract_collection_terms TEXT NOT NULL,
|
||||
main_contract_resolve_plan TEXT NOT NULL,
|
||||
calculation_collection TEXT NOT NULL COMMENT '计收计划',
|
||||
value_risk TEXT NOT NULL COMMENT '价值及风险',
|
||||
huazhi_amount NUMERIC(18, 4) NOT NULL,
|
||||
huizhi_amount NUMERIC(18, 4) NOT NULL,
|
||||
h3c_amount NUMERIC(18, 4) NOT NULL,
|
||||
other_product_amount NUMERIC(18, 4) NOT NULL,
|
||||
contract_amount NUMERIC(18, 4) NOT NULL,
|
||||
gross_profit_a NUMERIC(18, 4) NOT NULL,
|
||||
gross_profit_a_rate NUMERIC(18, 6) NOT NULL,
|
||||
gross_profit NUMERIC(18, 4) NOT NULL,
|
||||
gross_profit_rate NUMERIC(18, 6) NOT NULL,
|
||||
contribution_profit NUMERIC(18, 4) NOT NULL,
|
||||
contribution_profit_rate NUMERIC(18, 6) NOT NULL,
|
||||
advance_peak_amount NUMERIC(18, 4) NOT NULL,
|
||||
advance_interest_amount NUMERIC(18, 4) NOT NULL,
|
||||
advance_interest_rate NUMERIC(18, 6) NOT NULL COMMENT '垫资年利率',
|
||||
advance_plan_total NUMERIC(18, 4) NOT NULL COMMENT '各月垫资计划之和(老''峰值金额''的真实含义)',
|
||||
advance_peak_month VARCHAR(16) NOT NULL COMMENT '单月垫资最大值所在月份',
|
||||
advance_peak_value NUMERIC(18, 4) NOT NULL COMMENT '单月垫资最大值',
|
||||
calc_version VARCHAR(32) NOT NULL COMMENT '投影所属计算规则版本',
|
||||
calc_snapshot_id BIGINT UNSIGNED COMMENT '投影来源快照',
|
||||
calc_at DATETIME(3),
|
||||
deleted_at DATETIME(3) COMMENT '删除时间',
|
||||
deleted_by_id BIGINT UNSIGNED COMMENT '删除人账号',
|
||||
deleted_by_name VARCHAR(100) NOT NULL COMMENT '删除人姓名',
|
||||
delete_reason VARCHAR(500) NOT NULL COMMENT '删除原因',
|
||||
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
|
||||
is_deleted TINYINT UNSIGNED NOT NULL COMMENT '软删除 0=有效 1=已删除' DEFAULT '0',
|
||||
PRIMARY KEY (id),
|
||||
FOREIGN KEY(creator_id) REFERENCES accounts (id) ON DELETE RESTRICT,
|
||||
FOREIGN KEY(org_unit_id) REFERENCES org_unit (id) ON DELETE SET NULL
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE approval_record (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
instance_id BIGINT UNSIGNED NOT NULL,
|
||||
project_id BIGINT UNSIGNED NOT NULL,
|
||||
business_module VARCHAR(32) NOT NULL,
|
||||
node_key VARCHAR(64) NOT NULL,
|
||||
node_name VARCHAR(128) NOT NULL,
|
||||
action VARCHAR(16) NOT NULL,
|
||||
action_label VARCHAR(32) NOT NULL,
|
||||
operator_id BIGINT UNSIGNED,
|
||||
operator_name VARCHAR(100) NOT NULL,
|
||||
target_names VARCHAR(1000) NOT NULL,
|
||||
comment TEXT NOT NULL,
|
||||
rollback_to_node VARCHAR(64) NOT NULL,
|
||||
rollback_record_id BIGINT UNSIGNED NOT NULL DEFAULT '0',
|
||||
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (id),
|
||||
FOREIGN KEY(instance_id) REFERENCES approval_instance (id) ON DELETE CASCADE
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE approval_task (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
instance_id BIGINT UNSIGNED NOT NULL,
|
||||
node_key VARCHAR(64) NOT NULL,
|
||||
node_name VARCHAR(128) NOT NULL,
|
||||
sign_type VARCHAR(16) NOT NULL,
|
||||
assignee_id BIGINT UNSIGNED NOT NULL,
|
||||
assignee_name VARCHAR(100) NOT NULL,
|
||||
origin_assignee_id BIGINT UNSIGNED,
|
||||
status VARCHAR(16) NOT NULL,
|
||||
order_in_node INTEGER NOT NULL COMMENT '依次审批时的顺序号' DEFAULT '100',
|
||||
due_at DATETIME(3),
|
||||
acted_at DATETIME(3),
|
||||
action VARCHAR(16) NOT NULL,
|
||||
comment TEXT NOT NULL,
|
||||
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (id),
|
||||
FOREIGN KEY(instance_id) REFERENCES approval_instance (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(assignee_id) REFERENCES accounts (id) ON DELETE RESTRICT
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE biz_revision (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
module VARCHAR(16) NOT NULL COMMENT 'estimate/budget',
|
||||
project_id BIGINT UNSIGNED NOT NULL,
|
||||
version INTEGER NOT NULL DEFAULT '1',
|
||||
status VARCHAR(16) NOT NULL,
|
||||
title VARCHAR(255) NOT NULL COMMENT '版本说明',
|
||||
based_on_id BIGINT UNSIGNED,
|
||||
snapshot_id BIGINT UNSIGNED COMMENT '最近一次计算快照',
|
||||
calc_version VARCHAR(32) NOT NULL,
|
||||
freeze_json TEXT NOT NULL,
|
||||
creator_id BIGINT UNSIGNED NOT NULL,
|
||||
creator_name VARCHAR(100) NOT NULL,
|
||||
submitted_at DATETIME(3),
|
||||
decided_at DATETIME(3),
|
||||
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
|
||||
is_deleted TINYINT UNSIGNED NOT NULL COMMENT '软删除 0=有效 1=已删除' DEFAULT '0',
|
||||
PRIMARY KEY (id),
|
||||
CONSTRAINT uk_biz_revision_version UNIQUE (module, project_id, version),
|
||||
FOREIGN KEY(project_id) REFERENCES project (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(creator_id) REFERENCES accounts (id) ON DELETE RESTRICT
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE project_member (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
project_id BIGINT UNSIGNED NOT NULL,
|
||||
account_id BIGINT UNSIGNED NOT NULL,
|
||||
account_name VARCHAR(100) NOT NULL,
|
||||
member_role VARCHAR(24) NOT NULL,
|
||||
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (id),
|
||||
CONSTRAINT uk_project_member UNIQUE (project_id, account_id),
|
||||
FOREIGN KEY(project_id) REFERENCES project (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(account_id) REFERENCES accounts (id) ON DELETE CASCADE
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE project_stage_log (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
project_id BIGINT UNSIGNED NOT NULL,
|
||||
stage INTEGER NOT NULL,
|
||||
stage_label VARCHAR(64) NOT NULL,
|
||||
account_id BIGINT UNSIGNED,
|
||||
account_name VARCHAR(100) NOT NULL,
|
||||
remark VARCHAR(2000) NOT NULL,
|
||||
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (id),
|
||||
FOREIGN KEY(project_id) REFERENCES project (id) ON DELETE CASCADE
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE project_visible_role (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
project_id BIGINT UNSIGNED NOT NULL,
|
||||
role_id BIGINT UNSIGNED NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
CONSTRAINT uk_project_visible_role UNIQUE (project_id, role_id),
|
||||
FOREIGN KEY(project_id) REFERENCES project (id) ON DELETE CASCADE,
|
||||
FOREIGN KEY(role_id) REFERENCES perm_role (id) ON DELETE CASCADE
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE budget_fund_month (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
revision_id BIGINT UNSIGNED NOT NULL,
|
||||
project_id BIGINT UNSIGNED NOT NULL,
|
||||
month VARCHAR(8) NOT NULL COMMENT 'YYYY-MM',
|
||||
device_cost NUMERIC(18, 4) NOT NULL COMMENT '设备支出',
|
||||
construction_cost NUMERIC(18, 4) NOT NULL COMMENT '施工支出',
|
||||
service_cost NUMERIC(18, 4) NOT NULL COMMENT '服务支出',
|
||||
other_cost NUMERIC(18, 4) NOT NULL COMMENT '其他支出',
|
||||
manage_cost NUMERIC(18, 4) NOT NULL COMMENT '项目管理支出',
|
||||
earnest_cost NUMERIC(18, 4) NOT NULL COMMENT '保证金支出',
|
||||
sale_income NUMERIC(18, 4) NOT NULL COMMENT '销售收款',
|
||||
earnest_income NUMERIC(18, 4) NOT NULL COMMENT '保证金收入',
|
||||
interest_rate NUMERIC(18, 6) NOT NULL COMMENT '当月使用的年利率快照',
|
||||
opening_balance NUMERIC(18, 4) NOT NULL COMMENT '期初余额,首月一般为 0',
|
||||
manual_override TINYINT UNSIGNED NOT NULL DEFAULT '0',
|
||||
total_cost NUMERIC(18, 4) NOT NULL,
|
||||
total_income NUMERIC(18, 4) NOT NULL,
|
||||
balance NUMERIC(18, 4) NOT NULL COMMENT '月末资金余额',
|
||||
underwritten_plan NUMERIC(18, 4) NOT NULL COMMENT '垫资计划',
|
||||
repayment_plan NUMERIC(18, 4) NOT NULL COMMENT '还款计划',
|
||||
capital_interest NUMERIC(18, 4) NOT NULL COMMENT '资金利息',
|
||||
calc_version VARCHAR(32) NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
CONSTRAINT uk_budget_fund_month UNIQUE (revision_id, month),
|
||||
FOREIGN KEY(revision_id) REFERENCES biz_revision (id) ON DELETE CASCADE
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE budget_income_line (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
revision_id BIGINT UNSIGNED NOT NULL,
|
||||
project_id BIGINT UNSIGNED NOT NULL,
|
||||
income_type INTEGER NOT NULL COMMENT '1设备 2工程 3服务',
|
||||
name VARCHAR(255) NOT NULL COMMENT '产品名称',
|
||||
spec VARCHAR(255) NOT NULL COMMENT '规格型号',
|
||||
param TEXT NOT NULL COMMENT '参数',
|
||||
unit VARCHAR(64) NOT NULL COMMENT '单位',
|
||||
qty NUMERIC(18, 4) NOT NULL COMMENT '数量',
|
||||
unit_price NUMERIC(20, 5) NOT NULL COMMENT '单价',
|
||||
include_amount NUMERIC(18, 4) COMMENT '人工含税总额;为空时用 数量×单价',
|
||||
tax_rate NUMERIC(18, 6) NOT NULL,
|
||||
expiration_date VARCHAR(32) NOT NULL,
|
||||
remark VARCHAR(500) NOT NULL,
|
||||
sort INTEGER NOT NULL DEFAULT '100',
|
||||
PRIMARY KEY (id),
|
||||
FOREIGN KEY(revision_id) REFERENCES biz_revision (id) ON DELETE CASCADE
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE budget_income_plan_line (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
revision_id BIGINT UNSIGNED NOT NULL,
|
||||
project_id BIGINT UNSIGNED NOT NULL,
|
||||
receive_point VARCHAR(255) NOT NULL COMMENT '收款节点',
|
||||
receive_date DATE COMMENT '收款时间',
|
||||
amount NUMERIC(18, 4) NOT NULL COMMENT '收款金额',
|
||||
is_earnest TINYINT UNSIGNED NOT NULL DEFAULT '0',
|
||||
remark VARCHAR(500) NOT NULL,
|
||||
sort INTEGER NOT NULL DEFAULT '100',
|
||||
PRIMARY KEY (id),
|
||||
FOREIGN KEY(revision_id) REFERENCES biz_revision (id) ON DELETE CASCADE
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE budget_manage_line (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
revision_id BIGINT UNSIGNED NOT NULL,
|
||||
project_id BIGINT UNSIGNED NOT NULL,
|
||||
manage_type INTEGER NOT NULL COMMENT '1人工 2业务费用 3其他',
|
||||
item_code VARCHAR(64) NOT NULL,
|
||||
item_name VARCHAR(255) NOT NULL COMMENT '名称',
|
||||
detail TEXT NOT NULL,
|
||||
unit VARCHAR(64) NOT NULL,
|
||||
qty NUMERIC(18, 4) NOT NULL,
|
||||
unit_price NUMERIC(20, 5) NOT NULL,
|
||||
total NUMERIC(18, 4) COMMENT '人工总额;为空用 数量×单价',
|
||||
predict_method VARCHAR(255) NOT NULL COMMENT '预估计算方法',
|
||||
predict_why VARCHAR(255) NOT NULL COMMENT '预估依据',
|
||||
pay_date DATE,
|
||||
pay_amount NUMERIC(18, 4) NOT NULL,
|
||||
deletable TINYINT UNSIGNED NOT NULL DEFAULT '1',
|
||||
counts_to_travel_limit TINYINT UNSIGNED NOT NULL COMMENT '是否计入差旅/业务费 10%% 限额' DEFAULT '0',
|
||||
remark VARCHAR(500) NOT NULL,
|
||||
sort INTEGER NOT NULL DEFAULT '100',
|
||||
PRIMARY KEY (id),
|
||||
FOREIGN KEY(revision_id) REFERENCES biz_revision (id) ON DELETE CASCADE
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE budget_other_cost_line (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
revision_id BIGINT UNSIGNED NOT NULL,
|
||||
project_id BIGINT UNSIGNED NOT NULL,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
exclude_amount NUMERIC(18, 4) NOT NULL,
|
||||
remark VARCHAR(500) NOT NULL,
|
||||
sort INTEGER NOT NULL DEFAULT '100',
|
||||
PRIMARY KEY (id),
|
||||
FOREIGN KEY(revision_id) REFERENCES biz_revision (id) ON DELETE CASCADE
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE budget_pay_plan_line (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
revision_id BIGINT UNSIGNED NOT NULL,
|
||||
project_id BIGINT UNSIGNED NOT NULL,
|
||||
pay_point VARCHAR(255) NOT NULL COMMENT '付款节点',
|
||||
pay_date DATE,
|
||||
purchase_type INTEGER COMMENT '1设备 2施工 3服务 4其他',
|
||||
amount NUMERIC(18, 4) NOT NULL,
|
||||
supplier VARCHAR(255) NOT NULL COMMENT '供应商',
|
||||
is_earnest TINYINT UNSIGNED NOT NULL COMMENT '保证金付款' DEFAULT '0',
|
||||
remark VARCHAR(500) NOT NULL,
|
||||
sort INTEGER NOT NULL DEFAULT '100',
|
||||
PRIMARY KEY (id),
|
||||
FOREIGN KEY(revision_id) REFERENCES biz_revision (id) ON DELETE CASCADE
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE budget_purchase_line (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
revision_id BIGINT UNSIGNED NOT NULL,
|
||||
project_id BIGINT UNSIGNED NOT NULL,
|
||||
purchase_type INTEGER NOT NULL COMMENT '1设备 2施工 3服务 4其他',
|
||||
category VARCHAR(128) NOT NULL COMMENT '类别',
|
||||
product_category VARCHAR(64) NOT NULL COMMENT '汇智/华智/华三/紫光其他的编码',
|
||||
name VARCHAR(255) NOT NULL,
|
||||
unit VARCHAR(64) NOT NULL,
|
||||
qty NUMERIC(18, 4) NOT NULL,
|
||||
unit_price NUMERIC(20, 5) NOT NULL,
|
||||
include_amount NUMERIC(18, 4),
|
||||
tax_rate NUMERIC(18, 6) NOT NULL,
|
||||
contract_party VARCHAR(255) NOT NULL COMMENT '签约方',
|
||||
is_underwritten TINYINT UNSIGNED NOT NULL COMMENT '是否垫资' DEFAULT '0',
|
||||
underwritten_amount NUMERIC(18, 4) NOT NULL COMMENT '预估垫资金额',
|
||||
pay_date DATE COMMENT '支出时间',
|
||||
pay_amount NUMERIC(18, 4) NOT NULL COMMENT '支出金额',
|
||||
pay_way VARCHAR(255) NOT NULL COMMENT '付款方式;老库这列塞的是合同付款条款,实测最长 136 字',
|
||||
remark VARCHAR(500) NOT NULL,
|
||||
sort INTEGER NOT NULL DEFAULT '100',
|
||||
PRIMARY KEY (id),
|
||||
FOREIGN KEY(revision_id) REFERENCES biz_revision (id) ON DELETE CASCADE
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE estimate_cost_line (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
revision_id BIGINT UNSIGNED NOT NULL,
|
||||
project_id BIGINT UNSIGNED NOT NULL,
|
||||
purchase_type INTEGER NOT NULL COMMENT '1设备 2施工 3服务 4其他',
|
||||
name VARCHAR(255) NOT NULL,
|
||||
include_amount NUMERIC(18, 4) NOT NULL,
|
||||
tax_rate NUMERIC(18, 6) NOT NULL,
|
||||
qty NUMERIC(18, 4) NOT NULL,
|
||||
unit_price NUMERIC(20, 5) NOT NULL,
|
||||
product_category VARCHAR(64) NOT NULL,
|
||||
remark VARCHAR(500) NOT NULL,
|
||||
sort INTEGER NOT NULL DEFAULT '100',
|
||||
PRIMARY KEY (id),
|
||||
FOREIGN KEY(revision_id) REFERENCES biz_revision (id) ON DELETE CASCADE
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE estimate_income_line (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
revision_id BIGINT UNSIGNED NOT NULL,
|
||||
project_id BIGINT UNSIGNED NOT NULL,
|
||||
income_type INTEGER NOT NULL COMMENT '1设备 2工程 3服务',
|
||||
name VARCHAR(255) NOT NULL COMMENT '收入项名称',
|
||||
include_amount NUMERIC(18, 4) NOT NULL COMMENT '含税金额',
|
||||
tax_rate NUMERIC(18, 6) NOT NULL COMMENT '税率百分数,13 表示 13%%',
|
||||
qty NUMERIC(18, 4) NOT NULL,
|
||||
unit_price NUMERIC(20, 5) NOT NULL,
|
||||
remark VARCHAR(500) NOT NULL,
|
||||
sort INTEGER NOT NULL DEFAULT '100',
|
||||
PRIMARY KEY (id),
|
||||
FOREIGN KEY(revision_id) REFERENCES biz_revision (id) ON DELETE CASCADE
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
CREATE TABLE estimate_other_line (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
revision_id BIGINT UNSIGNED NOT NULL,
|
||||
project_id BIGINT UNSIGNED NOT NULL,
|
||||
bucket VARCHAR(32) NOT NULL COMMENT 'other_cost/project_manage/capital_interest/company_manage',
|
||||
name VARCHAR(255) NOT NULL,
|
||||
exclude_amount NUMERIC(18, 4) NOT NULL COMMENT '不含税金额',
|
||||
manual TINYINT UNSIGNED NOT NULL COMMENT '人工估算还是系统派生(TO-BE-EST-001)' DEFAULT '1',
|
||||
remark VARCHAR(500) NOT NULL,
|
||||
sort INTEGER NOT NULL DEFAULT '100',
|
||||
PRIMARY KEY (id),
|
||||
FOREIGN KEY(revision_id) REFERENCES biz_revision (id) ON DELETE CASCADE
|
||||
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
|
||||
-- ------------------------------------------------------------------------
|
||||
-- 索引(112 条)
|
||||
-- ------------------------------------------------------------------------
|
||||
|
||||
CREATE INDEX idx_approval_flow_module ON approval_flow (business_module, status);
|
||||
CREATE INDEX ix_approval_flow_is_deleted ON approval_flow (is_deleted);
|
||||
CREATE INDEX idx_attachment_object ON attachment (object_type, object_id);
|
||||
CREATE INDEX ix_attachment_is_deleted ON attachment (is_deleted);
|
||||
CREATE INDEX idx_calc_snapshot_revision ON calc_snapshot (module, revision_id, id);
|
||||
CREATE INDEX ix_calc_snapshot_project_id ON calc_snapshot (project_id);
|
||||
CREATE INDEX ix_calc_snapshot_revision_id ON calc_snapshot (revision_id);
|
||||
CREATE INDEX ix_dict_type_group ON dict_type (`group`);
|
||||
CREATE INDEX ix_dict_type_is_deleted ON dict_type (is_deleted);
|
||||
CREATE INDEX idx_hub_sync_run_started ON hub_sync_run (started_at);
|
||||
CREATE INDEX idx_login_log_account ON login_log (account, created_at);
|
||||
CREATE INDEX idx_operation_log_created ON operation_log (created_at);
|
||||
CREATE INDEX idx_operation_log_object ON operation_log (object_type, object_id);
|
||||
CREATE INDEX ix_operation_log_account_id ON operation_log (account_id);
|
||||
CREATE INDEX ix_org_position_is_deleted ON org_position (is_deleted);
|
||||
CREATE INDEX idx_org_unit_parent ON org_unit (parent_id);
|
||||
CREATE INDEX idx_org_unit_path ON org_unit (path(255));
|
||||
CREATE INDEX ix_org_unit_code ON org_unit (code);
|
||||
CREATE INDEX ix_org_unit_is_deleted ON org_unit (is_deleted);
|
||||
CREATE INDEX ix_org_unit_manager_id ON org_unit (manager_id);
|
||||
CREATE UNIQUE INDEX uq_org_unit_hub_org_id ON org_unit (hub_org_id);
|
||||
CREATE INDEX idx_perm_data_policy_module ON perm_data_policy (module, enabled);
|
||||
CREATE INDEX idx_perm_data_policy_subject ON perm_data_policy (subject_type, subject_id);
|
||||
CREATE INDEX ix_perm_data_policy_is_deleted ON perm_data_policy (is_deleted);
|
||||
CREATE INDEX idx_perm_node_parent ON perm_node (parent_id);
|
||||
CREATE INDEX ix_perm_node_is_deleted ON perm_node (is_deleted);
|
||||
CREATE INDEX ix_perm_node_module ON perm_node (module);
|
||||
CREATE INDEX ix_perm_role_is_deleted ON perm_role (is_deleted);
|
||||
CREATE INDEX idx_sso_handoff_expires ON sso_handoff (expires_at);
|
||||
CREATE INDEX ix_system_config_group ON system_config (`group`);
|
||||
CREATE INDEX idx_accounts_email ON accounts (email);
|
||||
CREATE INDEX idx_accounts_org ON accounts (org_unit_id);
|
||||
CREATE INDEX idx_accounts_status ON accounts (status);
|
||||
CREATE INDEX ix_accounts_emp_code ON accounts (emp_code);
|
||||
CREATE INDEX ix_accounts_is_deleted ON accounts (is_deleted);
|
||||
CREATE INDEX ix_accounts_leader_id ON accounts (leader_id);
|
||||
CREATE INDEX ix_accounts_position_id ON accounts (position_id);
|
||||
CREATE UNIQUE INDEX uq_accounts_hub_user_id ON accounts (hub_user_id);
|
||||
CREATE INDEX idx_approval_node_flow ON approval_node (flow_id, order_number);
|
||||
CREATE INDEX ix_approval_node_flow_id ON approval_node (flow_id);
|
||||
CREATE INDEX ix_approval_node_is_deleted ON approval_node (is_deleted);
|
||||
CREATE INDEX idx_dict_item_type_sort ON dict_item (dict_type_id, sort);
|
||||
CREATE INDEX ix_dict_item_is_deleted ON dict_item (is_deleted);
|
||||
CREATE INDEX ix_perm_field_scope_module ON perm_field_scope (module);
|
||||
CREATE INDEX ix_perm_field_scope_role_id ON perm_field_scope (role_id);
|
||||
CREATE INDEX idx_perm_role_node_node ON perm_role_node (node_id);
|
||||
CREATE INDEX ix_perm_role_node_node_id ON perm_role_node (node_id);
|
||||
CREATE INDEX ix_perm_role_node_role_id ON perm_role_node (role_id);
|
||||
CREATE INDEX idx_account_identity_unit ON account_identity (org_unit_id);
|
||||
CREATE INDEX ix_account_identity_account_id ON account_identity (account_id);
|
||||
CREATE INDEX idx_approval_delegate_from ON approval_delegate (from_id, enabled);
|
||||
CREATE INDEX ix_approval_delegate_from_id ON approval_delegate (from_id);
|
||||
CREATE INDEX ix_approval_delegate_is_deleted ON approval_delegate (is_deleted);
|
||||
CREATE INDEX idx_approval_instance_biz ON approval_instance (business_module, revision_id);
|
||||
CREATE INDEX idx_approval_instance_project ON approval_instance (project_id, status);
|
||||
CREATE INDEX idx_approval_instance_submitter ON approval_instance (submitter_id, status);
|
||||
CREATE INDEX ix_approval_instance_project_id ON approval_instance (project_id);
|
||||
CREATE INDEX idx_perm_account_role_role ON perm_account_role (role_id);
|
||||
CREATE INDEX ix_perm_account_role_account_id ON perm_account_role (account_id);
|
||||
CREATE INDEX ix_perm_account_role_role_id ON perm_account_role (role_id);
|
||||
CREATE INDEX idx_project_creator ON project (creator_id);
|
||||
CREATE INDEX idx_project_no ON project (project_no);
|
||||
CREATE INDEX idx_project_org ON project (org_unit_id);
|
||||
CREATE INDEX idx_project_stage ON project (stage);
|
||||
CREATE INDEX ix_project_is_deleted ON project (is_deleted);
|
||||
CREATE INDEX idx_approval_record_instance ON approval_record (instance_id, id);
|
||||
CREATE INDEX idx_approval_record_project ON approval_record (project_id, id);
|
||||
CREATE INDEX ix_approval_record_instance_id ON approval_record (instance_id);
|
||||
CREATE INDEX ix_approval_record_project_id ON approval_record (project_id);
|
||||
CREATE INDEX idx_approval_task_assignee ON approval_task (assignee_id, status);
|
||||
CREATE INDEX idx_approval_task_instance ON approval_task (instance_id, status);
|
||||
CREATE INDEX ix_approval_task_assignee_id ON approval_task (assignee_id);
|
||||
CREATE INDEX ix_approval_task_instance_id ON approval_task (instance_id);
|
||||
CREATE INDEX idx_biz_revision_project ON biz_revision (project_id, status);
|
||||
CREATE INDEX ix_biz_revision_is_deleted ON biz_revision (is_deleted);
|
||||
CREATE INDEX ix_biz_revision_project_id ON biz_revision (project_id);
|
||||
CREATE INDEX ix_biz_revision_status ON biz_revision (status);
|
||||
CREATE INDEX idx_project_member_account ON project_member (account_id, member_role);
|
||||
CREATE INDEX ix_project_member_project_id ON project_member (project_id);
|
||||
CREATE INDEX ix_project_stage_log_project_id ON project_stage_log (project_id);
|
||||
CREATE INDEX idx_project_visible_role ON project_visible_role (role_id);
|
||||
CREATE INDEX ix_project_visible_role_project_id ON project_visible_role (project_id);
|
||||
CREATE INDEX idx_budget_fund_month_project ON budget_fund_month (project_id, month);
|
||||
CREATE INDEX ix_budget_fund_month_project_id ON budget_fund_month (project_id);
|
||||
CREATE INDEX ix_budget_fund_month_revision_id ON budget_fund_month (revision_id);
|
||||
CREATE INDEX idx_budget_income_revision ON budget_income_line (revision_id, income_type);
|
||||
CREATE INDEX ix_budget_income_line_project_id ON budget_income_line (project_id);
|
||||
CREATE INDEX ix_budget_income_line_revision_id ON budget_income_line (revision_id);
|
||||
CREATE INDEX idx_budget_income_plan_revision ON budget_income_plan_line (revision_id);
|
||||
CREATE INDEX ix_budget_income_plan_line_project_id ON budget_income_plan_line (project_id);
|
||||
CREATE INDEX ix_budget_income_plan_line_revision_id ON budget_income_plan_line (revision_id);
|
||||
CREATE INDEX idx_budget_manage_revision ON budget_manage_line (revision_id, manage_type);
|
||||
CREATE INDEX ix_budget_manage_line_project_id ON budget_manage_line (project_id);
|
||||
CREATE INDEX ix_budget_manage_line_revision_id ON budget_manage_line (revision_id);
|
||||
CREATE INDEX idx_budget_other_cost_revision ON budget_other_cost_line (revision_id);
|
||||
CREATE INDEX ix_budget_other_cost_line_project_id ON budget_other_cost_line (project_id);
|
||||
CREATE INDEX ix_budget_other_cost_line_revision_id ON budget_other_cost_line (revision_id);
|
||||
CREATE INDEX idx_budget_pay_plan_revision ON budget_pay_plan_line (revision_id);
|
||||
CREATE INDEX ix_budget_pay_plan_line_project_id ON budget_pay_plan_line (project_id);
|
||||
CREATE INDEX ix_budget_pay_plan_line_revision_id ON budget_pay_plan_line (revision_id);
|
||||
CREATE INDEX idx_budget_purchase_revision ON budget_purchase_line (revision_id, purchase_type);
|
||||
CREATE INDEX ix_budget_purchase_line_project_id ON budget_purchase_line (project_id);
|
||||
CREATE INDEX ix_budget_purchase_line_revision_id ON budget_purchase_line (revision_id);
|
||||
CREATE INDEX idx_estimate_cost_revision ON estimate_cost_line (revision_id, purchase_type);
|
||||
CREATE INDEX ix_estimate_cost_line_project_id ON estimate_cost_line (project_id);
|
||||
CREATE INDEX ix_estimate_cost_line_revision_id ON estimate_cost_line (revision_id);
|
||||
CREATE INDEX idx_estimate_income_revision ON estimate_income_line (revision_id, income_type);
|
||||
CREATE INDEX ix_estimate_income_line_project_id ON estimate_income_line (project_id);
|
||||
CREATE INDEX ix_estimate_income_line_revision_id ON estimate_income_line (revision_id);
|
||||
CREATE INDEX idx_estimate_other_revision ON estimate_other_line (revision_id, bucket);
|
||||
CREATE INDEX ix_estimate_other_line_project_id ON estimate_other_line (project_id);
|
||||
CREATE INDEX ix_estimate_other_line_revision_id ON estimate_other_line (revision_id);
|
||||
|
||||
SET FOREIGN_KEY_CHECKS = 1;
|
||||
|
||||
-- ========================================================================
|
||||
-- 完。共 40 张表、112 条索引语句。
|
||||
-- 建完可以抽查一条确认口径:
|
||||
-- SHOW CREATE TABLE project\G
|
||||
-- SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE();
|
||||
-- ========================================================================
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,95 @@
|
|||
"""pytest 夹具。
|
||||
|
||||
单元测试(``test_calc_*``)不碰数据库,纯算公式,跑得快也不依赖环境。
|
||||
接口测试要连库,用的是配置文件里那台测试库;连不上就整组 skip,
|
||||
不让"没连上内网"伪装成"代码有 bug"。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from app.config import settings # noqa: E402
|
||||
|
||||
# 测试默认不把账号口令送去问真 Hub:hubtest 在不在、这个账号有没有、口令对不对,
|
||||
# 都不该成为本地用例的前提。要验这条路本身,用 test_hub_integration 里的 hub_on
|
||||
# 加假 httpx 自己把它打开。
|
||||
settings.hub.login_mode = "local"
|
||||
|
||||
|
||||
def _database_reachable() -> bool:
|
||||
try:
|
||||
from app.db import ensure_database, get_engine
|
||||
|
||||
ensure_database()
|
||||
with get_engine().connect() as connection:
|
||||
connection.exec_driver_sql("SELECT 1")
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
DB_READY = _database_reachable()
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def client():
|
||||
if not DB_READY:
|
||||
pytest.skip(f"测试库 {settings.database.host}:{settings.database.port} 连不上")
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.main import app
|
||||
|
||||
with TestClient(app) as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def _admin_not_left_locked():
|
||||
"""收尾把内置超管的失败计数与锁定状态清干净。
|
||||
|
||||
用例里有专门试错口令的那类,一次给 ``login_failed_count`` 加一点;攒够
|
||||
``login_max_errors`` 就是锁号 ``login_lock_minutes`` 分钟,下一轮连
|
||||
``admin_headers`` 都登不进去,报出来是满屏 429 locked,看着像代码坏了。
|
||||
开发库上这个账号只服务于用例,跑完清零;中途手滑锁的号也顺手解开。
|
||||
"""
|
||||
yield
|
||||
if not DB_READY:
|
||||
return
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.db import SessionFactory
|
||||
from app.models import Account
|
||||
|
||||
session = SessionFactory()()
|
||||
try:
|
||||
names = {settings.seed.admin_account or "admin",
|
||||
(settings.seed.emergency_account or "").strip()}
|
||||
for name in {n for n in names if n}:
|
||||
row = session.execute(
|
||||
select(Account).where(Account.account == name)
|
||||
).scalars().first()
|
||||
if row is not None and (row.login_failed_count or row.locked_until):
|
||||
row.login_failed_count = 0
|
||||
row.locked_until = None
|
||||
session.commit()
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def admin_headers(client):
|
||||
response = client.post("/api/v1/auth/login", json={
|
||||
"account": settings.seed.admin_account or "admin",
|
||||
"password": settings.seed.admin_password or "Admin@12345",
|
||||
})
|
||||
assert response.status_code == 200, (
|
||||
f"{response.text}(内置超管 {settings.seed.admin_account} 登不上,整组接口用例都会 "
|
||||
f"ERROR;先确认这个账号没被锁、口令还是配置档里的 [seed] admin_password)"
|
||||
)
|
||||
return {"Authorization": "Bearer " + response.json()["data"]["accessToken"]}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,312 @@
|
|||
"""计算内核单元测试。
|
||||
|
||||
用例编号直接引用《系统重构-计算逻辑详细设计》里的规则号,业务确认口径时可以逐条对。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app.service.calc import fund_plan, profit, rules, tax, validate
|
||||
from app.service.calc.money import money_str, ratio, round_money, to_dec
|
||||
|
||||
D = Decimal
|
||||
|
||||
|
||||
class TestMoney:
|
||||
@pytest.mark.parametrize("value,expected", [
|
||||
("0.005", "0.01"), ("0.004", "0.00"), ("113", "113.00"), ("-0.005", "-0.01"),
|
||||
])
|
||||
def test_round_half_up(self, value, expected):
|
||||
assert str(round_money(value)) == expected
|
||||
|
||||
def test_money_is_string_in_json(self):
|
||||
assert money_str(D("1234.5")) == "1234.50"
|
||||
|
||||
def test_none_is_zero(self):
|
||||
assert to_dec(None) == 0 and to_dec("abc") == 0
|
||||
|
||||
|
||||
class TestTax:
|
||||
"""TAX-001 / TAX-002。"""
|
||||
|
||||
@pytest.mark.parametrize("include,rate,exclude,tax_amount", [
|
||||
("113", "13", "100", "13"), # TAX-01
|
||||
("106", "6", "100", "6"), # TAX-02
|
||||
("100", "0", "100", "0"), # TAX-03
|
||||
])
|
||||
def test_split(self, include, rate, exclude, tax_amount):
|
||||
result = tax.split(D(include), D(rate))
|
||||
assert result.exclude == D(exclude)
|
||||
assert result.tax == D(tax_amount)
|
||||
|
||||
def test_rate_null_means_no_tax(self):
|
||||
"""TAX-04"""
|
||||
result = tax.split(D("100"), None)
|
||||
assert (result.exclude, result.tax) == (D("100"), D("0"))
|
||||
|
||||
def test_manual_total_wins_over_product(self):
|
||||
"""TAX-05:人工含税总额优先于 数量×单价。"""
|
||||
result = tax.line(D("999"), D("2"), D("500"), D("13"))
|
||||
assert result.include == D("999") and result.source == "manual"
|
||||
|
||||
def test_missing_quantity_does_not_crash(self):
|
||||
"""TAX-06:老代码这里会 NPE,现在按 0 处理并交给校验器。"""
|
||||
result = tax.line(None, None, D("500"), D("13"))
|
||||
assert result.include == D("0")
|
||||
|
||||
@pytest.mark.parametrize("stored_include", [None, "", "0", "0.00", D("0.00")])
|
||||
def test_blank_amount_falls_back_to_qty_times_price(self, stored_include):
|
||||
"""明细表 NOT NULL 列把"没填"存成 0.00,不能当成人工 0。
|
||||
|
||||
之前这里会把整行抹成 0,概算合计直接少掉一条明细。
|
||||
"""
|
||||
result = tax.line(stored_include, D("2"), D("1090000"), D("9"))
|
||||
assert result.include == D("2180000.00") and result.source == "product"
|
||||
assert result.exclude == D("2000000.00")
|
||||
|
||||
def test_explicit_zero_without_price_stays_zero(self):
|
||||
"""既没金额也没单价时才是真 0,来源记 manual,校验器据此报必填。"""
|
||||
result = tax.line("0.00", D("2"), None, D("9"))
|
||||
assert result.include == D("0.00") and result.source == "manual"
|
||||
|
||||
def test_include_equals_exclude_plus_tax(self):
|
||||
"""价内税必须可加:含税 = 不含税 + 税额,一分不差。"""
|
||||
for include, rate in [("113", "13"), ("1130", "13"), ("9999.99", "9"), ("1", "13")]:
|
||||
result = tax.split(D(include), D(rate))
|
||||
assert result.include == result.exclude + result.tax
|
||||
|
||||
def test_browser_bug_is_gone(self):
|
||||
"""RISK-TAX-002:老前端对 113/13% 会算出 14.69。"""
|
||||
assert tax.split(D("113"), D("13")).tax != D("14.69")
|
||||
|
||||
|
||||
class TestProfit:
|
||||
def test_ladder(self):
|
||||
result = profit.calculate(profit.ProfitInput(
|
||||
income_device=D("1000"), income_engineering=D("130"),
|
||||
purchase_device=D("600"), purchase_construction=D("100"),
|
||||
purchase_service=D("50"), purchase_other=D("10"),
|
||||
project_manage=D("30"), other_cost=D("5"), finance_cost=D("2"),
|
||||
))
|
||||
assert result.income_total == D("1130")
|
||||
assert result.purchase_total == D("760")
|
||||
assert result.gross_a == D("370")
|
||||
# 推荐口径:项目毛利 = 采购毛利 - 项目管理 - 其他成本 - 财务费用
|
||||
assert result.gross_b == D("333")
|
||||
# 公司管理费用按 2.8% 派生
|
||||
assert result.company_manage_source == "derived"
|
||||
assert result.contribution == result.gross_b - result.company_manage
|
||||
|
||||
def test_manual_company_manage_beats_rate(self):
|
||||
"""RISK-BUD-CM-001:人工填的值必须生效。"""
|
||||
result = profit.calculate(profit.ProfitInput(
|
||||
income_device=D("1000"), company_manage=D("1"),
|
||||
))
|
||||
assert result.company_manage == D("1") and result.company_manage_source == "manual"
|
||||
|
||||
def test_zero_income_rate_is_undefined(self):
|
||||
"""PROFIT-02/03:零收入时利润率"未定义",不是 0。"""
|
||||
result = profit.calculate(profit.ProfitInput(purchase_device=D("100")))
|
||||
assert not result.gross_a_rate.defined
|
||||
assert result.gross_a_rate.reason == "zero_denominator"
|
||||
assert result.gross_a_rate.to_dict()["value"] is None
|
||||
|
||||
def test_other_cost_can_be_excluded_for_reconciliation(self):
|
||||
"""关掉开关就能复现老后端口径(没扣其他成本)。"""
|
||||
args = dict(income_device=D("1000"), other_cost=D("50"))
|
||||
strict = profit.calculate(profit.ProfitInput(**args)).gross_b
|
||||
with rules.override(profit_other_cost_in_gross=False):
|
||||
legacy = profit.calculate(profit.ProfitInput(**args)).gross_b
|
||||
assert legacy == strict + D("50")
|
||||
|
||||
|
||||
class TestRatio:
|
||||
def test_zero_denominator_undefined(self):
|
||||
assert not ratio(D("1"), D("0")).defined
|
||||
|
||||
def test_zero_denominator_zero_mode(self):
|
||||
with rules.override(zero_denominator="zero"):
|
||||
assert ratio(D("1"), D("0")).value == 0
|
||||
|
||||
def test_zero_denominator_mode_is_a_front_end_switch(self):
|
||||
"""零分母行为改完立刻生效,不用重启:口径存在库里,不在配置文件里。"""
|
||||
rules.apply({"calc.zero_denominator": "zero"})
|
||||
try:
|
||||
assert ratio(D("1"), D("0")).value == 0
|
||||
finally:
|
||||
rules.reset_to_defaults()
|
||||
assert not ratio(D("1"), D("0")).defined
|
||||
|
||||
|
||||
class TestFundPlan:
|
||||
def test_plan_001_balance_chain(self):
|
||||
"""PLAN-001:余额 = 收入 - 支出 + 上月余额;垫资还款不重复计入余额。"""
|
||||
result = fund_plan.calculate([
|
||||
fund_plan.FundMonthInput("2026-01", device_cost=D("100"), interest_rate=D("6")),
|
||||
fund_plan.FundMonthInput("2026-02", sale_income=D("80"), interest_rate=D("6")),
|
||||
fund_plan.FundMonthInput("2026-03", sale_income=D("200"), interest_rate=D("6")),
|
||||
])
|
||||
assert [m.balance for m in result.months] == [D("-100.00"), D("-20.00"), D("180.00")]
|
||||
assert result.months[0].underwritten_plan == D("100.00")
|
||||
assert [m.repayment_plan for m in result.months[1:]] == [D("80.00"), D("20.00")]
|
||||
|
||||
def test_plan_int_001_interest(self):
|
||||
"""PLAN-INT-001:月息 = max(0, -余额 × 年利率/100/12)。"""
|
||||
assert fund_plan.capital_interest(D("-100"), D("6")) == D("0.50")
|
||||
assert fund_plan.capital_interest(D("500"), D("6")) == D("0")
|
||||
assert fund_plan.capital_interest(D("-100"), D("0")) == D("0")
|
||||
|
||||
def test_repayment_never_overpays(self):
|
||||
"""PLAN-REPAY-001:还款最多把历史负余额补到 0。"""
|
||||
assert fund_plan.repayment_plan(D("1000"), D("0"), D("-50")) == D("50")
|
||||
assert fund_plan.repayment_plan(D("1000"), D("0"), D("50")) == D("0")
|
||||
|
||||
def test_peak_is_real_peak(self):
|
||||
"""RISK-PLAN-STAT-001:峰值是单月最大值,不是各月之和。"""
|
||||
result = fund_plan.calculate([
|
||||
fund_plan.FundMonthInput("2026-01", device_cost=D("100")),
|
||||
fund_plan.FundMonthInput("2026-02", device_cost=D("300")),
|
||||
fund_plan.FundMonthInput("2026-03", device_cost=D("50")),
|
||||
])
|
||||
assert result.peak_month == "2026-02"
|
||||
assert result.peak_value == D("300.00")
|
||||
assert result.underwritten_total == D("450.00")
|
||||
|
||||
|
||||
class TestValidate:
|
||||
def test_bud_val_001_travel_limit(self):
|
||||
report = validate.ValidationReport()
|
||||
validate.check_travel_limit(report, D("370"), D("30"), D("100"))
|
||||
assert not report.passed
|
||||
assert report.errors[0].rule_id == "BUD-VAL-001"
|
||||
|
||||
def test_bud_val_001_within_limit_passes(self):
|
||||
report = validate.ValidationReport()
|
||||
validate.check_travel_limit(report, D("370"), D("30"), D("10"))
|
||||
assert report.passed
|
||||
|
||||
def test_plan_val_001_pay_plan_reconciles(self):
|
||||
report = validate.ValidationReport()
|
||||
validate.check_pay_plan_reconciles(report, {1: D("100")}, {1: D("120")})
|
||||
assert report.errors[0].rule_id == "PLAN-VAL-001"
|
||||
|
||||
def test_plan_val_003_missing_boundary_month(self):
|
||||
report = validate.ValidationReport()
|
||||
validate.check_fund_months(report, ["2026-01", "2026-01"], "2026-01", "2026-06")
|
||||
rules = {issue.rule_id for issue in report.errors}
|
||||
assert rules == {"PLAN-VAL-003"}
|
||||
|
||||
def test_tax_range_error(self):
|
||||
report = validate.ValidationReport()
|
||||
validate.check_tax_inputs(report, [{"tax_rate": "130"}], label="收入")
|
||||
assert report.errors[0].rule_id == "INPUT-TAX-RANGE"
|
||||
|
||||
|
||||
class TestCalcRules:
|
||||
"""口径参数搬进系统参数表之后的读取口(app/service/calc/rules.py)。"""
|
||||
|
||||
def test_config_file_no_longer_carries_calc_rules(self):
|
||||
"""配置文件里不该再有任何计算规则:口径改了要重启,等于没人敢改。"""
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
from app.config import BASE_DIR
|
||||
|
||||
for name in ("config.toml", "config.dev.toml", "config.prod.toml"):
|
||||
path = Path(BASE_DIR) / name
|
||||
if not path.is_file():
|
||||
continue
|
||||
with path.open("rb") as handle:
|
||||
data = tomllib.load(handle)
|
||||
assert "calc" not in data, f"{name} 里还留着 [calc] 段"
|
||||
|
||||
def test_every_rule_is_seeded_under_the_calc_group(self):
|
||||
"""种进 system_config 的行与内核读的字段一一对应,编码不多也不少。"""
|
||||
rows = rules.seed_rows()
|
||||
assert [row[0] for row in rows] == list(rules.RULE_CODES)
|
||||
assert all(row[4] == "calc" for row in rows)
|
||||
# 每行都能被自己校验通过,且折出来就是默认值——否则页面一打开就是"已改"
|
||||
for code, _name, value, _type, _group, _remark in rows:
|
||||
spec = rules.spec_for(code)
|
||||
assert rules.normalize(spec, value) == spec.default_text
|
||||
assert rules.parse(spec, rules.normalize(spec, value)) == spec.default
|
||||
|
||||
def test_apply_reads_the_stored_strings(self):
|
||||
rules.apply({"calc.money_scale": "3", "calc.rounding": "half_even",
|
||||
"calc.tax_rate_pre_round": "true", "calc.company_manage_fee_rate": "3.5"})
|
||||
try:
|
||||
# 位数与进位方式都换了:1.0005 在 3 位 + HALF_EVEN 下落到偶数 1.000
|
||||
assert round_money("1.0005") == D("1.000")
|
||||
assert rules.RULES.rounding == "HALF_EVEN"
|
||||
assert rules.RULES.tax_rate_pre_round is True
|
||||
assert rules.RULES.company_manage_fee_rate == 3.5
|
||||
finally:
|
||||
rules.reset_to_defaults()
|
||||
|
||||
def test_garbage_value_falls_back_instead_of_breaking_the_calc(self):
|
||||
"""库里被手写坏了一条:退回默认,别的条照常生效,试算不能停。"""
|
||||
rules.apply({"calc.money_scale": "两", "calc.rate_scale": "6"})
|
||||
try:
|
||||
assert rules.RULES.money_scale == 2
|
||||
assert rules.RULES.rate_scale == 6
|
||||
finally:
|
||||
rules.reset_to_defaults()
|
||||
|
||||
@pytest.mark.parametrize("key,value,message", [
|
||||
("rounding", "HALF_CENTIMETER", "只能是"),
|
||||
("zero_denominator", "nan", "只能是"),
|
||||
("contribution_rate_action", "block-it", "只能是"),
|
||||
("money_scale", "2.5", "必须是整数"),
|
||||
("money_scale", "99", "不能大于"),
|
||||
("company_manage_fee_rate", "-1", "不能小于"),
|
||||
("travel_business_limit_rate", "abc", "必须是数字"),
|
||||
("tax_from_complement", "maybe", "是"),
|
||||
("version", " ", "不能为空"),
|
||||
])
|
||||
def test_bad_values_are_rejected_with_a_readable_reason(self, key, value, message):
|
||||
spec = rules.SPECS_BY_ATTR[key]
|
||||
with pytest.raises(ValueError) as excinfo:
|
||||
rules.normalize(spec, value)
|
||||
assert message in str(excinfo.value)
|
||||
|
||||
def test_override_restores_everything_it_touched(self):
|
||||
before = rules.as_dict()
|
||||
with rules.override(money_scale=4, version="2027.01"):
|
||||
assert rules.RULES.money_scale == 4
|
||||
assert money_str(D("1.005")) == "1.0050"
|
||||
assert rules.as_dict() == before
|
||||
|
||||
def test_unknown_override_key_is_a_programming_error(self):
|
||||
with pytest.raises(KeyError):
|
||||
with rules.override(money_scales=3):
|
||||
pass
|
||||
|
||||
def test_view_shape_matches_the_front_end_contract(self):
|
||||
"""页面靠这份渲染控件:段落、控件类型、取值范围、默认值,一样都不能少。"""
|
||||
class FakeSession:
|
||||
def execute(self, _statement):
|
||||
return self
|
||||
|
||||
def scalars(self):
|
||||
return self
|
||||
|
||||
def all(self):
|
||||
return []
|
||||
|
||||
view = rules.view(FakeSession())
|
||||
assert view["changed"] == 0
|
||||
assert [section["key"] for section in view["sections"]] == [
|
||||
key for key, _title, _hint in rules.RULE_SECTIONS if any(
|
||||
spec.section == key and spec.attr != "version" for spec in rules.RULE_SPECS
|
||||
)
|
||||
]
|
||||
for section in view["sections"]:
|
||||
for item in section["rules"]:
|
||||
assert item["code"].startswith("calc.")
|
||||
assert item["kind"] in ("int", "decimal", "bool", "enum", "string")
|
||||
assert item["configured"] is False
|
||||
if item["kind"] == "enum":
|
||||
assert item["choices"], f"{item['code']} 是枚举但没有候选值"
|
||||
|
|
@ -0,0 +1,300 @@
|
|||
"""数据字典:代码同步、界面维护、护栏,以及"下拉框只剩一个来源"这条回归。
|
||||
|
||||
这里钉的都是会静默腐化的东西:内置取值被改掉、代码和库两份名字对不上、
|
||||
前端自己抄一份常量。真出事的时候没人报错,只是列表上显示的名字和下拉框不一样。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
|
||||
from app import dicts as store
|
||||
|
||||
VALUE_TAGS = {"A", "B"}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def ctx():
|
||||
return {}
|
||||
|
||||
|
||||
def _code(prefix: str = "cust") -> str:
|
||||
"""每次跑都换一个编码:字典表是留着不清的,撞了上一次的残留会误报"编码已存在"。"""
|
||||
return f"{prefix}{uuid.uuid4().hex[:8]}"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 代码层
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_every_code_dict_is_shipped_to_the_frontend(client, admin_headers):
|
||||
"""``/bootstrap`` 必须带上全部代码字典,前端就不用再为某个下拉框单开一条接口。"""
|
||||
enums = client.get("/api/v1/bootstrap", headers=admin_headers).json()["data"]["enums"]
|
||||
missing = set(store.SPECS) - set(enums)
|
||||
assert not missing, f"bootstrap 少了这些字典:{sorted(missing)}"
|
||||
|
||||
|
||||
def test_project_options_and_enums_agree(client, admin_headers):
|
||||
"""项目类型曾在接口和前端各写一份,名字对不上也没人报错——这条就是钉住那次。"""
|
||||
enums = client.get("/api/v1/bootstrap", headers=admin_headers).json()["data"]["enums"]
|
||||
options = client.get("/api/v1/projects/options", headers=admin_headers).json()["data"]
|
||||
assert options["types"] == enums["projectType"]
|
||||
assert options["stages"] == enums["projectStage"]
|
||||
assert options["underwrittenModes"] == enums["underwrittenMode"]
|
||||
assert options["memberRoles"] == enums["projectMemberRole"]
|
||||
|
||||
|
||||
def test_dict_values_match_what_the_calc_engine_reads():
|
||||
"""下拉框给的编码,必须是计算内核真认的那些。
|
||||
|
||||
老毛病:前端自己抄一份产品归属(integration/other),内核的映射表里根本没这两个键,
|
||||
于是那几笔采购额静默投影不到 project 的产品金额列上。费用归属同理多出一个
|
||||
finance_cost——选它的人等于白填一行。
|
||||
"""
|
||||
from app.models import OtherCostBucket, ProductCategory
|
||||
from app.service.calc import mapping
|
||||
|
||||
assert set(ProductCategory.LABELS) == set(mapping.PRODUCT_CATEGORY_TO_FIELD)
|
||||
# engine.estimate_payload 按这四个 bucket 取数,多一个少一个都算漏了一层
|
||||
assert set(OtherCostBucket.LABELS) == {
|
||||
"project_manage", "other_cost", "capital_interest", "company_manage"}
|
||||
# 两边都得已经同步进字典,前端才没有第二份可抄
|
||||
assert {row["value"] for row in store.SPECS["productCategory"].options()} == set(ProductCategory.LABELS)
|
||||
assert {row["value"] for row in store.SPECS["otherCostBucket"].options()} == set(OtherCostBucket.LABELS)
|
||||
|
||||
|
||||
def test_sync_is_idempotent():
|
||||
"""重启不能把界面上改过的名字冲回去,也不能长出第二份同样的取值。"""
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from app.db import SessionFactory
|
||||
from app.models import DictItem, DictType
|
||||
|
||||
with SessionFactory()() as db:
|
||||
store.sync(db)
|
||||
store.sync(db)
|
||||
db.commit()
|
||||
types = db.execute(select(func.count()).select_from(DictType)
|
||||
.where(DictType.is_deleted.is_(False))).scalar()
|
||||
dup = db.execute(select(func.count()).select_from(
|
||||
select(DictItem.dict_type_id, DictItem.value)
|
||||
.where(DictItem.is_deleted.is_(False))
|
||||
.group_by(DictItem.dict_type_id, DictItem.value)
|
||||
.having(func.count() > 1).subquery())).scalar()
|
||||
assert types >= len(store.SPECS)
|
||||
assert dup == 0, "同一份字典里出现了重复取值"
|
||||
|
||||
|
||||
def test_sync_does_not_overwrite_edited_labels():
|
||||
"""改过名字的内置字典,重启后还得是改过的名字(要回到代码值请用「恢复默认」)。"""
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.db import SessionFactory
|
||||
from app.models import DictItem, DictType
|
||||
|
||||
with SessionFactory()() as db:
|
||||
row = db.execute(select(DictItem).join(DictType, DictType.id == DictItem.dict_type_id)
|
||||
.where(DictType.code == "projectType", DictItem.value == "1")
|
||||
).scalars().first()
|
||||
assert row is not None
|
||||
original = row.label
|
||||
row.label = "工程集成类(临时改名)"
|
||||
db.commit()
|
||||
|
||||
store.sync(db)
|
||||
db.commit()
|
||||
again = db.get(DictItem, row.id)
|
||||
assert again.label == "工程集成类(临时改名)"
|
||||
|
||||
again.label = original
|
||||
db.commit()
|
||||
store.invalidate()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 维护页:自定义字典
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_custom_dict_end_to_end(client, admin_headers, ctx):
|
||||
code = _code("grade")
|
||||
created = client.post("/api/v1/system/dicts", headers=admin_headers, json={
|
||||
"code": code, "name": "客户等级", "group": "测试", "valueType": "string",
|
||||
"remark": "用例自建"})
|
||||
assert created.status_code == 200, created.text
|
||||
type_id = created.json()["data"]["id"]
|
||||
ctx.update(code=code, type_id=type_id)
|
||||
|
||||
for index, (value, label) in enumerate((("vip", "战略客户"), ("normal", "普通客户"))):
|
||||
resp = client.post(f"/api/v1/system/dicts/{code}/items", headers=admin_headers, json={
|
||||
"value": value, "label": label, "sort": (index + 1) * 10})
|
||||
assert resp.status_code == 200, resp.text
|
||||
|
||||
data = client.get("/api/v1/dicts", headers=admin_headers, params={"types": code}).json()["data"]
|
||||
assert [item["value"] for item in data[code]] == ["vip", "normal"]
|
||||
assert data[code][0]["label"] == "战略客户"
|
||||
|
||||
# 停用一条:下拉框里没有它,但历史数据上的值照样显示得出名字
|
||||
items = client.get(f"/api/v1/system/dicts/{code}/items", headers=admin_headers).json()["data"]["items"]
|
||||
vip = next(row for row in items if row["value"] == "vip")
|
||||
assert client.post(f"/api/v1/system/dicts/items/{vip['id']}/toggle",
|
||||
headers=admin_headers).json()["data"]["enabled"] is False
|
||||
data = client.get("/api/v1/dicts", headers=admin_headers, params={"types": code}).json()["data"]
|
||||
assert [item["value"] for item in data[code]] == ["normal"]
|
||||
|
||||
from app.db import session_scope
|
||||
|
||||
with session_scope() as db:
|
||||
assert store.label(db, code, "vip", "兜底") == "战略客户", "停用的取值也该查得到名字"
|
||||
|
||||
# 整类停用:下拉框给空列表,而不是报找不到
|
||||
assert client.put(f"/api/v1/system/dicts/{type_id}", headers=admin_headers, json={
|
||||
"code": code, "name": "客户等级", "group": "测试", "valueType": "string",
|
||||
"enabled": False}).status_code == 200
|
||||
data = client.get("/api/v1/dicts", headers=admin_headers, params={"types": code}).json()["data"]
|
||||
assert data[code] == []
|
||||
|
||||
|
||||
def test_custom_dict_is_visible_in_bootstrap(client, admin_headers, ctx):
|
||||
"""自建字典不用改一行代码就能进 bootstrap——这是加这个模块的全部理由。"""
|
||||
type_id = ctx["type_id"]
|
||||
client.put(f"/api/v1/system/dicts/{type_id}", headers=admin_headers, json={
|
||||
"code": ctx["code"], "name": "客户等级", "group": "测试", "valueType": "string",
|
||||
"enabled": True})
|
||||
enums = client.get("/api/v1/bootstrap", headers=admin_headers).json()["data"]["enums"]
|
||||
assert enums[ctx["code"]] == [{"value": "normal", "label": "普通客户"}]
|
||||
|
||||
|
||||
def test_custom_dict_cleanup(client, admin_headers, ctx):
|
||||
assert client.delete(f"/api/v1/system/dicts/{ctx['type_id']}",
|
||||
headers=admin_headers).json()["data"]["deleted"] is True
|
||||
data = client.get("/api/v1/dicts", headers=admin_headers,
|
||||
params={"types": ctx["code"]}).json()["data"]
|
||||
assert data == {}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 护栏
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload, code", [
|
||||
({"code": "Customer_Level", "name": "x", "valueType": "string"}, "invalid_code"),
|
||||
({"code": "projectStage", "name": "x", "valueType": "string"}, "reserved_code"),
|
||||
])
|
||||
def test_type_code_is_guarded(client, admin_headers, payload, code):
|
||||
resp = client.post("/api/v1/system/dicts", headers=admin_headers, json=payload)
|
||||
assert resp.json()["error"]["code"] == code, resp.text
|
||||
|
||||
|
||||
def test_reserved_code_case_insensitive_check(client, admin_headers):
|
||||
"""和内置字典撞编码要挡下来,但换个编码就该建得成(顺带清掉)。"""
|
||||
code = _code("stage")
|
||||
assert client.post("/api/v1/system/dicts", headers=admin_headers, json={
|
||||
"code": code, "name": "临时阶段字典", "valueType": "int"}).status_code == 200
|
||||
row = client.get("/api/v1/system/dicts", headers=admin_headers).json()["data"]
|
||||
created = next(item for item in row if item["code"] == code)
|
||||
assert client.delete(f"/api/v1/system/dicts/{created['id']}",
|
||||
headers=admin_headers).status_code == 200
|
||||
|
||||
|
||||
def test_builtin_values_are_immutable(client, admin_headers):
|
||||
"""内置取值是代码分支的依据:改 value、删条目都挡下来,改名字放行。"""
|
||||
items = client.get("/api/v1/system/dicts/projectStage/items",
|
||||
headers=admin_headers).json()["data"]["items"]
|
||||
row = items[0]
|
||||
body = {"value": "999", "label": row["label"], "sort": row["sort"],
|
||||
"enabled": True, "tag": "", "remark": ""}
|
||||
resp = client.put(f"/api/v1/system/dicts/items/{row['id']}", headers=admin_headers, json=body)
|
||||
assert resp.json()["error"]["code"] == "builtin_item", resp.text
|
||||
|
||||
resp = client.delete(f"/api/v1/system/dicts/items/{row['id']}", headers=admin_headers)
|
||||
assert resp.json()["error"]["code"] == "builtin_item", resp.text
|
||||
|
||||
body["value"] = row["value"]
|
||||
body["label"] = row["label"]
|
||||
assert client.put(f"/api/v1/system/dicts/items/{row['id']}",
|
||||
headers=admin_headers, json=body).status_code == 200
|
||||
|
||||
stage_type = next(item for item in client.get("/api/v1/system/dicts", headers=admin_headers
|
||||
).json()["data"]
|
||||
if item["code"] == "projectStage")
|
||||
resp = client.delete(f"/api/v1/system/dicts/{stage_type['id']}", headers=admin_headers)
|
||||
assert resp.json()["error"]["code"] == "builtin_type", resp.text
|
||||
|
||||
|
||||
def test_rename_then_reset(client, admin_headers):
|
||||
"""改名能立刻生效,「恢复默认」能回到代码里的名字。"""
|
||||
items = client.get("/api/v1/system/dicts/underwrittenMode/items",
|
||||
headers=admin_headers).json()["data"]["items"]
|
||||
row = items[0]
|
||||
original = store.SPECS["underwrittenMode"].items[0][1]
|
||||
body = {"value": str(row["value"]), "label": "A类-不垫资(改名)", "sort": row["sort"],
|
||||
"enabled": True, "tag": "", "remark": ""}
|
||||
assert client.put(f"/api/v1/system/dicts/items/{row['id']}",
|
||||
headers=admin_headers, json=body).status_code == 200
|
||||
enums = client.get("/api/v1/bootstrap", headers=admin_headers).json()["data"]["enums"]
|
||||
assert enums["underwrittenMode"][0]["label"] == "A类-不垫资(改名)"
|
||||
|
||||
assert client.post("/api/v1/system/dicts/underwrittenMode/reset",
|
||||
headers=admin_headers).status_code == 200
|
||||
enums = client.get("/api/v1/bootstrap", headers=admin_headers).json()["data"]["enums"]
|
||||
assert enums["underwrittenMode"][0]["label"] == original
|
||||
|
||||
|
||||
def test_reset_only_works_on_code_dicts(client, admin_headers):
|
||||
code = _code("noc")
|
||||
client.post("/api/v1/system/dicts", headers=admin_headers, json={
|
||||
"code": code, "name": "没有代码默认值", "valueType": "string"})
|
||||
row = next(item for item in client.get("/api/v1/system/dicts",
|
||||
headers=admin_headers).json()["data"]
|
||||
if item["code"] == code)
|
||||
resp = client.post(f"/api/v1/system/dicts/{code}/reset", headers=admin_headers)
|
||||
assert resp.json()["error"]["code"] == "not_builtin", resp.text
|
||||
client.delete(f"/api/v1/system/dicts/{row['id']}", headers=admin_headers)
|
||||
|
||||
|
||||
def test_int_dict_rejects_non_numeric_value(client, admin_headers):
|
||||
code = _code("num")
|
||||
client.post("/api/v1/system/dicts", headers=admin_headers, json={
|
||||
"code": code, "name": "整数型字典", "valueType": "int"})
|
||||
row = next(item for item in client.get("/api/v1/system/dicts",
|
||||
headers=admin_headers).json()["data"]
|
||||
if item["code"] == code)
|
||||
resp = client.post(f"/api/v1/system/dicts/{code}/items", headers=admin_headers, json={
|
||||
"value": "不是数字", "label": "任何名字", "sort": 10})
|
||||
assert resp.json()["error"]["code"] == "invalid_value", resp.text
|
||||
|
||||
assert client.post(f"/api/v1/system/dicts/{code}/items", headers=admin_headers, json={
|
||||
"value": " 7 ", "label": "七", "sort": 10}).status_code == 200
|
||||
data = client.get("/api/v1/dicts", headers=admin_headers, params={"types": code}).json()["data"]
|
||||
assert data[code] == [{"value": 7, "label": "七"}], "整数型字典要按数字下发"
|
||||
|
||||
dup = client.post(f"/api/v1/system/dicts/{code}/items", headers=admin_headers, json={
|
||||
"value": "7", "label": "重复", "sort": 20})
|
||||
assert dup.json()["error"]["code"] == "duplicated_value", dup.text
|
||||
client.delete(f"/api/v1/system/dicts/{row['id']}", headers=admin_headers)
|
||||
|
||||
|
||||
def test_edit_needs_the_permission(client, admin_headers):
|
||||
"""改字典是系统管理动作,只有超管那条权限码能改。"""
|
||||
from app.config import settings
|
||||
|
||||
from tests.test_api_flow import login
|
||||
|
||||
# 演示账号与内置超管同一个口令,见 README「快速开始」
|
||||
password = settings.seed.admin_password or "Admin@12345"
|
||||
try:
|
||||
headers = login(client, "wangwu", password)
|
||||
except AssertionError:
|
||||
pytest.skip("演示账号 wangwu 不在:[seed] demo_data = false 时没有演示账号")
|
||||
if any("system:dict:edit" in code for code in
|
||||
client.get("/api/v1/bootstrap", headers=headers).json()["data"]["permissions"]):
|
||||
pytest.skip("wangwu 被授了 system:dict:edit,这条越权用例没法验")
|
||||
resp = client.post("/api/v1/system/dicts", headers=headers, json={
|
||||
"code": _code("nope"), "name": "不该建成", "valueType": "string"})
|
||||
assert resp.status_code == 403, resp.text
|
||||
assert client.get("/api/v1/system/dicts", headers=headers).status_code == 403
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,323 @@
|
|||
"""导数脚本里那几个归一化函数的单元测试。
|
||||
|
||||
这些函数每一个都是踩过坑才写成现在这样的,改动前请先看注释里的实测数据:
|
||||
|
||||
* 税率和利润率在老库里是两套口径,混一次就是一次 100 倍误差;
|
||||
* ``sys_user.is_deleted`` 是 ``bit(1)``,pymysql 取回来是字节串,
|
||||
``bool(b'\\x00')`` 是 True;
|
||||
* 采购类别存的是字典 id,不是中文名。
|
||||
|
||||
都是"跑完不报错、数却悄悄错了"的那类 bug,所以值得钉住。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "migrate_legacy.py"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def mig():
|
||||
spec = importlib.util.spec_from_file_location("migrate_legacy", SCRIPT)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def report(mig):
|
||||
return mig.Report()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 利润率:老库 *_margin 本来就是百分数
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestMarginRate:
|
||||
def test_already_percent_is_left_alone(self, mig, report):
|
||||
# 实测 id=7:contract=12990, gross_profit=1578.60, margin=12.15
|
||||
assert mig.margin_rate("12.15", report, "gross_profit_margin") == Decimal("12.15")
|
||||
assert report.counts == {}
|
||||
|
||||
def test_small_margin_is_not_multiplied(self, mig, report):
|
||||
"""老库真有 0.03 这种利润率,那是 0.03%,不是 3%。
|
||||
|
||||
旧实现用 -1 < v < 1 一把梭,把 6 条这样的小利润率全放大了 100 倍。
|
||||
"""
|
||||
for raw, want in [("0.03", "0.03"), ("0.20", "0.20"), ("0.99", "0.99"), ("1", "1")]:
|
||||
assert mig.margin_rate(raw, report, "gross_profit_margin") == Decimal(want)
|
||||
|
||||
def test_negative_and_zero(self, mig, report):
|
||||
assert mig.margin_rate("-8.5", report, "m") == Decimal("-8.5")
|
||||
assert mig.margin_rate(None, report, "m") == Decimal("0")
|
||||
assert mig.margin_rate("", report, "m") == Decimal("0")
|
||||
|
||||
def test_absurd_rate_is_value_preserved_but_reported(self, mig, report):
|
||||
"""P00217 那种脏值照原值导,但要报出来,不能静默。"""
|
||||
assert mig.margin_rate("-49504", report, "gross_profit_a_margin") == Decimal("-49504")
|
||||
assert any("gross_profit_a_margin" in key for key in report.skips)
|
||||
assert report.notes
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 税率:老库 tax_rate 是小数
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestTaxRatePercent:
|
||||
def test_fraction_scales_up(self, mig, report):
|
||||
assert mig.tax_rate_percent("0.13", report) == Decimal("13")
|
||||
assert mig.tax_rate_percent("0", report) == Decimal("0")
|
||||
assert mig.tax_rate_percent(None, report) == Decimal("0")
|
||||
assert report.counts["换算:税率小数→百分数"] == 1
|
||||
|
||||
def test_boundary_one_is_full_hundred(self, mig, report):
|
||||
assert mig.tax_rate_percent("1", report) == Decimal("100")
|
||||
|
||||
def test_already_percent_not_double_scaled(self, mig, report):
|
||||
"""库里万一有行已经写成 13,落在 (0,1] 之外,不能再乘一次。"""
|
||||
assert mig.tax_rate_percent("13", report) == Decimal("13")
|
||||
assert mig.tax_rate_percent("6", report) == Decimal("6")
|
||||
assert report.counts == {}
|
||||
|
||||
def test_negative_stays_negative(self, mig, report):
|
||||
"""税率不该是负的,但负的也不能被当成小数放大成 -13。"""
|
||||
assert mig.tax_rate_percent("-0.13", report) == Decimal("-0.13")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# bit(1):bool(b'\x00') 是 True
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestIsDeleted:
|
||||
@pytest.mark.parametrize("value,expected", [
|
||||
(b"\x00", False),
|
||||
(b"\x01", True),
|
||||
(bytearray(b"\x00"), False),
|
||||
(bytearray(b"\x01"), True),
|
||||
(0, False),
|
||||
(1, True),
|
||||
(False, False),
|
||||
(True, True),
|
||||
("0", False),
|
||||
("1", True),
|
||||
("true", True),
|
||||
("Y", True),
|
||||
("", False),
|
||||
(None, False),
|
||||
])
|
||||
def test_all_three_legacy_shapes(self, mig, value, expected):
|
||||
assert mig.is_deleted(value) is expected
|
||||
|
||||
def test_naive_bool_would_have_deleted_everyone(self, mig):
|
||||
"""这条就是那个 bug 本身:125 个老账号因为 bool(b'\\x00') 全被当成已删除。"""
|
||||
assert bool(b"\x00") is True
|
||||
assert mig.is_deleted(b"\x00") is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 采购类别:存的是 procurement_type 的 id
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestResolveCategory:
|
||||
DICTIONARY = {"8": "华智产品", "9": "紫光其他产品", "12": "外购产品",
|
||||
"16": "汇智产品", "17": "华三产品", "10": "华智服务"}
|
||||
|
||||
def test_numeric_id_resolves_through_dictionary(self, mig, report):
|
||||
assert mig.resolve_category("8", self.DICTIONARY, report) == ("华智产品", "huazhi")
|
||||
assert mig.resolve_category("17", self.DICTIONARY, report) == ("华三产品", "h3c")
|
||||
assert report.counts["归一化:采购类别 id → 中文名"] == 2
|
||||
|
||||
def test_chinese_name_still_accepted(self, mig, report):
|
||||
"""少数老行直接存了中文名,两种都得认。"""
|
||||
assert mig.resolve_category("华三产品", self.DICTIONARY, report) == ("华三产品", "h3c")
|
||||
|
||||
def test_service_bucket_folds_into_brand(self, mig, report):
|
||||
assert mig.resolve_category("10", self.DICTIONARY, report) == ("华智服务", "huazhi")
|
||||
|
||||
def test_outside_the_four_buckets_counts_and_leaves_blank(self, mig, report):
|
||||
"""不在四个产品归属里:编码留空,但要按类别名计数,否则报告里查不到去向。"""
|
||||
mig.UNMAPPED_CATEGORY.clear()
|
||||
name, product = mig.resolve_category("12", self.DICTIONARY, report)
|
||||
assert (name, product) == ("外购产品", "")
|
||||
assert mig.UNMAPPED_CATEGORY == {"外购产品": 1}
|
||||
|
||||
def test_unmapped_counts_accumulate_instead_of_flooding_the_report(self, mig, report):
|
||||
"""老库自由文本几十个只出现一次的类别,一条条 skip 会把报告刷爆。"""
|
||||
mig.UNMAPPED_CATEGORY.clear()
|
||||
for raw in ("外购产品", "外购产品", "洪彦工程", "网线光纤"):
|
||||
mig.resolve_category(raw, self.DICTIONARY, report)
|
||||
assert mig.UNMAPPED_CATEGORY == {"外购产品": 2, "洪彦工程": 1, "网线光纤": 1}
|
||||
assert report.skips == {}
|
||||
|
||||
def test_free_text_and_empty(self, mig, report):
|
||||
assert mig.resolve_category(None, self.DICTIONARY, report) == ("", "")
|
||||
assert mig.resolve_category(" ", self.DICTIONARY, report) == ("", "")
|
||||
assert mig.resolve_category("洪彦工程", self.DICTIONARY, report)[:1] == ("洪彦工程",)
|
||||
|
||||
def test_known_id_beats_same_looking_text(self, mig, report):
|
||||
assert mig.resolve_category("16", self.DICTIONARY, report)[0] == "汇智产品"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 日期:DATE 列不接受空串
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestToDate:
|
||||
def test_datetime_and_date_string(self, mig):
|
||||
assert mig.to_date("2022-09-07 00:00:00") == date(2022, 9, 7)
|
||||
assert mig.to_date("2022-09-07") == date(2022, 9, 7)
|
||||
|
||||
def test_month_only_fills_first_day(self, mig):
|
||||
assert mig.to_date("2022-09") == date(2022, 9, 1)
|
||||
|
||||
@pytest.mark.parametrize("value", [None, "", " ", "0000-00-00", "abc"])
|
||||
def test_emptyish_becomes_null_not_empty_string(self, mig, value):
|
||||
"""MySQL 对 DATE 列写 '' 抛 1292,所以这里必须是 None。"""
|
||||
assert mig.to_date(value) is None
|
||||
|
||||
|
||||
class TestMonthOf:
|
||||
def test_formats(self, mig):
|
||||
assert mig.month_of("2022-09-07") == "2022-09"
|
||||
assert mig.month_of("2022-09") == "2022-09"
|
||||
assert mig.month_of(None) == ""
|
||||
assert mig.month_of("2022") == ""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 列宽:比率列撑不住老数据,就是那次 1264 Out of range
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestRateColumnWidth:
|
||||
def test_rate_columns_wide_enough_for_legacy_garbage(self):
|
||||
"""project.gross_profit_a_rate 曾经因为 DECIMAL(10,6) 撑不住 -49504 而整批插不进去。"""
|
||||
import app.models # noqa: F401
|
||||
from app.models.base import Base
|
||||
|
||||
rate_columns = [
|
||||
("project", "gross_profit_a_rate"),
|
||||
("project", "gross_profit_rate"),
|
||||
("project", "contribution_profit_rate"),
|
||||
("project", "advance_interest_rate"),
|
||||
("estimate_income_line", "tax_rate"),
|
||||
("estimate_cost_line", "tax_rate"),
|
||||
("budget_income_line", "tax_rate"),
|
||||
("budget_purchase_line", "tax_rate"),
|
||||
("budget_fund_month", "interest_rate"),
|
||||
]
|
||||
for table, column in rate_columns:
|
||||
col_type = Base.metadata.tables[table].columns[column].type
|
||||
capacity = col_type.precision - col_type.scale
|
||||
assert col_type.scale == 6, (table, column)
|
||||
assert capacity >= 12, f"{table}.{column} 只装得下 {capacity} 位整数部分"
|
||||
# -49504.00 必须能坐下
|
||||
assert abs(Decimal("-49504.00")) < Decimal(10) ** capacity
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 超长字符串兜底
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestClipGuard:
|
||||
def test_oversize_string_is_clipped_and_counted(self, mig):
|
||||
from app.models.finance import BudgetPurchaseLine
|
||||
|
||||
mig.install_clip_guard()
|
||||
mig.CLIPPED.clear()
|
||||
line = BudgetPurchaseLine(revision_id=1, project_id=1, purchase_type=1,
|
||||
name="x" * 400, pay_way="y" * 300)
|
||||
assert len(line.name) == 255 # 列宽从元数据现读
|
||||
assert len(line.pay_way) == 255
|
||||
assert mig.CLIPPED["budget_purchase_line.name"] == 1
|
||||
assert mig.CLIPPED["budget_purchase_line.pay_way"] == 1
|
||||
|
||||
def test_short_values_untouched(self, mig):
|
||||
from app.models.finance import BudgetPurchaseLine
|
||||
|
||||
mig.install_clip_guard()
|
||||
mig.CLIPPED.clear()
|
||||
line = BudgetPurchaseLine(revision_id=1, project_id=1, purchase_type=1,
|
||||
name="交换机", pay_way="转账")
|
||||
assert (line.name, line.pay_way) == ("交换机", "转账")
|
||||
assert mig.CLIPPED == {}
|
||||
|
||||
def test_text_columns_are_never_clipped(self, mig):
|
||||
"""TEXT 列装得下,截它才是丢数据。project.value_risk 就是 TEXT。"""
|
||||
from app.models.project import Project
|
||||
|
||||
mig.install_clip_guard()
|
||||
mig.CLIPPED.clear()
|
||||
long_text = "风险" * 4000
|
||||
project = Project(project_no="T1", name="p", creator_id=1, value_risk=long_text)
|
||||
assert project.value_risk == long_text
|
||||
assert mig.CLIPPED == {}
|
||||
|
||||
def test_guard_is_idempotent(self, mig):
|
||||
"""装两次不能截两遍 / 计两次。"""
|
||||
from app.models.finance import BudgetPurchaseLine
|
||||
|
||||
mig.install_clip_guard()
|
||||
mig.install_clip_guard()
|
||||
mig.CLIPPED.clear()
|
||||
line = BudgetPurchaseLine(revision_id=1, project_id=1, name="x" * 400)
|
||||
assert len(line.name) == 255
|
||||
assert mig.CLIPPED == {"budget_purchase_line.name": 1}
|
||||
|
||||
|
||||
class TestWideColumnsMatchLegacy:
|
||||
"""列宽对不齐老库,导数时就只有两种坏结果:报错或者悄悄截断。"""
|
||||
|
||||
def test_pay_way_holds_legacy_payment_clause(self):
|
||||
from app.models.base import Base
|
||||
|
||||
# 老 project_budget_cost_detail.pay_way 实测最长 136 字(合同付款条款)
|
||||
assert Base.metadata.tables["budget_purchase_line"].columns["pay_way"].type.length >= 255
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# project_visible:type 决定 tid 是"人"还是"角色"
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestVisibleTarget:
|
||||
"""老 project_visible 的 type=2 是**按人员**授权,不是按角色。
|
||||
|
||||
老版本按角色处理,两头都错:tid 撞上 sys_role 的那部分被批成整角色可见,
|
||||
真正的人数(15,302 行里 tid>33 的 14,357 行,sys_role 最大 id 才 33)
|
||||
整批当"老角色未导入"丢掉。这张表没有报错、只有静默的权限错配,所以钉住。
|
||||
"""
|
||||
|
||||
def test_type_2_is_per_person(self, mig):
|
||||
assert mig.visible_target(2) == "member"
|
||||
|
||||
def test_type_1_is_per_role(self, mig):
|
||||
assert mig.visible_target(1) == "role"
|
||||
|
||||
@pytest.mark.parametrize("value", [0, 3, None, "", "x", 2.5])
|
||||
def test_anything_else_is_not_guessed(self, mig, value):
|
||||
assert mig.visible_target(value) == ""
|
||||
|
||||
def test_legacy_tid_range_is_user_range(self, mig):
|
||||
"""老库 tid 落在 1~125(sys_user 的 id 区间),角色 id 最大只有 33。"""
|
||||
assert mig.LEGACY_VISIBLE_MEMBER == 2
|
||||
assert mig.LEGACY_VISIBLE_ROLE == 1
|
||||
|
||||
def test_member_role_is_viewer_not_participant(self, mig):
|
||||
"""按可见性授权的人不该算"我参与的"里的参与人,只能是仅可见。"""
|
||||
from app.models.project import ProjectMemberRole
|
||||
|
||||
assert ProjectMemberRole.VIEWER == "viewer"
|
||||
|
|
@ -0,0 +1,181 @@
|
|||
"""seed 与清理脚本一起守着的那两个账号:内置超管 + 本地应急管理员。
|
||||
|
||||
应急管理员必须是 seed 的一部分,而不是"谁记得就手动建一个":清库脚本会清 ``accounts``,
|
||||
重建库也会把它抹掉,而最需要它的恰恰是刚清完库、Hub 又配错、谁都进不去门的那一刻。
|
||||
这次翻过一次车,所以三条都钉住:seed 建得出、删了能长回来、它的口令绝不送去 Hub。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.config import settings
|
||||
|
||||
DB_READY = True
|
||||
try:
|
||||
from app.db import ensure_database, get_engine
|
||||
|
||||
ensure_database()
|
||||
with get_engine().connect() as _probe:
|
||||
_probe.exec_driver_sql("SELECT 1")
|
||||
except Exception: # pragma: no cover
|
||||
DB_READY = False
|
||||
|
||||
needs_db = pytest.mark.skipif(not DB_READY, reason="测试库连不上")
|
||||
|
||||
|
||||
def test_built_in_accounts_are_local_only_without_being_configured(monkeypatch):
|
||||
"""``local_only_accounts`` 写空也算数:内置的本地账号永远不去问 Hub。"""
|
||||
monkeypatch.setattr(settings.seed, "admin_account", "seedadmin", raising=False)
|
||||
monkeypatch.setattr(settings.seed, "emergency_account", "seedbackup", raising=False)
|
||||
monkeypatch.setattr(settings.hub, "local_only_accounts", "", raising=False)
|
||||
assert {"seedadmin", "seedbackup"} <= settings.hub.local_only_account_set
|
||||
|
||||
|
||||
def test_the_second_door_is_off_by_default(monkeypatch):
|
||||
"""默认只有一把本地门:``emergency_account`` 留空或跟超管同名,都不该多出第二个账号。"""
|
||||
monkeypatch.setattr(settings.seed, "emergency_account", "", raising=False)
|
||||
assert settings.seed.emergency_account == ""
|
||||
monkeypatch.setattr(settings.seed, "admin_account", "localadmin", raising=False)
|
||||
monkeypatch.setattr(settings.seed, "emergency_account", "localadmin", raising=False)
|
||||
from app.seed import _seed_emergency_admin # 同名时不该建号,也不该报错
|
||||
|
||||
assert _seed_emergency_admin(_NullSession()) == 0
|
||||
|
||||
|
||||
class _NullSession:
|
||||
"""同名那条分支在查库之前就返回,所以不需要真会话。"""
|
||||
|
||||
def execute(self, *_a, **_kw):
|
||||
raise AssertionError("账号名与内置超管相同时,不该去查库")
|
||||
|
||||
|
||||
def test_clean_script_protects_the_built_in_accounts(monkeypatch):
|
||||
"""清理脚本留着的账号必须跟 seed 建的是同一批,否则清一次库门就没了。"""
|
||||
import sys
|
||||
from pathlib import Path as _Path
|
||||
|
||||
sys.path.insert(0, str(_Path(__file__).resolve().parent.parent / "scripts"))
|
||||
import clean_demo_data
|
||||
|
||||
monkeypatch.setattr(settings.seed, "admin_account", "seedadmin", raising=False)
|
||||
monkeypatch.setattr(settings.seed, "emergency_account", "seedbackup", raising=False)
|
||||
assert set(clean_demo_data._protected_accounts()) == {"seedadmin", "seedbackup"}
|
||||
|
||||
# 第二把门关着时就只剩一个,且不会漏出空字符串
|
||||
monkeypatch.setattr(settings.seed, "emergency_account", "", raising=False)
|
||||
assert clean_demo_data._protected_accounts() == ("seedadmin",)
|
||||
|
||||
|
||||
@needs_db
|
||||
def test_seed_creates_the_emergency_admin_when_the_library_lacks_it(client, monkeypatch):
|
||||
"""库里没有这个账号时 seed 要能把它建出来:在编、系统管理员、本地口令可用。
|
||||
|
||||
故意换一个探针名字来验"从零建号",不去删真账号——真账号可能被业务单据引用
|
||||
(``biz_revision.creator_id`` 是 RESTRICT),删它等于把用例变成清理现场。
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import delete, select
|
||||
|
||||
from app.db import SessionFactory
|
||||
from app.models import Account, PermAccountRole, Status
|
||||
from app.security import verify_password
|
||||
from app.seed import seed_all
|
||||
|
||||
probe = f"seedprobe{datetime.now():%H%M%S%f}"
|
||||
password = settings.seed.emergency_password or "Probe@12345"
|
||||
monkeypatch.setattr(settings.seed, "emergency_account", probe, raising=False)
|
||||
monkeypatch.setattr(settings.seed, "emergency_password", password, raising=False)
|
||||
|
||||
assert seed_all()["emergency"] == 1, "库里没有应急账号时 seed 必须把它建出来"
|
||||
assert seed_all()["emergency"] == 0, "已经有了就不该重复建号"
|
||||
|
||||
with SessionFactory()() as db:
|
||||
row = db.execute(select(Account).where(Account.account == probe)).scalars().first()
|
||||
assert row is not None, "seed 报了建号却没落库"
|
||||
assert row.is_system_admin, "应急管理员得是全权限"
|
||||
assert row.source == "local" and row.status == Status.ACTIVE
|
||||
assert row.hub_user_id is None, "本地应急账号不该带统一身份主键"
|
||||
assert verify_password(password, row.password_hash)
|
||||
assert not verify_password(f"{password}-不对", row.password_hash)
|
||||
db.execute(delete(PermAccountRole).where(PermAccountRole.account_id == row.id))
|
||||
db.delete(row)
|
||||
db.commit()
|
||||
|
||||
|
||||
@needs_db
|
||||
def test_local_admin_password_never_leaves_the_system(client, monkeypatch):
|
||||
"""内置本地账号的口令只在本系统校验——就算整档是 ``login_mode = hub``。
|
||||
|
||||
这是本地门的全部意义:Hub 密钥配错、应用没登记的时候还得进得去门。这条一旦破功,
|
||||
"应急入口"就跟着 Hub 一起挂掉了。
|
||||
"""
|
||||
from app.api import auth as auth_api
|
||||
from app.service import hub_api
|
||||
|
||||
def boom(*args, **kwargs):
|
||||
raise AssertionError("内置本地账号的口令不该被送去统一身份")
|
||||
|
||||
monkeypatch.setattr(auth_api.settings.hub, "login_mode", "hub", raising=False)
|
||||
monkeypatch.setattr(hub_api, "login_with_password", boom)
|
||||
|
||||
names = [settings.seed.admin_account, settings.seed.emergency_account]
|
||||
for name in [n for n in names if n]:
|
||||
password = (settings.seed.admin_password if name == settings.seed.admin_account
|
||||
else settings.seed.emergency_password)
|
||||
if not password:
|
||||
continue # 随机口令的部署拿不来登,交给 seed 那条用例验
|
||||
response = client.post("/api/v1/auth/login", json={"account": name, "password": password})
|
||||
assert response.status_code == 200, f"{name} 登不上:{response.text}"
|
||||
data = response.json()["data"]
|
||||
assert data["via"] == "local"
|
||||
assert data["user"]["isSystemAdmin"] == 1
|
||||
|
||||
|
||||
@needs_db
|
||||
def test_legacy_duplicate_configs_merge_into_calc_then_disappear():
|
||||
"""两条"界面上有、内核从不读"的重复参数只能留一套口径。
|
||||
|
||||
搬完还得承认人在界面上存过的值,同时不能把口径页上后来改的值盖掉。用例整个跑在
|
||||
一个回滚掉的事务里——这是台共用的开发库。
|
||||
"""
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.db import SessionFactory
|
||||
from app.models import SystemConfig
|
||||
from app.seed import _seed_configs
|
||||
from app.service.calc import rules
|
||||
|
||||
spec = rules.SPECS_BY_CODE["calc.company_manage_fee_rate"]
|
||||
session = SessionFactory()()
|
||||
try:
|
||||
target = session.execute(select(SystemConfig).where(
|
||||
SystemConfig.code == spec.code)).scalars().first()
|
||||
assert target is not None, "startup seed 该把 calc.* 补齐"
|
||||
original_value = target.value
|
||||
original_type = target.value_type
|
||||
|
||||
session.add(SystemConfig(code="finance.company_manage_fee_rate",
|
||||
name="公司管理费用率(%)", value="3.5", value_type="number",
|
||||
group="calc", remark="旧参数"))
|
||||
session.flush() # sessionmaker 关着 autoflush,不 flush 这条旧参数查不出来
|
||||
# 假装新编码从没被改过,看看旧值搬不搬得过来
|
||||
target.value = spec.default_text
|
||||
assert _seed_configs(session) >= 0
|
||||
session.flush()
|
||||
|
||||
assert target.value == "3.5", "界面上存过的值必须在迁移时被承认"
|
||||
assert session.execute(select(SystemConfig).where(
|
||||
SystemConfig.code == "finance.company_manage_fee_rate")).scalars().first() is None, \
|
||||
"旧参数合并完就该删掉,别留两处口径"
|
||||
assert session.execute(select(SystemConfig).where(
|
||||
SystemConfig.code == "budget.travel_business_limit_rate")).scalars().first() is None
|
||||
|
||||
# 再跑一次不该重复插,也不该把值改回去
|
||||
assert _seed_configs(session) == 0
|
||||
assert target.value == "3.5"
|
||||
finally:
|
||||
session.rollback()
|
||||
session.close()
|
||||
assert original_value is not None and original_type == "number"
|
||||
|
|
@ -0,0 +1,299 @@
|
|||
# 前端布局方案(使用方视角)
|
||||
|
||||
> 适用系统:四算项目管理系统(fourcal-pms)
|
||||
> 覆盖范围:项目立项(概算)、项目预算、审批流程,以及配套的流程配置、角色权限、数据权限、菜单权限、系统账号、组织架构
|
||||
> 技术参照:sub2api 前端组件体系(Vue 3 + TypeScript + Tailwind + Pinia)
|
||||
|
||||
---
|
||||
|
||||
## 1. 布局要解决的真正问题
|
||||
|
||||
老系统(fourcal)的页面不是"不好看",而是**把系统的数据库结构直接摊在了屏幕上**。
|
||||
|
||||
最典型的就是送审前的预算录入页。原来是这样两层页签:
|
||||
|
||||
```
|
||||
┌ 项目立项(概算)信息 │ 项目预算信息 │ 项目审核记录 ┐ ← 第一层:业务对象
|
||||
└──────────────────────────────────────────────────┘
|
||||
┌ 项目基本信息 │ 预算信息 │ 收入明细表 │ 收款计划表 │ 采购成本明细表 │
|
||||
│ 付款计划表 │ 项目管理费用表 │ 资金计划表 ┐ ← 第二层:明细表
|
||||
└──────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
从填表人的角度看,这套结构有五个硬伤:
|
||||
|
||||
1. **页签数量超过一屏能记住的量**。8 个二级页签,眼睛要在页签条和表格之间来回确认"我现在在哪个表"。
|
||||
2. **录入时看不到结果**。毛利率、资金峰值在"预算信息"页签里,而正在改的数字在另外 6 个页签里。填表人的实际动作是"改一个数 → 切页签看结果 → 切回来改下一个"。
|
||||
3. **校验只在送审那一刻集中爆发**。填的时候一切正常,点"送审"才弹出十几条错误,得一条条回忆是哪个表哪个格子。
|
||||
4. **两张表之间的距离是一次页签切换**,而收入明细表和收款计划表本来必须相互勾稽,隔得最远的恰恰是最该对照看的。
|
||||
5. **嵌套页签的层级本身不可导航**。URL 只到项目,不到页签,收藏/回退/两个人协同看同一个表都做不到。
|
||||
|
||||
根因:**页签是按"数据表"划分的,而用户脑子里的单位是"我要完成的一件业务动作"。**
|
||||
|
||||
---
|
||||
|
||||
## 2. 总体信息架构
|
||||
|
||||
导航只有两层,第二层不用页签,用**目录**。
|
||||
|
||||
```
|
||||
侧边栏(服务端下发,按权限裁剪)
|
||||
├── 工作台 我的待办 / 我的已办 / 我发起的 / 审批委托
|
||||
├── 项目管理 项目列表 → 项目工作台(概算 / 预算 / 项目档案)
|
||||
├── 审批中心 流程监控 / 流程配置
|
||||
├── 组织与人员 组织架构 / 系统账号 / 岗位 / 统一身份同步
|
||||
└── 系统管理 角色与权限 / 数据权限 / 菜单与权限码 / 业务参数
|
||||
```
|
||||
|
||||
三条原则:
|
||||
|
||||
- **菜单来自 `/bootstrap`,前端不再抄一份权限表**。角色看不看得见某个入口,取决于后端有没有把它下发,不会出现"前端藏了、后端没拦"。
|
||||
- **一个业务对象只在工作台里做一次切分**。概算 / 预算 / 项目档案是三个**互不相干的评审对象**,用一级页签;它们各自内部的明细,一律用目录,不再出现第二层页签。
|
||||
- **路由到段落为止**。`/projects/:id/budget` 之外还带 `?section=purchase`,收藏、回退、把链接甩给同事都能精确到某张表。
|
||||
|
||||
---
|
||||
|
||||
## 3. 核心改动:录入工作台从"页签堆"改成"三栏"
|
||||
|
||||
这是整个方案里唯一需要认真设计的页面,其余页面都是它的下游。
|
||||
|
||||
```
|
||||
┌────────────────────────────────────────────────────────────────────────────┐
|
||||
│ 面包屑:项目管理 › 项目 #36 › 项目预算 │
|
||||
├────────────────────────────────────────────────────────────────────────────┤
|
||||
│ ← 复核项目-72BFBE [S3-预算评估] [2026.10] [草稿] [v2 草稿▾] [重新试算] [送审] │
|
||||
│ ────────────────────────────────────────────────────────────────────────── │
|
||||
│ 概算 │ (预算) │ 项目档案 ← 只有一层页签 │
|
||||
├──────────────┬────────────────────────────────────────┬────────────────────┤
|
||||
│ 项目预算 │ 合同额 11,300,000.00 不含税收入 10,000,000.00 … ← 常驻汇总条 │
|
||||
│ ├────────────────────────────────────────┼────────────────────┤
|
||||
│ ▸ 基本信息 ✓ │ │ ┌────────────────┐ │
|
||||
│ 收入明细 ✓ │ │ │ 毛利与贡献利润 │ │
|
||||
│ 收款计划 ✓ │ 当前段落 │ │ 不含税收入 1000万│ │
|
||||
│ ▸ 采购成本 ✓ │ (一次只放一张表, │ │ 采购成本 600万 │ │
|
||||
│ 付款计划 ✓ │ Excel 式行内编辑) │ │ 采购毛利 400万 │ │
|
||||
│ 管理费 ✓ │ │ │ 减 管理费 8万 │ │
|
||||
│ 其他成本 │ │ │ 减 财务费 6.8万│ │
|
||||
│ 资金计划 │ │ │ 项目毛利 385万 │ │
|
||||
│ 汇总与结果 │ │ │ 贡献利润 357万 │ │
|
||||
│ │ │ └────────────────┘ │
|
||||
│ ┌──────────┐ │ │ ┌────────────────┐ │
|
||||
│ │改完即自动 │ │ │ │ 提交前校验 │ │
|
||||
│ │重算 │ │ │ │ ● 全部通过 │ │
|
||||
│ └──────────┘ │ │ └────────────────┘ │
|
||||
│ │ │ ┌────────────────┐ │
|
||||
│ │ │ │ 审批记录 │ │
|
||||
│ │ │ │ 张三 审批通过 │ │
|
||||
└──────────────┴────────────────────────────────────────┴────────────────────┘
|
||||
左:目录栏 3 栏 中:录入区 右:常驻决策栏
|
||||
```
|
||||
|
||||
### 3.1 左栏:目录,不是页签
|
||||
|
||||
- 目录项 = 原来那 8 个二级页签,**数量一个没少,但层级降了一层**。
|
||||
- 每个目录项带两个状态标记:**未保存小圆点**(这一段的改动还没存)和 **错误计数徽标**(这一段有几条校验没过)。送审被拦时,不用点进去就知道该改哪儿。
|
||||
- 顺序按**填写顺序**而不是按表名字母:先录入和采购,再录收付款计划,最后看资金计划和汇总。资金计划是由收付款计划推导出来的,放在后面,用户不会误以为要手填。
|
||||
- 目录宽度可折叠。窄屏(<1280px)自动收成图标条,鼠标悬停出全名。
|
||||
|
||||
### 3.2 中栏:一次只做一张表
|
||||
|
||||
- 表格是 **Excel 式行内编辑**:单元格即输入框,去掉了"编辑/保存/取消"三件套。财务录入的本质是抄一张 Excel,多点一次"编辑"就多一次打断。
|
||||
- 数字列一律**右对齐 + 等宽数字**(`tabular-nums`),小数点上下对齐比字号更重要。
|
||||
- 表尾常驻合计行,边填边加,不用等保存。
|
||||
- **按段批量保存**,不做逐格保存。逐格保存会让一次误触产生十几次重算,也会让"这一段的改动"失去整体感。
|
||||
- 保存后**位置不丢**:仍在同一个目录项、同一个滚动位置,金额与校验同步刷新。这是"改完即重算"能用的前提——如果每次重算都把人弹回顶部,功能就变成了打扰。
|
||||
|
||||
### 3.3 右栏:算完了就摆在旁边
|
||||
|
||||
这一栏是三栏布局的全部理由。它在录入过程中**始终可见**,滚动时吸附不动。
|
||||
|
||||
| 模块 | 内容 | 为什么必须在旁边 |
|
||||
| --- | --- | --- |
|
||||
| 毛利与贡献利润 | 从不含税收入一路扣到贡献利润的阶梯,每层显示金额与占比 | 改任何一个数,第一反应是"毛利变了多少"。原来要切两个页签 |
|
||||
| 提交前校验 | 通过 / 未通过条数,点开定位到具体段落与字段 | 把送审时的报错前移成实时提示 |
|
||||
| 审批记录 | 时间线:谁在哪个节点、什么动作、什么意见 | 改预算时最常见的一句话是"上次是谁驳回的、驳的哪一条" |
|
||||
|
||||
利润率一律用**后端返回的 Ratio 对象**渲染:分母为 0 时显示"—(分母为 0)",而不是硬塞一个 0%。老系统在这里塞过 0、也塞过"利润×100",两种都误导人。
|
||||
|
||||
### 3.4 顶部汇总条
|
||||
|
||||
`合同额 / 不含税收入 / 采购成本 / 项目毛利 / 毛利率 / 贡献利润率 / 垫资峰值 / 资金成本` 八个指标常驻在页签下方。
|
||||
|
||||
它和右栏不重复:汇总条回答"这个项目现在几个大数是多少",右栏回答"这个数是怎么一层层扣出来的"。
|
||||
|
||||
---
|
||||
|
||||
## 4. 其余页面的布局
|
||||
|
||||
### 4.1 项目列表(`/projects`)
|
||||
|
||||
标准表格页:`TablePageLayout` = 标题 + 筛选条 + 表格 + 分页。
|
||||
|
||||
- 筛选条一行放得下:关键字、阶段、类型、归属部门、我参与的开关。**筛选状态写进 URL**,从详情页返回列表时不丢筛选。
|
||||
- 金额列用"万元"压缩(`formatWan`):项目金额动辄八位数,千分位读起来仍然慢,万元单位在列表密度下更快。
|
||||
- 行内操作只留高频:进入概算、进入预算、更多(阶段推进 / 成员 / 删除)。其余进详情页。
|
||||
- 删除是**软删除**,规则由后端一处给:确认框先打 `GET /projects/{id}/delete-check` 拿影响面
|
||||
(版本数 / 成员 / 附件 / 审批记录),审批还在流转就挡住删除,其余只提示不拦。删掉的项目连同
|
||||
概算预算一起从业务视图消失,勾"只看已删除"进回收站可恢复;谁删的、什么时候、写的原因
|
||||
留在 `project` 行上,同时进 `operation_log`。
|
||||
- 回收站行操作是**恢复 + 彻底删除**两个按钮,销毁走独立的权限码 `project:project:purge`
|
||||
(默认只给系统管理员),确认框要回敲项目编号,且项目一旦留有审批痕迹就不允许销毁。
|
||||
详见《操作审计》。
|
||||
- 表头带**数据范围提示**(`scope`):当前看到的是"本部门及下级"还是"仅本人"。数据权限是配置出来的,不写出来的话用户只会以为"数据丢了"。
|
||||
|
||||
### 4.2 项目档案(`/projects/:id`)
|
||||
|
||||
详情页不是录入页,只读为主:基本信息两列定义列表、成员、阶段流转、审批记录。维护动作跳回 `ProjectFormView`,避免"详情页里混着能编辑的格子"这种含混状态。
|
||||
|
||||
利率这类 Decimal(20,6) 字段在详情页统一格式化成 `6.00%`,不露出 `6.000000` 的尾巴。
|
||||
|
||||
### 4.3 工作台(`/workbench/todo`)
|
||||
|
||||
待办不是普通列表:**卡片行**而不是表格行,因为办理人关心的是"这个项目、到这一步、什么时候到期",三件事要在一次扫视内读完。
|
||||
|
||||
- 一行卡片:项目名(大)· 节点名 · 或签/会签 · 提交人 · 到期时间。
|
||||
- 审批动作直接落在卡片上:同意 / 驳回 / 退回到节点 / 转办 / 加签,展开后才出现意见输入框。
|
||||
- **批量办理**:勾选多行 → 一次同意(意见统一填)。例会集中清待办是常态,逐条点二十次不合理。
|
||||
- 有权限时显示"去单据",直接跳到对应项目的预算工作台并定位到该看的段落。
|
||||
|
||||
### 4.4 流程监控(`/approvals/monitor`)+ 流程详情抽屉
|
||||
|
||||
给管理员看的"卡在哪儿"视图,用表格(要看的是全量、要排序、要比较,卡片在这里反而低效)。
|
||||
|
||||
点行打开**右侧抽屉**(不是居中弹窗):
|
||||
|
||||
- 抽屉占屏 640px,右侧滑入。**监控列表始终可见**——管理员的动线是"扫列表 → 看一眼这条 → 关掉 → 看下一条",居中弹窗会把列表完全盖住,每看一条都要重新定位。
|
||||
- 抽屉三段:元信息(当前节点 / 发起人 / 提交与结束时间)· **节点进度**(同一节点的会签多人合并成一组,待办人直接挂在节点上)· 操作流水(含自动跳过、超时、转办,审计口径完整)。
|
||||
- 底部动作按身份出现:本人有代办→"去办理";本人是发起人→"撤回";有单据权限→"查看单据"。
|
||||
|
||||
### 4.5 流程配置(`/approvals/flows/:id`)
|
||||
|
||||
配置流程的人脑子里想的是"先部门、再财务、再分管领导"这条**线**,所以主视图是纵向节点链,不是表单列表。
|
||||
|
||||
- 每个节点一张卡:名称、类型、或签/会签/依次、候选人来源(角色 / 指定人 / 部门负责人 / 部门链上溯 N 级)、找不到人时的兜底策略、超时时长与动作。
|
||||
- 条件表达式保留后端 DSL 字符串(`contract_amount>=5000000 and type in [1,2]`),但旁边给出**人类可读复述**,避免配置人员被语法劝退。
|
||||
- **已发布的流程只读**,要改必须先下线。页面上直接禁用编辑并说明原因,而不是等保存时报错。
|
||||
- 发布前跑一次校验(错误列表来自后端),有错不允许发布。
|
||||
|
||||
### 4.6 数据权限(`/system/data-permission`)
|
||||
|
||||
配置数据权限最大的心理障碍是**不知道配完谁看得见什么**。所以这一页的中心不是策略表格,而是**当场验证**。
|
||||
|
||||
- 左侧策略列表(模块 / 主体 / 效果 / 范围 / 优先级),右侧编辑面板。
|
||||
- 编辑面板底部常驻 **"以某账号试算可见范围"**:选一个账号,后端 `/system/data-policies/explain` 返回这一条最终翻译成人话的范围描述。配置者不用靠脑子推演"allow 取并集、deny 再排除"。
|
||||
- 自定义条件用**条件树 UI**(and/or 可嵌套),字段下拉来自后端注册的可过滤字段白名单,不允许手输列名——手输早晚写错成一个悄悄失效的条件。
|
||||
- 效果分"允许"和"排除"两种配色(青 / 红),一眼区分正负向规则。
|
||||
|
||||
### 4.7 组织架构 / 系统账号
|
||||
|
||||
- 组织架构:左树右表。树支持禁用节点开关(历史数据要能在禁用节点下看到),右表是该部门成员 + 兼岗身份。
|
||||
- 系统账号:表格 + 抽屉编辑,角色、岗位、身份(部门)都是多选。**统一身份(Hub)来源的账号禁止本地改口令**,输入框直接禁用并说明来源。
|
||||
- 所有"选一个部门 / 选一个人"的地方都用同一套 `UnitTreeSelect` 与账号下拉,且走 `/org/accounts/options`(精简列表,不分页)。早期这里用分页接口取 300 条,撞了接口 `pageSize<=200` 的上限直接报错,而且人一多就会静默截断——选择器缺人是最难被发现的一类 bug。
|
||||
|
||||
### 4.8 角色与权限 / 菜单与权限码
|
||||
|
||||
- 角色与权限:左角色列表、右权限树。权限树用后端下发的**树**(带 `children`),不是平铺后前端猜父子。勾选父节点级联子节点,保存只提交叶子,减少前后端来回。
|
||||
- 菜单与权限码:只读权限树 + 编辑抽屉。这一页存在的意义是让"前端某个按钮该挂哪个码"有处可查,因此**权限码原文必须可选中复制**。
|
||||
|
||||
---
|
||||
|
||||
### 4.8b 操作日志(`/system/operation-logs`)
|
||||
|
||||
审计页是"标准表格页 + 两个页签",不玩花活:一行一笔操作,点开出明细。
|
||||
|
||||
- 页签切换不换路由(审计是同一件事的两个视角:进来之后改了什么 / 谁进过系统)。
|
||||
- 筛选条只有下拉与开关,动作与对象类型的取值来自后端"这段时间真出现过的"聚合,不摆空选项。
|
||||
- 失败的操作在结果列直接显示状态码与错误原因,不用点进去;点开后还有脱敏请求体与 `traceId`。
|
||||
- 全量口径与脱敏规则见《操作审计》。
|
||||
|
||||
### 4.9 登录页与免登落地(`/login`、`/sso/launch`)
|
||||
|
||||
统一身份开启后,登录页**不再保留口令表单**,只剩一张"请到统一门户点击本应用进入"的说明卡。
|
||||
理由不是省事:人已经在 Hub 那边了,本系统再留一个口令入口,等于同一批人两套凭据、两套锁定
|
||||
策略、两套改密流程,而离职下线只生效在一边。
|
||||
|
||||
所以布局上只有一个开关:`/bootstrap` 下发的 `localPasswordAllowed`。
|
||||
|
||||
| 状态 | 登录页 |
|
||||
| --- | --- |
|
||||
| Hub 未启用 | 账号 + 口令表单(开发档、独立部署) |
|
||||
| Hub 已启用 | 撤掉表单,显示"从统一门户进入"引导;逃生门只放行本地超管,界面上不再提示口令 |
|
||||
|
||||
`/sso/launch` 是门户 302 回来的落地页,它不是普通页面,处理的是**一次性票据**:
|
||||
|
||||
- 进页面第一件事是 `history.replaceState` 把 `ticket` 从地址栏抹掉。票据会过期、会被复制、
|
||||
会进 Referer,留在 URL 上等于把一次性的东西变成可分享的。
|
||||
- 中间态必须有明确的"正在校验"反馈。免登是"点一下就进来",如果中间空白,用户会以为没点上
|
||||
再点一次,而第二张票必然失效——**空白等待在这里是会制造故障的**。
|
||||
- 失败**不自动重试**,按 Hub 给的 `reason` 分句说人话并给出路:票据过期 → "回门户重新点";
|
||||
账号停用 → "联系管理员";密钥不匹配 → 明确写成配置问题,不要让用户以为是自己密码错了。
|
||||
|
||||
### 4.10 统一身份同步(`/org/hub-sync`)
|
||||
|
||||
这页要回答的是运维的一句话:"到底通没通、刚才同步做了什么、为什么人少了"。
|
||||
|
||||
- **两条密钥分开显示**(目录密钥 / 免登应用密钥)。它们各管一段接口、互不通用,配错最常见的
|
||||
表现是"同步下来是空的",合并成一个"凭据已配置"就会把人引向错误的排查方向。
|
||||
- **两个动作分开**:`拉增量` 只按游标取变更事件,`全量同步` 才是把平台现在的样子盖到本地。
|
||||
人员资料微调不产生事件,增量补不到;合成一个"立即同步",使用者事后对不上账时无从判断该点哪个。
|
||||
- **游标要可见并解释 0**。游标为 0 意味着从没成功全量过、增量无从谈起;不给这句解释,
|
||||
运维只会看到"游标 0"然后以为同步坏了。
|
||||
- 最近一次结果按 `success / partial / failed / skipped` 四态着色,并把 `error` 原文摊开。
|
||||
这个接口 HTTP 层恒 200,如果界面只显示"同步完成",就等于把对端故障粉饰成同步成功。
|
||||
|
||||
|
||||
## 5. 组件层(对齐 sub2api 约定)
|
||||
|
||||
沿用 sub2api 的类名与结构,团队换项目不用换肌肉记忆:
|
||||
|
||||
| 类别 | 组件 / 类名 |
|
||||
| --- | --- |
|
||||
| 按钮 | `btn` `btn-primary` `btn-secondary` `btn-ghost` `btn-danger` `btn-success` `btn-sm` `btn-icon` |
|
||||
| 表单 | `Input` `TextArea` `Select`(teleport 下拉,避免被容器裁切)`Toggle` `SearchInput` |
|
||||
| 表格 | `DataTable`(列定义 + 插槽 + 行点击)`Pagination` |
|
||||
| 容器 | `card` `card-header` `card-title` `TablePageLayout` `BaseDialog` `ConfirmDialog` |
|
||||
| 状态 | `StatusBadge` `StatCard` `EmptyState` `Skeleton` `SkeletonTable` `LoadingSpinner` `ToastHost` `HelpTooltip` |
|
||||
| 数字 | `MoneyText` + `formatMoney` / `formatWan` / `formatPercent` / `formatRatio` |
|
||||
| 图标 | lucide-vue-next,统一走 `Icon.vue` 做"后端菜单图标字符串 → 图标组件"的映射 |
|
||||
|
||||
深色模式沿用 `dark:` + `dark-800/950` 灰阶,录入页深浅两色的数字对齐一致。
|
||||
|
||||
### 5.1 金额与比率的前端纪律
|
||||
|
||||
- 金额**从后端到前端全程字符串**,前端任何地方都不 `Number(x).toFixed()` 一个大额数字(超过 2^53 会静默丢精度)。
|
||||
- 比率后端给的是"百分数本身"(13 表示 13%),前端只加 `%`,不再乘 100。
|
||||
- 空值统一渲染破折号,输入框里统一空串,不把 `0` 当成"没填"——库里没填就是 `0.00`,这个区别在算毛利时是真 bug。
|
||||
|
||||
---
|
||||
|
||||
## 6. 交互细则(决定"用起来顺不顺"的部分)
|
||||
|
||||
| 场景 | 规则 |
|
||||
| --- | --- |
|
||||
| 保存 | 段落级批量保存;保存中按钮 loading 且禁用,防重复提交 |
|
||||
| 重算 | 保存成功后端自动重算,前端原位刷新金额与校验,不跳滚动位置 |
|
||||
| 未保存离开 | 路由守卫拦截,提示"有 N 段未保存" |
|
||||
| 校验 | 送审前 400 返回结构化错误,前端把错误数标到对应目录项上并定位第一条 |
|
||||
| 错误提示 | 后端错误体带 `traceId`,Toast 一并显示,用户能直接贴给运维查日志 |
|
||||
| 空态 | 区分"还没有数据"和"没有权限看数据",文案不同,动作不同 |
|
||||
| 加载 | 首屏骨架屏(`SkeletonTable`),不用全屏转圈盖住结构 |
|
||||
| 破坏性动作 | 撤回、删除、下线流程一律二次确认;撤回需要填原因并写进审批流水 |
|
||||
| 令牌过期 | 静默用 refresh token 续期并重放原请求一次,用户无感 |
|
||||
| 键盘 | 表格内回车到下一格,Enter 提交,Esc 关抽屉/弹窗 |
|
||||
|
||||
---
|
||||
|
||||
## 7. 响应式与可达性
|
||||
|
||||
- **≥1280px**:完整三栏。
|
||||
- **1024–1280px**:右栏收成底部吸附条(点击展开完整阶梯),保证"改完能看到结果"这条不打折。
|
||||
- **<1024px**:左目录折叠为图标条;表格横向滚动,首列冻结。移动端定位是**查看与审批**,不承担预算录入——财务表格在手机上填是不体面的,我们不做半残的移动端录入。
|
||||
- 焦点环统一 `focus:ring-2`,深浅两色都可见;纯图标按钮一律带 tooltip 说明。
|
||||
- 正文对比度按 WCAG AA 校验;数字弱化态(灰色)仍保证 4.5:1。
|
||||
|
||||
---
|
||||
|
||||
## 8. 一句话总结
|
||||
|
||||
> 把"按数据表分的页签"换成"按填写顺序排的目录",把"要切页签才能看到的计算结果"搬到右手边常驻,
|
||||
> 再把送审那一刻才爆发的校验提前成实时提示——录入还是那些录入,但用户不再需要记住自己在哪里、也不再需要猜结果。
|
||||
|
|
@ -0,0 +1,205 @@
|
|||
# 审批流程设计
|
||||
|
||||
> 对应实现:`backend/app/service/approval/{engine,flow,candidates}.py`、
|
||||
> `backend/app/models/approval.py`、`backend/app/api/approvals.py`;
|
||||
> 前端 `frontend/src/views/approval/*` 与 `frontend/src/components/project/ApprovalTimeline.vue`
|
||||
|
||||
## 1. 为什么把 Activiti 整个拆掉
|
||||
|
||||
老系统用 Activiti 6 跑审批。它带来的不是能力,而是三笔长期成本:
|
||||
|
||||
1. **业务和流程隔着两张库**。项目状态在 `project`,流程实例在 `act_ru_task`,中间靠
|
||||
`project_instance_relation` 存一个流程实例 id 字符串。想显示"这单现在谁在审",
|
||||
要跨四张表 join,列表页因此一律不显示,只能点进详情。
|
||||
2. **改一个节点要发版**。节点、候选人、条件写死在 `.bpmn` 里,业务说"财务审核之后加一个
|
||||
分管领导"就得改流程定义、重新部署、回归。
|
||||
3. **表单和流程版本对不上**。流程定义升版后,在途实例还挂在旧版本上,
|
||||
而业务表只有一份当前数据,回看审批历史时看到的已经不是当时送审的那份数字。
|
||||
|
||||
新系统只做审批真正需要的东西:**流程定义 → 节点 → 实例 → 待办 → 流水**,五张表,全在同一
|
||||
个库、同一套 ORM、同一个事务里。
|
||||
|
||||
## 2. 模型
|
||||
|
||||
```
|
||||
approval_flow 流程定义(一个业务模块可配多条,按条件匹配)
|
||||
└ approval_node 节点(顺序、候选人、空签方式、条件、兜底、超时)
|
||||
approval_instance 一次送审(冻结业务版本与判定变量)
|
||||
├ approval_task 待办:某人在某节点上的一个待办
|
||||
└ approval_record 流水:谁在什么时候做了什么(含系统动作)
|
||||
approval_delegate 委托:某人休假期间整体转交
|
||||
```
|
||||
|
||||
### 2.1 `approval_flow`
|
||||
|
||||
| 字段 | 作用 |
|
||||
| --- | --- |
|
||||
| `key` / `name` / `version` | 流程标识、名称、版本 |
|
||||
| `business_module` | 挂在哪个业务:`estimate` / `budget` / `settlement` / `final` |
|
||||
| `status` | `draft` / `published` / `offline` |
|
||||
| `match_json` | 匹配条件:同一模块可按项目类型、金额区间走不同流程 |
|
||||
| `priority` | 多条已发布流程同时匹配时的取舍 |
|
||||
| `allow_self_select` | 送审人能否自己选审批人 |
|
||||
| `auto_skip_duplicate` | 与前序节点审批人重复时自动跳过 |
|
||||
|
||||
匹配规则在 `flow.match_flow()`:先按 `business_module` 过滤已发布流程,再用 `match_json`
|
||||
判定,多条命中取 `priority` 最小者。**没有匹配到流程时送审直接报错并说明原因**,
|
||||
不会静默走一条默认流程——静默兜底是"这单怎么跑到我这儿来了"的来源。
|
||||
|
||||
### 2.2 `approval_node`
|
||||
|
||||
| 字段 | 作用 |
|
||||
| --- | --- |
|
||||
| `node_key` / `name` / `order_number` | 节点标识、名称、顺序 |
|
||||
| `node_type` | `start` / `approve` / `cc`(抄送,不阻塞)/ `condition`(自动判定,不产生待办)/ `end` |
|
||||
| `sign_type` | `any` 或签 / `all` 会签 / `order` 依次审批 |
|
||||
| `candidates_json` | 候选人来源,见 2.3 |
|
||||
| `empty_strategy` | 找不到人时:`error` 阻塞 / `skip` 跳过节点 / `admin` 转系统管理员 |
|
||||
| `condition_json` | 满足才进入本节点,空表示无条件 |
|
||||
| `next_node_key` | 通过后去向:默认下一个 `order_number`,也可指定 |
|
||||
| `reject_to` | 驳回去向:`end` 直接结束 / `initiator` 退回发起人 / 指定节点 |
|
||||
| `rollback_keys_json` | 允许退回到的节点集合 |
|
||||
| `comment_required` / `reject_comment_required` | 通过 / 驳回时意见是否必填 |
|
||||
| `timeout_hours` / `timeout_action` | 限时与超时动作:`remind` / `auto_approve` / `none` |
|
||||
|
||||
**`empty_strategy` 是必填设计**。老系统找不到审批人时报一个空指针,运维来查半天,
|
||||
最后手工往 `act_ru_identitylink` 里塞人。现在必须显式选择怎么办,默认 `admin`。
|
||||
|
||||
### 2.3 候选人来源
|
||||
|
||||
`candidates_json` 是数组,可混用,结果去重:
|
||||
|
||||
```json
|
||||
[ { "type": "role", "ids": [4] },
|
||||
{ "type": "fixed", "ids": [7, 9] },
|
||||
{ "type": "org_manager" },
|
||||
{ "type": "org_manager_chain", "levels": 2 },
|
||||
{ "type": "position", "ids": [3] },
|
||||
{ "type": "project_principal" } ]
|
||||
```
|
||||
|
||||
`org_manager` = 发起人所在部门负责人;`org_manager_chain` 沿部门链上溯 `levels` 级
|
||||
("分管领导"就是这一种)。解析时会剔除停用账号、按岗位级别排序、并套用委托关系。
|
||||
|
||||
> 修过的一个真 bug:走 `empty_strategy=admin` 兜底时,兜底人只被写进 `picked`、
|
||||
> 没放回 `resolved.accounts`,导致建出来的待办 `assignee_name` 是空串,
|
||||
> 待办列表和流程详情上显示成"未指派"。现在兜底人一定回到候选人集合里。
|
||||
|
||||
## 3. 送审时冻结什么
|
||||
|
||||
`approval_instance` 在提交那一刻写入:
|
||||
|
||||
- `revision_id` / `snapshot_id`:审批人看的是**这一版**,之后送审人再改草稿不影响在途审批;
|
||||
- `variables_json`:判定用的关键数据(合同额、项目类型、毛利率…),流程条件读它,不读实时数据;
|
||||
- `flow_version` / `flow_name`:流程定义后来改了,历史记录仍然说得出当时是哪一版;
|
||||
- `freeze_json`:送审时刻的项目名、合同额、利润、计算口径版本号。
|
||||
|
||||
这一条直接消灭了老系统最说不清的问题:**"当时他批的到底是哪个数"**。
|
||||
|
||||
## 4. 状态与动作
|
||||
|
||||
实例状态:`reviewing` 审批中 / `approved` 已通过 / `rejected` 已驳回 / `withdrawn` 已撤回 / `canceled` 已作废
|
||||
|
||||
待办状态:`pending` 待办理 / `done` 已办理 / `skipped` 自动跳过 / `transferred` 已转办 / `canceled` 已作废
|
||||
|
||||
动作(`approval_record.action`,全部留痕):
|
||||
|
||||
`submit` 提交 · `approve` 通过 · `reject` 不通过 · `rollback` 退回指定节点 · `withdraw` 撤回 ·
|
||||
`transfer` 转办 · `add_sign` 加签 · `cc` 抄送 · `remind` 催办 · `auto_skip` 同一审批人自动跳过 · `timeout` 超时处理
|
||||
|
||||
状态标签一律由后端下发(`statusLabel` / `actionLabel` / `signTypeLabel`),
|
||||
前端不维护第二份中文映射——两份字典迟早对不上。
|
||||
|
||||
## 5. 流转语义
|
||||
|
||||
**或签 `any`**:任一人处理即定走向,其余人待办置 `canceled`。
|
||||
**会签 `all`**:全部通过才通过;**任一人驳回即整节点驳回**。
|
||||
**依次 `order`**:只给第一个人建待办,办理后按 `order_queue` 推进到下一个;任一人驳回即驳回。
|
||||
|
||||
**退回发起人重提**:原实例置 `rejected`,同时新建一个实例并把 `previous_instance_id` 指回原实例。
|
||||
于是"被打回去几次、每次是谁驳的、改了哪些数字"是一条能顺着走的链,而不是被覆盖掉的现状。
|
||||
|
||||
**自动跳过重复审批人**(`auto_skip_duplicate`):
|
||||
若某节点解析出的审批人与前面已办理的人完全重合(且不是会签),记 `auto_skip` 并跳过。
|
||||
老系统不跳,科长自填自批要手点两次"同意",于是大家给科长配了个助手代批——流程名存实亡。
|
||||
|
||||
**委托**(`approval_delegate`):设在人身上、带时间段,命中后待办直接建给受托人,
|
||||
`origin_assignee_id` 留下原始被指派人,流水里看得出是委托来的。
|
||||
|
||||
## 6. 权限判定
|
||||
|
||||
后端只认三件事:**令牌是谁 · 这条待办是不是他的 · 他有没有该业务权限码**。
|
||||
|
||||
- 待办列表只返回 `assignee_id = 当前人 AND status = pending`。**超管也不代收别人的待办**,
|
||||
超管看的是"流程监控"(全量实例),这两件事在界面和接口上都是分开的。
|
||||
这条边界很重要:一旦允许代签,`approval_record` 就不能作为审计依据了。
|
||||
- 撤回只允许"实例在 `reviewing` 且本人是发起人"。
|
||||
- 催办、监控类动作按 `approval:monitor:view` 判定。
|
||||
|
||||
## 7. 超时
|
||||
|
||||
`timeout_hours` 到点由扫描任务处理(`engine.py` 内 `remind` / `auto_approve` / `none` 三种动作),
|
||||
并在流水里记 `timeout`,备注写清是谁超时未处理。默认 `none`,只留痕不动作——
|
||||
**自动通过是可配的行为,绝不是系统的默认假设**。
|
||||
|
||||
## 8. 流程条件 DSL
|
||||
|
||||
节点条件与流程匹配条件用同一个受限表达式字符串:
|
||||
|
||||
```
|
||||
contract_amount >= 5000000 and type in [1,2]
|
||||
```
|
||||
|
||||
支持 `and` / `or`、`>= > <= < == != in not in`,右值支持数字、字符串、数组,变量名取自
|
||||
`variables_json` 的键。求值不用 `eval`,是自己解析成 AST 再取值的。
|
||||
|
||||
配置页旁边给出**人类可读复述**("合同额 ≥ 500 万 且 项目类型 ∈ {系统集成, 施工总承包}"),
|
||||
配置人员不必记语法。
|
||||
|
||||
## 9. 流程配置的状态机
|
||||
|
||||
```
|
||||
draft ──发布──> published ──下线──> offline
|
||||
↑ │
|
||||
└──────────── 复制为新草稿 ────────────┘
|
||||
```
|
||||
|
||||
- `draft` 可自由编辑;
|
||||
- `published` **一律只读**,要改必须先下线。前端直接禁用编辑控件并说明原因,
|
||||
而不是让人改完保存时才发现报错;
|
||||
- 发布前必须通过 `GET /approvals/flows/{id}` 返回的 `errors` 校验(节点缺候选人、
|
||||
条件引用了不存在的变量、没有审批节点等),有错不允许发布。
|
||||
|
||||
下线只影响**新送审**,在途实例继续按 `flow_version` 走完,不中途换轨。
|
||||
|
||||
## 10. 接口一览
|
||||
|
||||
| 方法 | 路径 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| GET | `/approvals/todo` `/done` `/created` `/monitor` | 四类列表(待办/已办/我发起/全量监控) |
|
||||
| GET | `/approvals/instances/{id}` | 详情:实例 + 待办 + 流水 + 送审版本 |
|
||||
| POST | `/approvals/instances/{id}/withdraw` | 撤回(body `{comment}`) |
|
||||
| GET | `/approvals/instances/{id}/rollback-targets` | 可退回哪些节点(**由后端算,前端不猜**) |
|
||||
| POST | `/approvals/tasks/{id}/act` | 办理:`approve/reject/rollback/transfer/add_sign` |
|
||||
| GET/POST | `/approvals/flows`、`/flows/{id}` | 流程定义增删改查 |
|
||||
| POST | `/approvals/flows/{id}/publish` `/offline` | 发布 / 下线 |
|
||||
| GET/POST | `/approvals/delegates` | 委托关系 |
|
||||
| GET | `/approvals/flows/options` | 配置页下拉项(候选人类型、动作、状态等) |
|
||||
|
||||
`rollback-targets` 单独成接口,是因为"能退回到哪儿"取决于运行时已经完成了哪些节点、
|
||||
以及当前节点允许哪些目标,前端如果自己推一遍,就会有两套规则。
|
||||
|
||||
## 11. 与老系统的对应
|
||||
|
||||
| 老系统 | 新系统 |
|
||||
| --- | --- |
|
||||
| `.bpmn` 流程定义 + `act_re_*` | `approval_flow` + `approval_node` |
|
||||
| `act_task_def`(自定义节点表) | `approval_node` |
|
||||
| `act_ru_task` | `approval_task` |
|
||||
| `project_task_record` | `approval_record` |
|
||||
| `project_instance_relation` | `approval_instance.project_id` / `revision_id`(直接外键) |
|
||||
| `candidate_types` 数字串 | `candidates_json` 结构化配置 |
|
||||
|
||||
迁移时 `act_task_def` 里每条节点定义映射成一行 `approval_node`,
|
||||
候选人从数字串解析成 `candidates_json`;在途实例**不迁**,切流前清干净,
|
||||
新送审一律走新流程(详见《数据迁移》章节)。
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
# 操作审计
|
||||
|
||||
> 对应实现:`backend/app/service/audit.py`(写入)、`backend/app/api/audit.py`(查询)、
|
||||
> `backend/app/models/org.py` 的 `operation_log` / `login_log`;
|
||||
> 前端 `frontend/src/views/system/OperationLogsView.vue`
|
||||
|
||||
## 1. 为什么审计挂在中间件上
|
||||
|
||||
老系统的审计是"谁想起来谁写一行":接口上百条,只有零星几条记得记日志,字段各写各的,
|
||||
出事之后拼不出完整链条。重构成按 **HTTP 方法**判定而不是按接口判定——
|
||||
|
||||
- `POST` / `PUT` / `PATCH` / `DELETE` 一律留一条 `operation_log`,新加接口不需要记得挂任何东西;
|
||||
- `GET` 不记(读操作量大且不改数据;要查"谁看过什么"应该单开一条读取审计,别混在这里);
|
||||
- 登录与免登走 `login_log` / `sso_handoff`,改口令在接口里写动作更明确的一条:这三条路径的
|
||||
请求体是要防着的东西,混进通用审计只是多存一份敏感数据。
|
||||
|
||||
一次操作只有一行。接口想补业务语义(项目名、删除原因、销毁清单)调
|
||||
`audit.enrich(request, ...)` 挂到 `request.state`,中间件在响应出去之后合并进同一行。
|
||||
|
||||
## 2. 记了什么
|
||||
|
||||
| 列 | 内容 |
|
||||
| --- | --- |
|
||||
| `account_id` / `account_name` | 谁。取自登录态,不由前端上报 |
|
||||
| `action` | `create` / `update` / `delete` / `purge` / `restore` / `submit` / `approve`…(路径尾巴上的动词优先,其余按方法推) |
|
||||
| `object_type` / `object_id` | 改的是哪个对象。按路由模板折出**最深**的那个:删成员记成员,项目 id 进 `detail` |
|
||||
| `object_name` | 对象名。由中间件按类型回查一次,接口另可用 `enrich` 覆盖(销毁后对象没了,就靠这个覆盖值留名) |
|
||||
| `detail_json` | `method` / `path` / `route` / `params` / `query` / `body` / `status` / `ok` / `durationMs` / `error{code,message,traceId}` + 接口补充 |
|
||||
| `ip` | 认 `X-Forwarded-For` 的第一段,同域反代后面记的才是真实来源 |
|
||||
|
||||
新增对象的 id 从统一响应约定里取:本系统所有创建接口都回 `ok({"id": N})`,认这一条就不必
|
||||
每个接口自己报一遍新建 id。
|
||||
|
||||
## 3. 三条硬口径
|
||||
|
||||
1. **口令绝不入库。** 键名命中 `password` / `token` / `secret` / `captcha` / `credential` /
|
||||
`authorization` / `ticket` 的一律替换成 `***`,递归处理嵌套结构;上传请求只记字节数。
|
||||
刻意不收 `code` / `key` 这类宽泛字样——部门编码、岗位编码、字典编码正是审计要看的,
|
||||
糊掉等于白记。
|
||||
2. **写失败不拖垮业务。** 日志写在响应之后,异常只打警告。一次已经成功的保存不能因为
|
||||
审计写不进去变成 500。
|
||||
3. **审计不受数据权限影响。** 它是"谁动了系统"的账,按 `system:audit:view` 一个码放行;
|
||||
给它套项目数据范围,等于让被审计的人自己决定别人能看到他什么。
|
||||
|
||||
## 4. 审计页
|
||||
|
||||
`系统管理 → 操作日志`(`/system/operation-logs`)两个页签:
|
||||
|
||||
- **操作日志**:关键字(对象名 / 编号 / 操作人 / 内容)、动作、对象类型、时间窗、只看失败。
|
||||
点一行看明细:请求、参数、脱敏后的请求体、业务补充、错误与 `traceId`。
|
||||
- **登录日志**:`login_log` 直读,含失败尝试与来源 IP、UA、验证方式。
|
||||
|
||||
审计表只增不删,查询强制带时间窗(默认 30 天,上限一年),避免一次全表扫把库拖住。
|
||||
需要长期归档请在库外做定时导出,不要在这里加删除。
|
||||
|
||||
## 5. 与"销毁项目"的关系
|
||||
|
||||
`DELETE /projects/{id}` 是软删除(可恢复),`DELETE /projects/{id}/purge` 是物理销毁,
|
||||
两个权限码(`project:project:delete` / `project:project:purge`)。销毁被两条规矩挡着:
|
||||
|
||||
- 只能销毁回收站里的项目;
|
||||
- 项目一旦留有审批实例或审批记录,**不允许销毁**——审批留痕是合规资产,项目可以作废,
|
||||
这条链不能断。
|
||||
|
||||
真正确要销毁时,销毁清单(各类数据各删了多少行、原项目名/编号/创建人/合同额/删除人与
|
||||
删除原因)整份写进那一条审计日志:销毁之后,这条日志就是这件事在这个世界上剩下的痕迹。
|
||||
|
|
@ -0,0 +1,151 @@
|
|||
# 四算 PMS 数据关系
|
||||
|
||||
配合 [老系统数据迁移.md](老系统数据迁移.md) 看:那篇讲怎么把老库搬进来,这篇讲搬进来之后
|
||||
新库里的数据是怎么串起来的。关系取自 `backend/app/models/`,外键以开发库
|
||||
`information_schema.KEY_COLUMN_USAGE` 为准(40 张表、39 条外键列,含 `dict_type` / `dict_item`
|
||||
两张数据字典表)。
|
||||
|
||||
## 一、四条主链
|
||||
|
||||
整个库其实是四条链,别的表都挂在它们身上:
|
||||
|
||||
1. **组织 → 账号 → 角色**:`org_unit` → `accounts` → `perm_account_role` → `perm_role` →
|
||||
`perm_role_node` → `perm_node`。决定"谁能点什么菜单、能看哪些数据"。
|
||||
2. **项目 → 版本 → 明细 → 快照**:`project` → `biz_revision` → 十张 `*_line` →
|
||||
`calc_snapshot`。业务数据全在这条链上,也是本次迁移的主战场。
|
||||
3. **流程定义 → 实例 → 待办 / 流水**:`approval_flow` → `approval_node`,运行时是
|
||||
`approval_instance` → `approval_task` / `approval_record`。
|
||||
4. **系统与日志**:`system_config`、`login_log`、`operation_log`、`hub_sync_run`、
|
||||
`sso_handoff`,不参与业务外键。
|
||||
|
||||
## 二、业务主链(项目 → 版本 → 明细)
|
||||
|
||||
```mermaid
|
||||
erDiagram
|
||||
org_unit ||--o{ accounts : "org_unit_id"
|
||||
org_unit ||--o{ org_unit : "parent_id"
|
||||
org_position ||--o{ accounts : "position_id"
|
||||
accounts ||--o{ accounts : "leader_id"
|
||||
accounts ||--o{ account_identity: ""
|
||||
accounts ||--o{ project : "creator_id"
|
||||
accounts ||--o{ perm_account_role: ""
|
||||
perm_role ||--o{ perm_account_role: ""
|
||||
perm_role ||--o{ perm_role_node : ""
|
||||
perm_node ||--o{ perm_role_node : ""
|
||||
|
||||
project ||--o{ biz_revision : "project_id"
|
||||
project ||--o{ project_member : "project_id"
|
||||
accounts ||--o{ project_member : "account_id"
|
||||
project ||--o{ project_stage_log : ""
|
||||
project ||--o{ project_visible_role : ""
|
||||
perm_role ||--o{ project_visible_role : ""
|
||||
|
||||
biz_revision ||--o{ estimate_income_line : "revision_id"
|
||||
biz_revision ||--o{ estimate_cost_line : "revision_id"
|
||||
biz_revision ||--o{ estimate_other_line : "revision_id"
|
||||
biz_revision ||--o{ budget_income_line : "revision_id"
|
||||
biz_revision ||--o{ budget_income_plan_line: "revision_id"
|
||||
biz_revision ||--o{ budget_purchase_line : "revision_id"
|
||||
biz_revision ||--o{ budget_pay_plan_line : "revision_id"
|
||||
biz_revision ||--o{ budget_manage_line : "revision_id"
|
||||
biz_revision ||--o{ budget_other_cost_line : "revision_id"
|
||||
biz_revision ||--o{ budget_fund_month : "revision_id"
|
||||
```
|
||||
|
||||
几个不太显眼但很重要的点:
|
||||
|
||||
- **十张明细表认的是 `revision_id`,不是 `project_id`。** `project_id` 是冗余列,
|
||||
只为按项目查得快。同一个项目改一版预算就多一版 `biz_revision`,老版本整版留着,
|
||||
所以任何一条明细都必须带上版本,不然会把两版数据加在一起。
|
||||
- **`biz_revision.module` 只有 `estimate` / `budget` 两个值**,决定这一版挂哪几张明细表。
|
||||
概算 3 张、预算 7 张,两边不会串。
|
||||
- **`project` 上那一排金额是投影,不是输入。** `contract_amount`、`gross_profit`、
|
||||
`contribution_profit`、`contribution_profit_rate` 这些由计算器按 `calc_snapshot_id`
|
||||
指向的快照写回,手改会在下一次试算时被覆盖。
|
||||
- **`budget_fund_month` 一半是输入一半是派生**,同一个表里两种身份的列混着,最容易改错:
|
||||
`device_cost` … `opening_balance`、`manual_override` 是人工列;
|
||||
`total_cost` / `total_income` / `balance` / `underwritten_plan` / `repayment_plan` /
|
||||
`capital_interest` 是派生列,只由 `app.service.calc.fund_plan` 整条重算后写回
|
||||
(`_persist_fund_derived` 只动派生列,人工列一律不碰)。
|
||||
- **唯一键挡住了三类重复**:`biz_revision(module, project_id, version)`、
|
||||
`project_member(project_id, account_id)`、`budget_fund_month(revision_id, month)`。
|
||||
注意 **`project.project_no` 上没有唯一约束**,去重归业务代码管——本次 812 个项目
|
||||
812 个编号一个没撞,但别把它当数据库层面的保证。
|
||||
|
||||
## 三、审批链
|
||||
|
||||
```mermaid
|
||||
erDiagram
|
||||
approval_flow ||--o{ approval_node : "flow_id"
|
||||
approval_flow ||--o{ approval_instance : "flow_id(无外键)"
|
||||
approval_instance ||--o{ approval_task : "instance_id"
|
||||
approval_instance ||--o{ approval_record: "instance_id"
|
||||
accounts ||--o{ approval_task : "assignee_id"
|
||||
accounts ||--o{ approval_instance : "submitter_id"
|
||||
accounts ||--o{ approval_delegate : "from_id / to_id"
|
||||
```
|
||||
|
||||
`approval_instance` 到 `approval_flow` **只有 `flow_id` 列,没有外键约束**:实例落库时把
|
||||
`flow_key` / `flow_name` / `flow_version` 一起冗余下来,流程定义后面怎么改,历史实例
|
||||
渲染出来的都还是它当时那一版。候选人不在实例里,`approval_node.candidates_json` 是定义侧的
|
||||
配置,找人是在送审那一刻算完再落成 `approval_task` 的。
|
||||
|
||||
审批对象走的是**多态**,没有外键:`approval_instance.business_module` +
|
||||
`project_id` / `revision_id` / `snapshot_id`。所以删项目不会级联删审批实例,反之也一样。
|
||||
|
||||
## 四、只有逻辑关联、没有外键的地方
|
||||
|
||||
这几处全靠约定,写代码时最容易踩:
|
||||
|
||||
| 表.列 | 指向 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `calc_snapshot.project_id` / `revision_id` | `project` / `biz_revision` | 快照存 JSON,不建外键是不让计算历史卡住业务删除 |
|
||||
| `project.calc_snapshot_id` | `calc_snapshot` | 反向指针,指向"当前生效"的那一份 |
|
||||
| `biz_revision.snapshot_id` | `calc_snapshot` | 同上,版本级 |
|
||||
| `approval_instance.business_module` | `project` / `biz_revision` | 多态:模块名决定 `project_id`/`revision_id` 谁起作用 |
|
||||
| `attachment.object_type` + `object_id` | 任意业务对象 | 多态附件,`field` 区分同一对象上的不同挂点 |
|
||||
| `project.principal_id` | `accounts` | 项目负责人;`principal` 是文本冗余 |
|
||||
| `perm_data_policy` / `perm_field_scope` | `perm_role` + 模块名 | 数据权限按模块名授权,模块名注册在 `app/service/data_scope.py` |
|
||||
|
||||
## 五、数据权限怎么用这张图
|
||||
|
||||
`app/service/data_scope.py` 里每一档口径都对应图上的一条路径:
|
||||
|
||||
- **我创建的** → `project.creator_id`
|
||||
- **我参与的** → `project_member(project_id, account_id)` 是否存在(不分成 `owner` 还是
|
||||
`viewer`,有一条就算)
|
||||
- **本部门 / 本部门及下级** → `project.org_unit_id`,再顺 `org_unit.parent_id` 收子树
|
||||
- **按角色整批放开** → `project_visible_role` 逐项目授权,或 `perm_data_policy` 按模块配策略
|
||||
|
||||
所以导入的数据一旦缺了 `creator_id`、`org_unit_id`、`project_member`,页面不会报错,
|
||||
只是那一档收出来是空的——本次迁移后正是这个状态,详见迁移文档第七节。
|
||||
|
||||
## 六、老库到新库的主键映射
|
||||
|
||||
新库**不保留老库主键**,全部重新发号,映射表只在一次运行的内存里(`maps` 字典)。
|
||||
撞号比报错可怕:老 id 直接搬会和 seed 出来的 `localadmin`、演示项目重叠,重叠就是静默覆盖。
|
||||
|
||||
| 映射 | 键 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| `maps["dept"]` | 老 `dept.id` → `org_unit.id` | 项目 `org_unit_id`、账号所属部门 |
|
||||
| `maps["user"]` | 老 `sys_user.id` → `accounts.id` | 项目创建人、可见性授权 |
|
||||
| `maps["role"]` | 老 `sys_role.id` → `perm_role.id` | 角色候选人、可见角色 |
|
||||
| `maps["position"]` | 老 `position_id` → `org_position.id` | 岗位(老库一批人 `position_id=0`,所以按名字去重) |
|
||||
| `maps["flow"]` | 老 `proc_def_key` → `approval_flow.id` | 流程归属 |
|
||||
| `maps["project"]` | 老 `project.id` → `project.id` | **所有明细表的挂靠都靠它**,映射不到就整批跳过 |
|
||||
| `maps["revision"]` | `(老 project_id, module)` → `biz_revision.id` | 明细落到哪一版 |
|
||||
|
||||
想事后回溯某一行是老库哪条记录,靠 `project_no`:老编号原样搬(老编号为空的补 `L<老id>`),
|
||||
`project` 表上它就是唯一键。
|
||||
|
||||
## 七、表清单
|
||||
|
||||
| 分组 | 表 |
|
||||
| --- | --- |
|
||||
| 组织账号 | `org_unit` `org_position` `accounts` `account_identity` |
|
||||
| 权限 | `perm_node` `perm_role` `perm_role_node` `perm_account_role` `perm_data_policy` `perm_field_scope` |
|
||||
| 项目 | `project` `project_member` `project_visible_role` `project_stage_log` `attachment` `system_config` |
|
||||
| 版本与明细 | `biz_revision` `calc_snapshot` `estimate_income_line` `estimate_cost_line` `estimate_other_line` `budget_income_line` `budget_income_plan_line` `budget_purchase_line` `budget_pay_plan_line` `budget_manage_line` `budget_other_cost_line` `budget_fund_month` |
|
||||
| 审批 | `approval_flow` `approval_node` `approval_instance` `approval_task` `approval_record` `approval_delegate` |
|
||||
| 数据字典 | `dict_type` `dict_item` |
|
||||
| 同步与日志 | `hub_sync_run` `sso_handoff` `login_log` `operation_log` |
|
||||
|
|
@ -0,0 +1,221 @@
|
|||
# 数据权限设计
|
||||
|
||||
> 对应实现:`backend/app/service/data_scope.py`、`backend/app/models/permission.py`、
|
||||
> `backend/app/api/system.py`;前端 `frontend/src/views/system/DataPermissionView.vue`
|
||||
|
||||
## 1. 为什么不能只在角色上挂一个 scope 字段
|
||||
|
||||
老系统里同时存在三种可见性口径,而且长期共存:
|
||||
|
||||
- `sys_role` 上的一个范围字段(本人 / 本部门 / 全部);
|
||||
- `project_visible` 表:按项目挑一批人能看;
|
||||
- `sys_permission` 里的部门过滤,靠登录后往 SQL 里拼 `dept_id in (...)`。
|
||||
|
||||
结果是:**同一个人在不同列表里的可见范围,没人能一次说清**,包括写代码的人。
|
||||
|
||||
真实需求长这样:
|
||||
|
||||
> 张三是市场部普通员工:项目列表看全公司(要报方案),
|
||||
> 结算列表只看本部门,
|
||||
> 预算列表看本部门及下级,但合同额 500 万以上的项目不让他看。
|
||||
|
||||
一个 scope 字段表达不了这句话。所以重构成**策略表**。
|
||||
|
||||
## 2. 模型
|
||||
|
||||
`perm_data_policy` 一条记录 = 一条规则:
|
||||
|
||||
| 字段 | 作用 |
|
||||
| --- | --- |
|
||||
| `module` | 生效的业务模块:`project` / `estimate` / `budget` / `settlement` / `final`;同口径的一组模块由族代表那一条策略统一生效,见 §5.1 |
|
||||
| `subject_type` + `subject_id` | 规则挂在谁身上:`all` / `role` / `account` / `org_unit` / `position` |
|
||||
| `effect` | `allow` 允许、`deny` 排除 |
|
||||
| `scope_type` | 范围类型,见下表 |
|
||||
| `target_ids_json` | `org_list` / `account_list` 时的 id 列表 |
|
||||
| `include_children` | 指定部门时是否含下级 |
|
||||
| `conditions_json` | 自定义条件树(可嵌套 and/or) |
|
||||
| `priority` | 同种效果内部的评估顺序 |
|
||||
| `enabled` | 开关 |
|
||||
| `valid_from` / `valid_to` | 临时授权,到期自动失效(项目交接期常用) |
|
||||
|
||||
主体的五种挂法是关键设计:**同一条规则可以挂在一个部门上**(这个部门里的人都吃这条),
|
||||
也可以挂在一个岗位、一个角色、或者某一个人身上。老系统只能挂角色,遇到"就这两个人特殊"
|
||||
只能新建一个角色,角色表就是这么长歪的。
|
||||
|
||||
## 3. 十种范围类型
|
||||
|
||||
| `scope_type` | 含义 | 落到哪些列 |
|
||||
| --- | --- | --- |
|
||||
| `all` | 全部数据 | 不加条件 |
|
||||
| `self` | 仅本人创建/负责 | `creator_id` / `principal_id` |
|
||||
| `unit` | 本部门 | `org_unit_id` |
|
||||
| `unit_and_below` | 本部门及下级 | `org_unit_id IN (递归子树)` |
|
||||
| `org_list` | 指定的若干部门(可含/不含下级) | `org_unit_id IN (...)` |
|
||||
| `identity_units` | 本人全部身份所在部门(**兼岗也算**) | `org_unit_id IN (身份表展开)` |
|
||||
| `participant` | 我参与的(成员 / 协作 / 被抄送) | `EXISTS(project_member)` |
|
||||
| `account_list` | 指定的若干人 | `creator_id IN (...)` |
|
||||
| `dept_of_record` | 按数据行上的部门字段判定(默认口径) | `org_unit_id` |
|
||||
| `custom` | 只用自定义条件,不限定主体范围 | 仅条件树 |
|
||||
|
||||
`identity_units` 是新增的。老系统只看主部门,兼岗的人(市场部兼财务室)在财务列表里看不到
|
||||
该看的单子,只能靠管理员手工加可见性。身份表 `account_identity` 把这件事变成一条范围类型。
|
||||
|
||||
## 4. 求值顺序
|
||||
|
||||
```
|
||||
命中主体 → allow 取并集 → deny 取并集后整体排除 → 兜底
|
||||
```
|
||||
|
||||
伪代码:
|
||||
|
||||
```python
|
||||
policies = 命中(全部人 ∪ 我的任一角色 ∪ 我本人 ∪ 我任一部门 ∪ 我任一岗位)
|
||||
|
||||
allow = OR([ 范围谓词(p) AND 条件树(p) for p in policies if p.effect == "allow" ])
|
||||
deny = OR([ 范围谓词(p) AND 条件树(p) for p in policies if p.effect == "deny" ])
|
||||
|
||||
if 是系统管理员: return 不加任何限制
|
||||
if allow 为空: return (self 范围) AND NOT deny # 兜底,不把人锁死
|
||||
return allow AND NOT deny
|
||||
```
|
||||
|
||||
四条容易踩的规则,明确写死:
|
||||
|
||||
1. **allow 之间是并集(OR),不是交集**。给一个人加第二条规则只会让他看见更多,不会互相抵消。
|
||||
2. **deny 永远赢**。`AND NOT (deny...)` 在最后统一施加,因此"给全公司开放 + 单独藏掉几个涉密项目"是可表达的。
|
||||
3. **一条 allow 都没命中时用兜底 `self`**,而不是返回空。老系统出现过"新角色配错,全组打不开列表"的工单。
|
||||
4. **未注册的模块一律拒绝**(返回空集)而不是放行。新模块上线时忘了注册 `ModuleSpec`,宁可看不见,不能漏看见。
|
||||
|
||||
系统管理员(`is_system_admin`)直接不加限制,短路在后端,不依赖前端隐藏。
|
||||
|
||||
## 5. 模块注册:业务代码里看不到权限
|
||||
|
||||
模块只要在启动时注册一次,业务查询里就只是 `.where(*scope_conditions)`,不出现任何权限细节:
|
||||
|
||||
```python
|
||||
register(ModuleSpec(
|
||||
module="project",
|
||||
label="项目列表",
|
||||
entity=Project,
|
||||
org_column="org_unit_id",
|
||||
owner_column="creator_id",
|
||||
participant_predicate=_project_participant, # EXISTS(project_member…)
|
||||
filterable={ "contract_amount": "contract_amount", "stage": "stage", … },
|
||||
numeric=("contract_amount", "contribution_profit_rate", "gross_profit"),
|
||||
))
|
||||
```
|
||||
|
||||
概算 / 预算 / 结算 / 决算四个模块**复用项目的归属**(`entity=Project`),刻意让它们和
|
||||
`project` 同口径。否则会出现"列表看得见、点进详情 403"这种最难解释的割裂。
|
||||
|
||||
### 5.1 口径组:一条策略管一族
|
||||
|
||||
口径既然相同,就不该再为每个模块抄一条策略。`ModuleSpec.family` 把这一族绑在一起
|
||||
(四个成员模块 `family="project"`),求值时按一条规则取策略:
|
||||
|
||||
> **本模块的专属策略优先;一条都没有,才用族代表(`project`)上的那条族策略。**
|
||||
|
||||
三条要点:
|
||||
|
||||
- **是"优先"不是"并集"**。项目上配了全部数据、预算想收窄成本部门,单独配一条预算策略
|
||||
就得真的收窄,不能被族策略又撑回去。
|
||||
- **族内编译必须一致**。同一条族策略在族内任何模块上都要编译出同一个谓词,所以这一族
|
||||
共用同一份 `filterable`(`_PROJECT_FILTERABLE`):白名单不一致时,写在 `project` 上的
|
||||
条件换到预算那一侧会因为字段不在白名单里被 `_condition_tree` 静默丢掉,同一条策略
|
||||
一边收着一边放开——那是最没人查得出来的放宽。
|
||||
- **seed 每个角色只种一条**(挂在 `project` 上)。从前按模块铺三条,授权页每个角色三张
|
||||
一模一样的卡片,还会因为"角色已配过权限节点就不再校准"而种漏:内置角色"公司领导"
|
||||
就漏了预算那条,他一进预算列表直接掉进 `self` 兜底。启动时会把与族策略逐字段相同、
|
||||
只差 `module` 的重复行软删掉;内容不同的那条留着,它按"专属优先"继续生效。
|
||||
|
||||
配置页据此说明每条策略的作用面:族代表那条显示"项目列表 等 5 个模块",
|
||||
`GET /system/data-policies` 里对应 `covers` 字段。
|
||||
|
||||
`filterable` 同时充当**自定义条件的字段白名单**。不在名单里的字段直接拒绝写入策略,
|
||||
配置人员也就不可能写出一个悄悄失效的条件。
|
||||
|
||||
## 6. 自定义条件树
|
||||
|
||||
`conditions_json` 是 JSON 树,不是 SQL 片段:
|
||||
|
||||
```json
|
||||
{
|
||||
"op": "and",
|
||||
"items": [
|
||||
{ "field": "contract_amount", "op": ">=", "value": "5000000" },
|
||||
{ "op": "or", "items": [
|
||||
{ "field": "stage", "op": "in", "value": [3, 4] },
|
||||
{ "field": "org_unit_id", "op": "in", "value": ["$org_unit_ids_with_children"] }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
安全性:
|
||||
|
||||
- `field` 必须命中 `filterable` 白名单,否则策略保存即失败;
|
||||
- 值一律走 SQLAlchemy 绑定参数,不拼字符串;
|
||||
- 声明为 `numeric` 的字段做数值比较前先转 `Decimal`,避免 `"900000" > "1000000"` 这种字符串比较结果。
|
||||
|
||||
**动态变量**让一条规则能被很多人复用,不必为每个人复制一份:
|
||||
|
||||
| 变量 | 展开为 |
|
||||
| --- | --- |
|
||||
| `$account_id` | 当前登录人 id |
|
||||
| `$org_unit_ids` | 当前人全部身份所在部门 |
|
||||
| `$org_unit_ids_with_children` | 上述部门及其全部下级 |
|
||||
|
||||
没有动态变量时,"本部门及下级的涉密项目对我隐藏"这类规则只能给每个部门抄一条。
|
||||
|
||||
## 7. 字段级权限
|
||||
|
||||
行看得见不代表每个字段都能看。`perm_field_scope` 按 `(module, field, role)` 配置:
|
||||
|
||||
- `hidden`:前端不渲染该列;后端在序列化时直接剔除(**后端剔除,不是前端隐藏**);
|
||||
- `masked`:显示为 `****`,用于"知道有这单、但不能看单价"。
|
||||
|
||||
典型用法:业务角色能看预算收入明细,但看不到采购成本列的单价与供应商名称。
|
||||
|
||||
`/bootstrap` 会一次性下发 `fieldMasks`,前端渲染表格时查表即可,不用逐列再问一次。
|
||||
|
||||
## 8. 配置页与"当场验证"
|
||||
|
||||
数据权限最难的是配完不知道谁会受影响。所以后端专门提供:
|
||||
|
||||
```
|
||||
POST /api/v1/system/data-policies/explain
|
||||
{ "accountId": 3, "module": "budget" }
|
||||
→ { "unlimited": false,
|
||||
"description": "本部门及下级(工程管理部 及下级 2 个部门),且 合同额 < 5000000" }
|
||||
```
|
||||
|
||||
配置页在编辑面板底部常驻这个试算:**选一个真人,看他在这个模块下最终是什么范围**。
|
||||
配置者不需要在脑子里跑"allow 并集、deny 排除"。
|
||||
|
||||
```
|
||||
GET /api/v1/system/data-policies/options
|
||||
→ { modules, scopeTypes, subjectTypes, effects, operators, dynamicValues, roles }
|
||||
```
|
||||
|
||||
下拉选项全部来自后端,前端不硬编码枚举,避免加一种范围类型要改三处。
|
||||
|
||||
## 9. 与列表接口的一致性
|
||||
|
||||
列表接口返回体里带 `scope`:
|
||||
|
||||
```json
|
||||
{ "items": [...], "meta": {...}, "scope": { "type": "unit_and_below", "label": "本部门及下级", "unlimited": false } }
|
||||
```
|
||||
|
||||
前端在表格上方把它显示出来。**数据权限是配出来的,用户看不见就会以为"数据丢了"**——
|
||||
这一行提示消灭掉的是一整类工单。
|
||||
|
||||
单条数据访问走同一条链路(`assert_project_visible`),因此权限模型只有一份实现,
|
||||
不存在"列表过滤了、详情忘了"。
|
||||
|
||||
## 10. 什么不做
|
||||
|
||||
- **不做行级 SQL 拼接的"自定义 SQL 片段"**。一次灵活换来 forever 的注入面。
|
||||
- **不在前端做数据过滤**。前端只负责显示范围,过滤全在后端。
|
||||
- **暂不做审批人可见性与数据权限的联动**:审批人办理时按"参与人"放开该单据,走 `participant` 范围,不需要单独一套机制。
|
||||
|
|
@ -0,0 +1,159 @@
|
|||
# 统一身份登录与免登(与 unisoa 对齐)
|
||||
|
||||
对端契约是 unisoa 仓库根目录的《dsh-hub 统一门户 第三方系统对接指南》。本文只写本系统
|
||||
这一侧:**登录与免登各有哪几条落法、Hub 后台该登记哪个地址、哪些地方与 unisoa 有意不一样**。
|
||||
|
||||
## 1. 四条入口,两套判定
|
||||
|
||||
| 入口 | 谁判口令 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| `POST /api/v1/auth/login` | 统一身份(Hub)或本地哈希,按 `hub.login_mode` 定 | 登录页那个账号口令框,见 §1.1 |
|
||||
| `GET /api/v1/auth/sso/callback` | 不用口令,门户签发的票据 | **推荐**的免登落法,Hub 的 `launch_url` / `redirect_uris` 填这一条 |
|
||||
| `GET /sso/hub` | 同上 | 别名:管理员照对接指南举例写 `/sso/hub` 时也接得住(同域反代把这条转给后端) |
|
||||
| `POST /api/v1/auth/sso/ticket` | 同上 | 只有人把 `launch_url` 登记成前端路由 `/sso` 时才用 |
|
||||
|
||||
三条免登路验票认人都走同一个 `_person_from_ticket`(`backend/app/api/auth.py`),不会出现
|
||||
"回调那条查得严、前端那条查得松"。
|
||||
|
||||
### 1.1 登录页直接输统一身份账号 + 口令
|
||||
|
||||
`hub.login_mode` 决定这个框收谁的账号、口令归谁验,界面上始终只有一个账号口令表单:
|
||||
|
||||
| 档 | 口令归谁验 | Hub 连不上时 | 应急账号(内置超管 + `hub.local_only_accounts`) |
|
||||
| --- | --- | --- | --- |
|
||||
| `hub`(默认) | 只问统一身份 | 当场回 `hub_unavailable`,不放行 | 走本地口令 |
|
||||
| `hybrid` | 先问统一身份 | 退回本地口令校验 | 走本地口令 |
|
||||
| `local` | 只问本地哈希 | 与档无关,本来就不问 | 走本地口令 |
|
||||
| `sso` | 谁都不问,口令登录关闭 | — | — |
|
||||
|
||||
两条不让步的口径:**统一身份说"账号或口令不对"就是不对**,绝不拿库里那个旧哈希再兜一层
|
||||
(否则 Hub 上的停用、离职下线、改口令会在故障期集体失效);被 Hub 拒**不去累加**本地锁定
|
||||
计数 `login_failed_count`,否则等于白送外面一条"把管理员锁在自己系统外面"的路。
|
||||
|
||||
验证码由 Hub 出(`GET /auth/captcha`,算术题 SVG),本系统只代理转发:`GET
|
||||
/api/v1/auth/captcha` 回 `{required, captchaId, image, question}`,`required=false` 时
|
||||
登录页不摆这一行。Hub 说验证码不对回 `captcha_required`,前端换一张再让人试;问不到验证码
|
||||
不锁死登录页,等 Hub 当场拒了再把框亮出来。
|
||||
|
||||
统一身份认下这个账号之后,认人顺序是 Hub 主键 `sub` -> 同名本地账号(只补空的主键)->
|
||||
当场建号。第二条只有口令这条路敢用:本人亲自在本系统页面上报了账号名并过了 Hub 的口令校验;
|
||||
免登那条路不行,票据里只有 `sub`,账号名只是 Hub 顺带下发的展示值,拿它认人等于允许别人
|
||||
用自己的票据把人登成他自己。同名账号已经绑着别人的主键时回
|
||||
`account_identity_conflict`——两个主键并成一条会把权限、待办、流程历史一起并掉,
|
||||
也不悄悄建一条 `xxx_hubNNN` 影子账号放人进来。
|
||||
|
||||
登录审计 `login_log.mode` 记的是"这次谁判的":`password` 本地口令、`hub` 统一身份口令、
|
||||
`sso` 免登。三条入口都从 `_issue_session` 过,全落成默认值最容易,所以每条都有用例钉着。
|
||||
|
||||
## 2. 后端回调这一条为什么中间要垫一条短码
|
||||
|
||||
票据不能留在浏览器(会过期、会被复制、会进 Referer 和访问日志),本地令牌同样不能拼在
|
||||
302 的地址上(那等于把会话钥匙写进浏览历史)。于是:
|
||||
|
||||
```
|
||||
门户 302 -> GET /api/v1/auth/sso/callback?ticket=…&state=…
|
||||
后端带 X-Integration-Key 验票、认人
|
||||
-> 发一条一次性短码,302 /sso#code=…(短码在 # 后面)
|
||||
同时在响应上写一条 HttpOnly Cookie(兑换串)
|
||||
-> 前端 POST /auth/sso/exchange {code} ← 必须带上那条 Cookie
|
||||
-> 本系统会话(accessToken / refreshToken)
|
||||
```
|
||||
|
||||
`sso_handoff` 表里只有两个 SHA-256:短码哈希与兑换串哈希。短码 60 秒过期、只能用一次,
|
||||
并发下靠一条条件 `UPDATE` 保证只有一条请求能用掉它;兑换失败对外只回一个
|
||||
`handoff_invalid`,真实原因(不存在 / 用过 / 过期 / Cookie 对不上)只进日志——这个接口
|
||||
不能变成"某条短码到底存在吗"的探针。把落地地址转发给别人也兑不出去:那条 HttpOnly
|
||||
Cookie 前端读不到,也只存在于收到 302 的那台浏览器上。
|
||||
|
||||
## 3. `state`:谁生成、存在哪儿、比几层
|
||||
|
||||
`state` 由**后端**生成(`POST /auth/sso/state`),值存在后端下发的 HttpOnly Cookie
|
||||
`pms_sso_state` 里(HMAC 签名 + 时间戳,600 秒),前端脚本读不到。落地时比两层:
|
||||
|
||||
1. 地址栏带回来的 `state` 与 Cookie 里那条比(证明"这一趟是本系统发起的");
|
||||
2. 票据校验响应回传的 `state` 与交回来的 `state` 比(证明"Hub 签的这张票本来就是开给
|
||||
这个 `state` 的")。少了第二层,别人就能拿自己的票据配我们的 `state`,把人登成他自己。
|
||||
|
||||
Cookie 一次性的,无论校验结果如何都立刻清掉。按 `hub.sso_state_required` 分两档:
|
||||
|
||||
- 默认(`false`):门户直点卡片那种"压根没带回 `state`"放行,但**只要带回来了就必须对上**;
|
||||
- 严格(`true`):连没带回也拒。开了这一档,每次免登都必须先从本系统登录页跳出去,
|
||||
否则没人进得来。
|
||||
|
||||
## 4. Hub 后台要登记什么
|
||||
|
||||
**落地地址(`launch_url` / `redirect_uris`)填后端回调**,本系统会按当前访问地址把完整
|
||||
URL 现算出来,直接抄:
|
||||
|
||||
- 「统一身份同步」页的「门户落地地址」那一行(带复制按钮),或
|
||||
- `GET /api/v1/auth/hub/status` 的 `sso.callbackUrl` / `sso.aliasUrl`。
|
||||
|
||||
开发档走 Vite 代理时是 `http://<本机IP>:5383/api/v1/auth/sso/callback`(代理开了 `xfwd`,
|
||||
后端才看得到浏览器真正访问的那个地址);生产同域反代就是 `https://<本系统>/api/v1/auth/sso/callback`。
|
||||
|
||||
另外还要有:应用编码 `app_code`(本系统开发档是 `pms`,Hub 用免登密钥验票时会把它回显出来,
|
||||
对不上按串号拒)、免登应用密钥 `integration_key`、以及"可访问角色"勾到人。
|
||||
三项配不齐**等于没开**,界面上 `/org/hub-sync` 与 `/auth/sso/status` 都会点名缺哪一项。
|
||||
|
||||
## 5. 失败时用户看到什么
|
||||
|
||||
回调是浏览器整页跳转过来的入口,失败不能回一屏 JSON,一律
|
||||
`302 /sso?error=<稳定原因码>`,句子由前端 `frontend/src/views/ssoErrors.ts` 说,
|
||||
码表见 `app/api/auth.py:LANDING_REASONS`。落地页角落把原码显示出来供报障。
|
||||
|
||||
Hub 侧把票据校验直接拒掉时(`401001` / `403001` / `404001`)分三句提示:密钥不对或应用
|
||||
被停用、应用编码与密钥不配对、应用编码不存在——一律糊成"密钥不对"会让人挨个试。
|
||||
|
||||
## 6. 与 unisoa 的差异(有意为之)
|
||||
|
||||
登录与免登这条链路上,落法、短码、`state`、票据口径、稳定原因码、`/sso/hub` 别名、
|
||||
状态接口回显回调地址,都按 unisoa 的同一套实现。下面这些不同是刻意的:
|
||||
|
||||
1. **会话形态**:本系统是无状态 JWT(`accessToken` / `refreshToken`),没有服务端会话表。
|
||||
unisoa 在 Hub 判 `user_inactive` 时会清掉这个人的刷新令牌;这里等价实现为"账号就地
|
||||
停用 + 每个请求重查账号状态",旧访问令牌同样立刻失效。
|
||||
2. **默认档更靠前一站**:口令代问与验证码这一套已经照 unisoa 做了(见 §1.1),差别在默认值
|
||||
——本系统默认 `hub`,Hub 连不上就当场报错;unisoa 默认 `hybrid`,连不上时退回本地口令。
|
||||
想要 unisoa 那套行为把 `hub.login_mode` 改成 `hybrid` 即可,两条路的"Hub 说口令不对就是
|
||||
不对"是一致的。另外本系统不给 Hub 账号留任何本地哈希后门(`_verify` 只认
|
||||
`source=local`),unisoa 那边靠随机哈希做到同样的事。
|
||||
3. **配置存放**:unisoa 支持在系统设置页改并落库、不重启生效,还有应急总闸与本地应急账号
|
||||
名单;本系统只有 `config.*.toml` 与 `PMS_HUB_*` 环境变量,改完重启。
|
||||
4. **没有权限层对接**:`me/roles`、`me/permissions`、`me/data-scope`、`admin/*` 代查、
|
||||
`shadow`/`enforce` 那一整层没做。本系统的角色与权限码自持,Hub 也不下发角色。
|
||||
5. **没有本地会话空闲超时**(对应 unisoa 的 `OA_SESSION_IDLE_MINUTES`):访问令牌 TTL 固定,
|
||||
靠刷新续期。
|
||||
|
||||
## 7. 验证到哪一步了
|
||||
|
||||
已经用真 Hub(`http://hubtest.oa.unissense.tech`)验过的:
|
||||
|
||||
- `POST /api/v1/auth/tickets/verify` 认这把免登密钥(`200` + `active:false` +
|
||||
`ticket_invalid`,密钥不对时回的是 `401 集成密钥无效`),并回显 `app_code: "pms"`;
|
||||
- `GET /api/v1/auth/directory` 与 `/directory/changes` 认那把目录密钥;
|
||||
- 完整回调链路:`http://<本机IP>:5383/api/v1/auth/sso/callback?ticket=…` → `302 /sso?error=…`,
|
||||
`/sso/hub` 别名同样;带 `state` Cookie 而地址栏 `state` 对不上时回 `sso_state_rejected`;
|
||||
凭空编的短码兑换回 `handoff_invalid`。
|
||||
|
||||
口令登录这一条也用真 Hub 验过(`POST /auth/login` 的字段名是 `account` / `password` /
|
||||
`captcha_id` / `captcha_answer`,验证码字段名写成驼体的 `captchaId` 会被当成"没填验证码"):
|
||||
|
||||
- `GET /api/v1/auth/captcha` 转出真题目(`4 + 9 = ?` 那种 SVG);
|
||||
- 验证码答对、口令故意写错 → `401 bad_credentials`,消息就是 Hub 原话"账号或密码错误",
|
||||
说明这一趟真的问到了 Hub 并让它判了口令;
|
||||
- 验证码故意答错 → `401 captcha_required`(Hub 原话"验证码错误或已过期");不带验证码 →
|
||||
同样是 `captcha_required`(Hub 回"请输入有效的账号、密码和验证码");
|
||||
- 内置超管与 `local_only_accounts` 里的账号一次 Hub 都不问,直接本地口令进来;
|
||||
- 真人拿自己的 Hub 账号在登录页输账号口令登进来:响应 `via: "hub"`,日志
|
||||
`统一身份口令校验通过(sub=227)`,账号 `source=hub`、`hub_user_id=227`。
|
||||
|
||||
再把 Hub 换成本地桩(unisoa 那份照对接文档写的 `tests/hub_stub.py`,走真 HTTP 而不是假
|
||||
`httpx`)把成功与几条不让步的判定整条跑过:本地存着正确口令、但 Hub 说"没这个人"的账号
|
||||
回 `401 bad_credentials`,绝不拿本地哈希兜第二层,也不去累加 `login_failed_count`;Hub 认
|
||||
口令而同名本地账号还没绑主键时认下那一条(同一条记录补上 `hub_user_id`,不建影子号);
|
||||
`local_only_accounts` 里的人一次 Hub 都不问。这些判定另有 `tests/test_hub_integration.py`
|
||||
的用例钉住——用例里是照着 hubtest 真实响应形状造的假 Hub,不依赖某个真人的口令。
|
||||
|
||||
**没验的只剩一段**:真人在门户里点卡片签出一张真票据(要一个 Hub 账号的登录态,本机没有)。
|
||||
短码兑换那一段用"库里塞哈希 + 浏览器塞 Cookie"的方式在浏览器里跑通过:落地后按
|
||||
`redirect` 进了 `/projects`,右上角是在登录态。
|
||||
|
|
@ -0,0 +1,228 @@
|
|||
# 老四算 → 四算 PMS 数据迁移
|
||||
|
||||
> 本文记的是 2026-10-13 在开发库上实际跑过一次的那一遍,命令、行数、对账结果都是真的,
|
||||
> 不是设计稿。表结构之间的关系另见 [数据关系.md](数据关系.md)。
|
||||
|
||||
## 一、这次跑完的结果
|
||||
|
||||
| 事项 | 结果 |
|
||||
| --- | --- |
|
||||
| 新库 | `fourcal_pms_dev`(`10.100.51.227:30306`),先清干净再导入 |
|
||||
| 老库 | `unis_fourcal_dev`,**只读挂载**,跑完 93 张表行数一字未改 |
|
||||
| 清理 | `scripts/clean_demo_data.py`,删光演示数据、界面造的单据、pytest 留下的垃圾;删前自动备份 |
|
||||
| 迁移范围 | 项目相关 + 流程相关(`flow,project,estimate,budget`);**账号、组织、角色按本次口径不迁** |
|
||||
| 导入量 | 项目 812、版本 1,183、概算行 8,932、预算行 8,036、资金计划 5,723 月、流程 4 条 / 节点 31 个 |
|
||||
| 对账 | 9 个模块行数逐张对上;合同额、毛利、贡献毛利、资金计划四类金额分毫不差 |
|
||||
| 备份 | `backend/storage/backups/clean-20261013-124823-fourcal_pms_dev.sql`(本次清理前的全量回放) |
|
||||
|
||||
还差最后一步没做:`calc_snapshot` 是 0 行。导入的明细要用新口径点一次
|
||||
**「重新试算」** 才会生成计算快照和投影,页面才看得到利润各层。
|
||||
|
||||
## 二、连接前提
|
||||
|
||||
两段配置,一份在 [config.dev.toml](../backend/config.dev.toml):
|
||||
|
||||
```toml
|
||||
[database] # 本系统自己的库,读写
|
||||
name = "fourcal_pms_dev"
|
||||
|
||||
[legacy] # 老四算库,只读
|
||||
enabled = true
|
||||
name = "unis_fourcal_dev"
|
||||
```
|
||||
|
||||
老库那条连接一开就 `START TRANSACTION READ ONLY`,脚本里只发 `SELECT`,误写会被 MySQL
|
||||
当场拒绝——老库还要继续跑生产,改一个字节都没人担得起。这一条不是口头承诺:
|
||||
迁移前后各拉了一次 `information_schema` 的行数快照做 diff,93 张表全部一致。
|
||||
|
||||
两个脚本都**默认干跑**,不加 `--apply` 只报数不落库。
|
||||
|
||||
## 三、第一步:清理测试数据
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
python3 scripts/clean_demo_data.py # 干跑:报每张表要删多少行
|
||||
python3 scripts/clean_demo_data.py --apply # 备份 + 真删
|
||||
python3 scripts/clean_demo_data.py --restore <备份文件> --apply # 回放
|
||||
```
|
||||
|
||||
分得清的两种数据:
|
||||
|
||||
- **留下**(系统基础数据,seed 随时能补):`perm_node` / `perm_role` / `perm_role_node` /
|
||||
`perm_field_scope` / `perm_data_policy` / `system_config` / `approval_flow` / `approval_node`,
|
||||
`accounts` 里只留 seed 那几个本地账号(本档就一个 `localadmin`)。
|
||||
- **清掉**:组织岗位、账号关系、项目与全部明细、审批运行时、各类流水日志。
|
||||
|
||||
删之前把被删的每一行写成 `INSERT` 落到 `storage/backups/`,回放走脚本自己,
|
||||
不依赖 `mysql` 客户端(这台机器就没装)。`PMS_ENV=prod` 时脚本直接拒绝执行。
|
||||
|
||||
### 顺手修的一个坑
|
||||
|
||||
原来的清理脚本把 `perm_role` / `approval_flow` 整表当基础数据留着,于是**上一次迁移导进去的
|
||||
老角色和老流程会被当成"基础数据"留下**:清完库再导一次,同 `key` 命中"已导入"直接跳过,
|
||||
既改不动也看不出问题。现在按 `legacy_` 前缀认这些导入件(`perm_role.code`、
|
||||
`approval_flow.key`,子表 `approval_node` 按 `flow_id` 连坐),seed 那几行照旧留。
|
||||
|
||||
顺带修掉一个更阴的:取 id 时漏了 `.scalars()`,拿 `(id,)` 元组去 `IN` 匹配不到任何行,
|
||||
删起来就是"报 0 行、什么也没删"的静默失败。
|
||||
|
||||
## 四、第二步:迁移(只迁新系统里存在的模块)
|
||||
|
||||
```bash
|
||||
python3 scripts/migrate_legacy.py # 全量干跑
|
||||
python3 scripts/migrate_legacy.py --apply --steps flow,project,estimate,budget
|
||||
```
|
||||
|
||||
步骤之间有依赖,脚本按 `STEPS` 定义的顺序跑,`--steps` 的书写顺序不算数。
|
||||
|
||||
### 覆盖范围
|
||||
|
||||
| 步骤 | 老表 | 新表 |
|
||||
| --- | --- | --- |
|
||||
| `project` | `project` | `project` |
|
||||
| `estimate` | `project_estimate_income` / `_cost` / `_cost_manage` | `estimate_income_line` / `estimate_cost_line` / `estimate_other_line` + 一版 `biz_revision` |
|
||||
| `budget` | `project_budget_income_detail` / `_cost_detail` / `_cost_manage` / `_pay_plan` / `_income_plan_detail` / `_plan_detail` | `budget_income_line` / `budget_purchase_line` / `budget_manage_line` / `budget_pay_plan_line` / `budget_income_plan_line` / `budget_fund_month` + 一版 `biz_revision` |
|
||||
| `flow` | `act_task_def` | `approval_flow` + `approval_node`(`key` 加 `legacy_` 前缀) |
|
||||
|
||||
### 明确不迁的,以及为什么
|
||||
|
||||
**新系统里没有这个模块**,迁过来没有地方放:
|
||||
|
||||
- 结算 `project_settle_*`、决算 `project_final_*`(新系统的模块注册里 `settlement` / `final`
|
||||
只是给数据权限用的别名,没有对应的明细表)
|
||||
- 销售合同 `sale_contract`、采购合同 `procurement_contract*`
|
||||
- 月度结账 `monthly_settle`、项目审批事件 `project_task_record`(8,640 行)
|
||||
- Activiti 引擎自带的 30 张 `act_*`:在途流程 `act_ru_*` 硬迁过来只会造出一堆来路不明的待办;
|
||||
历史流水 `act_hi_procinst`(2,040) / `act_hi_taskinst`(9,341) / `act_hi_comment`(17,419)
|
||||
要看得见的话,得先定"历史流水在新界面里怎么摆",不适合在导数脚本里顺手拍板
|
||||
- 老权限目录 `sys_permission` / `sys_role_permission`:新系统有自己的一套 `perm_node`,
|
||||
两边语义不是一套对一套
|
||||
|
||||
**按本次口径不迁**(账号与组织):`dept`、`sys_user`、`sys_role`、`sys_user_role`、
|
||||
`user_position`、`project_visible`。要补随时能补,脚本里那几步是现成的:
|
||||
`--steps org,role,positions,user,visible`。
|
||||
|
||||
**技术表和副本表**:`login_log`、`slide_captcha`、`num_seq`、`sys_config`、
|
||||
`*_copy` / `*_bak` / `project_budget_bakall`(老库自己留的备份,一共 2,000 多行)、
|
||||
`*_temp`(老库的草稿表,没丢,想看差异加 `--with-temp`)。
|
||||
|
||||
## 五、字段级归一化
|
||||
|
||||
老库有几处口径跟新系统不一样,脚本**显式换算并在报告里计数**,不静默改数:
|
||||
|
||||
| 项 | 老库 | 新库 | 本次 |
|
||||
| --- | --- | --- | --- |
|
||||
| 税率 | 小数 `0.13` | 百分数 `13` | 只放大 `(0,1]`,118 处。已经是 13 的不会被再乘一次 |
|
||||
| 利润率 | `*_margin` **本来就是百分数**(实测 1578.60/12990=12.15) | 百分数 | 原样搬,不乘 100。库里 0.03 那种是 0.03%,不是 3% |
|
||||
| 产品归类 | `category` 存 `procurement_type` 的 **id 字符串**(`"8"`) | 中文名 + 四个产品归属 | 先查字典翻中文(2,442 处),再折成华智/汇智/华三/紫光其他 |
|
||||
| 月份 | `datetime` | `YYYY-MM` | 优先取 `plan_start_str`/`plan_end_str`,没有才格式化 |
|
||||
| 日期列 | 空串 | `DATE` | 一律给 `NULL`。往 MySQL 的 `DATE` 列写 `''` 是 1292 报错 |
|
||||
| 软删标记 | `bit(1)` / `varchar` / `tinyint` 三种长相 | `bool` | 字节串单独判"有没有非零字节":`bool(b'\x00')` 是 **True**,早先用真值判断,125 个老账号一个都没导进来 |
|
||||
| 主键 | 老 id | 新库自己发号 | 不搬老 id,内存映射表串起来。直接搬会和 seed 撞号,撞了就是静默覆盖 |
|
||||
| 版本 | 概算/预算各一套明细 | `biz_revision` | 每个项目概算、预算各建一版 `draft` |
|
||||
|
||||
超长字符串有个兜底:超过列宽时按列宽截断并计数(列宽从 SQLAlchemy 元数据现读),
|
||||
而不是让整批导入死在 1406 上。`TEXT` 列一律不动。本次没触发。
|
||||
|
||||
## 六、对账
|
||||
|
||||
行数:`范围内` = 老表里属于"已导入项目 且 有预算版本"的行。
|
||||
|
||||
| 模块 | 老表 | 老库总行 | 范围内 | 新表 | 新库 | |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| 概算-收入 | `project_estimate_income` | 2,724 | 2,436 | `estimate_income_line` | 2,436 | OK |
|
||||
| 概算-采购 | `project_estimate_cost` | 5,448 | 4,872 | `estimate_cost_line` | 4,872 | OK |
|
||||
| 概算-管理费 | `project_estimate_cost_manage` | 1,816 | 1,624 | `estimate_other_line` | 1,624 | OK |
|
||||
| 预算-收入 | `project_budget_income_detail` | 3,356 | 2,750 | `budget_income_line` | 2,750 | OK |
|
||||
| 预算-采购 | `project_budget_cost_detail` | 3,486 | 2,824 | `budget_purchase_line` | 2,824 | OK |
|
||||
| 预算-管理费 | `project_budget_cost_manage` | 942 | 740 | `budget_manage_line` | 740 | OK |
|
||||
| 预算-付款计划 | `project_budget_pay_plan` | 1,044 | 920 | `budget_pay_plan_line` | 920 | OK |
|
||||
| 预算-收款计划 | `project_budget_income_plan_detail` | 882 | 802 | `budget_income_plan_line` | 802 | OK |
|
||||
| 预算-资金计划 | `project_budget_plan_detail` | 6,119 | 5,723 | `budget_fund_month` | 5,723 | OK |
|
||||
|
||||
差额全部来自"项目没导入"(老 `project` 897 行里 85 行是软删的),不是丢数据。
|
||||
|
||||
金额(812 个项目全量):
|
||||
|
||||
| 指标 | 老库(同范围) | 新库 |
|
||||
| --- | --- | --- |
|
||||
| 合同额 | 7,636,293,029.75 | 7,636,293,029.75 |
|
||||
| 毛利 | 444,397,702.95 | 444,397,702.95 |
|
||||
| 贡献毛利 A | 51,877,332.66 | 51,877,332.66 |
|
||||
| 资金计划-设备支出 | 1,227,140,576.19 | 1,227,140,576.19 |
|
||||
| 资金计划-施工支出 | 266,391,345.03 | 266,391,345.03 |
|
||||
| 资金计划-项目管理支出 | 31,218,239.66 | 31,218,239.66 |
|
||||
| 资金计划-销售收款 | 2,159,627,551.73 | 2,159,627,551.73 |
|
||||
|
||||
### 抽样复核
|
||||
|
||||
挑一个项目从头到尾对一遍(`P01092` 盈江县公安局无人机采购项目,新库 `id=8012`):
|
||||
|
||||
| 明细 | 老库该项目 | 新库该项目 |
|
||||
| --- | --- | --- |
|
||||
| 概算收入 / 采购 / 管理费 | 3 / 6 / 2 | 3 / 6 / 2 |
|
||||
| 预算收入 / 采购 / 管理费 | 1 / 1 / 2 | 1 / 1 / 2 |
|
||||
| 付款计划 / 收款计划 / 资金计划月 | 1 / 1 / 1 | 1 / 1 / 1 |
|
||||
|
||||
再从接口那头读一遍(`POST /api/v1/auth/login` → `GET /api/v1/projects` →
|
||||
`GET /api/v1/finance/{estimate,budget}/projects/8012/revision`),两个模块都回出
|
||||
`v1 draft` 和上面这些行数,说明导进来的数据不只是躺在表里,页面那条读取链路是通的。
|
||||
|
||||
## 七、没带过来的东西(会直接影响使用)
|
||||
|
||||
按影响大小排,前四条都是"账号组织不迁"这一条口径的直接后果:
|
||||
|
||||
1. **`creator_id` 全挂到 `localadmin`**:812 个项目全部命中"创建人映射不到"。
|
||||
`creator_name` 保留的是老库里的真实姓名,页面上看得是谁建的,但数据权限里
|
||||
"我创建的"这一档没人能用。
|
||||
2. **`org_unit_id` 全空**(`org_unit_name` 文本还在):按部门划的数据权限收不出东西。
|
||||
3. **流程候选人为空**:19 个节点的候选人角色映射不到(角色没迁)。导入的流程一律
|
||||
`empty_strategy=admin`,也就是找不到人时兜底给管理员。**上线前必须到「流程配置」里
|
||||
逐条重指候选人**,否则审批会一路兜到管理员。
|
||||
4. **`project_member` 0 行**:老 `project_visible` 15,302 行"按人授权可见"依赖账号,没账号
|
||||
就没法落。"我参与的"这一档对导入的项目恒为空。
|
||||
5. **`calc_snapshot` 0 行**:所有导入项目的利润各层要等一次「重新试算」。
|
||||
6. **1,272 行采购明细的 `product_category` 留空**:198 种老类别落不进华智/汇智/华三/紫光其他
|
||||
四个归属,出现最多的是外购产品×708、外购服务×165、外购工程×152。
|
||||
BUD-COST-002 汇总出来的四个产品金额因此少这部分。
|
||||
7. **垫资年利率统一 6%**:老库只存垫资利息金额、不存利率,脚本用 `--advance-rate=6` 统一
|
||||
赋值。资金计划的利息依赖它,得按项目逐个核。
|
||||
8. **项目管理费用只有类型和不含税金额**:`item_code`、是否计入差旅限额(BUD-VAL-001)要人工补。
|
||||
顺带说一句,老库其实有一张字段更全的 `project_budget_cost_project_manage_detail`
|
||||
(675 行 / 442 个项目,带 `name`、`detail`、`unit`、`price`、`predict_method`),
|
||||
但它 `total` 有 377 行是 NULL、要靠 `amount×price` 推,两种口径谁作准没定,
|
||||
**所以本次故意没换数据源**,宁可继续用金额安全的 `project_budget_cost_manage` 汇总值。
|
||||
9. **4 个项目没有月度资金计划**(有预算明细但 `project_budget_plan_detail` 无行)。
|
||||
|
||||
## 八、重跑与回滚
|
||||
|
||||
想从零再来一遍,顺序别换:
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
python3 scripts/clean_demo_data.py --apply # 清回基线
|
||||
python3 -c "from app.seed import seed_all; seed_all()" # 补回超管的角色关系
|
||||
python3 scripts/migrate_legacy.py --apply --steps flow,project,estimate,budget
|
||||
```
|
||||
|
||||
清理脚本是整表清 `perm_account_role` 的,账号留着、角色没了,所以要跑一次 seed 把
|
||||
`localadmin` 的 `super_admin` 挂回去(`_ensure_super_role` 就是为这件事存在的)。
|
||||
|
||||
回滚:`python3 scripts/clean_demo_data.py --restore storage/backups/<文件> --apply`。
|
||||
备份是标准 `INSERT`,`mysql 库名 < 备份文件` 也一样能吃。
|
||||
|
||||
**一个反复踩到的坑**:这套 pytest 用的就是开发库(`tests/conftest.py`),跑一次测试会往库里
|
||||
长几个"接口测试项目""脏数据拦截"之类的项目和一堆 `login_log`。清理和导入之间如果有人跑测试,
|
||||
库就不干净了。要么在跑测试后再清一次,要么给测试单独一个库。
|
||||
|
||||
## 九、还需要业务确认的
|
||||
|
||||
- 导入的 4 条流程(`legacy_estimate` / `legacy_budget` / `legacy_settle` / `legacy_final`)
|
||||
是 `published` 状态,但候选人是空的、且老流程 `task_type` 全是或签——会签需求要手工调。
|
||||
`act_task_def.candidate_users` 存的是老用户 id,这类候选人脚本一律没迁。
|
||||
- `legacy_final` / `legacy_settle` 这两条流程对应的**业务模块本身还没实现**,
|
||||
流程留在这儿只是为了不丢信息。
|
||||
- 老 `project_no=P00217` 是 `contract_amount=1.00` 的试算项目,毛利 -495.04 除出 -49504%,
|
||||
已按原值导入并计数。这类脏数据建议核对后清掉。
|
||||
- 812 个项目里有多少是还活着的?老库里有 235 个停在阶段 6、11 个在阶段 9,
|
||||
真正要接着用的可能只是一小部分,其余当历史档案看。
|
||||
|
|
@ -0,0 +1,215 @@
|
|||
# 计算口径
|
||||
|
||||
> 对应实现:`backend/app/service/calc/`(`money` `tax` `profit` `fund_plan` `validate` `mapping` `engine`),
|
||||
> 口径参数在 `backend/app/service/calc/rules.py`(默认值与校验规则)+ `system_config` 表 `calc.` 那一批,
|
||||
> 界面上改:登录后「系统 → 计算口径」,**保存即生效,不用重启,配置文件里不留任何计算规则**。
|
||||
> 每一次试算都把 `calc_version` 写进快照,所以三年后还能说清"这个数是哪套规则算出来的"。
|
||||
|
||||
## 0. 阅读约定
|
||||
|
||||
- 金额一律 `Decimal`,**绝不用 float**;JSON 出参用字符串,避免 JS 精度丢失。
|
||||
- 比率用**百分数本身**(13 表示 13%),与数据库列、前端展示同一口径,前端只加 `%` 不再乘 100。
|
||||
- 中间除法保留 `rate_scale`(默认 4)位,最终金额保留 `money_scale`(默认 2)位,进位默认 `HALF_UP`。
|
||||
- 舍入只发生在 `money.py` 一处,别的模块不允许自己 `round()`。老系统"同一个指标在 Java、浏览器、Excel 各舍一次"造成的对不上账,从根上关掉。
|
||||
|
||||
---
|
||||
|
||||
## 1. 价内税拆分(TAX-002)
|
||||
|
||||
给定含税额 `I` 与税率百分数 `r%`:
|
||||
|
||||
```
|
||||
r = 税率 / 100
|
||||
E = I / (1 + r) # 不含税
|
||||
T = I − E # 税额(补数口径)
|
||||
```
|
||||
|
||||
**税额取补数,不用 `I·r/(1+r)`。** 因为明细要逐行相加,只有补数口径能保证
|
||||
`含税额 = 不含税额 + 税额` 逐行严格成立、分毫不差。老公式在 `I=9999.99, r=9` 这类值上
|
||||
会出现一分钱的加不平(对应风险单 RISK-TAX-002)。
|
||||
|
||||
对账期间如需复现老口径:`tax_from_complement = false`。
|
||||
|
||||
### 含税金额从哪来(TAX-001)
|
||||
|
||||
```
|
||||
人工填了含税总额 → 用它(source=manual)
|
||||
否则 → 数量 × 单价(source=product)
|
||||
```
|
||||
|
||||
> 修过的真 bug:明细表这些列是 `NOT NULL`,"没填"落到库里就是 `0.00`。
|
||||
> 原来的判断是"字符串非空就用它",于是 `0.00` 被当成"人工填了 0",
|
||||
> 凡是走数量×单价的行被整行抹成 0,概算合计少掉一整条明细。
|
||||
> 现在的口径:**0 视为未填**,优先回落到 数量 × 单价;只有既没金额也没单价时才是真 0。
|
||||
> 概算侧和预算侧此前一个用 `or` 回落、一个不用,两边口径分叉,现已统一。
|
||||
|
||||
### 零分母不是 0(BUD-PROFIT-002 / RISK-SET-RATE-001)
|
||||
|
||||
比率一律返回 `Ratio` 对象:要么有值,要么带原因(`zero_denominator`)。
|
||||
前端显示 `—(分母为0)`,**不假装是 0%**。老系统在这里塞过 0、也塞过"利润×100",两种都误导决策。
|
||||
|
||||
需要回到老行为:`zero_denominator = "zero"`。
|
||||
|
||||
---
|
||||
|
||||
## 2. 利润阶梯
|
||||
|
||||
```
|
||||
不含税收入
|
||||
− 采购成本(四类:设备 / 材料 / 分包 / 服务,不含税)
|
||||
────────────────────────────────────
|
||||
= 采购毛利(gross_a) 毛利率 = 采购毛利 ÷ 不含税收入
|
||||
− 项目管理费用
|
||||
− 其他成本
|
||||
− 财务费用(垫资利息)
|
||||
────────────────────────────────────
|
||||
= 项目毛利(gross_b) 毛利率 = 项目毛利 ÷ 不含税收入
|
||||
− 公司管理费用(不含税收入 × 公司管理费用率)
|
||||
────────────────────────────────────
|
||||
= 贡献利润(contribution) 贡献利润率 = 贡献利润 ÷ 不含税收入
|
||||
− 所得税
|
||||
────────────────────────────────────
|
||||
= 净利润 净利润率 = 净利润 ÷ 不含税收入
|
||||
```
|
||||
|
||||
三个扣减项各有一个开关,默认全部扣(推荐口径):
|
||||
|
||||
| 开关 | 默认 | 关掉后等价于 |
|
||||
| --- | --- | --- |
|
||||
| `profit_manage_cost_in_gross` | `true` | 项目毛利不扣项目管理费用 |
|
||||
| `profit_other_cost_in_gross` | `true` | 复现老后端(老后端没扣"其他成本") |
|
||||
| `profit_finance_cost_in_gross` | `true` | 项目毛利不扣财务费用 |
|
||||
|
||||
**双跑对账的做法**:把开关调成老口径跑一遍,逐项目比差异;差异为 0 后把开关拨回推荐口径。
|
||||
不需要为了对账维护两套代码。
|
||||
|
||||
公司管理费用率 `company_manage_fee_rate`(老系统把 2.8% 写死在 `BudgetBean` 的 getter 里,
|
||||
改一次要发一次版)现在是显式配置;在"其他成本"里人工填一条即可覆盖自动值。
|
||||
|
||||
---
|
||||
|
||||
## 3. 资金计划与垫资利息
|
||||
|
||||
### 3.1 月份轴
|
||||
|
||||
从项目计划开始月到计划结束月铺月份轴,逐月:
|
||||
|
||||
```
|
||||
当月净额 = 收款计划(当月) − 付款计划(当月) − 管理费用支出(当月)
|
||||
累计余额 = 上月余额 + 当月净额
|
||||
```
|
||||
|
||||
**余额为负表示公司在垫资。**
|
||||
|
||||
### 3.2 利息
|
||||
|
||||
```
|
||||
当月利息 = max(0, −当月累计余额) × 垫资年利率 ÷ 12
|
||||
资金成本 = Σ 当月利息
|
||||
垫资峰值 = min(累计余额) 的绝对值,及其月份
|
||||
```
|
||||
|
||||
要点:
|
||||
|
||||
- 只对**负余额**月份计息,余额转正后不再累计;
|
||||
- 单利、按月,不做复利——老系统就是单利,改成复利会让历史项目全部对不上;
|
||||
- 包干/垫资模式(`underwritten_mode`)决定这个项目是否计息与计息口径;
|
||||
- 垫资年利率存在项目主表,`Decimal(20,6)`,前端展示统一格式化成 `6.00%`。
|
||||
|
||||
`budget_fund_month` 落库存的是**推导结果**,不是人工录入。人工只改收付款计划和管理费用支出日,
|
||||
重算后资金计划自动跟随;用户手填过的月份行以 `manual` 标记保留(见校验 PLAN-VAL-003)。
|
||||
|
||||
---
|
||||
|
||||
## 4. 送审前校验
|
||||
|
||||
| 规则号 | 内容 | 级别 |
|
||||
| --- | --- | --- |
|
||||
| `BUD-VAL-001` | 差旅费 + 业务费 ≤ [毛利 A − (项目管理费用总额 − 差旅费 − 业务费)] × `travel_business_limit_rate`% | error |
|
||||
| `BUD-VAL-002` | 贡献利润率 ≥ 阈值(`contribution_rate_action`:`block` / `warn` / `none`) | 按配置 |
|
||||
| `PLAN-VAL-001` | 付款计划四类采购的含税合计,分别等于采购明细对应分类的含税金额 | error |
|
||||
| `PLAN-VAL-002` | 资金计划的收 / 付总额与收款计划、付款计划明细勾稽 | error |
|
||||
| `PLAN-VAL-003` | 资金计划月份不得重复,起止月必须存在 | error |
|
||||
| `TAX-06` / `TAX-07` | 税率取值范围、高精度税率提示 | warning |
|
||||
|
||||
三条设计说明:
|
||||
|
||||
1. **老系统的 `BUD-VAL-001` 只在前端校验**(风险单 RISK-BUD-VAL-001),绕过界面调接口就能提交。
|
||||
现在校验在后端,`error` 级直接阻止送审。
|
||||
2. **`BUD-VAL-002` 在老系统里被注释掉了**,实际从不生效。现在默认 `warn`:提示但不拦停,
|
||||
等业务确认阈值口径后再切 `block`。**不敢默认拦停,是因为阈值本身还没和业务签认。**
|
||||
3. `error` 与 `warning` 是两种级别,`error` 才拦送审。返回体里两者分开,前端才能把
|
||||
"必须改"和"建议看一眼"用不同颜色显示。
|
||||
|
||||
校验结果连同 `passed` 布尔一起进快照,审批人看的就是送审那一刻的校验结论。
|
||||
|
||||
---
|
||||
|
||||
## 5. 老系统已知错误口径清单
|
||||
|
||||
重构时逐条比对过,新实现的行为如下(这些是**故意不一样**的地方,不是 bug):
|
||||
|
||||
| 编号 | 老系统行为 | 新系统 |
|
||||
| --- | --- | --- |
|
||||
| RISK-TAX-002 | 前端对 113 / 13% 算出税额 14.69 | 13.00(补数口径,有单测锁住) |
|
||||
| RISK-TAX-001 | 税率参与公式前先舍到 2 位,高精度税率先丢精度 | 默认不预舍;`tax_rate_pre_round=true` 可复现 |
|
||||
| TAX-006 | 单价有值、数量为空时乘法炸出 NPE | 数量为空按 0,交给校验器报必填 |
|
||||
| BUD-PROFIT-002 | 零分母返回 0 | 返回未定义 + 原因 |
|
||||
| FINAL-RATE-001 | 零分母把分母换成 1 | 同上 |
|
||||
| RISK-SET-RATE-001 | 零分母返回"利润×100" | 同上 |
|
||||
| RISK-BUD-VAL-001 | 关键校验只在前端 | 后端强制,`error` 拦送审 |
|
||||
| BUD-VAL-002 | 校验代码被注释,从不生效 | 生效,默认 `warn` |
|
||||
| BUD-PROFIT-001 | 项目毛利没扣"其他成本" | 默认扣,开关可关 |
|
||||
| RISK-EXPORT-001 | Java / 浏览器 / Excel 三处各自舍入 | 舍入只在 `money.py` 一处 |
|
||||
|
||||
---
|
||||
|
||||
## 6. 口径与版本
|
||||
|
||||
口径参数存在 `system_config` 表(`group='calc'`,编码一律 `calc.` 开头),在「系统 → 计算口径」
|
||||
页面上改。默认值(= 推荐口径)、取值范围、枚举候选、界面文案只有一份定义:
|
||||
`backend/app/service/calc/rules.py` 的 `CalcRules` + `RULE_SPECS`,seed 与页面都从它生成。
|
||||
|
||||
| 参数编码 | 默认 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `calc.version` | `2026.10` | 口径版本号,写进每一次快照 |
|
||||
| `calc.money_scale` | `2` | 金额保留位数 |
|
||||
| `calc.rate_scale` | `4` | 比率中间除法保留位数 |
|
||||
| `calc.percent_scale` | `2` | 百分比结果保留位数 |
|
||||
| `calc.rounding` | `HALF_UP` | 舍入方式(7 种,见 `money.py`) |
|
||||
| `calc.zero_denominator` | `undefined` | 零分母的利润率:`undefined` / `zero` |
|
||||
| `calc.tax_from_complement` | `true` | 税额取补数;`false` 回到 `TAX-002` 原式 |
|
||||
| `calc.tax_rate_pre_round` | `false` | 税率先舍到 2 位(`RISK-TAX-001`) |
|
||||
| `calc.profit_manage_cost_in_gross` | `true` | 项目毛利是否扣项目管理费用 |
|
||||
| `calc.profit_other_cost_in_gross` | `true` | 项目毛利是否扣其他成本(关掉即复现老后端) |
|
||||
| `calc.profit_finance_cost_in_gross` | `true` | 项目毛利是否扣财务费用 |
|
||||
| `calc.company_manage_fee_rate` | `2.8` | 公司管理费用率(%),没人工填写时按它派生 |
|
||||
| `calc.travel_business_limit_rate` | `10` | BUD-VAL-001 差旅及业务费限额比例(%) |
|
||||
| `calc.contribution_rate_action` | `warn` | BUD-VAL-002 不达标时:`block` / `warn` / `none` |
|
||||
|
||||
- 为什么不在配置文件里:调一个费率要登机器改文件重启,而重启期间跑出来的快照算哪套口径没人说得清。
|
||||
搬进数据库之后业务自己在页面上改,`app/service/calc/rules.py::normalize` 逐条校验取值
|
||||
(枚举、区间、是不是整数),非法值当场回中文原因;整页一起提交,有一条不合法就一条都不写。
|
||||
- 生效路径:保存后进程内立即重灌;多进程部署(`uvicorn --workers 2`)下别的 worker 看不见这次保存,
|
||||
所以每次试算前 `app.service.biz.apply_sys_config` 会按库里的值再读一遍——快照里的数字和快照上的
|
||||
版本号永远来自同一套口径。
|
||||
- 权限与业务参数分开:能改业务参数(`system:config:edit`)不等于能改财务口径
|
||||
(`system:calcrule:edit`);通用接口 `PUT /api/v1/system/configs/{code}` 遇到 `calc.*` 一律回
|
||||
`use_calc_rules`,避免同一套口径出现两个入口。
|
||||
- `version` 写进每一次 `calc_snapshot.payload_json`,也回写进 `project.calc_version`,
|
||||
并出现在项目详情页与顶部汇总条上。
|
||||
- 生产环境要改口径,**必须同时升 `version`**。否则同一个项目会出现"数字变了但版本号没变",
|
||||
那是最坏的情况:没人能发现。
|
||||
- 前端从 `/bootstrap` 读 `calcVersion` 与 `warnings`,`warnings` 非空时登录页与顶栏会提示
|
||||
(例如"当前生产档位仍在使用双跑对账开关 `tax_from_complement=false`")。
|
||||
|
||||
## 7. 测试覆盖
|
||||
|
||||
`backend/tests/test_calc.py` 的用例编号直接引用上面这些规则号,业务确认口径时可以逐条对:
|
||||
|
||||
```bash
|
||||
cd backend && python3 -m pytest tests/test_calc.py -q
|
||||
```
|
||||
|
||||
覆盖:金额舍入、价内税拆分与可加性、含税金额回落路径、零分母、利润阶梯、
|
||||
资金计划与垫资利息、五类送审校验。
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
VITE_DEV_PORT=5383
|
||||
VITE_DEV_PROXY_TARGET=http://127.0.0.1:8383
|
||||
|
|
@ -0,0 +1 @@
|
|||
VITE_API_TARGET=/
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
node_modules
|
||||
dist
|
||||
*.local
|
||||
.vite
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>四算项目管理系统</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,30 @@
|
|||
{
|
||||
"name": "fourcal-pms-frontend",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc -b && vite build",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "vue-tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@vueuse/core": "^10.11.1",
|
||||
"axios": "^1.7.7",
|
||||
"lucide-vue-next": "^0.451.0",
|
||||
"pinia": "^2.2.4",
|
||||
"vue": "^3.5.12",
|
||||
"vue-router": "^4.4.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.7.5",
|
||||
"@vitejs/plugin-vue": "^5.1.4",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"postcss": "^8.4.47",
|
||||
"tailwindcss": "^3.4.14",
|
||||
"typescript": "~5.6.0",
|
||||
"vite": "^5.4.9",
|
||||
"vue-tsc": "^2.1.6"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
export default {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
<template>
|
||||
<RouterView />
|
||||
<ToastHost />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import ToastHost from '@/components/common/ToastHost.vue'
|
||||
</script>
|
||||
|
|
@ -0,0 +1,143 @@
|
|||
import { ref } from 'vue'
|
||||
import axios, { type AxiosInstance, type AxiosRequestConfig } from 'axios'
|
||||
|
||||
/**
|
||||
* 统一请求层。
|
||||
*
|
||||
* 后端所有业务接口都返回 { ok, data } 或 { ok, error },这里直接把 data 拆出来,
|
||||
* 出错就 throw,业务代码只写 happy path。traceId 会挂在 error 上,报错时能报给后端查日志。
|
||||
*/
|
||||
|
||||
export class ApiRequestError extends Error {
|
||||
code: string
|
||||
traceId: string
|
||||
status: number
|
||||
detail: unknown
|
||||
|
||||
constructor(message: string, code: string, traceId: string, status: number, detail: unknown) {
|
||||
super(message)
|
||||
this.name = 'ApiRequestError'
|
||||
this.code = code
|
||||
this.traceId = traceId
|
||||
this.status = status
|
||||
this.detail = detail
|
||||
}
|
||||
}
|
||||
|
||||
const TOKEN_KEY = 'pms.access'
|
||||
const REFRESH_KEY = 'pms.refresh'
|
||||
|
||||
/**
|
||||
* 令牌同时放 localStorage(刷新后还在)和一个 ref(能被 Vue 追踪)。
|
||||
*
|
||||
* 只用 localStorage 的 getter 是不够的:auth.isLoggedIn 这类 computed 在
|
||||
* 还没登录时会在 "!!access" 处短路,压根没读到 user.value,于是没记下任何依赖,
|
||||
* 登录后也就永远不会重算,表现是"登录成功但被弹回登录页"。
|
||||
*/
|
||||
const accessRef = ref(localStorage.getItem(TOKEN_KEY) || '')
|
||||
const refreshRef = ref(localStorage.getItem(REFRESH_KEY) || '')
|
||||
|
||||
export const tokenStore = {
|
||||
get access() {
|
||||
return accessRef.value
|
||||
},
|
||||
get refresh() {
|
||||
return refreshRef.value
|
||||
},
|
||||
set(access: string, refresh: string) {
|
||||
accessRef.value = access || ''
|
||||
refreshRef.value = refresh || ''
|
||||
localStorage.setItem(TOKEN_KEY, accessRef.value)
|
||||
localStorage.setItem(REFRESH_KEY, refreshRef.value)
|
||||
},
|
||||
clear() {
|
||||
accessRef.value = ''
|
||||
refreshRef.value = ''
|
||||
localStorage.removeItem(TOKEN_KEY)
|
||||
localStorage.removeItem(REFRESH_KEY)
|
||||
}
|
||||
}
|
||||
|
||||
/** 登录过期时由 auth store 注册进来,避免 http 反向依赖 store。 */
|
||||
let onUnauthorized: ((reason: string) => void) | null = null
|
||||
export function setUnauthorizedHandler(fn: (reason: string) => void) {
|
||||
onUnauthorized = fn
|
||||
}
|
||||
|
||||
const http: AxiosInstance = axios.create({
|
||||
baseURL: '/api/v1',
|
||||
timeout: 30000,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
})
|
||||
|
||||
http.interceptors.request.use((config) => {
|
||||
const token = tokenStore.access
|
||||
if (token) config.headers.Authorization = `Bearer ${token}`
|
||||
return config
|
||||
})
|
||||
|
||||
let refreshing: Promise<boolean> | null = null
|
||||
|
||||
async function tryRefresh(): Promise<boolean> {
|
||||
const refresh = tokenStore.refresh
|
||||
if (!refresh) return false
|
||||
try {
|
||||
const resp = await axios.post('/api/v1/auth/refresh', { refreshToken: refresh })
|
||||
const data = resp.data?.data
|
||||
if (!data?.accessToken) return false
|
||||
tokenStore.set(data.accessToken, data.refreshToken || refresh)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function toError(payload: any, status: number): ApiRequestError {
|
||||
const err = payload?.error ?? {}
|
||||
return new ApiRequestError(
|
||||
err.message || `请求失败(${status})`,
|
||||
err.code || 'http_error',
|
||||
err.traceId || '',
|
||||
status,
|
||||
err.detail
|
||||
)
|
||||
}
|
||||
|
||||
http.interceptors.response.use(
|
||||
(response) => {
|
||||
const payload = response.data
|
||||
if (payload && typeof payload === 'object' && 'ok' in payload) {
|
||||
if (payload.ok === false) throw toError(payload, response.status)
|
||||
return payload.data
|
||||
}
|
||||
return payload
|
||||
},
|
||||
async (error) => {
|
||||
const original = error.config as AxiosRequestConfig & { _retried?: boolean }
|
||||
const status = error.response?.status ?? 0
|
||||
|
||||
// 令牌过期:静默续期一次,成功就重放原请求
|
||||
if (status === 401 && original && !original._retried && !original.url?.includes('/auth/')) {
|
||||
original._retried = true
|
||||
refreshing = refreshing ?? tryRefresh()
|
||||
const ok = await refreshing
|
||||
refreshing = null
|
||||
if (ok) return http.request(original)
|
||||
}
|
||||
|
||||
if (status === 401) {
|
||||
// 只有"本来带着令牌"才叫登录过期。免登兑换与口令输错都是没令牌状态下的 401,
|
||||
// 那时该由页面自己说话,全局再冒一句"登录状态已失效"只会把真正的原因盖掉。
|
||||
const wasLoggedIn = !!original?.headers?.Authorization
|
||||
tokenStore.clear()
|
||||
if (wasLoggedIn) onUnauthorized?.('登录状态已失效,请重新登录')
|
||||
}
|
||||
|
||||
const payload = error.response?.data
|
||||
if (payload && typeof payload === 'object' && 'ok' in payload) throw toError(payload, status)
|
||||
if (status === 0) throw new ApiRequestError('连不上服务端,请确认后端已启动', 'network', '', 0, null)
|
||||
throw new ApiRequestError(error.message || '请求失败', 'http_error', '', status, null)
|
||||
}
|
||||
)
|
||||
|
||||
export default http
|
||||
|
|
@ -0,0 +1,262 @@
|
|||
import axios from 'axios'
|
||||
import http from './http'
|
||||
import type * as T from './types'
|
||||
|
||||
/**
|
||||
* 接口按后端 router 分组成命名空间,调用点写成 api.projects.list(...),
|
||||
* 一眼能看出打的是哪个模块,也方便后面换实现(比如做离线 mock)。
|
||||
*/
|
||||
|
||||
export const api = {
|
||||
bootstrap: () => http.get<never, T.Bootstrap>('/bootstrap'),
|
||||
/** /api/health 不在 /api/v1 下,也不能带令牌,单独打。 */
|
||||
health: () => axios.get('/api/health').then((r) => r.data),
|
||||
|
||||
auth: {
|
||||
/**
|
||||
* 账号口令登录:统一身份开着的时候,这两个字段收的是 Hub 的账号口令,由 Hub 判定。
|
||||
* 验证码只有 Hub 要的时候才带值——后端对空串是不会往 Hub 塞的,前端也别凑。
|
||||
*/
|
||||
login: (account: string, password: string, captcha?: { captchaId?: string; captchaAnswer?: string }) =>
|
||||
http.post<never, T.LoginResult>('/auth/login', {
|
||||
account,
|
||||
password,
|
||||
captchaId: captcha?.captchaId || '',
|
||||
captchaAnswer: captcha?.captchaAnswer || ''
|
||||
}),
|
||||
/** 登录页验证码;不需要时后端直接回 required=false,不多跑一趟 Hub。 */
|
||||
loginCaptcha: () => http.get<never, T.LoginCaptcha>('/auth/captcha'),
|
||||
logout: () => http.post('/auth/logout'),
|
||||
me: () => http.get<never, T.Principal>('/auth/me'),
|
||||
menus: () => http.get<never, T.MenuNode[]>('/auth/menus'),
|
||||
changePassword: (oldPassword: string, newPassword: string) =>
|
||||
http.put('/auth/password', { oldPassword, newPassword }),
|
||||
ssoStatus: () => http.get<never, T.SsoStatus>('/auth/sso/status'),
|
||||
/**
|
||||
* 发起免登:后端把 state 存进它自己下发的 HttpOnly Cookie,前端只拿到明文那一份
|
||||
* 用来拼跳转地址。必须先调这一条再去门户,否则落地时后端没有可比的那一份。
|
||||
*/
|
||||
ssoBegin: () => http.post<never, T.SsoBegin>('/auth/sso/state'),
|
||||
/** Hub 把落地地址登记成前端路由时用:票据交给后端换会话。票据一次性,失败不重试。 */
|
||||
ssoTicketLogin: (ticket: string, state: string) =>
|
||||
http.post<never, T.LoginResult>('/auth/sso/ticket', { ticket, state }),
|
||||
/**
|
||||
* Hub 把落地地址登记成后端回调(默认那条)时用:后端已经验过票,这里只拿
|
||||
* 60 秒即失效的一次性短码换会话。短码必须配着回调当场下发的 HttpOnly Cookie,
|
||||
* 所以这条请求只能在收到 302 的那台浏览器上发,转发地址给别人是兑不出去的。
|
||||
*/
|
||||
ssoExchange: (code: string) =>
|
||||
http.post<never, T.LoginResult & { redirect?: string }>('/auth/sso/exchange', { code }),
|
||||
hubStatus: () =>
|
||||
http.get<never, T.HubStatus>('/auth/hub/status')
|
||||
},
|
||||
|
||||
org: {
|
||||
units: (params?: { keyword?: string; includeDisabled?: boolean }) =>
|
||||
http.get<never, T.OrgUnitNode[]>('/org/units', { params }),
|
||||
createUnit: (body: Record<string, unknown>) => http.post('/org/units', body),
|
||||
updateUnit: (id: number, body: Record<string, unknown>) => http.put(`/org/units/${id}`, body),
|
||||
removeUnit: (id: number) => http.delete(`/org/units/${id}`),
|
||||
positions: () => http.get<never, Array<Record<string, unknown>>>('/org/positions'),
|
||||
createPosition: (body: Record<string, unknown>) => http.post('/org/positions', body),
|
||||
updatePosition: (id: number, body: Record<string, unknown>) => http.put(`/org/positions/${id}`, body),
|
||||
accounts: (params: Record<string, unknown>) =>
|
||||
http.get<never, T.Paged<T.AccountRow>>('/org/accounts', { params }),
|
||||
/** 人员选择器用的精简列表,不分页。 */
|
||||
accountOptions: (keyword = '') =>
|
||||
http.get<never, Array<{ id: number; account: string; displayName: string; orgUnitName: string }>>(
|
||||
'/org/accounts/options',
|
||||
{ params: { keyword } }
|
||||
),
|
||||
account: (id: number) => http.get<never, Record<string, unknown>>(`/org/accounts/${id}`),
|
||||
createAccount: (body: Record<string, unknown>) => http.post('/org/accounts', body),
|
||||
updateAccount: (id: number, body: Record<string, unknown>) => http.put(`/org/accounts/${id}`, body),
|
||||
/** 给人挂角色用的候选角色;能管人就读得到,不需要角色管理权限。 */
|
||||
roleOptions: () => http.get<never, T.RoleOption[]>('/org/accounts/role-options'),
|
||||
/** 只换角色、不动档案:统一身份同步来的人本地能改的本来就只有角色。 */
|
||||
assignAccountRoles: (id: number, roleIds: number[]) =>
|
||||
http.put<never, { id: number; roles: T.RoleBrief[] }>(`/org/accounts/${id}/roles`, { roleIds }),
|
||||
/**
|
||||
* 一批人一起改角色。目标两种:``accountIds`` 点名,或 ``target`` 照抄列表筛选条件圈人;
|
||||
* 同步刚跑完"筛出未分配的一批 + 整批追加一个角色"是最常见的那一步。
|
||||
*/
|
||||
batchAssignRoles: (body: {
|
||||
accountIds?: number[]
|
||||
target?: Record<string, unknown>
|
||||
mode: 'append' | 'remove' | 'replace'
|
||||
roleIds: number[]
|
||||
}) =>
|
||||
http.post<never, { accounts: number; affected: number; added: number; removed: number }>(
|
||||
'/org/accounts/roles/batch',
|
||||
body
|
||||
),
|
||||
/** 默认全量镜像;mode=changes 只按游标蹭增量,补不了没发事件的变化。 */
|
||||
hubSync: (mode: 'full' | 'changes' = 'full') =>
|
||||
http.post<never, T.HubSyncRun>(`/org/hub/sync?mode=${mode}`)
|
||||
},
|
||||
|
||||
system: {
|
||||
catalog: () =>
|
||||
http.get<never, { nodes: T.PermNode[]; kinds: string[]; modules: Array<{ module: string; label: string }> }>(
|
||||
'/system/permissions/catalog'
|
||||
),
|
||||
createNode: (body: Record<string, unknown>) => http.post('/system/permissions/nodes', body),
|
||||
updateNode: (id: number, body: Record<string, unknown>) => http.put(`/system/permissions/nodes/${id}`, body),
|
||||
roles: () => http.get<never, T.RoleRow[]>('/system/roles'),
|
||||
createRole: (body: Record<string, unknown>) => http.post('/system/roles', body),
|
||||
updateRole: (id: number, body: Record<string, unknown>) => http.put(`/system/roles/${id}`, body),
|
||||
removeRole: (id: number) => http.delete(`/system/roles/${id}`),
|
||||
rolePermissions: (id: number) => http.get<never, { nodeIds: number[] }>(`/system/roles/${id}/permissions`),
|
||||
setRolePermissions: (id: number, nodeIds: number[]) =>
|
||||
http.put(`/system/roles/${id}/permissions`, { nodeIds }),
|
||||
policies: (module = '') => http.get<never, T.DataPolicy[]>('/system/data-policies', { params: { module } }),
|
||||
policyOptions: () => http.get<never, T.PolicyOptions>('/system/data-policies/options'),
|
||||
createPolicy: (body: Record<string, unknown>) => http.post('/system/data-policies', body),
|
||||
updatePolicy: (id: number, body: Record<string, unknown>) => http.put(`/system/data-policies/${id}`, body),
|
||||
removePolicy: (id: number) => http.delete(`/system/data-policies/${id}`),
|
||||
explain: (accountId: number, module: string) =>
|
||||
http.post<never, { unlimited: boolean; description: string }>('/system/data-policies/explain', {
|
||||
accountId,
|
||||
module
|
||||
}),
|
||||
fieldScopes: (module = '') =>
|
||||
http.get<never, Array<Record<string, unknown>>>('/system/field-scopes', { params: { module } }),
|
||||
setFieldScope: (body: Record<string, unknown>) => http.post('/system/field-scopes', body),
|
||||
configs: () => http.get<never, T.ConfigRow[]>('/system/configs'),
|
||||
updateConfig: (code: string, value: string) => http.put(`/system/configs/${code}`, { value }),
|
||||
calcRules: () => http.get<never, T.CalcRulesPayload>('/system/calc-rules'),
|
||||
/** 整页保存:后端先全部校验,有一条不合法就一条都不写 */
|
||||
updateCalcRules: (values: Record<string, string>) =>
|
||||
http.put<never, T.CalcRulesPayload>('/system/calc-rules', { values }),
|
||||
info: () => http.get<never, Record<string, unknown>>('/system/info')
|
||||
},
|
||||
|
||||
/**
|
||||
* 数据字典。``data`` 只要求登录(任何页面的下拉框都要取值),
|
||||
* 其余是「系统 → 数据字典」的维护接口,要 system:dict:* 权限。
|
||||
*/
|
||||
dicts: {
|
||||
/** 按需取几类字典的取值;留空取全量。 */
|
||||
data: (types: string[] = []) =>
|
||||
http.get<never, T.Enums>('/dicts', { params: { types: types.join(',') } }),
|
||||
types: (params: Record<string, unknown> = {}) =>
|
||||
http.get<never, T.DictTypeRow[]>('/system/dicts', { params }),
|
||||
groups: () => http.get<never, string[]>('/system/dicts/groups'),
|
||||
createType: (body: Record<string, unknown>) => http.post<never, { id: number }>('/system/dicts', body),
|
||||
updateType: (id: number, body: Record<string, unknown>) => http.put(`/system/dicts/${id}`, body),
|
||||
removeType: (id: number) => http.delete(`/system/dicts/${id}`),
|
||||
resetType: (code: string) => http.post<never, { code: string; count: number }>(`/system/dicts/${code}/reset`),
|
||||
items: (code: string) => http.get<never, T.DictItemsPayload>(`/system/dicts/${code}/items`),
|
||||
createItem: (code: string, body: Record<string, unknown>) =>
|
||||
http.post<never, { id: number }>(`/system/dicts/${code}/items`, body),
|
||||
updateItem: (id: number, body: Record<string, unknown>) => http.put(`/system/dicts/items/${id}`, body),
|
||||
removeItem: (id: number) => http.delete(`/system/dicts/items/${id}`),
|
||||
toggleItem: (id: number) =>
|
||||
http.post<never, { id: number; enabled: boolean }>(`/system/dicts/items/${id}/toggle`)
|
||||
},
|
||||
|
||||
projects: {
|
||||
list: (params: Record<string, unknown>) =>
|
||||
http.get<never, T.Paged<T.ProjectRow> & { scope: T.ScopeInfo }>('/projects', { params }),
|
||||
options: () => http.get<never, Array<{ id: number; name: string; projectNo: string }>>('/projects/options'),
|
||||
detail: (id: number) => http.get<never, T.ProjectRow>(`/projects/${id}`),
|
||||
create: (body: Record<string, unknown>) => http.post<never, { id: number }>('/projects', body),
|
||||
update: (id: number, body: Record<string, unknown>) => http.put(`/projects/${id}`, body),
|
||||
/** 删除确认框的数据:能不能删、牵连多少(成员/版本/附件/审批)。 */
|
||||
deleteCheck: (id: number) => http.get<never, T.DeleteCheckPayload>(`/projects/${id}/delete-check`),
|
||||
/** 软删除:项目连同概算预算一起从业务视图里消失,回收站里还能捞回来。 */
|
||||
remove: (id: number, reason = '') =>
|
||||
http.delete<never, { deleted: boolean; id: number }>(`/projects/${id}`, { data: { reason } }),
|
||||
restore: (id: number) => http.post<never, { restored: boolean; id: number }>(`/projects/${id}/restore`),
|
||||
/** 彻底删除前的清单:会销毁哪些数据、要回敲哪个确认词、有没有挡住的理由。 */
|
||||
purgeCheck: (id: number) => http.get<never, T.PurgeCheckPayload>(`/projects/${id}/purge-check`),
|
||||
/** 物理销毁,不可恢复;confirmName 必须与 purge-check 回的那串字一致。 */
|
||||
purge: (id: number, confirmName: string) =>
|
||||
http.delete<never, { purged: boolean; id: number; destroyed: Record<string, number> }>(
|
||||
`/projects/${id}/purge`,
|
||||
{ data: { confirmName } }
|
||||
),
|
||||
stage: (id: number, body: Record<string, unknown>) => http.post(`/projects/${id}/stage`, body),
|
||||
members: (id: number) => http.get<never, Array<Record<string, unknown>>>(`/projects/${id}/members`),
|
||||
addMembers: (id: number, body: Record<string, unknown>) => http.post(`/projects/${id}/members`, body),
|
||||
removeMember: (id: number, accountId: number) => http.delete(`/projects/${id}/members/${accountId}`),
|
||||
visibleRoles: (id: number) => http.get<never, Array<Record<string, unknown>>>(`/projects/${id}/visible-roles`),
|
||||
setVisibleRoles: (id: number, body: Record<string, unknown>) => http.put(`/projects/${id}/visible-roles`, body),
|
||||
attachments: (id: number) => http.get<never, Array<Record<string, unknown>>>(`/projects/${id}/attachments`)
|
||||
},
|
||||
|
||||
finance: {
|
||||
revision: (module: string, projectId: number) =>
|
||||
http.get<never, T.RevisionPayload>(`/finance/${module}/projects/${projectId}/revision`),
|
||||
version: (module: string, projectId: number, revisionId: number) =>
|
||||
http.get<never, T.RevisionPayload>(`/finance/${module}/projects/${projectId}/versions/${revisionId}`),
|
||||
upsertLine: (module: string, projectId: number, lineKey: string, data: Record<string, unknown>) =>
|
||||
http.post<never, T.LineRow>(`/finance/${module}/projects/${projectId}/lines/${lineKey}`, { data }),
|
||||
replaceLines: (module: string, projectId: number, lineKey: string, rows: Array<Record<string, unknown>>) =>
|
||||
http.put(`/finance/${module}/projects/${projectId}/lines/${lineKey}`, { rows }),
|
||||
removeLine: (module: string, projectId: number, lineKey: string, lineId: number) =>
|
||||
http.delete(`/finance/${module}/projects/${projectId}/lines/${lineKey}/${lineId}`),
|
||||
calculate: (module: string, projectId: number) =>
|
||||
http.post<never, T.CalcPayload>(`/finance/${module}/projects/${projectId}/calculate`),
|
||||
submit: (module: string, projectId: number, comment = '', selfSelected: Record<string, number[]> = {}) =>
|
||||
http.post<never, Record<string, unknown>>(`/finance/${module}/projects/${projectId}/submit`, {
|
||||
comment,
|
||||
selfSelected
|
||||
}),
|
||||
newVersion: (module: string, projectId: number) =>
|
||||
http.post<never, { id: number }>(`/finance/${module}/projects/${projectId}/new-version`),
|
||||
snapshots: (module: string, projectId: number) =>
|
||||
http.get<never, Array<Record<string, unknown>>>(`/finance/${module}/projects/${projectId}/snapshots`),
|
||||
snapshot: (module: string, snapshotId: number) =>
|
||||
http.get<never, { payload: T.CalcPayload }>(`/finance/${module}/snapshots/${snapshotId}`),
|
||||
approval: (module: string, projectId: number) =>
|
||||
http.get<never, { instances: T.ApprovalInstance[]; records: T.ApprovalRecord[] }>(
|
||||
`/finance/${module}/projects/${projectId}/approval`
|
||||
)
|
||||
},
|
||||
|
||||
/**
|
||||
* 审计。日志由后端中间件对全部写操作统一记,这里只查:
|
||||
* 操作日志(改了什么)与登录日志(谁进过系统)。
|
||||
*/
|
||||
audit: {
|
||||
logs: (params: Record<string, unknown>) =>
|
||||
http.get<never, T.Paged<T.AuditLogRow> & { window: { from: string; to: string } }>(
|
||||
'/system/operation-logs',
|
||||
{ params }
|
||||
),
|
||||
options: (days = 90) => http.get<never, T.AuditOptions>('/system/operation-logs/options', { params: { days } }),
|
||||
detail: (id: number) => http.get<never, T.AuditLogDetail>(`/system/operation-logs/${id}`),
|
||||
loginLogs: (params: Record<string, unknown>) =>
|
||||
http.get<never, T.Paged<T.LoginLogRow>>('/system/login-logs', { params })
|
||||
},
|
||||
|
||||
approvals: {
|
||||
todo: (params: Record<string, unknown>) =>
|
||||
http.get<never, T.Paged<T.ApprovalTaskRow>>('/approvals/todo', { params }),
|
||||
done: (params: Record<string, unknown>) =>
|
||||
http.get<never, T.Paged<T.ApprovalTaskRow>>('/approvals/done', { params }),
|
||||
created: (params: Record<string, unknown>) =>
|
||||
http.get<never, T.Paged<T.ApprovalInstance>>('/approvals/created', { params }),
|
||||
monitor: (params: Record<string, unknown>) =>
|
||||
http.get<never, T.Paged<T.ApprovalInstance>>('/approvals/monitor', { params }),
|
||||
instance: (id: number) => http.get<never, T.InstanceDetail>(`/approvals/instances/${id}`),
|
||||
/** 退回去哪些节点可选由后端算,前端不猜。 */
|
||||
rollbackTargets: (id: number) =>
|
||||
http.get<never, Array<{ value: string; label: string }>>(`/approvals/instances/${id}/rollback-targets`),
|
||||
act: (taskId: number, body: Record<string, unknown>) => http.post(`/approvals/tasks/${taskId}/act`, body),
|
||||
withdraw: (instanceId: number, comment = '') =>
|
||||
http.post(`/approvals/instances/${instanceId}/withdraw`, { comment }),
|
||||
flows: (module = '') => http.get<never, T.FlowSummary[]>('/approvals/flows', { params: { module } }),
|
||||
flowOptions: () => http.get<never, Record<string, unknown>>('/approvals/flows/options'),
|
||||
flow: (id: number) => http.get<never, T.FlowDetail>(`/approvals/flows/${id}`),
|
||||
createFlow: (body: Record<string, unknown>) => http.post<never, { id: number }>('/approvals/flows', body),
|
||||
updateFlow: (id: number, body: Record<string, unknown>) => http.put(`/approvals/flows/${id}`, body),
|
||||
publishFlow: (id: number) => http.post(`/approvals/flows/${id}/publish`),
|
||||
offlineFlow: (id: number) => http.post(`/approvals/flows/${id}/offline`),
|
||||
delegates: () => http.get<never, Array<Record<string, unknown>>>('/approvals/delegates'),
|
||||
createDelegate: (body: Record<string, unknown>) => http.post('/approvals/delegates', body)
|
||||
}
|
||||
}
|
||||
|
||||
export type { T }
|
||||
|
|
@ -0,0 +1,803 @@
|
|||
/**
|
||||
* 后端接口的类型定义。
|
||||
*
|
||||
* 两个约定要记住,都是后端 envelope 定的:
|
||||
* 1. 出参统一 { ok, data } / { ok, error },http.ts 已经拆过,业务层只拿 data。
|
||||
* 2. 金额一律字符串(防止 JS number 丢精度),比率是百分数数字(13 表示 13%)。
|
||||
*/
|
||||
|
||||
export interface PageMeta {
|
||||
total: number
|
||||
page: number
|
||||
pageSize: number
|
||||
}
|
||||
|
||||
export interface Paged<T> {
|
||||
items: T[]
|
||||
meta: PageMeta
|
||||
}
|
||||
|
||||
export interface ScopeInfo {
|
||||
unlimited: boolean
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface EnumOption {
|
||||
value: string | number
|
||||
label: string
|
||||
/** 状态色(success/warning/danger/info/gray),在「系统 → 数据字典」里配 */
|
||||
tag?: string
|
||||
remark?: string
|
||||
}
|
||||
|
||||
export type Enums = Record<string, EnumOption[]>
|
||||
|
||||
/* ---------------- 数据字典 ---------------- */
|
||||
|
||||
/** 「系统 → 数据字典」左侧那一列。 */
|
||||
export interface DictTypeRow {
|
||||
id: number
|
||||
code: string
|
||||
name: string
|
||||
group: string
|
||||
valueType: string
|
||||
source: string
|
||||
sourceLabel: string
|
||||
/** 代码内置:取值不许改,只能改名、排序、启停 */
|
||||
builtin: boolean
|
||||
enabled: boolean
|
||||
remark: string
|
||||
itemCount: number
|
||||
enabledCount: number
|
||||
/** 代码里有没有这一份字典(决定「恢复默认」按钮亮不亮) */
|
||||
codeDefined: boolean
|
||||
}
|
||||
|
||||
export interface DictItemRow {
|
||||
id: number | null
|
||||
value: string | number
|
||||
label: string
|
||||
sort: number
|
||||
enabled: boolean
|
||||
tag: string
|
||||
builtin: boolean
|
||||
remark: string
|
||||
}
|
||||
|
||||
export interface DictItemsPayload {
|
||||
code: string
|
||||
defined: boolean
|
||||
codeValues: string[]
|
||||
items: DictItemRow[]
|
||||
}
|
||||
|
||||
/* ---------------- 身份 ---------------- */
|
||||
|
||||
export interface UserProfile {
|
||||
id: number
|
||||
account: string
|
||||
displayName: string
|
||||
empCode: string
|
||||
email: string
|
||||
telephone: string
|
||||
avatarUrl: string
|
||||
orgUnitId: number | null
|
||||
orgUnitName: string
|
||||
identityOrgName: string
|
||||
positionId: number | null
|
||||
positionName: string
|
||||
isSystemAdmin: number
|
||||
source: string
|
||||
sourceLabel: string
|
||||
status: number
|
||||
statusLabel: string
|
||||
lastLoginAt: string
|
||||
workLocation: string
|
||||
}
|
||||
|
||||
export interface RoleBrief {
|
||||
id: number
|
||||
code: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface MenuNode {
|
||||
id: number
|
||||
code: string
|
||||
name: string
|
||||
path: string
|
||||
icon: string
|
||||
kind: string
|
||||
module: string
|
||||
parentId: number
|
||||
allowed?: boolean
|
||||
children: MenuNode[]
|
||||
}
|
||||
|
||||
export interface Bootstrap {
|
||||
env: string
|
||||
calcVersion: string
|
||||
production: boolean
|
||||
warnings: string[]
|
||||
hubEnabled: boolean
|
||||
ssoEnabled: boolean
|
||||
/** 登录页留不留"账号 + 口令"这个框。统一身份开着也留——那框收的是 Hub 账号。 */
|
||||
passwordLoginAllowed: boolean
|
||||
/** 口令归不归 Hub 验;true 时登录页要多摆一个验证码。 */
|
||||
hubPasswordLogin: boolean
|
||||
/** 本系统自建账号的口令还认不认;只影响提示语,不影响那个框在不在。 */
|
||||
localPasswordAllowed: boolean
|
||||
/** 口令校验口径:hub / hybrid / local / sso,与后端 [hub].login_mode 同名。 */
|
||||
loginMode: string
|
||||
enums: Enums
|
||||
user: UserProfile | null
|
||||
permissions: string[]
|
||||
roles: RoleBrief[]
|
||||
menus: MenuNode[]
|
||||
fieldMasks: Record<string, Record<string, string>>
|
||||
}
|
||||
|
||||
/** 只含"这个人能看什么",是 Bootstrap 的子集。 */
|
||||
export interface Principal {
|
||||
user: UserProfile
|
||||
permissions: string[]
|
||||
roles: RoleBrief[]
|
||||
menus: MenuNode[]
|
||||
fieldMasks: Record<string, Record<string, string>>
|
||||
}
|
||||
|
||||
export interface LoginResult {
|
||||
accessToken: string
|
||||
refreshToken: string
|
||||
tokenType: string
|
||||
expiresIn: number
|
||||
user: UserProfile
|
||||
/** 这次是统一身份验的口令(hub)还是本系统口令(local)。 */
|
||||
via?: string
|
||||
}
|
||||
|
||||
/** 登录页验证码。Hub 出的是算术题 SVG,image 直接就能喂给 <img>。 */
|
||||
export interface LoginCaptcha {
|
||||
required: boolean
|
||||
captchaId: string
|
||||
image: string
|
||||
/** 少数部署把题目写成文本回传,界面上就直接显示这句。 */
|
||||
question: string
|
||||
/** 问不到验证码时后端不挡登录页,只把原因捎在这里。 */
|
||||
warning?: string
|
||||
}
|
||||
|
||||
/* ---------------- 项目 ---------------- */
|
||||
|
||||
export interface ProjectRow {
|
||||
id: number
|
||||
projectNo: string
|
||||
name: string
|
||||
otherName: string
|
||||
type: number
|
||||
stage: number
|
||||
stageLabel: string
|
||||
customer: string
|
||||
terminalCustomer: string
|
||||
orgUnitId: number | null
|
||||
orgUnitName: string
|
||||
creatorId: number | null
|
||||
creatorName: string
|
||||
principal: string
|
||||
principalId: number | null
|
||||
underwrittenMode: number | null
|
||||
contractAmount: string
|
||||
grossProfitA: string
|
||||
grossProfitARate: number | string | null
|
||||
grossProfit: string
|
||||
grossProfitRate: number | string | null
|
||||
contributionProfit: string
|
||||
contributionProfitRate: number | string | null
|
||||
advancePeakAmount: string
|
||||
advancePeakMonth: string
|
||||
advanceInterestAmount: string
|
||||
calcVersion: string
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
/** 软删除留痕;未删除的项目是空串。 */
|
||||
deletedAt: string
|
||||
deletedByName: string
|
||||
deleteReason: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
|
||||
/** 删除项目前的影响面清单,由后端算,前端不复制规则。 */
|
||||
export interface DeleteRiskItem {
|
||||
code: string
|
||||
message: string
|
||||
}
|
||||
|
||||
export interface PurgeCheckPayload {
|
||||
projectName: string
|
||||
projectNo: string
|
||||
deletedAt: string
|
||||
deletedByName: string
|
||||
deletable: boolean
|
||||
blockers: DeleteRiskItem[]
|
||||
/** 要回敲进确认框的那串字:项目编号,没编号就用项目名。 */
|
||||
confirmName: string
|
||||
counts: Record<string, number>
|
||||
}
|
||||
|
||||
/** 审计:一条写操作日志(列表视图,明细里还带脱敏后的请求体)。 */
|
||||
export interface AuditLogRow {
|
||||
id: number
|
||||
accountName: string
|
||||
action: string
|
||||
actionLabel: string
|
||||
objectType: string
|
||||
objectId: string
|
||||
objectName: string
|
||||
ip: string
|
||||
createdAt: string
|
||||
method: string
|
||||
path: string
|
||||
status: number
|
||||
ok: boolean
|
||||
durationMs: number
|
||||
errorCode: string
|
||||
errorMessage: string
|
||||
traceId: string
|
||||
}
|
||||
|
||||
export interface AuditLogDetail {
|
||||
id: number
|
||||
accountId: number | null
|
||||
accountName: string
|
||||
action: string
|
||||
actionLabel: string
|
||||
objectType: string
|
||||
objectId: string
|
||||
objectName: string
|
||||
ip: string
|
||||
createdAt: string
|
||||
detail: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface AuditOptions {
|
||||
actions: Array<{ value: string; label: string; count: number }>
|
||||
objectTypes: Array<{ value: string; label: string; count: number }>
|
||||
}
|
||||
|
||||
export interface LoginLogRow {
|
||||
id: number
|
||||
account: string
|
||||
success: boolean
|
||||
reason: string
|
||||
ip: string
|
||||
userAgent: string
|
||||
mode: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export interface DeleteCheckPayload {
|
||||
projectName: string
|
||||
projectNo: string
|
||||
stage: number
|
||||
stageLabel: string
|
||||
deletable: boolean
|
||||
blockers: DeleteRiskItem[]
|
||||
warnings: DeleteRiskItem[]
|
||||
stats: {
|
||||
members: number
|
||||
attachments: number
|
||||
revisions: number
|
||||
approvedRevisions: number
|
||||
approvalInstances: number
|
||||
reviewingInstances: number
|
||||
}
|
||||
}
|
||||
|
||||
export type LineRow = Record<string, string | number | boolean | null>
|
||||
|
||||
export interface RevisionInfo {
|
||||
id: number
|
||||
version: number
|
||||
status: string
|
||||
statusLabel: string
|
||||
editable: boolean
|
||||
title: string
|
||||
basedOnId: number | null
|
||||
snapshotId: number | null
|
||||
calcVersion: string
|
||||
creatorName: string
|
||||
submittedAt: string
|
||||
decidedAt: string
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export interface RevisionPayload {
|
||||
module: string
|
||||
moduleLabel: string
|
||||
project: ProjectRow & { advanceInterestRate?: string }
|
||||
revision: RevisionInfo
|
||||
versions: RevisionInfo[]
|
||||
lines: Record<string, LineRow[]>
|
||||
snapshot: { id: number | null; calcVersion: string; createdAt: string; payload: CalcPayload }
|
||||
}
|
||||
|
||||
/* ---------------- 计算结果 ---------------- */
|
||||
|
||||
export interface Ratio {
|
||||
value: number | string | null
|
||||
defined: boolean
|
||||
reason: string | null
|
||||
numerator: string
|
||||
denominator: string
|
||||
}
|
||||
|
||||
export interface GroupAmount {
|
||||
count: number
|
||||
include: string
|
||||
exclude: string
|
||||
tax: string
|
||||
}
|
||||
|
||||
export interface FundMonth {
|
||||
month: string
|
||||
device_cost: string
|
||||
construction_cost: string
|
||||
service_cost: string
|
||||
other_cost: string
|
||||
manage_cost: string
|
||||
earnest_cost: string
|
||||
total_cost: string
|
||||
sale_income: string
|
||||
earnest_income: string
|
||||
total_income: string
|
||||
opening_balance: string
|
||||
balance: string
|
||||
underwritten_plan: string
|
||||
repayment_plan: string
|
||||
capital_interest: string
|
||||
interest_rate: string
|
||||
manual_override: boolean
|
||||
}
|
||||
|
||||
export interface FundPlan {
|
||||
months: FundMonth[]
|
||||
peak_month: string
|
||||
peak_value: string
|
||||
interest_total: string
|
||||
underwritten_total: string
|
||||
repayment_total: string
|
||||
}
|
||||
|
||||
export interface ValidationIssue {
|
||||
ruleId: string
|
||||
severity: 'error' | 'warning'
|
||||
message: string
|
||||
field: string
|
||||
detail?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface ValidationReport {
|
||||
passed: boolean
|
||||
errors: ValidationIssue[]
|
||||
warnings: ValidationIssue[]
|
||||
}
|
||||
|
||||
export interface CalcPayload {
|
||||
calc_version?: string
|
||||
contract_amount?: string
|
||||
groups?: Record<string, Record<string, GroupAmount>>
|
||||
product_amounts?: Record<string, GroupAmount>
|
||||
manage?: { total: string; travel_business: string }
|
||||
other_cost?: { total: string }
|
||||
profit?: Record<string, Ratio | string | undefined>
|
||||
fund_plan?: FundPlan
|
||||
validation?: ValidationReport
|
||||
}
|
||||
|
||||
/* ---------------- 审批 ---------------- */
|
||||
|
||||
/** 待办 / 已办共用行结构:mode=todo 用前半,mode=done 用后半。 */
|
||||
export interface ApprovalTaskRow {
|
||||
taskId: number
|
||||
instanceId: number
|
||||
projectId: number
|
||||
projectName: string
|
||||
businessModule?: string
|
||||
businessModuleLabel: string
|
||||
nodeName: string
|
||||
signType?: string
|
||||
signTypeLabel?: string
|
||||
submitterName?: string
|
||||
submittedAt?: string
|
||||
dueAt?: string
|
||||
snapshotId?: number | null
|
||||
action?: string
|
||||
actionLabel?: string
|
||||
comment?: string
|
||||
instanceStatus?: string
|
||||
instanceStatusLabel?: string
|
||||
actedAt?: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export interface ApprovalInstance {
|
||||
id: number
|
||||
flowName: string
|
||||
businessModule: string
|
||||
businessModuleLabel: string
|
||||
projectId: number
|
||||
projectName: string
|
||||
revisionId: number
|
||||
snapshotId: number | null
|
||||
status: string
|
||||
statusLabel: string
|
||||
currentNode: string
|
||||
submitterName: string
|
||||
submittedAt: string
|
||||
finishedAt: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export interface InstanceTask {
|
||||
id: number
|
||||
nodeKey: string
|
||||
nodeName: string
|
||||
assigneeName: string
|
||||
status: string
|
||||
statusLabel: string
|
||||
action?: string
|
||||
actionLabel?: string
|
||||
comment?: string
|
||||
actedAt?: string
|
||||
dueAt?: string
|
||||
signType?: string
|
||||
signTypeLabel?: string
|
||||
orderInNode?: number
|
||||
}
|
||||
|
||||
export interface InstanceDetail {
|
||||
instance: ApprovalInstance & { flowId?: number; businessId?: number }
|
||||
canWithdraw: boolean
|
||||
myTaskIds: number[]
|
||||
revision: { id: number; version: string; status: string; statusLabel: string } | null
|
||||
tasks: InstanceTask[]
|
||||
records: ApprovalRecord[]
|
||||
}
|
||||
|
||||
export interface ApprovalRecord {
|
||||
id: number
|
||||
action: string
|
||||
actionLabel: string
|
||||
operatorName: string
|
||||
nodeName: string
|
||||
comment: string
|
||||
createdAt: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
/** 流程设计器用的候选人项。 */
|
||||
export interface CandidateItem {
|
||||
type: string
|
||||
ids?: number[]
|
||||
levels?: number
|
||||
field?: string
|
||||
if?: string
|
||||
then_type?: string
|
||||
then_ids?: number[]
|
||||
}
|
||||
|
||||
export interface FlowNode {
|
||||
id?: number
|
||||
nodeKey: string
|
||||
name: string
|
||||
nodeType: string
|
||||
orderNumber: number
|
||||
signType: string
|
||||
/** [{type:'role',ids:[3]} | {type:'fixed',ids:[1,2]} | {type:'org_manager_chain',levels:2} ...] */
|
||||
candidates: CandidateItem[]
|
||||
emptyStrategy: string
|
||||
/** 受限表达式串:contract_amount>=5000000 and type in [1,2] */
|
||||
condition: string
|
||||
nextNodeKey: string
|
||||
rejectTo: string
|
||||
rollbackKeys: string[]
|
||||
commentRequired: boolean
|
||||
rejectCommentRequired: boolean
|
||||
timeoutHours: number
|
||||
timeoutAction: string
|
||||
enabled: boolean
|
||||
remark: string
|
||||
}
|
||||
|
||||
export interface FlowSummary {
|
||||
id: number
|
||||
key: string
|
||||
name: string
|
||||
businessModule: string
|
||||
businessModuleLabel: string
|
||||
version: number
|
||||
status: string
|
||||
priority: number
|
||||
matchExpressions: unknown[]
|
||||
allowSelfSelect: number
|
||||
autoSkipDuplicate: number
|
||||
remark: string
|
||||
nodeCount: number
|
||||
}
|
||||
|
||||
export interface FlowDetail {
|
||||
flow: FlowSummary
|
||||
nodes: FlowNode[]
|
||||
errors: string[]
|
||||
}
|
||||
|
||||
/* ---------------- 组织 / 系统 ---------------- */
|
||||
|
||||
export interface OrgUnitNode {
|
||||
id: number
|
||||
parentId: number
|
||||
name: string
|
||||
code: string
|
||||
shortName: string
|
||||
level: number
|
||||
path: string
|
||||
status: number
|
||||
statusLabel: string
|
||||
managerId: number | null
|
||||
managerName: string
|
||||
orderNumber: number
|
||||
isHub: number
|
||||
userCount: number
|
||||
children: OrgUnitNode[]
|
||||
}
|
||||
|
||||
export interface AccountRow {
|
||||
id: number
|
||||
account: string
|
||||
displayName: string
|
||||
empCode: string
|
||||
email: string
|
||||
telephone: string
|
||||
orgUnitId: number | null
|
||||
orgUnitName: string
|
||||
positionId: number | null
|
||||
positionName: string
|
||||
leaderId: number | null
|
||||
status: number
|
||||
statusLabel: string
|
||||
source: string
|
||||
sourceLabel: string
|
||||
isSystemAdmin: number
|
||||
roles: RoleBrief[]
|
||||
workLocation: string
|
||||
remark: string
|
||||
lastLoginAt: string
|
||||
canLoginLocally: boolean
|
||||
}
|
||||
|
||||
export interface PermNode {
|
||||
id: number
|
||||
parentId: number
|
||||
code: string
|
||||
name: string
|
||||
kind: string
|
||||
path: string
|
||||
icon: string
|
||||
module: string
|
||||
sort: number
|
||||
enabled: number
|
||||
children: PermNode[]
|
||||
}
|
||||
|
||||
/**
|
||||
* 给人挂角色时的候选角色。
|
||||
*
|
||||
* 与 ``RoleRow`` 分开:这条只要"叫什么、多少人挂着",看不到角色里的权限点,
|
||||
* 所以能管人(org:person:view)就够,不必一并给出角色管理(system:role:view)的权限。
|
||||
*/
|
||||
export interface RoleOption {
|
||||
id: number
|
||||
code: string
|
||||
name: string
|
||||
builtin: boolean
|
||||
/** 停用的角色带回来是为了"看得见、摘得掉",不是为了让人新挂。 */
|
||||
enabled: boolean
|
||||
remark: string
|
||||
memberCount: number
|
||||
}
|
||||
|
||||
export interface RoleRow {
|
||||
id: number
|
||||
code: string
|
||||
name: string
|
||||
builtin: number
|
||||
enabled: number
|
||||
orderNumber: number
|
||||
remark: string
|
||||
permissionCount: number
|
||||
}
|
||||
|
||||
export interface DataPolicy {
|
||||
id: number
|
||||
module: string
|
||||
/** 这条策略实际管到哪几个模块:族代表一条管全族,成员模块上配的只管自己 */
|
||||
covers?: Array<{ module: string; label: string }>
|
||||
name: string
|
||||
subjectType: string
|
||||
subjectId: number
|
||||
effect: string
|
||||
scopeType: string
|
||||
scopeLabel: string
|
||||
includeChildren: boolean
|
||||
targetIds: number[]
|
||||
conditions: ConditionGroup | null
|
||||
validFrom: string
|
||||
validTo: string
|
||||
enabled: number
|
||||
priority: number
|
||||
remark: string
|
||||
}
|
||||
|
||||
/** 条件树:{ op: "and"|"or", items: [ 叶子 | 子组 ] },叶子是 { field, operator, value }。 */
|
||||
export interface ConditionGroup {
|
||||
op?: 'and' | 'or'
|
||||
items?: Array<ConditionLeaf | ConditionGroup>
|
||||
}
|
||||
|
||||
export interface ConditionLeaf {
|
||||
field?: string
|
||||
operator?: string
|
||||
value?: string | number | null
|
||||
}
|
||||
|
||||
export interface ConfigRow {
|
||||
id: number
|
||||
code: string
|
||||
name: string
|
||||
value: string
|
||||
valueType: string
|
||||
group: string
|
||||
editable: number
|
||||
remark: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 一条计算口径:内核怎么算钱的一个参数。
|
||||
*
|
||||
* 默认值、取值范围、枚举候选都从后端来(app/service/calc/rules.py 是唯一一份定义),
|
||||
* 前端不抄常量表——抄一份就会和内核那份对不上,而对不上的是算钱的口径。
|
||||
*/
|
||||
export interface CalcRule {
|
||||
code: string
|
||||
key: string
|
||||
name: string
|
||||
/** int / decimal / bool / enum / string,决定用哪种控件 */
|
||||
kind: string
|
||||
valueType: string
|
||||
unit: string
|
||||
step: string
|
||||
min: number | null
|
||||
max: number | null
|
||||
choices: Array<{ value: string; label: string }>
|
||||
remark: string
|
||||
/** 当前生效值(库里存的折过之后的) */
|
||||
value: string
|
||||
/** 推荐口径 */
|
||||
default: string
|
||||
/** 库里原样存着的字符串 */
|
||||
stored: string
|
||||
/** 库里有没有这一行(没有则按默认值生效) */
|
||||
configured: boolean
|
||||
/** 库里存的和生效的不一样:存进了非法值,内核已退回默认,页面上必须看得见 */
|
||||
normalized: boolean
|
||||
}
|
||||
|
||||
export interface CalcRulesPayload {
|
||||
group: string
|
||||
version: string
|
||||
sections: Array<{ key: string; title: string; hint: string; rules: CalcRule[] }>
|
||||
/** 有多少条被改成跟推荐口径不一样 */
|
||||
changed: number
|
||||
seeded: number
|
||||
}
|
||||
|
||||
export interface PolicyOptions {
|
||||
modules: Array<{
|
||||
module: string
|
||||
label: string
|
||||
filterable: string[]
|
||||
numeric: string[]
|
||||
/** 口径组的族代表;空表示这个模块自己就是一个口径 */
|
||||
family?: string
|
||||
covers?: string[]
|
||||
}>
|
||||
scopeTypes: EnumOption[]
|
||||
subjectTypes: EnumOption[]
|
||||
effects: EnumOption[]
|
||||
operators: EnumOption[]
|
||||
dynamicValues: EnumOption[]
|
||||
roles: Array<{ id: number; name: string }>
|
||||
}
|
||||
|
||||
/** 一次统一身份同步的结果。status:success / partial / failed / skipped。 */
|
||||
export interface HubSyncRun {
|
||||
id: number
|
||||
trigger: string
|
||||
status: 'success' | 'partial' | 'failed' | 'skipped' | string
|
||||
startedAt: string
|
||||
finishedAt: string
|
||||
orgTotal: number
|
||||
orgCreated: number
|
||||
orgUpdated: number
|
||||
orgDisabled: number
|
||||
accountTotal: number
|
||||
accountCreated: number
|
||||
accountUpdated: number
|
||||
accountDisabled: number
|
||||
skippedLocal: number
|
||||
/** 目录游标;0 表示这次不是增量批次(或整批失败没推进)。 */
|
||||
cursorAfter: number
|
||||
error: string
|
||||
steps: Array<{ name: string; at: string; [key: string]: unknown }>
|
||||
}
|
||||
|
||||
/** 免登运行态:登录页据此决定留不留口令表单,"去门户"按钮据此决定跳哪。 */
|
||||
export interface SsoStatus {
|
||||
enabled: boolean
|
||||
hubEnabled: boolean
|
||||
passwordLoginAllowed: boolean
|
||||
hubPasswordLogin: boolean
|
||||
localPasswordAllowed: boolean
|
||||
loginMode: string
|
||||
hubBaseUrl: string
|
||||
portalUrl: string
|
||||
appCode: string
|
||||
/** 免登三件套缺哪几项;非空就等于免登没开。 */
|
||||
missing: string[]
|
||||
/** 要去 Hub 后台登记的落地地址,后端按当前访问地址现算,直接抄。 */
|
||||
callbackUrl: string
|
||||
aliasUrl: string
|
||||
landingUrl: string
|
||||
callbackPath: string
|
||||
aliasPath: string
|
||||
landingPath: string
|
||||
cookieName: string
|
||||
codeTtlSeconds: number
|
||||
}
|
||||
|
||||
/** ``POST /auth/sso/state`` 的返回:state 明文 + 门户地址。 */
|
||||
export interface SsoBegin {
|
||||
state: string
|
||||
portalUrl: string
|
||||
appCode: string
|
||||
ttlSeconds: number
|
||||
}
|
||||
|
||||
export interface HubStatus {
|
||||
enabled: boolean
|
||||
configured: boolean
|
||||
ssoConfigured: boolean
|
||||
/** 免登那一侧的运行态:缺哪几项、Hub 上该登记哪条回调地址。 */
|
||||
sso?: {
|
||||
enabled: boolean
|
||||
missing: string[]
|
||||
appCode: string
|
||||
portalUrl: string
|
||||
stateRequired: boolean
|
||||
callbackPath: string
|
||||
aliasPath: string
|
||||
landingPath: string
|
||||
callbackUrl: string
|
||||
aliasUrl: string
|
||||
landingUrl: string
|
||||
codeTtlSeconds: number
|
||||
}
|
||||
baseUrl: string
|
||||
syncIntervalMinutes: number
|
||||
changesIntervalSeconds: number
|
||||
/** 本地已同步到的游标;0 表示还没成功全量过,下一次定时任务会先补全量。 */
|
||||
cursor: number
|
||||
autoSyncActive: boolean
|
||||
latest: HubSyncRun | null
|
||||
}
|
||||
|
|
@ -0,0 +1,294 @@
|
|||
<template>
|
||||
<Teleport to="body">
|
||||
<Transition name="drawer">
|
||||
<div v-if="modelValue" class="fixed inset-0 z-[900]">
|
||||
<div class="absolute inset-0 bg-gray-900/45 backdrop-blur-[2px]" @click="close"></div>
|
||||
|
||||
<aside
|
||||
class="absolute inset-y-0 right-0 flex w-full max-w-[640px] flex-col bg-white shadow-2xl dark:bg-dark-900"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
>
|
||||
<!-- 头部:一眼看清"哪个项目、卡在哪、谁没处理" -->
|
||||
<header class="flex items-start justify-between gap-4 border-b border-gray-100 px-5 py-3.5 dark:border-dark-700">
|
||||
<div class="min-w-0">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<h3 class="truncate text-sm font-semibold text-gray-900 dark:text-gray-100">
|
||||
{{ detail?.instance.projectName || '流程详情' }}
|
||||
</h3>
|
||||
<StatusBadge v-if="detail" :status="detail.instance.status" :label="detail.instance.statusLabel" />
|
||||
</div>
|
||||
<p class="mt-0.5 truncate text-xs text-gray-500 dark:text-dark-400">
|
||||
{{ detail?.instance.flowName }} · {{ detail?.instance.businessModuleLabel }}
|
||||
<span v-if="detail?.revision"> · {{ detail.revision.version }}({{ detail.revision.statusLabel }})</span>
|
||||
</p>
|
||||
</div>
|
||||
<button class="btn btn-ghost btn-icon -mr-1 -mt-1 shrink-0" @click="close">
|
||||
<Icon name="x" size="sm" />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div class="flex-1 overflow-y-auto px-5 py-4">
|
||||
<LoadingSpinner v-if="loading && !detail" class="mx-auto mt-12" />
|
||||
|
||||
<EmptyState v-else-if="!detail" title="加载失败" description="关闭后重新打开可重试" />
|
||||
|
||||
<template v-else>
|
||||
<dl class="grid grid-cols-2 gap-x-4 gap-y-2.5 rounded-xl bg-gray-50 px-4 py-3 text-xs dark:bg-dark-800/60">
|
||||
<div v-for="item in metaItems" :key="item.label" class="min-w-0">
|
||||
<dt class="text-gray-400">{{ item.label }}</dt>
|
||||
<dd class="mt-0.5 truncate text-gray-800 dark:text-gray-200">{{ item.value || '-' }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<!-- 节点进度:按节点分组,待办人直接摆在节点上 -->
|
||||
<section class="mt-5">
|
||||
<h4 class="mb-2 text-xs font-semibold uppercase tracking-wide text-gray-400">节点进度</h4>
|
||||
<ol class="relative space-y-3">
|
||||
<li v-for="(group, index) in nodeGroups" :key="group.nodeKey + index" class="relative flex gap-3">
|
||||
<div class="relative flex flex-col items-center">
|
||||
<span :class="['z-10 flex h-6 w-6 shrink-0 items-center justify-center rounded-full', group.tone]">
|
||||
<Icon :name="group.icon" size="xs" />
|
||||
</span>
|
||||
<span v-if="index < nodeGroups.length - 1" class="absolute top-6 h-full w-px bg-gray-200 dark:bg-dark-700"></span>
|
||||
</div>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="text-sm font-medium text-gray-900 dark:text-gray-100">{{ group.nodeName }}</span>
|
||||
<span :class="['badge', group.badge]">{{ group.label }}</span>
|
||||
<span v-if="group.signTypeLabel" class="badge badge-gray">{{ group.signTypeLabel }}</span>
|
||||
</div>
|
||||
<ul class="mt-1.5 space-y-1.5">
|
||||
<li v-for="task in group.tasks" :key="task.id"
|
||||
class="flex items-start justify-between gap-3 rounded-lg border border-gray-100 px-2.5 py-1.5 dark:border-dark-700">
|
||||
<div class="min-w-0">
|
||||
<div class="flex flex-wrap items-center gap-1.5">
|
||||
<span class="text-xs font-medium text-gray-800 dark:text-gray-200">{{ task.assigneeName || '未指派' }}</span>
|
||||
<span :class="['badge', taskBadge(task.status)]">{{ taskStatusLabel(task) }}</span>
|
||||
<span v-if="task.actionLabel" class="text-xs text-gray-400">{{ task.actionLabel }}</span>
|
||||
</div>
|
||||
<p v-if="task.comment" class="mt-0.5 break-words text-xs leading-relaxed text-gray-500 dark:text-dark-400">
|
||||
{{ task.comment }}
|
||||
</p>
|
||||
<p v-if="task.status === 'pending' && task.dueAt" class="mt-0.5 text-xs text-warning-600 dark:text-warning-400">
|
||||
到期 {{ formatDateTime(task.dueAt) }}
|
||||
</p>
|
||||
</div>
|
||||
<span class="shrink-0 text-xs text-gray-400">{{ task.actedAt ? formatDateTime(task.actedAt) : '' }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</li>
|
||||
</ol>
|
||||
</section>
|
||||
|
||||
<!-- 审批流水:审计视角,含自动跳过和超时 -->
|
||||
<section class="mt-5">
|
||||
<h4 class="mb-2 text-xs font-semibold uppercase tracking-wide text-gray-400">操作流水</h4>
|
||||
<p v-if="!detail.records.length" class="text-xs text-gray-400">暂无操作记录</p>
|
||||
<ol v-else class="space-y-1.5">
|
||||
<li v-for="record in detail.records" :key="record.id"
|
||||
class="flex items-start gap-2.5 rounded-lg px-2.5 py-1.5 text-xs hover:bg-gray-50 dark:hover:bg-dark-800/50">
|
||||
<span class="mt-0.5 shrink-0 text-gray-400">{{ formatDateTime(record.createdAt) }}</span>
|
||||
<span class="min-w-0 flex-1">
|
||||
<span class="font-medium text-gray-800 dark:text-gray-200">{{ record.operatorName }}</span>
|
||||
<span class="mx-1 text-gray-400">{{ record.actionLabel }}</span>
|
||||
<span v-if="record.nodeName" class="text-gray-500 dark:text-dark-400">[{{ record.nodeName }}]</span>
|
||||
<span v-if="record.targetNames" class="text-gray-500 dark:text-dark-400">→ {{ record.targetNames }}</span>
|
||||
<span v-if="record.comment" class="mt-0.5 block break-words text-gray-500 dark:text-dark-400">{{ record.comment }}</span>
|
||||
</span>
|
||||
</li>
|
||||
</ol>
|
||||
</section>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<footer class="flex items-center justify-between gap-2 border-t border-gray-100 px-5 py-3 dark:border-dark-700">
|
||||
<div class="text-xs text-gray-400">
|
||||
<span v-if="detail?.myTaskIds?.length">你有 {{ detail.myTaskIds.length }} 条待办</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<RouterLink v-if="projectLink" :to="projectLink" class="btn btn-secondary btn-sm" @click="close">
|
||||
<Icon name="folder" size="sm" /> 查看单据
|
||||
</RouterLink>
|
||||
<RouterLink v-if="detail?.myTaskIds?.length" to="/workbench/todo" class="btn btn-primary btn-sm" @click="close">
|
||||
<Icon name="check" size="sm" /> 去办理
|
||||
</RouterLink>
|
||||
<button v-if="detail?.canWithdraw" class="btn btn-danger btn-sm" :disabled="withdrawing" @click="onWithdraw">
|
||||
<LoadingSpinner v-if="withdrawing" size="sm" /> 撤回
|
||||
</button>
|
||||
</div>
|
||||
</footer>
|
||||
</aside>
|
||||
|
||||
<BaseDialog
|
||||
v-model="withdrawOpen"
|
||||
title="撤回审批"
|
||||
description="撤回后单据回到可编辑状态,需要重新提交。"
|
||||
confirm-text="确认撤回"
|
||||
confirm-tone="danger"
|
||||
:confirming="withdrawing"
|
||||
width="sm"
|
||||
@confirm="doWithdraw"
|
||||
>
|
||||
<p class="text-sm leading-relaxed text-gray-700 dark:text-gray-300">
|
||||
确认撤回「{{ detail?.instance.projectName }}」的审批申请?
|
||||
</p>
|
||||
<textarea v-model="withdrawComment" class="input mt-3" rows="3"
|
||||
placeholder="撤回原因(可选,会记入审批流水)"></textarea>
|
||||
</BaseDialog>
|
||||
</div>
|
||||
</Transition>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import Icon from '@/components/icons/Icon.vue'
|
||||
import BaseDialog from '@/components/common/BaseDialog.vue'
|
||||
import EmptyState from '@/components/common/EmptyState.vue'
|
||||
import LoadingSpinner from '@/components/common/LoadingSpinner.vue'
|
||||
import StatusBadge from '@/components/common/StatusBadge.vue'
|
||||
import { api } from '@/api'
|
||||
import type { InstanceDetail, InstanceTask } from '@/api/types'
|
||||
import { formatDateTime } from '@/utils/format'
|
||||
import { useAsync, useAction } from '@/composables/useAsync'
|
||||
|
||||
const props = defineProps<{ modelValue: boolean; instanceId: number | null }>()
|
||||
const emit = defineEmits<{ 'update:modelValue': [boolean]; changed: [] }>()
|
||||
|
||||
const withdrawOpen = ref(false)
|
||||
// useAction 的 pending 直接接到按钮 loading 上,重复点击由 disabled 挡掉
|
||||
const { pending: withdrawing, perform: performWithdraw } = useAction()
|
||||
const withdrawComment = ref('')
|
||||
|
||||
const { loading, data, run } = useAsync<[number], InstanceDetail>((id) => api.approvals.instance(id))
|
||||
const detail = computed(() => data.value)
|
||||
|
||||
watch(
|
||||
() => [props.modelValue, props.instanceId] as const,
|
||||
([open, id]) => {
|
||||
if (open && id) run(id)
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
interface NodeGroup {
|
||||
nodeKey: string
|
||||
nodeName: string
|
||||
signTypeLabel?: string
|
||||
tasks: InstanceTask[]
|
||||
pending: boolean
|
||||
label: string
|
||||
icon: string
|
||||
tone: string
|
||||
badge: string
|
||||
}
|
||||
|
||||
/** 后端已经给了 statusLabel,这里只兜底,避免字典缺失时露出英文。 */
|
||||
const TASK_FALLBACK: Record<string, string> = {
|
||||
pending: '待办理',
|
||||
done: '已办理',
|
||||
skipped: '自动跳过',
|
||||
transferred: '已转办',
|
||||
canceled: '已作废'
|
||||
}
|
||||
|
||||
function taskStatusLabel(task: InstanceTask) {
|
||||
return task.statusLabel || TASK_FALLBACK[task.status] || task.status
|
||||
}
|
||||
function taskBadge(status: string) {
|
||||
return status === 'pending' ? 'badge-warning' : status === 'done' ? 'badge-success' : 'badge-gray'
|
||||
}
|
||||
|
||||
/**
|
||||
* 同一个节点的或签/会签多人合并成一组,读起来才像流程图而不是一长串流水。
|
||||
* 只合并相邻同名节点:退回到同一节点两次时,应该看到两段。
|
||||
*/
|
||||
const nodeGroups = computed<NodeGroup[]>(() => {
|
||||
const groups: Array<Omit<NodeGroup, 'label' | 'icon' | 'tone' | 'badge'>> = []
|
||||
for (const task of detail.value?.tasks ?? []) {
|
||||
const last = groups[groups.length - 1]
|
||||
if (last && last.nodeKey === task.nodeKey) {
|
||||
last.tasks.push(task)
|
||||
last.pending = last.pending || task.status === 'pending'
|
||||
continue
|
||||
}
|
||||
groups.push({
|
||||
nodeKey: task.nodeKey,
|
||||
nodeName: task.nodeName,
|
||||
signTypeLabel: task.signTypeLabel,
|
||||
tasks: [task],
|
||||
pending: task.status === 'pending'
|
||||
})
|
||||
}
|
||||
return groups.map((group) => ({
|
||||
...group,
|
||||
label: group.pending ? '办理中' : '已完成',
|
||||
icon: group.pending ? 'clock' : 'check',
|
||||
tone: group.pending
|
||||
? 'bg-warning-100 text-warning-700 dark:bg-warning-900/40 dark:text-warning-300'
|
||||
: 'bg-success-100 text-success-700 dark:bg-success-900/40 dark:text-success-300',
|
||||
badge: group.pending ? 'badge-warning' : 'badge-success'
|
||||
}))
|
||||
})
|
||||
|
||||
const metaItems = computed(() => {
|
||||
const instance = detail.value?.instance
|
||||
if (!instance) return []
|
||||
return [
|
||||
{ label: '当前节点', value: instance.currentNode },
|
||||
{ label: '发起人', value: instance.submitterName },
|
||||
{ label: '提交时间', value: formatDateTime(instance.submittedAt) },
|
||||
{ label: '结束时间', value: formatDateTime(instance.finishedAt) }
|
||||
]
|
||||
})
|
||||
|
||||
const projectLink = computed(() => {
|
||||
const instance = detail.value?.instance
|
||||
if (!instance?.projectId) return ''
|
||||
return `/projects/${instance.projectId}/${instance.businessModule || 'budget'}`
|
||||
})
|
||||
|
||||
function onWithdraw() {
|
||||
withdrawComment.value = ''
|
||||
withdrawOpen.value = true
|
||||
}
|
||||
|
||||
async function doWithdraw() {
|
||||
const instance = detail.value?.instance
|
||||
if (!instance) return
|
||||
const done = await performWithdraw(
|
||||
() => api.approvals.withdraw(instance.id, withdrawComment.value),
|
||||
'已撤回'
|
||||
)
|
||||
if (done) {
|
||||
withdrawOpen.value = false
|
||||
emit('changed')
|
||||
close()
|
||||
}
|
||||
}
|
||||
|
||||
function close() {
|
||||
emit('update:modelValue', false)
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.drawer-enter-active,
|
||||
.drawer-leave-active {
|
||||
transition: opacity 0.18s ease-out;
|
||||
}
|
||||
.drawer-enter-active aside,
|
||||
.drawer-leave-active aside {
|
||||
transition: transform 0.22s cubic-bezier(0.16, 1, 0.3, 1);
|
||||
}
|
||||
.drawer-enter-from,
|
||||
.drawer-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
.drawer-enter-from aside,
|
||||
.drawer-leave-to aside {
|
||||
transform: translateX(24px);
|
||||
}
|
||||
</style>
|
||||
|
|
@ -0,0 +1,116 @@
|
|||
<template>
|
||||
<Teleport to="body">
|
||||
<Transition name="dialog">
|
||||
<div v-if="modelValue" class="fixed inset-0 z-[900] flex items-start justify-center overflow-y-auto p-4 sm:p-6">
|
||||
<div class="fixed inset-0 bg-gray-900/45 backdrop-blur-[2px]" @click="tryClose"></div>
|
||||
<div
|
||||
:class="['relative my-8 w-full rounded-2xl bg-white shadow-xl animate-scale-in dark:bg-dark-800', widthClass]"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-4 border-b border-gray-100 px-5 py-3.5 dark:border-dark-700">
|
||||
<div class="min-w-0">
|
||||
<h3 class="text-sm font-semibold text-gray-900 dark:text-gray-100">{{ title }}</h3>
|
||||
<p v-if="description" class="mt-0.5 text-xs text-gray-500 dark:text-dark-400">{{ description }}</p>
|
||||
</div>
|
||||
<button class="btn btn-ghost btn-icon -mr-1 -mt-1 shrink-0" @click="tryClose">
|
||||
<Icon name="x" size="sm" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div :class="[bodyScroll ? 'max-h-[65vh] overflow-y-auto px-5 py-4' : 'px-5 py-4']">
|
||||
<slot />
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-end gap-2 border-t border-gray-100 px-5 py-3 dark:border-dark-700">
|
||||
<slot name="footer">
|
||||
<button class="btn btn-secondary btn-sm" @click="close">{{ cancelText }}</button>
|
||||
<button
|
||||
class="btn btn-sm"
|
||||
:class="confirmTone === 'danger' ? 'btn-danger' : 'btn-primary'"
|
||||
:disabled="confirming || confirmDisabled"
|
||||
@click="emit('confirm')"
|
||||
>
|
||||
<LoadingSpinner v-if="confirming" size="sm" />
|
||||
{{ confirmText }}
|
||||
</button>
|
||||
</slot>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Transition>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, watch } from 'vue'
|
||||
import Icon from '@/components/icons/Icon.vue'
|
||||
import LoadingSpinner from './LoadingSpinner.vue'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
modelValue: boolean
|
||||
title: string
|
||||
description?: string
|
||||
confirmText?: string
|
||||
cancelText?: string
|
||||
confirmTone?: 'primary' | 'danger'
|
||||
confirming?: boolean
|
||||
confirmDisabled?: boolean
|
||||
bodyScroll?: boolean
|
||||
width?: 'sm' | 'md' | 'lg' | 'xl'
|
||||
closeOnBackdrop?: boolean
|
||||
}>(),
|
||||
{
|
||||
confirmText: '确定',
|
||||
cancelText: '取消',
|
||||
confirmTone: 'primary',
|
||||
confirming: false,
|
||||
confirmDisabled: false,
|
||||
bodyScroll: true,
|
||||
width: 'md',
|
||||
closeOnBackdrop: true
|
||||
}
|
||||
)
|
||||
|
||||
const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'confirm'): void; (e: 'cancel'): void }>()
|
||||
|
||||
const WIDTHS: Record<string, string> = {
|
||||
sm: 'max-w-md',
|
||||
md: 'max-w-xl',
|
||||
lg: 'max-w-3xl',
|
||||
xl: 'max-w-5xl'
|
||||
}
|
||||
const widthClass = WIDTHS[props.width] ?? WIDTHS.md
|
||||
|
||||
function close() {
|
||||
emit('update:modelValue', false)
|
||||
emit('cancel')
|
||||
}
|
||||
function tryClose() {
|
||||
if (props.closeOnBackdrop && !props.confirming) close()
|
||||
}
|
||||
|
||||
function onKey(event: KeyboardEvent) {
|
||||
if (event.key === 'Escape' && props.modelValue && !props.confirming) close()
|
||||
}
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(open) => {
|
||||
if (open) document.addEventListener('keydown', onKey)
|
||||
else document.removeEventListener('keydown', onKey)
|
||||
}
|
||||
)
|
||||
onBeforeUnmount(() => document.removeEventListener('keydown', onKey))
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.dialog-enter-active,
|
||||
.dialog-leave-active {
|
||||
transition: opacity 0.18s ease;
|
||||
}
|
||||
.dialog-enter-from,
|
||||
.dialog-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
</style>
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
<template>
|
||||
<BaseDialog
|
||||
:model-value="modelValue"
|
||||
:title="title"
|
||||
:width="width"
|
||||
:confirm-text="confirmText"
|
||||
:confirm-tone="tone"
|
||||
:confirming="pending"
|
||||
@update:model-value="emit('update:modelValue', $event)"
|
||||
@confirm="emit('confirm')"
|
||||
@cancel="emit('cancel')"
|
||||
>
|
||||
<p class="text-sm leading-relaxed text-gray-700 dark:text-gray-300">{{ message }}</p>
|
||||
<p v-if="hint" class="mt-2 text-xs text-gray-500 dark:text-dark-400">{{ hint }}</p>
|
||||
</BaseDialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import BaseDialog from './BaseDialog.vue'
|
||||
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
modelValue: boolean
|
||||
title: string
|
||||
message: string
|
||||
hint?: string
|
||||
confirmText?: string
|
||||
tone?: 'primary' | 'danger'
|
||||
pending?: boolean
|
||||
width?: 'sm' | 'md' | 'lg' | 'xl'
|
||||
}>(),
|
||||
{ confirmText: '确定', tone: 'primary', pending: false, width: 'sm' }
|
||||
)
|
||||
|
||||
const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'confirm'): void; (e: 'cancel'): void }>()
|
||||
</script>
|
||||
|
|
@ -0,0 +1,167 @@
|
|||
<template>
|
||||
<div class="table-container">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th v-if="selectable" :style="{ width: selectionWidth }" class="text-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
class="h-4 w-4 accent-primary-600"
|
||||
:checked="allOnPage"
|
||||
:indeterminate="someOnPage"
|
||||
:aria-label="allOnPage ? '取消选择本页' : '选择本页'"
|
||||
@change="togglePage"
|
||||
/>
|
||||
</th>
|
||||
<th
|
||||
v-for="col in visibleColumns"
|
||||
:key="col.key"
|
||||
:style="col.width ? { width: col.width } : undefined"
|
||||
:class="[alignClass(col), col.headerClass, col.sticky && 'sticky left-0 z-10']"
|
||||
>
|
||||
{{ col.label }}
|
||||
</th>
|
||||
<th v-if="$slots.actions" :style="{ width: actionsWidth }" class="text-right">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="loading">
|
||||
<td :colspan="totalColumns" class="py-10 text-center text-gray-400">
|
||||
<LoadingSpinner label="加载中" />
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-else-if="!rows.length">
|
||||
<td :colspan="totalColumns" class="p-0">
|
||||
<EmptyState :icon="emptyIcon" :title="emptyTitle" :description="emptyDescription">
|
||||
<slot name="empty-action" />
|
||||
</EmptyState>
|
||||
</td>
|
||||
</tr>
|
||||
<tr
|
||||
v-else
|
||||
v-for="(row, index) in rows"
|
||||
:key="rowKeyOf(row, index)"
|
||||
:class="[rowClassFn?.(row) || '', clickable && 'cursor-pointer']"
|
||||
@click="clickable && emit('row-click', row)"
|
||||
>
|
||||
<td v-if="selectable" class="text-center" @click.stop>
|
||||
<input
|
||||
type="checkbox"
|
||||
class="h-4 w-4 accent-primary-600"
|
||||
:checked="selectedKeys.includes(rowKeyOf(row, index))"
|
||||
:aria-label="`选择第 ${index + 1} 行`"
|
||||
@change="toggleRow(rowKeyOf(row, index))"
|
||||
/>
|
||||
</td>
|
||||
<td
|
||||
v-for="col in visibleColumns"
|
||||
:key="col.key"
|
||||
:class="[alignClass(col), col.numeric && 'num', col.class, col.sticky && 'sticky left-0 bg-white dark:bg-dark-800']"
|
||||
>
|
||||
<slot v-if="slotName(col) && $slots[slotName(col)!]" :name="slotName(col)!" :row="row" :value="value(col, row)" :index="index">
|
||||
{{ value(col, row) }}
|
||||
</slot>
|
||||
<template v-else>{{ display(col, row) }}</template>
|
||||
</td>
|
||||
<td v-if="$slots.actions" class="text-right">
|
||||
<div class="flex items-center justify-end gap-1">
|
||||
<slot name="actions" :row="row" :index="index" />
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
<tfoot v-if="$slots.footer">
|
||||
<slot name="footer" :rows="rows" />
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, useSlots } from 'vue'
|
||||
import EmptyState from './EmptyState.vue'
|
||||
import LoadingSpinner from './LoadingSpinner.vue'
|
||||
import type { Column } from './types'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
columns: Column[]
|
||||
rows: any[]
|
||||
loading?: boolean
|
||||
rowKey?: string
|
||||
rowKeyFn?: (row: any, index: number) => string | number
|
||||
rowClassFn?: (row: any) => string
|
||||
clickable?: boolean
|
||||
/** 勾选列;配合 v-model:selected-keys 用,跨页选择会保留 */
|
||||
selectable?: boolean
|
||||
selectedKeys?: Array<string | number>
|
||||
selectionWidth?: string
|
||||
actionsWidth?: string
|
||||
emptyIcon?: string
|
||||
emptyTitle?: string
|
||||
emptyDescription?: string
|
||||
}>(),
|
||||
{
|
||||
loading: false, rowKey: 'id', clickable: false, selectable: false,
|
||||
selectedKeys: () => [], selectionWidth: '40px', actionsWidth: '120px', emptyTitle: '暂无数据'
|
||||
}
|
||||
)
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'row-click', row: any): void
|
||||
(e: 'update:selectedKeys', keys: Array<string | number>): void
|
||||
}>()
|
||||
const slots = useSlots()
|
||||
|
||||
const visibleColumns = computed(() => props.columns.filter((col) => !col.hidden))
|
||||
const totalColumns = computed(
|
||||
() => visibleColumns.value.length + (slots.actions ? 1 : 0) + (props.selectable ? 1 : 0)
|
||||
)
|
||||
|
||||
/** 勾选只按本页可见行给"全选",选中集合本身跨页保留——按部门挑几十个人不可能一页点完。 */
|
||||
const allOnPage = computed(
|
||||
() => props.rows.length > 0 && props.rows.every((row, index) => props.selectedKeys.includes(rowKeyOf(row, index)))
|
||||
)
|
||||
const someOnPage = computed(
|
||||
() => !allOnPage.value && props.rows.some((row, index) => props.selectedKeys.includes(rowKeyOf(row, index)))
|
||||
)
|
||||
|
||||
function toggleRow(key: string | number) {
|
||||
const next = new Set(props.selectedKeys)
|
||||
if (next.has(key)) next.delete(key)
|
||||
else next.add(key)
|
||||
emit('update:selectedKeys', [...next])
|
||||
}
|
||||
|
||||
function togglePage() {
|
||||
const next = new Set(props.selectedKeys)
|
||||
const keys = props.rows.map((row, index) => rowKeyOf(row, index))
|
||||
if (allOnPage.value) keys.forEach((key) => next.delete(key))
|
||||
else keys.forEach((key) => next.add(key))
|
||||
emit('update:selectedKeys', [...next])
|
||||
}
|
||||
|
||||
function rowKeyOf(row: any, index: number) {
|
||||
return props.rowKeyFn ? props.rowKeyFn(row, index) : row[props.rowKey] ?? index
|
||||
}
|
||||
|
||||
function slotName(col: Column) {
|
||||
return col.slot || `cell:${col.key}`
|
||||
}
|
||||
|
||||
function value(col: Column, row: any) {
|
||||
return col.key.split('.').reduce<any>((acc, key) => (acc == null ? acc : acc[key]), row)
|
||||
}
|
||||
|
||||
function display(col: Column, row: any) {
|
||||
const raw = value(col, row)
|
||||
if (col.formatter) return col.formatter(row, raw)
|
||||
if (raw === null || raw === undefined || raw === '') return '-'
|
||||
return String(raw)
|
||||
}
|
||||
|
||||
function alignClass(col: Column) {
|
||||
if (col.align) return `text-${col.align}`
|
||||
return col.numeric ? 'text-right' : ''
|
||||
}
|
||||
</script>
|
||||
|
|
@ -0,0 +1,59 @@
|
|||
<template>
|
||||
<Select
|
||||
:model-value="modelValue"
|
||||
:options="options"
|
||||
:label="label"
|
||||
:placeholder="placeholder"
|
||||
:disabled="disabled"
|
||||
:required="required"
|
||||
:clearable="clearable"
|
||||
:error="error"
|
||||
:hint="hint"
|
||||
:searchable="searchable"
|
||||
:size="size"
|
||||
:wrapper-class="wrapperClass"
|
||||
@update:model-value="emit('update:modelValue', $event)"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 按字典编码取值的下拉框:`<DictSelect v-model="form.type" dict="projectType" />`。
|
||||
*
|
||||
* 只是 Select 的一层薄壳——取值、名字、排序、启停都由「系统 → 数据字典」说了算,
|
||||
* 页面里不再出现 `{ value: 1, label: '系统集成' }` 这种自己抄的常量。
|
||||
*/
|
||||
import { toValue, type MaybeRefOrGetter } from 'vue'
|
||||
import Select from './Select.vue'
|
||||
import { useDict } from '@/composables/useDict'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
modelValue: string | number | null | undefined
|
||||
dict: MaybeRefOrGetter<string>
|
||||
label?: string
|
||||
placeholder?: string
|
||||
disabled?: boolean
|
||||
required?: boolean
|
||||
clearable?: boolean
|
||||
error?: string
|
||||
hint?: string
|
||||
searchable?: boolean
|
||||
size?: 'sm' | 'md'
|
||||
wrapperClass?: string
|
||||
/** 传文案就在最前面加一项"全部" */
|
||||
all?: string | boolean
|
||||
include?: Array<string | number>
|
||||
exclude?: Array<string | number>
|
||||
}>(),
|
||||
{ clearable: true, size: 'md', wrapperClass: 'w-full', searchable: true }
|
||||
)
|
||||
|
||||
const emit = defineEmits<{ (e: 'update:modelValue', value: string | number | null): void }>()
|
||||
|
||||
const { options } = useDict(() => toValue(props.dict), {
|
||||
all: props.all,
|
||||
include: () => props.include ?? [],
|
||||
exclude: () => props.exclude ?? []
|
||||
})
|
||||
</script>
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
<template>
|
||||
<div class="flex flex-col items-center justify-center gap-2 px-6 py-12 text-center">
|
||||
<div class="flex h-12 w-12 items-center justify-center rounded-full bg-gray-100 text-gray-400 dark:bg-dark-800 dark:text-dark-500">
|
||||
<Icon :name="icon" :size="22" />
|
||||
</div>
|
||||
<p class="text-sm font-medium text-gray-700 dark:text-gray-300">{{ title }}</p>
|
||||
<p v-if="description" class="max-w-sm text-xs text-gray-500 dark:text-dark-400">{{ description }}</p>
|
||||
<div v-if="$slots.default" class="mt-2"><slot /></div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import Icon from '@/components/icons/Icon.vue'
|
||||
withDefaults(defineProps<{ icon?: string; title: string; description?: string }>(), { icon: 'inbox' })
|
||||
</script>
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
<template>
|
||||
<span ref="rootRef" class="relative inline-flex">
|
||||
<button
|
||||
type="button"
|
||||
class="text-gray-400 transition-colors hover:text-primary-600 dark:hover:text-primary-400"
|
||||
@mouseenter="show = true"
|
||||
@mouseleave="show = false"
|
||||
@focus="show = true"
|
||||
@blur="show = false"
|
||||
@click="show = !show"
|
||||
>
|
||||
<Icon name="info" size="xs" />
|
||||
</button>
|
||||
<span
|
||||
v-if="show"
|
||||
class="absolute bottom-full left-1/2 z-50 mb-1.5 w-max max-w-[280px] -translate-x-1/2 rounded-lg bg-gray-900 px-2.5 py-1.5 text-xs font-normal leading-relaxed text-white shadow-lg dark:bg-dark-700"
|
||||
>
|
||||
{{ text }}
|
||||
</span>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import Icon from '@/components/icons/Icon.vue'
|
||||
defineProps<{ text: string }>()
|
||||
const show = ref(false)
|
||||
</script>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue