Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cf082d04e4 |
@@ -0,0 +1,13 @@
|
||||
.git
|
||||
.gitignore
|
||||
.impeccable
|
||||
.venv
|
||||
__pycache__
|
||||
*.py[cod]
|
||||
*.xls
|
||||
*.xlsx
|
||||
screenshots
|
||||
tests
|
||||
docs
|
||||
design-system
|
||||
流水模板
|
||||
@@ -0,0 +1 @@
|
||||
APP_PORT=4173
|
||||
-32
@@ -1,36 +1,4 @@
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.venv/
|
||||
.chrome-libs/
|
||||
.tmp-*/
|
||||
|
||||
# 运行时数据与真实银行文件一律不进仓库(样本仅限流水模板/中已脱敏的六份)
|
||||
data/
|
||||
uploads/
|
||||
exports/
|
||||
*.local
|
||||
deploy/.env
|
||||
server.pid
|
||||
server.out.log
|
||||
server.err.log
|
||||
nul
|
||||
|
||||
# 本地协作工具运行目录
|
||||
.multica/
|
||||
.opencode/
|
||||
.agent_context/
|
||||
.kimi/
|
||||
|
||||
vendor_pkgs/
|
||||
node_modules/
|
||||
package-lock.json
|
||||
|
||||
# local vendor for agent test env (not shipped)
|
||||
.vendor/
|
||||
vendor_wheels/
|
||||
|
||||
# 正式环境部署产物(证书私钥、备份)
|
||||
deploy/tls/certs/
|
||||
backups/
|
||||
ALERT.log
|
||||
backup.log
|
||||
|
||||
+8
-9
@@ -1,8 +1,6 @@
|
||||
# Design Tokens
|
||||
|
||||
**HEL-342 定稿:** 运行时视觉来源是 `web/design-system.css` 的霜曜日间 + 黑金夜间变量(`.v-fusion` / `[data-theme="night"]`),依据 `jinniu-fusion-design`。禁止退回旧青绿 token 或叠第二套覆盖层。主题偏好只存 `localStorage.jinniu-theme`(`day` | `night`),不跟随系统、不恢复业务数据。
|
||||
|
||||
下文是历史暗色合同存档,不再作为施工依据。
|
||||
This file maps the shipped dark visual system to its implementation source in `web/styles.css`. `DESIGN.md` is the portable design contract; the `:root` custom properties in `web/styles.css` are the runtime source of truth.
|
||||
|
||||
## Architecture
|
||||
|
||||
@@ -10,6 +8,7 @@
|
||||
- Keep shared primitives in `:root`; keep component behavior in its existing semantic rule group.
|
||||
- Business-component rules must not use `!important`.
|
||||
- Only accessibility utilities (`.sr-only`, `[hidden]`) and `prefers-reduced-motion` enforcement may force priority.
|
||||
- Do not restore warm-paper, white-card, cobalt-action, cream, or light-theme aliases. New code must consume the dark semantic tokens directly.
|
||||
- Keep administrator and cashier portals as independent route-level surfaces even when they share tokens and component primitives.
|
||||
|
||||
## Typography
|
||||
@@ -27,12 +26,12 @@ Body type is `13px/1.55`. Page headlines use `clamp(26px, 3vw, 35px)` with `1.15
|
||||
|
||||
| Token | Value | Use |
|
||||
| --- | --- | --- |
|
||||
| `--color-bg` | `#050505` | Continuous application canvas |
|
||||
| `--color-bg-soft` | `#0a0a0a` | Soft near-black tonal alternative |
|
||||
| `--color-nav` | `#0a0a0a` | Navigation frame fallback |
|
||||
| `--color-surface` | `rgba(22, 22, 22, 0.82)` | Primary neutral graphite glass |
|
||||
| `--color-surface-solid` | `#161616` | Opaque graphite fallback |
|
||||
| `--color-surface-raised` | `#1c1c1c` | Raised or denser surface |
|
||||
| `--color-bg` | `#050706` | Continuous application canvas |
|
||||
| `--color-bg-soft` | `#090d0b` | Soft near-black tonal alternative |
|
||||
| `--color-nav` | `#090c0b` | Navigation frame fallback |
|
||||
| `--color-surface` | `rgba(20, 26, 23, 0.82)` | Primary graphite glass |
|
||||
| `--color-surface-solid` | `#131916` | Opaque graphite fallback |
|
||||
| `--color-surface-raised` | `#18201c` | Raised or denser surface |
|
||||
| `--color-surface-muted` | `rgba(255, 255, 255, 0.035)` | Quiet inset field and row treatment |
|
||||
|
||||
### Structure and Ink
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
FROM python:3.12-slim
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
PYTHONPATH=/app/src \
|
||||
APP_HOST=0.0.0.0 \
|
||||
APP_PORT=4173
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN addgroup --system app && adduser --system --ingroup app app
|
||||
|
||||
COPY requirements.txt ./
|
||||
RUN python -m pip install --no-cache-dir --requirement requirements.txt
|
||||
|
||||
COPY server.py ./
|
||||
COPY src ./src
|
||||
COPY web ./web
|
||||
|
||||
USER app
|
||||
|
||||
EXPOSE 4173
|
||||
|
||||
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=5 \
|
||||
CMD ["python", "-c", "import os, urllib.request; port = os.getenv('APP_PORT', '4173'); urllib.request.urlopen(f'http://127.0.0.1:{port}/', timeout=2)"]
|
||||
|
||||
CMD ["python", "server.py"]
|
||||
@@ -19,46 +19,36 @@ The original Excel file is never modified.
|
||||
```powershell
|
||||
python -m pip install -r requirements.txt
|
||||
$env:PYTHONPATH = "src"
|
||||
python -m bank_importer.db # 创建/迁移 SQLite 数据库(默认 data/app.db)
|
||||
python -m bank_importer.cli "流水模板"
|
||||
python -m unittest discover -s tests -v
|
||||
python server.py
|
||||
```
|
||||
|
||||
数据库与原始文件默认保存在 `data/`(已加入 `.gitignore`)。上传文件按
|
||||
SHA-256 内容哈希不可变保存,重复上传返回 `duplicate` 状态并复用已有批次。
|
||||
同一公司重复上传返回原批次摘要;不同公司相同内容只返回通用重复状态,
|
||||
不暴露其他公司的批次标识或摘要。
|
||||
技术决策见 `docs/decisions/002-persistence.md`。
|
||||
## Docker 部署
|
||||
|
||||
## 登录与账号
|
||||
Windows PowerShell 一键启动:
|
||||
|
||||
系统已启用真实身份认证(决策见 `docs/decisions/003-auth.md`):
|
||||
```powershell
|
||||
.\start-docker.ps1
|
||||
```
|
||||
|
||||
- 首次启动若无管理员,自动创建引导管理员:用户名取环境变量
|
||||
`APP_ADMIN_USERNAME`(默认 `group-admin`),密码取
|
||||
`APP_BOOTSTRAP_ADMIN_PASSWORD`;未设置该变量则生成随机初始密码并
|
||||
只在控制台打印一次。
|
||||
- 引导管理员及管理员创建的公司账号首次登录都必须修改密码。
|
||||
- 公司、公司账号由管理员在总账端「公司与账号 → 新增公司」或
|
||||
`/api/admin/companies`、`/api/admin/users` 动态创建;
|
||||
公司账号创建时生成随机一次性初始密码,只在创建响应中显示一次,
|
||||
首次登录强制改密(「重置密码」同样生成随机一次性密码并吊销会话)。
|
||||
- 会话有效期 8 小时;同一账号同一 IP 10 分钟内登录失败 5 次将被限流。
|
||||
内网测试环境可设 `APP_LOGIN_RATE_LIMIT_DISABLED=1` 暂时关闭该锁定
|
||||
(默认未设置 = 保持限流,正式环境不得开启该变量)。
|
||||
Linux 或 macOS 一键启动:
|
||||
|
||||
访问地址(服务默认监听 `0.0.0.0:4173`,同局域网设备把 `127.0.0.1` 换成本机局域网 IP 即可访问;可用环境变量 `APP_HOST` / `APP_PORT` 覆盖):
|
||||
```sh
|
||||
./start-docker.sh
|
||||
```
|
||||
|
||||
默认访问 `http://localhost:4173/`。如需更换宿主机端口,可运行
|
||||
`.\start-docker.ps1 -Port 8080`,或运行 `APP_PORT=8080 ./start-docker.sh`。
|
||||
停止服务使用 `docker compose down`,查看日志使用 `docker compose logs -f app`。
|
||||
|
||||
访问地址:
|
||||
|
||||
- 登录入口:`http://127.0.0.1:4173/`
|
||||
- 总账管理端:`http://127.0.0.1:4173/admin.html`
|
||||
- 公司业务端:`http://127.0.0.1:4173/company.html`
|
||||
|
||||
公司端上传会把所选工作簿提交到本地 `/api/parse`,与 CLI 使用同一个确定性表头解析器;解析结果、原始文件、批次和源行会持久化到 SQLite,并按登录账号绑定的公司隔离。流水列表、往来查询、手工记录、月结与重开均走服务端接口;银行原始数据不可改,已确认与待确认金额分开计算。测试环境编排见 `deploy/`(默认 4173)。
|
||||
|
||||
## 样本数据政策
|
||||
|
||||
`流水模板/` 中的六份银行样本(中信、农行、工行、建行、河南农商、郑州银行)已经项目所有者(白栖知,2026-08-08)书面确认:**基于真实银行流水脱敏后的测试数据**,可以保留在仓库中作为解析器 fixture。新增银行样本的审核要求:必须先脱敏(户名、账号、对方信息等),由项目所有者确认后方可提交;真实生产流水、真实上传文件和导出文件一律不进仓库(见 `.gitignore` 中的 `data/`、`uploads/`、`exports/` 规则)。
|
||||
公司端上传会把所选工作簿提交到本地 `/api/parse`,与 CLI 使用同一个确定性表头解析器。当前前端是交互原型,公司、账号、期初、提醒和导入确认仅保存在当前浏览器页面中,尚未接入数据库和正式身份认证。
|
||||
|
||||
The CLI prints batch summaries only. It does not print sensitive transaction
|
||||
details.
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
services:
|
||||
app:
|
||||
build:
|
||||
context: .
|
||||
image: caiwuzongzhang:local
|
||||
ports:
|
||||
- "${APP_PORT:-4173}:4173"
|
||||
environment:
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: 4173
|
||||
init: true
|
||||
restart: unless-stopped
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp:size=64m,mode=1777
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
@@ -1,31 +0,0 @@
|
||||
# 测试环境变量示例。复制为 deploy/.env 后填写。
|
||||
# 正式环境口令不得提交进仓库。
|
||||
|
||||
# 容器运行 uid/gid:必须与 data/ 目录属主一致(宿主机 `id <用户>` 查看)
|
||||
APP_UID=10001
|
||||
APP_GID=10001
|
||||
|
||||
APP_HOST=0.0.0.0
|
||||
APP_PORT=4173
|
||||
APP_DB_PATH=/app/data/app.db
|
||||
APP_STORAGE_DIR=/app/data/files
|
||||
|
||||
# 引导管理员(库中尚无管理员时生效)
|
||||
APP_ADMIN_USERNAME=group-admin
|
||||
APP_BOOTSTRAP_ADMIN_PASSWORD=change-me-in-local-env
|
||||
|
||||
# 内网测试可暂时关闭登录失败锁定;正式环境不得开启
|
||||
# APP_LOGIN_RATE_LIMIT_DISABLED=1
|
||||
|
||||
# ---- 同宿主机第二套环境(正式)必须设置的隔离参数 ----
|
||||
# compose 项目名(默认 deploy;正式环境改为 caiwuzongzhang-prod)
|
||||
# COMPOSE_PROJECT_NAME=caiwuzongzhang-prod
|
||||
# 应用容器名与宿主机端口映射(正式默认只绑本机回环,由反代对外)
|
||||
# APP_CONTAINER_NAME=caiwuzongzhang-prod-app
|
||||
# APP_PORT_MAP=127.0.0.1:4174:4173
|
||||
|
||||
# ---- 正式 HTTPS 反代(COMPOSE_PROFILES=tls 启用 proxy 服务)----
|
||||
# COMPOSE_PROFILES=tls
|
||||
# PROXY_CONTAINER_NAME=caiwuzongzhang-proxy
|
||||
# PROXY_PORT_MAP=8443:8443
|
||||
# 首次启用前先执行 ./tls/gen-cert.sh 生成证书
|
||||
@@ -1,32 +0,0 @@
|
||||
FROM python:3.12-slim-bookworm
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
PYTHONPATH=/app/src \
|
||||
APP_HOST=0.0.0.0 \
|
||||
APP_PORT=4173 \
|
||||
APP_DB_PATH=/app/data/app.db \
|
||||
APP_STORAGE_DIR=/app/data/files
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN groupadd --system --gid 10001 app \
|
||||
&& useradd --system --uid 10001 --gid app --home-dir /app --shell /usr/sbin/nologin app \
|
||||
&& mkdir -p /app/data \
|
||||
&& chown -R app:app /app
|
||||
|
||||
COPY --chown=app:app requirements.txt ./
|
||||
RUN python -m pip install --no-cache-dir --requirement requirements.txt
|
||||
|
||||
COPY --chown=app:app server.py ./
|
||||
COPY --chown=app:app src ./src
|
||||
COPY --chown=app:app web ./web
|
||||
|
||||
USER app
|
||||
|
||||
EXPOSE 4173
|
||||
|
||||
HEALTHCHECK --interval=15s --timeout=3s --start-period=10s --retries=5 \
|
||||
CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:4173/', timeout=2)"]
|
||||
|
||||
CMD ["python", "server.py"]
|
||||
@@ -1,126 +0,0 @@
|
||||
# 部署与运维手册(与 `release/prod` 基线一致)
|
||||
|
||||
最后核对:2026-08-30,总工 HEL-270 上线前总验收。本手册是测试与正式环境唯一的部署/回滚/备份/巡检操作依据,取代散落在宿主机 `DEPLOYMENT.txt` 里的历史记录(旧记录仅作存档)。
|
||||
|
||||
## 1. 物料与目录
|
||||
|
||||
| 物料 | 说明 |
|
||||
|---|---|
|
||||
| `deploy/Dockerfile` | python:3.12-slim-bookworm,非 root(uid 10001 `app`),只读根文件系统 |
|
||||
| `deploy/compose.yaml` | cap_drop ALL、no-new-privileges、pids 128、mem 512m、cpu 1.0、healthcheck |
|
||||
| `deploy/.env.example` | 配置模板;`deploy/.env` 已 gitignore,口令永不入库 |
|
||||
| `deploy/deploy.sh` | `TAG=<tag> ./deploy.sh`,默认镜像 tag=当前提交 sha |
|
||||
| `deploy/rollback.sh` | `./rollback.sh <tag>`,只换应用不动数据 |
|
||||
| `deploy/backup.sh` | 在线热备 + 保留策略(30 天日备 + 12 个月月备) |
|
||||
| `deploy/monitor.sh` | 每 5 分钟健康 + 磁盘 ≥80% 告警,写 `ALERT.log` |
|
||||
|
||||
数据目录:`deploy/../data/`(`app.db` + `files/`)。银行原始文件按 SHA-256 内容哈希不可变保存,任何操作不得改写。
|
||||
|
||||
## 2. 正式配置铁律
|
||||
|
||||
- **不得出现 `admin/admin123`**:`APP_BOOTSTRAP_ADMIN_PASSWORD` 正式环境不设值,首启由控制台读取随机生成的一次性初始口令,首登立即改密;管理员用户名避开 `admin`。
|
||||
- **登录失败限流默认开启**(5 次/10 分钟锁账号+IP)。`APP_LOGIN_RATE_LIMIT_DISABLED=1` 仅限本地调试,正式 .env 不得携带。
|
||||
- 密钥/口令/证书私钥不进仓库、不进评论、不进任务元数据。
|
||||
- **HTTPS**:正式暴露一律经反向代理(推荐同机 Caddy 容器,内网自签或内部 CA 证书,反代到容器 4173);不占用 NAS 系统 nginx 的 80/443。公司电脑分发根证书即可。
|
||||
- **日志**:容器 stdout 走 docker json-file,限幅 `max-size=10m, max-file=3`(daemon 或 compose `logging` 配置);审计日志在库内(append-only 触发器保护)。
|
||||
|
||||
## 3. 部署步骤(测试与正式一致)
|
||||
|
||||
```bash
|
||||
git fetch && git checkout release/prod && git pull
|
||||
cd deploy
|
||||
cp .env.example .env # 首次;按上面铁律填写
|
||||
# .env 必设 APP_UID/APP_GID = data/ 目录属主的 uid/gid(宿主机 `id <用户>`),
|
||||
# 否则 SQLite WAL 写库报 readonly
|
||||
TAG=$(git rev-parse --short HEAD) ./deploy.sh
|
||||
curl -fsS http://127.0.0.1:4173/ >/dev/null && echo healthy
|
||||
```
|
||||
|
||||
部署前手工备份(四件套 + 镜像 tag 存档):
|
||||
|
||||
```bash
|
||||
STAMP=$(date +%Y%m%d-%H%M%S)
|
||||
tar -C .. -czf ../backups/source-$STAMP.tar.gz --exclude='../data' --exclude='../.git' .
|
||||
cp .env ../backups/env-$STAMP
|
||||
docker exec caiwuzongzhang-app python -c "import sqlite3; s=sqlite3.connect('/app/data/app.db'); d=sqlite3.connect('/tmp/b.db'); s.backup(d); d.close(); s.close()"
|
||||
docker cp caiwuzongzhang-app:/tmp/b.db ../backups/app.db.$STAMP
|
||||
```
|
||||
|
||||
## 3.1 正式环境部署(同宿主机隔离,2026-08-30 首次上线采用)
|
||||
|
||||
测试与正式同宿主机并行,靠 compose 项目名/容器名/端口三隔离:
|
||||
|
||||
| 项 | 测试环境 | 正式环境 |
|
||||
|---|---|---|
|
||||
| 目录 | `/home/leefer/caiwuzongzhang-test` | `/home/leefer/caiwuzongzhang-prod` |
|
||||
| compose 项目 | `deploy`(默认) | `COMPOSE_PROJECT_NAME=caiwuzongzhang-prod` |
|
||||
| 应用容器 | `caiwuzongzhang-app` | `caiwuzongzhang-prod-app` |
|
||||
| 端口 | `4173`(对外) | `127.0.0.1:4174`(仅本机,反代上游) |
|
||||
| HTTPS | 无 | nginx 反代 `8443`(`COMPOSE_PROFILES=tls`) |
|
||||
| 访问 | http://192.168.200.36:4173/ | https://192.168.200.36:8443/ |
|
||||
|
||||
首次部署顺序:
|
||||
|
||||
```bash
|
||||
git clone <repo> /home/leefer/caiwuzongzhang-prod && cd /home/leefer/caiwuzongzhang-prod
|
||||
git checkout release/prod
|
||||
mkdir -p data/files backups && chown -R 10001:10001 data # 容器内 app uid
|
||||
cd deploy
|
||||
cp .env.example .env # 按下述差异填写
|
||||
./tls/gen-cert.sh # 生成内部 CA + 服务器证书(SAN 含对外 IP)
|
||||
TAG=<发布镜像tag> docker compose up -d # 不带 --build,直接用已验收镜像
|
||||
docker logs <应用容器> 2>&1 | grep "shown once" # 首启一次性初始口令,只出现一次
|
||||
```
|
||||
|
||||
正式 `.env` 与测试的差异(铁律):
|
||||
|
||||
- `COMPOSE_PROJECT_NAME=caiwuzongzhang-prod`、`APP_CONTAINER_NAME=caiwuzongzhang-prod-app`、`APP_PORT_MAP=127.0.0.1:4174:4173`
|
||||
- `COMPOSE_PROFILES=tls`、`PROXY_CONTAINER_NAME=caiwuzongzhang-proxy`、`PROXY_PORT_MAP=8443:8443`
|
||||
- `APP_UID=10001` / `APP_GID=10001`(data/ 已 chown 10001)
|
||||
- 管理员用户名自定(如 `jinniu-admin`);**不设** `APP_BOOTSTRAP_ADMIN_PASSWORD`(首启控制台取随机一次性口令,首登立即改密)
|
||||
- **不设** `APP_LOGIN_RATE_LIMIT_DISABLED`(限流默认开启)
|
||||
|
||||
证书与信任分发:
|
||||
|
||||
- `tls/certs/ca.crt` 发给各公司电脑安装到「受信任的根证书颁发机构」(安装指引见交接文档);`ca.key`/`server.key` 永不离开宿主机。
|
||||
- 服务器证书有效期 5 年,到期前用 `./tls/gen-cert.sh` 重签并 `docker compose restart proxy`。
|
||||
|
||||
## 4. 回滚(应用层,5 分钟内)
|
||||
|
||||
```bash
|
||||
cd deploy && ./rollback.sh <上一个镜像tag>
|
||||
```
|
||||
|
||||
数据层恢复见下节。两套动作互不干扰:应用回滚不改数据;数据恢复不换镜像。
|
||||
|
||||
## 5. 备份与恢复演练
|
||||
|
||||
- 备份:cron `15 2 * * *` 运行 `deploy/backup.sh`;月结后再手动跑一次。
|
||||
- 恢复步骤(已演练,隔离环境验证):
|
||||
1. `mkdir -p /tmp/restore/data && cp backups/daily/app.db.<stamp> /tmp/restore/data/app.db`
|
||||
2. `tar -C /tmp/restore/data -xzf backups/daily/files.<stamp>.tar.gz`(解出 `files/`)
|
||||
3. 用一份独立 `deploy-restore` 目录(`.env` 指向 `/tmp/restore`、端口错开)`docker compose up -d --build`
|
||||
4. 核对:`PRAGMA integrity_check`、各表行数、金额合计、`source_files` 哈希清单与生产一致后才可顶替。
|
||||
- 演练频率:上线前 1 次(HEL-270 已做),之后每季度 1 次,结果记入本文件末尾。
|
||||
|
||||
## 6. 巡检与告警
|
||||
|
||||
cron `*/5 * * * *` 运行 `deploy/monitor.sh`;连续失败或磁盘 ≥80% 时查看 `deploy/ALERT.log` 并按需扩容/清理。容器重启策略 `unless-stopped`。
|
||||
|
||||
宿主机 crontab(leefer,2026-08-30 起,正式环境):
|
||||
|
||||
```cron
|
||||
15 2 * * * cd /home/leefer/caiwuzongzhang-prod/deploy && CONTAINER=caiwuzongzhang-prod-app ./backup.sh >> backup.log 2>&1
|
||||
*/5 * * * * cd /home/leefer/caiwuzongzhang-prod/deploy && CONTAINER=caiwuzongzhang-prod-app HEALTH_URL=http://127.0.0.1:4174/ ./monitor.sh >/dev/null 2>&1
|
||||
01 3 1 * * rsync -a /home/leefer/caiwuzongzhang-prod/backups/monthly/ /vol1/caiwuzongzhang-backups/monthly/
|
||||
```
|
||||
|
||||
(第三行为月度异盘副本:`/vol1` 是与系统盘不同的物理卷;如后续提供真正的异机目标,改为该目标。)
|
||||
|
||||
## 7. 升级数据库
|
||||
|
||||
应用启动时自动执行迁移(`MIGRATIONS`,当前版本 10)。迁移只前不改写历史;回退 schema 用对应 down 迁移,先备份后操作。
|
||||
|
||||
## 8. 演练记录
|
||||
|
||||
- 2026-08-30 HEL-270:备份恢复演练 + 版本回滚演练各 1 次,隔离环境完成,原始证据未改动。详见 HEL-270 验收评论。
|
||||
@@ -1,53 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# 在线热备:不停服备份 SQLite(backup API 保证一致性)+ files/ 原始文件目录。
|
||||
# 用法:./backup.sh [备份根目录](默认 ../backups)
|
||||
# 保留策略:日备保留 30 天,每月 1 号的首份备份额外保留 12 个月(monthly/)。
|
||||
# 建议宿主机 cron:15 2 * * * /path/to/deploy/backup.sh >> /path/to/deploy/backup.log 2>&1
|
||||
# 官方环境建议至少将 monthly/ 同步一份到异机/异盘。
|
||||
set -euo pipefail
|
||||
ROOT="$(cd "$(dirname "$0")" && pwd)"
|
||||
DEST="${1:-$ROOT/../backups}"
|
||||
CONTAINER="${CONTAINER:-caiwuzongzhang-app}"
|
||||
STAMP="$(date +%Y%m%d-%H%M%S)"
|
||||
DAY_DIR="$DEST/daily"
|
||||
MONTH_DIR="$DEST/monthly"
|
||||
mkdir -p "$DAY_DIR" "$MONTH_DIR"
|
||||
|
||||
# 1) SQLite 在线热备(容器内 python sqlite3 backup API,主库可继续写入)
|
||||
# 备份文件写进数据卷 /app/data(宿主机 deploy/../data 可直接读取),避免
|
||||
# read_only 容器 + tmpfs 下 docker cp 取不到文件的问题。
|
||||
docker exec -i "$CONTAINER" python - <<'PY'
|
||||
import os, sqlite3
|
||||
src = sqlite3.connect(os.environ.get("APP_DB_PATH", "/app/data/app.db"))
|
||||
dst = sqlite3.connect("/app/data/.backup-tmp.db")
|
||||
src.backup(dst)
|
||||
dst.close(); src.close()
|
||||
print("hot-backup ok")
|
||||
PY
|
||||
mv "$ROOT/../data/.backup-tmp.db" "$DAY_DIR/app.db.$STAMP"
|
||||
|
||||
# 2) 原始文件目录打包(银行原始证据,只读复制,绝不改动)
|
||||
tar -C "$ROOT/.." -czf "$DAY_DIR/files.$STAMP.tar.gz" data/files
|
||||
|
||||
# 3) 完整性自检:PRAGMA integrity_check + 关键计数
|
||||
docker run --rm -v "$DAY_DIR/app.db.$STAMP:/check/app.db:ro" python:3.12-slim-bookworm \
|
||||
python -c "
|
||||
import sqlite3
|
||||
c = sqlite3.connect('/check/app.db')
|
||||
print('integrity:', c.execute('PRAGMA integrity_check').fetchone()[0])
|
||||
for t in ('source_rows', 'transfer_match_decisions', 'period_close_runs', 'audit_log'):
|
||||
try:
|
||||
print(t, c.execute(f'SELECT COUNT(*) FROM {t}').fetchone()[0])
|
||||
except sqlite3.OperationalError:
|
||||
print(t, 'n/a')
|
||||
"
|
||||
|
||||
# 4) 保留策略:日备 >30 天删除;每月 1 号留档 monthly/
|
||||
find "$DAY_DIR" -name 'app.db.*' -mtime +30 -delete
|
||||
find "$DAY_DIR" -name 'files.*.tar.gz' -mtime +30 -delete
|
||||
if [ "$(date +%d)" = "01" ]; then
|
||||
cp "$DAY_DIR/app.db.$STAMP" "$MONTH_DIR/app.db.$STAMP"
|
||||
cp "$DAY_DIR/files.$STAMP.tar.gz" "$MONTH_DIR/files.$STAMP.tar.gz"
|
||||
find "$MONTH_DIR" -mtime +365 -delete
|
||||
fi
|
||||
echo "backup complete: $DAY_DIR/app.db.$STAMP"
|
||||
@@ -1,91 +0,0 @@
|
||||
# 测试/正式环境部署编排(正式口令不得写入本文件)。
|
||||
# 使用:复制 .env.example 为 .env 填写;TAG 指定镜像标签(默认取当前提交 sha)。
|
||||
# 例:TAG=v1.0.0-rc1 docker compose -f compose.yaml up -d --build
|
||||
#
|
||||
# 同宿主机多套环境(测试 + 正式)必须各自设置:
|
||||
# COMPOSE_PROJECT_NAME / APP_CONTAINER_NAME / APP_PORT_MAP 互不相同。
|
||||
# 正式环境启用 HTTPS 反代:.env 中设 COMPOSE_PROFILES=tls(先跑 tls/gen-cert.sh)。
|
||||
|
||||
name: ${COMPOSE_PROJECT_NAME:-deploy}
|
||||
|
||||
services:
|
||||
app:
|
||||
container_name: ${APP_CONTAINER_NAME:-caiwuzongzhang-app}
|
||||
image: caiwuzongzhang:${TAG:-latest}
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: deploy/Dockerfile
|
||||
env_file:
|
||||
- .env
|
||||
# 绑定挂载 data/ 时,容器运行 uid 必须与数据目录属主一致(.env 里设
|
||||
# APP_UID/APP_GID,正式与测试环境各自填写,默认镜像内 app=10001)
|
||||
user: "${APP_UID:-10001}:${APP_GID:-10001}"
|
||||
ports:
|
||||
- "${APP_PORT_MAP:-4173:4173}"
|
||||
volumes:
|
||||
- ../data:/app/data
|
||||
init: true
|
||||
restart: unless-stopped
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp:size=64m,mode=1777
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
cap_drop:
|
||||
- ALL
|
||||
pids_limit: 128
|
||||
mem_limit: 512m
|
||||
cpus: 1.0
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:4173/', timeout=2)"]
|
||||
interval: 15s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
start_period: 10s
|
||||
|
||||
# 可选 HTTPS 反向代理(正式环境用):COMPOSE_PROFILES=tls 启用。
|
||||
# 证书由 tls/gen-cert.sh 生成的内部 CA 签发(内网自受管信任),公司电脑
|
||||
# 安装 tls/certs/ca.crt 一次即可无告警访问。
|
||||
proxy:
|
||||
container_name: ${PROXY_CONTAINER_NAME:-caiwuzongzhang-proxy}
|
||||
image: nginx:1.27-alpine
|
||||
profiles: ["tls"]
|
||||
ports:
|
||||
- "${PROXY_PORT_MAP:-8443:8443}"
|
||||
volumes:
|
||||
- ./tls/nginx.conf:/etc/nginx/conf.d/default.conf:ro
|
||||
- ./tls/certs/server.crt:/etc/nginx/tls/server.crt:ro
|
||||
- ./tls/certs/server.key:/etc/nginx/tls/server.key:ro
|
||||
# 与证书文件属主一致的 uid/gid(默认 101=镜像 nginx 用户;宿主机生成证书时
|
||||
# 设为属主 uid/gid,保持 server.key 0600 不放宽)
|
||||
user: "${PROXY_UID:-101}:${PROXY_GID:-101}"
|
||||
depends_on:
|
||||
- app
|
||||
restart: unless-stopped
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /var/cache/nginx:size=16m,uid=${PROXY_UID:-101},gid=${PROXY_GID:-101},mode=700
|
||||
- /var/run:size=1m,uid=${PROXY_UID:-101},gid=${PROXY_GID:-101},mode=700
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
cap_drop:
|
||||
- ALL
|
||||
pids_limit: 64
|
||||
mem_limit: 64m
|
||||
cpus: 0.5
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "--no-check-certificate", "-O", "/dev/null", "https://127.0.0.1:8443/"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 10s
|
||||
@@ -1,17 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# 部署(测试或正式环境通用)。施工员不执行上线;由总工运行。
|
||||
# 用法:TAG=<镜像标签,默认当前 git 提交 sha> ./deploy.sh
|
||||
set -euo pipefail
|
||||
ROOT="$(cd "$(dirname "$0")" && pwd)"
|
||||
cd "$ROOT/.."
|
||||
if [[ ! -f deploy/.env ]]; then
|
||||
echo "缺少 deploy/.env。请复制 deploy/.env.example 后填写(正式口令不得入库)。" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ -z "${TAG:-}" ]]; then
|
||||
TAG="$(git rev-parse --short HEAD 2>/dev/null || echo latest)"
|
||||
fi
|
||||
mkdir -p data/files
|
||||
cd "$ROOT"
|
||||
TAG="$TAG" docker compose -f compose.yaml up -d --build
|
||||
echo "已启动:http://127.0.0.1:${APP_PORT:-4173}/ 镜像 caiwuzongzhang:$TAG"
|
||||
@@ -1,32 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# 巡检:健康端点 + 磁盘水位告警。失败/越线写 ALERT.log(供总管日检)。
|
||||
# 建议 cron:*/5 * * * * /path/to/deploy/monitor.sh >/dev/null 2>&1
|
||||
set -euo pipefail
|
||||
ROOT="$(cd "$(dirname "$0")" && pwd)"
|
||||
URL="${HEALTH_URL:-http://127.0.0.1:4173/}"
|
||||
DATA_DIR="${DATA_DIR:-$ROOT/../data}"
|
||||
ALERT="$ROOT/ALERT.log"
|
||||
DISK_THRESHOLD="${DISK_THRESHOLD:-80}"
|
||||
|
||||
now() { date "+%Y-%m-%d %H:%M:%S"; }
|
||||
|
||||
# 1) 健康检查:HTTP 200 才算通过
|
||||
if ! curl -fsS -m 8 -o /dev/null "$URL"; then
|
||||
echo "[$(now)] HEALTH FAIL: $URL 无响应" >> "$ALERT"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 2) 磁盘水位:数据所在分区使用率超阈值告警
|
||||
pct="$(df -P "$DATA_DIR" | awk 'NR==2 {gsub("%",""); print $5}')"
|
||||
if [ "${pct:-0}" -ge "$DISK_THRESHOLD" ]; then
|
||||
echo "[$(now)] DISK ALERT: $DATA_DIR 使用率 ${pct}% >= ${DISK_THRESHOLD}%" >> "$ALERT"
|
||||
exit 2
|
||||
fi
|
||||
|
||||
# 3) 容器状态:非 running/restarting 告警
|
||||
state="$(docker inspect -f '{{.State.Status}}' "${CONTAINER:-caiwuzongzhang-app}" 2>/dev/null || echo missing)"
|
||||
if [ "$state" != "running" ]; then
|
||||
echo "[$(now)] CONTAINER ALERT: ${CONTAINER:-caiwuzongzhang-app} state=$state" >> "$ALERT"
|
||||
exit 3
|
||||
fi
|
||||
echo "[$(now)] ok"
|
||||
@@ -1,27 +0,0 @@
|
||||
# Optional overlay for a separately approved, fresh finance integration instance.
|
||||
# Never point FINANCE_DATA at the standalone server's real database.
|
||||
services:
|
||||
backend:
|
||||
environment:
|
||||
FINANCE_SSO_ENABLED: "true"
|
||||
FINANCE_SSO_SECRET: ${FINANCE_SSO_SECRET}
|
||||
FINANCE_SSO_CALLBACK_URL: ${FINANCE_PUBLIC_URL}/portal-sso
|
||||
finance:
|
||||
image: ${FINANCE_IMAGE}
|
||||
container_name: jinniu-finance-portal-integration
|
||||
ports: ["${TEST_HOST}:18124:4173"]
|
||||
environment:
|
||||
PORTAL_SSO_ENABLED: "1"
|
||||
PORTAL_SSO_SECRET: ${FINANCE_SSO_SECRET}
|
||||
PORTAL_INTERNAL_URL: http://backend:8000
|
||||
PORTAL_PUBLIC_URL: http://${TEST_HOST}:18091
|
||||
APP_DB_PATH: /app/data/app.db
|
||||
APP_STORAGE_DIR: /app/data/files
|
||||
volumes:
|
||||
- ${FINANCE_SOURCE}/server.py:/app/server.py:ro
|
||||
- ${FINANCE_SOURCE}/src:/app/src:ro
|
||||
- ${FINANCE_SOURCE}/web:/app/web:ro
|
||||
- ${FINANCE_DATA}:/app/data
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:4173/healthz',timeout=3)"]
|
||||
depends_on: [backend]
|
||||
@@ -1,19 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# 回滚:回到指定镜像标签(或最近一次可用镜像)。
|
||||
# 用法:./rollback.sh <tag> 例:./rollback.sh f5e0915
|
||||
# 数据库与 files/ 原始证据不受影响;如需回退数据,见 deploy/README.md「数据恢复」。
|
||||
set -euo pipefail
|
||||
ROOT="$(cd "$(dirname "$0")" && pwd)"
|
||||
cd "$ROOT"
|
||||
TAG="${1:-}"
|
||||
if [[ -z "$TAG" ]]; then
|
||||
echo "用法:./rollback.sh <镜像tag>(可用 tag 见 docker images caiwuzongzhang)" >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! docker image inspect "caiwuzongzhang:$TAG" >/dev/null 2>&1; then
|
||||
echo "镜像 caiwuzongzhang:$TAG 不存在。" >&2
|
||||
exit 1
|
||||
fi
|
||||
TAG="$TAG" docker compose -f compose.yaml down
|
||||
TAG="$TAG" docker compose -f compose.yaml up -d
|
||||
echo "已回滚到 caiwuzongzhang:$TAG"
|
||||
@@ -1,45 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# 生成内网专用 CA 与服务器证书(自受管内部信任,不涉及公网域名)。
|
||||
# 用法:在正式环境 deploy/ 目录执行 ./tls/gen-cert.sh
|
||||
# 可用环境变量覆盖:
|
||||
# CERT_IP 对外访问 IP(默认 192.168.200.36)
|
||||
# CERT_DNS 额外 DNS 名称(空格分隔,默认 caiwuzongzhang.jinniu.internal)
|
||||
# 输出:tls/certs/{ca.crt,ca.key,server.crt,server.key}(key 永不入库、不分发)
|
||||
# 分发:仅把 ca.crt 发给公司电脑安装(受信任的根证书颁发机构)。
|
||||
set -euo pipefail
|
||||
ROOT="$(cd "$(dirname "$0")" && pwd)"
|
||||
CERTS="$ROOT/certs"
|
||||
mkdir -p "$CERTS"
|
||||
cd "$CERTS"
|
||||
|
||||
CERT_IP="${CERT_IP:-192.168.200.36}"
|
||||
CERT_DNS="${CERT_DNS:-caiwuzongzhang.jinniu.internal}"
|
||||
|
||||
SAN="IP:${CERT_IP}"
|
||||
for d in $CERT_DNS; do SAN="$SAN,DNS:$d"; done
|
||||
|
||||
if [[ ! -f ca.key ]]; then
|
||||
# 内部根 CA:10 年,仅本系统使用
|
||||
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 \
|
||||
-keyout ca.key -out ca.crt -days 3650 -nodes -subj "/CN=Jinniu Ledger Internal CA" \
|
||||
-addext "basicConstraints=critical,CA:TRUE" \
|
||||
-addext "keyUsage=critical,keyCertSign,cRLSign"
|
||||
chmod 600 ca.key
|
||||
echo "ca 已生成"
|
||||
fi
|
||||
|
||||
openssl req -newkey ec -pkeyopt ec_paramgen_curve:P-256 \
|
||||
-keyout server.key -out server.csr -nodes \
|
||||
-subj "/CN=${CERT_DNS%% *}" >/dev/null 2>&1
|
||||
cat > server.ext <<EXT
|
||||
subjectAltName=${SAN}
|
||||
basicConstraints=CA:FALSE
|
||||
keyUsage=digitalSignature,keyEncipherment
|
||||
extendedKeyUsage=serverAuth
|
||||
EXT
|
||||
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
|
||||
-out server.crt -days 1825 -sha256 -extfile server.ext >/dev/null 2>&1
|
||||
chmod 600 server.key
|
||||
rm -f server.csr server.ext ca.srl
|
||||
echo "server 证书已生成(SAN: ${SAN}),有效期 5 年"
|
||||
echo "分发文件:${CERTS}/ca.crt(其余文件不得离开本机)"
|
||||
@@ -1,31 +0,0 @@
|
||||
# 正式环境 HTTPS 反代(nginx)。证书挂载自 deploy/tls/certs/(gen-cert.sh 生成)。
|
||||
# 上游为同 compose 网络内的 app:4173;对外仅暴露本代理的 8443。
|
||||
server {
|
||||
listen 8443 ssl;
|
||||
listen [::]:8443 ssl;
|
||||
http2 on;
|
||||
server_name _;
|
||||
|
||||
ssl_certificate /etc/nginx/tls/server.crt;
|
||||
ssl_certificate_key /etc/nginx/tls/server.key;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||
ssl_prefer_server_ciphers on;
|
||||
ssl_session_cache shared:SSL:2m;
|
||||
ssl_session_timeout 1h;
|
||||
|
||||
# 银行流水 Excel 上传上限
|
||||
client_max_body_size 25m;
|
||||
|
||||
proxy_http_version 1.1;
|
||||
proxy_read_timeout 120s;
|
||||
proxy_send_timeout 120s;
|
||||
|
||||
location / {
|
||||
proxy_pass http://app:4173;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
}
|
||||
}
|
||||
+1
-3
@@ -1,5 +1,3 @@
|
||||
⚠️ 本文档已过时,仅留档备查,请勿删除。当前代码状态请看 `README.md`、`项目需求.md`、`最新进度.md` 和 `任务清单.md`。
|
||||
|
||||
# 项目交接说明
|
||||
|
||||
更新时间:2026-08-06
|
||||
@@ -162,7 +160,7 @@ bank_importer 解析内核
|
||||
### 测试与运行
|
||||
|
||||
1. 现有 6 项测试只覆盖解析内核,没有 `/api/parse`、认证、导入持久化、匹配、核算、权限或端到端测试。
|
||||
2. `server.py` 基于标准库开发服务器,默认绑定 `0.0.0.0`(可用 `APP_HOST` 覆盖),没有生产部署、TLS、日志、备份或监控方案。
|
||||
2. `server.py` 基于标准库开发服务器,只绑定 `127.0.0.1`,没有生产部署、TLS、日志、备份或监控方案。
|
||||
3. `流水模板/` 已进入 Git 历史;必须确认均为合成或已脱敏数据,真实生产流水不得继续提交到仓库。
|
||||
|
||||
## 6. 已作出的重要技术决策及原因
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
# 统一门户适配(2026-09-22)
|
||||
|
||||
分支 feature/portal-integration,基于 main 6eccbe9。代码完成但尚未替换外网测试实例;部署方向等待用户决定。
|
||||
|
||||
`PORTAL_SSO_ENABLED=1` 开启门户模式;必须配置独立的 PORTAL_SSO_SECRET、PORTAL_INTERNAL_URL、PORTAL_PUBLIC_URL。若使用 HTTPS,部署时还需相应安全 Cookie 配置。门户配置 FINANCE_SSO_ENABLED、FINANCE_SSO_SECRET、FINANCE_SSO_CALLBACK_URL,回调固定为 `/portal-sso`。
|
||||
|
||||
员工在门户中绑定已有财务用户的数字 ID;本地角色及 company_id 继续决定业务权限,不读取门户 admin 作为业务角色。每名员工应有独立本地账号,同一公司可有多名员工;不将多人映射到共享公司登录身份。账户停用及财务本地停用均拒绝访问。门户模式不允许原生登录、登出、改密、创建凭证或重置密码;管理员/出纳页面仍分开。
|
||||
|
||||
初始化会增量创建 portal_identity、portal_sessions 两表,不改银行流水、业务计算或原会话表。已有银行数据迁移不包含在本次工作中。全新实例须先配置测试公司和测试业务身份,再绑定门户员工;不会默认生成管理员密码。
|
||||
|
||||
候选内网部署 overlay 为 deploy/portal-integration.compose.yml,应叠加现有门户/OA融合 Compose,使用独立 FINANCE_DATA 目录并赋予容器用户 10001 写权限。健康检查使用 `/healthz`,原主页在门户模式跳回门户。FINANCE_IMAGE 应为已准备好依赖的 Python 3.12 财务镜像,代码目录通过 FINANCE_SOURCE 只读挂载。不得把候选测试实例数据路径指向现有正式或独立测试库。
|
||||
|
||||
验证命令:`PYTHONPATH=src python -m unittest discover -s tests`。本轮 395 项:391 通过、4 跳过,其中新增 6 项 SSO 回调/权限/隔离测试。外网到内网门户目前不可达,实际财务跨系统端到端部署验收待完成。
|
||||
@@ -1,21 +0,0 @@
|
||||
# 总账项目手册
|
||||
|
||||
最后核对:2026-08-23。核对依据是当前 `main` 最新代码(`5f21527`)、数据库迁移、接口、测试和近期提交记录。
|
||||
|
||||
这是接手本项目的第一站。阅读顺序如下:
|
||||
|
||||
1. [项目需求](项目需求.md):先知道系统要解决什么问题,以及哪些规则绝不能碰。
|
||||
2. [最新进度](最新进度.md):再确认哪些能力已经真实完成,哪些仍未完成。
|
||||
3. [任务清单](任务清单.md):最后挑选下一项工作,避免重复做已经完成的事。
|
||||
4. 需要技术细节时,再查看 `decisions/` 中的技术决定和 `issues/` 中保留的历史任务规格。
|
||||
|
||||
## 维护规矩
|
||||
|
||||
- 每新增、开始、完成、取消一项任务,负责的智能体都要在同一次提交里更新 `最新进度.md` 和 `任务清单.md`。
|
||||
- 新功能改变产品规则时,同时更新 `项目需求.md`;技术方案有变化时,补充 `decisions/` 的决定记录。
|
||||
- 写进手册的“已完成”必须能在代码、测试或已合并提交中找到依据;只有计划、页面演示或口头讨论的内容,一律写为“未完成”。
|
||||
- 不删除历史文档。旧内容与当前代码不一致时,在旧文件开头加“已过时,仅留档备查”提示,并在本目录写新版说明。
|
||||
|
||||
## 旧交接说明
|
||||
|
||||
`HANDOFF.md` 是 2026-08-06 的历史交接稿,已经不反映当前实现,保留仅作对照。当前事实以本手册三份正文为准。
|
||||
@@ -1,44 +0,0 @@
|
||||
# 002 持久化层技术决策
|
||||
|
||||
对应 Issue:B-39(`docs/issues/002-p0-persistence-and-immutable-imports.md`)。
|
||||
|
||||
## 数据库:SQLite(Python 标准库 `sqlite3`)
|
||||
|
||||
- 单文件、事务完整、零新增依赖,与当前标准库服务器和离线内网部署环境匹配。
|
||||
- 外键约束、CHECK 约束、唯一约束和触发器均可用,足以承载不可变证据模型。
|
||||
- 金额以 `TEXT` 保存 `Decimal` 的原始字符串,读取时还原为 `Decimal`,
|
||||
绝不经过二进制浮点。
|
||||
- 后续若并发写入成为瓶颈,可开启 WAL 或平迁 PostgreSQL;迁移版本表
|
||||
`schema_migrations` 不绑定具体引擎方言之外的特性。
|
||||
|
||||
## 迁移工具:仓库内置版本化迁移器(`src/bank_importer/db.py`)
|
||||
|
||||
- 每条迁移包含 `up` / `down` 两段 SQL,按版本号顺序执行并记录在
|
||||
`schema_migrations` 表中;重复执行无副作用。
|
||||
- 不引入 Alembic 等外部工具:当前模型规模小,内置迁移器保持零依赖,
|
||||
且回滚路径明确(`python -m bank_importer.db <db路径> --rollback-to <版本>`)。
|
||||
- 服务启动时自动执行 `migrate`,空数据库即可完整建表。
|
||||
|
||||
## 文件存储:内容寻址的本地文件系统(`data/files/`)
|
||||
|
||||
- 上传文件先计算 SHA-256,再写入 `data/files/<哈希前两位>/<完整哈希>.<扩展名>`。
|
||||
- 发布采用临时文件 + 硬链接:目标要么完整出现、要么不存在,且永不覆盖。
|
||||
- 相同内容(即使文件名不同)只保存一份文件、一条 `source_files` 记录。
|
||||
- `data/` 已加入 `.gitignore`,真实流水不进入版本库。
|
||||
|
||||
## 幂等与状态机
|
||||
|
||||
- 文件级幂等:`source_files.sha256` 唯一约束。重复上传插入一条
|
||||
`status='duplicate'` 的批次审计记录,指向首个批次,不产生第二份事实。
|
||||
- 行级幂等:`source_rows` 上 `UNIQUE (sheet_batch_id, source_row)`。
|
||||
- 批次状态:`parsing → parsed | exception | failed`,另有 `duplicate`。
|
||||
失败/异常批次保留 `import_exceptions` 诊断(阶段、消息、原始文件名),
|
||||
不产生任何已确认源行。
|
||||
- 事务边界:文件落盘后,`source_files` + 批次 + 工作表批次 + 源行在单个
|
||||
SQLite 事务内提交;解析失败时批次状态与异常记录同样在事务内落库。
|
||||
|
||||
## 不可变性
|
||||
|
||||
- `source_files`、`sheet_batches`、`source_rows` 三张表由数据库触发器禁止
|
||||
`UPDATE` 和 `DELETE`,任何修改只能走后续阶段的冲销/审计调整流程。
|
||||
- 该约束由 `tests/test_persistence.py` 自动化验证。
|
||||
@@ -1,69 +0,0 @@
|
||||
# 003 身份认证与租户隔离技术决策
|
||||
|
||||
对应 Issue:B-40(`docs/issues/003-p0-auth-and-tenant-isolation.md`)。
|
||||
|
||||
## 密码散列:标准库 PBKDF2-HMAC-SHA256
|
||||
|
||||
- 只使用 Python 标准库(`hashlib.pbkdf2_hmac` + `hmac.compare_digest` +
|
||||
`secrets`),不引入 bcrypt/argon2 等第三方依赖,与离线内网部署约束一致。
|
||||
- 260 000 次迭代、16 字节随机盐,存储格式
|
||||
`pbkdf2_sha256$<迭代数>$<盐hex>$<摘要hex>`,自描述、可平滑升级参数。
|
||||
- 明文密码永不入库、永不进日志、永不写入 `audit_log`;
|
||||
`password_hash` 字段从不出现在任何 API 响应中(有测试断言)。
|
||||
|
||||
## 会话:数据库保存令牌摘要,8 小时绝对过期
|
||||
|
||||
- 令牌为 `secrets.token_urlsafe(32)`,数据库只存其 SHA-256 摘要;
|
||||
数据库泄露不直接暴露可用令牌。
|
||||
- 绝对过期 8 小时(一个工作班次),不做滑动续期,语义简单可测。
|
||||
- 会话可吊销:退出登录、停用账号、重置密码都会立即吊销该用户全部会话。
|
||||
- Cookie 名 `cw_session`,`HttpOnly; SameSite=Lax; Path=/`。
|
||||
当前是纯 HTTP 的局域网部署,**刻意不加 `Secure`**(加了浏览器会直接拒发);
|
||||
若未来上 HTTPS,应补上 `Secure` 并配置反向代理。
|
||||
|
||||
## 登录限流:同一 (账号, IP) 10 分钟内失败 5 次即锁定
|
||||
|
||||
- 计数来自 `login_attempts` 表,窗口为滚动 10 分钟;触发后返回 429,
|
||||
且在窗口内不再记录新尝试,行为确定、可测试。
|
||||
- 失败提示统一为「账号或密码不正确」,不泄露是哪一部分错误。
|
||||
- 运维开关:环境变量 `APP_LOGIN_RATE_LIMIT_DISABLED` 设为 `1/true/yes/on`
|
||||
时完全跳过限流检查,仅限内网测试环境临时使用;默认未设置,保持
|
||||
「5 次失败锁 10 分钟」的生产安全策略不变。
|
||||
|
||||
## 角色与公司绑定
|
||||
|
||||
- `users.role` 仅 `admin` / `company`;数据库 CHECK 约束强制
|
||||
公司账号必须绑定公司、管理员不得绑定公司。
|
||||
- 登录时前端选择工作端口(portal),服务端校验 portal 与角色一致,
|
||||
不匹配返回 403「账号与该工作端口不匹配」。
|
||||
- 管理员创建公司账号时,初始密码为随机一次性密码并置
|
||||
`must_change_password=1`;首次登录必须改密,改密前所有业务 API 返回 403。
|
||||
初始密码只在创建成功响应中显示一次,永不入库明文、永不写日志;
|
||||
创建用户的审计 detail 只记录公司,不重复账号名。
|
||||
- 「重置密码」同样生成随机一次性密码并吊销既有会话。
|
||||
|
||||
## 租户隔离在服务端强制,404 优于 403
|
||||
|
||||
- 公司用户的批次列表、行明细、CSV 导出、上传归属全部由服务端按
|
||||
会话中的 `company_id` 过滤;请求体/参数里的 `company_id` 对公司用户
|
||||
一律忽略(跨公司上传防护)。
|
||||
- 访问他公司批次返回 404 而非 403:不暴露「该批次存在但属于别人」这一事实,
|
||||
避免 IDOR 探测。导出时显式指定他公司 `company_id` 仍返回 403,
|
||||
因为用户已声明知道该公司存在,此时给出明确拒绝更有操作性。
|
||||
- `GET /admin.html`、`/company.html` 的 302 跳转只是 UX 层引导,
|
||||
不是权限边界;真正的边界全部在 API 上。
|
||||
|
||||
## 引导管理员(bootstrap)
|
||||
|
||||
- 服务启动迁移后若无任何 admin 账号,创建 `APP_ADMIN_USERNAME`
|
||||
(默认 `group-admin`);密码取 `APP_BOOTSTRAP_ADMIN_PASSWORD`,
|
||||
未设置则生成随机初始密码并**只打印一次到 stdout**(不写日志文件),
|
||||
`must_change_password=1`。
|
||||
- 不在迁移或代码中预置任何公司或用户;公司与公司账号全部由管理员
|
||||
通过 `/api/admin/companies`、`/api/admin/users` 动态创建。
|
||||
|
||||
## 审计
|
||||
|
||||
- `audit_log` 记录登录成功/失败、退出、改密、上传、导出(含公司范围与行数)、
|
||||
建公司、建/停/启用户、重置密码等动作,含操作者、目标、IP、时间。
|
||||
- 初始密码、新旧密码均不进入审计内容。
|
||||
@@ -1,47 +0,0 @@
|
||||
# 004 动态主数据技术决策
|
||||
|
||||
对应 Issue:B-41(`docs/issues/004-p1-dynamic-master-data.md`)。
|
||||
|
||||
## 账户状态机与生效区间
|
||||
|
||||
- `bank_accounts.status`:`pending → active → disabled`,审核退回为
|
||||
`returned`;退回后同公司重新提交复用同一行并回到 `pending`,不产生
|
||||
第二条记录。停用这个动作只对 `active` 开放,退回只对 `pending` 开放,
|
||||
越界操作返回 409。
|
||||
- 生效区间 `effective_from` / `effective_to`(含当天):公司提交时填写
|
||||
期望启用日,管理员审核通过时确认;停用时写入 `effective_to`(默认当天)。
|
||||
- 两个判定函数分开:
|
||||
- `is_usable`(上传选择、当期操作):仅 `active` 且在生效区间内。
|
||||
- `is_identifiable`(历史流水所有权识别):`active` 或 `disabled` 且在
|
||||
生效区间内——停用只终止未来参与,不改写历史归属。
|
||||
|
||||
## 账号规范化与唯一性
|
||||
|
||||
- 账号入库前统一规范化:去空格/短横线、全角数字转半角,只存 6–32 位
|
||||
数字的规范形式;唯一性由数据库 `UNIQUE(account_number)` 保证,并发
|
||||
提交必然只有一个成功(有并发测试)。
|
||||
- 公司端任何响应只含脱敏形式 `****尾四位`;完整账号只在总账管理端
|
||||
(授权审计视图)返回。审计日志 detail 也只写脱敏账号。
|
||||
|
||||
## 别名匹配优先级
|
||||
|
||||
- `account_aliases` 支持户名(`name`)与账号(`account`)两类别名,
|
||||
各自带生效区间和 `priority` 列。
|
||||
- 匹配优先级确定:精确账号(0)< 账号别名(1000+priority)<
|
||||
户名别名(2000+priority);同层内按 `priority` 再按账户 id 排序。
|
||||
别名只在自身生效区间且账户 `is_identifiable` 时参与匹配。
|
||||
|
||||
## 审计轨迹
|
||||
|
||||
- 所有主数据变更写入 `master_data_changes`:实体、动作、前值 JSON、
|
||||
后值 JSON、原因、操作人、时间。公司创建、账户提交/退回重提/
|
||||
审核/停用、别名创建全部覆盖,管理员可按实体查询。
|
||||
|
||||
## 前端边界
|
||||
|
||||
- 公司下拉(往来查询、审核筛选、流水筛选、提醒、期初)和公司表格全部
|
||||
由 `/api/admin/companies` 渲染,新增公司无需改代码即可被检索。
|
||||
- 公司端账户目录、上传账户选择、手工记录资金来源只来自
|
||||
`/api/company/accounts`,且只有 `usable` 账户进入上传选择。
|
||||
- 手工记录仍是浏览器 localStorage 演示数据(属 Issue 007/012 范围),
|
||||
账户登记已完全切换到服务端。
|
||||
@@ -1,63 +0,0 @@
|
||||
# 005 规范转账事件与双边归并技术决策
|
||||
|
||||
对应 Issue:B-43/B-83/B-114(`docs/issues/006-p1-canonical-transfer-matching.md`)。
|
||||
|
||||
## 分层模型
|
||||
|
||||
- 银行源行是不可变观察;匹配层从不修改 `source_rows`。
|
||||
- 新增“不可变决定日志 + 可重建当前投影”的规范事件层:
|
||||
- `transfer_match_decisions` 等证据表只增不改(UPDATE/DELETE 被触发器拒绝)。
|
||||
- `current_transfer_decisions` 与 `transfer_observation_claims` 是可更新、可重建的
|
||||
当前投影,`source_row_id` 主键保证一条观察不可能同时属于两个当前事件。
|
||||
- B-44 余额计算只读 `eligible_intercompany_events` 视图,只含
|
||||
`active + current + classification='intercompany'`,且单边事件必须
|
||||
`locked = 1`(管理员按证据确认)才可计算;paired 事件不受锁定状态限制;
|
||||
单边内部、待审、同公司调拨、外部事件全部排除。
|
||||
|
||||
## 已确认业务口径(B-114)
|
||||
|
||||
1. 单边流水即使双方公司都能由批准账号唯一确认,也先进入未决金额,不进入 B-44
|
||||
已确认往来余额;只有完成双边归并(`intercompany` + `paired`)或管理员按证据确认
|
||||
(`intercompany` + locked 单边)后才可计算。
|
||||
2. 跨日事件经济日期取付款方 outgoing 银行入账时间,与导入顺序无关。
|
||||
3. 自动窗口 v1:非空参考号相同且账号镜像 <= 3 自然日(M1);无参考号精确账号镜像
|
||||
<= 1 自然日(M2);别名/个人映射镜像 <= 1 自然日且参考号或摘要相等(M3)。
|
||||
超窗或同层多候选全部进入人工审核,禁止按行号、导入顺序或名字破平局。
|
||||
4. 个人过账映射绑定具体账号、生效区间、允许方向和代表公司,必须管理员批准;
|
||||
姓名只作辅助证据,不能单独定案。
|
||||
|
||||
## 参与方解析
|
||||
|
||||
- 本方:源行 `own_account` 精确命中生效期内已批准账户(`own_exact`);缺失时才用
|
||||
上传时持久化的批准上传账户(`upload_account`),且必须与批次公司一致。冲突进入
|
||||
审核,不以 `company_id` 或户名反推。
|
||||
- 对方:严格按账号层解析——精确账号 -> 已审核账号别名 -> 已批准且在窗口内、方向
|
||||
允许的个人过账映射;每层唯一最佳结果才继续。户名/户名别名只用于一致性/冲突证据,
|
||||
冲突降级到审核。
|
||||
- 方向:`expense > 0 且 income = 0` 为 outgoing;`income > 0 且 expense = 0` 为
|
||||
incoming;双正/双零/负数/缺币种进入 `unresolved`。金额用 `Decimal` 精确相等,
|
||||
不设手续费容差。
|
||||
|
||||
## 匹配与状态机
|
||||
|
||||
- 候选硬门槛:双方工作表 confirmed、方向相反、金额与币种相等、公司端点互为反向。
|
||||
- M1/M2/M3 唯一候选自动 paired;R1(端点可确认但镜像/参考号证据不足)与 R2(同层
|
||||
多候选)进入 `needs_review`;待审行不能被其他自动匹配抢占。
|
||||
- 状态:`unresolved -> internal_single -> matched`、`needs_review -> matched |
|
||||
same_company_transfer | external`;单边确认两端同公司立即为同公司调拨。
|
||||
- 幂等:rule_version + 当前观察集合 + 证据未变时零写入;locked 人工决定自动重跑
|
||||
跳过;纠错只能通过 `reverse`(`mode='reversal'` 新记录)+ 原因,之后允许重跑。
|
||||
|
||||
## 事务、并发与回滚
|
||||
|
||||
- “确认工作表 + 为新增确认行建立/更新事件 + audit”在同一个服务事务,任一失败整体
|
||||
回滚,不存在 confirmed 但未匹配的半成品。
|
||||
- 独立重跑使用 `BEGIN IMMEDIATE`,按 `source_row_id` 升序写,SQLite 30 秒 busy
|
||||
timeout 保留;投影可从只增日志重建(`rebuild_current_projection`)。
|
||||
- migration down 只用于测试/上线前回退;生产产生决定后默认保留 migration 5 与审计
|
||||
数据,不执行破坏性 down。
|
||||
|
||||
## Decimal
|
||||
|
||||
金额全程以规范十进制字符串存储和比较,任何路径都不转 `float`;`100.0` 与 `100.00`
|
||||
视为相等,`100.00` 与 `100.01` 不匹配。
|
||||
@@ -1,87 +0,0 @@
|
||||
# 006: Intercompany positions, subject review and drill-down evidence (B-44)
|
||||
|
||||
Status: accepted (2026-08-19)
|
||||
|
||||
## Decision
|
||||
|
||||
The intercompany ledger adds one canonical layer above B-43's eligible events:
|
||||
|
||||
- **Append-only ledger events.** A canonical `ledger_event` carries an
|
||||
append-only `ledger_event_revisions` chain. A B-43 eligible bank event first
|
||||
becomes a `pending_subject` revision; an administrator confirms the subject
|
||||
into a `confirmed` revision. Corrections are never in-place edits — a
|
||||
reversal or adjustment is a *new* ledger event with its own effective date,
|
||||
and the original event keeps its history so earlier cutoffs are not
|
||||
rewritten.
|
||||
- **Manual records as immutable submitted facts.** Companies submit
|
||||
`manual_records`; only an administrator-approved record becomes a confirmed
|
||||
ledger event (`approve_new`) or joins one (`approve_link`). Returned,
|
||||
exception and pending records never affect a balance and never leak to the
|
||||
counterparty. Approved facts change only through `reverse` (a new opposite
|
||||
event) — the original is never edited.
|
||||
- **One perspective, fixed mirror.** Subjects are stored from one participating
|
||||
company's perspective (`receivable/payable/other_receivable/other_payable`);
|
||||
the other side is the fixed mirror (应收<->应付, 其他应收<->其他应付), so the
|
||||
two companies can never book conflicting subjects.
|
||||
- **Subjects are confirmed, never auto-posted.** Bank summary/purpose text only
|
||||
feeds a deterministic *suggestion* dictionary (`subject-suggest-draft-v1`,
|
||||
not group-approved). Without an approved trade dictionary every bank event
|
||||
stays in subject review until an administrator confirms.
|
||||
- **Decimal-only aggregation.** All money is stored as TEXT decimal strings and
|
||||
aggregated with Python `Decimal`. SQLite `SUM`, JavaScript `Number` and
|
||||
Python `float` never touch financial math. Different currencies are
|
||||
aggregated and displayed separately; nothing is converted to a group total.
|
||||
- **Conservation is asserted.** For every company pair and currency the two
|
||||
perspectives must mirror exactly (`C_A == -C_B`); a violation raises a
|
||||
calculation exception instead of rendering an unbalanced number.
|
||||
- **Unresolved is absolute gross.** Unresolved amounts are summed by absolute
|
||||
value per currency (never netted), broken down by reason
|
||||
(`subject_review`, `unmatched_single`, `manual_pending`), with count and
|
||||
gross amount exposed on every balance response.
|
||||
- **B-45 boundary.** Until the B-45 opening balance exists, every response
|
||||
returns `opening.status=unavailable`, `opening.amount=null` and
|
||||
`result.kind=period_net_change`; the UI labels this "期间净变动", never
|
||||
"期末余额".
|
||||
|
||||
## Background
|
||||
|
||||
B-43 produces `eligible_intercompany_events` as the only bank-event entry
|
||||
point. Before B-44 there was no canonical financial event, no statutory
|
||||
subject, no manual-record approval, and no server-side balance API. The
|
||||
revision-chain design is inherited from `transfer_match_decisions` in
|
||||
migration 5 and from the append-only audit posture of the rest of the system.
|
||||
|
||||
## Consequences
|
||||
|
||||
- **Positive:** balances are deterministic, conservable, auditable and
|
||||
drillable from a group directory down to bank source rows; manual records
|
||||
cannot double count; corrections never mutate evidence; company portals are
|
||||
tenant-scoped on the server.
|
||||
- **Negative:** pending bank events and returned/exception manual records are
|
||||
intentionally invisible to counterparties, which can surprise cashiers who
|
||||
expect symmetric disclosure; subject confirmation is manual until a
|
||||
group-approved dictionary exists.
|
||||
- **Operational:** migration 6 is forward-only for production once
|
||||
approvals/revisions exist; pre-production it can be rolled back with
|
||||
`--rollback-to 5`. Read aggregation runs against the rebuildable current
|
||||
projection (no day snapshots yet); if B-45 monthly close needs them, immutable
|
||||
monthly snapshots can be added behind the same API contract.
|
||||
|
||||
## Files
|
||||
|
||||
- `src/bank_importer/ledger_events.py` — event lifecycle, revision chain,
|
||||
bank reconciliation, reversal/adjustment/reopen, projection rebuild.
|
||||
- `src/bank_importer/subjects.py` — subject constants/mirror, suggestion
|
||||
dictionary, `confirm_subject`.
|
||||
- `src/bank_importer/manual_records.py` — submission, approval
|
||||
(new/link), return/exception/reverse, candidate hints, idempotency.
|
||||
- `src/bank_importer/positions.py` — Decimal aggregation, directories, pairs,
|
||||
events, evidence visibility, unresolved buckets, keyset pagination.
|
||||
- `server.py` — `/api/admin/intercompany/*` and `/api/company/intercompany/*`
|
||||
plus `/api/admin/subject-reviews` and `/api/admin/manual-records`.
|
||||
- `db.py` migration 6 — `manual_records`, `manual_record_decisions`,
|
||||
`ledger_events`, `ledger_event_revisions`, current-pointer projections,
|
||||
source claim tables, `ledger_subject_suggestions`, `eligible_position_events`.
|
||||
- Tests: `test_ledger_events.py`, `test_manual_records.py`,
|
||||
`test_positions.py`, `test_positions_api.py`, extended
|
||||
`test_persistence.py`.
|
||||
@@ -1,13 +0,0 @@
|
||||
# 员工与公司分配
|
||||
|
||||
门户决定员工是否可以进入财务系统;财务本地角色区分管理端和公司端。公司端员工可以暂未分配公司,一名出纳可负责多家公司,一家公司可分配多名出纳。
|
||||
|
||||
管理端“公司与账号”通过姓名和工号选择出纳。候选人必须同时满足:本地公司端角色且启用、门户仍授权财务系统、双方不可变身份绑定一致。门户不可用时拒绝保存分配,不使用过期名单继续授权。
|
||||
|
||||
`company_memberships` 是公司操作范围的唯一依据。`users.company_id` 仅保留兼容信息;公司业务接口每次请求都从分配表解析当前公司。多公司员工必须提交明确的公司范围,未分配、越权和已撤销范围均拒绝。CSV 下载也进行同样校验。浏览器按标签页保存所选公司,切换时确认并重载以清空未提交内容。
|
||||
|
||||
分配调整记录原员工和新员工 ID,不转移或重写历史业务记录。部门或岗位名称不自动授予财务管理权限。
|
||||
|
||||
迁移 11 保留原用户 ID、密码、会话及业务记录,把既有单公司关联迁入分配表。迁移禁止新增外键错误;已有孤立审计引用保持原样,不借升级重写历史。存在多公司或未分配公司员工时,回滚到旧结构会明确拒绝,需先制定人员迁移方案或恢复部署前备份。
|
||||
|
||||
验证包含真实 HTTP 的未分配拒绝、多公司范围、同公司多人、旧会话撤权、导出越权、员工停用、门户身份不匹配及迁移历史保留;另有完整回归测试和隔离页面检查。
|
||||
@@ -1,5 +1,3 @@
|
||||
⚠️ 本文档已过时,仅留档备查,请勿删除。该历史任务已落地;当前状态见 `../任务清单.md`。
|
||||
|
||||
# [P0] 仓库银行样本数据分级与脱敏治理
|
||||
|
||||
## 背景
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
⚠️ 本文档已过时,仅留档备查,请勿删除。该历史任务已落地;当前状态见 `../任务清单.md`。
|
||||
|
||||
# [P0] 持久化层与不可变银行导入基础
|
||||
|
||||
## 背景
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
⚠️ 本文档已过时,仅留档备查,请勿删除。该历史任务已落地;当前状态见 `../任务清单.md`。
|
||||
|
||||
# [P0] 正式认证、RBAC 与公司级数据隔离
|
||||
|
||||
## 背景
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
⚠️ 本文档已过时,仅留档备查,请勿删除。该历史任务已落地;当前状态见 `../任务清单.md`。
|
||||
|
||||
# [P1] 动态公司、用户、账户和别名主数据
|
||||
|
||||
## 背景
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
⚠️ 本文档已过时,仅留档备查,请勿删除。该历史任务已落地;当前状态见 `../任务清单.md`。
|
||||
|
||||
# [P1] 银行导入 API 加固与回归测试
|
||||
|
||||
## 背景
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
⚠️ 本文档已过时,仅留档备查,请勿删除。该历史任务已落地;当前状态见 `../任务清单.md`。
|
||||
|
||||
# [P1] 规范转账事件、双边匹配与调拨排除
|
||||
|
||||
## 背景
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
# 任务清单
|
||||
|
||||
最后核对:2026-08-30。状态以当前代码和已合并提交为准。
|
||||
|
||||
## 正在做
|
||||
|
||||
- HEL-270 上线前总验收(总工):代码审核、测试环境部署、备份恢复与回滚演练、边界自动化证据。
|
||||
|
||||
## 已做完
|
||||
|
||||
- 六类银行流水模板识别与解析。
|
||||
- 数据库迁移(至版本 10)、不可变原始证据、导入批次和重复导入处理;文件库 WAL。
|
||||
- 管理员/公司用户登录、密码策略、会话清理、限流、服务端公司隔离和审计。
|
||||
- 动态公司、用户、银行账户、别名与账户审核流程。
|
||||
- 导入接口加固、逐工作表确认、失败诊断和导出。
|
||||
- 规范转账事件、双边匹配、同公司调拨排除与个人过账映射。
|
||||
- 起算日、期初余额、流水覆盖断档检测和无业务校准。
|
||||
- 月结、重开审批、闭期补录、锁账写保护、月报与审计记录。
|
||||
- 服务端流水查询、筛选、分页和可追溯导出;往来查询与手工记录接入真实接口。
|
||||
- 站内提醒与状态流转。
|
||||
- 前端移除演示流水/往来造数和 `localStorage` 业务状态。
|
||||
- 登录页视觉融合改版;月结/重开/审计按 HEL-268 视觉规范落地。
|
||||
- 测试环境部署编排收编到 `deploy/`,含非 root 加固、备份/巡检脚本与运维手册(不在施工员职责内执行上线)。
|
||||
|
||||
## 还没安排
|
||||
|
||||
- 正式部署(P4):HTTPS 反代落地、异机备份副本、正式账号交接。覆盖正式环境必须老板明确同意。
|
||||
|
||||
每完成或新增一项任务,必须在同一次提交里把它从本清单的相应栏目移走或补上,并同步更新 `最新进度.md`。
|
||||
@@ -1,27 +0,0 @@
|
||||
# 最新进度
|
||||
|
||||
最后核对:2026-08-30。以下“已完成”均以当前代码、数据库迁移、接口和自动化测试为依据,不把页面演示当作真实功能。
|
||||
|
||||
## 已经真实完成
|
||||
|
||||
- 支持中信、农行、工行、建行、河南农商行、郑州银行六类样本的 `.xls` / `.xlsx` 流水解析;能识别变动的表头位置和列顺序,并校验余额连续性。
|
||||
- 已有 SQLite 数据库和 10 次版本迁移。原始文件按内容哈希保存,导入批次、工作表、源行和异常都有记录;原始文件、工作表和源行被数据库规则保护,不能直接改或删。文件库启用 WAL。
|
||||
- 已实现管理员与公司用户登录、首次改密、会话失效(过期会话在发新会话时清理)、登录失败限流、服务端权限隔离和审计记录。
|
||||
- 已实现公司、用户、银行账户、别名等主数据管理;公司提交的银行账户需管理员审核后才能参与上传和识别。
|
||||
- 已实现导入、逐工作表确认或忽略、失败诊断、重复上传处理和 CSV 导出;未确认的工作表不进入后续处理。
|
||||
- 已实现规范转账事件和双边流水匹配。匹配决定保留历史,无法自动判断的记录进入人工审核;同公司调拨、外部流水和未锁定的单边记录不进入已确认的公司间往来。
|
||||
- 已实现全局起算日、公司对期初余额、流水覆盖断档与无业务说明审核。
|
||||
- 已实现月结:结账日到达后生成待结账任务,管理员确认后锁账并生成带 SHA-256 的月报;重开须审批,窗口到期自动恢复锁定;闭期补录进入 `period_late_arrivals`,不改已结快照;写保护拒绝锁定月的普通修改。
|
||||
- 流水列表/导出、往来查询、公司端手工记录已改为服务器真实数据;空列表显示「暂无数据」。页面不再使用 `FLOW_DEMO` / `localStorage` 业务状态。
|
||||
- 已有登录页、总账端和公司端页面。管理端「结账与期初」承接月结,「审核中心」增加重开审批,「结账与期初」之后增加「审计记录」。
|
||||
- `deploy/` 收编测试环境 Dockerfile、compose、`.env.example` 与部署/回滚脚本(4173、非 root、只读根文件系统、drop ALL、pids/mem/cpu 限制、healthcheck)。正式口令不进仓库。
|
||||
- 备份(在线热备 + 30 天日备/12 个月月备保留策略)、巡检(健康 + 磁盘 ≥80% 告警)脚本与《部署与运维手册》`deploy/README.md` 已入库;HTTPS 走反向代理方案已在手册写明。
|
||||
|
||||
## 仍未完成或不能当成已完成
|
||||
|
||||
- 正式环境尚未部署(P4):HTTPS 反代、异机备份副本、正式账号交接在上线时落地。覆盖正式环境必须老板明确同意。
|
||||
- 发布基线:`release/prod` 长期分支已建立,`main` 待发布时快进。
|
||||
|
||||
## 最近验证
|
||||
|
||||
2026-08-30 已运行完整 Python 自动化测试(`PYTHONPATH=src python -m unittest discover -s tests -v`),覆盖解析、持久化、认证、导入、主数据、匹配、月结/重开/写保护、前端契约与 360/820/1440 布局冒烟(有 Chromium 时)。后续修改功能时必须再次运行完整测试并在本文件记录结果。
|
||||
@@ -1,26 +0,0 @@
|
||||
# 项目需求
|
||||
|
||||
## 这个系统做什么
|
||||
|
||||
这是河南金牛实业集团有限公司内部各公司之间的资金往来管理系统。它把各公司的银行流水集中起来,识别同一笔公司间转账的两边记录,形成可以一路查回原始银行流水的往来结果。
|
||||
|
||||
系统有两个独立入口:
|
||||
|
||||
- 总账管理端:管理公司、公司账号、银行账户、导入记录、异常和公司间转账匹配。
|
||||
- 公司出纳端:只处理本公司的账户登记、流水上传、工作表确认和本公司相关异常。
|
||||
|
||||
## 必须做到的业务规则
|
||||
|
||||
- 银行原始文件和原始流水是证据,导入后不能直接修改或删除;修正必须通过可追溯的审核决定、冲销或调整完成。
|
||||
- 一笔公司间转账的收、付两边只能算作一个经济事件,不能因为有两条银行流水就重复计算。
|
||||
- 同一家公司不同银行账户之间调拨,不计入公司间往来。
|
||||
- 账号、金额、方向、日期和余额等可核对信息优先于户名;信息不完整或有歧义时进入异常审核,不能猜。
|
||||
- 已确认金额和待确认金额必须分开;所有余额都要说明统计截止日期和未决金额。
|
||||
- 公司用户只能查看、上传和导出本公司的数据。这个限制由服务端执行,页面上“看不见”不等于有权限限制。
|
||||
- 起算日前的流水必须保留,但不参与期内计算;期初余额、流水覆盖断档、无业务校准、月结和调整都要留痕。
|
||||
|
||||
## 当前技术边界
|
||||
|
||||
项目使用 Python 标准库服务、SQLite 数据库和浏览器页面。银行模板支持 `.xls` 与 `.xlsx`,按表头识别而非依赖固定行列。金额使用精确十进制,真实运行数据放在 `data/`,不进入代码仓库。
|
||||
|
||||
系统目前仍是测试环境项目,不能当作已完成生产部署:正式上线前仍需补齐核算、期初与断档、月结、备份、监控和 HTTPS 等能力。
|
||||
@@ -1,126 +0,0 @@
|
||||
"""HEL-342: static visual shots + computed-style probe (no business data writes)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from functools import partial
|
||||
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from threading import Thread
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
WEB = ROOT / "web"
|
||||
OUT = ROOT.parent / "hel342-shots"
|
||||
|
||||
PROBES = [
|
||||
(".sidebar", ["width", "backgroundColor", "backdropFilter"]),
|
||||
(".brand-logo-day", ["width", "height"]),
|
||||
(".btn-primary", ["backgroundColor", "height", "borderRadius", "color"]),
|
||||
(".stat-card.gold .stat-value, .stat-card .stat-value", ["color", "fontSize", "fontVariantNumeric"]),
|
||||
(".page-head h1", ["fontSize", "fontWeight"]),
|
||||
(".ds-table th", ["fontSize", "color"]),
|
||||
]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
handler = partial(SimpleHTTPRequestHandler, directory=str(WEB))
|
||||
httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
Thread(target=httpd.serve_forever, daemon=True).start()
|
||||
base = f"http://127.0.0.1:{httpd.server_address[1]}"
|
||||
report = []
|
||||
|
||||
pages = [
|
||||
("index", "index.html", None, None),
|
||||
("login-admin", "login-admin.html", None, None),
|
||||
("login-company", "login-company.html", None, None),
|
||||
("admin-dashboard", "admin.html", "dashboard", None),
|
||||
("admin-flows", "admin.html", "flows", None),
|
||||
("admin-settings", "admin.html", "settings", None),
|
||||
("admin-audit", "admin.html", "audit", None),
|
||||
("admin-reminders", "admin.html", "reminders", None),
|
||||
("admin-period-audit", "admin.html", "period-audit", None),
|
||||
("admin-companies", "admin.html", "companies", None),
|
||||
("admin-pair", "admin.html", "pair", None),
|
||||
("company-workspace", "company.html", "workspace", None),
|
||||
("company-transfers", "company.html", "transfers", None),
|
||||
("company-reconcile", "company.html", "reconcile", None),
|
||||
("company-upload", "company.html", "upload", None),
|
||||
]
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, args=["--no-sandbox"])
|
||||
for theme in ("day", "night"):
|
||||
for width, height, tag in ((1440, 900, "1440"), (820, 900, "820"), (390, 844, "390")):
|
||||
if tag != "1440" and theme == "night" and width != 390:
|
||||
continue
|
||||
page = browser.new_page(viewport={"width": width, "height": height})
|
||||
page.add_init_script(
|
||||
f"() => {{ try {{ localStorage.setItem('jinniu-theme', '{theme}'); }} catch (e) {{}} }}"
|
||||
)
|
||||
for name, html, view, _ in pages:
|
||||
if tag != "1440" and name not in ("login-admin", "admin-flows", "company-transfers", "admin-dashboard"):
|
||||
continue
|
||||
page.route("**/app.js**", lambda route: route.abort())
|
||||
page.goto(f"{base}/{html}", wait_until="domcontentloaded")
|
||||
page.evaluate(
|
||||
"""(args) => {
|
||||
document.documentElement.classList.add('v-fusion');
|
||||
document.documentElement.setAttribute('data-theme', args.theme);
|
||||
if (args.view) {
|
||||
document.querySelectorAll('.app-view').forEach((el) => {
|
||||
el.classList.toggle('is-active', el.dataset.page === args.view);
|
||||
});
|
||||
}
|
||||
}""",
|
||||
{"theme": theme, "view": view},
|
||||
)
|
||||
page.wait_for_timeout(80)
|
||||
shot = OUT / f"{name}-{theme}-{tag}.png"
|
||||
page.screenshot(path=str(shot), full_page=False)
|
||||
if tag == "1440" and name in ("login-admin", "admin-dashboard", "admin-flows"):
|
||||
probe = page.evaluate(
|
||||
"""(sels) => sels.map(([sel, props]) => {
|
||||
const el = document.querySelector(sel);
|
||||
if (!el) return { sel, missing: true };
|
||||
const cs = getComputedStyle(el);
|
||||
const out = { sel };
|
||||
props.forEach((p) => { out[p] = cs[p]; });
|
||||
const box = el.getBoundingClientRect();
|
||||
out.box = { w: Math.round(box.width), h: Math.round(box.height) };
|
||||
return out;
|
||||
})""",
|
||||
PROBES,
|
||||
)
|
||||
overflow = page.evaluate(
|
||||
"() => document.documentElement.scrollWidth > document.documentElement.clientWidth + 1"
|
||||
)
|
||||
report.append({"page": name, "theme": theme, "overflow": overflow, "probe": probe})
|
||||
page.close()
|
||||
|
||||
# 390 drawer
|
||||
page = browser.new_page(viewport={"width": 390, "height": 844})
|
||||
page.add_init_script("() => { try { localStorage.setItem('jinniu-theme', 'day'); } catch (e) {} }")
|
||||
page.route("**/app.js**", lambda route: route.abort())
|
||||
page.goto(f"{base}/company.html", wait_until="domcontentloaded")
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
document.documentElement.classList.add('v-fusion');
|
||||
document.querySelectorAll('.app-view').forEach((el) => {
|
||||
el.classList.toggle('is-active', el.dataset.page === 'transfers');
|
||||
});
|
||||
const d = document.getElementById('transferEvidenceDrawer');
|
||||
if (d) d.classList.add('is-open');
|
||||
}"""
|
||||
)
|
||||
page.screenshot(path=str(OUT / "company-transfers-drawer-day-390.png"), full_page=False)
|
||||
page.close()
|
||||
browser.close()
|
||||
httpd.shutdown()
|
||||
(OUT / "probe.json").write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print(f"wrote {OUT} ({len(list(OUT.glob('*.png')))} png)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,186 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""HEL-174: 360 / 820 / 1440 截图——待确认黄 vs 已完成绿。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import threading
|
||||
from functools import partial
|
||||
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
WEB = ROOT / "web"
|
||||
OUT = Path(__file__).resolve().parent.parent / "hel174-shots"
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
VIEWPORTS = [
|
||||
(1440, 900, "1440"),
|
||||
(820, 900, "820"),
|
||||
(360, 800, "360"),
|
||||
]
|
||||
|
||||
|
||||
def extract_fn(source: str, name: str) -> str:
|
||||
marker = f"function {name}("
|
||||
start = source.index(marker)
|
||||
depth = 0
|
||||
for i, ch in enumerate(source[start:], start):
|
||||
if ch == "{":
|
||||
depth += 1
|
||||
elif ch == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return source[start : i + 1]
|
||||
raise RuntimeError(name)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
app_js = (WEB / "app.js").read_text(encoding="utf-8")
|
||||
inject = "\n".join(
|
||||
[
|
||||
"const state = {};",
|
||||
"function $(sel, root) { return (root || document).querySelector(sel); }",
|
||||
"function $$(sel, root) { return Array.from((root || document).querySelectorAll(sel)); }",
|
||||
extract_fn(app_js, "formatWorkspaceAmount"),
|
||||
extract_fn(app_js, "applyCompanyWorkspace"),
|
||||
]
|
||||
)
|
||||
|
||||
handler = partial(SimpleHTTPRequestHandler, directory=str(WEB))
|
||||
httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
port = httpd.server_address[1]
|
||||
thread = threading.Thread(target=httpd.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
base = f"http://127.0.0.1:{port}"
|
||||
|
||||
html = f"""<!doctype html>
|
||||
<html lang="zh-CN"><head>
|
||||
<meta charset="UTF-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
|
||||
<link rel="stylesheet" href="{base}/design-system.css"/>
|
||||
<title>HEL-174 往来确认状态色</title>
|
||||
<style>
|
||||
body {{ margin: 0; background: var(--bg); font-family: var(--font-body); color: var(--fg); }}
|
||||
.shot-wrap {{ padding: 16px; max-width: 1100px; margin: 0 auto; }}
|
||||
.shot-label {{ font-size: 13px; color: var(--muted); margin: 0 0 10px; }}
|
||||
</style>
|
||||
</head>
|
||||
<body data-portal="company">
|
||||
<div class="shot-wrap">
|
||||
<p class="shot-label" id="shotLabel">状态预览</p>
|
||||
<button id="workspaceUnilateralCta" class="btn btn-primary">去确认单边流水 (0)</button>
|
||||
<div class="card" id="workspaceTodos" style="margin-top:12px;">
|
||||
<div class="card-head">
|
||||
<span class="card-title">本月待办<span class="sub" id="workspaceTodoSub">…</span></span>
|
||||
<span class="pill pill-warn" id="workspacePendingStatus">加载中</span>
|
||||
</div>
|
||||
<div id="workspaceTodoList"></div>
|
||||
<div class="table-foot" id="workspaceTodoFoot"><span>…</span></div>
|
||||
</div>
|
||||
<div class="card" style="margin-top:12px;">
|
||||
<div class="card-head">
|
||||
<span class="card-title">账期流程 · 2026-07<span class="sub" id="workspaceFlowSub">…</span></span>
|
||||
</div>
|
||||
<div class="flow">
|
||||
<a class="flow-step part" href="#upload">
|
||||
<div class="fs-top"><span class="fs-idx">01</span><span class="fs-dot"></span><span class="fs-name">流水导入</span></div>
|
||||
<div class="fs-state">部分完成</div>
|
||||
</a>
|
||||
<a class="flow-step done" href="#manual">
|
||||
<div class="fs-top"><span class="fs-idx">02</span><span class="fs-dot"></span><span class="fs-name">手工补录</span></div>
|
||||
<div class="fs-state">已完成</div>
|
||||
</a>
|
||||
<a class="flow-step doing" data-view-link="reconcile" href="#reconcile">
|
||||
<div class="fs-top"><span class="fs-idx">03</span><span class="fs-dot"></span><span class="fs-name">往来确认</span></div>
|
||||
<div class="fs-state" id="workspaceConfirmState">加载中…</div>
|
||||
<div class="fs-meta" id="workspaceConfirmMeta">…</div>
|
||||
</a>
|
||||
<div class="flow-step wait">
|
||||
<div class="fs-top"><span class="fs-idx">04</span><span class="fs-dot"></span><span class="fs-name">管理复核</span></div>
|
||||
<div class="fs-state">等待集团</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="notice warn" id="blocking-notice" style="margin-top:12px;">
|
||||
<div>
|
||||
<div class="n-title" id="notice-title">…</div>
|
||||
<div class="n-body" id="notice-body">…</div>
|
||||
</div>
|
||||
</div>
|
||||
<div style="margin-top:12px;">
|
||||
<span class="pill pill-warn">待确认</span>
|
||||
<span class="pill pill-success" style="margin-left:8px;">已确认</span>
|
||||
</div>
|
||||
<span class="tab-count" id="count-match" hidden>0</span>
|
||||
<nav class="side-nav" hidden><a data-view="reconcile"><span class="nav-badge">0</span></a></nav>
|
||||
</div>
|
||||
</body></html>"""
|
||||
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, args=["--no-sandbox"])
|
||||
page = browser.new_page()
|
||||
for width, height, tag in VIEWPORTS:
|
||||
page.set_viewport_size({"width": width, "height": height})
|
||||
page.set_content(html, wait_until="domcontentloaded")
|
||||
page.add_script_tag(content=inject)
|
||||
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
document.getElementById('shotLabel').textContent = '待确认(应黄)';
|
||||
applyCompanyWorkspace({
|
||||
pending_unilateral: 3, pending_total: 3,
|
||||
unilateral_events: [
|
||||
{event_id:1, amount:'100000.00', currency:'CNY',
|
||||
counterparty_company_name:'金牛贸易', effective_at:'2026-07-03'},
|
||||
{event_id:2, amount:'200000.00', currency:'CNY',
|
||||
counterparty_company_name:'金牛物流', effective_at:'2026-07-11'},
|
||||
{event_id:3, amount:'300000.00', currency:'CNY',
|
||||
counterparty_company_name:'金牛置业', effective_at:'2026-07-24'}
|
||||
]
|
||||
});
|
||||
}"""
|
||||
)
|
||||
page.wait_for_timeout(200)
|
||||
page.screenshot(path=str(OUT / f"hel174-pending-{tag}.png"), full_page=True)
|
||||
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
document.getElementById('shotLabel').textContent = '已完成(应绿)';
|
||||
applyCompanyWorkspace({
|
||||
pending_unilateral: 0, pending_total: 0, unilateral_events: []
|
||||
});
|
||||
}"""
|
||||
)
|
||||
page.wait_for_timeout(200)
|
||||
page.screenshot(path=str(OUT / f"hel174-done-{tag}.png"), full_page=True)
|
||||
|
||||
colors = page.evaluate(
|
||||
"""() => {
|
||||
const step = document.querySelector('.flow-step[data-view-link="reconcile"]');
|
||||
const state = document.getElementById('workspaceConfirmState');
|
||||
const pill = document.getElementById('workspacePendingStatus');
|
||||
return {
|
||||
stepClass: step.className,
|
||||
stateText: state.textContent,
|
||||
stateColor: getComputedStyle(state).color,
|
||||
pillClass: pill.className,
|
||||
overflowX: document.documentElement.scrollWidth > document.documentElement.clientWidth + 1,
|
||||
};
|
||||
}"""
|
||||
)
|
||||
assert "done" in colors["stepClass"], colors
|
||||
assert "pill-success" in colors["pillClass"], colors
|
||||
assert colors["stateText"] == "已完成", colors
|
||||
assert not colors["overflowX"], colors
|
||||
print(tag, colors)
|
||||
|
||||
browser.close()
|
||||
httpd.shutdown()
|
||||
print("shots:", sorted(p.name for p in OUT.glob("*.png")))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,286 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""HEL-177: 转账往来页 360/820/1440 冒烟截图(mock 接口,不依赖登录库)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import threading
|
||||
from functools import partial
|
||||
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
WEB = ROOT / "web"
|
||||
OUT = ROOT / "hel177-shots"
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
VIEWPORTS = [(1440, 900, "1440"), (820, 900, "820"), (360, 800, "360")]
|
||||
|
||||
SUMMARY = {
|
||||
"status": "ok",
|
||||
"own_company": {"id": 3, "name": "河南金牛煤业有限公司"},
|
||||
"window": {
|
||||
"start": "2026-01-01",
|
||||
"end": "2026-08-20",
|
||||
"has_opening": False,
|
||||
"opening": None,
|
||||
"ending": None,
|
||||
},
|
||||
"confirmed": {
|
||||
"outflow_total": "123860000.00",
|
||||
"outflow_count": 48,
|
||||
"inflow_total": "184205000.00",
|
||||
"inflow_count": 77,
|
||||
"net_change": "-60345000.00",
|
||||
"net_direction": "payable",
|
||||
},
|
||||
"pending": {"count": 3, "amount_total": "3200000.00"},
|
||||
"counterparties": [
|
||||
{
|
||||
"company_id": 5,
|
||||
"company_name": "河南金牛置业有限公司",
|
||||
"confirmed_outflow": "52000000.00",
|
||||
"confirmed_inflow": "86000000.00",
|
||||
"net": "-34000000.00",
|
||||
"pending_count": 2,
|
||||
"last_effective_at": "2026-08-18",
|
||||
},
|
||||
{
|
||||
"company_id": 6,
|
||||
"company_name": "河南金牛贸易有限公司",
|
||||
"confirmed_outflow": "10000000.00",
|
||||
"confirmed_inflow": "12605000.00",
|
||||
"net": "-2605000.00",
|
||||
"pending_count": 1,
|
||||
"last_effective_at": "2026-08-10",
|
||||
},
|
||||
{
|
||||
"company_id": 7,
|
||||
"company_name": "河南金牛农业科技发展有限公司",
|
||||
"confirmed_outflow": "61860000.00",
|
||||
"confirmed_inflow": "85600000.00",
|
||||
"net": "-23740000.00",
|
||||
"pending_count": 0,
|
||||
"last_effective_at": "2026-07-30",
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
# 修正 mock:按 HEL-169 净变动=转出-转入,正数应收
|
||||
SUMMARY["confirmed"] = {
|
||||
"outflow_total": "184205000.00",
|
||||
"outflow_count": 80,
|
||||
"inflow_total": "123860000.00",
|
||||
"inflow_count": 48,
|
||||
"net_change": "60345000.00",
|
||||
"net_direction": "receivable",
|
||||
}
|
||||
SUMMARY["counterparties"] = [
|
||||
{
|
||||
"company_id": 5,
|
||||
"company_name": "河南金牛置业有限公司",
|
||||
"confirmed_outflow": "86000000.00",
|
||||
"confirmed_inflow": "52000000.00",
|
||||
"net": "34000000.00",
|
||||
"pending_count": 2,
|
||||
"last_effective_at": "2026-08-18",
|
||||
},
|
||||
{
|
||||
"company_id": 6,
|
||||
"company_name": "河南金牛贸易有限公司",
|
||||
"confirmed_outflow": "12605000.00",
|
||||
"confirmed_inflow": "10000000.00",
|
||||
"net": "2605000.00",
|
||||
"pending_count": 1,
|
||||
"last_effective_at": "2026-08-10",
|
||||
},
|
||||
{
|
||||
"company_id": 7,
|
||||
"company_name": "河南金牛农业科技发展有限公司",
|
||||
"confirmed_outflow": "85600000.00",
|
||||
"confirmed_inflow": "61860000.00",
|
||||
"net": "23740000.00",
|
||||
"pending_count": 0,
|
||||
"last_effective_at": "2026-07-30",
|
||||
},
|
||||
]
|
||||
|
||||
EVENTS = {
|
||||
"status": "ok",
|
||||
"window": {"start": "2026-01-01", "end": "2026-08-20"},
|
||||
"events": [
|
||||
{
|
||||
"event_id": 101,
|
||||
"direction": "in",
|
||||
"state": "confirmed",
|
||||
"pairing": "paired",
|
||||
"locked": False,
|
||||
"amount": "12000000.00",
|
||||
"currency": "CNY",
|
||||
"effective_at": "2026-08-18",
|
||||
"summary": "周转资金调拨",
|
||||
"status": "matched",
|
||||
},
|
||||
{
|
||||
"event_id": 102,
|
||||
"direction": "out",
|
||||
"state": "pending",
|
||||
"pairing": "unilateral",
|
||||
"locked": False,
|
||||
"amount": "1500000.00",
|
||||
"currency": "CNY",
|
||||
"effective_at": "2026-08-12",
|
||||
"summary": "工程款结算(待确认)",
|
||||
"status": "unresolved",
|
||||
},
|
||||
],
|
||||
"next_cursor": None,
|
||||
"has_more": False,
|
||||
}
|
||||
|
||||
DETAIL = {
|
||||
"status": "ok",
|
||||
"event": {
|
||||
"event_id": 101,
|
||||
"classification": "intercompany",
|
||||
"pairing": "paired",
|
||||
"status": "matched",
|
||||
"amount": "12000000.00",
|
||||
"currency": "CNY",
|
||||
"effective_at": "2026-08-18",
|
||||
"mode": "auto",
|
||||
"reason": "双边匹配",
|
||||
"counterparty": {
|
||||
"company_id": 5,
|
||||
"company_name": "河南金牛置业有限公司",
|
||||
"account_number_masked": "****8821",
|
||||
},
|
||||
"observations": [
|
||||
{
|
||||
"source_row_id": 1,
|
||||
"role": "payee",
|
||||
"source_row": 148,
|
||||
"sheet_name": "流水",
|
||||
"transaction_at": "2026-08-18 10:22:00",
|
||||
"income": "12000000.00",
|
||||
"expense": None,
|
||||
"import_batch_id": 19,
|
||||
"original_filename": "工行3305_202608.xls",
|
||||
"own_account_masked": "****3305",
|
||||
"counterparty_account_masked": "****8821",
|
||||
"counterparty_name": "河南金牛置业有限公司",
|
||||
"summary": "周转资金调拨",
|
||||
"reference": "JS20260818-00317",
|
||||
}
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
handler = partial(SimpleHTTPRequestHandler, directory=str(WEB))
|
||||
httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
port = httpd.server_address[1]
|
||||
threading.Thread(target=httpd.serve_forever, daemon=True).start()
|
||||
base = f"http://127.0.0.1:{port}"
|
||||
|
||||
mock_js = f"""
|
||||
window.__HEL177_MOCK__ = true;
|
||||
const SUMMARY = {json.dumps(SUMMARY, ensure_ascii=False)};
|
||||
const EVENTS = {json.dumps(EVENTS, ensure_ascii=False)};
|
||||
const DETAIL = {json.dumps(DETAIL, ensure_ascii=False)};
|
||||
const _fetch = window.fetch.bind(window);
|
||||
window.fetch = async (input, init) => {{
|
||||
const url = String(input);
|
||||
if (url.includes('/api/me') || url.includes('/api/session')) {{
|
||||
return new Response(JSON.stringify({{role:'company', company_id:3, username:'牛女士', company_name:'河南金牛煤业有限公司'}}), {{status:200, headers:{{'Content-Type':'application/json'}}}});
|
||||
}}
|
||||
if (url.includes('/api/company/workspace')) {{
|
||||
return new Response(JSON.stringify({{status:'ok', pending_unilateral:0, pending_total:0, unilateral_events:[]}}), {{status:200, headers:{{'Content-Type':'application/json'}}}});
|
||||
}}
|
||||
if (url.includes('/api/company/intercompany/summary')) {{
|
||||
return new Response(JSON.stringify(SUMMARY), {{status:200, headers:{{'Content-Type':'application/json'}}}});
|
||||
}}
|
||||
if (url.includes('/api/company/intercompany/events')) {{
|
||||
return new Response(JSON.stringify(EVENTS), {{status:200, headers:{{'Content-Type':'application/json'}}}});
|
||||
}}
|
||||
if (url.includes('/api/company/transfer-events/')) {{
|
||||
return new Response(JSON.stringify(DETAIL), {{status:200, headers:{{'Content-Type':'application/json'}}}});
|
||||
}}
|
||||
if (url.includes('/api/company/')) {{
|
||||
return new Response(JSON.stringify({{status:'ok'}}), {{status:200, headers:{{'Content-Type':'application/json'}}}});
|
||||
}}
|
||||
return _fetch(input, init);
|
||||
}};
|
||||
"""
|
||||
|
||||
console_errors: list[str] = []
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch()
|
||||
page = browser.new_page()
|
||||
page.on("pageerror", lambda exc: console_errors.append(f"pageerror:{exc}"))
|
||||
page.on("console", lambda msg: console_errors.append(f"console:{msg.type}:{msg.text}") if msg.type == "error" else None)
|
||||
|
||||
for width, height, label in VIEWPORTS:
|
||||
page.set_viewport_size({"width": width, "height": height})
|
||||
page.add_init_script(mock_js)
|
||||
# bypass auth guard
|
||||
page.add_init_script(
|
||||
"""
|
||||
const orig = window.fetch;
|
||||
// initAuthGuard 读 /api/me;已在 mock 中处理
|
||||
"""
|
||||
)
|
||||
page.goto(f"{base}/company.html", wait_until="domcontentloaded")
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
// 若鉴权把页面踢走,强制停留
|
||||
if (!document.body || document.body.dataset.portal !== 'company') return;
|
||||
}"""
|
||||
)
|
||||
# 等 summary 渲染
|
||||
page.wait_for_timeout(600)
|
||||
# 切到转账往来
|
||||
page.evaluate("() => { if (typeof showView === 'function') showView('transfers'); }")
|
||||
page.wait_for_selector("#transfersData:not([hidden])", timeout=5000)
|
||||
page.wait_for_timeout(300)
|
||||
overflow = page.evaluate(
|
||||
"() => document.documentElement.scrollWidth > document.documentElement.clientWidth + 1"
|
||||
)
|
||||
assert not overflow, f"{label} overview overflow"
|
||||
# 文案:期间净变动,无期末余额误用
|
||||
net_title = page.inner_text("#tfStatNetTitle")
|
||||
assert "期间净变动" in net_title, net_title
|
||||
page.screenshot(path=str(OUT / f"overview-{label}.png"), full_page=True)
|
||||
|
||||
# 下钻明细
|
||||
page.click("#transfersCpBody tr.clickable")
|
||||
page.wait_for_selector("#transfersDetailLayer:not([hidden])", timeout=5000)
|
||||
page.wait_for_timeout(300)
|
||||
overflow2 = page.evaluate(
|
||||
"() => document.documentElement.scrollWidth > document.documentElement.clientWidth + 1"
|
||||
)
|
||||
assert not overflow2, f"{label} detail overflow"
|
||||
page.screenshot(path=str(OUT / f"detail-{label}.png"), full_page=True)
|
||||
|
||||
# 打开抽屉
|
||||
page.click("[data-transfer-evidence]")
|
||||
page.wait_for_selector("#transferEvidenceDrawer.is-open", timeout=5000)
|
||||
page.wait_for_timeout(200)
|
||||
page.screenshot(path=str(OUT / f"drawer-{label}.png"), full_page=True)
|
||||
page.click("[data-close-transfer-evidence]")
|
||||
|
||||
browser.close()
|
||||
|
||||
hard = [e for e in console_errors if "Failed to load resource" not in e and "favicon" not in e]
|
||||
print("shots:", list(OUT.glob("*.png")))
|
||||
print("console_errors:", hard)
|
||||
if hard:
|
||||
raise SystemExit(1)
|
||||
print("OK")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,344 +0,0 @@
|
||||
"""Authentication, sessions, rate limiting and audit logging.
|
||||
|
||||
Passwords are hashed with PBKDF2-HMAC-SHA256 (stdlib ``hashlib.pbkdf2_hmac``)
|
||||
and per-user random salts; plaintext passwords are never stored or logged.
|
||||
Session tokens are random URL-safe strings; only their SHA-256 digest is
|
||||
persisted, so a database leak does not expose usable tokens. Every login
|
||||
attempt and every privileged action lands in ``audit_log``. The reasoning
|
||||
behind these choices is recorded in ``docs/decisions/003-auth.md``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import secrets
|
||||
import sqlite3
|
||||
import string
|
||||
|
||||
from .db import transaction, utc_now
|
||||
|
||||
|
||||
MIN_PASSWORD_LENGTH = 8
|
||||
PBKDF2_ITERATIONS = 260_000
|
||||
SESSION_TTL_HOURS = 8
|
||||
RATE_LIMIT_MAX_FAILURES = 5
|
||||
RATE_LIMIT_WINDOW_MINUTES = 10
|
||||
INITIAL_PASSWORD_LENGTH = 12
|
||||
|
||||
|
||||
def _env_flag(value: str | None) -> bool:
|
||||
"""Parse a yes/no style environment flag; blank/absent means False."""
|
||||
return (value or "").strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
# Ops switch for internal test environments: APP_LOGIN_RATE_LIMIT_DISABLED=1
|
||||
# turns off the login-failure lockout entirely. The default (unset) keeps the
|
||||
# production policy — 5 failures within 10 minutes lock the (账号, IP) pair.
|
||||
RATE_LIMIT_DISABLED = _env_flag(os.environ.get("APP_LOGIN_RATE_LIMIT_DISABLED"))
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
"""Hash ``password`` as ``pbkdf2_sha256$<iterations>$<salt_hex>$<hash_hex>``."""
|
||||
salt = secrets.token_bytes(16)
|
||||
digest = hashlib.pbkdf2_hmac(
|
||||
"sha256", password.encode("utf-8"), salt, PBKDF2_ITERATIONS
|
||||
)
|
||||
return f"pbkdf2_sha256${PBKDF2_ITERATIONS}${salt.hex()}${digest.hex()}"
|
||||
|
||||
|
||||
def verify_password(password: str, stored: str) -> bool:
|
||||
"""Constant-time check of ``password`` against a stored hash string."""
|
||||
try:
|
||||
scheme, iterations, salt_hex, hash_hex = stored.split("$")
|
||||
if scheme != "pbkdf2_sha256":
|
||||
return False
|
||||
salt = bytes.fromhex(salt_hex)
|
||||
expected = bytes.fromhex(hash_hex)
|
||||
digest = hashlib.pbkdf2_hmac(
|
||||
"sha256", password.encode("utf-8"), salt, int(iterations)
|
||||
)
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
return hmac.compare_digest(digest, expected)
|
||||
|
||||
|
||||
def generate_initial_password(exclude: str | None = None) -> str:
|
||||
"""Generate a 12-char initial password with upper, lower and digit chars.
|
||||
|
||||
When ``exclude`` is given, the result is guaranteed to differ from it
|
||||
(case-insensitive) so a fresh account never starts with a password equal
|
||||
to its own username.
|
||||
"""
|
||||
alphabet = string.ascii_letters + string.digits
|
||||
while True:
|
||||
password = "".join(
|
||||
secrets.choice(alphabet) for _ in range(INITIAL_PASSWORD_LENGTH)
|
||||
)
|
||||
if (
|
||||
any(char.isupper() for char in password)
|
||||
and any(char.islower() for char in password)
|
||||
and any(char.isdigit() for char in password)
|
||||
and (exclude is None or password.lower() != exclude.lower())
|
||||
):
|
||||
return password
|
||||
|
||||
|
||||
def validate_password_policy(password: str, username: str) -> str | None:
|
||||
"""Return an error message when ``password`` violates policy, else None."""
|
||||
if len(password) < MIN_PASSWORD_LENGTH:
|
||||
return f"密码长度至少为 {MIN_PASSWORD_LENGTH} 位。"
|
||||
if password.lower() == username.lower():
|
||||
return "密码不能与账号相同。"
|
||||
if not any(char.isalpha() for char in password) or not any(
|
||||
char.isdigit() for char in password
|
||||
):
|
||||
return "密码必须同时包含字母和数字。"
|
||||
return None
|
||||
|
||||
|
||||
def create_user(
|
||||
connection: sqlite3.Connection,
|
||||
username: str,
|
||||
password: str,
|
||||
role: str,
|
||||
company_id: int | None = None,
|
||||
must_change_password: bool = True,
|
||||
allow_unassigned: bool = False,
|
||||
) -> int:
|
||||
"""Create a user, enforcing the role/company binding rules. Returns the id."""
|
||||
username = username.strip()
|
||||
if not username:
|
||||
raise ValueError("用户名不能为空。")
|
||||
if role not in ("admin", "company"):
|
||||
raise ValueError("角色必须是 admin 或 company。")
|
||||
if role == "company":
|
||||
if company_id is None and not allow_unassigned:
|
||||
raise ValueError("公司账号必须绑定公司。")
|
||||
company = connection.execute(
|
||||
"SELECT id FROM companies WHERE id = ?", (company_id,)
|
||||
).fetchone()
|
||||
if company_id is not None and company is None:
|
||||
raise ValueError("绑定的公司不存在。")
|
||||
elif company_id is not None:
|
||||
raise ValueError("管理员账号不能绑定公司。")
|
||||
|
||||
now = utc_now()
|
||||
try:
|
||||
with connection:
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO users (
|
||||
username, password_hash, role, company_id,
|
||||
must_change_password, created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
username,
|
||||
hash_password(password),
|
||||
role,
|
||||
company_id,
|
||||
1 if must_change_password else 0,
|
||||
now,
|
||||
now,
|
||||
),
|
||||
)
|
||||
if role == 'company' and company_id is not None:
|
||||
connection.execute('INSERT INTO company_memberships(company_id,user_id,assigned_at) VALUES(?,?,?)',
|
||||
(company_id, cursor.lastrowid, now))
|
||||
except sqlite3.IntegrityError as exc:
|
||||
raise ValueError("用户名已存在。") from exc
|
||||
return int(cursor.lastrowid)
|
||||
|
||||
|
||||
def authenticate(
|
||||
connection: sqlite3.Connection, username: str, password: str, ip: str
|
||||
) -> tuple[sqlite3.Row | None, str | None]:
|
||||
"""Verify credentials; returns ``(user_row, None)`` or ``(None, reason)``.
|
||||
|
||||
``reason`` is one of ``rate_limited``, ``disabled``, ``bad_credentials``.
|
||||
Every non-rate-limited attempt is recorded in ``login_attempts`` and
|
||||
``audit_log``; the password itself is never stored anywhere.
|
||||
"""
|
||||
if not RATE_LIMIT_DISABLED:
|
||||
window_start = (
|
||||
datetime.now(timezone.utc) - timedelta(minutes=RATE_LIMIT_WINDOW_MINUTES)
|
||||
).isoformat()
|
||||
failures = connection.execute(
|
||||
"""
|
||||
SELECT COUNT(*) AS n FROM login_attempts
|
||||
WHERE username = ? AND ip = ? AND success = 0 AND created_at >= ?
|
||||
""",
|
||||
(username, ip, window_start),
|
||||
).fetchone()
|
||||
if failures["n"] >= RATE_LIMIT_MAX_FAILURES:
|
||||
return None, "rate_limited"
|
||||
|
||||
user = connection.execute(
|
||||
"SELECT * FROM users WHERE username = ?", (username,)
|
||||
).fetchone()
|
||||
|
||||
if user is not None and user["status"] == "disabled":
|
||||
_record_attempt(connection, username, ip, success=False)
|
||||
audit(
|
||||
connection,
|
||||
"login_failed",
|
||||
actor=user,
|
||||
detail="账号已停用",
|
||||
ip=ip,
|
||||
)
|
||||
return None, "disabled"
|
||||
|
||||
if user is None or not verify_password(password, user["password_hash"]):
|
||||
_record_attempt(connection, username, ip, success=False)
|
||||
audit(connection, "login_failed", actor=user, detail="账号或密码不正确", ip=ip)
|
||||
return None, "bad_credentials"
|
||||
|
||||
_record_attempt(connection, username, ip, success=True)
|
||||
audit(connection, "login_success", actor=user, ip=ip)
|
||||
return user, None
|
||||
|
||||
|
||||
def create_session(
|
||||
connection: sqlite3.Connection, user_id: int, ttl_hours: int = SESSION_TTL_HOURS
|
||||
) -> str:
|
||||
"""Create a session with absolute expiry; returns the raw token."""
|
||||
token = secrets.token_urlsafe(32)
|
||||
token_hash = hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
now = datetime.now(timezone.utc)
|
||||
purge_expired_sessions(connection)
|
||||
with connection:
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO sessions (token_hash, user_id, created_at, expires_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
token_hash,
|
||||
user_id,
|
||||
now.isoformat(),
|
||||
(now + timedelta(hours=ttl_hours)).isoformat(),
|
||||
),
|
||||
)
|
||||
return token
|
||||
|
||||
|
||||
def purge_expired_sessions(connection: sqlite3.Connection) -> int:
|
||||
"""Drop expired or revoked session rows so they do not accumulate."""
|
||||
now = utc_now()
|
||||
with connection:
|
||||
cursor = connection.execute(
|
||||
"DELETE FROM sessions WHERE expires_at <= ? OR revoked_at IS NOT NULL",
|
||||
(now,),
|
||||
)
|
||||
return int(cursor.rowcount or 0)
|
||||
|
||||
|
||||
def resolve_session(connection: sqlite3.Connection, token: str) -> sqlite3.Row | None:
|
||||
"""Return the user row for a live session token, else None.
|
||||
|
||||
Expired or revoked sessions and disabled users are all rejected.
|
||||
"""
|
||||
token_hash = hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
return connection.execute(
|
||||
"""
|
||||
SELECT u.*, s.id AS session_id
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = ?
|
||||
AND s.revoked_at IS NULL
|
||||
AND s.expires_at > ?
|
||||
AND u.status = 'active'
|
||||
""",
|
||||
(token_hash, utc_now()),
|
||||
).fetchone()
|
||||
|
||||
|
||||
def revoke_session(connection: sqlite3.Connection, token: str) -> None:
|
||||
token_hash = hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
with connection:
|
||||
connection.execute(
|
||||
"UPDATE sessions SET revoked_at = ? WHERE token_hash = ? AND revoked_at IS NULL",
|
||||
(utc_now(), token_hash),
|
||||
)
|
||||
|
||||
|
||||
def revoke_user_sessions(connection: sqlite3.Connection, user_id: int) -> None:
|
||||
with connection:
|
||||
connection.execute(
|
||||
"UPDATE sessions SET revoked_at = ? WHERE user_id = ? AND revoked_at IS NULL",
|
||||
(utc_now(), user_id),
|
||||
)
|
||||
|
||||
|
||||
def change_password(
|
||||
connection: sqlite3.Connection,
|
||||
user_id: int,
|
||||
old_password: str,
|
||||
new_password: str,
|
||||
) -> str | None:
|
||||
"""Change a user's password; returns an error message or None on success."""
|
||||
user = connection.execute(
|
||||
"SELECT * FROM users WHERE id = ?", (user_id,)
|
||||
).fetchone()
|
||||
if user is None:
|
||||
return "用户不存在。"
|
||||
if not verify_password(old_password, user["password_hash"]):
|
||||
return "原密码不正确。"
|
||||
error = validate_password_policy(new_password, user["username"])
|
||||
if error is not None:
|
||||
return error
|
||||
with connection:
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE users
|
||||
SET password_hash = ?, must_change_password = 0, updated_at = ?
|
||||
WHERE id = ?
|
||||
""",
|
||||
(hash_password(new_password), utc_now(), user_id),
|
||||
)
|
||||
audit(connection, "password_change", actor=user, target=f"user:{user_id}")
|
||||
return None
|
||||
|
||||
|
||||
def audit(
|
||||
connection: sqlite3.Connection,
|
||||
action: str,
|
||||
actor: sqlite3.Row | None = None,
|
||||
target: str | None = None,
|
||||
detail: str | None = None,
|
||||
ip: str | None = None,
|
||||
) -> None:
|
||||
"""Append an audit log entry. Never pass passwords in ``detail``."""
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO audit_log (
|
||||
actor_user_id, actor_username, action, target, detail, ip, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
actor["id"] if actor is not None else None,
|
||||
actor["username"] if actor is not None else None,
|
||||
action,
|
||||
target,
|
||||
detail,
|
||||
ip,
|
||||
utc_now(),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _record_attempt(
|
||||
connection: sqlite3.Connection, username: str, ip: str, success: bool
|
||||
) -> None:
|
||||
with connection:
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO login_attempts (username, ip, success, created_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
""",
|
||||
(username, ip, 1 if success else 0, utc_now()),
|
||||
)
|
||||
@@ -1,974 +0,0 @@
|
||||
"""Calculation window: start date, opening balances, coverage gaps and balances."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from decimal import Decimal, InvalidOperation
|
||||
import json
|
||||
import sqlite3
|
||||
|
||||
from .db import transaction, utc_now
|
||||
from . import auth, master_data, matching
|
||||
|
||||
|
||||
SETTING_START_DATE = "calculation_start_date"
|
||||
OPENING_STATUSES = ("draft", "confirmed", "superseded", "void")
|
||||
GAP_KINDS = ("head", "mid", "tail")
|
||||
GAP_STATUSES = ("open", "closed_attested")
|
||||
ATTESTATION_STATUSES = ("pending", "approved", "rejected")
|
||||
|
||||
|
||||
class LockedError(ValueError):
|
||||
"""Start date cannot change after a period is closed."""
|
||||
|
||||
|
||||
class ConflictError(ValueError):
|
||||
"""Revision or state conflict."""
|
||||
|
||||
|
||||
def utc_today() -> str:
|
||||
return datetime.now(timezone.utc).date().isoformat()
|
||||
|
||||
|
||||
def _parse_decimal(value: object) -> Decimal:
|
||||
try:
|
||||
return Decimal(str(value))
|
||||
except (InvalidOperation, TypeError):
|
||||
raise ValueError("金额格式无效。") from None
|
||||
|
||||
|
||||
def normalize_pair(company_a: int, company_b: int) -> tuple[int, int]:
|
||||
if company_a == company_b:
|
||||
raise ValueError("两家公司不能相同。")
|
||||
return (company_a, company_b) if company_a < company_b else (company_b, company_a)
|
||||
|
||||
|
||||
def signed_from_viewer(viewer_id: int, low_id: int, high_id: int, amount: Decimal) -> Decimal:
|
||||
return amount if viewer_id == low_id else -amount
|
||||
|
||||
|
||||
def get_setting(connection: sqlite3.Connection, key: str) -> str | None:
|
||||
row = connection.execute(
|
||||
"SELECT value FROM system_settings WHERE key = ?", (key,)
|
||||
).fetchone()
|
||||
return row["value"] if row is not None else None
|
||||
|
||||
|
||||
def get_calculation_start_date(connection: sqlite3.Connection) -> str | None:
|
||||
return get_setting(connection, SETTING_START_DATE)
|
||||
|
||||
|
||||
def has_closed_periods(connection: sqlite3.Connection) -> bool:
|
||||
row = connection.execute("SELECT 1 FROM closed_periods LIMIT 1").fetchone()
|
||||
return row is not None
|
||||
|
||||
|
||||
def is_start_date_locked(connection: sqlite3.Connection) -> bool:
|
||||
return has_closed_periods(connection)
|
||||
|
||||
|
||||
def set_calculation_start_date(
|
||||
connection: sqlite3.Connection,
|
||||
start_date: str,
|
||||
reason: str,
|
||||
actor: sqlite3.Row,
|
||||
) -> dict[str, object]:
|
||||
start_date = master_data.validate_date(start_date, "起算日", required=True)
|
||||
reason = str(reason or "").strip()
|
||||
if len(reason) < 2:
|
||||
raise ValueError("修改起算日必须填写原因。")
|
||||
if is_start_date_locked(connection):
|
||||
raise LockedError("已有结账月份,起算日已锁定。")
|
||||
before = get_calculation_start_date(connection)
|
||||
now = utc_now()
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO system_settings (key, value, updated_at, updated_by)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(key) DO UPDATE SET
|
||||
value = excluded.value,
|
||||
updated_at = excluded.updated_at,
|
||||
updated_by = excluded.updated_by
|
||||
""",
|
||||
(SETTING_START_DATE, start_date, now, actor["id"]),
|
||||
)
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO system_setting_changes (
|
||||
key, before_value, after_value,
|
||||
actor_user_id, actor_username, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
SETTING_START_DATE,
|
||||
before,
|
||||
start_date,
|
||||
actor["id"],
|
||||
actor["username"],
|
||||
now,
|
||||
),
|
||||
)
|
||||
master_data.record_change(
|
||||
connection,
|
||||
"system_setting",
|
||||
0,
|
||||
"update_start_date",
|
||||
{"calculation_start_date": before},
|
||||
{"calculation_start_date": start_date},
|
||||
reason,
|
||||
actor,
|
||||
)
|
||||
recalculate_coverage_gaps(connection)
|
||||
return {
|
||||
"calculation_start_date": start_date,
|
||||
"locked": False,
|
||||
"previous": before,
|
||||
}
|
||||
|
||||
|
||||
def start_date_payload(connection: sqlite3.Connection) -> dict[str, object]:
|
||||
return {
|
||||
"calculation_start_date": get_calculation_start_date(connection),
|
||||
"locked": is_start_date_locked(connection),
|
||||
}
|
||||
|
||||
|
||||
def _current_opening_revision(
|
||||
connection: sqlite3.Connection, low_id: int, high_id: int
|
||||
) -> sqlite3.Row | None:
|
||||
return connection.execute(
|
||||
"""
|
||||
SELECT * FROM opening_balance_revisions
|
||||
WHERE company_id_low = ? AND company_id_high = ?
|
||||
AND status IN ('draft', 'confirmed')
|
||||
ORDER BY revision DESC
|
||||
LIMIT 1
|
||||
""",
|
||||
(low_id, high_id),
|
||||
).fetchone()
|
||||
|
||||
|
||||
def _next_revision(connection: sqlite3.Connection, low_id: int, high_id: int) -> int:
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT MAX(revision) AS max_rev FROM opening_balance_revisions
|
||||
WHERE company_id_low = ? AND company_id_high = ?
|
||||
""",
|
||||
(low_id, high_id),
|
||||
).fetchone()
|
||||
return int(row["max_rev"] or 0) + 1
|
||||
|
||||
|
||||
def create_opening_balance(
|
||||
connection: sqlite3.Connection,
|
||||
company_a: int,
|
||||
company_b: int,
|
||||
amount: object,
|
||||
reason: str,
|
||||
actor: sqlite3.Row,
|
||||
*,
|
||||
currency: str = "CNY",
|
||||
viewer_company_id: int | None = None,
|
||||
) -> dict[str, object]:
|
||||
low_id, high_id = normalize_pair(company_a, company_b)
|
||||
decimal_amount = _parse_decimal(amount)
|
||||
if viewer_company_id is not None and viewer_company_id == high_id:
|
||||
decimal_amount = -decimal_amount
|
||||
reason = str(reason or "").strip()
|
||||
if len(reason) < 2:
|
||||
raise ValueError("录入期初必须填写原因。")
|
||||
existing = _current_opening_revision(connection, low_id, high_id)
|
||||
if existing is not None and existing["status"] == "draft":
|
||||
raise ConflictError("该公司对已有待确认期初,请先确认或作废后再录入。")
|
||||
if existing is not None and existing["status"] == "confirmed":
|
||||
raise ConflictError("该对公司已有确认期初,请使用修订。")
|
||||
revision = _next_revision(connection, low_id, high_id)
|
||||
now = utc_now()
|
||||
with transaction(connection):
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO opening_balance_revisions (
|
||||
company_id_low, company_id_high, amount, currency, revision,
|
||||
status, reason, actor_user_id, actor_username, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, 'draft', ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
low_id,
|
||||
high_id,
|
||||
str(decimal_amount),
|
||||
currency,
|
||||
revision,
|
||||
reason,
|
||||
actor["id"],
|
||||
actor["username"],
|
||||
now,
|
||||
),
|
||||
)
|
||||
row_id = int(cursor.lastrowid)
|
||||
master_data.record_change(
|
||||
connection,
|
||||
"opening_balance",
|
||||
row_id,
|
||||
"create_draft",
|
||||
None,
|
||||
{"company_id_low": low_id, "company_id_high": high_id, "amount": str(decimal_amount)},
|
||||
reason,
|
||||
actor,
|
||||
)
|
||||
return opening_balance_payload(connection, row_id)
|
||||
|
||||
|
||||
def confirm_opening_balance(
|
||||
connection: sqlite3.Connection,
|
||||
revision_id: int,
|
||||
reason: str,
|
||||
actor: sqlite3.Row,
|
||||
) -> dict[str, object]:
|
||||
row = connection.execute(
|
||||
"SELECT * FROM opening_balance_revisions WHERE id = ?", (revision_id,)
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise ValueError("期初记录不存在。")
|
||||
if row["status"] != "draft":
|
||||
raise ConflictError("只能确认待确认状态的期初。")
|
||||
reason = str(reason or "").strip()
|
||||
if len(reason) < 2:
|
||||
raise ValueError("确认期初必须填写原因。")
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE opening_balance_revisions SET status = 'confirmed', reason = ?
|
||||
WHERE id = ?
|
||||
""",
|
||||
(reason, revision_id),
|
||||
)
|
||||
master_data.record_change(
|
||||
connection,
|
||||
"opening_balance",
|
||||
revision_id,
|
||||
"confirm",
|
||||
{"status": "draft"},
|
||||
{"status": "confirmed"},
|
||||
reason,
|
||||
actor,
|
||||
)
|
||||
return opening_balance_payload(connection, revision_id)
|
||||
|
||||
|
||||
def revise_opening_balance(
|
||||
connection: sqlite3.Connection,
|
||||
revision_id: int,
|
||||
amount: object,
|
||||
reason: str,
|
||||
actor: sqlite3.Row,
|
||||
) -> dict[str, object]:
|
||||
row = connection.execute(
|
||||
"SELECT * FROM opening_balance_revisions WHERE id = ?", (revision_id,)
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise ValueError("期初记录不存在。")
|
||||
if row["status"] != "confirmed":
|
||||
raise ConflictError("只能修订已确认期初。")
|
||||
decimal_amount = _parse_decimal(amount)
|
||||
reason = str(reason or "").strip()
|
||||
if len(reason) < 2:
|
||||
raise ValueError("修订期初必须填写原因。")
|
||||
low_id = int(row["company_id_low"])
|
||||
high_id = int(row["company_id_high"])
|
||||
revision = _next_revision(connection, low_id, high_id)
|
||||
now = utc_now()
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"UPDATE opening_balance_revisions SET status = 'superseded' WHERE id = ?",
|
||||
(revision_id,),
|
||||
)
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO opening_balance_revisions (
|
||||
company_id_low, company_id_high, amount, currency, revision,
|
||||
status, reason, actor_user_id, actor_username, supersedes_id, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, 'draft', ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
low_id,
|
||||
high_id,
|
||||
str(decimal_amount),
|
||||
row["currency"],
|
||||
revision,
|
||||
reason,
|
||||
actor["id"],
|
||||
actor["username"],
|
||||
revision_id,
|
||||
now,
|
||||
),
|
||||
)
|
||||
new_id = int(cursor.lastrowid)
|
||||
master_data.record_change(
|
||||
connection,
|
||||
"opening_balance",
|
||||
new_id,
|
||||
"revise",
|
||||
{"amount": row["amount"], "revision_id": revision_id},
|
||||
{"amount": str(decimal_amount), "revision_id": new_id},
|
||||
reason,
|
||||
actor,
|
||||
)
|
||||
return opening_balance_payload(connection, new_id)
|
||||
|
||||
|
||||
def void_opening_balance(
|
||||
connection: sqlite3.Connection,
|
||||
revision_id: int,
|
||||
reason: str,
|
||||
actor: sqlite3.Row,
|
||||
) -> dict[str, object]:
|
||||
row = connection.execute(
|
||||
"SELECT * FROM opening_balance_revisions WHERE id = ?", (revision_id,)
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise ValueError("期初记录不存在。")
|
||||
if row["status"] not in ("draft", "confirmed"):
|
||||
raise ConflictError("该期初已作废或已被替代。")
|
||||
reason = str(reason or "").strip()
|
||||
if len(reason) < 2:
|
||||
raise ValueError("作废期初必须填写原因。")
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"UPDATE opening_balance_revisions SET status = 'void', reason = ? WHERE id = ?",
|
||||
(reason, revision_id),
|
||||
)
|
||||
master_data.record_change(
|
||||
connection,
|
||||
"opening_balance",
|
||||
revision_id,
|
||||
"void",
|
||||
{"status": row["status"]},
|
||||
{"status": "void"},
|
||||
reason,
|
||||
actor,
|
||||
)
|
||||
return opening_balance_payload(connection, revision_id)
|
||||
|
||||
|
||||
def opening_balance_payload(connection: sqlite3.Connection, revision_id: int) -> dict[str, object]:
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT r.*, cl.name AS company_low_name, ch.name AS company_high_name
|
||||
FROM opening_balance_revisions r
|
||||
JOIN companies cl ON cl.id = r.company_id_low
|
||||
JOIN companies ch ON ch.id = r.company_id_high
|
||||
WHERE r.id = ?
|
||||
""",
|
||||
(revision_id,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise ValueError("期初记录不存在。")
|
||||
amount = _parse_decimal(row["amount"])
|
||||
return {
|
||||
"id": row["id"],
|
||||
"company_id_low": row["company_id_low"],
|
||||
"company_id_high": row["company_id_high"],
|
||||
"company_low_name": row["company_low_name"],
|
||||
"company_high_name": row["company_high_name"],
|
||||
"amount": str(amount),
|
||||
"currency": row["currency"],
|
||||
"revision": row["revision"],
|
||||
"status": row["status"],
|
||||
"reason": row["reason"],
|
||||
"actor_username": row["actor_username"],
|
||||
"supersedes_id": row["supersedes_id"],
|
||||
"created_at": row["created_at"],
|
||||
"direction_low": "receivable" if amount >= 0 else "payable",
|
||||
}
|
||||
|
||||
|
||||
def list_opening_balances(connection: sqlite3.Connection) -> list[dict[str, object]]:
|
||||
rows = connection.execute(
|
||||
"""
|
||||
SELECT r.id FROM opening_balance_revisions r
|
||||
JOIN (
|
||||
SELECT company_id_low, company_id_high, MAX(revision) AS max_rev
|
||||
FROM opening_balance_revisions
|
||||
WHERE status IN ('draft', 'confirmed', 'void')
|
||||
GROUP BY company_id_low, company_id_high
|
||||
) latest ON latest.company_id_low = r.company_id_low
|
||||
AND latest.company_id_high = r.company_id_high
|
||||
AND latest.max_rev = r.revision
|
||||
WHERE r.status IN ('draft', 'confirmed', 'void')
|
||||
ORDER BY r.company_id_low, r.company_id_high
|
||||
"""
|
||||
).fetchall()
|
||||
return [opening_balance_payload(connection, row["id"]) for row in rows]
|
||||
|
||||
|
||||
def confirmed_opening_amount(
|
||||
connection: sqlite3.Connection, low_id: int, high_id: int
|
||||
) -> Decimal | None:
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT amount FROM opening_balance_revisions
|
||||
WHERE company_id_low = ? AND company_id_high = ? AND status = 'confirmed'
|
||||
ORDER BY revision DESC LIMIT 1
|
||||
""",
|
||||
(low_id, high_id),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
return _parse_decimal(row["amount"])
|
||||
|
||||
|
||||
def _date_add(day: str, delta: int) -> str:
|
||||
return (date.fromisoformat(day) + timedelta(days=delta)).isoformat()
|
||||
|
||||
|
||||
def _merge_intervals(intervals: list[tuple[str, str]]) -> list[tuple[str, str]]:
|
||||
if not intervals:
|
||||
return []
|
||||
sorted_intervals = sorted(intervals, key=lambda item: item[0])
|
||||
merged = [sorted_intervals[0]]
|
||||
for start, end in sorted_intervals[1:]:
|
||||
last_start, last_end = merged[-1]
|
||||
if date.fromisoformat(start) <= date.fromisoformat(_date_add(last_end, 1)):
|
||||
if date.fromisoformat(end) > date.fromisoformat(last_end):
|
||||
merged[-1] = (last_start, end)
|
||||
else:
|
||||
merged.append((start, end))
|
||||
return merged
|
||||
|
||||
|
||||
def _account_coverage_intervals(
|
||||
connection: sqlite3.Connection, account: sqlite3.Row
|
||||
) -> list[tuple[str, str]]:
|
||||
rows = connection.execute(
|
||||
"""
|
||||
SELECT MIN(substr(r.transaction_at, 1, 10)) AS interval_start,
|
||||
MAX(substr(r.transaction_at, 1, 10)) AS interval_end
|
||||
FROM source_rows r
|
||||
JOIN sheet_batches s ON s.id = r.sheet_batch_id
|
||||
JOIN sheet_reviews rv ON rv.sheet_batch_id = s.id AND rv.review_status = 'confirmed'
|
||||
JOIN import_batches b ON b.id = s.import_batch_id
|
||||
WHERE b.upload_bank_account_id = ?
|
||||
OR r.own_account = ?
|
||||
GROUP BY s.id
|
||||
ORDER BY interval_start
|
||||
""",
|
||||
(account["id"], account["account_number"]),
|
||||
).fetchall()
|
||||
return [
|
||||
(row["interval_start"], row["interval_end"])
|
||||
for row in rows
|
||||
if row["interval_start"] and row["interval_end"]
|
||||
]
|
||||
|
||||
|
||||
def _account_transaction_dates(
|
||||
connection: sqlite3.Connection, account: sqlite3.Row
|
||||
) -> list[str]:
|
||||
intervals = _account_coverage_intervals(connection, account)
|
||||
dates: list[str] = []
|
||||
for start, end in intervals:
|
||||
current = date.fromisoformat(start)
|
||||
end_day = date.fromisoformat(end)
|
||||
while current <= end_day:
|
||||
dates.append(current.isoformat())
|
||||
current += timedelta(days=1)
|
||||
return dates
|
||||
|
||||
|
||||
def _dates_to_intervals(dates: list[str]) -> list[tuple[str, str]]:
|
||||
if not dates:
|
||||
return []
|
||||
intervals: list[tuple[str, str]] = []
|
||||
start = dates[0]
|
||||
prev = dates[0]
|
||||
for current in dates[1:]:
|
||||
if date.fromisoformat(current) == date.fromisoformat(prev) + timedelta(days=1):
|
||||
prev = current
|
||||
continue
|
||||
intervals.append((start, prev))
|
||||
start = current
|
||||
prev = current
|
||||
intervals.append((start, prev))
|
||||
return intervals
|
||||
|
||||
|
||||
def _detect_gaps(
|
||||
required_start: str,
|
||||
required_end: str,
|
||||
covered: list[tuple[str, str]],
|
||||
) -> list[tuple[str, str, str]]:
|
||||
if required_start > required_end:
|
||||
return []
|
||||
gaps: list[tuple[str, str, str]] = []
|
||||
if not covered:
|
||||
gaps.append((required_start, required_end, "head"))
|
||||
return gaps
|
||||
merged = _merge_intervals(covered)
|
||||
first_start, first_end = merged[0]
|
||||
if required_start < first_start:
|
||||
gaps.append((required_start, _date_add(first_start, -1), "head"))
|
||||
for index in range(len(merged) - 1):
|
||||
_, left_end = merged[index]
|
||||
right_start, _ = merged[index + 1]
|
||||
gap_start = _date_add(left_end, 1)
|
||||
gap_end = _date_add(right_start, -1)
|
||||
if gap_start <= gap_end:
|
||||
gaps.append((gap_start, gap_end, "mid"))
|
||||
last_start, last_end = merged[-1]
|
||||
tail_start = _date_add(last_end, 1)
|
||||
gap_from = max(tail_start, required_start)
|
||||
if gap_from <= required_end:
|
||||
kind = "tail" if last_end >= required_start else "head"
|
||||
gaps.append((gap_from, required_end, kind))
|
||||
return gaps
|
||||
|
||||
|
||||
def detect_account_gaps(
|
||||
connection: sqlite3.Connection,
|
||||
account: sqlite3.Row,
|
||||
*,
|
||||
start_date: str | None,
|
||||
today: str | None = None,
|
||||
) -> list[tuple[str, str, str]]:
|
||||
if account["status"] != "active":
|
||||
return []
|
||||
today = today or utc_today()
|
||||
effective_from = account["effective_from"] or start_date or today
|
||||
effective_to = account["effective_to"] or today
|
||||
required_start = max(filter(None, [start_date, effective_from]))
|
||||
required_end = min(today, effective_to)
|
||||
if not master_data.is_usable(account, required_start):
|
||||
return []
|
||||
intervals = _account_coverage_intervals(connection, account)
|
||||
return _detect_gaps(required_start, required_end, intervals)
|
||||
|
||||
|
||||
def recalculate_coverage_gaps(connection: sqlite3.Connection) -> int:
|
||||
start_date = get_calculation_start_date(connection)
|
||||
today = utc_today()
|
||||
accounts = connection.execute(
|
||||
"SELECT * FROM bank_accounts WHERE status = 'active'"
|
||||
).fetchall()
|
||||
rebuilt = 0
|
||||
with transaction(connection):
|
||||
for account in accounts:
|
||||
connection.execute(
|
||||
"""
|
||||
DELETE FROM coverage_gaps
|
||||
WHERE bank_account_id = ? AND status = 'open'
|
||||
""",
|
||||
(account["id"],),
|
||||
)
|
||||
for gap_start, gap_end, gap_kind in detect_account_gaps(
|
||||
connection, account, start_date=start_date, today=today
|
||||
):
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO coverage_gaps (
|
||||
bank_account_id, gap_start, gap_end, gap_kind,
|
||||
status, first_detected_at
|
||||
) VALUES (?, ?, ?, ?, 'open', ?)
|
||||
ON CONFLICT(bank_account_id, gap_start, gap_end) DO UPDATE SET
|
||||
gap_kind = excluded.gap_kind,
|
||||
status = CASE coverage_gaps.status
|
||||
WHEN 'closed_attested' THEN 'closed_attested'
|
||||
ELSE 'open'
|
||||
END
|
||||
""",
|
||||
(account["id"], gap_start, gap_end, gap_kind, utc_now()),
|
||||
)
|
||||
rebuilt += 1
|
||||
return rebuilt
|
||||
|
||||
|
||||
def coverage_gap_payload(connection: sqlite3.Connection, row: sqlite3.Row) -> dict[str, object]:
|
||||
account = master_data.get_account(connection, row["bank_account_id"])
|
||||
if account is None:
|
||||
raise ValueError("账户不存在。")
|
||||
company = connection.execute(
|
||||
"SELECT name FROM companies WHERE id = ?", (account["company_id"],)
|
||||
).fetchone()
|
||||
start = date.fromisoformat(row["gap_start"])
|
||||
end = date.fromisoformat(row["gap_end"])
|
||||
gap_days = (end - start).days + 1
|
||||
pending = connection.execute(
|
||||
"""
|
||||
SELECT id FROM no_business_attestations
|
||||
WHERE bank_account_id = ?
|
||||
AND gap_start = ? AND gap_end = ?
|
||||
AND status = 'pending'
|
||||
ORDER BY id DESC LIMIT 1
|
||||
""",
|
||||
(row["bank_account_id"], row["gap_start"], row["gap_end"]),
|
||||
).fetchone()
|
||||
return {
|
||||
"id": row["id"],
|
||||
"bank_account_id": row["bank_account_id"],
|
||||
"company_id": account["company_id"],
|
||||
"company_name": company["name"] if company else None,
|
||||
"account_number_masked": master_data.mask_account_number(account["account_number"]),
|
||||
"gap_start": row["gap_start"],
|
||||
"gap_end": row["gap_end"],
|
||||
"gap_kind": row["gap_kind"],
|
||||
"gap_days": gap_days,
|
||||
"day_count": gap_days,
|
||||
"status": row["status"],
|
||||
"first_detected_at": row["first_detected_at"],
|
||||
"pending_attestation_id": pending["id"] if pending else None,
|
||||
}
|
||||
|
||||
|
||||
def list_coverage_gaps(
|
||||
connection: sqlite3.Connection,
|
||||
*,
|
||||
company_id: int | None = None,
|
||||
status: str | None = None,
|
||||
) -> list[dict[str, object]]:
|
||||
clauses: list[str] = []
|
||||
params: list[object] = []
|
||||
if company_id is not None:
|
||||
clauses.append("ba.company_id = ?")
|
||||
params.append(company_id)
|
||||
if status is not None:
|
||||
clauses.append("g.status = ?")
|
||||
params.append(status)
|
||||
where = f"WHERE {' AND '.join(clauses)}" if clauses else ""
|
||||
rows = connection.execute(
|
||||
f"""
|
||||
SELECT g.* FROM coverage_gaps g
|
||||
JOIN bank_accounts ba ON ba.id = g.bank_account_id
|
||||
{where}
|
||||
ORDER BY g.gap_start, g.bank_account_id
|
||||
""",
|
||||
params,
|
||||
).fetchall()
|
||||
return [coverage_gap_payload(connection, row) for row in rows]
|
||||
|
||||
|
||||
def submit_no_business_attestation(
|
||||
connection: sqlite3.Connection,
|
||||
*,
|
||||
company_id: int,
|
||||
bank_account_id: int,
|
||||
gap_start: str,
|
||||
gap_end: str,
|
||||
reason: str,
|
||||
evidence: str | None,
|
||||
actor: sqlite3.Row,
|
||||
) -> dict[str, object]:
|
||||
gap_start = master_data.validate_date(gap_start, "断档起始日", required=True)
|
||||
gap_end = master_data.validate_date(gap_end, "断档结束日", required=True)
|
||||
if gap_start > gap_end:
|
||||
raise ValueError("断档起始日不能晚于结束日。")
|
||||
reason = str(reason or "").strip()
|
||||
if len(reason) < 5:
|
||||
raise ValueError("无业务说明至少 5 个字符。")
|
||||
account = master_data.get_account(connection, bank_account_id)
|
||||
if account["company_id"] != company_id:
|
||||
raise ValueError("只能为本公司账户提交说明。")
|
||||
now = utc_now()
|
||||
with transaction(connection):
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO no_business_attestations (
|
||||
bank_account_id, gap_start, gap_end, reason, evidence,
|
||||
submitted_by, company_id, status, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?)
|
||||
""",
|
||||
(
|
||||
bank_account_id,
|
||||
gap_start,
|
||||
gap_end,
|
||||
reason,
|
||||
evidence,
|
||||
actor["id"],
|
||||
company_id,
|
||||
now,
|
||||
),
|
||||
)
|
||||
attestation_id = int(cursor.lastrowid)
|
||||
auth.audit(
|
||||
connection,
|
||||
"attestation_submit",
|
||||
actor=actor,
|
||||
target=f"attestation:{attestation_id}",
|
||||
detail=f"account:{bank_account_id};gap:{gap_start}..{gap_end}",
|
||||
)
|
||||
return attestation_payload(connection, attestation_id)
|
||||
|
||||
|
||||
def review_no_business_attestation(
|
||||
connection: sqlite3.Connection,
|
||||
attestation_id: int,
|
||||
decision: str,
|
||||
review_reason: str,
|
||||
actor: sqlite3.Row,
|
||||
) -> dict[str, object]:
|
||||
row = connection.execute(
|
||||
"SELECT * FROM no_business_attestations WHERE id = ?", (attestation_id,)
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise ValueError("无业务说明不存在。")
|
||||
if row["status"] != "pending":
|
||||
raise ConflictError("该说明已审核。")
|
||||
review_reason = str(review_reason or "").strip()
|
||||
if decision not in ("approve", "reject"):
|
||||
raise ValueError("审核决定无效。")
|
||||
if len(review_reason) < 2:
|
||||
raise ValueError("审核必须填写理由。")
|
||||
status = "approved" if decision == "approve" else "rejected"
|
||||
now = utc_now()
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE no_business_attestations
|
||||
SET status = ?, reviewed_by = ?, reviewed_at = ?, review_reason = ?
|
||||
WHERE id = ?
|
||||
""",
|
||||
(status, actor["id"], now, review_reason, attestation_id),
|
||||
)
|
||||
if status == "approved":
|
||||
# Exact match first so the attested row survives recalculate's
|
||||
# "DELETE ... status='open'" and stays closed_attested.
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE coverage_gaps
|
||||
SET status = 'closed_attested'
|
||||
WHERE bank_account_id = ?
|
||||
AND gap_start = ? AND gap_end = ?
|
||||
""",
|
||||
(row["bank_account_id"], row["gap_start"], row["gap_end"]),
|
||||
)
|
||||
recalculate_coverage_gaps(connection)
|
||||
if status == "approved":
|
||||
# Overlap match: if recalculate shifts boundaries, still close
|
||||
# any open gap that intersects the attested interval.
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE coverage_gaps
|
||||
SET status = 'closed_attested'
|
||||
WHERE bank_account_id = ?
|
||||
AND status = 'open'
|
||||
AND gap_start <= ?
|
||||
AND gap_end >= ?
|
||||
""",
|
||||
(row["bank_account_id"], row["gap_end"], row["gap_start"]),
|
||||
)
|
||||
auth.audit(
|
||||
connection,
|
||||
f"attestation_{decision}",
|
||||
actor=actor,
|
||||
target=f"attestation:{attestation_id}",
|
||||
detail=review_reason,
|
||||
)
|
||||
return attestation_payload(connection, attestation_id)
|
||||
|
||||
|
||||
def attestation_payload(connection: sqlite3.Connection, attestation_id: int) -> dict[str, object]:
|
||||
row = connection.execute(
|
||||
"SELECT * FROM no_business_attestations WHERE id = ?", (attestation_id,)
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise ValueError("无业务说明不存在。")
|
||||
account = master_data.get_account(connection, row["bank_account_id"])
|
||||
if account is None:
|
||||
raise ValueError("账户不存在。")
|
||||
return {
|
||||
"id": row["id"],
|
||||
"bank_account_id": row["bank_account_id"],
|
||||
"company_id": row["company_id"],
|
||||
"gap_start": row["gap_start"],
|
||||
"gap_end": row["gap_end"],
|
||||
"reason": row["reason"],
|
||||
"evidence": row["evidence"],
|
||||
"status": row["status"],
|
||||
"review_reason": row["review_reason"],
|
||||
"reviewed_at": row["reviewed_at"],
|
||||
"created_at": row["created_at"],
|
||||
"account_number_masked": master_data.mask_account_number(account["account_number"]),
|
||||
}
|
||||
|
||||
|
||||
def list_change_log(connection: sqlite3.Connection, limit: int = 100) -> list[dict[str, object]]:
|
||||
rows = connection.execute(
|
||||
"""
|
||||
SELECT * FROM master_data_changes
|
||||
WHERE entity_type IN ('system_setting', 'opening_balance')
|
||||
ORDER BY id DESC LIMIT ?
|
||||
""",
|
||||
(limit,),
|
||||
).fetchall()
|
||||
items: list[dict[str, object]] = []
|
||||
for row in rows:
|
||||
before = json.loads(row["before_json"]) if row["before_json"] else None
|
||||
after = json.loads(row["after_json"]) if row["after_json"] else None
|
||||
target = "起算日"
|
||||
if row["entity_type"] == "opening_balance":
|
||||
target = f"期初 #{row['entity_id']}"
|
||||
items.append(
|
||||
{
|
||||
"id": row["id"],
|
||||
"created_at": row["created_at"],
|
||||
"actor_username": row["actor_username"],
|
||||
"action": row["action"],
|
||||
"target": target,
|
||||
"before": before,
|
||||
"after": after,
|
||||
"reason": row["reason"],
|
||||
}
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
def _pair_net_change(
|
||||
connection: sqlite3.Connection,
|
||||
viewer_id: int,
|
||||
counterparty_id: int,
|
||||
*,
|
||||
cutoff: str | None,
|
||||
start_date: str | None,
|
||||
) -> Decimal:
|
||||
cutoff_where = ""
|
||||
params: list[object] = [viewer_id, counterparty_id, counterparty_id, viewer_id]
|
||||
if cutoff:
|
||||
cutoff_where = "AND substr(d.effective_at, 1, 10) <= ?"
|
||||
params.append(cutoff)
|
||||
start_where = ""
|
||||
if start_date:
|
||||
start_where = "AND substr(d.effective_at, 1, 10) >= ?"
|
||||
params.append(start_date)
|
||||
rows = connection.execute(
|
||||
f"""
|
||||
SELECT d.amount, payer.company_id AS payer_id, payee.company_id AS payee_id
|
||||
FROM eligible_intercompany_events e
|
||||
JOIN transfer_match_decisions d ON d.id = e.decision_id
|
||||
JOIN transfer_decision_participants payer ON payer.decision_id = d.id AND payer.role = 'payer'
|
||||
JOIN transfer_decision_participants payee ON payee.decision_id = d.id AND payee.role = 'payee'
|
||||
WHERE (
|
||||
(payer.company_id = ? AND payee.company_id = ?)
|
||||
OR (payer.company_id = ? AND payee.company_id = ?)
|
||||
)
|
||||
{cutoff_where}
|
||||
{start_where}
|
||||
""",
|
||||
params,
|
||||
).fetchall()
|
||||
# 站在本公司视角:正数=应收方向。转出/垫付(payer)使应收增加。
|
||||
# 与 company_transfers.net = outflow − inflow 及页面文案口径一致。
|
||||
total = Decimal("0")
|
||||
for row in rows:
|
||||
amount = _parse_decimal(row["amount"])
|
||||
if row["payer_id"] == viewer_id:
|
||||
total += amount
|
||||
elif row["payee_id"] == viewer_id:
|
||||
total -= amount
|
||||
return total
|
||||
|
||||
|
||||
def pair_has_confirmed_opening(
|
||||
connection: sqlite3.Connection, company_a: int, company_b: int
|
||||
) -> bool:
|
||||
low_id, high_id = normalize_pair(company_a, company_b)
|
||||
return confirmed_opening_amount(connection, low_id, high_id) is not None
|
||||
|
||||
|
||||
def compute_pair_balance(
|
||||
connection: sqlite3.Connection,
|
||||
viewer_id: int,
|
||||
counterparty_id: int,
|
||||
*,
|
||||
cutoff: str | None = None,
|
||||
) -> dict[str, object]:
|
||||
cutoff = cutoff or utc_today()
|
||||
cutoff = master_data.validate_date(cutoff, "截止日", required=True)
|
||||
start_date = get_calculation_start_date(connection)
|
||||
low_id, high_id = normalize_pair(viewer_id, counterparty_id)
|
||||
opening_amount: Decimal | None = None
|
||||
if start_date and pair_has_confirmed_opening(connection, viewer_id, counterparty_id):
|
||||
stored = confirmed_opening_amount(connection, low_id, high_id)
|
||||
assert stored is not None
|
||||
opening_amount = signed_from_viewer(viewer_id, low_id, high_id, stored)
|
||||
net_change = _pair_net_change(
|
||||
connection,
|
||||
viewer_id,
|
||||
counterparty_id,
|
||||
cutoff=cutoff,
|
||||
start_date=start_date,
|
||||
)
|
||||
unresolved = matching.unresolved_amounts(connection, viewer_id, cutoff=cutoff)
|
||||
pending_total = Decimal("0")
|
||||
for row in unresolved:
|
||||
pending_total += _parse_decimal(row["amount"] or "0")
|
||||
basis = "full" if opening_amount is not None and start_date else "net_change"
|
||||
payload: dict[str, object] = {
|
||||
"viewer_company_id": viewer_id,
|
||||
"counterparty_company_id": counterparty_id,
|
||||
"effective_at": cutoff,
|
||||
"calculation_start_date": start_date,
|
||||
"net_change": str(net_change),
|
||||
"basis": basis,
|
||||
"pending_unconfirmed": str(pending_total),
|
||||
"currency": "CNY",
|
||||
}
|
||||
if basis == "full" and opening_amount is not None:
|
||||
closing = opening_amount + net_change
|
||||
payload["opening"] = str(opening_amount)
|
||||
payload["closing"] = str(closing)
|
||||
payload["opening_effective_at"] = _date_add(start_date, -1)
|
||||
return payload
|
||||
|
||||
|
||||
def list_company_counterparties(
|
||||
connection: sqlite3.Connection, company_id: int
|
||||
) -> list[int]:
|
||||
rows = connection.execute(
|
||||
"""
|
||||
SELECT DISTINCT CASE
|
||||
WHEN payer.company_id = ? THEN payee.company_id
|
||||
ELSE payer.company_id
|
||||
END AS other_id
|
||||
FROM eligible_intercompany_events e
|
||||
JOIN transfer_decision_participants payer ON payer.decision_id = e.decision_id AND payer.role = 'payer'
|
||||
JOIN transfer_decision_participants payee ON payee.decision_id = e.decision_id AND payee.role = 'payee'
|
||||
WHERE payer.company_id = ? OR payee.company_id = ?
|
||||
""",
|
||||
(company_id, company_id, company_id),
|
||||
).fetchall()
|
||||
return [int(row["other_id"]) for row in rows if row["other_id"] is not None]
|
||||
|
||||
|
||||
def compute_company_balances(
|
||||
connection: sqlite3.Connection,
|
||||
company_id: int,
|
||||
*,
|
||||
cutoff: str | None = None,
|
||||
) -> dict[str, object]:
|
||||
cutoff = cutoff or utc_today()
|
||||
start_date = get_calculation_start_date(connection)
|
||||
counterparties = list_company_counterparties(connection, company_id)
|
||||
pairs = [
|
||||
compute_pair_balance(connection, company_id, other_id, cutoff=cutoff)
|
||||
for other_id in counterparties
|
||||
]
|
||||
complete = bool(start_date) and all(item["basis"] == "full" for item in pairs)
|
||||
return {
|
||||
"company_id": company_id,
|
||||
"cutoff": cutoff,
|
||||
"calculation_start_date": start_date,
|
||||
"basis": "full" if complete and pairs else "net_change",
|
||||
"pairs": pairs,
|
||||
}
|
||||
|
||||
|
||||
def opening_coverage_summary(connection: sqlite3.Connection) -> dict[str, int]:
|
||||
companies = connection.execute(
|
||||
"SELECT COUNT(*) AS n FROM companies"
|
||||
).fetchone()["n"]
|
||||
recorded = connection.execute(
|
||||
"""
|
||||
SELECT COUNT(DISTINCT company_id_low || ':' || company_id_high) AS n
|
||||
FROM opening_balance_revisions WHERE status = 'confirmed'
|
||||
"""
|
||||
).fetchone()["n"]
|
||||
return {"company_count": companies, "confirmed_pair_count": recorded}
|
||||
@@ -1,92 +0,0 @@
|
||||
"""Explicit many-to-many company assignments; no company means no business access."""
|
||||
import json
|
||||
|
||||
from . import auth, master_data, portal_sso
|
||||
from .db import transaction, utc_now
|
||||
|
||||
|
||||
def companies_for(connection, user_id):
|
||||
return [dict(r) for r in connection.execute(
|
||||
"SELECT c.id,c.name FROM company_memberships m JOIN companies c ON c.id=m.company_id "
|
||||
"WHERE m.user_id=? AND c.status='active' ORDER BY c.id", (user_id,))]
|
||||
|
||||
|
||||
def scoped_user(connection, user, selected=None):
|
||||
if user['role'] != 'company':
|
||||
return user
|
||||
companies = companies_for(connection, user['id'])
|
||||
ids = {str(c['id']) for c in companies}
|
||||
if selected is not None and selected not in ids:
|
||||
raise ValueError('该公司的操作权限已失效,请重新选择公司。')
|
||||
if selected is None:
|
||||
if not companies:
|
||||
raise ValueError('尚未分配负责公司,请联系财务管理员。')
|
||||
if len(companies) > 1:
|
||||
raise ValueError('请先选择本次操作的公司。')
|
||||
selected = str(companies[0]['id'])
|
||||
return {**dict(user), 'company_id': int(selected)}
|
||||
|
||||
|
||||
def candidates(connection):
|
||||
rows = [dict(r) for r in connection.execute(
|
||||
"SELECT id,username,display_name FROM users WHERE role='company' AND status='active' ORDER BY username")]
|
||||
if not portal_sso.enabled():
|
||||
return rows
|
||||
# Read current portal grants rather than trusting an old synchronized flag.
|
||||
identities = portal_sso.call('directory', {})['employees']
|
||||
eligible = {}
|
||||
for identity in identities:
|
||||
pin = connection.execute('SELECT empid FROM portal_identity WHERE uid=?', (identity['local_uid'],)).fetchone()
|
||||
if pin and pin['empid'] == identity['empid']:
|
||||
eligible[identity['local_uid']] = identity
|
||||
return [{**r, 'username': eligible[r['id']]['username'],
|
||||
'display_name': eligible[r['id']]['display_name']} for r in rows if r['id'] in eligible]
|
||||
|
||||
|
||||
def validate_members(value, available):
|
||||
if not isinstance(value, list) or any(type(i) is not int for i in value):
|
||||
raise ValueError('请选择有效的出纳员工。')
|
||||
ids = set(value)
|
||||
if len(ids) != len(value) or not ids.issubset({u['id'] for u in available}):
|
||||
raise ValueError('所选员工已停用、未获财务公司端权限或身份绑定无效,请刷新后重选。')
|
||||
return sorted(ids)
|
||||
|
||||
|
||||
def replace_members(connection, company_id, ids, actor):
|
||||
with transaction(connection):
|
||||
before = [r['user_id'] for r in connection.execute(
|
||||
'SELECT user_id FROM company_memberships WHERE company_id=? ORDER BY user_id', (company_id,))]
|
||||
connection.execute('DELETE FROM company_memberships WHERE company_id=?', (company_id,))
|
||||
connection.executemany('INSERT INTO company_memberships(company_id,user_id,assigned_at,assigned_by) VALUES(?,?,?,?)',
|
||||
[(company_id, uid, utc_now(), actor['id']) for uid in ids])
|
||||
# Legacy column is informational only; all company-side requests use memberships.
|
||||
for uid in set(before) | set(ids):
|
||||
connection.execute('UPDATE users SET company_id=(SELECT MIN(company_id) FROM company_memberships WHERE user_id=?) WHERE id=?', (uid, uid))
|
||||
if before != ids:
|
||||
auth.audit(connection, 'company_members_changed', actor=actor, target=f'company:{company_id}',
|
||||
detail=json.dumps({'before': before, 'after': ids}))
|
||||
|
||||
|
||||
def save_company(connection, company_id, data, actor, available):
|
||||
ids = validate_members(data.get('cashier_user_ids', []), available)
|
||||
name = str(data.get('name') or '').strip()
|
||||
if not name:
|
||||
raise ValueError('公司名称不能为空。')
|
||||
credit = str(data.get('credit_code') or '').strip()
|
||||
names = '、'.join(u['display_name'] or u['username'] for u in available if u['id'] in ids)
|
||||
with transaction(connection):
|
||||
if company_id is None:
|
||||
company_id = master_data.create_company(connection, name, credit, names, actor)
|
||||
else:
|
||||
before = connection.execute('SELECT * FROM companies WHERE id=?', (company_id,)).fetchone()
|
||||
if before is None:
|
||||
raise ValueError('公司不存在。')
|
||||
duplicate = connection.execute('SELECT id FROM companies WHERE name=? AND id<>?', (name, company_id)).fetchone()
|
||||
if duplicate:
|
||||
raise ValueError('公司名称已存在。')
|
||||
connection.execute('UPDATE companies SET name=?,credit_code=?,cashier_name=?,updated_at=? WHERE id=?',
|
||||
(name, credit, names, utc_now(), company_id))
|
||||
after = connection.execute('SELECT * FROM companies WHERE id=?', (company_id,)).fetchone()
|
||||
master_data.record_change(connection, 'company', company_id, 'update', dict(before), dict(after), '更新公司资料和负责出纳', actor)
|
||||
replace_members(connection, company_id, ids, actor)
|
||||
return company_id
|
||||
@@ -1,754 +0,0 @@
|
||||
"""Company-portal intercompany transfer summary / detail / export (HEL-175/176).
|
||||
|
||||
Confirmed totals reuse the authoritative ``eligible_intercompany_events``
|
||||
view (intercompany + paired or locked). Pending counts/amounts are listed
|
||||
separately and never enter outflow, inflow or net. All money math uses
|
||||
``Decimal`` on stored TEXT amounts — never float or SQLite SUM.
|
||||
|
||||
Detail listing (HEL-176) applies counterparty / date / direction / state
|
||||
filters inside SQL before LIMIT, and uses keyset pagination on
|
||||
(effective_at, event_id) descending. Export only ships confirmed rows.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import csv
|
||||
import io
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from decimal import Decimal, InvalidOperation
|
||||
import re
|
||||
import sqlite3
|
||||
|
||||
from . import calculation, matching, settings
|
||||
|
||||
_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
||||
_ZERO = Decimal("0.00")
|
||||
_DEFAULT_PAGE = 50
|
||||
_MAX_PAGE = 200
|
||||
_MAX_EXPORT_ROWS = 20000
|
||||
|
||||
|
||||
class TransferSummaryInputError(ValueError):
|
||||
"""Invalid query parameters (mapped to HTTP 400)."""
|
||||
|
||||
|
||||
def today_shanghai() -> str:
|
||||
return datetime.now(timezone(timedelta(hours=8))).date().isoformat()
|
||||
|
||||
|
||||
def _validate_date(value: object, label: str) -> str:
|
||||
text = str(value or "").strip()
|
||||
if not text or not _DATE_RE.fullmatch(text):
|
||||
raise TransferSummaryInputError(f"{label}必须是 YYYY-MM-DD 格式。")
|
||||
try:
|
||||
datetime.strptime(text, "%Y-%m-%d")
|
||||
except ValueError as exc:
|
||||
raise TransferSummaryInputError(f"{label}不是有效日期。") from exc
|
||||
return text
|
||||
|
||||
|
||||
def _money(value: Decimal) -> str:
|
||||
return format(value.quantize(Decimal("0.01")), "f")
|
||||
|
||||
|
||||
def _as_decimal(raw: object) -> Decimal:
|
||||
try:
|
||||
return Decimal(str(raw))
|
||||
except (InvalidOperation, TypeError) as exc:
|
||||
raise TransferSummaryInputError("金额数据无效,无法汇总。") from exc
|
||||
|
||||
|
||||
def _company_row(connection: sqlite3.Connection, company_id: int) -> dict[str, object]:
|
||||
row = connection.execute(
|
||||
"SELECT id, name FROM companies WHERE id = ?", (company_id,)
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise TransferSummaryInputError("本公司不存在。")
|
||||
return {"id": int(row["id"]), "name": row["name"]}
|
||||
|
||||
|
||||
def _window_bounds(
|
||||
connection: sqlite3.Connection, as_of: str | None
|
||||
) -> tuple[str, str]:
|
||||
end = _validate_date(as_of, "as_of") if as_of else today_shanghai()
|
||||
calc_start = calculation.get_calculation_start_date(connection)
|
||||
start = calc_start or settings.get_settings(connection).get("start_date") or "2026-01-01"
|
||||
start = _validate_date(start, "start_date")
|
||||
if start > end:
|
||||
# Opening / start-date plumbing may lag; clamp rather than 500.
|
||||
start = end
|
||||
return start, end
|
||||
|
||||
|
||||
def _load_confirmed(
|
||||
connection: sqlite3.Connection, company_id: int, start: str, end: str
|
||||
) -> list[sqlite3.Row]:
|
||||
return connection.execute(
|
||||
"""
|
||||
SELECT e.event_id, e.decision_id, e.effective_at, e.amount, e.currency,
|
||||
e.payer_company_id, e.payee_company_id, e.pairing,
|
||||
cpayer.name AS payer_company_name,
|
||||
cpayee.name AS payee_company_name
|
||||
FROM eligible_intercompany_events e
|
||||
JOIN companies cpayer ON cpayer.id = e.payer_company_id
|
||||
JOIN companies cpayee ON cpayee.id = e.payee_company_id
|
||||
WHERE (e.payer_company_id = ? OR e.payee_company_id = ?)
|
||||
AND e.effective_at >= ?
|
||||
AND e.effective_at <= ?
|
||||
ORDER BY e.event_id
|
||||
""",
|
||||
(company_id, company_id, start, end + "T23:59:59"),
|
||||
).fetchall()
|
||||
|
||||
|
||||
def _load_pending(
|
||||
connection: sqlite3.Connection, company_id: int, start: str, end: str
|
||||
) -> list[sqlite3.Row]:
|
||||
"""Pending = not eligible confirmed, still company-visible for tip only.
|
||||
|
||||
Includes unresolved / needs_review / internal_single, plus any
|
||||
intercompany decision that is neither paired nor locked.
|
||||
"""
|
||||
return connection.execute(
|
||||
"""
|
||||
SELECT c.event_id, d.id AS decision_id, d.effective_at, d.amount,
|
||||
d.currency, d.classification, d.pairing, d.locked,
|
||||
payer.company_id AS payer_company_id,
|
||||
payee.company_id AS payee_company_id,
|
||||
cpayer.name AS payer_company_name,
|
||||
cpayee.name AS payee_company_name
|
||||
FROM current_transfer_decisions c
|
||||
JOIN transfer_match_decisions d ON d.id = c.decision_id
|
||||
JOIN canonical_transfer_events e ON e.id = c.event_id
|
||||
LEFT JOIN transfer_decision_participants payer
|
||||
ON payer.decision_id = d.id AND payer.role = 'payer'
|
||||
LEFT JOIN transfer_decision_participants payee
|
||||
ON payee.decision_id = d.id AND payee.role = 'payee'
|
||||
LEFT JOIN companies cpayer ON cpayer.id = payer.company_id
|
||||
LEFT JOIN companies cpayee ON cpayee.id = payee.company_id
|
||||
WHERE e.lifecycle = 'active'
|
||||
AND (payer.company_id = ? OR payee.company_id = ?)
|
||||
AND d.effective_at >= ?
|
||||
AND d.effective_at <= ?
|
||||
AND (
|
||||
d.classification IN ('unresolved', 'needs_review', 'internal_single')
|
||||
OR (
|
||||
d.classification = 'intercompany'
|
||||
AND d.pairing != 'paired'
|
||||
AND d.locked = 0
|
||||
)
|
||||
)
|
||||
ORDER BY c.event_id
|
||||
""",
|
||||
(company_id, company_id, start, end + "T23:59:59"),
|
||||
).fetchall()
|
||||
|
||||
|
||||
def _counterparty_of(row: sqlite3.Row, company_id: int) -> tuple[int | None, str | None]:
|
||||
payer = row["payer_company_id"]
|
||||
payee = row["payee_company_id"]
|
||||
if payer is not None and int(payer) == int(company_id):
|
||||
if payee is None:
|
||||
return None, None
|
||||
return int(payee), row["payee_company_name"]
|
||||
if payee is not None and int(payee) == int(company_id):
|
||||
if payer is None:
|
||||
return None, None
|
||||
return int(payer), row["payer_company_name"]
|
||||
return None, None
|
||||
|
||||
|
||||
def _is_outflow(row: sqlite3.Row, company_id: int) -> bool:
|
||||
return row["payer_company_id"] is not None and int(row["payer_company_id"]) == int(
|
||||
company_id
|
||||
)
|
||||
|
||||
|
||||
def company_intercompany_summary(
|
||||
connection: sqlite3.Connection,
|
||||
*,
|
||||
company_id: int,
|
||||
as_of: str | None = None,
|
||||
) -> dict[str, object]:
|
||||
"""Build the HEL-169 summary payload for one company session."""
|
||||
own = _company_row(connection, company_id)
|
||||
start, end = _window_bounds(connection, as_of)
|
||||
|
||||
confirmed_rows = _load_confirmed(connection, company_id, start, end)
|
||||
pending_rows = _load_pending(connection, company_id, start, end)
|
||||
|
||||
seen_confirmed: set[int] = set()
|
||||
outflow = _ZERO
|
||||
inflow = _ZERO
|
||||
outflow_count = 0
|
||||
inflow_count = 0
|
||||
|
||||
# counterparty_id -> bucket
|
||||
buckets: dict[int, dict[str, object]] = {}
|
||||
|
||||
def bucket_for(cp_id: int, cp_name: str | None) -> dict[str, object]:
|
||||
bucket = buckets.get(cp_id)
|
||||
if bucket is None:
|
||||
bucket = {
|
||||
"company_id": cp_id,
|
||||
"company_name": cp_name or "",
|
||||
"confirmed_outflow": _ZERO,
|
||||
"confirmed_inflow": _ZERO,
|
||||
"pending_count": 0,
|
||||
"last_effective_at": None,
|
||||
}
|
||||
buckets[cp_id] = bucket
|
||||
elif cp_name and not bucket["company_name"]:
|
||||
bucket["company_name"] = cp_name
|
||||
return bucket
|
||||
|
||||
def touch_last(bucket: dict[str, object], effective_at: str | None) -> None:
|
||||
if not effective_at:
|
||||
return
|
||||
previous = bucket["last_effective_at"]
|
||||
if previous is None or str(effective_at) > str(previous):
|
||||
bucket["last_effective_at"] = effective_at
|
||||
|
||||
for row in confirmed_rows:
|
||||
event_id = int(row["event_id"])
|
||||
if event_id in seen_confirmed:
|
||||
continue
|
||||
seen_confirmed.add(event_id)
|
||||
amount = _as_decimal(row["amount"])
|
||||
cp_id, cp_name = _counterparty_of(row, company_id)
|
||||
if _is_outflow(row, company_id):
|
||||
outflow += amount
|
||||
outflow_count += 1
|
||||
if cp_id is not None:
|
||||
bucket = bucket_for(cp_id, cp_name)
|
||||
bucket["confirmed_outflow"] += amount
|
||||
touch_last(bucket, row["effective_at"])
|
||||
else:
|
||||
inflow += amount
|
||||
inflow_count += 1
|
||||
if cp_id is not None:
|
||||
bucket = bucket_for(cp_id, cp_name)
|
||||
bucket["confirmed_inflow"] += amount
|
||||
touch_last(bucket, row["effective_at"])
|
||||
|
||||
pending_total = _ZERO
|
||||
seen_pending: set[int] = set()
|
||||
for row in pending_rows:
|
||||
event_id = int(row["event_id"])
|
||||
if event_id in seen_pending or event_id in seen_confirmed:
|
||||
continue
|
||||
seen_pending.add(event_id)
|
||||
amount = _as_decimal(row["amount"])
|
||||
pending_total += amount
|
||||
cp_id, cp_name = _counterparty_of(row, company_id)
|
||||
if cp_id is not None:
|
||||
bucket = bucket_for(cp_id, cp_name)
|
||||
bucket["pending_count"] = int(bucket["pending_count"]) + 1
|
||||
touch_last(bucket, row["effective_at"])
|
||||
|
||||
net = outflow - inflow
|
||||
if net > 0:
|
||||
net_direction: str | None = "receivable"
|
||||
elif net < 0:
|
||||
net_direction = "payable"
|
||||
else:
|
||||
net_direction = None
|
||||
|
||||
counterparties = []
|
||||
for cp_id in sorted(
|
||||
buckets.keys(),
|
||||
key=lambda i: (
|
||||
-(
|
||||
buckets[i]["confirmed_outflow"] # type: ignore[operator]
|
||||
+ buckets[i]["confirmed_inflow"]
|
||||
),
|
||||
buckets[i]["company_name"] or "",
|
||||
i,
|
||||
),
|
||||
):
|
||||
bucket = buckets[cp_id]
|
||||
conf_out = bucket["confirmed_outflow"]
|
||||
conf_in = bucket["confirmed_inflow"]
|
||||
assert isinstance(conf_out, Decimal) and isinstance(conf_in, Decimal)
|
||||
counterparties.append(
|
||||
{
|
||||
"company_id": cp_id,
|
||||
"company_name": bucket["company_name"],
|
||||
"confirmed_outflow": _money(conf_out),
|
||||
"confirmed_inflow": _money(conf_in),
|
||||
"net": _money(conf_out - conf_in),
|
||||
"pending_count": int(bucket["pending_count"]),
|
||||
"last_effective_at": bucket["last_effective_at"],
|
||||
}
|
||||
)
|
||||
|
||||
# Enrich window with calculation-basis opening/ending when configured.
|
||||
balances = calculation.compute_company_balances(
|
||||
connection, company_id, cutoff=end
|
||||
)
|
||||
has_opening = balances.get("basis") == "full"
|
||||
opening_total = _ZERO
|
||||
ending_total = _ZERO
|
||||
if has_opening:
|
||||
for pair in balances.get("pairs") or []:
|
||||
opening_total += _as_decimal(pair.get("opening") or "0")
|
||||
ending_total += _as_decimal(pair.get("closing") or "0")
|
||||
|
||||
return {
|
||||
"own_company": own,
|
||||
"window": {
|
||||
"start": start,
|
||||
"end": end,
|
||||
"has_opening": has_opening,
|
||||
"opening": _money(opening_total) if has_opening else None,
|
||||
"ending": _money(ending_total) if has_opening else None,
|
||||
"basis": balances.get("basis"),
|
||||
"calculation_start_date": balances.get("calculation_start_date"),
|
||||
},
|
||||
"confirmed": {
|
||||
"outflow_total": _money(outflow),
|
||||
"outflow_count": outflow_count,
|
||||
"inflow_total": _money(inflow),
|
||||
"inflow_count": inflow_count,
|
||||
"net_change": _money(net),
|
||||
"net_direction": net_direction,
|
||||
},
|
||||
"pending": {
|
||||
"count": len(seen_pending),
|
||||
"amount_total": _money(pending_total),
|
||||
},
|
||||
"counterparties": counterparties,
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Detail list + CSV export (HEL-176)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def encode_cursor(effective_at: str, event_id: int) -> str:
|
||||
raw = f"{effective_at}|{event_id}"
|
||||
return base64.urlsafe_b64encode(raw.encode("utf-8")).decode("ascii")
|
||||
|
||||
|
||||
def decode_cursor(cursor: str | None) -> tuple[str, int] | None:
|
||||
if not cursor:
|
||||
return None
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(cursor.encode("ascii")).decode("utf-8")
|
||||
effective_at, event_id_text = raw.split("|", 1)
|
||||
return effective_at, int(event_id_text)
|
||||
except Exception as exc:
|
||||
raise TransferSummaryInputError("分页游标无效。") from exc
|
||||
|
||||
|
||||
def _parse_limit(raw: object | None, default: int = _DEFAULT_PAGE) -> int:
|
||||
if raw is None or str(raw).strip() == "":
|
||||
return default
|
||||
try:
|
||||
value = int(str(raw).strip())
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise TransferSummaryInputError("limit 必须是正整数。") from exc
|
||||
if value < 1:
|
||||
raise TransferSummaryInputError("limit 必须是正整数。")
|
||||
return min(value, _MAX_PAGE)
|
||||
|
||||
|
||||
def _parse_optional_date(raw: object | None, label: str) -> str | None:
|
||||
if raw is None or str(raw).strip() == "":
|
||||
return None
|
||||
return _validate_date(raw, label)
|
||||
|
||||
|
||||
def _parse_direction(raw: object | None) -> str | None:
|
||||
if raw is None or str(raw).strip() == "":
|
||||
return None
|
||||
value = str(raw).strip().lower()
|
||||
if value not in ("out", "in"):
|
||||
raise TransferSummaryInputError("direction 只能是 out 或 in。")
|
||||
return value
|
||||
|
||||
|
||||
def _parse_state(raw: object | None) -> str | None:
|
||||
if raw is None or str(raw).strip() == "":
|
||||
return None
|
||||
value = str(raw).strip().lower()
|
||||
if value not in ("confirmed", "pending"):
|
||||
raise TransferSummaryInputError("state 只能是 confirmed 或 pending。")
|
||||
return value
|
||||
|
||||
|
||||
def _parse_counterparty_id(raw: object | None) -> int | None:
|
||||
if raw is None or str(raw).strip() == "":
|
||||
return None
|
||||
try:
|
||||
value = int(str(raw).strip())
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise TransferSummaryInputError("counterparty_id 参数无效。") from exc
|
||||
if value < 1:
|
||||
raise TransferSummaryInputError("counterparty_id 参数无效。")
|
||||
return value
|
||||
|
||||
|
||||
def _event_window(
|
||||
connection: sqlite3.Connection,
|
||||
*,
|
||||
from_: str | None,
|
||||
to: str | None,
|
||||
) -> tuple[str, str]:
|
||||
end = _parse_optional_date(to, "to") or today_shanghai()
|
||||
start_default = settings.get_settings(connection).get("start_date") or "2026-01-01"
|
||||
start = _parse_optional_date(from_, "from") or _validate_date(
|
||||
start_default, "start_date"
|
||||
)
|
||||
if start > end:
|
||||
raise TransferSummaryInputError("from 不能晚于 to。")
|
||||
return start, end
|
||||
|
||||
|
||||
# Confirmed = eligible_intercompany_events. Pending matches summary tip set.
|
||||
_CONFIRMED_PREDICATE = """
|
||||
d.classification = 'intercompany'
|
||||
AND (d.pairing = 'paired' OR d.locked = 1)
|
||||
"""
|
||||
|
||||
_PENDING_PREDICATE = """
|
||||
(
|
||||
d.classification IN ('unresolved', 'needs_review', 'internal_single')
|
||||
OR (
|
||||
d.classification = 'intercompany'
|
||||
AND d.pairing != 'paired'
|
||||
AND d.locked = 0
|
||||
)
|
||||
)
|
||||
"""
|
||||
|
||||
_BOTH_PREDICATE = f"""
|
||||
(
|
||||
({_CONFIRMED_PREDICATE})
|
||||
OR ({_PENDING_PREDICATE})
|
||||
)
|
||||
"""
|
||||
|
||||
|
||||
def _state_predicate(state: str | None) -> str:
|
||||
if state == "confirmed":
|
||||
return f"({_CONFIRMED_PREDICATE})"
|
||||
if state == "pending":
|
||||
return f"({_PENDING_PREDICATE})"
|
||||
return _BOTH_PREDICATE
|
||||
|
||||
|
||||
def _list_select_sql() -> str:
|
||||
return """
|
||||
SELECT c.event_id, d.id AS decision_id, d.revision, d.classification,
|
||||
d.pairing, d.amount, d.currency, d.effective_at, d.mode,
|
||||
d.locked, d.rule_version, d.created_at, d.reason,
|
||||
payer.company_id AS payer_company_id,
|
||||
payee.company_id AS payee_company_id,
|
||||
payer.bank_account_id AS payer_account_id,
|
||||
payee.bank_account_id AS payee_account_id,
|
||||
cpayer.name AS payer_company_name,
|
||||
cpayee.name AS payee_company_name,
|
||||
(SELECT COUNT(*) FROM transfer_decision_observations o
|
||||
WHERE o.decision_id = d.id) AS evidence_count,
|
||||
(SELECT r.summary
|
||||
FROM transfer_decision_observations o
|
||||
JOIN source_rows r ON r.id = o.source_row_id
|
||||
JOIN sheet_batches s ON s.id = r.sheet_batch_id
|
||||
JOIN import_batches b ON b.id = s.import_batch_id
|
||||
WHERE o.decision_id = d.id AND b.company_id = ?
|
||||
ORDER BY o.id
|
||||
LIMIT 1) AS summary
|
||||
FROM current_transfer_decisions c
|
||||
JOIN transfer_match_decisions d ON d.id = c.decision_id
|
||||
JOIN canonical_transfer_events e ON e.id = c.event_id
|
||||
LEFT JOIN transfer_decision_participants payer
|
||||
ON payer.decision_id = d.id AND payer.role = 'payer'
|
||||
LEFT JOIN transfer_decision_participants payee
|
||||
ON payee.decision_id = d.id AND payee.role = 'payee'
|
||||
LEFT JOIN companies cpayer ON cpayer.id = payer.company_id
|
||||
LEFT JOIN companies cpayee ON cpayee.id = payee.company_id
|
||||
"""
|
||||
|
||||
|
||||
def _build_event_filters(
|
||||
*,
|
||||
company_id: int,
|
||||
start: str,
|
||||
end: str,
|
||||
counterparty_id: int | None,
|
||||
direction: str | None,
|
||||
state: str | None,
|
||||
cursor: tuple[str, int] | None,
|
||||
) -> tuple[str, list[object]]:
|
||||
conditions = [
|
||||
"e.lifecycle = 'active'",
|
||||
"(payer.company_id = ? OR payee.company_id = ?)",
|
||||
"d.effective_at >= ?",
|
||||
"d.effective_at <= ?",
|
||||
_state_predicate(state),
|
||||
]
|
||||
params: list[object] = [
|
||||
company_id,
|
||||
company_id,
|
||||
start,
|
||||
end + "T23:59:59",
|
||||
]
|
||||
|
||||
if counterparty_id is not None:
|
||||
# Counterparty is the other participant; own company stays forced above.
|
||||
conditions.append(
|
||||
"""
|
||||
(
|
||||
(payer.company_id = ? AND payee.company_id = ?)
|
||||
OR (payee.company_id = ? AND payer.company_id = ?)
|
||||
)
|
||||
"""
|
||||
)
|
||||
params.extend([company_id, counterparty_id, company_id, counterparty_id])
|
||||
|
||||
if direction == "out":
|
||||
conditions.append("payer.company_id = ?")
|
||||
params.append(company_id)
|
||||
elif direction == "in":
|
||||
conditions.append("payee.company_id = ?")
|
||||
params.append(company_id)
|
||||
|
||||
if cursor is not None:
|
||||
cursor_at, cursor_id = cursor
|
||||
conditions.append(
|
||||
"""
|
||||
(
|
||||
d.effective_at < ?
|
||||
OR (d.effective_at = ? AND c.event_id < ?)
|
||||
)
|
||||
"""
|
||||
)
|
||||
params.extend([cursor_at, cursor_at, cursor_id])
|
||||
|
||||
where = " WHERE " + " AND ".join(conditions)
|
||||
return where, params
|
||||
|
||||
|
||||
def _row_state(row: sqlite3.Row) -> str:
|
||||
classification = row["classification"]
|
||||
pairing = row["pairing"]
|
||||
locked = bool(row["locked"])
|
||||
if classification == "intercompany" and (pairing == "paired" or locked):
|
||||
return "confirmed"
|
||||
return "pending"
|
||||
|
||||
|
||||
def _row_direction(row: sqlite3.Row, company_id: int) -> str | None:
|
||||
if row["payer_company_id"] is not None and int(row["payer_company_id"]) == int(
|
||||
company_id
|
||||
):
|
||||
return "out"
|
||||
if row["payee_company_id"] is not None and int(row["payee_company_id"]) == int(
|
||||
company_id
|
||||
):
|
||||
return "in"
|
||||
return None
|
||||
|
||||
|
||||
def _event_list_item(row: sqlite3.Row, company_id: int) -> dict[str, object]:
|
||||
direction = _row_direction(row, company_id)
|
||||
state = _row_state(row)
|
||||
if direction == "out":
|
||||
counterparty_company_id = row["payee_company_id"]
|
||||
counterparty_company_name = row["payee_company_name"]
|
||||
else:
|
||||
counterparty_company_id = row["payer_company_id"]
|
||||
counterparty_company_name = row["payer_company_name"]
|
||||
summary = row["summary"] or row["reason"] or ""
|
||||
return {
|
||||
"event_id": int(row["event_id"]),
|
||||
"decision_id": int(row["decision_id"]),
|
||||
"revision": row["revision"],
|
||||
"classification": row["classification"],
|
||||
"pairing": row["pairing"],
|
||||
"status": matching.exposed_status(row),
|
||||
"state": state,
|
||||
"direction": direction,
|
||||
"amount": row["amount"],
|
||||
"currency": row["currency"],
|
||||
"effective_at": row["effective_at"],
|
||||
"mode": row["mode"],
|
||||
"locked": bool(row["locked"]),
|
||||
"rule_version": row["rule_version"],
|
||||
"summary": summary,
|
||||
"own_company_id": company_id,
|
||||
"counterparty_company_id": (
|
||||
int(counterparty_company_id) if counterparty_company_id is not None else None
|
||||
),
|
||||
"counterparty_company_name": counterparty_company_name,
|
||||
"evidence_count": row["evidence_count"],
|
||||
}
|
||||
|
||||
|
||||
def company_intercompany_events(
|
||||
connection: sqlite3.Connection,
|
||||
*,
|
||||
company_id: int,
|
||||
from_: str | None = None,
|
||||
to: str | None = None,
|
||||
counterparty_id: int | None | object = None,
|
||||
direction: str | None | object = None,
|
||||
state: str | None | object = None,
|
||||
limit: object | None = None,
|
||||
cursor: str | None = None,
|
||||
) -> dict[str, object]:
|
||||
"""Filtered keyset page of company-visible transfer events (HEL-176)."""
|
||||
start, end = _event_window(connection, from_=from_, to=to)
|
||||
cp_id = _parse_counterparty_id(counterparty_id)
|
||||
direction_value = _parse_direction(direction)
|
||||
state_value = _parse_state(state)
|
||||
page_size = _parse_limit(limit)
|
||||
cursor_tuple = decode_cursor(cursor)
|
||||
|
||||
where, params = _build_event_filters(
|
||||
company_id=company_id,
|
||||
start=start,
|
||||
end=end,
|
||||
counterparty_id=cp_id,
|
||||
direction=direction_value,
|
||||
state=state_value,
|
||||
cursor=cursor_tuple,
|
||||
)
|
||||
# summary subquery binds own company_id first.
|
||||
sql = (
|
||||
_list_select_sql()
|
||||
+ where
|
||||
+ " ORDER BY d.effective_at DESC, c.event_id DESC LIMIT ?"
|
||||
)
|
||||
rows = connection.execute(
|
||||
sql, (company_id, *params, page_size + 1)
|
||||
).fetchall()
|
||||
|
||||
has_more = len(rows) > page_size
|
||||
page = rows[:page_size]
|
||||
items = [_event_list_item(row, company_id) for row in page]
|
||||
next_cursor = None
|
||||
if has_more and page:
|
||||
last = page[-1]
|
||||
next_cursor = encode_cursor(str(last["effective_at"]), int(last["event_id"]))
|
||||
|
||||
return {
|
||||
"window": {"start": start, "end": end},
|
||||
"events": items,
|
||||
"next_cursor": next_cursor,
|
||||
"has_more": has_more,
|
||||
}
|
||||
|
||||
|
||||
def company_intercompany_export_rows(
|
||||
connection: sqlite3.Connection,
|
||||
*,
|
||||
company_id: int,
|
||||
from_: str | None = None,
|
||||
to: str | None = None,
|
||||
counterparty_id: int | None | object = None,
|
||||
direction: str | None | object = None,
|
||||
) -> tuple[list[dict[str, object]], dict[str, object]]:
|
||||
"""Confirmed-only rows for CSV export; pending never included."""
|
||||
start, end = _event_window(connection, from_=from_, to=to)
|
||||
cp_id = _parse_counterparty_id(counterparty_id)
|
||||
direction_value = _parse_direction(direction)
|
||||
|
||||
where, params = _build_event_filters(
|
||||
company_id=company_id,
|
||||
start=start,
|
||||
end=end,
|
||||
counterparty_id=cp_id,
|
||||
direction=direction_value,
|
||||
state="confirmed",
|
||||
cursor=None,
|
||||
)
|
||||
sql = (
|
||||
_list_select_sql()
|
||||
+ where
|
||||
+ " ORDER BY d.effective_at DESC, c.event_id DESC LIMIT ?"
|
||||
)
|
||||
rows = connection.execute(
|
||||
sql, (company_id, *params, _MAX_EXPORT_ROWS + 1)
|
||||
).fetchall()
|
||||
if len(rows) > _MAX_EXPORT_ROWS:
|
||||
raise TransferSummaryInputError(
|
||||
f"导出行数超过上限 {_MAX_EXPORT_ROWS},请缩小筛选范围。"
|
||||
)
|
||||
items = [_event_list_item(row, company_id) for row in rows]
|
||||
meta = {
|
||||
"start": start,
|
||||
"end": end,
|
||||
"counterparty_id": cp_id,
|
||||
"direction": direction_value,
|
||||
"state": "confirmed",
|
||||
"row_count": len(items),
|
||||
}
|
||||
return items, meta
|
||||
|
||||
|
||||
def render_intercompany_export_csv(items: list[dict[str, object]]) -> bytes:
|
||||
buffer = io.StringIO()
|
||||
writer = csv.writer(buffer)
|
||||
writer.writerow(
|
||||
[
|
||||
"日期",
|
||||
"方向",
|
||||
"对方公司",
|
||||
"金额",
|
||||
"币种",
|
||||
"摘要",
|
||||
"状态",
|
||||
"配对",
|
||||
"事件ID",
|
||||
"决策ID",
|
||||
]
|
||||
)
|
||||
direction_label = {"out": "转出", "in": "转入"}
|
||||
for item in items:
|
||||
writer.writerow(
|
||||
[
|
||||
item.get("effective_at") or "",
|
||||
direction_label.get(str(item.get("direction") or ""), ""),
|
||||
item.get("counterparty_company_name") or "",
|
||||
item.get("amount") or "",
|
||||
item.get("currency") or "",
|
||||
item.get("summary") or "",
|
||||
"已确认",
|
||||
item.get("pairing") or "",
|
||||
item.get("event_id") or "",
|
||||
item.get("decision_id") or "",
|
||||
]
|
||||
)
|
||||
# UTF-8 BOM so Excel opens the CSV with the right encoding.
|
||||
return (chr(0xFEFF) + buffer.getvalue()).encode("utf-8")
|
||||
|
||||
|
||||
def is_transfer_summary_events_query(query: dict[str, list[str]]) -> bool:
|
||||
"""Discriminate HEL-176 transfer list from B-44 ledger ``/events``.
|
||||
|
||||
B-44 uses ``cutoff`` / subject / posting_kind / source_kind / pending_subject.
|
||||
HEL-176 uses ``to`` / direction / counterparty_id / state=pending|confirmed
|
||||
(without ledger-only knobs).
|
||||
"""
|
||||
if (query.get("direction") or [None])[0] is not None:
|
||||
return True
|
||||
if (query.get("counterparty_id") or [None])[0] is not None:
|
||||
return True
|
||||
if (query.get("to") or [None])[0] is not None:
|
||||
return True
|
||||
state = (query.get("state") or [None])[0]
|
||||
if state in ("pending", "confirmed") and (query.get("cutoff") or [None])[0] is None:
|
||||
# Bare state=confirmed without cutoff is the transfer-summary list;
|
||||
# B-44 confirmed always pairs with cutoff in existing callers/tests.
|
||||
if (query.get("subject") or [None])[0] is not None:
|
||||
return False
|
||||
if (query.get("posting_kind") or [None])[0] is not None:
|
||||
return False
|
||||
if (query.get("source_kind") or [None])[0] is not None:
|
||||
return False
|
||||
return True
|
||||
return False
|
||||
@@ -1,502 +0,0 @@
|
||||
"""Admin dashboard aggregates over existing B-43 eligible events and review queues.
|
||||
|
||||
No fabricated demo amounts. Opening balances are unavailable until B-45; peer
|
||||
group ``opening`` is always null and ``ending`` equals period net change.
|
||||
Period closing status is unknown without the monthly-close module — returned
|
||||
as null so the UI shows an em dash rather than a guessed label.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from calendar import monthrange
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from decimal import Decimal, ROUND_HALF_UP
|
||||
import sqlite3
|
||||
|
||||
|
||||
WAN = Decimal("10000")
|
||||
ZERO = Decimal("0")
|
||||
TWOPLACES = Decimal("0.01")
|
||||
|
||||
|
||||
def today_shanghai() -> str:
|
||||
return datetime.now(timezone(timedelta(hours=8))).date().isoformat()
|
||||
|
||||
|
||||
def _month_bounds(year_month: str) -> tuple[str, str]:
|
||||
year, month = (int(part) for part in year_month.split("-"))
|
||||
last = monthrange(year, month)[1]
|
||||
return f"{year_month}-01", f"{year_month}-{last:02d}"
|
||||
|
||||
|
||||
def _q2(value: Decimal) -> str:
|
||||
return str(value.quantize(TWOPLACES, rounding=ROUND_HALF_UP))
|
||||
|
||||
|
||||
def _to_wan(amount: Decimal) -> str:
|
||||
return _q2(amount / WAN)
|
||||
|
||||
|
||||
def _parse_day(iso_ts: str | None) -> str | None:
|
||||
if not iso_ts:
|
||||
return None
|
||||
text = str(iso_ts)
|
||||
return text[:10] if len(text) >= 10 else None
|
||||
|
||||
|
||||
def audit_counts(connection: sqlite3.Connection) -> dict[str, int]:
|
||||
"""Derive pending review counts from real queues only.
|
||||
|
||||
Priority mapping (aligned with current admin audit UI semantics):
|
||||
- high: unresolved / needs_review match exceptions
|
||||
- medium: pending bank-account registrations + pending manual records
|
||||
- low: reserved for future low-risk queues (currently always 0)
|
||||
|
||||
Homepage card, sidebar badge and audit-center heading must all read this
|
||||
same payload (via ``/api/admin/dashboard`` → ``audit``).
|
||||
"""
|
||||
high = connection.execute(
|
||||
"""
|
||||
SELECT COUNT(*) AS n
|
||||
FROM current_transfer_decisions c
|
||||
JOIN transfer_match_decisions d ON d.id = c.decision_id
|
||||
JOIN canonical_transfer_events e ON e.id = c.event_id
|
||||
WHERE e.lifecycle = 'active'
|
||||
AND d.classification IN ('unresolved', 'needs_review')
|
||||
"""
|
||||
).fetchone()["n"]
|
||||
medium_accounts = connection.execute(
|
||||
"SELECT COUNT(*) AS n FROM bank_accounts WHERE status = 'pending'"
|
||||
).fetchone()["n"]
|
||||
medium_manuals = connection.execute(
|
||||
"""
|
||||
SELECT COUNT(*) AS n
|
||||
FROM manual_records m
|
||||
JOIN current_manual_record_decisions c ON c.record_id = m.id
|
||||
JOIN manual_record_decisions d ON d.id = c.decision_id
|
||||
WHERE d.state = 'pending'
|
||||
"""
|
||||
).fetchone()["n"]
|
||||
medium = int(medium_accounts) + int(medium_manuals)
|
||||
low = 0
|
||||
return {
|
||||
"total": int(high) + int(medium) + int(low),
|
||||
"high": int(high),
|
||||
"medium": int(medium),
|
||||
"low": int(low),
|
||||
}
|
||||
|
||||
|
||||
def _load_eligible(
|
||||
connection: sqlite3.Connection, *, from_date: str, cutoff: str
|
||||
) -> list[sqlite3.Row]:
|
||||
return connection.execute(
|
||||
"""
|
||||
SELECT e.event_id, e.decision_id, e.effective_at, e.amount, e.currency,
|
||||
e.payer_company_id, e.payee_company_id, e.pairing,
|
||||
cpayer.name AS payer_name, cpayee.name AS payee_name
|
||||
FROM eligible_intercompany_events e
|
||||
JOIN companies cpayer ON cpayer.id = e.payer_company_id
|
||||
JOIN companies cpayee ON cpayee.id = e.payee_company_id
|
||||
WHERE date(e.effective_at) >= date(?)
|
||||
AND date(e.effective_at) <= date(?)
|
||||
ORDER BY e.effective_at, e.event_id
|
||||
""",
|
||||
(from_date, cutoff),
|
||||
).fetchall()
|
||||
|
||||
|
||||
def _company_rows(connection: sqlite3.Connection) -> list[sqlite3.Row]:
|
||||
return connection.execute(
|
||||
"""
|
||||
SELECT id, name FROM companies
|
||||
WHERE status != 'disabled'
|
||||
ORDER BY id
|
||||
"""
|
||||
).fetchall()
|
||||
|
||||
|
||||
def _period_status_for_cutoff(
|
||||
connection: sqlite3.Connection, cutoff: str
|
||||
) -> tuple[str | None, str]:
|
||||
ym = str(cutoff or "")[:7]
|
||||
exists = connection.execute(
|
||||
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'period_close_runs'"
|
||||
).fetchone()
|
||||
if exists is None:
|
||||
return None, "—"
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT status FROM period_close_runs
|
||||
WHERE year_month = ?
|
||||
ORDER BY version DESC LIMIT 1
|
||||
""",
|
||||
(ym,),
|
||||
).fetchone()
|
||||
mapping = {
|
||||
"closed": ("closed", "已锁定"),
|
||||
"reopened": ("reopened", "已重开"),
|
||||
"failed": ("failed", "结账失败"),
|
||||
"pending": ("pending", "待结账"),
|
||||
"closing": ("closing", "处理中"),
|
||||
}
|
||||
if row is not None:
|
||||
return mapping.get(row["status"], (row["status"], str(row["status"])))
|
||||
locked = connection.execute(
|
||||
"SELECT 1 FROM closed_periods WHERE year_month = ?", (ym,)
|
||||
).fetchone()
|
||||
if locked is not None:
|
||||
return "closed", "已锁定"
|
||||
return None, "—"
|
||||
|
||||
|
||||
def company_summaries(
|
||||
connection: sqlite3.Connection, *, from_date: str, cutoff: str
|
||||
) -> tuple[list[dict[str, object]], dict[str, object]]:
|
||||
companies = _company_rows(connection)
|
||||
events = _load_eligible(connection, from_date=from_date, cutoff=cutoff)
|
||||
period_status, period_label = _period_status_for_cutoff(connection, cutoff)
|
||||
|
||||
debit_total = ZERO
|
||||
credit_total = ZERO
|
||||
by_id: dict[int, dict[str, object]] = {}
|
||||
for company in companies:
|
||||
by_id[int(company["id"])] = {
|
||||
"id": int(company["id"]),
|
||||
"name": company["name"],
|
||||
"detail_count": 0,
|
||||
"debit": ZERO,
|
||||
"credit": ZERO,
|
||||
"period_status": period_status,
|
||||
"period_status_label": period_label,
|
||||
}
|
||||
|
||||
for event in events:
|
||||
amount = Decimal(str(event["amount"]))
|
||||
debit_total += amount
|
||||
credit_total += amount
|
||||
payer_id = int(event["payer_company_id"])
|
||||
payee_id = int(event["payee_company_id"])
|
||||
if payer_id in by_id:
|
||||
row = by_id[payer_id]
|
||||
row["detail_count"] = int(row["detail_count"]) + 1
|
||||
row["debit"] = Decimal(row["debit"]) + amount
|
||||
if payee_id in by_id:
|
||||
row = by_id[payee_id]
|
||||
row["detail_count"] = int(row["detail_count"]) + 1
|
||||
row["credit"] = Decimal(row["credit"]) + amount
|
||||
|
||||
items: list[dict[str, object]] = []
|
||||
for company in companies:
|
||||
row = by_id[int(company["id"])]
|
||||
debit = Decimal(row["debit"])
|
||||
credit = Decimal(row["credit"])
|
||||
# Payee inflow − payer outflow = signed net from this company's view.
|
||||
net = credit - debit
|
||||
items.append(
|
||||
{
|
||||
"id": row["id"],
|
||||
"name": row["name"],
|
||||
"detail_count": row["detail_count"],
|
||||
"debit_wan": _to_wan(debit),
|
||||
"credit_wan": _to_wan(credit),
|
||||
"net_wan": _to_wan(net),
|
||||
"period_status": row["period_status"],
|
||||
"period_status_label": row["period_status_label"],
|
||||
}
|
||||
)
|
||||
|
||||
totals = {
|
||||
"company_count": len(items),
|
||||
"detail_count": len(events),
|
||||
"debit_wan": _to_wan(debit_total),
|
||||
"credit_wan": _to_wan(credit_total),
|
||||
"net_wan": _to_wan(debit_total - credit_total),
|
||||
}
|
||||
return items, totals
|
||||
|
||||
|
||||
def period_progress(
|
||||
connection: sqlite3.Connection, *, year_month: str
|
||||
) -> dict[str, object]:
|
||||
"""Per-company coverage of the cutoff month: done / in progress / unsubmitted.
|
||||
|
||||
Only companies with at least one active bank account are counted — the same
|
||||
rule as monthly-close submission checks. Covered = confirmed source rows in
|
||||
the month, or an approved no-business attestation that spans the month.
|
||||
"""
|
||||
start, end = _month_bounds(year_month)
|
||||
enabled_rows = connection.execute(
|
||||
"SELECT DISTINCT company_id FROM bank_accounts WHERE status = 'active'"
|
||||
).fetchall()
|
||||
enabled_ids = {int(row["company_id"]) for row in enabled_rows}
|
||||
empty = {
|
||||
"year_month": year_month,
|
||||
"enabled_count": 0,
|
||||
"done": 0,
|
||||
"in_progress": 0,
|
||||
"unsubmitted": 0,
|
||||
"percent": 0,
|
||||
}
|
||||
if not enabled_ids:
|
||||
return empty
|
||||
|
||||
submitted = {
|
||||
int(row["company_id"])
|
||||
for row in connection.execute(
|
||||
"""
|
||||
SELECT DISTINCT b.company_id AS company_id
|
||||
FROM source_rows r
|
||||
JOIN sheet_batches s ON s.id = r.sheet_batch_id
|
||||
JOIN import_batches b ON b.id = s.import_batch_id
|
||||
JOIN sheet_reviews rv ON rv.sheet_batch_id = s.id AND rv.review_status = 'confirmed'
|
||||
WHERE date(r.transaction_at) >= date(?) AND date(r.transaction_at) <= date(?)
|
||||
""",
|
||||
(start, end),
|
||||
).fetchall()
|
||||
}
|
||||
attested = {
|
||||
int(row["company_id"])
|
||||
for row in connection.execute(
|
||||
"""
|
||||
SELECT DISTINCT a.company_id AS company_id
|
||||
FROM no_business_attestations a
|
||||
WHERE a.status = 'approved'
|
||||
AND date(a.gap_start) <= date(?)
|
||||
AND date(a.gap_end) >= date(?)
|
||||
""",
|
||||
(end, start),
|
||||
).fetchall()
|
||||
}
|
||||
covered = (submitted | attested) & enabled_ids
|
||||
|
||||
pending: set[int] = set()
|
||||
for row in connection.execute(
|
||||
"""
|
||||
SELECT DISTINCT p.company_id AS company_id
|
||||
FROM current_transfer_decisions c
|
||||
JOIN transfer_match_decisions d ON d.id = c.decision_id
|
||||
JOIN canonical_transfer_events e ON e.id = c.event_id
|
||||
JOIN transfer_decision_participants p ON p.decision_id = d.id
|
||||
WHERE e.lifecycle = 'active'
|
||||
AND d.classification IN ('unresolved', 'needs_review')
|
||||
AND date(d.effective_at) >= date(?) AND date(d.effective_at) <= date(?)
|
||||
""",
|
||||
(start, end),
|
||||
):
|
||||
pending.add(int(row["company_id"]))
|
||||
for row in connection.execute(
|
||||
"""
|
||||
SELECT DISTINCT m.company_id AS company_id
|
||||
FROM manual_records m
|
||||
JOIN current_manual_record_decisions c ON c.record_id = m.id
|
||||
JOIN manual_record_decisions d ON d.id = c.decision_id
|
||||
WHERE d.state = 'pending'
|
||||
AND date(m.occurred_at) >= date(?) AND date(m.occurred_at) <= date(?)
|
||||
""",
|
||||
(start, end),
|
||||
):
|
||||
pending.add(int(row["company_id"]))
|
||||
for row in connection.execute(
|
||||
"SELECT DISTINCT company_id FROM bank_accounts WHERE status = 'pending'"
|
||||
):
|
||||
pending.add(int(row["company_id"]))
|
||||
|
||||
pending_enabled = pending & enabled_ids
|
||||
done = covered - pending_enabled
|
||||
in_progress = pending_enabled
|
||||
unsubmitted = enabled_ids - covered - pending_enabled
|
||||
enabled_count = len(enabled_ids)
|
||||
percent = round(100 * len(done) / enabled_count) if enabled_count else 0
|
||||
return {
|
||||
"year_month": year_month,
|
||||
"enabled_count": enabled_count,
|
||||
"done": len(done),
|
||||
"in_progress": len(in_progress),
|
||||
"unsubmitted": len(unsubmitted),
|
||||
"percent": percent,
|
||||
}
|
||||
|
||||
|
||||
def company_peer_groups(
|
||||
connection: sqlite3.Connection,
|
||||
company_id: int,
|
||||
*,
|
||||
from_date: str,
|
||||
cutoff: str,
|
||||
) -> dict[str, object]:
|
||||
company = connection.execute(
|
||||
"SELECT id, name FROM companies WHERE id = ?", (company_id,)
|
||||
).fetchone()
|
||||
if company is None:
|
||||
raise KeyError(company_id)
|
||||
|
||||
events = connection.execute(
|
||||
"""
|
||||
SELECT e.event_id, e.effective_at, e.amount, e.currency,
|
||||
e.payer_company_id, e.payee_company_id,
|
||||
cpayer.name AS payer_name, cpayee.name AS payee_name
|
||||
FROM eligible_intercompany_events e
|
||||
JOIN companies cpayer ON cpayer.id = e.payer_company_id
|
||||
JOIN companies cpayee ON cpayee.id = e.payee_company_id
|
||||
WHERE (e.payer_company_id = ? OR e.payee_company_id = ?)
|
||||
AND date(e.effective_at) >= date(?)
|
||||
AND date(e.effective_at) <= date(?)
|
||||
ORDER BY e.effective_at, e.event_id
|
||||
""",
|
||||
(company_id, company_id, from_date, cutoff),
|
||||
).fetchall()
|
||||
|
||||
groups: dict[int, dict[str, object]] = {}
|
||||
for event in events:
|
||||
amount = Decimal(str(event["amount"]))
|
||||
payer_id = int(event["payer_company_id"])
|
||||
payee_id = int(event["payee_company_id"])
|
||||
if payer_id == company_id:
|
||||
peer_id = payee_id
|
||||
peer_name = event["payee_name"]
|
||||
direction = "debit"
|
||||
summary = f"付往 {peer_name}"
|
||||
else:
|
||||
peer_id = payer_id
|
||||
peer_name = event["payer_name"]
|
||||
direction = "credit"
|
||||
summary = f"收自 {peer_name}"
|
||||
|
||||
bucket = groups.get(peer_id)
|
||||
if bucket is None:
|
||||
bucket = {
|
||||
"peer_id": peer_id,
|
||||
"peer_name": peer_name,
|
||||
"count": 0,
|
||||
"opening": None,
|
||||
"opening_status": "unavailable",
|
||||
"debit": ZERO,
|
||||
"credit": ZERO,
|
||||
"lines": [],
|
||||
}
|
||||
groups[peer_id] = bucket
|
||||
|
||||
bucket["count"] = int(bucket["count"]) + 1
|
||||
if direction == "debit":
|
||||
bucket["debit"] = Decimal(bucket["debit"]) + amount
|
||||
else:
|
||||
bucket["credit"] = Decimal(bucket["credit"]) + amount
|
||||
|
||||
day = _parse_day(event["effective_at"]) or ""
|
||||
bucket["lines"].append(
|
||||
{
|
||||
"event_id": int(event["event_id"]),
|
||||
"date": day,
|
||||
"direction": direction,
|
||||
"summary": summary,
|
||||
"amount_wan": _to_wan(amount),
|
||||
"currency": event["currency"] or "CNY",
|
||||
}
|
||||
)
|
||||
|
||||
result_groups: list[dict[str, object]] = []
|
||||
for peer_id in sorted(groups.keys(), key=lambda i: groups[i]["peer_name"]):
|
||||
bucket = groups[peer_id]
|
||||
debit = Decimal(bucket["debit"])
|
||||
credit = Decimal(bucket["credit"])
|
||||
ending = credit - debit
|
||||
result_groups.append(
|
||||
{
|
||||
"peer_id": bucket["peer_id"],
|
||||
"peer_name": bucket["peer_name"],
|
||||
"count": bucket["count"],
|
||||
"opening": None,
|
||||
"opening_status": "unavailable",
|
||||
"debit_wan": _to_wan(debit),
|
||||
"credit_wan": _to_wan(credit),
|
||||
"ending_wan": _to_wan(ending),
|
||||
"result_kind": "period_net_change",
|
||||
"lines": bucket["lines"],
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"company_id": int(company["id"]),
|
||||
"company_name": company["name"],
|
||||
"from_date": from_date,
|
||||
"cutoff": cutoff,
|
||||
"groups": result_groups,
|
||||
}
|
||||
|
||||
|
||||
def weekly_flow(
|
||||
connection: sqlite3.Connection, *, cutoff: str, days: int = 7
|
||||
) -> dict[str, object]:
|
||||
end = datetime.strptime(cutoff, "%Y-%m-%d").date()
|
||||
start = end - timedelta(days=days - 1)
|
||||
labels: list[str] = []
|
||||
inflow = [ZERO] * days
|
||||
outflow = [ZERO] * days
|
||||
index: dict[str, int] = {}
|
||||
for offset in range(days):
|
||||
day = start + timedelta(days=offset)
|
||||
key = day.isoformat()
|
||||
index[key] = offset
|
||||
labels.append(f"{day.month:02d}-{day.day:02d}")
|
||||
|
||||
rows = connection.execute(
|
||||
"""
|
||||
SELECT date(e.effective_at) AS day, e.amount
|
||||
FROM eligible_intercompany_events e
|
||||
WHERE date(e.effective_at) >= date(?)
|
||||
AND date(e.effective_at) <= date(?)
|
||||
""",
|
||||
(start.isoformat(), cutoff),
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
day = row["day"]
|
||||
if day not in index:
|
||||
continue
|
||||
amount = Decimal(str(row["amount"]))
|
||||
# Group-level flow: every eligible transfer is both an outflow (payer)
|
||||
# and an inflow (payee); plot both series with the same absolute amount.
|
||||
inflow[index[day]] += amount
|
||||
outflow[index[day]] += amount
|
||||
|
||||
return {
|
||||
"labels": labels,
|
||||
"inflow_wan": [_to_wan(v) for v in inflow],
|
||||
"outflow_wan": [_to_wan(v) for v in outflow],
|
||||
}
|
||||
|
||||
|
||||
def build_dashboard(
|
||||
connection: sqlite3.Connection,
|
||||
*,
|
||||
from_date: str = "2026-01-01",
|
||||
cutoff: str | None = None,
|
||||
) -> dict[str, object]:
|
||||
cutoff_date = cutoff or today_shanghai()
|
||||
try:
|
||||
datetime.strptime(from_date, "%Y-%m-%d")
|
||||
datetime.strptime(cutoff_date, "%Y-%m-%d")
|
||||
except ValueError as exc:
|
||||
raise ValueError("日期必须是 YYYY-MM-DD") from exc
|
||||
if from_date > cutoff_date:
|
||||
raise ValueError("from 不能晚于 cutoff")
|
||||
|
||||
period = datetime.strptime(cutoff_date, "%Y-%m-%d")
|
||||
# Display month for the status column header: use the calendar month of cutoff.
|
||||
period_month = period.month
|
||||
companies, totals = company_summaries(
|
||||
connection, from_date=from_date, cutoff=cutoff_date
|
||||
)
|
||||
period_label = f"{period.year}-{period.month:02d}"
|
||||
return {
|
||||
"from_date": from_date,
|
||||
"cutoff": cutoff_date,
|
||||
"period_month": period_month,
|
||||
"period_label": period_label,
|
||||
"audit": audit_counts(connection),
|
||||
"totals": totals,
|
||||
"period_progress": period_progress(connection, year_month=period_label),
|
||||
"companies": companies,
|
||||
"weekly_flow": weekly_flow(connection, cutoff=cutoff_date),
|
||||
"opening_status": "unavailable",
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,172 +0,0 @@
|
||||
"""Server-side flow listing and export from confirmed source rows.
|
||||
|
||||
Lists and exports only cashier-confirmed worksheets. Match state is derived
|
||||
from current transfer decisions when a source row is claimed; otherwise the
|
||||
row is labelled 未归集. Company users only see their own company.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal, InvalidOperation
|
||||
import sqlite3
|
||||
|
||||
|
||||
def _dec(value: object) -> Decimal:
|
||||
try:
|
||||
return Decimal(str(value or "0"))
|
||||
except (InvalidOperation, TypeError):
|
||||
return Decimal("0")
|
||||
|
||||
|
||||
def _direction(income: object, expense: object) -> tuple[str, Decimal]:
|
||||
income_d = _dec(income)
|
||||
expense_d = _dec(expense)
|
||||
if expense_d > 0 and income_d <= 0:
|
||||
return "付", expense_d
|
||||
return "收", income_d if income_d > 0 else expense_d
|
||||
|
||||
|
||||
def _status_label(classification: str | None, pairing: str | None, locked: int | None) -> tuple[str, str]:
|
||||
if classification in ("unresolved", "needs_review"):
|
||||
return "单边", "danger"
|
||||
if classification == "intercompany" and pairing == "paired":
|
||||
return "已归集", "success"
|
||||
if classification == "intercompany" and locked:
|
||||
return "已归集", "success"
|
||||
if classification == "intercompany":
|
||||
return "待确认", "warn"
|
||||
if classification == "same_company":
|
||||
return "同公司调拨", "muted"
|
||||
if classification == "external":
|
||||
return "未归集 · 外部", "muted"
|
||||
if classification:
|
||||
return "未归集", "muted"
|
||||
return "未归集", "muted"
|
||||
|
||||
|
||||
def list_flows(
|
||||
connection: sqlite3.Connection,
|
||||
*,
|
||||
company_id: int | None = None,
|
||||
bank: str | None = None,
|
||||
account: str | None = None,
|
||||
start: str | None = None,
|
||||
end: str | None = None,
|
||||
keyword: str | None = None,
|
||||
limit: int = 200,
|
||||
offset: int = 0,
|
||||
) -> dict[str, object]:
|
||||
clauses = ["rv.review_status = 'confirmed'"]
|
||||
params: list[object] = []
|
||||
if company_id is not None:
|
||||
clauses.append("b.company_id = ?")
|
||||
params.append(int(company_id))
|
||||
if start:
|
||||
clauses.append("date(r.transaction_at) >= date(?)")
|
||||
params.append(start)
|
||||
if end:
|
||||
clauses.append("date(r.transaction_at) <= date(?)")
|
||||
params.append(end)
|
||||
if account:
|
||||
clauses.append("r.own_account LIKE ?")
|
||||
params.append(f"%{account}%")
|
||||
if bank:
|
||||
clauses.append("(COALESCE(ba.bank_name, '') LIKE ? OR r.own_name LIKE ?)")
|
||||
params.extend([f"%{bank}%", f"%{bank}%"])
|
||||
if keyword:
|
||||
like = f"%{keyword}%"
|
||||
clauses.append(
|
||||
"(r.counterparty_name LIKE ? OR r.summary LIKE ? OR r.reference LIKE ? "
|
||||
"OR r.purpose LIKE ? OR c.name LIKE ?)"
|
||||
)
|
||||
params.extend([like, like, like, like, like])
|
||||
where = " AND ".join(clauses)
|
||||
limit = max(1, min(int(limit), 500))
|
||||
offset = max(0, int(offset))
|
||||
count_row = connection.execute(
|
||||
f"""
|
||||
SELECT COUNT(*) AS n
|
||||
FROM source_rows r
|
||||
JOIN sheet_batches s ON s.id = r.sheet_batch_id
|
||||
JOIN import_batches b ON b.id = s.import_batch_id
|
||||
JOIN sheet_reviews rv ON rv.sheet_batch_id = s.id
|
||||
JOIN companies c ON c.id = b.company_id
|
||||
LEFT JOIN bank_accounts ba ON ba.account_number = r.own_account
|
||||
WHERE {where}
|
||||
""",
|
||||
params,
|
||||
).fetchone()
|
||||
rows = connection.execute(
|
||||
f"""
|
||||
SELECT r.id, r.transaction_at, r.income, r.expense, r.balance,
|
||||
r.own_account, r.own_name, r.counterparty_account, r.counterparty_name,
|
||||
r.counterparty_bank, r.summary, r.purpose, r.reference, r.currency,
|
||||
b.id AS batch_id, b.company_id, c.name AS company_name,
|
||||
COALESCE(ba.bank_name, '') AS bank_name,
|
||||
s.sheet_name, r.source_row,
|
||||
d.classification, d.pairing, d.locked, d.effective_at
|
||||
FROM source_rows r
|
||||
JOIN sheet_batches s ON s.id = r.sheet_batch_id
|
||||
JOIN import_batches b ON b.id = s.import_batch_id
|
||||
JOIN sheet_reviews rv ON rv.sheet_batch_id = s.id
|
||||
JOIN companies c ON c.id = b.company_id
|
||||
LEFT JOIN bank_accounts ba ON ba.account_number = r.own_account
|
||||
LEFT JOIN transfer_observation_claims toc ON toc.source_row_id = r.id
|
||||
LEFT JOIN transfer_match_decisions d ON d.id = toc.decision_id
|
||||
WHERE {where}
|
||||
ORDER BY r.transaction_at DESC, r.id DESC
|
||||
LIMIT ? OFFSET ?
|
||||
""",
|
||||
[*params, limit, offset],
|
||||
).fetchall()
|
||||
items = []
|
||||
inflow = Decimal("0")
|
||||
outflow = Decimal("0")
|
||||
for row in rows:
|
||||
direction, amount = _direction(row["income"], row["expense"])
|
||||
if direction == "收":
|
||||
inflow += amount
|
||||
else:
|
||||
outflow += amount
|
||||
status, status_kind = _status_label(
|
||||
row["classification"], row["pairing"], row["locked"]
|
||||
)
|
||||
tail = str(row["own_account"] or "")[-4:]
|
||||
items.append(
|
||||
{
|
||||
"id": int(row["id"]),
|
||||
"date": str(row["transaction_at"] or "")[:10],
|
||||
"time": str(row["transaction_at"] or ""),
|
||||
"company_id": int(row["company_id"]),
|
||||
"company": row["company_name"],
|
||||
"bank": row["bank_name"] or "",
|
||||
"account": row["own_account"],
|
||||
"account_label": (
|
||||
f"{row['bank_name']} · 尾号 {tail}" if row["bank_name"] and tail else (row["own_account"] or "—")
|
||||
),
|
||||
"own_name": row["own_name"],
|
||||
"direction": direction,
|
||||
"peer": row["counterparty_name"] or "—",
|
||||
"peer_account": row["counterparty_account"] or "—",
|
||||
"peer_bank": row["counterparty_bank"] or "—",
|
||||
"summary": row["summary"] or row["purpose"] or "—",
|
||||
"serial": row["reference"] or "—",
|
||||
"status": status,
|
||||
"status_kind": status_kind,
|
||||
"amount": str(amount),
|
||||
"balance": str(row["balance"] or ""),
|
||||
"currency": row["currency"] or "CNY",
|
||||
"batch_id": int(row["batch_id"]),
|
||||
"batch": f"IMP-{int(row['batch_id']):06d}",
|
||||
"locator": f"{row['sheet_name']}!R{row['source_row']}",
|
||||
"year_month": str(row["transaction_at"] or "")[:7],
|
||||
}
|
||||
)
|
||||
return {
|
||||
"items": items,
|
||||
"total": int(count_row["n"]),
|
||||
"inflow": str(inflow),
|
||||
"outflow": str(outflow),
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
}
|
||||
@@ -1,671 +0,0 @@
|
||||
"""Immutable statement import pipeline with per-worksheet review lifecycle.
|
||||
|
||||
Every uploaded file is hashed (SHA-256) and written once to content-addressed
|
||||
storage before parsing. A repeated upload of identical bytes never creates a
|
||||
second set of facts: it records a ``duplicate`` batch that points at the
|
||||
original batch. Parse failures keep the batch and its diagnostics as an
|
||||
``exception`` batch without producing any confirmed source rows.
|
||||
|
||||
Each worksheet is parsed independently into a :class:`SheetResult`
|
||||
(``parsed`` / ``exception`` / ``ignored``) that is persisted in
|
||||
``sheet_reviews`` as immutable evidence. Whether a parsed sheet may take part
|
||||
in later matching and calculation is a separate, auditable human decision
|
||||
(``review_status``): only ``confirmed`` sheets participate.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sqlite3
|
||||
import tempfile
|
||||
|
||||
from . import auth
|
||||
from . import ledger_events
|
||||
from . import matching
|
||||
from .db import utc_now
|
||||
from .models import SheetResult, StatementBatch
|
||||
from .parser import StatementParseError, analyze_workbook
|
||||
from .reader import CorruptWorkbookError
|
||||
|
||||
|
||||
class SheetReviewError(ValueError):
|
||||
"""A review decision cannot be applied to the worksheet (mapped to 409)."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ImportResult:
|
||||
batch_id: int
|
||||
status: str # parsed | duplicate | exception
|
||||
sha256: str
|
||||
source_file_id: int
|
||||
batches: tuple[StatementBatch, ...] = ()
|
||||
sheets: tuple[SheetResult, ...] = ()
|
||||
message: str | None = None
|
||||
duplicate_same_company: bool = False # only meaningful when status == 'duplicate'
|
||||
|
||||
|
||||
def import_statement(
|
||||
connection: sqlite3.Connection,
|
||||
storage_dir: str | Path,
|
||||
original_filename: str,
|
||||
content: bytes,
|
||||
company_id: int | None = None,
|
||||
upload_bank_account_id: int | None = None,
|
||||
) -> ImportResult:
|
||||
sha256 = hashlib.sha256(content).hexdigest()
|
||||
existing_file = connection.execute(
|
||||
"SELECT id FROM source_files WHERE sha256 = ?", (sha256,)
|
||||
).fetchone()
|
||||
|
||||
if existing_file is not None:
|
||||
return _record_duplicate(connection, existing_file["id"], sha256, company_id)
|
||||
|
||||
stored_path = _store_immutable(Path(storage_dir), original_filename, content, sha256)
|
||||
try:
|
||||
source_file_id, batch_id = _create_batch_records(
|
||||
connection, sha256, original_filename, len(content), stored_path,
|
||||
company_id, upload_bank_account_id,
|
||||
)
|
||||
except sqlite3.IntegrityError:
|
||||
# Lost a concurrent-insert race on the sha256 UNIQUE constraint: the
|
||||
# identical content was already persisted by another request, so this
|
||||
# upload is a duplicate. The content-addressed file already exists.
|
||||
existing = connection.execute(
|
||||
"SELECT id FROM source_files WHERE sha256 = ?", (sha256,)
|
||||
).fetchone()
|
||||
if existing is not None:
|
||||
return _record_duplicate(connection, existing["id"], sha256, company_id)
|
||||
raise
|
||||
return _parse_and_persist(
|
||||
connection, stored_path, sha256, original_filename, source_file_id, batch_id
|
||||
)
|
||||
|
||||
|
||||
def import_statement_path(
|
||||
connection: sqlite3.Connection,
|
||||
storage_dir: str | Path,
|
||||
original_filename: str,
|
||||
upload_path: str | Path,
|
||||
company_id: int | None = None,
|
||||
upload_bank_account_id: int | None = None,
|
||||
) -> ImportResult:
|
||||
"""Import from an already-downloaded upload file (streaming-friendly).
|
||||
|
||||
``upload_path`` names the temp file the multipart handler streamed to
|
||||
disk; it is hashed incrementally and either discarded (duplicate) or
|
||||
published into the content-addressed store. The upload file itself is
|
||||
never modified. The approved ``upload_bank_account_id`` used at upload time
|
||||
is persisted on the batch so ownership can be resolved later even when the
|
||||
source rows carry no own account.
|
||||
"""
|
||||
source = Path(upload_path)
|
||||
sha256 = _file_sha256(source)
|
||||
existing_file = connection.execute(
|
||||
"SELECT id FROM source_files WHERE sha256 = ?", (sha256,)
|
||||
).fetchone()
|
||||
|
||||
if existing_file is not None:
|
||||
source.unlink(missing_ok=True)
|
||||
return _record_duplicate(connection, existing_file["id"], sha256, company_id)
|
||||
|
||||
stored_path = _publish_immutable(Path(storage_dir), original_filename, source, sha256)
|
||||
size = stored_path.stat().st_size
|
||||
try:
|
||||
source_file_id, batch_id = _create_batch_records(
|
||||
connection, sha256, original_filename, size, stored_path,
|
||||
company_id, upload_bank_account_id,
|
||||
)
|
||||
except sqlite3.IntegrityError:
|
||||
# Lost a concurrent-insert race on the sha256 UNIQUE constraint: the
|
||||
# identical content was already persisted by another request, so this
|
||||
# upload is a duplicate. The content-addressed file already exists.
|
||||
existing = connection.execute(
|
||||
"SELECT id FROM source_files WHERE sha256 = ?", (sha256,)
|
||||
).fetchone()
|
||||
if existing is not None:
|
||||
return _record_duplicate(connection, existing["id"], sha256, company_id)
|
||||
raise
|
||||
return _parse_and_persist(
|
||||
connection, stored_path, sha256, original_filename, source_file_id, batch_id
|
||||
)
|
||||
|
||||
|
||||
def _create_batch_records(
|
||||
connection: sqlite3.Connection,
|
||||
sha256: str,
|
||||
original_filename: str,
|
||||
size_bytes: int,
|
||||
stored_path: Path,
|
||||
company_id: int | None,
|
||||
upload_bank_account_id: int | None,
|
||||
) -> tuple[int, int]:
|
||||
now = utc_now()
|
||||
with connection:
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO source_files (sha256, original_filename, size_bytes, storage_path, created_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
""",
|
||||
(sha256, original_filename, size_bytes, str(stored_path), now),
|
||||
)
|
||||
source_file_id = cursor.lastrowid
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO import_batches (source_file_id, status, company_id, upload_bank_account_id, created_at, updated_at)
|
||||
VALUES (?, 'parsing', ?, ?, ?, ?)
|
||||
""",
|
||||
(source_file_id, company_id, upload_bank_account_id, now, now),
|
||||
)
|
||||
batch_id = cursor.lastrowid
|
||||
return source_file_id, batch_id
|
||||
|
||||
|
||||
def _parse_and_persist(
|
||||
connection: sqlite3.Connection,
|
||||
stored_path: Path,
|
||||
sha256: str,
|
||||
original_filename: str,
|
||||
source_file_id: int,
|
||||
batch_id: int,
|
||||
) -> ImportResult:
|
||||
try:
|
||||
sheets = analyze_workbook(stored_path)
|
||||
except CorruptWorkbookError as exc:
|
||||
message = _clean_message(str(exc), stored_path, original_filename)
|
||||
with connection:
|
||||
_insert_exception(
|
||||
connection, batch_id, "parse", message, original_filename,
|
||||
diagnostics={"original_filename": original_filename},
|
||||
)
|
||||
_set_batch_status(connection, batch_id, "exception")
|
||||
return ImportResult(batch_id, "exception", sha256, source_file_id, message=message)
|
||||
except Exception as exc:
|
||||
message = f"文件解析失败,请检查文件是否完整。({type(exc).__name__})"
|
||||
with connection:
|
||||
_insert_exception(
|
||||
connection, batch_id, "internal", message, original_filename,
|
||||
diagnostics={"original_filename": original_filename},
|
||||
)
|
||||
_set_batch_status(connection, batch_id, "failed")
|
||||
raise
|
||||
|
||||
with connection:
|
||||
parsed_batches: list[StatementBatch] = []
|
||||
for sheet in sheets:
|
||||
if sheet.outcome == "parsed" and sheet.batch is not None:
|
||||
sheet_batch_id = _insert_sheet_batch(connection, batch_id, sheet.batch)
|
||||
_insert_sheet_review(connection, batch_id, sheet, sheet_batch_id)
|
||||
parsed_batches.append(sheet.batch)
|
||||
else:
|
||||
_insert_sheet_review(connection, batch_id, sheet, None)
|
||||
if not parsed_batches:
|
||||
message = _whole_file_message(original_filename, sheets)
|
||||
with connection:
|
||||
_insert_exception(
|
||||
connection, batch_id, "parse", message, original_filename,
|
||||
diagnostics=_exception_diagnostics(original_filename, sheets),
|
||||
)
|
||||
_set_batch_status(connection, batch_id, "exception")
|
||||
return ImportResult(
|
||||
batch_id, "exception", sha256, source_file_id,
|
||||
message=message, sheets=sheets,
|
||||
)
|
||||
_set_batch_status(connection, batch_id, "parsed")
|
||||
return ImportResult(
|
||||
batch_id, "parsed", sha256, source_file_id,
|
||||
batches=tuple(parsed_batches), sheets=sheets,
|
||||
)
|
||||
|
||||
|
||||
def _record_duplicate(
|
||||
connection: sqlite3.Connection,
|
||||
source_file_id: int,
|
||||
sha256: str,
|
||||
company_id: int | None = None,
|
||||
) -> ImportResult:
|
||||
original = connection.execute(
|
||||
"""
|
||||
SELECT id, company_id FROM import_batches
|
||||
WHERE source_file_id = ? AND status = 'parsed'
|
||||
ORDER BY id LIMIT 1
|
||||
""",
|
||||
(source_file_id,),
|
||||
).fetchone()
|
||||
if original is None:
|
||||
original = connection.execute(
|
||||
"""
|
||||
SELECT id, company_id FROM import_batches
|
||||
WHERE source_file_id = ? AND status != 'duplicate'
|
||||
ORDER BY id LIMIT 1
|
||||
""",
|
||||
(source_file_id,),
|
||||
).fetchone()
|
||||
now = utc_now()
|
||||
with connection:
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO import_batches
|
||||
(source_file_id, status, duplicate_of_id, company_id, diagnostics, created_at, updated_at)
|
||||
VALUES (?, 'duplicate', ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
source_file_id,
|
||||
original["id"],
|
||||
company_id,
|
||||
json.dumps({"note": "内容哈希相同,复用已有批次,不产生第二份事实。"}, ensure_ascii=False),
|
||||
now,
|
||||
now,
|
||||
),
|
||||
)
|
||||
# A duplicate is only "same company" when the uploader belongs to the
|
||||
# same tenant that owns the original batch. Cross-company duplicates
|
||||
# must stay opaque: the caller gets the new duplicate batch id (which
|
||||
# belongs to its own company) but never the other company's batch id.
|
||||
same_company = original["company_id"] == company_id
|
||||
if same_company:
|
||||
batch_id = original["id"]
|
||||
else:
|
||||
batch_id = int(cursor.lastrowid)
|
||||
return ImportResult(
|
||||
batch_id,
|
||||
"duplicate",
|
||||
sha256,
|
||||
source_file_id,
|
||||
message="相同内容的文件已导入,本次按重复上传处理。",
|
||||
duplicate_same_company=same_company,
|
||||
)
|
||||
|
||||
|
||||
def _store_immutable(
|
||||
storage_dir: Path, original_filename: str, content: bytes, sha256: str
|
||||
) -> Path:
|
||||
suffix = Path(original_filename).suffix.lower()
|
||||
target_dir = storage_dir / sha256[:2]
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
target = target_dir / f"{sha256}{suffix}"
|
||||
# Publish via a unique temporary file + hard link: the content-addressed
|
||||
# target either appears complete or not at all, and is never overwritten.
|
||||
# The temp name is unique per writer, so concurrent uploads of the same
|
||||
# bytes cannot corrupt each other's staging file (B-43 baseline fix).
|
||||
fd, temp_path = tempfile.mkstemp(prefix=f".{sha256}.", suffix=".tmp", dir=target_dir)
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as handle:
|
||||
handle.write(content)
|
||||
try:
|
||||
os.link(temp_path, target)
|
||||
except FileExistsError:
|
||||
# Content-addressed name means identical bytes; never overwrite.
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
os.unlink(temp_path)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
return target
|
||||
|
||||
|
||||
def _publish_immutable(
|
||||
storage_dir: Path, original_filename: str, upload_path: Path, sha256: str
|
||||
) -> Path:
|
||||
suffix = Path(original_filename).suffix.lower()
|
||||
target_dir = storage_dir / sha256[:2]
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
target = target_dir / f"{sha256}{suffix}"
|
||||
fd, temp_path = tempfile.mkstemp(prefix=f".{sha256}.", suffix=".tmp", dir=target_dir)
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as handle:
|
||||
# Copy keeps the same-filesystem guarantee even if the upload temp
|
||||
# lives elsewhere; the hard link then publishes atomically. The
|
||||
# staging file is unique per writer, so two concurrent uploads of
|
||||
# the same bytes never corrupt each other's copy.
|
||||
with upload_path.open("rb") as source:
|
||||
shutil.copyfileobj(source, handle, length=1024 * 1024)
|
||||
try:
|
||||
os.link(temp_path, target)
|
||||
except FileExistsError:
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
os.unlink(temp_path)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
upload_path.unlink(missing_ok=True)
|
||||
return target
|
||||
|
||||
|
||||
def _file_sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as handle:
|
||||
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _insert_sheet_batch(
|
||||
connection: sqlite3.Connection, batch_id: int, batch: StatementBatch
|
||||
) -> int:
|
||||
now = utc_now()
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO sheet_batches (
|
||||
import_batch_id, sheet_name, bank_name, template_id, template_version,
|
||||
header_row, own_account, own_name, period_start, period_end,
|
||||
transaction_count, warnings, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
batch_id,
|
||||
batch.sheet_name,
|
||||
batch.bank_name,
|
||||
batch.template_id,
|
||||
batch.template_version,
|
||||
batch.header_row,
|
||||
batch.own_account,
|
||||
batch.own_name,
|
||||
batch.period_start.isoformat() if batch.period_start else None,
|
||||
batch.period_end.isoformat() if batch.period_end else None,
|
||||
len(batch.transactions),
|
||||
json.dumps(list(batch.warnings), ensure_ascii=False),
|
||||
now,
|
||||
),
|
||||
)
|
||||
sheet_batch_id = cursor.lastrowid
|
||||
for transaction in batch.transactions:
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO source_rows (
|
||||
sheet_batch_id, source_row, transaction_at, income, expense, balance,
|
||||
own_account, own_name, counterparty_account, counterparty_name,
|
||||
counterparty_bank, summary, purpose, reference, currency, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
sheet_batch_id,
|
||||
transaction.source_row,
|
||||
transaction.transaction_at.isoformat(),
|
||||
str(transaction.income),
|
||||
str(transaction.expense),
|
||||
str(transaction.balance) if transaction.balance is not None else None,
|
||||
transaction.own_account,
|
||||
transaction.own_name,
|
||||
transaction.counterparty_account,
|
||||
transaction.counterparty_name,
|
||||
transaction.counterparty_bank,
|
||||
transaction.summary,
|
||||
transaction.purpose,
|
||||
transaction.reference,
|
||||
transaction.currency,
|
||||
now,
|
||||
),
|
||||
)
|
||||
return sheet_batch_id
|
||||
|
||||
|
||||
def _insert_sheet_review(
|
||||
connection: sqlite3.Connection,
|
||||
batch_id: int,
|
||||
sheet: SheetResult,
|
||||
sheet_batch_id: int | None,
|
||||
) -> None:
|
||||
# Parse-side ignored sheets are terminal: there is nothing to confirm, so
|
||||
# their review lifecycle is closed with a machine reason.
|
||||
if sheet.outcome == "ignored":
|
||||
review_status = "ignored"
|
||||
review_reason = "空表或无有效内容,自动忽略。"
|
||||
else:
|
||||
review_status = "pending"
|
||||
review_reason = None
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO sheet_reviews (
|
||||
import_batch_id, sheet_name, outcome, message, scanned_rows,
|
||||
candidate_headers, sheet_batch_id, review_status, review_reason, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
batch_id,
|
||||
sheet.sheet_name,
|
||||
sheet.outcome,
|
||||
sheet.message,
|
||||
sheet.scanned_rows,
|
||||
json.dumps(list(sheet.candidate_headers), ensure_ascii=False)
|
||||
if sheet.candidate_headers
|
||||
else None,
|
||||
sheet_batch_id,
|
||||
review_status,
|
||||
review_reason,
|
||||
utc_now(),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _insert_exception(
|
||||
connection: sqlite3.Connection,
|
||||
batch_id: int,
|
||||
stage: str,
|
||||
message: str,
|
||||
original_filename: str,
|
||||
*,
|
||||
diagnostics: dict[str, object] | None = None,
|
||||
) -> None:
|
||||
payload = {"original_filename": original_filename}
|
||||
if diagnostics:
|
||||
payload.update(diagnostics)
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO import_exceptions (import_batch_id, stage, message, diagnostics, created_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
batch_id,
|
||||
stage,
|
||||
message,
|
||||
json.dumps(payload, ensure_ascii=False),
|
||||
utc_now(),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _set_batch_status(connection: sqlite3.Connection, batch_id: int, status: str) -> None:
|
||||
connection.execute(
|
||||
"UPDATE import_batches SET status = ?, updated_at = ? WHERE id = ?",
|
||||
(status, utc_now(), batch_id),
|
||||
)
|
||||
|
||||
|
||||
def _whole_file_message(original_filename: str, sheets: tuple[SheetResult, ...]) -> str:
|
||||
detail = ";".join(
|
||||
f"{sheet.sheet_name}:{sheet.message}" for sheet in sheets if sheet.message
|
||||
)
|
||||
return f"文件「{original_filename}」没有可确认的工作表。{detail}"
|
||||
|
||||
|
||||
def _exception_diagnostics(
|
||||
original_filename: str, sheets: tuple[SheetResult, ...]
|
||||
) -> dict[str, object]:
|
||||
return {
|
||||
"original_filename": original_filename,
|
||||
"sheets": [
|
||||
{
|
||||
"sheet_name": sheet.sheet_name,
|
||||
"outcome": sheet.outcome,
|
||||
"message": sheet.message,
|
||||
"scanned_rows": sheet.scanned_rows,
|
||||
"candidate_headers": list(sheet.candidate_headers),
|
||||
}
|
||||
for sheet in sheets
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _clean_message(message: str, stored_path: Path, original_filename: str) -> str:
|
||||
return message.replace(str(stored_path), original_filename).replace(
|
||||
stored_path.name, original_filename
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Per-sheet review lifecycle
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def sheet_review_rows(connection: sqlite3.Connection, batch_id: int) -> list[sqlite3.Row]:
|
||||
return connection.execute(
|
||||
"""
|
||||
SELECT r.id, r.sheet_name, r.outcome, r.message, r.scanned_rows,
|
||||
r.candidate_headers, r.review_status, r.review_reason,
|
||||
r.reviewed_by, r.reviewed_at,
|
||||
s.bank_name, s.template_id, s.header_row, s.own_account, s.own_name,
|
||||
s.period_start, s.period_end, s.transaction_count, s.warnings
|
||||
FROM sheet_reviews r
|
||||
LEFT JOIN sheet_batches s ON s.id = r.sheet_batch_id
|
||||
WHERE r.import_batch_id = ?
|
||||
ORDER BY r.id
|
||||
""",
|
||||
(batch_id,),
|
||||
).fetchall()
|
||||
|
||||
|
||||
def scoped_batch(
|
||||
connection: sqlite3.Connection, batch_id: int, company_id: int | None
|
||||
) -> sqlite3.Row | None:
|
||||
"""Load a batch, scoping company users to their own tenant.
|
||||
|
||||
``company_id is None`` (admin) sees any batch; a company user only sees
|
||||
batches owned by that company. Returns None when out of scope so callers
|
||||
can answer 404 without leaking the batch's existence.
|
||||
"""
|
||||
if company_id is None:
|
||||
return connection.execute(
|
||||
"SELECT id, company_id FROM import_batches WHERE id = ?", (batch_id,)
|
||||
).fetchone()
|
||||
return connection.execute(
|
||||
"SELECT id, company_id FROM import_batches WHERE id = ? AND company_id = ?",
|
||||
(batch_id, company_id),
|
||||
).fetchone()
|
||||
|
||||
|
||||
def review_sheets(
|
||||
connection: sqlite3.Connection,
|
||||
batch_id: int,
|
||||
sheet_names: list[str],
|
||||
decision: str,
|
||||
actor: sqlite3.Row | None,
|
||||
company_id: int | None,
|
||||
reason: str | None = None,
|
||||
) -> dict[str, object]:
|
||||
"""Apply ``confirm`` or ``ignore`` to whole worksheets atomically.
|
||||
|
||||
Multi-sheet writes run in one transaction; a failure rolls back every
|
||||
sheet in the request. Idempotent repeats of the same decision succeed
|
||||
without touching the audit log; changing a settled decision is a
|
||||
conflict. Returns ``{"updated": [...], "already": [...]}``.
|
||||
"""
|
||||
if decision not in ("confirm", "ignore"):
|
||||
raise ValueError("decision 必须是 confirm 或 ignore。")
|
||||
names = [str(name).strip() for name in sheet_names]
|
||||
if not names:
|
||||
raise ValueError("必须至少指定一个工作表。")
|
||||
reason = (reason or "").strip() or None
|
||||
if decision == "ignore" and not reason:
|
||||
raise ValueError("忽略工作表必须填写原因。")
|
||||
|
||||
batch = scoped_batch(connection, batch_id, company_id)
|
||||
if batch is None:
|
||||
raise LookupError("批次不存在。")
|
||||
|
||||
placeholders = ",".join("?" for _ in names)
|
||||
rows = connection.execute(
|
||||
f"""
|
||||
SELECT * FROM sheet_reviews
|
||||
WHERE import_batch_id = ? AND sheet_name IN ({placeholders})
|
||||
""",
|
||||
(batch_id, *names),
|
||||
).fetchall()
|
||||
found = {row["sheet_name"] for row in rows}
|
||||
missing = [name for name in names if name not in found]
|
||||
if missing:
|
||||
raise ValueError(f"工作表不存在或不属于该批次:{'、'.join(missing)}")
|
||||
|
||||
target = "confirmed" if decision == "confirm" else "ignored"
|
||||
now = utc_now()
|
||||
updated: list[str] = []
|
||||
already: list[str] = []
|
||||
matching_result: dict[str, object] | None = None
|
||||
# BEGIN IMMEDIATE serializes concurrent confirmations: the write lock is
|
||||
# taken before the read, so two cashiers confirming matching worksheets can
|
||||
# never derive their match decisions from stale snapshots.
|
||||
began = False
|
||||
if not connection.in_transaction:
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
began = True
|
||||
try:
|
||||
for row in rows:
|
||||
if row["review_status"] == target:
|
||||
already.append(row["sheet_name"])
|
||||
continue
|
||||
if decision == "confirm" and row["outcome"] != "parsed":
|
||||
raise SheetReviewError(
|
||||
f"工作表「{row['sheet_name']}」没有可确认的交易,只能忽略或保留待处理。"
|
||||
)
|
||||
if row["review_status"] != "pending":
|
||||
raise SheetReviewError(
|
||||
f"工作表「{row['sheet_name']}」已处理,不能更改决定。"
|
||||
)
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
UPDATE sheet_reviews
|
||||
SET review_status = ?, review_reason = ?, reviewed_by = ?, reviewed_at = ?
|
||||
WHERE id = ? AND review_status = 'pending'
|
||||
""",
|
||||
(target, reason, actor["id"] if actor is not None else None, now, row["id"]),
|
||||
)
|
||||
if cursor.rowcount:
|
||||
updated.append(row["sheet_name"])
|
||||
|
||||
# Confirming a worksheet and reconciling its rows must succeed or fail
|
||||
# together: any matching failure rolls the confirmation back, so there
|
||||
# is never a "confirmed but unmatched" half state.
|
||||
if updated and decision == "confirm":
|
||||
placeholders = ",".join("?" for _ in updated)
|
||||
confirmed_rows = connection.execute(
|
||||
f"""
|
||||
SELECT r.id FROM source_rows r
|
||||
JOIN sheet_batches s ON s.id = r.sheet_batch_id
|
||||
JOIN sheet_reviews rv ON rv.sheet_batch_id = s.id
|
||||
WHERE rv.sheet_name IN ({placeholders})
|
||||
AND rv.import_batch_id = ?
|
||||
ORDER BY r.id
|
||||
""",
|
||||
(*updated, batch_id),
|
||||
).fetchall()
|
||||
matching_result = matching.reconcile_rows(
|
||||
connection,
|
||||
[item["id"] for item in confirmed_rows],
|
||||
actor=actor,
|
||||
)
|
||||
ledger_events.reconcile_bank_events(connection, actor=actor)
|
||||
if updated:
|
||||
auth.audit(
|
||||
connection,
|
||||
f"sheet_{decision}",
|
||||
actor=actor,
|
||||
target=f"batch:{batch_id}",
|
||||
detail=f"sheets:{','.join(updated)}" + (f";reason:{reason}" if reason else ""),
|
||||
)
|
||||
if began:
|
||||
connection.commit()
|
||||
except Exception:
|
||||
if began:
|
||||
connection.rollback()
|
||||
raise
|
||||
|
||||
payload: dict[str, object] = {"updated": updated, "already": already}
|
||||
if matching_result is not None:
|
||||
payload["matching"] = matching_result
|
||||
return payload
|
||||
@@ -1,689 +0,0 @@
|
||||
"""Canonical intercompany ledger events and the revision chain (B-44).
|
||||
|
||||
Bank source rows and approved manual records are immutable evidence. This
|
||||
module turns them into one canonical ledger event each through ``reconcile_*``
|
||||
functions and an append-only revision chain. Corrections are never in-place
|
||||
edits: a reversal or adjustment is a new ledger event with its own effective
|
||||
date, and the original event keeps its history so no earlier cutoff is
|
||||
rewritten. Current revisions and source claims are rebuildable projections.
|
||||
|
||||
Only B-43 ``eligible_intercompany_events`` feeds bank facts here; same-company
|
||||
transfers, external transactions, unresolved rows and unlocked single
|
||||
observations never reach the confirmed balance.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal, InvalidOperation
|
||||
import json
|
||||
import sqlite3
|
||||
|
||||
from .db import transaction, utc_now
|
||||
from .subjects import MIRROR, SUBJECTS, mirror_subject
|
||||
|
||||
|
||||
class LedgerConflictError(ValueError):
|
||||
"""A revision/claim/idempotency conflict (mapped to HTTP 409)."""
|
||||
|
||||
|
||||
class LedgerInputError(ValueError):
|
||||
"""Invalid input for a ledger operation (mapped to HTTP 400/422)."""
|
||||
|
||||
|
||||
SUBJECT_RULE_VERSION = "subject-suggest-draft-v1"
|
||||
|
||||
|
||||
def amount_scale(amount: object) -> int:
|
||||
"""Decimal places of a decimal-string amount, never negative."""
|
||||
try:
|
||||
exponent = Decimal(str(amount)).as_tuple().exponent
|
||||
except InvalidOperation:
|
||||
return 0
|
||||
return max(0, -int(exponent))
|
||||
|
||||
|
||||
def parse_amount(amount: object) -> Decimal:
|
||||
"""Parse a positive, valid decimal-string amount."""
|
||||
try:
|
||||
value = Decimal(str(amount))
|
||||
except InvalidOperation:
|
||||
raise LedgerInputError("金额不是有效的十进制数。") from None
|
||||
if not value.is_finite() or value <= 0:
|
||||
raise LedgerInputError("金额必须大于零。")
|
||||
return value
|
||||
|
||||
|
||||
def _company_exists(connection: sqlite3.Connection, company_id: int, label: str) -> None:
|
||||
row = connection.execute(
|
||||
"SELECT id FROM companies WHERE id = ?", (company_id,)
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise LedgerInputError(f"{label}指向的公司不存在。")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Revision helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _ensure_transaction(connection: sqlite3.Connection) -> bool:
|
||||
"""Begin an immediate transaction unless one is already open.
|
||||
|
||||
Write helpers may run standalone (they own the transaction) or nested
|
||||
inside a caller's transaction (e.g. the sheet-confirm flow); nested calls
|
||||
never start their own commit.
|
||||
"""
|
||||
began = False
|
||||
if not connection.in_transaction:
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
began = True
|
||||
return began
|
||||
|
||||
|
||||
def current_revision(connection: sqlite3.Connection, ledger_event_id: int) -> sqlite3.Row | None:
|
||||
return connection.execute(
|
||||
"""
|
||||
SELECT r.* FROM current_ledger_event_revisions c
|
||||
JOIN ledger_event_revisions r ON r.id = c.revision_id
|
||||
WHERE c.ledger_event_id = ?
|
||||
""",
|
||||
(ledger_event_id,),
|
||||
).fetchone()
|
||||
|
||||
|
||||
def _event_lifecycle(connection: sqlite3.Connection, ledger_event_id: int) -> str | None:
|
||||
row = connection.execute(
|
||||
"SELECT lifecycle FROM ledger_events WHERE id = ?", (ledger_event_id,)
|
||||
).fetchone()
|
||||
return row["lifecycle"] if row is not None else None
|
||||
|
||||
|
||||
def _next_revision_number(connection: sqlite3.Connection, ledger_event_id: int) -> int:
|
||||
row = connection.execute(
|
||||
"SELECT COALESCE(MAX(revision), 0) AS m FROM ledger_event_revisions WHERE ledger_event_id = ?",
|
||||
(ledger_event_id,),
|
||||
).fetchone()
|
||||
return int(row["m"]) + 1
|
||||
|
||||
|
||||
def create_event(
|
||||
connection: sqlite3.Connection,
|
||||
*,
|
||||
state: str,
|
||||
effective_at: str,
|
||||
amount: str,
|
||||
currency: str,
|
||||
payer_company_id: int,
|
||||
payee_company_id: int,
|
||||
perspective_company_id: int | None,
|
||||
subject_code: str | None,
|
||||
source_kind: str,
|
||||
source_revision_token: str | None,
|
||||
posting_kind: str,
|
||||
reverses_ledger_event_id: int | None = None,
|
||||
adjusts_ledger_event_id: int | None = None,
|
||||
rule_version: str | None = None,
|
||||
evidence_json: str | None = None,
|
||||
idempotency_key: str | None = None,
|
||||
actor: sqlite3.Row | None = None,
|
||||
reason: str | None = None,
|
||||
supersedes_revision_id: int | None = None,
|
||||
) -> tuple[int, int]:
|
||||
"""Insert a new ledger event with one revision. Returns ``(event_id, revision_id)``."""
|
||||
if state == "confirmed":
|
||||
if perspective_company_id is None or subject_code is None:
|
||||
raise LedgerInputError("已确认事件必须提供视角公司与科目。")
|
||||
if subject_code not in SUBJECTS:
|
||||
raise LedgerInputError("科目必须是应收/应付/其他应收/其他应付之一。")
|
||||
if int(payer_company_id) == int(payee_company_id):
|
||||
raise LedgerInputError("付款公司与收款公司不能相同。")
|
||||
if perspective_company_id is not None and perspective_company_id not in (
|
||||
int(payer_company_id), int(payee_company_id),
|
||||
):
|
||||
raise LedgerInputError("视角公司必须是事件参与方。")
|
||||
began = _ensure_transaction(connection)
|
||||
try:
|
||||
now = utc_now()
|
||||
cursor = connection.execute(
|
||||
"INSERT INTO ledger_events (lifecycle, created_at) VALUES ('active', ?)",
|
||||
(now,),
|
||||
)
|
||||
event_id = int(cursor.lastrowid)
|
||||
revision_id = append_revision(
|
||||
connection,
|
||||
event_id,
|
||||
state=state,
|
||||
effective_at=effective_at,
|
||||
amount=amount,
|
||||
currency=currency,
|
||||
payer_company_id=payer_company_id,
|
||||
payee_company_id=payee_company_id,
|
||||
perspective_company_id=perspective_company_id,
|
||||
subject_code=subject_code,
|
||||
source_kind=source_kind,
|
||||
source_revision_token=source_revision_token,
|
||||
posting_kind=posting_kind,
|
||||
reverses_ledger_event_id=reverses_ledger_event_id,
|
||||
adjusts_ledger_event_id=adjusts_ledger_event_id,
|
||||
rule_version=rule_version,
|
||||
evidence_json=evidence_json,
|
||||
idempotency_key=idempotency_key,
|
||||
actor=actor,
|
||||
reason=reason,
|
||||
supersedes_revision_id=supersedes_revision_id,
|
||||
)
|
||||
except Exception:
|
||||
if began:
|
||||
connection.rollback()
|
||||
raise
|
||||
else:
|
||||
if began:
|
||||
connection.commit()
|
||||
return event_id, revision_id
|
||||
|
||||
|
||||
def append_revision(
|
||||
connection: sqlite3.Connection,
|
||||
ledger_event_id: int,
|
||||
*,
|
||||
state: str,
|
||||
effective_at: str,
|
||||
amount: str,
|
||||
currency: str,
|
||||
payer_company_id: int,
|
||||
payee_company_id: int,
|
||||
perspective_company_id: int | None,
|
||||
subject_code: str | None,
|
||||
source_kind: str,
|
||||
source_revision_token: str | None,
|
||||
posting_kind: str,
|
||||
reverses_ledger_event_id: int | None = None,
|
||||
adjusts_ledger_event_id: int | None = None,
|
||||
rule_version: str | None = None,
|
||||
evidence_json: str | None = None,
|
||||
idempotency_key: str | None = None,
|
||||
actor: sqlite3.Row | None = None,
|
||||
reason: str | None = None,
|
||||
supersedes_revision_id: int | None = None,
|
||||
) -> int:
|
||||
"""Append one immutable revision and repoint the current projection."""
|
||||
if _event_lifecycle(connection, ledger_event_id) != "active":
|
||||
raise LedgerConflictError("该事件已停用,不能追加修订。")
|
||||
if state == "confirmed":
|
||||
if perspective_company_id is None or subject_code is None:
|
||||
raise LedgerInputError("已确认事件必须提供视角公司与科目。")
|
||||
if subject_code not in SUBJECTS:
|
||||
raise LedgerInputError("科目必须是应收/应付/其他应收/其他应付之一。")
|
||||
if perspective_company_id not in (int(payer_company_id), int(payee_company_id)):
|
||||
raise LedgerInputError("视角公司必须是事件参与方。")
|
||||
elif state != "pending_subject":
|
||||
raise LedgerInputError("事件状态必须是 pending_subject 或 confirmed。")
|
||||
revision = _next_revision_number(connection, ledger_event_id)
|
||||
now = utc_now()
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO ledger_event_revisions (
|
||||
ledger_event_id, revision, state, effective_at, amount,
|
||||
amount_scale, currency, payer_company_id, payee_company_id,
|
||||
perspective_company_id, subject_code, source_kind,
|
||||
source_revision_token, posting_kind, reverses_ledger_event_id,
|
||||
adjusts_ledger_event_id, rule_version, evidence_json,
|
||||
idempotency_key, actor_user_id, actor_username, reason,
|
||||
supersedes_revision_id, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
ledger_event_id, revision, state, effective_at, amount,
|
||||
amount_scale(amount), currency, payer_company_id, payee_company_id,
|
||||
perspective_company_id, subject_code, source_kind,
|
||||
source_revision_token, posting_kind, reverses_ledger_event_id,
|
||||
adjusts_ledger_event_id, rule_version, evidence_json,
|
||||
idempotency_key,
|
||||
actor["id"] if actor is not None else None,
|
||||
actor["username"] if actor is not None else None,
|
||||
reason, supersedes_revision_id, now,
|
||||
),
|
||||
)
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT OR REPLACE INTO current_ledger_event_revisions (ledger_event_id, revision_id)
|
||||
VALUES (?, ?)
|
||||
""",
|
||||
(ledger_event_id, cursor.lastrowid),
|
||||
)
|
||||
return int(cursor.lastrowid)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Source claims
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def bank_source_claim(connection: sqlite3.Connection, bank_event_id: int) -> sqlite3.Row | None:
|
||||
return connection.execute(
|
||||
"SELECT * FROM ledger_event_bank_sources WHERE bank_event_id = ?",
|
||||
(bank_event_id,),
|
||||
).fetchone()
|
||||
|
||||
|
||||
def manual_source_claim(connection: sqlite3.Connection, manual_record_id: int) -> sqlite3.Row | None:
|
||||
return connection.execute(
|
||||
"SELECT * FROM ledger_event_manual_sources WHERE manual_record_id = ?",
|
||||
(manual_record_id,),
|
||||
).fetchone()
|
||||
|
||||
|
||||
def _facts_of(connection: sqlite3.Connection, ledger_event_id: int) -> dict[str, object]:
|
||||
revision = current_revision(connection, ledger_event_id)
|
||||
if revision is None:
|
||||
return {}
|
||||
return {
|
||||
"amount": revision["amount"],
|
||||
"currency": revision["currency"],
|
||||
"effective_at": revision["effective_at"],
|
||||
"payer_company_id": revision["payer_company_id"],
|
||||
"payee_company_id": revision["payee_company_id"],
|
||||
}
|
||||
|
||||
|
||||
def _eligible_facts(event: sqlite3.Row) -> dict[str, object]:
|
||||
return {
|
||||
"amount": event["amount"],
|
||||
"currency": event["currency"],
|
||||
"effective_at": event["effective_at"],
|
||||
"payer_company_id": event["payer_company_id"],
|
||||
"payee_company_id": event["payee_company_id"],
|
||||
}
|
||||
|
||||
|
||||
def _has_reversal(connection: sqlite3.Connection, original_event_id: int) -> bool:
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT 1 FROM ledger_event_revisions r
|
||||
JOIN current_ledger_event_revisions c ON c.revision_id = r.id
|
||||
WHERE r.reverses_ledger_event_id = ? AND r.posting_kind = 'reversal'
|
||||
LIMIT 1
|
||||
""",
|
||||
(original_event_id,),
|
||||
).fetchone()
|
||||
return row is not None
|
||||
|
||||
|
||||
def create_reversal(
|
||||
connection: sqlite3.Connection,
|
||||
original_event_id: int,
|
||||
*,
|
||||
source_kind: str,
|
||||
source_revision_token: str | None = None,
|
||||
effective_at: str | None = None,
|
||||
reason: str,
|
||||
actor: sqlite3.Row | None,
|
||||
idempotency_key: str | None = None,
|
||||
rule_version: str | None = None,
|
||||
) -> tuple[int, int]:
|
||||
"""Create an equal-amount, opposite-direction reversal as a new ledger event.
|
||||
|
||||
The subject mirrors the original (应收<->应付, 其他应收<->其他应付). ``effective_at``
|
||||
defaults to the original event's effective date so an earlier cutoff keeps
|
||||
the original impact and later cutoffs see the net zero. The original event
|
||||
is never modified or deleted.
|
||||
"""
|
||||
original = current_revision(connection, original_event_id)
|
||||
if original is None:
|
||||
raise LedgerConflictError("原事件不存在或没有当前修订。")
|
||||
if original["state"] != "confirmed":
|
||||
raise LedgerInputError("只有已确认事件才能生成冲销。")
|
||||
perspective = mirror_perspective(original)
|
||||
if effective_at is None:
|
||||
effective_at = original["effective_at"]
|
||||
return create_event(
|
||||
connection,
|
||||
state="confirmed",
|
||||
effective_at=effective_at,
|
||||
amount=original["amount"],
|
||||
currency=original["currency"],
|
||||
payer_company_id=original["payee_company_id"],
|
||||
payee_company_id=original["payer_company_id"],
|
||||
perspective_company_id=perspective,
|
||||
subject_code=mirror_subject(original["subject_code"]),
|
||||
source_kind=source_kind,
|
||||
source_revision_token=source_revision_token,
|
||||
posting_kind="reversal",
|
||||
reverses_ledger_event_id=original_event_id,
|
||||
rule_version=rule_version or original["rule_version"],
|
||||
idempotency_key=idempotency_key,
|
||||
actor=actor,
|
||||
reason=reason,
|
||||
)
|
||||
|
||||
|
||||
def mirror_perspective(revision: sqlite3.Row) -> int:
|
||||
"""The counterparty company from ``revision``'s perspective."""
|
||||
perspective = int(revision["perspective_company_id"])
|
||||
if perspective == int(revision["payer_company_id"]):
|
||||
return int(revision["payee_company_id"])
|
||||
return int(revision["payer_company_id"])
|
||||
|
||||
|
||||
def create_adjustment(
|
||||
connection: sqlite3.Connection,
|
||||
ledger_event_id: int,
|
||||
*,
|
||||
effective_at: str,
|
||||
amount: str,
|
||||
currency: str,
|
||||
payer_company_id: int,
|
||||
payee_company_id: int,
|
||||
perspective_company_id: int,
|
||||
subject_code: str,
|
||||
reason: str,
|
||||
actor: sqlite3.Row,
|
||||
idempotency_key: str | None = None,
|
||||
rule_version: str | None = None,
|
||||
) -> tuple[int, int]:
|
||||
"""Create an audit adjustment event; the original event stays unchanged."""
|
||||
return create_event(
|
||||
connection,
|
||||
state="confirmed",
|
||||
effective_at=effective_at,
|
||||
amount=str(parse_amount(amount)),
|
||||
currency=currency,
|
||||
payer_company_id=payer_company_id,
|
||||
payee_company_id=payee_company_id,
|
||||
perspective_company_id=perspective_company_id,
|
||||
subject_code=subject_code,
|
||||
source_kind="adjustment",
|
||||
source_revision_token=None,
|
||||
posting_kind="adjustment",
|
||||
adjusts_ledger_event_id=ledger_event_id,
|
||||
rule_version=rule_version or SUBJECT_RULE_VERSION,
|
||||
idempotency_key=idempotency_key,
|
||||
actor=actor,
|
||||
reason=reason,
|
||||
)
|
||||
|
||||
|
||||
def reopen_subject(
|
||||
connection: sqlite3.Connection,
|
||||
ledger_event_id: int,
|
||||
*,
|
||||
reason: str,
|
||||
actor: sqlite3.Row,
|
||||
idempotency_key: str | None = None,
|
||||
) -> tuple[int, int]:
|
||||
"""Reverse a confirmed event and re-open it for subject re-review.
|
||||
|
||||
Creates an equal-amount reversal plus a fresh ``pending_subject`` event
|
||||
that re-claims the original bank source, so the administrator can confirm
|
||||
a corrected subject. The original event and its reversal keep history.
|
||||
"""
|
||||
current = current_revision(connection, ledger_event_id)
|
||||
if current is None or current["state"] != "confirmed":
|
||||
raise LedgerConflictError("只有已确认事件可以重新进入科目审核。")
|
||||
bank_claim = connection.execute(
|
||||
"SELECT * FROM ledger_event_bank_sources WHERE ledger_event_id = ?",
|
||||
(ledger_event_id,),
|
||||
).fetchone()
|
||||
if bank_claim is None:
|
||||
raise LedgerInputError(
|
||||
"该事件没有银行来源,无法重新进入科目审核;请改用调整或冲销。"
|
||||
)
|
||||
ev = connection.execute(
|
||||
"SELECT * FROM eligible_intercompany_events WHERE event_id = ?",
|
||||
(bank_claim["bank_event_id"],),
|
||||
).fetchone()
|
||||
if ev is None:
|
||||
raise LedgerInputError("银行事件已不再纳入往来,无法重新入账。")
|
||||
# One nestable transaction: reversal, replacement event, source re-claim
|
||||
# and suggestions commit together. create_event used to commit on its own,
|
||||
# leaving the bank-source UPDATE uncommitted for connection.close().
|
||||
with transaction(connection):
|
||||
if not _has_reversal(connection, ledger_event_id):
|
||||
create_reversal(
|
||||
connection, ledger_event_id,
|
||||
source_kind=current["source_kind"],
|
||||
source_revision_token=current["source_revision_token"],
|
||||
reason="科目复核:原确认事件冲销",
|
||||
actor=actor,
|
||||
idempotency_key=(idempotency_key + ":rev" if idempotency_key else None),
|
||||
rule_version=current["rule_version"],
|
||||
)
|
||||
event_id, revision_id = _create_bank_event(
|
||||
connection, ev, actor, reason="科目复核后重新入账,待确认科目",
|
||||
replacing_claim=bank_claim,
|
||||
)
|
||||
return event_id, revision_id
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Bank event reconciliation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def reconcile_bank_events(
|
||||
connection: sqlite3.Connection, actor: sqlite3.Row | None = None
|
||||
) -> dict[str, object]:
|
||||
"""Reconcile the current eligible intercompany events into ledger events.
|
||||
|
||||
Idempotent: first sight creates a ``pending_subject`` event; a changed B-43
|
||||
decision updates a still-pending event's revision, or (for a confirmed
|
||||
event) creates a reversal plus a fresh pending event. A source that left
|
||||
the eligible set with a confirmed impact gets one reversal. Runs inside the
|
||||
caller's transaction when one is open, otherwise in its own transaction.
|
||||
"""
|
||||
began = _ensure_transaction(connection)
|
||||
try:
|
||||
eligible = {
|
||||
row["event_id"]: row
|
||||
for row in connection.execute(
|
||||
"SELECT * FROM eligible_intercompany_events"
|
||||
).fetchall()
|
||||
}
|
||||
claims = {
|
||||
row["bank_event_id"]: row
|
||||
for row in connection.execute(
|
||||
"SELECT * FROM ledger_event_bank_sources"
|
||||
).fetchall()
|
||||
}
|
||||
stats = {
|
||||
"created": 0, "updated_pending": 0, "reversal": 0,
|
||||
"reopened": 0, "unchanged": 0, "sources": len(eligible),
|
||||
}
|
||||
for bank_event_id, event in sorted(eligible.items()):
|
||||
claim = claims.get(bank_event_id)
|
||||
if claim is None:
|
||||
_create_bank_event(
|
||||
connection, event, actor, reason="B-43 事件首次入账,待确认科目"
|
||||
)
|
||||
stats["created"] += 1
|
||||
continue
|
||||
current = current_revision(connection, claim["ledger_event_id"])
|
||||
if current is None or _facts_of(connection, claim["ledger_event_id"]) != _eligible_facts(event):
|
||||
if current is not None and current["state"] == "confirmed":
|
||||
if not _has_reversal(connection, claim["ledger_event_id"]):
|
||||
create_reversal(
|
||||
connection, claim["ledger_event_id"],
|
||||
source_kind="bank",
|
||||
source_revision_token=event["decision_id"],
|
||||
reason="B-43 事件事实变更,原确认事件冲销",
|
||||
actor=actor,
|
||||
)
|
||||
stats["reversal"] += 1
|
||||
_create_bank_event(
|
||||
connection, event, actor,
|
||||
reason="B-43 事件事实变更后重新入账,待确认科目",
|
||||
replacing_claim=claim,
|
||||
)
|
||||
stats["reopened"] += 1
|
||||
elif current is None or current["state"] == "pending_subject":
|
||||
_append_bank_pending_revision(
|
||||
connection, claim["ledger_event_id"], event, actor
|
||||
)
|
||||
stats["updated_pending"] += 1
|
||||
else:
|
||||
stats["unchanged"] += 1
|
||||
else:
|
||||
stats["unchanged"] += 1
|
||||
|
||||
for bank_event_id, claim in sorted(claims.items()):
|
||||
if bank_event_id in eligible:
|
||||
continue
|
||||
current = current_revision(connection, claim["ledger_event_id"])
|
||||
if current is not None and current["state"] == "confirmed":
|
||||
if not _has_reversal(connection, claim["ledger_event_id"]):
|
||||
create_reversal(
|
||||
connection, claim["ledger_event_id"],
|
||||
source_kind="bank",
|
||||
source_revision_token=None,
|
||||
reason="B-43 事件不再纳入往来,原确认事件冲销",
|
||||
actor=actor,
|
||||
)
|
||||
stats["reversal"] += 1
|
||||
except Exception:
|
||||
if began:
|
||||
connection.rollback()
|
||||
raise
|
||||
else:
|
||||
if began:
|
||||
connection.commit()
|
||||
return stats
|
||||
|
||||
|
||||
def _create_bank_event(
|
||||
connection: sqlite3.Connection,
|
||||
event: sqlite3.Row,
|
||||
actor: sqlite3.Row | None,
|
||||
*,
|
||||
reason: str,
|
||||
replacing_claim: sqlite3.Row | None = None,
|
||||
) -> tuple[int, int]:
|
||||
with transaction(connection):
|
||||
event_id, revision_id = create_event(
|
||||
connection,
|
||||
state="pending_subject",
|
||||
effective_at=event["effective_at"],
|
||||
amount=event["amount"],
|
||||
currency=event["currency"],
|
||||
payer_company_id=event["payer_company_id"],
|
||||
payee_company_id=event["payee_company_id"],
|
||||
perspective_company_id=None,
|
||||
subject_code=None,
|
||||
source_kind="bank",
|
||||
source_revision_token=event["decision_id"],
|
||||
posting_kind="normal",
|
||||
rule_version=SUBJECT_RULE_VERSION,
|
||||
evidence_json=json.dumps(
|
||||
{
|
||||
"bank_event_id": event["event_id"],
|
||||
"decision_id": event["decision_id"],
|
||||
"pairing": event["pairing"],
|
||||
"evidence_count": event["evidence_count"],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
actor=actor,
|
||||
reason=reason,
|
||||
)
|
||||
if replacing_claim is not None:
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE ledger_event_bank_sources SET ledger_event_id = ?
|
||||
WHERE bank_event_id = ?
|
||||
""",
|
||||
(event_id, event["event_id"]),
|
||||
)
|
||||
else:
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO ledger_event_bank_sources (bank_event_id, ledger_event_id)
|
||||
VALUES (?, ?)
|
||||
""",
|
||||
(event["event_id"], event_id),
|
||||
)
|
||||
from .subjects import store_suggestions
|
||||
|
||||
store_suggestions(connection, event_id)
|
||||
return event_id, revision_id
|
||||
|
||||
|
||||
def _append_bank_pending_revision(
|
||||
connection: sqlite3.Connection,
|
||||
ledger_event_id: int,
|
||||
event: sqlite3.Row,
|
||||
actor: sqlite3.Row | None,
|
||||
) -> int:
|
||||
current = current_revision(connection, ledger_event_id)
|
||||
revision_id = append_revision(
|
||||
connection,
|
||||
ledger_event_id,
|
||||
state="pending_subject",
|
||||
effective_at=event["effective_at"],
|
||||
amount=event["amount"],
|
||||
currency=event["currency"],
|
||||
payer_company_id=event["payer_company_id"],
|
||||
payee_company_id=event["payee_company_id"],
|
||||
perspective_company_id=None,
|
||||
subject_code=None,
|
||||
source_kind="bank",
|
||||
source_revision_token=event["decision_id"],
|
||||
posting_kind="normal",
|
||||
rule_version=SUBJECT_RULE_VERSION,
|
||||
evidence_json=json.dumps(
|
||||
{
|
||||
"bank_event_id": event["event_id"],
|
||||
"decision_id": event["decision_id"],
|
||||
"pairing": event["pairing"],
|
||||
"evidence_count": event["evidence_count"],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
actor=actor,
|
||||
reason="B-43 事件事实更新,追加待审修订",
|
||||
supersedes_revision_id=current["id"] if current is not None else None,
|
||||
)
|
||||
from .subjects import store_suggestions
|
||||
|
||||
store_suggestions(connection, ledger_event_id)
|
||||
return revision_id
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Projection rebuild
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def rebuild_current_ledger_projection(connection: sqlite3.Connection) -> int:
|
||||
"""Rebuild current ledger revisions from the append-only log."""
|
||||
began = _ensure_transaction(connection)
|
||||
try:
|
||||
connection.execute("DELETE FROM current_ledger_event_revisions")
|
||||
rows = connection.execute(
|
||||
"""
|
||||
SELECT e.id AS ledger_event_id,
|
||||
(SELECT r2.id FROM ledger_event_revisions r2
|
||||
WHERE r2.ledger_event_id = e.id
|
||||
ORDER BY r2.revision DESC LIMIT 1) AS latest_id
|
||||
FROM ledger_events e
|
||||
WHERE e.lifecycle = 'active'
|
||||
""",
|
||||
).fetchall()
|
||||
rebuilt = 0
|
||||
for row in rows:
|
||||
if row["latest_id"] is None:
|
||||
continue
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT OR REPLACE INTO current_ledger_event_revisions (ledger_event_id, revision_id)
|
||||
VALUES (?, ?)
|
||||
""",
|
||||
(row["ledger_event_id"], row["latest_id"]),
|
||||
)
|
||||
rebuilt += 1
|
||||
except Exception:
|
||||
if began:
|
||||
connection.rollback()
|
||||
raise
|
||||
else:
|
||||
if began:
|
||||
connection.commit()
|
||||
return rebuilt
|
||||
@@ -1,818 +0,0 @@
|
||||
"""Manual evidence records, administrator approval and audit-safe reversal.
|
||||
|
||||
Manual records are immutable submitted facts. Only an approved record becomes
|
||||
a canonical ledger event (``approve_new``) or joins one (``approve_link``);
|
||||
returned/exception/pending records never affect a balance and never leak to
|
||||
the counterparty. Approved facts change only through a ``reverse`` decision
|
||||
that creates an opposite new event (or detaches a linked claim) — the original
|
||||
is never edited. Idempotency keys and UNIQUE claims prevent double counting.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from decimal import Decimal, InvalidOperation
|
||||
import json
|
||||
import sqlite3
|
||||
|
||||
from .db import utc_now
|
||||
from .ledger_events import (
|
||||
LedgerConflictError,
|
||||
LedgerInputError,
|
||||
create_event,
|
||||
create_reversal,
|
||||
current_revision,
|
||||
manual_source_claim,
|
||||
)
|
||||
from .subjects import SUBJECTS
|
||||
|
||||
MANUAL_STATES = ("pending", "approved", "returned", "exception", "reversed")
|
||||
FUNDING_SOURCES = ("approved_bank_account", "personal_transit", "other")
|
||||
DATE_KEYS = ("occurred_at",)
|
||||
|
||||
|
||||
class ManualConflictError(ValueError):
|
||||
"""A claim/idempotency/revision conflict (mapped to HTTP 409)."""
|
||||
|
||||
|
||||
class ManualInputError(ValueError):
|
||||
"""Invalid manual record input (mapped to HTTP 400/422)."""
|
||||
|
||||
|
||||
def _parse_amount(amount: object) -> Decimal:
|
||||
try:
|
||||
value = Decimal(str(amount))
|
||||
except InvalidOperation:
|
||||
raise ManualInputError("金额不是有效的十进制数。") from None
|
||||
if not value.is_finite() or value <= 0:
|
||||
raise ManualInputError("金额必须大于零。")
|
||||
return value
|
||||
|
||||
|
||||
def _validate_date(value: object, field: str) -> str:
|
||||
text = str(value or "").strip()
|
||||
if len(text) < 10:
|
||||
raise ManualInputError(f"{field}必须是 YYYY-MM-DD 或完整时间。")
|
||||
try:
|
||||
datetime.fromisoformat(text[:10])
|
||||
except ValueError:
|
||||
raise ManualInputError(f"{field}必须是 YYYY-MM-DD 或完整时间。") from None
|
||||
return text
|
||||
|
||||
|
||||
def _business_today() -> str:
|
||||
"""Shanghai business date (the default reversal effective date)."""
|
||||
return datetime.now(timezone(timedelta(hours=8))).date().isoformat()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Submit
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def submit(
|
||||
connection: sqlite3.Connection,
|
||||
*,
|
||||
company_id: int,
|
||||
counterparty_company_id: int,
|
||||
occurred_at: str,
|
||||
direction: str,
|
||||
amount: str,
|
||||
currency: str,
|
||||
funding_source: str,
|
||||
requested_subject: str,
|
||||
request_key: str,
|
||||
actor: sqlite3.Row,
|
||||
bank_account_id: object = None,
|
||||
personal_transit_mapping_id: object = None,
|
||||
related_source_row_id: object = None,
|
||||
summary: object = None,
|
||||
reason: object = None,
|
||||
evidence: object = None,
|
||||
supersedes_record_id: object = None,
|
||||
) -> dict[str, object]:
|
||||
"""Submit one manual record for review. Idempotent on ``(company_id, request_key)``."""
|
||||
request_key = str(request_key or "").strip()
|
||||
if not request_key:
|
||||
raise ManualInputError("必须提供提交幂等键 request_key。")
|
||||
if int(company_id) == int(counterparty_company_id):
|
||||
raise ManualInputError("对方公司不能与本公司相同。")
|
||||
if direction not in ("outgoing", "incoming"):
|
||||
raise ManualInputError("方向必须是 outgoing 或 incoming。")
|
||||
if funding_source not in FUNDING_SOURCES:
|
||||
raise ManualInputError(f"资金来源必须是:{'、'.join(FUNDING_SOURCES)}。")
|
||||
if requested_subject not in SUBJECTS:
|
||||
raise ManualInputError("科目必须是应收/应付/其他应收/其他应付之一。")
|
||||
_validate_date(occurred_at, "业务日期")
|
||||
currency = str(currency or "").strip()
|
||||
if not currency:
|
||||
raise ManualInputError("币种不能为空。")
|
||||
amount = str(_parse_amount(amount))
|
||||
|
||||
for label, raw in (
|
||||
("company_id", company_id), ("counterparty_company_id", counterparty_company_id),
|
||||
):
|
||||
row = connection.execute("SELECT id FROM companies WHERE id = ?", (int(raw),)).fetchone()
|
||||
if row is None:
|
||||
raise ManualInputError(f"{label} 指向的公司不存在。")
|
||||
|
||||
bank_account_id = _resolve_account_ref(
|
||||
connection, bank_account_id, company_id, "银行账户"
|
||||
)
|
||||
mapping_id = _resolve_account_ref(
|
||||
connection, personal_transit_mapping_id, company_id, "个人过账映射"
|
||||
)
|
||||
related_row = None
|
||||
if related_source_row_id not in (None, ""):
|
||||
related_row = connection.execute(
|
||||
"SELECT r.id, b.company_id FROM source_rows r "
|
||||
"JOIN sheet_batches s ON s.id = r.sheet_batch_id "
|
||||
"JOIN import_batches b ON b.id = s.import_batch_id "
|
||||
"WHERE r.id = ?",
|
||||
(int(related_source_row_id),),
|
||||
).fetchone()
|
||||
if related_row is None:
|
||||
raise ManualInputError("关联银行源行不存在。")
|
||||
|
||||
if funding_source == "approved_bank_account" and bank_account_id is None:
|
||||
raise ManualInputError("资金来源为已批准账户时必须指定银行账户。")
|
||||
if funding_source == "personal_transit" and mapping_id is None:
|
||||
raise ManualInputError("资金来源为个人过账时必须指定个人过账映射。")
|
||||
|
||||
supersedes_id = None
|
||||
if supersedes_record_id not in (None, ""):
|
||||
parent = connection.execute(
|
||||
"SELECT id, company_id FROM manual_records WHERE id = ?",
|
||||
(int(supersedes_record_id),),
|
||||
).fetchone()
|
||||
if parent is None or parent["company_id"] != int(company_id):
|
||||
raise ManualInputError("supersedes_record_id 无效。")
|
||||
supersedes_id = int(supersedes_record_id)
|
||||
|
||||
now = utc_now()
|
||||
began = False
|
||||
if not connection.in_transaction:
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
began = True
|
||||
try:
|
||||
# Re-check inside the write transaction: concurrent identical submits
|
||||
# serialize here, so a replay is found before any INSERT.
|
||||
existing = connection.execute(
|
||||
"SELECT id FROM manual_records WHERE company_id = ? AND request_key = ?",
|
||||
(int(company_id), request_key),
|
||||
).fetchone()
|
||||
if existing is not None:
|
||||
if began:
|
||||
connection.commit()
|
||||
return _record_payload(connection, existing["id"], idempotent_replay=True)
|
||||
try:
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO manual_records (
|
||||
company_id, counterparty_company_id, occurred_at, direction,
|
||||
amount, amount_scale, currency, funding_source, bank_account_id,
|
||||
personal_transit_mapping_id, related_source_row_id,
|
||||
requested_subject, summary, reason, evidence_json, request_key,
|
||||
supersedes_record_id, submitted_by, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
int(company_id), int(counterparty_company_id), occurred_at, direction,
|
||||
amount, _scale_of(amount), currency, funding_source, bank_account_id,
|
||||
mapping_id, related_row["id"] if related_row is not None else None,
|
||||
requested_subject, str(summary or "") or None,
|
||||
str(reason or "") or None,
|
||||
json.dumps(evidence, ensure_ascii=False) if evidence else None,
|
||||
request_key, supersedes_id,
|
||||
actor["id"], now,
|
||||
),
|
||||
)
|
||||
except sqlite3.IntegrityError:
|
||||
# A concurrent identical submit won the race and committed first;
|
||||
# surface the existing record idempotently instead of a UNIQUE 500.
|
||||
if began:
|
||||
connection.rollback()
|
||||
existing = connection.execute(
|
||||
"SELECT id FROM manual_records WHERE company_id = ? AND request_key = ?",
|
||||
(int(company_id), request_key),
|
||||
).fetchone()
|
||||
if existing is not None:
|
||||
return _record_payload(connection, existing["id"], idempotent_replay=True)
|
||||
raise
|
||||
record_id = int(cursor.lastrowid)
|
||||
_append_decision(
|
||||
connection, record_id, state="pending", action="submit",
|
||||
reason=str(reason or "") or None, actor=actor,
|
||||
)
|
||||
except Exception:
|
||||
if began:
|
||||
connection.rollback()
|
||||
raise
|
||||
else:
|
||||
if began:
|
||||
connection.commit()
|
||||
return _record_payload(connection, record_id)
|
||||
|
||||
|
||||
def _resolve_account_ref(connection, raw, company_id: int, label: str) -> int | None:
|
||||
if raw in (None, ""):
|
||||
return None
|
||||
row = connection.execute(
|
||||
"SELECT id, company_id FROM bank_accounts WHERE id = ?", (int(raw),)
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise ManualInputError(f"{label}不存在。")
|
||||
if row["company_id"] != int(company_id):
|
||||
raise ManualInputError(f"{label}必须属于提交公司。")
|
||||
return int(raw)
|
||||
|
||||
|
||||
def _scale_of(amount: str) -> int:
|
||||
exponent = Decimal(amount).as_tuple().exponent
|
||||
return max(0, -int(exponent))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Decisions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _append_decision(
|
||||
connection: sqlite3.Connection,
|
||||
record_id: int,
|
||||
*,
|
||||
state: str,
|
||||
action: str,
|
||||
reason: str | None,
|
||||
actor: sqlite3.Row,
|
||||
idempotency_key: str | None = None,
|
||||
supersedes_decision_id: int | None = None,
|
||||
) -> int:
|
||||
row = connection.execute(
|
||||
"SELECT COALESCE(MAX(revision), 0) AS m FROM manual_record_decisions WHERE record_id = ?",
|
||||
(record_id,),
|
||||
).fetchone()
|
||||
revision = int(row["m"]) + 1
|
||||
now = utc_now()
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO manual_record_decisions (
|
||||
record_id, revision, state, action, reason, actor_user_id,
|
||||
actor_username, idempotency_key, supersedes_decision_id, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
record_id, revision, state, action, reason,
|
||||
actor["id"], actor["username"], idempotency_key,
|
||||
supersedes_decision_id, now,
|
||||
),
|
||||
)
|
||||
decision_id = int(cursor.lastrowid)
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT OR REPLACE INTO current_manual_record_decisions (record_id, decision_id)
|
||||
VALUES (?, ?)
|
||||
""",
|
||||
(record_id, decision_id),
|
||||
)
|
||||
return decision_id
|
||||
|
||||
|
||||
def _current_decision(connection: sqlite3.Connection, record_id: int) -> sqlite3.Row | None:
|
||||
return connection.execute(
|
||||
"""
|
||||
SELECT d.* FROM current_manual_record_decisions c
|
||||
JOIN manual_record_decisions d ON d.id = c.decision_id
|
||||
WHERE c.record_id = ?
|
||||
""",
|
||||
(record_id,),
|
||||
).fetchone()
|
||||
|
||||
|
||||
def decide(
|
||||
connection: sqlite3.Connection,
|
||||
record_id: int,
|
||||
action: str,
|
||||
*,
|
||||
reason: str,
|
||||
expected_decision_id: int | None,
|
||||
request_key: str | None,
|
||||
actor: sqlite3.Row,
|
||||
subject_code: object = None,
|
||||
target_ledger_event_id: object = None,
|
||||
effective_at: object = None,
|
||||
) -> dict[str, object]:
|
||||
"""Apply an administrator decision to a manual record.
|
||||
|
||||
``approve_new`` creates a confirmed ledger event; ``approve_link`` joins an
|
||||
existing ledger event without adding a second economic impact; ``return``
|
||||
and ``exception`` never produce a balance; ``reverse`` creates an opposite
|
||||
reversal event (or detaches a linked claim) with an independent business
|
||||
effective date — explicit ``effective_at`` or the approval business day.
|
||||
Replays return the earlier outcome via ``idempotency_key``.
|
||||
"""
|
||||
reason = (reason or "").strip()
|
||||
if not reason:
|
||||
raise ManualInputError("必须填写审核原因。")
|
||||
if action not in ("approve_new", "approve_link", "return", "exception", "reverse"):
|
||||
raise ManualInputError("未知的审核决定类型。")
|
||||
|
||||
began = False
|
||||
if not connection.in_transaction:
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
began = True
|
||||
try:
|
||||
record = connection.execute(
|
||||
"SELECT * FROM manual_records WHERE id = ?", (record_id,)
|
||||
).fetchone()
|
||||
if record is None:
|
||||
raise ManualConflictError("手工记录不存在。")
|
||||
if request_key:
|
||||
existing = connection.execute(
|
||||
"SELECT * FROM manual_record_decisions WHERE record_id = ? AND idempotency_key = ?",
|
||||
(record_id, request_key),
|
||||
).fetchone()
|
||||
if existing is not None:
|
||||
if began:
|
||||
connection.commit()
|
||||
return _decision_payload(connection, record_id, existing["id"])
|
||||
|
||||
current = _current_decision(connection, record_id)
|
||||
if current is None:
|
||||
raise ManualConflictError("该记录没有当前状态。")
|
||||
if expected_decision_id is not None and int(expected_decision_id) != current["id"]:
|
||||
raise ManualConflictError("记录已发生变更,请刷新后重试。")
|
||||
|
||||
if action == "approve_new":
|
||||
outcome = _approve_new(
|
||||
connection, record, current, actor, subject_code, reason, request_key
|
||||
)
|
||||
elif action == "approve_link":
|
||||
outcome = _approve_link(
|
||||
connection, record, current, actor, target_ledger_event_id, reason,
|
||||
request_key,
|
||||
)
|
||||
elif action == "return":
|
||||
if current["state"] != "pending":
|
||||
raise ManualConflictError("只有待复核的记录可以退回。")
|
||||
decision_id = _append_decision(
|
||||
connection, record_id, state="returned", action=action,
|
||||
reason=reason, actor=actor, idempotency_key=request_key,
|
||||
supersedes_decision_id=current["id"],
|
||||
)
|
||||
outcome = {"decision_id": decision_id, "ledger_event_id": None}
|
||||
elif action == "exception":
|
||||
if current["state"] != "pending":
|
||||
raise ManualConflictError("只有待复核的记录可以转为异常。")
|
||||
decision_id = _append_decision(
|
||||
connection, record_id, state="exception", action=action,
|
||||
reason=reason, actor=actor, idempotency_key=request_key,
|
||||
supersedes_decision_id=current["id"],
|
||||
)
|
||||
outcome = {"decision_id": decision_id, "ledger_event_id": None}
|
||||
else: # reverse
|
||||
if current["state"] != "approved":
|
||||
raise ManualConflictError("只有已批准记录可以冲销。")
|
||||
outcome = _reverse(
|
||||
connection, record, current, actor, request_key, reason,
|
||||
effective_at=effective_at,
|
||||
)
|
||||
|
||||
_store_audit(connection, record, current, action, outcome, reason, actor)
|
||||
except Exception:
|
||||
if began:
|
||||
connection.rollback()
|
||||
raise
|
||||
else:
|
||||
if began:
|
||||
connection.commit()
|
||||
return _decision_payload(connection, record_id, outcome["decision_id"])
|
||||
|
||||
|
||||
def _approve_new(
|
||||
connection: sqlite3.Connection,
|
||||
record: sqlite3.Row,
|
||||
current: sqlite3.Row,
|
||||
actor: sqlite3.Row,
|
||||
subject_code: object,
|
||||
reason: str,
|
||||
idempotency_key: str | None,
|
||||
) -> dict[str, object]:
|
||||
subject = str(subject_code or record["requested_subject"] or "")
|
||||
if subject not in SUBJECTS:
|
||||
raise ManualInputError("科目必须是应收/应付/其他应收/其他应付之一。")
|
||||
if record["direction"] == "outgoing":
|
||||
payer, payee = record["company_id"], record["counterparty_company_id"]
|
||||
else:
|
||||
payer, payee = record["counterparty_company_id"], record["company_id"]
|
||||
event_id, _revision_id = create_event(
|
||||
connection,
|
||||
state="confirmed",
|
||||
effective_at=record["occurred_at"],
|
||||
amount=record["amount"],
|
||||
currency=record["currency"],
|
||||
payer_company_id=payer,
|
||||
payee_company_id=payee,
|
||||
perspective_company_id=record["company_id"],
|
||||
subject_code=subject,
|
||||
source_kind="manual",
|
||||
source_revision_token=None,
|
||||
posting_kind="normal",
|
||||
rule_version="manual-record-v1",
|
||||
evidence_json=json.dumps({"manual_record_id": record["id"]}, ensure_ascii=False),
|
||||
actor=actor,
|
||||
reason=reason,
|
||||
)
|
||||
decision_id = _append_decision(
|
||||
connection, record["id"], state="approved", action="approve_new",
|
||||
reason=reason, actor=actor,
|
||||
idempotency_key=idempotency_key,
|
||||
supersedes_decision_id=current["id"],
|
||||
)
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO ledger_event_manual_sources (manual_record_id, ledger_event_id)
|
||||
VALUES (?, ?)
|
||||
""",
|
||||
(record["id"], event_id),
|
||||
)
|
||||
return {"decision_id": decision_id, "ledger_event_id": event_id}
|
||||
|
||||
|
||||
def _approve_link(
|
||||
connection: sqlite3.Connection,
|
||||
record: sqlite3.Row,
|
||||
current: sqlite3.Row,
|
||||
actor: sqlite3.Row,
|
||||
target_ledger_event_id: object,
|
||||
reason: str,
|
||||
idempotency_key: str | None,
|
||||
) -> dict[str, object]:
|
||||
if target_ledger_event_id in (None, ""):
|
||||
raise ManualInputError("approve_link 必须指定目标往来事件。")
|
||||
target = connection.execute(
|
||||
"SELECT id, lifecycle FROM ledger_events WHERE id = ?",
|
||||
(int(target_ledger_event_id),),
|
||||
).fetchone()
|
||||
if target is None or target["lifecycle"] != "active":
|
||||
raise ManualConflictError("目标往来事件不存在。")
|
||||
if manual_source_claim(connection, record["id"]) is not None:
|
||||
raise ManualConflictError("该手工记录已关联往来事件。")
|
||||
decision_id = _append_decision(
|
||||
connection, record["id"], state="approved", action="approve_link",
|
||||
reason=reason, actor=actor,
|
||||
idempotency_key=idempotency_key,
|
||||
supersedes_decision_id=current["id"],
|
||||
)
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO ledger_event_manual_sources (manual_record_id, ledger_event_id)
|
||||
VALUES (?, ?)
|
||||
""",
|
||||
(record["id"], int(target_ledger_event_id)),
|
||||
)
|
||||
return {"decision_id": decision_id, "ledger_event_id": int(target_ledger_event_id)}
|
||||
|
||||
|
||||
def _reverse(
|
||||
connection: sqlite3.Connection,
|
||||
record: sqlite3.Row,
|
||||
current: sqlite3.Row,
|
||||
actor: sqlite3.Row,
|
||||
request_key: str | None,
|
||||
reason: str,
|
||||
effective_at: object = None,
|
||||
) -> dict[str, object]:
|
||||
claim = manual_source_claim(connection, record["id"])
|
||||
if claim is None:
|
||||
raise ManualConflictError("该记录尚未关联往来事件,无法冲销。")
|
||||
event_id = claim["ledger_event_id"]
|
||||
revision = current_revision(connection, event_id)
|
||||
if revision is None:
|
||||
raise ManualConflictError("关联的往来事件没有当前修订。")
|
||||
|
||||
if _is_manual_creation_source(revision, record["id"]):
|
||||
# This record created the event (approve_new): it added the economic
|
||||
# impact, so reversing it must always produce an equal-amount reversal
|
||||
# event — even when other manual evidence was later linked onto the
|
||||
# same event. The original impact must not survive in balances.
|
||||
if effective_at is not None and str(effective_at).strip():
|
||||
effective_at = _validate_date(effective_at, "冲销生效日")
|
||||
else:
|
||||
effective_at = _business_today()
|
||||
create_reversal(
|
||||
connection,
|
||||
event_id,
|
||||
source_kind="manual",
|
||||
source_revision_token=str(record["id"]),
|
||||
effective_at=effective_at,
|
||||
reason=reason,
|
||||
actor=actor,
|
||||
idempotency_key=request_key,
|
||||
rule_version="manual-record-v1",
|
||||
)
|
||||
else:
|
||||
# The manual was linked evidence (approve_link) on an event it never
|
||||
# created: it added no second impact, so reversing detaches the claim
|
||||
# and the underlying economic impact stays.
|
||||
connection.execute(
|
||||
"DELETE FROM ledger_event_manual_sources WHERE manual_record_id = ?",
|
||||
(record["id"],),
|
||||
)
|
||||
decision_id = _append_decision(
|
||||
connection, record["id"], state="reversed", action="reverse",
|
||||
reason=reason, actor=actor, idempotency_key=request_key,
|
||||
supersedes_decision_id=current["id"],
|
||||
)
|
||||
return {"decision_id": decision_id, "ledger_event_id": None}
|
||||
|
||||
|
||||
def _is_manual_creation_source(revision: sqlite3.Row, manual_record_id: int) -> bool:
|
||||
"""True when ``manual_record_id`` created the event via ``approve_new``.
|
||||
|
||||
The creation source is recorded in the event's immutable revision
|
||||
``evidence_json``; a linked evidence record is never the creation source
|
||||
and carries no second economic impact.
|
||||
"""
|
||||
if revision["source_kind"] != "manual":
|
||||
return False
|
||||
try:
|
||||
evidence = json.loads(revision["evidence_json"] or "{}")
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
return evidence.get("manual_record_id") == manual_record_id
|
||||
|
||||
|
||||
def _store_audit(
|
||||
connection, record, current, action, outcome, reason, actor
|
||||
) -> None:
|
||||
from .auth import audit
|
||||
|
||||
audit(
|
||||
connection,
|
||||
f"manual_{action}",
|
||||
actor=actor,
|
||||
target=f"manual_record:{record['id']}",
|
||||
detail=(
|
||||
f"decision:{outcome['decision_id']};"
|
||||
f"ledger_event:{outcome.get('ledger_event_id')};reason:{reason}"
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Candidates and queries
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def find_candidates(connection: sqlite3.Connection, record_id: int) -> list[dict[str, object]]:
|
||||
"""Deterministic hints shown before approval; never auto-merged."""
|
||||
record = connection.execute(
|
||||
"SELECT * FROM manual_records WHERE id = ?", (record_id,)
|
||||
).fetchone()
|
||||
if record is None:
|
||||
return []
|
||||
wanted_direction = "incoming" if record["direction"] == "outgoing" else "outgoing"
|
||||
date_prefix = str(record["occurred_at"])[:10]
|
||||
candidates: list[dict[str, object]] = []
|
||||
|
||||
bank_rows = connection.execute(
|
||||
"""
|
||||
SELECT e.event_id, e.amount, e.currency, e.effective_at, e.pairing,
|
||||
e.payer_company_id, e.payee_company_id, e.decision_id
|
||||
FROM eligible_intercompany_events e
|
||||
WHERE (e.payer_company_id = ? AND e.payee_company_id = ?)
|
||||
OR (e.payer_company_id = ? AND e.payee_company_id = ?)
|
||||
ORDER BY e.event_id
|
||||
""",
|
||||
(
|
||||
record["company_id"], record["counterparty_company_id"],
|
||||
record["counterparty_company_id"], record["company_id"],
|
||||
),
|
||||
).fetchall()
|
||||
for row in bank_rows:
|
||||
if row["amount"] != record["amount"] or row["currency"] != record["currency"]:
|
||||
continue
|
||||
event_direction = (
|
||||
"outgoing" if row["payer_company_id"] == record["company_id"] else "incoming"
|
||||
)
|
||||
if event_direction != wanted_direction:
|
||||
continue
|
||||
candidates.append(
|
||||
{
|
||||
"kind": "bank_event",
|
||||
"ledger_event_id": _ledger_event_of_bank(connection, row["event_id"]),
|
||||
"bank_event_id": row["event_id"],
|
||||
"decision_id": row["decision_id"],
|
||||
"amount": row["amount"],
|
||||
"currency": row["currency"],
|
||||
"effective_at": row["effective_at"],
|
||||
"pairing": row["pairing"],
|
||||
"hint": "已存在匹配的银行规范事件,建议关联",
|
||||
}
|
||||
)
|
||||
|
||||
manual_rows = connection.execute(
|
||||
"""
|
||||
SELECT m.id, m.company_id, m.counterparty_company_id, m.direction,
|
||||
m.amount, m.currency, m.occurred_at, d.state
|
||||
FROM manual_records m
|
||||
JOIN current_manual_record_decisions c ON c.record_id = m.id
|
||||
JOIN manual_record_decisions d ON d.id = c.decision_id
|
||||
WHERE m.id != ? AND m.amount = ? AND m.currency = ?
|
||||
AND (
|
||||
(m.company_id = ? AND m.counterparty_company_id = ?)
|
||||
OR (m.company_id = ? AND m.counterparty_company_id = ?)
|
||||
)
|
||||
ORDER BY m.id
|
||||
""",
|
||||
(
|
||||
record["id"], record["amount"], record["currency"],
|
||||
record["company_id"], record["counterparty_company_id"],
|
||||
record["counterparty_company_id"], record["company_id"],
|
||||
),
|
||||
).fetchall()
|
||||
for row in manual_rows:
|
||||
if row["direction"] != wanted_direction:
|
||||
continue
|
||||
if row["state"] not in ("approved", "pending"):
|
||||
continue
|
||||
candidates.append(
|
||||
{
|
||||
"kind": "manual_record",
|
||||
"ledger_event_id": None,
|
||||
"manual_record_id": row["id"],
|
||||
"amount": row["amount"],
|
||||
"currency": row["currency"],
|
||||
"occurred_at": row["occurred_at"],
|
||||
"state": row["state"],
|
||||
"hint": "存在方向相反的同额手工记录,建议核对后关联",
|
||||
}
|
||||
)
|
||||
return candidates
|
||||
|
||||
|
||||
def _ledger_event_of_bank(connection, bank_event_id: int) -> int | None:
|
||||
claim = connection.execute(
|
||||
"SELECT ledger_event_id FROM ledger_event_bank_sources WHERE bank_event_id = ?",
|
||||
(bank_event_id,),
|
||||
).fetchone()
|
||||
return claim["ledger_event_id"] if claim is not None else None
|
||||
|
||||
|
||||
def list_records(
|
||||
connection: sqlite3.Connection,
|
||||
*,
|
||||
company_id: int | None = None,
|
||||
state: str | None = None,
|
||||
limit: int = 100,
|
||||
) -> list[sqlite3.Row]:
|
||||
conditions: list[str] = []
|
||||
params: list[object] = []
|
||||
if company_id is not None:
|
||||
conditions.append("(m.company_id = ? OR m.counterparty_company_id = ?)")
|
||||
params.extend([company_id, company_id])
|
||||
if state is not None:
|
||||
if state not in MANUAL_STATES:
|
||||
raise ManualInputError("无效的记录状态。")
|
||||
conditions.append("d.state = ?")
|
||||
params.append(state)
|
||||
where = f"WHERE {' AND '.join(conditions)}" if conditions else ""
|
||||
return connection.execute(
|
||||
f"""
|
||||
SELECT m.*, d.id AS decision_id, d.state AS state, d.revision AS decision_revision,
|
||||
d.action AS action, d.reason AS decision_reason,
|
||||
d.actor_username AS decision_actor, d.created_at AS decision_at,
|
||||
c.name AS company_name, cc.name AS counterparty_company_name,
|
||||
u.username AS submitted_by_username
|
||||
FROM manual_records m
|
||||
JOIN current_manual_record_decisions c ON c.record_id = m.id
|
||||
JOIN manual_record_decisions d ON d.id = c.decision_id
|
||||
LEFT JOIN companies c ON c.id = m.company_id
|
||||
LEFT JOIN companies cc ON cc.id = m.counterparty_company_id
|
||||
LEFT JOIN users u ON u.id = m.submitted_by
|
||||
{where}
|
||||
ORDER BY m.id DESC
|
||||
LIMIT ?
|
||||
""",
|
||||
(*params, max(1, int(limit))),
|
||||
).fetchall()
|
||||
|
||||
|
||||
def rebuild_current_manual_projection(connection: sqlite3.Connection) -> int:
|
||||
began = False
|
||||
if not connection.in_transaction:
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
began = True
|
||||
try:
|
||||
connection.execute("DELETE FROM current_manual_record_decisions")
|
||||
rows = connection.execute(
|
||||
"""
|
||||
SELECT m.id AS record_id,
|
||||
(SELECT d2.id FROM manual_record_decisions d2
|
||||
WHERE d2.record_id = m.id
|
||||
ORDER BY d2.revision DESC LIMIT 1) AS latest_id
|
||||
FROM manual_records m
|
||||
"""
|
||||
).fetchall()
|
||||
rebuilt = 0
|
||||
for row in rows:
|
||||
if row["latest_id"] is None:
|
||||
continue
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT OR REPLACE INTO current_manual_record_decisions (record_id, decision_id)
|
||||
VALUES (?, ?)
|
||||
""",
|
||||
(row["record_id"], row["latest_id"]),
|
||||
)
|
||||
rebuilt += 1
|
||||
except Exception:
|
||||
if began:
|
||||
connection.rollback()
|
||||
raise
|
||||
else:
|
||||
if began:
|
||||
connection.commit()
|
||||
return rebuilt
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Payloads
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _record_payload(connection: sqlite3.Connection, record_id: int, *, idempotent_replay: bool = False) -> dict[str, object]:
|
||||
rows = list_records(connection, limit=1000)
|
||||
row = next((item for item in rows if item["id"] == record_id), None)
|
||||
if row is None:
|
||||
raise ManualInputError("手工记录不存在。")
|
||||
payload = _row_payload(connection, row)
|
||||
if idempotent_replay:
|
||||
payload["idempotent_replay"] = True
|
||||
return payload
|
||||
|
||||
|
||||
def _row_payload(connection: sqlite3.Connection, row: sqlite3.Row) -> dict[str, object]:
|
||||
evidence = json.loads(row["evidence_json"] or "{}") if row["evidence_json"] else {}
|
||||
return {
|
||||
"id": row["id"],
|
||||
"company_id": row["company_id"],
|
||||
"company_name": row["company_name"],
|
||||
"counterparty_company_id": row["counterparty_company_id"],
|
||||
"counterparty_company_name": row["counterparty_company_name"],
|
||||
"occurred_at": row["occurred_at"],
|
||||
"direction": row["direction"],
|
||||
"amount": row["amount"],
|
||||
"currency": row["currency"],
|
||||
"funding_source": row["funding_source"],
|
||||
"bank_account_id": row["bank_account_id"],
|
||||
"personal_transit_mapping_id": row["personal_transit_mapping_id"],
|
||||
"related_source_row_id": row["related_source_row_id"],
|
||||
"requested_subject": row["requested_subject"],
|
||||
"summary": row["summary"],
|
||||
"reason": row["reason"],
|
||||
"request_key": row["request_key"],
|
||||
"supersedes_record_id": row["supersedes_record_id"],
|
||||
"submitted_by": row["submitted_by"],
|
||||
"submitted_by_username": row["submitted_by_username"] if "submitted_by_username" in row.keys() else None,
|
||||
"attachment_name": evidence.get("attachment_name"),
|
||||
"created_at": row["created_at"],
|
||||
"state": row["state"],
|
||||
"decision_id": row["decision_id"],
|
||||
"decision_revision": row["decision_revision"],
|
||||
"decision_action": row["action"],
|
||||
"decision_reason": row["decision_reason"],
|
||||
"decision_actor": row["decision_actor"],
|
||||
"decision_at": row["decision_at"],
|
||||
"candidates": find_candidates(connection, row["id"]),
|
||||
}
|
||||
|
||||
|
||||
def _decision_payload(connection: sqlite3.Connection, record_id: int, decision_id: int) -> dict[str, object]:
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT d.* FROM manual_record_decisions d
|
||||
WHERE d.id = ?
|
||||
""",
|
||||
(decision_id,),
|
||||
).fetchone()
|
||||
record = connection.execute(
|
||||
"SELECT * FROM manual_records WHERE id = ?", (record_id,)
|
||||
).fetchone()
|
||||
claim = manual_source_claim(connection, record_id)
|
||||
return {
|
||||
"record_id": record_id,
|
||||
"decision_id": decision_id,
|
||||
"revision": row["revision"],
|
||||
"state": row["state"],
|
||||
"action": row["action"],
|
||||
"reason": row["reason"],
|
||||
"actor_username": row["actor_username"],
|
||||
"created_at": row["created_at"],
|
||||
"ledger_event_id": claim["ledger_event_id"] if claim is not None else None,
|
||||
"requested_subject": record["requested_subject"],
|
||||
"amount": record["amount"],
|
||||
"currency": record["currency"],
|
||||
"occurred_at": record["occurred_at"],
|
||||
}
|
||||
@@ -1,567 +0,0 @@
|
||||
"""Dynamic master data: companies, bank accounts, aliases and audit trail.
|
||||
|
||||
Companies, cashier logins and bank accounts live in the database instead of
|
||||
being hard-coded in the UI. Bank account numbers are stored normalized
|
||||
(digits only) under a database UNIQUE constraint, so two concurrent
|
||||
submissions can never produce two usable accounts for the same number.
|
||||
Company-side registrations are requests: only administrator-approved
|
||||
(``active``) accounts inside their effective interval may identify ownership,
|
||||
accept uploads or take part in coverage calculation. Every change is recorded
|
||||
in ``master_data_changes`` with before/after values, actor, time and reason.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
import json
|
||||
import re
|
||||
import sqlite3
|
||||
|
||||
from .db import transaction, utc_now
|
||||
|
||||
|
||||
ACCOUNT_TYPES = ("基本户", "一般户", "专用户")
|
||||
ACCOUNT_STATUSES = ("pending", "active", "returned", "disabled")
|
||||
ALIAS_KINDS = ("name", "account")
|
||||
|
||||
# Deterministic alias match priority: an exact account-number hit always
|
||||
# beats an account alias, which always beats a name alias. The per-alias
|
||||
# ``priority`` column only orders matches within the same tier.
|
||||
PRIORITY_EXACT_ACCOUNT = 0
|
||||
PRIORITY_ACCOUNT_ALIAS = 1000
|
||||
PRIORITY_NAME_ALIAS = 2000
|
||||
|
||||
_ACCOUNT_NUMBER_PATTERN = re.compile(r"^[0-9]{6,32}$")
|
||||
_DATE_PATTERN = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
||||
_FULL_WIDTH_DIGITS = str.maketrans("0123456789", "0123456789")
|
||||
|
||||
|
||||
class ConflictError(ValueError):
|
||||
"""A uniqueness or ownership conflict (mapped to HTTP 409)."""
|
||||
|
||||
|
||||
def utc_today() -> str:
|
||||
return datetime.now(timezone.utc).date().isoformat()
|
||||
|
||||
|
||||
def normalize_account_number(raw: object) -> str:
|
||||
"""Normalize an account number to digits only; raise ValueError if invalid.
|
||||
|
||||
Spaces, dashes and full-width digits entered by cashiers or emitted by
|
||||
bank exports collapse to one canonical form, which is what the UNIQUE
|
||||
constraint and all matching operate on.
|
||||
"""
|
||||
text = str(raw or "").translate(_FULL_WIDTH_DIGITS)
|
||||
text = re.sub(r"[\s\-‐-‒–—]+", "", text)
|
||||
if not _ACCOUNT_NUMBER_PATTERN.fullmatch(text):
|
||||
raise ValueError("银行账号须为 6-32 位数字(可含空格或短横线分隔)。")
|
||||
return text
|
||||
|
||||
|
||||
def mask_account_number(number: str) -> str:
|
||||
"""Masked display form; the full number stays server-side."""
|
||||
if len(number) <= 4:
|
||||
return f"****{number}"
|
||||
return f"****{number[-4:]}"
|
||||
|
||||
|
||||
def validate_date(value: object, field: str, *, required: bool = False) -> str | None:
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
if required:
|
||||
raise ValueError(f"{field}不能为空。")
|
||||
return None
|
||||
if not _DATE_PATTERN.fullmatch(text):
|
||||
raise ValueError(f"{field}须为 YYYY-MM-DD 格式。")
|
||||
try:
|
||||
date.fromisoformat(text)
|
||||
except ValueError:
|
||||
raise ValueError(f"{field}不是有效日期。") from None
|
||||
return text
|
||||
|
||||
|
||||
def validate_account_type(value: object) -> str:
|
||||
text = str(value or "").strip() or "一般户"
|
||||
if text not in ACCOUNT_TYPES:
|
||||
raise ValueError(f"账户类型必须是:{'、'.join(ACCOUNT_TYPES)}。")
|
||||
return text
|
||||
|
||||
|
||||
def _snapshot(row: sqlite3.Row | None) -> dict[str, object] | None:
|
||||
if row is None:
|
||||
return None
|
||||
return {key: row[key] for key in row.keys()}
|
||||
|
||||
|
||||
def record_change(
|
||||
connection: sqlite3.Connection,
|
||||
entity_type: str,
|
||||
entity_id: int,
|
||||
action: str,
|
||||
before: dict[str, object] | None,
|
||||
after: dict[str, object] | None,
|
||||
reason: str | None,
|
||||
actor: sqlite3.Row | None,
|
||||
) -> None:
|
||||
"""Append a before/after audit entry for a master data change."""
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO master_data_changes (
|
||||
entity_type, entity_id, action, before_json, after_json,
|
||||
reason, actor_user_id, actor_username, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
entity_type,
|
||||
entity_id,
|
||||
action,
|
||||
json.dumps(before, ensure_ascii=False) if before is not None else None,
|
||||
json.dumps(after, ensure_ascii=False) if after is not None else None,
|
||||
reason,
|
||||
actor["id"] if actor is not None else None,
|
||||
actor["username"] if actor is not None else None,
|
||||
utc_now(),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Companies
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def create_company(
|
||||
connection: sqlite3.Connection,
|
||||
name: str,
|
||||
credit_code: str | None,
|
||||
cashier_name: str | None,
|
||||
actor: sqlite3.Row | None,
|
||||
) -> int:
|
||||
"""Create a company master record; returns the new id."""
|
||||
name = name.strip()
|
||||
if not name:
|
||||
raise ValueError("公司名称不能为空。")
|
||||
now = utc_now()
|
||||
try:
|
||||
with transaction(connection):
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO companies (
|
||||
name, credit_code, cashier_name, status, created_at, updated_at
|
||||
) VALUES (?, ?, ?, 'active', ?, ?)
|
||||
""",
|
||||
(name, (credit_code or "").strip() or None,
|
||||
(cashier_name or "").strip() or None, now, now),
|
||||
)
|
||||
company_id = int(cursor.lastrowid)
|
||||
record_change(
|
||||
connection, "company", company_id, "create",
|
||||
None, {"name": name, "credit_code": credit_code or None,
|
||||
"cashier_name": cashier_name or None, "status": "active"},
|
||||
None, actor,
|
||||
)
|
||||
except sqlite3.IntegrityError as exc:
|
||||
raise ConflictError("公司名称已存在。") from exc
|
||||
return company_id
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Bank accounts
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def get_account(connection: sqlite3.Connection, account_id: int) -> sqlite3.Row | None:
|
||||
return connection.execute(
|
||||
"SELECT * FROM bank_accounts WHERE id = ?", (account_id,)
|
||||
).fetchone()
|
||||
|
||||
|
||||
def submit_bank_account(
|
||||
connection: sqlite3.Connection,
|
||||
*,
|
||||
company_id: int,
|
||||
bank_name: str,
|
||||
account_type: object,
|
||||
account_number: object,
|
||||
account_name: object = None,
|
||||
start_date: object = None,
|
||||
actor: sqlite3.Row | None,
|
||||
) -> sqlite3.Row:
|
||||
"""Register an account for review; returns the resulting account row.
|
||||
|
||||
A normalized number already present is never duplicated: resubmitting a
|
||||
returned request from the same company reopens that same row as pending;
|
||||
any other existing row is a conflict. The UNIQUE constraint on
|
||||
``account_number`` is the final guard for concurrent submissions.
|
||||
"""
|
||||
number = normalize_account_number(account_number)
|
||||
bank = str(bank_name or "").strip()
|
||||
if not bank:
|
||||
raise ValueError("开户银行不能为空。")
|
||||
kind = validate_account_type(account_type)
|
||||
holder = str(account_name or "").strip() or None
|
||||
requested_from = validate_date(start_date, "启用日期")
|
||||
now = utc_now()
|
||||
|
||||
existing = connection.execute(
|
||||
"SELECT * FROM bank_accounts WHERE account_number = ?", (number,)
|
||||
).fetchone()
|
||||
|
||||
if existing is None:
|
||||
try:
|
||||
with transaction(connection):
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO bank_accounts (
|
||||
company_id, account_number, account_name, bank_name,
|
||||
account_type, status, effective_from, submitted_by,
|
||||
created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?)
|
||||
""",
|
||||
(company_id, number, holder, bank, kind,
|
||||
requested_from, actor["id"] if actor else None, now, now),
|
||||
)
|
||||
account_id = int(cursor.lastrowid)
|
||||
record_change(
|
||||
connection, "bank_account", account_id, "submit", None,
|
||||
{"company_id": company_id, "account_number": number,
|
||||
"bank_name": bank, "account_type": kind, "status": "pending",
|
||||
"effective_from": requested_from},
|
||||
None, actor,
|
||||
)
|
||||
except sqlite3.IntegrityError as exc:
|
||||
# Lost a concurrent-insert race on the UNIQUE constraint.
|
||||
raise ConflictError("该银行账号已登记,请等待现有申请处理。") from exc
|
||||
return get_account(connection, account_id)
|
||||
|
||||
if existing["status"] == "returned" and existing["company_id"] == company_id:
|
||||
before = _snapshot(existing)
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE bank_accounts
|
||||
SET account_name = ?, bank_name = ?, account_type = ?,
|
||||
status = 'pending', effective_from = ?,
|
||||
submitted_by = ?, reviewed_by = NULL, reviewed_at = NULL,
|
||||
review_reason = NULL, updated_at = ?
|
||||
WHERE id = ? AND status = 'returned'
|
||||
""",
|
||||
(holder, bank, kind, requested_from,
|
||||
actor["id"] if actor else None, now, existing["id"]),
|
||||
)
|
||||
record_change(
|
||||
connection, "bank_account", existing["id"], "resubmit",
|
||||
before, {"account_number": number, "bank_name": bank,
|
||||
"account_type": kind, "status": "pending",
|
||||
"effective_from": requested_from},
|
||||
"退回后重新提交", actor,
|
||||
)
|
||||
return get_account(connection, existing["id"])
|
||||
|
||||
if existing["company_id"] == company_id:
|
||||
raise ConflictError("该银行账号已登记,请等待现有申请处理。")
|
||||
raise ConflictError("该银行账号已被其他公司登记,请联系管理员核对。")
|
||||
|
||||
|
||||
def review_bank_account(
|
||||
connection: sqlite3.Connection,
|
||||
account_id: int,
|
||||
decision: str,
|
||||
reason: str | None,
|
||||
actor: sqlite3.Row,
|
||||
*,
|
||||
effective_from: object = None,
|
||||
effective_to: object = None,
|
||||
) -> sqlite3.Row:
|
||||
"""Approve, return or disable a registration; returns the updated row."""
|
||||
account = get_account(connection, account_id)
|
||||
if account is None:
|
||||
raise LookupError("账户不存在。")
|
||||
reason = (reason or "").strip() or None
|
||||
today = utc_today()
|
||||
before = _snapshot(account)
|
||||
|
||||
if decision == "approve":
|
||||
if account["status"] != "pending":
|
||||
raise ConflictError("只有待复核的账户可以审核通过。")
|
||||
start = validate_date(effective_from, "启用日期") or account["effective_from"] or today
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE bank_accounts
|
||||
SET status = 'active', effective_from = ?, effective_to = NULL,
|
||||
reviewed_by = ?, reviewed_at = ?, review_reason = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
""",
|
||||
(start, actor["id"], utc_now(), reason, utc_now(), account_id),
|
||||
)
|
||||
record_change(
|
||||
connection, "bank_account", account_id, "approve", before,
|
||||
{"status": "active", "effective_from": start}, reason, actor,
|
||||
)
|
||||
elif decision == "return":
|
||||
if account["status"] != "pending":
|
||||
raise ConflictError("只有待复核的账户可以退回。")
|
||||
if reason is None:
|
||||
raise ValueError("退回必须填写原因。")
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE bank_accounts
|
||||
SET status = 'returned', reviewed_by = ?, reviewed_at = ?,
|
||||
review_reason = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
""",
|
||||
(actor["id"], utc_now(), reason, utc_now(), account_id),
|
||||
)
|
||||
record_change(
|
||||
connection, "bank_account", account_id, "return", before,
|
||||
{"status": "returned"}, reason, actor,
|
||||
)
|
||||
elif decision == "disable":
|
||||
if account["status"] != "active":
|
||||
raise ConflictError("只有已启用的账户可以停用。")
|
||||
if reason is None:
|
||||
raise ValueError("停用必须填写原因。")
|
||||
end = validate_date(effective_to, "停用日期") or today
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE bank_accounts
|
||||
SET status = 'disabled', effective_to = ?,
|
||||
reviewed_by = ?, reviewed_at = ?, review_reason = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
""",
|
||||
(end, actor["id"], utc_now(), reason, utc_now(), account_id),
|
||||
)
|
||||
record_change(
|
||||
connection, "bank_account", account_id, "disable", before,
|
||||
{"status": "disabled", "effective_to": end}, reason, actor,
|
||||
)
|
||||
else:
|
||||
raise ValueError("审核决定必须是 approve、return 或 disable。")
|
||||
return get_account(connection, account_id)
|
||||
|
||||
|
||||
def in_effective_window(account: sqlite3.Row, on_date: str) -> bool:
|
||||
"""True when ``on_date`` falls inside the account's effective interval.
|
||||
|
||||
``effective_to`` is the last participating day (inclusive).
|
||||
"""
|
||||
if account["effective_from"] and on_date < account["effective_from"]:
|
||||
return False
|
||||
if account["effective_to"] and on_date > account["effective_to"]:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def is_usable(account: sqlite3.Row, on_date: str) -> bool:
|
||||
"""True when the account may accept uploads / be selected on a date."""
|
||||
return account["status"] == "active" and in_effective_window(account, on_date)
|
||||
|
||||
|
||||
def is_identifiable(account: sqlite3.Row, on_date: str) -> bool:
|
||||
"""True when the account may resolve ownership for a transaction date.
|
||||
|
||||
A disabled account keeps identifying historical rows inside its effective
|
||||
window — disabling stops future participation, it never rewrites history.
|
||||
"""
|
||||
return account["status"] in ("active", "disabled") and in_effective_window(
|
||||
account, on_date
|
||||
)
|
||||
|
||||
|
||||
def list_accounts(
|
||||
connection: sqlite3.Connection,
|
||||
company_id: int | None = None,
|
||||
status: str | None = None,
|
||||
) -> list[sqlite3.Row]:
|
||||
conditions: list[str] = []
|
||||
params: list[object] = []
|
||||
if company_id is not None:
|
||||
conditions.append("a.company_id = ?")
|
||||
params.append(company_id)
|
||||
if status is not None:
|
||||
if status not in ACCOUNT_STATUSES:
|
||||
raise ValueError("无效的账户状态。")
|
||||
conditions.append("a.status = ?")
|
||||
params.append(status)
|
||||
where = f"WHERE {' AND '.join(conditions)}" if conditions else ""
|
||||
return connection.execute(
|
||||
f"""
|
||||
SELECT a.*, c.name AS company_name
|
||||
FROM bank_accounts a
|
||||
JOIN companies c ON c.id = a.company_id
|
||||
{where}
|
||||
ORDER BY a.id
|
||||
""",
|
||||
params,
|
||||
).fetchall()
|
||||
|
||||
|
||||
def usable_accounts(
|
||||
connection: sqlite3.Connection, company_id: int, on_date: str | None = None
|
||||
) -> list[sqlite3.Row]:
|
||||
"""Accounts allowed to upload / identify ownership for the company today."""
|
||||
day = on_date or utc_today()
|
||||
return [
|
||||
account
|
||||
for account in list_accounts(connection, company_id=company_id)
|
||||
if is_usable(account, day)
|
||||
]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Aliases
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def add_alias(
|
||||
connection: sqlite3.Connection,
|
||||
account_id: int,
|
||||
alias_kind: str,
|
||||
alias_value: object,
|
||||
priority: object = None,
|
||||
effective_from: object = None,
|
||||
effective_to: object = None,
|
||||
actor: sqlite3.Row | None = None,
|
||||
) -> int:
|
||||
"""Attach a name/account alias with an effective interval; returns the id."""
|
||||
if get_account(connection, account_id) is None:
|
||||
raise LookupError("账户不存在。")
|
||||
if alias_kind not in ALIAS_KINDS:
|
||||
raise ValueError("别名类型必须是 name 或 account。")
|
||||
if alias_kind == "account":
|
||||
value = normalize_account_number(alias_value)
|
||||
else:
|
||||
value = re.sub(r"\s+", "", str(alias_value or ""))
|
||||
if not value:
|
||||
raise ValueError("户名别名不能为空。")
|
||||
try:
|
||||
rank = int(priority) if priority not in (None, "") else 100
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError("优先级必须是整数。") from None
|
||||
start = validate_date(effective_from, "别名生效日期")
|
||||
end = validate_date(effective_to, "别名失效日期")
|
||||
if start and end and end < start:
|
||||
raise ValueError("别名失效日期不能早于生效日期。")
|
||||
try:
|
||||
with transaction(connection):
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO account_aliases (
|
||||
bank_account_id, alias_kind, alias_value, priority,
|
||||
effective_from, effective_to, created_by, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(account_id, alias_kind, value, rank, start, end,
|
||||
actor["id"] if actor else None, utc_now()),
|
||||
)
|
||||
alias_id = int(cursor.lastrowid)
|
||||
record_change(
|
||||
connection, "account_alias", alias_id, "create", None,
|
||||
{"bank_account_id": account_id, "alias_kind": alias_kind,
|
||||
"alias_value": value, "priority": rank,
|
||||
"effective_from": start, "effective_to": end},
|
||||
None, actor,
|
||||
)
|
||||
except sqlite3.IntegrityError as exc:
|
||||
raise ConflictError("该账户下相同别名已存在。") from exc
|
||||
return alias_id
|
||||
|
||||
|
||||
def list_aliases(connection: sqlite3.Connection, account_id: int) -> list[sqlite3.Row]:
|
||||
return connection.execute(
|
||||
"SELECT * FROM account_aliases WHERE bank_account_id = ? ORDER BY id",
|
||||
(account_id,),
|
||||
).fetchall()
|
||||
|
||||
|
||||
def match_account(
|
||||
connection: sqlite3.Connection,
|
||||
*,
|
||||
account_number: object = None,
|
||||
name: object = None,
|
||||
on_date: str | None = None,
|
||||
) -> list[dict[str, object]]:
|
||||
"""Resolve an observed counterparty to operating, in-window accounts.
|
||||
|
||||
Deterministic priority: exact account number < account alias < name
|
||||
alias; within one tier the alias ``priority`` column orders the hits.
|
||||
Pending and returned accounts never match; disabled accounts still match
|
||||
transaction dates inside their effective window (see ``is_identifiable``).
|
||||
"""
|
||||
day = on_date or utc_today()
|
||||
hits: list[tuple[int, sqlite3.Row, str]] = []
|
||||
|
||||
number = str(account_number or "").strip()
|
||||
if number:
|
||||
try:
|
||||
normalized = normalize_account_number(number)
|
||||
except ValueError:
|
||||
normalized = None
|
||||
if normalized is not None:
|
||||
exact = connection.execute(
|
||||
"SELECT * FROM bank_accounts WHERE account_number = ?",
|
||||
(normalized,),
|
||||
).fetchone()
|
||||
if exact is not None and is_identifiable(exact, day):
|
||||
hits.append((PRIORITY_EXACT_ACCOUNT, exact, "account_exact"))
|
||||
alias_rows = connection.execute(
|
||||
"""
|
||||
SELECT a.*, al.priority AS alias_priority,
|
||||
al.effective_from AS alias_from, al.effective_to AS alias_to
|
||||
FROM account_aliases al
|
||||
JOIN bank_accounts a ON a.id = al.bank_account_id
|
||||
WHERE al.alias_kind = 'account' AND al.alias_value = ?
|
||||
""",
|
||||
(normalized,),
|
||||
).fetchall()
|
||||
for alias in alias_rows:
|
||||
if _alias_in_window(alias, day) and is_identifiable(alias, day):
|
||||
hits.append(
|
||||
(PRIORITY_ACCOUNT_ALIAS + alias["alias_priority"], alias, "account_alias")
|
||||
)
|
||||
|
||||
normalized_name = re.sub(r"\s+", "", str(name or ""))
|
||||
if normalized_name:
|
||||
alias_rows = connection.execute(
|
||||
"""
|
||||
SELECT a.*, al.priority AS alias_priority,
|
||||
al.effective_from AS alias_from, al.effective_to AS alias_to
|
||||
FROM account_aliases al
|
||||
JOIN bank_accounts a ON a.id = al.bank_account_id
|
||||
WHERE al.alias_kind = 'name' AND al.alias_value = ?
|
||||
""",
|
||||
(normalized_name,),
|
||||
).fetchall()
|
||||
for alias in alias_rows:
|
||||
if _alias_in_window(alias, day) and is_identifiable(alias, day):
|
||||
hits.append(
|
||||
(PRIORITY_NAME_ALIAS + alias["alias_priority"], alias, "name_alias")
|
||||
)
|
||||
|
||||
hits.sort(key=lambda item: (item[0], item[1]["id"]))
|
||||
seen: set[int] = set()
|
||||
results: list[dict[str, object]] = []
|
||||
for rank, account, via in hits:
|
||||
if account["id"] in seen:
|
||||
continue
|
||||
seen.add(account["id"])
|
||||
results.append(
|
||||
{
|
||||
"bank_account_id": account["id"],
|
||||
"company_id": account["company_id"],
|
||||
"via": via,
|
||||
"priority": rank,
|
||||
}
|
||||
)
|
||||
return results
|
||||
|
||||
|
||||
def _alias_in_window(alias: sqlite3.Row, on_date: str) -> bool:
|
||||
if alias["alias_from"] and on_date < alias["alias_from"]:
|
||||
return False
|
||||
if alias["alias_to"] and on_date > alias["alias_to"]:
|
||||
return False
|
||||
return True
|
||||
File diff suppressed because it is too large
Load Diff
@@ -39,24 +39,3 @@ class StatementBatch:
|
||||
period_end: date | None
|
||||
transactions: tuple[NormalizedTransaction, ...]
|
||||
warnings: tuple[str, ...]
|
||||
template_version: int = 1
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SheetResult:
|
||||
"""Per-worksheet parse outcome with the four diagnostic evidence items.
|
||||
|
||||
``outcome`` is the deterministic parse verdict: ``parsed`` (transactions
|
||||
normalized), ``exception`` (template/header/balance problems) or
|
||||
``ignored`` (empty or single-cell sheets with no bank content). The human
|
||||
decision about whether a parsed sheet may participate in calculations is
|
||||
a separate lifecycle stage (``review_status``), persisted in
|
||||
``sheet_reviews``; it is never decided here.
|
||||
"""
|
||||
|
||||
sheet_name: str
|
||||
outcome: str # parsed | exception | ignored
|
||||
message: str | None = None
|
||||
scanned_rows: int | None = None
|
||||
candidate_headers: tuple[str, ...] = ()
|
||||
batch: StatementBatch | None = None
|
||||
|
||||
@@ -1,275 +0,0 @@
|
||||
"""Streaming multipart/form-data parser for the stdlib HTTP server.
|
||||
|
||||
The upload body is consumed in chunks from the request stream and never
|
||||
assembled into memory as a whole. File parts are streamed straight to a temp
|
||||
file on disk with an incremental size cap; text fields are capped at a small
|
||||
field size. File bytes are preserved exactly (no trailing-byte trimming), the
|
||||
first file part is the only one accepted, and both the extension and the file
|
||||
signature are validated by the caller.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
import re
|
||||
from typing import BinaryIO
|
||||
|
||||
MAX_FIELD_BYTES = 16 * 1024
|
||||
MAX_HEADER_BYTES = 32 * 1024
|
||||
CHUNK_SIZE = 64 * 1024
|
||||
# .xlsx files are ZIP containers (PK\x03\x04 local header or an empty-archive
|
||||
# PK\x05\x06); .xls files are OLE2 compound documents.
|
||||
XLSX_MAGIC = (b"PK\x03\x04", b"PK\x05\x06")
|
||||
XLS_MAGIC = (b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1",)
|
||||
|
||||
|
||||
class MultipartError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class UploadedFile:
|
||||
filename: str
|
||||
path: Path
|
||||
size: int
|
||||
|
||||
|
||||
def valid_file_signature(path: Path, suffix: str) -> bool:
|
||||
"""True when the file's leading bytes match its declared extension."""
|
||||
with path.open("rb") as handle:
|
||||
head = handle.read(8)
|
||||
if suffix == ".xlsx":
|
||||
return any(head.startswith(magic) for magic in XLSX_MAGIC)
|
||||
if suffix == ".xls":
|
||||
return any(head.startswith(magic) for magic in XLS_MAGIC)
|
||||
return False
|
||||
|
||||
|
||||
class _MultipartStream:
|
||||
def __init__(
|
||||
self,
|
||||
rfile: BinaryIO,
|
||||
content_length: int,
|
||||
content_type: str,
|
||||
*,
|
||||
max_body_bytes: int,
|
||||
) -> None:
|
||||
lowered = content_type.lower()
|
||||
if not lowered.startswith("multipart/form-data"):
|
||||
raise MultipartError("上传请求必须是 multipart/form-data。")
|
||||
match = re.search(r"boundary=(?:\"([^\"]+)\"|([^;]+))", content_type)
|
||||
if not match:
|
||||
raise MultipartError("上传请求缺少文件边界。")
|
||||
boundary = (match.group(1) or match.group(2)).strip().encode("utf-8")
|
||||
if not boundary or len(boundary) > 200:
|
||||
raise MultipartError("上传请求的文件边界无效。")
|
||||
if content_length <= 0:
|
||||
raise MultipartError("上传请求为空。")
|
||||
if content_length > max_body_bytes:
|
||||
raise MultipartError(f"上传请求超过 {max_body_bytes // (1024 * 1024)} MB 限制。")
|
||||
self.rfile = rfile
|
||||
self.remaining = content_length
|
||||
self.total_read = 0
|
||||
self.buffer = bytearray()
|
||||
self.boundary = boundary
|
||||
self._fill()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Low-level stream helpers
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _fill(self) -> None:
|
||||
if self.total_read >= self.remaining:
|
||||
return
|
||||
want = min(CHUNK_SIZE, self.remaining - self.total_read)
|
||||
data = self.rfile.read(want)
|
||||
if not data:
|
||||
# Client closed early; clamp remaining so every helper sees EOF.
|
||||
self.remaining = self.total_read
|
||||
return
|
||||
self.total_read += len(data)
|
||||
self.buffer.extend(data)
|
||||
|
||||
def _take(self, count: int) -> bytes:
|
||||
while len(self.buffer) < count:
|
||||
if self.total_read >= self.remaining:
|
||||
raise MultipartError("multipart 请求体不完整。")
|
||||
self._fill()
|
||||
out = bytes(self.buffer[:count])
|
||||
del self.buffer[:count]
|
||||
return out
|
||||
|
||||
def _read_line(self) -> bytes:
|
||||
while True:
|
||||
index = self.buffer.find(b"\n")
|
||||
if index >= 0:
|
||||
line = bytes(self.buffer[: index + 1])
|
||||
del self.buffer[: index + 1]
|
||||
return line
|
||||
if self.total_read >= self.remaining:
|
||||
if not self.buffer:
|
||||
raise MultipartError("multipart 请求体不完整。")
|
||||
line = bytes(self.buffer)
|
||||
self.buffer.clear()
|
||||
return line
|
||||
self._fill()
|
||||
|
||||
def _skip_preamble(self) -> None:
|
||||
marker = b"--" + self.boundary
|
||||
while True:
|
||||
index = self.buffer.find(marker)
|
||||
if index >= 0:
|
||||
del self.buffer[: index + len(marker)]
|
||||
return
|
||||
keep = len(marker) - 1
|
||||
if len(self.buffer) > keep:
|
||||
del self.buffer[: len(self.buffer) - keep]
|
||||
if self.total_read >= self.remaining:
|
||||
raise MultipartError("上传请求中没有找到文件。")
|
||||
self._fill()
|
||||
|
||||
def _iter_content(self, boundary: bytes):
|
||||
"""Yield content bytes up to (excluding) the ``\\r\\n--boundary`` marker."""
|
||||
marker = b"\r\n--" + boundary
|
||||
keep = len(marker) - 1
|
||||
while True:
|
||||
index = self.buffer.find(marker)
|
||||
if index >= 0:
|
||||
content = bytes(self.buffer[:index])
|
||||
del self.buffer[:index]
|
||||
if content:
|
||||
yield content
|
||||
return
|
||||
if len(self.buffer) > keep:
|
||||
safe = len(self.buffer) - keep
|
||||
content = bytes(self.buffer[:safe])
|
||||
del self.buffer[:safe]
|
||||
if content:
|
||||
yield content
|
||||
if self.total_read >= self.remaining:
|
||||
raise MultipartError("multipart 请求体缺少结束边界。")
|
||||
self._fill()
|
||||
|
||||
def _after_content_boundary(self) -> str:
|
||||
"""Consume the content-ending marker; return 'part' or 'end'."""
|
||||
marker = b"\r\n--" + self.boundary
|
||||
del self.buffer[: len(marker)]
|
||||
indicator = self._take(2)
|
||||
if indicator == b"--":
|
||||
if self.buffer.startswith(b"\r\n"):
|
||||
del self.buffer[:2]
|
||||
elif self.buffer.startswith(b"\n"):
|
||||
del self.buffer[:1]
|
||||
return "end"
|
||||
if indicator != b"\r\n":
|
||||
raise MultipartError("上传请求格式无效。")
|
||||
return "part"
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Part parsing
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _read_headers(self) -> bytes:
|
||||
total = 0
|
||||
lines: list[bytes] = []
|
||||
while True:
|
||||
line = self._read_line()
|
||||
total += len(line)
|
||||
if total > MAX_HEADER_BYTES:
|
||||
raise MultipartError("multipart 头部过长。")
|
||||
if line in (b"\r\n", b"\n"):
|
||||
return b"".join(lines)
|
||||
lines.append(line)
|
||||
|
||||
@staticmethod
|
||||
def _parse_disposition(header: bytes) -> tuple[str | None, str | None]:
|
||||
name = None
|
||||
filename = None
|
||||
name_match = re.search(br'name="([^"]*)"', header)
|
||||
if name_match:
|
||||
name = name_match.group(1).decode("utf-8", errors="replace")
|
||||
filename_match = re.search(br'filename="([^"]*)"', header)
|
||||
if filename_match:
|
||||
filename = filename_match.group(1).decode("utf-8", errors="replace")
|
||||
return name, filename
|
||||
|
||||
def parse(self, work_dir: Path) -> tuple[dict[str, str], UploadedFile | None]:
|
||||
import tempfile
|
||||
|
||||
self._skip_preamble()
|
||||
next_bytes = self._take(2)
|
||||
if next_bytes == b"--":
|
||||
# Empty multipart body: opening boundary immediately closes.
|
||||
return {}, None
|
||||
if next_bytes != b"\r\n":
|
||||
raise MultipartError("上传请求格式无效。")
|
||||
|
||||
fields: dict[str, str] = {}
|
||||
uploaded: UploadedFile | None = None
|
||||
while True:
|
||||
header = self._read_headers()
|
||||
name, filename = self._parse_disposition(header)
|
||||
if name is None:
|
||||
raise MultipartError("上传请求缺少字段名。")
|
||||
|
||||
if filename is not None:
|
||||
if uploaded is not None:
|
||||
raise MultipartError("一次只能上传一个文件。")
|
||||
with tempfile.NamedTemporaryFile(
|
||||
dir=str(work_dir), prefix="upload-", delete=False
|
||||
) as sink:
|
||||
temp_path = Path(sink.name)
|
||||
size = 0
|
||||
try:
|
||||
for chunk in self._iter_content(self.boundary):
|
||||
size += len(chunk)
|
||||
sink.write(chunk)
|
||||
except Exception:
|
||||
temp_path.unlink(missing_ok=True)
|
||||
raise
|
||||
uploaded = UploadedFile(
|
||||
filename=filename, path=temp_path, size=size
|
||||
)
|
||||
if self._after_content_boundary() == "end":
|
||||
break
|
||||
else:
|
||||
chunks: list[bytes] = []
|
||||
total = 0
|
||||
for chunk in self._iter_content(self.boundary):
|
||||
total += len(chunk)
|
||||
if total > MAX_FIELD_BYTES:
|
||||
raise MultipartError("表单字段超过大小限制。")
|
||||
chunks.append(chunk)
|
||||
fields[name] = b"".join(chunks).decode(
|
||||
"utf-8", errors="replace"
|
||||
).strip()
|
||||
if self._after_content_boundary() == "end":
|
||||
break
|
||||
return fields, uploaded
|
||||
|
||||
|
||||
def parse_upload(
|
||||
rfile: BinaryIO,
|
||||
content_length: int,
|
||||
content_type: str,
|
||||
work_dir: str | Path,
|
||||
*,
|
||||
max_file_bytes: int,
|
||||
) -> tuple[dict[str, str], UploadedFile | None]:
|
||||
"""Stream a multipart upload; returns ``(fields, uploaded_file)``.
|
||||
|
||||
Raises :class:`MultipartError` for malformed or oversized bodies. The
|
||||
caller owns the uploaded temp file and must remove it when done.
|
||||
"""
|
||||
work = Path(work_dir)
|
||||
work.mkdir(parents=True, exist_ok=True)
|
||||
stream = _MultipartStream(
|
||||
rfile, content_length, content_type, max_body_bytes=max_file_bytes + MAX_FIELD_BYTES
|
||||
)
|
||||
fields, uploaded = stream.parse(work)
|
||||
if uploaded is None:
|
||||
raise MultipartError("上传请求中没有找到文件。")
|
||||
if uploaded.size > max_file_bytes:
|
||||
raise MultipartError(f"文件超过 {max_file_bytes // (1024 * 1024)} MB 限制。")
|
||||
return fields, uploaded
|
||||
+21
-78
@@ -7,7 +7,7 @@ from pathlib import Path
|
||||
import re
|
||||
from typing import Any, Iterable
|
||||
|
||||
from .models import NormalizedTransaction, SheetResult, StatementBatch
|
||||
from .models import NormalizedTransaction, StatementBatch
|
||||
from .reader import RawSheet, read_workbook
|
||||
from .templates import BankTemplate, TEMPLATES, normalize_header
|
||||
|
||||
@@ -24,11 +24,8 @@ class AmbiguousTemplateError(StatementParseError):
|
||||
pass
|
||||
|
||||
|
||||
SCAN_LIMIT = 50
|
||||
|
||||
|
||||
def detect_header(
|
||||
rows: tuple[tuple[Any, ...], ...], scan_limit: int = SCAN_LIMIT
|
||||
rows: tuple[tuple[Any, ...], ...], scan_limit: int = 50
|
||||
) -> tuple[BankTemplate, int, dict[str, int]]:
|
||||
candidates: list[tuple[int, BankTemplate, int, dict[str, int]]] = []
|
||||
for row_index, row in enumerate(rows[:scan_limit]):
|
||||
@@ -45,8 +42,8 @@ def detect_header(
|
||||
|
||||
if not candidates:
|
||||
inspected = min(len(rows), scan_limit)
|
||||
candidate_rows = _header_candidate_rows(rows[:scan_limit])
|
||||
detail = f";候选表头:{';'.join(candidate_rows)}" if candidate_rows else ""
|
||||
candidate_rows = _header_candidate_summary(rows[:scan_limit])
|
||||
detail = f";候选表头:{candidate_rows}" if candidate_rows else ""
|
||||
raise UnknownTemplateError(
|
||||
f"未识别到受支持的银行表头(已扫描前 {inspected} 行){detail}。"
|
||||
)
|
||||
@@ -63,69 +60,21 @@ def detect_header(
|
||||
|
||||
|
||||
def parse_statement(path: str | Path) -> tuple[StatementBatch, ...]:
|
||||
batches = tuple(result.batch for result in analyze_workbook(path) if result.batch)
|
||||
if not batches:
|
||||
raise UnknownTemplateError(f"{Path(path).name}: 工作簿中没有可解析的工作表。")
|
||||
return batches
|
||||
|
||||
|
||||
def analyze_workbook(path: str | Path) -> tuple[SheetResult, ...]:
|
||||
"""Parse every worksheet into an independent result.
|
||||
|
||||
Each worksheet yields exactly one :class:`SheetResult` whose ``outcome``
|
||||
is ``parsed``, ``exception`` or ``ignored``. Unreadable workbooks raise
|
||||
``CorruptWorkbookError``; a workbook that reads but contains no parsable
|
||||
sheet still returns one result per sheet so the UI can surface the
|
||||
filename / sheet / scanned range / candidate headers evidence.
|
||||
"""
|
||||
source = Path(path)
|
||||
return tuple(_analyze_sheet(source, sheet) for sheet in read_workbook(source))
|
||||
batches: list[StatementBatch] = []
|
||||
errors: list[str] = []
|
||||
for sheet in read_workbook(source):
|
||||
if not any(any(_text(value) for value in row) for row in sheet.rows):
|
||||
continue
|
||||
try:
|
||||
batches.append(_parse_sheet(source, sheet))
|
||||
except UnknownTemplateError as exc:
|
||||
errors.append(f"{sheet.name}: {exc}")
|
||||
|
||||
|
||||
def _analyze_sheet(source: Path, sheet: RawSheet) -> SheetResult:
|
||||
rows = sheet.rows
|
||||
scanned = min(len(rows), SCAN_LIMIT)
|
||||
if not rows:
|
||||
return SheetResult(
|
||||
sheet_name=sheet.name,
|
||||
outcome="ignored",
|
||||
message=f"工作表「{sheet.name}」为空,已跳过。",
|
||||
scanned_rows=0,
|
||||
)
|
||||
if not any(any(_text(value) for value in row) for row in rows):
|
||||
return SheetResult(
|
||||
sheet_name=sheet.name,
|
||||
outcome="ignored",
|
||||
message=f"工作表「{sheet.name}」无有效内容,已跳过。",
|
||||
scanned_rows=scanned,
|
||||
)
|
||||
try:
|
||||
batch = _parse_sheet(source, sheet)
|
||||
except UnknownTemplateError as exc:
|
||||
return SheetResult(
|
||||
sheet_name=sheet.name,
|
||||
outcome="exception",
|
||||
message=_clean_sheet_message(str(exc), source),
|
||||
scanned_rows=scanned,
|
||||
candidate_headers=_header_candidate_rows(rows),
|
||||
)
|
||||
except (AmbiguousTemplateError, StatementParseError) as exc:
|
||||
return SheetResult(
|
||||
sheet_name=sheet.name,
|
||||
outcome="exception",
|
||||
message=_clean_sheet_message(str(exc), source),
|
||||
scanned_rows=scanned,
|
||||
)
|
||||
return SheetResult(
|
||||
sheet_name=sheet.name,
|
||||
outcome="parsed",
|
||||
scanned_rows=scanned,
|
||||
batch=batch,
|
||||
)
|
||||
|
||||
|
||||
def _clean_sheet_message(message: str, source: Path) -> str:
|
||||
return message.replace(str(source), source.name).replace(source.name, "本文件")
|
||||
if not batches:
|
||||
detail = "; ".join(errors) or "Workbook contains no readable worksheets."
|
||||
raise UnknownTemplateError(f"{source.name}: {detail}")
|
||||
return tuple(batches)
|
||||
|
||||
|
||||
def parse_directory(path: str | Path) -> tuple[StatementBatch, ...]:
|
||||
@@ -141,14 +90,9 @@ def parse_directory(path: str | Path) -> tuple[StatementBatch, ...]:
|
||||
return tuple(batch for file in files for batch in parse_statement(file))
|
||||
|
||||
|
||||
def _header_candidate_rows(
|
||||
def _header_candidate_summary(
|
||||
rows: tuple[tuple[Any, ...], ...], limit: int = 3
|
||||
) -> tuple[str, ...]:
|
||||
"""Preview up to ``limit`` plausible header rows.
|
||||
|
||||
Every non-empty row counts as a candidate, including single-cell rows, so
|
||||
an ambiguous workbook always has explicit scan evidence for the UI.
|
||||
"""
|
||||
) -> str:
|
||||
known_headers = {
|
||||
alias
|
||||
for template in TEMPLATES
|
||||
@@ -158,7 +102,7 @@ def _header_candidate_rows(
|
||||
candidates: list[tuple[int, int, int, tuple[str, ...]]] = []
|
||||
for row_index, row in enumerate(rows):
|
||||
values = tuple(_text(value) for value in row if _text(value))
|
||||
if not values:
|
||||
if len(values) < 2:
|
||||
continue
|
||||
matched = sum(normalize_header(value) in known_headers for value in values)
|
||||
candidates.append((matched, len(values), row_index, values))
|
||||
@@ -170,7 +114,7 @@ def _header_candidate_rows(
|
||||
if len(values) > 8:
|
||||
preview += "……"
|
||||
summaries.append(f"第 {row_index + 1} 行「{preview}」")
|
||||
return tuple(summaries)
|
||||
return ";".join(summaries)
|
||||
|
||||
|
||||
def _parse_sheet(source: Path, sheet: RawSheet) -> StatementBatch:
|
||||
@@ -246,7 +190,6 @@ def _parse_sheet(source: Path, sheet: RawSheet) -> StatementBatch:
|
||||
else None,
|
||||
transactions=tuple(transactions),
|
||||
warnings=tuple(warnings),
|
||||
template_version=template.version,
|
||||
)
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,280 +0,0 @@
|
||||
"""Personal transit account mappings and their administrator approval.
|
||||
|
||||
A personal transit mapping states that a personal bank account represents a
|
||||
company for a specific flow direction inside an effective interval. The key is
|
||||
the normalized account number; the account holder name is display-only and
|
||||
never resolves a counterparty on its own (``AGENTS.md``: never infer a
|
||||
financial fact from a name alone). Only administrator-approved (``active``)
|
||||
mappings inside their effective window participate in counterparty resolution.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
|
||||
from .db import transaction, utc_now
|
||||
from .master_data import (
|
||||
ConflictError,
|
||||
mask_account_number,
|
||||
normalize_account_number,
|
||||
record_change,
|
||||
validate_date,
|
||||
)
|
||||
|
||||
MAPPING_STATUSES = ("pending", "active", "returned", "disabled")
|
||||
ALLOWED_DIRECTIONS = ("outgoing", "incoming", "both")
|
||||
|
||||
|
||||
def get_mapping(connection: sqlite3.Connection, mapping_id: int) -> sqlite3.Row | None:
|
||||
return connection.execute(
|
||||
"SELECT * FROM personal_transit_mappings WHERE id = ?", (mapping_id,)
|
||||
).fetchone()
|
||||
|
||||
|
||||
def submit_mapping(
|
||||
connection: sqlite3.Connection,
|
||||
*,
|
||||
account_number: object,
|
||||
account_name: object,
|
||||
represented_company_id: int,
|
||||
allowed_direction: str,
|
||||
effective_from: object = None,
|
||||
actor: sqlite3.Row | None,
|
||||
) -> sqlite3.Row:
|
||||
"""Create a pending personal transit mapping; returns the new row.
|
||||
|
||||
The account number is normalized (digits only) and unique: resubmitting a
|
||||
returned request from the same company reopens the same row as pending;
|
||||
any other existing row is a conflict guarded by the UNIQUE constraint.
|
||||
"""
|
||||
number = normalize_account_number(account_number)
|
||||
holder = str(account_name or "").strip() or None
|
||||
direction = str(allowed_direction or "").strip()
|
||||
if direction not in ALLOWED_DIRECTIONS:
|
||||
raise ValueError(f"允许方向必须是:{'、'.join(ALLOWED_DIRECTIONS)}。")
|
||||
if not holder:
|
||||
raise ValueError("账户户名不能为空(仅作展示,不作匹配键)。")
|
||||
company = connection.execute(
|
||||
"SELECT id FROM companies WHERE id = ?", (represented_company_id,)
|
||||
).fetchone()
|
||||
if company is None:
|
||||
raise ValueError("代表的公司不存在。")
|
||||
start = validate_date(effective_from, "生效日期")
|
||||
now = utc_now()
|
||||
|
||||
existing = connection.execute(
|
||||
"SELECT * FROM personal_transit_mappings WHERE account_number = ?", (number,)
|
||||
).fetchone()
|
||||
if existing is None:
|
||||
try:
|
||||
with transaction(connection):
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO personal_transit_mappings (
|
||||
account_number, account_name, represented_company_id,
|
||||
allowed_direction, status, effective_from, submitted_by,
|
||||
created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, 'pending', ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
number, holder, represented_company_id, direction,
|
||||
start, actor["id"] if actor else None, now, now,
|
||||
),
|
||||
)
|
||||
mapping_id = int(cursor.lastrowid)
|
||||
record_change(
|
||||
connection, "personal_transit_mapping", mapping_id, "submit", None,
|
||||
{"account_number": number, "account_name": holder,
|
||||
"represented_company_id": represented_company_id,
|
||||
"allowed_direction": direction, "status": "pending",
|
||||
"effective_from": start},
|
||||
None, actor,
|
||||
)
|
||||
except sqlite3.IntegrityError as exc:
|
||||
raise ConflictError("该个人过账账号已登记,请等待现有申请处理。") from exc
|
||||
return get_mapping(connection, mapping_id)
|
||||
|
||||
if existing["status"] == "returned":
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE personal_transit_mappings
|
||||
SET account_name = ?, represented_company_id = ?,
|
||||
allowed_direction = ?, status = 'pending', effective_from = ?,
|
||||
submitted_by = ?, reviewed_by = NULL, reviewed_at = NULL,
|
||||
review_reason = NULL, updated_at = ?
|
||||
WHERE id = ? AND status = 'returned'
|
||||
""",
|
||||
(
|
||||
holder, represented_company_id, direction, start,
|
||||
actor["id"] if actor else None, now, existing["id"],
|
||||
),
|
||||
)
|
||||
record_change(
|
||||
connection, "personal_transit_mapping", existing["id"], "resubmit",
|
||||
None, {"account_number": number, "status": "pending",
|
||||
"allowed_direction": direction, "effective_from": start},
|
||||
"退回后重新提交", actor,
|
||||
)
|
||||
return get_mapping(connection, existing["id"])
|
||||
|
||||
raise ConflictError("该个人过账账号已登记,请等待现有申请处理。")
|
||||
|
||||
|
||||
def review_mapping(
|
||||
connection: sqlite3.Connection,
|
||||
mapping_id: int,
|
||||
decision: str,
|
||||
reason: str | None,
|
||||
actor: sqlite3.Row,
|
||||
*,
|
||||
effective_from: object = None,
|
||||
effective_to: object = None,
|
||||
) -> sqlite3.Row:
|
||||
"""Approve, return or disable a mapping; returns the updated row."""
|
||||
mapping = get_mapping(connection, mapping_id)
|
||||
if mapping is None:
|
||||
raise LookupError("个人过账映射不存在。")
|
||||
reason = (reason or "").strip() or None
|
||||
today = utc_now()[:10]
|
||||
|
||||
if decision == "approve":
|
||||
if mapping["status"] != "pending":
|
||||
raise ConflictError("只有待复核的映射可以审核通过。")
|
||||
start = validate_date(effective_from, "生效日期") or mapping["effective_from"] or today
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE personal_transit_mappings
|
||||
SET status = 'active', effective_from = ?, effective_to = NULL,
|
||||
reviewed_by = ?, reviewed_at = ?, review_reason = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
""",
|
||||
(start, actor["id"], utc_now(), reason, utc_now(), mapping_id),
|
||||
)
|
||||
record_change(
|
||||
connection, "personal_transit_mapping", mapping_id, "approve", None,
|
||||
{"status": "active", "effective_from": start}, reason, actor,
|
||||
)
|
||||
elif decision == "return":
|
||||
if mapping["status"] != "pending":
|
||||
raise ConflictError("只有待复核的映射可以退回。")
|
||||
if reason is None:
|
||||
raise ValueError("退回必须填写原因。")
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE personal_transit_mappings
|
||||
SET status = 'returned', reviewed_by = ?, reviewed_at = ?,
|
||||
review_reason = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
""",
|
||||
(actor["id"], utc_now(), reason, utc_now(), mapping_id),
|
||||
)
|
||||
record_change(
|
||||
connection, "personal_transit_mapping", mapping_id, "return", None,
|
||||
{"status": "returned"}, reason, actor,
|
||||
)
|
||||
elif decision == "disable":
|
||||
if mapping["status"] != "active":
|
||||
raise ConflictError("只有已启用的映射可以停用。")
|
||||
if reason is None:
|
||||
raise ValueError("停用必须填写原因。")
|
||||
end = validate_date(effective_to, "停用日期") or today
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE personal_transit_mappings
|
||||
SET status = 'disabled', effective_to = ?,
|
||||
reviewed_by = ?, reviewed_at = ?, review_reason = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
""",
|
||||
(end, actor["id"], utc_now(), reason, utc_now(), mapping_id),
|
||||
)
|
||||
record_change(
|
||||
connection, "personal_transit_mapping", mapping_id, "disable", None,
|
||||
{"status": "disabled", "effective_to": end}, reason, actor,
|
||||
)
|
||||
else:
|
||||
raise ValueError("审核决定必须是 approve、return 或 disable。")
|
||||
return get_mapping(connection, mapping_id)
|
||||
|
||||
|
||||
def list_mappings(
|
||||
connection: sqlite3.Connection,
|
||||
company_id: int | None = None,
|
||||
status: str | None = None,
|
||||
) -> list[sqlite3.Row]:
|
||||
conditions: list[str] = []
|
||||
params: list[object] = []
|
||||
if company_id is not None:
|
||||
conditions.append("m.represented_company_id = ?")
|
||||
params.append(company_id)
|
||||
if status is not None:
|
||||
if status not in MAPPING_STATUSES:
|
||||
raise ValueError("无效的映射状态。")
|
||||
conditions.append("m.status = ?")
|
||||
params.append(status)
|
||||
where = f"WHERE {' AND '.join(conditions)}" if conditions else ""
|
||||
return connection.execute(
|
||||
f"""
|
||||
SELECT m.*, c.name AS company_name
|
||||
FROM personal_transit_mappings m
|
||||
JOIN companies c ON c.id = m.represented_company_id
|
||||
{where}
|
||||
ORDER BY m.id
|
||||
""",
|
||||
params,
|
||||
).fetchall()
|
||||
|
||||
|
||||
def is_mapping_active(mapping: sqlite3.Row, on_date: str) -> bool:
|
||||
"""True when the mapping may resolve a counterparty on ``on_date``.
|
||||
|
||||
``effective_to`` is the last participating day (inclusive). Disabled
|
||||
mappings stop resolving new rows but keep identifying historical rows
|
||||
inside their effective window, matching ``bank_accounts`` semantics.
|
||||
"""
|
||||
if mapping["status"] not in ("active", "disabled"):
|
||||
return False
|
||||
if mapping["effective_from"] and on_date < mapping["effective_from"]:
|
||||
return False
|
||||
if mapping["effective_to"] and on_date > mapping["effective_to"]:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def direction_allowed(mapping: sqlite3.Row, row_direction: str) -> bool:
|
||||
"""True when the personal account may represent the company for this flow.
|
||||
|
||||
``allowed_direction`` describes the transfer from the represented company's
|
||||
perspective: when the personal account appears as the counterparty of an
|
||||
outgoing row, the represented company is receiving (incoming); for an
|
||||
incoming row the represented company is paying out (outgoing).
|
||||
"""
|
||||
counterparty_flow = "incoming" if row_direction == "outgoing" else "outgoing"
|
||||
allowed = mapping["allowed_direction"]
|
||||
return allowed == "both" or allowed == counterparty_flow
|
||||
|
||||
|
||||
def mapping_payload(mapping: sqlite3.Row, *, full: bool) -> dict[str, object]:
|
||||
"""Serialize a mapping; company-facing views only ever see masked numbers."""
|
||||
payload: dict[str, object] = {
|
||||
"id": mapping["id"],
|
||||
"account_name": mapping["account_name"],
|
||||
"represented_company_id": mapping["represented_company_id"],
|
||||
"allowed_direction": mapping["allowed_direction"],
|
||||
"status": mapping["status"],
|
||||
"effective_from": mapping["effective_from"],
|
||||
"effective_to": mapping["effective_to"],
|
||||
"reviewed_at": mapping["reviewed_at"],
|
||||
"review_reason": mapping["review_reason"],
|
||||
"created_at": mapping["created_at"],
|
||||
}
|
||||
if "company_name" in mapping.keys():
|
||||
payload["company_name"] = mapping["company_name"]
|
||||
if full:
|
||||
payload["account_number"] = mapping["account_number"]
|
||||
else:
|
||||
payload["account_number_masked"] = mask_account_number(mapping["account_number"])
|
||||
return payload
|
||||
@@ -1,187 +0,0 @@
|
||||
"""Optional portal identity bridge. Financial role and company scope stay local."""
|
||||
import hashlib
|
||||
import html
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
from http.cookies import SimpleCookie
|
||||
from urllib.parse import urlencode, urlsplit
|
||||
from urllib.request import Request, build_opener, HTTPRedirectHandler
|
||||
|
||||
from . import auth
|
||||
from .db import connect
|
||||
|
||||
|
||||
def enabled():
|
||||
return os.environ.get("PORTAL_SSO_ENABLED") == "1"
|
||||
|
||||
|
||||
def base_url(name):
|
||||
value = os.environ.get(name, "").rstrip("/")
|
||||
url = urlsplit(value)
|
||||
if (url.scheme not in {"http", "https"} or not url.hostname or url.username
|
||||
or url.password or url.path or url.query or url.fragment):
|
||||
raise ValueError("Portal URL unavailable")
|
||||
return value
|
||||
|
||||
|
||||
class NoRedirect(HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
def call(operation, payload):
|
||||
secret = os.environ.get("PORTAL_SSO_SECRET", "")
|
||||
if len(secret) < 32:
|
||||
raise ValueError("Portal secret unavailable")
|
||||
req = Request(base_url("PORTAL_INTERNAL_URL") + "/api/sso/apps/finance/" + operation,
|
||||
data=json.dumps(payload).encode(),
|
||||
headers={"Content-Type": "application/json", "Authorization": "Bearer " + secret})
|
||||
with build_opener(NoRedirect).open(req, timeout=5) as response:
|
||||
body = response.read(32769)
|
||||
if len(body) > 32768:
|
||||
raise ValueError("Invalid portal response")
|
||||
return json.loads(body)
|
||||
|
||||
|
||||
def migrate(connection):
|
||||
connection.executescript("""
|
||||
CREATE TABLE IF NOT EXISTS portal_identity (
|
||||
uid INTEGER PRIMARY KEY REFERENCES users(id), empid TEXT UNIQUE NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS portal_sessions (
|
||||
token_hash TEXT PRIMARY KEY, handle TEXT NOT NULL,
|
||||
empid TEXT NOT NULL, uid INTEGER NOT NULL REFERENCES users(id)
|
||||
);
|
||||
""")
|
||||
|
||||
|
||||
def resolve(connection, token):
|
||||
user = auth.resolve_session(connection, token)
|
||||
if user is None:
|
||||
return None
|
||||
row = connection.execute("SELECT * FROM portal_sessions WHERE token_hash=?",
|
||||
(hashlib.sha256(token.encode()).hexdigest(),)).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
result = call("introspect", {"session_handle": row["handle"]})
|
||||
who = result.get("identity") or {}
|
||||
if (not result.get("active") or who.get("local_uid") != user["id"]
|
||||
or who.get("empid") != row["empid"] or row["uid"] != user["id"]):
|
||||
auth.revoke_session(connection, token)
|
||||
return None
|
||||
return user
|
||||
|
||||
|
||||
class PortalMixin:
|
||||
def _portal_error(self, status, message):
|
||||
home = html.escape(base_url("PORTAL_PUBLIC_URL"), quote=True)
|
||||
body = ('<!doctype html><html lang="zh-CN"><meta charset="utf-8">'
|
||||
'<title>金牛财务往来</title><p>' + html.escape(message)
|
||||
+ '</p><a href="' + home + '">返回统一门户</a></html>').encode()
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("Referrer-Policy", "no-referrer")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def _portal_redirect(self, target, cookie=None):
|
||||
self.send_response(303)
|
||||
self.send_header("Location", target)
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("Referrer-Policy", "no-referrer")
|
||||
if cookie:
|
||||
self.send_header("Set-Cookie", cookie)
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
|
||||
def _portal_callback(self, query, db_path):
|
||||
if not enabled():
|
||||
self.send_error(404)
|
||||
return
|
||||
secure = "; Secure" if os.environ.get("PORTAL_COOKIE_SECURE") == "1" else ""
|
||||
flags = "; HttpOnly; SameSite=Lax; Path=/portal-sso" + secure
|
||||
if "ticket" not in query:
|
||||
verifier = secrets.token_hex(32)
|
||||
theme = "night" if query.get("theme") == ["night"] else "day"
|
||||
self._portal_redirect(base_url("PORTAL_PUBLIC_URL") + "/api/sso/apps/finance/authorize?"
|
||||
+ urlencode({"challenge": hashlib.sha256(verifier.encode()).hexdigest()}),
|
||||
"cw_portal_proof=" + verifier + "." + theme + flags + "; Max-Age=120")
|
||||
return
|
||||
cookie = SimpleCookie()
|
||||
cookie.load(self.headers.get("Cookie", ""))
|
||||
proof = cookie.get("cw_portal_proof")
|
||||
parts = proof.value.split(".") if proof else []
|
||||
ticket = query["ticket"][0]
|
||||
if len(parts) != 2 or not re.fullmatch("[a-f0-9]{64}", parts[0]) or not re.fullmatch("[a-f0-9]{64}", ticket):
|
||||
self._portal_error(401, "登录请求已失效,请从统一门户重新进入。")
|
||||
return
|
||||
connection = connect(db_path)
|
||||
try:
|
||||
result = call("exchange", {"ticket": ticket, "verifier": parts[0]})
|
||||
who = result["identity"]
|
||||
handle = result["session_handle"]
|
||||
if not re.fullmatch("[a-f0-9]{64}", handle) or not re.fullmatch("[a-f0-9-]{36}", who["empid"]):
|
||||
raise ValueError("Invalid identity")
|
||||
user = connection.execute("SELECT * FROM users WHERE id=? AND status='active'", (who["local_uid"],)).fetchone()
|
||||
if user is None:
|
||||
raise ValueError("Local account unavailable")
|
||||
with connection:
|
||||
connection.execute("INSERT OR IGNORE INTO portal_identity(uid,empid) VALUES (?,?)", (user["id"], who["empid"]))
|
||||
binding = connection.execute("SELECT empid FROM portal_identity WHERE uid=?", (user["id"],)).fetchone()
|
||||
if not binding or binding["empid"] != who["empid"]:
|
||||
raise ValueError("Binding mismatch")
|
||||
token = auth.create_session(connection, user["id"])
|
||||
with connection:
|
||||
connection.execute("INSERT INTO portal_sessions(token_hash,handle,empid,uid) VALUES (?,?,?,?)",
|
||||
(hashlib.sha256(token.encode()).hexdigest(), handle, who["empid"], user["id"]))
|
||||
connection.execute("DELETE FROM portal_sessions WHERE token_hash NOT IN (SELECT token_hash FROM sessions)")
|
||||
auth.audit(connection, "portal_login", actor=user, detail=who["empid"])
|
||||
target = "/admin.html" if user["role"] == "admin" else "/company.html"
|
||||
theme = "night" if parts[1] == "night" else "day"
|
||||
self.send_response(303)
|
||||
self._set_session_cookie(token)
|
||||
self.send_header("Set-Cookie", "cw_portal_proof=" + flags + "; Max-Age=0")
|
||||
self.send_header("Location", target + "?theme=" + theme)
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("Referrer-Policy", "no-referrer")
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
except Exception:
|
||||
self._portal_error(401, "无法进入,请检查门户授权、账号绑定及子系统可用状态。")
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def send_head(self):
|
||||
# Serve the existing two business surfaces, with account controls hidden
|
||||
# before first paint. The API gate separately blocks native credentials.
|
||||
path = urlsplit(self.path).path
|
||||
if enabled() and path in {"/admin.html", "/company.html"}:
|
||||
from pathlib import Path
|
||||
body = Path(self.directory, path[1:]).read_text(encoding="utf-8")
|
||||
home = base_url("PORTAL_PUBLIC_URL")
|
||||
script = '<script>window.PORTAL_HOME=' + json.dumps(home) + ';</script>'
|
||||
style = '<style>.account-box,.portal-native-account{display:none!important}</style>'
|
||||
style += '<link rel="stylesheet" href="/portal-return.css?v=20260924">'
|
||||
style += '<style>.topbar.jn-portal-bar{position:sticky;padding-top:10px;padding-bottom:10px}</style>'
|
||||
body = body.replace('</head>', script + style + '</head>')
|
||||
portal_link = '<a class="jn-portal-return" data-return-portal title="返回统一门户" aria-label="返回统一门户" href="' + html.escape(home, quote=True) + '"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m3 10 9-7 9 7v10a1 1 0 0 1-1 1h-5v-7H9v7H4a1 1 0 0 1-1-1Z"/></svg><span>统一门户</span></a>'
|
||||
body = body.replace('<div class="topbar">', '<div class="topbar jn-portal-bar">' + portal_link)
|
||||
data = body.encode("utf-8")
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
return io.BytesIO(data)
|
||||
return super().send_head()
|
||||
|
||||
def log_message(self, fmt, *args):
|
||||
# Callback URLs contain short-lived credentials. Never write them to logs.
|
||||
if urlsplit(self.path).path == "/portal-sso":
|
||||
return
|
||||
super().log_message(fmt, *args)
|
||||
File diff suppressed because it is too large
Load Diff
+13
-59
@@ -10,23 +10,6 @@ class UnsupportedWorkbookError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class CorruptWorkbookError(RuntimeError):
|
||||
"""The file cannot be opened as a valid Excel workbook.
|
||||
|
||||
Raised for corrupt/truncated files, wrong signatures and files that
|
||||
exceed the resource limits. The message is user-safe: it never contains
|
||||
server-side paths or the content-addressed storage filename.
|
||||
"""
|
||||
|
||||
|
||||
# Workbook resource guards (defense against decompression bombs and
|
||||
# accidentally giant exports). Bank statements are small; these bounds are
|
||||
# generous enough for real exports while keeping memory bounded.
|
||||
MAX_SHEETS = 50
|
||||
MAX_ROWS_PER_SHEET = 200_000
|
||||
MAX_COLS_PER_SHEET = 64
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RawSheet:
|
||||
name: str
|
||||
@@ -35,18 +18,11 @@ class RawSheet:
|
||||
|
||||
def read_workbook(path: Path) -> tuple[RawSheet, ...]:
|
||||
suffix = path.suffix.lower()
|
||||
try:
|
||||
if suffix == ".xlsx":
|
||||
return _read_xlsx(path)
|
||||
if suffix == ".xls":
|
||||
return _read_xls(path)
|
||||
raise UnsupportedWorkbookError(f"Unsupported workbook type: {suffix}")
|
||||
except (UnsupportedWorkbookError, CorruptWorkbookError):
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise CorruptWorkbookError(
|
||||
"文件无法读取,可能已损坏或不是有效的 Excel 文件。"
|
||||
) from exc
|
||||
if suffix == ".xlsx":
|
||||
return _read_xlsx(path)
|
||||
if suffix == ".xls":
|
||||
return _read_xls(path)
|
||||
raise UnsupportedWorkbookError(f"Unsupported workbook type: {suffix}")
|
||||
|
||||
|
||||
def _read_xlsx(path: Path) -> tuple[RawSheet, ...]:
|
||||
@@ -59,24 +35,13 @@ def _read_xlsx(path: Path) -> tuple[RawSheet, ...]:
|
||||
|
||||
workbook = load_workbook(path, read_only=True, data_only=True)
|
||||
try:
|
||||
sheets: list[RawSheet] = []
|
||||
for worksheet in workbook.worksheets:
|
||||
rows: list[tuple[Any, ...]] = []
|
||||
for row_index, row in enumerate(worksheet.iter_rows(values_only=True)):
|
||||
if row_index >= MAX_ROWS_PER_SHEET:
|
||||
raise CorruptWorkbookError(
|
||||
f"工作表「{worksheet.title}」超过 {MAX_ROWS_PER_SHEET} 行,已拒绝读取。"
|
||||
)
|
||||
values = tuple(row)
|
||||
if len(values) > MAX_COLS_PER_SHEET:
|
||||
raise CorruptWorkbookError(
|
||||
f"工作表「{worksheet.title}」列数超过 {MAX_COLS_PER_SHEET},已拒绝读取。"
|
||||
)
|
||||
rows.append(values)
|
||||
sheets.append(RawSheet(name=worksheet.title, rows=tuple(rows)))
|
||||
if len(sheets) > MAX_SHEETS:
|
||||
raise CorruptWorkbookError(f"工作簿工作表数量超过 {MAX_SHEETS} 个,已拒绝读取。")
|
||||
return tuple(sheets)
|
||||
return tuple(
|
||||
RawSheet(
|
||||
name=worksheet.title,
|
||||
rows=tuple(tuple(row) for row in worksheet.iter_rows(values_only=True)),
|
||||
)
|
||||
for worksheet in workbook.worksheets
|
||||
)
|
||||
finally:
|
||||
workbook.close()
|
||||
|
||||
@@ -92,19 +57,8 @@ def _read_xls(path: Path) -> tuple[RawSheet, ...]:
|
||||
workbook = xlrd.open_workbook(path, on_demand=True)
|
||||
sheets: list[RawSheet] = []
|
||||
try:
|
||||
names = workbook.sheet_names()
|
||||
if len(names) > MAX_SHEETS:
|
||||
raise CorruptWorkbookError(f"工作簿工作表数量超过 {MAX_SHEETS} 个,已拒绝读取。")
|
||||
for sheet_name in names:
|
||||
for sheet_name in workbook.sheet_names():
|
||||
worksheet = workbook.sheet_by_name(sheet_name)
|
||||
if worksheet.nrows > MAX_ROWS_PER_SHEET:
|
||||
raise CorruptWorkbookError(
|
||||
f"工作表「{sheet_name}」超过 {MAX_ROWS_PER_SHEET} 行,已拒绝读取。"
|
||||
)
|
||||
if worksheet.ncols > MAX_COLS_PER_SHEET:
|
||||
raise CorruptWorkbookError(
|
||||
f"工作表「{sheet_name}」列数超过 {MAX_COLS_PER_SHEET},已拒绝读取。"
|
||||
)
|
||||
rows: list[tuple[Any, ...]] = []
|
||||
for row_index in range(worksheet.nrows):
|
||||
values: list[Any] = []
|
||||
|
||||
@@ -1,757 +0,0 @@
|
||||
"""Read-only reminder rule engine and delivery helpers.
|
||||
|
||||
Scans existing tables to surface pending items; delivery writes append-only
|
||||
``reminders`` / ``reminder_events`` rows without touching bank or business data.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
import json
|
||||
import sqlite3
|
||||
from typing import Any
|
||||
import uuid
|
||||
|
||||
from bank_importer import auth
|
||||
from bank_importer.db import utc_now
|
||||
|
||||
RULE_UNSUBMITTED = "unsubmitted"
|
||||
RULE_GAP = "gap"
|
||||
RULE_PENDING = "pending_review"
|
||||
RULE_MANUAL = "manual"
|
||||
|
||||
SETTING_MONTHLY_START_DAY = "monthly_start_day"
|
||||
SETTING_GAP_DAYS = "gap_days"
|
||||
SETTING_SCAN_TIME = "scan_time"
|
||||
|
||||
DEFAULT_SETTINGS: dict[str, str] = {
|
||||
SETTING_MONTHLY_START_DAY: "5",
|
||||
SETTING_GAP_DAYS: "5",
|
||||
SETTING_SCAN_TIME: "08:00",
|
||||
}
|
||||
|
||||
RULE_LABELS = {
|
||||
RULE_UNSUBMITTED: "流水未提交",
|
||||
RULE_GAP: "流水断档",
|
||||
RULE_PENDING: "待确认/待审核",
|
||||
}
|
||||
|
||||
ACTION_LINKS = {
|
||||
RULE_UNSUBMITTED: "upload",
|
||||
RULE_GAP: "flows",
|
||||
RULE_PENDING: "reconcile",
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ScanFinding:
|
||||
company_id: int
|
||||
company_name: str
|
||||
rule_key: str
|
||||
dedupe_key: str
|
||||
rule_params: dict[str, Any]
|
||||
title: str
|
||||
content: str
|
||||
reason: str
|
||||
days_open: int
|
||||
deadline: str | None
|
||||
action_link: str
|
||||
existing_reminder_id: int | None
|
||||
send_count: int
|
||||
|
||||
|
||||
def _today() -> date:
|
||||
return datetime.now(timezone.utc).date()
|
||||
|
||||
|
||||
def get_settings(connection: sqlite3.Connection) -> dict[str, str]:
|
||||
rows = connection.execute("SELECT key, value FROM reminder_settings").fetchall()
|
||||
settings = dict(DEFAULT_SETTINGS)
|
||||
for row in rows:
|
||||
settings[row["key"]] = row["value"]
|
||||
return settings
|
||||
|
||||
|
||||
def _valid_scan_time(value: str) -> bool:
|
||||
parts = value.strip().split(":")
|
||||
if len(parts) != 2 or not parts[0].isdigit() or not parts[1].isdigit():
|
||||
return False
|
||||
if len(parts[1]) != 2:
|
||||
return False
|
||||
hour, minute = int(parts[0]), int(parts[1])
|
||||
return 0 <= hour <= 23 and 0 <= minute <= 59
|
||||
|
||||
|
||||
def validate_setting(key: str, value: str) -> str:
|
||||
raw = str(value).strip()
|
||||
if key == SETTING_MONTHLY_START_DAY:
|
||||
try:
|
||||
day = int(raw)
|
||||
except ValueError as exc:
|
||||
raise ValueError("每月起始日须为 1 到 28 的整数。") from exc
|
||||
if day < 1 or day > 28:
|
||||
raise ValueError("每月起始日须为 1 到 28 的整数。")
|
||||
return str(day)
|
||||
if key == SETTING_GAP_DAYS:
|
||||
try:
|
||||
days = int(raw)
|
||||
except ValueError as exc:
|
||||
raise ValueError("断档天数须为大于等于 1 的整数。") from exc
|
||||
if days < 1:
|
||||
raise ValueError("断档天数须为大于等于 1 的整数。")
|
||||
return str(days)
|
||||
if key == SETTING_SCAN_TIME:
|
||||
if not _valid_scan_time(raw):
|
||||
raise ValueError("扫描时间须为合法的 HH:MM。")
|
||||
hour, minute = raw.split(":")
|
||||
return f"{int(hour):02d}:{minute}"
|
||||
raise ValueError(f"unknown setting: {key}")
|
||||
|
||||
|
||||
def update_settings(connection: sqlite3.Connection, updates: dict[str, str]) -> dict[str, str]:
|
||||
allowed = set(DEFAULT_SETTINGS)
|
||||
cleaned: dict[str, str] = {}
|
||||
for key, value in updates.items():
|
||||
if key not in allowed:
|
||||
raise ValueError(f"unknown setting: {key}")
|
||||
cleaned[key] = validate_setting(key, value)
|
||||
now = utc_now()
|
||||
with connection:
|
||||
for key, value in cleaned.items():
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO reminder_settings (key, value, updated_at)
|
||||
VALUES (?, ?, ?)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at
|
||||
""",
|
||||
(key, value, now),
|
||||
)
|
||||
return get_settings(connection)
|
||||
|
||||
|
||||
def _setting_int(settings: dict[str, str], key: str) -> int:
|
||||
try:
|
||||
return int(validate_setting(key, settings.get(key, DEFAULT_SETTINGS[key])))
|
||||
except (TypeError, ValueError):
|
||||
return int(DEFAULT_SETTINGS[key])
|
||||
|
||||
|
||||
def _month_period(day: date | None = None) -> str:
|
||||
ref = day or _today()
|
||||
return f"{ref.year:04d}-{ref.month:02d}"
|
||||
|
||||
|
||||
def _parse_date(value: str | None) -> date | None:
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
return date.fromisoformat(value[:10])
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _days_between(start: date, end: date) -> int:
|
||||
return max(0, (end - start).days)
|
||||
|
||||
|
||||
def _duration_pill_class(days: int) -> str:
|
||||
if days >= 7:
|
||||
return "pill-danger"
|
||||
if days >= 3:
|
||||
return "pill-warn"
|
||||
return "pill-muted"
|
||||
|
||||
|
||||
def _existing_reminder(connection: sqlite3.Connection, dedupe_key: str) -> sqlite3.Row | None:
|
||||
return connection.execute(
|
||||
"""
|
||||
SELECT id, send_count, status, last_sent_at
|
||||
FROM reminders
|
||||
WHERE dedupe_key = ? AND status != 'resolved'
|
||||
""",
|
||||
(dedupe_key,),
|
||||
).fetchone()
|
||||
|
||||
|
||||
def _company_has_month_batch(connection: sqlite3.Connection, company_id: int, period: str) -> bool:
|
||||
year, month = period.split("-")
|
||||
prefix = f"{year}-{month}"
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT 1
|
||||
FROM import_batches b
|
||||
JOIN sheet_batches s ON s.import_batch_id = b.id
|
||||
WHERE b.company_id = ?
|
||||
AND (
|
||||
substr(s.period_start, 1, 7) = ?
|
||||
OR substr(s.period_end, 1, 7) = ?
|
||||
OR (s.period_start <= ? || '-31' AND s.period_end >= ? || '-01')
|
||||
)
|
||||
LIMIT 1
|
||||
""",
|
||||
(company_id, prefix, prefix, prefix, prefix),
|
||||
).fetchone()
|
||||
return row is not None
|
||||
|
||||
|
||||
def _latest_batch_end(connection: sqlite3.Connection, company_id: int) -> date | None:
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT MAX(s.period_end) AS latest_end
|
||||
FROM import_batches b
|
||||
JOIN sheet_batches s ON s.import_batch_id = b.id
|
||||
WHERE b.company_id = ?
|
||||
""",
|
||||
(company_id,),
|
||||
).fetchone()
|
||||
return _parse_date(row["latest_end"] if row else None)
|
||||
|
||||
|
||||
def _pending_review_count(connection: sqlite3.Connection, company_id: int) -> int:
|
||||
match_count = connection.execute(
|
||||
"""
|
||||
SELECT COUNT(DISTINCT e.id)
|
||||
FROM canonical_transfer_events e
|
||||
JOIN current_transfer_decisions c ON c.event_id = e.id
|
||||
JOIN transfer_match_decisions d ON d.id = c.decision_id
|
||||
JOIN transfer_decision_participants payer ON payer.decision_id = d.id AND payer.role = 'payer'
|
||||
JOIN transfer_decision_participants payee ON payee.decision_id = d.id AND payee.role = 'payee'
|
||||
WHERE e.lifecycle = 'active'
|
||||
AND d.classification IN ('unresolved', 'needs_review')
|
||||
AND (payer.company_id = ? OR payee.company_id = ?)
|
||||
""",
|
||||
(company_id, company_id),
|
||||
).fetchone()[0]
|
||||
sheet_count = connection.execute(
|
||||
"""
|
||||
SELECT COUNT(*)
|
||||
FROM sheet_reviews r
|
||||
JOIN import_batches b ON b.id = r.import_batch_id
|
||||
WHERE b.company_id = ?
|
||||
AND r.outcome = 'parsed'
|
||||
AND r.review_status = 'pending'
|
||||
""",
|
||||
(company_id,),
|
||||
).fetchone()[0]
|
||||
account_count = connection.execute(
|
||||
"""
|
||||
SELECT COUNT(*) FROM bank_accounts
|
||||
WHERE company_id = ? AND status = 'pending'
|
||||
""",
|
||||
(company_id,),
|
||||
).fetchone()[0]
|
||||
return int(match_count) + int(sheet_count) + int(account_count)
|
||||
|
||||
|
||||
def _active_companies(connection: sqlite3.Connection) -> list[sqlite3.Row]:
|
||||
return connection.execute(
|
||||
"""
|
||||
SELECT id, name FROM companies
|
||||
WHERE COALESCE(status, 'active') != 'disabled'
|
||||
ORDER BY name
|
||||
"""
|
||||
).fetchall()
|
||||
|
||||
|
||||
def scan_findings(connection: sqlite3.Connection) -> list[ScanFinding]:
|
||||
settings = get_settings(connection)
|
||||
today = _today()
|
||||
period = _month_period(today)
|
||||
monthly_start = _setting_int(settings, SETTING_MONTHLY_START_DAY)
|
||||
gap_days = _setting_int(settings, SETTING_GAP_DAYS)
|
||||
findings: list[ScanFinding] = []
|
||||
|
||||
for company in _active_companies(connection):
|
||||
company_id = int(company["id"])
|
||||
company_name = company["name"]
|
||||
|
||||
if today.day >= monthly_start and not _company_has_month_batch(connection, company_id, period):
|
||||
dedupe_key = f"{company_id}:{RULE_UNSUBMITTED}:{period}"
|
||||
days_open = _days_between(date(today.year, today.month, monthly_start), today)
|
||||
existing = _existing_reminder(connection, dedupe_key)
|
||||
findings.append(
|
||||
ScanFinding(
|
||||
company_id=company_id,
|
||||
company_name=company_name,
|
||||
rule_key=RULE_UNSUBMITTED,
|
||||
dedupe_key=dedupe_key,
|
||||
rule_params={"period": period},
|
||||
title=f"{company_name} · {today.month} 月流水未提交",
|
||||
content=(
|
||||
f"贵公司 {period} 银行流水尚未提交。"
|
||||
f"请于截止日前完成全部账户流水上传。"
|
||||
),
|
||||
reason=f"应交 {today.month:02d}-{monthly_start:02d} · 已逾期 {days_open} 天",
|
||||
days_open=days_open,
|
||||
deadline=None,
|
||||
action_link=ACTION_LINKS[RULE_UNSUBMITTED],
|
||||
existing_reminder_id=int(existing["id"]) if existing else None,
|
||||
send_count=int(existing["send_count"]) if existing else 0,
|
||||
)
|
||||
)
|
||||
|
||||
latest_end = _latest_batch_end(connection, company_id)
|
||||
if latest_end is not None:
|
||||
gap = _days_between(latest_end, today)
|
||||
if gap > gap_days:
|
||||
dedupe_key = f"{company_id}:{RULE_GAP}:{latest_end.isoformat()}"
|
||||
existing = _existing_reminder(connection, dedupe_key)
|
||||
findings.append(
|
||||
ScanFinding(
|
||||
company_id=company_id,
|
||||
company_name=company_name,
|
||||
rule_key=RULE_GAP,
|
||||
dedupe_key=dedupe_key,
|
||||
rule_params={"latest_end": latest_end.isoformat(), "gap_days": gap},
|
||||
title=f"{company_name} · 流水断档 {gap} 天",
|
||||
content=(
|
||||
f"最近流水截止日为 {latest_end.isoformat()},"
|
||||
f"已连续 {gap} 天无新数据,请补传断档期间银行流水。"
|
||||
),
|
||||
reason=f"最近截止 {latest_end.strftime('%m-%d')} · 断档 {gap} 天",
|
||||
days_open=gap,
|
||||
deadline=None,
|
||||
action_link=ACTION_LINKS[RULE_GAP],
|
||||
existing_reminder_id=int(existing["id"]) if existing else None,
|
||||
send_count=int(existing["send_count"]) if existing else 0,
|
||||
)
|
||||
)
|
||||
|
||||
pending_count = _pending_review_count(connection, company_id)
|
||||
if pending_count > 0:
|
||||
dedupe_key = f"{company_id}:{RULE_PENDING}:active"
|
||||
existing = _existing_reminder(connection, dedupe_key)
|
||||
first_seen = _parse_date(existing["last_sent_at"][:10] if existing and existing["last_sent_at"] else None)
|
||||
days_open = _days_between(first_seen, today) if first_seen else 0
|
||||
findings.append(
|
||||
ScanFinding(
|
||||
company_id=company_id,
|
||||
company_name=company_name,
|
||||
rule_key=RULE_PENDING,
|
||||
dedupe_key=dedupe_key,
|
||||
rule_params={"pending_count": pending_count},
|
||||
title=f"{company_name} · {pending_count} 项待确认/待审核",
|
||||
content=(
|
||||
f"贵公司当前有 {pending_count} 项往来确认、流水审核或账户登记待处理,"
|
||||
f"请尽快完成确认以免影响结账。"
|
||||
),
|
||||
reason=f"待处理 {pending_count} 项",
|
||||
days_open=days_open,
|
||||
deadline=None,
|
||||
action_link=ACTION_LINKS[RULE_PENDING],
|
||||
existing_reminder_id=int(existing["id"]) if existing else None,
|
||||
send_count=int(existing["send_count"]) if existing else 0,
|
||||
)
|
||||
)
|
||||
|
||||
findings.sort(key=lambda item: item.days_open, reverse=True)
|
||||
return findings
|
||||
|
||||
|
||||
def run_scan(
|
||||
connection: sqlite3.Connection,
|
||||
*,
|
||||
actor: sqlite3.Row | None = None,
|
||||
ip: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
findings = scan_findings(connection)
|
||||
counts = {
|
||||
RULE_UNSUBMITTED: sum(1 for f in findings if f.rule_key == RULE_UNSUBMITTED),
|
||||
RULE_GAP: sum(1 for f in findings if f.rule_key == RULE_GAP),
|
||||
RULE_PENDING: sum(1 for f in findings if f.rule_key == RULE_PENDING),
|
||||
}
|
||||
auth.audit(
|
||||
connection,
|
||||
"reminder_scan",
|
||||
actor=actor,
|
||||
detail=json.dumps({"total": len(findings), "by_rule": counts}, ensure_ascii=False),
|
||||
ip=ip,
|
||||
)
|
||||
return {"findings": findings, "counts": counts}
|
||||
|
||||
|
||||
def finding_to_dict(finding: ScanFinding) -> dict[str, Any]:
|
||||
return {
|
||||
"company_id": finding.company_id,
|
||||
"company_name": finding.company_name,
|
||||
"rule_key": finding.rule_key,
|
||||
"rule_label": RULE_LABELS.get(finding.rule_key, finding.rule_key),
|
||||
"dedupe_key": finding.dedupe_key,
|
||||
"rule_params": finding.rule_params,
|
||||
"title": finding.title,
|
||||
"content": finding.content,
|
||||
"reason": finding.reason,
|
||||
"days_open": finding.days_open,
|
||||
"duration_pill": _duration_pill_class(finding.days_open),
|
||||
"deadline": finding.deadline,
|
||||
"action_link": finding.action_link,
|
||||
"existing_reminder_id": finding.existing_reminder_id,
|
||||
"send_count": finding.send_count,
|
||||
}
|
||||
|
||||
|
||||
def _append_event(
|
||||
connection: sqlite3.Connection,
|
||||
reminder_id: int,
|
||||
event_type: str,
|
||||
actor: str,
|
||||
detail: str | None = None,
|
||||
) -> None:
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO reminder_events (reminder_id, event_type, actor, detail, created_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
""",
|
||||
(reminder_id, event_type, actor, detail, utc_now()),
|
||||
)
|
||||
|
||||
|
||||
def _actor_label(actor: sqlite3.Row | None) -> str:
|
||||
if actor is None:
|
||||
return "system"
|
||||
return str(actor["id"])
|
||||
|
||||
|
||||
def deliver_finding(
|
||||
connection: sqlite3.Connection,
|
||||
dedupe_key: str,
|
||||
*,
|
||||
actor: sqlite3.Row | None = None,
|
||||
ip: str | None = None,
|
||||
) -> int | None:
|
||||
findings = {item.dedupe_key: item for item in scan_findings(connection)}
|
||||
finding = findings.get(dedupe_key)
|
||||
if finding is None:
|
||||
return None
|
||||
return _deliver(connection, finding, actor=actor, ip=ip)
|
||||
|
||||
|
||||
def _deliver(
|
||||
connection: sqlite3.Connection,
|
||||
finding: ScanFinding,
|
||||
*,
|
||||
actor: sqlite3.Row | None = None,
|
||||
ip: str | None = None,
|
||||
) -> int:
|
||||
now = utc_now()
|
||||
actor_ref = _actor_label(actor)
|
||||
existing = connection.execute(
|
||||
"SELECT id, send_count, status FROM reminders WHERE dedupe_key = ?",
|
||||
(finding.dedupe_key,),
|
||||
).fetchone()
|
||||
|
||||
with connection:
|
||||
if existing is not None:
|
||||
reminder_id = int(existing["id"])
|
||||
send_count = int(existing["send_count"]) + 1
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE reminders
|
||||
SET send_count = ?, last_sent_at = ?, status = 'open',
|
||||
title = ?, content = ?, rule_params = ?, action_link = ?
|
||||
WHERE id = ?
|
||||
""",
|
||||
(
|
||||
send_count,
|
||||
now,
|
||||
finding.title,
|
||||
finding.content,
|
||||
json.dumps(finding.rule_params, ensure_ascii=False),
|
||||
finding.action_link,
|
||||
reminder_id,
|
||||
),
|
||||
)
|
||||
event_type = "sent" if existing["status"] == "resolved" else (
|
||||
"escalated" if send_count > 1 else "sent"
|
||||
)
|
||||
_append_event(
|
||||
connection,
|
||||
reminder_id,
|
||||
event_type,
|
||||
actor_ref,
|
||||
f"第 {send_count} 次催办",
|
||||
)
|
||||
else:
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO reminders (
|
||||
company_id, rule_key, dedupe_key, rule_params, title, content,
|
||||
deadline, source, status, send_count, first_sent_at, last_sent_at,
|
||||
created_by, created_at, action_link
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, 'auto', 'open', 1, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
finding.company_id,
|
||||
finding.rule_key,
|
||||
finding.dedupe_key,
|
||||
json.dumps(finding.rule_params, ensure_ascii=False),
|
||||
finding.title,
|
||||
finding.content,
|
||||
finding.deadline,
|
||||
now,
|
||||
now,
|
||||
actor_ref,
|
||||
now,
|
||||
finding.action_link,
|
||||
),
|
||||
)
|
||||
reminder_id = int(connection.execute("SELECT last_insert_rowid()").fetchone()[0])
|
||||
_append_event(connection, reminder_id, "sent", actor_ref, finding.reason)
|
||||
|
||||
auth.audit(
|
||||
connection,
|
||||
"reminder_send",
|
||||
actor=actor,
|
||||
target=f"reminder:{reminder_id}",
|
||||
detail=finding.dedupe_key,
|
||||
ip=ip,
|
||||
)
|
||||
return reminder_id
|
||||
|
||||
|
||||
def deliver_many(
|
||||
connection: sqlite3.Connection,
|
||||
dedupe_keys: list[str],
|
||||
*,
|
||||
actor: sqlite3.Row | None = None,
|
||||
ip: str | None = None,
|
||||
) -> list[int]:
|
||||
sent: list[int] = []
|
||||
for key in dedupe_keys:
|
||||
try:
|
||||
reminder_id = deliver_finding(connection, key, actor=actor, ip=ip)
|
||||
except Exception:
|
||||
continue
|
||||
if reminder_id is not None:
|
||||
sent.append(reminder_id)
|
||||
return sent
|
||||
|
||||
|
||||
def send_manual(
|
||||
connection: sqlite3.Connection,
|
||||
*,
|
||||
company_id: int,
|
||||
display_type: str,
|
||||
content: str,
|
||||
deadline: str | None,
|
||||
actor: sqlite3.Row,
|
||||
ip: str | None = None,
|
||||
) -> int:
|
||||
company = connection.execute(
|
||||
"SELECT name FROM companies WHERE id = ?", (company_id,)
|
||||
).fetchone()
|
||||
if company is None:
|
||||
raise ValueError("company not found")
|
||||
now = utc_now()
|
||||
dedupe_key = f"{company_id}:{RULE_MANUAL}:{uuid.uuid4().hex}"
|
||||
title = f"{company['name']} · {display_type}"
|
||||
with connection:
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO reminders (
|
||||
company_id, rule_key, dedupe_key, rule_params, title, content,
|
||||
deadline, source, status, send_count, first_sent_at, last_sent_at,
|
||||
created_by, created_at, action_link
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, 'manual', 'open', 1, ?, ?, ?, ?, NULL)
|
||||
""",
|
||||
(
|
||||
company_id,
|
||||
RULE_MANUAL,
|
||||
dedupe_key,
|
||||
json.dumps({"display_type": display_type}, ensure_ascii=False),
|
||||
title,
|
||||
content,
|
||||
deadline,
|
||||
now,
|
||||
now,
|
||||
str(actor["id"]),
|
||||
now,
|
||||
),
|
||||
)
|
||||
reminder_id = int(connection.execute("SELECT last_insert_rowid()").fetchone()[0])
|
||||
_append_event(connection, reminder_id, "sent", str(actor["id"]), display_type)
|
||||
auth.audit(
|
||||
connection,
|
||||
"reminder_send_manual",
|
||||
actor=actor,
|
||||
target=f"reminder:{reminder_id}",
|
||||
detail=display_type,
|
||||
ip=ip,
|
||||
)
|
||||
return reminder_id
|
||||
|
||||
|
||||
def resend_reminder(
|
||||
connection: sqlite3.Connection,
|
||||
reminder_id: int,
|
||||
*,
|
||||
actor: sqlite3.Row,
|
||||
ip: str | None = None,
|
||||
) -> None:
|
||||
row = connection.execute(
|
||||
"SELECT id, send_count, status FROM reminders WHERE id = ?", (reminder_id,)
|
||||
).fetchone()
|
||||
if row is None or row["status"] == "resolved":
|
||||
raise ValueError("reminder not available")
|
||||
now = utc_now()
|
||||
send_count = int(row["send_count"]) + 1
|
||||
with connection:
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE reminders
|
||||
SET send_count = ?, last_sent_at = ?, status = 'open'
|
||||
WHERE id = ?
|
||||
""",
|
||||
(send_count, now, reminder_id),
|
||||
)
|
||||
_append_event(
|
||||
connection,
|
||||
reminder_id,
|
||||
"escalated",
|
||||
str(actor["id"]),
|
||||
f"第 {send_count} 次催办",
|
||||
)
|
||||
auth.audit(
|
||||
connection,
|
||||
"reminder_resend",
|
||||
actor=actor,
|
||||
target=f"reminder:{reminder_id}",
|
||||
ip=ip,
|
||||
)
|
||||
|
||||
|
||||
def _reminder_row_to_dict(row: sqlite3.Row, *, company_name: str | None = None) -> dict[str, Any]:
|
||||
params = json.loads(row["rule_params"]) if row["rule_params"] else {}
|
||||
rule_key = row["rule_key"]
|
||||
display_type = params.get("display_type") if rule_key == RULE_MANUAL else RULE_LABELS.get(rule_key, rule_key)
|
||||
status = row["status"]
|
||||
status_ui = {"open": "unread", "acknowledged": "doing", "resolved": "done"}[status]
|
||||
return {
|
||||
"id": row["id"],
|
||||
"company_id": row["company_id"],
|
||||
"company_name": company_name or row["company_name"],
|
||||
"rule_key": rule_key,
|
||||
"display_type": display_type,
|
||||
"title": row["title"],
|
||||
"content": row["content"],
|
||||
"deadline": row["deadline"],
|
||||
"source": row["source"],
|
||||
"status": status,
|
||||
"status_ui": status_ui,
|
||||
"send_count": row["send_count"],
|
||||
"first_sent_at": row["first_sent_at"],
|
||||
"last_sent_at": row["last_sent_at"],
|
||||
"created_by": row["created_by"],
|
||||
"created_at": row["created_at"],
|
||||
"action_link": row["action_link"],
|
||||
"rule_params": params,
|
||||
}
|
||||
|
||||
|
||||
def list_admin_reminders(
|
||||
connection: sqlite3.Connection,
|
||||
*,
|
||||
source: str | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
conditions = ["r.send_count > 0"]
|
||||
params: list[Any] = []
|
||||
if source in {"auto", "manual"}:
|
||||
conditions.append("r.source = ?")
|
||||
params.append(source)
|
||||
where = " AND ".join(conditions)
|
||||
rows = connection.execute(
|
||||
f"""
|
||||
SELECT r.*, c.name AS company_name
|
||||
FROM reminders r
|
||||
JOIN companies c ON c.id = r.company_id
|
||||
WHERE {where}
|
||||
ORDER BY r.last_sent_at DESC, r.id DESC
|
||||
""",
|
||||
params,
|
||||
).fetchall()
|
||||
return [_reminder_row_to_dict(row) for row in rows]
|
||||
|
||||
|
||||
def list_company_reminders(connection: sqlite3.Connection, company_id: int) -> list[dict[str, Any]]:
|
||||
rows = connection.execute(
|
||||
"""
|
||||
SELECT r.*, c.name AS company_name
|
||||
FROM reminders r
|
||||
JOIN companies c ON c.id = r.company_id
|
||||
WHERE r.company_id = ? AND r.send_count > 0
|
||||
ORDER BY
|
||||
CASE r.status WHEN 'open' THEN 0 WHEN 'acknowledged' THEN 1 ELSE 2 END,
|
||||
r.last_sent_at DESC
|
||||
""",
|
||||
(company_id,),
|
||||
).fetchall()
|
||||
return [_reminder_row_to_dict(row) for row in rows]
|
||||
|
||||
|
||||
def get_reminder_detail(connection: sqlite3.Connection, reminder_id: int) -> dict[str, Any] | None:
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT r.*, c.name AS company_name
|
||||
FROM reminders r
|
||||
JOIN companies c ON c.id = r.company_id
|
||||
WHERE r.id = ?
|
||||
""",
|
||||
(reminder_id,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
events = connection.execute(
|
||||
"""
|
||||
SELECT event_type, actor, detail, created_at
|
||||
FROM reminder_events
|
||||
WHERE reminder_id = ?
|
||||
ORDER BY id
|
||||
""",
|
||||
(reminder_id,),
|
||||
).fetchall()
|
||||
payload = _reminder_row_to_dict(row)
|
||||
payload["events"] = [dict(item) for item in events]
|
||||
return payload
|
||||
|
||||
|
||||
def update_reminder_status(
|
||||
connection: sqlite3.Connection,
|
||||
reminder_id: int,
|
||||
new_status: str,
|
||||
*,
|
||||
company_id: int | None = None,
|
||||
actor: sqlite3.Row | None = None,
|
||||
) -> bool:
|
||||
if new_status not in {"acknowledged", "resolved"}:
|
||||
raise ValueError("invalid status")
|
||||
row = connection.execute(
|
||||
"SELECT id, company_id, status FROM reminders WHERE id = ?",
|
||||
(reminder_id,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return False
|
||||
if company_id is not None and int(row["company_id"]) != company_id:
|
||||
return False
|
||||
if row["status"] == "resolved":
|
||||
return False
|
||||
event_type = "acknowledged" if new_status == "acknowledged" else "resolved"
|
||||
actor_ref = _actor_label(actor)
|
||||
with connection:
|
||||
connection.execute(
|
||||
"UPDATE reminders SET status = ? WHERE id = ?",
|
||||
(new_status, reminder_id),
|
||||
)
|
||||
_append_event(connection, reminder_id, event_type, actor_ref, None)
|
||||
return True
|
||||
|
||||
|
||||
def company_unread_count(connection: sqlite3.Connection, company_id: int) -> int:
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT COUNT(*) AS n FROM reminders
|
||||
WHERE company_id = ? AND status = 'open' AND send_count > 0
|
||||
""",
|
||||
(company_id,),
|
||||
).fetchone()
|
||||
return int(row["n"])
|
||||
@@ -1,133 +0,0 @@
|
||||
"""System settings.
|
||||
|
||||
System-wide parameters (closing day, global start date, auto-reminder toggle
|
||||
and lead days) are persisted in ``system_settings`` with an append-only
|
||||
``system_setting_changes`` trail. The auto-reminder engine itself lives in
|
||||
``reminders.py`` (HEL-195); this module only owns the settings store.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sqlite3
|
||||
from datetime import datetime
|
||||
|
||||
from .db import utc_now, transaction
|
||||
|
||||
|
||||
# Defaults are applied when a key is absent; the value type is always string.
|
||||
DEFAULT_SETTINGS: dict[str, str] = {
|
||||
"closing_day": "5",
|
||||
"start_date": "2026-01-01",
|
||||
"auto_remind": "1",
|
||||
"remind_days": "3",
|
||||
}
|
||||
|
||||
_SETTING_KEYS = frozenset({"closing_day", "start_date", "auto_remind", "remind_days"})
|
||||
|
||||
_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
||||
|
||||
|
||||
def _valid_date(value: str) -> bool:
|
||||
if not _DATE_RE.match(value):
|
||||
return False
|
||||
try:
|
||||
datetime.strptime(value, "%Y-%m-%d")
|
||||
except ValueError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def get_settings(connection: sqlite3.Connection) -> dict[str, str]:
|
||||
settings = dict(DEFAULT_SETTINGS)
|
||||
rows = connection.execute(
|
||||
"SELECT key, value FROM system_settings"
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
settings[row["key"]] = row["value"]
|
||||
return settings
|
||||
|
||||
|
||||
def validate_settings(values: dict[str, object]) -> tuple[dict[str, str], str | None]:
|
||||
"""Return ``(cleaned, error)``; ``cleaned`` holds only recognized keys."""
|
||||
cleaned: dict[str, str] = {}
|
||||
if "closing_day" in values:
|
||||
raw = str(values["closing_day"]).strip()
|
||||
try:
|
||||
day = int(raw)
|
||||
except ValueError:
|
||||
return cleaned, "每月结账日须为 1-28 之间的整数。"
|
||||
if day < 1 or day > 28:
|
||||
return cleaned, "每月结账日须为 1-28 之间的整数。"
|
||||
cleaned["closing_day"] = str(day)
|
||||
if "start_date" in values:
|
||||
raw = str(values["start_date"]).strip()
|
||||
if not _valid_date(raw):
|
||||
return cleaned, "全局起算日须为有效日期(YYYY-MM-DD)。"
|
||||
cleaned["start_date"] = raw
|
||||
if "auto_remind" in values:
|
||||
raw = str(values["auto_remind"]).strip()
|
||||
if raw not in {"0", "1"}:
|
||||
return cleaned, "自动提醒开关须为 0 或 1。"
|
||||
cleaned["auto_remind"] = raw
|
||||
if "remind_days" in values:
|
||||
raw = str(values["remind_days"]).strip()
|
||||
try:
|
||||
days = int(raw)
|
||||
except ValueError:
|
||||
return cleaned, "提前提醒天数须为不小于 1 的整数。"
|
||||
if days < 1 or days > 30:
|
||||
return cleaned, "提前提醒天数须为 1-30 之间的整数。"
|
||||
cleaned["remind_days"] = str(days)
|
||||
return cleaned, None
|
||||
|
||||
|
||||
def update_settings(
|
||||
connection: sqlite3.Connection,
|
||||
values: dict[str, object],
|
||||
actor: sqlite3.Row,
|
||||
) -> dict[str, str]:
|
||||
cleaned, error = validate_settings(values)
|
||||
if error is not None:
|
||||
raise ValueError(error)
|
||||
if not cleaned:
|
||||
raise ValueError("没有需要保存的设置项。")
|
||||
current = get_settings(connection)
|
||||
with transaction(connection):
|
||||
for key, new_value in cleaned.items():
|
||||
old_value = current.get(key)
|
||||
if old_value == new_value:
|
||||
continue
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO system_settings (key, value, updated_by, updated_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(key) DO UPDATE SET
|
||||
value = excluded.value,
|
||||
updated_by = excluded.updated_by,
|
||||
updated_at = excluded.updated_at
|
||||
""",
|
||||
(key, new_value, actor["id"], utc_now()),
|
||||
)
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO system_setting_changes (
|
||||
key, before_value, after_value,
|
||||
actor_user_id, actor_username, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
key,
|
||||
old_value,
|
||||
new_value,
|
||||
actor["id"],
|
||||
actor["username"],
|
||||
utc_now(),
|
||||
),
|
||||
)
|
||||
return get_settings(connection)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
# Reminder pending items
|
||||
# ----------------------------------------------------------------------
|
||||
@@ -1,398 +0,0 @@
|
||||
"""Statutory subject suggestions, mirror mapping and confirmation (B-44).
|
||||
|
||||
Subjects are stored from one participating company's perspective and the
|
||||
other side is the fixed mirror (应收<->应付, 其他应收<->其他应付), so the two
|
||||
companies can never record conflicting subjects. Bank summary/purpose text
|
||||
only ever produces a *suggestion*; nothing here confirms a subject
|
||||
automatically. Confirmation is an explicit administrator decision carrying
|
||||
``expected_revision`` and an idempotency key.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import sqlite3
|
||||
|
||||
from . import matching
|
||||
|
||||
SUBJECTS = ("receivable", "payable", "other_receivable", "other_payable")
|
||||
SUBJECT_RULE_VERSION = "subject-suggest-draft-v1"
|
||||
|
||||
MIRROR = {
|
||||
"receivable": "payable",
|
||||
"payable": "receivable",
|
||||
"other_receivable": "other_payable",
|
||||
"other_payable": "other_receivable",
|
||||
}
|
||||
|
||||
SUBJECT_LABELS = {
|
||||
"receivable": "应收",
|
||||
"payable": "应付",
|
||||
"other_receivable": "其他应收",
|
||||
"other_payable": "其他应付",
|
||||
}
|
||||
|
||||
_FULL_WIDTH = str.maketrans(
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
"abcdefghijklmnopqrstuvwxyz0123456789",
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
"abcdefghijklmnopqrstuvwxyz0123456789",
|
||||
)
|
||||
|
||||
# Draft v1 dictionary. Exact-keyword matching only; every hit is a suggestion
|
||||
# and never an automatic posting. Trade-type keywords are deliberately absent
|
||||
# until the group supplies an approved dictionary (they always go to review).
|
||||
_LOAN_LIKE = ("借款", "往来款", "资金往来", "临时借款", "资金调拨", "代垫", "垫付")
|
||||
_REPAY_LIKE = ("还款", "归还借款", "归还往来款")
|
||||
|
||||
|
||||
class SubjectConflictError(ValueError):
|
||||
"""A stale revision or idempotency conflict (mapped to HTTP 409)."""
|
||||
|
||||
|
||||
class SubjectInputError(ValueError):
|
||||
"""Invalid input for a subject decision (mapped to HTTP 400/422)."""
|
||||
|
||||
|
||||
def mirror_subject(subject_code: str) -> str:
|
||||
if subject_code not in MIRROR:
|
||||
raise SubjectInputError("科目必须是应收/应付/其他应收/其他应付之一。")
|
||||
return MIRROR[subject_code]
|
||||
|
||||
|
||||
def subject_label(subject_code: str) -> str:
|
||||
return SUBJECT_LABELS.get(subject_code, subject_code)
|
||||
|
||||
|
||||
def _normalize(text: object) -> str:
|
||||
return re.sub(r"[\s\ufeff]+", "", str(text or "").translate(_FULL_WIDTH))
|
||||
|
||||
|
||||
def _bank_evidence_texts(connection: sqlite3.Connection, ledger_event_id: int) -> dict[str, str]:
|
||||
"""Purpose/summary text of the B-43 source rows behind a bank event."""
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT bs.bank_event_id FROM ledger_event_bank_sources bs
|
||||
WHERE bs.ledger_event_id = ?
|
||||
""",
|
||||
(ledger_event_id,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return {"purpose": "", "summary": ""}
|
||||
decision = matching._current_decision_for_event(connection, row["bank_event_id"])
|
||||
if decision is None:
|
||||
return {"purpose": "", "summary": ""}
|
||||
observations = matching._decision_observations(connection, decision["id"])
|
||||
texts: dict[str, list[str]] = {"purpose": [], "summary": []}
|
||||
for observation in observations:
|
||||
source = connection.execute(
|
||||
"SELECT purpose, summary FROM source_rows WHERE id = ?",
|
||||
(observation["source_row_id"],),
|
||||
).fetchone()
|
||||
if source is None:
|
||||
continue
|
||||
for key in ("purpose", "summary"):
|
||||
value = str(source[key] or "").strip()
|
||||
if value:
|
||||
texts[key].append(value)
|
||||
return {
|
||||
"purpose": " ".join(texts["purpose"]),
|
||||
"summary": " ".join(texts["summary"]),
|
||||
}
|
||||
|
||||
|
||||
def compute_suggestions(
|
||||
connection: sqlite3.Connection, ledger_event_id: int
|
||||
) -> list[dict[str, object]]:
|
||||
""" Deterministic draft suggestions for a pending event, never confirmation.
|
||||
|
||||
Purpose rules take precedence over summary rules. When both loan-like and
|
||||
repay-like keywords match, both candidates are returned as a conflict for
|
||||
the reviewer; no priority breaks the tie.
|
||||
"""
|
||||
from .ledger_events import current_revision
|
||||
|
||||
revision = current_revision(connection, ledger_event_id)
|
||||
if revision is None or revision["state"] != "pending_subject":
|
||||
return []
|
||||
texts = _bank_evidence_texts(connection, ledger_event_id)
|
||||
purpose = _normalize(texts["purpose"])
|
||||
summary = _normalize(texts["summary"])
|
||||
search = purpose or summary
|
||||
payer = revision["payer_company_id"]
|
||||
payee = revision["payee_company_id"]
|
||||
|
||||
loan_hit = next((word for word in _LOAN_LIKE if word in search), None)
|
||||
repay_hit = next((word for word in _REPAY_LIKE if word in search), None)
|
||||
|
||||
suggestions: list[dict[str, object]] = []
|
||||
if loan_hit:
|
||||
suggestions.append(
|
||||
{
|
||||
"suggested_perspective_company_id": payer,
|
||||
"suggested_subject_code": "other_receivable",
|
||||
"reason": f"匹配建议词典「{loan_hit}」,建议付款方其他应收",
|
||||
"rule_version": SUBJECT_RULE_VERSION,
|
||||
"evidence": {
|
||||
"keyword": loan_hit,
|
||||
"matched_text": search,
|
||||
"approved": False,
|
||||
},
|
||||
}
|
||||
)
|
||||
if repay_hit:
|
||||
suggestions.append(
|
||||
{
|
||||
"suggested_perspective_company_id": payee,
|
||||
"suggested_subject_code": "other_receivable",
|
||||
"reason": f"匹配建议词典「{repay_hit}」,建议收款方其他应收",
|
||||
"rule_version": SUBJECT_RULE_VERSION,
|
||||
"evidence": {
|
||||
"keyword": repay_hit,
|
||||
"matched_text": search,
|
||||
"approved": False,
|
||||
},
|
||||
}
|
||||
)
|
||||
return suggestions
|
||||
|
||||
|
||||
def store_suggestions(connection: sqlite3.Connection, ledger_event_id: int) -> int:
|
||||
"""Compute and append suggestions for a pending event. Returns count stored."""
|
||||
from .ledger_events import current_revision
|
||||
|
||||
revision = current_revision(connection, ledger_event_id)
|
||||
if revision is None or revision["state"] != "pending_subject":
|
||||
return 0
|
||||
stored = 0
|
||||
for suggestion in compute_suggestions(connection, ledger_event_id):
|
||||
from .db import utc_now
|
||||
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO ledger_subject_suggestions (
|
||||
ledger_event_id, source_revision_id,
|
||||
suggested_perspective_company_id, suggested_subject_code,
|
||||
rule_version, evidence_json, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
ledger_event_id, revision["id"],
|
||||
suggestion["suggested_perspective_company_id"],
|
||||
suggestion["suggested_subject_code"],
|
||||
suggestion["rule_version"],
|
||||
json.dumps(suggestion.get("evidence", {}), ensure_ascii=False),
|
||||
utc_now(),
|
||||
),
|
||||
)
|
||||
stored += 1
|
||||
return stored
|
||||
|
||||
|
||||
def confirm_subject(
|
||||
connection: sqlite3.Connection,
|
||||
ledger_event_id: int,
|
||||
*,
|
||||
perspective_company_id: int,
|
||||
subject_code: str,
|
||||
reason: str,
|
||||
expected_revision: int | None,
|
||||
request_key: str | None,
|
||||
actor: sqlite3.Row,
|
||||
) -> dict[str, object]:
|
||||
"""Confirm a subject, turning a pending event into a confirmed revision."""
|
||||
from .ledger_events import append_revision, current_revision
|
||||
|
||||
reason = (reason or "").strip()
|
||||
if not reason:
|
||||
raise SubjectInputError("必须填写科目确认依据。")
|
||||
if subject_code not in SUBJECTS:
|
||||
raise SubjectInputError("科目必须是应收/应付/其他应收/其他应付之一。")
|
||||
|
||||
began = False
|
||||
if not connection.in_transaction:
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
began = True
|
||||
try:
|
||||
if request_key:
|
||||
existing = connection.execute(
|
||||
"""
|
||||
SELECT * FROM ledger_event_revisions
|
||||
WHERE ledger_event_id = ? AND idempotency_key = ?
|
||||
ORDER BY id LIMIT 1
|
||||
""",
|
||||
(ledger_event_id, request_key),
|
||||
).fetchone()
|
||||
if existing is not None:
|
||||
if began:
|
||||
connection.commit()
|
||||
return _revision_payload(connection, existing)
|
||||
|
||||
current = current_revision(connection, ledger_event_id)
|
||||
if current is None:
|
||||
raise SubjectConflictError("该事件不存在或没有当前修订。")
|
||||
if current["state"] != "pending_subject":
|
||||
raise SubjectConflictError("只有待确认科目的事件可以确认科目。")
|
||||
# ``expected_revision`` may be the revision row id (what the API/UI
|
||||
# sends as ``ledger_revision_id``) or the per-event sequence number;
|
||||
# both identify the exact revision the client saw.
|
||||
if expected_revision is not None and int(expected_revision) not in (
|
||||
current["id"], current["revision"],
|
||||
):
|
||||
raise SubjectConflictError("事件已发生变更,请刷新后重试。")
|
||||
participants = {current["payer_company_id"], current["payee_company_id"]}
|
||||
if perspective_company_id not in participants:
|
||||
raise SubjectInputError("视角公司必须是事件参与方。")
|
||||
|
||||
revision_id = append_revision(
|
||||
connection,
|
||||
ledger_event_id,
|
||||
state="confirmed",
|
||||
effective_at=current["effective_at"],
|
||||
amount=current["amount"],
|
||||
currency=current["currency"],
|
||||
payer_company_id=current["payer_company_id"],
|
||||
payee_company_id=current["payee_company_id"],
|
||||
perspective_company_id=perspective_company_id,
|
||||
subject_code=subject_code,
|
||||
source_kind=current["source_kind"],
|
||||
source_revision_token=current["source_revision_token"],
|
||||
posting_kind=current["posting_kind"],
|
||||
reverses_ledger_event_id=current["reverses_ledger_event_id"],
|
||||
adjusts_ledger_event_id=current["adjusts_ledger_event_id"],
|
||||
rule_version=current["rule_version"] or SUBJECT_RULE_VERSION,
|
||||
evidence_json=current["evidence_json"],
|
||||
idempotency_key=request_key,
|
||||
actor=actor,
|
||||
reason=reason,
|
||||
supersedes_revision_id=current["id"],
|
||||
)
|
||||
row = connection.execute(
|
||||
"SELECT * FROM ledger_event_revisions WHERE id = ?", (revision_id,)
|
||||
).fetchone()
|
||||
except Exception:
|
||||
if began:
|
||||
connection.rollback()
|
||||
raise
|
||||
else:
|
||||
if began:
|
||||
connection.commit()
|
||||
return _revision_payload(connection, row)
|
||||
|
||||
|
||||
def park_subject(
|
||||
connection: sqlite3.Connection,
|
||||
ledger_event_id: int,
|
||||
*,
|
||||
disposition: str,
|
||||
reason: str,
|
||||
expected_revision: int | None,
|
||||
request_key: str | None,
|
||||
actor: sqlite3.Row,
|
||||
) -> dict[str, object]:
|
||||
"""Record 退回/转异常 without confirming a statutory subject.
|
||||
|
||||
The event stays ``pending_subject`` so it never enters confirmed balances.
|
||||
``exception`` is hidden from the active review queue; ``return`` remains
|
||||
visible so the company can supplement materials.
|
||||
"""
|
||||
from .ledger_events import append_revision, current_revision
|
||||
|
||||
if disposition not in ("return", "exception"):
|
||||
raise SubjectInputError("科目处理只能是退回或转异常。")
|
||||
reason = (reason or "").strip()
|
||||
if not reason:
|
||||
raise SubjectInputError("必须填写处理依据。")
|
||||
|
||||
began = False
|
||||
if not connection.in_transaction:
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
began = True
|
||||
try:
|
||||
if request_key:
|
||||
existing = connection.execute(
|
||||
"""
|
||||
SELECT * FROM ledger_event_revisions
|
||||
WHERE ledger_event_id = ? AND idempotency_key = ?
|
||||
ORDER BY id LIMIT 1
|
||||
""",
|
||||
(ledger_event_id, request_key),
|
||||
).fetchone()
|
||||
if existing is not None:
|
||||
if began:
|
||||
connection.commit()
|
||||
return _revision_payload(connection, existing)
|
||||
|
||||
current = current_revision(connection, ledger_event_id)
|
||||
if current is None:
|
||||
raise SubjectConflictError("该事件不存在或没有当前修订。")
|
||||
if current["state"] != "pending_subject":
|
||||
raise SubjectConflictError("只有待确认科目的事件可以退回或转异常。")
|
||||
if expected_revision is not None and int(expected_revision) not in (
|
||||
current["id"], current["revision"],
|
||||
):
|
||||
raise SubjectConflictError("事件已发生变更,请刷新后重试。")
|
||||
evidence = json.loads(current["evidence_json"] or "{}") if current["evidence_json"] else {}
|
||||
evidence["admin_disposition"] = disposition
|
||||
revision_id = append_revision(
|
||||
connection,
|
||||
ledger_event_id,
|
||||
state="pending_subject",
|
||||
effective_at=current["effective_at"],
|
||||
amount=current["amount"],
|
||||
currency=current["currency"],
|
||||
payer_company_id=current["payer_company_id"],
|
||||
payee_company_id=current["payee_company_id"],
|
||||
perspective_company_id=None,
|
||||
subject_code=None,
|
||||
source_kind=current["source_kind"],
|
||||
source_revision_token=current["source_revision_token"],
|
||||
posting_kind=current["posting_kind"],
|
||||
reverses_ledger_event_id=current["reverses_ledger_event_id"],
|
||||
adjusts_ledger_event_id=current["adjusts_ledger_event_id"],
|
||||
rule_version=current["rule_version"] or SUBJECT_RULE_VERSION,
|
||||
evidence_json=json.dumps(evidence, ensure_ascii=False),
|
||||
idempotency_key=request_key,
|
||||
actor=actor,
|
||||
reason=reason,
|
||||
supersedes_revision_id=current["id"],
|
||||
)
|
||||
row = connection.execute(
|
||||
"SELECT * FROM ledger_event_revisions WHERE id = ?", (revision_id,)
|
||||
).fetchone()
|
||||
except Exception:
|
||||
if began:
|
||||
connection.rollback()
|
||||
raise
|
||||
else:
|
||||
if began:
|
||||
connection.commit()
|
||||
return _revision_payload(connection, row)
|
||||
|
||||
|
||||
def _revision_payload(connection: sqlite3.Connection, revision: sqlite3.Row) -> dict[str, object]:
|
||||
company = connection.execute(
|
||||
"SELECT name FROM companies WHERE id = ?", (revision["perspective_company_id"],)
|
||||
).fetchone()
|
||||
return {
|
||||
"ledger_event_id": revision["ledger_event_id"],
|
||||
"revision_id": revision["id"],
|
||||
"revision": revision["revision"],
|
||||
"state": revision["state"],
|
||||
"effective_at": revision["effective_at"],
|
||||
"amount": revision["amount"],
|
||||
"currency": revision["currency"],
|
||||
"payer_company_id": revision["payer_company_id"],
|
||||
"payee_company_id": revision["payee_company_id"],
|
||||
"perspective_company_id": revision["perspective_company_id"],
|
||||
"perspective_company_name": company["name"] if company else None,
|
||||
"subject_code": revision["subject_code"],
|
||||
"subject_label": subject_label(revision["subject_code"])
|
||||
if revision["subject_code"]
|
||||
else None,
|
||||
"posting_kind": revision["posting_kind"],
|
||||
"source_kind": revision["source_kind"],
|
||||
"reason": revision["reason"],
|
||||
"created_at": revision["created_at"],
|
||||
}
|
||||
@@ -10,7 +10,6 @@ class BankTemplate:
|
||||
bank_name: str
|
||||
columns: dict[str, tuple[str, ...]]
|
||||
required: tuple[str, ...]
|
||||
version: int = 1
|
||||
|
||||
|
||||
def normalize_header(value: object) -> str:
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
param(
|
||||
[ValidateRange(1, 65535)]
|
||||
[int]$Port = 4173
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
docker compose version | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Docker Compose is not available."
|
||||
}
|
||||
|
||||
docker info | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Docker is not running."
|
||||
}
|
||||
|
||||
$env:APP_PORT = $Port.ToString()
|
||||
docker compose up --build --detach
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Docker Compose failed to start the application."
|
||||
}
|
||||
|
||||
$containerId = (docker compose ps --quiet app).Trim()
|
||||
if (-not $containerId) {
|
||||
throw "The application container was not created."
|
||||
}
|
||||
|
||||
for ($attempt = 0; $attempt -lt 60; $attempt++) {
|
||||
$state = docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' $containerId
|
||||
if ($state -eq "healthy") {
|
||||
Write-Host "Application is ready: http://localhost:$Port"
|
||||
exit 0
|
||||
}
|
||||
if ($state -eq "unhealthy" -or $state -eq "exited" -or $state -eq "dead") {
|
||||
docker compose logs --no-color --tail 100 app
|
||||
throw "The application container entered state: $state"
|
||||
}
|
||||
Start-Sleep -Seconds 1
|
||||
}
|
||||
|
||||
docker compose logs --no-color --tail 100 app
|
||||
throw "Timed out waiting for the application health check."
|
||||
Executable
+48
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env sh
|
||||
set -eu
|
||||
|
||||
APP_PORT="${APP_PORT:-${1:-4173}}"
|
||||
export APP_PORT
|
||||
|
||||
case "$APP_PORT" in
|
||||
''|*[!0-9]*)
|
||||
echo "APP_PORT must be an integer between 1 and 65535." >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
if [ "$APP_PORT" -lt 1 ] || [ "$APP_PORT" -gt 65535 ]; then
|
||||
echo "APP_PORT must be an integer between 1 and 65535." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
docker compose version >/dev/null
|
||||
docker info >/dev/null
|
||||
docker compose up --build --detach
|
||||
|
||||
container_id="$(docker compose ps --quiet app)"
|
||||
if [ -z "$container_id" ]; then
|
||||
echo "The application container was not created." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
attempt=0
|
||||
while [ "$attempt" -lt 60 ]; do
|
||||
state="$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' "$container_id")"
|
||||
case "$state" in
|
||||
healthy)
|
||||
echo "Application is ready: http://localhost:${APP_PORT}"
|
||||
exit 0
|
||||
;;
|
||||
unhealthy|exited|dead)
|
||||
docker compose logs --no-color --tail 100 app
|
||||
echo "The application container entered state: $state" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
attempt=$((attempt + 1))
|
||||
sleep 1
|
||||
done
|
||||
|
||||
docker compose logs --no-color --tail 100 app
|
||||
echo "Timed out waiting for the application health check." >&2
|
||||
exit 1
|
||||
@@ -1,179 +0,0 @@
|
||||
"""Shared fixtures for B-44 ledger / manual / position tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import hashlib
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from bank_importer import auth, matching, master_data
|
||||
from bank_importer.db import connect, migrate, utc_now
|
||||
|
||||
|
||||
class LedgerBase(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self._source_file_sequence = 0
|
||||
self.temp_dir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp_dir.cleanup)
|
||||
root = Path(self.temp_dir.name)
|
||||
self.db_path = root / "app.db"
|
||||
self.connection = connect(self.db_path)
|
||||
self.addCleanup(self.connection.close)
|
||||
migrate(self.connection)
|
||||
self.admin = self._admin()
|
||||
self.company_a = self._company("甲公司")
|
||||
self.company_b = self._company("乙公司")
|
||||
self.company_c = self._company("丙公司")
|
||||
self.account_a = self._approved_account(self.company_a, "6222000000000001")
|
||||
self.account_b = self._approved_account(self.company_b, "6222000000000002")
|
||||
|
||||
def _admin(self):
|
||||
auth.create_user(self.connection, "admin-u", "AdminPass123", "admin")
|
||||
return self.connection.execute(
|
||||
"SELECT * FROM users WHERE username = 'admin-u'"
|
||||
).fetchone()
|
||||
|
||||
def _company(self, name: str) -> int:
|
||||
with self.connection:
|
||||
cursor = self.connection.execute(
|
||||
"INSERT INTO companies (name, created_at, updated_at) VALUES (?, ?, ?)",
|
||||
(name, utc_now(), utc_now()),
|
||||
)
|
||||
return int(cursor.lastrowid)
|
||||
|
||||
def _approved_account(self, company_id: int, number: str, start: str = "2026-01-01"):
|
||||
account = master_data.submit_bank_account(
|
||||
self.connection, company_id=company_id, bank_name="中信银行",
|
||||
account_type="基本户", account_number=number, start_date=start,
|
||||
actor=None,
|
||||
)
|
||||
return master_data.review_bank_account(
|
||||
self.connection, account["id"], "approve", None, self.admin,
|
||||
effective_from=start,
|
||||
)
|
||||
|
||||
def add_row(
|
||||
self,
|
||||
company_id: int,
|
||||
*,
|
||||
own_account: str,
|
||||
cp_account: str | None = None,
|
||||
income: str = "0",
|
||||
expense: str = "0",
|
||||
at: str = "2026-01-05T10:00:00",
|
||||
currency: str = "CNY",
|
||||
reference: str | None = None,
|
||||
summary: str | None = None,
|
||||
purpose: str | None = None,
|
||||
) -> int:
|
||||
self._source_file_sequence = getattr(self, "_source_file_sequence", 0) + 1
|
||||
fixture_hash = hashlib.sha256(f"ledger-fixture-{self._source_file_sequence}".encode()).hexdigest()
|
||||
with self.connection:
|
||||
cursor = self.connection.execute(
|
||||
"""
|
||||
INSERT INTO source_files (sha256, original_filename, size_bytes, storage_path, created_at)
|
||||
VALUES (?, '测试.xlsx', 1, 'data/files/测试.xlsx', ?)
|
||||
""",
|
||||
(fixture_hash, utc_now()),
|
||||
)
|
||||
source_file_id = int(cursor.lastrowid)
|
||||
cursor = self.connection.execute(
|
||||
"""
|
||||
INSERT INTO import_batches (source_file_id, status, company_id, created_at, updated_at)
|
||||
VALUES (?, 'parsing', ?, ?, ?)
|
||||
""",
|
||||
(source_file_id, company_id, utc_now(), utc_now()),
|
||||
)
|
||||
batch_id = int(cursor.lastrowid)
|
||||
cursor = self.connection.execute(
|
||||
"""
|
||||
INSERT INTO sheet_batches (
|
||||
import_batch_id, sheet_name, bank_name, template_id, template_version,
|
||||
header_row, own_account, own_name, period_start, period_end,
|
||||
transaction_count, warnings, created_at
|
||||
) VALUES (?, '流水', '测试银行', 'test-v1', 1, 1, NULL, NULL, NULL, NULL, 1, '[]', ?)
|
||||
""",
|
||||
(batch_id, utc_now()),
|
||||
)
|
||||
sheet_batch_id = int(cursor.lastrowid)
|
||||
self.connection.execute(
|
||||
"""
|
||||
INSERT INTO sheet_reviews (
|
||||
import_batch_id, sheet_name, outcome, sheet_batch_id,
|
||||
review_status, created_at
|
||||
) VALUES (?, '流水', 'parsed', ?, 'confirmed', ?)
|
||||
""",
|
||||
(batch_id, sheet_batch_id, utc_now()),
|
||||
)
|
||||
cursor = self.connection.execute(
|
||||
"""
|
||||
INSERT INTO source_rows (
|
||||
sheet_batch_id, source_row, transaction_at, income, expense, balance,
|
||||
own_account, own_name, counterparty_account, counterparty_name,
|
||||
counterparty_bank, summary, purpose, reference, currency, created_at
|
||||
) VALUES (?, 1, ?, ?, ?, NULL, ?, '测试', ?, '对方', NULL, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
sheet_batch_id, at, income, expense, own_account,
|
||||
cp_account, summary, purpose, reference, currency, utc_now(),
|
||||
),
|
||||
)
|
||||
return int(cursor.lastrowid)
|
||||
|
||||
def pair(
|
||||
self,
|
||||
payer: int,
|
||||
payee: int,
|
||||
amount: str,
|
||||
at: str = "2026-01-05T10:00:00",
|
||||
*,
|
||||
currency: str = "CNY",
|
||||
summary: str = "借款",
|
||||
purpose: str = "往来款",
|
||||
) -> tuple[int, int]:
|
||||
"""Create a mirrored A/B pair and reconcile into an eligible event."""
|
||||
payer_account = self._account_of(payer)
|
||||
payee_account = self._account_of(payee)
|
||||
row_payer = self.add_row(
|
||||
payer, own_account=payer_account, cp_account=payee_account,
|
||||
expense=amount, at=at, currency=currency, summary=summary, purpose=purpose,
|
||||
)
|
||||
row_payee = self.add_row(
|
||||
payee, own_account=payee_account, cp_account=payer_account,
|
||||
income=amount, at=at.replace("T10:", "T11:"), currency=currency,
|
||||
summary=summary, purpose=purpose,
|
||||
)
|
||||
matching.reconcile_rows(self.connection, [row_payer, row_payee])
|
||||
return row_payer, row_payee
|
||||
|
||||
def _account_of(self, company_id: int) -> str:
|
||||
if company_id == self.company_a:
|
||||
return self.account_a["account_number"]
|
||||
if company_id == self.company_b:
|
||||
return self.account_b["account_number"]
|
||||
return "6222000000000005"
|
||||
|
||||
def eligible(self) -> list[sqlite3.Row]:
|
||||
return matching.eligible_intercompany_events(self.connection)
|
||||
|
||||
def ledger_events(self) -> list[sqlite3.Row]:
|
||||
return self.connection.execute(
|
||||
"SELECT * FROM ledger_events ORDER BY id"
|
||||
).fetchall()
|
||||
|
||||
def current(self, ledger_event_id: int) -> sqlite3.Row | None:
|
||||
return self.connection.execute(
|
||||
"""
|
||||
SELECT r.* FROM current_ledger_event_revisions c
|
||||
JOIN ledger_event_revisions r ON r.id = c.revision_id
|
||||
WHERE c.ledger_event_id = ?
|
||||
""",
|
||||
(ledger_event_id,),
|
||||
).fetchone()
|
||||
|
||||
def position_events(self) -> list[sqlite3.Row]:
|
||||
return self.connection.execute(
|
||||
"SELECT * FROM eligible_position_events ORDER BY ledger_event_id"
|
||||
).fetchall()
|
||||
@@ -1,287 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import hashlib
|
||||
import sqlite3
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
from bank_importer import auth
|
||||
from bank_importer.db import connect, migrate, utc_now
|
||||
|
||||
|
||||
class AuthTestCase(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.connection = connect(":memory:")
|
||||
self.addCleanup(self.connection.close)
|
||||
migrate(self.connection)
|
||||
now = utc_now()
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
"INSERT INTO companies (name, created_at, updated_at) VALUES ('甲公司', ?, ?)",
|
||||
(now, now),
|
||||
)
|
||||
self.company_id = int(self.connection.execute("SELECT id FROM companies").fetchone()["id"])
|
||||
|
||||
def create_company_user(self, username: str = "cashier-a", password: str = "Init1234") -> int:
|
||||
return auth.create_user(
|
||||
self.connection, username, password, "company", company_id=self.company_id
|
||||
)
|
||||
|
||||
def create_admin(self, username: str = "group-admin", password: str = "Admin1234") -> int:
|
||||
return auth.create_user(self.connection, username, password, "admin")
|
||||
|
||||
|
||||
class PasswordHashTests(unittest.TestCase):
|
||||
def test_hash_format_and_verify_roundtrip(self) -> None:
|
||||
stored = auth.hash_password("Secret123")
|
||||
scheme, iterations, salt_hex, hash_hex = stored.split("$")
|
||||
self.assertEqual("pbkdf2_sha256", scheme)
|
||||
self.assertEqual(str(auth.PBKDF2_ITERATIONS), iterations)
|
||||
self.assertEqual(32, len(salt_hex))
|
||||
self.assertEqual(64, len(hash_hex))
|
||||
self.assertTrue(auth.verify_password("Secret123", stored))
|
||||
|
||||
def test_wrong_password_is_rejected(self) -> None:
|
||||
stored = auth.hash_password("Secret123")
|
||||
self.assertFalse(auth.verify_password("Secret124", stored))
|
||||
|
||||
def test_same_password_gets_different_salts(self) -> None:
|
||||
self.assertNotEqual(auth.hash_password("Secret123"), auth.hash_password("Secret123"))
|
||||
|
||||
def test_malformed_stored_hash_is_rejected(self) -> None:
|
||||
for stored in ("", "plain", "pbkdf2_sha256$x$y$z", "bcrypt$1$aa$bb"):
|
||||
with self.subTest(stored=stored):
|
||||
self.assertFalse(auth.verify_password("Secret123", stored))
|
||||
|
||||
|
||||
class PasswordPolicyTests(unittest.TestCase):
|
||||
def test_policy_rejects_short_username_like_and_single_charset(self) -> None:
|
||||
self.assertIsNotNone(auth.validate_password_policy("Ab1", "cashier"))
|
||||
self.assertIsNotNone(auth.validate_password_policy("Cashier99", "cashier99"))
|
||||
self.assertIsNotNone(auth.validate_password_policy("abcdefgh", "cashier"))
|
||||
self.assertIsNotNone(auth.validate_password_policy("12345678", "cashier"))
|
||||
self.assertIsNone(auth.validate_password_policy("GoodPass1", "cashier"))
|
||||
|
||||
def test_initial_password_generator_guarantees_charset(self) -> None:
|
||||
for _ in range(50):
|
||||
password = auth.generate_initial_password()
|
||||
self.assertEqual(12, len(password))
|
||||
self.assertTrue(any(char.isupper() for char in password))
|
||||
self.assertTrue(any(char.islower() for char in password))
|
||||
self.assertTrue(any(char.isdigit() for char in password))
|
||||
self.assertIsNone(auth.validate_password_policy(auth.generate_initial_password(), "x"))
|
||||
|
||||
def test_initial_password_exclude_never_equals_username(self) -> None:
|
||||
for _ in range(50):
|
||||
password = auth.generate_initial_password(exclude="Cashier99")
|
||||
self.assertNotEqual(password.lower(), "cashier99")
|
||||
|
||||
|
||||
class CreateUserTests(AuthTestCase):
|
||||
def test_company_role_requires_company(self) -> None:
|
||||
with self.assertRaises(ValueError):
|
||||
auth.create_user(self.connection, "cashier-x", "Init1234", "company")
|
||||
|
||||
def test_company_must_exist(self) -> None:
|
||||
with self.assertRaises(ValueError):
|
||||
auth.create_user(self.connection, "cashier-x", "Init1234", "company", company_id=999)
|
||||
|
||||
def test_admin_cannot_bind_company(self) -> None:
|
||||
with self.assertRaises(ValueError):
|
||||
auth.create_user(
|
||||
self.connection, "admin-x", "Init1234", "admin", company_id=self.company_id
|
||||
)
|
||||
|
||||
def test_invalid_role_rejected(self) -> None:
|
||||
with self.assertRaises(ValueError):
|
||||
auth.create_user(self.connection, "nobody", "Init1234", "superuser")
|
||||
|
||||
def test_duplicate_username_rejected(self) -> None:
|
||||
self.create_company_user()
|
||||
with self.assertRaises(ValueError):
|
||||
self.create_company_user()
|
||||
|
||||
def test_new_company_user_must_change_password_by_default(self) -> None:
|
||||
user_id = self.create_company_user()
|
||||
user = self.connection.execute(
|
||||
"SELECT must_change_password, status FROM users WHERE id = ?", (user_id,)
|
||||
).fetchone()
|
||||
self.assertEqual(1, user["must_change_password"])
|
||||
self.assertEqual("active", user["status"])
|
||||
|
||||
|
||||
class AuthenticateTests(AuthTestCase):
|
||||
def test_success_returns_user_and_records_attempt(self) -> None:
|
||||
self.create_company_user()
|
||||
user, reason = auth.authenticate(self.connection, "cashier-a", "Init1234", "127.0.0.1")
|
||||
self.assertIsNotNone(user)
|
||||
self.assertIsNone(reason)
|
||||
attempt = self.connection.execute("SELECT success FROM login_attempts").fetchone()
|
||||
self.assertEqual(1, attempt["success"])
|
||||
entry = self.connection.execute(
|
||||
"SELECT action FROM audit_log WHERE action = 'login_success'"
|
||||
).fetchone()
|
||||
self.assertIsNotNone(entry)
|
||||
|
||||
def test_bad_credentials_do_not_leak_which_part_failed(self) -> None:
|
||||
self.create_company_user()
|
||||
for username, password in (("cashier-a", "Wrong999"), ("no-such-user", "Init1234")):
|
||||
with self.subTest(username=username):
|
||||
user, reason = auth.authenticate(self.connection, username, password, "127.0.0.1")
|
||||
self.assertIsNone(user)
|
||||
self.assertEqual("bad_credentials", reason)
|
||||
|
||||
def test_disabled_user_gets_disabled_reason(self) -> None:
|
||||
user_id = self.create_company_user()
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
"UPDATE users SET status = 'disabled', updated_at = ? WHERE id = ?",
|
||||
(utc_now(), user_id),
|
||||
)
|
||||
user, reason = auth.authenticate(self.connection, "cashier-a", "Init1234", "127.0.0.1")
|
||||
self.assertIsNone(user)
|
||||
self.assertEqual("disabled", reason)
|
||||
|
||||
def test_five_failures_within_window_trigger_rate_limit(self) -> None:
|
||||
self.create_company_user()
|
||||
for _ in range(auth.RATE_LIMIT_MAX_FAILURES):
|
||||
user, reason = auth.authenticate(self.connection, "cashier-a", "Wrong999", "10.0.0.1")
|
||||
self.assertEqual("bad_credentials", reason)
|
||||
user, reason = auth.authenticate(self.connection, "cashier-a", "Init1234", "10.0.0.1")
|
||||
self.assertIsNone(user)
|
||||
self.assertEqual("rate_limited", reason)
|
||||
# A different IP is not limited.
|
||||
user, reason = auth.authenticate(self.connection, "cashier-a", "Init1234", "10.0.0.2")
|
||||
self.assertIsNotNone(user)
|
||||
|
||||
def test_failures_outside_window_do_not_count(self) -> None:
|
||||
self.create_company_user()
|
||||
old = (datetime.now(timezone.utc) - timedelta(minutes=30)).isoformat()
|
||||
with self.connection:
|
||||
for _ in range(auth.RATE_LIMIT_MAX_FAILURES):
|
||||
self.connection.execute(
|
||||
"INSERT INTO login_attempts (username, ip, success, created_at) VALUES (?, ?, 0, ?)",
|
||||
("cashier-a", "10.0.0.9", old),
|
||||
)
|
||||
user, reason = auth.authenticate(self.connection, "cashier-a", "Init1234", "10.0.0.9")
|
||||
self.assertIsNotNone(user)
|
||||
self.assertIsNone(reason)
|
||||
|
||||
def test_env_flag_parses_truthy_and_falsy_values(self) -> None:
|
||||
cases = {
|
||||
"1": True,
|
||||
"true": True,
|
||||
"YES": True,
|
||||
" on ": True,
|
||||
"": False,
|
||||
"0": False,
|
||||
"false": False,
|
||||
"off": False,
|
||||
None: False,
|
||||
}
|
||||
for value, expected in cases.items():
|
||||
with self.subTest(value=value):
|
||||
self.assertEqual(expected, auth._env_flag(value))
|
||||
|
||||
def test_rate_limit_enabled_by_default(self) -> None:
|
||||
self.assertFalse(auth.RATE_LIMIT_DISABLED)
|
||||
|
||||
def test_env_switch_disables_rate_limit_but_not_credential_checks(self) -> None:
|
||||
self.create_company_user()
|
||||
with mock.patch.object(auth, "RATE_LIMIT_DISABLED", True):
|
||||
for _ in range(auth.RATE_LIMIT_MAX_FAILURES + 2):
|
||||
user, reason = auth.authenticate(
|
||||
self.connection, "cashier-a", "Wrong999", "10.0.0.1"
|
||||
)
|
||||
self.assertIsNone(user)
|
||||
self.assertEqual("bad_credentials", reason)
|
||||
user, reason = auth.authenticate(
|
||||
self.connection, "cashier-a", "Init1234", "10.0.0.1"
|
||||
)
|
||||
self.assertIsNotNone(user)
|
||||
self.assertIsNone(reason)
|
||||
|
||||
|
||||
class SessionTests(AuthTestCase):
|
||||
def test_create_and_resolve_roundtrip(self) -> None:
|
||||
user_id = self.create_company_user()
|
||||
token = auth.create_session(self.connection, user_id)
|
||||
user = auth.resolve_session(self.connection, token)
|
||||
self.assertIsNotNone(user)
|
||||
self.assertEqual(user_id, user["id"])
|
||||
# Only the digest is stored, never the raw token.
|
||||
row = self.connection.execute("SELECT token_hash FROM sessions").fetchone()
|
||||
self.assertEqual(hashlib.sha256(token.encode()).hexdigest(), row["token_hash"])
|
||||
self.assertNotIn(token, row["token_hash"])
|
||||
|
||||
def test_expired_session_is_rejected(self) -> None:
|
||||
user_id = self.create_company_user()
|
||||
token = auth.create_session(self.connection, user_id)
|
||||
past = (datetime.now(timezone.utc) - timedelta(hours=1)).isoformat()
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
"UPDATE sessions SET expires_at = ? WHERE token_hash = ?",
|
||||
(past, hashlib.sha256(token.encode()).hexdigest()),
|
||||
)
|
||||
self.assertIsNone(auth.resolve_session(self.connection, token))
|
||||
|
||||
def test_revoked_session_is_rejected(self) -> None:
|
||||
user_id = self.create_company_user()
|
||||
token = auth.create_session(self.connection, user_id)
|
||||
auth.revoke_session(self.connection, token)
|
||||
self.assertIsNone(auth.resolve_session(self.connection, token))
|
||||
|
||||
def test_revoke_user_sessions_kills_all_sessions(self) -> None:
|
||||
user_id = self.create_company_user()
|
||||
first = auth.create_session(self.connection, user_id)
|
||||
second = auth.create_session(self.connection, user_id)
|
||||
auth.revoke_user_sessions(self.connection, user_id)
|
||||
self.assertIsNone(auth.resolve_session(self.connection, first))
|
||||
self.assertIsNone(auth.resolve_session(self.connection, second))
|
||||
|
||||
def test_disabled_user_session_is_rejected(self) -> None:
|
||||
user_id = self.create_company_user()
|
||||
token = auth.create_session(self.connection, user_id)
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
"UPDATE users SET status = 'disabled', updated_at = ? WHERE id = ?",
|
||||
(utc_now(), user_id),
|
||||
)
|
||||
self.assertIsNone(auth.resolve_session(self.connection, token))
|
||||
|
||||
|
||||
class ChangePasswordTests(AuthTestCase):
|
||||
def test_change_password_clears_flag_and_updates_hash(self) -> None:
|
||||
user_id = self.create_company_user()
|
||||
error = auth.change_password(self.connection, user_id, "Init1234", "NewPass99")
|
||||
self.assertIsNone(error)
|
||||
user = self.connection.execute(
|
||||
"SELECT password_hash, must_change_password FROM users WHERE id = ?", (user_id,)
|
||||
).fetchone()
|
||||
self.assertEqual(0, user["must_change_password"])
|
||||
self.assertTrue(auth.verify_password("NewPass99", user["password_hash"]))
|
||||
self.assertFalse(auth.verify_password("Init1234", user["password_hash"]))
|
||||
entry = self.connection.execute(
|
||||
"SELECT detail FROM audit_log WHERE action = 'password_change'"
|
||||
).fetchone()
|
||||
self.assertIsNotNone(entry)
|
||||
self.assertNotIn("NewPass99", entry["detail"] or "")
|
||||
|
||||
def test_wrong_old_password_rejected(self) -> None:
|
||||
user_id = self.create_company_user()
|
||||
error = auth.change_password(self.connection, user_id, "Wrong999", "NewPass99")
|
||||
self.assertIsNotNone(error)
|
||||
user = self.connection.execute(
|
||||
"SELECT must_change_password FROM users WHERE id = ?", (user_id,)
|
||||
).fetchone()
|
||||
self.assertEqual(1, user["must_change_password"])
|
||||
|
||||
def test_policy_violation_rejected(self) -> None:
|
||||
user_id = self.create_company_user()
|
||||
error = auth.change_password(self.connection, user_id, "Init1234", "short")
|
||||
self.assertIsNotNone(error)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,653 +0,0 @@
|
||||
"""Tests for calculation window: start date, opening balances, coverage gaps."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
import json
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
|
||||
from bank_importer import auth, calculation, matching, master_data
|
||||
from bank_importer.db import connect, migrate, utc_now
|
||||
|
||||
import server
|
||||
from test_server_auth import Client, as_json
|
||||
|
||||
|
||||
class CalculationBase(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.temp_dir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp_dir.cleanup)
|
||||
self.db_path = Path(self.temp_dir.name) / "app.db"
|
||||
self.connection = connect(self.db_path)
|
||||
self.addCleanup(self.connection.close)
|
||||
migrate(self.connection)
|
||||
self.admin = self._admin()
|
||||
self.company_a = self._company("甲公司")
|
||||
self.company_b = self._company("乙公司")
|
||||
self.account_a = self._approved_account(self.company_a, "6222000000000001")
|
||||
self.account_b = self._approved_account(self.company_b, "6222000000000002")
|
||||
|
||||
def _admin(self):
|
||||
auth.create_user(self.connection, "admin-u", "AdminPass123", "admin")
|
||||
return self.connection.execute(
|
||||
"SELECT * FROM users WHERE username = 'admin-u'"
|
||||
).fetchone()
|
||||
|
||||
def _company(self, name: str) -> int:
|
||||
with self.connection:
|
||||
cursor = self.connection.execute(
|
||||
"INSERT INTO companies (name, created_at, updated_at) VALUES (?, ?, ?)",
|
||||
(name, utc_now(), utc_now()),
|
||||
)
|
||||
return int(cursor.lastrowid)
|
||||
|
||||
def _approved_account(self, company_id: int, number: str, start: str = "2026-01-01"):
|
||||
account = master_data.submit_bank_account(
|
||||
self.connection,
|
||||
company_id=company_id,
|
||||
bank_name="中信银行",
|
||||
account_type="基本户",
|
||||
account_number=number,
|
||||
start_date=start,
|
||||
actor=None,
|
||||
)
|
||||
return master_data.review_bank_account(
|
||||
self.connection, account["id"], "approve", None, self.admin,
|
||||
effective_from=start,
|
||||
)
|
||||
|
||||
def add_confirmed_row(
|
||||
self,
|
||||
company_id: int,
|
||||
*,
|
||||
account_id: int,
|
||||
own_account: str,
|
||||
at: str,
|
||||
income: str = "0",
|
||||
expense: str = "0",
|
||||
cp_account: str | None = None,
|
||||
sheet: str = "流水",
|
||||
source_row: int = 1,
|
||||
) -> int:
|
||||
with self.connection:
|
||||
cursor = self.connection.execute(
|
||||
"""
|
||||
INSERT INTO source_files (sha256, original_filename, size_bytes, storage_path, created_at)
|
||||
VALUES (?, '测试.xlsx', 1, 'data/files/测试.xlsx', ?)
|
||||
""",
|
||||
(f"sha-{at}-{own_account}-{source_row}", utc_now()),
|
||||
)
|
||||
source_file_id = int(cursor.lastrowid)
|
||||
cursor = self.connection.execute(
|
||||
"""
|
||||
INSERT INTO import_batches (
|
||||
source_file_id, status, company_id, upload_bank_account_id,
|
||||
created_at, updated_at
|
||||
) VALUES (?, 'parsed', ?, ?, ?, ?)
|
||||
""",
|
||||
(source_file_id, company_id, account_id, utc_now(), utc_now()),
|
||||
)
|
||||
batch_id = int(cursor.lastrowid)
|
||||
cursor = self.connection.execute(
|
||||
"""
|
||||
INSERT INTO sheet_batches (
|
||||
import_batch_id, sheet_name, bank_name, template_id, template_version,
|
||||
header_row, transaction_count, warnings, created_at
|
||||
) VALUES (?, ?, '测试银行', 'test-v1', 1, 1, 1, '[]', ?)
|
||||
""",
|
||||
(batch_id, sheet, utc_now()),
|
||||
)
|
||||
sheet_batch_id = int(cursor.lastrowid)
|
||||
self.connection.execute(
|
||||
"""
|
||||
INSERT INTO sheet_reviews (
|
||||
import_batch_id, sheet_name, outcome, sheet_batch_id,
|
||||
review_status, created_at
|
||||
) VALUES (?, ?, 'parsed', ?, 'confirmed', ?)
|
||||
""",
|
||||
(batch_id, sheet, sheet_batch_id, utc_now()),
|
||||
)
|
||||
cursor = self.connection.execute(
|
||||
"""
|
||||
INSERT INTO source_rows (
|
||||
sheet_batch_id, source_row, transaction_at, income, expense,
|
||||
own_account, counterparty_account, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(sheet_batch_id, source_row, at, income, expense, own_account, cp_account, utc_now()),
|
||||
)
|
||||
return int(cursor.lastrowid)
|
||||
|
||||
def add_confirmed_batch_range(
|
||||
self,
|
||||
company_id: int,
|
||||
*,
|
||||
account_id: int,
|
||||
own_account: str,
|
||||
start: str,
|
||||
end: str,
|
||||
sheet: str,
|
||||
) -> None:
|
||||
with self.connection:
|
||||
cursor = self.connection.execute(
|
||||
"""
|
||||
INSERT INTO source_files (sha256, original_filename, size_bytes, storage_path, created_at)
|
||||
VALUES (?, '测试.xlsx', 1, 'data/files/测试.xlsx', ?)
|
||||
""",
|
||||
(f"sha-batch-{sheet}", utc_now()),
|
||||
)
|
||||
source_file_id = int(cursor.lastrowid)
|
||||
cursor = self.connection.execute(
|
||||
"""
|
||||
INSERT INTO import_batches (
|
||||
source_file_id, status, company_id, upload_bank_account_id,
|
||||
created_at, updated_at
|
||||
) VALUES (?, 'parsed', ?, ?, ?, ?)
|
||||
""",
|
||||
(source_file_id, company_id, account_id, utc_now(), utc_now()),
|
||||
)
|
||||
batch_id = int(cursor.lastrowid)
|
||||
cursor = self.connection.execute(
|
||||
"""
|
||||
INSERT INTO sheet_batches (
|
||||
import_batch_id, sheet_name, bank_name, template_id, template_version,
|
||||
header_row, transaction_count, warnings, created_at
|
||||
) VALUES (?, ?, '测试银行', 'test-v1', 1, 1, 2, '[]', ?)
|
||||
""",
|
||||
(batch_id, sheet, utc_now()),
|
||||
)
|
||||
sheet_batch_id = int(cursor.lastrowid)
|
||||
self.connection.execute(
|
||||
"""
|
||||
INSERT INTO sheet_reviews (
|
||||
import_batch_id, sheet_name, outcome, sheet_batch_id,
|
||||
review_status, created_at
|
||||
) VALUES (?, ?, 'parsed', ?, 'confirmed', ?)
|
||||
""",
|
||||
(batch_id, sheet, sheet_batch_id, utc_now()),
|
||||
)
|
||||
for source_row, day in ((1, start), (2, end)):
|
||||
self.connection.execute(
|
||||
"""
|
||||
INSERT INTO source_rows (
|
||||
sheet_batch_id, source_row, transaction_at, income, expense,
|
||||
own_account, created_at
|
||||
) VALUES (?, ?, ?, '0', '0', ?, ?)
|
||||
""",
|
||||
(sheet_batch_id, source_row, f"{day}T10:00:00", own_account, utc_now()),
|
||||
)
|
||||
|
||||
|
||||
class StartDateTests(CalculationBase):
|
||||
def test_set_start_date_records_change(self) -> None:
|
||||
result = calculation.set_calculation_start_date(
|
||||
self.connection, "2026-01-01", "首次设定", self.admin
|
||||
)
|
||||
self.assertEqual("2026-01-01", result["calculation_start_date"])
|
||||
row = self.connection.execute(
|
||||
"SELECT 1 FROM master_data_changes WHERE entity_type = 'system_setting'"
|
||||
).fetchone()
|
||||
self.assertIsNotNone(row)
|
||||
|
||||
def test_locked_after_closed_period(self) -> None:
|
||||
calculation.set_calculation_start_date(
|
||||
self.connection, "2026-01-01", "首次设定", self.admin
|
||||
)
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
"INSERT INTO closed_periods (year_month, closed_at, closed_by) VALUES ('2026-01', ?, ?)",
|
||||
(utc_now(), self.admin["id"]),
|
||||
)
|
||||
with self.assertRaises(calculation.LockedError):
|
||||
calculation.set_calculation_start_date(
|
||||
self.connection, "2026-02-01", "尝试修改", self.admin
|
||||
)
|
||||
|
||||
|
||||
class OpeningBalanceTests(CalculationBase):
|
||||
def setUp(self) -> None:
|
||||
super().setUp()
|
||||
calculation.set_calculation_start_date(
|
||||
self.connection, "2026-01-01", "测试起算日", self.admin
|
||||
)
|
||||
|
||||
def test_bilateral_conservation_on_storage(self) -> None:
|
||||
item = calculation.create_opening_balance(
|
||||
self.connection,
|
||||
self.company_a,
|
||||
self.company_b,
|
||||
"100.00",
|
||||
"期初录入",
|
||||
self.admin,
|
||||
viewer_company_id=self.company_a,
|
||||
)
|
||||
low, high = calculation.normalize_pair(self.company_a, self.company_b)
|
||||
self.assertEqual(low, item["company_id_low"])
|
||||
stored = calculation.confirmed_opening_amount(self.connection, low, high)
|
||||
self.assertIsNone(stored)
|
||||
calculation.confirm_opening_balance(
|
||||
self.connection, item["id"], "确认期初", self.admin
|
||||
)
|
||||
stored = calculation.confirmed_opening_amount(self.connection, low, high)
|
||||
self.assertEqual(Decimal("100.00"), stored)
|
||||
from_b = calculation.signed_from_viewer(self.company_b, low, high, stored)
|
||||
self.assertEqual(Decimal("-100.00"), from_b)
|
||||
|
||||
def test_confirmed_requires_revision_not_overwrite(self) -> None:
|
||||
item = calculation.create_opening_balance(
|
||||
self.connection, self.company_a, self.company_b, "50", "录入", self.admin
|
||||
)
|
||||
calculation.confirm_opening_balance(
|
||||
self.connection, item["id"], "确认", self.admin
|
||||
)
|
||||
with self.assertRaises(calculation.ConflictError):
|
||||
calculation.create_opening_balance(
|
||||
self.connection, self.company_a, self.company_b, "80", "重复录入", self.admin
|
||||
)
|
||||
revised = calculation.revise_opening_balance(
|
||||
self.connection, item["id"], "80", "修订", self.admin
|
||||
)
|
||||
self.assertEqual("draft", revised["status"])
|
||||
|
||||
|
||||
class CoverageGapTests(CalculationBase):
|
||||
def setUp(self) -> None:
|
||||
super().setUp()
|
||||
calculation.set_calculation_start_date(
|
||||
self.connection, "2026-06-01", "起算", self.admin
|
||||
)
|
||||
|
||||
def test_adjacent_intervals_no_mid_gap(self) -> None:
|
||||
self.add_confirmed_batch_range(
|
||||
self.company_a,
|
||||
account_id=self.account_a["id"],
|
||||
own_account="6222000000000001",
|
||||
start="2026-06-21",
|
||||
end="2026-07-21",
|
||||
sheet="批次A",
|
||||
)
|
||||
self.add_confirmed_batch_range(
|
||||
self.company_a,
|
||||
account_id=self.account_a["id"],
|
||||
own_account="6222000000000001",
|
||||
start="2026-07-22",
|
||||
end="2026-08-21",
|
||||
sheet="批次B",
|
||||
)
|
||||
calculation.recalculate_coverage_gaps(self.connection)
|
||||
mids = self.connection.execute(
|
||||
"SELECT * FROM coverage_gaps WHERE gap_kind = 'mid'"
|
||||
).fetchall()
|
||||
self.assertEqual([], mids)
|
||||
|
||||
def test_missing_day_mid_gap(self) -> None:
|
||||
self.add_confirmed_batch_range(
|
||||
self.company_a,
|
||||
account_id=self.account_a["id"],
|
||||
own_account="6222000000000001",
|
||||
start="2026-06-21",
|
||||
end="2026-07-21",
|
||||
sheet="批次A",
|
||||
)
|
||||
self.add_confirmed_batch_range(
|
||||
self.company_a,
|
||||
account_id=self.account_a["id"],
|
||||
own_account="6222000000000001",
|
||||
start="2026-07-23",
|
||||
end="2026-08-21",
|
||||
sheet="批次B",
|
||||
)
|
||||
calculation.recalculate_coverage_gaps(self.connection)
|
||||
gap = self.connection.execute(
|
||||
"""
|
||||
SELECT gap_start, gap_end FROM coverage_gaps
|
||||
WHERE gap_kind = 'mid' AND gap_start = '2026-07-22'
|
||||
"""
|
||||
).fetchone()
|
||||
self.assertIsNotNone(gap)
|
||||
self.assertEqual("2026-07-22", gap["gap_end"])
|
||||
|
||||
def test_attestation_closes_gap_without_bank_row(self) -> None:
|
||||
self.add_confirmed_row(
|
||||
self.company_a,
|
||||
account_id=self.account_a["id"],
|
||||
own_account="6222000000000001",
|
||||
at="2026-06-21T10:00:00",
|
||||
)
|
||||
calculation.recalculate_coverage_gaps(self.connection)
|
||||
gap = self.connection.execute(
|
||||
"SELECT * FROM coverage_gaps WHERE status = 'open'"
|
||||
).fetchone()
|
||||
self.assertIsNotNone(gap)
|
||||
before_rows = self.connection.execute("SELECT COUNT(*) AS n FROM source_rows").fetchone()["n"]
|
||||
cashier_id = auth.create_user(
|
||||
self.connection, "cashier-a", "CashierA123", "company", self.company_a
|
||||
)
|
||||
cashier = self.connection.execute(
|
||||
"SELECT * FROM users WHERE id = ?", (cashier_id,)
|
||||
).fetchone()
|
||||
att = calculation.submit_no_business_attestation(
|
||||
self.connection,
|
||||
company_id=self.company_a,
|
||||
bank_account_id=self.account_a["id"],
|
||||
gap_start=gap["gap_start"],
|
||||
gap_end=gap["gap_end"],
|
||||
reason="当日账户无资金往来",
|
||||
evidence=None,
|
||||
actor=cashier,
|
||||
)
|
||||
calculation.review_no_business_attestation(
|
||||
self.connection, att["id"], "approve", "审核通过", self.admin
|
||||
)
|
||||
after_rows = self.connection.execute("SELECT COUNT(*) AS n FROM source_rows").fetchone()["n"]
|
||||
self.assertEqual(before_rows, after_rows)
|
||||
closed = self.connection.execute(
|
||||
"SELECT status FROM coverage_gaps WHERE id = ?", (gap["id"],)
|
||||
).fetchone()
|
||||
self.assertEqual("closed_attested", closed["status"])
|
||||
|
||||
def test_attestation_and_audit_survive_connection_close(self) -> None:
|
||||
"""HEL-282: attestation writes used to skip the change log; review also
|
||||
nested-committed coverage recalculation before the overlap close."""
|
||||
from bank_importer.db import connect as db_connect
|
||||
|
||||
self.add_confirmed_row(
|
||||
self.company_a,
|
||||
account_id=self.account_a["id"],
|
||||
own_account="6222000000000001",
|
||||
at="2026-06-21T10:00:00",
|
||||
)
|
||||
calculation.recalculate_coverage_gaps(self.connection)
|
||||
gap = self.connection.execute(
|
||||
"SELECT * FROM coverage_gaps WHERE status = 'open'"
|
||||
).fetchone()
|
||||
cashier_id = auth.create_user(
|
||||
self.connection, "cashier-close", "CashierA123", "company", self.company_a
|
||||
)
|
||||
cashier = self.connection.execute(
|
||||
"SELECT * FROM users WHERE id = ?", (cashier_id,)
|
||||
).fetchone()
|
||||
att = calculation.submit_no_business_attestation(
|
||||
self.connection,
|
||||
company_id=self.company_a,
|
||||
bank_account_id=self.account_a["id"],
|
||||
gap_start=gap["gap_start"],
|
||||
gap_end=gap["gap_end"],
|
||||
reason="当日账户无资金往来",
|
||||
evidence=None,
|
||||
actor=cashier,
|
||||
)
|
||||
calculation.review_no_business_attestation(
|
||||
self.connection, att["id"], "approve", "审核通过", self.admin
|
||||
)
|
||||
att_id = att["id"]
|
||||
self.connection.close()
|
||||
fresh = db_connect(self.db_path)
|
||||
try:
|
||||
row = fresh.execute(
|
||||
"SELECT status FROM no_business_attestations WHERE id = ?", (att_id,)
|
||||
).fetchone()
|
||||
actions = [
|
||||
item["action"]
|
||||
for item in fresh.execute(
|
||||
"""
|
||||
SELECT action FROM audit_log
|
||||
WHERE action LIKE 'attestation_%'
|
||||
ORDER BY id
|
||||
"""
|
||||
).fetchall()
|
||||
]
|
||||
closed = fresh.execute(
|
||||
"SELECT status FROM coverage_gaps WHERE id = ?", (gap["id"],)
|
||||
).fetchone()
|
||||
finally:
|
||||
fresh.close()
|
||||
self.assertEqual("approved", row["status"])
|
||||
self.assertEqual(["attestation_submit", "attestation_approve"], actions)
|
||||
self.assertEqual("closed_attested", closed["status"])
|
||||
|
||||
|
||||
class BalanceBasisTests(CalculationBase):
|
||||
def setUp(self) -> None:
|
||||
super().setUp()
|
||||
calculation.set_calculation_start_date(
|
||||
self.connection, "2026-01-01", "起算", self.admin
|
||||
)
|
||||
|
||||
def test_without_opening_returns_net_change(self) -> None:
|
||||
row_a = self.add_confirmed_row(
|
||||
self.company_a,
|
||||
account_id=self.account_a["id"],
|
||||
own_account="6222000000000001",
|
||||
at="2026-01-05T10:00:00",
|
||||
expense="100.00",
|
||||
cp_account="6222000000000002",
|
||||
)
|
||||
row_b = self.add_confirmed_row(
|
||||
self.company_b,
|
||||
account_id=self.account_b["id"],
|
||||
own_account="6222000000000002",
|
||||
at="2026-01-05T11:00:00",
|
||||
income="100.00",
|
||||
cp_account="6222000000000001",
|
||||
)
|
||||
matching.reconcile_rows(self.connection, [row_a, row_b])
|
||||
balance = calculation.compute_pair_balance(
|
||||
self.connection, self.company_a, self.company_b, cutoff="2026-01-31"
|
||||
)
|
||||
self.assertEqual("net_change", balance["basis"])
|
||||
self.assertNotIn("closing", balance)
|
||||
|
||||
def test_with_opening_returns_full_basis(self) -> None:
|
||||
item = calculation.create_opening_balance(
|
||||
self.connection, self.company_a, self.company_b, "200", "录入", self.admin
|
||||
)
|
||||
calculation.confirm_opening_balance(
|
||||
self.connection, item["id"], "确认", self.admin
|
||||
)
|
||||
balance = calculation.compute_pair_balance(
|
||||
self.connection, self.company_a, self.company_b, cutoff="2026-01-31"
|
||||
)
|
||||
self.assertEqual("full", balance["basis"])
|
||||
self.assertEqual("200", balance["opening"])
|
||||
self.assertEqual("200", balance["closing"])
|
||||
|
||||
def test_pre_start_events_excluded(self) -> None:
|
||||
item = calculation.create_opening_balance(
|
||||
self.connection, self.company_a, self.company_b, "0", "零期初", self.admin
|
||||
)
|
||||
calculation.confirm_opening_balance(
|
||||
self.connection, item["id"], "确认", self.admin
|
||||
)
|
||||
row_a = self.add_confirmed_row(
|
||||
self.company_a,
|
||||
account_id=self.account_a["id"],
|
||||
own_account="6222000000000001",
|
||||
at="2025-12-31T10:00:00",
|
||||
expense="50.00",
|
||||
cp_account="6222000000000002",
|
||||
)
|
||||
row_b = self.add_confirmed_row(
|
||||
self.company_b,
|
||||
account_id=self.account_b["id"],
|
||||
own_account="6222000000000002",
|
||||
at="2025-12-31T11:00:00",
|
||||
income="50.00",
|
||||
cp_account="6222000000000001",
|
||||
)
|
||||
matching.reconcile_rows(self.connection, [row_a, row_b])
|
||||
balance = calculation.compute_pair_balance(
|
||||
self.connection, self.company_a, self.company_b, cutoff="2026-01-31"
|
||||
)
|
||||
self.assertEqual("0", balance["net_change"])
|
||||
|
||||
def test_cutoff_day_event_is_included(self) -> None:
|
||||
"""effective_at with time on the cutoff date must still count."""
|
||||
from test_matching import MatchingBase
|
||||
|
||||
item = calculation.create_opening_balance(
|
||||
self.connection, self.company_a, self.company_b, "0", "零期初", self.admin
|
||||
)
|
||||
calculation.confirm_opening_balance(
|
||||
self.connection, item["id"], "确认", self.admin
|
||||
)
|
||||
helper = object.__new__(MatchingBase)
|
||||
helper.connection = self.connection
|
||||
row_a = helper.add_row(
|
||||
self.company_a,
|
||||
own_account="6222000000000001",
|
||||
cp_account="6222000000000002",
|
||||
expense="80.00",
|
||||
at="2026-01-31T10:00:00",
|
||||
)
|
||||
matching.reconcile_rows(self.connection, [row_a])
|
||||
row_b = helper.add_row(
|
||||
self.company_b,
|
||||
own_account="6222000000000002",
|
||||
cp_account="6222000000000001",
|
||||
income="80.00",
|
||||
at="2026-01-31T11:00:00",
|
||||
)
|
||||
matching.reconcile_rows(self.connection, [row_b])
|
||||
eligible = self.connection.execute(
|
||||
"SELECT effective_at, amount FROM eligible_intercompany_events"
|
||||
).fetchall()
|
||||
self.assertEqual(1, len(eligible))
|
||||
self.assertEqual("2026-01-31T10:00:00", eligible[0]["effective_at"])
|
||||
# Full-timestamp string compare wrongly excludes the cutoff day.
|
||||
self.assertEqual(
|
||||
[],
|
||||
self.connection.execute(
|
||||
"""
|
||||
SELECT 1 FROM eligible_intercompany_events
|
||||
WHERE effective_at <= '2026-01-31'
|
||||
"""
|
||||
).fetchall(),
|
||||
)
|
||||
balance = calculation.compute_pair_balance(
|
||||
self.connection, self.company_a, self.company_b, cutoff="2026-01-31"
|
||||
)
|
||||
# 甲转出 80 → 应收方向为正
|
||||
self.assertEqual("80.00", balance["net_change"])
|
||||
self.assertEqual("80.00", balance["closing"])
|
||||
|
||||
def test_opening_plus_outflow_increases_receivable(self) -> None:
|
||||
"""期初应收 200 + 本期转出垫付 100 → 期末应收 300;乙方对称为应付 300。"""
|
||||
from test_matching import MatchingBase
|
||||
|
||||
item = calculation.create_opening_balance(
|
||||
self.connection, self.company_a, self.company_b, "200", "期初应收", self.admin
|
||||
)
|
||||
calculation.confirm_opening_balance(
|
||||
self.connection, item["id"], "确认", self.admin
|
||||
)
|
||||
helper = object.__new__(MatchingBase)
|
||||
helper.connection = self.connection
|
||||
row_a = helper.add_row(
|
||||
self.company_a,
|
||||
own_account="6222000000000001",
|
||||
cp_account="6222000000000002",
|
||||
expense="100.00",
|
||||
at="2026-01-15T10:00:00",
|
||||
)
|
||||
matching.reconcile_rows(self.connection, [row_a])
|
||||
row_b = helper.add_row(
|
||||
self.company_b,
|
||||
own_account="6222000000000002",
|
||||
cp_account="6222000000000001",
|
||||
income="100.00",
|
||||
at="2026-01-15T11:00:00",
|
||||
)
|
||||
matching.reconcile_rows(self.connection, [row_b])
|
||||
|
||||
bal_a = calculation.compute_pair_balance(
|
||||
self.connection, self.company_a, self.company_b, cutoff="2026-01-31"
|
||||
)
|
||||
self.assertEqual("full", bal_a["basis"])
|
||||
self.assertEqual("200", bal_a["opening"])
|
||||
self.assertEqual("100.00", bal_a["net_change"])
|
||||
self.assertEqual("300.00", bal_a["closing"])
|
||||
|
||||
bal_b = calculation.compute_pair_balance(
|
||||
self.connection, self.company_b, self.company_a, cutoff="2026-01-31"
|
||||
)
|
||||
self.assertEqual("full", bal_b["basis"])
|
||||
self.assertEqual("-200", bal_b["opening"])
|
||||
self.assertEqual("-100.00", bal_b["net_change"])
|
||||
self.assertEqual("-300.00", bal_b["closing"])
|
||||
# 双边守恒
|
||||
self.assertEqual(
|
||||
Decimal(bal_a["closing"]) + Decimal(bal_b["closing"]),
|
||||
Decimal("0"),
|
||||
)
|
||||
|
||||
|
||||
class CalculationApiTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
cls.temp_dir = tempfile.TemporaryDirectory()
|
||||
cls.db_path = Path(cls.temp_dir.name) / "app.db"
|
||||
cls.storage_dir = Path(cls.temp_dir.name) / "files"
|
||||
cls.storage_dir.mkdir()
|
||||
server.DB_PATH = cls.db_path
|
||||
server.STORAGE_DIR = cls.storage_dir
|
||||
connection = connect(cls.db_path)
|
||||
migrate(connection)
|
||||
auth.create_user(
|
||||
connection, "group-admin", "AdminPass123", "admin",
|
||||
must_change_password=False,
|
||||
)
|
||||
company_id = master_data.create_company(connection, "甲公司", None, None, None)
|
||||
auth.create_user(
|
||||
connection, "cashier-a", "CashierA123", "company", company_id,
|
||||
must_change_password=False,
|
||||
)
|
||||
connection.close()
|
||||
cls.httpd = server.ThreadingHTTPServer(("127.0.0.1", 0), server.AppHandler)
|
||||
cls.port = cls.httpd.server_address[1]
|
||||
cls.thread = threading.Thread(target=cls.httpd.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
cls.client = Client("127.0.0.1", cls.port)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls) -> None:
|
||||
cls.httpd.shutdown()
|
||||
cls.temp_dir.cleanup()
|
||||
|
||||
def test_company_cannot_call_admin_start_date(self) -> None:
|
||||
self.client.post_json("/api/login", {
|
||||
"username": "cashier-a", "password": "CashierA123", "portal": "company",
|
||||
})
|
||||
status, _, _ = self.client.request(
|
||||
"PUT",
|
||||
"/api/admin/settings/calculation-start",
|
||||
body=json.dumps(
|
||||
{"calculation_start_date": "2026-01-01", "reason": "越权"}
|
||||
).encode("utf-8"),
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
self.assertEqual(403, status)
|
||||
|
||||
def test_admin_can_set_start_date(self) -> None:
|
||||
client = Client("127.0.0.1", self.port)
|
||||
client.post_json("/api/login", {
|
||||
"username": "group-admin", "password": "AdminPass123", "portal": "admin",
|
||||
})
|
||||
status, _, body = client.request(
|
||||
"PUT",
|
||||
"/api/admin/settings/calculation-start",
|
||||
body=json.dumps(
|
||||
{"calculation_start_date": "2026-01-01", "reason": "初始化"}
|
||||
).encode("utf-8"),
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
self.assertEqual(200, status)
|
||||
data = as_json(body)
|
||||
self.assertEqual("2026-01-01", data["calculation_start_date"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,221 +0,0 @@
|
||||
"""HEL-174: 公司端往来确认完成态用 success 绿,待确认保留 warn 黄。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import threading
|
||||
import unittest
|
||||
from functools import partial
|
||||
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
WEB = ROOT / "web"
|
||||
|
||||
try:
|
||||
from playwright.sync_api import sync_playwright
|
||||
except ImportError: # pragma: no cover - 默认测试环境无浏览器依赖
|
||||
sync_playwright = None
|
||||
|
||||
|
||||
class ConfirmStatusSourceContractTests(unittest.TestCase):
|
||||
"""不依赖浏览器:锁住完成态切绿 / 待确认仍黄的实现契约。"""
|
||||
|
||||
def test_app_js_toggles_success_green_when_pending_zero(self) -> None:
|
||||
js = (WEB / "app.js").read_text(encoding="utf-8")
|
||||
self.assertIn('pill ${total ? "pill-warn" : "pill-success"}', js)
|
||||
self.assertIn('flowStep.classList.toggle("doing", pending > 0)', js)
|
||||
self.assertIn('flowStep.classList.toggle("done", pending === 0)', js)
|
||||
self.assertIn('notice.classList.toggle("warn", pending > 0)', js)
|
||||
self.assertIn('notice.classList.toggle("success", pending === 0)', js)
|
||||
# 文案:完成=已完成,不把待确认一并改绿
|
||||
self.assertRegex(js, r'status\.textContent = total \? `\$\{total\} 项待处理` : "已完成"')
|
||||
self.assertRegex(js, r'flowState\.textContent = pending \? `待处理 \$\{pending\} 笔` : "已完成"')
|
||||
|
||||
def test_design_tokens_map_done_to_success_doing_to_warn(self) -> None:
|
||||
css = (WEB / "design-system.css").read_text(encoding="utf-8")
|
||||
self.assertIn("--success:", css)
|
||||
self.assertIn("--warn:", css)
|
||||
self.assertIn(".flow-step.done .fs-dot { background: var(--success); }", css)
|
||||
self.assertIn(".flow-step.done .fs-state { color: var(--success); }", css)
|
||||
self.assertIn(".flow-step.doing .fs-dot { background: var(--warn);", css)
|
||||
self.assertIn(".pill-success { background: var(--success-soft); color: var(--success); }", css)
|
||||
self.assertIn(".pill-warn { background: var(--warn-soft);", css)
|
||||
self.assertIn(".notice.success { background: var(--success-soft);", css)
|
||||
self.assertIn(".notice.warn { background: var(--warn-soft);", css)
|
||||
|
||||
def test_company_html_exposes_flow_step_and_cache_bust(self) -> None:
|
||||
html = (WEB / "company.html").read_text(encoding="utf-8")
|
||||
self.assertIn('id="workspaceConfirmState"', html)
|
||||
self.assertIn('id="workspacePendingStatus"', html)
|
||||
self.assertIn('id="workspaceFlowSub"', html)
|
||||
self.assertIn('data-view-link="reconcile"', html)
|
||||
self.assertIn("app.js?v=18", html)
|
||||
# 静态初值仍为进行中(黄),由 JS 在 pending=0 时切 done
|
||||
self.assertRegex(html, r'class="flow-step doing"[^>]*data-view-link="reconcile"')
|
||||
|
||||
|
||||
def _extract_fn(source: str, name: str) -> str:
|
||||
marker = f"function {name}("
|
||||
start = source.index(marker)
|
||||
depth = 0
|
||||
for i, ch in enumerate(source[start:], start):
|
||||
if ch == "{":
|
||||
depth += 1
|
||||
elif ch == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return source[start : i + 1]
|
||||
raise AssertionError(f"未能截取 function {name}")
|
||||
|
||||
|
||||
def _chromium_available() -> bool:
|
||||
"""本机缺 libatk 等系统库时 chromium 无法启动。"""
|
||||
try:
|
||||
import ctypes.util
|
||||
|
||||
return bool(ctypes.util.find_library("atk-1.0"))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
@unittest.skipUnless(sync_playwright, "playwright 未安装,跳过真实 DOM 色值校验")
|
||||
@unittest.skipUnless(_chromium_available(), "系统缺少 chromium 依赖库(如 libatk),跳过浏览器色值校验")
|
||||
class ConfirmStatusDomTests(unittest.TestCase):
|
||||
"""真实浏览器:pending>0 为黄,pending=0 为绿。"""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
handler = partial(SimpleHTTPRequestHandler, directory=str(WEB))
|
||||
cls.httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
cls.port = cls.httpd.server_address[1]
|
||||
cls.thread = threading.Thread(target=cls.httpd.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
cls.base = f"http://127.0.0.1:{cls.port}"
|
||||
app_js = (WEB / "app.js").read_text(encoding="utf-8")
|
||||
cls.inject_js = "\n".join(
|
||||
[
|
||||
"const state = {};",
|
||||
"function $(sel, root) { return (root || document).querySelector(sel); }",
|
||||
"function $$(sel, root) { return Array.from((root || document).querySelectorAll(sel)); }",
|
||||
_extract_fn(app_js, "formatWorkspaceAmount"),
|
||||
_extract_fn(app_js, "applyCompanyWorkspace"),
|
||||
]
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls) -> None:
|
||||
cls.httpd.shutdown()
|
||||
cls.httpd.server_close()
|
||||
|
||||
def _open_fixture(self, page):
|
||||
page.goto(f"{self.base}/design-system.css", wait_until="domcontentloaded")
|
||||
page.set_content(
|
||||
f"""<!doctype html>
|
||||
<html lang="zh-CN"><head>
|
||||
<meta charset="UTF-8"/>
|
||||
<link rel="stylesheet" href="{self.base}/design-system.css"/>
|
||||
</head>
|
||||
<body data-portal="company">
|
||||
<button id="workspaceUnilateralCta" class="btn btn-primary">去确认单边流水 (0)</button>
|
||||
<div class="card" id="workspaceTodos">
|
||||
<div class="card-head">
|
||||
<span class="card-title">本月待办<span class="sub" id="workspaceTodoSub">…</span></span>
|
||||
<span class="pill pill-warn" id="workspacePendingStatus">加载中</span>
|
||||
</div>
|
||||
<div id="workspaceTodoList"></div>
|
||||
<div class="table-foot" id="workspaceTodoFoot"><span>…</span></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head">
|
||||
<span class="card-title">账期流程<span class="sub" id="workspaceFlowSub">…</span></span>
|
||||
</div>
|
||||
<div class="flow">
|
||||
<a class="flow-step doing" data-view-link="reconcile" href="#reconcile">
|
||||
<div class="fs-top"><span class="fs-idx">03</span><span class="fs-dot"></span><span class="fs-name">往来确认</span></div>
|
||||
<div class="fs-state" id="workspaceConfirmState">加载中…</div>
|
||||
<div class="fs-meta" id="workspaceConfirmMeta">…</div>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="notice warn" id="blocking-notice">
|
||||
<div class="n-title" id="notice-title">…</div>
|
||||
<div class="n-body" id="notice-body">…</div>
|
||||
</div>
|
||||
<span class="tab-count" id="count-match">0</span>
|
||||
<nav class="side-nav"><a data-view="reconcile"><span class="nav-badge">0</span></a></nav>
|
||||
</body></html>""",
|
||||
wait_until="domcontentloaded",
|
||||
)
|
||||
page.add_script_tag(content=self.inject_js)
|
||||
page.wait_for_function("() => typeof applyCompanyWorkspace === 'function'")
|
||||
|
||||
@staticmethod
|
||||
def _colors(page) -> dict:
|
||||
return page.evaluate(
|
||||
"""() => {
|
||||
const step = document.querySelector('.flow-step[data-view-link="reconcile"]');
|
||||
const state = document.getElementById('workspaceConfirmState');
|
||||
const pill = document.getElementById('workspacePendingStatus');
|
||||
const notice = document.getElementById('blocking-notice');
|
||||
const cs = (el) => getComputedStyle(el);
|
||||
return {
|
||||
stepClass: step.className,
|
||||
stateText: state.textContent,
|
||||
stateColor: cs(state).color,
|
||||
pillClass: pill.className,
|
||||
pillColor: cs(pill).color,
|
||||
pillText: pill.textContent,
|
||||
noticeClass: notice.className,
|
||||
};
|
||||
}"""
|
||||
)
|
||||
|
||||
def test_pending_stays_warn_completed_turns_success(self) -> None:
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, args=["--no-sandbox"])
|
||||
page = browser.new_page(viewport={"width": 1440, "height": 900})
|
||||
self._open_fixture(page)
|
||||
|
||||
page.evaluate(
|
||||
"""() => applyCompanyWorkspace({
|
||||
pending_unilateral: 2,
|
||||
pending_total: 2,
|
||||
unilateral_events: [
|
||||
{event_id: 1, amount: '100.00', currency: 'CNY',
|
||||
counterparty_company_name: '乙', effective_at: '2026-07-01'}
|
||||
]
|
||||
})"""
|
||||
)
|
||||
pending = self._colors(page)
|
||||
self.assertIn("doing", pending["stepClass"])
|
||||
self.assertNotIn("done", pending["stepClass"].split())
|
||||
self.assertIn("pill-warn", pending["pillClass"])
|
||||
self.assertNotIn("pill-success", pending["pillClass"])
|
||||
self.assertIn("warn", pending["noticeClass"].split())
|
||||
self.assertIn("待处理", pending["stateText"])
|
||||
self.assertIn("待处理", pending["pillText"])
|
||||
|
||||
page.evaluate(
|
||||
"""() => applyCompanyWorkspace({
|
||||
pending_unilateral: 0,
|
||||
pending_total: 0,
|
||||
unilateral_events: []
|
||||
})"""
|
||||
)
|
||||
done = self._colors(page)
|
||||
self.assertIn("done", done["stepClass"])
|
||||
self.assertNotIn("doing", done["stepClass"].split())
|
||||
self.assertIn("pill-success", done["pillClass"])
|
||||
self.assertNotIn("pill-warn", done["pillClass"])
|
||||
self.assertIn("success", done["noticeClass"].split())
|
||||
self.assertEqual("已完成", done["stateText"])
|
||||
self.assertEqual("已完成", done["pillText"])
|
||||
|
||||
self.assertNotEqual(pending["stateColor"], done["stateColor"])
|
||||
self.assertNotEqual(pending["pillColor"], done["pillColor"])
|
||||
browser.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,136 +0,0 @@
|
||||
"""Company assignments checked through real HTTP routes, including old sessions."""
|
||||
import json
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import server
|
||||
from bank_importer import auth, company_access, master_data, portal_sso
|
||||
from bank_importer.db import connect, migrate, MIGRATIONS, utc_now
|
||||
from test_server_auth import Client, as_json
|
||||
|
||||
|
||||
class CompanyMembershipTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.path = Path(self.temp.name) / 'test.db'
|
||||
self.db = connect(self.path)
|
||||
self.addCleanup(self.db.close)
|
||||
migrate(self.db)
|
||||
self.admin = auth.create_user(self.db, 'manager', 'Password123', 'admin', must_change_password=False)
|
||||
self.cashier = auth.create_user(self.db, '010013', 'Password123', 'company', allow_unassigned=True, must_change_password=False)
|
||||
self.other = auth.create_user(self.db, '010015', 'Password123', 'company', allow_unassigned=True, must_change_password=False)
|
||||
self.actor = self.db.execute('SELECT * FROM users WHERE id=?', (self.admin,)).fetchone()
|
||||
self.a, self.b, self.c = [master_data.create_company(self.db, name, '', '', self.actor) for name in ['公司甲','公司乙','公司丙']]
|
||||
self.env = patch.dict('os.environ', {'PORTAL_SSO_ENABLED':'0'})
|
||||
self.env.start(); self.addCleanup(self.env.stop)
|
||||
self.dbpatch = patch.object(server, 'DB_PATH', self.path)
|
||||
self.dbpatch.start(); self.addCleanup(self.dbpatch.stop)
|
||||
class Quiet(server.AppHandler):
|
||||
def log_message(self, *args): pass
|
||||
self.httpd = server.ThreadingHTTPServer(('127.0.0.1', 0), Quiet)
|
||||
threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
|
||||
self.addCleanup(self.httpd.server_close); self.addCleanup(self.httpd.shutdown)
|
||||
self.client = self.client_for(self.cashier)
|
||||
self.manager = self.client_for(self.admin)
|
||||
|
||||
def client_for(self, uid):
|
||||
client = Client('127.0.0.1', self.httpd.server_port)
|
||||
client.cookies[server.SESSION_COOKIE] = auth.create_session(self.db, uid)
|
||||
return client
|
||||
|
||||
def assign(self, cid, ids):
|
||||
company_access.replace_members(self.db, cid, ids, self.actor)
|
||||
|
||||
def test_unassigned_can_see_identity_but_no_business_endpoints(self):
|
||||
status, _, body = self.client.get('/api/me')
|
||||
self.assertEqual(status, 200)
|
||||
self.assertEqual(as_json(body)['companies'], [])
|
||||
for route in ['/api/batches','/api/flows','/api/export.csv','/api/company/workspace', '/api/company/accounts', '/api/company/intercompany/export.csv']:
|
||||
self.assertEqual(self.client.get(route)[0], 403, route)
|
||||
self.assertEqual(self.client.post_json('/api/parse', {})[0], 403)
|
||||
|
||||
def test_multiple_companies_require_explicit_scope_and_reject_forged_scope(self):
|
||||
self.assign(self.a,[self.cashier]); self.assign(self.b,[self.cashier])
|
||||
me = as_json(self.client.get('/api/me')[2])
|
||||
self.assertEqual([c['id'] for c in me['companies']], [self.a,self.b])
|
||||
self.assertEqual(self.client.get('/api/batches')[0],403)
|
||||
for cid in [self.a, self.b]:
|
||||
self.assertEqual(self.client.request('GET','/api/batches',headers={'X-Company-ID':str(cid)})[0],200)
|
||||
for route in ['/api/batches','/api/flows','/api/export.csv','/api/company/accounts']:
|
||||
self.assertEqual(self.client.request('GET',route,headers={'X-Company-ID':str(self.c)})[0],403)
|
||||
self.assertEqual(self.client.get(f'/api/export.csv?_company_scope={self.c}')[0],403)
|
||||
self.assertEqual(self.client.get(f'/api/export.csv?_company_scope={self.b}')[0],200)
|
||||
|
||||
def test_two_cashiers_and_revocation_apply_to_existing_session(self):
|
||||
self.assign(self.a,[self.cashier,self.other])
|
||||
other = self.client_for(self.other)
|
||||
self.assertEqual(self.client.get('/api/batches')[0],200)
|
||||
self.assertEqual(other.get('/api/batches')[0],200)
|
||||
self.assign(self.a,[self.other])
|
||||
self.assertEqual(self.client.get('/api/batches')[0],403)
|
||||
self.assertEqual(other.get('/api/batches')[0],200)
|
||||
audit = self.db.execute("SELECT detail FROM audit_log WHERE action='company_members_changed' ORDER BY id DESC").fetchone()
|
||||
self.assertEqual(json.loads(audit['detail'])['before'], [self.cashier,self.other])
|
||||
|
||||
def test_company_admin_assignment_is_atomic_and_role_limited(self):
|
||||
payload = {'name':'新公司','credit_code':'','cashier_user_ids':[self.cashier,self.other]}
|
||||
self.assertEqual(self.client.post_json('/api/admin/companies',payload)[0],403)
|
||||
status,_,body = self.manager.post_json('/api/admin/companies',payload)
|
||||
self.assertEqual(status,200)
|
||||
cid=as_json(body)['company_id']
|
||||
self.assertEqual(len(self.db.execute('SELECT * FROM company_memberships WHERE company_id=?',(cid,)).fetchall()),2)
|
||||
payload.update(id=cid,name='新公司改名',cashier_user_ids=[self.admin])
|
||||
self.assertEqual(self.manager.post_json('/api/admin/companies',payload)[0],400)
|
||||
self.assertEqual(self.db.execute('SELECT name FROM companies WHERE id=?',(cid,)).fetchone()[0],'新公司')
|
||||
payload['cashier_user_ids']=[]
|
||||
self.assertEqual(self.manager.post_json('/api/admin/companies',payload)[0],200)
|
||||
|
||||
def test_disabled_employee_cannot_be_assigned_and_disabled_company_denies_access(self):
|
||||
with self.db: self.db.execute("UPDATE users SET status='disabled' WHERE id=?",(self.other,))
|
||||
status,_,_=self.manager.post_json('/api/admin/companies',{'id':self.a,'name':'公司甲','cashier_user_ids':[self.other]})
|
||||
self.assertEqual(status,400)
|
||||
self.assign(self.a,[self.cashier])
|
||||
with self.db: self.db.execute("UPDATE companies SET status='disabled' WHERE id=?",(self.a,))
|
||||
self.assertEqual(self.client.get('/api/batches')[0],403)
|
||||
|
||||
def test_portal_directory_requires_matching_pinned_identity(self):
|
||||
portal_sso.migrate(self.db)
|
||||
with self.db: self.db.execute('INSERT INTO portal_identity(uid,empid) VALUES(?,?)',(self.cashier,'correct'))
|
||||
with patch.object(portal_sso,'enabled',return_value=True), patch.object(portal_sso,'call',return_value={'employees':[
|
||||
{'local_uid':self.cashier,'empid':'wrong','username':'010013','display_name':'某出纳'}]}):
|
||||
self.assertEqual(company_access.candidates(self.db),[])
|
||||
|
||||
|
||||
class MembershipMigrationTests(unittest.TestCase):
|
||||
def test_upgrade_preserves_preexisting_orphan_audit_instead_of_rewriting_history(self):
|
||||
db=connect(':memory:'); self.addCleanup(db.close)
|
||||
with patch('bank_importer.db.MIGRATIONS', MIGRATIONS[:-1]): migrate(db)
|
||||
db.execute('PRAGMA foreign_keys=OFF')
|
||||
with db: db.execute("INSERT INTO audit_log(actor_user_id,actor_username,action,created_at) VALUES(99,'former-employee','history',?)",(utc_now(),))
|
||||
db.execute('PRAGMA foreign_keys=ON')
|
||||
before=[tuple(r) for r in db.execute('PRAGMA foreign_key_check')]
|
||||
self.assertEqual(len(before),1)
|
||||
migrate(db)
|
||||
self.assertEqual([tuple(r) for r in db.execute('PRAGMA foreign_key_check')],before)
|
||||
self.assertEqual(db.execute('SELECT actor_username FROM audit_log').fetchone()[0],'former-employee')
|
||||
|
||||
def test_upgrade_keeps_ids_passwords_sessions_and_audit_history(self):
|
||||
db=connect(':memory:')
|
||||
self.addCleanup(db.close)
|
||||
with patch('bank_importer.db.MIGRATIONS', MIGRATIONS[:-1]): migrate(db)
|
||||
now=utc_now()
|
||||
with db:
|
||||
db.execute('INSERT INTO companies(id,name,created_at,updated_at) VALUES(7,?,?,?)',('历史公司',now,now))
|
||||
db.execute("INSERT INTO users(id,username,password_hash,role,company_id,created_at,updated_at) VALUES(9,'old','unchanged','company',7,?,?)",(now,now))
|
||||
db.execute("INSERT INTO audit_log(actor_user_id,actor_username,action,created_at) VALUES(9,'old','history',?)",(now,))
|
||||
token=auth.create_session(db,9)
|
||||
migrate(db)
|
||||
self.assertEqual(auth.resolve_session(db,token)['id'],9)
|
||||
self.assertEqual(db.execute('SELECT password_hash FROM users WHERE id=9').fetchone()[0],'unchanged')
|
||||
self.assertEqual(company_access.companies_for(db,9),[{'id':7,'name':'历史公司'}])
|
||||
self.assertEqual(db.execute('PRAGMA foreign_key_check').fetchall(),[])
|
||||
self.assertEqual(migrate(db),[])
|
||||
@@ -1,500 +0,0 @@
|
||||
"""HTTP tests for company intercompany events list + CSV export (HEL-176).
|
||||
|
||||
Covers combined filters, keyset pagination, empty state, lateral access,
|
||||
forged company_id, ID guessing, export isolation and audit logging.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
|
||||
from openpyxl import Workbook
|
||||
|
||||
from bank_importer.db import connect, migrate
|
||||
|
||||
import server
|
||||
from test_server_auth import Client, as_json
|
||||
|
||||
BOOTSTRAP_PASSWORD = "BootAdmin123"
|
||||
ADMIN_PASSWORD = "AdminPass123"
|
||||
CASHIER_PASSWORD = "Cashier123"
|
||||
|
||||
CCB_HEADER = [
|
||||
"客户账号", "账户名称", "交易时间", "借方发生额(支取)", "贷方发生额(收入)",
|
||||
"余额", "币种", "对方户名", "对方账号", "对方开户机构", "摘要", "备注",
|
||||
]
|
||||
|
||||
ACCOUNT_A = "6222000000000001"
|
||||
ACCOUNT_B = "6222000000000002"
|
||||
ACCOUNT_C = "6222000000000003"
|
||||
|
||||
|
||||
def workbook_bytes(rows) -> bytes:
|
||||
workbook = Workbook()
|
||||
sheet = workbook.active
|
||||
sheet.title = "正常流水"
|
||||
sheet.append(CCB_HEADER)
|
||||
for row in rows:
|
||||
sheet.append(row)
|
||||
buffer = io.BytesIO()
|
||||
workbook.save(buffer)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def outgoing(own: str, cp: str, amount: str, at: str = "2026-01-05 10:00:00"):
|
||||
return [own, "测试公司", at, amount, "", "50000.00", "RMB", "对方", cp, "某银行", "货款", ""]
|
||||
|
||||
|
||||
def incoming(own: str, cp: str, amount: str, at: str = "2026-01-05 11:00:00"):
|
||||
return [own, "测试公司", at, "", amount, "50000.00", "RMB", "对方", cp, "某银行", "收款", ""]
|
||||
|
||||
|
||||
class CompanyIntercompanyEventsTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.temp_dir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp_dir.cleanup)
|
||||
root = Path(self.temp_dir.name)
|
||||
self.db_path = root / "app.db"
|
||||
self.storage = root / "files"
|
||||
|
||||
self._old_db_path = server.DB_PATH
|
||||
self._old_storage = server.STORAGE_DIR
|
||||
server.DB_PATH = self.db_path
|
||||
server.STORAGE_DIR = self.storage
|
||||
|
||||
os.environ["APP_BOOTSTRAP_ADMIN_PASSWORD"] = BOOTSTRAP_PASSWORD
|
||||
connection = connect(self.db_path)
|
||||
migrate(connection)
|
||||
assert server.ensure_bootstrap_admin(connection) is None
|
||||
connection.close()
|
||||
|
||||
class QuietHandler(server.AppHandler):
|
||||
def log_message(self, *args) -> None:
|
||||
pass
|
||||
|
||||
self.httpd = server.ThreadingHTTPServer(("127.0.0.1", 0), QuietHandler)
|
||||
self.port = self.httpd.server_address[1]
|
||||
self.thread = threading.Thread(target=self.httpd.serve_forever, daemon=True)
|
||||
self.thread.start()
|
||||
|
||||
self.admin = Client("127.0.0.1", self.port)
|
||||
status, _, data = self.admin.post_json(
|
||||
"/api/login",
|
||||
{"username": "group-admin", "password": BOOTSTRAP_PASSWORD, "portal": "admin"},
|
||||
)
|
||||
assert status == 200, data
|
||||
status, _, data = self.admin.post_json(
|
||||
"/api/password/change",
|
||||
{"old_password": BOOTSTRAP_PASSWORD, "new_password": ADMIN_PASSWORD},
|
||||
)
|
||||
assert status == 200, data
|
||||
|
||||
self.initial_passwords: dict[str, str] = {}
|
||||
self.company_a = self._create_company("甲公司", "cashier-a")
|
||||
self.company_b = self._create_company("乙公司", "cashier-b")
|
||||
self.company_c = self._create_company("丙公司", "cashier-c")
|
||||
self.cashier_a = self._login_company("cashier-a")
|
||||
self.cashier_b = self._login_company("cashier-b")
|
||||
self.cashier_c = self._login_company("cashier-c")
|
||||
|
||||
self._approve_account(self.company_a, ACCOUNT_A, self.cashier_a)
|
||||
self._approve_account(self.company_b, ACCOUNT_B, self.cashier_b)
|
||||
self._approve_account(self.company_c, ACCOUNT_C, self.cashier_c)
|
||||
|
||||
def tearDown(self) -> None:
|
||||
self.httpd.shutdown()
|
||||
self.httpd.server_close()
|
||||
server.DB_PATH = self._old_db_path
|
||||
server.STORAGE_DIR = self._old_storage
|
||||
os.environ.pop("APP_BOOTSTRAP_ADMIN_PASSWORD", None)
|
||||
|
||||
def _create_company(self, name: str, username: str) -> int:
|
||||
status, _, data = self.admin.post_json(
|
||||
"/api/admin/companies", {"name": name, "username": username}
|
||||
)
|
||||
assert status == 200, data
|
||||
self.initial_passwords[username] = as_json(data)["initial_password"]
|
||||
return as_json(data)["company_id"]
|
||||
|
||||
def _login_company(self, username: str) -> Client:
|
||||
client = Client("127.0.0.1", self.port)
|
||||
initial = self.initial_passwords[username]
|
||||
status, _, data = client.post_json(
|
||||
"/api/login", {"username": username, "password": initial, "portal": "company"}
|
||||
)
|
||||
assert status == 200, data
|
||||
status, _, data = client.post_json(
|
||||
"/api/password/change",
|
||||
{"old_password": initial, "new_password": CASHIER_PASSWORD},
|
||||
)
|
||||
assert status == 200, data
|
||||
return client
|
||||
|
||||
def _approve_account(self, company_id: int, number: str, client: Client) -> int:
|
||||
status, _, data = client.post_json(
|
||||
"/api/company/accounts",
|
||||
{
|
||||
"bank_name": "中信银行",
|
||||
"account_type": "基本户",
|
||||
"account_number": number,
|
||||
"start_date": "2026-01-01",
|
||||
},
|
||||
)
|
||||
assert status == 200, data
|
||||
account_id = as_json(data)["account"]["id"]
|
||||
status, _, data = self.admin.post_json(
|
||||
f"/api/admin/accounts/{account_id}/review",
|
||||
{
|
||||
"decision": "approve",
|
||||
"reason": "测试启用",
|
||||
"effective_from": "2026-01-01",
|
||||
},
|
||||
)
|
||||
assert status == 200, data
|
||||
return account_id
|
||||
|
||||
def _upload_and_confirm(self, client: Client, company_id: int, rows) -> int:
|
||||
content = workbook_bytes(rows)
|
||||
status, _, data = self.admin.post_multipart(
|
||||
"/api/parse", {"company_id": str(company_id)}, "账单.xlsx", content
|
||||
)
|
||||
assert status == 200, data
|
||||
batch_id = as_json(data)["batch_id"]
|
||||
status, _, data = client.get(f"/api/batches/{batch_id}/sheets")
|
||||
names = [s["sheet_name"] for s in as_json(data)["sheets"] if s["outcome"] == "parsed"]
|
||||
status, _, data = client.post_json(
|
||||
f"/api/batches/{batch_id}/confirm", {"sheets": names}
|
||||
)
|
||||
assert status == 200, data
|
||||
return batch_id
|
||||
|
||||
def _lock_single(self, amount: str, at: str = "2026-03-01 10:00:00") -> dict:
|
||||
self._upload_and_confirm(
|
||||
self.cashier_a,
|
||||
self.company_a,
|
||||
[outgoing(ACCOUNT_A, ACCOUNT_B, amount, at)],
|
||||
)
|
||||
status, _, data = self.admin.get("/api/admin/transfer-events")
|
||||
self.assertEqual(200, status, data)
|
||||
single = next(
|
||||
e
|
||||
for e in as_json(data)["events"]
|
||||
if e["status"] == "internal_single" and e["amount"] == amount
|
||||
)
|
||||
status, _, data = self.admin.get(f"/api/admin/transfer-events/{single['event_id']}")
|
||||
self.assertEqual(200, status, data)
|
||||
revision = as_json(data)["event"]["revision"]
|
||||
status, _, data = self.admin.post_json(
|
||||
f"/api/admin/transfer-events/{single['event_id']}/decisions",
|
||||
{
|
||||
"action": "assign_participant",
|
||||
"reason": "函证确认",
|
||||
"expected_revision": revision,
|
||||
"request_key": f"lock-{amount}-{at}",
|
||||
"participant": {"role": "payee", "company_id": self.company_b},
|
||||
},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
return as_json(data)["decision"]
|
||||
|
||||
def _seed_mixed(self) -> None:
|
||||
"""Paired A→B 100, B→A 40, locked A→B 25, pending A→B 7, B→C 200."""
|
||||
self._upload_and_confirm(
|
||||
self.cashier_a, self.company_a,
|
||||
[outgoing(ACCOUNT_A, ACCOUNT_B, "100.00", "2026-01-05 10:00:00")],
|
||||
)
|
||||
self._upload_and_confirm(
|
||||
self.cashier_b, self.company_b,
|
||||
[incoming(ACCOUNT_B, ACCOUNT_A, "100.00", "2026-01-05 11:00:00")],
|
||||
)
|
||||
self._upload_and_confirm(
|
||||
self.cashier_b, self.company_b,
|
||||
[outgoing(ACCOUNT_B, ACCOUNT_A, "40.00", "2026-01-10 10:00:00")],
|
||||
)
|
||||
self._upload_and_confirm(
|
||||
self.cashier_a, self.company_a,
|
||||
[incoming(ACCOUNT_A, ACCOUNT_B, "40.00", "2026-01-10 11:00:00")],
|
||||
)
|
||||
self._lock_single("25.00", "2026-02-01 10:00:00")
|
||||
self._upload_and_confirm(
|
||||
self.cashier_a, self.company_a,
|
||||
[outgoing(ACCOUNT_A, ACCOUNT_B, "7.00", "2026-02-15 10:00:00")],
|
||||
)
|
||||
self._upload_and_confirm(
|
||||
self.cashier_b, self.company_b,
|
||||
[outgoing(ACCOUNT_B, ACCOUNT_C, "200.00", "2026-01-20 10:00:00")],
|
||||
)
|
||||
self._upload_and_confirm(
|
||||
self.cashier_c, self.company_c,
|
||||
[incoming(ACCOUNT_C, ACCOUNT_B, "200.00", "2026-01-20 11:00:00")],
|
||||
)
|
||||
|
||||
def _events(self, client: Client, query: str = "from=2026-01-01&to=2026-12-31"):
|
||||
status, _, data = client.get(f"/api/company/intercompany/events?{query}")
|
||||
return status, as_json(data) if data else {}
|
||||
|
||||
def _export(self, client: Client, query: str = "from=2026-01-01&to=2026-12-31"):
|
||||
return client.get(f"/api/company/intercompany/export.csv?{query}")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Auth / parameter guards
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_requires_company_role(self) -> None:
|
||||
status, payload = self._events(self.admin)
|
||||
self.assertEqual(403, status, payload)
|
||||
|
||||
def test_rejects_forged_company_id_on_events_and_export(self) -> None:
|
||||
status, payload = self._events(
|
||||
self.cashier_a,
|
||||
f"from=2026-01-01&to=2026-12-31&company_id={self.company_b}",
|
||||
)
|
||||
self.assertEqual(400, status, payload)
|
||||
|
||||
status, _, data = self._export(
|
||||
self.cashier_a,
|
||||
f"from=2026-01-01&to=2026-12-31&company_id={self.company_a}",
|
||||
)
|
||||
self.assertEqual(400, status, data)
|
||||
|
||||
def test_rejects_bad_filters(self) -> None:
|
||||
status, payload = self._events(
|
||||
self.cashier_a, "from=2026-01-01&to=2026-12-31&direction=sideways"
|
||||
)
|
||||
self.assertEqual(400, status, payload)
|
||||
status, payload = self._events(
|
||||
self.cashier_a, "from=2026-01-01&to=2026-12-31&state=maybe"
|
||||
)
|
||||
self.assertEqual(400, status, payload)
|
||||
status, payload = self._events(
|
||||
self.cashier_a, "from=2026-13-40&to=2026-12-31"
|
||||
)
|
||||
self.assertEqual(400, status, payload)
|
||||
|
||||
def test_empty_window(self) -> None:
|
||||
status, payload = self._events(self.cashier_a)
|
||||
self.assertEqual(200, status, payload)
|
||||
self.assertEqual([], payload["events"])
|
||||
self.assertFalse(payload["has_more"])
|
||||
self.assertIsNone(payload["next_cursor"])
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Combined filters + confirmed/pending separation
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_combined_filters_and_state_split(self) -> None:
|
||||
self._seed_mixed()
|
||||
|
||||
status, payload = self._events(self.cashier_a)
|
||||
self.assertEqual(200, status, payload)
|
||||
events = payload["events"]
|
||||
# A sees: out 100, in 40, locked out 25, pending out 7 — not B↔C 200
|
||||
self.assertEqual(4, len(events))
|
||||
amounts = {e["amount"] for e in events}
|
||||
self.assertEqual({"100.00", "40.00", "25.00", "7.00"}, amounts)
|
||||
for event in events:
|
||||
self.assertNotEqual(self.company_c, event["counterparty_company_id"])
|
||||
self.assertIn(event["state"], ("confirmed", "pending"))
|
||||
self.assertIn(event["direction"], ("out", "in"))
|
||||
|
||||
status, confirmed = self._events(
|
||||
self.cashier_a, "from=2026-01-01&to=2026-12-31&state=confirmed"
|
||||
)
|
||||
self.assertEqual(200, status, confirmed)
|
||||
self.assertEqual(3, len(confirmed["events"]))
|
||||
self.assertTrue(all(e["state"] == "confirmed" for e in confirmed["events"]))
|
||||
self.assertNotIn("7.00", {e["amount"] for e in confirmed["events"]})
|
||||
|
||||
status, pending = self._events(
|
||||
self.cashier_a, "from=2026-01-01&to=2026-12-31&state=pending"
|
||||
)
|
||||
self.assertEqual(200, status, pending)
|
||||
self.assertEqual(1, len(pending["events"]))
|
||||
self.assertEqual("7.00", pending["events"][0]["amount"])
|
||||
self.assertEqual("pending", pending["events"][0]["state"])
|
||||
|
||||
status, outs = self._events(
|
||||
self.cashier_a, "from=2026-01-01&to=2026-12-31&direction=out&state=confirmed"
|
||||
)
|
||||
self.assertEqual(200, status, outs)
|
||||
self.assertEqual({"100.00", "25.00"}, {e["amount"] for e in outs["events"]})
|
||||
self.assertTrue(all(e["direction"] == "out" for e in outs["events"]))
|
||||
|
||||
status, by_cp = self._events(
|
||||
self.cashier_a,
|
||||
f"from=2026-01-01&to=2026-12-31&counterparty_id={self.company_b}&state=confirmed",
|
||||
)
|
||||
self.assertEqual(200, status, by_cp)
|
||||
self.assertEqual(3, len(by_cp["events"]))
|
||||
|
||||
# Date window excludes Feb locked/pending
|
||||
status, jan = self._events(
|
||||
self.cashier_a, "from=2026-01-01&to=2026-01-31&state=confirmed"
|
||||
)
|
||||
self.assertEqual(200, status, jan)
|
||||
self.assertEqual({"100.00", "40.00"}, {e["amount"] for e in jan["events"]})
|
||||
|
||||
def test_keyset_pagination_no_dup_no_gap(self) -> None:
|
||||
# Three confirmed A→B outs on distinct days
|
||||
for i, amount in enumerate(("11.00", "12.00", "13.00", "14.00", "15.00")):
|
||||
day = 5 + i
|
||||
self._upload_and_confirm(
|
||||
self.cashier_a, self.company_a,
|
||||
[outgoing(ACCOUNT_A, ACCOUNT_B, amount, f"2026-01-{day:02d} 10:00:00")],
|
||||
)
|
||||
self._upload_and_confirm(
|
||||
self.cashier_b, self.company_b,
|
||||
[incoming(ACCOUNT_B, ACCOUNT_A, amount, f"2026-01-{day:02d} 11:00:00")],
|
||||
)
|
||||
|
||||
status, page1 = self._events(
|
||||
self.cashier_a,
|
||||
"from=2026-01-01&to=2026-12-31&state=confirmed&direction=out&limit=2",
|
||||
)
|
||||
self.assertEqual(200, status, page1)
|
||||
self.assertEqual(2, len(page1["events"]))
|
||||
self.assertTrue(page1["has_more"])
|
||||
self.assertIsNotNone(page1["next_cursor"])
|
||||
|
||||
status, page2 = self._events(
|
||||
self.cashier_a,
|
||||
"from=2026-01-01&to=2026-12-31&state=confirmed&direction=out"
|
||||
f"&limit=2&cursor={page1['next_cursor']}",
|
||||
)
|
||||
self.assertEqual(200, status, page2)
|
||||
self.assertEqual(2, len(page2["events"]))
|
||||
self.assertTrue(page2["has_more"])
|
||||
|
||||
status, page3 = self._events(
|
||||
self.cashier_a,
|
||||
"from=2026-01-01&to=2026-12-31&state=confirmed&direction=out"
|
||||
f"&limit=2&cursor={page2['next_cursor']}",
|
||||
)
|
||||
self.assertEqual(200, status, page3)
|
||||
self.assertEqual(1, len(page3["events"]))
|
||||
self.assertFalse(page3["has_more"])
|
||||
self.assertIsNone(page3["next_cursor"])
|
||||
|
||||
ids = [e["event_id"] for e in page1["events"] + page2["events"] + page3["events"]]
|
||||
self.assertEqual(5, len(ids))
|
||||
self.assertEqual(len(ids), len(set(ids)))
|
||||
# Descending by effective_at then event_id
|
||||
amounts = [e["amount"] for e in page1["events"] + page2["events"] + page3["events"]]
|
||||
self.assertEqual(["15.00", "14.00", "13.00", "12.00", "11.00"], amounts)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Isolation / ID guess / detail reuse
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_lateral_isolation_and_id_guess_404(self) -> None:
|
||||
self._seed_mixed()
|
||||
|
||||
status, payload_a = self._events(self.cashier_a)
|
||||
self.assertEqual(200, status, payload_a)
|
||||
a_ids = {e["event_id"] for e in payload_a["events"]}
|
||||
|
||||
status, payload_c = self._events(self.cashier_c)
|
||||
self.assertEqual(200, status, payload_c)
|
||||
# C only participates in B↔C 200
|
||||
self.assertTrue(payload_c["events"])
|
||||
for event in payload_c["events"]:
|
||||
self.assertEqual("200.00", event["amount"])
|
||||
self.assertNotIn(event["event_id"], a_ids)
|
||||
|
||||
# C guessing A's event id via transfer-events detail → 404
|
||||
a_event_id = next(iter(a_ids))
|
||||
status, _, data = self.cashier_c.get(
|
||||
f"/api/company/transfer-events/{a_event_id}"
|
||||
)
|
||||
self.assertEqual(404, status, data)
|
||||
|
||||
# A can open own event; counterparty account masked; only own observations
|
||||
status, _, data = self.cashier_a.get(
|
||||
f"/api/company/transfer-events/{a_event_id}"
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
detail = as_json(data)["event"]
|
||||
if detail.get("counterparty") and "account_number_masked" in detail["counterparty"]:
|
||||
masked = detail["counterparty"]["account_number_masked"]
|
||||
self.assertTrue(str(masked).startswith("****"))
|
||||
self.assertNotIn(ACCOUNT_B, masked)
|
||||
for obs in detail["observations"]:
|
||||
self.assertEqual(self.company_a, obs["batch_company_id"])
|
||||
self.assertNotIn(ACCOUNT_B, json.dumps(obs, ensure_ascii=False))
|
||||
|
||||
# Filtering by counterparty C still cannot leak B↔C into A's list
|
||||
status, filtered = self._events(
|
||||
self.cashier_a,
|
||||
f"from=2026-01-01&to=2026-12-31&counterparty_id={self.company_c}",
|
||||
)
|
||||
self.assertEqual(200, status, filtered)
|
||||
self.assertEqual([], filtered["events"])
|
||||
|
||||
def test_b44_events_path_still_works_with_cutoff(self) -> None:
|
||||
# Without HEL-176 discriminators, /events stays on B-44 ledger list.
|
||||
status, _, data = self.cashier_a.get(
|
||||
"/api/company/intercompany/events?from=2026-01-01&cutoff=2026-12-31"
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
payload = as_json(data)
|
||||
self.assertIn("items", payload)
|
||||
self.assertNotIn("events", payload)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Export: confirmed only + audit + isolation
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_export_confirmed_only_isolated_and_audited(self) -> None:
|
||||
self._seed_mixed()
|
||||
|
||||
status, headers, data = self._export(self.cashier_a)
|
||||
self.assertEqual(200, status, data)
|
||||
self.assertEqual("text/csv; charset=utf-8", headers.get("content-type"))
|
||||
text = data.decode("utf-8-sig")
|
||||
lines = [line for line in text.splitlines() if line]
|
||||
self.assertGreaterEqual(len(lines), 2)
|
||||
body = "\n".join(lines[1:])
|
||||
self.assertIn("100.00", body)
|
||||
self.assertIn("40.00", body)
|
||||
self.assertIn("25.00", body)
|
||||
self.assertNotIn("7.00", body) # pending excluded
|
||||
self.assertNotIn("200.00", body) # B↔C excluded
|
||||
|
||||
# Explicit pending state rejected
|
||||
status, _, data = self._export(
|
||||
self.cashier_a, "from=2026-01-01&to=2026-12-31&state=pending"
|
||||
)
|
||||
self.assertEqual(400, status, data)
|
||||
|
||||
# C export must not contain A's amounts
|
||||
status, _, data = self._export(self.cashier_c)
|
||||
self.assertEqual(200, status, data)
|
||||
text_c = data.decode("utf-8-sig")
|
||||
self.assertNotIn("100.00", text_c)
|
||||
self.assertNotIn("25.00", text_c)
|
||||
self.assertIn("200.00", text_c)
|
||||
|
||||
status, _, data = self.admin.get("/api/admin/audit-log?limit=50")
|
||||
self.assertEqual(200, status, data)
|
||||
actions = [row["action"] for row in as_json(data)["entries"]]
|
||||
self.assertIn("export_intercompany_csv", actions)
|
||||
export_rows = [
|
||||
row
|
||||
for row in as_json(data)["entries"]
|
||||
if row["action"] == "export_intercompany_csv"
|
||||
]
|
||||
self.assertTrue(export_rows)
|
||||
self.assertTrue(
|
||||
any(f"company:{self.company_a}" == row.get("target") for row in export_rows)
|
||||
)
|
||||
self.assertTrue(any("state:confirmed" in (row.get("detail") or "") for row in export_rows))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,362 +0,0 @@
|
||||
"""HTTP tests for GET /api/company/intercompany/summary (HEL-175).
|
||||
|
||||
Covers session-scoped company_id, forged company_id rejection, confirmed vs
|
||||
pending separation, Decimal net math, dual-company isolation and empty data.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
|
||||
from openpyxl import Workbook
|
||||
|
||||
from bank_importer.db import connect, migrate
|
||||
|
||||
import server
|
||||
from test_server_auth import Client, as_json
|
||||
|
||||
BOOTSTRAP_PASSWORD = "BootAdmin123"
|
||||
ADMIN_PASSWORD = "AdminPass123"
|
||||
CASHIER_PASSWORD = "Cashier123"
|
||||
|
||||
CCB_HEADER = [
|
||||
"客户账号", "账户名称", "交易时间", "借方发生额(支取)", "贷方发生额(收入)",
|
||||
"余额", "币种", "对方户名", "对方账号", "对方开户机构", "摘要", "备注",
|
||||
]
|
||||
|
||||
ACCOUNT_A = "6222000000000001"
|
||||
ACCOUNT_B = "6222000000000002"
|
||||
ACCOUNT_C = "6222000000000003"
|
||||
|
||||
|
||||
def workbook_bytes(rows) -> bytes:
|
||||
workbook = Workbook()
|
||||
sheet = workbook.active
|
||||
sheet.title = "正常流水"
|
||||
sheet.append(CCB_HEADER)
|
||||
for row in rows:
|
||||
sheet.append(row)
|
||||
buffer = io.BytesIO()
|
||||
workbook.save(buffer)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def outgoing(own: str, cp: str, amount: str, at: str = "2026-01-05 10:00:00"):
|
||||
return [own, "测试公司", at, amount, "", "50000.00", "RMB", "对方", cp, "某银行", "货款", ""]
|
||||
|
||||
|
||||
def incoming(own: str, cp: str, amount: str, at: str = "2026-01-05 11:00:00"):
|
||||
return [own, "测试公司", at, "", amount, "50000.00", "RMB", "对方", cp, "某银行", "收款", ""]
|
||||
|
||||
|
||||
class CompanyIntercompanySummaryTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.temp_dir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp_dir.cleanup)
|
||||
root = Path(self.temp_dir.name)
|
||||
self.db_path = root / "app.db"
|
||||
self.storage = root / "files"
|
||||
|
||||
self._old_db_path = server.DB_PATH
|
||||
self._old_storage = server.STORAGE_DIR
|
||||
server.DB_PATH = self.db_path
|
||||
server.STORAGE_DIR = self.storage
|
||||
|
||||
os.environ["APP_BOOTSTRAP_ADMIN_PASSWORD"] = BOOTSTRAP_PASSWORD
|
||||
connection = connect(self.db_path)
|
||||
migrate(connection)
|
||||
assert server.ensure_bootstrap_admin(connection) is None
|
||||
connection.close()
|
||||
|
||||
class QuietHandler(server.AppHandler):
|
||||
def log_message(self, *args) -> None:
|
||||
pass
|
||||
|
||||
self.httpd = server.ThreadingHTTPServer(("127.0.0.1", 0), QuietHandler)
|
||||
self.port = self.httpd.server_address[1]
|
||||
self.thread = threading.Thread(target=self.httpd.serve_forever, daemon=True)
|
||||
self.thread.start()
|
||||
|
||||
self.admin = Client("127.0.0.1", self.port)
|
||||
status, _, data = self.admin.post_json(
|
||||
"/api/login",
|
||||
{"username": "group-admin", "password": BOOTSTRAP_PASSWORD, "portal": "admin"},
|
||||
)
|
||||
assert status == 200, data
|
||||
status, _, data = self.admin.post_json(
|
||||
"/api/password/change",
|
||||
{"old_password": BOOTSTRAP_PASSWORD, "new_password": ADMIN_PASSWORD},
|
||||
)
|
||||
assert status == 200, data
|
||||
|
||||
self.initial_passwords: dict[str, str] = {}
|
||||
self.company_a = self._create_company("甲公司", "cashier-a")
|
||||
self.company_b = self._create_company("乙公司", "cashier-b")
|
||||
self.company_c = self._create_company("丙公司", "cashier-c")
|
||||
self.cashier_a = self._login_company("cashier-a")
|
||||
self.cashier_b = self._login_company("cashier-b")
|
||||
self.cashier_c = self._login_company("cashier-c")
|
||||
|
||||
self._approve_account(self.company_a, ACCOUNT_A, self.cashier_a)
|
||||
self._approve_account(self.company_b, ACCOUNT_B, self.cashier_b)
|
||||
self._approve_account(self.company_c, ACCOUNT_C, self.cashier_c)
|
||||
|
||||
def tearDown(self) -> None:
|
||||
self.httpd.shutdown()
|
||||
self.httpd.server_close()
|
||||
server.DB_PATH = self._old_db_path
|
||||
server.STORAGE_DIR = self._old_storage
|
||||
os.environ.pop("APP_BOOTSTRAP_ADMIN_PASSWORD", None)
|
||||
|
||||
def _create_company(self, name: str, username: str) -> int:
|
||||
status, _, data = self.admin.post_json(
|
||||
"/api/admin/companies", {"name": name, "username": username}
|
||||
)
|
||||
assert status == 200, data
|
||||
self.initial_passwords[username] = as_json(data)["initial_password"]
|
||||
return as_json(data)["company_id"]
|
||||
|
||||
def _login_company(self, username: str) -> Client:
|
||||
client = Client("127.0.0.1", self.port)
|
||||
initial = self.initial_passwords[username]
|
||||
status, _, data = client.post_json(
|
||||
"/api/login", {"username": username, "password": initial, "portal": "company"}
|
||||
)
|
||||
assert status == 200, data
|
||||
status, _, data = client.post_json(
|
||||
"/api/password/change",
|
||||
{"old_password": initial, "new_password": CASHIER_PASSWORD},
|
||||
)
|
||||
assert status == 200, data
|
||||
return client
|
||||
|
||||
def _approve_account(self, company_id: int, number: str, client: Client) -> int:
|
||||
status, _, data = client.post_json(
|
||||
"/api/company/accounts",
|
||||
{
|
||||
"bank_name": "中信银行",
|
||||
"account_type": "基本户",
|
||||
"account_number": number,
|
||||
"start_date": "2026-01-01",
|
||||
},
|
||||
)
|
||||
assert status == 200, data
|
||||
account_id = as_json(data)["account"]["id"]
|
||||
status, _, data = self.admin.post_json(
|
||||
f"/api/admin/accounts/{account_id}/review",
|
||||
{
|
||||
"decision": "approve",
|
||||
"reason": "测试启用",
|
||||
"effective_from": "2026-01-01",
|
||||
},
|
||||
)
|
||||
assert status == 200, data
|
||||
return account_id
|
||||
|
||||
def _upload_and_confirm(self, client: Client, company_id: int, rows) -> int:
|
||||
content = workbook_bytes(rows)
|
||||
status, _, data = self.admin.post_multipart(
|
||||
"/api/parse", {"company_id": str(company_id)}, "账单.xlsx", content
|
||||
)
|
||||
assert status == 200, data
|
||||
batch_id = as_json(data)["batch_id"]
|
||||
status, _, data = client.get(f"/api/batches/{batch_id}/sheets")
|
||||
names = [s["sheet_name"] for s in as_json(data)["sheets"] if s["outcome"] == "parsed"]
|
||||
status, _, data = client.post_json(
|
||||
f"/api/batches/{batch_id}/confirm", {"sheets": names}
|
||||
)
|
||||
assert status == 200, data
|
||||
return batch_id
|
||||
|
||||
def _lock_single(self, amount: str, at: str = "2026-03-01 10:00:00") -> dict:
|
||||
"""A-side only upload → admin locks as intercompany single."""
|
||||
self._upload_and_confirm(
|
||||
self.cashier_a,
|
||||
self.company_a,
|
||||
[outgoing(ACCOUNT_A, ACCOUNT_B, amount, at)],
|
||||
)
|
||||
status, _, data = self.admin.get("/api/admin/transfer-events")
|
||||
self.assertEqual(200, status, data)
|
||||
single = next(
|
||||
e
|
||||
for e in as_json(data)["events"]
|
||||
if e["status"] == "internal_single" and e["amount"] == amount
|
||||
)
|
||||
status, _, data = self.admin.get(f"/api/admin/transfer-events/{single['event_id']}")
|
||||
self.assertEqual(200, status, data)
|
||||
revision = as_json(data)["event"]["revision"]
|
||||
status, _, data = self.admin.post_json(
|
||||
f"/api/admin/transfer-events/{single['event_id']}/decisions",
|
||||
{
|
||||
"action": "assign_participant",
|
||||
"reason": "函证确认",
|
||||
"expected_revision": revision,
|
||||
"request_key": f"lock-{amount}-{at}",
|
||||
"participant": {"role": "payee", "company_id": self.company_b},
|
||||
},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
return as_json(data)["decision"]
|
||||
|
||||
def _summary(self, client: Client, query: str = "as_of=2026-12-31"):
|
||||
status, _, data = client.get(f"/api/company/intercompany/summary?{query}")
|
||||
return status, as_json(data) if data else {}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Auth / parameter guards
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_requires_company_role(self) -> None:
|
||||
status, payload = self._summary(self.admin)
|
||||
self.assertEqual(403, status, payload)
|
||||
|
||||
def test_rejects_forged_company_id(self) -> None:
|
||||
status, payload = self._summary(
|
||||
self.cashier_a, f"as_of=2026-12-31&company_id={self.company_b}"
|
||||
)
|
||||
self.assertEqual(400, status, payload)
|
||||
self.assertIn("company_id", payload.get("message", ""))
|
||||
|
||||
def test_rejects_own_company_id_param(self) -> None:
|
||||
# Even matching the session company is forbidden.
|
||||
status, payload = self._summary(
|
||||
self.cashier_a, f"as_of=2026-12-31&company_id={self.company_a}"
|
||||
)
|
||||
self.assertEqual(400, status, payload)
|
||||
|
||||
def test_rejects_bad_as_of(self) -> None:
|
||||
status, payload = self._summary(self.cashier_a, "as_of=2026-13-40")
|
||||
self.assertEqual(400, status, payload)
|
||||
|
||||
def test_anonymous_is_unauthorized(self) -> None:
|
||||
anon = Client("127.0.0.1", self.port)
|
||||
status, _, data = anon.get("/api/company/intercompany/summary?as_of=2026-12-31")
|
||||
self.assertIn(status, (401, 403))
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Empty / confirmed math / pending isolation
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_empty_window_returns_zeros(self) -> None:
|
||||
status, payload = self._summary(self.cashier_a)
|
||||
self.assertEqual(200, status, payload)
|
||||
self.assertEqual(self.company_a, payload["own_company"]["id"])
|
||||
self.assertFalse(payload["window"]["has_opening"])
|
||||
self.assertIsNone(payload["window"]["opening"])
|
||||
self.assertEqual("0.00", payload["confirmed"]["outflow_total"])
|
||||
self.assertEqual("0.00", payload["confirmed"]["inflow_total"])
|
||||
self.assertEqual("0.00", payload["confirmed"]["net_change"])
|
||||
self.assertEqual(0, payload["pending"]["count"])
|
||||
self.assertEqual([], payload["counterparties"])
|
||||
# Amounts must be strings, never floats.
|
||||
self.assertIsInstance(payload["confirmed"]["net_change"], str)
|
||||
self.assertNotIsInstance(payload["confirmed"]["net_change"], float)
|
||||
|
||||
def test_paired_locked_pending_math_and_isolation(self) -> None:
|
||||
# Paired A→B 100 + B→A 40 → A net outflow 60
|
||||
self._upload_and_confirm(
|
||||
self.cashier_a, self.company_a,
|
||||
[outgoing(ACCOUNT_A, ACCOUNT_B, "100.00", "2026-01-05 10:00:00")],
|
||||
)
|
||||
self._upload_and_confirm(
|
||||
self.cashier_b, self.company_b,
|
||||
[incoming(ACCOUNT_B, ACCOUNT_A, "100.00", "2026-01-05 11:00:00")],
|
||||
)
|
||||
self._upload_and_confirm(
|
||||
self.cashier_b, self.company_b,
|
||||
[outgoing(ACCOUNT_B, ACCOUNT_A, "40.00", "2026-01-10 10:00:00")],
|
||||
)
|
||||
self._upload_and_confirm(
|
||||
self.cashier_a, self.company_a,
|
||||
[incoming(ACCOUNT_A, ACCOUNT_B, "40.00", "2026-01-10 11:00:00")],
|
||||
)
|
||||
|
||||
# Locked single A→B 25 (confirmed)
|
||||
self._lock_single("25.00", "2026-02-01 10:00:00")
|
||||
|
||||
# Pending unilateral A→B 7 (internal_single, not confirmed)
|
||||
self._upload_and_confirm(
|
||||
self.cashier_a, self.company_a,
|
||||
[outgoing(ACCOUNT_A, ACCOUNT_B, "7.00", "2026-02-15 10:00:00")],
|
||||
)
|
||||
|
||||
# B↔C paired 200 — must not appear in A's summary
|
||||
self._upload_and_confirm(
|
||||
self.cashier_b, self.company_b,
|
||||
[outgoing(ACCOUNT_B, ACCOUNT_C, "200.00", "2026-01-20 10:00:00")],
|
||||
)
|
||||
self._upload_and_confirm(
|
||||
self.cashier_c, self.company_c,
|
||||
[incoming(ACCOUNT_C, ACCOUNT_B, "200.00", "2026-01-20 11:00:00")],
|
||||
)
|
||||
|
||||
status, payload = self._summary(self.cashier_a)
|
||||
self.assertEqual(200, status, payload)
|
||||
|
||||
confirmed = payload["confirmed"]
|
||||
self.assertEqual("125.00", confirmed["outflow_total"]) # 100 + 25
|
||||
self.assertEqual(2, confirmed["outflow_count"])
|
||||
self.assertEqual("40.00", confirmed["inflow_total"])
|
||||
self.assertEqual(1, confirmed["inflow_count"])
|
||||
self.assertEqual("85.00", confirmed["net_change"]) # 125 - 40
|
||||
self.assertEqual("receivable", confirmed["net_direction"])
|
||||
|
||||
# Pending tip only — never folded into confirmed totals
|
||||
self.assertEqual(1, payload["pending"]["count"])
|
||||
self.assertEqual("7.00", payload["pending"]["amount_total"])
|
||||
|
||||
# Decimal identity: net = outflow - inflow, no float drift
|
||||
net = Decimal(confirmed["net_change"])
|
||||
self.assertEqual(
|
||||
Decimal(confirmed["outflow_total"]) - Decimal(confirmed["inflow_total"]),
|
||||
net,
|
||||
)
|
||||
|
||||
counterparties = {row["company_id"]: row for row in payload["counterparties"]}
|
||||
self.assertIn(self.company_b, counterparties)
|
||||
self.assertNotIn(self.company_c, counterparties)
|
||||
row_b = counterparties[self.company_b]
|
||||
self.assertEqual("125.00", row_b["confirmed_outflow"])
|
||||
self.assertEqual("40.00", row_b["confirmed_inflow"])
|
||||
self.assertEqual("85.00", row_b["net"])
|
||||
self.assertEqual(1, row_b["pending_count"])
|
||||
|
||||
# B must not see C-only? B sees C; A must not see B's C totals via forgery
|
||||
status_b, payload_b = self._summary(self.cashier_b)
|
||||
self.assertEqual(200, status_b, payload_b)
|
||||
cps_b = {row["company_id"] for row in payload_b["counterparties"]}
|
||||
self.assertIn(self.company_c, cps_b)
|
||||
# A's view still excludes C
|
||||
self.assertNotIn(self.company_c, counterparties)
|
||||
|
||||
# Same event counted once: eligible event count equals outflow+inflow counts
|
||||
self.assertEqual(
|
||||
confirmed["outflow_count"] + confirmed["inflow_count"],
|
||||
3,
|
||||
)
|
||||
|
||||
def test_company_b_cannot_see_a_only_pending(self) -> None:
|
||||
self._upload_and_confirm(
|
||||
self.cashier_a, self.company_a,
|
||||
[outgoing(ACCOUNT_A, ACCOUNT_B, "9.00", "2026-04-01 10:00:00")],
|
||||
)
|
||||
status_a, payload_a = self._summary(self.cashier_a)
|
||||
self.assertEqual(200, status_a, payload_a)
|
||||
self.assertEqual(1, payload_a["pending"]["count"])
|
||||
|
||||
status_c, payload_c = self._summary(self.cashier_c)
|
||||
self.assertEqual(200, status_c, payload_c)
|
||||
self.assertEqual(0, payload_c["pending"]["count"])
|
||||
self.assertEqual("0.00", payload_c["confirmed"]["outflow_total"])
|
||||
self.assertEqual([], payload_c["counterparties"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,140 +0,0 @@
|
||||
"""HEL-177: 公司端转账往来页面(方案 A)结构与接口契约。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import threading
|
||||
import unittest
|
||||
from functools import partial
|
||||
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
WEB = ROOT / "web"
|
||||
|
||||
try:
|
||||
from playwright.sync_api import sync_playwright
|
||||
except ImportError: # pragma: no cover
|
||||
sync_playwright = None
|
||||
|
||||
|
||||
class TransfersPageSourceContractTests(unittest.TestCase):
|
||||
def test_company_html_has_nav_overview_and_layers(self) -> None:
|
||||
html = (WEB / "company.html").read_text(encoding="utf-8")
|
||||
self.assertIn('data-view="transfers"', html)
|
||||
self.assertIn("转账往来", html)
|
||||
self.assertIn('id="workspaceTransfersCard"', html)
|
||||
self.assertIn("转账往来概览", html)
|
||||
self.assertIn('data-page="transfers"', html)
|
||||
self.assertIn('id="transfersOverviewLayer"', html)
|
||||
self.assertIn('id="transfersDetailLayer"', html)
|
||||
self.assertIn('id="transferEvidenceDrawer"', html)
|
||||
self.assertIn("期间净变动", html)
|
||||
self.assertNotIn("本公司往来合计", html)
|
||||
self.assertIn("design-system.css?v=14", html)
|
||||
self.assertIn("app.js?v=18", html)
|
||||
# 侧栏顺序:流水管理 → 转账往来 → 往来确认
|
||||
flows = html.index('data-view="flows"')
|
||||
transfers = html.index('data-view="transfers"')
|
||||
reconcile = html.index('data-view="reconcile"')
|
||||
self.assertLess(flows, transfers)
|
||||
self.assertLess(transfers, reconcile)
|
||||
|
||||
def test_app_js_wires_real_apis_no_demo_totals(self) -> None:
|
||||
js = (WEB / "app.js").read_text(encoding="utf-8")
|
||||
self.assertIn('transfers: "转账往来"', js)
|
||||
self.assertIn("/api/company/intercompany/summary", js)
|
||||
self.assertIn("/api/company/intercompany/events", js)
|
||||
self.assertIn("/api/company/intercompany/export.csv", js)
|
||||
self.assertIn("/api/company/transfer-events/", js)
|
||||
self.assertIn("function loadTransfersSummary", js)
|
||||
self.assertIn("function openTransfersDetail", js)
|
||||
self.assertIn("function openTransferEvidence", js)
|
||||
self.assertIn("function initTransfers", js)
|
||||
self.assertIn("initTransfers()", js)
|
||||
self.assertIn("期间净变动", js)
|
||||
self.assertIn("has_opening", js)
|
||||
self.assertNotIn("FLOW_DEMO", js)
|
||||
self.assertNotIn("COMPANY_FLOWS", js)
|
||||
self.assertNotIn("IMP-DEMO", js)
|
||||
self.assertNotIn("ledger-demo-manual-records", js)
|
||||
# 不得把「期末余额」写死为无期初时的标签
|
||||
self.assertNotRegex(js, r'netLabelForWindow[^{]+{[^}]*return "期末余额"')
|
||||
|
||||
def test_design_system_scopes_info_to_transfers_module(self) -> None:
|
||||
css = (WEB / "design-system.css").read_text(encoding="utf-8")
|
||||
self.assertIn('a[data-view="transfers"].active', css)
|
||||
self.assertIn("var(--info-soft)", css)
|
||||
self.assertIn('[data-page="transfers"] .btn-primary', css)
|
||||
self.assertIn(".xfer-split", css)
|
||||
self.assertIn(".xfer-split-pane.confirmed", css)
|
||||
self.assertIn(".xfer-split-pane.pending", css)
|
||||
# 无新色硬编码
|
||||
self.assertNotRegex(css, r"\.xfer-split[^\{]*\{[^}]*#[0-9a-fA-F]{3,8}")
|
||||
|
||||
|
||||
class TransfersDetailObservationContractTests(unittest.TestCase):
|
||||
def test_server_exposes_batch_fields_on_observations(self) -> None:
|
||||
server = (ROOT / "server.py").read_text(encoding="utf-8")
|
||||
self.assertIn("import_batch_id", server)
|
||||
self.assertIn("original_filename", server)
|
||||
self.assertIn("counterparty_account_masked", server)
|
||||
|
||||
|
||||
def _chromium_available() -> bool:
|
||||
try:
|
||||
import ctypes.util
|
||||
|
||||
return bool(ctypes.util.find_library("atk-1.0"))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
@unittest.skipUnless(sync_playwright, "playwright 未安装,跳过布局冒烟")
|
||||
@unittest.skipUnless(_chromium_available(), "系统缺少 chromium 依赖库(如 libatk),跳过布局冒烟")
|
||||
class TransfersPageLayoutSmokeTests(unittest.TestCase):
|
||||
"""静态壳:360 / 820 / 1440 无横向溢出。"""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
handler = partial(SimpleHTTPRequestHandler, directory=str(WEB))
|
||||
cls.httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
cls.port = cls.httpd.server_address[1]
|
||||
cls.thread = threading.Thread(target=cls.httpd.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
cls.base = f"http://127.0.0.1:{cls.port}"
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls) -> None:
|
||||
cls.httpd.shutdown()
|
||||
cls.httpd.server_close()
|
||||
|
||||
def test_transfers_shell_no_horizontal_overflow(self) -> None:
|
||||
html = (WEB / "company.html").read_text(encoding="utf-8")
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch()
|
||||
page = browser.new_page()
|
||||
for width in (360, 820, 1440):
|
||||
page.set_viewport_size({"width": width, "height": 900})
|
||||
page.route("**/app.js**", lambda route: route.abort())
|
||||
page.goto(f"{self.base}/company.html")
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
document.querySelectorAll('.app-view').forEach((el) => {
|
||||
el.classList.toggle('is-active', el.dataset.page === 'transfers');
|
||||
});
|
||||
const data = document.getElementById('transfersData');
|
||||
const loading = document.getElementById('transfersLoading');
|
||||
if (loading) loading.hidden = true;
|
||||
if (data) data.hidden = false;
|
||||
}"""
|
||||
)
|
||||
overflow = page.evaluate(
|
||||
"() => document.documentElement.scrollWidth > document.documentElement.clientWidth + 1"
|
||||
)
|
||||
self.assertFalse(overflow, f"{width}px 出现横向溢出")
|
||||
browser.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,313 +0,0 @@
|
||||
"""HEL-168: company workspace pending unilateral counts sync after confirm."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
|
||||
from openpyxl import Workbook
|
||||
|
||||
import server
|
||||
from test_server_auth import Client, as_json
|
||||
|
||||
BOOTSTRAP_PASSWORD = "BootAdmin123"
|
||||
ADMIN_PASSWORD = "AdminPass123"
|
||||
CASHIER_PASSWORD = "Cashier123"
|
||||
|
||||
CCB_HEADER = [
|
||||
"客户账号", "账户名称", "交易时间", "借方发生额(支取)", "贷方发生额(收入)",
|
||||
"余额", "币种", "对方户名", "对方账号", "对方开户机构", "摘要", "备注",
|
||||
]
|
||||
|
||||
ACCOUNT_A = "6222000000001001"
|
||||
ACCOUNT_B = "6222000000001002"
|
||||
|
||||
|
||||
def workbook_bytes(rows) -> bytes:
|
||||
workbook = Workbook()
|
||||
sheet = workbook.active
|
||||
sheet.title = "正常流水"
|
||||
sheet.append(CCB_HEADER)
|
||||
for row in rows:
|
||||
sheet.append(row)
|
||||
buffer = io.BytesIO()
|
||||
workbook.save(buffer)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def outgoing(own: str, cp: str, amount: str, at: str) -> list:
|
||||
return [own, "测试公司", at, amount, "", "50000.00", "RMB", "对方", cp, "某银行", "货款", ""]
|
||||
|
||||
|
||||
class CompanyWorkspaceTodoTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
cls.temp_dir = tempfile.TemporaryDirectory()
|
||||
root = Path(cls.temp_dir.name)
|
||||
cls.db_path = root / "app.db"
|
||||
cls.storage = root / "files"
|
||||
|
||||
cls._old_db_path = server.DB_PATH
|
||||
cls._old_storage = server.STORAGE_DIR
|
||||
server.DB_PATH = cls.db_path
|
||||
server.STORAGE_DIR = cls.storage
|
||||
|
||||
os.environ["APP_BOOTSTRAP_ADMIN_PASSWORD"] = BOOTSTRAP_PASSWORD
|
||||
from bank_importer.db import connect, migrate
|
||||
|
||||
connection = connect(cls.db_path)
|
||||
migrate(connection)
|
||||
assert server.ensure_bootstrap_admin(connection) is None
|
||||
connection.close()
|
||||
|
||||
class QuietHandler(server.AppHandler):
|
||||
def log_message(self, *args) -> None:
|
||||
pass
|
||||
|
||||
cls.httpd = server.ThreadingHTTPServer(("127.0.0.1", 0), QuietHandler)
|
||||
cls.port = cls.httpd.server_address[1]
|
||||
cls.thread = threading.Thread(target=cls.httpd.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
|
||||
cls.admin = Client("127.0.0.1", cls.port)
|
||||
status, _, data = cls.admin.post_json(
|
||||
"/api/login",
|
||||
{"username": "group-admin", "password": BOOTSTRAP_PASSWORD, "portal": "admin"},
|
||||
)
|
||||
assert status == 200, data
|
||||
status, _, data = cls.admin.post_json(
|
||||
"/api/password/change",
|
||||
{"old_password": BOOTSTRAP_PASSWORD, "new_password": ADMIN_PASSWORD},
|
||||
)
|
||||
assert status == 200, data
|
||||
|
||||
cls.initial_passwords: dict[str, str] = {}
|
||||
cls.company_a = cls._create_company("甲公司", "ws-cashier-a")
|
||||
cls.company_b = cls._create_company("乙公司", "ws-cashier-b")
|
||||
cls.cashier_a = cls._login_company("ws-cashier-a")
|
||||
cls.cashier_b = cls._login_company("ws-cashier-b")
|
||||
cls._approve_account(cls.cashier_a, ACCOUNT_A)
|
||||
cls._approve_account(cls.cashier_b, ACCOUNT_B)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls) -> None:
|
||||
cls.httpd.shutdown()
|
||||
cls.httpd.server_close()
|
||||
server.DB_PATH = cls._old_db_path
|
||||
server.STORAGE_DIR = cls._old_storage
|
||||
os.environ.pop("APP_BOOTSTRAP_ADMIN_PASSWORD", None)
|
||||
cls.temp_dir.cleanup()
|
||||
|
||||
@classmethod
|
||||
def _create_company(cls, name: str, username: str) -> int:
|
||||
status, _, data = cls.admin.post_json(
|
||||
"/api/admin/companies",
|
||||
{"name": name, "username": username},
|
||||
)
|
||||
assert status == 200, data
|
||||
payload = as_json(data)
|
||||
cls.initial_passwords[username] = payload["initial_password"]
|
||||
return payload["company_id"]
|
||||
|
||||
@classmethod
|
||||
def _login_company(cls, username: str) -> Client:
|
||||
client = Client("127.0.0.1", cls.port)
|
||||
initial = cls.initial_passwords[username]
|
||||
status, _, data = client.post_json(
|
||||
"/api/login",
|
||||
{"username": username, "password": initial, "portal": "company"},
|
||||
)
|
||||
assert status == 200, data
|
||||
status, _, data = client.post_json(
|
||||
"/api/password/change",
|
||||
{"old_password": initial, "new_password": CASHIER_PASSWORD},
|
||||
)
|
||||
assert status == 200, data
|
||||
return client
|
||||
|
||||
@classmethod
|
||||
def _approve_account(cls, company_client: Client, number: str) -> int:
|
||||
status, _, data = company_client.post_json(
|
||||
"/api/company/accounts",
|
||||
{
|
||||
"bank_name": "中信银行",
|
||||
"account_type": "基本户",
|
||||
"account_number": number,
|
||||
"start_date": "2026-01-01",
|
||||
},
|
||||
)
|
||||
assert status == 200, data
|
||||
account_id = as_json(data)["account"]["id"]
|
||||
status, _, data = cls.admin.post_json(
|
||||
f"/api/admin/accounts/{account_id}/review",
|
||||
{"decision": "approve", "reason": "测试启用", "effective_from": "2026-01-01"},
|
||||
)
|
||||
assert status == 200, data
|
||||
return account_id
|
||||
|
||||
def _seed_unilateral(self, amount: str, at: str, cp_account: str = "9999999999999999") -> dict:
|
||||
status, _, data = self.admin.post_multipart(
|
||||
"/api/parse",
|
||||
{"company_id": str(self.company_a)},
|
||||
f"单边-{amount}.xlsx",
|
||||
workbook_bytes([outgoing(ACCOUNT_A, cp_account, amount, at)]),
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
batch_id = as_json(data)["batch_id"]
|
||||
status, _, data = self.cashier_a.get(f"/api/batches/{batch_id}/sheets")
|
||||
self.assertEqual(200, status, data)
|
||||
names = [s["sheet_name"] for s in as_json(data)["sheets"] if s["outcome"] == "parsed"]
|
||||
status, _, data = self.cashier_a.post_json(
|
||||
f"/api/batches/{batch_id}/confirm", {"sheets": names}
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
|
||||
status, _, data = self.cashier_a.get("/api/company/workspace")
|
||||
self.assertEqual(200, status, data)
|
||||
events = [
|
||||
e for e in as_json(data)["unilateral_events"] if e["amount"] == amount
|
||||
]
|
||||
self.assertEqual(1, len(events), data)
|
||||
return events[0]
|
||||
|
||||
def _workspace(self, client: Client) -> dict:
|
||||
status, _, data = client.get("/api/company/workspace")
|
||||
self.assertEqual(200, status, data)
|
||||
payload = as_json(data)
|
||||
self.assertEqual("ok", payload["status"])
|
||||
return payload
|
||||
|
||||
def test_seed_three_confirm_sync_and_isolation(self) -> None:
|
||||
# Seed 3 pending unilaterals for company A.
|
||||
e1 = self._seed_unilateral("11.00", "2026-03-01 10:00:00")
|
||||
e2 = self._seed_unilateral("22.00", "2026-03-02 10:00:00")
|
||||
e3 = self._seed_unilateral("33.00", "2026-03-03 10:00:00")
|
||||
seeded_ids = {e1["event_id"], e2["event_id"], e3["event_id"]}
|
||||
|
||||
ws = self._workspace(self.cashier_a)
|
||||
own = [e for e in ws["unilateral_events"] if e["event_id"] in seeded_ids]
|
||||
self.assertEqual(3, len(own))
|
||||
self.assertEqual(ws["pending_unilateral"], ws["pending_total"])
|
||||
self.assertGreaterEqual(ws["pending_unilateral"], 3)
|
||||
# 两处数字与列表同一权威口径
|
||||
self.assertEqual(ws["pending_unilateral"], len(ws["unilateral_events"]))
|
||||
|
||||
# 另一公司看不到甲公司这 3 笔
|
||||
ws_b = self._workspace(self.cashier_b)
|
||||
self.assertEqual(
|
||||
[],
|
||||
[e for e in ws_b["unilateral_events"] if e["event_id"] in seeded_ids],
|
||||
)
|
||||
|
||||
# match-exceptions 与 workspace 同集合
|
||||
status, _, data = self.cashier_a.get("/api/company/match-exceptions")
|
||||
self.assertEqual(200, status, data)
|
||||
exceptions = as_json(data)["exceptions"]
|
||||
exception_ids = {e["event_id"] for e in exceptions}
|
||||
self.assertTrue(seeded_ids.issubset(exception_ids))
|
||||
|
||||
remaining = [e1, e2, e3]
|
||||
for expected in (2, 1, 0):
|
||||
event = remaining.pop(0)
|
||||
status, _, data = self.cashier_a.post_json(
|
||||
f"/api/company/transfer-events/{event['event_id']}/confirm",
|
||||
{
|
||||
"expected_revision": event["revision"],
|
||||
"request_key": f"hel168-{event['event_id']}-ok",
|
||||
"counterparty_company_id": self.company_b,
|
||||
"reason": "公司端确认单边流水",
|
||||
},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
body = as_json(data)
|
||||
self.assertIn("workspace", body)
|
||||
left = [
|
||||
e
|
||||
for e in body["workspace"]["unilateral_events"]
|
||||
if e["event_id"] in seeded_ids
|
||||
]
|
||||
self.assertEqual(expected, len(left))
|
||||
self.assertEqual(body["workspace"]["pending_unilateral"], len(body["workspace"]["unilateral_events"]))
|
||||
|
||||
# 刷新等价:重新 GET 仍为同步后的数字
|
||||
ws = self._workspace(self.cashier_a)
|
||||
left = [e for e in ws["unilateral_events"] if e["event_id"] in seeded_ids]
|
||||
self.assertEqual(expected, len(left))
|
||||
|
||||
# 重复确认:事件已离开待确认集合且 request_key 不同 → 404,数字不得误减
|
||||
status, _, data = self.cashier_a.post_json(
|
||||
f"/api/company/transfer-events/{e1['event_id']}/confirm",
|
||||
{
|
||||
"expected_revision": e1["revision"],
|
||||
"request_key": f"hel168-{e1['event_id']}-again",
|
||||
"counterparty_company_id": self.company_b,
|
||||
"reason": "公司端确认单边流水",
|
||||
},
|
||||
)
|
||||
self.assertEqual(404, status, data)
|
||||
ws = self._workspace(self.cashier_a)
|
||||
left = [e for e in ws["unilateral_events"] if e["event_id"] in seeded_ids]
|
||||
self.assertEqual(0, len(left))
|
||||
|
||||
# 同一 request_key 重放:幂等成功,数字不误减
|
||||
e4 = self._seed_unilateral("44.00", "2026-03-04 10:00:00")
|
||||
key = f"hel168-{e4['event_id']}-replay"
|
||||
status, _, data = self.cashier_a.post_json(
|
||||
f"/api/company/transfer-events/{e4['event_id']}/confirm",
|
||||
{
|
||||
"expected_revision": e4["revision"],
|
||||
"request_key": key,
|
||||
"counterparty_company_id": self.company_b,
|
||||
"reason": "公司端确认单边流水",
|
||||
},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
after_first = self._workspace(self.cashier_a)["pending_unilateral"]
|
||||
status, _, data = self.cashier_a.post_json(
|
||||
f"/api/company/transfer-events/{e4['event_id']}/confirm",
|
||||
{
|
||||
"expected_revision": e4["revision"],
|
||||
"request_key": key,
|
||||
"counterparty_company_id": self.company_b,
|
||||
"reason": "公司端确认单边流水",
|
||||
},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
self.assertEqual(after_first, as_json(data)["workspace"]["pending_unilateral"])
|
||||
self.assertEqual(after_first, self._workspace(self.cashier_a)["pending_unilateral"])
|
||||
|
||||
# 失败请求不得误减:用不存在的事件
|
||||
before = self._workspace(self.cashier_a)["pending_unilateral"]
|
||||
status, _, data = self.cashier_a.post_json(
|
||||
"/api/company/transfer-events/999999/confirm",
|
||||
{
|
||||
"expected_revision": 1,
|
||||
"request_key": "hel168-fail",
|
||||
"counterparty_company_id": self.company_b,
|
||||
},
|
||||
)
|
||||
self.assertEqual(404, status, data)
|
||||
self.assertEqual(before, self._workspace(self.cashier_a)["pending_unilateral"])
|
||||
|
||||
# 乙公司不能确认甲公司事件(即使猜到 id)
|
||||
status, _, data = self.cashier_b.post_json(
|
||||
f"/api/company/transfer-events/{e2['event_id']}/confirm",
|
||||
{
|
||||
"expected_revision": e2["revision"],
|
||||
"request_key": "hel168-cross",
|
||||
"counterparty_company_id": self.company_a,
|
||||
},
|
||||
)
|
||||
self.assertEqual(404, status, data)
|
||||
|
||||
def test_admin_forbidden_on_company_workspace(self) -> None:
|
||||
status, _, data = self.admin.get("/api/company/workspace")
|
||||
self.assertEqual(403, status, data)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,571 +0,0 @@
|
||||
"""Dashboard aggregate helpers and admin HTTP endpoints (no openpyxl dependency)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
|
||||
from bank_importer import dashboard, master_data
|
||||
from bank_importer.db import connect, migrate
|
||||
|
||||
import server
|
||||
from test_server_auth import Client, as_json
|
||||
|
||||
BOOTSTRAP_PASSWORD = "BootAdmin123"
|
||||
ADMIN_PASSWORD = "AdminPass123"
|
||||
|
||||
|
||||
class DashboardUnitTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.connection = connect(":memory:")
|
||||
migrate(self.connection)
|
||||
|
||||
def tearDown(self) -> None:
|
||||
self.connection.close()
|
||||
|
||||
def test_empty_dashboard(self) -> None:
|
||||
payload = dashboard.build_dashboard(
|
||||
self.connection, from_date="2026-01-01", cutoff="2026-08-20"
|
||||
)
|
||||
self.assertEqual(0, payload["audit"]["total"])
|
||||
self.assertEqual([], payload["companies"])
|
||||
self.assertEqual(7, len(payload["weekly_flow"]["labels"]))
|
||||
self.assertEqual(0, payload["totals"]["company_count"])
|
||||
self.assertEqual(0, payload["totals"]["detail_count"])
|
||||
self.assertEqual("0.00", payload["totals"]["debit_wan"])
|
||||
self.assertEqual("0.00", payload["totals"]["credit_wan"])
|
||||
progress = payload["period_progress"]
|
||||
self.assertEqual("2026-08", progress["year_month"])
|
||||
self.assertEqual(0, progress["enabled_count"])
|
||||
self.assertEqual(0, progress["done"])
|
||||
self.assertEqual(0, progress["in_progress"])
|
||||
self.assertEqual(0, progress["unsubmitted"])
|
||||
self.assertEqual(0, progress["percent"])
|
||||
|
||||
def test_period_progress_unsubmitted_when_account_active_no_flows(self) -> None:
|
||||
now = master_data.utc_now()
|
||||
cursor = self.connection.execute(
|
||||
"INSERT INTO companies (name, credit_code, cashier_name, status, created_at, updated_at) "
|
||||
"VALUES ('甲公司', NULL, NULL, 'active', ?, ?)",
|
||||
(now, now),
|
||||
)
|
||||
company_id = int(cursor.lastrowid)
|
||||
self.connection.execute(
|
||||
"""
|
||||
INSERT INTO bank_accounts (
|
||||
company_id, account_number, bank_name, account_type, status,
|
||||
created_at, updated_at
|
||||
) VALUES (?, '6222020000000099', '工行', '一般户', 'active', ?, ?)
|
||||
""",
|
||||
(company_id, now, now),
|
||||
)
|
||||
self.connection.commit()
|
||||
progress = dashboard.period_progress(self.connection, year_month="2026-08")
|
||||
self.assertEqual(1, progress["enabled_count"])
|
||||
self.assertEqual(0, progress["done"])
|
||||
self.assertEqual(0, progress["in_progress"])
|
||||
self.assertEqual(1, progress["unsubmitted"])
|
||||
self.assertEqual(0, progress["percent"])
|
||||
|
||||
def test_pending_account_counts_as_medium(self) -> None:
|
||||
now = master_data.utc_now()
|
||||
cursor = self.connection.execute(
|
||||
"INSERT INTO companies (name, credit_code, cashier_name, status, created_at, updated_at) "
|
||||
"VALUES ('甲公司', NULL, NULL, 'active', ?, ?)",
|
||||
(now, now),
|
||||
)
|
||||
company_id = int(cursor.lastrowid)
|
||||
self.connection.commit()
|
||||
master_data.submit_bank_account(
|
||||
self.connection,
|
||||
company_id=company_id,
|
||||
bank_name="工行",
|
||||
account_type="一般户",
|
||||
account_number="6222020000000001",
|
||||
start_date="2026-01-01",
|
||||
actor=None,
|
||||
)
|
||||
counts = dashboard.audit_counts(self.connection)
|
||||
self.assertEqual(1, counts["medium"])
|
||||
self.assertEqual(0, counts["high"])
|
||||
self.assertEqual(1, counts["total"])
|
||||
|
||||
def test_pending_manual_counts_as_medium(self) -> None:
|
||||
from bank_importer import auth, manual_records
|
||||
|
||||
now = master_data.utc_now()
|
||||
a = self.connection.execute(
|
||||
"INSERT INTO companies (name, credit_code, cashier_name, status, created_at, updated_at) "
|
||||
"VALUES ('甲公司', NULL, NULL, 'active', ?, ?)",
|
||||
(now, now),
|
||||
).lastrowid
|
||||
b = self.connection.execute(
|
||||
"INSERT INTO companies (name, credit_code, cashier_name, status, created_at, updated_at) "
|
||||
"VALUES ('乙公司', NULL, NULL, 'active', ?, ?)",
|
||||
(now, now),
|
||||
).lastrowid
|
||||
self.connection.commit()
|
||||
auth.create_user(
|
||||
self.connection, "cashier-a", "CashierPass123", "company", company_id=int(a)
|
||||
)
|
||||
actor = self.connection.execute(
|
||||
"SELECT * FROM users WHERE username = 'cashier-a'"
|
||||
).fetchone()
|
||||
manual_records.submit(
|
||||
self.connection,
|
||||
company_id=int(a),
|
||||
counterparty_company_id=int(b),
|
||||
occurred_at="2026-02-01T09:00:00",
|
||||
direction="incoming",
|
||||
amount="100.00",
|
||||
currency="CNY",
|
||||
funding_source="other",
|
||||
requested_subject="receivable",
|
||||
request_key="hel157-manual-1",
|
||||
actor=actor,
|
||||
)
|
||||
counts = dashboard.audit_counts(self.connection)
|
||||
self.assertEqual(1, counts["medium"])
|
||||
self.assertEqual(0, counts["high"])
|
||||
self.assertEqual(1, counts["total"])
|
||||
|
||||
def test_audit_total_equals_queue_sum(self) -> None:
|
||||
"""Homepage / badge / audit heading must share one backend total."""
|
||||
now = master_data.utc_now()
|
||||
a = self.connection.execute(
|
||||
"INSERT INTO companies (name, credit_code, cashier_name, status, created_at, updated_at) "
|
||||
"VALUES ('甲公司', NULL, NULL, 'active', ?, ?)",
|
||||
(now, now),
|
||||
).lastrowid
|
||||
self.connection.commit()
|
||||
master_data.submit_bank_account(
|
||||
self.connection,
|
||||
company_id=int(a),
|
||||
bank_name="工行",
|
||||
account_type="一般户",
|
||||
account_number="6222020000000002",
|
||||
start_date="2026-01-01",
|
||||
actor=None,
|
||||
)
|
||||
event_id = self.connection.execute(
|
||||
"INSERT INTO canonical_transfer_events (lifecycle, created_at) VALUES ('active', ?)",
|
||||
(now,),
|
||||
).lastrowid
|
||||
decision_id = self.connection.execute(
|
||||
"""
|
||||
INSERT INTO transfer_match_decisions (
|
||||
event_id, revision, effective_at, amount, currency, classification,
|
||||
pairing, locked, mode, rule_version, created_at
|
||||
) VALUES (?, 1, '2026-07-05T10:00:00', '100000.00', 'CNY', 'unresolved',
|
||||
'single', 0, 'manual', 'test', ?)
|
||||
""",
|
||||
(event_id, now),
|
||||
).lastrowid
|
||||
self.connection.execute(
|
||||
"INSERT INTO current_transfer_decisions (event_id, decision_id) VALUES (?, ?)",
|
||||
(event_id, decision_id),
|
||||
)
|
||||
self.connection.commit()
|
||||
|
||||
counts = dashboard.audit_counts(self.connection)
|
||||
payload = dashboard.build_dashboard(
|
||||
self.connection, from_date="2026-01-01", cutoff="2026-08-20"
|
||||
)
|
||||
self.assertEqual(counts, payload["audit"])
|
||||
self.assertEqual(
|
||||
counts["total"],
|
||||
counts["high"] + counts["medium"] + counts["low"],
|
||||
)
|
||||
self.assertEqual(1, counts["high"])
|
||||
self.assertEqual(1, counts["medium"])
|
||||
self.assertEqual(2, counts["total"])
|
||||
|
||||
def test_company_summaries_from_eligible_events(self) -> None:
|
||||
now = master_data.utc_now()
|
||||
a = self.connection.execute(
|
||||
"INSERT INTO companies (name, credit_code, cashier_name, status, created_at, updated_at) "
|
||||
"VALUES ('甲公司', NULL, NULL, 'active', ?, ?)",
|
||||
(now, now),
|
||||
).lastrowid
|
||||
b = self.connection.execute(
|
||||
"INSERT INTO companies (name, credit_code, cashier_name, status, created_at, updated_at) "
|
||||
"VALUES ('乙公司', NULL, NULL, 'active', ?, ?)",
|
||||
(now, now),
|
||||
).lastrowid
|
||||
event_id = self.connection.execute(
|
||||
"INSERT INTO canonical_transfer_events (lifecycle, created_at) VALUES ('active', ?)",
|
||||
(now,),
|
||||
).lastrowid
|
||||
decision_id = self.connection.execute(
|
||||
"""
|
||||
INSERT INTO transfer_match_decisions (
|
||||
event_id, revision, effective_at, amount, currency, classification,
|
||||
pairing, locked, mode, rule_version, created_at
|
||||
) VALUES (?, 1, '2026-07-05T10:00:00', '100000.00', 'CNY', 'intercompany',
|
||||
'paired', 0, 'manual', 'test', ?)
|
||||
""",
|
||||
(event_id, now),
|
||||
).lastrowid
|
||||
self.connection.execute(
|
||||
"INSERT INTO current_transfer_decisions (event_id, decision_id) VALUES (?, ?)",
|
||||
(event_id, decision_id),
|
||||
)
|
||||
self.connection.execute(
|
||||
"""
|
||||
INSERT INTO transfer_decision_participants (
|
||||
decision_id, role, company_id, bank_account_id, resolve_method, created_at
|
||||
) VALUES (?, 'payer', ?, NULL, 'manual', ?), (?, 'payee', ?, NULL, 'manual', ?)
|
||||
""",
|
||||
(decision_id, a, now, decision_id, b, now),
|
||||
)
|
||||
self.connection.commit()
|
||||
|
||||
items, totals = dashboard.company_summaries(
|
||||
self.connection, from_date="2026-01-01", cutoff="2026-08-20"
|
||||
)
|
||||
self.assertEqual(1, totals["detail_count"])
|
||||
by_name = {row["name"]: row for row in items}
|
||||
self.assertEqual(1, by_name["甲公司"]["detail_count"])
|
||||
self.assertEqual("10.00", by_name["甲公司"]["debit_wan"])
|
||||
self.assertEqual("-10.00", by_name["甲公司"]["net_wan"])
|
||||
self.assertEqual("10.00", by_name["乙公司"]["credit_wan"])
|
||||
self.assertEqual("10.00", by_name["乙公司"]["net_wan"])
|
||||
|
||||
detail = dashboard.company_peer_groups(
|
||||
self.connection, int(a), from_date="2026-01-01", cutoff="2026-08-20"
|
||||
)
|
||||
self.assertEqual(1, len(detail["groups"]))
|
||||
self.assertEqual("乙公司", detail["groups"][0]["peer_name"])
|
||||
self.assertIsNone(detail["groups"][0]["opening"])
|
||||
|
||||
|
||||
class DashboardApiTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
cls.temp_dir = tempfile.TemporaryDirectory()
|
||||
root = Path(cls.temp_dir.name)
|
||||
cls.db_path = root / "app.db"
|
||||
cls.storage = root / "files"
|
||||
|
||||
cls._old_db_path = server.DB_PATH
|
||||
cls._old_storage = server.STORAGE_DIR
|
||||
server.DB_PATH = cls.db_path
|
||||
server.STORAGE_DIR = cls.storage
|
||||
|
||||
os.environ["APP_BOOTSTRAP_ADMIN_PASSWORD"] = BOOTSTRAP_PASSWORD
|
||||
connection = connect(cls.db_path)
|
||||
migrate(connection)
|
||||
assert server.ensure_bootstrap_admin(connection) is None
|
||||
connection.close()
|
||||
|
||||
class QuietHandler(server.AppHandler):
|
||||
def log_message(self, *args) -> None:
|
||||
pass
|
||||
|
||||
cls.httpd = server.ThreadingHTTPServer(("127.0.0.1", 0), QuietHandler)
|
||||
cls.port = cls.httpd.server_address[1]
|
||||
cls.thread = threading.Thread(target=cls.httpd.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
|
||||
cls.admin = Client("127.0.0.1", cls.port)
|
||||
status, _, data = cls.admin.post_json(
|
||||
"/api/login",
|
||||
{"username": "group-admin", "password": BOOTSTRAP_PASSWORD, "portal": "admin"},
|
||||
)
|
||||
assert status == 200, data
|
||||
status, _, data = cls.admin.post_json(
|
||||
"/api/password/change",
|
||||
{"old_password": BOOTSTRAP_PASSWORD, "new_password": ADMIN_PASSWORD},
|
||||
)
|
||||
assert status == 200, data
|
||||
|
||||
status, _, data = cls.admin.post_json(
|
||||
"/api/admin/companies", {"name": "甲公司", "username": "cashier-a"}
|
||||
)
|
||||
assert status == 200, data
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls) -> None:
|
||||
cls.httpd.shutdown()
|
||||
cls.httpd.server_close()
|
||||
server.DB_PATH = cls._old_db_path
|
||||
server.STORAGE_DIR = cls._old_storage
|
||||
cls.temp_dir.cleanup()
|
||||
|
||||
def test_dashboard_ok_for_admin(self) -> None:
|
||||
status, _, raw = self.admin.get(
|
||||
"/api/admin/dashboard?from=2026-01-01&cutoff=2026-08-20"
|
||||
)
|
||||
data = as_json(raw)
|
||||
self.assertEqual(200, status)
|
||||
self.assertEqual("ok", data["status"])
|
||||
self.assertIn("audit", data)
|
||||
self.assertIn("totals", data)
|
||||
self.assertIn("period_progress", data)
|
||||
self.assertIn("debit_wan", data["totals"])
|
||||
self.assertEqual(1, len(data["companies"]))
|
||||
self.assertEqual("甲公司", data["companies"][0]["name"])
|
||||
|
||||
def test_audit_counts_sync_after_account_review(self) -> None:
|
||||
"""Pending account raises dashboard.audit; approve brings total back down."""
|
||||
from bank_importer.db import connect as db_connect
|
||||
from bank_importer import master_data as md
|
||||
|
||||
status, _, raw = self.admin.get("/api/admin/companies")
|
||||
company_id = as_json(raw)["companies"][0]["id"]
|
||||
|
||||
connection = db_connect(self.db_path)
|
||||
try:
|
||||
account = md.submit_bank_account(
|
||||
connection,
|
||||
company_id=company_id,
|
||||
bank_name="工行",
|
||||
account_type="一般户",
|
||||
account_number="6222020000000099",
|
||||
start_date="2026-01-01",
|
||||
actor=None,
|
||||
)
|
||||
account_id = account["id"]
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
status, _, raw = self.admin.get("/api/admin/dashboard")
|
||||
before = as_json(raw)["audit"]
|
||||
self.assertEqual(200, status)
|
||||
self.assertGreaterEqual(before["medium"], 1)
|
||||
self.assertGreaterEqual(before["total"], 1)
|
||||
|
||||
status, _, raw = self.admin.post_json(
|
||||
f"/api/admin/accounts/{account_id}/review",
|
||||
{"decision": "approve", "reason": "HEL-157 sync test"},
|
||||
)
|
||||
self.assertEqual(200, status, raw)
|
||||
|
||||
status, _, raw = self.admin.get("/api/admin/dashboard")
|
||||
after = as_json(raw)["audit"]
|
||||
self.assertEqual(after["medium"], before["medium"] - 1)
|
||||
self.assertEqual(after["total"], before["total"] - 1)
|
||||
self.assertEqual(
|
||||
after["total"], after["high"] + after["medium"] + after["low"]
|
||||
)
|
||||
|
||||
def test_three_queue_audit_parity_and_dispose_sync(self) -> None:
|
||||
"""Seed account+manual+exception: list sizes == dashboard.audit; dispose syncs -1."""
|
||||
from bank_importer.db import connect as db_connect
|
||||
from bank_importer import auth, manual_records, master_data as md
|
||||
|
||||
status, _, raw = self.admin.get("/api/admin/companies")
|
||||
company_id = as_json(raw)["companies"][0]["id"]
|
||||
|
||||
# Second company for manual counterparty.
|
||||
status, _, raw = self.admin.post_json(
|
||||
"/api/admin/companies", {"name": "乙公司", "username": "cashier-b-hel157"}
|
||||
)
|
||||
self.assertEqual(200, status, raw)
|
||||
company_b = as_json(raw).get("company_id") or as_json(raw).get("id")
|
||||
self.assertIsNotNone(company_b)
|
||||
|
||||
connection = db_connect(self.db_path)
|
||||
try:
|
||||
account = md.submit_bank_account(
|
||||
connection,
|
||||
company_id=company_id,
|
||||
bank_name="工行",
|
||||
account_type="一般户",
|
||||
account_number="6222020000000157",
|
||||
start_date="2026-01-01",
|
||||
actor=None,
|
||||
)
|
||||
account_id = account["id"]
|
||||
|
||||
cashier = connection.execute(
|
||||
"SELECT * FROM users WHERE username = 'cashier-a'"
|
||||
).fetchone()
|
||||
if cashier is None:
|
||||
auth.create_user(
|
||||
connection,
|
||||
"cashier-a",
|
||||
"CashierPass123",
|
||||
"company",
|
||||
company_id=company_id,
|
||||
)
|
||||
cashier = connection.execute(
|
||||
"SELECT * FROM users WHERE username = 'cashier-a'"
|
||||
).fetchone()
|
||||
manual = manual_records.submit(
|
||||
connection,
|
||||
company_id=company_id,
|
||||
counterparty_company_id=int(company_b),
|
||||
occurred_at="2026-02-01T09:00:00",
|
||||
direction="incoming",
|
||||
amount="100.00",
|
||||
currency="CNY",
|
||||
funding_source="other",
|
||||
requested_subject="receivable",
|
||||
request_key="hel157-queue-manual",
|
||||
actor=cashier,
|
||||
)
|
||||
|
||||
now = md.utc_now()
|
||||
event_id = connection.execute(
|
||||
"INSERT INTO canonical_transfer_events (lifecycle, created_at) VALUES ('active', ?)",
|
||||
(now,),
|
||||
).lastrowid
|
||||
decision_id = connection.execute(
|
||||
"""
|
||||
INSERT INTO transfer_match_decisions (
|
||||
event_id, revision, effective_at, amount, currency, classification,
|
||||
pairing, locked, mode, rule_version, created_at
|
||||
) VALUES (?, 1, '2026-07-05T10:00:00', '100000.00', 'CNY', 'unresolved',
|
||||
'single', 0, 'manual', 'test', ?)
|
||||
""",
|
||||
(event_id, now),
|
||||
).lastrowid
|
||||
connection.execute(
|
||||
"INSERT INTO current_transfer_decisions (event_id, decision_id) VALUES (?, ?)",
|
||||
(event_id, decision_id),
|
||||
)
|
||||
connection.commit()
|
||||
manual_id = manual["id"]
|
||||
manual_decision_id = manual["decision_id"]
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def queue_sizes():
|
||||
st, _, body = self.admin.get("/api/admin/accounts?status=pending")
|
||||
self.assertEqual(200, st, body)
|
||||
accounts_n = len(as_json(body)["accounts"])
|
||||
st, _, body = self.admin.get("/api/admin/manual-records?state=pending")
|
||||
self.assertEqual(200, st, body)
|
||||
manuals_n = len(as_json(body)["records"])
|
||||
st, _, body = self.admin.get("/api/admin/match-exceptions")
|
||||
self.assertEqual(200, st, body)
|
||||
exceptions_n = len(as_json(body)["exceptions"])
|
||||
return accounts_n, manuals_n, exceptions_n, accounts_n + manuals_n + exceptions_n
|
||||
|
||||
def assert_parity(expected_total: int) -> dict:
|
||||
st, _, body = self.admin.get("/api/admin/dashboard")
|
||||
self.assertEqual(200, st, body)
|
||||
audit = as_json(body)["audit"]
|
||||
accounts_n, manuals_n, exceptions_n, list_total = queue_sizes()
|
||||
self.assertEqual(expected_total, audit["total"])
|
||||
self.assertEqual(expected_total, list_total)
|
||||
self.assertEqual(
|
||||
audit["total"], audit["high"] + audit["medium"] + audit["low"]
|
||||
)
|
||||
self.assertGreaterEqual(accounts_n, 1 if expected_total >= 3 else 0)
|
||||
return {
|
||||
"audit": audit,
|
||||
"accounts": accounts_n,
|
||||
"manuals": manuals_n,
|
||||
"exceptions": exceptions_n,
|
||||
}
|
||||
|
||||
before = assert_parity(3)
|
||||
self.assertEqual(1, before["accounts"])
|
||||
self.assertEqual(1, before["manuals"])
|
||||
self.assertEqual(1, before["exceptions"])
|
||||
self.assertEqual(1, before["audit"]["high"])
|
||||
self.assertEqual(2, before["audit"]["medium"])
|
||||
|
||||
# Dispose account → total 2
|
||||
st, _, body = self.admin.post_json(
|
||||
f"/api/admin/accounts/{account_id}/review",
|
||||
{"decision": "approve", "reason": "HEL-157 three-queue dispose account"},
|
||||
)
|
||||
self.assertEqual(200, st, body)
|
||||
after_account = assert_parity(2)
|
||||
|
||||
# Dispose manual → total 1
|
||||
st, _, body = self.admin.post_json(
|
||||
f"/api/admin/manual-records/{manual_id}/decisions",
|
||||
{
|
||||
"action": "approve_new",
|
||||
"reason": "HEL-157 three-queue dispose manual",
|
||||
"expected_decision_id": manual_decision_id,
|
||||
"request_key": "hel157-dispose-manual",
|
||||
},
|
||||
)
|
||||
self.assertEqual(200, st, body)
|
||||
after_manual = assert_parity(1)
|
||||
self.assertEqual(0, after_manual["manuals"])
|
||||
|
||||
# Dispose match exception via reverse → total 0
|
||||
st, _, body = self.admin.get("/api/admin/match-exceptions")
|
||||
exceptions = as_json(body)["exceptions"]
|
||||
self.assertEqual(1, len(exceptions))
|
||||
target = exceptions[0]
|
||||
st, _, body = self.admin.post_json(
|
||||
f"/api/admin/transfer-events/{target['event_id']}/decisions",
|
||||
{
|
||||
"action": "reverse",
|
||||
"reason": "HEL-157 three-queue dispose match",
|
||||
"expected_revision": target["revision"],
|
||||
"request_key": "hel157-dispose-match",
|
||||
},
|
||||
)
|
||||
self.assertEqual(200, st, body)
|
||||
after_match = assert_parity(0)
|
||||
self.assertEqual(0, after_match["exceptions"])
|
||||
self.assertEqual(after_account["audit"]["total"] - 1, after_manual["audit"]["total"])
|
||||
self.assertEqual(after_manual["audit"]["total"] - 1, after_match["audit"]["total"])
|
||||
|
||||
def test_company_detail_missing(self) -> None:
|
||||
status, _, raw = self.admin.get(
|
||||
"/api/admin/dashboard/companies/999999?from=2026-01-01&cutoff=2026-08-20"
|
||||
)
|
||||
data = as_json(raw)
|
||||
self.assertEqual(404, status)
|
||||
self.assertEqual("error", data["status"])
|
||||
|
||||
def test_company_detail_ok(self) -> None:
|
||||
status, _, raw = self.admin.get("/api/admin/dashboard")
|
||||
data = as_json(raw)
|
||||
company_id = data["companies"][0]["id"]
|
||||
status, _, raw = self.admin.get(
|
||||
f"/api/admin/dashboard/companies/{company_id}?from=2026-01-01&cutoff=2026-08-20"
|
||||
)
|
||||
detail = as_json(raw)
|
||||
self.assertEqual(200, status)
|
||||
self.assertEqual([], detail["groups"])
|
||||
|
||||
|
||||
class DashboardPageContractTests(unittest.TestCase):
|
||||
"""HEL-343 阻断项:管理总览 KPI 不得写死演示金额。"""
|
||||
|
||||
def test_admin_html_kpi_placeholders_not_demo_amounts(self) -> None:
|
||||
html = (Path(__file__).resolve().parents[1] / "web" / "admin.html").read_text(
|
||||
encoding="utf-8"
|
||||
)
|
||||
self.assertIn('id="dashPageSub"', html)
|
||||
self.assertIn('id="dashDebitValue"', html)
|
||||
self.assertIn('id="dashCreditValue"', html)
|
||||
self.assertIn('id="dashPeriodPercent"', html)
|
||||
self.assertIn('id="dashPeriodBar"', html)
|
||||
self.assertIn('id="dashPeriodFoot"', html)
|
||||
self.assertNotIn("42,040.30", html)
|
||||
self.assertNotIn("39,040.30", html)
|
||||
self.assertNotIn("8.11 亿", html)
|
||||
self.assertNotIn("392 笔", html)
|
||||
self.assertNotIn("3 家已完成 · 2 家在途 · 1 家未提交", html)
|
||||
self.assertNotRegex(html, r'id="flowStart"[^>]*value="2026-07-01"')
|
||||
self.assertIn('id="pending-check-all"', html)
|
||||
self.assertIn("pending-check-all", html)
|
||||
|
||||
def test_app_js_binds_dashboard_totals(self) -> None:
|
||||
js = (Path(__file__).resolve().parents[1] / "web" / "app.js").read_text(
|
||||
encoding="utf-8"
|
||||
)
|
||||
self.assertIn("function applyDashKpis(", js)
|
||||
self.assertIn("applyDashKpis(data)", js)
|
||||
self.assertIn("dashDebitValue", js)
|
||||
self.assertIn("dashCreditValue", js)
|
||||
self.assertIn("period_progress", js)
|
||||
self.assertIn("master.disabled = boxes.length === 0", js)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,518 +0,0 @@
|
||||
"""HEL-203: 真实浏览器冒烟——原因弹窗、首屏断档、表单 reset。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from bank_importer import auth, calculation, matching, master_data
|
||||
from bank_importer.db import connect, migrate, utc_now
|
||||
|
||||
import server
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
WEB = ROOT / "web"
|
||||
ADMIN_PASSWORD = "AdminPass123"
|
||||
CASHIER_PASSWORD = "CashierA123"
|
||||
|
||||
try:
|
||||
from playwright.sync_api import sync_playwright
|
||||
except ImportError: # pragma: no cover
|
||||
sync_playwright = None
|
||||
|
||||
|
||||
def _prepare_chrome_libs() -> Path | None:
|
||||
"""本机缺系统 atk 时,复用仓库旁的本地 chromium 依赖目录。"""
|
||||
candidates = [ROOT / ".chrome-libs" / "lib"]
|
||||
for lib_dir in candidates:
|
||||
if (lib_dir / "libatk-1.0.so.0").exists():
|
||||
current = os.environ.get("LD_LIBRARY_PATH", "")
|
||||
prefix = str(lib_dir)
|
||||
if prefix not in current.split(":"):
|
||||
os.environ["LD_LIBRARY_PATH"] = (
|
||||
f"{prefix}:{current}" if current else prefix
|
||||
)
|
||||
return lib_dir
|
||||
return None
|
||||
|
||||
|
||||
def _chromium_available() -> bool:
|
||||
if not sync_playwright:
|
||||
return False
|
||||
_prepare_chrome_libs()
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, args=["--no-sandbox"])
|
||||
browser.close()
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
class Hel203SourceContractTests(unittest.TestCase):
|
||||
"""不依赖浏览器:锁住 N1~N3 的源码契约。"""
|
||||
|
||||
def test_open_modal_is_single_top_level(self) -> None:
|
||||
js = (WEB / "app.js").read_text(encoding="utf-8")
|
||||
defs = list(re.finditer(r"(?m)^function openModal\(", js))
|
||||
self.assertEqual(1, len(defs), "openModal 必须只有一处顶层定义")
|
||||
# 不得再出现在 initAdmin / initCompany 函数体内的局部副本
|
||||
self.assertNotRegex(
|
||||
js,
|
||||
r"function initAdmin\(\)[\s\S]*?function openModal\(",
|
||||
)
|
||||
self.assertNotRegex(
|
||||
js,
|
||||
r"function initCompany\(\)[\s\S]*?function openModal\(",
|
||||
)
|
||||
self.assertIn("function askReason(", js)
|
||||
ask_pos = js.index("function askReason(")
|
||||
open_pos = defs[0].start()
|
||||
self.assertLess(open_pos, ask_pos, "openModal 须在 askReason 之前定义")
|
||||
|
||||
def test_init_company_boots_coverage_gaps(self) -> None:
|
||||
js = (WEB / "app.js").read_text(encoding="utf-8")
|
||||
company_fn = js[js.index("function initCompany(") :]
|
||||
boot = company_fn[: company_fn.index("\nif (portal ===")]
|
||||
self.assertIn("await loadCompanyWorkspace()", boot)
|
||||
self.assertIn("await loadCompanyCoverageGaps()", boot)
|
||||
|
||||
def test_async_forms_capture_form_before_await(self) -> None:
|
||||
js = (WEB / "app.js").read_text(encoding="utf-8")
|
||||
self.assertNotIn("event.currentTarget.reset()", js)
|
||||
for marker in ("#companyForm", "#openingForm", "#accountForm"):
|
||||
idx = js.index(marker)
|
||||
chunk = js[idx : idx + 2500]
|
||||
self.assertIn("const form = event.currentTarget", chunk)
|
||||
self.assertIn("form.reset()", chunk)
|
||||
|
||||
|
||||
@unittest.skipUnless(sync_playwright, "playwright 未安装,跳过浏览器冒烟")
|
||||
@unittest.skipUnless(_chromium_available(), "chromium 无法启动,跳过浏览器冒烟")
|
||||
class Hel203BrowserSmokeTests(unittest.TestCase):
|
||||
"""真实 Chromium:改起算日→期初→公司端期末;断档首屏→说明→审核。"""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
_prepare_chrome_libs()
|
||||
cls.temp_dir = tempfile.TemporaryDirectory()
|
||||
root = Path(cls.temp_dir.name)
|
||||
cls.db_path = root / "app.db"
|
||||
cls.storage = root / "files"
|
||||
cls.storage.mkdir()
|
||||
|
||||
cls._old_db = server.DB_PATH
|
||||
cls._old_storage = server.STORAGE_DIR
|
||||
server.DB_PATH = cls.db_path
|
||||
server.STORAGE_DIR = cls.storage
|
||||
|
||||
connection = connect(cls.db_path)
|
||||
migrate(connection)
|
||||
auth.create_user(
|
||||
connection,
|
||||
"group-admin",
|
||||
ADMIN_PASSWORD,
|
||||
"admin",
|
||||
must_change_password=False,
|
||||
)
|
||||
cls.company_a = master_data.create_company(
|
||||
connection, "甲公司", None, None, None
|
||||
)
|
||||
cls.company_b = master_data.create_company(
|
||||
connection, "乙公司", None, None, None
|
||||
)
|
||||
auth.create_user(
|
||||
connection,
|
||||
"cashier-a",
|
||||
CASHIER_PASSWORD,
|
||||
"company",
|
||||
cls.company_a,
|
||||
must_change_password=False,
|
||||
)
|
||||
admin = connection.execute(
|
||||
"SELECT * FROM users WHERE username = 'group-admin'"
|
||||
).fetchone()
|
||||
account = master_data.submit_bank_account(
|
||||
connection,
|
||||
company_id=cls.company_a,
|
||||
bank_name="中信银行",
|
||||
account_type="基本户",
|
||||
account_number="6222000000000001",
|
||||
start_date="2026-06-01",
|
||||
actor=None,
|
||||
)
|
||||
cls.account_a = master_data.review_bank_account(
|
||||
connection,
|
||||
account["id"],
|
||||
"approve",
|
||||
None,
|
||||
admin,
|
||||
effective_from="2026-06-01",
|
||||
)
|
||||
account_b = master_data.submit_bank_account(
|
||||
connection,
|
||||
company_id=cls.company_b,
|
||||
bank_name="中信银行",
|
||||
account_type="基本户",
|
||||
account_number="6222000000000002",
|
||||
start_date="2026-06-01",
|
||||
actor=None,
|
||||
)
|
||||
master_data.review_bank_account(
|
||||
connection,
|
||||
account_b["id"],
|
||||
"approve",
|
||||
None,
|
||||
admin,
|
||||
effective_from="2026-06-01",
|
||||
)
|
||||
# 制造一处 mid 断档,供公司端首屏提醒
|
||||
with connection:
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO source_files
|
||||
(sha256, original_filename, size_bytes, storage_path, created_at)
|
||||
VALUES (?, 'gap.xlsx', 1, 'data/files/gap.xlsx', ?)
|
||||
""",
|
||||
("sha-hel203-gap", utc_now()),
|
||||
)
|
||||
source_file_id = int(cursor.lastrowid)
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO import_batches (
|
||||
source_file_id, status, company_id, upload_bank_account_id,
|
||||
created_at, updated_at
|
||||
) VALUES (?, 'parsed', ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
source_file_id,
|
||||
cls.company_a,
|
||||
cls.account_a["id"],
|
||||
utc_now(),
|
||||
utc_now(),
|
||||
),
|
||||
)
|
||||
batch_id = int(cursor.lastrowid)
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO sheet_batches (
|
||||
import_batch_id, sheet_name, bank_name, template_id,
|
||||
template_version, header_row, transaction_count, warnings,
|
||||
created_at
|
||||
) VALUES (?, '流水', '测试银行', 'test-v1', 1, 1, 1, '[]', ?)
|
||||
""",
|
||||
(batch_id, utc_now()),
|
||||
)
|
||||
sheet_batch_id = int(cursor.lastrowid)
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO sheet_reviews (
|
||||
import_batch_id, sheet_name, outcome, sheet_batch_id,
|
||||
review_status, created_at
|
||||
) VALUES (?, '流水', 'parsed', ?, 'confirmed', ?)
|
||||
""",
|
||||
(batch_id, sheet_batch_id, utc_now()),
|
||||
)
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO source_rows (
|
||||
sheet_batch_id, source_row, transaction_at, income, expense,
|
||||
own_account, created_at
|
||||
) VALUES (?, 1, '2026-06-21T10:00:00', '0', '0', ?, ?)
|
||||
""",
|
||||
(sheet_batch_id, "6222000000000001", utc_now()),
|
||||
)
|
||||
calculation.set_calculation_start_date(
|
||||
connection, "2026-06-01", "初始化起算", admin
|
||||
)
|
||||
calculation.recalculate_coverage_gaps(connection)
|
||||
|
||||
# 种一笔已确认往来,确认期初后公司端才能进入完整期末口径
|
||||
def _add_row(company_id, account_id, own, cp, *, income, expense, at, ref):
|
||||
with connection:
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO source_files
|
||||
(sha256, original_filename, size_bytes, storage_path, created_at)
|
||||
VALUES (?, 'xfer.xlsx', 1, 'data/files/xfer.xlsx', ?)
|
||||
""",
|
||||
(ref, utc_now()),
|
||||
)
|
||||
source_file_id = int(cursor.lastrowid)
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO import_batches (
|
||||
source_file_id, status, company_id, upload_bank_account_id,
|
||||
created_at, updated_at
|
||||
) VALUES (?, 'parsed', ?, ?, ?, ?)
|
||||
""",
|
||||
(source_file_id, company_id, account_id, utc_now(), utc_now()),
|
||||
)
|
||||
batch_id = int(cursor.lastrowid)
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO sheet_batches (
|
||||
import_batch_id, sheet_name, bank_name, template_id,
|
||||
template_version, header_row, transaction_count, warnings,
|
||||
created_at
|
||||
) VALUES (?, '流水', '测试银行', 'test-v1', 1, 1, 1, '[]', ?)
|
||||
""",
|
||||
(batch_id, utc_now()),
|
||||
)
|
||||
sheet_batch_id = int(cursor.lastrowid)
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO sheet_reviews (
|
||||
import_batch_id, sheet_name, outcome, sheet_batch_id,
|
||||
review_status, created_at
|
||||
) VALUES (?, '流水', 'parsed', ?, 'confirmed', ?)
|
||||
""",
|
||||
(batch_id, sheet_batch_id, utc_now()),
|
||||
)
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO source_rows (
|
||||
sheet_batch_id, source_row, transaction_at, income, expense,
|
||||
own_account, own_name, counterparty_account, counterparty_name,
|
||||
summary, purpose, currency, created_at
|
||||
) VALUES (?, 1, ?, ?, ?, ?, '测试', ?, '对方', '往来', '往来款', 'CNY', ?)
|
||||
""",
|
||||
(
|
||||
sheet_batch_id,
|
||||
at,
|
||||
income,
|
||||
expense,
|
||||
own,
|
||||
cp,
|
||||
utc_now(),
|
||||
),
|
||||
)
|
||||
return int(cursor.lastrowid)
|
||||
|
||||
row_a = _add_row(
|
||||
cls.company_a,
|
||||
cls.account_a["id"],
|
||||
"6222000000000001",
|
||||
"6222000000000002",
|
||||
income="0",
|
||||
expense="100.00",
|
||||
at="2026-06-20T10:00:00",
|
||||
ref="sha-hel203-a",
|
||||
)
|
||||
row_b = _add_row(
|
||||
cls.company_b,
|
||||
account_b["id"],
|
||||
"6222000000000002",
|
||||
"6222000000000001",
|
||||
income="100.00",
|
||||
expense="0",
|
||||
at="2026-06-20T11:00:00",
|
||||
ref="sha-hel203-b",
|
||||
)
|
||||
matching.reconcile_rows(connection, [row_a, row_b])
|
||||
connection.close()
|
||||
|
||||
class QuietHandler(server.AppHandler):
|
||||
def log_message(self, *args) -> None:
|
||||
pass
|
||||
|
||||
cls.httpd = server.ThreadingHTTPServer(("127.0.0.1", 0), QuietHandler)
|
||||
cls.port = cls.httpd.server_address[1]
|
||||
cls.thread = threading.Thread(target=cls.httpd.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
cls.base = f"http://127.0.0.1:{cls.port}"
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls) -> None:
|
||||
cls.httpd.shutdown()
|
||||
cls.httpd.server_close()
|
||||
server.DB_PATH = cls._old_db
|
||||
server.STORAGE_DIR = cls._old_storage
|
||||
cls.temp_dir.cleanup()
|
||||
|
||||
def _new_page(self, playwright):
|
||||
browser = playwright.chromium.launch(
|
||||
headless=True, args=["--no-sandbox", "--disable-dev-shm-usage"]
|
||||
)
|
||||
context = browser.new_context(viewport={"width": 1440, "height": 900})
|
||||
page = context.new_page()
|
||||
errors: list[str] = []
|
||||
page.on("pageerror", lambda err: errors.append(str(err)))
|
||||
page.on(
|
||||
"console",
|
||||
lambda msg: errors.append(f"console.{msg.type}: {msg.text}")
|
||||
if msg.type == "error"
|
||||
else None,
|
||||
)
|
||||
return browser, page, errors
|
||||
|
||||
def _login(self, page, *, portal: str, username: str, password: str) -> None:
|
||||
login_path = "login-admin.html" if portal == "admin" else "login-company.html"
|
||||
page.goto(f"{self.base}/{login_path}", wait_until="domcontentloaded")
|
||||
page.fill("#account", username)
|
||||
page.fill("#password", password)
|
||||
page.click('button[type="submit"]')
|
||||
expect = "admin.html" if portal == "admin" else "company.html"
|
||||
page.wait_for_url(f"**/{expect}", timeout=15000)
|
||||
|
||||
def test_02_admin_start_date_opening_company_ending(self) -> None:
|
||||
with sync_playwright() as p:
|
||||
browser, page, errors = self._new_page(p)
|
||||
try:
|
||||
self._login(
|
||||
page,
|
||||
portal="admin",
|
||||
username="group-admin",
|
||||
password=ADMIN_PASSWORD,
|
||||
)
|
||||
page.click('a[data-view="settings"]')
|
||||
page.wait_for_selector("#cs-start", state="visible")
|
||||
|
||||
# 修改起算日 → 原因弹窗必须打开且发出 PUT
|
||||
page.fill("#cs-start", "2026-06-15")
|
||||
with page.expect_request(
|
||||
lambda req: req.method == "PUT"
|
||||
and "/api/admin/settings/calculation-start" in req.url
|
||||
) as start_req:
|
||||
page.click('#systemSettings button[type="submit"]')
|
||||
page.wait_for_selector("#reasonDialog.open", timeout=5000)
|
||||
page.fill("#reasonInput", "调整起算日供冒烟")
|
||||
page.click("#reasonSubmit")
|
||||
self.assertTrue(start_req.value.post_data)
|
||||
page.wait_for_function(
|
||||
"() => document.getElementById('cs-start')?.value === '2026-06-15'"
|
||||
)
|
||||
|
||||
# 创建期初并确认
|
||||
page.click("#openOpeningDialog")
|
||||
page.wait_for_selector("#openingDialog.open")
|
||||
page.select_option("#ob-from", label="甲公司")
|
||||
page.select_option("#ob-to", label="乙公司")
|
||||
page.fill("#ob-amount", "200")
|
||||
page.fill("#ob-reason", "冒烟期初录入")
|
||||
with page.expect_request(
|
||||
lambda req: req.method == "POST"
|
||||
and req.url.endswith("/api/admin/opening-balances")
|
||||
):
|
||||
page.click('#openingForm button[type="submit"]')
|
||||
page.wait_for_selector(
|
||||
'#openingRows button[data-confirm-opening]',
|
||||
timeout=8000,
|
||||
)
|
||||
|
||||
with page.expect_request(
|
||||
lambda req: req.method == "POST"
|
||||
and "/opening-balances/" in req.url
|
||||
and req.url.endswith("/confirm")
|
||||
):
|
||||
page.click('#openingRows button[data-confirm-opening]')
|
||||
page.wait_for_selector("#reasonDialog.open", timeout=5000)
|
||||
page.fill("#reasonInput", "确认期初冒烟")
|
||||
page.click("#reasonSubmit")
|
||||
page.wait_for_selector(
|
||||
'#openingRows button[data-void-opening]',
|
||||
timeout=8000,
|
||||
)
|
||||
|
||||
# 公司端看到完整期末口径
|
||||
self._login(
|
||||
page,
|
||||
portal="company",
|
||||
username="cashier-a",
|
||||
password=CASHIER_PASSWORD,
|
||||
)
|
||||
page.click('a[data-view="transfers"]')
|
||||
page.wait_for_function(
|
||||
"""() => {
|
||||
const data = document.getElementById('transfersData');
|
||||
const empty = document.getElementById('transfersEmpty');
|
||||
const ready = (data && !data.hidden) || (empty && !empty.hidden);
|
||||
const card = document.getElementById('tfStatEndingCard');
|
||||
const title = document.getElementById('tfStatNetTitle');
|
||||
const emptyHtml = document.getElementById('transfersEmptyStats')?.innerHTML || '';
|
||||
return ready && (
|
||||
(card && !card.hidden) ||
|
||||
(title && title.textContent.includes('期末')) ||
|
||||
emptyHtml.includes('期末')
|
||||
);
|
||||
}""",
|
||||
timeout=15000,
|
||||
)
|
||||
fatal = [e for e in errors if "openModal is not defined" in e
|
||||
or "Cannot read properties of null" in e]
|
||||
self.assertEqual([], fatal, fatal)
|
||||
finally:
|
||||
browser.close()
|
||||
|
||||
def test_01_company_gap_notice_then_admin_approve(self) -> None:
|
||||
with sync_playwright() as p:
|
||||
browser, page, errors = self._new_page(p)
|
||||
try:
|
||||
self._login(
|
||||
page,
|
||||
portal="company",
|
||||
username="cashier-a",
|
||||
password=CASHIER_PASSWORD,
|
||||
)
|
||||
# 首屏即可见断档提醒,无需手动刷新
|
||||
page.wait_for_selector(
|
||||
"#companyCoverageNotice",
|
||||
state="visible",
|
||||
timeout=10000,
|
||||
)
|
||||
body = page.locator("#companyCoverageBody").inner_text()
|
||||
self.assertTrue(body.strip())
|
||||
self.assertNotIn("0002", body)
|
||||
|
||||
page.click("#openAttestationFromWorkspace")
|
||||
page.wait_for_selector("#attestationDialog.open", timeout=5000)
|
||||
page.fill("#att-reason", "节假日账户无资金往来")
|
||||
with page.expect_request(
|
||||
lambda req: req.method == "POST"
|
||||
and req.url.endswith("/api/company/no-business-attestations")
|
||||
) as att_req:
|
||||
page.click('#attestationForm button[type="submit"]')
|
||||
self.assertTrue(att_req.value.post_data)
|
||||
page.wait_for_function(
|
||||
"""() => !document.getElementById('attestationDialog')?.classList.contains('open')""",
|
||||
timeout=8000,
|
||||
)
|
||||
|
||||
self._login(
|
||||
page,
|
||||
portal="admin",
|
||||
username="group-admin",
|
||||
password=ADMIN_PASSWORD,
|
||||
)
|
||||
page.click('a[data-view="audit"]')
|
||||
page.wait_for_selector(
|
||||
'button[data-audit-action="approve-attestation"]',
|
||||
timeout=10000,
|
||||
)
|
||||
with page.expect_request(
|
||||
lambda req: req.method == "POST"
|
||||
and "/no-business-attestations/" in req.url
|
||||
and req.url.endswith("/review")
|
||||
):
|
||||
page.click('button[data-audit-action="approve-attestation"]')
|
||||
page.wait_for_selector("#reasonDialog.open", timeout=5000)
|
||||
page.fill("#reasonInput", "审核通过说明")
|
||||
page.click("#reasonSubmit")
|
||||
page.wait_for_function(
|
||||
"""() => !document.querySelector(
|
||||
'button[data-audit-action=\"approve-attestation\"]'
|
||||
)""",
|
||||
timeout=10000,
|
||||
)
|
||||
fatal = [e for e in errors if "openModal is not defined" in e]
|
||||
self.assertEqual([], fatal, fatal)
|
||||
finally:
|
||||
browser.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,417 +0,0 @@
|
||||
"""HEL-206: 公司间期末余额方向——期初应收 + 转出垫付 = 期末应收增加。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
from bank_importer import auth, calculation, matching, master_data
|
||||
from bank_importer.db import connect, migrate, utc_now
|
||||
|
||||
import server
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ADMIN_PASSWORD = "AdminPass123"
|
||||
CASHIER_A_PASSWORD = "CashierA123"
|
||||
CASHIER_B_PASSWORD = "CashierB123"
|
||||
|
||||
try:
|
||||
from playwright.sync_api import sync_playwright
|
||||
except ImportError: # pragma: no cover
|
||||
sync_playwright = None
|
||||
|
||||
|
||||
def _prepare_chrome_libs() -> Path | None:
|
||||
candidates = [ROOT / ".chrome-libs" / "lib"]
|
||||
for lib_dir in candidates:
|
||||
if (lib_dir / "libatk-1.0.so.0").exists():
|
||||
current = os.environ.get("LD_LIBRARY_PATH", "")
|
||||
prefix = str(lib_dir)
|
||||
if prefix not in current.split(":"):
|
||||
os.environ["LD_LIBRARY_PATH"] = (
|
||||
f"{prefix}:{current}" if current else prefix
|
||||
)
|
||||
return lib_dir
|
||||
return None
|
||||
|
||||
|
||||
def _chromium_available() -> bool:
|
||||
if not sync_playwright:
|
||||
return False
|
||||
_prepare_chrome_libs()
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, args=["--no-sandbox"])
|
||||
browser.close()
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
class Hel206BalanceDirectionUnitTests(unittest.TestCase):
|
||||
"""不依赖浏览器:期初 200 + 转出 100 → 甲应收 300 / 乙应付 300。"""
|
||||
|
||||
def setUp(self) -> None:
|
||||
self.temp_dir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp_dir.cleanup)
|
||||
self.db_path = Path(self.temp_dir.name) / "app.db"
|
||||
self.connection = connect(self.db_path)
|
||||
self.addCleanup(self.connection.close)
|
||||
migrate(self.connection)
|
||||
auth.create_user(self.connection, "admin-u", ADMIN_PASSWORD, "admin")
|
||||
self.admin = self.connection.execute(
|
||||
"SELECT * FROM users WHERE username = 'admin-u'"
|
||||
).fetchone()
|
||||
self.company_a = master_data.create_company(
|
||||
self.connection, "甲公司", None, None, None
|
||||
)
|
||||
self.company_b = master_data.create_company(
|
||||
self.connection, "乙公司", None, None, None
|
||||
)
|
||||
self.account_a = self._approve("6222000000000001", self.company_a)
|
||||
self.account_b = self._approve("6222000000000002", self.company_b)
|
||||
calculation.set_calculation_start_date(
|
||||
self.connection, "2026-01-01", "起算", self.admin
|
||||
)
|
||||
|
||||
def _approve(self, number: str, company_id: int):
|
||||
account = master_data.submit_bank_account(
|
||||
self.connection,
|
||||
company_id=company_id,
|
||||
bank_name="中信银行",
|
||||
account_type="基本户",
|
||||
account_number=number,
|
||||
start_date="2026-01-01",
|
||||
actor=None,
|
||||
)
|
||||
return master_data.review_bank_account(
|
||||
self.connection,
|
||||
account["id"],
|
||||
"approve",
|
||||
None,
|
||||
self.admin,
|
||||
effective_from="2026-01-01",
|
||||
)
|
||||
|
||||
def _add_row(self, company_id, account_id, own, cp, *, income, expense, at, ref):
|
||||
with self.connection:
|
||||
cursor = self.connection.execute(
|
||||
"""
|
||||
INSERT INTO source_files
|
||||
(sha256, original_filename, size_bytes, storage_path, created_at)
|
||||
VALUES (?, 'xfer.xlsx', 1, 'data/files/xfer.xlsx', ?)
|
||||
""",
|
||||
(ref, utc_now()),
|
||||
)
|
||||
source_file_id = int(cursor.lastrowid)
|
||||
cursor = self.connection.execute(
|
||||
"""
|
||||
INSERT INTO import_batches (
|
||||
source_file_id, status, company_id, upload_bank_account_id,
|
||||
created_at, updated_at
|
||||
) VALUES (?, 'parsed', ?, ?, ?, ?)
|
||||
""",
|
||||
(source_file_id, company_id, account_id, utc_now(), utc_now()),
|
||||
)
|
||||
batch_id = int(cursor.lastrowid)
|
||||
cursor = self.connection.execute(
|
||||
"""
|
||||
INSERT INTO sheet_batches (
|
||||
import_batch_id, sheet_name, bank_name, template_id,
|
||||
template_version, header_row, transaction_count, warnings,
|
||||
created_at
|
||||
) VALUES (?, '流水', '测试银行', 'test-v1', 1, 1, 1, '[]', ?)
|
||||
""",
|
||||
(batch_id, utc_now()),
|
||||
)
|
||||
sheet_batch_id = int(cursor.lastrowid)
|
||||
self.connection.execute(
|
||||
"""
|
||||
INSERT INTO sheet_reviews (
|
||||
import_batch_id, sheet_name, outcome, sheet_batch_id,
|
||||
review_status, created_at
|
||||
) VALUES (?, '流水', 'parsed', ?, 'confirmed', ?)
|
||||
""",
|
||||
(batch_id, sheet_batch_id, utc_now()),
|
||||
)
|
||||
cursor = self.connection.execute(
|
||||
"""
|
||||
INSERT INTO source_rows (
|
||||
sheet_batch_id, source_row, transaction_at, income, expense,
|
||||
own_account, own_name, counterparty_account, counterparty_name,
|
||||
summary, purpose, currency, created_at
|
||||
) VALUES (?, 1, ?, ?, ?, ?, '测试', ?, '对方', '往来', '往来款', 'CNY', ?)
|
||||
""",
|
||||
(sheet_batch_id, at, income, expense, own, cp, utc_now()),
|
||||
)
|
||||
return int(cursor.lastrowid)
|
||||
|
||||
def test_opening_200_plus_outflow_100_equals_closing_300(self) -> None:
|
||||
item = calculation.create_opening_balance(
|
||||
self.connection, self.company_a, self.company_b, "200", "期初应收", self.admin
|
||||
)
|
||||
calculation.confirm_opening_balance(
|
||||
self.connection, item["id"], "确认", self.admin
|
||||
)
|
||||
row_a = self._add_row(
|
||||
self.company_a,
|
||||
self.account_a["id"],
|
||||
"6222000000000001",
|
||||
"6222000000000002",
|
||||
income="0",
|
||||
expense="100.00",
|
||||
at="2026-01-15T10:00:00",
|
||||
ref="sha-hel206-a",
|
||||
)
|
||||
row_b = self._add_row(
|
||||
self.company_b,
|
||||
self.account_b["id"],
|
||||
"6222000000000002",
|
||||
"6222000000000001",
|
||||
income="100.00",
|
||||
expense="0",
|
||||
at="2026-01-15T11:00:00",
|
||||
ref="sha-hel206-b",
|
||||
)
|
||||
matching.reconcile_rows(self.connection, [row_a, row_b])
|
||||
|
||||
bal_a = calculation.compute_pair_balance(
|
||||
self.connection, self.company_a, self.company_b, cutoff="2026-01-31"
|
||||
)
|
||||
bal_b = calculation.compute_pair_balance(
|
||||
self.connection, self.company_b, self.company_a, cutoff="2026-01-31"
|
||||
)
|
||||
self.assertEqual("200", bal_a["opening"])
|
||||
self.assertEqual("100.00", bal_a["net_change"])
|
||||
self.assertEqual("300.00", bal_a["closing"])
|
||||
self.assertEqual("-200", bal_b["opening"])
|
||||
self.assertEqual("-100.00", bal_b["net_change"])
|
||||
self.assertEqual("-300.00", bal_b["closing"])
|
||||
self.assertEqual(
|
||||
Decimal(bal_a["closing"]) + Decimal(bal_b["closing"]),
|
||||
Decimal("0"),
|
||||
)
|
||||
|
||||
|
||||
@unittest.skipUnless(sync_playwright, "playwright 未安装,跳过浏览器冒烟")
|
||||
@unittest.skipUnless(_chromium_available(), "chromium 无法启动,跳过浏览器冒烟")
|
||||
class Hel206BrowserDirectionTests(unittest.TestCase):
|
||||
"""真实 Chromium:公司端转账往来页期末方向与对手公司对称。"""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
_prepare_chrome_libs()
|
||||
cls.temp_dir = tempfile.TemporaryDirectory()
|
||||
root = Path(cls.temp_dir.name)
|
||||
cls.db_path = root / "app.db"
|
||||
cls.storage = root / "files"
|
||||
cls.storage.mkdir()
|
||||
|
||||
cls._old_db = server.DB_PATH
|
||||
cls._old_storage = server.STORAGE_DIR
|
||||
server.DB_PATH = cls.db_path
|
||||
server.STORAGE_DIR = cls.storage
|
||||
|
||||
connection = connect(cls.db_path)
|
||||
migrate(connection)
|
||||
auth.create_user(
|
||||
connection, "group-admin", ADMIN_PASSWORD, "admin",
|
||||
must_change_password=False,
|
||||
)
|
||||
cls.company_a = master_data.create_company(
|
||||
connection, "甲公司", None, None, None
|
||||
)
|
||||
cls.company_b = master_data.create_company(
|
||||
connection, "乙公司", None, None, None
|
||||
)
|
||||
auth.create_user(
|
||||
connection, "cashier-a", CASHIER_A_PASSWORD, "company",
|
||||
cls.company_a, must_change_password=False,
|
||||
)
|
||||
auth.create_user(
|
||||
connection, "cashier-b", CASHIER_B_PASSWORD, "company",
|
||||
cls.company_b, must_change_password=False,
|
||||
)
|
||||
admin = connection.execute(
|
||||
"SELECT * FROM users WHERE username = 'group-admin'"
|
||||
).fetchone()
|
||||
|
||||
def approve(company_id, number):
|
||||
account = master_data.submit_bank_account(
|
||||
connection,
|
||||
company_id=company_id,
|
||||
bank_name="中信银行",
|
||||
account_type="基本户",
|
||||
account_number=number,
|
||||
start_date="2026-01-01",
|
||||
actor=None,
|
||||
)
|
||||
return master_data.review_bank_account(
|
||||
connection, account["id"], "approve", None, admin,
|
||||
effective_from="2026-01-01",
|
||||
)
|
||||
|
||||
account_a = approve(cls.company_a, "6222000000000001")
|
||||
account_b = approve(cls.company_b, "6222000000000002")
|
||||
calculation.set_calculation_start_date(
|
||||
connection, "2026-01-01", "初始化起算", admin
|
||||
)
|
||||
item = calculation.create_opening_balance(
|
||||
connection, cls.company_a, cls.company_b, "200", "期初应收", admin
|
||||
)
|
||||
calculation.confirm_opening_balance(connection, item["id"], "确认", admin)
|
||||
|
||||
def add_row(company_id, account_id, own, cp, *, income, expense, at, ref):
|
||||
with connection:
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO source_files
|
||||
(sha256, original_filename, size_bytes, storage_path, created_at)
|
||||
VALUES (?, 'xfer.xlsx', 1, 'data/files/xfer.xlsx', ?)
|
||||
""",
|
||||
(ref, utc_now()),
|
||||
)
|
||||
source_file_id = int(cursor.lastrowid)
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO import_batches (
|
||||
source_file_id, status, company_id, upload_bank_account_id,
|
||||
created_at, updated_at
|
||||
) VALUES (?, 'parsed', ?, ?, ?, ?)
|
||||
""",
|
||||
(source_file_id, company_id, account_id, utc_now(), utc_now()),
|
||||
)
|
||||
batch_id = int(cursor.lastrowid)
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO sheet_batches (
|
||||
import_batch_id, sheet_name, bank_name, template_id,
|
||||
template_version, header_row, transaction_count, warnings,
|
||||
created_at
|
||||
) VALUES (?, '流水', '测试银行', 'test-v1', 1, 1, 1, '[]', ?)
|
||||
""",
|
||||
(batch_id, utc_now()),
|
||||
)
|
||||
sheet_batch_id = int(cursor.lastrowid)
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO sheet_reviews (
|
||||
import_batch_id, sheet_name, outcome, sheet_batch_id,
|
||||
review_status, created_at
|
||||
) VALUES (?, '流水', 'parsed', ?, 'confirmed', ?)
|
||||
""",
|
||||
(batch_id, sheet_batch_id, utc_now()),
|
||||
)
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO source_rows (
|
||||
sheet_batch_id, source_row, transaction_at, income, expense,
|
||||
own_account, own_name, counterparty_account, counterparty_name,
|
||||
summary, purpose, currency, created_at
|
||||
) VALUES (?, 1, ?, ?, ?, ?, '测试', ?, '对方', '往来', '往来款', 'CNY', ?)
|
||||
""",
|
||||
(sheet_batch_id, at, income, expense, own, cp, utc_now()),
|
||||
)
|
||||
return int(cursor.lastrowid)
|
||||
|
||||
row_a = add_row(
|
||||
cls.company_a, account_a["id"], "6222000000000001", "6222000000000002",
|
||||
income="0", expense="100.00", at="2026-01-15T10:00:00", ref="sha-hel206-br-a",
|
||||
)
|
||||
row_b = add_row(
|
||||
cls.company_b, account_b["id"], "6222000000000002", "6222000000000001",
|
||||
income="100.00", expense="0", at="2026-01-15T11:00:00", ref="sha-hel206-br-b",
|
||||
)
|
||||
matching.reconcile_rows(connection, [row_a, row_b])
|
||||
connection.close()
|
||||
|
||||
class QuietHandler(server.AppHandler):
|
||||
def log_message(self, *args) -> None:
|
||||
pass
|
||||
|
||||
cls.httpd = server.ThreadingHTTPServer(("127.0.0.1", 0), QuietHandler)
|
||||
cls.port = cls.httpd.server_address[1]
|
||||
cls.thread = threading.Thread(target=cls.httpd.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
cls.base = f"http://127.0.0.1:{cls.port}"
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls) -> None:
|
||||
cls.httpd.shutdown()
|
||||
cls.httpd.server_close()
|
||||
server.DB_PATH = cls._old_db
|
||||
server.STORAGE_DIR = cls._old_storage
|
||||
cls.temp_dir.cleanup()
|
||||
|
||||
def _login(self, page, *, username: str, password: str) -> None:
|
||||
page.goto(f"{self.base}/login-company.html", wait_until="domcontentloaded")
|
||||
page.fill("#account", username)
|
||||
page.fill("#password", password)
|
||||
page.click('button[type="submit"]')
|
||||
page.wait_for_url("**/company.html", timeout=15000)
|
||||
|
||||
def test_company_ending_direction_in_browser(self) -> None:
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(
|
||||
headless=True, args=["--no-sandbox", "--disable-dev-shm-usage"]
|
||||
)
|
||||
try:
|
||||
context = browser.new_context(viewport={"width": 1440, "height": 900})
|
||||
page = context.new_page()
|
||||
errors: list[str] = []
|
||||
page.on("pageerror", lambda err: errors.append(str(err)))
|
||||
|
||||
# 甲公司:期初 200 + 转出 100 → 期末应收 300
|
||||
self._login(page, username="cashier-a", password=CASHIER_A_PASSWORD)
|
||||
page.click('a[data-view="transfers"]')
|
||||
page.wait_for_selector("#tfStatEndingCard:not([hidden])", timeout=15000)
|
||||
bal_a = page.evaluate(
|
||||
"""async () => {
|
||||
const res = await fetch('/api/company/balances?cutoff=2026-01-31');
|
||||
return await res.json();
|
||||
}"""
|
||||
)
|
||||
self.assertEqual("ok", bal_a.get("status"))
|
||||
self.assertEqual("full", bal_a.get("basis"))
|
||||
pair_a = next(
|
||||
p for p in bal_a["pairs"]
|
||||
if p["counterparty_company_id"] == self.company_b
|
||||
)
|
||||
self.assertEqual("200", pair_a["opening"])
|
||||
self.assertEqual("100.00", pair_a["net_change"])
|
||||
self.assertEqual("300.00", pair_a["closing"])
|
||||
ending_text = page.locator("#tfStatEnding").inner_text()
|
||||
self.assertIn("0.03", ending_text) # 300 元 = 0.03 万元
|
||||
self.assertEqual([], errors, errors)
|
||||
|
||||
# 乙公司:对称应付 300
|
||||
self._login(page, username="cashier-b", password=CASHIER_B_PASSWORD)
|
||||
page.click('a[data-view="transfers"]')
|
||||
page.wait_for_selector("#tfStatEndingCard:not([hidden])", timeout=15000)
|
||||
bal_b = page.evaluate(
|
||||
"""async () => {
|
||||
const res = await fetch('/api/company/balances?cutoff=2026-01-31');
|
||||
return await res.json();
|
||||
}"""
|
||||
)
|
||||
pair_b = next(
|
||||
p for p in bal_b["pairs"]
|
||||
if p["counterparty_company_id"] == self.company_a
|
||||
)
|
||||
self.assertEqual("-200", pair_b["opening"])
|
||||
self.assertEqual("-100.00", pair_b["net_change"])
|
||||
self.assertEqual("-300.00", pair_b["closing"])
|
||||
ending_b = page.locator("#tfStatEnding").inner_text()
|
||||
self.assertIn("0.03", ending_b)
|
||||
fatal = [e for e in errors if "is not defined" in e or "Cannot read" in e]
|
||||
self.assertEqual([], fatal, fatal)
|
||||
finally:
|
||||
browser.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,294 +0,0 @@
|
||||
"""HEL-351: 夜间控件、一次性初始密码交付、缩放滚动条契约。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import threading
|
||||
import unittest
|
||||
from functools import partial
|
||||
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
WEB = ROOT / "web"
|
||||
|
||||
try:
|
||||
from playwright.sync_api import sync_playwright
|
||||
except ImportError: # pragma: no cover
|
||||
sync_playwright = None
|
||||
|
||||
|
||||
def _prepare_chrome_libs() -> Path | None:
|
||||
candidates = [ROOT / ".chrome-libs" / "lib"]
|
||||
for lib_dir in candidates:
|
||||
if (lib_dir / "libatk-1.0.so.0").exists():
|
||||
current = os.environ.get("LD_LIBRARY_PATH", "")
|
||||
prefix = str(lib_dir)
|
||||
if prefix not in current.split(":"):
|
||||
os.environ["LD_LIBRARY_PATH"] = (
|
||||
f"{prefix}:{current}" if current else prefix
|
||||
)
|
||||
return lib_dir
|
||||
return None
|
||||
|
||||
|
||||
def _chromium_available() -> bool:
|
||||
if not sync_playwright:
|
||||
return False
|
||||
_prepare_chrome_libs()
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, args=["--no-sandbox"])
|
||||
browser.close()
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
class Hel351SourceContractTests(unittest.TestCase):
|
||||
def test_night_select_and_scrollbar_use_tokens(self) -> None:
|
||||
css = (WEB / "design-system.css").read_text(encoding="utf-8")
|
||||
self.assertIn("color-scheme: light", css)
|
||||
self.assertIn("color-scheme: dark", css)
|
||||
self.assertIn("scrollbar-color: var(--gold) var(--surface-2)", css)
|
||||
self.assertIn("html[data-theme=\"night\"] ::-webkit-scrollbar-thumb", css)
|
||||
self.assertIn("background-color: var(--gold)", css)
|
||||
self.assertIn(".select option", css)
|
||||
self.assertIn("background-color: var(--surface)", css)
|
||||
self.assertIn("html[data-theme=\"night\"] .ds-dp-day.is-selected", css)
|
||||
self.assertIn("color: var(--gold)", css)
|
||||
self.assertNotIn("overflow: hidden; /* HEL-351", css)
|
||||
|
||||
def test_tabs_and_table_split_overflow_axes(self) -> None:
|
||||
css = (WEB / "design-system.css").read_text(encoding="utf-8")
|
||||
tabs = css[css.index(".tabs {") : css.index(".tabs button")]
|
||||
self.assertIn("overflow-x: auto", tabs)
|
||||
self.assertIn("overflow-y: hidden", tabs)
|
||||
wrap = css[css.index(".table-wrap {") : css.index(".table-wrap.dash-master-scroll")]
|
||||
self.assertIn("overflow-x: auto", wrap)
|
||||
self.assertIn("overflow-y: hidden", wrap)
|
||||
self.assertIn(".table-wrap.dash-master-scroll", css)
|
||||
self.assertIn("overflow-y: auto", css[css.index(".table-wrap.dash-master-scroll") :][:180])
|
||||
|
||||
def test_admin_delivers_once_password_window(self) -> None:
|
||||
html = (WEB / "admin.html").read_text(encoding="utf-8")
|
||||
self.assertIn('id="credentialDialog"', html)
|
||||
self.assertIn('id="cred-pass"', html)
|
||||
self.assertIn('id="cred-copy-pass"', html)
|
||||
self.assertIn("select.js?v=1", html)
|
||||
self.assertIn("datepicker.js?v=2", html)
|
||||
self.assertNotIn("初始密码由管理员统一发放", html)
|
||||
js = (WEB / "app.js").read_text(encoding="utf-8")
|
||||
self.assertIn("function showOnceCredentials(", js)
|
||||
self.assertIn("function wipeCredentials(", js)
|
||||
self.assertNotIn("初始密码已生成(仅此一次显示):${result.initial_password}", js)
|
||||
self.assertNotIn("临时密码已生成(仅此一次):${result.initial_password}", js)
|
||||
self.assertIn('openModal("credentialDialog")', js)
|
||||
|
||||
def test_datepicker_follows_trigger_and_flips(self) -> None:
|
||||
js = (WEB / "datepicker.js").read_text(encoding="utf-8")
|
||||
css = (WEB / "design-system.css").read_text(encoding="utf-8")
|
||||
self.assertIn("visualViewport", js)
|
||||
self.assertIn("getBoundingClientRect", js)
|
||||
self.assertIn("rect.top - gap - height", js)
|
||||
self.assertIn('addEventListener("scroll", position, true)', js)
|
||||
block = css[css.index(".ds-datepicker {") : css.index(".ds-datepicker[hidden]")]
|
||||
self.assertIn("position: fixed", block)
|
||||
self.assertIn("z-index: var(--z-tooltip)", block)
|
||||
|
||||
|
||||
@unittest.skipUnless(sync_playwright, "playwright 未安装,跳过浏览器探针")
|
||||
@unittest.skipUnless(_chromium_available(), "chromium 无法启动,跳过浏览器探针")
|
||||
class Hel351BrowserProbeTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
handler = partial(SimpleHTTPRequestHandler, directory=str(WEB))
|
||||
cls.httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
cls.port = cls.httpd.server_address[1]
|
||||
cls.thread = threading.Thread(target=cls.httpd.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
cls.base = f"http://127.0.0.1:{cls.port}"
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls) -> None:
|
||||
cls.httpd.shutdown()
|
||||
cls.httpd.server_close()
|
||||
|
||||
def _open(self, page, *, night: bool, width: int = 1440, zoom: float = 1) -> None:
|
||||
page.set_viewport_size({"width": width, "height": 900})
|
||||
theme_attr = 'data-theme="night"' if night else 'data-theme="day"'
|
||||
page.set_content(
|
||||
f"""<!doctype html>
|
||||
<html lang="zh-CN" class="v-fusion" {theme_attr}>
|
||||
<head>
|
||||
<meta charset="UTF-8"/>
|
||||
<link rel="stylesheet" href="{self.base}/design-system.css"/>
|
||||
</head>
|
||||
<body class="is-app" {theme_attr}>
|
||||
<div class="tabs" id="probe-tabs">
|
||||
<button class="active">全部</button>
|
||||
<button>流水断档</button>
|
||||
<button>单边匹配</button>
|
||||
<button>科目确认</button>
|
||||
<button>起算区间校准</button>
|
||||
<button>银行账户登记</button>
|
||||
<button>公司手工记录</button>
|
||||
<button>重开审批</button>
|
||||
</div>
|
||||
<select class="select" id="probe-select">
|
||||
<option value="">请选择公司</option>
|
||||
<option>河南金牛农业科技发展有限公司</option>
|
||||
<option>河南金牛煤业有限公司</option>
|
||||
<option disabled>停用账户(不可选)</option>
|
||||
</select>
|
||||
<input class="input" id="probe-date" type="date" value="2026-09-01" />
|
||||
<script src="{self.base}/select.js"></script>
|
||||
<script src="{self.base}/datepicker.js"></script>
|
||||
</body></html>""",
|
||||
wait_until="domcontentloaded",
|
||||
)
|
||||
page.wait_for_function("() => window.JinniuDatePicker && window.JinniuSelect")
|
||||
if zoom != 1:
|
||||
page.evaluate(f"() => {{ document.body.style.zoom = '{zoom}'; }}")
|
||||
|
||||
def test_night_select_is_not_white_on_white(self) -> None:
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, args=["--no-sandbox"])
|
||||
page = browser.new_page(viewport={"width": 1440, "height": 900})
|
||||
self._open(page, night=True)
|
||||
page.locator("#probe-select").locator("xpath=ancestor::div[contains(@class,'ds-combo')]").locator(".ds-combo-trigger").click()
|
||||
page.wait_for_selector("#ds-listbox:not([hidden])")
|
||||
colors = page.evaluate(
|
||||
"""() => {
|
||||
const trigger = document.querySelector('#probe-select').closest('.ds-combo').querySelector('.ds-combo-trigger');
|
||||
const box = document.getElementById('ds-listbox');
|
||||
const placeholder = box.querySelector('.is-placeholder');
|
||||
const plain = [...box.querySelectorAll('.ds-listbox-option')].find((el) => !el.classList.contains('is-placeholder') && !el.classList.contains('is-disabled') && !el.classList.contains('is-selected'));
|
||||
const disabled = box.querySelector('.is-disabled');
|
||||
const tcs = getComputedStyle(trigger);
|
||||
const bcs = getComputedStyle(box);
|
||||
const pcs = placeholder && getComputedStyle(placeholder);
|
||||
const ncs = plain && getComputedStyle(plain);
|
||||
const dcs = disabled && getComputedStyle(disabled);
|
||||
return {
|
||||
triggerBg: tcs.backgroundColor,
|
||||
triggerColor: tcs.color,
|
||||
boxBg: bcs.backgroundColor,
|
||||
boxColor: bcs.color,
|
||||
placeholderColor: pcs && pcs.color,
|
||||
placeholderBg: pcs && pcs.backgroundColor,
|
||||
plainColor: ncs && ncs.color,
|
||||
plainBg: ncs && ncs.backgroundColor,
|
||||
disabledColor: dcs && dcs.color,
|
||||
};
|
||||
}"""
|
||||
)
|
||||
browser.close()
|
||||
white = "rgb(255, 255, 255)"
|
||||
self.assertNotEqual(white, colors["triggerBg"])
|
||||
self.assertNotEqual(white, colors["triggerColor"])
|
||||
self.assertNotEqual(white, colors["boxBg"])
|
||||
self.assertNotEqual(white, colors["boxColor"])
|
||||
self.assertNotEqual(white, colors["placeholderBg"])
|
||||
self.assertNotEqual(white, colors["placeholderColor"])
|
||||
self.assertNotEqual(white, colors["plainBg"])
|
||||
self.assertNotEqual(white, colors["plainColor"])
|
||||
self.assertNotEqual(white, colors["disabledColor"])
|
||||
|
||||
def test_tabs_have_no_vertical_scrollbar_at_zoom(self) -> None:
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, args=["--no-sandbox"])
|
||||
page = browser.new_page(viewport={"width": 390, "height": 800})
|
||||
self._open(page, night=False, width=390, zoom=1.25)
|
||||
metrics = page.evaluate(
|
||||
"""() => {
|
||||
const tabs = document.getElementById('probe-tabs');
|
||||
const cs = getComputedStyle(tabs);
|
||||
return {
|
||||
overflowX: cs.overflowX,
|
||||
overflowY: cs.overflowY,
|
||||
clientHeight: tabs.clientHeight,
|
||||
scrollHeight: tabs.scrollHeight,
|
||||
clientWidth: tabs.clientWidth,
|
||||
scrollWidth: tabs.scrollWidth,
|
||||
};
|
||||
}"""
|
||||
)
|
||||
browser.close()
|
||||
self.assertEqual("auto", metrics["overflowX"])
|
||||
self.assertEqual("hidden", metrics["overflowY"])
|
||||
self.assertLessEqual(metrics["scrollHeight"] - metrics["clientHeight"], 1)
|
||||
|
||||
def test_datepicker_anchors_and_night_gold(self) -> None:
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, args=["--no-sandbox"])
|
||||
page = browser.new_page(viewport={"width": 1440, "height": 900})
|
||||
self._open(page, night=True)
|
||||
page.click("#probe-date")
|
||||
page.wait_for_selector("#ds-datepicker:not([hidden])")
|
||||
box = page.evaluate(
|
||||
"""() => {
|
||||
const input = document.getElementById('probe-date');
|
||||
const panel = document.getElementById('ds-datepicker');
|
||||
const ir = input.getBoundingClientRect();
|
||||
const pr = panel.getBoundingClientRect();
|
||||
const selected = panel.querySelector('.ds-dp-day.is-selected');
|
||||
const cs = selected ? getComputedStyle(selected) : null;
|
||||
return {
|
||||
inputBottom: ir.bottom,
|
||||
inputLeft: ir.left,
|
||||
panelTop: pr.top,
|
||||
panelLeft: pr.left,
|
||||
panelRight: pr.right,
|
||||
viewportWidth: window.innerWidth,
|
||||
selectedColor: cs && cs.color,
|
||||
selectedBg: cs && cs.backgroundColor,
|
||||
hidden: panel.hidden,
|
||||
};
|
||||
}"""
|
||||
)
|
||||
browser.close()
|
||||
self.assertFalse(box["hidden"])
|
||||
self.assertLess(abs(box["panelTop"] - box["inputBottom"]), 24)
|
||||
self.assertLess(abs(box["panelLeft"] - box["inputLeft"]), 24)
|
||||
self.assertLess(box["panelRight"], box["viewportWidth"])
|
||||
self.assertIsNotNone(box["selectedColor"])
|
||||
self.assertNotEqual("rgb(255, 255, 255)", box["selectedBg"])
|
||||
self.assertIn("217", box["selectedColor"])
|
||||
|
||||
def test_datepicker_flips_when_near_bottom(self) -> None:
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, args=["--no-sandbox"])
|
||||
page = browser.new_page(viewport={"width": 1440, "height": 500})
|
||||
page.set_content(
|
||||
f"""<!doctype html>
|
||||
<html lang="zh-CN" class="v-fusion" data-theme="night">
|
||||
<head>
|
||||
<meta charset="UTF-8"/>
|
||||
<link rel="stylesheet" href="{self.base}/design-system.css"/>
|
||||
</head>
|
||||
<body class="is-app" data-theme="night" style="min-height:100vh">
|
||||
<input class="input" id="probe-date" type="date" value="2026-09-01" style="position:fixed;left:24px;bottom:12px;width:180px" />
|
||||
<script src="{self.base}/datepicker.js"></script>
|
||||
</body></html>""",
|
||||
wait_until="domcontentloaded",
|
||||
)
|
||||
page.wait_for_function("() => window.JinniuDatePicker")
|
||||
page.click("#probe-date")
|
||||
page.wait_for_selector("#ds-datepicker:not([hidden])")
|
||||
box = page.evaluate(
|
||||
"""() => {
|
||||
const input = document.getElementById('probe-date');
|
||||
const panel = document.getElementById('ds-datepicker');
|
||||
const ir = input.getBoundingClientRect();
|
||||
const pr = panel.getBoundingClientRect();
|
||||
return { inputTop: ir.top, panelBottom: pr.bottom, panelTop: pr.top };
|
||||
}"""
|
||||
)
|
||||
browser.close()
|
||||
self.assertLess(box["panelBottom"], box["inputTop"] + 2)
|
||||
self.assertGreater(box["inputTop"] - box["panelBottom"], 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,411 +0,0 @@
|
||||
"""HEL-360: 手机端 Toast 覆盖层不得拦截页面点击。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from functools import partial
|
||||
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
from bank_importer import auth, master_data
|
||||
from bank_importer.db import connect, migrate
|
||||
|
||||
import server
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
WEB = ROOT / "web"
|
||||
ADMIN_PASSWORD = "AdminPass123"
|
||||
CASHIER_PASSWORD = "CashierA123"
|
||||
|
||||
try:
|
||||
from playwright.sync_api import sync_playwright
|
||||
except ImportError: # pragma: no cover
|
||||
sync_playwright = None
|
||||
|
||||
|
||||
def _prepare_chrome_libs() -> Path | None:
|
||||
candidates = [ROOT / ".chrome-libs" / "lib"]
|
||||
for lib_dir in candidates:
|
||||
if (lib_dir / "libatk-1.0.so.0").exists():
|
||||
current = os.environ.get("LD_LIBRARY_PATH", "")
|
||||
prefix = str(lib_dir)
|
||||
if prefix not in current.split(":"):
|
||||
os.environ["LD_LIBRARY_PATH"] = (
|
||||
f"{prefix}:{current}" if current else prefix
|
||||
)
|
||||
return lib_dir
|
||||
return None
|
||||
|
||||
|
||||
def _chromium_available() -> bool:
|
||||
if not sync_playwright:
|
||||
return False
|
||||
_prepare_chrome_libs()
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, args=["--no-sandbox"])
|
||||
browser.close()
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _css_rule(css: str, selector: str) -> str:
|
||||
match = re.search(rf"{re.escape(selector)} \{{([^}}]*)\}}", css)
|
||||
if not match:
|
||||
raise AssertionError(f"missing rule {selector}")
|
||||
return match.group(1)
|
||||
|
||||
|
||||
def _mouse_click_center(page, selector: str) -> tuple[float, float]:
|
||||
loc = page.locator(selector).first
|
||||
loc.wait_for(state="visible", timeout=8000)
|
||||
loc.scroll_into_view_if_needed()
|
||||
page.wait_for_function(
|
||||
"""(sel) => {
|
||||
const el = document.querySelector(sel);
|
||||
if (!el) return false;
|
||||
const r = el.getBoundingClientRect();
|
||||
return r.width > 2 && r.height > 2 && r.right > 0 && r.bottom > 0
|
||||
&& r.left < window.innerWidth && r.top < window.innerHeight;
|
||||
}""",
|
||||
arg=selector,
|
||||
timeout=4000,
|
||||
)
|
||||
box = loc.bounding_box()
|
||||
assert box, f"{selector} has no box"
|
||||
x = box["x"] + box["width"] / 2
|
||||
y = box["y"] + box["height"] / 2
|
||||
page.mouse.click(x, y)
|
||||
return x, y
|
||||
|
||||
|
||||
def _hit(page, x: float, y: float) -> dict:
|
||||
return page.evaluate(
|
||||
"""({x, y}) => {
|
||||
const el = document.elementFromPoint(x, y);
|
||||
const region = document.getElementById('toastRegion');
|
||||
const toast = el && el.closest ? el.closest('.toast') : null;
|
||||
return {
|
||||
tag: el ? el.tagName : null,
|
||||
id: el ? el.id : null,
|
||||
className: el && el.className ? String(el.className) : '',
|
||||
inRegion: !!(region && el && region.contains(el)),
|
||||
inToast: !!toast,
|
||||
regionPe: region ? getComputedStyle(region).pointerEvents : null,
|
||||
toastPe: toast ? getComputedStyle(toast).pointerEvents : null,
|
||||
};
|
||||
}""",
|
||||
{"x": x, "y": y},
|
||||
)
|
||||
|
||||
|
||||
class Hel360SourceContractTests(unittest.TestCase):
|
||||
def test_toast_region_passes_clicks_to_toast_only(self) -> None:
|
||||
css = (WEB / "design-system.css").read_text(encoding="utf-8")
|
||||
region = _css_rule(css, ".toast-region")
|
||||
toast = _css_rule(css, ".toast")
|
||||
self.assertIn("pointer-events: none", region)
|
||||
self.assertIn("pointer-events: auto", toast)
|
||||
self.assertIn("z-index: var(--z-toast)", region)
|
||||
mobile = css[css.index("@media (max-width: 720px) {\n .toast-region") :]
|
||||
mobile_block = mobile[: mobile.index("\n}")]
|
||||
self.assertIn("left: 12px", mobile_block)
|
||||
self.assertIn("bottom: 12px", mobile_block)
|
||||
self.assertIn("right: 12px", mobile_block)
|
||||
self.assertNotIn("pointer-events: none !important", css)
|
||||
self.assertNotIn("z-index: -1", region)
|
||||
self.assertNotIn("z-index: 0", region)
|
||||
|
||||
|
||||
@unittest.skipUnless(sync_playwright, "playwright 未安装,跳过浏览器探针")
|
||||
@unittest.skipUnless(_chromium_available(), "chromium 无法启动,跳过浏览器探针")
|
||||
class Hel360CssPointerProbeTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
handler = partial(SimpleHTTPRequestHandler, directory=str(WEB))
|
||||
cls.httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
cls.port = cls.httpd.server_address[1]
|
||||
cls.thread = threading.Thread(target=cls.httpd.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
cls.base = f"http://127.0.0.1:{cls.port}"
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls) -> None:
|
||||
cls.httpd.shutdown()
|
||||
cls.httpd.server_close()
|
||||
|
||||
def _open(self, page, *, night: bool, width: int, height: int = 640) -> None:
|
||||
page.set_viewport_size({"width": width, "height": height})
|
||||
theme = "night" if night else "day"
|
||||
page.set_content(
|
||||
f"""<!doctype html>
|
||||
<html lang="zh-CN" class="v-fusion" data-theme="{theme}">
|
||||
<head>
|
||||
<meta charset="UTF-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
|
||||
<link rel="stylesheet" href="{self.base}/design-system.css"/>
|
||||
</head>
|
||||
<body class="is-app" data-theme="{theme}" style="margin:0;min-height:100vh">
|
||||
<button type="button" id="page-btn" style="position:fixed;left:50%;top:58%;transform:translate(-50%,-50%);z-index:1">页面按钮</button>
|
||||
<a id="page-nav" href="#pair" style="position:fixed;left:16px;top:88px;z-index:1">往来查询</a>
|
||||
<div class="tabs" style="position:fixed;left:16px;top:124px;z-index:1;width:220px">
|
||||
<button type="button" id="page-tab">页签</button>
|
||||
</div>
|
||||
<input class="input" id="page-date" type="date" value="2026-09-01" style="position:fixed;left:16px;top:176px;z-index:1;width:160px" />
|
||||
<div class="toast-region" id="toastRegion" aria-live="polite">
|
||||
<div class="toast info" id="the-toast" role="status">
|
||||
<span class="t-dot"></span>
|
||||
<div class="t-body">
|
||||
<div class="t-title">提示</div>
|
||||
<button type="button" id="toast-copy">复制</button>
|
||||
<button type="button" id="toast-close">关闭</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
window.__clicks = [];
|
||||
["page-btn","page-nav","page-tab","page-date","toast-copy","toast-close"].forEach((id) => {{
|
||||
document.getElementById(id).addEventListener("click", () => window.__clicks.push(id));
|
||||
}});
|
||||
</script>
|
||||
</body></html>""",
|
||||
wait_until="domcontentloaded",
|
||||
)
|
||||
page.wait_for_selector("#toastRegion")
|
||||
|
||||
def test_empty_overlay_does_not_eat_real_clicks(self) -> None:
|
||||
cases = [
|
||||
(360, False, 640),
|
||||
(390, True, 640),
|
||||
(820, False, 900),
|
||||
(1440, True, 900),
|
||||
]
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, args=["--no-sandbox"])
|
||||
page = browser.new_page()
|
||||
try:
|
||||
for width, night, height in cases:
|
||||
with self.subTest(width=width, night=night):
|
||||
self._open(page, night=night, width=width, height=height)
|
||||
metrics = page.evaluate(
|
||||
"""() => {
|
||||
const tr = document.getElementById('toastRegion');
|
||||
const toast = document.getElementById('the-toast');
|
||||
const r = tr.getBoundingClientRect();
|
||||
return {
|
||||
regionPe: getComputedStyle(tr).pointerEvents,
|
||||
toastPe: getComputedStyle(toast).pointerEvents,
|
||||
height: r.height,
|
||||
width: r.width,
|
||||
top: r.top,
|
||||
viewportH: window.innerHeight,
|
||||
};
|
||||
}"""
|
||||
)
|
||||
self.assertEqual("none", metrics["regionPe"], metrics)
|
||||
self.assertEqual("auto", metrics["toastPe"], metrics)
|
||||
if width <= 720:
|
||||
self.assertGreater(metrics["height"], metrics["viewportH"] - 40, metrics)
|
||||
|
||||
page.evaluate("() => { window.__clicks = []; }")
|
||||
_mouse_click_center(page, "#page-btn")
|
||||
_mouse_click_center(page, "#page-nav")
|
||||
_mouse_click_center(page, "#page-tab")
|
||||
_mouse_click_center(page, "#page-date")
|
||||
clicks = page.evaluate("() => window.__clicks.slice()")
|
||||
self.assertEqual(
|
||||
["page-btn", "page-nav", "page-tab", "page-date"],
|
||||
clicks,
|
||||
f"width={width} night={night} clicks={clicks}",
|
||||
)
|
||||
|
||||
cx, cy = _mouse_click_center(page, "#toast-copy")
|
||||
hit = _hit(page, cx, cy)
|
||||
self.assertTrue(hit["inToast"], hit)
|
||||
_mouse_click_center(page, "#toast-close")
|
||||
toast_clicks = page.evaluate("() => window.__clicks.slice(-2)")
|
||||
self.assertEqual(["toast-copy", "toast-close"], toast_clicks)
|
||||
|
||||
mid_x = width / 2
|
||||
mid_y = height * 0.58
|
||||
mid = _hit(page, mid_x, mid_y)
|
||||
self.assertFalse(mid["inRegion"] and not mid["inToast"], mid)
|
||||
self.assertEqual("none", mid["regionPe"], mid)
|
||||
finally:
|
||||
browser.close()
|
||||
|
||||
|
||||
@unittest.skipUnless(sync_playwright, "playwright 未安装,跳过浏览器冒烟")
|
||||
@unittest.skipUnless(_chromium_available(), "chromium 无法启动,跳过浏览器冒烟")
|
||||
class Hel360LiveAppClickTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
_prepare_chrome_libs()
|
||||
cls.temp_dir = tempfile.TemporaryDirectory()
|
||||
root = Path(cls.temp_dir.name)
|
||||
cls.db_path = root / "app.db"
|
||||
cls.storage = root / "files"
|
||||
cls.storage.mkdir()
|
||||
cls._old_db = server.DB_PATH
|
||||
cls._old_storage = server.STORAGE_DIR
|
||||
server.DB_PATH = cls.db_path
|
||||
server.STORAGE_DIR = cls.storage
|
||||
connection = connect(cls.db_path)
|
||||
migrate(connection)
|
||||
auth.create_user(
|
||||
connection, "group-admin", ADMIN_PASSWORD, "admin", must_change_password=False
|
||||
)
|
||||
company_id = master_data.create_company(connection, "甲公司", None, None, None)
|
||||
auth.create_user(
|
||||
connection,
|
||||
"cashier-a",
|
||||
CASHIER_PASSWORD,
|
||||
"company",
|
||||
company_id,
|
||||
must_change_password=False,
|
||||
)
|
||||
connection.close()
|
||||
|
||||
class QuietHandler(server.AppHandler):
|
||||
def log_message(self, *args) -> None:
|
||||
pass
|
||||
|
||||
cls.httpd = server.ThreadingHTTPServer(("127.0.0.1", 0), QuietHandler)
|
||||
cls.port = cls.httpd.server_address[1]
|
||||
cls.thread = threading.Thread(target=cls.httpd.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
cls.base = f"http://127.0.0.1:{cls.port}"
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls) -> None:
|
||||
cls.httpd.shutdown()
|
||||
cls.httpd.server_close()
|
||||
server.DB_PATH = cls._old_db
|
||||
server.STORAGE_DIR = cls._old_storage
|
||||
cls.temp_dir.cleanup()
|
||||
|
||||
def _login(self, page, *, portal: str) -> None:
|
||||
login_path = "login-admin.html" if portal == "admin" else "login-company.html"
|
||||
username = "group-admin" if portal == "admin" else "cashier-a"
|
||||
password = ADMIN_PASSWORD if portal == "admin" else CASHIER_PASSWORD
|
||||
page.goto(f"{self.base}/{login_path}", wait_until="domcontentloaded")
|
||||
page.fill("#account", username)
|
||||
page.fill("#password", password)
|
||||
page.locator('button[type="submit"]').click()
|
||||
expect = "admin.html" if portal == "admin" else "company.html"
|
||||
page.wait_for_url(f"**/{expect}", timeout=15000)
|
||||
page.wait_for_selector(".side-nav", timeout=10000)
|
||||
|
||||
def _set_theme(self, page, night: bool) -> None:
|
||||
theme = "night" if night else "day"
|
||||
page.evaluate(
|
||||
"""(theme) => {
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
document.body.setAttribute('data-theme', theme);
|
||||
try { localStorage.setItem('jinniu-theme', theme); } catch (e) {}
|
||||
}""",
|
||||
theme,
|
||||
)
|
||||
|
||||
def _goto_view(self, page, view: str) -> None:
|
||||
_mouse_click_center(page, f'.side-nav a[data-view="{view}"]')
|
||||
page.wait_for_selector(f'.app-view[data-page="{view}"].is-active', timeout=4000)
|
||||
|
||||
def _probe_toast_passthrough(self, page, width: int, height: int) -> None:
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
window.__pageHits = 0;
|
||||
const btn = document.querySelector('.topbar .icon-button, .menu-button, .btn');
|
||||
if (btn) btn.addEventListener('click', () => { window.__pageHits += 1; }, { once: true });
|
||||
if (typeof showToast === 'function') showToast('HEL-360', '点击穿透', 'info');
|
||||
}"""
|
||||
)
|
||||
page.wait_for_selector("#toastRegion .toast", timeout=4000)
|
||||
toast_box = page.locator("#toastRegion .toast").first.bounding_box()
|
||||
self.assertIsNotNone(toast_box)
|
||||
page.mouse.click(
|
||||
toast_box["x"] + toast_box["width"] / 2,
|
||||
toast_box["y"] + toast_box["height"] / 2,
|
||||
)
|
||||
toast_hit = _hit(
|
||||
page,
|
||||
toast_box["x"] + toast_box["width"] / 2,
|
||||
toast_box["y"] + toast_box["height"] / 2,
|
||||
)
|
||||
self.assertTrue(toast_hit["inToast"], toast_hit)
|
||||
self.assertEqual("auto", toast_hit["toastPe"], toast_hit)
|
||||
|
||||
empty_x = width / 2
|
||||
empty_y = height * 0.62
|
||||
empty = _hit(page, empty_x, empty_y)
|
||||
self.assertEqual("none", empty["regionPe"], empty)
|
||||
self.assertFalse(empty["inToast"], empty)
|
||||
self.assertFalse(empty["inRegion"], empty)
|
||||
page.mouse.click(empty_x, empty_y)
|
||||
after = _hit(page, empty_x, empty_y)
|
||||
self.assertFalse(after["inRegion"], after)
|
||||
|
||||
def test_real_clicks_reach_admin_and_company_controls(self) -> None:
|
||||
cases = [
|
||||
("admin", 360, 640, False),
|
||||
("admin", 390, 640, True),
|
||||
("company", 360, 640, True),
|
||||
("company", 390, 640, False),
|
||||
("admin", 820, 900, False),
|
||||
("admin", 1440, 900, True),
|
||||
]
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(
|
||||
headless=True, args=["--no-sandbox", "--disable-dev-shm-usage"]
|
||||
)
|
||||
try:
|
||||
for portal, width, height, night in cases:
|
||||
with self.subTest(portal=portal, width=width, night=night):
|
||||
context = browser.new_context(viewport={"width": 1440, "height": 900})
|
||||
page = context.new_page()
|
||||
try:
|
||||
self._login(page, portal=portal)
|
||||
self._set_theme(page, night)
|
||||
page.set_viewport_size({"width": width, "height": height})
|
||||
page.wait_for_timeout(200)
|
||||
region = page.evaluate(
|
||||
"""() => {
|
||||
const tr = document.getElementById('toastRegion');
|
||||
const cs = getComputedStyle(tr);
|
||||
const r = tr.getBoundingClientRect();
|
||||
return { pe: cs.pointerEvents, height: r.height, vw: window.innerWidth };
|
||||
}"""
|
||||
)
|
||||
self.assertEqual("none", region["pe"], region)
|
||||
|
||||
if portal == "admin":
|
||||
self._goto_view(page, "audit")
|
||||
tab_sel = '#auditTabs button[data-audit-filter="断档"]'
|
||||
_mouse_click_center(page, tab_sel)
|
||||
self.assertEqual("true", page.locator(tab_sel).get_attribute("aria-pressed"))
|
||||
self._goto_view(page, "pair")
|
||||
date_sel = "#pairEnd"
|
||||
else:
|
||||
self._goto_view(page, "reconcile")
|
||||
_mouse_click_center(page, "#tab-subject")
|
||||
self.assertTrue(page.locator("#panel-subject").is_visible())
|
||||
self._goto_view(page, "flows")
|
||||
date_sel = "#flowStart"
|
||||
page.locator(date_sel).scroll_into_view_if_needed()
|
||||
_mouse_click_center(page, date_sel)
|
||||
page.wait_for_selector("#ds-datepicker:not([hidden])", timeout=4000)
|
||||
page.keyboard.press("Escape")
|
||||
self._probe_toast_passthrough(page, width, height)
|
||||
finally:
|
||||
context.close()
|
||||
finally:
|
||||
browser.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,425 +0,0 @@
|
||||
"""HEL-373: 黑金下拉全状态 + 日期年月直选。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import threading
|
||||
import unittest
|
||||
from functools import partial
|
||||
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
WEB = ROOT / "web"
|
||||
SHOT_DIR = ROOT.parent / "hel373-shots"
|
||||
|
||||
try:
|
||||
from playwright.sync_api import sync_playwright
|
||||
except ImportError: # pragma: no cover
|
||||
sync_playwright = None
|
||||
|
||||
|
||||
def _prepare_chrome_libs() -> Path | None:
|
||||
candidates = [ROOT / ".chrome-libs" / "lib"]
|
||||
for lib_dir in candidates:
|
||||
if (lib_dir / "libatk-1.0.so.0").exists():
|
||||
current = os.environ.get("LD_LIBRARY_PATH", "")
|
||||
prefix = str(lib_dir)
|
||||
if prefix not in current.split(":"):
|
||||
os.environ["LD_LIBRARY_PATH"] = (
|
||||
f"{prefix}:{current}" if current else prefix
|
||||
)
|
||||
return lib_dir
|
||||
return None
|
||||
|
||||
|
||||
def _chromium_available() -> bool:
|
||||
if not sync_playwright:
|
||||
return False
|
||||
_prepare_chrome_libs()
|
||||
try:
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, args=["--no-sandbox"])
|
||||
browser.close()
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
PROBE_HTML = """<!doctype html>
|
||||
<html lang="zh-CN" class="v-fusion" {theme_attr}>
|
||||
<head>
|
||||
<meta charset="UTF-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||
<link rel="stylesheet" href="{base}/design-system.css"/>
|
||||
</head>
|
||||
<body class="is-app" {theme_attr} style="padding:24px">
|
||||
<div class="filters" style="max-width:720px">
|
||||
<div class="field" style="flex:1 1 220px">
|
||||
<label for="probe-empty">对方公司</label>
|
||||
<select class="select" id="probe-empty">
|
||||
<option value="">请选择集团内公司</option>
|
||||
<option value="a">河南金牛农业科技发展有限公司</option>
|
||||
<option value="b">河南金牛煤业有限公司</option>
|
||||
<option value="c" disabled>停用账户</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="field" style="flex:1 1 220px">
|
||||
<label for="probe-filled">本方公司</label>
|
||||
<select class="select" id="probe-filled">
|
||||
<option value="a">河南金牛农业科技发展有限公司</option>
|
||||
<option value="b" selected>河南金牛煤业有限公司</option>
|
||||
<option value="c">河南金牛物流有限公司</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="field" style="max-width:220px;margin-top:16px">
|
||||
<label for="probe-date">起算日</label>
|
||||
<input class="input" id="probe-date" type="date" value="2026-01-31" min="2020-03-15" max="2028-11-30" />
|
||||
</div>
|
||||
<div class="field" style="max-width:220px;margin-top:16px">
|
||||
<label for="probe-free-date">无上下限日期</label>
|
||||
<input class="input" id="probe-free-date" type="date" value="2026-09-01" />
|
||||
</div>
|
||||
<script src="{base}/select.js"></script>
|
||||
<script src="{base}/datepicker.js"></script>
|
||||
</body></html>
|
||||
"""
|
||||
|
||||
|
||||
class Hel373SourceContractTests(unittest.TestCase):
|
||||
def test_custom_listbox_and_year_month_exist(self) -> None:
|
||||
css = (WEB / "design-system.css").read_text(encoding="utf-8")
|
||||
js_select = (WEB / "select.js").read_text(encoding="utf-8")
|
||||
js_date = (WEB / "datepicker.js").read_text(encoding="utf-8")
|
||||
admin = (WEB / "admin.html").read_text(encoding="utf-8")
|
||||
company = (WEB / "company.html").read_text(encoding="utf-8")
|
||||
self.assertIn("select.select", js_select)
|
||||
self.assertIn('setAttribute("role", "combobox")', js_select)
|
||||
self.assertIn('setAttribute("role", "listbox")', js_select)
|
||||
self.assertIn("JinniuSelect", js_select)
|
||||
self.assertIn("data-dp-year", js_date)
|
||||
self.assertIn("data-dp-month", js_date)
|
||||
self.assertIn("YEAR_PAD", js_date)
|
||||
self.assertIn(".ds-listbox", css)
|
||||
self.assertIn(".ds-combo-trigger", css)
|
||||
self.assertIn(".ds-listbox-option.is-placeholder", css)
|
||||
self.assertIn("html[data-theme=\"night\"] .ds-listbox", css)
|
||||
self.assertIn("var(--gold-line)", css[css.index("html[data-theme=\"night\"] .ds-listbox") :])
|
||||
self.assertIn("html[data-theme=\"night\"] .ds-listbox-option.is-selected", css)
|
||||
self.assertIn("select.js?v=1", admin)
|
||||
self.assertIn("select.js?v=1", company)
|
||||
self.assertIn("datepicker.js?v=2", admin)
|
||||
self.assertIn("datepicker.js?v=2", company)
|
||||
self.assertIn("design-system.css?v=14", admin)
|
||||
self.assertIn("design-system.css?v=14", company)
|
||||
|
||||
def test_listbox_uses_tokens_not_hardcoded_night_hex(self) -> None:
|
||||
css = (WEB / "design-system.css").read_text(encoding="utf-8")
|
||||
start = css.index("/* ─── 主题化 combobox")
|
||||
end = css.index("@media (prefers-reduced-motion: reduce)", start)
|
||||
block = css[start:end]
|
||||
self.assertNotIn("#fff", block)
|
||||
self.assertNotIn("#ffffff", block.lower())
|
||||
self.assertNotIn("#000", block)
|
||||
self.assertIn("var(--surface)", block)
|
||||
self.assertIn("var(--text)", block)
|
||||
self.assertIn("var(--gold)", block)
|
||||
self.assertIn("var(--fill)", block)
|
||||
|
||||
|
||||
@unittest.skipUnless(sync_playwright, "playwright 未安装,跳过浏览器探针")
|
||||
@unittest.skipUnless(_chromium_available(), "chromium 无法启动,跳过浏览器探针")
|
||||
class Hel373BrowserProbeTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
handler = partial(SimpleHTTPRequestHandler, directory=str(WEB))
|
||||
cls.httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
cls.port = cls.httpd.server_address[1]
|
||||
cls.thread = threading.Thread(target=cls.httpd.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
cls.base = f"http://127.0.0.1:{cls.port}"
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls) -> None:
|
||||
cls.httpd.shutdown()
|
||||
cls.httpd.server_close()
|
||||
|
||||
def _open(self, page, *, night: bool, width: int = 1440, height: int = 900) -> None:
|
||||
page.set_viewport_size({"width": width, "height": height})
|
||||
theme_attr = 'data-theme="night"' if night else 'data-theme="day"'
|
||||
page.set_content(
|
||||
PROBE_HTML.format(theme_attr=theme_attr, base=self.base),
|
||||
wait_until="domcontentloaded",
|
||||
)
|
||||
page.wait_for_function("() => window.JinniuDatePicker && window.JinniuSelect")
|
||||
page.wait_for_selector("#probe-empty + .ds-combo-trigger, .ds-combo #probe-empty")
|
||||
page.wait_for_function(
|
||||
"() => document.querySelectorAll('.ds-combo-trigger').length >= 2"
|
||||
)
|
||||
|
||||
def _trigger(self, page, select_id: str):
|
||||
return page.locator(f"#{select_id}").locator(
|
||||
"xpath=ancestor::div[contains(@class,'ds-combo')]"
|
||||
).locator(".ds-combo-trigger")
|
||||
|
||||
def test_night_placeholder_unselected_selected_disabled(self) -> None:
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, args=["--no-sandbox"])
|
||||
page = browser.new_page(viewport={"width": 1440, "height": 900})
|
||||
self._open(page, night=True)
|
||||
empty_btn = self._trigger(page, "probe-empty")
|
||||
self.assertTrue(empty_btn.evaluate("el => el.classList.contains('is-placeholder')"))
|
||||
empty_btn.click()
|
||||
page.wait_for_selector("#ds-listbox:not([hidden])")
|
||||
snapshot = page.evaluate(
|
||||
"""() => {
|
||||
const box = document.getElementById('ds-listbox');
|
||||
const opts = [...box.querySelectorAll('.ds-listbox-option')].map((el) => {
|
||||
const cs = getComputedStyle(el);
|
||||
return {
|
||||
text: el.textContent,
|
||||
color: cs.color,
|
||||
bg: cs.backgroundColor,
|
||||
selected: el.classList.contains('is-selected'),
|
||||
placeholder: el.classList.contains('is-placeholder'),
|
||||
disabled: el.classList.contains('is-disabled'),
|
||||
};
|
||||
});
|
||||
const bcs = getComputedStyle(box);
|
||||
const tcs = getComputedStyle(document.querySelector('#probe-empty').closest('.ds-combo').querySelector('.ds-combo-trigger'));
|
||||
return {
|
||||
boxBg: bcs.backgroundColor,
|
||||
boxColor: bcs.color,
|
||||
boxBorder: bcs.borderTopColor,
|
||||
triggerBg: tcs.backgroundColor,
|
||||
triggerColor: tcs.color,
|
||||
opts,
|
||||
};
|
||||
}"""
|
||||
)
|
||||
page.keyboard.press("Escape")
|
||||
filled = self._trigger(page, "probe-filled")
|
||||
filled.click()
|
||||
page.wait_for_selector("#ds-listbox:not([hidden])")
|
||||
selected = page.evaluate(
|
||||
"""() => {
|
||||
const el = document.querySelector('#ds-listbox .is-selected');
|
||||
const cs = getComputedStyle(el);
|
||||
return { color: cs.color, bg: cs.backgroundColor, text: el.textContent };
|
||||
}"""
|
||||
)
|
||||
native = page.evaluate("() => document.getElementById('probe-filled').value")
|
||||
browser.close()
|
||||
white = "rgb(255, 255, 255)"
|
||||
self.assertNotEqual(white, snapshot["boxBg"])
|
||||
self.assertNotEqual(white, snapshot["boxColor"])
|
||||
self.assertNotEqual(white, snapshot["triggerBg"])
|
||||
self.assertNotEqual(white, snapshot["triggerColor"])
|
||||
placeholder = next(o for o in snapshot["opts"] if o["placeholder"])
|
||||
plain = next(o for o in snapshot["opts"] if not o["placeholder"] and not o["disabled"] and not o["selected"])
|
||||
disabled = next(o for o in snapshot["opts"] if o["disabled"])
|
||||
self.assertNotEqual(white, placeholder["color"])
|
||||
self.assertNotEqual(white, placeholder["bg"])
|
||||
self.assertNotEqual(white, plain["color"])
|
||||
self.assertNotEqual(white, plain["bg"])
|
||||
self.assertNotEqual(white, disabled["color"])
|
||||
self.assertIn("217", selected["color"])
|
||||
self.assertEqual("河南金牛煤业有限公司", selected["text"])
|
||||
self.assertEqual("b", native)
|
||||
|
||||
def test_keyboard_and_form_value(self) -> None:
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, args=["--no-sandbox"])
|
||||
page = browser.new_page(viewport={"width": 1440, "height": 900})
|
||||
self._open(page, night=True)
|
||||
btn = self._trigger(page, "probe-empty")
|
||||
btn.focus()
|
||||
page.keyboard.press("ArrowDown")
|
||||
page.wait_for_selector("#ds-listbox:not([hidden])")
|
||||
page.keyboard.press("ArrowDown")
|
||||
page.keyboard.press("Enter")
|
||||
value = page.evaluate("() => document.getElementById('probe-empty').value")
|
||||
label = btn.inner_text()
|
||||
btn.focus()
|
||||
page.keyboard.press("Enter")
|
||||
page.wait_for_selector("#ds-listbox:not([hidden])")
|
||||
page.keyboard.press("Escape")
|
||||
hidden = page.evaluate("() => document.getElementById('ds-listbox').hidden")
|
||||
browser.close()
|
||||
self.assertEqual("a", value)
|
||||
self.assertIn("农业", label)
|
||||
self.assertTrue(hidden)
|
||||
|
||||
def test_year_month_jump_keeps_selected_and_skips_invalid_day(self) -> None:
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, args=["--no-sandbox"])
|
||||
page = browser.new_page(viewport={"width": 1440, "height": 900})
|
||||
self._open(page, night=True)
|
||||
page.click("#probe-date")
|
||||
page.wait_for_selector("#ds-datepicker:not([hidden])")
|
||||
before = page.evaluate("() => document.getElementById('probe-date').value")
|
||||
year_btn = page.locator("#ds-datepicker [data-dp-year]").locator(
|
||||
"xpath=ancestor::div[contains(@class,'ds-combo')]"
|
||||
).locator(".ds-combo-trigger")
|
||||
year_btn.click()
|
||||
page.wait_for_selector("#ds-listbox:not([hidden])")
|
||||
page.locator("#ds-listbox .ds-listbox-option", has_text="2024年").click()
|
||||
page.wait_for_function(
|
||||
"() => document.querySelector('[data-dp-year]').value === '2024'"
|
||||
)
|
||||
month_btn = page.locator("#ds-datepicker [data-dp-month]").locator(
|
||||
"xpath=ancestor::div[contains(@class,'ds-combo')]"
|
||||
).locator(".ds-combo-trigger")
|
||||
month_btn.click()
|
||||
page.wait_for_selector("#ds-listbox:not([hidden])")
|
||||
page.locator("#ds-listbox .ds-listbox-option", has_text="02月").click()
|
||||
after = page.evaluate(
|
||||
"""() => {
|
||||
const input = document.getElementById('probe-date');
|
||||
const panel = document.getElementById('ds-datepicker');
|
||||
const selected = panel.querySelector('.ds-dp-day.is-selected');
|
||||
const days = [...panel.querySelectorAll('.ds-dp-day:not(.is-other)')].map((el) => el.textContent);
|
||||
const year = document.querySelector('[data-dp-year]').value;
|
||||
const month = document.querySelector('[data-dp-month]').value;
|
||||
return {
|
||||
value: input.value,
|
||||
selected: selected && selected.getAttribute('data-iso'),
|
||||
has31: days.includes('31'),
|
||||
year,
|
||||
month,
|
||||
titleYear: document.querySelector('#ds-datepicker .ds-combo-trigger').textContent,
|
||||
};
|
||||
}"""
|
||||
)
|
||||
browser.close()
|
||||
self.assertEqual("2026-01-31", before)
|
||||
self.assertEqual("2026-01-31", after["value"])
|
||||
self.assertIsNone(after["selected"])
|
||||
self.assertFalse(after["has31"])
|
||||
self.assertEqual("2024", after["year"])
|
||||
self.assertEqual("1", after["month"])
|
||||
|
||||
def test_leap_year_feb29_and_minmax_year_range(self) -> None:
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, args=["--no-sandbox"])
|
||||
page = browser.new_page(viewport={"width": 1440, "height": 900})
|
||||
self._open(page, night=False)
|
||||
page.click("#probe-date")
|
||||
page.wait_for_selector("#ds-datepicker:not([hidden])")
|
||||
page.locator("#ds-datepicker [data-dp-year]").locator(
|
||||
"xpath=ancestor::div[contains(@class,'ds-combo')]"
|
||||
).locator(".ds-combo-trigger").click()
|
||||
years = page.evaluate(
|
||||
"""() => [...document.querySelectorAll('#ds-listbox .ds-listbox-option')].map((el) => el.textContent)"""
|
||||
)
|
||||
page.locator("#ds-listbox .ds-listbox-option", has_text="2024年").click()
|
||||
page.locator("#ds-datepicker [data-dp-month]").locator(
|
||||
"xpath=ancestor::div[contains(@class,'ds-combo')]"
|
||||
).locator(".ds-combo-trigger").click()
|
||||
page.locator("#ds-listbox .ds-listbox-option", has_text="02月").click()
|
||||
days = page.evaluate(
|
||||
"""() => [...document.querySelectorAll('#ds-datepicker .ds-dp-day:not(.is-other)')].map((el) => el.textContent)"""
|
||||
)
|
||||
page.click('#ds-datepicker [data-iso="2024-02-29"]')
|
||||
value = page.evaluate("() => document.getElementById('probe-date').value")
|
||||
page.click("#probe-free-date")
|
||||
page.wait_for_selector("#ds-datepicker:not([hidden])")
|
||||
page.locator("#ds-datepicker [data-dp-year]").locator(
|
||||
"xpath=ancestor::div[contains(@class,'ds-combo')]"
|
||||
).locator(".ds-combo-trigger").click()
|
||||
free_years = page.evaluate(
|
||||
"""() => [...document.querySelectorAll('#ds-listbox .ds-listbox-option')].map((el) => el.textContent)"""
|
||||
)
|
||||
browser.close()
|
||||
from datetime import date
|
||||
year = date.today().year
|
||||
self.assertIn("2020年", years)
|
||||
self.assertIn("2028年", years)
|
||||
self.assertNotIn("2019年", years)
|
||||
self.assertIn("29", days)
|
||||
self.assertEqual("2024-02-29", value)
|
||||
self.assertIn(f"{year - 80}年", free_years)
|
||||
self.assertIn(f"{year + 20}年", free_years)
|
||||
|
||||
def test_prev_next_month_still_works(self) -> None:
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, args=["--no-sandbox"])
|
||||
page = browser.new_page(viewport={"width": 1440, "height": 900})
|
||||
self._open(page, night=True)
|
||||
page.click("#probe-date")
|
||||
page.wait_for_selector("#ds-datepicker:not([hidden])")
|
||||
page.click('#ds-datepicker [data-dp-nav="1"]')
|
||||
state = page.evaluate(
|
||||
"""() => ({
|
||||
month: document.querySelector('[data-dp-month]').value,
|
||||
year: document.querySelector('[data-dp-year]').value,
|
||||
value: document.getElementById('probe-date').value,
|
||||
})"""
|
||||
)
|
||||
browser.close()
|
||||
self.assertEqual("1", state["month"])
|
||||
self.assertEqual("2026", state["year"])
|
||||
self.assertEqual("2026-01-31", state["value"])
|
||||
|
||||
def test_day_theme_trigger_stays_light(self) -> None:
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, args=["--no-sandbox"])
|
||||
page = browser.new_page(viewport={"width": 1440, "height": 900})
|
||||
self._open(page, night=False)
|
||||
colors = page.evaluate(
|
||||
"""() => {
|
||||
const btn = document.querySelector('#probe-filled').closest('.ds-combo').querySelector('.ds-combo-trigger');
|
||||
const cs = getComputedStyle(btn);
|
||||
return { bg: cs.backgroundColor, color: cs.color };
|
||||
}"""
|
||||
)
|
||||
browser.close()
|
||||
self.assertNotEqual("rgb(16, 15, 13)", colors["bg"])
|
||||
|
||||
def test_viewports_and_shots(self) -> None:
|
||||
SHOT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
viewports = [360, 390, 820, 1440]
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch(headless=True, args=["--no-sandbox"])
|
||||
for width in viewports:
|
||||
for night in (False, True):
|
||||
page = browser.new_page(viewport={"width": width, "height": 800})
|
||||
self._open(page, night=night, width=width, height=800)
|
||||
theme = "night" if night else "day"
|
||||
self._trigger(page, "probe-empty").click()
|
||||
page.wait_for_selector("#ds-listbox:not([hidden])")
|
||||
page.screenshot(
|
||||
path=str(SHOT_DIR / f"select-empty-{theme}-{width}.png"),
|
||||
full_page=True,
|
||||
)
|
||||
page.keyboard.press("Escape")
|
||||
self._trigger(page, "probe-filled").click()
|
||||
page.wait_for_selector("#ds-listbox:not([hidden])")
|
||||
page.screenshot(
|
||||
path=str(SHOT_DIR / f"select-filled-{theme}-{width}.png"),
|
||||
full_page=True,
|
||||
)
|
||||
page.keyboard.press("Escape")
|
||||
page.click("#probe-date")
|
||||
page.wait_for_selector("#ds-datepicker:not([hidden])")
|
||||
page.screenshot(
|
||||
path=str(SHOT_DIR / f"datepicker-{theme}-{width}.png"),
|
||||
full_page=True,
|
||||
)
|
||||
page.locator("#ds-datepicker [data-dp-year]").locator(
|
||||
"xpath=ancestor::div[contains(@class,'ds-combo')]"
|
||||
).locator(".ds-combo-trigger").click()
|
||||
page.wait_for_selector("#ds-listbox:not([hidden])")
|
||||
page.screenshot(
|
||||
path=str(SHOT_DIR / f"datepicker-year-{theme}-{width}.png"),
|
||||
full_page=True,
|
||||
)
|
||||
page.close()
|
||||
browser.close()
|
||||
self.assertTrue((SHOT_DIR / "select-empty-night-1440.png").exists())
|
||||
self.assertTrue((SHOT_DIR / "datepicker-year-night-360.png").exists())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,735 +0,0 @@
|
||||
"""HTTP integration tests for the hardened import API (B-42).
|
||||
|
||||
Covers streaming multipart limits, per-worksheet parse results with the four
|
||||
diagnostic evidence items, the confirm/ignore review lifecycle with tenant
|
||||
scoping and idempotency, unconfirmed-sheet export gating, and concurrent
|
||||
duplicate uploads. Uses a real ``ThreadingHTTPServer`` like
|
||||
``test_server_auth``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import itertools
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
from openpyxl import Workbook
|
||||
|
||||
from bank_importer import auth
|
||||
from bank_importer.db import connect, migrate
|
||||
|
||||
import server
|
||||
from test_server_auth import Client, as_json
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SAMPLES = ROOT / "流水模板"
|
||||
CCB_SAMPLE = SAMPLES / "中国建设银行账户流水.xls"
|
||||
CITIC_SAMPLE = SAMPLES / "中信银行账户流水.xlsx"
|
||||
|
||||
BOOTSTRAP_PASSWORD = "BootAdmin123"
|
||||
ADMIN_PASSWORD = "AdminPass123"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fixtures
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
CCB_HEADER = [
|
||||
"客户账号", "账户名称", "交易时间", "借方发生额(支取)", "贷方发生额(收入)",
|
||||
"余额", "币种", "对方户名", "对方账号", "对方开户机构", "摘要", "备注",
|
||||
]
|
||||
CCB_DATA = [
|
||||
["6228480000000000", "测试公司", "2026-01-05 10:00:00", "100.00", "", "99900.00", "RMB", "供应商", "1002003004", "某银行", "货款", ""],
|
||||
["6228480000000000", "测试公司", "2026-01-06 11:00:00", "", "200.00", "100100.00", "RMB", "客户", "2003004005", "某银行", "收款", ""],
|
||||
]
|
||||
|
||||
|
||||
def ccb_row(own, cp, *, expense="", income="", at="2026-01-05 10:00:00"):
|
||||
return [own, "测试公司", at, expense or "", income or "", "99900.00", "RMB", "对方", cp, "某银行", "货款", ""]
|
||||
|
||||
|
||||
def ccb_bytes(rows):
|
||||
return workbook_bytes([("正常流水", [CCB_HEADER, *rows])])
|
||||
|
||||
|
||||
def workbook_bytes(sheets):
|
||||
"""Build an xlsx in memory.
|
||||
|
||||
``sheets`` is a list of ``(name, rows)``; an empty ``rows`` list means an
|
||||
empty worksheet.
|
||||
"""
|
||||
workbook = Workbook()
|
||||
workbook.remove(workbook.active)
|
||||
for name, rows in sheets:
|
||||
worksheet = workbook.create_sheet(name)
|
||||
for row in rows:
|
||||
worksheet.append(row)
|
||||
buffer = io.BytesIO()
|
||||
workbook.save(buffer)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
# Workbook fixtures are content-hashed for dedupe, so every helper produces
|
||||
# distinct bytes per call (each test uploads a genuinely new file).
|
||||
_counter = itertools.count()
|
||||
|
||||
|
||||
def multi_sheet_bytes():
|
||||
"""Valid CCB sheet + unknown-header sheet + empty sheet in one workbook."""
|
||||
return workbook_bytes(
|
||||
[
|
||||
("正常流水", [CCB_HEADER, *CCB_DATA]),
|
||||
("未知模板", [["日期", "金额", "备注"], ["2026-01-01", next(_counter), "x"]]),
|
||||
("空表", []),
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def empty_workbook_bytes():
|
||||
return workbook_bytes([("Sheet1", [])])
|
||||
|
||||
|
||||
def single_cell_bytes():
|
||||
return workbook_bytes([("候选", [[f"只有一个单元格 {next(_counter)}"]])])
|
||||
|
||||
|
||||
def unknown_header_bytes():
|
||||
return workbook_bytes([("流水", [["日期", "金额", "备注"], ["2026-01-01", next(_counter), "x"]])])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Test server
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class ImportApiServerTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
cls.temp_dir = tempfile.TemporaryDirectory()
|
||||
root = Path(cls.temp_dir.name)
|
||||
cls.db_path = root / "app.db"
|
||||
cls.storage = root / "files"
|
||||
|
||||
cls._old_db_path = server.DB_PATH
|
||||
cls._old_storage = server.STORAGE_DIR
|
||||
server.DB_PATH = cls.db_path
|
||||
server.STORAGE_DIR = cls.storage
|
||||
|
||||
os.environ["APP_BOOTSTRAP_ADMIN_PASSWORD"] = BOOTSTRAP_PASSWORD
|
||||
connection = connect(cls.db_path)
|
||||
migrate(connection)
|
||||
generated = server.ensure_bootstrap_admin(connection)
|
||||
assert generated is None
|
||||
connection.close()
|
||||
|
||||
class QuietHandler(server.AppHandler):
|
||||
def log_message(self, *args) -> None:
|
||||
pass
|
||||
|
||||
cls.httpd = server.ThreadingHTTPServer(("127.0.0.1", 0), QuietHandler)
|
||||
cls.port = cls.httpd.server_address[1]
|
||||
cls.thread = threading.Thread(target=cls.httpd.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
|
||||
cls.admin = Client("127.0.0.1", cls.port)
|
||||
status, _, data = cls.admin.post_json(
|
||||
"/api/login",
|
||||
{"username": "group-admin", "password": BOOTSTRAP_PASSWORD, "portal": "admin"},
|
||||
)
|
||||
assert status == 200, data
|
||||
status, _, data = cls.admin.post_json(
|
||||
"/api/password/change",
|
||||
{"old_password": BOOTSTRAP_PASSWORD, "new_password": ADMIN_PASSWORD},
|
||||
)
|
||||
assert status == 200, data
|
||||
|
||||
status, _, data = cls.admin.post_json("/api/admin/companies", {"name": "甲公司"})
|
||||
assert status == 200, data
|
||||
cls.company_a = as_json(data)["company_id"]
|
||||
status, _, data = cls.admin.post_json("/api/admin/companies", {"name": "乙公司"})
|
||||
assert status == 200, data
|
||||
cls.company_b = as_json(data)["company_id"]
|
||||
|
||||
cls.cashier_a, cls.cashier_a_password = cls.create_company_user(
|
||||
cls.admin, cls.port, "cashier-a"
|
||||
)
|
||||
cls.cashier_b, cls.cashier_b_password = cls.create_company_user(
|
||||
cls.admin, cls.port, "cashier-b"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def create_company_user(cls, admin, port, username):
|
||||
status, _, data = admin.post_json(
|
||||
"/api/admin/users", {"username": username, "company_id": cls.company_a}
|
||||
)
|
||||
assert status == 200, data
|
||||
initial = as_json(data)["initial_password"]
|
||||
client = Client("127.0.0.1", port)
|
||||
status, _, data = client.post_json(
|
||||
"/api/login",
|
||||
{"username": username, "password": initial, "portal": "company"},
|
||||
)
|
||||
assert status == 200, data
|
||||
new_password = "Changed456"
|
||||
status, _, data = client.post_json(
|
||||
"/api/password/change",
|
||||
{"old_password": initial, "new_password": new_password},
|
||||
)
|
||||
assert status == 200, data
|
||||
return client, new_password
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls) -> None:
|
||||
cls.httpd.shutdown()
|
||||
cls.httpd.server_close()
|
||||
server.DB_PATH = cls._old_db_path
|
||||
server.STORAGE_DIR = cls._old_storage
|
||||
os.environ.pop("APP_BOOTSTRAP_ADMIN_PASSWORD", None)
|
||||
cls.temp_dir.cleanup()
|
||||
|
||||
def fresh_client(self) -> Client:
|
||||
return Client("127.0.0.1", self.port)
|
||||
|
||||
def upload(self, client, content: bytes, filename: str = "语句.xlsx", fields=None):
|
||||
return client.post_multipart(
|
||||
"/api/parse", fields or {}, filename, content
|
||||
)
|
||||
|
||||
def upload_for_company(self, content: bytes, company_id: int, filename: str = "语句.xlsx"):
|
||||
return self.admin.post_multipart(
|
||||
"/api/parse", {"company_id": str(company_id)}, filename, content
|
||||
)
|
||||
|
||||
def upload_for_a(self, content: bytes, filename: str = "语句.xlsx"):
|
||||
return self.cashier_a.post_multipart("/api/parse", {}, filename, content)
|
||||
|
||||
def batch_sheets(self, client, batch_id: int):
|
||||
status, _, data = client.get(f"/api/batches/{batch_id}/sheets")
|
||||
self.assertEqual(200, status, data)
|
||||
return as_json(data)["sheets"]
|
||||
|
||||
def confirm(self, client, batch_id: int, sheets, reason=None):
|
||||
payload = {"sheets": sheets}
|
||||
if reason is not None:
|
||||
payload["reason"] = reason
|
||||
return client.post_json(f"/api/batches/{batch_id}/confirm", payload)
|
||||
|
||||
def ignore(self, client, batch_id: int, sheets, reason):
|
||||
return client.post_json(
|
||||
f"/api/batches/{batch_id}/ignore", {"sheets": sheets, "reason": reason}
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Multipart validation
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_oversized_body_returns_stable_error(self) -> None:
|
||||
content = b"x" * (server.MAX_UPLOAD_BYTES + 1)
|
||||
status, _, data = self.upload_for_a(content)
|
||||
self.assertEqual(422, status)
|
||||
payload = as_json(data)
|
||||
self.assertIn("20 MB", payload["message"])
|
||||
self.assertNotIn(server.STORAGE_DIR.as_posix(), payload["message"])
|
||||
self.assertNotIn(str(self.storage), payload["message"])
|
||||
|
||||
def test_missing_boundary_returns_stable_error(self) -> None:
|
||||
status, _, data = self.cashier_a.request(
|
||||
"POST",
|
||||
"/api/parse",
|
||||
body=b"whatever",
|
||||
headers={"Content-Type": "multipart/form-data"},
|
||||
)
|
||||
self.assertEqual(422, status)
|
||||
self.assertIn("边界", as_json(data)["message"])
|
||||
|
||||
def test_wrong_content_type_returns_stable_error(self) -> None:
|
||||
status, _, data = self.cashier_a.request(
|
||||
"POST",
|
||||
"/api/parse",
|
||||
body=CCB_SAMPLE.read_bytes(),
|
||||
headers={"Content-Type": "application/octet-stream"},
|
||||
)
|
||||
self.assertEqual(422, status)
|
||||
|
||||
def test_missing_content_length_returns_stable_error(self) -> None:
|
||||
boundary = "----missingcl"
|
||||
body = f"--{boundary}--\r\n".encode()
|
||||
status, _, data = self.cashier_a.request(
|
||||
"POST",
|
||||
"/api/parse",
|
||||
body=body,
|
||||
headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
|
||||
)
|
||||
self.assertEqual(422, status)
|
||||
|
||||
def test_bad_extension_returns_stable_error(self) -> None:
|
||||
status, _, data = self.upload_for_a(CCB_SAMPLE.read_bytes(), filename="statement.pdf")
|
||||
self.assertEqual(422, status)
|
||||
self.assertIn(".xls", as_json(data)["message"])
|
||||
|
||||
def test_signature_mismatch_returns_stable_error(self) -> None:
|
||||
# Valid .xls content renamed with a .xlsx extension must be rejected.
|
||||
status, _, data = self.upload_for_a(CCB_SAMPLE.read_bytes(), filename="fake.xlsx")
|
||||
self.assertEqual(422, status)
|
||||
self.assertIn("损坏", as_json(data)["message"])
|
||||
|
||||
def test_corrupt_file_returns_stable_error_without_temp_path(self) -> None:
|
||||
status, _, data = self.upload_for_a(b"PK\x03\x04 not a real zip at all")
|
||||
self.assertEqual(422, status)
|
||||
payload = as_json(data)
|
||||
text = json.dumps(payload, ensure_ascii=False)
|
||||
self.assertNotIn(str(self.storage), text)
|
||||
self.assertNotIn("temp", text.lower())
|
||||
self.assertNotIn("data/files", text)
|
||||
|
||||
def test_two_file_parts_rejected(self) -> None:
|
||||
boundary = "----twofilesboundary"
|
||||
content = CCB_SAMPLE.read_bytes()
|
||||
crlf = b"\r\n"
|
||||
body = (
|
||||
b"--" + boundary.encode() + crlf
|
||||
+ b'Content-Disposition: form-data; name="file"; filename="a.xls"' + crlf
|
||||
+ b"Content-Type: application/octet-stream" + crlf + crlf
|
||||
+ content + crlf
|
||||
+ b"--" + boundary.encode() + crlf
|
||||
+ b'Content-Disposition: form-data; name="file"; filename="b.xls"' + crlf
|
||||
+ b"Content-Type: application/octet-stream" + crlf + crlf
|
||||
+ content + crlf
|
||||
+ b"--" + boundary.encode() + b"--" + crlf
|
||||
)
|
||||
status, _, data = self.cashier_a.request(
|
||||
"POST",
|
||||
"/api/parse",
|
||||
body=body,
|
||||
headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
|
||||
)
|
||||
self.assertEqual(422, status)
|
||||
|
||||
def test_no_file_part_rejected(self) -> None:
|
||||
boundary = "----nofile"
|
||||
crlf = b"\r\n"
|
||||
body = (
|
||||
b"--" + boundary.encode() + crlf
|
||||
+ b'Content-Disposition: form-data; name="company_id"' + crlf + crlf
|
||||
+ b"1" + crlf
|
||||
+ b"--" + boundary.encode() + b"--" + crlf
|
||||
)
|
||||
status, _, data = self.cashier_a.request(
|
||||
"POST",
|
||||
"/api/parse",
|
||||
body=body,
|
||||
headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
|
||||
)
|
||||
self.assertEqual(422, status)
|
||||
self.assertIn("文件", as_json(data)["message"])
|
||||
|
||||
def test_upload_trailing_bytes_preserved_exactly(self) -> None:
|
||||
# The stored source file must be byte-identical to what was uploaded
|
||||
# even when it ends with CRLF/LF; the parser must never trim tail
|
||||
# bytes, and the upload temp must not appear anywhere in the payload.
|
||||
content = CCB_SAMPLE.read_bytes()
|
||||
uploaded = content + b"\r\n\r\n\x00\x01"
|
||||
status, _, data = self.upload_for_a(uploaded, filename="尾部字节.xls")
|
||||
self.assertEqual(200, status, data)
|
||||
batch_id = as_json(data)["batch_id"]
|
||||
connection = connect(self.db_path)
|
||||
try:
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT f.storage_path FROM source_files f
|
||||
JOIN import_batches b ON b.source_file_id = f.id
|
||||
WHERE b.id = ?
|
||||
""",
|
||||
(batch_id,),
|
||||
).fetchone()
|
||||
finally:
|
||||
connection.close()
|
||||
self.assertIsNotNone(row)
|
||||
self.assertEqual(uploaded, Path(row["storage_path"]).read_bytes())
|
||||
self.assertNotIn("upload-", json.dumps(as_json(data), ensure_ascii=False))
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Per-sheet results and four-item evidence
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_multi_sheet_workbook_returns_every_sheet_result(self) -> None:
|
||||
status, _, data = self.upload_for_a(multi_sheet_bytes(), filename="多工作表.xlsx")
|
||||
self.assertEqual(200, status, data)
|
||||
payload = as_json(data)
|
||||
self.assertEqual("parsed", payload["status"])
|
||||
self.assertEqual("多工作表.xlsx", payload.get("original_filename"))
|
||||
sheets = payload["sheets"]
|
||||
self.assertEqual(3, len(sheets))
|
||||
|
||||
by_name = {sheet["sheet_name"]: sheet for sheet in sheets}
|
||||
self.assertEqual("parsed", by_name["正常流水"]["outcome"])
|
||||
self.assertEqual("pending", by_name["正常流水"]["review_status"])
|
||||
self.assertEqual("中国建设银行", by_name["正常流水"]["bank"])
|
||||
self.assertEqual(2, by_name["正常流水"]["transactions"])
|
||||
|
||||
unknown = by_name["未知模板"]
|
||||
self.assertEqual("exception", unknown["outcome"])
|
||||
self.assertIn("未识别到受支持的银行表头", unknown["message"])
|
||||
self.assertGreaterEqual(unknown["scanned_rows"], 2)
|
||||
self.assertTrue(unknown["candidate_headers"])
|
||||
self.assertIn("日期、金额、备注", ";".join(unknown["candidate_headers"]))
|
||||
|
||||
empty = by_name["空表"]
|
||||
self.assertEqual("ignored", empty["outcome"])
|
||||
self.assertIn("为空", empty["message"])
|
||||
self.assertEqual(0, empty["scanned_rows"])
|
||||
|
||||
def test_batch_detail_matches_parse_response(self) -> None:
|
||||
status, _, data = self.upload_for_a(multi_sheet_bytes(), filename="详情.xlsx")
|
||||
batch_id = as_json(data)["batch_id"]
|
||||
sheets = self.batch_sheets(self.cashier_a, batch_id)
|
||||
self.assertEqual(3, len(sheets))
|
||||
status, _, data = self.cashier_a.get(f"/api/batches/{batch_id}/sheets")
|
||||
self.assertEqual(200, status)
|
||||
detail = as_json(data)
|
||||
self.assertEqual("详情.xlsx", detail["original_filename"])
|
||||
|
||||
def test_unknown_header_file_returns_four_evidence_items(self) -> None:
|
||||
status, _, data = self.upload_for_a(unknown_header_bytes(), filename="未知银行.xlsx")
|
||||
self.assertEqual(422, status, data)
|
||||
payload = as_json(data)
|
||||
self.assertEqual("exception", payload["status"])
|
||||
self.assertEqual("未知银行.xlsx", payload.get("original_filename"))
|
||||
sheet = payload["sheets"][0]
|
||||
self.assertEqual("exception", sheet["outcome"])
|
||||
self.assertEqual("流水", sheet["sheet_name"])
|
||||
self.assertGreaterEqual(sheet["scanned_rows"], 1)
|
||||
self.assertTrue(sheet["candidate_headers"])
|
||||
text = json.dumps(payload, ensure_ascii=False)
|
||||
for evidence in (str(self.storage), "data/files", ".uploads", "upload-"):
|
||||
self.assertNotIn(evidence, text)
|
||||
|
||||
def test_empty_workbook_returns_evidence(self) -> None:
|
||||
status, _, data = self.upload_for_a(empty_workbook_bytes(), filename="空工作簿.xlsx")
|
||||
self.assertEqual(422, status, data)
|
||||
payload = as_json(data)
|
||||
self.assertEqual("空工作簿.xlsx", payload.get("original_filename"))
|
||||
sheet = payload["sheets"][0]
|
||||
self.assertEqual("ignored", sheet["outcome"])
|
||||
self.assertEqual("Sheet1", sheet["sheet_name"])
|
||||
self.assertEqual(0, sheet["scanned_rows"])
|
||||
|
||||
def test_single_cell_sheet_returns_candidate_evidence(self) -> None:
|
||||
status, _, data = self.upload_for_a(single_cell_bytes(), filename="单格.xlsx")
|
||||
self.assertEqual(422, status, data)
|
||||
sheet = as_json(data)["sheets"][0]
|
||||
self.assertEqual("exception", sheet["outcome"])
|
||||
self.assertEqual("候选", sheet["sheet_name"])
|
||||
self.assertEqual(1, sheet["scanned_rows"])
|
||||
self.assertTrue(sheet["candidate_headers"])
|
||||
self.assertIn("只有一个单元格", ";".join(sheet["candidate_headers"]))
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Confirm / ignore lifecycle
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_confirm_and_ignore_lifecycle(self) -> None:
|
||||
status, _, data = self.upload_for_a(multi_sheet_bytes(), filename="确认.xlsx")
|
||||
payload = as_json(data)
|
||||
batch_id = payload["batch_id"]
|
||||
names = [s["sheet_name"] for s in payload["sheets"]]
|
||||
self.assertIn("正常流水", names)
|
||||
|
||||
# Confirm the parsed sheet; exception/ignored cannot be confirmed.
|
||||
status, _, data = self.confirm(self.cashier_a, batch_id, ["正常流水"])
|
||||
self.assertEqual(200, status, data)
|
||||
result = as_json(data)
|
||||
self.assertEqual(["正常流水"], result["updated"])
|
||||
sheet = next(s for s in result["sheets"] if s["sheet_name"] == "正常流水")
|
||||
self.assertEqual("confirmed", sheet["review_status"])
|
||||
|
||||
# Confirming an exception sheet is a conflict.
|
||||
status, _, data = self.confirm(self.cashier_a, batch_id, ["未知模板"])
|
||||
self.assertEqual(409, status, data)
|
||||
|
||||
# Ignore the exception sheet with a reason.
|
||||
status, _, data = self.ignore(self.cashier_a, batch_id, ["未知模板"], "模板待补充")
|
||||
self.assertEqual(200, status, data)
|
||||
sheet = next(s for s in as_json(data)["sheets"] if s["sheet_name"] == "未知模板")
|
||||
self.assertEqual("ignored", sheet["review_status"])
|
||||
self.assertEqual("模板待补充", sheet["review_reason"])
|
||||
|
||||
# Idempotent repeat of an already-applied decision.
|
||||
status, _, data = self.confirm(self.cashier_a, batch_id, ["正常流水"])
|
||||
self.assertEqual(200, status, data)
|
||||
result = as_json(data)
|
||||
self.assertEqual([], result["updated"])
|
||||
self.assertEqual(["正常流水"], result["already"])
|
||||
|
||||
# Changing a settled decision is a conflict.
|
||||
status, _, data = self.ignore(self.cashier_a, batch_id, ["正常流水"], "改主意")
|
||||
self.assertEqual(409, status, data)
|
||||
|
||||
def test_ignore_requires_reason(self) -> None:
|
||||
status, _, data = self.upload_for_a(multi_sheet_bytes(), filename="忽略原因.xlsx")
|
||||
batch_id = as_json(data)["batch_id"]
|
||||
status, _, data = self.cashier_a.post_json(
|
||||
f"/api/batches/{batch_id}/ignore", {"sheets": ["未知模板"], "reason": " "}
|
||||
)
|
||||
self.assertEqual(400, status, data)
|
||||
self.assertIn("原因", as_json(data)["message"])
|
||||
|
||||
def test_unknown_sheet_name_is_rejected_and_atomic(self) -> None:
|
||||
status, _, data = self.upload_for_a(multi_sheet_bytes(), filename="原子.xlsx")
|
||||
batch_id = as_json(data)["batch_id"]
|
||||
# One valid + one unknown sheet in the same request must not leave a
|
||||
# half-applied confirmation behind.
|
||||
status, _, data = self.confirm(self.cashier_a, batch_id, ["正常流水", "不存在"])
|
||||
self.assertEqual(400, status, data)
|
||||
sheet = next(
|
||||
s for s in self.batch_sheets(self.cashier_a, batch_id)
|
||||
if s["sheet_name"] == "正常流水"
|
||||
)
|
||||
self.assertEqual("pending", sheet["review_status"])
|
||||
|
||||
def test_company_cannot_confirm_another_companys_batch(self) -> None:
|
||||
status, _, data = self.upload_for_company(multi_sheet_bytes(), self.company_b)
|
||||
batch_b = as_json(data)["batch_id"]
|
||||
status, _, data = self.confirm(self.cashier_a, batch_b, ["正常流水"])
|
||||
self.assertEqual(404, status, data)
|
||||
status, _, data = self.cashier_a.get(f"/api/batches/{batch_b}/sheets")
|
||||
self.assertEqual(404, status, data)
|
||||
|
||||
def test_export_excludes_unconfirmed_and_ignore_keeps_excluded(self) -> None:
|
||||
def export_line_count() -> int:
|
||||
status, _, data = self.cashier_a.get("/api/export.csv")
|
||||
self.assertEqual(200, status)
|
||||
return len([line for line in data.decode("utf-8-sig").splitlines() if line])
|
||||
|
||||
baseline = export_line_count()
|
||||
|
||||
# Unconfirmed upload: export stays unchanged (no downstream leak).
|
||||
status, _, data = self.upload_for_a(CCB_SAMPLE.read_bytes(), filename="导出.xls")
|
||||
batch_id = as_json(data)["batch_id"]
|
||||
self.assertEqual("parsed", as_json(data)["status"])
|
||||
self.assertEqual(baseline, export_line_count())
|
||||
|
||||
# Confirm → the sheet's rows enter the export.
|
||||
sheets = self.batch_sheets(self.cashier_a, batch_id)
|
||||
name = sheets[0]["sheet_name"]
|
||||
status, _, data = self.confirm(self.cashier_a, batch_id, [name])
|
||||
self.assertEqual(200, status, data)
|
||||
self.assertGreater(export_line_count(), baseline)
|
||||
|
||||
# A confirmed sheet cannot be silently revoked: the settled decision
|
||||
# is a conflict, not a silent data removal.
|
||||
status, _, data = self.ignore(self.cashier_a, batch_id, [name], "取消")
|
||||
self.assertEqual(409, status, data)
|
||||
self.assertGreater(export_line_count(), baseline)
|
||||
|
||||
# A sheet that was only ever ignored never enters the export.
|
||||
status, _, data = self.upload_for_a(multi_sheet_bytes(), filename="忽略.xlsx")
|
||||
batch2 = as_json(data)["batch_id"]
|
||||
parsed = [
|
||||
sheet for sheet in self.batch_sheets(self.cashier_a, batch2)
|
||||
if sheet["outcome"] == "parsed"
|
||||
]
|
||||
self.assertTrue(parsed)
|
||||
before_ignore = export_line_count()
|
||||
status, _, data = self.ignore(
|
||||
self.cashier_a, batch2, [parsed[0]["sheet_name"]], "该表复核后不采用"
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
self.assertEqual(before_ignore, export_line_count())
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Concurrency
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_concurrent_duplicate_upload_keeps_one_fact_set(self) -> None:
|
||||
content = CITIC_SAMPLE.read_bytes()
|
||||
results: list[tuple[int, dict]] = []
|
||||
errors: list[Exception] = []
|
||||
barrier = threading.Barrier(2)
|
||||
|
||||
def upload() -> None:
|
||||
try:
|
||||
client = self.fresh_client()
|
||||
client.cookies.update(self.cashier_a.cookies)
|
||||
barrier.wait(timeout=10)
|
||||
status, _, data = client.post_multipart(
|
||||
"/api/parse", {}, "并发.xlsx", content
|
||||
)
|
||||
results.append((status, as_json(data)))
|
||||
except Exception as exc: # pragma: no cover
|
||||
errors.append(exc)
|
||||
|
||||
threads = [threading.Thread(target=upload) for _ in range(2)]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join(timeout=30)
|
||||
|
||||
self.assertEqual([], errors)
|
||||
self.assertEqual(2, len(results))
|
||||
statuses = sorted(payload["status"] for _, payload in results)
|
||||
self.assertEqual(["duplicate", "parsed"], statuses)
|
||||
|
||||
connection = connect(self.db_path)
|
||||
try:
|
||||
# The concurrent upload adds exactly one source file: identical
|
||||
# bytes never create a second fact set.
|
||||
count = connection.execute(
|
||||
"SELECT COUNT(*) AS n FROM source_files WHERE original_filename = '并发.xlsx'"
|
||||
).fetchone()["n"]
|
||||
self.assertEqual(1, count)
|
||||
duplicates = connection.execute(
|
||||
"SELECT COUNT(*) AS n FROM import_batches WHERE status = 'duplicate'"
|
||||
).fetchone()["n"]
|
||||
self.assertGreaterEqual(duplicates, 1)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Worksheet confirmation drives canonical matching in the same transaction
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _approve_test_account(self, company_client, number: str) -> int:
|
||||
status, _, data = company_client.post_json(
|
||||
"/api/company/accounts",
|
||||
{"bank_name": "中信银行", "account_type": "基本户",
|
||||
"account_number": number, "start_date": "2026-01-01"},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
account_id = as_json(data)["account"]["id"]
|
||||
status, _, data = self.admin.post_json(
|
||||
f"/api/admin/accounts/{account_id}/review",
|
||||
{"decision": "approve", "reason": "测试启用", "effective_from": "2026-01-01"},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
return account_id
|
||||
|
||||
def _company_cashier(self, username: str, company_id: int) -> Client:
|
||||
"""A company cashier bound to the given company (the class fixture binds
|
||||
both cashiers to company A, so tests needing a real tenant B create one)."""
|
||||
status, _, data = self.admin.post_json(
|
||||
"/api/admin/users", {"username": username, "company_id": company_id}
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
initial = as_json(data)["initial_password"]
|
||||
client = self.fresh_client()
|
||||
status, _, data = client.post_json(
|
||||
"/api/login",
|
||||
{"username": username, "password": initial, "portal": "company"},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
status, _, data = client.post_json(
|
||||
"/api/password/change",
|
||||
{"old_password": initial, "new_password": "Changed456"},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
return client
|
||||
|
||||
def test_confirm_drives_bilateral_matching_atomically(self) -> None:
|
||||
account_a = self._approve_test_account(self.cashier_a, "6222000000000001")
|
||||
cashier_b = self._company_cashier("cashier-b2", self.company_b)
|
||||
account_b = self._approve_test_account(cashier_b, "6222000000000002")
|
||||
|
||||
# A's side first: confirming the worksheet reconciles its row into an
|
||||
# internal single (not yet eligible for the intercompany balance).
|
||||
status, _, data = self.upload_for_a(
|
||||
ccb_bytes([ccb_row("6222000000000001", "6222000000000002", expense="100.00")]),
|
||||
filename="A方.xlsx",
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
batch_a = as_json(data)["batch_id"]
|
||||
status, _, data = self.confirm(self.cashier_a, batch_a, ["正常流水"])
|
||||
self.assertEqual(200, status, data)
|
||||
self.assertEqual(1, as_json(data)["matching"]["created_events"])
|
||||
connection = connect(self.db_path)
|
||||
try:
|
||||
row_a = connection.execute(
|
||||
"""
|
||||
SELECT r.id FROM source_rows r
|
||||
JOIN sheet_batches s ON s.id = r.sheet_batch_id
|
||||
WHERE s.import_batch_id = ?
|
||||
""",
|
||||
(batch_a,),
|
||||
).fetchone()
|
||||
status_a = connection.execute(
|
||||
"""
|
||||
SELECT d.classification FROM transfer_observation_claims c
|
||||
JOIN transfer_match_decisions d ON d.id = c.decision_id
|
||||
WHERE c.source_row_id = ?
|
||||
""",
|
||||
(row_a["id"],),
|
||||
).fetchone()
|
||||
self.assertEqual("internal_single", status_a["classification"])
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
# B's side arrives later: the second confirmation merges both into one
|
||||
# paired intercompany event without duplicating the first.
|
||||
status, _, data = cashier_b.post_multipart(
|
||||
"/api/parse", {}, "B方.xlsx",
|
||||
ccb_bytes([ccb_row("6222000000000002", "6222000000000001", income="100.00")]),
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
batch_b = as_json(data)["batch_id"]
|
||||
status, _, data = self.confirm(cashier_b, batch_b, ["正常流水"])
|
||||
self.assertEqual(200, status, data)
|
||||
connection = connect(self.db_path)
|
||||
try:
|
||||
eligible = connection.execute(
|
||||
"SELECT * FROM eligible_intercompany_events"
|
||||
).fetchall()
|
||||
self.assertEqual(1, len(eligible))
|
||||
self.assertEqual("100.00", eligible[0]["amount"])
|
||||
self.assertEqual("paired", eligible[0]["pairing"])
|
||||
# Exactly one current intercompany decision for the pair.
|
||||
self.assertEqual(1, connection.execute(
|
||||
"""
|
||||
SELECT COUNT(*) AS n FROM current_transfer_decisions c
|
||||
JOIN transfer_match_decisions d ON d.id = c.decision_id
|
||||
WHERE d.classification = 'intercompany'
|
||||
"""
|
||||
).fetchone()["n"])
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def test_confirm_rolls_back_when_matching_fails(self) -> None:
|
||||
account_a = self._approve_test_account(self.cashier_a, "6222000000000003")
|
||||
status, _, data = self.upload_for_a(
|
||||
ccb_bytes([ccb_row("6222000000000003", "6222000000000004", expense="50.00")]),
|
||||
filename="回滚.xlsx",
|
||||
)
|
||||
batch_id = as_json(data)["batch_id"]
|
||||
with mock.patch(
|
||||
"bank_importer.importing.matching.reconcile_rows",
|
||||
side_effect=RuntimeError("simulated matching failure"),
|
||||
):
|
||||
status, _, data = self.confirm(self.cashier_a, batch_id, ["正常流水"])
|
||||
self.assertEqual(500, status, data)
|
||||
# The worksheet confirmation was rolled back with the failed matching.
|
||||
sheet = self.batch_sheets(self.cashier_a, batch_id)[0]
|
||||
self.assertEqual("pending", sheet["review_status"])
|
||||
connection = connect(self.db_path)
|
||||
try:
|
||||
# No decision or claim was left behind for this batch's rows.
|
||||
claims = connection.execute(
|
||||
"""
|
||||
SELECT COUNT(*) AS n FROM transfer_observation_claims c
|
||||
JOIN source_rows r ON r.id = c.source_row_id
|
||||
JOIN sheet_batches s ON s.id = r.sheet_batch_id
|
||||
WHERE s.import_batch_id = ?
|
||||
""",
|
||||
(batch_id,),
|
||||
).fetchone()["n"]
|
||||
self.assertEqual(0, claims)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,356 +0,0 @@
|
||||
"""B-44 ledger event layer tests: bank reconciliation, revision chain,
|
||||
reversal/adjustment, projection rebuild and immutability boundaries."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
import sqlite3
|
||||
import unittest
|
||||
|
||||
from bank_importer import ledger_events, matching, subjects
|
||||
from ledger_helpers import LedgerBase
|
||||
|
||||
|
||||
class BankReconcileTests(LedgerBase):
|
||||
def test_paired_eligible_event_creates_pending_subject_only(self) -> None:
|
||||
self.pair(self.company_a, self.company_b, "100.00")
|
||||
self.assertEqual(1, len(self.eligible()))
|
||||
stats = ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
self.assertEqual(1, stats["created"])
|
||||
events = self.ledger_events()
|
||||
self.assertEqual(1, len(events))
|
||||
revision = self.current(events[0]["id"])
|
||||
self.assertEqual("pending_subject", revision["state"])
|
||||
self.assertEqual(Decimal("100.00"), Decimal(revision["amount"]))
|
||||
self.assertEqual("CNY", revision["currency"])
|
||||
# Nothing confirmed yet -> no position event.
|
||||
self.assertEqual([], self.position_events())
|
||||
# The event is unresolved as subject_review.
|
||||
from bank_importer import positions
|
||||
unresolved = positions.unresolved_for_company(self.connection, self.company_a, "2026-12-31")
|
||||
self.assertEqual("100.00", unresolved["by_reason"]["subject_review"]["gross_amount"])
|
||||
|
||||
def test_unlocked_single_never_enters_ledger(self) -> None:
|
||||
self.add_row(
|
||||
self.company_a, own_account="6222000000000001",
|
||||
cp_account="6222000000000002", expense="100.00",
|
||||
)
|
||||
matching.reconcile_rows(self.connection, [1])
|
||||
self.assertEqual([], self.eligible())
|
||||
stats = ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
self.assertEqual(0, stats["created"])
|
||||
self.assertEqual([], self.ledger_events())
|
||||
|
||||
def test_same_company_transfer_never_enters_ledger(self) -> None:
|
||||
self.add_row(
|
||||
self.company_a, own_account="6222000000000001",
|
||||
cp_account="6222000000000001", expense="100.00",
|
||||
)
|
||||
self.add_row(
|
||||
self.company_a, own_account="6222000000000001",
|
||||
cp_account="6222000000000001", income="100.00",
|
||||
)
|
||||
matching.reconcile_rows(self.connection, [1, 2])
|
||||
eligible = self.eligible()
|
||||
self.assertEqual(0, len([e for e in eligible if e["payer_company_id"] == e["payee_company_id"]]))
|
||||
stats = ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
self.assertEqual(0, stats["created"])
|
||||
|
||||
def test_reconcile_is_idempotent(self) -> None:
|
||||
self.pair(self.company_a, self.company_b, "100.00")
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
events = self.ledger_events()
|
||||
self.assertEqual(1, len(events))
|
||||
before_revisions = self.connection.execute(
|
||||
"SELECT COUNT(*) AS n FROM ledger_event_revisions"
|
||||
).fetchone()["n"]
|
||||
stats = ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
self.assertEqual(1, stats["unchanged"])
|
||||
after_revisions = self.connection.execute(
|
||||
"SELECT COUNT(*) AS n FROM ledger_event_revisions"
|
||||
).fetchone()["n"]
|
||||
self.assertEqual(before_revisions, after_revisions)
|
||||
|
||||
def test_reconcile_picks_up_newly_linked_rows_as_new_pending_event(self) -> None:
|
||||
# A single observation locked as intercompany -> pending ledger event.
|
||||
row_a = self.add_row(
|
||||
self.company_a, own_account="6222000000000001",
|
||||
cp_account="6222000000000002", expense="100.00",
|
||||
)
|
||||
matching.reconcile_rows(self.connection, [row_a])
|
||||
single = self.connection.execute(
|
||||
"SELECT * FROM current_transfer_decisions"
|
||||
).fetchone()
|
||||
event_id = single["event_id"]
|
||||
decision = self.connection.execute(
|
||||
"SELECT * FROM transfer_match_decisions WHERE id = ?",
|
||||
(single["decision_id"],),
|
||||
).fetchone()
|
||||
matching.apply_manual_decision(
|
||||
self.connection, event_id, "assign_participant",
|
||||
reason="函证确认对方",
|
||||
expected_revision=decision["revision"], request_key="assign-1",
|
||||
actor=self.admin,
|
||||
participant={"role": "payee", "company_id": self.company_b},
|
||||
)
|
||||
self.assertEqual(1, len(self.eligible()))
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
self.assertEqual(1, len(self.ledger_events()))
|
||||
|
||||
# The administrator links two fresh rows with a different amount onto a
|
||||
# new canonical event; reconcile creates a second pending event.
|
||||
row_a2 = self.add_row(
|
||||
self.company_a, own_account="6222000000000001",
|
||||
cp_account="6222000000000002", expense="150.00",
|
||||
at="2026-02-01T10:00:00",
|
||||
)
|
||||
row_b2 = self.add_row(
|
||||
self.company_b, own_account="6222000000000002",
|
||||
cp_account="6222000000000001", income="150.00",
|
||||
at="2026-02-01T11:00:00",
|
||||
)
|
||||
current_row = self.connection.execute(
|
||||
"SELECT d.* FROM current_transfer_decisions c "
|
||||
"JOIN transfer_match_decisions d ON d.id = c.decision_id "
|
||||
"WHERE c.event_id = ?",
|
||||
(event_id,),
|
||||
).fetchone()
|
||||
matching.apply_manual_decision(
|
||||
self.connection, event_id, "link_rows",
|
||||
reason="补录双边流水",
|
||||
expected_revision=current_row["revision"], request_key="link-1",
|
||||
actor=self.admin, source_row_ids=[row_a2, row_b2],
|
||||
)
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
amounts = sorted(
|
||||
row["amount"] for row in self.connection.execute(
|
||||
"SELECT amount FROM ledger_event_revisions WHERE state = 'pending_subject'"
|
||||
).fetchall()
|
||||
)
|
||||
self.assertEqual(["100.00", "150.00"], amounts)
|
||||
|
||||
def test_confirm_subject_enters_position_view(self) -> None:
|
||||
self.pair(self.company_a, self.company_b, "100.00")
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
event_id = self.ledger_events()[0]["id"]
|
||||
subjects.confirm_subject(
|
||||
self.connection, event_id,
|
||||
perspective_company_id=self.company_a, subject_code="other_receivable",
|
||||
reason="借款建议其他应收", expected_revision=1, request_key="k1",
|
||||
actor=self.admin,
|
||||
)
|
||||
positions = self.position_events()
|
||||
self.assertEqual(1, len(positions))
|
||||
self.assertEqual("other_receivable", positions[0]["subject_code"])
|
||||
self.assertEqual(self.company_a, positions[0]["perspective_company_id"])
|
||||
|
||||
def test_confirm_stale_revision_conflicts(self) -> None:
|
||||
self.pair(self.company_a, self.company_b, "100.00")
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
event_id = self.ledger_events()[0]["id"]
|
||||
subjects.confirm_subject(
|
||||
self.connection, event_id,
|
||||
perspective_company_id=self.company_a, subject_code="receivable",
|
||||
reason="确认应收", expected_revision=1, request_key="k1",
|
||||
actor=self.admin,
|
||||
)
|
||||
with self.assertRaises(subjects.SubjectConflictError):
|
||||
subjects.confirm_subject(
|
||||
self.connection, event_id,
|
||||
perspective_company_id=self.company_a, subject_code="receivable",
|
||||
reason="重复确认", expected_revision=1, request_key="k2",
|
||||
actor=self.admin,
|
||||
)
|
||||
|
||||
def test_reversal_mirrors_direction_and_subject(self) -> None:
|
||||
self.pair(self.company_a, self.company_b, "100.00")
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
event_id = self.ledger_events()[0]["id"]
|
||||
subjects.confirm_subject(
|
||||
self.connection, event_id,
|
||||
perspective_company_id=self.company_a, subject_code="other_receivable",
|
||||
reason="借款", expected_revision=1, request_key="k1", actor=self.admin,
|
||||
)
|
||||
reversal_id, _ = ledger_events.create_reversal(
|
||||
self.connection, event_id, source_kind="adjustment",
|
||||
reason="冲销错误确认", actor=self.admin,
|
||||
)
|
||||
reversal = self.current(reversal_id)
|
||||
self.assertEqual("reversal", reversal["posting_kind"])
|
||||
self.assertEqual(self.company_b, reversal["payer_company_id"])
|
||||
self.assertEqual(self.company_a, reversal["payee_company_id"])
|
||||
self.assertEqual("other_payable", reversal["subject_code"])
|
||||
self.assertEqual(self.company_b, reversal["perspective_company_id"])
|
||||
# Original event stays confirmed and still in the position view.
|
||||
self.assertEqual("confirmed", self.current(event_id)["state"])
|
||||
positions = self.position_events()
|
||||
self.assertEqual(2, len(positions))
|
||||
signed = sum(
|
||||
Decimal(position["amount"]) * (
|
||||
1 if position["payer_company_id"] == self.company_a else -1
|
||||
)
|
||||
for position in positions
|
||||
)
|
||||
self.assertEqual(Decimal("0"), signed)
|
||||
|
||||
def test_evidence_rows_stay_immutable_under_reversal(self) -> None:
|
||||
self.pair(self.company_a, self.company_b, "100.00")
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
event_id = self.ledger_events()[0]["id"]
|
||||
subjects.confirm_subject(
|
||||
self.connection, event_id,
|
||||
perspective_company_id=self.company_a, subject_code="receivable",
|
||||
reason="确认", expected_revision=1, request_key="k1", actor=self.admin,
|
||||
)
|
||||
before = self.connection.execute(
|
||||
"SELECT income, expense FROM source_rows ORDER BY id"
|
||||
).fetchall()
|
||||
ledger_events.create_reversal(
|
||||
self.connection, event_id, source_kind="adjustment",
|
||||
reason="冲销", actor=self.admin,
|
||||
)
|
||||
after = self.connection.execute(
|
||||
"SELECT income, expense FROM source_rows ORDER BY id"
|
||||
).fetchall()
|
||||
self.assertEqual(before, after)
|
||||
|
||||
def test_reversal_idempotent_guard(self) -> None:
|
||||
self.pair(self.company_a, self.company_b, "100.00")
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
event_id = self.ledger_events()[0]["id"]
|
||||
subjects.confirm_subject(
|
||||
self.connection, event_id,
|
||||
perspective_company_id=self.company_a, subject_code="receivable",
|
||||
reason="确认", expected_revision=1, request_key="k1", actor=self.admin,
|
||||
)
|
||||
# Simulate the B-43 event leaving the eligible set.
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
"UPDATE canonical_transfer_events SET lifecycle = 'superseded' WHERE id = ?",
|
||||
(self.eligible()[0]["event_id"],),
|
||||
)
|
||||
stats = ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
self.assertEqual(1, stats["reversal"])
|
||||
reversals = self.connection.execute(
|
||||
"SELECT COUNT(*) AS n FROM ledger_event_revisions WHERE posting_kind = 'reversal'"
|
||||
).fetchone()["n"]
|
||||
self.assertEqual(1, reversals)
|
||||
# Re-run does not create a second reversal.
|
||||
stats = ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
self.assertEqual(0, stats["reversal"])
|
||||
|
||||
|
||||
class ProjectionTests(LedgerBase):
|
||||
def test_rebuild_current_projection(self) -> None:
|
||||
self.pair(self.company_a, self.company_b, "100.00")
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
event_id = self.ledger_events()[0]["id"]
|
||||
subjects.confirm_subject(
|
||||
self.connection, event_id,
|
||||
perspective_company_id=self.company_a, subject_code="receivable",
|
||||
reason="确认", expected_revision=1, request_key="k1", actor=self.admin,
|
||||
)
|
||||
self.connection.execute("DELETE FROM current_ledger_event_revisions")
|
||||
rebuilt = ledger_events.rebuild_current_ledger_projection(self.connection)
|
||||
self.assertGreaterEqual(rebuilt, 1)
|
||||
revision = self.current(event_id)
|
||||
self.assertEqual("confirmed", revision["state"])
|
||||
self.assertEqual("receivable", revision["subject_code"])
|
||||
|
||||
def test_reopen_subject_survives_connection_close(self) -> None:
|
||||
"""HEL-282: create_event used to commit the replacement event while
|
||||
the bank-source re-claim stayed uncommitted; close() dropped the claim."""
|
||||
from bank_importer.db import connect as db_connect
|
||||
|
||||
self.pair(self.company_a, self.company_b, "100.00")
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
original_id = self.ledger_events()[0]["id"]
|
||||
subjects.confirm_subject(
|
||||
self.connection, original_id,
|
||||
perspective_company_id=self.company_a, subject_code="receivable",
|
||||
reason="确认应收", expected_revision=1, request_key="k1",
|
||||
actor=self.admin,
|
||||
)
|
||||
new_id, _ = ledger_events.reopen_subject(
|
||||
self.connection, original_id,
|
||||
reason="科目复核更正为其他应收", actor=self.admin,
|
||||
)
|
||||
self.connection.close()
|
||||
fresh = db_connect(self.db_path)
|
||||
try:
|
||||
claim = fresh.execute(
|
||||
"SELECT ledger_event_id FROM ledger_event_bank_sources"
|
||||
).fetchone()
|
||||
new_state = fresh.execute(
|
||||
"""
|
||||
SELECT r.state FROM current_ledger_event_revisions c
|
||||
JOIN ledger_event_revisions r ON r.id = c.revision_id
|
||||
WHERE c.ledger_event_id = ?
|
||||
""",
|
||||
(new_id,),
|
||||
).fetchone()
|
||||
suggestions = fresh.execute(
|
||||
"SELECT COUNT(*) AS n FROM ledger_subject_suggestions WHERE ledger_event_id = ?",
|
||||
(new_id,),
|
||||
).fetchone()["n"]
|
||||
reversal = fresh.execute(
|
||||
"""
|
||||
SELECT COUNT(*) AS n FROM ledger_event_revisions
|
||||
WHERE posting_kind = 'reversal' AND reverses_ledger_event_id = ?
|
||||
""",
|
||||
(original_id,),
|
||||
).fetchone()["n"]
|
||||
finally:
|
||||
fresh.close()
|
||||
self.assertEqual(new_id, claim["ledger_event_id"])
|
||||
self.assertEqual("pending_subject", new_state["state"])
|
||||
self.assertGreaterEqual(suggestions, 1)
|
||||
self.assertEqual(1, reversal)
|
||||
|
||||
|
||||
class SubjectSuggestionTests(LedgerBase):
|
||||
def test_mirror_mapping_is_symmetric(self) -> None:
|
||||
for subject, mirror in (
|
||||
("receivable", "payable"), ("payable", "receivable"),
|
||||
("other_receivable", "other_payable"), ("other_payable", "other_receivable"),
|
||||
):
|
||||
self.assertEqual(mirror, subjects.mirror_subject(subject))
|
||||
self.assertEqual(subject, subjects.mirror_subject(mirror))
|
||||
|
||||
def test_loan_keyword_suggests_payer_other_receivable(self) -> None:
|
||||
self.pair(self.company_a, self.company_b, "100.00", summary="借款", purpose="往来款")
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
event_id = self.ledger_events()[0]["id"]
|
||||
suggestions = subjects.compute_suggestions(self.connection, event_id)
|
||||
self.assertEqual(1, len(suggestions))
|
||||
self.assertEqual(self.company_a, suggestions[0]["suggested_perspective_company_id"])
|
||||
self.assertEqual("other_receivable", suggestions[0]["suggested_subject_code"])
|
||||
self.assertFalse(suggestions[0]["evidence"]["approved"])
|
||||
|
||||
def test_repay_keyword_suggests_payee(self) -> None:
|
||||
self.pair(self.company_a, self.company_b, "100.00", summary="归还往来款", purpose="还款")
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
event_id = self.ledger_events()[0]["id"]
|
||||
suggestions = subjects.compute_suggestions(self.connection, event_id)
|
||||
self.assertEqual(1, len(suggestions))
|
||||
self.assertEqual(self.company_b, suggestions[0]["suggested_perspective_company_id"])
|
||||
|
||||
def test_trade_keyword_never_suggests(self) -> None:
|
||||
# Trade vocabulary needs group approval; no dictionary hit -> review.
|
||||
self.pair(self.company_a, self.company_b, "100.00", summary="货款", purpose="采购货款")
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
event_id = self.ledger_events()[0]["id"]
|
||||
self.assertEqual([], subjects.compute_suggestions(self.connection, event_id))
|
||||
|
||||
def test_name_alone_never_confirms(self) -> None:
|
||||
# A name match on the counterparty cannot decide the subject.
|
||||
self.pair(self.company_a, self.company_b, "100.00", summary="某客户往来", purpose=None)
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
event_id = self.ledger_events()[0]["id"]
|
||||
current = self.current(event_id)
|
||||
self.assertEqual("pending_subject", current["state"])
|
||||
self.assertEqual([], subjects.compute_suggestions(self.connection, event_id))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,607 +0,0 @@
|
||||
"""B-44 manual record tests: submit idempotency, approve new/link, return,
|
||||
exception, reverse, deduplication, idempotent replay and concurrency."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
import threading
|
||||
import unittest
|
||||
|
||||
from bank_importer import ledger_events, manual_records, matching, subjects
|
||||
from ledger_helpers import LedgerBase
|
||||
|
||||
|
||||
class SubmitTests(LedgerBase):
|
||||
def submit(self, **overrides):
|
||||
params = dict(
|
||||
company_id=self.company_a,
|
||||
counterparty_company_id=self.company_b,
|
||||
occurred_at="2026-01-10T09:00:00",
|
||||
direction="incoming",
|
||||
amount="50.00",
|
||||
currency="CNY",
|
||||
funding_source="other",
|
||||
requested_subject="other_receivable",
|
||||
request_key="mr-key",
|
||||
actor=self.admin,
|
||||
summary="归还往来款",
|
||||
)
|
||||
params.update(overrides)
|
||||
return manual_records.submit(self.connection, **params)
|
||||
|
||||
def test_submit_creates_pending_decision(self) -> None:
|
||||
payload = self.submit()
|
||||
self.assertEqual("pending", payload["state"])
|
||||
self.assertEqual(Decimal("50.00"), Decimal(payload["amount"]))
|
||||
self.assertEqual(1, payload["decision_revision"])
|
||||
self.assertEqual([], payload["candidates"])
|
||||
|
||||
def test_submit_idempotent_on_request_key(self) -> None:
|
||||
first = self.submit()
|
||||
second = self.submit()
|
||||
self.assertEqual(first["id"], second["id"])
|
||||
self.assertTrue(second["idempotent_replay"])
|
||||
decisions = self.connection.execute(
|
||||
"SELECT COUNT(*) AS n FROM manual_record_decisions"
|
||||
).fetchone()["n"]
|
||||
self.assertEqual(1, decisions)
|
||||
|
||||
def test_submit_validations(self) -> None:
|
||||
cases = (
|
||||
({"counterparty_company_id": self.company_a}, "不能与本公司相同"),
|
||||
({"amount": "0"}, "必须大于零"),
|
||||
({"amount": "abc"}, "十进制"),
|
||||
({"funding_source": "credit_card"}, "资金来源"),
|
||||
({"requested_subject": "equity"}, "科目"),
|
||||
({"request_key": ""}, "request_key"),
|
||||
({"counterparty_company_id": 9999}, "公司不存在"),
|
||||
)
|
||||
for overrides, expected in cases:
|
||||
with self.subTest(overrides=overrides):
|
||||
with self.assertRaises(manual_records.ManualInputError) as ctx:
|
||||
self.submit(**overrides)
|
||||
self.assertIn(expected, str(ctx.exception))
|
||||
|
||||
def test_bank_account_must_belong_to_submitting_company(self) -> None:
|
||||
with self.assertRaises(manual_records.ManualInputError):
|
||||
self.submit(
|
||||
funding_source="approved_bank_account",
|
||||
bank_account_id=self.account_b["id"],
|
||||
)
|
||||
|
||||
def test_related_source_row_never_modified(self) -> None:
|
||||
row_id = self.add_row(
|
||||
self.company_a, own_account="6222000000000001",
|
||||
cp_account="6222000000000002", expense="100.00",
|
||||
)
|
||||
payload = self.submit(related_source_row_id=row_id)
|
||||
self.assertEqual(row_id, payload["related_source_row_id"])
|
||||
with self.assertRaises(Exception):
|
||||
self.connection.execute(
|
||||
"UPDATE source_rows SET expense = '0' WHERE id = ?", (row_id,)
|
||||
)
|
||||
self.connection.rollback()
|
||||
|
||||
|
||||
class DecisionTests(LedgerBase):
|
||||
def setUp(self) -> None:
|
||||
super().setUp()
|
||||
self.record = manual_records.submit(
|
||||
self.connection,
|
||||
company_id=self.company_a, counterparty_company_id=self.company_b,
|
||||
occurred_at="2026-01-10T09:00:00", direction="incoming",
|
||||
amount="50.00", currency="CNY", funding_source="other",
|
||||
requested_subject="other_receivable", request_key="mr-1",
|
||||
actor=self.admin, summary="归还往来款",
|
||||
)
|
||||
|
||||
def decide(self, action, **overrides):
|
||||
params = dict(
|
||||
record_id=self.record["id"],
|
||||
action=action,
|
||||
reason="管理员审核",
|
||||
expected_decision_id=self.record["decision_id"],
|
||||
request_key="dec-key",
|
||||
actor=self.admin,
|
||||
)
|
||||
params.update(overrides)
|
||||
return manual_records.decide(self.connection, **params)
|
||||
|
||||
def test_approve_new_creates_confirmed_event_with_requested_subject(self) -> None:
|
||||
outcome = self.decide("approve_new")
|
||||
self.assertEqual("approved", outcome["state"])
|
||||
event_id = outcome["ledger_event_id"]
|
||||
revision = ledger_events.current_revision(self.connection, event_id)
|
||||
self.assertEqual("confirmed", revision["state"])
|
||||
# incoming 50 from A's perspective: B is the payer, A the payee.
|
||||
self.assertEqual(self.company_b, revision["payer_company_id"])
|
||||
self.assertEqual(self.company_a, revision["payee_company_id"])
|
||||
self.assertEqual(self.company_a, revision["perspective_company_id"])
|
||||
self.assertEqual("other_receivable", revision["subject_code"])
|
||||
# Exactly one position impact.
|
||||
positions = self.connection.execute(
|
||||
"SELECT * FROM eligible_position_events"
|
||||
).fetchall()
|
||||
self.assertEqual(1, len(positions))
|
||||
|
||||
def test_approve_new_replay_is_idempotent(self) -> None:
|
||||
first = self.decide("approve_new")
|
||||
second = self.decide("approve_new")
|
||||
self.assertEqual(first["decision_id"], second["decision_id"])
|
||||
events = self.connection.execute(
|
||||
"SELECT COUNT(*) AS n FROM ledger_events"
|
||||
).fetchone()["n"]
|
||||
self.assertEqual(1, events)
|
||||
|
||||
def test_return_and_exception_never_produce_balance(self) -> None:
|
||||
for action in ("return", "exception"):
|
||||
with self.subTest(action=action):
|
||||
fresh = manual_records.submit(
|
||||
self.connection,
|
||||
company_id=self.company_a, counterparty_company_id=self.company_b,
|
||||
occurred_at="2026-01-11T09:00:00", direction="incoming",
|
||||
amount="10.00", currency="CNY", funding_source="other",
|
||||
requested_subject="receivable", request_key=f"mr-{action}",
|
||||
actor=self.admin,
|
||||
)
|
||||
outcome = manual_records.decide(
|
||||
self.connection, fresh["id"], action,
|
||||
reason="材料不足" if action == "return" else "转入异常",
|
||||
expected_decision_id=fresh["decision_id"],
|
||||
request_key=f"dec-{action}", actor=self.admin,
|
||||
)
|
||||
expected_state = "returned" if action == "return" else "exception"
|
||||
self.assertEqual(expected_state, outcome["state"])
|
||||
self.assertEqual(0, self.connection.execute(
|
||||
"SELECT COUNT(*) AS n FROM eligible_position_events"
|
||||
).fetchone()["n"])
|
||||
|
||||
def test_reverse_of_approved_record_creates_reversal_event(self) -> None:
|
||||
approved = self.decide("approve_new")
|
||||
reversed_outcome = manual_records.decide(
|
||||
self.connection, self.record["id"], "reverse",
|
||||
reason="误录,冲销", expected_decision_id=approved["decision_id"],
|
||||
request_key="dec-rev", actor=self.admin,
|
||||
)
|
||||
self.assertEqual("reversed", reversed_outcome["state"])
|
||||
rows = self.connection.execute(
|
||||
"SELECT * FROM eligible_position_events ORDER BY ledger_event_id"
|
||||
).fetchall()
|
||||
self.assertEqual(2, len(rows))
|
||||
original, reversal = rows
|
||||
self.assertEqual("normal", original["posting_kind"])
|
||||
self.assertEqual("reversal", reversal["posting_kind"])
|
||||
self.assertEqual(original["payer_company_id"], reversal["payee_company_id"])
|
||||
self.assertEqual(Decimal(original["amount"]), Decimal(reversal["amount"]))
|
||||
# Net position is zero.
|
||||
signed = Decimal(original["amount"]) * (
|
||||
1 if original["payer_company_id"] == self.company_a else -1
|
||||
) + Decimal(reversal["amount"]) * (
|
||||
1 if reversal["payer_company_id"] == self.company_a else -1
|
||||
)
|
||||
self.assertEqual(Decimal("0"), signed)
|
||||
|
||||
def test_approve_link_to_bank_event_adds_evidence_not_impact(self) -> None:
|
||||
# Build an eligible bank event and confirm its subject.
|
||||
self.pair(self.company_a, self.company_b, "100.00")
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
bank_ledger_id = self.ledger_events()[0]["id"]
|
||||
subjects.confirm_subject(
|
||||
self.connection, bank_ledger_id,
|
||||
perspective_company_id=self.company_a, subject_code="other_receivable",
|
||||
reason="借款", expected_revision=1, request_key="subj-1",
|
||||
actor=self.admin,
|
||||
)
|
||||
before = len(self.position_events())
|
||||
outcome = manual_records.decide(
|
||||
self.connection, self.record["id"], "approve_link",
|
||||
reason="与银行事件同源", expected_decision_id=self.record["decision_id"],
|
||||
request_key="dec-link", actor=self.admin,
|
||||
target_ledger_event_id=bank_ledger_id,
|
||||
)
|
||||
self.assertEqual("approved", outcome["state"])
|
||||
self.assertEqual(bank_ledger_id, outcome["ledger_event_id"])
|
||||
after = len(self.position_events())
|
||||
self.assertEqual(before, after)
|
||||
sources = self.connection.execute(
|
||||
"SELECT * FROM ledger_event_manual_sources WHERE manual_record_id = ?",
|
||||
(self.record["id"],),
|
||||
).fetchall()
|
||||
self.assertEqual(1, len(sources))
|
||||
self.assertEqual(bank_ledger_id, sources[0]["ledger_event_id"])
|
||||
|
||||
def test_approve_link_requires_target(self) -> None:
|
||||
with self.assertRaises(manual_records.ManualInputError):
|
||||
self.decide("approve_link")
|
||||
|
||||
def test_reverse_of_linked_record_detaches_claim_only(self) -> None:
|
||||
self.pair(self.company_a, self.company_b, "100.00")
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
bank_ledger_id = self.ledger_events()[0]["id"]
|
||||
subjects.confirm_subject(
|
||||
self.connection, bank_ledger_id,
|
||||
perspective_company_id=self.company_a, subject_code="other_receivable",
|
||||
reason="借款", expected_revision=1, request_key="subj-1",
|
||||
actor=self.admin,
|
||||
)
|
||||
approved = manual_records.decide(
|
||||
self.connection, self.record["id"], "approve_link",
|
||||
reason="同源", expected_decision_id=self.record["decision_id"],
|
||||
request_key="dec-link", actor=self.admin,
|
||||
target_ledger_event_id=bank_ledger_id,
|
||||
)
|
||||
reversed_outcome = manual_records.decide(
|
||||
self.connection, self.record["id"], "reverse",
|
||||
reason="撤销关联", expected_decision_id=approved["decision_id"],
|
||||
request_key="dec-unlink", actor=self.admin,
|
||||
)
|
||||
self.assertEqual("reversed", reversed_outcome["state"])
|
||||
# No reversal event is created for a linked claim.
|
||||
reversals = self.connection.execute(
|
||||
"SELECT COUNT(*) AS n FROM ledger_event_revisions WHERE posting_kind = 'reversal'"
|
||||
).fetchone()["n"]
|
||||
self.assertEqual(0, reversals)
|
||||
# The bank impact is untouched.
|
||||
self.assertEqual(1, len(self.position_events()))
|
||||
|
||||
def test_stale_expected_decision_conflicts(self) -> None:
|
||||
approved = self.decide("approve_new")
|
||||
with self.assertRaises(manual_records.ManualConflictError):
|
||||
manual_records.decide(
|
||||
self.connection, self.record["id"], "reverse",
|
||||
reason="冲销", expected_decision_id=self.record["decision_id"],
|
||||
request_key="dec-stale", actor=self.admin,
|
||||
)
|
||||
|
||||
def test_returned_record_cannot_be_reversed(self) -> None:
|
||||
returned = self.decide("return", reason="材料不足")
|
||||
with self.assertRaises(manual_records.ManualConflictError):
|
||||
manual_records.decide(
|
||||
self.connection, self.record["id"], "reverse",
|
||||
reason="冲销", expected_decision_id=returned["decision_id"],
|
||||
request_key="dec-x", actor=self.admin,
|
||||
)
|
||||
|
||||
def test_reverse_uses_explicit_effective_date_across_cutoff(self) -> None:
|
||||
# Reversing with an independent effective date must keep the original
|
||||
# impact for cutoffs before it and net it to zero only on/after it —
|
||||
# never rewrite the historical period retroactively.
|
||||
from bank_importer import positions
|
||||
approved = self.decide("approve_new")
|
||||
event_id = approved["ledger_event_id"]
|
||||
self.assertEqual("2026-01-10", self.current(event_id)["effective_at"][:10])
|
||||
|
||||
manual_records.decide(
|
||||
self.connection, self.record["id"], "reverse",
|
||||
reason="误录冲销", expected_decision_id=approved["decision_id"],
|
||||
request_key="dec-rev-date", actor=self.admin,
|
||||
effective_at="2026-06-15",
|
||||
)
|
||||
reversal = self.connection.execute(
|
||||
"SELECT * FROM ledger_event_revisions WHERE posting_kind = 'reversal'"
|
||||
).fetchone()
|
||||
self.assertEqual("2026-06-15", reversal["effective_at"][:10])
|
||||
|
||||
before = positions.company_balances(
|
||||
self.connection, from_="2026-01-01", cutoff="2026-05-31"
|
||||
)
|
||||
after = positions.company_balances(
|
||||
self.connection, from_="2026-01-01", cutoff="2026-07-31"
|
||||
)
|
||||
for item in before["items"]:
|
||||
if item["company_id"] == self.company_a:
|
||||
self.assertEqual("-50.00", item["result"]["signed_amount"])
|
||||
for item in after["items"]:
|
||||
if item["company_id"] == self.company_a:
|
||||
self.assertEqual("0.00", item["result"]["signed_amount"])
|
||||
|
||||
def test_reverse_defaults_to_approval_business_day(self) -> None:
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from bank_importer import positions
|
||||
approved = self.decide("approve_new")
|
||||
manual_records.decide(
|
||||
self.connection, self.record["id"], "reverse",
|
||||
reason="误录冲销", expected_decision_id=approved["decision_id"],
|
||||
request_key="dec-rev-default", actor=self.admin,
|
||||
)
|
||||
today = datetime.now(timezone(timedelta(hours=8))).date().isoformat()
|
||||
reversal = self.connection.execute(
|
||||
"SELECT * FROM ledger_event_revisions WHERE posting_kind = 'reversal'"
|
||||
).fetchone()
|
||||
self.assertEqual(today, reversal["effective_at"][:10])
|
||||
|
||||
# The day before the approval business day keeps the original impact.
|
||||
before = positions.company_balances(
|
||||
self.connection, from_="2026-01-01",
|
||||
cutoff=(datetime.fromisoformat(today) - timedelta(days=1)).date().isoformat(),
|
||||
)
|
||||
for item in before["items"]:
|
||||
if item["company_id"] == self.company_a:
|
||||
self.assertEqual("-50.00", item["result"]["signed_amount"])
|
||||
|
||||
def test_reverse_of_creation_source_with_later_linked_evidence(self) -> None:
|
||||
# approve_new created the event; a second manual record later links
|
||||
# onto it. Reversing the creation source must still create an
|
||||
# equal-amount reversal — the original economic impact must not survive
|
||||
# just because other evidence was attached later.
|
||||
approved = self.decide("approve_new")
|
||||
event_id = approved["ledger_event_id"]
|
||||
|
||||
linked = manual_records.submit(
|
||||
self.connection, company_id=self.company_a,
|
||||
counterparty_company_id=self.company_b,
|
||||
occurred_at="2026-01-12T09:00:00", direction="incoming",
|
||||
amount="50.00", currency="CNY", funding_source="other",
|
||||
requested_subject="receivable", request_key="mr-link-ev",
|
||||
actor=self.admin,
|
||||
)
|
||||
manual_records.decide(
|
||||
self.connection, linked["id"], "approve_link",
|
||||
reason="同源补充证据", expected_decision_id=linked["decision_id"],
|
||||
request_key="dec-link-ev", actor=self.admin,
|
||||
target_ledger_event_id=event_id,
|
||||
)
|
||||
self.assertEqual(1, len(self.position_events()))
|
||||
|
||||
reversed_outcome = manual_records.decide(
|
||||
self.connection, self.record["id"], "reverse",
|
||||
reason="误录冲销", expected_decision_id=approved["decision_id"],
|
||||
request_key="dec-rev-create", actor=self.admin,
|
||||
)
|
||||
self.assertEqual("reversed", reversed_outcome["state"])
|
||||
rows = self.connection.execute(
|
||||
"SELECT * FROM eligible_position_events ORDER BY ledger_event_id"
|
||||
).fetchall()
|
||||
self.assertEqual(2, len(rows))
|
||||
original, reversal = rows
|
||||
self.assertEqual("normal", original["posting_kind"])
|
||||
self.assertEqual("reversal", reversal["posting_kind"])
|
||||
self.assertEqual(Decimal(original["amount"]), Decimal(reversal["amount"]))
|
||||
# The later linked evidence stays attached to the event.
|
||||
links = self.connection.execute(
|
||||
"SELECT * FROM ledger_event_manual_sources ORDER BY manual_record_id"
|
||||
).fetchall()
|
||||
self.assertEqual(2, len(links))
|
||||
|
||||
def test_reverse_of_linked_record_after_creation_reversal_detaches_only(self) -> None:
|
||||
# M1 creates the event, M2 links; after M1's reversal created the
|
||||
# offset, reversing the linked M2 must only detach, never add a second
|
||||
# reversal event.
|
||||
approved = self.decide("approve_new")
|
||||
event_id = approved["ledger_event_id"]
|
||||
linked = manual_records.submit(
|
||||
self.connection, company_id=self.company_a,
|
||||
counterparty_company_id=self.company_b,
|
||||
occurred_at="2026-01-12T09:00:00", direction="incoming",
|
||||
amount="50.00", currency="CNY", funding_source="other",
|
||||
requested_subject="receivable", request_key="mr-link-ev2",
|
||||
actor=self.admin,
|
||||
)
|
||||
linked_approved = manual_records.decide(
|
||||
self.connection, linked["id"], "approve_link",
|
||||
reason="同源补充证据", expected_decision_id=linked["decision_id"],
|
||||
request_key="dec-link-ev2", actor=self.admin,
|
||||
target_ledger_event_id=event_id,
|
||||
)
|
||||
manual_records.decide(
|
||||
self.connection, self.record["id"], "reverse",
|
||||
reason="误录冲销", expected_decision_id=approved["decision_id"],
|
||||
request_key="dec-rev-create2", actor=self.admin,
|
||||
)
|
||||
manual_records.decide(
|
||||
self.connection, linked["id"], "reverse",
|
||||
reason="撤销关联证据", expected_decision_id=linked_approved["decision_id"],
|
||||
request_key="dec-rev-link2", actor=self.admin,
|
||||
)
|
||||
reversals = self.connection.execute(
|
||||
"SELECT COUNT(*) AS n FROM ledger_event_revisions WHERE posting_kind = 'reversal'"
|
||||
).fetchone()["n"]
|
||||
self.assertEqual(1, reversals)
|
||||
links = self.connection.execute(
|
||||
"SELECT * FROM ledger_event_manual_sources"
|
||||
).fetchall()
|
||||
self.assertEqual(1, len(links))
|
||||
|
||||
|
||||
class DedupAndConcurrencyTests(LedgerBase):
|
||||
def test_duplicate_manual_record_pairing_candidate(self) -> None:
|
||||
manual_records.submit(
|
||||
self.connection, company_id=self.company_a,
|
||||
counterparty_company_id=self.company_b,
|
||||
occurred_at="2026-01-10T09:00:00", direction="outgoing",
|
||||
amount="40.00", currency="CNY", funding_source="other",
|
||||
requested_subject="other_receivable", request_key="mr-a",
|
||||
actor=self.admin,
|
||||
)
|
||||
other = manual_records.submit(
|
||||
self.connection, company_id=self.company_b,
|
||||
counterparty_company_id=self.company_a,
|
||||
occurred_at="2026-01-10T10:00:00", direction="incoming",
|
||||
amount="40.00", currency="CNY", funding_source="other",
|
||||
requested_subject="other_payable", request_key="mr-b",
|
||||
actor=self.admin,
|
||||
)
|
||||
candidates = manual_records.find_candidates(self.connection, other["id"])
|
||||
self.assertEqual(1, len(candidates))
|
||||
self.assertEqual("manual_record", candidates[0]["kind"])
|
||||
|
||||
def test_duplicate_bank_event_candidate_hints_link(self) -> None:
|
||||
self.pair(self.company_a, self.company_b, "100.00")
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
record = manual_records.submit(
|
||||
self.connection, company_id=self.company_a,
|
||||
counterparty_company_id=self.company_b,
|
||||
occurred_at="2026-01-05T12:00:00", direction="incoming",
|
||||
amount="100.00", currency="CNY", funding_source="other",
|
||||
requested_subject="other_receivable", request_key="mr-c",
|
||||
actor=self.admin,
|
||||
)
|
||||
candidates = manual_records.find_candidates(self.connection, record["id"])
|
||||
self.assertTrue(any(c["kind"] == "bank_event" for c in candidates))
|
||||
|
||||
def test_concurrent_approve_new_counts_once(self) -> None:
|
||||
record = manual_records.submit(
|
||||
self.connection, company_id=self.company_a,
|
||||
counterparty_company_id=self.company_b,
|
||||
occurred_at="2026-01-10T09:00:00", direction="incoming",
|
||||
amount="50.00", currency="CNY", funding_source="other",
|
||||
requested_subject="receivable", request_key="mr-conc",
|
||||
actor=self.admin,
|
||||
)
|
||||
errors: list[Exception] = []
|
||||
|
||||
def worker(thread_key: str) -> None:
|
||||
import sqlite3
|
||||
|
||||
try:
|
||||
connection = sqlite3.connect(self.db_path, timeout=30)
|
||||
connection.row_factory = sqlite3.Row
|
||||
try:
|
||||
manual_records.decide(
|
||||
connection, record["id"], "approve_new",
|
||||
reason="并发审批", expected_decision_id=record["decision_id"],
|
||||
request_key=f"dec-{thread_key}", actor=self.admin,
|
||||
)
|
||||
finally:
|
||||
connection.close()
|
||||
except Exception as exc: # pragma: no cover
|
||||
errors.append(exc)
|
||||
|
||||
threads = [
|
||||
threading.Thread(target=worker, args=(f"t{i}",)) for i in range(4)
|
||||
]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
|
||||
# Two connections can still double-commit, so the UNIQUE manual source
|
||||
# claim must make the second write fail or be a no-op; either way only
|
||||
# one ledger event may exist.
|
||||
events = self.connection.execute(
|
||||
"SELECT COUNT(*) AS n FROM ledger_events"
|
||||
).fetchone()["n"]
|
||||
self.assertEqual(1, events)
|
||||
|
||||
def test_concurrent_submit_same_request_key_is_idempotent(self) -> None:
|
||||
import sqlite3
|
||||
|
||||
results: list[dict] = []
|
||||
errors: list[Exception] = []
|
||||
|
||||
def worker(thread_key: str) -> None:
|
||||
try:
|
||||
connection = sqlite3.connect(self.db_path, timeout=30)
|
||||
connection.row_factory = sqlite3.Row
|
||||
try:
|
||||
payload = manual_records.submit(
|
||||
connection, company_id=self.company_a,
|
||||
counterparty_company_id=self.company_b,
|
||||
occurred_at="2026-01-10T09:00:00", direction="incoming",
|
||||
amount="50.00", currency="CNY", funding_source="other",
|
||||
requested_subject="receivable",
|
||||
request_key="mr-conc-submit", actor=self.admin,
|
||||
)
|
||||
results.append(payload)
|
||||
finally:
|
||||
connection.close()
|
||||
except Exception as exc: # pragma: no cover
|
||||
errors.append(exc)
|
||||
|
||||
threads = [
|
||||
threading.Thread(target=worker, args=(f"t{i}",)) for i in range(4)
|
||||
]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
|
||||
self.assertEqual([], errors)
|
||||
rows = self.connection.execute(
|
||||
"SELECT COUNT(*) AS n FROM manual_records"
|
||||
).fetchone()["n"]
|
||||
self.assertEqual(1, rows)
|
||||
self.assertEqual(1, len({payload["id"] for payload in results}))
|
||||
decisions = self.connection.execute(
|
||||
"SELECT COUNT(*) AS n FROM manual_record_decisions"
|
||||
).fetchone()["n"]
|
||||
self.assertEqual(1, decisions)
|
||||
|
||||
def test_concurrent_confirm_subject_same_key_creates_single_revision(self) -> None:
|
||||
import sqlite3
|
||||
|
||||
self.pair(self.company_a, self.company_b, "100.00")
|
||||
from bank_importer import ledger_events
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
event_id = self.ledger_events()[0]["id"]
|
||||
|
||||
outcomes: list[dict] = []
|
||||
errors: list[Exception] = []
|
||||
|
||||
def worker(thread_key: str) -> None:
|
||||
try:
|
||||
connection = sqlite3.connect(self.db_path, timeout=30)
|
||||
connection.row_factory = sqlite3.Row
|
||||
try:
|
||||
payload = subjects.confirm_subject(
|
||||
connection, event_id,
|
||||
perspective_company_id=self.company_a,
|
||||
subject_code="other_receivable", reason="并发确认",
|
||||
expected_revision=1, request_key="conc-subj-key",
|
||||
actor=self.admin,
|
||||
)
|
||||
outcomes.append(payload)
|
||||
finally:
|
||||
connection.close()
|
||||
except Exception as exc: # pragma: no cover
|
||||
errors.append(exc)
|
||||
|
||||
threads = [
|
||||
threading.Thread(target=worker, args=(f"t{i}",)) for i in range(4)
|
||||
]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
|
||||
self.assertEqual([], errors)
|
||||
confirmed = self.connection.execute(
|
||||
"SELECT COUNT(*) AS n FROM ledger_event_revisions WHERE state = 'confirmed'"
|
||||
).fetchone()["n"]
|
||||
self.assertEqual(1, confirmed)
|
||||
self.assertEqual(1, len({payload["revision_id"] for payload in outcomes}))
|
||||
|
||||
def test_repeated_confirm_same_key_appends_no_noise_revision(self) -> None:
|
||||
self.pair(self.company_a, self.company_b, "100.00")
|
||||
from bank_importer import ledger_events
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
event_id = self.ledger_events()[0]["id"]
|
||||
first = subjects.confirm_subject(
|
||||
self.connection, event_id,
|
||||
perspective_company_id=self.company_a, subject_code="other_receivable",
|
||||
reason="确认", expected_revision=1, request_key="noise-key",
|
||||
actor=self.admin,
|
||||
)
|
||||
second = subjects.confirm_subject(
|
||||
self.connection, event_id,
|
||||
perspective_company_id=self.company_a, subject_code="other_receivable",
|
||||
reason="重复确认", expected_revision=1, request_key="noise-key",
|
||||
actor=self.admin,
|
||||
)
|
||||
self.assertEqual(first["revision_id"], second["revision_id"])
|
||||
revisions = self.connection.execute(
|
||||
"SELECT COUNT(*) AS n FROM ledger_event_revisions WHERE ledger_event_id = ?",
|
||||
(event_id,),
|
||||
).fetchone()["n"]
|
||||
# One pending_subject + one confirmed; the replay appended nothing.
|
||||
self.assertEqual(2, revisions)
|
||||
confirmed = self.connection.execute(
|
||||
"SELECT COUNT(*) AS n FROM ledger_event_revisions "
|
||||
"WHERE ledger_event_id = ? AND state = 'confirmed'",
|
||||
(event_id,),
|
||||
).fetchone()["n"]
|
||||
self.assertEqual(1, confirmed)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,631 +0,0 @@
|
||||
"""Tests for dynamic master data (companies, bank accounts, aliases).
|
||||
|
||||
Unit tests exercise normalization, masking, effective-window boundaries and
|
||||
alias-match priority against an in-memory database; the HTTP integration
|
||||
class drives a live server to cover the submission -> review -> disable
|
||||
workflow, uniqueness under concurrency, masking boundaries and RBAC.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
|
||||
from bank_importer import auth, master_data
|
||||
from bank_importer.db import connect, migrate
|
||||
|
||||
import server
|
||||
from test_server_auth import Client, as_json
|
||||
|
||||
|
||||
BOOTSTRAP_PASSWORD = "BootAdmin123"
|
||||
ADMIN_PASSWORD = "AdminPass123"
|
||||
CASHIER_PASSWORD = "Cashier123"
|
||||
|
||||
|
||||
class MasterDataUnitTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.connection = connect(":memory:")
|
||||
migrate(self.connection)
|
||||
now = master_data.utc_now()
|
||||
cursor = self.connection.execute(
|
||||
"INSERT INTO companies (name, created_at, updated_at) VALUES ('甲公司', ?, ?)",
|
||||
(now, now),
|
||||
)
|
||||
self.company_id = int(cursor.lastrowid)
|
||||
self.connection.commit()
|
||||
|
||||
def tearDown(self) -> None:
|
||||
self.connection.close()
|
||||
|
||||
def _active_account(self, number: str = "1234567890123") -> object:
|
||||
return master_data.submit_bank_account(
|
||||
self.connection,
|
||||
company_id=self.company_id,
|
||||
bank_name="中信银行",
|
||||
account_type="基本户",
|
||||
account_number=number,
|
||||
start_date="2026-01-01",
|
||||
actor=None,
|
||||
)
|
||||
|
||||
def test_normalize_account_number(self) -> None:
|
||||
self.assertEqual("1234567890", master_data.normalize_account_number("1234 5678-90"))
|
||||
self.assertEqual("1234567890", master_data.normalize_account_number("1234567890"))
|
||||
for invalid in ("", "123", "abc123456", "12345678901234567890123456789012345"):
|
||||
with self.assertRaises(ValueError):
|
||||
master_data.normalize_account_number(invalid)
|
||||
|
||||
def test_mask_account_number(self) -> None:
|
||||
self.assertEqual("****9012", master_data.mask_account_number("123456789012"))
|
||||
self.assertEqual("****123", master_data.mask_account_number("123"))
|
||||
|
||||
def test_is_usable_window_boundaries(self) -> None:
|
||||
account = self._active_account()
|
||||
account = master_data.review_bank_account(
|
||||
self.connection, account["id"], "approve", None, self._admin(),
|
||||
effective_from="2026-02-01",
|
||||
)
|
||||
self.assertFalse(master_data.is_usable(account, "2026-01-31"))
|
||||
self.assertTrue(master_data.is_usable(account, "2026-02-01"))
|
||||
# A scheduled effective_to bounds the usable window (inclusive).
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
"UPDATE bank_accounts SET effective_to = '2026-06-30' WHERE id = ?",
|
||||
(account["id"],),
|
||||
)
|
||||
account = master_data.get_account(self.connection, account["id"])
|
||||
self.assertTrue(master_data.is_usable(account, "2026-06-30"))
|
||||
self.assertFalse(master_data.is_usable(account, "2026-07-01"))
|
||||
# Disabled accounts never accept new uploads, even inside the window.
|
||||
account = master_data.review_bank_account(
|
||||
self.connection, account["id"], "disable", "账户销户", self._admin(),
|
||||
effective_to="2026-06-30",
|
||||
)
|
||||
self.assertFalse(master_data.is_usable(account, "2026-06-30"))
|
||||
# …but they still identify historical rows inside the window.
|
||||
self.assertTrue(master_data.is_identifiable(account, "2026-06-30"))
|
||||
self.assertFalse(master_data.is_identifiable(account, "2026-07-01"))
|
||||
|
||||
def _admin(self):
|
||||
user = self.connection.execute(
|
||||
"SELECT * FROM users WHERE username = 'admin-u'"
|
||||
).fetchone()
|
||||
if user is None:
|
||||
auth.create_user(self.connection, "admin-u", "AdminPass123", "admin")
|
||||
user = self.connection.execute(
|
||||
"SELECT * FROM users WHERE username = 'admin-u'"
|
||||
).fetchone()
|
||||
return user
|
||||
|
||||
def test_pending_and_returned_accounts_never_usable(self) -> None:
|
||||
account = master_data.submit_bank_account(
|
||||
self.connection,
|
||||
company_id=self.company_id,
|
||||
bank_name="中信银行",
|
||||
account_type="一般户",
|
||||
account_number="9988776655",
|
||||
start_date="2026-01-01",
|
||||
actor=None,
|
||||
)
|
||||
self.assertFalse(master_data.is_usable(account, "2026-06-01"))
|
||||
account = master_data.review_bank_account(
|
||||
self.connection, account["id"], "return", "资料不全", self._admin()
|
||||
)
|
||||
self.assertEqual("returned", account["status"])
|
||||
self.assertFalse(master_data.is_usable(account, "2026-06-01"))
|
||||
|
||||
def test_alias_match_priority_and_window(self) -> None:
|
||||
exact_account = self._active_account("1111222233334")
|
||||
exact_account = master_data.review_bank_account(
|
||||
self.connection, exact_account["id"], "approve", None, self._admin(),
|
||||
effective_from="2026-01-01",
|
||||
)
|
||||
alias_account = master_data.submit_bank_account(
|
||||
self.connection,
|
||||
company_id=self.company_id,
|
||||
bank_name="建设银行",
|
||||
account_type="一般户",
|
||||
account_number="5555666677778",
|
||||
start_date="2026-01-01",
|
||||
actor=None,
|
||||
)
|
||||
alias_account = master_data.review_bank_account(
|
||||
self.connection, alias_account["id"], "approve", None, self._admin(),
|
||||
effective_from="2026-01-01",
|
||||
)
|
||||
master_data.add_alias(
|
||||
self.connection, alias_account["id"], "account", "9999000011112",
|
||||
priority=5, actor=None,
|
||||
)
|
||||
master_data.add_alias(
|
||||
self.connection, alias_account["id"], "name", "甲公司郑州分部",
|
||||
effective_from="2026-03-01", effective_to="2026-03-31", actor=None,
|
||||
)
|
||||
|
||||
# Exact account number beats the account alias tier.
|
||||
master_data.add_alias(
|
||||
self.connection, alias_account["id"], "account", "1111222233334",
|
||||
priority=1, actor=None,
|
||||
)
|
||||
hits = master_data.match_account(
|
||||
self.connection, account_number="1111-2222 3333 4", on_date="2026-06-01"
|
||||
)
|
||||
self.assertEqual(exact_account["id"], hits[0]["bank_account_id"])
|
||||
self.assertEqual("account_exact", hits[0]["via"])
|
||||
self.assertEqual(alias_account["id"], hits[1]["bank_account_id"])
|
||||
self.assertEqual("account_alias", hits[1]["via"])
|
||||
|
||||
# Name alias only matches inside its effective window.
|
||||
hits = master_data.match_account(
|
||||
self.connection, name="甲公司郑州分部 ", on_date="2026-03-15"
|
||||
)
|
||||
self.assertEqual(alias_account["id"], hits[0]["bank_account_id"])
|
||||
self.assertEqual("name_alias", hits[0]["via"])
|
||||
self.assertEqual(
|
||||
[],
|
||||
master_data.match_account(
|
||||
self.connection, name="甲公司郑州分部", on_date="2026-04-01"
|
||||
),
|
||||
)
|
||||
|
||||
def test_match_never_returns_pending_or_disabled(self) -> None:
|
||||
pending = master_data.submit_bank_account(
|
||||
self.connection,
|
||||
company_id=self.company_id,
|
||||
bank_name="郑州银行",
|
||||
account_type="一般户",
|
||||
account_number="7777888899990",
|
||||
actor=None,
|
||||
)
|
||||
self.assertEqual(
|
||||
[],
|
||||
master_data.match_account(self.connection, account_number="7777888899990"),
|
||||
)
|
||||
account = master_data.review_bank_account(
|
||||
self.connection, pending["id"], "approve", None, self._admin(),
|
||||
effective_from="2026-01-01",
|
||||
)
|
||||
self.assertTrue(
|
||||
master_data.match_account(self.connection, account_number="7777888899990")
|
||||
)
|
||||
master_data.review_bank_account(
|
||||
self.connection, account["id"], "disable", "销户", self._admin(),
|
||||
effective_to="2026-06-30",
|
||||
)
|
||||
# Disabled accounts still resolve dates inside their effective window…
|
||||
self.assertTrue(
|
||||
master_data.match_account(
|
||||
self.connection, account_number="7777888899990", on_date="2026-06-30"
|
||||
)
|
||||
)
|
||||
# …and never resolve dates after it.
|
||||
self.assertEqual(
|
||||
[],
|
||||
master_data.match_account(
|
||||
self.connection, account_number="7777888899990", on_date="2026-07-01"
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class MasterDataCommitTests(unittest.TestCase):
|
||||
"""File-database checks that business rows and audit share one commit."""
|
||||
|
||||
def setUp(self) -> None:
|
||||
self.temp_dir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp_dir.cleanup)
|
||||
self.db_path = Path(self.temp_dir.name) / "app.db"
|
||||
self.connection = connect(self.db_path)
|
||||
self.addCleanup(self.connection.close)
|
||||
migrate(self.connection)
|
||||
|
||||
def test_create_company_and_audit_survive_connection_close(self) -> None:
|
||||
company_id = master_data.create_company(
|
||||
self.connection, "丁公司", None, None, actor=None
|
||||
)
|
||||
self.connection.close()
|
||||
fresh = connect(self.db_path)
|
||||
try:
|
||||
company = fresh.execute(
|
||||
"SELECT name FROM companies WHERE id = ?", (company_id,)
|
||||
).fetchone()
|
||||
change = fresh.execute(
|
||||
"""
|
||||
SELECT action, entity_id FROM master_data_changes
|
||||
WHERE entity_type = 'company'
|
||||
"""
|
||||
).fetchone()
|
||||
finally:
|
||||
fresh.close()
|
||||
self.assertEqual("丁公司", company["name"])
|
||||
self.assertEqual("create", change["action"])
|
||||
self.assertEqual(company_id, change["entity_id"])
|
||||
|
||||
|
||||
class MasterDataApiTests(unittest.TestCase):
|
||||
"""Live-server workflow tests for account registration and review."""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
import os
|
||||
|
||||
cls.temp_dir = tempfile.TemporaryDirectory()
|
||||
root = Path(cls.temp_dir.name)
|
||||
cls.db_path = root / "app.db"
|
||||
cls.storage = root / "files"
|
||||
|
||||
cls._old_db_path = server.DB_PATH
|
||||
cls._old_storage = server.STORAGE_DIR
|
||||
server.DB_PATH = cls.db_path
|
||||
server.STORAGE_DIR = cls.storage
|
||||
|
||||
os.environ["APP_BOOTSTRAP_ADMIN_PASSWORD"] = BOOTSTRAP_PASSWORD
|
||||
connection = connect(cls.db_path)
|
||||
migrate(connection)
|
||||
server.ensure_bootstrap_admin(connection)
|
||||
connection.close()
|
||||
|
||||
class QuietHandler(server.AppHandler):
|
||||
def log_message(self, *args) -> None:
|
||||
pass
|
||||
|
||||
cls.httpd = server.ThreadingHTTPServer(("127.0.0.1", 0), QuietHandler)
|
||||
cls.port = cls.httpd.server_address[1]
|
||||
cls.thread = threading.Thread(target=cls.httpd.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
|
||||
cls.admin = Client("127.0.0.1", cls.port)
|
||||
status, _, data = cls.admin.post_json(
|
||||
"/api/login",
|
||||
{"username": "group-admin", "password": BOOTSTRAP_PASSWORD, "portal": "admin"},
|
||||
)
|
||||
assert status == 200, data
|
||||
status, _, data = cls.admin.post_json(
|
||||
"/api/password/change",
|
||||
{"old_password": BOOTSTRAP_PASSWORD, "new_password": ADMIN_PASSWORD},
|
||||
)
|
||||
assert status == 200, data
|
||||
|
||||
# Company A created together with its cashier login in one call.
|
||||
status, _, data = cls.admin.post_json(
|
||||
"/api/admin/companies",
|
||||
{"name": "甲公司", "credit_code": "91410100TEST", "cashier_name": "牛女士",
|
||||
"username": "cashier-a"},
|
||||
)
|
||||
assert status == 200, data
|
||||
payload = as_json(data)
|
||||
cls.company_a = payload["company_id"]
|
||||
cls.initial_a = payload["initial_password"]
|
||||
assert cls.initial_a != "cashier-a"
|
||||
assert len(cls.initial_a) >= 12
|
||||
|
||||
status, _, data = cls.admin.post_json("/api/admin/companies", {"name": "乙公司"})
|
||||
assert status == 200, data
|
||||
cls.company_b = as_json(data)["company_id"]
|
||||
status, _, data = cls.admin.post_json(
|
||||
"/api/admin/users", {"username": "cashier-b", "company_id": cls.company_b}
|
||||
)
|
||||
assert status == 200, data
|
||||
cls.initial_b = as_json(data)["initial_password"]
|
||||
assert cls.initial_b != "cashier-b"
|
||||
|
||||
cls.cashier_a = cls._login_company_user("cashier-a", cls.initial_a)
|
||||
cls.cashier_b = cls._login_company_user("cashier-b", cls.initial_b)
|
||||
|
||||
@classmethod
|
||||
def _login_company_user(cls, username: str, initial: str) -> Client:
|
||||
client = Client("127.0.0.1", cls.port)
|
||||
status, _, data = client.post_json(
|
||||
"/api/login", {"username": username, "password": initial, "portal": "company"}
|
||||
)
|
||||
assert status == 200, data
|
||||
status, _, data = client.post_json(
|
||||
"/api/password/change",
|
||||
{"old_password": initial, "new_password": CASHIER_PASSWORD},
|
||||
)
|
||||
assert status == 200, data
|
||||
return client
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls) -> None:
|
||||
import os
|
||||
|
||||
cls.httpd.shutdown()
|
||||
cls.httpd.server_close()
|
||||
server.DB_PATH = cls._old_db_path
|
||||
server.STORAGE_DIR = cls._old_storage
|
||||
os.environ.pop("APP_BOOTSTRAP_ADMIN_PASSWORD", None)
|
||||
cls.temp_dir.cleanup()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def submit_account(self, client: Client, number: str, bank: str = "郑州银行"):
|
||||
return client.post_json(
|
||||
"/api/company/accounts",
|
||||
{"bank_name": bank, "account_type": "一般户",
|
||||
"account_number": number, "start_date": "2026-08-01"},
|
||||
)
|
||||
|
||||
def review(self, account_id: int, decision: str, reason: str = ""):
|
||||
return self.admin.post_json(
|
||||
f"/api/admin/accounts/{account_id}/review",
|
||||
{"decision": decision, "reason": reason},
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Company management
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_new_company_appears_in_admin_list_with_user(self) -> None:
|
||||
status, _, data = self.admin.get("/api/admin/companies")
|
||||
self.assertEqual(200, status)
|
||||
companies = {c["name"]: c for c in as_json(data)["companies"]}
|
||||
self.assertIn("甲公司", companies)
|
||||
self.assertEqual("91410100TEST", companies["甲公司"]["credit_code"])
|
||||
self.assertEqual("牛女士", companies["甲公司"]["cashier_name"])
|
||||
self.assertIn("cashier-a", companies["甲公司"]["usernames"])
|
||||
self.assertEqual(0, companies["乙公司"]["account_count"])
|
||||
|
||||
def test_company_user_cannot_change_own_company_binding(self) -> None:
|
||||
# A company_id in the submission body is ignored: the account is
|
||||
# always bound to the session company.
|
||||
status, _, data = self.cashier_a.post_json(
|
||||
"/api/company/accounts",
|
||||
{"bank_name": "民生银行", "account_type": "一般户",
|
||||
"account_number": "6001000100010001", "company_id": self.company_b},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
self.assertEqual(self.company_a, as_json(data)["account"]["company_id"])
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Account registration -> review workflow
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_full_registration_workflow(self) -> None:
|
||||
status, _, data = self.submit_account(self.cashier_a, "6222 0210-0100 8888")
|
||||
self.assertEqual(200, status, data)
|
||||
account = as_json(data)["account"]
|
||||
account_id = account["id"]
|
||||
self.assertEqual("pending", account["status"])
|
||||
# Company view is masked only.
|
||||
self.assertEqual("****8888", account["account_number_masked"])
|
||||
self.assertNotIn("account_number", account)
|
||||
self.assertFalse(account.get("usable", True))
|
||||
|
||||
# Admin audit view shows the full normalized number.
|
||||
status, _, data = self.admin.get("/api/admin/accounts")
|
||||
self.assertEqual(200, status)
|
||||
full = [a for a in as_json(data)["accounts"] if a["id"] == account_id][0]
|
||||
self.assertEqual("62220210010088 88".replace(" ", ""), full["account_number"])
|
||||
self.assertEqual("甲公司", full["company_name"])
|
||||
|
||||
# Pending account cannot upload.
|
||||
sample = Path("流水模板/中信银行账户流水.xlsx")
|
||||
status, _, data = self.cashier_a.post_multipart(
|
||||
"/api/parse", {"bank_account_id": str(account_id)},
|
||||
sample.name, sample.read_bytes(),
|
||||
)
|
||||
self.assertEqual(409, status, data)
|
||||
|
||||
# Approve -> active and usable.
|
||||
status, _, data = self.review(account_id, "approve")
|
||||
self.assertEqual(200, status, data)
|
||||
self.assertEqual("active", as_json(data)["account"]["status"])
|
||||
self.assertEqual("2026-08-01", as_json(data)["account"]["effective_from"])
|
||||
|
||||
status, _, data = self.cashier_a.get("/api/company/accounts")
|
||||
mine = [a for a in as_json(data)["accounts"] if a["id"] == account_id][0]
|
||||
self.assertTrue(mine["usable"])
|
||||
|
||||
# Approved account accepts uploads.
|
||||
status, _, data = self.cashier_a.post_multipart(
|
||||
"/api/parse", {"bank_account_id": str(account_id)},
|
||||
sample.name, sample.read_bytes(),
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
|
||||
# Disable -> leaves the usable window.
|
||||
status, _, data = self.review(account_id, "disable", "账户销户")
|
||||
self.assertEqual(200, status, data)
|
||||
disabled = as_json(data)["account"]
|
||||
self.assertEqual("disabled", disabled["status"])
|
||||
self.assertIsNotNone(disabled["effective_to"])
|
||||
|
||||
status, _, data = self.cashier_a.get("/api/company/accounts")
|
||||
mine = [a for a in as_json(data)["accounts"] if a["id"] == account_id][0]
|
||||
self.assertFalse(mine["usable"])
|
||||
|
||||
def test_return_and_resubmit_reuses_same_row(self) -> None:
|
||||
status, _, data = self.submit_account(self.cashier_a, "3100998877665")
|
||||
self.assertEqual(200, status, data)
|
||||
account_id = as_json(data)["account"]["id"]
|
||||
|
||||
status, _, data = self.review(account_id, "return", "开户许可证模糊")
|
||||
self.assertEqual(200, status, data)
|
||||
self.assertEqual("returned", as_json(data)["account"]["status"])
|
||||
|
||||
# Return requires a reason.
|
||||
status, _, data = self.submit_account(self.cashier_a, "3100998877666")
|
||||
other_id = as_json(data)["account"]["id"]
|
||||
status, _, _ = self.review(other_id, "return")
|
||||
self.assertEqual(400, status)
|
||||
|
||||
# Resubmission reopens the same row as pending.
|
||||
status, _, data = self.submit_account(self.cashier_a, "3100 9988-7766 5")
|
||||
self.assertEqual(200, status, data)
|
||||
resubmitted = as_json(data)["account"]
|
||||
self.assertEqual(account_id, resubmitted["id"])
|
||||
self.assertEqual("pending", resubmitted["status"])
|
||||
|
||||
# The whole trail is auditable with actor, time and reason.
|
||||
status, _, data = self.admin.get(
|
||||
f"/api/admin/master-changes?entity_type=bank_account&entity_id={account_id}"
|
||||
)
|
||||
self.assertEqual(200, status)
|
||||
changes = as_json(data)["changes"]
|
||||
actions = [change["action"] for change in changes]
|
||||
self.assertEqual(["resubmit", "return", "submit"], actions)
|
||||
returned = [c for c in changes if c["action"] == "return"][0]
|
||||
self.assertEqual("开户许可证模糊", returned["reason"])
|
||||
self.assertEqual("group-admin", returned["actor_username"])
|
||||
self.assertIn('"pending"', returned["before_json"])
|
||||
self.assertIn('"returned"', returned["after_json"])
|
||||
|
||||
def test_duplicate_normalized_number_conflicts(self) -> None:
|
||||
status, _, _ = self.submit_account(self.cashier_a, "4501111222233")
|
||||
self.assertEqual(200, status)
|
||||
# Same company, same number with different separators.
|
||||
status, _, data = self.submit_account(self.cashier_a, "4501-1112 2223-3")
|
||||
self.assertEqual(409, status, data)
|
||||
# Another company registering the same number conflicts too.
|
||||
status, _, data = self.submit_account(self.cashier_b, "4501111222233")
|
||||
self.assertEqual(409, status, data)
|
||||
self.assertIn("其他公司", as_json(data)["message"])
|
||||
|
||||
def test_concurrent_submissions_create_only_one_account(self) -> None:
|
||||
number = "8800123456789"
|
||||
results: list[int] = []
|
||||
|
||||
def submit() -> None:
|
||||
client = Client("127.0.0.1", self.port)
|
||||
client.cookies.update(self.cashier_a.cookies)
|
||||
status, _, _ = client.post_json(
|
||||
"/api/company/accounts",
|
||||
{"bank_name": "中信银行", "account_type": "基本户",
|
||||
"account_number": number},
|
||||
)
|
||||
results.append(status)
|
||||
|
||||
threads = [threading.Thread(target=submit) for _ in range(2)]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
self.assertEqual(sorted(results), [200, 409])
|
||||
|
||||
connection = connect(self.db_path)
|
||||
try:
|
||||
count = connection.execute(
|
||||
"SELECT COUNT(*) AS n FROM bank_accounts WHERE account_number = ?",
|
||||
(number,),
|
||||
).fetchone()["n"]
|
||||
finally:
|
||||
connection.close()
|
||||
self.assertEqual(1, count)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# RBAC and masking
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_company_user_forbidden_on_admin_account_endpoints(self) -> None:
|
||||
for call in (
|
||||
lambda: self.cashier_a.get("/api/admin/accounts"),
|
||||
lambda: self.cashier_a.post_json(
|
||||
"/api/admin/accounts/1/review", {"decision": "approve"}
|
||||
),
|
||||
lambda: self.cashier_a.get("/api/admin/accounts/1/aliases"),
|
||||
lambda: self.cashier_a.post_json(
|
||||
"/api/admin/accounts/1/aliases",
|
||||
{"alias_kind": "name", "alias_value": "x"},
|
||||
),
|
||||
lambda: self.cashier_a.get("/api/admin/master-changes"),
|
||||
):
|
||||
status, _, data = call()
|
||||
self.assertEqual(403, status, data)
|
||||
|
||||
def test_admin_cannot_use_company_account_endpoint(self) -> None:
|
||||
status, _, _ = self.admin.get("/api/company/accounts")
|
||||
self.assertEqual(403, status)
|
||||
status, _, _ = self.submit_account(self.admin, "1000200030004")
|
||||
self.assertEqual(403, status)
|
||||
|
||||
def test_unauthenticated_master_data_calls_return_401(self) -> None:
|
||||
anon = Client("127.0.0.1", self.port)
|
||||
for call in (
|
||||
lambda: anon.get("/api/company/accounts"),
|
||||
lambda: anon.get("/api/admin/accounts"),
|
||||
lambda: anon.post_json("/api/company/accounts", {}),
|
||||
lambda: anon.get("/api/admin/master-changes"),
|
||||
):
|
||||
status, _, _ = call()
|
||||
self.assertEqual(401, status)
|
||||
|
||||
def test_company_account_list_scoped_and_masked(self) -> None:
|
||||
status, _, data = self.cashier_b.get("/api/company/accounts")
|
||||
self.assertEqual(200, status)
|
||||
for account in as_json(data)["accounts"]:
|
||||
self.assertEqual(self.company_b, account["company_id"])
|
||||
self.assertNotIn("account_number", account)
|
||||
self.assertTrue(account["account_number_masked"].startswith("****"))
|
||||
|
||||
def test_upload_with_other_companys_account_returns_404(self) -> None:
|
||||
status, _, data = self.submit_account(self.cashier_a, "5550001112223")
|
||||
account_id = as_json(data)["account"]["id"]
|
||||
status, _, _ = self.review(account_id, "approve")
|
||||
self.assertEqual(200, status)
|
||||
sample = Path("流水模板/中信银行账户流水.xlsx")
|
||||
status, _, data = self.cashier_b.post_multipart(
|
||||
"/api/parse", {"bank_account_id": str(account_id)},
|
||||
sample.name, sample.read_bytes(),
|
||||
)
|
||||
self.assertEqual(404, status, data)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Aliases via API
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_alias_crud_and_audit(self) -> None:
|
||||
status, _, data = self.submit_account(self.cashier_a, "6601234509876")
|
||||
account_id = as_json(data)["account"]["id"]
|
||||
status, _, _ = self.review(account_id, "approve")
|
||||
self.assertEqual(200, status)
|
||||
|
||||
status, _, data = self.admin.post_json(
|
||||
f"/api/admin/accounts/{account_id}/aliases",
|
||||
{"alias_kind": "name", "alias_value": "甲公司工会",
|
||||
"effective_from": "2026-01-01", "effective_to": "2026-12-31",
|
||||
"priority": 10},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
alias_id = as_json(data)["alias_id"]
|
||||
|
||||
# Duplicate alias on the same account conflicts.
|
||||
status, _, _ = self.admin.post_json(
|
||||
f"/api/admin/accounts/{account_id}/aliases",
|
||||
{"alias_kind": "name", "alias_value": "甲公司工会"},
|
||||
)
|
||||
self.assertEqual(409, status)
|
||||
|
||||
status, _, data = self.admin.get(f"/api/admin/accounts/{account_id}/aliases")
|
||||
self.assertEqual(200, status)
|
||||
aliases = as_json(data)["aliases"]
|
||||
self.assertEqual(1, len(aliases))
|
||||
self.assertEqual("甲公司工会", aliases[0]["alias_value"])
|
||||
self.assertEqual(10, aliases[0]["priority"])
|
||||
|
||||
status, _, data = self.admin.get(
|
||||
f"/api/admin/master-changes?entity_type=account_alias&entity_id={alias_id}"
|
||||
)
|
||||
changes = as_json(data)["changes"]
|
||||
self.assertEqual("create", changes[0]["action"])
|
||||
self.assertIn("2026-12-31", changes[0]["after_json"])
|
||||
|
||||
# Invalid alias input is rejected, unknown account is 404.
|
||||
status, _, _ = self.admin.post_json(
|
||||
f"/api/admin/accounts/{account_id}/aliases",
|
||||
{"alias_kind": "account", "alias_value": "abc"},
|
||||
)
|
||||
self.assertEqual(400, status)
|
||||
status, _, _ = self.admin.post_json(
|
||||
"/api/admin/accounts/99999/aliases",
|
||||
{"alias_kind": "name", "alias_value": "x"},
|
||||
)
|
||||
self.assertEqual(404, status)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,463 +0,0 @@
|
||||
"""HTTP integration tests for the canonical transfer event APIs (B-43).
|
||||
|
||||
Covers the admin event list/detail, manual decisions and reconcile endpoints,
|
||||
personal transit mapping workflow, upload-account persistence, and the
|
||||
company-side read scoping with masked counterparty evidence. Uses a real
|
||||
``ThreadingHTTPServer`` like ``test_server_auth``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
|
||||
from openpyxl import Workbook
|
||||
|
||||
from bank_importer.db import connect, migrate
|
||||
|
||||
import server
|
||||
from test_server_auth import Client, as_json
|
||||
|
||||
BOOTSTRAP_PASSWORD = "BootAdmin123"
|
||||
ADMIN_PASSWORD = "AdminPass123"
|
||||
CASHIER_PASSWORD = "Cashier123"
|
||||
|
||||
CCB_HEADER = [
|
||||
"客户账号", "账户名称", "交易时间", "借方发生额(支取)", "贷方发生额(收入)",
|
||||
"余额", "币种", "对方户名", "对方账号", "对方开户机构", "摘要", "备注",
|
||||
]
|
||||
|
||||
ACCOUNT_A = "6222000000000001"
|
||||
ACCOUNT_B = "6222000000000002"
|
||||
ACCOUNT_C = "6222000000000003"
|
||||
|
||||
|
||||
def workbook_bytes(rows) -> bytes:
|
||||
workbook = Workbook()
|
||||
sheet = workbook.active
|
||||
sheet.title = "正常流水"
|
||||
sheet.append(CCB_HEADER)
|
||||
for row in rows:
|
||||
sheet.append(row)
|
||||
buffer = io.BytesIO()
|
||||
workbook.save(buffer)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def outgoing(own: str, cp: str, amount: str, at: str = "2026-01-05 10:00:00"):
|
||||
return [own, "测试公司", at, amount, "", "50000.00", "RMB", "对方", cp, "某银行", "货款", ""]
|
||||
|
||||
|
||||
def incoming(own: str, cp: str, amount: str, at: str = "2026-01-05 11:00:00"):
|
||||
return [own, "测试公司", at, "", amount, "50000.00", "RMB", "对方", cp, "某银行", "收款", ""]
|
||||
|
||||
|
||||
class MatchingApiTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
cls.temp_dir = tempfile.TemporaryDirectory()
|
||||
root = Path(cls.temp_dir.name)
|
||||
cls.db_path = root / "app.db"
|
||||
cls.storage = root / "files"
|
||||
|
||||
cls._old_db_path = server.DB_PATH
|
||||
cls._old_storage = server.STORAGE_DIR
|
||||
server.DB_PATH = cls.db_path
|
||||
server.STORAGE_DIR = cls.storage
|
||||
|
||||
os.environ["APP_BOOTSTRAP_ADMIN_PASSWORD"] = BOOTSTRAP_PASSWORD
|
||||
connection = connect(cls.db_path)
|
||||
migrate(connection)
|
||||
assert server.ensure_bootstrap_admin(connection) is None
|
||||
connection.close()
|
||||
|
||||
class QuietHandler(server.AppHandler):
|
||||
def log_message(self, *args) -> None:
|
||||
pass
|
||||
|
||||
cls.httpd = server.ThreadingHTTPServer(("127.0.0.1", 0), QuietHandler)
|
||||
cls.port = cls.httpd.server_address[1]
|
||||
cls.thread = threading.Thread(target=cls.httpd.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
|
||||
cls.admin = Client("127.0.0.1", cls.port)
|
||||
status, _, data = cls.admin.post_json(
|
||||
"/api/login",
|
||||
{"username": "group-admin", "password": BOOTSTRAP_PASSWORD, "portal": "admin"},
|
||||
)
|
||||
assert status == 200, data
|
||||
status, _, data = cls.admin.post_json(
|
||||
"/api/password/change",
|
||||
{"old_password": BOOTSTRAP_PASSWORD, "new_password": ADMIN_PASSWORD},
|
||||
)
|
||||
assert status == 200, data
|
||||
|
||||
cls.company_a = cls._create_company("甲公司", "cashier-a")
|
||||
cls.company_b = cls._create_company("乙公司", "cashier-b")
|
||||
cls.company_c = cls._create_company("丙公司", "cashier-c")
|
||||
cls.cashier_a = cls._login_company("cashier-a", cls.company_a)
|
||||
cls.cashier_b = cls._login_company("cashier-b", cls.company_b)
|
||||
cls.cashier_c = cls._login_company("cashier-c", cls.company_c)
|
||||
|
||||
cls.account_a = cls._approve_account(cls.company_a, ACCOUNT_A)
|
||||
cls.account_b = cls._approve_account(cls.company_b, ACCOUNT_B)
|
||||
cls.account_c = cls._approve_account(cls.company_c, ACCOUNT_C)
|
||||
|
||||
# One A<->B matched event and one B<->C matched event.
|
||||
cls._upload_and_confirm(cls.cashier_a, cls.company_a, [outgoing(ACCOUNT_A, ACCOUNT_B, "100.00")])
|
||||
cls._upload_and_confirm(cls.cashier_b, cls.company_b, [incoming(ACCOUNT_B, ACCOUNT_A, "100.00")])
|
||||
cls._upload_and_confirm(cls.cashier_b, cls.company_b, [outgoing(ACCOUNT_B, ACCOUNT_C, "200.00")])
|
||||
cls._upload_and_confirm(cls.cashier_c, cls.company_c, [incoming(ACCOUNT_C, ACCOUNT_B, "200.00")])
|
||||
|
||||
@classmethod
|
||||
def _create_company(cls, name: str, username: str) -> int:
|
||||
status, _, data = cls.admin.post_json(
|
||||
"/api/admin/companies",
|
||||
{"name": name, "username": username},
|
||||
)
|
||||
assert status == 200, data
|
||||
cls.initial_passwords.setdefault(username, as_json(data)["initial_password"])
|
||||
return as_json(data)["company_id"]
|
||||
|
||||
initial_passwords: dict[str, str] = {}
|
||||
|
||||
@classmethod
|
||||
def _login_company(cls, username: str, company_id: int) -> Client:
|
||||
client = Client("127.0.0.1", cls.port)
|
||||
initial = cls.initial_passwords[username]
|
||||
status, _, data = client.post_json(
|
||||
"/api/login", {"username": username, "password": initial, "portal": "company"}
|
||||
)
|
||||
assert status == 200, data
|
||||
status, _, data = client.post_json(
|
||||
"/api/password/change",
|
||||
{"old_password": initial, "new_password": CASHIER_PASSWORD},
|
||||
)
|
||||
assert status == 200, data
|
||||
return client
|
||||
|
||||
@classmethod
|
||||
def _approve_account(cls, company_id: int, number: str) -> int:
|
||||
# Build the account through company submission + admin review.
|
||||
company_client = {
|
||||
cls.company_a: cls.cashier_a,
|
||||
cls.company_b: cls.cashier_b,
|
||||
cls.company_c: cls.cashier_c,
|
||||
}[company_id]
|
||||
status, _, data = company_client.post_json(
|
||||
"/api/company/accounts",
|
||||
{"bank_name": "中信银行", "account_type": "基本户",
|
||||
"account_number": number, "start_date": "2026-01-01"},
|
||||
)
|
||||
assert status == 200, data
|
||||
account_id = as_json(data)["account"]["id"]
|
||||
status, _, data = cls.admin.post_json(
|
||||
f"/api/admin/accounts/{account_id}/review",
|
||||
{"decision": "approve", "reason": "测试启用",
|
||||
"effective_from": "2026-01-01"},
|
||||
)
|
||||
assert status == 200, data
|
||||
return account_id
|
||||
|
||||
@classmethod
|
||||
def _upload_and_confirm(cls, client, company_id: int, rows) -> int:
|
||||
content = workbook_bytes(rows)
|
||||
status, _, data = cls.admin.post_multipart(
|
||||
"/api/parse", {"company_id": str(company_id)}, "账单.xlsx", content
|
||||
)
|
||||
assert status == 200, data
|
||||
batch_id = as_json(data)["batch_id"]
|
||||
status, _, data = client.get(f"/api/batches/{batch_id}/sheets")
|
||||
assert status == 200, data
|
||||
names = [s["sheet_name"] for s in as_json(data)["sheets"] if s["outcome"] == "parsed"]
|
||||
status, _, data = client.post_json(
|
||||
f"/api/batches/{batch_id}/confirm", {"sheets": names}
|
||||
)
|
||||
assert status == 200, data
|
||||
return batch_id
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls) -> None:
|
||||
cls.httpd.shutdown()
|
||||
cls.httpd.server_close()
|
||||
server.DB_PATH = cls._old_db_path
|
||||
server.STORAGE_DIR = cls._old_storage
|
||||
os.environ.pop("APP_BOOTSTRAP_ADMIN_PASSWORD", None)
|
||||
cls.temp_dir.cleanup()
|
||||
|
||||
def events(self, client) -> list[dict]:
|
||||
status, _, data = client.get("/api/admin/transfer-events")
|
||||
self.assertEqual(200, status, data)
|
||||
return as_json(data)["events"]
|
||||
|
||||
def company_events(self, client) -> list[dict]:
|
||||
status, _, data = client.get("/api/company/transfer-events")
|
||||
self.assertEqual(200, status, data)
|
||||
return as_json(data)["events"]
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Admin event views
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_admin_lists_matched_events(self) -> None:
|
||||
events = self.events(self.admin)
|
||||
matched = [e for e in events if e["status"] == "matched"]
|
||||
self.assertGreaterEqual(len(matched), 2)
|
||||
by_amount = {e["amount"]: e for e in matched}
|
||||
self.assertEqual(self.company_a, by_amount["100.00"]["payer_company_id"])
|
||||
self.assertEqual(self.company_b, by_amount["100.00"]["payee_company_id"])
|
||||
self.assertEqual("paired", by_amount["100.00"]["pairing"])
|
||||
self.assertEqual(2, by_amount["100.00"]["evidence_count"])
|
||||
|
||||
def test_admin_event_detail_has_history_and_observations(self) -> None:
|
||||
events = self.events(self.admin)
|
||||
event = next(e for e in events if e["status"] == "matched")
|
||||
status, _, data = self.admin.get(f"/api/admin/transfer-events/{event['event_id']}")
|
||||
self.assertEqual(200, status, data)
|
||||
detail = as_json(data)["event"]
|
||||
self.assertEqual("matched", detail["status"])
|
||||
self.assertEqual(2, len(detail["observations"]))
|
||||
self.assertTrue(detail["history"])
|
||||
self.assertTrue(detail["candidates"])
|
||||
|
||||
def test_admin_match_exceptions(self) -> None:
|
||||
status, _, data = self.admin.get("/api/admin/match-exceptions")
|
||||
self.assertEqual(200, status, data)
|
||||
self.assertIsInstance(as_json(data)["exceptions"], list)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Admin manual decisions and reconcile via API
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_admin_reconcile_by_batch_is_idempotent(self) -> None:
|
||||
# Re-running reconcile on an already settled batch changes nothing.
|
||||
status, _, data = self.admin.post_json(
|
||||
"/api/admin/transfer-events/reconcile", {"batch_id": 1}
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
result = as_json(data)["matching"]
|
||||
self.assertEqual(0, result["created_events"])
|
||||
self.assertEqual(0, result["updated_events"])
|
||||
|
||||
def test_admin_confirm_single_and_reverse_via_api(self) -> None:
|
||||
# A uploads its side only -> internal_single.
|
||||
status, _, data = self.admin.post_multipart(
|
||||
"/api/parse", {"company_id": str(self.company_a)},
|
||||
"单边.xlsx", workbook_bytes([outgoing(ACCOUNT_A, ACCOUNT_B, "300.00", "2026-02-01 10:00:00")]),
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
batch_id = as_json(data)["batch_id"]
|
||||
status, _, data = self.cashier_a.get(f"/api/batches/{batch_id}/sheets")
|
||||
names = [s["sheet_name"] for s in as_json(data)["sheets"] if s["outcome"] == "parsed"]
|
||||
status, _, data = self.cashier_a.post_json(
|
||||
f"/api/batches/{batch_id}/confirm", {"sheets": names}
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
events = self.events(self.admin)
|
||||
single = next(e for e in events if e["status"] == "internal_single" and e["amount"] == "300.00")
|
||||
detail = self._admin_detail(single["event_id"])
|
||||
revision = detail["revision"]
|
||||
|
||||
# Company users cannot write manual decisions.
|
||||
status, _, data = self.cashier_a.post_json(
|
||||
f"/api/admin/transfer-events/{single['event_id']}/decisions",
|
||||
{"action": "reverse", "reason": "不应允许", "expected_revision": revision},
|
||||
)
|
||||
self.assertEqual(403, status, data)
|
||||
|
||||
# Admin confirms the single event based on evidence.
|
||||
status, _, data = self.admin.post_json(
|
||||
f"/api/admin/transfer-events/{single['event_id']}/decisions",
|
||||
{"action": "assign_participant", "reason": "函证确认",
|
||||
"expected_revision": revision, "request_key": "confirm-300",
|
||||
"participant": {"role": "payee", "company_id": self.company_b}},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
decision = as_json(data)["decision"]
|
||||
self.assertEqual("intercompany", decision["classification"])
|
||||
self.assertTrue(decision["locked"])
|
||||
|
||||
# Replaying the same request key is idempotent.
|
||||
status, _, data = self.admin.post_json(
|
||||
f"/api/admin/transfer-events/{single['event_id']}/decisions",
|
||||
{"action": "assign_participant", "reason": "函证确认",
|
||||
"expected_revision": revision, "request_key": "confirm-300",
|
||||
"participant": {"role": "payee", "company_id": self.company_b}},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
|
||||
# Stale revision conflicts.
|
||||
status, _, data = self.admin.post_json(
|
||||
f"/api/admin/transfer-events/{single['event_id']}/decisions",
|
||||
{"action": "reverse", "reason": "撤销", "expected_revision": revision},
|
||||
)
|
||||
self.assertEqual(409, status, data)
|
||||
|
||||
def _admin_detail(self, event_id: int) -> dict:
|
||||
status, _, data = self.admin.get(f"/api/admin/transfer-events/{event_id}")
|
||||
self.assertEqual(200, status, data)
|
||||
return as_json(data)["event"]
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Company scope and masking
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_company_sees_only_events_it_participates_in(self) -> None:
|
||||
events = self.company_events(self.cashier_a)
|
||||
self.assertTrue(events)
|
||||
for event in events:
|
||||
self.assertEqual(self.company_a, event["own_company_id"])
|
||||
matched = [e for e in events if e["status"] == "matched"]
|
||||
self.assertTrue(matched)
|
||||
self.assertEqual(
|
||||
{"乙公司"},
|
||||
{e["counterparty_company_name"] for e in matched},
|
||||
)
|
||||
# B<->C event is invisible to A.
|
||||
status, _, data = self.cashier_a.get("/api/company/transfer-events")
|
||||
bc_events = [
|
||||
e for e in as_json(data)["events"]
|
||||
if e["counterparty_company_name"] == "丙公司"
|
||||
]
|
||||
self.assertEqual([], bc_events)
|
||||
|
||||
def test_company_detail_masks_counterparty_and_own_rows_only(self) -> None:
|
||||
events = self.company_events(self.cashier_a)
|
||||
event = next(e for e in events if e["status"] == "matched")
|
||||
status, _, data = self.cashier_a.get(
|
||||
f"/api/company/transfer-events/{event['event_id']}"
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
detail = as_json(data)["event"]
|
||||
self.assertEqual("乙公司", detail["counterparty"]["company_name"])
|
||||
self.assertTrue(detail["counterparty"].get("account_number_masked", "").startswith("****"))
|
||||
# The counterparty's full account number never leaves the server.
|
||||
self.assertNotIn(ACCOUNT_B, json.dumps(detail, ensure_ascii=False))
|
||||
# Only A's own observation rows are exposed.
|
||||
self.assertEqual(1, len(detail["observations"]))
|
||||
observation = detail["observations"][0]
|
||||
self.assertTrue(observation["own_account_masked"].startswith("****"))
|
||||
self.assertEqual(self.company_a, observation.get("batch_company_id"))
|
||||
|
||||
def test_company_cannot_read_event_it_does_not_participate_in(self) -> None:
|
||||
# The B<->C event id comes from B's own list; A probing it returns 404.
|
||||
status, _, data = self.cashier_b.get("/api/company/transfer-events")
|
||||
bc_event_ids = [
|
||||
e["event_id"] for e in as_json(data)["events"]
|
||||
if e["counterparty_company_name"] == "丙公司"
|
||||
]
|
||||
self.assertTrue(bc_event_ids)
|
||||
for event_id in bc_event_ids:
|
||||
status, _, data = self.cashier_a.get(f"/api/company/transfer-events/{event_id}")
|
||||
self.assertEqual(404, status, data)
|
||||
status, _, data = self.cashier_a.get(f"/api/admin/transfer-events/{event_id}")
|
||||
self.assertEqual(403, status, data)
|
||||
|
||||
def test_company_match_exceptions_scoped_to_own_company(self) -> None:
|
||||
status, _, data = self.admin.post_multipart(
|
||||
"/api/parse", {"company_id": str(self.company_a)},
|
||||
"未决.xlsx",
|
||||
workbook_bytes([outgoing(ACCOUNT_A, "9999999999999999", "77.00", "2026-02-05 10:00:00")]),
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
batch_id = as_json(data)["batch_id"]
|
||||
status, _, data = self.cashier_a.get(f"/api/batches/{batch_id}/sheets")
|
||||
names = [s["sheet_name"] for s in as_json(data)["sheets"] if s["outcome"] == "parsed"]
|
||||
status, _, data = self.cashier_a.post_json(
|
||||
f"/api/batches/{batch_id}/confirm", {"sheets": names}
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
|
||||
status, _, data = self.cashier_a.get("/api/company/match-exceptions")
|
||||
self.assertEqual(200, status, data)
|
||||
mine = [e for e in as_json(data)["exceptions"] if e["amount"] == "77.00"]
|
||||
self.assertEqual(1, len(mine))
|
||||
self.assertEqual("unresolved", mine[0]["status"])
|
||||
|
||||
status, _, data = self.cashier_b.get("/api/company/match-exceptions")
|
||||
self.assertEqual(200, status, data)
|
||||
self.assertEqual(
|
||||
[],
|
||||
[e for e in as_json(data)["exceptions"] if e["amount"] == "77.00"],
|
||||
)
|
||||
|
||||
def test_company_forbidden_on_admin_event_endpoints(self) -> None:
|
||||
for call in (
|
||||
lambda: self.cashier_a.get("/api/admin/transfer-events"),
|
||||
lambda: self.cashier_a.get("/api/admin/match-exceptions"),
|
||||
lambda: self.cashier_a.post_json(
|
||||
"/api/admin/transfer-events/reconcile", {"batch_id": 1}
|
||||
),
|
||||
lambda: self.cashier_a.post_json(
|
||||
"/api/admin/personal-transit-mappings", {}
|
||||
),
|
||||
lambda: self.cashier_a.get("/api/admin/personal-transit-mappings"),
|
||||
):
|
||||
status, _, data = call()
|
||||
self.assertEqual(403, status, data)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Personal transit mappings
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_personal_transit_mapping_workflow(self) -> None:
|
||||
status, _, data = self.admin.post_json(
|
||||
"/api/admin/personal-transit-mappings",
|
||||
{"account_number": "880088008800", "account_name": "张个人",
|
||||
"represented_company_id": self.company_b,
|
||||
"allowed_direction": "incoming", "effective_from": "2026-01-01"},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
mapping_id = as_json(data)["mapping"]["id"]
|
||||
self.assertEqual("pending", as_json(data)["mapping"]["status"])
|
||||
|
||||
status, _, data = self.admin.post_json(
|
||||
f"/api/admin/personal-transit-mappings/{mapping_id}/review",
|
||||
{"decision": "approve", "reason": "资料齐全", "effective_from": "2026-01-01"},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
self.assertEqual("active", as_json(data)["mapping"]["status"])
|
||||
|
||||
status, _, data = self.admin.get("/api/admin/personal-transit-mappings")
|
||||
self.assertEqual(200, status, data)
|
||||
mappings = as_json(data)["mappings"]
|
||||
self.assertTrue(any(m["id"] == mapping_id for m in mappings))
|
||||
|
||||
# Duplicate account number conflicts.
|
||||
status, _, data = self.admin.post_json(
|
||||
"/api/admin/personal-transit-mappings",
|
||||
{"account_number": "880088008800", "account_name": "张个人",
|
||||
"represented_company_id": self.company_b, "allowed_direction": "both"},
|
||||
)
|
||||
self.assertEqual(409, status, data)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Upload account persistence
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_upload_persists_approved_bank_account(self) -> None:
|
||||
content = workbook_bytes([outgoing(ACCOUNT_A, ACCOUNT_B, "55.00", "2026-03-01 10:00:00")])
|
||||
status, _, data = self.cashier_a.post_multipart(
|
||||
"/api/parse", {"bank_account_id": str(self.account_a)},
|
||||
"带账户.xlsx", content,
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
batch_id = as_json(data)["batch_id"]
|
||||
connection = connect(self.db_path)
|
||||
try:
|
||||
row = connection.execute(
|
||||
"SELECT upload_bank_account_id FROM import_batches WHERE id = ?",
|
||||
(batch_id,),
|
||||
).fetchone()
|
||||
finally:
|
||||
connection.close()
|
||||
self.assertEqual(self.account_a, row["upload_bank_account_id"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+1
-67
@@ -1,19 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
import io
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from openpyxl import Workbook
|
||||
|
||||
from bank_importer.parser import (
|
||||
UnknownTemplateError,
|
||||
analyze_workbook,
|
||||
detect_header,
|
||||
parse_directory,
|
||||
)
|
||||
from bank_importer.parser import UnknownTemplateError, detect_header, parse_directory
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
@@ -92,62 +83,5 @@ class StatementParserTests(unittest.TestCase):
|
||||
self.assertIn("日期、金额、备注", message)
|
||||
|
||||
|
||||
class SheetResultTests(unittest.TestCase):
|
||||
"""Per-worksheet outcomes: parsed / exception / ignored with evidence."""
|
||||
|
||||
def setUp(self) -> None:
|
||||
self.temp_dir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp_dir.cleanup)
|
||||
|
||||
def _write(self, sheets) -> Path:
|
||||
workbook = Workbook()
|
||||
workbook.remove(workbook.active)
|
||||
for name, rows in sheets.items():
|
||||
worksheet = workbook.create_sheet(name)
|
||||
for row in rows:
|
||||
worksheet.append(row)
|
||||
path = Path(self.temp_dir.name) / "workbook.xlsx"
|
||||
workbook.save(path)
|
||||
return path
|
||||
|
||||
def test_every_sheet_has_an_independent_result(self) -> None:
|
||||
path = self._write(
|
||||
{
|
||||
"正常": [
|
||||
["客户账号", "账户名称", "交易时间", "借方发生额(支取)", "贷方发生额(收入)", "余额", "对方账号"],
|
||||
["6228480000000000", "测试", "2026-01-05 10:00:00", "100.00", "", "99900.00", "1002003004"],
|
||||
],
|
||||
"未知": [["日期", "金额", "备注"], ["2026-01-01", "100", "x"]],
|
||||
"空表": [],
|
||||
}
|
||||
)
|
||||
results = analyze_workbook(path)
|
||||
by_name = {result.sheet_name: result for result in results}
|
||||
self.assertEqual({"正常", "未知", "空表"}, set(by_name))
|
||||
self.assertEqual("parsed", by_name["正常"].outcome)
|
||||
self.assertIsNotNone(by_name["正常"].batch)
|
||||
self.assertEqual("exception", by_name["未知"].outcome)
|
||||
self.assertIn("未识别到受支持的银行表头", by_name["未知"].message)
|
||||
self.assertGreaterEqual(by_name["未知"].scanned_rows, 2)
|
||||
self.assertTrue(any("日期、金额、备注" in row for row in by_name["未知"].candidate_headers))
|
||||
self.assertEqual("ignored", by_name["空表"].outcome)
|
||||
self.assertEqual(0, by_name["空表"].scanned_rows)
|
||||
|
||||
def test_single_cell_rows_are_candidate_evidence(self) -> None:
|
||||
path = self._write({"候选": [["只有一个单元格"], ["又一格"]]})
|
||||
(result,) = analyze_workbook(path)
|
||||
self.assertEqual("exception", result.outcome)
|
||||
self.assertEqual(2, result.scanned_rows)
|
||||
self.assertTrue(result.candidate_headers)
|
||||
self.assertIn("只有一个单元格", ";".join(result.candidate_headers))
|
||||
|
||||
def test_messages_never_contain_stored_filename(self) -> None:
|
||||
path = self._write({"流水": [["日期", "金额", "备注"]]})
|
||||
(result,) = analyze_workbook(path)
|
||||
self.assertEqual("exception", result.outcome)
|
||||
self.assertNotIn(path.name, result.message)
|
||||
self.assertNotIn(str(path), result.message)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -1,234 +0,0 @@
|
||||
"""Monthly close, reopen approval, snapshot hash and locked-period writes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
from bank_importer import period_close
|
||||
from ledger_helpers import LedgerBase
|
||||
|
||||
|
||||
class PeriodCloseTests(LedgerBase):
|
||||
TODAY = date(2026, 8, 30)
|
||||
MONTH = "2026-07"
|
||||
|
||||
def _cover_month(self) -> None:
|
||||
self.add_row(
|
||||
self.company_a, own_account="6222000000000001",
|
||||
expense="100.00", at="2026-07-10T10:00:00",
|
||||
)
|
||||
self.add_row(
|
||||
self.company_b, own_account="6222000000000002",
|
||||
income="80.00", at="2026-07-12T10:00:00",
|
||||
)
|
||||
|
||||
def _close(self, month: str = MONTH):
|
||||
period_close.ensure_pending_tasks(self.connection, today=self.TODAY)
|
||||
return period_close.execute_close(
|
||||
self.connection, month, self.admin, confirm=True,
|
||||
)
|
||||
|
||||
def test_execute_requires_confirm_checkbox(self) -> None:
|
||||
self._cover_month()
|
||||
with self.assertRaises(period_close.PeriodCloseError) as ctx:
|
||||
period_close.execute_close(
|
||||
self.connection, self.MONTH, self.admin, confirm=False,
|
||||
)
|
||||
self.assertIn("勾选", str(ctx.exception))
|
||||
|
||||
def test_blockers_reject_close(self) -> None:
|
||||
period_close.ensure_pending_tasks(self.connection, today=self.TODAY)
|
||||
evaluation = period_close.evaluate_preconditions(self.connection, self.MONTH)
|
||||
self.assertFalse(evaluation["ready"])
|
||||
with self.assertRaises(period_close.PeriodCloseError):
|
||||
period_close.execute_close(
|
||||
self.connection, self.MONTH, self.admin, confirm=True,
|
||||
)
|
||||
|
||||
def test_close_snapshot_hash_stable_and_idempotent(self) -> None:
|
||||
self._cover_month()
|
||||
period_close.ensure_pending_tasks(self.connection, today=self.TODAY)
|
||||
before = period_close.build_snapshot(self.connection, self.MONTH)
|
||||
digest_before = hashlib.sha256(
|
||||
json.dumps(before, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
||||
).hexdigest()
|
||||
first = period_close.execute_close(
|
||||
self.connection, self.MONTH, self.admin, confirm=True,
|
||||
)
|
||||
self.assertEqual("closed", first["status"])
|
||||
self.assertTrue(first["report_no"].startswith("MR-202607-"))
|
||||
digest = first["snapshot_hash"]
|
||||
self.assertEqual(64, len(digest))
|
||||
self.assertEqual(digest_before, digest)
|
||||
run = self.connection.execute(
|
||||
"SELECT snapshot_json, snapshot_hash FROM period_close_runs WHERE year_month = ?",
|
||||
(self.MONTH,),
|
||||
).fetchone()
|
||||
self.assertEqual(digest, run["snapshot_hash"])
|
||||
self.assertEqual(
|
||||
digest,
|
||||
hashlib.sha256(run["snapshot_json"].encode("utf-8")).hexdigest(),
|
||||
)
|
||||
self.assertEqual(
|
||||
digest,
|
||||
hashlib.sha256(run["snapshot_json"].encode("utf-8")).hexdigest(),
|
||||
)
|
||||
with self.assertRaises(period_close.PeriodConflictError):
|
||||
period_close.execute_close(
|
||||
self.connection, self.MONTH, self.admin, confirm=True,
|
||||
)
|
||||
|
||||
def test_locked_month_rejects_writes(self) -> None:
|
||||
self._cover_month()
|
||||
self._close()
|
||||
with self.assertRaises(period_close.PeriodLockedError) as ctx:
|
||||
period_close.assert_date_writable(self.connection, "2026-07-15")
|
||||
self.assertIn("2026-07", str(ctx.exception))
|
||||
self.assertIn("已结账锁定", str(ctx.exception))
|
||||
period_close.assert_date_writable(self.connection, "2026-08-01")
|
||||
|
||||
def test_late_arrivals_do_not_rewrite_snapshot(self) -> None:
|
||||
self._cover_month()
|
||||
closed = self._close()
|
||||
digest = closed["snapshot_hash"]
|
||||
late_id = self.add_row(
|
||||
self.company_a, own_account="6222000000000001",
|
||||
expense="12.00", at="2026-07-28T11:00:00",
|
||||
)
|
||||
writable, locked = period_close.split_writable_row_ids(self.connection, [late_id])
|
||||
self.assertEqual([], writable)
|
||||
self.assertEqual([(late_id, "2026-07")], locked)
|
||||
n = period_close.record_late_arrivals(self.connection, locked, self.admin)
|
||||
self.assertEqual(1, n)
|
||||
again = period_close.close_payload(self.connection, self.MONTH)
|
||||
self.assertEqual(digest, again["snapshot_hash"])
|
||||
|
||||
def test_late_arrivals_survive_connection_close(self) -> None:
|
||||
"""Regression: the reconcile handler closes its connection right after
|
||||
recording locked rows; uncommitted inserts used to vanish silently."""
|
||||
from bank_importer.db import connect as db_connect
|
||||
|
||||
self._cover_month()
|
||||
self._close()
|
||||
late_id = self.add_row(
|
||||
self.company_a, own_account="6222000000000001",
|
||||
expense="12.00", at="2026-07-28T11:00:00",
|
||||
)
|
||||
writable, locked = period_close.split_writable_row_ids(self.connection, [late_id])
|
||||
self.assertEqual(1, period_close.record_late_arrivals(self.connection, locked, self.admin))
|
||||
self.connection.close()
|
||||
fresh = db_connect(self.db_path)
|
||||
try:
|
||||
rows = fresh.execute(
|
||||
"SELECT source_row_id FROM period_late_arrivals"
|
||||
).fetchall()
|
||||
audits = fresh.execute(
|
||||
"SELECT action FROM period_audit_events WHERE action = 'late_arrival'"
|
||||
).fetchall()
|
||||
finally:
|
||||
fresh.close()
|
||||
self.assertEqual([late_id], [r["source_row_id"] for r in rows])
|
||||
self.assertEqual(1, len(audits))
|
||||
|
||||
def test_snapshot_row_cannot_be_updated(self) -> None:
|
||||
self._cover_month()
|
||||
self._close()
|
||||
with self.assertRaises(Exception):
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
"UPDATE period_close_runs SET snapshot_json = '{}' WHERE year_month = ?",
|
||||
(self.MONTH,),
|
||||
)
|
||||
|
||||
def test_reopen_reject_then_approve_and_reclose_version_chain(self) -> None:
|
||||
self._cover_month()
|
||||
first = self._close()
|
||||
with self.assertRaises(period_close.PeriodCloseError):
|
||||
period_close.request_reopen(
|
||||
self.connection, self.MONTH, self.admin, reason="太短",
|
||||
)
|
||||
req = period_close.request_reopen(
|
||||
self.connection, self.MONTH, self.admin,
|
||||
reason="补录金牛煤业七月运输费并核对金额",
|
||||
companies_note="甲公司 ↔ 乙公司",
|
||||
window_days=3,
|
||||
)
|
||||
self.assertEqual("pending", req["status"])
|
||||
rejected = period_close.decide_reopen(
|
||||
self.connection, req["id"], self.admin, approve=False, comment="证据不足",
|
||||
)
|
||||
self.assertEqual("rejected", rejected["status"])
|
||||
self.assertTrue(period_close.is_month_locked(self.connection, self.MONTH))
|
||||
req2 = period_close.request_reopen(
|
||||
self.connection, self.MONTH, self.admin,
|
||||
reason="已补齐银行回单,申请重开更正科目",
|
||||
)
|
||||
approved = period_close.decide_reopen(
|
||||
self.connection, req2["id"], self.admin, approve=True, comment="同意",
|
||||
)
|
||||
self.assertEqual("approved", approved["status"])
|
||||
self.assertFalse(period_close.is_month_locked(self.connection, self.MONTH))
|
||||
period_close.assert_date_writable(self.connection, "2026-07-15")
|
||||
second = period_close.execute_close(
|
||||
self.connection, self.MONTH, self.admin, confirm=True,
|
||||
)
|
||||
self.assertEqual("closed", second["status"])
|
||||
self.assertNotEqual(first["report_no"], second["report_no"])
|
||||
versions = self.connection.execute(
|
||||
"SELECT version, report_no FROM period_close_runs WHERE year_month = ? ORDER BY version",
|
||||
(self.MONTH,),
|
||||
).fetchall()
|
||||
self.assertGreaterEqual(len(versions), 2)
|
||||
self.assertEqual(1, versions[0]["version"])
|
||||
self.assertEqual(2, versions[-1]["version"])
|
||||
|
||||
def test_close_and_reopen_request_survive_connection_close(self) -> None:
|
||||
"""HEL-282: monthly close / reopen request must persist with audit."""
|
||||
from bank_importer.db import connect as db_connect
|
||||
|
||||
self._cover_month()
|
||||
closed = self._close()
|
||||
req = period_close.request_reopen(
|
||||
self.connection, self.MONTH, self.admin,
|
||||
reason="补录金牛煤业七月运输费并核对金额",
|
||||
)
|
||||
report_no = closed["report_no"]
|
||||
request_id = req["id"]
|
||||
self.connection.close()
|
||||
fresh = db_connect(self.db_path)
|
||||
try:
|
||||
run = fresh.execute(
|
||||
"SELECT status, report_no FROM period_close_runs WHERE year_month = ?",
|
||||
(self.MONTH,),
|
||||
).fetchone()
|
||||
reopen = fresh.execute(
|
||||
"SELECT status FROM period_reopen_requests WHERE id = ?",
|
||||
(request_id,),
|
||||
).fetchone()
|
||||
actions = {
|
||||
row["action"]
|
||||
for row in fresh.execute(
|
||||
"SELECT action FROM period_audit_events"
|
||||
).fetchall()
|
||||
}
|
||||
finally:
|
||||
fresh.close()
|
||||
self.assertEqual("closed", run["status"])
|
||||
self.assertEqual(report_no, run["report_no"])
|
||||
self.assertEqual("pending", reopen["status"])
|
||||
self.assertTrue({"close_execute", "reopen_request"} <= actions)
|
||||
|
||||
def test_wal_on_file_database(self) -> None:
|
||||
mode = self.connection.execute("PRAGMA journal_mode").fetchone()[0]
|
||||
self.assertEqual("wal", str(mode).lower())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,101 +0,0 @@
|
||||
"""HEL-269: 月结面板、重开审批、审计记录页结构与三档宽度。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import unittest
|
||||
from functools import partial
|
||||
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
WEB = ROOT / "web"
|
||||
|
||||
try:
|
||||
from playwright.sync_api import sync_playwright
|
||||
except ImportError: # pragma: no cover
|
||||
sync_playwright = None
|
||||
|
||||
|
||||
class PeriodClosePageContractTests(unittest.TestCase):
|
||||
def test_admin_has_closing_reopen_and_audit_surfaces(self) -> None:
|
||||
html = (WEB / "admin.html").read_text(encoding="utf-8")
|
||||
self.assertIn('id="closingPanel"', html)
|
||||
self.assertIn('id="periodTimeline"', html)
|
||||
self.assertIn('data-page="period-audit"', html)
|
||||
self.assertIn('data-view="period-audit"', html)
|
||||
self.assertIn("重开审批", html)
|
||||
self.assertIn('id="reopenQueue"', html)
|
||||
self.assertIn('id="reopenRequestDialog"', html)
|
||||
self.assertIn('id="reopenDecideDialog"', html)
|
||||
self.assertIn("btn-warn", html)
|
||||
settings = html.index('data-view="settings"')
|
||||
audit_nav = html.index('data-view="period-audit"')
|
||||
reminders = html.index('data-view="reminders"')
|
||||
self.assertLess(settings, audit_nav)
|
||||
self.assertLess(audit_nav, reminders)
|
||||
css = (WEB / "design-system.css").read_text(encoding="utf-8")
|
||||
self.assertIn(".btn-warn", css)
|
||||
self.assertIn(".pill-lock", css)
|
||||
self.assertIn(".tl-cell.locked", css)
|
||||
self.assertIn(".diff-grid", css)
|
||||
self.assertIn(".empty-icon", css)
|
||||
js = (WEB / "app.js").read_text(encoding="utf-8")
|
||||
self.assertIn("/api/admin/period-closes", js)
|
||||
self.assertIn("/api/admin/period-reopens", js)
|
||||
self.assertIn("/api/admin/period-audit", js)
|
||||
self.assertIn("/api/flows", js)
|
||||
self.assertIn("/api/company/manual-records", js)
|
||||
|
||||
|
||||
def _chromium_available() -> bool:
|
||||
try:
|
||||
import ctypes.util
|
||||
return bool(ctypes.util.find_library("atk-1.0"))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
@unittest.skipUnless(sync_playwright, "playwright 未安装,跳过布局冒烟")
|
||||
@unittest.skipUnless(_chromium_available(), "系统缺少 chromium 依赖库(如 libatk),跳过布局冒烟")
|
||||
class PeriodCloseLayoutSmokeTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
handler = partial(SimpleHTTPRequestHandler, directory=str(WEB))
|
||||
cls.httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
cls.port = cls.httpd.server_address[1]
|
||||
cls.thread = threading.Thread(target=cls.httpd.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
cls.base = f"http://127.0.0.1:{cls.port}"
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls) -> None:
|
||||
cls.httpd.shutdown()
|
||||
cls.httpd.server_close()
|
||||
|
||||
def test_settings_and_audit_no_horizontal_overflow(self) -> None:
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch()
|
||||
page = browser.new_page()
|
||||
page.route("**/app.js**", lambda route: route.abort())
|
||||
for width in (360, 820, 1440):
|
||||
page.set_viewport_size({"width": width, "height": 900})
|
||||
page.goto(f"{self.base}/admin.html")
|
||||
for view in ("settings", "period-audit"):
|
||||
page.evaluate(
|
||||
"""(view) => {
|
||||
document.querySelectorAll('.app-view').forEach((el) => {
|
||||
el.classList.toggle('is-active', el.dataset.page === view);
|
||||
});
|
||||
}""",
|
||||
view,
|
||||
)
|
||||
overflow = page.evaluate(
|
||||
"() => document.documentElement.scrollWidth > document.documentElement.clientWidth + 1"
|
||||
)
|
||||
self.assertFalse(overflow, f"{width}px {view} 出现横向溢出")
|
||||
browser.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,558 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
import hashlib
|
||||
import sqlite3
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
from openpyxl import Workbook
|
||||
|
||||
from bank_importer.db import applied_versions, connect, migrate, rollback, utc_now
|
||||
from bank_importer.importing import import_statement
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SAMPLES = ROOT / "流水模板"
|
||||
SAMPLE_FILE = SAMPLES / "中国建设银行账户流水.xls"
|
||||
|
||||
|
||||
class PersistenceTestCase(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.temp_dir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp_dir.cleanup)
|
||||
root = Path(self.temp_dir.name)
|
||||
self.db_path = root / "app.db"
|
||||
self.storage = root / "files"
|
||||
self.connection = connect(self.db_path)
|
||||
self.addCleanup(self.connection.close)
|
||||
migrate(self.connection)
|
||||
|
||||
def import_sample(self) -> object:
|
||||
return import_statement(
|
||||
self.connection,
|
||||
self.storage,
|
||||
SAMPLE_FILE.name,
|
||||
SAMPLE_FILE.read_bytes(),
|
||||
)
|
||||
|
||||
|
||||
class MigrationTests(PersistenceTestCase):
|
||||
def test_migrate_creates_schema_and_is_idempotent(self) -> None:
|
||||
first = applied_versions(self.connection)
|
||||
self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], first)
|
||||
self.assertEqual([], migrate(self.connection))
|
||||
self.assertEqual(first, applied_versions(self.connection))
|
||||
tables = {
|
||||
row["name"]
|
||||
for row in self.connection.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type = 'table'"
|
||||
)
|
||||
}
|
||||
for table in (
|
||||
"companies",
|
||||
"bank_accounts",
|
||||
"account_aliases",
|
||||
"master_data_changes",
|
||||
"source_files",
|
||||
"import_batches",
|
||||
"sheet_batches",
|
||||
"sheet_reviews",
|
||||
"source_rows",
|
||||
"import_exceptions",
|
||||
"users",
|
||||
"sessions",
|
||||
"login_attempts",
|
||||
"audit_log",
|
||||
"personal_transit_mappings",
|
||||
"canonical_transfer_events",
|
||||
"transfer_match_decisions",
|
||||
"transfer_decision_observations",
|
||||
"transfer_decision_participants",
|
||||
"transfer_match_candidates",
|
||||
"current_transfer_decisions",
|
||||
"transfer_observation_claims",
|
||||
"manual_records",
|
||||
"manual_record_decisions",
|
||||
"current_manual_record_decisions",
|
||||
"ledger_events",
|
||||
"ledger_event_revisions",
|
||||
"current_ledger_event_revisions",
|
||||
"ledger_event_bank_sources",
|
||||
"ledger_event_manual_sources",
|
||||
"ledger_subject_suggestions",
|
||||
"system_settings",
|
||||
"system_setting_changes",
|
||||
"closed_periods",
|
||||
"opening_balance_revisions",
|
||||
"coverage_gaps",
|
||||
"no_business_attestations",
|
||||
"reminders_legacy_manual",
|
||||
"period_close_runs",
|
||||
"period_reopen_requests",
|
||||
"period_late_arrivals",
|
||||
"period_audit_events",
|
||||
"schema_migrations",
|
||||
):
|
||||
self.assertIn(table, tables)
|
||||
|
||||
def test_rollback_removes_schema_and_forward_rebuilds_it(self) -> None:
|
||||
self.assertEqual([11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], rollback(self.connection, 0))
|
||||
self.assertEqual([], applied_versions(self.connection))
|
||||
remaining = self.connection.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'source_rows'"
|
||||
).fetchone()
|
||||
self.assertIsNone(remaining)
|
||||
self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], migrate(self.connection))
|
||||
self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], applied_versions(self.connection))
|
||||
|
||||
def test_rollback_to_4_keeps_bank_evidence_and_drops_event_layer(self) -> None:
|
||||
self.import_sample()
|
||||
row_count = self.connection.execute(
|
||||
"SELECT COUNT(*) AS n FROM source_rows"
|
||||
).fetchone()["n"]
|
||||
self.assertGreater(row_count, 0)
|
||||
self.assertEqual([11, 10, 9, 8, 7, 6, 5], rollback(self.connection, 4))
|
||||
# The pre-migration evidence and schema are untouched.
|
||||
self.assertEqual(
|
||||
row_count,
|
||||
self.connection.execute("SELECT COUNT(*) AS n FROM source_rows").fetchone()["n"],
|
||||
)
|
||||
self.assertEqual(
|
||||
"parsed",
|
||||
self.connection.execute(
|
||||
"SELECT status FROM import_batches LIMIT 1"
|
||||
).fetchone()["status"],
|
||||
)
|
||||
remaining = self.connection.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'transfer_match_decisions'"
|
||||
).fetchone()
|
||||
self.assertIsNone(remaining)
|
||||
ledger_remaining = self.connection.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'ledger_event_revisions'"
|
||||
).fetchone()
|
||||
self.assertIsNone(ledger_remaining)
|
||||
|
||||
def test_event_layer_views_exist_after_migration(self) -> None:
|
||||
view = self.connection.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type = 'view' AND name = 'eligible_intercompany_events'"
|
||||
).fetchone()
|
||||
self.assertIsNotNone(view)
|
||||
|
||||
def test_ledger_layer_views_exist_after_migration(self) -> None:
|
||||
view = self.connection.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type = 'view' AND name = 'eligible_position_events'"
|
||||
).fetchone()
|
||||
self.assertIsNotNone(view)
|
||||
table = self.connection.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'ledger_event_revisions'"
|
||||
).fetchone()
|
||||
self.assertIsNotNone(table)
|
||||
|
||||
def test_ledger_revision_log_is_immutable(self) -> None:
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
"INSERT INTO companies (name, created_at, updated_at) VALUES ('甲公司', ?, ?)",
|
||||
(utc_now(), utc_now()),
|
||||
)
|
||||
self.connection.execute(
|
||||
"INSERT INTO companies (name, created_at, updated_at) VALUES ('乙公司', ?, ?)",
|
||||
(utc_now(), utc_now()),
|
||||
)
|
||||
company_a, company_b = [
|
||||
row["id"]
|
||||
for row in self.connection.execute("SELECT id FROM companies ORDER BY id")
|
||||
]
|
||||
self.connection.execute(
|
||||
"INSERT INTO ledger_events (lifecycle, created_at) VALUES ('active', ?)",
|
||||
(utc_now(),),
|
||||
)
|
||||
event_id = self.connection.execute(
|
||||
"SELECT id FROM ledger_events LIMIT 1"
|
||||
).fetchone()["id"]
|
||||
self.connection.execute(
|
||||
"""
|
||||
INSERT INTO ledger_event_revisions (
|
||||
ledger_event_id, revision, state, effective_at, amount,
|
||||
amount_scale, currency, payer_company_id, payee_company_id,
|
||||
source_kind, posting_kind, created_at
|
||||
) VALUES (?, 1, 'pending_subject', '2026-01-01T00:00:00', '1.00', 2,
|
||||
'CNY', ?, ?, 'bank', 'normal', ?)
|
||||
""",
|
||||
(event_id, company_a, company_b, utc_now()),
|
||||
)
|
||||
for statement in (
|
||||
"UPDATE ledger_event_revisions SET amount = '9.99'",
|
||||
"DELETE FROM ledger_event_revisions",
|
||||
"UPDATE ledger_events SET created_at = '2020-01-01T00:00:00'",
|
||||
"DELETE FROM ledger_events",
|
||||
):
|
||||
with self.subTest(statement=statement):
|
||||
with self.assertRaises(sqlite3.IntegrityError):
|
||||
self.connection.execute(statement)
|
||||
self.connection.rollback()
|
||||
|
||||
def test_manual_record_facts_are_immutable(self) -> None:
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
"INSERT INTO companies (name, created_at, updated_at) VALUES ('甲公司', ?, ?)",
|
||||
(utc_now(), utc_now()),
|
||||
)
|
||||
self.connection.execute(
|
||||
"INSERT INTO companies (name, created_at, updated_at) VALUES ('乙公司', ?, ?)",
|
||||
(utc_now(), utc_now()),
|
||||
)
|
||||
company_a, company_b = [
|
||||
row["id"]
|
||||
for row in self.connection.execute("SELECT id FROM companies ORDER BY id")
|
||||
]
|
||||
self.connection.execute(
|
||||
"""
|
||||
INSERT INTO manual_records (
|
||||
company_id, counterparty_company_id, occurred_at, direction,
|
||||
amount, amount_scale, currency, funding_source, requested_subject,
|
||||
request_key, created_at
|
||||
) VALUES (?, ?, '2026-01-01T00:00:00', 'incoming', '1.00', 2,
|
||||
'CNY', 'other', 'receivable', 'k1', ?)
|
||||
""",
|
||||
(company_a, company_b, utc_now()),
|
||||
)
|
||||
for statement in (
|
||||
"UPDATE manual_records SET amount = '9.99'",
|
||||
"DELETE FROM manual_records",
|
||||
):
|
||||
with self.subTest(statement=statement):
|
||||
with self.assertRaises(sqlite3.IntegrityError):
|
||||
self.connection.execute(statement)
|
||||
self.connection.rollback()
|
||||
|
||||
def test_decision_log_immutability_triggers(self) -> None:
|
||||
self.import_sample()
|
||||
source_row_id = self.connection.execute(
|
||||
"SELECT id FROM source_rows LIMIT 1"
|
||||
).fetchone()["id"]
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
"INSERT INTO canonical_transfer_events (lifecycle, created_at) VALUES ('active', ?)",
|
||||
(utc_now(),),
|
||||
)
|
||||
event_id = self.connection.execute(
|
||||
"SELECT id FROM canonical_transfer_events LIMIT 1"
|
||||
).fetchone()["id"]
|
||||
self.connection.execute(
|
||||
"""
|
||||
INSERT INTO transfer_match_decisions (
|
||||
event_id, revision, classification, pairing, mode, rule_version,
|
||||
locked, created_at
|
||||
) VALUES (?, 1, 'unresolved', 'not_applicable', 'auto', 'transfer-match-v1', 0, ?)
|
||||
""",
|
||||
(event_id, utc_now()),
|
||||
)
|
||||
decision_id = self.connection.execute(
|
||||
"SELECT id FROM transfer_match_decisions LIMIT 1"
|
||||
).fetchone()["id"]
|
||||
self.connection.execute(
|
||||
"""
|
||||
INSERT INTO transfer_match_candidates (
|
||||
decision_id, source_row_id, rule_tier, rule_version, created_at
|
||||
) VALUES (?, ?, 'R1', 'transfer-match-v1', ?)
|
||||
""",
|
||||
(decision_id, source_row_id, utc_now()),
|
||||
)
|
||||
for statement in (
|
||||
"UPDATE transfer_match_decisions SET classification = 'external'",
|
||||
"DELETE FROM transfer_match_decisions",
|
||||
"UPDATE transfer_match_candidates SET rule_tier = 'M1'",
|
||||
"DELETE FROM transfer_match_candidates",
|
||||
"DELETE FROM canonical_transfer_events",
|
||||
):
|
||||
with self.subTest(statement=statement):
|
||||
with self.assertRaises(sqlite3.IntegrityError):
|
||||
self.connection.execute(statement)
|
||||
self.connection.rollback()
|
||||
|
||||
def test_observation_claims_source_row_is_unique(self) -> None:
|
||||
self.import_sample()
|
||||
source_row_id = self.connection.execute(
|
||||
"SELECT id FROM source_rows LIMIT 1"
|
||||
).fetchone()["id"]
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
"INSERT INTO canonical_transfer_events (lifecycle, created_at) VALUES ('active', ?)",
|
||||
(utc_now(),),
|
||||
)
|
||||
event_id = self.connection.execute(
|
||||
"SELECT id FROM canonical_transfer_events LIMIT 1"
|
||||
).fetchone()["id"]
|
||||
self.connection.execute(
|
||||
"""
|
||||
INSERT INTO transfer_match_decisions (
|
||||
event_id, revision, classification, pairing, mode, locked, created_at
|
||||
) VALUES (?, 1, 'unresolved', 'not_applicable', 'auto', 0, ?)
|
||||
""",
|
||||
(event_id, utc_now()),
|
||||
)
|
||||
decision_id = self.connection.execute(
|
||||
"SELECT id FROM transfer_match_decisions LIMIT 1"
|
||||
).fetchone()["id"]
|
||||
self.connection.execute(
|
||||
"""
|
||||
INSERT INTO transfer_observation_claims (source_row_id, event_id, decision_id)
|
||||
VALUES (?, ?, ?)
|
||||
""",
|
||||
(source_row_id, event_id, decision_id),
|
||||
)
|
||||
with self.assertRaises(sqlite3.IntegrityError):
|
||||
self.connection.execute(
|
||||
"""
|
||||
INSERT INTO transfer_observation_claims (source_row_id, event_id, decision_id)
|
||||
VALUES (?, ?, ?)
|
||||
""",
|
||||
(source_row_id, event_id, decision_id),
|
||||
)
|
||||
self.connection.rollback()
|
||||
|
||||
|
||||
class ImportPersistenceTests(PersistenceTestCase):
|
||||
def test_import_persists_batch_sheets_and_rows(self) -> None:
|
||||
result = self.import_sample()
|
||||
self.assertEqual("parsed", result.status)
|
||||
|
||||
batch = self.connection.execute(
|
||||
"SELECT status FROM import_batches WHERE id = ?", (result.batch_id,)
|
||||
).fetchone()
|
||||
self.assertEqual("parsed", batch["status"])
|
||||
|
||||
sheets = self.connection.execute(
|
||||
"SELECT * FROM sheet_batches WHERE import_batch_id = ?", (result.batch_id,)
|
||||
).fetchall()
|
||||
self.assertEqual(1, len(sheets))
|
||||
self.assertEqual("中国建设银行", sheets[0]["bank_name"])
|
||||
self.assertEqual("ccb-account-detail-v1", sheets[0]["template_id"])
|
||||
self.assertEqual(1, sheets[0]["template_version"])
|
||||
|
||||
rows = self.connection.execute(
|
||||
"SELECT * FROM source_rows WHERE sheet_batch_id = ?", (sheets[0]["id"],)
|
||||
).fetchall()
|
||||
self.assertEqual(sheets[0]["transaction_count"], len(rows))
|
||||
|
||||
def test_amounts_keep_decimal_precision(self) -> None:
|
||||
result = self.import_sample()
|
||||
rows = self.connection.execute(
|
||||
"""
|
||||
SELECT income, expense FROM source_rows
|
||||
WHERE sheet_batch_id IN (
|
||||
SELECT id FROM sheet_batches WHERE import_batch_id = ?
|
||||
)
|
||||
""",
|
||||
(result.batch_id,),
|
||||
).fetchall()
|
||||
self.assertTrue(rows)
|
||||
for row in rows:
|
||||
self.assertEqual(row["income"], str(Decimal(row["income"])))
|
||||
self.assertEqual(row["expense"], str(Decimal(row["expense"])))
|
||||
|
||||
def test_every_row_traces_back_to_file_sheet_and_template(self) -> None:
|
||||
result = self.import_sample()
|
||||
row = self.connection.execute(
|
||||
"""
|
||||
SELECT r.source_row, s.sheet_name, s.template_id, s.template_version, f.sha256
|
||||
FROM source_rows r
|
||||
JOIN sheet_batches s ON s.id = r.sheet_batch_id
|
||||
JOIN import_batches b ON b.id = s.import_batch_id
|
||||
JOIN source_files f ON f.id = b.source_file_id
|
||||
WHERE b.id = ?
|
||||
LIMIT 1
|
||||
""",
|
||||
(result.batch_id,),
|
||||
).fetchone()
|
||||
self.assertIsNotNone(row)
|
||||
self.assertEqual(
|
||||
hashlib.sha256(SAMPLE_FILE.read_bytes()).hexdigest(), row["sha256"]
|
||||
)
|
||||
self.assertEqual("ccb-account-detail-v1", row["template_id"])
|
||||
self.assertEqual(1, row["template_version"])
|
||||
self.assertGreater(row["source_row"], 0)
|
||||
self.assertTrue(row["sheet_name"])
|
||||
|
||||
def test_source_file_is_stored_immutably_by_content_hash(self) -> None:
|
||||
self.import_sample()
|
||||
stored = self.connection.execute(
|
||||
"SELECT storage_path FROM source_files"
|
||||
).fetchone()
|
||||
stored_path = Path(stored["storage_path"])
|
||||
self.assertTrue(stored_path.is_file())
|
||||
self.assertEqual(SAMPLE_FILE.read_bytes(), stored_path.read_bytes())
|
||||
self.assertIn(hashlib.sha256(SAMPLE_FILE.read_bytes()).hexdigest(), stored_path.name)
|
||||
|
||||
def test_data_survives_reconnect(self) -> None:
|
||||
result = self.import_sample()
|
||||
self.connection.close()
|
||||
|
||||
reopened = connect(self.db_path)
|
||||
self.addCleanup(reopened.close)
|
||||
batch = reopened.execute(
|
||||
"SELECT status FROM import_batches WHERE id = ?", (result.batch_id,)
|
||||
).fetchone()
|
||||
self.assertEqual("parsed", batch["status"])
|
||||
files = reopened.execute("SELECT COUNT(*) AS n FROM source_files").fetchone()
|
||||
self.assertEqual(1, files["n"])
|
||||
rows = reopened.execute("SELECT COUNT(*) AS n FROM source_rows").fetchone()
|
||||
self.assertGreater(rows["n"], 0)
|
||||
|
||||
|
||||
class IdempotencyTests(PersistenceTestCase):
|
||||
def test_duplicate_upload_creates_no_second_facts(self) -> None:
|
||||
first = self.import_sample()
|
||||
second = self.import_sample()
|
||||
|
||||
self.assertEqual("parsed", first.status)
|
||||
self.assertEqual("duplicate", second.status)
|
||||
self.assertEqual(first.batch_id, second.batch_id)
|
||||
self.assertTrue(second.duplicate_same_company)
|
||||
|
||||
files = self.connection.execute("SELECT COUNT(*) AS n FROM source_files").fetchone()
|
||||
self.assertEqual(1, files["n"])
|
||||
sheets = self.connection.execute("SELECT COUNT(*) AS n FROM sheet_batches").fetchone()
|
||||
self.assertEqual(1, sheets["n"])
|
||||
rows = self.connection.execute("SELECT COUNT(*) AS n FROM source_rows").fetchone()
|
||||
self.assertEqual(first.batches[0].transactions.__len__(), rows["n"])
|
||||
|
||||
duplicate = self.connection.execute(
|
||||
"SELECT status, duplicate_of_id FROM import_batches WHERE status = 'duplicate'"
|
||||
).fetchone()
|
||||
self.assertEqual(first.batch_id, duplicate["duplicate_of_id"])
|
||||
|
||||
def test_cross_company_duplicate_never_returns_other_companys_batch(self) -> None:
|
||||
now = utc_now()
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
"INSERT INTO companies (name, created_at, updated_at) VALUES ('甲公司', ?, ?)",
|
||||
(now, now),
|
||||
)
|
||||
self.connection.execute(
|
||||
"INSERT INTO companies (name, created_at, updated_at) VALUES ('乙公司', ?, ?)",
|
||||
(now, now),
|
||||
)
|
||||
company_a, company_b = [
|
||||
row["id"]
|
||||
for row in self.connection.execute("SELECT id FROM companies ORDER BY id").fetchall()
|
||||
]
|
||||
|
||||
first = import_statement(
|
||||
self.connection, self.storage, SAMPLE_FILE.name,
|
||||
SAMPLE_FILE.read_bytes(), company_id=company_a,
|
||||
)
|
||||
self.assertEqual("parsed", first.status)
|
||||
|
||||
second = import_statement(
|
||||
self.connection, self.storage, SAMPLE_FILE.name,
|
||||
SAMPLE_FILE.read_bytes(), company_id=company_b,
|
||||
)
|
||||
self.assertEqual("duplicate", second.status)
|
||||
self.assertFalse(second.duplicate_same_company)
|
||||
# The returned batch id is the uploader's own duplicate batch, never
|
||||
# the other company's original batch.
|
||||
self.assertNotEqual(first.batch_id, second.batch_id)
|
||||
self.assertNotEqual(second.batch_id, first.batch_id)
|
||||
own = self.connection.execute(
|
||||
"SELECT company_id FROM import_batches WHERE id = ?", (second.batch_id,)
|
||||
).fetchone()
|
||||
self.assertEqual(company_b, own["company_id"])
|
||||
|
||||
def test_repeated_upload_under_a_different_filename_is_still_duplicate(self) -> None:
|
||||
first = self.import_sample()
|
||||
second = import_statement(
|
||||
self.connection,
|
||||
self.storage,
|
||||
"改名后的流水.xls",
|
||||
SAMPLE_FILE.read_bytes(),
|
||||
)
|
||||
self.assertEqual("duplicate", second.status)
|
||||
self.assertEqual(first.batch_id, second.batch_id)
|
||||
files = self.connection.execute("SELECT COUNT(*) AS n FROM source_files").fetchone()
|
||||
self.assertEqual(1, files["n"])
|
||||
|
||||
def test_immutability_triggers_block_updates_and_deletes(self) -> None:
|
||||
self.import_sample()
|
||||
for statement in (
|
||||
"UPDATE source_rows SET income = '0'",
|
||||
"DELETE FROM source_rows",
|
||||
"UPDATE source_files SET sha256 = 'x'",
|
||||
"DELETE FROM source_files",
|
||||
"UPDATE sheet_batches SET bank_name = 'x'",
|
||||
"DELETE FROM sheet_batches",
|
||||
):
|
||||
with self.subTest(statement=statement):
|
||||
with self.assertRaises(sqlite3.IntegrityError):
|
||||
self.connection.execute(statement)
|
||||
self.connection.rollback()
|
||||
|
||||
def test_row_level_unique_constraint_blocks_duplicate_rows(self) -> None:
|
||||
self.import_sample()
|
||||
row = self.connection.execute(
|
||||
"SELECT sheet_batch_id, source_row FROM source_rows LIMIT 1"
|
||||
).fetchone()
|
||||
with self.assertRaises(sqlite3.IntegrityError):
|
||||
self.connection.execute(
|
||||
"""
|
||||
INSERT INTO source_rows (
|
||||
sheet_batch_id, source_row, transaction_at, income, expense, created_at
|
||||
) VALUES (?, ?, '2026-01-01T00:00:00', '1', '0', '2026-01-01T00:00:00Z')
|
||||
""",
|
||||
(row["sheet_batch_id"], row["source_row"]),
|
||||
)
|
||||
self.connection.rollback()
|
||||
|
||||
|
||||
class FailedImportTests(PersistenceTestCase):
|
||||
def _unknown_template_bytes(self) -> bytes:
|
||||
workbook = Workbook()
|
||||
sheet = workbook.active
|
||||
sheet.title = "流水"
|
||||
sheet.append(["日期", "金额", "备注"])
|
||||
sheet.append(["2026-01-01", "100.00", "测试"])
|
||||
target = Path(self.temp_dir.name) / "unknown.xlsx"
|
||||
workbook.save(target)
|
||||
return target.read_bytes()
|
||||
|
||||
def test_parse_failure_keeps_exception_batch_without_rows(self) -> None:
|
||||
result = import_statement(
|
||||
self.connection, self.storage, "未知银行.xlsx", self._unknown_template_bytes()
|
||||
)
|
||||
self.assertEqual("exception", result.status)
|
||||
self.assertIsNotNone(result.message)
|
||||
self.assertIn("未知银行.xlsx", result.message)
|
||||
self.assertNotIn(result.sha256, result.message)
|
||||
|
||||
batch = self.connection.execute(
|
||||
"SELECT status FROM import_batches WHERE id = ?", (result.batch_id,)
|
||||
).fetchone()
|
||||
self.assertEqual("exception", batch["status"])
|
||||
|
||||
exceptions = self.connection.execute(
|
||||
"SELECT * FROM import_exceptions WHERE import_batch_id = ?",
|
||||
(result.batch_id,),
|
||||
).fetchall()
|
||||
self.assertEqual(1, len(exceptions))
|
||||
self.assertEqual("parse", exceptions[0]["stage"])
|
||||
|
||||
rows = self.connection.execute("SELECT COUNT(*) AS n FROM source_rows").fetchone()
|
||||
self.assertEqual(0, rows["n"])
|
||||
|
||||
# The source file is still preserved as evidence for later diagnosis.
|
||||
files = self.connection.execute("SELECT COUNT(*) AS n FROM source_files").fetchone()
|
||||
self.assertEqual(1, files["n"])
|
||||
|
||||
def test_reupload_after_failure_is_tracked_as_duplicate(self) -> None:
|
||||
content = self._unknown_template_bytes()
|
||||
first = import_statement(self.connection, self.storage, "未知银行.xlsx", content)
|
||||
second = import_statement(self.connection, self.storage, "未知银行.xlsx", content)
|
||||
self.assertEqual("exception", first.status)
|
||||
self.assertEqual("duplicate", second.status)
|
||||
self.assertEqual(first.batch_id, second.batch_id)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,135 +0,0 @@
|
||||
import hashlib
|
||||
from http.client import HTTPConnection
|
||||
from http.cookies import SimpleCookie
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from bank_importer import auth, portal_sso
|
||||
from bank_importer.db import connect, migrate, utc_now
|
||||
import server
|
||||
from test_server_auth import Client
|
||||
|
||||
|
||||
class PortalSsoTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.db_path = Path(self.temp.name) / 'app.db'
|
||||
self.db = connect(self.db_path)
|
||||
self.addCleanup(self.db.close)
|
||||
migrate(self.db)
|
||||
portal_sso.migrate(self.db)
|
||||
with self.db:
|
||||
self.db.execute('INSERT INTO companies(name,created_at,updated_at) VALUES (?,?,?)', ('测试公司甲', utc_now(), utc_now()))
|
||||
self.db.execute('INSERT INTO companies(name,created_at,updated_at) VALUES (?,?,?)', ('测试公司乙', utc_now(), utc_now()))
|
||||
self.uid = auth.create_user(self.db, 'staff-a', 'UnusedPass123', 'company', company_id=1)
|
||||
self.token = auth.create_session(self.db, self.uid)
|
||||
self.empid = '11111111-2222-3333-4444-555555555555'
|
||||
self.claims = {'active': True, 'identity': {'empid': self.empid, 'local_uid': self.uid}}
|
||||
self.env = patch.dict(os.environ, {'PORTAL_SSO_ENABLED': '1', 'PORTAL_PUBLIC_URL': 'http://portal.test'})
|
||||
self.env.start()
|
||||
self.addCleanup(self.env.stop)
|
||||
|
||||
def bind_session(self):
|
||||
with self.db:
|
||||
self.db.execute('INSERT INTO portal_sessions VALUES (?,?,?,?)',
|
||||
(hashlib.sha256(self.token.encode()).hexdigest(), 'a' * 64, self.empid, self.uid))
|
||||
|
||||
def test_native_session_does_not_bypass_portal(self):
|
||||
with patch.object(portal_sso, 'call') as call:
|
||||
self.assertIsNone(portal_sso.resolve(self.db, self.token))
|
||||
call.assert_not_called()
|
||||
|
||||
def test_native_role_and_company_are_retained(self):
|
||||
self.bind_session()
|
||||
with patch.object(portal_sso, 'call', return_value=self.claims):
|
||||
user = portal_sso.resolve(self.db, self.token)
|
||||
self.assertEqual('company', user['role'])
|
||||
self.assertEqual(1, user['company_id'])
|
||||
|
||||
def test_revocation_mismatch_and_local_disable_reject(self):
|
||||
self.bind_session()
|
||||
with patch.object(portal_sso, 'call', return_value={'active': False}):
|
||||
self.assertIsNone(portal_sso.resolve(self.db, self.token))
|
||||
self.assertIsNone(auth.resolve_session(self.db, self.token))
|
||||
|
||||
def test_portal_outage_does_not_fallback(self):
|
||||
self.bind_session()
|
||||
with patch.object(portal_sso, 'call', side_effect=TimeoutError):
|
||||
with self.assertRaises(TimeoutError):
|
||||
portal_sso.resolve(self.db, self.token)
|
||||
|
||||
def test_http_guards_company_scope_and_hidden_credentials(self):
|
||||
self.bind_session()
|
||||
class Quiet(server.AppHandler):
|
||||
def log_message(self, *args): pass
|
||||
with patch.object(server, 'DB_PATH', self.db_path), patch.object(portal_sso, 'call', return_value=self.claims):
|
||||
httpd = server.ThreadingHTTPServer(('127.0.0.1', 0), Quiet)
|
||||
thread = threading.Thread(target=httpd.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
client = Client('127.0.0.1', httpd.server_port)
|
||||
self.assertEqual(401, client.get('/api/company/accounts')[0])
|
||||
client.cookies[server.SESSION_COOKIE] = self.token
|
||||
self.assertEqual(200, client.get('/api/company/accounts?company_id=2')[0])
|
||||
self.assertEqual(403, client.get('/api/admin/companies')[0])
|
||||
status, _, data = client.get('/api/me')
|
||||
self.assertEqual(200, status)
|
||||
self.assertEqual(1, json.loads(data)['company_id'])
|
||||
for path in ['/api/login', '/api/logout', '/api/password/change', '/api/admin/users', '/api/admin/users/1/reset-password']:
|
||||
self.assertEqual(403, client.post_json(path, {})[0])
|
||||
status, _, data = client.get('/company.html')
|
||||
self.assertEqual(200, status)
|
||||
self.assertIn(b'data-return-portal', data)
|
||||
self.assertIn(b'display:none!important', data)
|
||||
self.assertEqual('http://portal.test', client.get('/login-company.html')[1]['location'])
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
thread.join()
|
||||
|
||||
def test_callback_checks_browser_proof_and_pins_local_identity(self):
|
||||
class Quiet(server.AppHandler):
|
||||
def log_message(self, *args): pass
|
||||
def response(operation, payload):
|
||||
if operation == 'exchange':
|
||||
self.assertEqual('a' * 64, payload['verifier'])
|
||||
return {'session_handle': 'b' * 64, 'identity': self.claims['identity']}
|
||||
return self.claims
|
||||
with patch.object(server, 'DB_PATH', self.db_path), patch.object(portal_sso, 'call', side_effect=response):
|
||||
httpd = server.ThreadingHTTPServer(('127.0.0.1', 0), Quiet)
|
||||
thread = threading.Thread(target=httpd.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
client = Client('127.0.0.1', httpd.server_port)
|
||||
status, headers, _ = client.get('/portal-sso?theme=night')
|
||||
self.assertEqual(303, status)
|
||||
self.assertIn('/api/sso/apps/finance/authorize?challenge=', headers['location'])
|
||||
client.cookies.clear()
|
||||
status, _, body = client.get('/portal-sso?ticket=' + 'c' * 64)
|
||||
self.assertEqual(401, status)
|
||||
self.assertIn(b'http://portal.test', body)
|
||||
conn = HTTPConnection('127.0.0.1', httpd.server_port)
|
||||
conn.request('GET', '/portal-sso?ticket=' + 'c' * 64,
|
||||
headers={'Cookie': 'cw_portal_proof=' + 'a' * 64 + '.night'})
|
||||
res = conn.getresponse()
|
||||
self.assertEqual(303, res.status)
|
||||
self.assertEqual('/company.html?theme=night', res.getheader('Location'))
|
||||
for key, value in res.getheaders():
|
||||
if key.lower() == 'set-cookie':
|
||||
cookies = SimpleCookie(value)
|
||||
if server.SESSION_COOKIE in cookies:
|
||||
client.cookies[server.SESSION_COOKIE] = cookies[server.SESSION_COOKIE].value
|
||||
res.read()
|
||||
conn.close()
|
||||
self.assertEqual(1, json.loads(client.get('/api/me')[2])['company_id'])
|
||||
self.assertEqual(self.empid, self.db.execute('SELECT empid FROM portal_identity WHERE uid=?', (self.uid,)).fetchone()['empid'])
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
thread.join()
|
||||
@@ -1,430 +0,0 @@
|
||||
"""B-44 position aggregation tests: conservation, repayments, reversals across
|
||||
cutoffs, currency isolation, Decimal precision, unresolved gross, normal
|
||||
balance exceptions and keyset pagination."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal, getcontext
|
||||
import unittest
|
||||
|
||||
from bank_importer import ledger_events, manual_records, positions, subjects
|
||||
from ledger_helpers import LedgerBase
|
||||
|
||||
|
||||
def confirm(connection, event_id: int, perspective: int, subject: str, key: str, actor):
|
||||
return subjects.confirm_subject(
|
||||
connection, event_id,
|
||||
perspective_company_id=perspective, subject_code=subject,
|
||||
reason="审核确认", expected_revision=1, request_key=key, actor=actor,
|
||||
)
|
||||
|
||||
|
||||
class ConservationTests(LedgerBase):
|
||||
def setUp(self) -> None:
|
||||
super().setUp()
|
||||
getcontext().prec = 50
|
||||
|
||||
def _confirm_all(self, subject: str = "other_receivable"):
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
for event in self.ledger_events():
|
||||
revision = self.current(event["id"])
|
||||
confirm(
|
||||
self.connection, event["id"],
|
||||
revision["payer_company_id"], subject, f"subj-{event['id']}",
|
||||
self.admin,
|
||||
)
|
||||
|
||||
def test_both_perspectives_mirror_exactly(self) -> None:
|
||||
self.pair(self.company_a, self.company_b, "100.00")
|
||||
self.pair(self.company_a, self.company_b, "30.00", at="2026-01-10T10:00:00")
|
||||
self.pair(self.company_a, self.company_b, "70.00", at="2026-02-05T10:00:00")
|
||||
self._confirm_all()
|
||||
pair = positions.pair_detail(
|
||||
self.connection, self.company_a, self.company_b,
|
||||
from_="2026-01-01", cutoff="2026-07-31",
|
||||
)
|
||||
item = pair["items"][0]
|
||||
self.assertTrue(item["conservation"]["opposite"])
|
||||
self.assertTrue(item["conservation"]["abs_equal"])
|
||||
self.assertEqual(Decimal("200.00"), Decimal(item["a"]["result"]["signed_amount"]))
|
||||
self.assertEqual(Decimal("-200.00"), Decimal(item["b"]["result"]["signed_amount"]))
|
||||
|
||||
def test_repayment_reduces_the_original_balance(self) -> None:
|
||||
# A lends B 100 (A pays) then B repays 40 (B pays).
|
||||
self.pair(self.company_a, self.company_b, "100.00")
|
||||
self.pair(self.company_b, self.company_a, "40.00", at="2026-03-01T10:00:00",
|
||||
summary="还款", purpose="归还借款")
|
||||
self._confirm_all()
|
||||
balances = positions.company_balances(
|
||||
self.connection, from_="2026-01-01", cutoff="2026-07-31"
|
||||
)
|
||||
for item in balances["items"]:
|
||||
if item["company_id"] == self.company_a:
|
||||
self.assertEqual(Decimal("60.00"), Decimal(item["result"]["signed_amount"]))
|
||||
self.assertEqual(Decimal("100.00"), Decimal(item["period"]["debit"]))
|
||||
self.assertEqual(Decimal("40.00"), Decimal(item["period"]["credit"]))
|
||||
else:
|
||||
self.assertEqual(Decimal("-60.00"), Decimal(item["result"]["signed_amount"]))
|
||||
self.assertEqual(Decimal("40.00"), Decimal(item["period"]["debit"]))
|
||||
self.assertEqual(Decimal("100.00"), Decimal(item["period"]["credit"]))
|
||||
|
||||
def test_over_repayment_flags_normal_balance_exception(self) -> None:
|
||||
# A lends B 100, then B repays 150 while A books the repayment against
|
||||
# its receivable: A's receivable and B's payable both go negative.
|
||||
self.pair(self.company_a, self.company_b, "100.00")
|
||||
self.pair(self.company_b, self.company_a, "150.00", at="2026-03-01T10:00:00",
|
||||
summary="还款", purpose="归还借款")
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
for event in self.ledger_events():
|
||||
revision = self.current(event["id"])
|
||||
# Book every event from A's perspective on the receivable side so
|
||||
# the over-repayment produces abnormal balances.
|
||||
confirm(
|
||||
self.connection, event["id"], self.company_a,
|
||||
"other_receivable", f"k-{event['id']}", self.admin,
|
||||
)
|
||||
pair = positions.pair_detail(
|
||||
self.connection, self.company_a, self.company_b,
|
||||
from_="2026-01-01", cutoff="2026-07-31",
|
||||
)
|
||||
item = pair["items"][0]
|
||||
self.assertTrue(item["normal_balance_exception"])
|
||||
self.assertIn("other_receivable", item["normal_balance_exception"])
|
||||
self.assertIn("other_payable", item["normal_balance_exception"])
|
||||
|
||||
|
||||
class CutoffAndReversalTests(LedgerBase):
|
||||
def _loan(self) -> int:
|
||||
self.pair(self.company_a, self.company_b, "100.00")
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
event_id = self.ledger_events()[0]["id"]
|
||||
confirm(self.connection, event_id, self.company_a, "other_receivable", "k1", self.admin)
|
||||
return event_id
|
||||
|
||||
def test_cutoff_before_reversal_keeps_original_impact(self) -> None:
|
||||
event_id = self._loan()
|
||||
# Reversal dated after the original event.
|
||||
ledger_events.create_reversal(
|
||||
self.connection, event_id, source_kind="adjustment",
|
||||
effective_at="2026-06-15T00:00:00", reason="冲销", actor=self.admin,
|
||||
)
|
||||
before = positions.company_balances(
|
||||
self.connection, from_="2026-01-01", cutoff="2026-05-31"
|
||||
)
|
||||
after = positions.company_balances(
|
||||
self.connection, from_="2026-01-01", cutoff="2026-07-31"
|
||||
)
|
||||
for item in before["items"]:
|
||||
if item["company_id"] == self.company_a:
|
||||
self.assertEqual(Decimal("100.00"), Decimal(item["result"]["signed_amount"]))
|
||||
for item in after["items"]:
|
||||
if item["company_id"] == self.company_a:
|
||||
self.assertEqual(Decimal("0"), Decimal(item["result"]["signed_amount"]))
|
||||
|
||||
def test_from_gt_cutoff_is_rejected(self) -> None:
|
||||
with self.assertRaises(positions.PositionInputError):
|
||||
positions.validate_window("2026-08-01", "2026-07-31")
|
||||
|
||||
def test_events_before_from_are_excluded_from_period(self) -> None:
|
||||
self._loan()
|
||||
balances = positions.company_balances(
|
||||
self.connection, from_="2026-06-01", cutoff="2026-07-31"
|
||||
)
|
||||
self.assertEqual([], balances["items"])
|
||||
|
||||
def test_reversal_uses_approved_effective_date(self) -> None:
|
||||
event_id = self._loan()
|
||||
ledger_events.create_reversal(
|
||||
self.connection, event_id, source_kind="adjustment",
|
||||
effective_at="2026-08-01T00:00:00", reason="未来冲销", actor=self.admin,
|
||||
)
|
||||
balances = positions.company_balances(
|
||||
self.connection, from_="2026-01-01", cutoff="2026-07-31"
|
||||
)
|
||||
for item in balances["items"]:
|
||||
if item["company_id"] == self.company_a:
|
||||
# The future reversal does not rewrite the earlier cutoff.
|
||||
self.assertEqual(Decimal("100.00"), Decimal(item["result"]["signed_amount"]))
|
||||
|
||||
|
||||
class CurrencyAndPrecisionTests(LedgerBase):
|
||||
def test_currencies_never_mix(self) -> None:
|
||||
self.pair(self.company_a, self.company_b, "100.00", currency="CNY")
|
||||
self.pair(self.company_a, self.company_b, "50.00", at="2026-01-20T10:00:00",
|
||||
currency="USD")
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
events = self.ledger_events()
|
||||
for event in events:
|
||||
revision = self.current(event["id"])
|
||||
confirm(self.connection, event["id"], revision["payer_company_id"],
|
||||
"other_receivable", f"k-{event['id']}", self.admin)
|
||||
balances = positions.company_balances(
|
||||
self.connection, from_="2026-01-01", cutoff="2026-07-31"
|
||||
)
|
||||
by_company = {}
|
||||
for item in balances["items"]:
|
||||
by_company.setdefault(item["company_id"], {})[item["currency"]] = item["result"]
|
||||
self.assertEqual(Decimal("100.00"), Decimal(by_company[self.company_a]["CNY"]["signed_amount"]))
|
||||
self.assertEqual(Decimal("50.00"), Decimal(by_company[self.company_a]["USD"]["signed_amount"]))
|
||||
|
||||
def test_decimal_precision_is_preserved(self) -> None:
|
||||
self.pair(self.company_a, self.company_b, "0.01")
|
||||
self.pair(self.company_a, self.company_b, "12345.6789", at="2026-01-11T10:00:00")
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
for event in self.ledger_events():
|
||||
revision = self.current(event["id"])
|
||||
confirm(self.connection, event["id"], revision["payer_company_id"],
|
||||
"other_receivable", f"k-{event['id']}", self.admin)
|
||||
balances = positions.company_balances(
|
||||
self.connection, from_="2026-01-01", cutoff="2026-07-31"
|
||||
)
|
||||
for item in balances["items"]:
|
||||
if item["company_id"] == self.company_a:
|
||||
self.assertEqual(
|
||||
Decimal("12345.6889"), Decimal(item["result"]["signed_amount"])
|
||||
)
|
||||
# The stored string keeps every decimal place.
|
||||
self.assertIn("12345.6889", item["result"]["signed_amount"])
|
||||
|
||||
def test_manual_record_preserves_amount_scale(self) -> None:
|
||||
record = manual_records.submit(
|
||||
self.connection, company_id=self.company_a,
|
||||
counterparty_company_id=self.company_b,
|
||||
occurred_at="2026-02-01T09:00:00", direction="incoming",
|
||||
amount="12.3400", currency="CNY", funding_source="other",
|
||||
requested_subject="receivable", request_key="mr-prec",
|
||||
actor=self.admin,
|
||||
)
|
||||
manual_records.decide(
|
||||
self.connection, record["id"], "approve_new",
|
||||
reason="确认", expected_decision_id=record["decision_id"],
|
||||
request_key="dec-prec", actor=self.admin,
|
||||
)
|
||||
stored = self.connection.execute(
|
||||
"SELECT amount, amount_scale FROM eligible_position_events"
|
||||
).fetchone()
|
||||
self.assertEqual("12.3400", stored["amount"])
|
||||
self.assertEqual(4, stored["amount_scale"])
|
||||
|
||||
|
||||
class UnresolvedTests(LedgerBase):
|
||||
def test_unresolved_gross_never_nets(self) -> None:
|
||||
# Two pending_subject events of opposite economic signs must sum their
|
||||
# absolute values, never cancel.
|
||||
self.pair(self.company_a, self.company_b, "100.00")
|
||||
self.pair(self.company_a, self.company_b, "40.00", at="2026-01-20T10:00:00",
|
||||
summary="还款", purpose="归还借款")
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
unresolved = positions.unresolved_for_company(
|
||||
self.connection, self.company_a, "2026-07-31"
|
||||
)
|
||||
self.assertEqual(2, unresolved["count"])
|
||||
self.assertEqual(
|
||||
Decimal("140.00"), Decimal(unresolved["gross_amount"])
|
||||
)
|
||||
self.assertEqual(
|
||||
Decimal("140.00"),
|
||||
Decimal(unresolved["by_reason"]["subject_review"]["gross_amount"]),
|
||||
)
|
||||
|
||||
def test_unmatched_single_reason_bucket(self) -> None:
|
||||
self.add_row(
|
||||
self.company_a, own_account="6222000000000001",
|
||||
cp_account="6222000000000002", expense="88.00",
|
||||
)
|
||||
from bank_importer import matching
|
||||
matching.reconcile_rows(self.connection, [1])
|
||||
unresolved = positions.unresolved_for_company(
|
||||
self.connection, self.company_a, "2026-07-31"
|
||||
)
|
||||
self.assertEqual(1, unresolved["count"])
|
||||
self.assertEqual(
|
||||
Decimal("88.00"),
|
||||
Decimal(unresolved["by_reason"]["unmatched_single"]["gross_amount"]),
|
||||
)
|
||||
|
||||
def test_pending_manual_only_counts_for_submitting_company(self) -> None:
|
||||
manual_records.submit(
|
||||
self.connection, company_id=self.company_a,
|
||||
counterparty_company_id=self.company_b,
|
||||
occurred_at="2026-01-10T09:00:00", direction="incoming",
|
||||
amount="50.00", currency="CNY", funding_source="other",
|
||||
requested_subject="receivable", request_key="mr-a",
|
||||
actor=self.admin,
|
||||
)
|
||||
a_unresolved = positions.unresolved_for_company(
|
||||
self.connection, self.company_a, "2026-07-31"
|
||||
)
|
||||
b_unresolved = positions.unresolved_for_company(
|
||||
self.connection, self.company_b, "2026-07-31"
|
||||
)
|
||||
self.assertEqual(1, a_unresolved["count"])
|
||||
self.assertEqual(
|
||||
Decimal("50.00"), Decimal(a_unresolved["by_reason"]["manual_pending"]["gross_amount"])
|
||||
)
|
||||
# The counterparty never sees the unapproved declaration.
|
||||
self.assertEqual(0, b_unresolved["count"])
|
||||
|
||||
|
||||
class PaginationTests(LedgerBase):
|
||||
def test_subject_filter_matches_stored_and_mirror_subjects(self) -> None:
|
||||
# A books "receivable" from its own perspective; B sees the mirror
|
||||
# "payable". Filtering by B's mirror subject must still find the event.
|
||||
self.pair(self.company_a, self.company_b, "100.00")
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
event_id = self.ledger_events()[0]["id"]
|
||||
confirm(self.connection, event_id, self.company_a, "receivable", "k-mirror",
|
||||
self.admin)
|
||||
|
||||
stored = positions.list_events(
|
||||
self.connection, from_="2026-01-01", cutoff="2026-07-31",
|
||||
subject="receivable",
|
||||
)
|
||||
self.assertTrue(any(
|
||||
item["ledger_event_id"] == event_id for item in stored["items"]
|
||||
))
|
||||
# Company B filters by its own perspective: the stored "receivable" is
|
||||
# the mirror of "payable", so it must be included.
|
||||
mirror = positions.list_events(
|
||||
self.connection, from_="2026-01-01", cutoff="2026-07-31",
|
||||
subject="payable", viewer_company_id=self.company_b,
|
||||
)
|
||||
self.assertTrue(any(
|
||||
item["ledger_event_id"] == event_id for item in mirror["items"]
|
||||
), mirror)
|
||||
for item in mirror["items"]:
|
||||
if item["ledger_event_id"] == event_id:
|
||||
self.assertEqual("payable", item["own_subject"])
|
||||
|
||||
def test_subject_filter_without_match_returns_empty(self) -> None:
|
||||
self.pair(self.company_a, self.company_b, "100.00")
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
event_id = self.ledger_events()[0]["id"]
|
||||
confirm(self.connection, event_id, self.company_a, "receivable", "k-none",
|
||||
self.admin)
|
||||
other = positions.list_events(
|
||||
self.connection, from_="2026-01-01", cutoff="2026-07-31",
|
||||
subject="other_receivable",
|
||||
)
|
||||
self.assertEqual([], other["items"])
|
||||
|
||||
def test_pagination_is_stable_and_complete(self) -> None:
|
||||
for index in range(7):
|
||||
at = f"2026-01-{(index % 28) + 1:02d}T10:00:00"
|
||||
self.pair(self.company_a, self.company_b, f"{index + 1}.00", at=at)
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
for event in self.ledger_events():
|
||||
revision = self.current(event["id"])
|
||||
confirm(self.connection, event["id"], revision["payer_company_id"],
|
||||
"other_receivable", f"k-{event['id']}", self.admin)
|
||||
|
||||
seen: list[int] = []
|
||||
cursor = None
|
||||
pages = 0
|
||||
while True:
|
||||
page = positions.list_events(
|
||||
self.connection, from_="2026-01-01", cutoff="2026-07-31",
|
||||
limit=3, cursor=cursor,
|
||||
)
|
||||
pages += 1
|
||||
seen.extend(item["ledger_event_id"] for item in page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if not page["has_more"]:
|
||||
break
|
||||
self.assertEqual(7, len(seen))
|
||||
self.assertEqual(len(set(seen)), len(seen))
|
||||
self.assertGreater(pages, 2)
|
||||
|
||||
def test_directory_pagination_complete(self) -> None:
|
||||
for index in range(6):
|
||||
at = f"2026-01-{(index % 28) + 1:02d}T10:00:00"
|
||||
self.pair(self.company_a, self.company_b, f"{index + 1}.00", at=at)
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
for event in self.ledger_events():
|
||||
revision = self.current(event["id"])
|
||||
confirm(self.connection, event["id"], revision["payer_company_id"],
|
||||
"other_receivable", f"k-{event['id']}", self.admin)
|
||||
seen: set[tuple[int, str]] = set()
|
||||
cursor = None
|
||||
while True:
|
||||
page = positions.company_balances(
|
||||
self.connection, from_="2026-01-01", cutoff="2026-07-31",
|
||||
limit=1, cursor=cursor,
|
||||
)
|
||||
seen.update((item["company_id"], item["currency"]) for item in page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if not page["has_more"]:
|
||||
break
|
||||
self.assertEqual(
|
||||
{(self.company_a, "CNY"), (self.company_b, "CNY")}, seen
|
||||
)
|
||||
|
||||
def test_event_payload_account_chip_and_repayment_flag(self) -> None:
|
||||
self.pair(
|
||||
self.company_a, self.company_b, "40.00",
|
||||
summary="归还往来款", purpose="还款",
|
||||
)
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
event_id = int(self.ledger_events()[0]["id"])
|
||||
detail = positions.event_detail(self.connection, event_id)
|
||||
event = detail["event"]
|
||||
self.assertEqual("visible", event["payer_account"]["visibility"])
|
||||
self.assertEqual("测试 0001", event["payer_account"]["label"])
|
||||
self.assertEqual("visible", event["payee_account"]["visibility"])
|
||||
self.assertEqual("测试 0002", event["payee_account"]["label"])
|
||||
self.assertEqual("归还往来款", event["summary"])
|
||||
self.assertTrue(event["is_repayment"])
|
||||
|
||||
company_view = positions.event_payload(
|
||||
self.connection,
|
||||
self.connection.execute(
|
||||
positions._DETAIL_SELECT + " WHERE p.ledger_event_id = ?",
|
||||
(event_id,),
|
||||
).fetchone(),
|
||||
viewer_company_id=self.company_a,
|
||||
)
|
||||
self.assertEqual("visible", company_view["payer_account"]["visibility"])
|
||||
self.assertEqual("masked", company_view["payee_account"]["visibility"])
|
||||
self.assertEqual("按对方授权不可见", company_view["payee_account"]["label"])
|
||||
|
||||
def test_park_subject_exception_hides_from_review_queue(self) -> None:
|
||||
self.pair(self.company_a, self.company_b, "100.00")
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
event_id = int(self.ledger_events()[0]["id"])
|
||||
current = self.current(event_id)
|
||||
subjects.park_subject(
|
||||
self.connection, event_id,
|
||||
disposition="exception", reason="转异常核查",
|
||||
expected_revision=current["id"], request_key="park-exc-1",
|
||||
actor=self.admin,
|
||||
)
|
||||
queue = positions.subject_review_queue(
|
||||
self.connection, from_="2026-01-01", cutoff="2026-07-31",
|
||||
)
|
||||
self.assertFalse(
|
||||
any(item["ledger_event_id"] == event_id for item in queue["items"])
|
||||
)
|
||||
revision = self.current(event_id)
|
||||
self.assertEqual("pending_subject", revision["state"])
|
||||
|
||||
def test_park_subject_return_stays_in_review_queue(self) -> None:
|
||||
self.pair(self.company_a, self.company_b, "80.00")
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
event_id = int(self.ledger_events()[0]["id"])
|
||||
current = self.current(event_id)
|
||||
subjects.park_subject(
|
||||
self.connection, event_id,
|
||||
disposition="return", reason="退回补充摘要",
|
||||
expected_revision=current["id"], request_key="park-ret-1",
|
||||
actor=self.admin,
|
||||
)
|
||||
queue = positions.subject_review_queue(
|
||||
self.connection, from_="2026-01-01", cutoff="2026-07-31",
|
||||
)
|
||||
self.assertTrue(
|
||||
any(item["ledger_event_id"] == event_id for item in queue["items"])
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,594 +0,0 @@
|
||||
"""HTTP integration tests for the B-44 intercompany position APIs.
|
||||
|
||||
Covers the admin balances/pair/events/evidence/subject-review/manual-record
|
||||
endpoints and the company-side scoped reads with masked evidence, plus
|
||||
cross-tenant 404s and company-forbidden admin writes. Every test method spins
|
||||
up its own server with a fresh database so subject confirmations and matched
|
||||
fixtures never leak across tests.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
|
||||
from openpyxl import Workbook
|
||||
|
||||
from bank_importer.db import connect, migrate
|
||||
|
||||
import server
|
||||
from test_server_auth import Client, as_json
|
||||
|
||||
BOOTSTRAP_PASSWORD = "BootAdmin123"
|
||||
ADMIN_PASSWORD = "AdminPass123"
|
||||
CASHIER_PASSWORD = "Cashier123"
|
||||
|
||||
CCB_HEADER = [
|
||||
"客户账号", "账户名称", "交易时间", "借方发生额(支取)", "贷方发生额(收入)",
|
||||
"余额", "币种", "对方户名", "对方账号", "对方开户机构", "摘要", "备注",
|
||||
]
|
||||
|
||||
ACCOUNT_A = "6222000000000001"
|
||||
ACCOUNT_B = "6222000000000002"
|
||||
|
||||
|
||||
def workbook_bytes(rows) -> bytes:
|
||||
workbook = Workbook()
|
||||
sheet = workbook.active
|
||||
sheet.title = "正常流水"
|
||||
sheet.append(CCB_HEADER)
|
||||
for row in rows:
|
||||
sheet.append(row)
|
||||
buffer = io.BytesIO()
|
||||
workbook.save(buffer)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def outgoing(own: str, cp: str, amount: str, at: str = "2026-01-05 10:00:00",
|
||||
currency: str = "RMB"):
|
||||
return [own, "测试公司", at, amount, "", "50000.00", currency, "对方", cp, "某银行", "借款", ""]
|
||||
|
||||
|
||||
def incoming(own: str, cp: str, amount: str, at: str = "2026-01-05 11:00:00",
|
||||
currency: str = "RMB"):
|
||||
return [own, "测试公司", at, "", amount, "50000.00", currency, "对方", cp, "某银行", "借款", ""]
|
||||
|
||||
|
||||
class IntercompanyApiTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.temp_dir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp_dir.cleanup)
|
||||
root = Path(self.temp_dir.name)
|
||||
self.db_path = root / "app.db"
|
||||
self.storage = root / "files"
|
||||
self.initial_passwords: dict[str, str] = {}
|
||||
|
||||
self._old_db_path = server.DB_PATH
|
||||
self._old_storage = server.STORAGE_DIR
|
||||
server.DB_PATH = self.db_path
|
||||
server.STORAGE_DIR = self.storage
|
||||
|
||||
os.environ["APP_BOOTSTRAP_ADMIN_PASSWORD"] = BOOTSTRAP_PASSWORD
|
||||
connection = connect(self.db_path)
|
||||
migrate(connection)
|
||||
assert server.ensure_bootstrap_admin(connection) is None
|
||||
connection.close()
|
||||
|
||||
class QuietHandler(server.AppHandler):
|
||||
def log_message(self, *args) -> None:
|
||||
pass
|
||||
|
||||
self.httpd = server.ThreadingHTTPServer(("127.0.0.1", 0), QuietHandler)
|
||||
self.port = self.httpd.server_address[1]
|
||||
self.thread = threading.Thread(target=self.httpd.serve_forever, daemon=True)
|
||||
self.thread.start()
|
||||
|
||||
self.admin = Client("127.0.0.1", self.port)
|
||||
status, _, data = self.admin.post_json(
|
||||
"/api/login",
|
||||
{"username": "group-admin", "password": BOOTSTRAP_PASSWORD, "portal": "admin"},
|
||||
)
|
||||
assert status == 200, data
|
||||
status, _, data = self.admin.post_json(
|
||||
"/api/password/change",
|
||||
{"old_password": BOOTSTRAP_PASSWORD, "new_password": ADMIN_PASSWORD},
|
||||
)
|
||||
assert status == 200, data
|
||||
|
||||
self.company_a = self._create_company("甲公司", "cashier-a")
|
||||
self.company_b = self._create_company("乙公司", "cashier-b")
|
||||
self.company_c = self._create_company("丙公司", "cashier-c")
|
||||
self.cashier_a = self._login_company("cashier-a", self.company_a)
|
||||
self.cashier_b = self._login_company("cashier-b", self.company_b)
|
||||
self.cashier_c = self._login_company("cashier-c", self.company_c)
|
||||
|
||||
self._approve_account(self.company_a, ACCOUNT_A)
|
||||
self._approve_account(self.company_b, ACCOUNT_B)
|
||||
|
||||
def tearDown(self) -> None:
|
||||
self.httpd.shutdown()
|
||||
self.httpd.server_close()
|
||||
server.DB_PATH = self._old_db_path
|
||||
server.STORAGE_DIR = self._old_storage
|
||||
os.environ.pop("APP_BOOTSTRAP_ADMIN_PASSWORD", None)
|
||||
|
||||
def _create_company(self, name: str, username: str) -> int:
|
||||
status, _, data = self.admin.post_json(
|
||||
"/api/admin/companies", {"name": name, "username": username}
|
||||
)
|
||||
assert status == 200, data
|
||||
self.initial_passwords.setdefault(username, as_json(data)["initial_password"])
|
||||
return as_json(data)["company_id"]
|
||||
|
||||
def _login_company(self, username: str, company_id: int) -> Client:
|
||||
client = Client("127.0.0.1", self.port)
|
||||
initial = self.initial_passwords[username]
|
||||
status, _, data = client.post_json(
|
||||
"/api/login", {"username": username, "password": initial, "portal": "company"}
|
||||
)
|
||||
assert status == 200, data
|
||||
status, _, data = client.post_json(
|
||||
"/api/password/change",
|
||||
{"old_password": initial, "new_password": CASHIER_PASSWORD},
|
||||
)
|
||||
assert status == 200, data
|
||||
return client
|
||||
|
||||
def _approve_account(self, company_id: int, number: str) -> None:
|
||||
client = {self.company_a: self.cashier_a, self.company_b: self.cashier_b}[company_id]
|
||||
status, _, data = client.post_json(
|
||||
"/api/company/accounts",
|
||||
{"bank_name": "中信银行", "account_type": "基本户",
|
||||
"account_number": number, "start_date": "2026-01-01"},
|
||||
)
|
||||
assert status == 200, data
|
||||
account_id = as_json(data)["account"]["id"]
|
||||
status, _, data = self.admin.post_json(
|
||||
f"/api/admin/accounts/{account_id}/review",
|
||||
{"decision": "approve", "reason": "测试启用", "effective_from": "2026-01-01"},
|
||||
)
|
||||
assert status == 200, data
|
||||
|
||||
def _upload_and_confirm(self, client, company_id: int, rows) -> int:
|
||||
content = workbook_bytes(rows)
|
||||
status, _, data = self.admin.post_multipart(
|
||||
"/api/parse", {"company_id": str(company_id)}, "账单.xlsx", content
|
||||
)
|
||||
assert status == 200, data
|
||||
batch_id = as_json(data)["batch_id"]
|
||||
status, _, data = client.get(f"/api/batches/{batch_id}/sheets")
|
||||
names = [s["sheet_name"] for s in as_json(data)["sheets"] if s["outcome"] == "parsed"]
|
||||
status, _, data = client.post_json(
|
||||
f"/api/batches/{batch_id}/confirm", {"sheets": names}
|
||||
)
|
||||
assert status == 200, data
|
||||
return batch_id
|
||||
|
||||
def _fresh_pair(self, amount: str = "100.00", at: str = "2026-01-05 10:00:00",
|
||||
currency: str = "RMB") -> dict:
|
||||
"""Upload+confirm a new A<->B pair; returns the pending review item."""
|
||||
self._upload_and_confirm(
|
||||
self.cashier_a, self.company_a,
|
||||
[outgoing(ACCOUNT_A, ACCOUNT_B, amount, at, currency)],
|
||||
)
|
||||
self._upload_and_confirm(
|
||||
self.cashier_b, self.company_b,
|
||||
[incoming(ACCOUNT_B, ACCOUNT_A, amount, at.replace("10:", "11:"), currency)],
|
||||
)
|
||||
status, _, data = self.admin.get(
|
||||
"/api/admin/subject-reviews?from=2026-01-01&cutoff=2026-12-31"
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
items = as_json(data)["items"]
|
||||
pending = [item for item in items if item["amount"] == amount]
|
||||
self.assertEqual(1, len(pending), data)
|
||||
return pending[0]
|
||||
|
||||
def _confirm(self, ledger_event_id: int) -> dict:
|
||||
status, _, data = self.admin.get(
|
||||
f"/api/admin/intercompany/events/{ledger_event_id}"
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
detail = as_json(data)
|
||||
status, _, data = self.admin.post_json(
|
||||
f"/api/admin/intercompany/events/{ledger_event_id}/subject-decisions",
|
||||
{
|
||||
"perspective_company_id": detail["event"]["payer_company_id"],
|
||||
"subject_code": "other_receivable",
|
||||
"reason": "借款确认其他应收",
|
||||
"expected_revision": detail["event"]["ledger_revision_id"],
|
||||
"request_key": f"subj-{ledger_event_id}",
|
||||
},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
return as_json(data)["revision"]
|
||||
|
||||
def balances(self, client=None, path="/api/admin/intercompany/balances") -> dict:
|
||||
client = client or self.admin
|
||||
status, _, data = client.get(path + "?from=2026-01-01&cutoff=2026-12-31")
|
||||
self.assertEqual(200, status, data)
|
||||
return as_json(data)
|
||||
|
||||
def _by_company(self, payload: dict, company_id: int) -> dict:
|
||||
return next(item for item in payload["items"] if item["company_id"] == company_id)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Admin balances / pair / events
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_admin_balances_directory(self) -> None:
|
||||
self._fresh_pair("100.00")
|
||||
payload = self.balances()
|
||||
self.assertEqual("2026-12-31", payload["window"]["cutoff"])
|
||||
companies = {item["company_id"] for item in payload["items"]}
|
||||
self.assertIn(self.company_a, companies)
|
||||
self.assertIn(self.company_b, companies)
|
||||
for item in payload["items"]:
|
||||
self.assertEqual("unavailable", item["opening"]["status"])
|
||||
self.assertIsNone(item["opening"]["amount"])
|
||||
self.assertEqual("period_net_change", item["result"]["kind"])
|
||||
self.assertIn("gross_amount", item["unresolved"])
|
||||
self.assertIn("count", item["unresolved"])
|
||||
self.assertIn("by_reason", item["unresolved"])
|
||||
self.assertEqual("RMB", item["currency"])
|
||||
|
||||
def test_admin_balances_pending_subject_shows_unresolved(self) -> None:
|
||||
self._fresh_pair("100.00")
|
||||
payload = self.balances()
|
||||
item = self._by_company(payload, self.company_a)
|
||||
self.assertEqual(1, item["unresolved"]["count"])
|
||||
self.assertEqual(
|
||||
"100.00", item["unresolved"]["by_reason"]["subject_review"]["gross_amount"]
|
||||
)
|
||||
self.assertEqual("0", item["period"]["debit"])
|
||||
self.assertEqual("0", item["period"]["credit"])
|
||||
|
||||
def test_admin_pair_detail_conserves(self) -> None:
|
||||
self._fresh_pair("100.00")
|
||||
status, _, data = self.admin.get(
|
||||
f"/api/admin/intercompany/pairs/{self.company_a}/{self.company_b}"
|
||||
"?from=2026-01-01&cutoff=2026-12-31"
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
payload = as_json(data)
|
||||
item = payload["items"][0]
|
||||
self.assertTrue(item["conservation"]["opposite"])
|
||||
self.assertTrue(item["conservation"]["abs_equal"])
|
||||
self.assertEqual("unavailable", item["opening"]["status"])
|
||||
self.assertIn("subjects", item)
|
||||
self.assertEqual(1, item["unresolved"]["count"])
|
||||
|
||||
def test_admin_subject_decision_flows_to_balances(self) -> None:
|
||||
pending = self._fresh_pair("100.00")
|
||||
revision = self._confirm(pending["ledger_event_id"])
|
||||
self.assertEqual("confirmed", revision["state"])
|
||||
self.assertEqual("other_receivable", revision["subject_code"])
|
||||
payload = self.balances()
|
||||
item = self._by_company(payload, self.company_a)
|
||||
self.assertEqual(0, item["unresolved"]["count"])
|
||||
self.assertEqual("100.00", item["period"]["debit"])
|
||||
self.assertEqual("100.00", item["result"]["signed_amount"])
|
||||
|
||||
def test_admin_subject_decision_stale_revision_conflicts(self) -> None:
|
||||
pending = self._fresh_pair("100.00")
|
||||
status, _, data = self.admin.post_json(
|
||||
f"/api/admin/intercompany/events/{pending['ledger_event_id']}/subject-decisions",
|
||||
{
|
||||
"perspective_company_id": pending["payer_company_id"],
|
||||
"subject_code": "other_receivable", "reason": "确认",
|
||||
"expected_revision": 999, "request_key": "stale-key",
|
||||
},
|
||||
)
|
||||
self.assertEqual(409, status, data)
|
||||
|
||||
def test_admin_events_list_and_evidence(self) -> None:
|
||||
pending = self._fresh_pair("100.00")
|
||||
revision = self._confirm(pending["ledger_event_id"])
|
||||
status, _, data = self.admin.get(
|
||||
"/api/admin/intercompany/events?from=2026-01-01&cutoff=2026-12-31"
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
items = as_json(data)["items"]
|
||||
self.assertTrue(items)
|
||||
event = next(
|
||||
item for item in items
|
||||
if item["ledger_event_id"] == revision["ledger_event_id"]
|
||||
)
|
||||
self.assertEqual("confirmed", event["state"])
|
||||
self.assertEqual("other_receivable", event["subject_code"])
|
||||
self.assertIn("payer_company_name", event)
|
||||
self.assertIn("amount", event)
|
||||
|
||||
status, _, data = self.admin.get(
|
||||
f"/api/admin/intercompany/events/{event['ledger_event_id']}"
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
self.assertEqual("confirmed", as_json(data)["state"])
|
||||
|
||||
status, _, data = self.admin.get(
|
||||
f"/api/admin/intercompany/events/{event['ledger_event_id']}/evidence"
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
blocks = as_json(data)["blocks"]
|
||||
self.assertTrue(blocks)
|
||||
for block in blocks:
|
||||
self.assertEqual("visible", block["visibility"])
|
||||
|
||||
def test_admin_events_list_includes_pending_subject(self) -> None:
|
||||
pending = self._fresh_pair("100.00")
|
||||
status, _, data = self.admin.get(
|
||||
"/api/admin/intercompany/events?from=2026-01-01&cutoff=2026-12-31"
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
items = as_json(data)["items"]
|
||||
item = next(
|
||||
item for item in items
|
||||
if item["ledger_event_id"] == pending["ledger_event_id"]
|
||||
)
|
||||
self.assertEqual("pending_subject", item["state"])
|
||||
self.assertIsNone(item["subject_code"])
|
||||
|
||||
def test_admin_manual_record_decision_via_api(self) -> None:
|
||||
status, _, data = self.cashier_a.post_json(
|
||||
"/api/company/manual-records",
|
||||
{
|
||||
"counterparty_company_id": self.company_b,
|
||||
"occurred_at": "2026-02-01T09:00:00",
|
||||
"direction": "incoming", "amount": "20.00", "currency": "CNY",
|
||||
"funding_source": "other", "requested_subject": "other_receivable",
|
||||
"request_key": "mr-api-1", "summary": "还款",
|
||||
},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
record = as_json(data)["record"]
|
||||
self.assertEqual("pending", record["state"])
|
||||
|
||||
status, _, data = self.admin.get("/api/admin/manual-records")
|
||||
self.assertEqual(200, status, data)
|
||||
records = as_json(data)["records"]
|
||||
self.assertTrue(any(item["id"] == record["id"] for item in records))
|
||||
|
||||
status, _, data = self.admin.post_json(
|
||||
f"/api/admin/manual-records/{record['id']}/decisions",
|
||||
{"action": "approve_new", "reason": "银行流水中无此事实",
|
||||
"expected_decision_id": record["decision_id"], "request_key": "dec-api-1"},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
self.assertEqual("approved", as_json(data)["decision"]["state"])
|
||||
|
||||
status, _, data = self.cashier_a.get("/api/company/manual-records")
|
||||
self.assertEqual(200, status, data)
|
||||
own = [item for item in as_json(data)["records"] if item["id"] == record["id"]]
|
||||
self.assertEqual(1, len(own))
|
||||
self.assertEqual("approved", own[0]["state"])
|
||||
|
||||
status, _, data = self.cashier_b.get("/api/company/manual-records")
|
||||
self.assertEqual(200, status, data)
|
||||
self.assertEqual([], [
|
||||
item for item in as_json(data)["records"] if item["id"] == record["id"]
|
||||
])
|
||||
|
||||
def test_admin_adjustment_reverse_via_api(self) -> None:
|
||||
pending = self._fresh_pair("100.00")
|
||||
revision = self._confirm(pending["ledger_event_id"])
|
||||
status, _, data = self.admin.post_json(
|
||||
f"/api/admin/intercompany/events/{revision['ledger_event_id']}/adjustments",
|
||||
{"action": "reverse", "reason": "科目误判,冲销"},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
self.assertEqual("reverse", as_json(data)["action"])
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Company scope and masking
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_company_balances_scoped_to_own_company(self) -> None:
|
||||
self._fresh_pair("100.00")
|
||||
status, _, data = self.cashier_a.get(
|
||||
"/api/company/intercompany/balances?from=2026-01-01&cutoff=2026-12-31"
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
payload = as_json(data)
|
||||
for item in payload["items"]:
|
||||
self.assertEqual(self.company_a, item["company_id"])
|
||||
self.assertIn("counterparties", payload)
|
||||
self.assertTrue(payload["counterparties"])
|
||||
|
||||
def test_company_pair_and_events_are_own_scope(self) -> None:
|
||||
self._fresh_pair("100.00")
|
||||
status, _, data = self.cashier_a.get(
|
||||
f"/api/company/intercompany/pairs/{self.company_b}"
|
||||
"?from=2026-01-01&cutoff=2026-12-31"
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
self.assertEqual(self.company_a, as_json(data)["companies"]["a"]["company_id"])
|
||||
|
||||
status, _, data = self.cashier_a.get(
|
||||
"/api/company/intercompany/events?from=2026-01-01&cutoff=2026-12-31"
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
items = as_json(data)["items"]
|
||||
self.assertTrue(items)
|
||||
for item in items:
|
||||
self.assertIn("direction", item)
|
||||
self.assertIn("own_subject_label", item)
|
||||
self.assertIn(item["direction"], ("incoming", "outgoing"))
|
||||
|
||||
def test_company_evidence_masks_counterparty_side(self) -> None:
|
||||
pending = self._fresh_pair("100.00")
|
||||
self._confirm(pending["ledger_event_id"])
|
||||
status, _, data = self.cashier_a.get(
|
||||
f"/api/company/intercompany/events/{pending['ledger_event_id']}/evidence"
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
blocks = as_json(data)["blocks"]
|
||||
visibilities = {block["visibility"] for block in blocks}
|
||||
self.assertTrue(visibilities & {"visible", "masked"})
|
||||
for block in blocks:
|
||||
if block["visibility"] == "masked":
|
||||
self.assertEqual("按对方授权不可见", block["fields"].get("note"))
|
||||
self.assertNotIn(ACCOUNT_B, json.dumps(block["fields"], ensure_ascii=False))
|
||||
|
||||
def test_company_cannot_read_or_write_admin_intercompany(self) -> None:
|
||||
self._fresh_pair("100.00")
|
||||
status, _, data = self.cashier_a.get("/api/admin/intercompany/balances")
|
||||
self.assertEqual(403, status, data)
|
||||
status, _, data = self.cashier_a.get("/api/admin/manual-records")
|
||||
self.assertEqual(403, status, data)
|
||||
status, _, data = self.cashier_a.post_json(
|
||||
"/api/admin/manual-records/1/decisions", {"action": "approve_new", "reason": "x"}
|
||||
)
|
||||
self.assertEqual(403, status, data)
|
||||
status, _, data = self.cashier_a.post_json(
|
||||
"/api/admin/intercompany/events/1/adjustments",
|
||||
{"action": "reverse", "reason": "越权"},
|
||||
)
|
||||
self.assertEqual(403, status, data)
|
||||
|
||||
def test_cross_company_reads_are_404(self) -> None:
|
||||
pending = self._fresh_pair("100.00")
|
||||
status, _, data = self.cashier_c.get(
|
||||
f"/api/company/intercompany/events/{pending['ledger_event_id']}"
|
||||
)
|
||||
self.assertEqual(404, status, data)
|
||||
status, _, data = self.cashier_c.get(
|
||||
f"/api/company/intercompany/events/{pending['ledger_event_id']}/evidence"
|
||||
)
|
||||
self.assertEqual(404, status, data)
|
||||
|
||||
def test_company_counterparty_summary_splits_by_currency(self) -> None:
|
||||
# A->B 100 CNY and A->B 50 USD must render two rows, never a mixed
|
||||
# "CNY 150.00" bucket.
|
||||
cny = self._fresh_pair("100.00", currency="CNY")
|
||||
usd = self._fresh_pair("50.00", at="2026-01-20 10:00:00", currency="USD")
|
||||
for pending in (cny, usd):
|
||||
self._confirm(pending["ledger_event_id"])
|
||||
|
||||
status, _, data = self.cashier_a.get(
|
||||
"/api/company/intercompany/balances?from=2026-01-01&cutoff=2026-12-31"
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
counterparties = as_json(data)["counterparties"]
|
||||
rows = [row for row in counterparties if row["counterparty_company_id"] == self.company_b]
|
||||
self.assertEqual(2, len(rows), counterparties)
|
||||
by_currency = {row["currency"]: row for row in rows}
|
||||
self.assertEqual({"CNY", "USD"}, set(by_currency))
|
||||
self.assertEqual("100.00", by_currency["CNY"]["result"]["signed_amount"])
|
||||
self.assertEqual("50.00", by_currency["USD"]["result"]["signed_amount"])
|
||||
for row in rows:
|
||||
self.assertNotEqual("150.00", row["result"]["signed_amount"])
|
||||
self.assertEqual(1, row["event_count"])
|
||||
|
||||
def test_company_events_subject_filter_matches_mirror(self) -> None:
|
||||
# A confirms subject "receivable" (stored from A's perspective); B must
|
||||
# still find the event when filtering by the mirror subject "payable".
|
||||
pending = self._fresh_pair("100.00")
|
||||
status, _, data = self.admin.post_json(
|
||||
f"/api/admin/intercompany/events/{pending['ledger_event_id']}/subject-decisions",
|
||||
{
|
||||
"perspective_company_id": self.company_a,
|
||||
"subject_code": "receivable", "reason": "确认应收",
|
||||
"expected_revision": 1, "request_key": "mirror-subj",
|
||||
},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
|
||||
status, _, data = self.cashier_b.get(
|
||||
"/api/company/intercompany/events?from=2026-01-01&cutoff=2026-12-31&subject=payable"
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
items = as_json(data)["items"]
|
||||
self.assertTrue(any(
|
||||
item["ledger_event_id"] == pending["ledger_event_id"] for item in items
|
||||
), data)
|
||||
|
||||
def test_manual_reverse_via_api_uses_explicit_effective_date(self) -> None:
|
||||
status, _, data = self.cashier_a.post_json(
|
||||
"/api/company/manual-records",
|
||||
{
|
||||
"counterparty_company_id": self.company_b,
|
||||
"occurred_at": "2026-02-01T09:00:00",
|
||||
"direction": "incoming", "amount": "20.00", "currency": "CNY",
|
||||
"funding_source": "other", "requested_subject": "other_receivable",
|
||||
"request_key": "mr-rev-api", "summary": "还款",
|
||||
},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
record = as_json(data)["record"]
|
||||
status, _, data = self.admin.post_json(
|
||||
f"/api/admin/manual-records/{record['id']}/decisions",
|
||||
{"action": "approve_new", "reason": "确认入账",
|
||||
"expected_decision_id": record["decision_id"], "request_key": "dec-rev-api"},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
event_id = as_json(data)["decision"]["ledger_event_id"]
|
||||
|
||||
status, _, data = self.admin.get(
|
||||
f"/api/admin/intercompany/events/{event_id}"
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
revision_id = as_json(data)["event"]["ledger_revision_id"]
|
||||
|
||||
status, _, data = self.admin.post_json(
|
||||
f"/api/admin/manual-records/{record['id']}/decisions",
|
||||
{"action": "reverse", "reason": "误录冲销", "effective_at": "2026-06-15",
|
||||
"expected_decision_id": None, "request_key": "dec-rev-api-2"},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
|
||||
status, _, data = self.admin.get(
|
||||
"/api/admin/intercompany/events?from=2026-01-01&cutoff=2026-12-31"
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
reversals = [item for item in as_json(data)["items"] if item["posting_kind"] == "reversal"]
|
||||
self.assertEqual(1, len(reversals))
|
||||
self.assertEqual("2026-06-15", reversals[0]["effective_at"][:10])
|
||||
self.assertEqual(event_id, reversals[0]["reverses_ledger_event_id"])
|
||||
|
||||
def test_admin_events_include_account_chips(self) -> None:
|
||||
pending = self._fresh_pair("100.00")
|
||||
revision = self._confirm(pending["ledger_event_id"])
|
||||
status, _, data = self.admin.get(
|
||||
"/api/admin/intercompany/events?from=2026-01-01&cutoff=2026-12-31"
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
event = next(
|
||||
item for item in as_json(data)["items"]
|
||||
if item["ledger_event_id"] == revision["ledger_event_id"]
|
||||
)
|
||||
self.assertIn("payer_account", event)
|
||||
self.assertIn("payee_account", event)
|
||||
self.assertEqual("visible", event["payer_account"]["visibility"])
|
||||
self.assertTrue(event["payer_account"]["label"])
|
||||
self.assertIn("summary", event)
|
||||
self.assertIn("is_repayment", event)
|
||||
|
||||
def test_subject_exception_drops_from_review_queue(self) -> None:
|
||||
pending = self._fresh_pair("77.00")
|
||||
status, _, data = self.admin.post_json(
|
||||
f"/api/admin/intercompany/events/{pending['ledger_event_id']}/subject-decisions",
|
||||
{
|
||||
"perspective_company_id": pending["payer_company_id"],
|
||||
"action": "exception",
|
||||
"reason": "转异常待核查",
|
||||
"expected_revision": pending["revision_id"],
|
||||
"request_key": "park-exc-api",
|
||||
},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
self.assertEqual("pending_subject", as_json(data)["revision"]["state"])
|
||||
status, _, data = self.admin.get(
|
||||
"/api/admin/subject-reviews?from=2026-01-01&cutoff=2026-12-31"
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
ids = [item["ledger_event_id"] for item in as_json(data)["items"]]
|
||||
self.assertNotIn(pending["ledger_event_id"], ids)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,495 +0,0 @@
|
||||
"""Tests for automatic reminder detection, delivery, isolation and audit trail."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
import json
|
||||
import sqlite3
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from bank_importer import auth, reminders
|
||||
from bank_importer.db import connect, migrate, utc_now
|
||||
|
||||
|
||||
class ReminderTestCase(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.connection = connect(":memory:")
|
||||
self.addCleanup(self.connection.close)
|
||||
migrate(self.connection)
|
||||
now = utc_now()
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
"INSERT INTO companies (name, created_at, updated_at) VALUES ('甲公司', ?, ?)",
|
||||
(now, now),
|
||||
)
|
||||
self.connection.execute(
|
||||
"INSERT INTO companies (name, created_at, updated_at) VALUES ('乙公司', ?, ?)",
|
||||
(now, now),
|
||||
)
|
||||
self.company_a = int(
|
||||
self.connection.execute("SELECT id FROM companies WHERE name = '甲公司'").fetchone()["id"]
|
||||
)
|
||||
self.company_b = int(
|
||||
self.connection.execute("SELECT id FROM companies WHERE name = '乙公司'").fetchone()["id"]
|
||||
)
|
||||
self.admin_id = auth.create_user(self.connection, "admin1", "AdminPass123", "admin")
|
||||
self.user_a = auth.create_user(
|
||||
self.connection, "cashier-a", "CashierA123", "company", company_id=self.company_a
|
||||
)
|
||||
self.user_b = auth.create_user(
|
||||
self.connection, "cashier-b", "CashierB123", "company", company_id=self.company_b
|
||||
)
|
||||
self.admin = self.connection.execute(
|
||||
"SELECT * FROM users WHERE id = ?", (self.admin_id,)
|
||||
).fetchone()
|
||||
self.actor_a = self.connection.execute(
|
||||
"SELECT * FROM users WHERE id = ?", (self.user_a,)
|
||||
).fetchone()
|
||||
|
||||
def _insert_batch(
|
||||
self,
|
||||
company_id: int,
|
||||
*,
|
||||
period_start: str,
|
||||
period_end: str,
|
||||
) -> None:
|
||||
now = utc_now()
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
"""
|
||||
INSERT INTO source_files (sha256, original_filename, size_bytes, storage_path, created_at)
|
||||
VALUES (?, 'f.xls', 1, '/tmp/f.xls', ?)
|
||||
""",
|
||||
(f"sha-{company_id}-{period_end}", now),
|
||||
)
|
||||
file_id = int(self.connection.execute("SELECT last_insert_rowid()").fetchone()[0])
|
||||
self.connection.execute(
|
||||
"""
|
||||
INSERT INTO import_batches (source_file_id, status, company_id, created_at, updated_at)
|
||||
VALUES (?, 'parsed', ?, ?, ?)
|
||||
""",
|
||||
(file_id, company_id, now, now),
|
||||
)
|
||||
batch_id = int(self.connection.execute("SELECT last_insert_rowid()").fetchone()[0])
|
||||
self.connection.execute(
|
||||
"""
|
||||
INSERT INTO sheet_batches (
|
||||
import_batch_id, sheet_name, bank_name, template_id, template_version,
|
||||
header_row, period_start, period_end, transaction_count, created_at
|
||||
) VALUES (?, 's1', '工行', 'tpl', 1, 1, ?, ?, 1, ?)
|
||||
""",
|
||||
(batch_id, period_start, period_end, now),
|
||||
)
|
||||
|
||||
def _insert_pending_account(self, company_id: int) -> None:
|
||||
now = utc_now()
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
"""
|
||||
INSERT INTO bank_accounts (
|
||||
company_id, account_number, bank_name, status, created_at, updated_at
|
||||
) VALUES (?, ?, '工行', 'pending', ?, ?)
|
||||
""",
|
||||
(company_id, f"622{company_id:012d}", now, now),
|
||||
)
|
||||
|
||||
|
||||
class RuleDetectionTests(ReminderTestCase):
|
||||
def test_unsubmitted_detected_when_no_current_month_batch(self) -> None:
|
||||
today = date.today()
|
||||
if today.day < 5:
|
||||
self.skipTest("monthly start day gate not reached today")
|
||||
findings = reminders.scan_findings(self.connection)
|
||||
keys = {item.company_id: item for item in findings if item.rule_key == reminders.RULE_UNSUBMITTED}
|
||||
self.assertIn(self.company_a, keys)
|
||||
self.assertIn(self.company_b, keys)
|
||||
|
||||
def test_unsubmitted_not_reported_when_batch_exists(self) -> None:
|
||||
today = date.today()
|
||||
if today.day < 5:
|
||||
self.skipTest("monthly start day gate not reached today")
|
||||
period = f"{today.year:04d}-{today.month:02d}"
|
||||
self._insert_batch(self.company_a, period_start=f"{period}-01", period_end=f"{period}-15")
|
||||
findings = reminders.scan_findings(self.connection)
|
||||
for item in findings:
|
||||
if item.rule_key == reminders.RULE_UNSUBMITTED:
|
||||
self.assertNotEqual(self.company_a, item.company_id)
|
||||
|
||||
def test_gap_detected_after_threshold(self) -> None:
|
||||
old_end = (date.today() - timedelta(days=10)).isoformat()
|
||||
self._insert_batch(self.company_a, period_start="2026-01-01", period_end=old_end)
|
||||
findings = reminders.scan_findings(self.connection)
|
||||
gap = [item for item in findings if item.rule_key == reminders.RULE_GAP and item.company_id == self.company_a]
|
||||
self.assertEqual(1, len(gap))
|
||||
|
||||
def test_gap_not_reported_for_recent_batch(self) -> None:
|
||||
recent = (date.today() - timedelta(days=1)).isoformat()
|
||||
self._insert_batch(self.company_a, period_start="2026-07-01", period_end=recent)
|
||||
findings = reminders.scan_findings(self.connection)
|
||||
gap = [item for item in findings if item.rule_key == reminders.RULE_GAP and item.company_id == self.company_a]
|
||||
self.assertEqual(0, len(gap))
|
||||
|
||||
def test_pending_review_detected_with_pending_account(self) -> None:
|
||||
self._insert_pending_account(self.company_a)
|
||||
findings = reminders.scan_findings(self.connection)
|
||||
pending = [
|
||||
item for item in findings
|
||||
if item.rule_key == reminders.RULE_PENDING and item.company_id == self.company_a
|
||||
]
|
||||
self.assertEqual(1, len(pending))
|
||||
self.assertGreater(pending[0].rule_params["pending_count"], 0)
|
||||
|
||||
def test_pending_review_not_reported_when_clean(self) -> None:
|
||||
findings = reminders.scan_findings(self.connection)
|
||||
pending = [
|
||||
item for item in findings
|
||||
if item.rule_key == reminders.RULE_PENDING and item.company_id == self.company_a
|
||||
]
|
||||
self.assertEqual(0, len(pending))
|
||||
|
||||
|
||||
class DeliveryAndDedupTests(ReminderTestCase):
|
||||
def test_send_creates_reminder_and_event(self) -> None:
|
||||
today = date.today()
|
||||
if today.day < 5:
|
||||
self.skipTest("monthly start day gate not reached today")
|
||||
findings = reminders.scan_findings(self.connection)
|
||||
self.assertTrue(findings)
|
||||
key = findings[0].dedupe_key
|
||||
reminder_id = reminders.deliver_finding(self.connection, key, actor=self.admin)
|
||||
self.assertIsNotNone(reminder_id)
|
||||
row = self.connection.execute(
|
||||
"SELECT send_count, status FROM reminders WHERE id = ?", (reminder_id,)
|
||||
).fetchone()
|
||||
self.assertEqual(1, row["send_count"])
|
||||
self.assertEqual("open", row["status"])
|
||||
events = self.connection.execute(
|
||||
"SELECT event_type FROM reminder_events WHERE reminder_id = ?", (reminder_id,)
|
||||
).fetchall()
|
||||
self.assertEqual(["sent"], [item["event_type"] for item in events])
|
||||
|
||||
def test_repeat_send_increments_count_without_new_row(self) -> None:
|
||||
today = date.today()
|
||||
if today.day < 5:
|
||||
self.skipTest("monthly start day gate not reached today")
|
||||
findings = reminders.scan_findings(self.connection)
|
||||
key = findings[0].dedupe_key
|
||||
first = reminders.deliver_finding(self.connection, key, actor=self.admin)
|
||||
second = reminders.deliver_finding(self.connection, key, actor=self.admin)
|
||||
self.assertEqual(first, second)
|
||||
row = self.connection.execute(
|
||||
"SELECT send_count FROM reminders WHERE dedupe_key = ?", (key,)
|
||||
).fetchone()
|
||||
self.assertEqual(2, row["send_count"])
|
||||
count = self.connection.execute("SELECT COUNT(*) FROM reminders WHERE dedupe_key = ?", (key,)).fetchone()[0]
|
||||
self.assertEqual(1, count)
|
||||
events = self.connection.execute(
|
||||
"SELECT COUNT(*) FROM reminder_events WHERE reminder_id = ?", (first,)
|
||||
).fetchone()[0]
|
||||
self.assertEqual(2, events)
|
||||
|
||||
def test_resolved_reminder_reopens_same_row(self) -> None:
|
||||
self._insert_pending_account(self.company_a)
|
||||
finding = next(
|
||||
item
|
||||
for item in reminders.scan_findings(self.connection)
|
||||
if item.rule_key == reminders.RULE_PENDING and item.company_id == self.company_a
|
||||
)
|
||||
first = reminders.deliver_finding(self.connection, finding.dedupe_key, actor=self.admin)
|
||||
self.assertIsNotNone(first)
|
||||
reminders.update_reminder_status(
|
||||
self.connection, first, "resolved", company_id=self.company_a, actor=self.actor_a
|
||||
)
|
||||
second = reminders.deliver_finding(self.connection, finding.dedupe_key, actor=self.admin)
|
||||
self.assertEqual(first, second)
|
||||
row = self.connection.execute(
|
||||
"SELECT send_count, status, dedupe_key FROM reminders WHERE id = ?",
|
||||
(first,),
|
||||
).fetchone()
|
||||
self.assertEqual(2, row["send_count"])
|
||||
self.assertEqual("open", row["status"])
|
||||
count = self.connection.execute(
|
||||
"SELECT COUNT(*) FROM reminders WHERE dedupe_key = ?", (finding.dedupe_key,)
|
||||
).fetchone()[0]
|
||||
self.assertEqual(1, count)
|
||||
events = [
|
||||
item["event_type"]
|
||||
for item in self.connection.execute(
|
||||
"SELECT event_type FROM reminder_events WHERE reminder_id = ? ORDER BY id",
|
||||
(first,),
|
||||
).fetchall()
|
||||
]
|
||||
self.assertEqual(["sent", "resolved", "sent"], events)
|
||||
|
||||
def test_deliver_many_continues_after_one_failure(self) -> None:
|
||||
self._insert_pending_account(self.company_a)
|
||||
finding = next(
|
||||
item
|
||||
for item in reminders.scan_findings(self.connection)
|
||||
if item.rule_key == reminders.RULE_PENDING and item.company_id == self.company_a
|
||||
)
|
||||
original = reminders.deliver_finding
|
||||
|
||||
def flaky(connection, key, **kwargs):
|
||||
if key == "boom":
|
||||
raise sqlite3.IntegrityError("UNIQUE constraint failed: reminders.dedupe_key")
|
||||
return original(connection, key, **kwargs)
|
||||
|
||||
with patch.object(reminders, "deliver_finding", side_effect=flaky):
|
||||
sent = reminders.deliver_many(
|
||||
self.connection, ["boom", finding.dedupe_key], actor=self.admin
|
||||
)
|
||||
self.assertEqual(1, len(sent))
|
||||
self.assertEqual(
|
||||
1,
|
||||
self.connection.execute("SELECT COUNT(*) FROM reminders").fetchone()[0],
|
||||
)
|
||||
|
||||
def test_manual_reminder_each_send_is_separate(self) -> None:
|
||||
first = reminders.send_manual(
|
||||
self.connection,
|
||||
company_id=self.company_a,
|
||||
display_type="其他",
|
||||
content="请尽快处理",
|
||||
deadline="2026-09-01",
|
||||
actor=self.admin,
|
||||
)
|
||||
second = reminders.send_manual(
|
||||
self.connection,
|
||||
company_id=self.company_a,
|
||||
display_type="其他",
|
||||
content="再次提醒",
|
||||
deadline=None,
|
||||
actor=self.admin,
|
||||
)
|
||||
self.assertNotEqual(first, second)
|
||||
|
||||
|
||||
class IsolationTests(ReminderTestCase):
|
||||
def setUp(self) -> None:
|
||||
super().setUp()
|
||||
reminders.send_manual(
|
||||
self.connection,
|
||||
company_id=self.company_a,
|
||||
display_type="流水未提交",
|
||||
content="甲公司专属",
|
||||
deadline=None,
|
||||
actor=self.admin,
|
||||
)
|
||||
reminders.send_manual(
|
||||
self.connection,
|
||||
company_id=self.company_b,
|
||||
display_type="流水未提交",
|
||||
content="乙公司专属",
|
||||
deadline=None,
|
||||
actor=self.admin,
|
||||
)
|
||||
|
||||
def test_company_sees_only_own_reminders(self) -> None:
|
||||
items_a = reminders.list_company_reminders(self.connection, self.company_a)
|
||||
items_b = reminders.list_company_reminders(self.connection, self.company_b)
|
||||
self.assertEqual(1, len(items_a))
|
||||
self.assertEqual(1, len(items_b))
|
||||
self.assertIn("甲公司", items_a[0]["title"])
|
||||
self.assertIn("乙公司", items_b[0]["title"])
|
||||
|
||||
def test_company_cannot_update_other_company_reminder(self) -> None:
|
||||
other_id = reminders.list_company_reminders(self.connection, self.company_b)[0]["id"]
|
||||
ok = reminders.update_reminder_status(
|
||||
self.connection, other_id, "acknowledged", company_id=self.company_a, actor=self.actor_a
|
||||
)
|
||||
self.assertFalse(ok)
|
||||
|
||||
|
||||
class AuditTrailTests(ReminderTestCase):
|
||||
def test_scan_writes_audit_log(self) -> None:
|
||||
reminders.run_scan(self.connection, actor=self.admin, ip="127.0.0.1")
|
||||
row = self.connection.execute(
|
||||
"SELECT action, detail FROM audit_log WHERE action = 'reminder_scan'"
|
||||
).fetchone()
|
||||
self.assertIsNotNone(row)
|
||||
detail = json.loads(row["detail"])
|
||||
self.assertIn("total", detail)
|
||||
|
||||
def test_events_are_append_only(self) -> None:
|
||||
reminder_id = reminders.send_manual(
|
||||
self.connection,
|
||||
company_id=self.company_a,
|
||||
display_type="测试",
|
||||
content="内容",
|
||||
deadline=None,
|
||||
actor=self.admin,
|
||||
)
|
||||
with self.assertRaises(Exception):
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
"UPDATE reminder_events SET detail = 'tampered' WHERE reminder_id = ?",
|
||||
(reminder_id,),
|
||||
)
|
||||
with self.assertRaises(Exception):
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
"DELETE FROM reminder_events WHERE reminder_id = ?", (reminder_id,)
|
||||
)
|
||||
|
||||
def test_reminders_cannot_be_deleted(self) -> None:
|
||||
reminder_id = reminders.send_manual(
|
||||
self.connection,
|
||||
company_id=self.company_a,
|
||||
display_type="测试",
|
||||
content="内容",
|
||||
deadline=None,
|
||||
actor=self.admin,
|
||||
)
|
||||
with self.assertRaises(Exception):
|
||||
with self.connection:
|
||||
self.connection.execute("DELETE FROM reminders WHERE id = ?", (reminder_id,))
|
||||
|
||||
|
||||
class StatusFlowTests(ReminderTestCase):
|
||||
def test_acknowledge_and_resolve(self) -> None:
|
||||
reminder_id = reminders.send_manual(
|
||||
self.connection,
|
||||
company_id=self.company_a,
|
||||
display_type="待确认",
|
||||
content="请处理",
|
||||
deadline=None,
|
||||
actor=self.admin,
|
||||
)
|
||||
ok = reminders.update_reminder_status(
|
||||
self.connection, reminder_id, "acknowledged", company_id=self.company_a, actor=self.actor_a
|
||||
)
|
||||
self.assertTrue(ok)
|
||||
row = self.connection.execute(
|
||||
"SELECT status FROM reminders WHERE id = ?", (reminder_id,)
|
||||
).fetchone()
|
||||
self.assertEqual("acknowledged", row["status"])
|
||||
ok = reminders.update_reminder_status(
|
||||
self.connection, reminder_id, "resolved", company_id=self.company_a, actor=self.actor_a
|
||||
)
|
||||
self.assertTrue(ok)
|
||||
events = self.connection.execute(
|
||||
"SELECT event_type FROM reminder_events WHERE reminder_id = ? ORDER BY id",
|
||||
(reminder_id,),
|
||||
).fetchall()
|
||||
self.assertEqual(
|
||||
["sent", "acknowledged", "resolved"],
|
||||
[item["event_type"] for item in events],
|
||||
)
|
||||
|
||||
|
||||
class SettingsTests(ReminderTestCase):
|
||||
def test_default_settings_and_update(self) -> None:
|
||||
settings = reminders.get_settings(self.connection)
|
||||
self.assertEqual("5", settings["monthly_start_day"])
|
||||
self.assertEqual("5", settings["gap_days"])
|
||||
updated = reminders.update_settings(
|
||||
self.connection, {"gap_days": "7", "monthly_start_day": "6"}
|
||||
)
|
||||
self.assertEqual("7", updated["gap_days"])
|
||||
self.assertEqual("6", updated["monthly_start_day"])
|
||||
|
||||
def test_unknown_setting_rejected(self) -> None:
|
||||
with self.assertRaises(ValueError):
|
||||
reminders.update_settings(self.connection, {"unknown_key": "1"})
|
||||
|
||||
def test_invalid_monthly_start_day_rejected(self) -> None:
|
||||
with self.assertRaises(ValueError):
|
||||
reminders.update_settings(self.connection, {"monthly_start_day": "0"})
|
||||
with self.assertRaises(ValueError):
|
||||
reminders.update_settings(self.connection, {"monthly_start_day": "29"})
|
||||
self.assertEqual("5", reminders.get_settings(self.connection)["monthly_start_day"])
|
||||
|
||||
def test_invalid_gap_days_rejected(self) -> None:
|
||||
with self.assertRaises(ValueError):
|
||||
reminders.update_settings(self.connection, {"gap_days": "0"})
|
||||
with self.assertRaises(ValueError):
|
||||
reminders.update_settings(self.connection, {"gap_days": "abc"})
|
||||
self.assertEqual("5", reminders.get_settings(self.connection)["gap_days"])
|
||||
|
||||
def test_invalid_scan_time_rejected(self) -> None:
|
||||
with self.assertRaises(ValueError):
|
||||
reminders.update_settings(self.connection, {"scan_time": "25:00"})
|
||||
with self.assertRaises(ValueError):
|
||||
reminders.update_settings(self.connection, {"scan_time": "8:0"})
|
||||
self.assertEqual("08:00", reminders.get_settings(self.connection)["scan_time"])
|
||||
|
||||
def test_corrupt_settings_do_not_break_scan(self) -> None:
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
"UPDATE reminder_settings SET value = 'not-a-number' WHERE key = 'monthly_start_day'"
|
||||
)
|
||||
self.connection.execute(
|
||||
"UPDATE reminder_settings SET value = '0' WHERE key = 'gap_days'"
|
||||
)
|
||||
findings = reminders.scan_findings(self.connection)
|
||||
self.assertIsInstance(findings, list)
|
||||
|
||||
|
||||
class NoticeListDelegationTests(unittest.TestCase):
|
||||
def test_async_notice_go_handle_uses_event_delegation(self) -> None:
|
||||
source = (Path(__file__).resolve().parents[1] / "web" / "app.js").read_text(
|
||||
encoding="utf-8"
|
||||
)
|
||||
init_body = source.split("function initNotifications()", 1)[1].split("\nfunction ", 1)[0]
|
||||
self.assertIn('list.addEventListener("click"', init_body)
|
||||
self.assertIn('closest("[data-view-link]")', init_body)
|
||||
self.assertIn("showView(viewLink.dataset.viewLink)", init_body)
|
||||
self.assertIn('document.addEventListener("click"', source)
|
||||
self.assertNotIn(
|
||||
'$$("[data-view-link]").forEach((button) => button.addEventListener("click"',
|
||||
source,
|
||||
)
|
||||
|
||||
def test_delegated_lookup_finds_button_inserted_after_init(self) -> None:
|
||||
"""Simulate #notice-list after async replaceChildren: click target is the new button."""
|
||||
list_root = {"id": "notice-list", "parent": None, "attrs": {}}
|
||||
side = {"id": "lr-side", "parent": list_root, "attrs": {}}
|
||||
button = {
|
||||
"id": "go",
|
||||
"parent": side,
|
||||
"attrs": {"data-view-link": "reconcile"},
|
||||
}
|
||||
list_root["children"] = [side]
|
||||
side["children"] = [button]
|
||||
|
||||
def closest(node, attr):
|
||||
current = node
|
||||
while current is not None:
|
||||
if attr in current.get("attrs", {}):
|
||||
return current
|
||||
current = current.get("parent")
|
||||
return None
|
||||
|
||||
clicked = closest(button, "data-view-link")
|
||||
self.assertIsNotNone(clicked)
|
||||
self.assertEqual("reconcile", clicked["attrs"]["data-view-link"])
|
||||
self.assertIs(list_root, clicked["parent"]["parent"])
|
||||
|
||||
|
||||
class MigrationTests(unittest.TestCase):
|
||||
def test_v6_migration_applies_and_rolls_back(self) -> None:
|
||||
connection = connect(":memory:")
|
||||
self.addCleanup(connection.close)
|
||||
migrate(connection)
|
||||
versions = connection.execute(
|
||||
"SELECT version FROM schema_migrations ORDER BY version"
|
||||
).fetchall()
|
||||
self.assertEqual(11, versions[-1]["version"])
|
||||
connection.execute("DELETE FROM schema_migrations WHERE version = 10")
|
||||
connection.executescript(
|
||||
"""
|
||||
DROP TRIGGER IF EXISTS reminders_no_delete;
|
||||
DROP TRIGGER IF EXISTS reminder_events_no_delete;
|
||||
DROP TRIGGER IF EXISTS reminder_events_no_update;
|
||||
DROP TABLE IF EXISTS reminder_events;
|
||||
DROP TABLE IF EXISTS reminders;
|
||||
DROP TABLE IF EXISTS reminder_settings;
|
||||
"""
|
||||
)
|
||||
row = connection.execute(
|
||||
"SELECT name FROM sqlite_master WHERE name = 'reminders'"
|
||||
).fetchone()
|
||||
self.assertIsNone(row)
|
||||
@@ -1,169 +0,0 @@
|
||||
"""HEL-230: 提醒管理页通栏三块与三步发送流的结构/响应式契约。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import unittest
|
||||
from functools import partial
|
||||
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
WEB = ROOT / "web"
|
||||
|
||||
try:
|
||||
from playwright.sync_api import sync_playwright
|
||||
except ImportError: # pragma: no cover
|
||||
sync_playwright = None
|
||||
|
||||
|
||||
class RemindersPageSourceContractTests(unittest.TestCase):
|
||||
def test_admin_html_order_and_send_flow(self) -> None:
|
||||
html = (WEB / "admin.html").read_text(encoding="utf-8")
|
||||
self.assertIn('data-page="reminders"', html)
|
||||
self.assertIn('id="pending-reminders-card"', html)
|
||||
self.assertIn('id="reminder-history-card"', html)
|
||||
self.assertIn('id="send-reminder-card"', html)
|
||||
self.assertIn('class="send-flow"', html)
|
||||
self.assertIn('class="sf-step"', html)
|
||||
self.assertIn('id="pick-count"', html)
|
||||
self.assertIn('id="reminderForm"', html)
|
||||
self.assertIn('id="reminderCompanyList"', html)
|
||||
self.assertIn('id="reminder-type"', html)
|
||||
self.assertIn('id="reminder-content"', html)
|
||||
self.assertIn('id="reminder-deadline"', html)
|
||||
self.assertIn('id="send-btn"', html)
|
||||
self.assertIn('id="send-hint"', html)
|
||||
self.assertIn('id="reminder-tbody"', html)
|
||||
self.assertIn('id="reminder-tabs"', html)
|
||||
self.assertIn('id="reminder-detail-drawer"', html)
|
||||
self.assertIn("design-system.css?v=14", html)
|
||||
self.assertIn("app.js?v=18", html)
|
||||
pending = html.index('id="pending-reminders-card"')
|
||||
history = html.index('id="reminder-history-card"')
|
||||
send = html.index('id="send-reminder-card"')
|
||||
self.assertLess(pending, history)
|
||||
self.assertLess(history, send)
|
||||
reminders = html[html.index('data-page="reminders"') : html.index("新增公司弹窗")]
|
||||
self.assertNotIn("grid-1-2", reminders)
|
||||
self.assertEqual(reminders.count('class="sf-step"'), 3)
|
||||
self.assertIn("选择接收公司", reminders)
|
||||
self.assertIn("填写提醒内容", reminders)
|
||||
self.assertIn("设定截止并发送", reminders)
|
||||
|
||||
def test_app_js_keeps_real_reminder_apis(self) -> None:
|
||||
js = (WEB / "app.js").read_text(encoding="utf-8")
|
||||
self.assertIn('label.className = "pick"', js)
|
||||
self.assertIn("function updatePickCount", js)
|
||||
self.assertIn("function syncPendingPicks", js)
|
||||
self.assertIn("/api/admin/reminders/pending", js)
|
||||
self.assertIn("/api/admin/reminders/manual", js)
|
||||
self.assertIn("/api/admin/reminders/send", js)
|
||||
self.assertIn("/api/admin/reminders/scan", js)
|
||||
self.assertIn("function loadAdminRemindersPending", js)
|
||||
self.assertIn("function loadAdminRemindersHistory", js)
|
||||
self.assertIn("function openReminderDetailDrawer", js)
|
||||
self.assertIn("initAdminReminders()", js)
|
||||
self.assertIn("dataset.companyId", js)
|
||||
|
||||
def test_design_system_send_flow_uses_tokens(self) -> None:
|
||||
css = (WEB / "design-system.css").read_text(encoding="utf-8")
|
||||
self.assertIn(".send-flow", css)
|
||||
self.assertIn(".sf-step", css)
|
||||
self.assertIn(".pick", css)
|
||||
self.assertIn("minmax(0, 1.5fr)", css)
|
||||
block_start = css.index("提醒管理:三步发送流")
|
||||
block_end = css.index("月结 / 重开 / 审计")
|
||||
block = css[block_start:block_end]
|
||||
self.assertIn("var(--border)", block)
|
||||
self.assertIn("var(--accent-soft)", block)
|
||||
self.assertIn("var(--accent)", block)
|
||||
self.assertIn("@media (max-width: 1100px)", block)
|
||||
self.assertNotRegex(block, r"#[0-9a-fA-F]{3,8}")
|
||||
self.assertNotRegex(block, r"rgb\(")
|
||||
self.assertNotIn("box-shadow: 0 0", block)
|
||||
|
||||
|
||||
def _chromium_available() -> bool:
|
||||
try:
|
||||
import ctypes.util
|
||||
|
||||
return bool(ctypes.util.find_library("atk-1.0"))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
@unittest.skipUnless(sync_playwright, "playwright 未安装,跳过布局冒烟")
|
||||
@unittest.skipUnless(_chromium_available(), "系统缺少 chromium 依赖库(如 libatk),跳过布局冒烟")
|
||||
class RemindersPageLayoutSmokeTests(unittest.TestCase):
|
||||
"""桌面三列 / 窄屏竖排,360 / 820 / 1440 无页面级横向溢出。"""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
handler = partial(SimpleHTTPRequestHandler, directory=str(WEB))
|
||||
cls.httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
cls.port = cls.httpd.server_address[1]
|
||||
cls.thread = threading.Thread(target=cls.httpd.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
cls.base = f"http://127.0.0.1:{cls.port}"
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls) -> None:
|
||||
cls.httpd.shutdown()
|
||||
cls.httpd.server_close()
|
||||
|
||||
def _open_reminders(self, page, width: int) -> None:
|
||||
page.route("**/app.js**", lambda route: route.abort())
|
||||
page.set_viewport_size({"width": width, "height": 900})
|
||||
page.goto(f"{self.base}/admin.html")
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
document.querySelectorAll('.app-view').forEach((el) => {
|
||||
el.classList.toggle('is-active', el.dataset.page === 'reminders');
|
||||
});
|
||||
const list = document.getElementById('reminderCompanyList');
|
||||
if (list && !list.children.length) {
|
||||
['A公司', 'B公司', '郑州金牛建业煤炭有限责任公司'].forEach((name, i) => {
|
||||
const label = document.createElement('label');
|
||||
label.className = 'pick';
|
||||
label.innerHTML = '<input type="checkbox" name="company" value="' + (i + 1) + '">' + name;
|
||||
if (i < 2) label.querySelector('input').checked = true;
|
||||
list.append(label);
|
||||
});
|
||||
}
|
||||
}"""
|
||||
)
|
||||
|
||||
def test_send_flow_columns_and_no_page_overflow(self) -> None:
|
||||
html = (WEB / "admin.html").read_text(encoding="utf-8")
|
||||
self.assertIn("app.js?v=18", html)
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch()
|
||||
page = browser.new_page()
|
||||
self._open_reminders(page, 1440)
|
||||
cols_wide = page.evaluate(
|
||||
"() => getComputedStyle(document.querySelector('.send-flow')).gridTemplateColumns"
|
||||
)
|
||||
self.assertEqual(len(cols_wide.split()), 3, f"桌面端应为三列,实际: {cols_wide}")
|
||||
overflow_wide = page.evaluate(
|
||||
"() => document.documentElement.scrollWidth > document.documentElement.clientWidth + 1"
|
||||
)
|
||||
self.assertFalse(overflow_wide, "1440px 出现页面级横向溢出")
|
||||
|
||||
self._open_reminders(page, 900)
|
||||
cols_narrow = page.evaluate(
|
||||
"() => getComputedStyle(document.querySelector('.send-flow')).gridTemplateColumns"
|
||||
)
|
||||
self.assertEqual(len(cols_narrow.split()), 1, f"窄屏应为单列,实际: {cols_narrow}")
|
||||
|
||||
for width in (360, 820, 1440):
|
||||
self._open_reminders(page, width)
|
||||
overflow = page.evaluate(
|
||||
"() => document.documentElement.scrollWidth > document.documentElement.clientWidth + 1"
|
||||
)
|
||||
self.assertFalse(overflow, f"{width}px 出现页面级横向溢出")
|
||||
browser.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,17 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from unittest import TestCase
|
||||
from unittest.mock import patch
|
||||
|
||||
import server
|
||||
|
||||
|
||||
class ServerConfigurationTests(TestCase):
|
||||
@patch.dict(os.environ, {"APP_HOST": "0.0.0.0", "APP_PORT": "8080"})
|
||||
@patch("server.ThreadingHTTPServer")
|
||||
def test_main_uses_configured_host_and_port(self, http_server) -> None:
|
||||
server.main()
|
||||
|
||||
http_server.assert_called_once_with(("0.0.0.0", 8080), server.AppHandler)
|
||||
http_server.return_value.serve_forever.assert_called_once_with()
|
||||
@@ -1,595 +0,0 @@
|
||||
"""HTTP integration tests for authentication, RBAC and tenant isolation.
|
||||
|
||||
Spins up a real ``ThreadingHTTPServer`` with a temp database/storage and
|
||||
drives it with stdlib ``http.client`` (cookies handled by hand). The server
|
||||
module reads ``APP_DB_PATH`` / ``APP_STORAGE_DIR`` from module globals at
|
||||
request time, so tests patch them per class.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from http.client import HTTPConnection
|
||||
from http.cookies import SimpleCookie
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
|
||||
from bank_importer import auth
|
||||
from bank_importer.db import connect, migrate, utc_now
|
||||
|
||||
import server
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SAMPLES = ROOT / "流水模板"
|
||||
CCB_SAMPLE = SAMPLES / "中国建设银行账户流水.xls"
|
||||
CITIC_SAMPLE = SAMPLES / "中信银行账户流水.xlsx"
|
||||
|
||||
BOOTSTRAP_PASSWORD = "BootAdmin123"
|
||||
ADMIN_PASSWORD = "AdminPass123"
|
||||
CASHIER_A_PASSWORD = "CashierA123"
|
||||
|
||||
|
||||
class Client:
|
||||
"""Minimal HTTP client with a cookie jar."""
|
||||
|
||||
def __init__(self, host: str, port: int) -> None:
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.cookies: dict[str, str] = {}
|
||||
|
||||
def request(
|
||||
self,
|
||||
method: str,
|
||||
path: str,
|
||||
body: bytes | None = None,
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> tuple[int, dict[str, str], bytes]:
|
||||
connection = HTTPConnection(self.host, self.port)
|
||||
request_headers = dict(headers or {})
|
||||
if self.cookies:
|
||||
request_headers["Cookie"] = "; ".join(
|
||||
f"{key}={value}" for key, value in self.cookies.items()
|
||||
)
|
||||
connection.request(method, path, body=body, headers=request_headers)
|
||||
response = connection.getresponse()
|
||||
data = response.read()
|
||||
response_headers = {key.lower(): value for key, value in response.getheaders()}
|
||||
set_cookie = response_headers.get("set-cookie")
|
||||
if set_cookie:
|
||||
cookie = SimpleCookie()
|
||||
cookie.load(set_cookie)
|
||||
for key, morsel in cookie.items():
|
||||
if morsel.value:
|
||||
self.cookies[key] = morsel.value
|
||||
else:
|
||||
self.cookies.pop(key, None)
|
||||
status = response.status
|
||||
connection.close()
|
||||
return status, response_headers, data
|
||||
|
||||
def get(self, path: str) -> tuple[int, dict[str, str], bytes]:
|
||||
return self.request("GET", path)
|
||||
|
||||
def post_json(self, path: str, payload: dict) -> tuple[int, dict, bytes]:
|
||||
return self.request(
|
||||
"POST",
|
||||
path,
|
||||
body=json.dumps(payload).encode("utf-8"),
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
|
||||
def post_multipart(
|
||||
self, path: str, fields: dict[str, str], filename: str, content: bytes
|
||||
) -> tuple[int, dict, bytes]:
|
||||
boundary = "----cwtestboundary7f3a9c1e"
|
||||
parts: list[bytes] = []
|
||||
for name, value in fields.items():
|
||||
parts.append(
|
||||
f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode()
|
||||
)
|
||||
parts.append(
|
||||
f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="{filename}"\r\n'
|
||||
"Content-Type: application/octet-stream\r\n\r\n".encode()
|
||||
+ content
|
||||
+ b"\r\n"
|
||||
)
|
||||
parts.append(f"--{boundary}--\r\n".encode())
|
||||
return self.request(
|
||||
"POST",
|
||||
path,
|
||||
body=b"".join(parts),
|
||||
headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
|
||||
)
|
||||
|
||||
|
||||
def as_json(data: bytes) -> dict:
|
||||
return json.loads(data.decode("utf-8"))
|
||||
|
||||
|
||||
class ServerAuthMatrixTests(unittest.TestCase):
|
||||
"""One live server; setUpClass builds the shared fixture via the API."""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
cls.temp_dir = tempfile.TemporaryDirectory()
|
||||
root = Path(cls.temp_dir.name)
|
||||
cls.db_path = root / "app.db"
|
||||
cls.storage = root / "files"
|
||||
|
||||
cls._old_db_path = server.DB_PATH
|
||||
cls._old_storage = server.STORAGE_DIR
|
||||
server.DB_PATH = cls.db_path
|
||||
server.STORAGE_DIR = cls.storage
|
||||
|
||||
os.environ["APP_BOOTSTRAP_ADMIN_PASSWORD"] = BOOTSTRAP_PASSWORD
|
||||
connection = connect(cls.db_path)
|
||||
migrate(connection)
|
||||
generated = server.ensure_bootstrap_admin(connection)
|
||||
assert generated is None, "env password set, nothing should be generated"
|
||||
connection.close()
|
||||
|
||||
class QuietHandler(server.AppHandler):
|
||||
def log_message(self, *args) -> None: # silence per-request logs
|
||||
pass
|
||||
|
||||
cls.httpd = server.ThreadingHTTPServer(("127.0.0.1", 0), QuietHandler)
|
||||
cls.port = cls.httpd.server_address[1]
|
||||
cls.thread = threading.Thread(target=cls.httpd.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
|
||||
cls.known_passwords = {BOOTSTRAP_PASSWORD, ADMIN_PASSWORD, CASHIER_A_PASSWORD}
|
||||
|
||||
# --- Admin bootstrap: must_change_password gate, then change. ---
|
||||
cls.admin = Client("127.0.0.1", cls.port)
|
||||
status, _, data = cls.admin.post_json(
|
||||
"/api/login",
|
||||
{"username": "group-admin", "password": BOOTSTRAP_PASSWORD, "portal": "admin"},
|
||||
)
|
||||
assert status == 200, data
|
||||
assert as_json(data)["must_change_password"] is True
|
||||
status, _, data = cls.admin.get("/api/batches")
|
||||
assert status == 403, "must_change_password must block API access"
|
||||
status, _, data = cls.admin.post_json(
|
||||
"/api/password/change",
|
||||
{"old_password": BOOTSTRAP_PASSWORD, "new_password": ADMIN_PASSWORD},
|
||||
)
|
||||
assert status == 200, data
|
||||
status, _, _ = cls.admin.get("/api/batches")
|
||||
assert status == 200
|
||||
|
||||
# --- Companies A and B. ---
|
||||
status, _, data = cls.admin.post_json("/api/admin/companies", {"name": "甲公司"})
|
||||
assert status == 200, data
|
||||
cls.company_a = as_json(data)["company_id"]
|
||||
status, _, data = cls.admin.post_json("/api/admin/companies", {"name": "乙公司"})
|
||||
assert status == 200, data
|
||||
cls.company_b = as_json(data)["company_id"]
|
||||
|
||||
# --- Company user A: random one-time initial password, forced change. ---
|
||||
status, _, data = cls.admin.post_json(
|
||||
"/api/admin/users", {"username": "cashier-a", "company_id": cls.company_a}
|
||||
)
|
||||
assert status == 200, data
|
||||
payload = as_json(data)
|
||||
# Security: the initial password is random and never equals the username.
|
||||
assert payload["initial_password"] != "cashier-a"
|
||||
assert len(payload["initial_password"]) >= 12
|
||||
cls.initial_password_a = payload["initial_password"]
|
||||
cls.known_passwords.add(cls.initial_password_a)
|
||||
|
||||
cls.cashier_a = Client("127.0.0.1", cls.port)
|
||||
status, _, data = cls.cashier_a.post_json(
|
||||
"/api/login",
|
||||
{
|
||||
"username": "cashier-a",
|
||||
"password": cls.initial_password_a,
|
||||
"portal": "company",
|
||||
},
|
||||
)
|
||||
assert status == 200, data
|
||||
assert as_json(data)["must_change_password"] is True
|
||||
status, _, _ = cls.cashier_a.get("/api/batches")
|
||||
assert status == 403, "must_change_password must block company API access"
|
||||
status, _, data = cls.cashier_a.post_json(
|
||||
"/api/password/change",
|
||||
{"old_password": cls.initial_password_a, "new_password": CASHIER_A_PASSWORD},
|
||||
)
|
||||
assert status == 200, data
|
||||
|
||||
# --- B gets a batch (admin upload), A gets its own batch. ---
|
||||
status, _, data = cls.admin.post_multipart(
|
||||
"/api/parse",
|
||||
{"company_id": str(cls.company_b)},
|
||||
CCB_SAMPLE.name,
|
||||
CCB_SAMPLE.read_bytes(),
|
||||
)
|
||||
assert status == 200, data
|
||||
cls.b_batch_id = as_json(data)["batch_id"]
|
||||
cls.confirm_all_sheets(cls.admin, cls.b_batch_id)
|
||||
|
||||
status, _, data = cls.cashier_a.post_multipart(
|
||||
"/api/parse", {}, CITIC_SAMPLE.name, CITIC_SAMPLE.read_bytes()
|
||||
)
|
||||
assert status == 200, data
|
||||
cls.a_batch_id = as_json(data)["batch_id"]
|
||||
cls.confirm_all_sheets(cls.cashier_a, cls.a_batch_id)
|
||||
|
||||
@classmethod
|
||||
def confirm_all_sheets(cls, client, batch_id: int) -> None:
|
||||
status, _, data = client.get(f"/api/batches/{batch_id}/sheets")
|
||||
assert status == 200, data
|
||||
names = [
|
||||
sheet["sheet_name"]
|
||||
for sheet in as_json(data)["sheets"]
|
||||
if sheet["outcome"] == "parsed"
|
||||
]
|
||||
if not names:
|
||||
return
|
||||
status, _, data = client.post_json(
|
||||
f"/api/batches/{batch_id}/confirm", {"sheets": names}
|
||||
)
|
||||
assert status == 200, data
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls) -> None:
|
||||
cls.httpd.shutdown()
|
||||
cls.httpd.server_close()
|
||||
server.DB_PATH = cls._old_db_path
|
||||
server.STORAGE_DIR = cls._old_storage
|
||||
os.environ.pop("APP_BOOTSTRAP_ADMIN_PASSWORD", None)
|
||||
cls.temp_dir.cleanup()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def fresh_client(self) -> Client:
|
||||
return Client("127.0.0.1", self.port)
|
||||
|
||||
def create_company_user(self, username: str) -> tuple[Client, str, int]:
|
||||
status, _, data = self.admin.post_json(
|
||||
"/api/admin/users", {"username": username, "company_id": self.company_a}
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
payload = as_json(data)
|
||||
initial = payload["initial_password"]
|
||||
self.known_passwords.add(initial)
|
||||
client = self.fresh_client()
|
||||
status, _, data = client.post_json(
|
||||
"/api/login",
|
||||
{"username": username, "password": initial, "portal": "company"},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
new_password = "Changed123"
|
||||
self.known_passwords.add(new_password)
|
||||
status, _, data = client.post_json(
|
||||
"/api/password/change",
|
||||
{"old_password": initial, "new_password": new_password},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
return client, new_password, payload["user_id"]
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Unauthenticated matrix
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_unauthenticated_api_calls_return_401(self) -> None:
|
||||
anon = self.fresh_client()
|
||||
for method_check in (
|
||||
lambda: anon.post_multipart("/api/parse", {}, "x.xls", b"data"),
|
||||
lambda: anon.get("/api/batches"),
|
||||
lambda: anon.get(f"/api/batches/{self.a_batch_id}/rows"),
|
||||
lambda: anon.get("/api/export.csv"),
|
||||
lambda: anon.get("/api/admin/users"),
|
||||
lambda: anon.get("/api/admin/companies"),
|
||||
lambda: anon.get("/api/admin/audit-log"),
|
||||
lambda: anon.get("/api/admin/reminders"),
|
||||
lambda: anon.get("/api/company/reminders"),
|
||||
lambda: anon.get("/api/me"),
|
||||
):
|
||||
status, _, data = method_check()
|
||||
self.assertEqual(401, status, data)
|
||||
self.assertEqual("error", as_json(data)["status"])
|
||||
|
||||
def test_unauthenticated_portal_pages_redirect(self) -> None:
|
||||
anon = self.fresh_client()
|
||||
for page in ("/admin.html", "/company.html"):
|
||||
status, headers, _ = anon.get(page)
|
||||
self.assertEqual(302, status, page)
|
||||
self.assertEqual("/", headers.get("location"))
|
||||
|
||||
def test_wrong_password_returns_generic_401(self) -> None:
|
||||
anon = self.fresh_client()
|
||||
status, _, data = anon.post_json(
|
||||
"/api/login",
|
||||
{"username": "group-admin", "password": "WrongPass1", "portal": "admin"},
|
||||
)
|
||||
self.assertEqual(401, status)
|
||||
message = as_json(data)["message"]
|
||||
self.assertNotIn("密码不正确", message.replace("账号或密码不正确", ""))
|
||||
|
||||
def test_rate_limit_after_five_failures(self) -> None:
|
||||
anon = self.fresh_client()
|
||||
for _ in range(5):
|
||||
status, _, _ = anon.post_json(
|
||||
"/api/login",
|
||||
{"username": "ghost-user", "password": "WrongPass1", "portal": "admin"},
|
||||
)
|
||||
self.assertEqual(401, status)
|
||||
status, _, _ = anon.post_json(
|
||||
"/api/login",
|
||||
{"username": "ghost-user", "password": "WrongPass1", "portal": "admin"},
|
||||
)
|
||||
self.assertEqual(429, status)
|
||||
|
||||
def test_portal_mismatch_returns_403(self) -> None:
|
||||
anon = self.fresh_client()
|
||||
status, _, data = anon.post_json(
|
||||
"/api/login",
|
||||
{"username": "group-admin", "password": ADMIN_PASSWORD, "portal": "company"},
|
||||
)
|
||||
self.assertEqual(403, status)
|
||||
self.assertIn("端口", as_json(data)["message"])
|
||||
|
||||
def test_logout_revokes_session(self) -> None:
|
||||
client, _, _ = self.create_company_user("cashier-logout")
|
||||
status, _, _ = client.get("/api/me")
|
||||
self.assertEqual(200, status)
|
||||
status, _, _ = client.request("POST", "/api/logout")
|
||||
self.assertEqual(200, status)
|
||||
self.assertNotIn("cw_session", client.cookies)
|
||||
status, _, _ = client.get("/api/me")
|
||||
self.assertEqual(401, status)
|
||||
|
||||
def test_expired_session_returns_401(self) -> None:
|
||||
client, _, user_id = self.create_company_user("cashier-expired")
|
||||
connection = connect(self.db_path)
|
||||
try:
|
||||
with connection:
|
||||
connection.execute(
|
||||
"UPDATE sessions SET expires_at = ? WHERE user_id = ?",
|
||||
("2000-01-01T00:00:00+00:00", user_id),
|
||||
)
|
||||
finally:
|
||||
connection.close()
|
||||
status, _, _ = client.get("/api/me")
|
||||
self.assertEqual(401, status)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Admin and company lifecycle
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_duplicate_company_name_returns_409(self) -> None:
|
||||
status, _, _ = self.admin.post_json("/api/admin/companies", {"name": "甲公司"})
|
||||
self.assertEqual(409, status)
|
||||
|
||||
def test_me_returns_profile_without_password_material(self) -> None:
|
||||
status, _, data = self.cashier_a.get("/api/me")
|
||||
self.assertEqual(200, status)
|
||||
payload = as_json(data)
|
||||
self.assertEqual("cashier-a", payload["username"])
|
||||
self.assertEqual("company", payload["role"])
|
||||
self.assertEqual(self.company_a, payload["company_id"])
|
||||
self.assertEqual("甲公司", payload["company_name"])
|
||||
self.assertFalse(payload["must_change_password"])
|
||||
|
||||
def test_company_user_forbidden_on_all_admin_endpoints(self) -> None:
|
||||
calls = (
|
||||
lambda: self.cashier_a.get("/api/admin/companies"),
|
||||
lambda: self.cashier_a.post_json("/api/admin/companies", {"name": "丙公司"}),
|
||||
lambda: self.cashier_a.get("/api/admin/users"),
|
||||
lambda: self.cashier_a.post_json(
|
||||
"/api/admin/users", {"username": "x", "company_id": self.company_a}
|
||||
),
|
||||
lambda: self.cashier_a.request("POST", "/api/admin/users/1/disable"),
|
||||
lambda: self.cashier_a.request("POST", "/api/admin/users/1/enable"),
|
||||
lambda: self.cashier_a.request("POST", "/api/admin/users/1/reset-password"),
|
||||
lambda: self.cashier_a.get("/api/admin/audit-log"),
|
||||
lambda: self.cashier_a.get("/api/admin/reminders"),
|
||||
lambda: self.cashier_a.get("/api/admin/reminders/pending"),
|
||||
lambda: self.cashier_a.post_json("/api/admin/reminder-settings", {"gap_days": "3"}),
|
||||
lambda: self.cashier_a.post_json("/api/admin/reminders/send", {"dedupe_keys": ["x"]}),
|
||||
)
|
||||
for call in calls:
|
||||
status, _, data = call()
|
||||
self.assertEqual(403, status, data)
|
||||
|
||||
def test_admin_upload_requires_company_id(self) -> None:
|
||||
status, _, data = self.admin.post_multipart(
|
||||
"/api/parse", {}, CCB_SAMPLE.name, CCB_SAMPLE.read_bytes()
|
||||
)
|
||||
self.assertEqual(400, status, data)
|
||||
|
||||
def test_admin_batches_filter_by_company(self) -> None:
|
||||
status, _, data = self.admin.get(f"/api/batches?company_id={self.company_b}")
|
||||
self.assertEqual(200, status)
|
||||
batches = as_json(data)["batches"]
|
||||
self.assertTrue(batches)
|
||||
for batch in batches:
|
||||
self.assertEqual(self.company_b, batch["company_id"])
|
||||
self.assertEqual("乙公司", batch["company_name"])
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Tenant isolation
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_batches_scoped_to_own_company(self) -> None:
|
||||
status, _, data = self.cashier_a.get("/api/batches")
|
||||
self.assertEqual(200, status)
|
||||
batches = as_json(data)["batches"]
|
||||
self.assertTrue(batches)
|
||||
for batch in batches:
|
||||
self.assertEqual(self.company_a, batch["company_id"])
|
||||
self.assertNotIn(self.b_batch_id, [batch["id"] for batch in batches])
|
||||
|
||||
def test_idor_batch_rows_of_other_company_return_404(self) -> None:
|
||||
status, _, _ = self.cashier_a.get(f"/api/batches/{self.b_batch_id}/rows")
|
||||
self.assertEqual(404, status)
|
||||
status, _, data = self.cashier_a.get(f"/api/batches/{self.a_batch_id}/rows")
|
||||
self.assertEqual(200, status)
|
||||
self.assertTrue(as_json(data)["rows"])
|
||||
|
||||
def test_export_csv_forced_to_own_company(self) -> None:
|
||||
status, _, _ = self.cashier_a.get(f"/api/export.csv?company_id={self.company_b}")
|
||||
self.assertEqual(403, status)
|
||||
|
||||
status, headers, data = self.cashier_a.get("/api/export.csv")
|
||||
self.assertEqual(200, status)
|
||||
self.assertEqual("text/csv; charset=utf-8", headers.get("content-type"))
|
||||
text = data.decode("utf-8-sig")
|
||||
lines = [line for line in text.splitlines() if line]
|
||||
self.assertGreater(len(lines), 1)
|
||||
for line in lines[1:]:
|
||||
self.assertEqual(str(self.a_batch_id), line.split(",", 1)[0])
|
||||
|
||||
def test_cross_company_upload_is_recorded_under_own_company(self) -> None:
|
||||
# A uploads B's file bytes while claiming company B in the form; the
|
||||
# server must bind the new (duplicate) batch to A from the session.
|
||||
status, _, data = self.cashier_a.post_multipart(
|
||||
"/api/parse",
|
||||
{"company_id": str(self.company_b)},
|
||||
CCB_SAMPLE.name,
|
||||
CCB_SAMPLE.read_bytes(),
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
payload = as_json(data)
|
||||
self.assertEqual("duplicate", payload["status"])
|
||||
# Cross-company duplicate: no original batch id, bank, template,
|
||||
# period, transaction count or diagnostics may be exposed.
|
||||
self.assertNotEqual(self.b_batch_id, payload.get("batch_id"))
|
||||
for leaked_key in ("bank", "template", "header_row", "period_start", "period_end", "transactions", "warnings"):
|
||||
self.assertNotIn(leaked_key, payload, leaked_key)
|
||||
connection = connect(self.db_path)
|
||||
try:
|
||||
duplicate = connection.execute(
|
||||
"SELECT company_id FROM import_batches WHERE status = 'duplicate'"
|
||||
).fetchone()
|
||||
finally:
|
||||
connection.close()
|
||||
self.assertIsNotNone(duplicate)
|
||||
self.assertEqual(self.company_a, duplicate["company_id"])
|
||||
|
||||
def test_same_company_duplicate_keeps_idempotent_summary(self) -> None:
|
||||
# A re-uploads its own file; the idempotent duplicate response keeps
|
||||
# the original batch id and the parsed summary.
|
||||
status, _, data = self.cashier_a.post_multipart(
|
||||
"/api/parse", {}, CITIC_SAMPLE.name, CITIC_SAMPLE.read_bytes()
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
payload = as_json(data)
|
||||
self.assertEqual("duplicate", payload["status"])
|
||||
self.assertEqual(self.a_batch_id, payload["batch_id"])
|
||||
self.assertTrue(payload.get("sheets"))
|
||||
self.assertEqual("中信银行", payload["sheets"][0].get("bank"))
|
||||
self.assertTrue(payload["sheets"][0].get("transactions", 0) > 0)
|
||||
self.assertIn("period_start", payload["sheets"][0])
|
||||
self.assertIn("warnings", payload["sheets"][0])
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Disable / reset flows
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_disabled_user_session_and_login_rejected(self) -> None:
|
||||
client, password, user_id = self.create_company_user("cashier-disable")
|
||||
status, _, _ = client.get("/api/me")
|
||||
self.assertEqual(200, status)
|
||||
|
||||
status, _, data = self.admin.request("POST", f"/api/admin/users/{user_id}/disable")
|
||||
self.assertEqual(200, status, data)
|
||||
|
||||
status, _, _ = client.get("/api/me")
|
||||
self.assertEqual(401, status)
|
||||
|
||||
fresh = self.fresh_client()
|
||||
status, _, data = fresh.post_json(
|
||||
"/api/login",
|
||||
{"username": "cashier-disable", "password": password, "portal": "company"},
|
||||
)
|
||||
self.assertEqual(403, status, data)
|
||||
|
||||
def test_reset_password_returns_once_and_revokes_sessions(self) -> None:
|
||||
client, old_password, user_id = self.create_company_user("cashier-reset")
|
||||
status, _, data = self.admin.request(
|
||||
"POST", f"/api/admin/users/{user_id}/reset-password"
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
new_password = as_json(data)["initial_password"]
|
||||
self.known_passwords.add(new_password)
|
||||
|
||||
status, _, _ = client.get("/api/me")
|
||||
self.assertEqual(401, status)
|
||||
|
||||
fresh = self.fresh_client()
|
||||
status, _, data = fresh.post_json(
|
||||
"/api/login",
|
||||
{"username": "cashier-reset", "password": new_password, "portal": "company"},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
self.assertTrue(as_json(data)["must_change_password"])
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Secrets hygiene
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def test_no_response_contains_password_hash(self) -> None:
|
||||
bodies = []
|
||||
status, _, data = self.admin.get("/api/admin/users")
|
||||
self.assertEqual(200, status)
|
||||
bodies.append(data)
|
||||
status, _, data = self.admin.get("/api/admin/companies")
|
||||
self.assertEqual(200, status)
|
||||
bodies.append(data)
|
||||
status, _, data = self.admin.get("/api/admin/audit-log?limit=100")
|
||||
self.assertEqual(200, status)
|
||||
bodies.append(data)
|
||||
status, _, data = self.cashier_a.get("/api/me")
|
||||
bodies.append(data)
|
||||
status, _, data = self.cashier_a.get("/api/batches")
|
||||
bodies.append(data)
|
||||
for body in bodies:
|
||||
text = body.decode("utf-8")
|
||||
self.assertNotIn("password_hash", text)
|
||||
self.assertNotIn("initial_password", text)
|
||||
|
||||
def test_audit_log_contains_no_plaintext_passwords(self) -> None:
|
||||
connection = connect(self.db_path)
|
||||
try:
|
||||
rows = connection.execute(
|
||||
"SELECT detail, target FROM audit_log"
|
||||
).fetchall()
|
||||
finally:
|
||||
connection.close()
|
||||
for password in self.known_passwords:
|
||||
for row in rows:
|
||||
self.assertNotIn(password, row["detail"] or "")
|
||||
self.assertNotIn(password, row["target"] or "")
|
||||
|
||||
def test_invalid_reminder_settings_return_400_and_do_not_persist(self) -> None:
|
||||
cases = (
|
||||
{"monthly_start_day": "0"},
|
||||
{"gap_days": "0"},
|
||||
{"scan_time": "25:99"},
|
||||
)
|
||||
for payload in cases:
|
||||
with self.subTest(payload=payload):
|
||||
status, _, data = self.admin.post_json(
|
||||
"/api/admin/reminder-settings", {"settings": payload}
|
||||
)
|
||||
self.assertEqual(400, status, data)
|
||||
self.assertEqual("error", as_json(data)["status"])
|
||||
status, _, data = self.admin.get("/api/admin/reminder-settings")
|
||||
self.assertEqual(200, status)
|
||||
settings = as_json(data)["settings"]
|
||||
self.assertEqual("5", settings["monthly_start_day"])
|
||||
self.assertEqual("5", settings["gap_days"])
|
||||
self.assertEqual("08:00", settings["scan_time"])
|
||||
status, _, data = self.admin.get("/api/admin/reminders/pending")
|
||||
self.assertEqual(200, status, data)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,274 +0,0 @@
|
||||
"""Integration tests for system settings persistence and reminder flow."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from http.client import HTTPConnection
|
||||
from http.cookies import SimpleCookie
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
|
||||
from bank_importer.db import connect, migrate
|
||||
from bank_importer import auth, settings
|
||||
|
||||
import server
|
||||
|
||||
|
||||
BOOTSTRAP_PASSWORD = "BootAdmin123"
|
||||
ADMIN_PASSWORD = "AdminPass123"
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self, host: str, port: int) -> None:
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.cookies: dict[str, str] = {}
|
||||
|
||||
def request(self, method, path, body=None, headers=None):
|
||||
connection = HTTPConnection(self.host, self.port)
|
||||
request_headers = dict(headers or {})
|
||||
if self.cookies:
|
||||
request_headers["Cookie"] = "; ".join(
|
||||
f"{k}={v}" for k, v in self.cookies.items()
|
||||
)
|
||||
connection.request(method, path, body=body, headers=request_headers)
|
||||
response = connection.getresponse()
|
||||
data = response.read()
|
||||
set_cookie = dict(response.getheaders()).get("Set-Cookie")
|
||||
if set_cookie:
|
||||
cookie = SimpleCookie()
|
||||
cookie.load(set_cookie)
|
||||
for key, morsel in cookie.items():
|
||||
if morsel.value:
|
||||
self.cookies[key] = morsel.value
|
||||
else:
|
||||
self.cookies.pop(key, None)
|
||||
status = response.status
|
||||
connection.close()
|
||||
return status, data
|
||||
|
||||
def get(self, path):
|
||||
return self.request("GET", path)
|
||||
|
||||
def post_json(self, path, payload):
|
||||
return self.request(
|
||||
"POST", path, body=json.dumps(payload).encode("utf-8"),
|
||||
headers={"Content-Type": "application/json"},
|
||||
)
|
||||
|
||||
|
||||
def as_json(data: bytes):
|
||||
return json.loads(data.decode("utf-8"))
|
||||
|
||||
|
||||
class SettingsAndRemindersTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
cls.temp_dir = tempfile.TemporaryDirectory()
|
||||
root = Path(cls.temp_dir.name)
|
||||
cls.db_path = root / "app.db"
|
||||
cls.storage = root / "files"
|
||||
|
||||
cls._old_db_path = server.DB_PATH
|
||||
cls._old_storage = server.STORAGE_DIR
|
||||
server.DB_PATH = cls.db_path
|
||||
server.STORAGE_DIR = cls.storage
|
||||
|
||||
os.environ["APP_BOOTSTRAP_ADMIN_PASSWORD"] = BOOTSTRAP_PASSWORD
|
||||
connection = connect(cls.db_path)
|
||||
migrate(connection)
|
||||
server.ensure_bootstrap_admin(connection)
|
||||
# One active account for company 1 so pending items are generated.
|
||||
with connection:
|
||||
connection.execute(
|
||||
"INSERT INTO companies (name, credit_code, status, created_at, updated_at) "
|
||||
"VALUES ('甲公司', NULL, 'active', 't', 't')"
|
||||
)
|
||||
company_id = connection.execute(
|
||||
"SELECT id FROM companies WHERE name = '甲公司'"
|
||||
).fetchone()["id"]
|
||||
connection.execute(
|
||||
"INSERT INTO bank_accounts (company_id, account_number, bank_name, status, created_at, updated_at) "
|
||||
"VALUES (?, '11112222', '工行', 'active', 't', 't')",
|
||||
(company_id,),
|
||||
)
|
||||
cls.company_id = company_id
|
||||
connection.close()
|
||||
|
||||
class QuietHandler(server.AppHandler):
|
||||
def log_message(self, *args) -> None:
|
||||
pass
|
||||
|
||||
cls.httpd = server.ThreadingHTTPServer(("127.0.0.1", 0), QuietHandler)
|
||||
cls.port = cls.httpd.server_address[1]
|
||||
cls.thread = threading.Thread(target=cls.httpd.serve_forever, daemon=True)
|
||||
cls.thread.start()
|
||||
|
||||
cls.admin = Client("127.0.0.1", cls.port)
|
||||
status, data = cls.admin.post_json(
|
||||
"/api/login",
|
||||
{"username": "group-admin", "password": BOOTSTRAP_PASSWORD, "portal": "admin"},
|
||||
)
|
||||
assert status == 200, data
|
||||
status, data = cls.admin.post_json(
|
||||
"/api/password/change",
|
||||
{"old_password": BOOTSTRAP_PASSWORD, "new_password": ADMIN_PASSWORD},
|
||||
)
|
||||
assert status == 200, data
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls) -> None:
|
||||
cls.httpd.shutdown()
|
||||
cls.httpd.server_close()
|
||||
server.DB_PATH = cls._old_db_path
|
||||
server.STORAGE_DIR = cls._old_storage
|
||||
os.environ.pop("APP_BOOTSTRAP_ADMIN_PASSWORD", None)
|
||||
cls.temp_dir.cleanup()
|
||||
|
||||
def test_settings_roundtrip_persists(self) -> None:
|
||||
status, data = self.admin.post_json(
|
||||
"/api/admin/settings",
|
||||
{"closing_day": "1", "start_date": "2026-01-05", "auto_remind": "0", "remind_days": "5"},
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
updated = as_json(data)["settings"]
|
||||
self.assertEqual("1", updated["closing_day"])
|
||||
self.assertEqual("2026-01-05", updated["start_date"])
|
||||
self.assertEqual("0", updated["auto_remind"])
|
||||
self.assertEqual("5", updated["remind_days"])
|
||||
|
||||
status, data = self.admin.get("/api/admin/settings")
|
||||
self.assertEqual(200, status)
|
||||
self.assertEqual("1", as_json(data)["settings"]["closing_day"])
|
||||
|
||||
def test_invalid_closing_day_rejected(self) -> None:
|
||||
for bad in ("0", "29", "abc"):
|
||||
status, data = self.admin.post_json("/api/admin/settings", {"closing_day": bad})
|
||||
self.assertEqual(400, status, (bad, data))
|
||||
|
||||
def test_setting_change_is_audited(self) -> None:
|
||||
status, data = self.admin.post_json("/api/admin/settings", {"closing_day": "7"})
|
||||
self.assertEqual(200, status)
|
||||
connection = connect(self.db_path)
|
||||
try:
|
||||
rows = connection.execute(
|
||||
"SELECT key, before_value, after_value, actor_username "
|
||||
"FROM system_setting_changes WHERE key = 'closing_day' "
|
||||
"ORDER BY id DESC LIMIT 1"
|
||||
).fetchall()
|
||||
finally:
|
||||
connection.close()
|
||||
self.assertTrue(rows)
|
||||
self.assertEqual("7", rows[0]["after_value"])
|
||||
self.assertNotEqual(rows[0]["before_value"], rows[0]["after_value"])
|
||||
self.assertEqual("group-admin", rows[0]["actor_username"])
|
||||
|
||||
def test_company_user_forbidden_on_settings_and_reminders(self) -> None:
|
||||
# A company user must not be able to read or write admin settings.
|
||||
status, data = self.admin.post_json(
|
||||
"/api/admin/users", {"username": "cashier-x", "company_id": self.company_id}
|
||||
)
|
||||
self.assertEqual(200, status, data)
|
||||
initial = as_json(data)["initial_password"]
|
||||
cashier = Client("127.0.0.1", self.port)
|
||||
status, data = cashier.post_json(
|
||||
"/api/login",
|
||||
{"username": "cashier-x", "password": initial, "portal": "company"},
|
||||
)
|
||||
self.assertEqual(200, status)
|
||||
status, data = cashier.post_json(
|
||||
"/api/password/change",
|
||||
{"old_password": initial, "new_password": "Changed123"},
|
||||
)
|
||||
self.assertEqual(200, status)
|
||||
|
||||
for path in ("/api/admin/settings", "/api/admin/reminders"):
|
||||
status, _ = cashier.get(path)
|
||||
self.assertEqual(403, status, path)
|
||||
|
||||
# Company session must get 403 on admin write endpoints (settings /
|
||||
# reminders / review decisions), not just GETs.
|
||||
write_calls = (
|
||||
("POST /api/admin/settings", lambda: cashier.post_json(
|
||||
"/api/admin/settings",
|
||||
{"closing_day": "10", "start_date": "2026-01-01", "auto_remind": "0", "remind_days": "3"},
|
||||
)),
|
||||
("POST /api/admin/reminders/send", lambda: cashier.post_json(
|
||||
"/api/admin/reminders/send", {"company_id": self.company_id}
|
||||
)),
|
||||
("POST /api/admin/accounts/1/review", lambda: cashier.post_json(
|
||||
"/api/admin/accounts/1/review", {"decision": "approve"}
|
||||
)),
|
||||
("POST /api/admin/transfer-events/1/decisions", lambda: cashier.post_json(
|
||||
"/api/admin/transfer-events/1/decisions",
|
||||
{"action": "confirm_single", "reason": "越权"},
|
||||
)),
|
||||
("POST /api/admin/manual-records/1/decisions", lambda: cashier.post_json(
|
||||
"/api/admin/manual-records/1/decisions",
|
||||
{"action": "approve_new", "reason": "越权"},
|
||||
)),
|
||||
("POST /api/admin/intercompany/events/1/subject-decisions", lambda: cashier.post_json(
|
||||
"/api/admin/intercompany/events/1/subject-decisions",
|
||||
{"subject": "other_receivable", "reason": "越权"},
|
||||
)),
|
||||
("POST /api/admin/intercompany/events/1/adjustments", lambda: cashier.post_json(
|
||||
"/api/admin/intercompany/events/1/adjustments",
|
||||
{"action": "reverse", "reason": "越权"},
|
||||
)),
|
||||
)
|
||||
for label, call in write_calls:
|
||||
status, data = call()
|
||||
self.assertEqual(403, status, f"{label}: {data}")
|
||||
# Settings must be unchanged after the forbidden write attempt.
|
||||
status, data = self.admin.get("/api/admin/settings")
|
||||
self.assertEqual(200, status)
|
||||
self.assertEqual("5", as_json(data)["settings"]["closing_day"])
|
||||
|
||||
|
||||
class SettingsModuleTests(unittest.TestCase):
|
||||
"""Unit tests for the settings module on a fresh in-memory database."""
|
||||
|
||||
def setUp(self) -> None:
|
||||
self.connection = connect(":memory:")
|
||||
self.addCleanup(self.connection.close)
|
||||
migrate(self.connection)
|
||||
|
||||
def test_defaults_applied_when_no_row_exists(self) -> None:
|
||||
values = settings.get_settings(self.connection)
|
||||
self.assertEqual("5", values["closing_day"])
|
||||
self.assertEqual("2026-01-01", values["start_date"])
|
||||
self.assertEqual("1", values["auto_remind"])
|
||||
self.assertEqual("3", values["remind_days"])
|
||||
|
||||
def test_validate_rejects_bad_values(self) -> None:
|
||||
for bad in ({"closing_day": "0"}, {"closing_day": "29"}, {"closing_day": "abc"}):
|
||||
_, error = settings.validate_settings(bad)
|
||||
self.assertIsNotNone(error)
|
||||
_, error = settings.validate_settings({"start_date": "2026-13-40"})
|
||||
self.assertIsNotNone(error)
|
||||
_, error = settings.validate_settings({"auto_remind": "2"})
|
||||
self.assertIsNotNone(error)
|
||||
|
||||
def test_update_writes_value_and_trail(self) -> None:
|
||||
user_id = auth.create_user(self.connection, "group-admin", "AdminPass123", "admin")
|
||||
user = self.connection.execute(
|
||||
"SELECT id, username FROM users WHERE id = ?", (user_id,)
|
||||
).fetchone()
|
||||
updated = settings.update_settings(
|
||||
self.connection, {"closing_day": "1", "auto_remind": "0"}, user
|
||||
)
|
||||
self.assertEqual("1", updated["closing_day"])
|
||||
self.assertEqual("0", updated["auto_remind"])
|
||||
changes = self.connection.execute(
|
||||
"SELECT key, before_value, after_value FROM system_setting_changes ORDER BY id"
|
||||
).fetchall()
|
||||
self.assertEqual(2, len(changes))
|
||||
self.assertEqual("5", changes[0]["before_value"])
|
||||
self.assertEqual("1", changes[0]["after_value"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+192
-1203
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user