Compare commits
34
Commits
deploy/hel171
...
v1.0.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e0e4a103a | ||
|
|
2d0ae4d7d1 | ||
|
|
9cfd515b8f | ||
|
|
267ebd37f5 | ||
|
|
e857a0e46d | ||
|
|
c1c41760f5 | ||
|
|
e5e326514d | ||
|
|
f5e0915f63 | ||
|
|
85e11a4f72 | ||
|
|
212b1f9b9b | ||
|
|
f17636183d | ||
|
|
d6f39e018d | ||
|
|
2fb1f2b462 | ||
|
|
fe6b4e59ec | ||
|
|
27f2b0b69a | ||
|
|
b27016d71d | ||
|
|
96309eb2cc | ||
|
|
40f7a91a0f | ||
|
|
cad12b3d28 | ||
|
|
7e7354a809 | ||
|
|
951b353765 | ||
|
|
20d967a4a4 | ||
|
|
31fdc2e456 | ||
|
|
1d07812fa8 | ||
|
|
2fe06b74ae | ||
|
|
307f9ba76f | ||
|
|
020b556801 | ||
|
|
7938a274f2 | ||
|
|
dc0fb76f8f | ||
|
|
5a6a629597 | ||
|
|
5f215271af | ||
|
|
3b10a58d93 | ||
|
|
6d23711e6c | ||
|
|
a621ebc323 |
@@ -1,6 +1,7 @@
|
|||||||
__pycache__/
|
__pycache__/
|
||||||
*.py[cod]
|
*.py[cod]
|
||||||
.venv/
|
.venv/
|
||||||
|
.chrome-libs/
|
||||||
.tmp-*/
|
.tmp-*/
|
||||||
|
|
||||||
# 运行时数据与真实银行文件一律不进仓库(样本仅限流水模板/中已脱敏的六份)
|
# 运行时数据与真实银行文件一律不进仓库(样本仅限流水模板/中已脱敏的六份)
|
||||||
@@ -8,6 +9,7 @@ data/
|
|||||||
uploads/
|
uploads/
|
||||||
exports/
|
exports/
|
||||||
*.local
|
*.local
|
||||||
|
deploy/.env
|
||||||
server.pid
|
server.pid
|
||||||
server.out.log
|
server.out.log
|
||||||
server.err.log
|
server.err.log
|
||||||
@@ -26,3 +28,9 @@ package-lock.json
|
|||||||
# local vendor for agent test env (not shipped)
|
# local vendor for agent test env (not shipped)
|
||||||
.vendor/
|
.vendor/
|
||||||
vendor_wheels/
|
vendor_wheels/
|
||||||
|
|
||||||
|
# 正式环境部署产物(证书私钥、备份)
|
||||||
|
deploy/tls/certs/
|
||||||
|
backups/
|
||||||
|
ALERT.log
|
||||||
|
backup.log
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ SHA-256 内容哈希不可变保存,重复上传返回 `duplicate` 状态并
|
|||||||
- 总账管理端:`http://127.0.0.1:4173/admin.html`
|
- 总账管理端:`http://127.0.0.1:4173/admin.html`
|
||||||
- 公司业务端:`http://127.0.0.1:4173/company.html`
|
- 公司业务端:`http://127.0.0.1:4173/company.html`
|
||||||
|
|
||||||
公司端上传会把所选工作簿提交到本地 `/api/parse`,与 CLI 使用同一个确定性表头解析器;解析结果、原始文件、批次和源行会持久化到 SQLite,并按登录账号绑定的公司隔离。当前前端仍是交互原型,期初、提醒、往来匹配等业务状态仅保存在当前浏览器页面中,尚未接入数据库。
|
公司端上传会把所选工作簿提交到本地 `/api/parse`,与 CLI 使用同一个确定性表头解析器;解析结果、原始文件、批次和源行会持久化到 SQLite,并按登录账号绑定的公司隔离。流水列表、往来查询、手工记录、月结与重开均走服务端接口;银行原始数据不可改,已确认与待确认金额分开计算。测试环境编排见 `deploy/`(默认 4173)。
|
||||||
|
|
||||||
## 样本数据政策
|
## 样本数据政策
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
# 测试环境变量示例。复制为 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 生成证书
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
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"]
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
# 部署与运维手册(与 `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 验收评论。
|
||||||
Executable
+53
@@ -0,0 +1,53 @@
|
|||||||
|
#!/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"
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
# 测试/正式环境部署编排(正式口令不得写入本文件)。
|
||||||
|
# 使用:复制 .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
|
||||||
Executable
+17
@@ -0,0 +1,17 @@
|
|||||||
|
#!/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"
|
||||||
Executable
+32
@@ -0,0 +1,32 @@
|
|||||||
|
#!/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"
|
||||||
Executable
+19
@@ -0,0 +1,19 @@
|
|||||||
|
#!/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"
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
#!/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(其余文件不得离开本机)"
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
# 正式环境 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 @@
|
|||||||
|
⚠️ 本文档已过时,仅留档备查,请勿删除。当前代码状态请看 `README.md`、`项目需求.md`、`最新进度.md` 和 `任务清单.md`。
|
||||||
|
|
||||||
# 项目交接说明
|
# 项目交接说明
|
||||||
|
|
||||||
更新时间:2026-08-06
|
更新时间:2026-08-06
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
⚠️ 本文档已过时,仅留档备查,请勿删除。该历史任务已落地;当前状态见 `../任务清单.md`。
|
||||||
|
|
||||||
# [P0] 仓库银行样本数据分级与脱敏治理
|
# [P0] 仓库银行样本数据分级与脱敏治理
|
||||||
|
|
||||||
## 背景
|
## 背景
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
⚠️ 本文档已过时,仅留档备查,请勿删除。该历史任务已落地;当前状态见 `../任务清单.md`。
|
||||||
|
|
||||||
# [P0] 持久化层与不可变银行导入基础
|
# [P0] 持久化层与不可变银行导入基础
|
||||||
|
|
||||||
## 背景
|
## 背景
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
⚠️ 本文档已过时,仅留档备查,请勿删除。该历史任务已落地;当前状态见 `../任务清单.md`。
|
||||||
|
|
||||||
# [P0] 正式认证、RBAC 与公司级数据隔离
|
# [P0] 正式认证、RBAC 与公司级数据隔离
|
||||||
|
|
||||||
## 背景
|
## 背景
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
⚠️ 本文档已过时,仅留档备查,请勿删除。该历史任务已落地;当前状态见 `../任务清单.md`。
|
||||||
|
|
||||||
# [P1] 动态公司、用户、账户和别名主数据
|
# [P1] 动态公司、用户、账户和别名主数据
|
||||||
|
|
||||||
## 背景
|
## 背景
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
⚠️ 本文档已过时,仅留档备查,请勿删除。该历史任务已落地;当前状态见 `../任务清单.md`。
|
||||||
|
|
||||||
# [P1] 银行导入 API 加固与回归测试
|
# [P1] 银行导入 API 加固与回归测试
|
||||||
|
|
||||||
## 背景
|
## 背景
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
⚠️ 本文档已过时,仅留档备查,请勿删除。该历史任务已落地;当前状态见 `../任务清单.md`。
|
||||||
|
|
||||||
# [P1] 规范转账事件、双边匹配与调拨排除
|
# [P1] 规范转账事件、双边匹配与调拨排除
|
||||||
|
|
||||||
## 背景
|
## 背景
|
||||||
|
|||||||
+12
-12
@@ -1,29 +1,29 @@
|
|||||||
# 任务清单
|
# 任务清单
|
||||||
|
|
||||||
最后核对:2026-08-23。状态以当前代码和已合并提交为准。
|
最后核对:2026-08-30。状态以当前代码和已合并提交为准。
|
||||||
|
|
||||||
## 正在做
|
## 正在做
|
||||||
|
|
||||||
- 当前没有已确认正在进行的业务功能开发。下一项工作开始前,先在此处写明负责人、范围和验收标准。
|
- HEL-270 上线前总验收(总工):代码审核、测试环境部署、备份恢复与回滚演练、边界自动化证据。
|
||||||
|
|
||||||
## 已做完
|
## 已做完
|
||||||
|
|
||||||
- 六类银行流水模板识别与解析。
|
- 六类银行流水模板识别与解析。
|
||||||
- 数据库迁移、不可变原始证据、导入批次和重复导入处理。
|
- 数据库迁移(至版本 10)、不可变原始证据、导入批次和重复导入处理;文件库 WAL。
|
||||||
- 管理员/公司用户登录、密码策略、会话、限流、服务端公司隔离和审计。
|
- 管理员/公司用户登录、密码策略、会话清理、限流、服务端公司隔离和审计。
|
||||||
- 动态公司、用户、银行账户、别名与账户审核流程。
|
- 动态公司、用户、银行账户、别名与账户审核流程。
|
||||||
- 导入接口加固、逐工作表确认、失败诊断和导出。
|
- 导入接口加固、逐工作表确认、失败诊断和导出。
|
||||||
- 规范转账事件、双边匹配、同公司调拨排除与个人过账映射。
|
- 规范转账事件、双边匹配、同公司调拨排除与个人过账映射。
|
||||||
- 登录页视觉融合改版。
|
- 起算日、期初余额、流水覆盖断档检测和无业务校准。
|
||||||
|
- 月结、重开审批、闭期补录、锁账写保护、月报与审计记录。
|
||||||
|
- 服务端流水查询、筛选、分页和可追溯导出;往来查询与手工记录接入真实接口。
|
||||||
|
- 站内提醒与状态流转。
|
||||||
|
- 前端移除演示流水/往来造数和 `localStorage` 业务状态。
|
||||||
|
- 登录页视觉融合改版;月结/重开/审计按 HEL-268 视觉规范落地。
|
||||||
|
- 测试环境部署编排收编到 `deploy/`,含非 root 加固、备份/巡检脚本与运维手册(不在施工员职责内执行上线)。
|
||||||
|
|
||||||
## 还没安排
|
## 还没安排
|
||||||
|
|
||||||
- 公司间余额和四类往来科目的正式计算,已批准手工记录入账,以及从余额逐层查回原始流水。
|
- 正式部署(P4):HTTPS 反代落地、异机备份副本、正式账号交接。覆盖正式环境必须老板明确同意。
|
||||||
- 起算日、期初余额、流水覆盖断档检测和无业务校准。
|
|
||||||
- 月结、重开、调整/冲销审批与审计报告。
|
|
||||||
- 服务端流水查询、筛选、分页和可追溯导出。
|
|
||||||
- 站内提醒与状态流转;外部通知只预留扩展位置,不默认启用。
|
|
||||||
- 前端全面接入真实接口,移除模拟金额、静态业务记录和 `localStorage` 业务状态。
|
|
||||||
- 测试环境之外的运行保障,包括 HTTPS、备份、监控和正式部署方案。
|
|
||||||
|
|
||||||
每完成或新增一项任务,必须在同一次提交里把它从本清单的相应栏目移走或补上,并同步更新 `最新进度.md`。
|
每完成或新增一项任务,必须在同一次提交里把它从本清单的相应栏目移走或补上,并同步更新 `最新进度.md`。
|
||||||
|
|||||||
+12
-9
@@ -1,24 +1,27 @@
|
|||||||
# 最新进度
|
# 最新进度
|
||||||
|
|
||||||
最后核对:2026-08-23。以下“已完成”均以当前代码、数据库迁移、接口和自动化测试为依据,不把页面演示当作真实功能。
|
最后核对:2026-08-30。以下“已完成”均以当前代码、数据库迁移、接口和自动化测试为依据,不把页面演示当作真实功能。
|
||||||
|
|
||||||
## 已经真实完成
|
## 已经真实完成
|
||||||
|
|
||||||
- 支持中信、农行、工行、建行、河南农商行、郑州银行六类样本的 `.xls` / `.xlsx` 流水解析;能识别变动的表头位置和列顺序,并校验余额连续性。
|
- 支持中信、农行、工行、建行、河南农商行、郑州银行六类样本的 `.xls` / `.xlsx` 流水解析;能识别变动的表头位置和列顺序,并校验余额连续性。
|
||||||
- 已有 SQLite 数据库和 5 次版本迁移。原始文件按内容哈希保存,导入批次、工作表、源行和异常都有记录;原始文件、工作表和源行被数据库规则保护,不能直接改或删。
|
- 已有 SQLite 数据库和 10 次版本迁移。原始文件按内容哈希保存,导入批次、工作表、源行和异常都有记录;原始文件、工作表和源行被数据库规则保护,不能直接改或删。文件库启用 WAL。
|
||||||
- 已实现管理员与公司用户登录、首次改密、会话失效、登录失败限流、服务端权限隔离和审计记录。
|
- 已实现管理员与公司用户登录、首次改密、会话失效(过期会话在发新会话时清理)、登录失败限流、服务端权限隔离和审计记录。
|
||||||
- 已实现公司、用户、银行账户、别名等主数据管理;公司提交的银行账户需管理员审核后才能参与上传和识别。
|
- 已实现公司、用户、银行账户、别名等主数据管理;公司提交的银行账户需管理员审核后才能参与上传和识别。
|
||||||
- 已实现导入、逐工作表确认或忽略、失败诊断、重复上传处理和 CSV 导出;未确认的工作表不进入后续处理。
|
- 已实现导入、逐工作表确认或忽略、失败诊断、重复上传处理和 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` 待发布时快进。
|
||||||
- 提醒、完整的服务端查询导出,以及前端彻底移除演示数据和浏览器本地业务状态尚未完成。
|
|
||||||
- 生产部署所需的 HTTPS、反向代理、备份、监控和正式运行保障尚未完成;本项目当前只允许测试环境部署。
|
|
||||||
|
|
||||||
## 最近验证
|
## 最近验证
|
||||||
|
|
||||||
2026-08-23 已运行完整 Python 自动化测试:解析、持久化、认证与权限、导入接口、主数据和双边匹配相关测试均通过。后续修改功能时,必须再次运行完整测试并在本文件记录结果。
|
2026-08-30 已运行完整 Python 自动化测试(`PYTHONPATH=src python -m unittest discover -s tests -v`),覆盖解析、持久化、认证、导入、主数据、匹配、月结/重开/写保护、前端契约与 360/820/1440 布局冒烟(有 Chromium 时)。后续修改功能时必须再次运行完整测试并在本文件记录结果。
|
||||||
|
|||||||
@@ -0,0 +1,186 @@
|
|||||||
|
#!/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()
|
||||||
@@ -0,0 +1,286 @@
|
|||||||
|
#!/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()
|
||||||
@@ -204,6 +204,7 @@ def create_session(
|
|||||||
token = secrets.token_urlsafe(32)
|
token = secrets.token_urlsafe(32)
|
||||||
token_hash = hashlib.sha256(token.encode("utf-8")).hexdigest()
|
token_hash = hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||||
now = datetime.now(timezone.utc)
|
now = datetime.now(timezone.utc)
|
||||||
|
purge_expired_sessions(connection)
|
||||||
with connection:
|
with connection:
|
||||||
connection.execute(
|
connection.execute(
|
||||||
"""
|
"""
|
||||||
@@ -220,6 +221,17 @@ def create_session(
|
|||||||
return token
|
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:
|
def resolve_session(connection: sqlite3.Connection, token: str) -> sqlite3.Row | None:
|
||||||
"""Return the user row for a live session token, else None.
|
"""Return the user row for a live session token, else None.
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,960 @@
|
|||||||
|
"""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 utc_now
|
||||||
|
from . import 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 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 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 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 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 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 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 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)
|
||||||
|
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 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"]),
|
||||||
|
)
|
||||||
|
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}
|
||||||
@@ -0,0 +1,754 @@
|
|||||||
|
"""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
|
||||||
@@ -109,11 +109,46 @@ def _company_rows(connection: sqlite3.Connection) -> list[sqlite3.Row]:
|
|||||||
).fetchall()
|
).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(
|
def company_summaries(
|
||||||
connection: sqlite3.Connection, *, from_date: str, cutoff: str
|
connection: sqlite3.Connection, *, from_date: str, cutoff: str
|
||||||
) -> tuple[list[dict[str, object]], dict[str, object]]:
|
) -> tuple[list[dict[str, object]], dict[str, object]]:
|
||||||
companies = _company_rows(connection)
|
companies = _company_rows(connection)
|
||||||
events = _load_eligible(connection, from_date=from_date, cutoff=cutoff)
|
events = _load_eligible(connection, from_date=from_date, cutoff=cutoff)
|
||||||
|
period_status, period_label = _period_status_for_cutoff(connection, cutoff)
|
||||||
|
|
||||||
debit_total = ZERO
|
debit_total = ZERO
|
||||||
credit_total = ZERO
|
credit_total = ZERO
|
||||||
@@ -125,8 +160,8 @@ def company_summaries(
|
|||||||
"detail_count": 0,
|
"detail_count": 0,
|
||||||
"debit": ZERO,
|
"debit": ZERO,
|
||||||
"credit": ZERO,
|
"credit": ZERO,
|
||||||
"period_status": None,
|
"period_status": period_status,
|
||||||
"period_status_label": "—",
|
"period_status_label": period_label,
|
||||||
}
|
}
|
||||||
|
|
||||||
for event in events:
|
for event in events:
|
||||||
|
|||||||
@@ -846,6 +846,356 @@ MIGRATIONS: tuple[Migration, ...] = (
|
|||||||
DROP TABLE IF EXISTS system_settings;
|
DROP TABLE IF EXISTS system_settings;
|
||||||
""",
|
""",
|
||||||
),
|
),
|
||||||
|
|
||||||
|
Migration(
|
||||||
|
version=8,
|
||||||
|
name="0008_calculation_window",
|
||||||
|
# HEL-194/202: opening balances, coverage gaps, no-business attestations.
|
||||||
|
# Reuses system_settings / system_setting_changes from 0007; does not
|
||||||
|
# recreate them. Extends master_data_changes CHECK and overlays the
|
||||||
|
# calculation_start_date filter onto eligible_intercompany_events.
|
||||||
|
up="""
|
||||||
|
CREATE TABLE closed_periods (
|
||||||
|
year_month TEXT PRIMARY KEY,
|
||||||
|
closed_at TEXT NOT NULL,
|
||||||
|
closed_by INTEGER REFERENCES users (id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE opening_balance_revisions (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
company_id_low INTEGER NOT NULL REFERENCES companies (id),
|
||||||
|
company_id_high INTEGER NOT NULL REFERENCES companies (id),
|
||||||
|
amount TEXT NOT NULL,
|
||||||
|
currency TEXT NOT NULL DEFAULT 'CNY',
|
||||||
|
revision INTEGER NOT NULL,
|
||||||
|
status TEXT NOT NULL
|
||||||
|
CHECK (status IN ('draft', 'confirmed', 'superseded', 'void')),
|
||||||
|
reason TEXT NOT NULL,
|
||||||
|
actor_user_id INTEGER REFERENCES users (id),
|
||||||
|
actor_username TEXT,
|
||||||
|
supersedes_id INTEGER REFERENCES opening_balance_revisions (id),
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
UNIQUE (company_id_low, company_id_high, revision),
|
||||||
|
CHECK (company_id_low < company_id_high)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE coverage_gaps (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
bank_account_id INTEGER NOT NULL REFERENCES bank_accounts (id),
|
||||||
|
gap_start TEXT NOT NULL,
|
||||||
|
gap_end TEXT NOT NULL,
|
||||||
|
gap_kind TEXT NOT NULL CHECK (gap_kind IN ('head', 'mid', 'tail')),
|
||||||
|
status TEXT NOT NULL DEFAULT 'open'
|
||||||
|
CHECK (status IN ('open', 'closed_attested')),
|
||||||
|
first_detected_at TEXT NOT NULL,
|
||||||
|
UNIQUE (bank_account_id, gap_start, gap_end)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE no_business_attestations (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
bank_account_id INTEGER NOT NULL REFERENCES bank_accounts (id),
|
||||||
|
gap_start TEXT NOT NULL,
|
||||||
|
gap_end TEXT NOT NULL,
|
||||||
|
reason TEXT NOT NULL,
|
||||||
|
evidence TEXT,
|
||||||
|
submitted_by INTEGER REFERENCES users (id),
|
||||||
|
company_id INTEGER NOT NULL REFERENCES companies (id),
|
||||||
|
status TEXT NOT NULL DEFAULT 'pending'
|
||||||
|
CHECK (status IN ('pending', 'approved', 'rejected')),
|
||||||
|
reviewed_by INTEGER REFERENCES users (id),
|
||||||
|
reviewed_at TEXT,
|
||||||
|
review_reason TEXT,
|
||||||
|
created_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_opening_balance_pair ON opening_balance_revisions (company_id_low, company_id_high);
|
||||||
|
CREATE INDEX idx_coverage_gaps_account ON coverage_gaps (bank_account_id);
|
||||||
|
CREATE INDEX idx_attestations_company ON no_business_attestations (company_id);
|
||||||
|
|
||||||
|
CREATE TABLE master_data_changes_new (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
entity_type TEXT NOT NULL
|
||||||
|
CHECK (entity_type IN (
|
||||||
|
'company', 'user', 'bank_account', 'account_alias',
|
||||||
|
'personal_transit_mapping', 'system_setting', 'opening_balance'
|
||||||
|
)),
|
||||||
|
entity_id INTEGER NOT NULL,
|
||||||
|
action TEXT NOT NULL,
|
||||||
|
before_json TEXT,
|
||||||
|
after_json TEXT,
|
||||||
|
reason TEXT,
|
||||||
|
actor_user_id INTEGER REFERENCES users (id),
|
||||||
|
actor_username TEXT,
|
||||||
|
created_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
INSERT INTO master_data_changes_new SELECT * FROM master_data_changes;
|
||||||
|
DROP TABLE master_data_changes;
|
||||||
|
ALTER TABLE master_data_changes_new RENAME TO master_data_changes;
|
||||||
|
|
||||||
|
DROP VIEW IF EXISTS eligible_intercompany_events;
|
||||||
|
CREATE VIEW eligible_intercompany_events AS
|
||||||
|
SELECT e.id AS event_id, d.id AS decision_id, d.revision AS revision,
|
||||||
|
d.effective_at AS effective_at, d.amount AS amount, d.currency AS currency,
|
||||||
|
payer.company_id AS payer_company_id,
|
||||||
|
payer.bank_account_id AS payer_account_id,
|
||||||
|
payee.company_id AS payee_company_id,
|
||||||
|
payee.bank_account_id AS payee_account_id,
|
||||||
|
d.pairing AS pairing, d.rule_version AS rule_version,
|
||||||
|
(SELECT COUNT(*) FROM transfer_decision_observations o
|
||||||
|
WHERE o.decision_id = d.id) AS evidence_count
|
||||||
|
FROM current_transfer_decisions c
|
||||||
|
JOIN canonical_transfer_events e ON e.id = c.event_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 = 'intercompany'
|
||||||
|
AND (d.pairing = 'paired' OR d.locked = 1)
|
||||||
|
AND (
|
||||||
|
(SELECT value FROM system_settings WHERE key = 'calculation_start_date') IS NULL
|
||||||
|
OR substr(d.effective_at, 1, 10) >= (
|
||||||
|
SELECT value FROM system_settings WHERE key = 'calculation_start_date'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
""",
|
||||||
|
down="""
|
||||||
|
DROP VIEW IF EXISTS eligible_intercompany_events;
|
||||||
|
CREATE VIEW eligible_intercompany_events AS
|
||||||
|
SELECT e.id AS event_id, d.id AS decision_id, d.revision AS revision,
|
||||||
|
d.effective_at AS effective_at, d.amount AS amount, d.currency AS currency,
|
||||||
|
payer.company_id AS payer_company_id,
|
||||||
|
payer.bank_account_id AS payer_account_id,
|
||||||
|
payee.company_id AS payee_company_id,
|
||||||
|
payee.bank_account_id AS payee_account_id,
|
||||||
|
d.pairing AS pairing, d.rule_version AS rule_version,
|
||||||
|
(SELECT COUNT(*) FROM transfer_decision_observations o
|
||||||
|
WHERE o.decision_id = d.id) AS evidence_count
|
||||||
|
FROM current_transfer_decisions c
|
||||||
|
JOIN canonical_transfer_events e ON e.id = c.event_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 = 'intercompany'
|
||||||
|
AND (d.pairing = 'paired' OR d.locked = 1);
|
||||||
|
|
||||||
|
CREATE TABLE master_data_changes_new (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
entity_type TEXT NOT NULL
|
||||||
|
CHECK (entity_type IN (
|
||||||
|
'company', 'user', 'bank_account', 'account_alias',
|
||||||
|
'personal_transit_mapping'
|
||||||
|
)),
|
||||||
|
entity_id INTEGER NOT NULL,
|
||||||
|
action TEXT NOT NULL,
|
||||||
|
before_json TEXT,
|
||||||
|
after_json TEXT,
|
||||||
|
reason TEXT,
|
||||||
|
actor_user_id INTEGER REFERENCES users (id),
|
||||||
|
actor_username TEXT,
|
||||||
|
created_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
INSERT INTO master_data_changes_new SELECT * FROM master_data_changes
|
||||||
|
WHERE entity_type NOT IN ('system_setting', 'opening_balance');
|
||||||
|
DROP TABLE master_data_changes;
|
||||||
|
ALTER TABLE master_data_changes_new RENAME TO master_data_changes;
|
||||||
|
|
||||||
|
DROP INDEX IF EXISTS idx_attestations_company;
|
||||||
|
DROP INDEX IF EXISTS idx_coverage_gaps_account;
|
||||||
|
DROP INDEX IF EXISTS idx_opening_balance_pair;
|
||||||
|
DROP TABLE IF EXISTS no_business_attestations;
|
||||||
|
DROP TABLE IF EXISTS coverage_gaps;
|
||||||
|
DROP TABLE IF EXISTS opening_balance_revisions;
|
||||||
|
DROP TABLE IF EXISTS closed_periods;
|
||||||
|
""",
|
||||||
|
),
|
||||||
|
|
||||||
|
Migration(
|
||||||
|
version=9,
|
||||||
|
name="0009_reminders_engine",
|
||||||
|
# HEL-195/215 auto-reminder engine. The old manual reminders table
|
||||||
|
# from 0007 is preserved verbatim under reminders_legacy_manual so
|
||||||
|
# existing test-env history stays queryable; the new engine uses its
|
||||||
|
# own append-only reminders/reminder_events schema.
|
||||||
|
up="""
|
||||||
|
ALTER TABLE reminders RENAME TO reminders_legacy_manual;
|
||||||
|
DROP INDEX IF EXISTS idx_reminders_company;
|
||||||
|
CREATE INDEX idx_reminders_legacy_company
|
||||||
|
ON reminders_legacy_manual (company_id);
|
||||||
|
|
||||||
|
CREATE TABLE reminder_settings (
|
||||||
|
key TEXT PRIMARY KEY,
|
||||||
|
value TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO reminder_settings (key, value, updated_at) VALUES
|
||||||
|
('monthly_start_day', '5', datetime('now')),
|
||||||
|
('gap_days', '5', datetime('now')),
|
||||||
|
('scan_time', '08:00', datetime('now'));
|
||||||
|
|
||||||
|
CREATE TABLE reminders (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
company_id INTEGER NOT NULL REFERENCES companies (id),
|
||||||
|
rule_key TEXT NOT NULL CHECK (rule_key IN (
|
||||||
|
'unsubmitted', 'gap', 'pending_review', 'manual'
|
||||||
|
)),
|
||||||
|
dedupe_key TEXT NOT NULL UNIQUE,
|
||||||
|
rule_params TEXT NOT NULL DEFAULT '{}',
|
||||||
|
title TEXT NOT NULL,
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
deadline TEXT,
|
||||||
|
source TEXT NOT NULL CHECK (source IN ('auto', 'manual')),
|
||||||
|
status TEXT NOT NULL DEFAULT 'open'
|
||||||
|
CHECK (status IN ('open', 'acknowledged', 'resolved')),
|
||||||
|
send_count INTEGER NOT NULL DEFAULT 0,
|
||||||
|
first_sent_at TEXT,
|
||||||
|
last_sent_at TEXT,
|
||||||
|
created_by TEXT NOT NULL,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
action_link TEXT
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_reminders_company ON reminders (company_id);
|
||||||
|
CREATE INDEX idx_reminders_status ON reminders (status);
|
||||||
|
|
||||||
|
CREATE TABLE reminder_events (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
reminder_id INTEGER NOT NULL REFERENCES reminders (id),
|
||||||
|
event_type TEXT NOT NULL CHECK (event_type IN (
|
||||||
|
'sent', 'acknowledged', 'resolved', 'escalated'
|
||||||
|
)),
|
||||||
|
actor TEXT NOT NULL,
|
||||||
|
detail TEXT,
|
||||||
|
created_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_reminder_events_reminder ON reminder_events (reminder_id);
|
||||||
|
|
||||||
|
CREATE TRIGGER reminder_events_no_update BEFORE UPDATE ON reminder_events
|
||||||
|
BEGIN SELECT RAISE (ABORT, 'reminder_events rows are append-only'); END;
|
||||||
|
CREATE TRIGGER reminder_events_no_delete BEFORE DELETE ON reminder_events
|
||||||
|
BEGIN SELECT RAISE (ABORT, 'reminder_events rows are append-only'); END;
|
||||||
|
CREATE TRIGGER reminders_no_delete BEFORE DELETE ON reminders
|
||||||
|
BEGIN SELECT RAISE (ABORT, 'reminders rows are immutable history'); END;
|
||||||
|
""",
|
||||||
|
down="""
|
||||||
|
DROP TRIGGER IF EXISTS reminders_no_delete;
|
||||||
|
DROP TRIGGER IF EXISTS reminder_events_no_delete;
|
||||||
|
DROP TRIGGER IF EXISTS reminder_events_no_update;
|
||||||
|
DROP INDEX IF EXISTS idx_reminder_events_reminder;
|
||||||
|
DROP TABLE IF EXISTS reminder_events;
|
||||||
|
DROP INDEX IF EXISTS idx_reminders_status;
|
||||||
|
DROP INDEX IF EXISTS idx_reminders_company;
|
||||||
|
DROP TABLE IF EXISTS reminders;
|
||||||
|
DROP TABLE IF EXISTS reminder_settings;
|
||||||
|
DROP INDEX IF EXISTS idx_reminders_legacy_company;
|
||||||
|
ALTER TABLE reminders_legacy_manual RENAME TO reminders;
|
||||||
|
CREATE INDEX idx_reminders_company ON reminders (company_id);
|
||||||
|
""",
|
||||||
|
),
|
||||||
|
|
||||||
|
Migration(
|
||||||
|
version=10,
|
||||||
|
name="00010_period_close_reopen",
|
||||||
|
# HEL-196/269: monthly close snapshots, reopen approval, late arrivals
|
||||||
|
# after lock, and an append-only period audit trail. closed_periods
|
||||||
|
# (from 0008) remains the live lock index; this table is the versioned
|
||||||
|
# report history.
|
||||||
|
up="""
|
||||||
|
CREATE TABLE period_close_runs (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
year_month TEXT NOT NULL,
|
||||||
|
version INTEGER NOT NULL,
|
||||||
|
status TEXT NOT NULL CHECK (status IN (
|
||||||
|
'pending', 'closing', 'closed', 'failed', 'reopened'
|
||||||
|
)),
|
||||||
|
snapshot_json TEXT,
|
||||||
|
snapshot_hash TEXT,
|
||||||
|
report_no TEXT,
|
||||||
|
blockers_json TEXT,
|
||||||
|
fail_reason TEXT,
|
||||||
|
closed_at TEXT,
|
||||||
|
closed_by INTEGER REFERENCES users (id),
|
||||||
|
closed_by_username TEXT,
|
||||||
|
reopen_window_end TEXT,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL,
|
||||||
|
UNIQUE (year_month, version)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE period_reopen_requests (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
period_close_id INTEGER NOT NULL REFERENCES period_close_runs (id),
|
||||||
|
year_month TEXT NOT NULL,
|
||||||
|
reason TEXT NOT NULL,
|
||||||
|
companies_note TEXT,
|
||||||
|
window_days INTEGER NOT NULL DEFAULT 3,
|
||||||
|
status TEXT NOT NULL CHECK (status IN ('pending', 'approved', 'rejected')),
|
||||||
|
requester_id INTEGER REFERENCES users (id),
|
||||||
|
requester_username TEXT,
|
||||||
|
requested_at TEXT NOT NULL,
|
||||||
|
reviewer_id INTEGER REFERENCES users (id),
|
||||||
|
reviewer_username TEXT,
|
||||||
|
reviewed_at TEXT,
|
||||||
|
review_comment TEXT,
|
||||||
|
before_json TEXT,
|
||||||
|
after_json TEXT
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE period_late_arrivals (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
year_month TEXT NOT NULL,
|
||||||
|
source_row_id INTEGER NOT NULL UNIQUE REFERENCES source_rows (id),
|
||||||
|
status TEXT NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'absorbed')),
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
actor_user_id INTEGER REFERENCES users (id),
|
||||||
|
actor_username TEXT
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE period_audit_events (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
created_at TEXT NOT NULL,
|
||||||
|
actor_user_id INTEGER REFERENCES users (id),
|
||||||
|
actor_username TEXT,
|
||||||
|
actor_role TEXT,
|
||||||
|
action TEXT NOT NULL,
|
||||||
|
year_month TEXT,
|
||||||
|
object_label TEXT,
|
||||||
|
reason TEXT,
|
||||||
|
before_json TEXT,
|
||||||
|
after_json TEXT,
|
||||||
|
report_no TEXT,
|
||||||
|
related_id INTEGER
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_period_close_month ON period_close_runs (year_month, version);
|
||||||
|
CREATE INDEX idx_period_reopen_status ON period_reopen_requests (status, year_month);
|
||||||
|
CREATE INDEX idx_period_audit_created ON period_audit_events (created_at);
|
||||||
|
|
||||||
|
CREATE TRIGGER period_audit_no_update BEFORE UPDATE ON period_audit_events
|
||||||
|
BEGIN SELECT RAISE (ABORT, 'period_audit_events rows are append-only'); END;
|
||||||
|
CREATE TRIGGER period_audit_no_delete BEFORE DELETE ON period_audit_events
|
||||||
|
BEGIN SELECT RAISE (ABORT, 'period_audit_events rows are immutable history'); END;
|
||||||
|
CREATE TRIGGER period_close_snapshot_no_update BEFORE UPDATE ON period_close_runs
|
||||||
|
WHEN OLD.snapshot_json IS NOT NULL AND NEW.snapshot_json IS NOT OLD.snapshot_json
|
||||||
|
BEGIN SELECT RAISE (ABORT, 'closed snapshots cannot be rewritten'); END;
|
||||||
|
""",
|
||||||
|
down="""
|
||||||
|
DROP TRIGGER IF EXISTS period_close_snapshot_no_update;
|
||||||
|
DROP TRIGGER IF EXISTS period_audit_no_delete;
|
||||||
|
DROP TRIGGER IF EXISTS period_audit_no_update;
|
||||||
|
DROP INDEX IF EXISTS idx_period_audit_created;
|
||||||
|
DROP INDEX IF EXISTS idx_period_reopen_status;
|
||||||
|
DROP INDEX IF EXISTS idx_period_close_month;
|
||||||
|
DROP TABLE IF EXISTS period_audit_events;
|
||||||
|
DROP TABLE IF EXISTS period_late_arrivals;
|
||||||
|
DROP TABLE IF EXISTS period_reopen_requests;
|
||||||
|
DROP TABLE IF EXISTS period_close_runs;
|
||||||
|
""",
|
||||||
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -858,6 +1208,10 @@ def connect(path: str | Path) -> sqlite3.Connection:
|
|||||||
connection = sqlite3.connect(str(db_path), timeout=30)
|
connection = sqlite3.connect(str(db_path), timeout=30)
|
||||||
connection.row_factory = sqlite3.Row
|
connection.row_factory = sqlite3.Row
|
||||||
connection.execute("PRAGMA foreign_keys = ON")
|
connection.execute("PRAGMA foreign_keys = ON")
|
||||||
|
# WAL lowers write-lock contention on file databases. Skip :memory:
|
||||||
|
# because WAL requires a real file.
|
||||||
|
if str(db_path) != ":memory:":
|
||||||
|
connection.execute("PRAGMA journal_mode=WAL")
|
||||||
return connection
|
return connection
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,172 @@
|
|||||||
|
"""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,
|
||||||
|
}
|
||||||
@@ -1523,7 +1523,7 @@ def unresolved_amounts(
|
|||||||
count as unresolved; paired intercompany, same-company and external events
|
count as unresolved; paired intercompany, same-company and external events
|
||||||
are resolved classifications and never appear here.
|
are resolved classifications and never appear here.
|
||||||
"""
|
"""
|
||||||
cutoff_where = "AND d.effective_at <= ?" if cutoff else ""
|
cutoff_where = "AND substr(d.effective_at, 1, 10) <= ?" if cutoff else ""
|
||||||
params: list[object] = []
|
params: list[object] = []
|
||||||
if cutoff:
|
if cutoff:
|
||||||
params.append(cutoff)
|
params.append(cutoff)
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,757 @@
|
|||||||
|
"""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,20 +1,20 @@
|
|||||||
"""System settings and reminder item generation.
|
"""System settings.
|
||||||
|
|
||||||
System-wide parameters (closing day, global start date, auto-reminder toggle
|
System-wide parameters (closing day, global start date, auto-reminder toggle
|
||||||
and lead days) are persisted in ``system_settings`` with an append-only
|
and lead days) are persisted in ``system_settings`` with an append-only
|
||||||
``system_setting_changes`` trail. Reminder pending items are derived from real
|
``system_setting_changes`` trail. The auto-reminder engine itself lives in
|
||||||
backend data (per-sheet reviews, bank accounts, canonical transfer decisions)
|
``reminders.py`` (HEL-195); this module only owns the settings store.
|
||||||
rather than hard-coded rosters.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import re
|
import re
|
||||||
import sqlite3
|
import sqlite3
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime
|
||||||
|
|
||||||
from .db import utc_now
|
from .db import utc_now
|
||||||
|
|
||||||
|
|
||||||
# Defaults are applied when a key is absent; the value type is always string.
|
# Defaults are applied when a key is absent; the value type is always string.
|
||||||
DEFAULT_SETTINGS: dict[str, str] = {
|
DEFAULT_SETTINGS: dict[str, str] = {
|
||||||
"closing_day": "5",
|
"closing_day": "5",
|
||||||
@@ -131,179 +131,3 @@ def update_settings(
|
|||||||
# ----------------------------------------------------------------------
|
# ----------------------------------------------------------------------
|
||||||
# Reminder pending items
|
# Reminder pending items
|
||||||
# ----------------------------------------------------------------------
|
# ----------------------------------------------------------------------
|
||||||
|
|
||||||
def _current_period() -> tuple[str, str]:
|
|
||||||
"""Return the current calendar month as ``(start, end_exclusive)`` dates."""
|
|
||||||
today = datetime.now(timezone.utc)
|
|
||||||
start = today.strftime("%Y-%m-01")
|
|
||||||
year, month = today.year, today.month
|
|
||||||
if month == 12:
|
|
||||||
end = f"{year + 1}-01-01"
|
|
||||||
else:
|
|
||||||
end = f"{year}-{month + 1:02d}-01"
|
|
||||||
return start, end
|
|
||||||
|
|
||||||
|
|
||||||
def pending_items(connection: sqlite3.Connection, company_id: int) -> list[dict[str, str]]:
|
|
||||||
"""Derive the list of pending reminder items for one company."""
|
|
||||||
items: list[dict[str, str]] = []
|
|
||||||
|
|
||||||
company = connection.execute(
|
|
||||||
"SELECT id, name FROM companies WHERE id = ?", (company_id,)
|
|
||||||
).fetchone()
|
|
||||||
if company is None:
|
|
||||||
return items
|
|
||||||
|
|
||||||
period_start, _ = _current_period()
|
|
||||||
|
|
||||||
# 1) 本月流水未提交:有已启用账户,但本月没有任何已确认的工作表。
|
|
||||||
active_accounts = connection.execute(
|
|
||||||
"""
|
|
||||||
SELECT id, account_number FROM bank_accounts
|
|
||||||
WHERE company_id = ? AND status = 'active'
|
|
||||||
""",
|
|
||||||
(company_id,),
|
|
||||||
).fetchall()
|
|
||||||
confirmed_this_period = connection.execute(
|
|
||||||
"""
|
|
||||||
SELECT COUNT(*) AS n
|
|
||||||
FROM sheet_reviews rv
|
|
||||||
JOIN import_batches b ON b.id = rv.import_batch_id
|
|
||||||
WHERE b.company_id = ? AND rv.review_status = 'confirmed'
|
|
||||||
AND rv.sheet_batch_id IN (
|
|
||||||
SELECT id FROM sheet_batches s
|
|
||||||
WHERE s.period_end >= ?
|
|
||||||
)
|
|
||||||
""",
|
|
||||||
(company_id, period_start),
|
|
||||||
).fetchone()["n"]
|
|
||||||
if active_accounts and confirmed_this_period == 0:
|
|
||||||
items.append(
|
|
||||||
{
|
|
||||||
"kind": "流水未提交",
|
|
||||||
"content": "本月各银行账户流水尚未提交,请尽快上传本月银行流水。",
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
# 2) 待确认工作表:仍有未确认的解析结果。
|
|
||||||
pending_sheets = connection.execute(
|
|
||||||
"""
|
|
||||||
SELECT COUNT(*) AS n
|
|
||||||
FROM sheet_reviews rv
|
|
||||||
JOIN import_batches b ON b.id = rv.import_batch_id
|
|
||||||
WHERE b.company_id = ? AND rv.review_status = 'pending'
|
|
||||||
""",
|
|
||||||
(company_id,),
|
|
||||||
).fetchone()["n"]
|
|
||||||
if pending_sheets:
|
|
||||||
items.append(
|
|
||||||
{
|
|
||||||
"kind": "待确认工作表",
|
|
||||||
"content": f"有 {pending_sheets} 个导入工作表尚未确认,请核对后确认。",
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
# 3) 待审核账户登记:处于待复核状态的银行账户。
|
|
||||||
pending_accounts = connection.execute(
|
|
||||||
"""
|
|
||||||
SELECT COUNT(*) AS n FROM bank_accounts
|
|
||||||
WHERE company_id = ? AND status = 'pending'
|
|
||||||
""",
|
|
||||||
(company_id,),
|
|
||||||
).fetchone()["n"]
|
|
||||||
if pending_accounts:
|
|
||||||
items.append(
|
|
||||||
{
|
|
||||||
"kind": "账户登记",
|
|
||||||
"content": f"有 {pending_accounts} 个银行账户登记待审核。",
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
# 4) 待确认往来事项:尚未解决的往来匹配。
|
|
||||||
pending_transfers = connection.execute(
|
|
||||||
"""
|
|
||||||
SELECT COUNT(*) AS n
|
|
||||||
FROM current_transfer_decisions c
|
|
||||||
JOIN transfer_match_decisions d ON d.id = c.decision_id
|
|
||||||
JOIN transfer_decision_participants p
|
|
||||||
ON p.decision_id = d.id AND p.company_id = ?
|
|
||||||
WHERE d.classification IN ('unresolved', 'needs_review')
|
|
||||||
""",
|
|
||||||
(company_id,),
|
|
||||||
).fetchone()["n"]
|
|
||||||
if pending_transfers:
|
|
||||||
items.append(
|
|
||||||
{
|
|
||||||
"kind": "往来待确认",
|
|
||||||
"content": f"有 {pending_transfers} 项往来流水待确认,请核对对方银行流水佐证。",
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
return items
|
|
||||||
|
|
||||||
|
|
||||||
def send_reminders(
|
|
||||||
connection: sqlite3.Connection,
|
|
||||||
company_id: int,
|
|
||||||
actor: sqlite3.Row,
|
|
||||||
) -> tuple[list[dict[str, str]], str | None]:
|
|
||||||
"""Create reminder rows for a company's pending items.
|
|
||||||
|
|
||||||
Returns ``(created, deadline)``. ``created`` is the list of persisted
|
|
||||||
reminder payloads; ``deadline`` is derived from the closing-day setting.
|
|
||||||
"""
|
|
||||||
items = pending_items(connection, company_id)
|
|
||||||
if not items:
|
|
||||||
return [], None
|
|
||||||
|
|
||||||
settings = get_settings(connection)
|
|
||||||
try:
|
|
||||||
closing_day = int(settings["closing_day"])
|
|
||||||
except ValueError:
|
|
||||||
closing_day = 5
|
|
||||||
today = datetime.now(timezone.utc)
|
|
||||||
# Deadline: next month's closing day (current month if today is before it).
|
|
||||||
if today.day < closing_day:
|
|
||||||
deadline = today.strftime(f"%Y-%m-{closing_day:02d}")
|
|
||||||
else:
|
|
||||||
year, month = today.year, today.month
|
|
||||||
if month == 12:
|
|
||||||
year, month = year + 1, 1
|
|
||||||
else:
|
|
||||||
month += 1
|
|
||||||
deadline = f"{year}-{month:02d}-{closing_day:02d}"
|
|
||||||
|
|
||||||
created: list[dict[str, str]] = []
|
|
||||||
with connection:
|
|
||||||
for item in items:
|
|
||||||
cursor = connection.execute(
|
|
||||||
"""
|
|
||||||
INSERT INTO reminders (
|
|
||||||
company_id, kind, content, deadline, source,
|
|
||||||
actor_user_id, actor_username, created_at
|
|
||||||
) VALUES (?, ?, ?, ?, 'manual', ?, ?, ?)
|
|
||||||
""",
|
|
||||||
(
|
|
||||||
company_id,
|
|
||||||
item["kind"],
|
|
||||||
item["content"],
|
|
||||||
deadline,
|
|
||||||
actor["id"],
|
|
||||||
actor["username"],
|
|
||||||
utc_now(),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
created.append(
|
|
||||||
{
|
|
||||||
"id": cursor.lastrowid,
|
|
||||||
"company_id": company_id,
|
|
||||||
"kind": item["kind"],
|
|
||||||
"content": item["content"],
|
|
||||||
"deadline": deadline,
|
|
||||||
"source": "manual",
|
|
||||||
"status": "unread",
|
|
||||||
"actor_username": actor["username"],
|
|
||||||
"created_at": utc_now(),
|
|
||||||
}
|
|
||||||
)
|
|
||||||
return created, deadline
|
|
||||||
|
|||||||
@@ -0,0 +1,593 @@
|
|||||||
|
"""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"])
|
||||||
|
|
||||||
|
|
||||||
|
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()
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
"""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=15", 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()
|
||||||
@@ -0,0 +1,500 @@
|
|||||||
|
"""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()
|
||||||
@@ -0,0 +1,362 @@
|
|||||||
|
"""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()
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
"""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=7", html)
|
||||||
|
self.assertIn("app.js?v=15", 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()
|
||||||
@@ -0,0 +1,518 @@
|
|||||||
|
"""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()
|
||||||
@@ -0,0 +1,417 @@
|
|||||||
|
"""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()
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
"""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_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()
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
"""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()
|
||||||
@@ -41,7 +41,7 @@ class PersistenceTestCase(unittest.TestCase):
|
|||||||
class MigrationTests(PersistenceTestCase):
|
class MigrationTests(PersistenceTestCase):
|
||||||
def test_migrate_creates_schema_and_is_idempotent(self) -> None:
|
def test_migrate_creates_schema_and_is_idempotent(self) -> None:
|
||||||
first = applied_versions(self.connection)
|
first = applied_versions(self.connection)
|
||||||
self.assertEqual([1, 2, 3, 4, 5, 6, 7], first)
|
self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], first)
|
||||||
self.assertEqual([], migrate(self.connection))
|
self.assertEqual([], migrate(self.connection))
|
||||||
self.assertEqual(first, applied_versions(self.connection))
|
self.assertEqual(first, applied_versions(self.connection))
|
||||||
tables = {
|
tables = {
|
||||||
@@ -84,20 +84,28 @@ class MigrationTests(PersistenceTestCase):
|
|||||||
"ledger_subject_suggestions",
|
"ledger_subject_suggestions",
|
||||||
"system_settings",
|
"system_settings",
|
||||||
"system_setting_changes",
|
"system_setting_changes",
|
||||||
"reminders",
|
"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",
|
"schema_migrations",
|
||||||
):
|
):
|
||||||
self.assertIn(table, tables)
|
self.assertIn(table, tables)
|
||||||
|
|
||||||
def test_rollback_removes_schema_and_forward_rebuilds_it(self) -> None:
|
def test_rollback_removes_schema_and_forward_rebuilds_it(self) -> None:
|
||||||
self.assertEqual([7, 6, 5, 4, 3, 2, 1], rollback(self.connection, 0))
|
self.assertEqual([10, 9, 8, 7, 6, 5, 4, 3, 2, 1], rollback(self.connection, 0))
|
||||||
self.assertEqual([], applied_versions(self.connection))
|
self.assertEqual([], applied_versions(self.connection))
|
||||||
remaining = self.connection.execute(
|
remaining = self.connection.execute(
|
||||||
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'source_rows'"
|
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'source_rows'"
|
||||||
).fetchone()
|
).fetchone()
|
||||||
self.assertIsNone(remaining)
|
self.assertIsNone(remaining)
|
||||||
self.assertEqual([1, 2, 3, 4, 5, 6, 7], migrate(self.connection))
|
self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], migrate(self.connection))
|
||||||
self.assertEqual([1, 2, 3, 4, 5, 6, 7], applied_versions(self.connection))
|
self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], applied_versions(self.connection))
|
||||||
|
|
||||||
def test_rollback_to_4_keeps_bank_evidence_and_drops_event_layer(self) -> None:
|
def test_rollback_to_4_keeps_bank_evidence_and_drops_event_layer(self) -> None:
|
||||||
self.import_sample()
|
self.import_sample()
|
||||||
@@ -105,7 +113,7 @@ class MigrationTests(PersistenceTestCase):
|
|||||||
"SELECT COUNT(*) AS n FROM source_rows"
|
"SELECT COUNT(*) AS n FROM source_rows"
|
||||||
).fetchone()["n"]
|
).fetchone()["n"]
|
||||||
self.assertGreater(row_count, 0)
|
self.assertGreater(row_count, 0)
|
||||||
self.assertEqual([7, 6, 5], rollback(self.connection, 4))
|
self.assertEqual([10, 9, 8, 7, 6, 5], rollback(self.connection, 4))
|
||||||
# The pre-migration evidence and schema are untouched.
|
# The pre-migration evidence and schema are untouched.
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
row_count,
|
row_count,
|
||||||
|
|||||||
@@ -0,0 +1,495 @@
|
|||||||
|
"""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(10, 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)
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
"""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=10", html)
|
||||||
|
self.assertIn("app.js?v=15", 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 = css[block_start:]
|
||||||
|
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=15", 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()
|
||||||
@@ -287,6 +287,8 @@ class ServerAuthMatrixTests(unittest.TestCase):
|
|||||||
lambda: anon.get("/api/admin/users"),
|
lambda: anon.get("/api/admin/users"),
|
||||||
lambda: anon.get("/api/admin/companies"),
|
lambda: anon.get("/api/admin/companies"),
|
||||||
lambda: anon.get("/api/admin/audit-log"),
|
lambda: anon.get("/api/admin/audit-log"),
|
||||||
|
lambda: anon.get("/api/admin/reminders"),
|
||||||
|
lambda: anon.get("/api/company/reminders"),
|
||||||
lambda: anon.get("/api/me"),
|
lambda: anon.get("/api/me"),
|
||||||
):
|
):
|
||||||
status, _, data = method_check()
|
status, _, data = method_check()
|
||||||
@@ -387,6 +389,10 @@ class ServerAuthMatrixTests(unittest.TestCase):
|
|||||||
lambda: self.cashier_a.request("POST", "/api/admin/users/1/enable"),
|
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.request("POST", "/api/admin/users/1/reset-password"),
|
||||||
lambda: self.cashier_a.get("/api/admin/audit-log"),
|
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:
|
for call in calls:
|
||||||
status, _, data = call()
|
status, _, data = call()
|
||||||
@@ -557,6 +563,28 @@ class ServerAuthMatrixTests(unittest.TestCase):
|
|||||||
self.assertNotIn(password, row["detail"] or "")
|
self.assertNotIn(password, row["detail"] or "")
|
||||||
self.assertNotIn(password, row["target"] 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__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -166,28 +166,6 @@ class SettingsAndRemindersTests(unittest.TestCase):
|
|||||||
self.assertNotEqual(rows[0]["before_value"], rows[0]["after_value"])
|
self.assertNotEqual(rows[0]["before_value"], rows[0]["after_value"])
|
||||||
self.assertEqual("group-admin", rows[0]["actor_username"])
|
self.assertEqual("group-admin", rows[0]["actor_username"])
|
||||||
|
|
||||||
def test_reminder_pending_and_send(self) -> None:
|
|
||||||
status, data = self.admin.get(
|
|
||||||
f"/api/admin/reminders/pending?company_id={self.company_id}"
|
|
||||||
)
|
|
||||||
self.assertEqual(200, status, data)
|
|
||||||
items = as_json(data)["items"]
|
|
||||||
self.assertTrue(items)
|
|
||||||
|
|
||||||
status, data = self.admin.post_json(
|
|
||||||
"/api/admin/reminders/send", {"company_id": self.company_id}
|
|
||||||
)
|
|
||||||
self.assertEqual(200, status, data)
|
|
||||||
payload = as_json(data)
|
|
||||||
self.assertGreaterEqual(len(payload["reminders"]), 1)
|
|
||||||
self.assertTrue(payload["deadline"])
|
|
||||||
|
|
||||||
status, data = self.admin.get("/api/admin/reminders")
|
|
||||||
self.assertEqual(200, status)
|
|
||||||
history = as_json(data)["reminders"]
|
|
||||||
self.assertGreaterEqual(len(history), 1)
|
|
||||||
self.assertEqual(self.company_id, history[0]["company_id"])
|
|
||||||
|
|
||||||
def test_company_user_forbidden_on_settings_and_reminders(self) -> None:
|
def test_company_user_forbidden_on_settings_and_reminders(self) -> None:
|
||||||
# A company user must not be able to read or write admin settings.
|
# A company user must not be able to read or write admin settings.
|
||||||
status, data = self.admin.post_json(
|
status, data = self.admin.post_json(
|
||||||
|
|||||||
+356
-90
@@ -5,7 +5,7 @@
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<meta name="description" content="金牛集团管理端" />
|
<meta name="description" content="金牛集团管理端" />
|
||||||
<title>管理端 · 金牛集团</title>
|
<title>管理端 · 金牛集团</title>
|
||||||
<link rel="stylesheet" href="design-system.css?v=8" />
|
<link rel="stylesheet" href="design-system.css?v=10" />
|
||||||
</head>
|
</head>
|
||||||
<body data-portal="admin">
|
<body data-portal="admin">
|
||||||
<a class="skip-link" href="#main-content">跳到主要内容</a>
|
<a class="skip-link" href="#main-content">跳到主要内容</a>
|
||||||
@@ -25,6 +25,7 @@
|
|||||||
<div class="nav-group">基础与结账</div>
|
<div class="nav-group">基础与结账</div>
|
||||||
<a data-view="companies" href="#companies"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M4 21V8l8-5 8 5v13"/><path d="M9 21v-6h6v6"/></svg><span class="nav-label">公司与账号</span></a>
|
<a data-view="companies" href="#companies"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M4 21V8l8-5 8 5v13"/><path d="M9 21v-6h6v6"/></svg><span class="nav-label">公司与账号</span></a>
|
||||||
<a data-view="settings" href="#settings"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><circle cx="12" cy="12" r="8.5"/><path d="M12 7v5l3.5 2"/></svg><span class="nav-label">结账与期初</span></a>
|
<a data-view="settings" href="#settings"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><circle cx="12" cy="12" r="8.5"/><path d="M12 7v5l3.5 2"/></svg><span class="nav-label">结账与期初</span></a>
|
||||||
|
<a data-view="period-audit" href="#period-audit"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M12 8v5l3 1.5"/><circle cx="12" cy="12" r="8.5"/></svg><span class="nav-label">审计记录</span></a>
|
||||||
<a data-view="reminders" href="#reminders"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M6 9a6 6 0 1 1 12 0c0 5 2 6 2 6H4s2-1 2-6"/><path d="M10 19a2 2 0 0 0 4 0"/></svg><span class="nav-label">提醒管理</span></a>
|
<a data-view="reminders" href="#reminders"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M6 9a6 6 0 1 1 12 0c0 5 2 6 2 6H4s2-1 2-6"/><path d="M10 19a2 2 0 0 0 4 0"/></svg><span class="nav-label">提醒管理</span></a>
|
||||||
</nav>
|
</nav>
|
||||||
<div class="side-foot">
|
<div class="side-foot">
|
||||||
@@ -241,7 +242,7 @@
|
|||||||
<div class="notice warn" id="pairNotice" style="display: none; margin-bottom: 14px;">
|
<div class="notice warn" id="pairNotice" style="display: none; margin-bottom: 14px;">
|
||||||
<div>
|
<div>
|
||||||
<div class="n-title">该公司组合暂无归集数据</div>
|
<div class="n-title">该公司组合暂无归集数据</div>
|
||||||
<div class="n-body">所选组合在正式环境中将按相同口径实时归集,当前仅内置演示数据组合。</div>
|
<div class="n-body">所选组合暂无已确认往来,列表将显示「暂无数据」。</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -336,6 +337,7 @@
|
|||||||
<button data-audit-filter="起算" data-label="起算区间校准" aria-pressed="false">起算区间校准<span class="tab-count">0</span></button>
|
<button data-audit-filter="起算" data-label="起算区间校准" aria-pressed="false">起算区间校准<span class="tab-count">0</span></button>
|
||||||
<button data-audit-filter="账户" data-label="银行账户登记" aria-pressed="false">银行账户登记<span class="tab-count">0</span></button>
|
<button data-audit-filter="账户" data-label="银行账户登记" aria-pressed="false">银行账户登记<span class="tab-count">0</span></button>
|
||||||
<button data-audit-filter="手工" data-label="公司手工记录" aria-pressed="false">公司手工记录<span class="tab-count">0</span></button>
|
<button data-audit-filter="手工" data-label="公司手工记录" aria-pressed="false">公司手工记录<span class="tab-count">0</span></button>
|
||||||
|
<button data-audit-filter="reopen" data-label="重开审批" aria-pressed="false">重开审批<span class="tab-count" id="reopenTabCount">0</span></button>
|
||||||
</div>
|
</div>
|
||||||
<div class="field" style="min-width: 180px;">
|
<div class="field" style="min-width: 180px;">
|
||||||
<label for="auditCompany">公司</label>
|
<label for="auditCompany">公司</label>
|
||||||
@@ -343,7 +345,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="table-wrap" style="margin-top: 14px;">
|
<div class="table-wrap" style="margin-top: 14px;" id="auditTableWrap">
|
||||||
<table class="ds-table audit-table">
|
<table class="ds-table audit-table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
@@ -364,6 +366,19 @@
|
|||||||
<span>审核人:系统管理员 · 操作实时写入审核日志</span>
|
<span>审核人:系统管理员 · 操作实时写入审核日志</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div id="reopenQueue" hidden style="margin-top: 14px;">
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-head">
|
||||||
|
<span class="card-title">重开审批<span class="sub">待审批申请需管理员确认后才解除锁定</span></span>
|
||||||
|
</div>
|
||||||
|
<div id="reopenQueueList"></div>
|
||||||
|
<div class="empty" id="reopenQueueEmpty">
|
||||||
|
<svg class="empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4"><circle cx="12" cy="12" r="8.5"/><path d="M12 8v5l3 1.5"/></svg>
|
||||||
|
<div class="e-title">暂无重开申请</div>
|
||||||
|
锁定账期的重开申请会显示在这里。
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="app-view" data-page="flows">
|
<section class="app-view" data-page="flows">
|
||||||
@@ -426,9 +441,14 @@
|
|||||||
</thead>
|
</thead>
|
||||||
<tbody></tbody>
|
<tbody></tbody>
|
||||||
</table>
|
</table>
|
||||||
|
<div class="empty" id="flowEmpty" hidden>
|
||||||
|
<svg class="empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4"><rect x="4" y="5" width="16" height="14" rx="2"/><path d="M4 10h16"/></svg>
|
||||||
|
<div class="e-title">暂无数据</div>
|
||||||
|
当前筛选条件下没有已确认工作表的银行流水。
|
||||||
|
</div>
|
||||||
<div class="table-foot">
|
<div class="table-foot">
|
||||||
<span id="flowCount">共 0 笔</span>
|
<span id="flowCount">共 0 笔</span>
|
||||||
<span class="meta" id="flowsRangeMeta">数据范围:加载中…</span>
|
<span class="num" id="flowSum"></span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
@@ -491,15 +511,8 @@
|
|||||||
<div class="card-head">
|
<div class="card-head">
|
||||||
<span class="card-title">账期时间轴<span class="sub" id="timelineSub">全局起算日 2026-01-01 起,每月 5 日结账</span></span>
|
<span class="card-title">账期时间轴<span class="sub" id="timelineSub">全局起算日 2026-01-01 起,每月 5 日结账</span></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="timeline">
|
<div class="timeline" id="periodTimeline">
|
||||||
<div class="tl-cell closed"><div class="tl-month">2026-01</div><div class="tl-state">已结账</div></div>
|
<div class="tl-cell open"><div class="tl-month">—</div><div class="tl-state">加载中</div></div>
|
||||||
<div class="tl-cell closed"><div class="tl-month">2026-02</div><div class="tl-state">已结账</div></div>
|
|
||||||
<div class="tl-cell closed"><div class="tl-month">2026-03</div><div class="tl-state">已结账</div></div>
|
|
||||||
<div class="tl-cell closed"><div class="tl-month">2026-04</div><div class="tl-state">已结账</div></div>
|
|
||||||
<div class="tl-cell closed"><div class="tl-month">2026-05</div><div class="tl-state">已结账</div></div>
|
|
||||||
<div class="tl-cell closed"><div class="tl-month">2026-06</div><div class="tl-state">已结账</div></div>
|
|
||||||
<div class="tl-cell current" id="tl-current"><div class="tl-month">2026-07</div><div class="tl-state" id="tl-current-state">进行中</div></div>
|
|
||||||
<div class="tl-cell open"><div class="tl-month">2026-08</div><div class="tl-state">归集中</div></div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -512,8 +525,9 @@
|
|||||||
<form id="systemSettings" novalidate>
|
<form id="systemSettings" novalidate>
|
||||||
<div class="field" style="margin-bottom: 14px;">
|
<div class="field" style="margin-bottom: 14px;">
|
||||||
<label for="cs-start">全局起算日</label>
|
<label for="cs-start">全局起算日</label>
|
||||||
<input class="input num-input" type="date" name="startDate" id="cs-start" value="2026-01-01" />
|
<input class="input num-input" type="date" name="startDate" id="cs-start" />
|
||||||
<span class="hint">期初余额以此日前一日的期末数为准</span>
|
<span class="hint" id="cs-start-hint">期初余额以此日前一日的期末数为准</span>
|
||||||
|
<span class="pill pill-muted" id="cs-start-locked" style="display: none; margin-top: 8px;">已锁定</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="field" style="margin-bottom: 14px;">
|
<div class="field" style="margin-bottom: 14px;">
|
||||||
<label for="cs-day">每月结账日</label>
|
<label for="cs-day">每月结账日</label>
|
||||||
@@ -547,15 +561,30 @@
|
|||||||
|
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="card-head">
|
<div class="card-head">
|
||||||
<span class="card-title">期初余额管理<span class="sub" id="openingSub">2026-01-01 起算的公司间往来期初数</span></span>
|
<span class="card-title">期初余额管理<span class="sub" id="openingSub">公司间往来期初数</span></span>
|
||||||
<button class="btn btn-sm" id="openOpeningDialog">新增</button>
|
<button class="btn btn-sm" id="openOpeningDialog">新增</button>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="notice info" id="openingSummary" style="margin: 0 0 14px; display: none;"></div>
|
||||||
|
<div class="table-wrap" style="border: 0;">
|
||||||
|
<table class="ds-table">
|
||||||
|
<thead>
|
||||||
|
<tr><th>本方公司</th><th>对方公司</th><th>方向</th><th class="num-col">金额</th><th>录入人</th><th>录入时间</th><th>状态</th><th></th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="openingRows"></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-head">
|
||||||
|
<span class="card-title">变更记录<span class="sub">起算日与期初余额改动留痕</span></span>
|
||||||
|
</div>
|
||||||
<div class="table-wrap" style="border: 0;">
|
<div class="table-wrap" style="border: 0;">
|
||||||
<table class="ds-table">
|
<table class="ds-table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr><th>本方公司</th><th>对方公司</th><th>科目</th><th>方向</th><th class="num-col">金额(万元)</th><th>生效日</th><th>状态</th></tr>
|
<tr><th>时间</th><th>操作人</th><th>对象</th><th>变更</th><th>原因</th></tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody id="openingRows"></tbody>
|
<tbody id="calculationChangeRows"><tr><td colspan="5" class="empty">暂无变更记录</td></tr></tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -563,86 +592,172 @@
|
|||||||
|
|
||||||
<div class="card" id="closingPanel">
|
<div class="card" id="closingPanel">
|
||||||
<div class="card-head">
|
<div class="card-head">
|
||||||
<span class="card-title">月度结账<span class="sub" id="closingDescription">2026 年 7 月 · 当前未达到结账条件</span></span>
|
<span class="card-title">月度结账<span class="sub" id="closingDescription">加载账期状态…</span></span>
|
||||||
<span class="pill pill-danger" id="closingStatus">已阻断</span>
|
<span class="pill pill-muted" id="closingStatus">—</span>
|
||||||
</div>
|
</div>
|
||||||
|
<div id="closingBody">
|
||||||
<div class="closing-check-list">
|
<div class="closing-check-list">
|
||||||
<div class="list-row">
|
<div class="list-row" data-closing-key="submissions">
|
||||||
<span class="pill pill-success" data-closing-check>公司流水提交</span>
|
<span class="pill pill-muted" data-closing-check>流水提交</span>
|
||||||
<div class="lr-main"><div class="lr-title">流水提交</div><div class="lr-sub" data-closing-sub>5 / 6 家已完成</div></div>
|
<div class="lr-main"><div class="lr-title">流水提交</div><div class="lr-sub" data-closing-sub>—</div></div>
|
||||||
<div class="lr-side"><span class="pill pill-warn" data-closing-state>待处理</span></div>
|
<div class="lr-side"><span class="pill pill-muted" data-closing-state>—</span></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="list-row">
|
<div class="list-row" data-closing-key="coverage">
|
||||||
<span class="pill pill-success" data-closing-check>账户连续性</span>
|
<span class="pill pill-muted" data-closing-check>账户连续</span>
|
||||||
<div class="lr-main"><div class="lr-title">账户连续</div><div class="lr-sub" data-closing-sub>2 个账户存在断档</div></div>
|
<div class="lr-main"><div class="lr-title">账户连续</div><div class="lr-sub" data-closing-sub>—</div></div>
|
||||||
<div class="lr-side"><span class="pill pill-danger" data-closing-state>阻断</span></div>
|
<div class="lr-side"><span class="pill pill-muted" data-closing-state>—</span></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="list-row">
|
<div class="list-row" data-closing-key="reviews">
|
||||||
<span class="pill pill-success" data-closing-check>审核事项</span>
|
<span class="pill pill-muted" data-closing-check>审核完成</span>
|
||||||
<div class="lr-main"><div class="lr-title">审核完成</div><div class="lr-sub" data-closing-sub>0 项尚未处理</div></div>
|
<div class="lr-main"><div class="lr-title">审核完成</div><div class="lr-sub" data-closing-sub>—</div></div>
|
||||||
<div class="lr-side"><span class="pill pill-danger" data-closing-state>阻断</span></div>
|
<div class="lr-side"><span class="pill pill-muted" data-closing-state>—</span></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="list-row">
|
<div class="list-row" data-closing-key="opening">
|
||||||
<span class="pill pill-success" data-closing-check>期初余额</span>
|
<span class="pill pill-muted" data-closing-check>期初锁定</span>
|
||||||
<div class="lr-main"><div class="lr-title">期初锁定</div><div class="lr-sub" data-closing-sub>已锁定 2026.01.01</div></div>
|
<div class="lr-main"><div class="lr-title">期初锁定</div><div class="lr-sub" data-closing-sub>—</div></div>
|
||||||
<div class="lr-side"><span class="pill pill-success" data-closing-state>已通过</span></div>
|
<div class="lr-side"><span class="pill pill-muted" data-closing-state>—</span></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="grid grid-4" id="closingSummary" style="margin-top: 16px;">
|
||||||
|
<div><div class="meta">账期</div><div class="num" id="ckMonth">—</div></div>
|
||||||
|
<div><div class="meta">期末归集</div><div class="num" id="ckNet">—</div></div>
|
||||||
|
<div><div class="meta">结转去向</div><div class="num" id="ckCarry">—</div></div>
|
||||||
|
<div><div class="meta">月报编号</div><div class="num" id="ckReport">尚未生成</div></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="notice danger" id="block-notice" style="margin-top: 16px; display: none;">
|
<div class="notice danger" id="block-notice" style="margin-top: 16px; display: none;">
|
||||||
<div>
|
<div>
|
||||||
<div class="n-title">存在阻断项,暂不能执行 2026-07 月度结账</div>
|
<div class="n-title" id="block-notice-title">存在阻断项,暂不能执行月度结账</div>
|
||||||
<div class="n-body" id="block-notice-body">请先处理待审核事项与账户断档。</div>
|
<div class="n-body" id="block-notice-body">请先处理待审核事项与账户断档。</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="notice danger" id="failed-notice" style="margin-top: 16px; display: none;">
|
||||||
|
<div>
|
||||||
|
<div class="n-title">结账失败</div>
|
||||||
|
<div class="n-body" id="failed-notice-body">未改动任何数据,可重新执行结账。</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<div class="notice info" id="closed-notice" style="margin-top: 16px; display: none;">
|
<div class="notice info" id="closed-notice" style="margin-top: 16px; display: none;">
|
||||||
<div>
|
<div>
|
||||||
<div class="n-title">2026-07 已结账</div>
|
<div class="n-title" id="closed-notice-title">账期已锁定</div>
|
||||||
<div class="n-body" id="closed-notice-body">结账后各公司 7 月往来数据已锁定,期初数将结转至 2026-08 账期。</div>
|
<div class="n-body" id="closed-notice-body">结账后各公司往来数据已锁定,期初数将结转至下一账期。</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="notice warn" id="reopened-notice" style="margin-top: 16px; display: none;">
|
||||||
|
<div>
|
||||||
|
<div class="n-title">账期已重开</div>
|
||||||
|
<div class="n-body" id="reopened-notice-body">窗口内可更正并留痕,到期自动恢复锁定。</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="row" style="margin-top: 16px; justify-content: flex-end; flex-wrap: wrap;">
|
<div class="row" style="margin-top: 16px; justify-content: flex-end; flex-wrap: wrap; gap: 8px;">
|
||||||
<span class="meta" id="closingHistory" style="margin-right: auto;">最近结账:2026 年 6 月 · 系统管理员 · 2026.07.05 18:10</span>
|
<span class="meta" id="closingHistory" style="margin-right: auto;">—</span>
|
||||||
|
<span class="loading-inline" id="closingBusy" hidden>正在锁定账期并生成月报…请勿关闭页面</span>
|
||||||
|
<button class="btn" id="downloadMonthReport" hidden>下载月报</button>
|
||||||
<button class="btn" id="runClosingCheck">重新检查</button>
|
<button class="btn" id="runClosingCheck">重新检查</button>
|
||||||
<button class="btn btn-primary" id="executeClosing" disabled title="请先处理全部阻断事项">执行 2026-07 月度结账</button>
|
<button class="btn btn-primary" id="executeClosing" disabled title="请先处理全部阻断事项">执行月度结账</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="app-view" data-page="period-audit">
|
||||||
|
<div class="page-head">
|
||||||
|
<div>
|
||||||
|
<h1>审计记录</h1>
|
||||||
|
<p class="page-sub">谁、什么时间、改了什么、为什么。记录只增不改,可倒查至银行原始流水。</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="filters">
|
||||||
|
<div class="field">
|
||||||
|
<label for="paSince">起始日期</label>
|
||||||
|
<input class="input" id="paSince" type="date" />
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="paUntil">结束日期</label>
|
||||||
|
<input class="input" id="paUntil" type="date" />
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="paAction">动作类型</label>
|
||||||
|
<select class="select" id="paAction">
|
||||||
|
<option value="">全部动作</option>
|
||||||
|
<option value="close_execute">月结</option>
|
||||||
|
<option value="reopen_request">重开申请</option>
|
||||||
|
<option value="reopen_approve">重开审批通过</option>
|
||||||
|
<option value="reopen_reject">重开驳回</option>
|
||||||
|
<option value="reopen_expire">重开到期恢复</option>
|
||||||
|
<option value="close_fail">月结失败</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="paCompany">涉及公司</label>
|
||||||
|
<input class="input" id="paCompany" type="text" placeholder="公司名 / 月报号" />
|
||||||
|
</div>
|
||||||
|
<button class="btn" id="paApply" type="button">查询</button>
|
||||||
|
<button class="btn btn-ghost" id="paReset" type="button">清除筛选条件</button>
|
||||||
|
</div>
|
||||||
|
<div class="notice danger" id="paError" style="display: none; margin-bottom: 14px;">
|
||||||
|
<div>
|
||||||
|
<div class="n-title">审计记录加载失败</div>
|
||||||
|
<div class="n-body">已加载的数据未被改动 · 请稍后重试</div>
|
||||||
|
</div>
|
||||||
|
<button class="btn btn-primary btn-sm" type="button" id="paReload">重新加载</button>
|
||||||
|
</div>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="ds-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>时间</th>
|
||||||
|
<th>操作人</th>
|
||||||
|
<th>动作</th>
|
||||||
|
<th class="wrap">对象与原因</th>
|
||||||
|
<th>前后变化</th>
|
||||||
|
<th>凭证</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="periodAuditRows"></tbody>
|
||||||
|
</table>
|
||||||
|
<div class="table-foot">
|
||||||
|
<span id="periodAuditFoot">共 0 条</span>
|
||||||
|
<span>审计记录只增不改 · 永久保留</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="audit-event-cards" id="periodAuditCards"></div>
|
||||||
|
<div class="empty" id="periodAuditEmpty" hidden>
|
||||||
|
<svg class="empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4"><circle cx="12" cy="12" r="8.5"/><path d="M12 8v5l3 1.5"/></svg>
|
||||||
|
<div class="e-title">没有符合条件的审计记录</div>
|
||||||
|
调整筛选条件后再查询,或清除筛选查看全部留痕。
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<section class="app-view" data-page="reminders">
|
<section class="app-view" data-page="reminders">
|
||||||
<div class="page-head">
|
<div class="page-head">
|
||||||
<div>
|
<div>
|
||||||
<h1>提醒管理</h1>
|
<h1>提醒管理</h1>
|
||||||
<p class="page-sub">向成员公司发送处理提醒,并跟踪系统提醒与人工提醒的触达与处理状态。</p>
|
<p class="page-sub">向成员公司发送处理提醒,并跟踪系统提醒与人工提醒的触达与处理状态。</p>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="page-actions">
|
||||||
|
<button type="button" class="btn btn-sm" id="reminder-scan-btn">立即扫描</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="grid grid-1-2">
|
<div class="stack">
|
||||||
<div class="card">
|
<div class="card" id="pending-reminders-card">
|
||||||
<div class="card-head">
|
<div class="card-head">
|
||||||
<span class="card-title">发送处理提醒<span class="sub">选择公司后系统自动列出待提醒事项,核对后一键发送</span></span>
|
<span class="card-title">待提醒清单<span class="sub">系统按流水提交、断档、待确认自动发现,点发送即送达对应公司</span></span>
|
||||||
|
<div class="row" style="gap: 10px; align-items: center;">
|
||||||
|
<span class="meta" id="pending-summary">—</span>
|
||||||
|
<button type="button" class="btn btn-primary btn-sm" id="pending-send-all" disabled>全部一键发送</button>
|
||||||
</div>
|
</div>
|
||||||
<form id="reminderForm" novalidate>
|
|
||||||
<div class="field" style="margin-bottom: 14px;">
|
|
||||||
<label for="reminder-company">接收公司</label>
|
|
||||||
<select class="select" id="reminder-company"><option value="">请选择公司</option></select>
|
|
||||||
<span class="hint error" id="company-error" style="display: none;">请选择一家接收公司</span>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="field" style="margin-bottom: 16px;">
|
<div id="pending-list">
|
||||||
<label>待提醒事项(系统自动列出)</label>
|
<div class="empty" id="pending-empty">暂无需要提醒的事项 · 各公司流水与确认进度正常</div>
|
||||||
<div id="reminder-items">
|
|
||||||
<div class="empty">请先选择公司,系统将自动列出该公司待提醒事项。</div>
|
|
||||||
</div>
|
</div>
|
||||||
<span class="hint error" id="reminder-error" style="display: none;">该公司当前没有待提醒事项</span>
|
|
||||||
</div>
|
|
||||||
<button type="submit" class="btn btn-primary" id="send-btn" style="width: 100%;" disabled>发送提醒</button>
|
|
||||||
<p class="hint" id="send-hint" style="margin-top: 10px; display: none;"></p>
|
|
||||||
</form>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="card">
|
<div class="card" id="reminder-history-card">
|
||||||
<div class="card-head">
|
<div class="card-head">
|
||||||
<span class="card-title">提醒历史<span class="sub">含系统自动触发与人工发送的全部提醒记录</span></span>
|
<span class="card-title">提醒历史<span class="sub">含系统自动触发与人工发送的全部提醒记录</span></span>
|
||||||
</div>
|
</div>
|
||||||
@@ -651,11 +766,12 @@
|
|||||||
<button type="button" data-filter="system">系统提醒<span class="tab-count" id="count-system">0</span></button>
|
<button type="button" data-filter="system">系统提醒<span class="tab-count" id="count-system">0</span></button>
|
||||||
<button type="button" data-filter="manual">人工提醒<span class="tab-count" id="count-manual">0</span></button>
|
<button type="button" data-filter="manual">人工提醒<span class="tab-count" id="count-manual">0</span></button>
|
||||||
</div>
|
</div>
|
||||||
<div class="table-wrap" style="border: 0;">
|
<div class="table-wrap history-table">
|
||||||
<table class="ds-table">
|
<table class="ds-table">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>公司</th>
|
<th>公司</th>
|
||||||
|
<th>来源</th>
|
||||||
<th>类型</th>
|
<th>类型</th>
|
||||||
<th class="wrap">内容摘要</th>
|
<th class="wrap">内容摘要</th>
|
||||||
<th>发送时间</th>
|
<th>发送时间</th>
|
||||||
@@ -672,6 +788,62 @@
|
|||||||
<span id="table-foot-state">未读 0 · 处理中 0 · 已完成 0</span>
|
<span id="table-foot-state">未读 0 · 处理中 0 · 已完成 0</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="card" id="send-reminder-card">
|
||||||
|
<div class="card-head">
|
||||||
|
<span class="card-title">发送处理提醒<span class="sub">将以人工提醒形式送达所选公司出纳与财务负责人</span></span>
|
||||||
|
</div>
|
||||||
|
<form id="reminderForm" novalidate>
|
||||||
|
<div class="send-flow">
|
||||||
|
<div class="sf-step">
|
||||||
|
<div class="sf-step-head">
|
||||||
|
<span class="sf-idx">01</span>
|
||||||
|
<span>选择接收公司</span>
|
||||||
|
<span class="meta" id="pick-count">已选 0 家</span>
|
||||||
|
</div>
|
||||||
|
<div class="pick-list" id="reminderCompanyList"></div>
|
||||||
|
<span class="hint error" id="company-error" style="display: none;">请至少选择一家接收公司</span>
|
||||||
|
<p class="hint">每家公司将分别生成一条提醒,可在上方「待提醒清单」勾选后自动带入。</p>
|
||||||
|
</div>
|
||||||
|
<div class="sf-step">
|
||||||
|
<div class="sf-step-head">
|
||||||
|
<span class="sf-idx">02</span>
|
||||||
|
<span>填写提醒内容</span>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="reminder-type">提醒类型</label>
|
||||||
|
<select class="select" id="reminder-type">
|
||||||
|
<option selected>流水未提交</option>
|
||||||
|
<option>单边待确认</option>
|
||||||
|
<option>科目待确认</option>
|
||||||
|
<option>账户登记</option>
|
||||||
|
<option>其他</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="reminder-content">提醒内容</label>
|
||||||
|
<textarea class="textarea" id="reminder-content">请于截止日期前完成 2026 年 7 月银行流水上传与待确认事项处理。</textarea>
|
||||||
|
<span class="hint error" id="content-error" style="display: none;">提醒内容不能为空</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="sf-step">
|
||||||
|
<div class="sf-step-head">
|
||||||
|
<span class="sf-idx">03</span>
|
||||||
|
<span>设定截止并发送</span>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="reminder-deadline">截止日期</label>
|
||||||
|
<input class="input" type="date" id="reminder-deadline" value="2026-08-29" min="2026-08-20" />
|
||||||
|
</div>
|
||||||
|
<div class="sf-send">
|
||||||
|
<button type="submit" class="btn btn-primary" id="send-btn">发送提醒</button>
|
||||||
|
<p class="hint" id="send-result-hint">发送后可在上方「提醒历史」中跟踪触达与处理状态。</p>
|
||||||
|
<p class="hint" id="send-hint" style="display: none;"></p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
@@ -762,31 +934,15 @@
|
|||||||
<select class="select" name="to" id="ob-to" required></select>
|
<select class="select" name="to" id="ob-to" required></select>
|
||||||
</div>
|
</div>
|
||||||
<div class="field">
|
<div class="field">
|
||||||
<label for="ob-subject">科目</label>
|
<label for="ob-amount">金额</label>
|
||||||
<select class="select" name="subject" id="ob-subject" required>
|
<input class="input num-input" name="amount" id="ob-amount" type="number" step="0.01" required />
|
||||||
<option>应收</option>
|
|
||||||
<option>应付</option>
|
|
||||||
<option>其他应收</option>
|
|
||||||
<option>其他应付</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="field">
|
<div class="field">
|
||||||
<label for="ob-direction">方向</label>
|
<label for="ob-reason">录入原因</label>
|
||||||
<select class="select" name="direction" id="ob-direction" required>
|
<input class="input" name="reason" id="ob-reason" required placeholder="必填,将写入变更记录" />
|
||||||
<option>借方</option>
|
|
||||||
<option>贷方</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div class="field">
|
|
||||||
<label for="ob-amount">金额(万元)</label>
|
|
||||||
<input class="input num-input" name="amount" id="ob-amount" type="number" min="0" step="0.01" required />
|
|
||||||
</div>
|
|
||||||
<div class="field">
|
|
||||||
<label for="ob-effective">生效日</label>
|
|
||||||
<input class="input" name="effectiveDate" id="ob-effective" type="date" value="2026-01-01" required />
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<p class="hint" style="margin-top: 10px;">提交后进入复核,不能直接修改已确认期初。</p>
|
<p class="hint" style="margin-top: 10px;">正数表示本方对对方为应收;提交后进入待确认,确认后才计入公司端余额。</p>
|
||||||
<div class="modal-actions">
|
<div class="modal-actions">
|
||||||
<button type="button" class="btn" data-close-opening>取消</button>
|
<button type="button" class="btn" data-close-opening>取消</button>
|
||||||
<button type="submit" class="btn btn-primary">提交复核</button>
|
<button type="submit" class="btn btn-primary">提交复核</button>
|
||||||
@@ -795,6 +951,26 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="modal-backdrop" id="reasonDialog">
|
||||||
|
<div class="modal">
|
||||||
|
<div class="modal-head">
|
||||||
|
<span class="modal-title" id="reasonDialogTitle">填写原因</span>
|
||||||
|
<button type="button" class="modal-close" data-close-reason aria-label="关闭">×</button>
|
||||||
|
</div>
|
||||||
|
<p class="modal-sub" id="reasonDialogSub">该操作必须填写原因并留痕。</p>
|
||||||
|
<form id="reasonForm" novalidate>
|
||||||
|
<div class="field">
|
||||||
|
<label for="reasonInput">原因</label>
|
||||||
|
<textarea class="input" id="reasonInput" name="reason" rows="3" required placeholder="至少 2 个字"></textarea>
|
||||||
|
</div>
|
||||||
|
<div class="modal-actions">
|
||||||
|
<button type="button" class="btn" data-close-reason>取消</button>
|
||||||
|
<button type="submit" class="btn btn-primary" id="reasonSubmit">确认</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- 审核通过弹窗 -->
|
<!-- 审核通过弹窗 -->
|
||||||
<div class="modal-backdrop" id="modal-approve">
|
<div class="modal-backdrop" id="modal-approve">
|
||||||
<div class="modal">
|
<div class="modal">
|
||||||
@@ -842,29 +1018,99 @@
|
|||||||
<div class="modal-backdrop" id="closingDialog">
|
<div class="modal-backdrop" id="closingDialog">
|
||||||
<div class="modal">
|
<div class="modal">
|
||||||
<div class="modal-head">
|
<div class="modal-head">
|
||||||
<span class="modal-title">确认执行 2026-07 月度结账</span>
|
<span class="modal-title" id="closingDialogTitle">确认执行月度结账</span>
|
||||||
<button type="button" class="modal-close" data-close-closing aria-label="关闭">×</button>
|
<button type="button" class="modal-close" data-close-closing aria-label="关闭">×</button>
|
||||||
</div>
|
</div>
|
||||||
<p class="modal-sub">结账后成员公司的 7 月流水与往来确认将锁定,不可再修改。</p>
|
<p class="modal-sub" id="closingDialogSub">结账后该月流水与往来确认将锁定,不可再直接修改。</p>
|
||||||
<form id="closingForm" novalidate>
|
<form id="closingForm" novalidate>
|
||||||
|
<div class="notice warn" style="margin-bottom: 14px;">
|
||||||
|
<div>
|
||||||
|
<div class="n-title">请确认后果</div>
|
||||||
|
<div class="n-body" id="closingConsequences">① 该账期往来结果锁定,普通写入将被拒绝。<br />② 生成不可静默改写的月报并结转期末。<br />③ 确需更正须申请重开,经审批后留痕修改。</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<div class="detail-box">
|
<div class="detail-box">
|
||||||
<dl class="kv">
|
<dl class="kv">
|
||||||
<dt>结账账期</dt><dd>2026-07</dd>
|
<dt>结账账期</dt><dd id="cdMonth">—</dd>
|
||||||
<dt>检查通过</dt><dd>全部前置检查已通过</dd>
|
<dt>检查通过</dt><dd id="cdChecks">—</dd>
|
||||||
<dt>期末归集</dt><dd>往来净额将结转至 2026-08 期初</dd>
|
<dt>期末归集</dt><dd id="cdCarry">往来净额将结转至下一账期期初</dd>
|
||||||
</dl>
|
</dl>
|
||||||
</div>
|
</div>
|
||||||
<label class="row" style="gap: 6px; font-size: 13px; margin-top: 14px; cursor: pointer;">
|
<label class="row" style="gap: 6px; font-size: 13px; margin-top: 14px; cursor: pointer;">
|
||||||
<input type="checkbox" name="confirm" required style="width: auto;" />我已复核 2026 年 7 月结账结果
|
<input type="checkbox" name="confirm" id="closingConfirmBox" required style="width: auto;" />我已复核结账结果并知晓锁定后果
|
||||||
</label>
|
</label>
|
||||||
<div class="modal-actions">
|
<div class="modal-actions">
|
||||||
<button type="button" class="btn" data-close-closing>再想想</button>
|
<button type="button" class="btn" data-close-closing>再想想</button>
|
||||||
<button type="submit" class="btn btn-primary">确认结账</button>
|
<button type="submit" class="btn btn-primary" id="closingConfirmBtn">确认结账并锁定</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="modal-backdrop" id="reopenRequestDialog">
|
||||||
|
<div class="modal">
|
||||||
|
<div class="modal-head">
|
||||||
|
<span class="modal-title" id="reopenRequestTitle">申请重开账期</span>
|
||||||
|
<button type="button" class="modal-close" data-close-reopen-req aria-label="关闭">×</button>
|
||||||
|
</div>
|
||||||
|
<p class="modal-sub">重开解除锁定但保留原月报;更正后须重新结账。</p>
|
||||||
|
<form id="reopenRequestForm" novalidate>
|
||||||
|
<div class="notice warn" style="margin-bottom: 14px;">
|
||||||
|
<div>
|
||||||
|
<div class="n-title">请确认后果</div>
|
||||||
|
<div class="n-body">① 批准后该账期暂时解除锁定,所有更正留痕。<br />② 原月报作废,窗口结束后或提前结束须重新结账。<br />③ 申请人、原因、时间与前后变化可倒查。</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="reopenReason">重开原因 *</label>
|
||||||
|
<textarea class="textarea" id="reopenReason" minlength="10" required placeholder="不少于 10 个字,将写入审计记录"></textarea>
|
||||||
|
<span class="hint">原因会进入审计记录,不可事后删改。</span>
|
||||||
|
</div>
|
||||||
|
<div class="field" style="margin-top: 12px;">
|
||||||
|
<label for="reopenCompanies">涉及公司与事项</label>
|
||||||
|
<input class="input" id="reopenCompanies" placeholder="例如:金牛煤业 ↔ 金牛物流 运输费补录" />
|
||||||
|
</div>
|
||||||
|
<div class="field" style="margin-top: 12px;">
|
||||||
|
<label for="reopenDays">申请窗口(天)</label>
|
||||||
|
<input class="input num-input" id="reopenDays" type="number" min="1" max="30" value="3" />
|
||||||
|
<span class="hint">到期自动恢复锁定;默认 3 天。</span>
|
||||||
|
</div>
|
||||||
|
<div class="modal-actions">
|
||||||
|
<button type="button" class="btn" data-close-reopen-req>取消</button>
|
||||||
|
<button type="submit" class="btn btn-warn">提交重开申请</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="modal-backdrop" id="reopenDecideDialog">
|
||||||
|
<div class="modal wide">
|
||||||
|
<div class="modal-head">
|
||||||
|
<span class="modal-title" id="reopenDecideTitle">重开审批</span>
|
||||||
|
<button type="button" class="modal-close" data-close-reopen-dec aria-label="关闭">×</button>
|
||||||
|
</div>
|
||||||
|
<p class="modal-sub" id="reopenDecideSub">—</p>
|
||||||
|
<div class="detail-box">
|
||||||
|
<dl class="kv" id="reopenDecideKv"></dl>
|
||||||
|
</div>
|
||||||
|
<div class="diff-grid" id="reopenDiff" style="margin-top: 16px;"></div>
|
||||||
|
<div class="notice info" style="margin-top: 14px;">
|
||||||
|
<div>
|
||||||
|
<div class="n-title">凭证与入账方式</div>
|
||||||
|
<div class="n-body">批准后按审批窗口解除锁定;银行原始流水永不改写,更正通过新决定与留痕完成。</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="field" style="margin-top: 14px;">
|
||||||
|
<label for="reopenComment">审批意见(驳回必填)</label>
|
||||||
|
<textarea class="textarea" id="reopenComment" placeholder="通过可写备注;驳回须说明原因"></textarea>
|
||||||
|
</div>
|
||||||
|
<div class="modal-actions">
|
||||||
|
<button type="button" class="btn btn-danger" id="reopenRejectBtn">驳回申请</button>
|
||||||
|
<button type="button" class="btn btn-warn" id="reopenApproveBtn">同意重开</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- 往来穿透弹窗 -->
|
<!-- 往来穿透弹窗 -->
|
||||||
<div class="modal-backdrop" id="traceModal">
|
<div class="modal-backdrop" id="traceModal">
|
||||||
<div class="modal wide">
|
<div class="modal wide">
|
||||||
@@ -927,6 +1173,26 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- 提醒详情抽屉 -->
|
||||||
|
<aside class="drawer" id="reminder-detail-drawer" aria-label="提醒详情">
|
||||||
|
<div class="drawer-head">
|
||||||
|
<div>
|
||||||
|
<span class="pill pill-info" id="rd-source-pill">系统</span>
|
||||||
|
<h2 class="d-title" id="rd-title">提醒详情</h2>
|
||||||
|
<p class="d-desc" id="rd-sub"></p>
|
||||||
|
</div>
|
||||||
|
<button type="button" class="icon-button" data-close-rd aria-label="关闭详情" title="关闭详情">×</button>
|
||||||
|
</div>
|
||||||
|
<div class="drawer-body">
|
||||||
|
<dl class="kv" id="rd-fields"></dl>
|
||||||
|
<h3 style="font-size: 13px; margin: 16px 0 8px; color: var(--muted);">事件留痕</h3>
|
||||||
|
<div id="rd-events"></div>
|
||||||
|
</div>
|
||||||
|
<div class="drawer-foot">
|
||||||
|
<button type="button" class="btn" data-close-rd>关闭</button>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
<!-- 提醒历史弹窗 -->
|
<!-- 提醒历史弹窗 -->
|
||||||
<div class="modal-backdrop" id="history-modal">
|
<div class="modal-backdrop" id="history-modal">
|
||||||
<div class="modal">
|
<div class="modal">
|
||||||
@@ -942,6 +1208,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="toast-region" id="toastRegion" aria-live="polite"></div>
|
<div class="toast-region" id="toastRegion" aria-live="polite"></div>
|
||||||
<script src="app.js?v=9"></script>
|
<script src="app.js?v=15"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+2329
-604
File diff suppressed because it is too large
Load Diff
+320
-125
@@ -5,7 +5,7 @@
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<meta name="description" content="金牛集团公司业务端" />
|
<meta name="description" content="金牛集团公司业务端" />
|
||||||
<title>公司业务端 · 金牛集团</title>
|
<title>公司业务端 · 金牛集团</title>
|
||||||
<link rel="stylesheet" href="design-system.css?v=5" />
|
<link rel="stylesheet" href="design-system.css?v=7" />
|
||||||
</head>
|
</head>
|
||||||
<body data-portal="company">
|
<body data-portal="company">
|
||||||
<a class="skip-link" href="#main-content">跳到主要内容</a>
|
<a class="skip-link" href="#main-content">跳到主要内容</a>
|
||||||
@@ -22,10 +22,11 @@
|
|||||||
<a data-view="upload" href="#upload"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M12 16V4m0 0l-4 4m4-4l4 4"/><path d="M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"/></svg><span class="nav-label">流水导入</span></a>
|
<a data-view="upload" href="#upload"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M12 16V4m0 0l-4 4m4-4l4 4"/><path d="M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"/></svg><span class="nav-label">流水导入</span></a>
|
||||||
<a data-view="manual" href="#manual"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg><span class="nav-label">手工记录</span></a>
|
<a data-view="manual" href="#manual"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg><span class="nav-label">手工记录</span></a>
|
||||||
<a data-view="flows" href="#flows"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M4 6h16M4 12h16M4 18h10"/></svg><span class="nav-label">流水管理</span></a>
|
<a data-view="flows" href="#flows"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M4 6h16M4 12h16M4 18h10"/></svg><span class="nav-label">流水管理</span></a>
|
||||||
|
<a data-view="transfers" href="#transfers"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M7 7h13v3l-4-2.5L20 5V8"/><path d="M17 17H4v-3l4 2.5L4 19v-3"/><rect x="3" y="3" width="18" height="18" rx="2"/></svg><span class="nav-label">转账往来</span><span class="nav-badge" id="transfersNavBadge" hidden>0</span></a>
|
||||||
<a data-view="reconcile" href="#reconcile"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M9 11.5l2 2 4-4.5"/><rect x="4" y="3" width="16" height="18" rx="2"/></svg><span class="nav-label">往来确认</span><span class="nav-badge">5</span></a>
|
<a data-view="reconcile" href="#reconcile"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M9 11.5l2 2 4-4.5"/><rect x="4" y="3" width="16" height="18" rx="2"/></svg><span class="nav-label">往来确认</span><span class="nav-badge">5</span></a>
|
||||||
<div class="nav-group">账户与消息</div>
|
<div class="nav-group">账户与消息</div>
|
||||||
<a data-view="accounts" href="#accounts"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 10h18"/></svg><span class="nav-label">银行账户</span></a>
|
<a data-view="accounts" href="#accounts"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 10h18"/></svg><span class="nav-label">银行账户</span></a>
|
||||||
<a data-view="notifications" href="#notifications"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M6 9a6 6 0 1 1 12 0c0 5 2 6 2 6H4s2-1 2-6"/><path d="M10 19a2 2 0 0 0 4 0"/></svg><span class="nav-label">通知</span><span class="nav-badge">3</span></a>
|
<a data-view="notifications" href="#notifications"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M6 9a6 6 0 1 1 12 0c0 5 2 6 2 6H4s2-1 2-6"/><path d="M10 19a2 2 0 0 0 4 0"/></svg><span class="nav-label">通知</span><span class="nav-badge" id="notice-nav-badge" style="display: none;">0</span></a>
|
||||||
</nav>
|
</nav>
|
||||||
<div class="side-foot">
|
<div class="side-foot">
|
||||||
<div class="user-row">
|
<div class="user-row">
|
||||||
@@ -63,7 +64,7 @@
|
|||||||
|
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="card-head">
|
<div class="card-head">
|
||||||
<span class="card-title">账期流程 · 2026-07<span class="sub">当前停在第 3 步「往来确认」,完成后即可等待集团结账</span></span>
|
<span class="card-title">账期流程 · 2026-07<span class="sub" id="workspaceFlowSub">当前停在第 3 步「往来确认」,完成后即可等待集团结账</span></span>
|
||||||
<span class="pill pill-warn">结账日顺延至 08-29</span>
|
<span class="pill pill-warn">结账日顺延至 08-29</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="flow">
|
<div class="flow">
|
||||||
@@ -97,6 +98,17 @@
|
|||||||
|
|
||||||
<div class="grid grid-3-2" style="margin-top: 14px;">
|
<div class="grid grid-3-2" style="margin-top: 14px;">
|
||||||
<div class="stack">
|
<div class="stack">
|
||||||
|
<div class="notice danger" id="companyCoverageNotice" style="display: none; margin-bottom: 14px;">
|
||||||
|
<div>
|
||||||
|
<div class="n-title" id="companyCoverageTitle">流水断档提醒</div>
|
||||||
|
<div class="n-body" id="companyCoverageBody"></div>
|
||||||
|
</div>
|
||||||
|
<div class="row" style="margin-top: 10px; gap: 8px; flex-wrap: wrap;">
|
||||||
|
<button type="button" class="btn btn-sm btn-primary" data-view-link="upload">去上传</button>
|
||||||
|
<button type="button" class="btn btn-sm" id="openAttestationFromWorkspace">提交无业务说明</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="card" id="workspaceTodos">
|
<div class="card" id="workspaceTodos">
|
||||||
<div class="card-head">
|
<div class="card-head">
|
||||||
<span class="card-title">本月待办<span class="sub" id="workspaceTodoSub">按权威待确认单边流水同步</span></span>
|
<span class="card-title">本月待办<span class="sub" id="workspaceTodoSub">按权威待确认单边流水同步</span></span>
|
||||||
@@ -141,59 +153,38 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="stack">
|
<div class="stack">
|
||||||
<div class="card">
|
<div class="card" id="workspaceTransfersCard">
|
||||||
<div class="card-head">
|
<div class="card-head">
|
||||||
<span class="card-title">本公司往来合计<span class="sub">2026-01-01 至 2026-08-20 · 与管理端口径一致 · 单位:万元</span></span>
|
<span class="card-title">转账往来概览<span class="sub" id="workspaceTransfersSub">加载中…</span></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="mini-stats">
|
<div class="mini-stats" id="workspaceTransfersStats">
|
||||||
<div class="mini-stat">
|
<div class="mini-stat">
|
||||||
<div class="ms-label">借方合计</div>
|
<div class="ms-label">转入合计</div>
|
||||||
<div class="ms-value">18,420.50<span class="unit">万元</span></div>
|
<div class="ms-value pos" id="wsTfIn">—</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="mini-stat">
|
<div class="mini-stat">
|
||||||
<div class="ms-label">贷方合计</div>
|
<div class="ms-label">转出合计</div>
|
||||||
<div class="ms-value">12,386.00<span class="unit">万元</span></div>
|
<div class="ms-value neg" id="wsTfOut">—</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="mini-stat">
|
<div class="mini-stat">
|
||||||
<div class="ms-label">明细笔数</div>
|
<div class="ms-label" id="wsTfNetLabel">期间净变动</div>
|
||||||
<div class="ms-value">128<span class="unit">笔</span></div>
|
<div class="ms-value" id="wsTfNet">—</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="mini-stat">
|
<div class="mini-stat">
|
||||||
<div class="ms-label">期末净往来 · 应收方向</div>
|
<div class="ms-label">待确认 · 不计入合计</div>
|
||||||
<div class="ms-value pos">+6,034.50<span class="unit">万元</span></div>
|
<div class="ms-value" id="wsTfPending" style="color: var(--warn);">—</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<button class="btn btn-ghost" data-view-link="flows" style="width: 100%; margin-top: 12px;">查看本公司逐笔流水 →</button>
|
<button class="btn btn-ghost" data-view-link="transfers" style="width: 100%; margin-top: 12px;">查看转账往来明细 →</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="card-head">
|
<div class="card-head">
|
||||||
<span class="card-title">最新通知<span class="sub">来自管理端</span></span>
|
<span class="card-title">最新通知<span class="sub">来自管理端</span></span>
|
||||||
<button class="btn btn-sm btn-ghost" data-view-link="notifications">全部通知 (3) →</button>
|
<button class="btn btn-sm btn-ghost" data-view-link="notifications" id="workspace-notice-link">全部通知 →</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="list-row">
|
<div id="workspace-notice-list">
|
||||||
<span class="pill pill-warn">提醒</span>
|
<div class="empty"><div class="e-title">暂无通知</div></div>
|
||||||
<div class="lr-main">
|
|
||||||
<div class="lr-title">7 月账期结账日顺延至 08-29</div>
|
|
||||||
<div class="lr-sub">请在此之前完成往来确认事项</div>
|
|
||||||
</div>
|
|
||||||
<span class="lr-side meta">08-18</span>
|
|
||||||
</div>
|
|
||||||
<div class="list-row">
|
|
||||||
<span class="pill pill-warn">提醒</span>
|
|
||||||
<div class="lr-main">
|
|
||||||
<div class="lr-title">3 笔单边流水待确认</div>
|
|
||||||
<div class="lr-sub">涉及金牛置业、金牛贸易往来</div>
|
|
||||||
</div>
|
|
||||||
<span class="lr-side meta">08-16</span>
|
|
||||||
</div>
|
|
||||||
<div class="list-row">
|
|
||||||
<span class="pill pill-success">通过</span>
|
|
||||||
<div class="lr-main">
|
|
||||||
<div class="lr-title">中行尾号 9916 流水导入成功</div>
|
|
||||||
<div class="lr-sub">流水覆盖至 08-12</div>
|
|
||||||
</div>
|
|
||||||
<span class="lr-side meta">08-12</span>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -310,7 +301,7 @@
|
|||||||
<div class="field"><label>金额(元)*</label><input class="input num-input" name="amount" type="number" min="0.01" step="0.01" required /></div>
|
<div class="field"><label>金额(元)*</label><input class="input num-input" name="amount" type="number" min="0.01" step="0.01" required /></div>
|
||||||
<div class="field"><label>资金来源 *</label><select class="select" name="sourceAccount" required><option value="">请选择</option><option>个人过账</option></select></div>
|
<div class="field"><label>资金来源 *</label><select class="select" name="sourceAccount" required><option value="">请选择</option><option>个人过账</option></select></div>
|
||||||
<div class="field"><label>对方类型 *</label><select class="select" name="counterpartyType" required><option>集团内部公司</option><option>个人过账方</option><option>外部单位</option></select></div>
|
<div class="field"><label>对方类型 *</label><select class="select" name="counterpartyType" required><option>集团内部公司</option><option>个人过账方</option><option>外部单位</option></select></div>
|
||||||
<div class="field"><label>对方名称 *</label><input class="input" name="counterparty" maxlength="100" placeholder="公司全称或个人姓名" required /></div>
|
<div class="field"><label>对方公司 *</label><select class="select" name="counterparty" id="manualCounterparty" required><option value="">请选择集团内公司</option></select></div>
|
||||||
<div class="field"><label>对方账号</label><input class="input" name="counterpartyAccount" maxlength="64" placeholder="可选" /></div>
|
<div class="field"><label>对方账号</label><input class="input" name="counterpartyAccount" maxlength="64" placeholder="可选" /></div>
|
||||||
<div class="field"><label>往来科目 *</label><select class="select" name="subject" required><option>应收</option><option>应付</option><option>其他应收</option><option>其他应付</option></select></div>
|
<div class="field"><label>往来科目 *</label><select class="select" name="subject" required><option>应收</option><option>应付</option><option>其他应收</option><option>其他应付</option></select></div>
|
||||||
</div>
|
</div>
|
||||||
@@ -356,6 +347,16 @@
|
|||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section class="app-view" data-page="flows">
|
<section class="app-view" data-page="flows">
|
||||||
|
<div class="notice danger" id="flowsCoverageNotice" style="display: none; margin-bottom: 14px;">
|
||||||
|
<div>
|
||||||
|
<div class="n-title">流水断档提醒</div>
|
||||||
|
<div class="n-body" id="flowsCoverageBody"></div>
|
||||||
|
</div>
|
||||||
|
<div class="row" style="margin-top: 10px; gap: 8px;">
|
||||||
|
<button type="button" class="btn btn-sm btn-primary" data-view-link="upload">去上传</button>
|
||||||
|
<button type="button" class="btn btn-sm" id="openAttestationFromFlows">提交无业务说明</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<div class="page-head">
|
<div class="page-head">
|
||||||
<div>
|
<div>
|
||||||
<h1>流水管理</h1>
|
<h1>流水管理</h1>
|
||||||
@@ -421,6 +422,224 @@
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="app-view" data-page="transfers">
|
||||||
|
<div id="transfersOverviewLayer">
|
||||||
|
<div class="page-head">
|
||||||
|
<div>
|
||||||
|
<h1>转账往来</h1>
|
||||||
|
<p class="page-sub" id="transfersPageSub">加载本公司与集团内其他公司的转账往来…</p>
|
||||||
|
</div>
|
||||||
|
<div class="page-actions">
|
||||||
|
<button class="btn" type="button" id="transfersExportBtn">导出台账</button>
|
||||||
|
<button class="btn btn-primary" type="button" id="transfersGoConfirm" data-view-link="reconcile" hidden>去确认待确认</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="transfersLoading" class="card" hidden>
|
||||||
|
<div class="grid grid-4" style="margin-bottom: 14px;">
|
||||||
|
<div class="skeleton" style="height: 88px;"></div>
|
||||||
|
<div class="skeleton" style="height: 88px;"></div>
|
||||||
|
<div class="skeleton" style="height: 88px;"></div>
|
||||||
|
<div class="skeleton" style="height: 88px;"></div>
|
||||||
|
</div>
|
||||||
|
<div class="skeleton skeleton-line" style="width: 70%;"></div>
|
||||||
|
<div class="skeleton skeleton-line" style="width: 92%;"></div>
|
||||||
|
<div class="skeleton skeleton-line" style="width: 55%; margin-bottom: 0;"></div>
|
||||||
|
<div class="loading-inline" style="margin-top: 16px;">加载中,正在计算往来余额…</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="transfersError" class="notice danger" hidden>
|
||||||
|
<div>
|
||||||
|
<div class="n-title">转账往来数据加载失败</div>
|
||||||
|
<div class="n-body" id="transfersErrorBody">服务器连接异常。为避免误读,本页不展示任何金额。</div>
|
||||||
|
</div>
|
||||||
|
<div class="row" style="margin-top: 12px; gap: 8px;">
|
||||||
|
<button class="btn btn-primary" type="button" id="transfersRetryBtn">重新加载</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="transfersEmpty" class="card" hidden>
|
||||||
|
<div class="grid grid-4" id="transfersEmptyStats"></div>
|
||||||
|
<div class="empty" style="margin-top: 14px;">
|
||||||
|
<div class="e-title">该期间暂无转账往来</div>
|
||||||
|
<div>可能尚未导入流水,或集团内往来确认尚未完成。导入本公司银行流水后,系统会自动计算公司间往来。</div>
|
||||||
|
<div class="row" style="justify-content: center; margin-top: 14px; gap: 8px;">
|
||||||
|
<button class="btn btn-primary" type="button" data-view-link="upload">去导入流水</button>
|
||||||
|
<button class="btn" type="button" data-view-link="accounts">查看银行账户</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="transfersData" hidden>
|
||||||
|
<div class="grid grid-4" id="transfersStatGrid">
|
||||||
|
<div class="card stat-card" id="tfStatOpeningCard" hidden>
|
||||||
|
<div class="stat-label"><span class="stat-dot muted"></span>期初余额</div>
|
||||||
|
<div class="stat-value" id="tfStatOpening">—</div>
|
||||||
|
<div class="stat-foot">起算日前一日结转</div>
|
||||||
|
</div>
|
||||||
|
<div class="card stat-card">
|
||||||
|
<div class="stat-label"><span class="stat-dot info"></span>往来公司数</div>
|
||||||
|
<div class="stat-value" id="tfStatCompanies">—<span class="unit">家</span></div>
|
||||||
|
<div class="stat-foot" id="tfStatCompaniesFoot">统计窗口内有往来的对方公司</div>
|
||||||
|
</div>
|
||||||
|
<div class="card stat-card">
|
||||||
|
<div class="stat-label"><span class="stat-dot success"></span>本期转入 · 流入</div>
|
||||||
|
<div class="stat-value amt-in" id="tfStatIn">—</div>
|
||||||
|
<div class="stat-foot">已确认转入合计 · 待确认不计入</div>
|
||||||
|
</div>
|
||||||
|
<div class="card stat-card">
|
||||||
|
<div class="stat-label"><span class="stat-dot danger"></span>本期转出 · 流出</div>
|
||||||
|
<div class="stat-value amt-out" id="tfStatOut">—</div>
|
||||||
|
<div class="stat-foot">已确认转出合计 · 待确认不计入</div>
|
||||||
|
</div>
|
||||||
|
<div class="card stat-card">
|
||||||
|
<div class="stat-label"><span class="stat-dot info"></span><span id="tfStatNetTitle">期间净变动</span></div>
|
||||||
|
<div class="stat-value" id="tfStatNet">—</div>
|
||||||
|
<div class="stat-foot" id="tfStatNetFoot">正数=应收方向 · 负数=应付方向</div>
|
||||||
|
</div>
|
||||||
|
<div class="card stat-card" id="tfStatEndingCard" hidden>
|
||||||
|
<div class="stat-label"><span class="stat-dot success"></span>期末余额</div>
|
||||||
|
<div class="stat-value" id="tfStatEnding">—</div>
|
||||||
|
<div class="stat-foot">期初 + 本期变动</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="xfer-split" id="transfersSplit" style="margin-top: 14px;">
|
||||||
|
<div class="xfer-split-pane confirmed">
|
||||||
|
<div class="xfer-split-head">
|
||||||
|
<span class="pill pill-success">已确认</span>
|
||||||
|
<span class="meta" id="tfConfirmedCount">0 笔</span>
|
||||||
|
</div>
|
||||||
|
<div class="xfer-split-value num" id="tfConfirmedNet">—</div>
|
||||||
|
<div class="xfer-split-note">计入上方合计与期间净变动</div>
|
||||||
|
</div>
|
||||||
|
<div class="xfer-split-pane pending">
|
||||||
|
<div class="xfer-split-head">
|
||||||
|
<span class="pill pill-warn">待确认</span>
|
||||||
|
<span class="meta" id="tfPendingCount">0 笔</span>
|
||||||
|
</div>
|
||||||
|
<div class="xfer-split-value num" id="tfPendingAmount">—</div>
|
||||||
|
<div class="xfer-split-note">单列展示,不计入已确认合计</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card" style="margin-top: 14px;">
|
||||||
|
<div class="card-head">
|
||||||
|
<span class="card-title">按对方公司查看<span class="sub">点击行进入该公司往来明细</span></span>
|
||||||
|
<span class="pill pill-info">仅本公司数据</span>
|
||||||
|
</div>
|
||||||
|
<div class="table-wrap" style="border: 0;">
|
||||||
|
<table class="ds-table" id="transfersCpTable">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>对方公司</th>
|
||||||
|
<th class="num-col">已确认转入</th>
|
||||||
|
<th class="num-col">已确认转出</th>
|
||||||
|
<th class="num-col">净往来</th>
|
||||||
|
<th>方向</th>
|
||||||
|
<th>待确认</th>
|
||||||
|
<th>最近往来日</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="transfersCpBody"></tbody>
|
||||||
|
<tfoot id="transfersCpFoot"></tfoot>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="notice info" style="margin-top: 14px;">
|
||||||
|
<div class="n-title">口径说明</div>
|
||||||
|
<div class="n-body">仅含集团内公司间转账(HEL-169)。已确认与待确认严格分开;待确认不计入合计。起算日/期初未就绪时展示「期间净变动」,不得当作期末余额。银行原始流水只读,调整须走冲销/调整单留痕。</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="transfersDetailLayer" hidden>
|
||||||
|
<div class="page-head">
|
||||||
|
<div>
|
||||||
|
<button class="btn btn-ghost" type="button" id="transfersBackBtn" style="padding-left: 0; margin-bottom: 4px;">← 返回总览</button>
|
||||||
|
<h1 id="transfersDetailTitle">往来明细</h1>
|
||||||
|
<p class="page-sub" id="transfersDetailSub">筛选后加载更多 · 单位:万元</p>
|
||||||
|
</div>
|
||||||
|
<div class="page-actions">
|
||||||
|
<button class="btn" type="button" id="transfersDetailExportBtn">导出台账</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid grid-3" id="transfersDetailStats" style="margin-bottom: 14px;">
|
||||||
|
<div class="card stat-card">
|
||||||
|
<div class="stat-label">往来笔数</div>
|
||||||
|
<div class="stat-value" id="tfDetailCount">—</div>
|
||||||
|
<div class="stat-foot" id="tfDetailCountFoot">当前筛选</div>
|
||||||
|
</div>
|
||||||
|
<div class="card stat-card">
|
||||||
|
<div class="stat-label">转入 · 流入</div>
|
||||||
|
<div class="stat-value amt-in" id="tfDetailIn">—</div>
|
||||||
|
</div>
|
||||||
|
<div class="card stat-card">
|
||||||
|
<div class="stat-label">转出 · 流出</div>
|
||||||
|
<div class="stat-value amt-out" id="tfDetailOut">—</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form class="filters" id="transfersFilterForm" novalidate>
|
||||||
|
<div class="field">
|
||||||
|
<label for="tfFilterDirection">方向</label>
|
||||||
|
<select class="select" id="tfFilterDirection" name="direction">
|
||||||
|
<option value="">全部</option>
|
||||||
|
<option value="in">转入</option>
|
||||||
|
<option value="out">转出</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="tfFilterState">确认状态</label>
|
||||||
|
<select class="select" id="tfFilterState" name="state">
|
||||||
|
<option value="">全部</option>
|
||||||
|
<option value="confirmed">已确认</option>
|
||||||
|
<option value="pending">待确认</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="tfFilterFrom">日期起</label>
|
||||||
|
<input class="input num-input" id="tfFilterFrom" name="from" type="date" />
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="tfFilterTo">日期止</label>
|
||||||
|
<input class="input num-input" id="tfFilterTo" name="to" type="date" />
|
||||||
|
</div>
|
||||||
|
<button class="btn" type="button" id="tfFilterReset">清空筛选</button>
|
||||||
|
<button class="btn btn-primary" type="submit">查询</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="ds-table" id="transfersEventTable">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>日期</th>
|
||||||
|
<th class="wrap">摘要</th>
|
||||||
|
<th>方向</th>
|
||||||
|
<th class="num-col">金额(万元)</th>
|
||||||
|
<th>状态</th>
|
||||||
|
<th></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody id="transfersEventBody"></tbody>
|
||||||
|
</table>
|
||||||
|
<div class="empty" id="transfersEventEmpty" hidden>
|
||||||
|
<div class="e-title">当前筛选条件下没有流水</div>
|
||||||
|
<div>可清空筛选后重试,或返回总览查看其他对方公司。</div>
|
||||||
|
<div class="row" style="justify-content: center; margin-top: 12px;">
|
||||||
|
<button class="btn" type="button" id="tfEmptyClear">清空筛选</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="table-foot">
|
||||||
|
<span id="transfersEventFoot">共 0 笔</span>
|
||||||
|
<button class="btn btn-sm" type="button" id="transfersLoadMore" hidden>加载更多</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<section class="app-view" data-page="reconcile">
|
<section class="app-view" data-page="reconcile">
|
||||||
<div class="page-head">
|
<div class="page-head">
|
||||||
<div>
|
<div>
|
||||||
@@ -564,93 +783,15 @@
|
|||||||
|
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="tabs" id="notice-tabs">
|
<div class="tabs" id="notice-tabs">
|
||||||
<button type="button" class="active" data-filter="all" aria-pressed="true">全部<span class="tab-count" id="count-all">9</span></button>
|
<button type="button" class="active" data-filter="all" aria-pressed="true">全部<span class="tab-count" id="count-all">0</span></button>
|
||||||
<button type="button" data-filter="unread" aria-pressed="false">未读<span class="tab-count" id="count-unread">3</span></button>
|
<button type="button" data-filter="unread" aria-pressed="false">未读<span class="tab-count" id="count-unread">0</span></button>
|
||||||
<button type="button" data-filter="doing" aria-pressed="false">处理中<span class="tab-count" id="count-doing">2</span></button>
|
<button type="button" data-filter="doing" aria-pressed="false">处理中<span class="tab-count" id="count-doing">0</span></button>
|
||||||
<button type="button" data-filter="done" aria-pressed="false">已完成<span class="tab-count" id="count-done">4</span></button>
|
<button type="button" data-filter="done" aria-pressed="false">已完成<span class="tab-count" id="count-done">0</span></button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="notice-list">
|
<div id="notice-list"></div>
|
||||||
<div class="list-row" data-status="unread">
|
|
||||||
<span class="pill pill-danger" style="flex: none;">未读</span>
|
|
||||||
<span class="tag">系统</span>
|
|
||||||
<div class="lr-main">
|
|
||||||
<div class="lr-title">7 月流水存在断档风险:交行 尾号 7710 未上传</div>
|
|
||||||
<div class="lr-sub"><span class="meta">2026-08-20 14:32</span> · 交行 7710 账户(待审核)7 月流水尚未上传,距 7 月结账日(顺延至 08-29)仅剩 9 天,请尽快补传。</div>
|
|
||||||
</div>
|
|
||||||
<div class="lr-side"><button class="btn btn-sm btn-mark-read">标记已读</button></div>
|
|
||||||
</div>
|
|
||||||
<div class="list-row" data-status="unread">
|
|
||||||
<span class="pill pill-danger" style="flex: none;">未读</span>
|
|
||||||
<span class="tag">系统</span>
|
|
||||||
<div class="lr-main">
|
|
||||||
<div class="lr-title">您有 2 笔单边流水待选择对方证据</div>
|
|
||||||
<div class="lr-sub"><span class="meta">2026-08-19 09:15</span> · 与金牛置业的煤炭采购款 ¥3,200,000.00 等 2 笔流水仅有本方记录,需选择对方银行流水佐证。</div>
|
|
||||||
</div>
|
|
||||||
<div class="lr-side"><button class="btn btn-sm btn-mark-read">标记已读</button></div>
|
|
||||||
</div>
|
|
||||||
<div class="list-row" data-status="unread">
|
|
||||||
<span class="pill pill-danger" style="flex: none;">未读</span>
|
|
||||||
<span class="tag">管理员</span>
|
|
||||||
<div class="lr-main">
|
|
||||||
<div class="lr-title">管理员提醒:请于 08-29 前完成待确认事项</div>
|
|
||||||
<div class="lr-sub"><span class="meta">2026-08-18 16:40</span> · 7 月账期结账顺延至 08-29,贵公司当前仍有 5 项往来确认未完成,请合理安排时间。</div>
|
|
||||||
</div>
|
|
||||||
<div class="lr-side"><button class="btn btn-sm btn-mark-read">标记已读</button></div>
|
|
||||||
</div>
|
|
||||||
<div class="list-row" data-status="doing">
|
|
||||||
<span class="pill pill-warn" style="flex: none;">处理中</span>
|
|
||||||
<span class="tag">系统</span>
|
|
||||||
<div class="lr-main">
|
|
||||||
<div class="lr-title">手工记录科目待确认:其他应收 ¥86,500.00</div>
|
|
||||||
<div class="lr-sub"><span class="meta">2026-08-15 10:02</span> · 07-28 录入的矿区备用金垫付记录,往来科目「其他应收」待管理员复核。</div>
|
|
||||||
</div>
|
|
||||||
<div class="lr-side"><button class="btn btn-sm btn-primary" data-view-link="manual">去处理</button></div>
|
|
||||||
</div>
|
|
||||||
<div class="list-row" data-status="doing">
|
|
||||||
<span class="pill pill-warn" style="flex: none;">处理中</span>
|
|
||||||
<span class="tag">管理员</span>
|
|
||||||
<div class="lr-main">
|
|
||||||
<div class="lr-title">往来确认回复:置业已确认 320 万煤炭采购款</div>
|
|
||||||
<div class="lr-sub"><span class="meta">2026-08-12 11:26</span> · 金牛置业已确认 07-14 煤炭采购款 ¥3,200,000.00,请补充本方工行 3305 账户流水证据完成闭环。</div>
|
|
||||||
</div>
|
|
||||||
<div class="lr-side"><button class="btn btn-sm btn-primary" data-view-link="reconcile">去处理</button></div>
|
|
||||||
</div>
|
|
||||||
<div class="list-row" data-status="done">
|
|
||||||
<span class="pill pill-success" style="flex: none;">已完成</span>
|
|
||||||
<span class="tag">系统</span>
|
|
||||||
<div class="lr-main">
|
|
||||||
<div class="lr-title">流水导入成功:中行 尾号 9916 · 42 笔</div>
|
|
||||||
<div class="lr-sub"><span class="meta">2026-08-06 15:52</span> · 7 月中行一般户流水已导入,42 笔全部校验通过,无重复记录。</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="list-row" data-status="done">
|
|
||||||
<span class="pill pill-success" style="flex: none;">已完成</span>
|
|
||||||
<span class="tag">系统</span>
|
|
||||||
<div class="lr-main">
|
|
||||||
<div class="lr-title">流水导入成功:工行 尾号 3305 · 86 笔</div>
|
|
||||||
<div class="lr-sub"><span class="meta">2026-08-06 15:48</span> · 7 月工行基本户流水已导入,86 笔全部校验通过,无重复记录。</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="list-row" data-status="done">
|
|
||||||
<span class="pill pill-success" style="flex: none;">已完成</span>
|
|
||||||
<span class="tag">管理员</span>
|
|
||||||
<div class="lr-main">
|
|
||||||
<div class="lr-title">交行 尾号 7710 账户开户资料已受理</div>
|
|
||||||
<div class="lr-sub"><span class="meta">2026-07-22 13:10</span> · 新账户开户资料已提交管理员,审核通过后方可启用并上传流水。</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="list-row" data-status="done">
|
|
||||||
<span class="pill pill-success" style="flex: none;">已完成</span>
|
|
||||||
<span class="tag">系统</span>
|
|
||||||
<div class="lr-main">
|
|
||||||
<div class="lr-title">2026 年 6 月账期已结账</div>
|
|
||||||
<div class="lr-sub"><span class="meta">2026-07-05 09:00</span> · 6 月账期已按每月 5 日结账规则完成结账,期末数据已锁定,不可再修改。</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="empty" id="notice-empty" style="display: none;">
|
<div class="empty" id="notice-empty">
|
||||||
<div class="e-title">暂无该状态的通知</div>
|
<div class="e-title">暂无该状态的通知</div>
|
||||||
<div>切换其他状态查看,或等待新的系统与管理员消息。</div>
|
<div>切换其他状态查看,或等待新的系统与管理员消息。</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -661,6 +802,37 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 导入批次详情弹窗 -->
|
<!-- 导入批次详情弹窗 -->
|
||||||
|
<div class="modal-backdrop" id="attestationDialog">
|
||||||
|
<div class="modal">
|
||||||
|
<div class="modal-head">
|
||||||
|
<span class="modal-title">提交无业务说明</span>
|
||||||
|
<button type="button" class="modal-close" data-close-attestation aria-label="关闭">×</button>
|
||||||
|
</div>
|
||||||
|
<p class="modal-sub">说明经管理员审核通过后仅关闭断档提醒,不会生成银行流水。</p>
|
||||||
|
<form id="attestationForm" novalidate>
|
||||||
|
<input type="hidden" id="att-gap-start" name="gap_start" />
|
||||||
|
<input type="hidden" id="att-gap-end" name="gap_end" />
|
||||||
|
<input type="hidden" id="att-account-id" name="bank_account_id" />
|
||||||
|
<div class="field">
|
||||||
|
<label>断档区间</label>
|
||||||
|
<div class="meta num" id="att-gap-label">—</div>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="att-reason">说明(至少 5 个字)</label>
|
||||||
|
<textarea class="input" id="att-reason" name="reason" rows="3" required></textarea>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="att-evidence">佐证(可选)</label>
|
||||||
|
<input class="input" id="att-evidence" name="evidence" placeholder="如:节假日无业务、账户停用说明编号" />
|
||||||
|
</div>
|
||||||
|
<div class="modal-actions">
|
||||||
|
<button type="button" class="btn" data-close-attestation>取消</button>
|
||||||
|
<button type="submit" class="btn btn-primary">提交审核</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="modal-backdrop" id="modal-batch">
|
<div class="modal-backdrop" id="modal-batch">
|
||||||
<div class="modal">
|
<div class="modal">
|
||||||
<div class="modal-head">
|
<div class="modal-head">
|
||||||
@@ -813,7 +985,30 @@
|
|||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<aside class="drawer" id="transferEvidenceDrawer" aria-label="银行原始流水" aria-hidden="true">
|
||||||
|
<div class="drawer-head">
|
||||||
|
<div>
|
||||||
|
<span class="pill pill-info" id="tfEvTag">银行原始流水 · 只读</span>
|
||||||
|
<h2 class="d-title" id="tfEvTitle">原始流水</h2>
|
||||||
|
<p class="d-desc" id="tfEvDesc"></p>
|
||||||
|
</div>
|
||||||
|
<button type="button" class="icon-button" data-close-transfer-evidence aria-label="关闭" title="关闭">
|
||||||
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7"><path d="M6 6l12 12M18 6L6 18"/></svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="drawer-body">
|
||||||
|
<dl class="kv" id="tfEvFields"></dl>
|
||||||
|
</div>
|
||||||
|
<div class="drawer-tip">
|
||||||
|
<strong>铁律提示</strong>
|
||||||
|
银行原始流水永远只读。金额或归属有误时,须由管理员通过冲销/调整单留痕处理,本页不得直接改数。
|
||||||
|
</div>
|
||||||
|
<div class="drawer-foot">
|
||||||
|
<button type="button" class="btn" data-close-transfer-evidence>关闭</button>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
<div class="toast-region" id="toastRegion" aria-live="polite"></div>
|
<div class="toast-region" id="toastRegion" aria-live="polite"></div>
|
||||||
<script src="app.js?v=10"></script>
|
<script src="app.js?v=15"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -988,3 +988,306 @@ a.flow-step.doing:hover { background: color-mix(in oklch, var(--warn) 16%, trans
|
|||||||
/* ─── 提示条补充:成功态 ───────────────────────────────────────── */
|
/* ─── 提示条补充:成功态 ───────────────────────────────────────── */
|
||||||
.notice.success { background: var(--success-soft); border-color: color-mix(in oklch, var(--success) 30%, transparent); }
|
.notice.success { background: var(--success-soft); border-color: color-mix(in oklch, var(--success) 30%, transparent); }
|
||||||
.notice.success .n-title { color: color-mix(in oklch, var(--success) 82%, black); }
|
.notice.success .n-title { color: color-mix(in oklch, var(--success) 82%, black); }
|
||||||
|
|
||||||
|
/* ─── 公司端 · 转账往来(方案 A,HEL-177)───────────────────────────
|
||||||
|
新模块范围内用 --info 品蓝;不改全站 accent。取值一律既有 token。 */
|
||||||
|
body[data-portal="company"] .side-nav a[data-view="transfers"].active {
|
||||||
|
background: var(--info-soft);
|
||||||
|
color: var(--fg);
|
||||||
|
}
|
||||||
|
body[data-portal="company"] .side-nav a[data-view="transfers"].active svg {
|
||||||
|
color: var(--info);
|
||||||
|
}
|
||||||
|
[data-page="transfers"] .btn-primary {
|
||||||
|
background: var(--info);
|
||||||
|
border-color: var(--info);
|
||||||
|
color: var(--surface);
|
||||||
|
}
|
||||||
|
[data-page="transfers"] .btn-primary:hover {
|
||||||
|
background: color-mix(in oklch, var(--info) 88%, black);
|
||||||
|
border-color: color-mix(in oklch, var(--info) 88%, black);
|
||||||
|
}
|
||||||
|
[data-page="transfers"] .loading-inline::before {
|
||||||
|
border-top-color: var(--info);
|
||||||
|
}
|
||||||
|
[data-page="transfers"] .stat-card .stat-value.amt-in { color: var(--success); }
|
||||||
|
[data-page="transfers"] .stat-card .stat-value.amt-out { color: var(--danger); }
|
||||||
|
[data-page="transfers"] .ds-table tbody tr.is-pending {
|
||||||
|
background: color-mix(in oklch, var(--warn) 8%, transparent);
|
||||||
|
}
|
||||||
|
[data-page="transfers"] .ds-table tbody tr.is-pending:hover {
|
||||||
|
background: color-mix(in oklch, var(--warn) 14%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.xfer-split {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1fr 1fr;
|
||||||
|
gap: 0;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
overflow: hidden;
|
||||||
|
background: var(--surface);
|
||||||
|
}
|
||||||
|
.xfer-split-pane {
|
||||||
|
padding: 16px 18px;
|
||||||
|
}
|
||||||
|
.xfer-split-pane.confirmed {
|
||||||
|
background: color-mix(in oklch, var(--success) 6%, var(--surface));
|
||||||
|
border-right: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.xfer-split-pane.pending {
|
||||||
|
background: color-mix(in oklch, var(--warn) 8%, var(--surface));
|
||||||
|
}
|
||||||
|
.xfer-split-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 10px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
.xfer-split-value {
|
||||||
|
font-size: 22px;
|
||||||
|
font-weight: 650;
|
||||||
|
letter-spacing: -0.02em;
|
||||||
|
}
|
||||||
|
.xfer-split-pane.confirmed .xfer-split-value { color: var(--success); }
|
||||||
|
.xfer-split-pane.pending .xfer-split-value { color: color-mix(in oklch, var(--warn) 80%, black); }
|
||||||
|
.xfer-split-note {
|
||||||
|
margin-top: 6px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
.xfer-dir-tag {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
padding: 2px 8px;
|
||||||
|
border-radius: 999px;
|
||||||
|
}
|
||||||
|
.xfer-dir-tag.recv {
|
||||||
|
background: var(--success-soft);
|
||||||
|
color: var(--success);
|
||||||
|
}
|
||||||
|
.xfer-dir-tag.pay {
|
||||||
|
background: var(--danger-soft);
|
||||||
|
color: var(--danger);
|
||||||
|
}
|
||||||
|
.xfer-dir-tag.flat {
|
||||||
|
background: var(--fg-soft);
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 820px) {
|
||||||
|
.xfer-split { grid-template-columns: 1fr; }
|
||||||
|
.xfer-split-pane.confirmed { border-right: 0; border-bottom: 1px solid var(--border); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ─── 提醒管理:三步发送流(HEL-230) ─────────────────────────── */
|
||||||
|
.send-flow {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1fr) minmax(0, 1.5fr) minmax(0, 1fr);
|
||||||
|
align-items: stretch;
|
||||||
|
gap: 0;
|
||||||
|
}
|
||||||
|
.sf-step {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
min-width: 0;
|
||||||
|
padding: 0 18px;
|
||||||
|
}
|
||||||
|
.sf-step:first-child { padding-left: 0; }
|
||||||
|
.sf-step:last-child { padding-right: 0; }
|
||||||
|
.sf-step + .sf-step { border-left: 1px solid var(--border); }
|
||||||
|
.sf-step-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.sf-idx {
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 650;
|
||||||
|
color: var(--accent);
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
.sf-step-head > span:nth-child(2) { font-size: 13px; font-weight: 650; }
|
||||||
|
.sf-step-head .meta { margin-left: auto; }
|
||||||
|
.sf-step .hint { font-size: 11.5px; color: var(--muted); }
|
||||||
|
.sf-step .hint.error { color: var(--danger); }
|
||||||
|
.pick-list {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
.pick {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
padding: 5px 10px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 999px;
|
||||||
|
background: var(--surface);
|
||||||
|
color: var(--fg);
|
||||||
|
font-size: 13px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background 0.12s ease, border-color 0.12s ease, color 0.12s ease;
|
||||||
|
}
|
||||||
|
.pick:hover { background: var(--fg-soft); }
|
||||||
|
.pick:has(input:checked) {
|
||||||
|
background: var(--accent-soft);
|
||||||
|
border-color: var(--accent);
|
||||||
|
color: var(--accent);
|
||||||
|
}
|
||||||
|
.pick input { width: auto; margin: 0; }
|
||||||
|
.sf-send {
|
||||||
|
margin-top: auto;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.sf-send .btn-primary { width: 100%; }
|
||||||
|
|
||||||
|
[data-page="reminders"] .history-table {
|
||||||
|
border: 0;
|
||||||
|
}
|
||||||
|
[data-page="reminders"] .history-table .ds-table {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
[data-page="reminders"] .history-table .ds-table th:nth-child(1),
|
||||||
|
[data-page="reminders"] .history-table .ds-table td:nth-child(1) {
|
||||||
|
width: 14%;
|
||||||
|
}
|
||||||
|
[data-page="reminders"] .history-table .ds-table th:nth-child(4),
|
||||||
|
[data-page="reminders"] .history-table .ds-table td:nth-child(4) {
|
||||||
|
width: 28%;
|
||||||
|
white-space: normal;
|
||||||
|
min-width: 160px;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 1100px) {
|
||||||
|
.send-flow { grid-template-columns: minmax(0, 1fr); }
|
||||||
|
.sf-step { padding: 14px 0 0; }
|
||||||
|
.sf-step:first-child { padding-top: 0; }
|
||||||
|
.sf-step + .sf-step {
|
||||||
|
border-left: 0;
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ─── 月结 / 重开 / 审计(HEL-268,仅 5 条组件规则) ───────────── */
|
||||||
|
.btn-warn {
|
||||||
|
background: var(--warn);
|
||||||
|
border-color: var(--warn);
|
||||||
|
color: var(--surface);
|
||||||
|
}
|
||||||
|
.btn-warn:hover {
|
||||||
|
background: color-mix(in oklch, var(--warn) 88%, black);
|
||||||
|
border-color: color-mix(in oklch, var(--warn) 88%, black);
|
||||||
|
}
|
||||||
|
.btn-warn[disabled] {
|
||||||
|
opacity: 1;
|
||||||
|
background: var(--fg-soft);
|
||||||
|
border-color: var(--border);
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pill-lock {
|
||||||
|
background: var(--fg-soft);
|
||||||
|
color: var(--muted);
|
||||||
|
height: 23px;
|
||||||
|
}
|
||||||
|
.pill-lock::before {
|
||||||
|
width: 11px;
|
||||||
|
height: 11px;
|
||||||
|
border-radius: 0;
|
||||||
|
background-color: currentColor;
|
||||||
|
mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2'%3E%3Crect x='5' y='11' width='14' height='10' rx='1.5'/%3E%3Cpath d='M8 11V8a4 4 0 0 1 8 0v3'/%3E%3C/svg%3E") center / contain no-repeat;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tl-cell.locked { background: var(--fg-soft); }
|
||||||
|
.tl-cell.locked .tl-state { color: var(--muted); }
|
||||||
|
.tl-cell.locked .tl-state::before {
|
||||||
|
content: "";
|
||||||
|
width: 11px;
|
||||||
|
height: 11px;
|
||||||
|
background-color: currentColor;
|
||||||
|
mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2'%3E%3Crect x='5' y='11' width='14' height='10' rx='1.5'/%3E%3Cpath d='M8 11V8a4 4 0 0 1 8 0v3'/%3E%3C/svg%3E") center / contain no-repeat;
|
||||||
|
}
|
||||||
|
.tl-cell.reopened { background: var(--warn-soft); }
|
||||||
|
.tl-cell.reopened .tl-state { color: color-mix(in oklch, var(--warn) 80%, black); }
|
||||||
|
.tl-cell.failed { background: var(--danger-soft); }
|
||||||
|
.tl-cell.failed .tl-state { color: var(--danger); }
|
||||||
|
|
||||||
|
.diff-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);
|
||||||
|
gap: 10px 12px;
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
.diff-grid .diff-row {
|
||||||
|
display: contents;
|
||||||
|
}
|
||||||
|
.diff-grid .diff-label {
|
||||||
|
grid-column: 1 / -1;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
.diff-grid .diff-before {
|
||||||
|
color: var(--muted);
|
||||||
|
text-decoration: line-through;
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.diff-grid .diff-arrow {
|
||||||
|
color: var(--muted);
|
||||||
|
align-self: center;
|
||||||
|
}
|
||||||
|
.diff-grid .diff-after {
|
||||||
|
color: color-mix(in oklch, var(--warn) 78%, black);
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.diff-grid .diff-row.changed .diff-before,
|
||||||
|
.diff-grid .diff-row.changed .diff-after,
|
||||||
|
.diff-grid .diff-row.changed .diff-arrow {
|
||||||
|
box-shadow: inset 3px 0 0 var(--warn);
|
||||||
|
padding-left: 8px;
|
||||||
|
}
|
||||||
|
@media (max-width: 860px) {
|
||||||
|
.diff-grid { grid-template-columns: minmax(0, 1fr); }
|
||||||
|
.diff-grid .diff-arrow { transform: rotate(90deg); justify-self: center; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-icon {
|
||||||
|
width: 48px;
|
||||||
|
height: 48px;
|
||||||
|
margin: 0 auto 12px;
|
||||||
|
color: var(--border);
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.closing-panel.is-processing {
|
||||||
|
pointer-events: none;
|
||||||
|
opacity: 0.55;
|
||||||
|
}
|
||||||
|
.closing-kv {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||||
|
gap: 12px;
|
||||||
|
margin-top: 16px;
|
||||||
|
padding-top: 14px;
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.closing-kv .ck-label { font-size: 12px; color: var(--muted); }
|
||||||
|
.closing-kv .ck-value { font-family: var(--font-mono); font-size: 13px; margin-top: 4px; }
|
||||||
|
.lock-view-only { color: var(--muted); font-size: 12px; }
|
||||||
|
.audit-event-cards { display: none; }
|
||||||
|
@media (max-width: 460px) {
|
||||||
|
.closing-kv { grid-template-columns: 1fr 1fr; }
|
||||||
|
[data-page="period-audit"] .table-wrap { display: none; }
|
||||||
|
.audit-event-cards { display: grid; gap: 10px; }
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user