Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9193a3fce0 | ||
|
|
9e0e4a103a | ||
|
|
2d0ae4d7d1 | ||
|
|
9cfd515b8f | ||
|
|
267ebd37f5 | ||
|
|
e857a0e46d | ||
|
|
c1c41760f5 | ||
|
|
e5e326514d | ||
|
|
f5e0915f63 |
@@ -9,6 +9,7 @@ data/
|
||||
uploads/
|
||||
exports/
|
||||
*.local
|
||||
deploy/.env
|
||||
server.pid
|
||||
server.out.log
|
||||
server.err.log
|
||||
@@ -27,3 +28,9 @@ package-lock.json
|
||||
# local vendor for agent test env (not shipped)
|
||||
.vendor/
|
||||
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/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;
|
||||
}
|
||||
}
|
||||
+12
-12
@@ -1,29 +1,29 @@
|
||||
# 任务清单
|
||||
|
||||
最后核对:2026-08-23。状态以当前代码和已合并提交为准。
|
||||
最后核对:2026-08-30。状态以当前代码和已合并提交为准。
|
||||
|
||||
## 正在做
|
||||
|
||||
- 当前没有已确认正在进行的业务功能开发。下一项工作开始前,先在此处写明负责人、范围和验收标准。
|
||||
- HEL-270 上线前总验收(总工):代码审核、测试环境部署、备份恢复与回滚演练、边界自动化证据。
|
||||
|
||||
## 已做完
|
||||
|
||||
- 六类银行流水模板识别与解析。
|
||||
- 数据库迁移、不可变原始证据、导入批次和重复导入处理。
|
||||
- 管理员/公司用户登录、密码策略、会话、限流、服务端公司隔离和审计。
|
||||
- 数据库迁移(至版本 10)、不可变原始证据、导入批次和重复导入处理;文件库 WAL。
|
||||
- 管理员/公司用户登录、密码策略、会话清理、限流、服务端公司隔离和审计。
|
||||
- 动态公司、用户、银行账户、别名与账户审核流程。
|
||||
- 导入接口加固、逐工作表确认、失败诊断和导出。
|
||||
- 规范转账事件、双边匹配、同公司调拨排除与个人过账映射。
|
||||
- 登录页视觉融合改版。
|
||||
- 起算日、期初余额、流水覆盖断档检测和无业务校准。
|
||||
- 月结、重开审批、闭期补录、锁账写保护、月报与审计记录。
|
||||
- 服务端流水查询、筛选、分页和可追溯导出;往来查询与手工记录接入真实接口。
|
||||
- 站内提醒与状态流转。
|
||||
- 前端移除演示流水/往来造数和 `localStorage` 业务状态。
|
||||
- 登录页视觉融合改版;月结/重开/审计按 HEL-268 视觉规范落地。
|
||||
- 测试环境部署编排收编到 `deploy/`,含非 root 加固、备份/巡检脚本与运维手册(不在施工员职责内执行上线)。
|
||||
|
||||
## 还没安排
|
||||
|
||||
- 公司间余额和四类往来科目的正式计算,已批准手工记录入账,以及从余额逐层查回原始流水。
|
||||
- 起算日、期初余额、流水覆盖断档检测和无业务校准。
|
||||
- 月结、重开、调整/冲销审批与审计报告。
|
||||
- 服务端流水查询、筛选、分页和可追溯导出。
|
||||
- 站内提醒与状态流转;外部通知只预留扩展位置,不默认启用。
|
||||
- 前端全面接入真实接口,移除模拟金额、静态业务记录和 `localStorage` 业务状态。
|
||||
- 测试环境之外的运行保障,包括 HTTPS、备份、监控和正式部署方案。
|
||||
- 正式部署(P4):HTTPS 反代落地、异机备份副本、正式账号交接。覆盖正式环境必须老板明确同意。
|
||||
|
||||
每完成或新增一项任务,必须在同一次提交里把它从本清单的相应栏目移走或补上,并同步更新 `最新进度.md`。
|
||||
|
||||
+12
-9
@@ -1,24 +1,27 @@
|
||||
# 最新进度
|
||||
|
||||
最后核对:2026-08-23。以下“已完成”均以当前代码、数据库迁移、接口和自动化测试为依据,不把页面演示当作真实功能。
|
||||
最后核对:2026-08-30。以下“已完成”均以当前代码、数据库迁移、接口和自动化测试为依据,不把页面演示当作真实功能。
|
||||
|
||||
## 已经真实完成
|
||||
|
||||
- 支持中信、农行、工行、建行、河南农商行、郑州银行六类样本的 `.xls` / `.xlsx` 流水解析;能识别变动的表头位置和列顺序,并校验余额连续性。
|
||||
- 已有 SQLite 数据库和 5 次版本迁移。原始文件按内容哈希保存,导入批次、工作表、源行和异常都有记录;原始文件、工作表和源行被数据库规则保护,不能直接改或删。
|
||||
- 已实现管理员与公司用户登录、首次改密、会话失效、登录失败限流、服务端权限隔离和审计记录。
|
||||
- 已有 SQLite 数据库和 10 次版本迁移。原始文件按内容哈希保存,导入批次、工作表、源行和异常都有记录;原始文件、工作表和源行被数据库规则保护,不能直接改或删。文件库启用 WAL。
|
||||
- 已实现管理员与公司用户登录、首次改密、会话失效(过期会话在发新会话时清理)、登录失败限流、服务端权限隔离和审计记录。
|
||||
- 已实现公司、用户、银行账户、别名等主数据管理;公司提交的银行账户需管理员审核后才能参与上传和识别。
|
||||
- 已实现导入、逐工作表确认或忽略、失败诊断、重复上传处理和 CSV 导出;未确认的工作表不进入后续处理。
|
||||
- 已实现规范转账事件和双边流水匹配。匹配决定保留历史,无法自动判断的记录进入人工审核;同公司调拨、外部流水和未锁定的单边记录不进入已确认的公司间往来。
|
||||
- 已有登录页、总账端和公司端页面,最近一次合并完成了登录页视觉改版。
|
||||
- 已实现全局起算日、公司对期初余额、流水覆盖断档与无业务说明审核。
|
||||
- 已实现月结:结账日到达后生成待结账任务,管理员确认后锁账并生成带 SHA-256 的月报;重开须审批,窗口到期自动恢复锁定;闭期补录进入 `period_late_arrivals`,不改已结快照;写保护拒绝锁定月的普通修改。
|
||||
- 流水列表/导出、往来查询、公司端手工记录已改为服务器真实数据;空列表显示「暂无数据」。页面不再使用 `FLOW_DEMO` / `localStorage` 业务状态。
|
||||
- 已有登录页、总账端和公司端页面。管理端「结账与期初」承接月结,「审核中心」增加重开审批,「结账与期初」之后增加「审计记录」。
|
||||
- `deploy/` 收编测试环境 Dockerfile、compose、`.env.example` 与部署/回滚脚本(4173、非 root、只读根文件系统、drop ALL、pids/mem/cpu 限制、healthcheck)。正式口令不进仓库。
|
||||
- 备份(在线热备 + 30 天日备/12 个月月备保留策略)、巡检(健康 + 磁盘 ≥80% 告警)脚本与《部署与运维手册》`deploy/README.md` 已入库;HTTPS 走反向代理方案已在手册写明。
|
||||
|
||||
## 仍未完成或不能当成已完成
|
||||
|
||||
- 公司间余额与会计科目的正式计算、已批准手工记录入账和逐层余额追溯尚未完成。
|
||||
- 全局起算日、期初余额、流水覆盖断档、无业务校准、月结、重开和调整审批尚未完成。
|
||||
- 提醒、完整的服务端查询导出,以及前端彻底移除演示数据和浏览器本地业务状态尚未完成。
|
||||
- 生产部署所需的 HTTPS、反向代理、备份、监控和正式运行保障尚未完成;本项目当前只允许测试环境部署。
|
||||
- 正式环境尚未部署(P4):HTTPS 反代、异机备份副本、正式账号交接在上线时落地。覆盖正式环境必须老板明确同意。
|
||||
- 发布基线:`release/prod` 长期分支已建立,`main` 待发布时快进。
|
||||
|
||||
## 最近验证
|
||||
|
||||
2026-08-23 已运行完整 Python 自动化测试:解析、持久化、认证与权限、导入接口、主数据和双边匹配相关测试均通过。后续修改功能时,必须再次运行完整测试并在本文件记录结果。
|
||||
2026-08-30 已运行完整 Python 自动化测试(`PYTHONPATH=src python -m unittest discover -s tests -v`),覆盖解析、持久化、认证、导入、主数据、匹配、月结/重开/写保护、前端契约与 360/820/1440 布局冒烟(有 Chromium 时)。后续修改功能时必须再次运行完整测试并在本文件记录结果。
|
||||
|
||||
@@ -14,11 +14,11 @@ from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
from bank_importer import (
|
||||
auth, calculation, company_transfers, dashboard, importing, ledger_events,
|
||||
manual_records, master_data, matching, multipart, personal_transit, positions,
|
||||
reminders, settings, subjects,
|
||||
auth, calculation, company_transfers, dashboard, flows, importing, ledger_events,
|
||||
manual_records, master_data, matching, multipart, period_close, personal_transit,
|
||||
positions, reminders, settings, subjects,
|
||||
)
|
||||
from bank_importer.db import connect, migrate, utc_now
|
||||
from bank_importer.db import connect, migrate, transaction, utc_now
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
@@ -62,6 +62,9 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
if path == "/api/export.csv":
|
||||
self._handle_export_csv(query)
|
||||
return
|
||||
if path == "/api/flows":
|
||||
self._handle_flows(query)
|
||||
return
|
||||
if path == "/api/admin/companies":
|
||||
self._handle_admin_companies()
|
||||
return
|
||||
@@ -108,6 +111,29 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
if path == "/api/admin/audit-log":
|
||||
self._handle_admin_audit_log(query)
|
||||
return
|
||||
if path == "/api/admin/period-closes":
|
||||
self._handle_admin_period_closes()
|
||||
return
|
||||
period_close_one = re.fullmatch(r"/api/admin/period-closes/(\d{4}-\d{2})", path)
|
||||
if period_close_one:
|
||||
self._handle_admin_period_close_one(period_close_one.group(1))
|
||||
return
|
||||
period_report = re.fullmatch(
|
||||
r"/api/admin/period-closes/(\d{4}-\d{2})/report.json", path
|
||||
)
|
||||
if period_report:
|
||||
self._handle_admin_period_report(period_report.group(1))
|
||||
return
|
||||
if path == "/api/admin/period-reopens":
|
||||
self._handle_admin_period_reopens(query)
|
||||
return
|
||||
period_reopen_one = re.fullmatch(r"/api/admin/period-reopens/(\d+)", path)
|
||||
if period_reopen_one:
|
||||
self._handle_admin_period_reopen_one(int(period_reopen_one.group(1)))
|
||||
return
|
||||
if path == "/api/admin/period-audit":
|
||||
self._handle_admin_period_audit(query)
|
||||
return
|
||||
if path == "/api/admin/settings":
|
||||
self._handle_admin_settings()
|
||||
return
|
||||
@@ -384,6 +410,22 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
if path == "/api/admin/reminder-settings":
|
||||
self._handle_admin_reminder_settings_put()
|
||||
return
|
||||
period_execute = re.fullmatch(
|
||||
r"/api/admin/period-closes/(\d{4}-\d{2})/execute", path
|
||||
)
|
||||
if period_execute:
|
||||
self._handle_admin_period_execute(period_execute.group(1))
|
||||
return
|
||||
period_reopen = re.fullmatch(
|
||||
r"/api/admin/period-closes/(\d{4}-\d{2})/reopen", path
|
||||
)
|
||||
if period_reopen:
|
||||
self._handle_admin_period_reopen_request(period_reopen.group(1))
|
||||
return
|
||||
period_decide = re.fullmatch(r"/api/admin/period-reopens/(\d+)/decide", path)
|
||||
if period_decide:
|
||||
self._handle_admin_period_reopen_decide(int(period_decide.group(1)))
|
||||
return
|
||||
company_status_match = re.fullmatch(
|
||||
r"/api/company/reminders/(\d+)/(acknowledge|resolve)", path
|
||||
)
|
||||
@@ -1022,6 +1064,46 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def _handle_flows(self, query: dict[str, list[str]]) -> None:
|
||||
connection = connect(DB_PATH)
|
||||
try:
|
||||
user = self._require_user(connection)
|
||||
if user is None:
|
||||
return
|
||||
raw_company = (query.get("company_id") or [None])[0]
|
||||
company_id = None
|
||||
if user["role"] == "company":
|
||||
if raw_company is not None and raw_company != str(user["company_id"]):
|
||||
self._send_json(403, {"status": "error", "message": "只能查看本公司的流水。"})
|
||||
return
|
||||
company_id = user["company_id"]
|
||||
elif raw_company is not None:
|
||||
try:
|
||||
company_id = int(raw_company)
|
||||
except ValueError:
|
||||
self._send_json(400, {"status": "error", "message": "company_id 参数无效。"})
|
||||
return
|
||||
try:
|
||||
limit = int((query.get("limit") or ["200"])[0])
|
||||
offset = int((query.get("offset") or ["0"])[0])
|
||||
except ValueError:
|
||||
limit, offset = 200, 0
|
||||
payload = flows.list_flows(
|
||||
connection,
|
||||
company_id=company_id,
|
||||
bank=(query.get("bank") or [None])[0] or None,
|
||||
account=(query.get("account") or [None])[0] or None,
|
||||
start=(query.get("start") or [None])[0] or None,
|
||||
end=(query.get("end") or [None])[0] or None,
|
||||
keyword=(query.get("keyword") or [None])[0] or None,
|
||||
limit=limit,
|
||||
offset=offset,
|
||||
)
|
||||
payload["status"] = "ok"
|
||||
self._send_json(200, payload)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Admin endpoints
|
||||
# ------------------------------------------------------------------
|
||||
@@ -1550,6 +1632,229 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def _handle_admin_period_closes(self) -> None:
|
||||
connection = connect(DB_PATH)
|
||||
try:
|
||||
user = self._require_admin(connection)
|
||||
if user is None:
|
||||
return
|
||||
payload = period_close.overview(connection)
|
||||
payload["status"] = "ok"
|
||||
self._send_json(200, payload)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def _handle_admin_period_close_one(self, year_month: str) -> None:
|
||||
connection = connect(DB_PATH)
|
||||
try:
|
||||
user = self._require_admin(connection)
|
||||
if user is None:
|
||||
return
|
||||
try:
|
||||
payload = period_close.close_payload(connection, year_month)
|
||||
except period_close.PeriodCloseError as exc:
|
||||
self._send_json(400, {"status": "error", "message": str(exc)})
|
||||
return
|
||||
body = dict(payload)
|
||||
body["period_status"] = body.get("status")
|
||||
body["status"] = "ok"
|
||||
self._send_json(200, body)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def _handle_admin_period_report(self, year_month: str) -> None:
|
||||
connection = connect(DB_PATH)
|
||||
try:
|
||||
user = self._require_admin(connection)
|
||||
if user is None:
|
||||
return
|
||||
try:
|
||||
payload = period_close.close_payload(connection, year_month)
|
||||
except period_close.PeriodCloseError as exc:
|
||||
self._send_json(400, {"status": "error", "message": str(exc)})
|
||||
return
|
||||
if not payload.get("snapshot") or payload.get("status") not in ("closed", "reopened"):
|
||||
self._send_json(404, {"status": "error", "message": "该账期尚无月报。"})
|
||||
return
|
||||
body = json.dumps(
|
||||
{
|
||||
"report_no": payload["report_no"],
|
||||
"snapshot_hash": payload["snapshot_hash"],
|
||||
"year_month": year_month,
|
||||
"snapshot": payload["snapshot"],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
).encode("utf-8")
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header(
|
||||
"Content-Disposition",
|
||||
f'attachment; filename="{payload["report_no"] or year_month}.json"',
|
||||
)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def _handle_admin_period_reopens(self, query: dict[str, list[str]]) -> None:
|
||||
connection = connect(DB_PATH)
|
||||
try:
|
||||
user = self._require_admin(connection)
|
||||
if user is None:
|
||||
return
|
||||
status = (query.get("status") or [None])[0] or None
|
||||
items = period_close.list_reopen_requests(connection, status=status)
|
||||
self._send_json(200, {"status": "ok", "items": items})
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def _handle_admin_period_reopen_one(self, request_id: int) -> None:
|
||||
connection = connect(DB_PATH)
|
||||
try:
|
||||
user = self._require_admin(connection)
|
||||
if user is None:
|
||||
return
|
||||
try:
|
||||
payload = period_close.reopen_payload(connection, request_id)
|
||||
except period_close.PeriodCloseError as exc:
|
||||
self._send_json(404, {"status": "error", "message": str(exc)})
|
||||
return
|
||||
payload["status_ok"] = "ok"
|
||||
payload["ok"] = True
|
||||
self._send_json(200, {"status": "ok", "item": payload})
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def _handle_admin_period_audit(self, query: dict[str, list[str]]) -> None:
|
||||
connection = connect(DB_PATH)
|
||||
try:
|
||||
user = self._require_admin(connection)
|
||||
if user is None:
|
||||
return
|
||||
try:
|
||||
limit = int((query.get("limit") or ["100"])[0])
|
||||
except ValueError:
|
||||
limit = 100
|
||||
items = period_close.list_audit_events(
|
||||
connection,
|
||||
action=(query.get("action") or [None])[0] or None,
|
||||
year_month=(query.get("year_month") or [None])[0] or None,
|
||||
company_q=(query.get("company") or [None])[0] or None,
|
||||
since=(query.get("since") or [None])[0] or None,
|
||||
until=(query.get("until") or [None])[0] or None,
|
||||
limit=limit,
|
||||
)
|
||||
self._send_json(200, {"status": "ok", "items": items})
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def _handle_admin_period_execute(self, year_month: str) -> None:
|
||||
connection = connect(DB_PATH)
|
||||
try:
|
||||
user = self._require_admin(connection)
|
||||
if user is None:
|
||||
return
|
||||
data = self._read_json_body() or {}
|
||||
try:
|
||||
payload = period_close.execute_close(
|
||||
connection,
|
||||
year_month,
|
||||
user,
|
||||
confirm=bool(data.get("confirm")),
|
||||
)
|
||||
except period_close.PeriodConflictError as exc:
|
||||
self._send_json(409, {"status": "error", "message": str(exc)})
|
||||
return
|
||||
except period_close.PeriodCloseError as exc:
|
||||
self._send_json(400, {"status": "error", "message": str(exc)})
|
||||
return
|
||||
except Exception as exc:
|
||||
period_close.mark_close_failed(connection, year_month, user, str(exc))
|
||||
self._send_json(
|
||||
500,
|
||||
{
|
||||
"status": "error",
|
||||
"message": f"结账失败,未改动任何数据:{exc}",
|
||||
},
|
||||
)
|
||||
return
|
||||
auth.audit(
|
||||
connection, "period_close", actor=user,
|
||||
target=year_month, detail=payload.get("report_no"), ip=self._client_ip,
|
||||
)
|
||||
payload["period_status"] = payload.get("status")
|
||||
payload["status"] = "ok"
|
||||
self._send_json(200, payload)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def _handle_admin_period_reopen_request(self, year_month: str) -> None:
|
||||
connection = connect(DB_PATH)
|
||||
try:
|
||||
user = self._require_admin(connection)
|
||||
if user is None:
|
||||
return
|
||||
data = self._read_json_body() or {}
|
||||
try:
|
||||
payload = period_close.request_reopen(
|
||||
connection,
|
||||
year_month,
|
||||
user,
|
||||
reason=str(data.get("reason") or ""),
|
||||
companies_note=str(data.get("companies_note") or ""),
|
||||
window_days=data.get("window_days") or 3,
|
||||
)
|
||||
except period_close.PeriodConflictError as exc:
|
||||
self._send_json(409, {"status": "error", "message": str(exc)})
|
||||
return
|
||||
except period_close.PeriodCloseError as exc:
|
||||
self._send_json(400, {"status": "error", "message": str(exc)})
|
||||
return
|
||||
auth.audit(
|
||||
connection, "period_reopen_request", actor=user,
|
||||
target=year_month, detail=payload.get("number"), ip=self._client_ip,
|
||||
)
|
||||
self._send_json(200, {"status": "ok", "item": payload})
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def _handle_admin_period_reopen_decide(self, request_id: int) -> None:
|
||||
connection = connect(DB_PATH)
|
||||
try:
|
||||
user = self._require_admin(connection)
|
||||
if user is None:
|
||||
return
|
||||
data = self._read_json_body() or {}
|
||||
approve = bool(data.get("approve"))
|
||||
try:
|
||||
payload = period_close.decide_reopen(
|
||||
connection,
|
||||
request_id,
|
||||
user,
|
||||
approve=approve,
|
||||
comment=str(data.get("comment") or ""),
|
||||
)
|
||||
except period_close.PeriodConflictError as exc:
|
||||
self._send_json(409, {"status": "error", "message": str(exc)})
|
||||
return
|
||||
except period_close.PeriodCloseError as exc:
|
||||
self._send_json(400, {"status": "error", "message": str(exc)})
|
||||
return
|
||||
auth.audit(
|
||||
connection,
|
||||
"period_reopen_approve" if approve else "period_reopen_reject",
|
||||
actor=user,
|
||||
target=payload.get("year_month"),
|
||||
detail=payload.get("number"),
|
||||
ip=self._client_ip,
|
||||
)
|
||||
self._send_json(200, {"status": "ok", "item": payload})
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# System settings (admin read/write, persisted + audited)
|
||||
# ------------------------------------------------------------------
|
||||
@@ -2292,23 +2597,41 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
if not row_ids:
|
||||
self._send_json(400, {"status": "error", "message": "必须指定 source_row_ids 或 batch_id。"})
|
||||
return
|
||||
writable, locked_rows = period_close.split_writable_row_ids(connection, row_ids)
|
||||
late = 0
|
||||
if locked_rows:
|
||||
late = period_close.record_late_arrivals(connection, locked_rows, user)
|
||||
if not writable:
|
||||
self._send_json(
|
||||
200,
|
||||
{
|
||||
"status": "ok",
|
||||
"matching": {
|
||||
"created_events": 0, "updated_events": 0, "unchanged": 0,
|
||||
"skipped_locked": len(locked_rows), "rows": len(row_ids),
|
||||
},
|
||||
"late_arrivals": late,
|
||||
},
|
||||
)
|
||||
return
|
||||
try:
|
||||
result = matching.reconcile_rows(connection, row_ids, actor=user)
|
||||
with transaction(connection):
|
||||
result = matching.reconcile_rows(connection, writable, actor=user)
|
||||
ledger_events.reconcile_bank_events(connection, actor=user)
|
||||
result["late_arrivals"] = late
|
||||
auth.audit(
|
||||
connection, "transfer_reconcile", actor=user,
|
||||
target=f"rows:{len(writable)}",
|
||||
detail=(
|
||||
f"created:{result['created_events']};"
|
||||
f"updated:{result['updated_events']};late:{late}"
|
||||
),
|
||||
ip=self._client_ip,
|
||||
)
|
||||
except Exception as exc:
|
||||
self._send_json(500, {"status": "error", "message": f"重跑匹配失败:{exc}"})
|
||||
return
|
||||
try:
|
||||
ledger_events.reconcile_bank_events(connection, actor=user)
|
||||
except Exception as exc:
|
||||
self._send_json(500, {"status": "error", "message": f"同步往来事件失败:{exc}"})
|
||||
return
|
||||
auth.audit(
|
||||
connection, "transfer_reconcile", actor=user,
|
||||
target=f"rows:{len(row_ids)}",
|
||||
detail=f"created:{result['created_events']};updated:{result['updated_events']}",
|
||||
ip=self._client_ip,
|
||||
)
|
||||
self._send_json(200, {"status": "ok", "matching": result})
|
||||
self._send_json(200, {"status": "ok", "matching": result, "late_arrivals": late})
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@@ -2336,27 +2659,31 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
self._send_json(400, {"status": "error", "message": "source_row_ids 必须是数组。"})
|
||||
return
|
||||
try:
|
||||
payload = matching.apply_manual_decision(
|
||||
connection,
|
||||
event_id,
|
||||
action,
|
||||
reason=str(data.get("reason") or ""),
|
||||
expected_revision=expected_revision,
|
||||
request_key=str(data.get("request_key") or "") or None,
|
||||
actor=user,
|
||||
source_row_ids=[int(item) for item in source_row_ids]
|
||||
if source_row_ids
|
||||
else None,
|
||||
participant=data.get("participant"),
|
||||
)
|
||||
period_close.assert_event_writable(connection, event_id)
|
||||
with transaction(connection):
|
||||
payload = matching.apply_manual_decision(
|
||||
connection,
|
||||
event_id,
|
||||
action,
|
||||
reason=str(data.get("reason") or ""),
|
||||
expected_revision=expected_revision,
|
||||
request_key=str(data.get("request_key") or "") or None,
|
||||
actor=user,
|
||||
source_row_ids=[int(item) for item in source_row_ids]
|
||||
if source_row_ids
|
||||
else None,
|
||||
participant=data.get("participant"),
|
||||
)
|
||||
ledger_events.reconcile_bank_events(connection, actor=user)
|
||||
except period_close.PeriodLockedError as exc:
|
||||
self._send_json(409, {"status": "error", "message": str(exc), "year_month": exc.year_month})
|
||||
return
|
||||
except matching.MatchConflictError as exc:
|
||||
self._send_json(409, {"status": "error", "message": str(exc)})
|
||||
return
|
||||
except matching.MatchInputError as exc:
|
||||
self._send_json(400, {"status": "error", "message": str(exc)})
|
||||
return
|
||||
try:
|
||||
ledger_events.reconcile_bank_events(connection, actor=user)
|
||||
except Exception as exc:
|
||||
self._send_json(500, {"status": "error", "message": f"同步往来事件失败:{exc}"})
|
||||
return
|
||||
@@ -2648,27 +2975,31 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
return
|
||||
reason = str(data.get("reason") or "").strip() or "公司端确认单边流水"
|
||||
try:
|
||||
payload = matching.apply_manual_decision(
|
||||
connection,
|
||||
event_id,
|
||||
"assign_participant",
|
||||
reason=reason,
|
||||
expected_revision=expected_revision,
|
||||
request_key=request_key,
|
||||
actor=user,
|
||||
participant={
|
||||
"role": role,
|
||||
"company_id": counterparty_company_id,
|
||||
},
|
||||
)
|
||||
period_close.assert_event_writable(connection, event_id)
|
||||
with transaction(connection):
|
||||
payload = matching.apply_manual_decision(
|
||||
connection,
|
||||
event_id,
|
||||
"assign_participant",
|
||||
reason=reason,
|
||||
expected_revision=expected_revision,
|
||||
request_key=request_key,
|
||||
actor=user,
|
||||
participant={
|
||||
"role": role,
|
||||
"company_id": counterparty_company_id,
|
||||
},
|
||||
)
|
||||
ledger_events.reconcile_bank_events(connection, actor=user)
|
||||
except period_close.PeriodLockedError as exc:
|
||||
self._send_json(409, {"status": "error", "message": str(exc), "year_month": exc.year_month})
|
||||
return
|
||||
except matching.MatchConflictError as exc:
|
||||
self._send_json(409, {"status": "error", "message": str(exc)})
|
||||
return
|
||||
except matching.MatchInputError as exc:
|
||||
self._send_json(400, {"status": "error", "message": str(exc)})
|
||||
return
|
||||
try:
|
||||
ledger_events.reconcile_bank_events(connection, actor=user)
|
||||
except Exception as exc:
|
||||
self._send_json(500, {"status": "error", "message": f"同步往来事件失败:{exc}"})
|
||||
return
|
||||
@@ -3025,6 +3356,7 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
)
|
||||
return
|
||||
try:
|
||||
period_close.assert_ledger_writable(connection, event_id)
|
||||
action = str(data.get("action") or "confirm")
|
||||
if action in ("return", "exception"):
|
||||
payload = subjects.park_subject(
|
||||
@@ -3047,6 +3379,9 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
request_key=str(data.get("request_key") or "") or None,
|
||||
actor=user,
|
||||
)
|
||||
except period_close.PeriodLockedError as exc:
|
||||
self._send_json(409, {"status": "error", "message": str(exc), "year_month": exc.year_month})
|
||||
return
|
||||
except subjects.SubjectConflictError as exc:
|
||||
self._send_json(409, {"status": "error", "message": str(exc)})
|
||||
return
|
||||
@@ -3079,61 +3414,68 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
self._send_json(400, {"status": "error", "message": "必须填写操作原因。"})
|
||||
return
|
||||
try:
|
||||
if action == "reverse":
|
||||
event_id, _revision_id = ledger_events.create_reversal(
|
||||
connection, event_id,
|
||||
source_kind="adjustment",
|
||||
source_revision_token=None,
|
||||
effective_at=data.get("effective_at") or None,
|
||||
reason=reason, actor=user, idempotency_key=request_key,
|
||||
)
|
||||
outcome: dict[str, object] = {
|
||||
"action": "reverse", "ledger_event_id": event_id,
|
||||
}
|
||||
elif action == "adjust":
|
||||
try:
|
||||
effective_at = str(data.get("effective_at") or "")
|
||||
amount = str(data.get("amount") or "")
|
||||
currency = str(data.get("currency") or "")
|
||||
payer = int(data["payer_company_id"])
|
||||
payee = int(data["payee_company_id"])
|
||||
perspective = int(data["perspective_company_id"])
|
||||
subject_code = str(data.get("subject_code") or "")
|
||||
except (KeyError, TypeError, ValueError):
|
||||
self._send_json(
|
||||
400, {"status": "error", "message": "adjust 参数不完整或无效。"}
|
||||
)
|
||||
return
|
||||
event_id, _revision_id = ledger_events.create_adjustment(
|
||||
connection, event_id,
|
||||
effective_at=effective_at, amount=amount, currency=currency,
|
||||
payer_company_id=payer, payee_company_id=payee,
|
||||
perspective_company_id=perspective, subject_code=subject_code,
|
||||
reason=reason, actor=user, idempotency_key=request_key,
|
||||
)
|
||||
outcome = {"action": "adjust", "ledger_event_id": event_id}
|
||||
elif action == "reopen":
|
||||
event_id, _revision_id = ledger_events.reopen_subject(
|
||||
connection, event_id, reason=reason, actor=user,
|
||||
idempotency_key=request_key,
|
||||
)
|
||||
outcome = {"action": "reopen", "ledger_event_id": event_id}
|
||||
else:
|
||||
period_close.assert_ledger_writable(connection, event_id)
|
||||
if action in ("adjust", "reverse") and data.get("effective_at"):
|
||||
period_close.assert_date_writable(connection, str(data.get("effective_at")))
|
||||
if action not in ("reverse", "adjust", "reopen"):
|
||||
self._send_json(
|
||||
400,
|
||||
{"status": "error", "message": "action 必须是 reverse、adjust 或 reopen。"},
|
||||
)
|
||||
return
|
||||
with transaction(connection):
|
||||
if action == "reverse":
|
||||
event_id, _revision_id = ledger_events.create_reversal(
|
||||
connection, event_id,
|
||||
source_kind="adjustment",
|
||||
source_revision_token=None,
|
||||
effective_at=data.get("effective_at") or None,
|
||||
reason=reason, actor=user, idempotency_key=request_key,
|
||||
)
|
||||
outcome = {
|
||||
"action": "reverse", "ledger_event_id": event_id,
|
||||
}
|
||||
elif action == "adjust":
|
||||
try:
|
||||
effective_at = str(data.get("effective_at") or "")
|
||||
amount = str(data.get("amount") or "")
|
||||
currency = str(data.get("currency") or "")
|
||||
payer = int(data["payer_company_id"])
|
||||
payee = int(data["payee_company_id"])
|
||||
perspective = int(data["perspective_company_id"])
|
||||
subject_code = str(data.get("subject_code") or "")
|
||||
except (KeyError, TypeError, ValueError):
|
||||
self._send_json(
|
||||
400, {"status": "error", "message": "adjust 参数不完整或无效。"}
|
||||
)
|
||||
return
|
||||
event_id, _revision_id = ledger_events.create_adjustment(
|
||||
connection, event_id,
|
||||
effective_at=effective_at, amount=amount, currency=currency,
|
||||
payer_company_id=payer, payee_company_id=payee,
|
||||
perspective_company_id=perspective, subject_code=subject_code,
|
||||
reason=reason, actor=user, idempotency_key=request_key,
|
||||
)
|
||||
outcome = {"action": "adjust", "ledger_event_id": event_id}
|
||||
else:
|
||||
event_id, _revision_id = ledger_events.reopen_subject(
|
||||
connection, event_id, reason=reason, actor=user,
|
||||
idempotency_key=request_key,
|
||||
)
|
||||
outcome = {"action": "reopen", "ledger_event_id": event_id}
|
||||
auth.audit(
|
||||
connection, f"ledger_{action}", actor=user,
|
||||
target=f"ledger_event:{event_id}", detail=reason, ip=self._client_ip,
|
||||
)
|
||||
except period_close.PeriodLockedError as exc:
|
||||
self._send_json(409, {"status": "error", "message": str(exc), "year_month": exc.year_month})
|
||||
return
|
||||
except ledger_events.LedgerConflictError as exc:
|
||||
self._send_json(409, {"status": "error", "message": str(exc)})
|
||||
return
|
||||
except ledger_events.LedgerInputError as exc:
|
||||
self._send_json(400, {"status": "error", "message": str(exc)})
|
||||
return
|
||||
auth.audit(
|
||||
connection, f"ledger_{action}", actor=user,
|
||||
target=f"ledger_event:{event_id}", detail=reason, ip=self._client_ip,
|
||||
)
|
||||
self._send_json(200, {"status": "ok", **outcome})
|
||||
finally:
|
||||
connection.close()
|
||||
@@ -3157,6 +3499,13 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
self._send_json(400, {"status": "error", "message": "expected_decision_id 无效。"})
|
||||
return
|
||||
try:
|
||||
existing = connection.execute(
|
||||
"SELECT occurred_at FROM manual_records WHERE id = ?", (record_id,)
|
||||
).fetchone()
|
||||
if existing is not None:
|
||||
period_close.assert_date_writable(
|
||||
connection, data.get("effective_at") or existing["occurred_at"]
|
||||
)
|
||||
payload = manual_records.decide(
|
||||
connection,
|
||||
record_id,
|
||||
@@ -3169,6 +3518,9 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
target_ledger_event_id=data.get("target_ledger_event_id"),
|
||||
effective_at=data.get("effective_at"),
|
||||
)
|
||||
except period_close.PeriodLockedError as exc:
|
||||
self._send_json(409, {"status": "error", "message": str(exc), "year_month": exc.year_month})
|
||||
return
|
||||
except manual_records.ManualConflictError as exc:
|
||||
self._send_json(409, {"status": "error", "message": str(exc)})
|
||||
return
|
||||
@@ -3617,6 +3969,7 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
if data is None:
|
||||
return
|
||||
try:
|
||||
period_close.assert_date_writable(connection, str(data.get("occurred_at") or ""))
|
||||
payload = manual_records.submit(
|
||||
connection,
|
||||
company_id=company_id,
|
||||
@@ -3636,6 +3989,9 @@ class AppHandler(SimpleHTTPRequestHandler):
|
||||
reason=data.get("reason"),
|
||||
evidence=data.get("evidence"),
|
||||
)
|
||||
except period_close.PeriodLockedError as exc:
|
||||
self._send_json(409, {"status": "error", "message": str(exc), "year_month": exc.year_month})
|
||||
return
|
||||
except manual_records.ManualConflictError as exc:
|
||||
self._send_json(409, {"status": "error", "message": str(exc)})
|
||||
return
|
||||
|
||||
@@ -18,7 +18,7 @@ import secrets
|
||||
import sqlite3
|
||||
import string
|
||||
|
||||
from .db import utc_now
|
||||
from .db import transaction, utc_now
|
||||
|
||||
|
||||
MIN_PASSWORD_LENGTH = 8
|
||||
@@ -204,6 +204,7 @@ def create_session(
|
||||
token = secrets.token_urlsafe(32)
|
||||
token_hash = hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
now = datetime.now(timezone.utc)
|
||||
purge_expired_sessions(connection)
|
||||
with connection:
|
||||
connection.execute(
|
||||
"""
|
||||
@@ -220,6 +221,17 @@ def create_session(
|
||||
return token
|
||||
|
||||
|
||||
def purge_expired_sessions(connection: sqlite3.Connection) -> int:
|
||||
"""Drop expired or revoked session rows so they do not accumulate."""
|
||||
now = utc_now()
|
||||
with connection:
|
||||
cursor = connection.execute(
|
||||
"DELETE FROM sessions WHERE expires_at <= ? OR revoked_at IS NOT NULL",
|
||||
(now,),
|
||||
)
|
||||
return int(cursor.rowcount or 0)
|
||||
|
||||
|
||||
def resolve_session(connection: sqlite3.Connection, token: str) -> sqlite3.Row | None:
|
||||
"""Return the user row for a live session token, else None.
|
||||
|
||||
@@ -296,7 +308,7 @@ def audit(
|
||||
ip: str | None = None,
|
||||
) -> None:
|
||||
"""Append an audit log entry. Never pass passwords in ``detail``."""
|
||||
with connection:
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO audit_log (
|
||||
|
||||
@@ -7,8 +7,8 @@ from decimal import Decimal, InvalidOperation
|
||||
import json
|
||||
import sqlite3
|
||||
|
||||
from .db import utc_now
|
||||
from . import master_data, matching
|
||||
from .db import transaction, utc_now
|
||||
from . import auth, master_data, matching
|
||||
|
||||
|
||||
SETTING_START_DATE = "calculation_start_date"
|
||||
@@ -81,7 +81,7 @@ def set_calculation_start_date(
|
||||
raise LockedError("已有结账月份,起算日已锁定。")
|
||||
before = get_calculation_start_date(connection)
|
||||
now = utc_now()
|
||||
with connection:
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO system_settings (key, value, updated_at, updated_by)
|
||||
@@ -185,7 +185,7 @@ def create_opening_balance(
|
||||
raise ConflictError("该对公司已有确认期初,请使用修订。")
|
||||
revision = _next_revision(connection, low_id, high_id)
|
||||
now = utc_now()
|
||||
with connection:
|
||||
with transaction(connection):
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO opening_balance_revisions (
|
||||
@@ -235,7 +235,7 @@ def confirm_opening_balance(
|
||||
reason = str(reason or "").strip()
|
||||
if len(reason) < 2:
|
||||
raise ValueError("确认期初必须填写原因。")
|
||||
with connection:
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE opening_balance_revisions SET status = 'confirmed', reason = ?
|
||||
@@ -278,7 +278,7 @@ def revise_opening_balance(
|
||||
high_id = int(row["company_id_high"])
|
||||
revision = _next_revision(connection, low_id, high_id)
|
||||
now = utc_now()
|
||||
with connection:
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"UPDATE opening_balance_revisions SET status = 'superseded' WHERE id = ?",
|
||||
(revision_id,),
|
||||
@@ -333,7 +333,7 @@ def void_opening_balance(
|
||||
reason = str(reason or "").strip()
|
||||
if len(reason) < 2:
|
||||
raise ValueError("作废期初必须填写原因。")
|
||||
with connection:
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"UPDATE opening_balance_revisions SET status = 'void', reason = ? WHERE id = ?",
|
||||
(reason, revision_id),
|
||||
@@ -551,7 +551,7 @@ def recalculate_coverage_gaps(connection: sqlite3.Connection) -> int:
|
||||
"SELECT * FROM bank_accounts WHERE status = 'active'"
|
||||
).fetchall()
|
||||
rebuilt = 0
|
||||
with connection:
|
||||
with transaction(connection):
|
||||
for account in accounts:
|
||||
connection.execute(
|
||||
"""
|
||||
@@ -668,7 +668,7 @@ def submit_no_business_attestation(
|
||||
if account["company_id"] != company_id:
|
||||
raise ValueError("只能为本公司账户提交说明。")
|
||||
now = utc_now()
|
||||
with connection:
|
||||
with transaction(connection):
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO no_business_attestations (
|
||||
@@ -688,6 +688,13 @@ def submit_no_business_attestation(
|
||||
),
|
||||
)
|
||||
attestation_id = int(cursor.lastrowid)
|
||||
auth.audit(
|
||||
connection,
|
||||
"attestation_submit",
|
||||
actor=actor,
|
||||
target=f"attestation:{attestation_id}",
|
||||
detail=f"account:{bank_account_id};gap:{gap_start}..{gap_end}",
|
||||
)
|
||||
return attestation_payload(connection, attestation_id)
|
||||
|
||||
|
||||
@@ -712,7 +719,7 @@ def review_no_business_attestation(
|
||||
raise ValueError("审核必须填写理由。")
|
||||
status = "approved" if decision == "approve" else "rejected"
|
||||
now = utc_now()
|
||||
with connection:
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE no_business_attestations
|
||||
@@ -748,6 +755,13 @@ def review_no_business_attestation(
|
||||
""",
|
||||
(row["bank_account_id"], row["gap_end"], row["gap_start"]),
|
||||
)
|
||||
auth.audit(
|
||||
connection,
|
||||
f"attestation_{decision}",
|
||||
actor=actor,
|
||||
target=f"attestation:{attestation_id}",
|
||||
detail=review_reason,
|
||||
)
|
||||
return attestation_payload(connection, attestation_id)
|
||||
|
||||
|
||||
|
||||
@@ -109,11 +109,46 @@ def _company_rows(connection: sqlite3.Connection) -> list[sqlite3.Row]:
|
||||
).fetchall()
|
||||
|
||||
|
||||
def _period_status_for_cutoff(
|
||||
connection: sqlite3.Connection, cutoff: str
|
||||
) -> tuple[str | None, str]:
|
||||
ym = str(cutoff or "")[:7]
|
||||
exists = connection.execute(
|
||||
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'period_close_runs'"
|
||||
).fetchone()
|
||||
if exists is None:
|
||||
return None, "—"
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT status FROM period_close_runs
|
||||
WHERE year_month = ?
|
||||
ORDER BY version DESC LIMIT 1
|
||||
""",
|
||||
(ym,),
|
||||
).fetchone()
|
||||
mapping = {
|
||||
"closed": ("closed", "已锁定"),
|
||||
"reopened": ("reopened", "已重开"),
|
||||
"failed": ("failed", "结账失败"),
|
||||
"pending": ("pending", "待结账"),
|
||||
"closing": ("closing", "处理中"),
|
||||
}
|
||||
if row is not None:
|
||||
return mapping.get(row["status"], (row["status"], str(row["status"])))
|
||||
locked = connection.execute(
|
||||
"SELECT 1 FROM closed_periods WHERE year_month = ?", (ym,)
|
||||
).fetchone()
|
||||
if locked is not None:
|
||||
return "closed", "已锁定"
|
||||
return None, "—"
|
||||
|
||||
|
||||
def company_summaries(
|
||||
connection: sqlite3.Connection, *, from_date: str, cutoff: str
|
||||
) -> tuple[list[dict[str, object]], dict[str, object]]:
|
||||
companies = _company_rows(connection)
|
||||
events = _load_eligible(connection, from_date=from_date, cutoff=cutoff)
|
||||
period_status, period_label = _period_status_for_cutoff(connection, cutoff)
|
||||
|
||||
debit_total = ZERO
|
||||
credit_total = ZERO
|
||||
@@ -125,8 +160,8 @@ def company_summaries(
|
||||
"detail_count": 0,
|
||||
"debit": ZERO,
|
||||
"credit": ZERO,
|
||||
"period_status": None,
|
||||
"period_status_label": "—",
|
||||
"period_status": period_status,
|
||||
"period_status_label": period_label,
|
||||
}
|
||||
|
||||
for event in events:
|
||||
|
||||
@@ -10,10 +10,12 @@ version order; each records itself in ``schema_migrations`` so re-running
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
from typing import Iterator
|
||||
|
||||
|
||||
DEFAULT_DB_PATH = Path("data/app.db")
|
||||
@@ -23,6 +25,31 @@ def utc_now() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def transaction(connection: sqlite3.Connection) -> Iterator[sqlite3.Connection]:
|
||||
"""Own a write transaction only when the caller has not already started one.
|
||||
|
||||
Nested helpers join the outer boundary so business rows and their audit
|
||||
trail commit or roll back together. Standalone callers still commit before
|
||||
return, so ``connection.close()`` cannot silently drop the work (HEL-270).
|
||||
``sqlite3.Connection`` as a context manager always commits on exit even
|
||||
when it did not begin the transaction; do not use it for nestable writes.
|
||||
"""
|
||||
began = False
|
||||
if not connection.in_transaction:
|
||||
connection.execute("BEGIN IMMEDIATE")
|
||||
began = True
|
||||
try:
|
||||
yield connection
|
||||
except Exception:
|
||||
if began:
|
||||
connection.rollback()
|
||||
raise
|
||||
else:
|
||||
if began:
|
||||
connection.commit()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Migration:
|
||||
version: int
|
||||
@@ -1096,6 +1123,106 @@ MIGRATIONS: tuple[Migration, ...] = (
|
||||
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;
|
||||
""",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -1108,6 +1235,10 @@ def connect(path: str | Path) -> sqlite3.Connection:
|
||||
connection = sqlite3.connect(str(db_path), timeout=30)
|
||||
connection.row_factory = sqlite3.Row
|
||||
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
|
||||
|
||||
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -650,6 +650,14 @@ def review_sheets(
|
||||
actor=actor,
|
||||
)
|
||||
ledger_events.reconcile_bank_events(connection, actor=actor)
|
||||
if updated:
|
||||
auth.audit(
|
||||
connection,
|
||||
f"sheet_{decision}",
|
||||
actor=actor,
|
||||
target=f"batch:{batch_id}",
|
||||
detail=f"sheets:{','.join(updated)}" + (f";reason:{reason}" if reason else ""),
|
||||
)
|
||||
if began:
|
||||
connection.commit()
|
||||
except Exception:
|
||||
@@ -657,14 +665,6 @@ def review_sheets(
|
||||
connection.rollback()
|
||||
raise
|
||||
|
||||
if updated:
|
||||
auth.audit(
|
||||
connection,
|
||||
f"sheet_{decision}",
|
||||
actor=actor,
|
||||
target=f"batch:{batch_id}",
|
||||
detail=f"sheets:{','.join(updated)}" + (f";reason:{reason}" if reason else ""),
|
||||
)
|
||||
payload: dict[str, object] = {"updated": updated, "already": already}
|
||||
if matching_result is not None:
|
||||
payload["matching"] = matching_result
|
||||
|
||||
@@ -18,7 +18,7 @@ from decimal import Decimal, InvalidOperation
|
||||
import json
|
||||
import sqlite3
|
||||
|
||||
from .db import utc_now
|
||||
from .db import transaction, utc_now
|
||||
from .subjects import MIRROR, SUBJECTS, mirror_subject
|
||||
|
||||
|
||||
@@ -428,26 +428,30 @@ def reopen_subject(
|
||||
raise LedgerInputError(
|
||||
"该事件没有银行来源,无法重新进入科目审核;请改用调整或冲销。"
|
||||
)
|
||||
if not _has_reversal(connection, ledger_event_id):
|
||||
create_reversal(
|
||||
connection, ledger_event_id,
|
||||
source_kind=current["source_kind"],
|
||||
source_revision_token=current["source_revision_token"],
|
||||
reason="科目复核:原确认事件冲销",
|
||||
actor=actor,
|
||||
idempotency_key=(idempotency_key + ":rev" if idempotency_key else None),
|
||||
rule_version=current["rule_version"],
|
||||
)
|
||||
ev = connection.execute(
|
||||
"SELECT * FROM eligible_intercompany_events WHERE event_id = ?",
|
||||
(bank_claim["bank_event_id"],),
|
||||
).fetchone()
|
||||
if ev is None:
|
||||
raise LedgerInputError("银行事件已不再纳入往来,无法重新入账。")
|
||||
event_id, revision_id = _create_bank_event(
|
||||
connection, ev, actor, reason="科目复核后重新入账,待确认科目",
|
||||
replacing_claim=bank_claim,
|
||||
)
|
||||
# One nestable transaction: reversal, replacement event, source re-claim
|
||||
# and suggestions commit together. create_event used to commit on its own,
|
||||
# leaving the bank-source UPDATE uncommitted for connection.close().
|
||||
with transaction(connection):
|
||||
if not _has_reversal(connection, ledger_event_id):
|
||||
create_reversal(
|
||||
connection, ledger_event_id,
|
||||
source_kind=current["source_kind"],
|
||||
source_revision_token=current["source_revision_token"],
|
||||
reason="科目复核:原确认事件冲销",
|
||||
actor=actor,
|
||||
idempotency_key=(idempotency_key + ":rev" if idempotency_key else None),
|
||||
rule_version=current["rule_version"],
|
||||
)
|
||||
event_id, revision_id = _create_bank_event(
|
||||
connection, ev, actor, reason="科目复核后重新入账,待确认科目",
|
||||
replacing_claim=bank_claim,
|
||||
)
|
||||
return event_id, revision_id
|
||||
|
||||
|
||||
@@ -553,51 +557,52 @@ def _create_bank_event(
|
||||
reason: str,
|
||||
replacing_claim: sqlite3.Row | None = None,
|
||||
) -> tuple[int, int]:
|
||||
event_id, revision_id = create_event(
|
||||
connection,
|
||||
state="pending_subject",
|
||||
effective_at=event["effective_at"],
|
||||
amount=event["amount"],
|
||||
currency=event["currency"],
|
||||
payer_company_id=event["payer_company_id"],
|
||||
payee_company_id=event["payee_company_id"],
|
||||
perspective_company_id=None,
|
||||
subject_code=None,
|
||||
source_kind="bank",
|
||||
source_revision_token=event["decision_id"],
|
||||
posting_kind="normal",
|
||||
rule_version=SUBJECT_RULE_VERSION,
|
||||
evidence_json=json.dumps(
|
||||
{
|
||||
"bank_event_id": event["event_id"],
|
||||
"decision_id": event["decision_id"],
|
||||
"pairing": event["pairing"],
|
||||
"evidence_count": event["evidence_count"],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
actor=actor,
|
||||
reason=reason,
|
||||
)
|
||||
if replacing_claim is not None:
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE ledger_event_bank_sources SET ledger_event_id = ?
|
||||
WHERE bank_event_id = ?
|
||||
""",
|
||||
(event_id, event["event_id"]),
|
||||
with transaction(connection):
|
||||
event_id, revision_id = create_event(
|
||||
connection,
|
||||
state="pending_subject",
|
||||
effective_at=event["effective_at"],
|
||||
amount=event["amount"],
|
||||
currency=event["currency"],
|
||||
payer_company_id=event["payer_company_id"],
|
||||
payee_company_id=event["payee_company_id"],
|
||||
perspective_company_id=None,
|
||||
subject_code=None,
|
||||
source_kind="bank",
|
||||
source_revision_token=event["decision_id"],
|
||||
posting_kind="normal",
|
||||
rule_version=SUBJECT_RULE_VERSION,
|
||||
evidence_json=json.dumps(
|
||||
{
|
||||
"bank_event_id": event["event_id"],
|
||||
"decision_id": event["decision_id"],
|
||||
"pairing": event["pairing"],
|
||||
"evidence_count": event["evidence_count"],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
actor=actor,
|
||||
reason=reason,
|
||||
)
|
||||
else:
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO ledger_event_bank_sources (bank_event_id, ledger_event_id)
|
||||
VALUES (?, ?)
|
||||
""",
|
||||
(event["event_id"], event_id),
|
||||
)
|
||||
from .subjects import store_suggestions
|
||||
if replacing_claim is not None:
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE ledger_event_bank_sources SET ledger_event_id = ?
|
||||
WHERE bank_event_id = ?
|
||||
""",
|
||||
(event_id, event["event_id"]),
|
||||
)
|
||||
else:
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO ledger_event_bank_sources (bank_event_id, ledger_event_id)
|
||||
VALUES (?, ?)
|
||||
""",
|
||||
(event["event_id"], event_id),
|
||||
)
|
||||
from .subjects import store_suggestions
|
||||
|
||||
store_suggestions(connection, event_id)
|
||||
store_suggestions(connection, event_id)
|
||||
return event_id, revision_id
|
||||
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ import json
|
||||
import re
|
||||
import sqlite3
|
||||
|
||||
from .db import utc_now
|
||||
from .db import transaction, utc_now
|
||||
|
||||
|
||||
ACCOUNT_TYPES = ("基本户", "一般户", "专用户")
|
||||
@@ -143,7 +143,7 @@ def create_company(
|
||||
raise ValueError("公司名称不能为空。")
|
||||
now = utc_now()
|
||||
try:
|
||||
with connection:
|
||||
with transaction(connection):
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO companies (
|
||||
@@ -153,16 +153,15 @@ def create_company(
|
||||
(name, (credit_code or "").strip() or None,
|
||||
(cashier_name or "").strip() or None, now, now),
|
||||
)
|
||||
company_id = int(cursor.lastrowid)
|
||||
record_change(
|
||||
connection, "company", company_id, "create",
|
||||
None, {"name": name, "credit_code": credit_code or None,
|
||||
"cashier_name": cashier_name or None, "status": "active"},
|
||||
None, actor,
|
||||
)
|
||||
except sqlite3.IntegrityError as exc:
|
||||
raise ConflictError("公司名称已存在。") from exc
|
||||
company_id = int(cursor.lastrowid)
|
||||
with connection:
|
||||
record_change(
|
||||
connection, "company", company_id, "create",
|
||||
None, {"name": name, "credit_code": credit_code or None,
|
||||
"cashier_name": cashier_name or None, "status": "active"},
|
||||
None, actor,
|
||||
)
|
||||
return company_id
|
||||
|
||||
|
||||
@@ -210,7 +209,7 @@ def submit_bank_account(
|
||||
|
||||
if existing is None:
|
||||
try:
|
||||
with connection:
|
||||
with transaction(connection):
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO bank_accounts (
|
||||
@@ -222,23 +221,22 @@ def submit_bank_account(
|
||||
(company_id, number, holder, bank, kind,
|
||||
requested_from, actor["id"] if actor else None, now, now),
|
||||
)
|
||||
account_id = int(cursor.lastrowid)
|
||||
record_change(
|
||||
connection, "bank_account", account_id, "submit", None,
|
||||
{"company_id": company_id, "account_number": number,
|
||||
"bank_name": bank, "account_type": kind, "status": "pending",
|
||||
"effective_from": requested_from},
|
||||
None, actor,
|
||||
)
|
||||
except sqlite3.IntegrityError as exc:
|
||||
# Lost a concurrent-insert race on the UNIQUE constraint.
|
||||
raise ConflictError("该银行账号已登记,请等待现有申请处理。") from exc
|
||||
account_id = int(cursor.lastrowid)
|
||||
with connection:
|
||||
record_change(
|
||||
connection, "bank_account", account_id, "submit", None,
|
||||
{"company_id": company_id, "account_number": number,
|
||||
"bank_name": bank, "account_type": kind, "status": "pending",
|
||||
"effective_from": requested_from},
|
||||
None, actor,
|
||||
)
|
||||
return get_account(connection, account_id)
|
||||
|
||||
if existing["status"] == "returned" and existing["company_id"] == company_id:
|
||||
before = _snapshot(existing)
|
||||
with connection:
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE bank_accounts
|
||||
@@ -287,7 +285,7 @@ def review_bank_account(
|
||||
if account["status"] != "pending":
|
||||
raise ConflictError("只有待复核的账户可以审核通过。")
|
||||
start = validate_date(effective_from, "启用日期") or account["effective_from"] or today
|
||||
with connection:
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE bank_accounts
|
||||
@@ -306,7 +304,7 @@ def review_bank_account(
|
||||
raise ConflictError("只有待复核的账户可以退回。")
|
||||
if reason is None:
|
||||
raise ValueError("退回必须填写原因。")
|
||||
with connection:
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE bank_accounts
|
||||
@@ -326,7 +324,7 @@ def review_bank_account(
|
||||
if reason is None:
|
||||
raise ValueError("停用必须填写原因。")
|
||||
end = validate_date(effective_to, "停用日期") or today
|
||||
with connection:
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE bank_accounts
|
||||
@@ -448,7 +446,7 @@ def add_alias(
|
||||
if start and end and end < start:
|
||||
raise ValueError("别名失效日期不能早于生效日期。")
|
||||
try:
|
||||
with connection:
|
||||
with transaction(connection):
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO account_aliases (
|
||||
@@ -459,17 +457,16 @@ def add_alias(
|
||||
(account_id, alias_kind, value, rank, start, end,
|
||||
actor["id"] if actor else None, utc_now()),
|
||||
)
|
||||
alias_id = int(cursor.lastrowid)
|
||||
record_change(
|
||||
connection, "account_alias", alias_id, "create", None,
|
||||
{"bank_account_id": account_id, "alias_kind": alias_kind,
|
||||
"alias_value": value, "priority": rank,
|
||||
"effective_from": start, "effective_to": end},
|
||||
None, actor,
|
||||
)
|
||||
except sqlite3.IntegrityError as exc:
|
||||
raise ConflictError("该账户下相同别名已存在。") from exc
|
||||
alias_id = int(cursor.lastrowid)
|
||||
with connection:
|
||||
record_change(
|
||||
connection, "account_alias", alias_id, "create", None,
|
||||
{"bank_account_id": account_id, "alias_kind": alias_kind,
|
||||
"alias_value": value, "priority": rank,
|
||||
"effective_from": start, "effective_to": end},
|
||||
None, actor,
|
||||
)
|
||||
return alias_id
|
||||
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ import re
|
||||
import sqlite3
|
||||
|
||||
from .auth import audit
|
||||
from .db import utc_now
|
||||
from .db import transaction, utc_now
|
||||
from .master_data import (
|
||||
is_identifiable,
|
||||
normalize_account_number,
|
||||
@@ -1457,36 +1457,36 @@ def rebuild_current_projection(connection: sqlite3.Connection) -> int:
|
||||
no current pointer and no claims. Returns the number of current decisions
|
||||
rebuilt. Intended as a recovery/consistency entry point.
|
||||
"""
|
||||
connection.execute("DELETE FROM transfer_observation_claims")
|
||||
connection.execute("DELETE FROM current_transfer_decisions")
|
||||
events = connection.execute(
|
||||
"""
|
||||
SELECT e.id AS event_id,
|
||||
(SELECT d2.id FROM transfer_match_decisions d2
|
||||
WHERE d2.event_id = e.id
|
||||
ORDER BY d2.revision DESC LIMIT 1) AS latest_id
|
||||
FROM canonical_transfer_events e
|
||||
WHERE e.lifecycle = 'active'
|
||||
"""
|
||||
).fetchall()
|
||||
rebuilt = 0
|
||||
for event in events:
|
||||
if event["latest_id"] is None:
|
||||
continue
|
||||
latest = connection.execute(
|
||||
"SELECT mode FROM transfer_match_decisions WHERE id = ?",
|
||||
(event["latest_id"],),
|
||||
).fetchone()
|
||||
if latest is None or latest["mode"] == MODE_REVERSAL:
|
||||
continue
|
||||
observations = connection.execute(
|
||||
with transaction(connection):
|
||||
connection.execute("DELETE FROM transfer_observation_claims")
|
||||
connection.execute("DELETE FROM current_transfer_decisions")
|
||||
events = connection.execute(
|
||||
"""
|
||||
SELECT source_row_id FROM transfer_decision_observations
|
||||
WHERE decision_id = ? ORDER BY id
|
||||
SELECT e.id AS event_id,
|
||||
(SELECT d2.id FROM transfer_match_decisions d2
|
||||
WHERE d2.event_id = e.id
|
||||
ORDER BY d2.revision DESC LIMIT 1) AS latest_id
|
||||
FROM canonical_transfer_events e
|
||||
WHERE e.lifecycle = 'active'
|
||||
""",
|
||||
(event["latest_id"],),
|
||||
).fetchall()
|
||||
with connection:
|
||||
for event in events:
|
||||
if event["latest_id"] is None:
|
||||
continue
|
||||
latest = connection.execute(
|
||||
"SELECT mode FROM transfer_match_decisions WHERE id = ?",
|
||||
(event["latest_id"],),
|
||||
).fetchone()
|
||||
if latest is None or latest["mode"] == MODE_REVERSAL:
|
||||
continue
|
||||
observations = connection.execute(
|
||||
"""
|
||||
SELECT source_row_id FROM transfer_decision_observations
|
||||
WHERE decision_id = ? ORDER BY id
|
||||
""",
|
||||
(event["latest_id"],),
|
||||
).fetchall()
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT OR REPLACE INTO current_transfer_decisions (event_id, decision_id)
|
||||
@@ -1502,7 +1502,7 @@ def rebuild_current_projection(connection: sqlite3.Connection) -> int:
|
||||
""",
|
||||
(observation["source_row_id"], event["event_id"], event["latest_id"]),
|
||||
)
|
||||
rebuilt += 1
|
||||
rebuilt += 1
|
||||
return rebuilt
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -12,7 +12,7 @@ from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
|
||||
from .db import utc_now
|
||||
from .db import transaction, utc_now
|
||||
from .master_data import (
|
||||
ConflictError,
|
||||
mask_account_number,
|
||||
@@ -67,7 +67,7 @@ def submit_mapping(
|
||||
).fetchone()
|
||||
if existing is None:
|
||||
try:
|
||||
with connection:
|
||||
with transaction(connection):
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO personal_transit_mappings (
|
||||
@@ -81,22 +81,21 @@ def submit_mapping(
|
||||
start, actor["id"] if actor else None, now, now,
|
||||
),
|
||||
)
|
||||
mapping_id = int(cursor.lastrowid)
|
||||
record_change(
|
||||
connection, "personal_transit_mapping", mapping_id, "submit", None,
|
||||
{"account_number": number, "account_name": holder,
|
||||
"represented_company_id": represented_company_id,
|
||||
"allowed_direction": direction, "status": "pending",
|
||||
"effective_from": start},
|
||||
None, actor,
|
||||
)
|
||||
except sqlite3.IntegrityError as exc:
|
||||
raise ConflictError("该个人过账账号已登记,请等待现有申请处理。") from exc
|
||||
mapping_id = int(cursor.lastrowid)
|
||||
with connection:
|
||||
record_change(
|
||||
connection, "personal_transit_mapping", mapping_id, "submit", None,
|
||||
{"account_number": number, "account_name": holder,
|
||||
"represented_company_id": represented_company_id,
|
||||
"allowed_direction": direction, "status": "pending",
|
||||
"effective_from": start},
|
||||
None, actor,
|
||||
)
|
||||
return get_mapping(connection, mapping_id)
|
||||
|
||||
if existing["status"] == "returned":
|
||||
with connection:
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE personal_transit_mappings
|
||||
@@ -143,7 +142,7 @@ def review_mapping(
|
||||
if mapping["status"] != "pending":
|
||||
raise ConflictError("只有待复核的映射可以审核通过。")
|
||||
start = validate_date(effective_from, "生效日期") or mapping["effective_from"] or today
|
||||
with connection:
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE personal_transit_mappings
|
||||
@@ -162,7 +161,7 @@ def review_mapping(
|
||||
raise ConflictError("只有待复核的映射可以退回。")
|
||||
if reason is None:
|
||||
raise ValueError("退回必须填写原因。")
|
||||
with connection:
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE personal_transit_mappings
|
||||
@@ -182,7 +181,7 @@ def review_mapping(
|
||||
if reason is None:
|
||||
raise ValueError("停用必须填写原因。")
|
||||
end = validate_date(effective_to, "停用日期") or today
|
||||
with connection:
|
||||
with transaction(connection):
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE personal_transit_mappings
|
||||
|
||||
@@ -12,7 +12,7 @@ import re
|
||||
import sqlite3
|
||||
from datetime import datetime
|
||||
|
||||
from .db import utc_now
|
||||
from .db import utc_now, transaction
|
||||
|
||||
|
||||
# Defaults are applied when a key is absent; the value type is always string.
|
||||
@@ -93,7 +93,7 @@ def update_settings(
|
||||
if not cleaned:
|
||||
raise ValueError("没有需要保存的设置项。")
|
||||
current = get_settings(connection)
|
||||
with connection:
|
||||
with transaction(connection):
|
||||
for key, new_value in cleaned.items():
|
||||
old_value = current.get(key)
|
||||
if old_value == new_value:
|
||||
|
||||
@@ -349,6 +349,66 @@ class CoverageGapTests(CalculationBase):
|
||||
).fetchone()
|
||||
self.assertEqual("closed_attested", closed["status"])
|
||||
|
||||
def test_attestation_and_audit_survive_connection_close(self) -> None:
|
||||
"""HEL-282: attestation writes used to skip the change log; review also
|
||||
nested-committed coverage recalculation before the overlap close."""
|
||||
from bank_importer.db import connect as db_connect
|
||||
|
||||
self.add_confirmed_row(
|
||||
self.company_a,
|
||||
account_id=self.account_a["id"],
|
||||
own_account="6222000000000001",
|
||||
at="2026-06-21T10:00:00",
|
||||
)
|
||||
calculation.recalculate_coverage_gaps(self.connection)
|
||||
gap = self.connection.execute(
|
||||
"SELECT * FROM coverage_gaps WHERE status = 'open'"
|
||||
).fetchone()
|
||||
cashier_id = auth.create_user(
|
||||
self.connection, "cashier-close", "CashierA123", "company", self.company_a
|
||||
)
|
||||
cashier = self.connection.execute(
|
||||
"SELECT * FROM users WHERE id = ?", (cashier_id,)
|
||||
).fetchone()
|
||||
att = calculation.submit_no_business_attestation(
|
||||
self.connection,
|
||||
company_id=self.company_a,
|
||||
bank_account_id=self.account_a["id"],
|
||||
gap_start=gap["gap_start"],
|
||||
gap_end=gap["gap_end"],
|
||||
reason="当日账户无资金往来",
|
||||
evidence=None,
|
||||
actor=cashier,
|
||||
)
|
||||
calculation.review_no_business_attestation(
|
||||
self.connection, att["id"], "approve", "审核通过", self.admin
|
||||
)
|
||||
att_id = att["id"]
|
||||
self.connection.close()
|
||||
fresh = db_connect(self.db_path)
|
||||
try:
|
||||
row = fresh.execute(
|
||||
"SELECT status FROM no_business_attestations WHERE id = ?", (att_id,)
|
||||
).fetchone()
|
||||
actions = [
|
||||
item["action"]
|
||||
for item in fresh.execute(
|
||||
"""
|
||||
SELECT action FROM audit_log
|
||||
WHERE action LIKE 'attestation_%'
|
||||
ORDER BY id
|
||||
"""
|
||||
).fetchall()
|
||||
]
|
||||
closed = fresh.execute(
|
||||
"SELECT status FROM coverage_gaps WHERE id = ?", (gap["id"],)
|
||||
).fetchone()
|
||||
finally:
|
||||
fresh.close()
|
||||
self.assertEqual("approved", row["status"])
|
||||
self.assertEqual(["attestation_submit", "attestation_approve"], actions)
|
||||
self.assertEqual("closed_attested", closed["status"])
|
||||
|
||||
|
||||
class BalanceBasisTests(CalculationBase):
|
||||
def setUp(self) -> None:
|
||||
|
||||
@@ -50,7 +50,7 @@ class ConfirmStatusSourceContractTests(unittest.TestCase):
|
||||
self.assertIn('id="workspacePendingStatus"', html)
|
||||
self.assertIn('id="workspaceFlowSub"', html)
|
||||
self.assertIn('data-view-link="reconcile"', html)
|
||||
self.assertIn("app.js?v=13", html)
|
||||
self.assertIn("app.js?v=15", html)
|
||||
# 静态初值仍为进行中(黄),由 JS 在 pending=0 时切 done
|
||||
self.assertRegex(html, r'class="flow-step doing"[^>]*data-view-link="reconcile"')
|
||||
|
||||
|
||||
@@ -31,8 +31,8 @@ class TransfersPageSourceContractTests(unittest.TestCase):
|
||||
self.assertIn('id="transferEvidenceDrawer"', html)
|
||||
self.assertIn("期间净变动", html)
|
||||
self.assertNotIn("本公司往来合计", html)
|
||||
self.assertIn("design-system.css?v=6", html)
|
||||
self.assertIn("app.js?v=13", 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"')
|
||||
@@ -54,6 +54,10 @@ class TransfersPageSourceContractTests(unittest.TestCase):
|
||||
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 "期末余额"')
|
||||
|
||||
@@ -112,10 +116,8 @@ class TransfersPageLayoutSmokeTests(unittest.TestCase):
|
||||
page = browser.new_page()
|
||||
for width in (360, 820, 1440):
|
||||
page.set_viewport_size({"width": width, "height": 900})
|
||||
page.set_content(
|
||||
html.replace('src="app.js?v=13"', 'src=""'),
|
||||
base_url=self.base,
|
||||
)
|
||||
page.route("**/app.js**", lambda route: route.abort())
|
||||
page.goto(f"{self.base}/company.html")
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
document.querySelectorAll('.app-view').forEach((el) => {
|
||||
|
||||
@@ -257,6 +257,56 @@ class ProjectionTests(LedgerBase):
|
||||
self.assertEqual("confirmed", revision["state"])
|
||||
self.assertEqual("receivable", revision["subject_code"])
|
||||
|
||||
def test_reopen_subject_survives_connection_close(self) -> None:
|
||||
"""HEL-282: create_event used to commit the replacement event while
|
||||
the bank-source re-claim stayed uncommitted; close() dropped the claim."""
|
||||
from bank_importer.db import connect as db_connect
|
||||
|
||||
self.pair(self.company_a, self.company_b, "100.00")
|
||||
ledger_events.reconcile_bank_events(self.connection, actor=self.admin)
|
||||
original_id = self.ledger_events()[0]["id"]
|
||||
subjects.confirm_subject(
|
||||
self.connection, original_id,
|
||||
perspective_company_id=self.company_a, subject_code="receivable",
|
||||
reason="确认应收", expected_revision=1, request_key="k1",
|
||||
actor=self.admin,
|
||||
)
|
||||
new_id, _ = ledger_events.reopen_subject(
|
||||
self.connection, original_id,
|
||||
reason="科目复核更正为其他应收", actor=self.admin,
|
||||
)
|
||||
self.connection.close()
|
||||
fresh = db_connect(self.db_path)
|
||||
try:
|
||||
claim = fresh.execute(
|
||||
"SELECT ledger_event_id FROM ledger_event_bank_sources"
|
||||
).fetchone()
|
||||
new_state = fresh.execute(
|
||||
"""
|
||||
SELECT r.state FROM current_ledger_event_revisions c
|
||||
JOIN ledger_event_revisions r ON r.id = c.revision_id
|
||||
WHERE c.ledger_event_id = ?
|
||||
""",
|
||||
(new_id,),
|
||||
).fetchone()
|
||||
suggestions = fresh.execute(
|
||||
"SELECT COUNT(*) AS n FROM ledger_subject_suggestions WHERE ledger_event_id = ?",
|
||||
(new_id,),
|
||||
).fetchone()["n"]
|
||||
reversal = fresh.execute(
|
||||
"""
|
||||
SELECT COUNT(*) AS n FROM ledger_event_revisions
|
||||
WHERE posting_kind = 'reversal' AND reverses_ledger_event_id = ?
|
||||
""",
|
||||
(original_id,),
|
||||
).fetchone()["n"]
|
||||
finally:
|
||||
fresh.close()
|
||||
self.assertEqual(new_id, claim["ledger_event_id"])
|
||||
self.assertEqual("pending_subject", new_state["state"])
|
||||
self.assertGreaterEqual(suggestions, 1)
|
||||
self.assertEqual(1, reversal)
|
||||
|
||||
|
||||
class SubjectSuggestionTests(LedgerBase):
|
||||
def test_mirror_mapping_is_symmetric(self) -> None:
|
||||
|
||||
@@ -210,6 +210,40 @@ class MasterDataUnitTests(unittest.TestCase):
|
||||
)
|
||||
|
||||
|
||||
class MasterDataCommitTests(unittest.TestCase):
|
||||
"""File-database checks that business rows and audit share one commit."""
|
||||
|
||||
def setUp(self) -> None:
|
||||
self.temp_dir = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp_dir.cleanup)
|
||||
self.db_path = Path(self.temp_dir.name) / "app.db"
|
||||
self.connection = connect(self.db_path)
|
||||
self.addCleanup(self.connection.close)
|
||||
migrate(self.connection)
|
||||
|
||||
def test_create_company_and_audit_survive_connection_close(self) -> None:
|
||||
company_id = master_data.create_company(
|
||||
self.connection, "丁公司", None, None, actor=None
|
||||
)
|
||||
self.connection.close()
|
||||
fresh = connect(self.db_path)
|
||||
try:
|
||||
company = fresh.execute(
|
||||
"SELECT name FROM companies WHERE id = ?", (company_id,)
|
||||
).fetchone()
|
||||
change = fresh.execute(
|
||||
"""
|
||||
SELECT action, entity_id FROM master_data_changes
|
||||
WHERE entity_type = 'company'
|
||||
"""
|
||||
).fetchone()
|
||||
finally:
|
||||
fresh.close()
|
||||
self.assertEqual("丁公司", company["name"])
|
||||
self.assertEqual("create", change["action"])
|
||||
self.assertEqual(company_id, change["entity_id"])
|
||||
|
||||
|
||||
class MasterDataApiTests(unittest.TestCase):
|
||||
"""Live-server workflow tests for account registration and review."""
|
||||
|
||||
|
||||
@@ -943,6 +943,38 @@ class ProjectionRebuildTests(MatchingBase):
|
||||
self.assertEqual(sorted(before), sorted(after))
|
||||
self.assertEqual(sorted(claims_before), sorted(claims_after))
|
||||
|
||||
def test_rebuild_clears_stale_projection_and_survives_close(self) -> None:
|
||||
"""HEL-282: DELETEs used to stay uncommitted when nothing was restored."""
|
||||
from bank_importer.db import connect as db_connect
|
||||
|
||||
row_a = self.add_row(
|
||||
self.company_a, own_account="6222000000000001",
|
||||
cp_account="6222000000000002", expense="100.00",
|
||||
)
|
||||
row_b = self.add_row(
|
||||
self.company_b, own_account="6222000000000002",
|
||||
cp_account="6222000000000001", income="100.00",
|
||||
)
|
||||
matching.reconcile_rows(self.connection, [row_a, row_b])
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
"UPDATE canonical_transfer_events SET lifecycle = 'superseded'"
|
||||
)
|
||||
matching.rebuild_current_projection(self.connection)
|
||||
self.connection.close()
|
||||
fresh = db_connect(self.db_path)
|
||||
try:
|
||||
remaining = fresh.execute(
|
||||
"SELECT COUNT(*) AS n FROM current_transfer_decisions"
|
||||
).fetchone()["n"]
|
||||
claims = fresh.execute(
|
||||
"SELECT COUNT(*) AS n FROM transfer_observation_claims"
|
||||
).fetchone()["n"]
|
||||
finally:
|
||||
fresh.close()
|
||||
self.assertEqual(0, remaining)
|
||||
self.assertEqual(0, claims)
|
||||
|
||||
|
||||
class ConcurrentReconcileTests(MatchingBase):
|
||||
def test_concurrent_reconcile_creates_one_event(self) -> None:
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
"""Monthly close, reopen approval, snapshot hash and locked-period writes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
from bank_importer import period_close
|
||||
from ledger_helpers import LedgerBase
|
||||
|
||||
|
||||
class PeriodCloseTests(LedgerBase):
|
||||
TODAY = date(2026, 8, 30)
|
||||
MONTH = "2026-07"
|
||||
|
||||
def _cover_month(self) -> None:
|
||||
self.add_row(
|
||||
self.company_a, own_account="6222000000000001",
|
||||
expense="100.00", at="2026-07-10T10:00:00",
|
||||
)
|
||||
self.add_row(
|
||||
self.company_b, own_account="6222000000000002",
|
||||
income="80.00", at="2026-07-12T10:00:00",
|
||||
)
|
||||
|
||||
def _close(self, month: str = MONTH):
|
||||
period_close.ensure_pending_tasks(self.connection, today=self.TODAY)
|
||||
return period_close.execute_close(
|
||||
self.connection, month, self.admin, confirm=True,
|
||||
)
|
||||
|
||||
def test_execute_requires_confirm_checkbox(self) -> None:
|
||||
self._cover_month()
|
||||
with self.assertRaises(period_close.PeriodCloseError) as ctx:
|
||||
period_close.execute_close(
|
||||
self.connection, self.MONTH, self.admin, confirm=False,
|
||||
)
|
||||
self.assertIn("勾选", str(ctx.exception))
|
||||
|
||||
def test_blockers_reject_close(self) -> None:
|
||||
period_close.ensure_pending_tasks(self.connection, today=self.TODAY)
|
||||
evaluation = period_close.evaluate_preconditions(self.connection, self.MONTH)
|
||||
self.assertFalse(evaluation["ready"])
|
||||
with self.assertRaises(period_close.PeriodCloseError):
|
||||
period_close.execute_close(
|
||||
self.connection, self.MONTH, self.admin, confirm=True,
|
||||
)
|
||||
|
||||
def test_close_snapshot_hash_stable_and_idempotent(self) -> None:
|
||||
self._cover_month()
|
||||
period_close.ensure_pending_tasks(self.connection, today=self.TODAY)
|
||||
before = period_close.build_snapshot(self.connection, self.MONTH)
|
||||
digest_before = hashlib.sha256(
|
||||
json.dumps(before, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
||||
).hexdigest()
|
||||
first = period_close.execute_close(
|
||||
self.connection, self.MONTH, self.admin, confirm=True,
|
||||
)
|
||||
self.assertEqual("closed", first["status"])
|
||||
self.assertTrue(first["report_no"].startswith("MR-202607-"))
|
||||
digest = first["snapshot_hash"]
|
||||
self.assertEqual(64, len(digest))
|
||||
self.assertEqual(digest_before, digest)
|
||||
run = self.connection.execute(
|
||||
"SELECT snapshot_json, snapshot_hash FROM period_close_runs WHERE year_month = ?",
|
||||
(self.MONTH,),
|
||||
).fetchone()
|
||||
self.assertEqual(digest, run["snapshot_hash"])
|
||||
self.assertEqual(
|
||||
digest,
|
||||
hashlib.sha256(run["snapshot_json"].encode("utf-8")).hexdigest(),
|
||||
)
|
||||
self.assertEqual(
|
||||
digest,
|
||||
hashlib.sha256(run["snapshot_json"].encode("utf-8")).hexdigest(),
|
||||
)
|
||||
with self.assertRaises(period_close.PeriodConflictError):
|
||||
period_close.execute_close(
|
||||
self.connection, self.MONTH, self.admin, confirm=True,
|
||||
)
|
||||
|
||||
def test_locked_month_rejects_writes(self) -> None:
|
||||
self._cover_month()
|
||||
self._close()
|
||||
with self.assertRaises(period_close.PeriodLockedError) as ctx:
|
||||
period_close.assert_date_writable(self.connection, "2026-07-15")
|
||||
self.assertIn("2026-07", str(ctx.exception))
|
||||
self.assertIn("已结账锁定", str(ctx.exception))
|
||||
period_close.assert_date_writable(self.connection, "2026-08-01")
|
||||
|
||||
def test_late_arrivals_do_not_rewrite_snapshot(self) -> None:
|
||||
self._cover_month()
|
||||
closed = self._close()
|
||||
digest = closed["snapshot_hash"]
|
||||
late_id = self.add_row(
|
||||
self.company_a, own_account="6222000000000001",
|
||||
expense="12.00", at="2026-07-28T11:00:00",
|
||||
)
|
||||
writable, locked = period_close.split_writable_row_ids(self.connection, [late_id])
|
||||
self.assertEqual([], writable)
|
||||
self.assertEqual([(late_id, "2026-07")], locked)
|
||||
n = period_close.record_late_arrivals(self.connection, locked, self.admin)
|
||||
self.assertEqual(1, n)
|
||||
again = period_close.close_payload(self.connection, self.MONTH)
|
||||
self.assertEqual(digest, again["snapshot_hash"])
|
||||
|
||||
def test_late_arrivals_survive_connection_close(self) -> None:
|
||||
"""Regression: the reconcile handler closes its connection right after
|
||||
recording locked rows; uncommitted inserts used to vanish silently."""
|
||||
from bank_importer.db import connect as db_connect
|
||||
|
||||
self._cover_month()
|
||||
self._close()
|
||||
late_id = self.add_row(
|
||||
self.company_a, own_account="6222000000000001",
|
||||
expense="12.00", at="2026-07-28T11:00:00",
|
||||
)
|
||||
writable, locked = period_close.split_writable_row_ids(self.connection, [late_id])
|
||||
self.assertEqual(1, period_close.record_late_arrivals(self.connection, locked, self.admin))
|
||||
self.connection.close()
|
||||
fresh = db_connect(self.db_path)
|
||||
try:
|
||||
rows = fresh.execute(
|
||||
"SELECT source_row_id FROM period_late_arrivals"
|
||||
).fetchall()
|
||||
audits = fresh.execute(
|
||||
"SELECT action FROM period_audit_events WHERE action = 'late_arrival'"
|
||||
).fetchall()
|
||||
finally:
|
||||
fresh.close()
|
||||
self.assertEqual([late_id], [r["source_row_id"] for r in rows])
|
||||
self.assertEqual(1, len(audits))
|
||||
|
||||
def test_snapshot_row_cannot_be_updated(self) -> None:
|
||||
self._cover_month()
|
||||
self._close()
|
||||
with self.assertRaises(Exception):
|
||||
with self.connection:
|
||||
self.connection.execute(
|
||||
"UPDATE period_close_runs SET snapshot_json = '{}' WHERE year_month = ?",
|
||||
(self.MONTH,),
|
||||
)
|
||||
|
||||
def test_reopen_reject_then_approve_and_reclose_version_chain(self) -> None:
|
||||
self._cover_month()
|
||||
first = self._close()
|
||||
with self.assertRaises(period_close.PeriodCloseError):
|
||||
period_close.request_reopen(
|
||||
self.connection, self.MONTH, self.admin, reason="太短",
|
||||
)
|
||||
req = period_close.request_reopen(
|
||||
self.connection, self.MONTH, self.admin,
|
||||
reason="补录金牛煤业七月运输费并核对金额",
|
||||
companies_note="甲公司 ↔ 乙公司",
|
||||
window_days=3,
|
||||
)
|
||||
self.assertEqual("pending", req["status"])
|
||||
rejected = period_close.decide_reopen(
|
||||
self.connection, req["id"], self.admin, approve=False, comment="证据不足",
|
||||
)
|
||||
self.assertEqual("rejected", rejected["status"])
|
||||
self.assertTrue(period_close.is_month_locked(self.connection, self.MONTH))
|
||||
req2 = period_close.request_reopen(
|
||||
self.connection, self.MONTH, self.admin,
|
||||
reason="已补齐银行回单,申请重开更正科目",
|
||||
)
|
||||
approved = period_close.decide_reopen(
|
||||
self.connection, req2["id"], self.admin, approve=True, comment="同意",
|
||||
)
|
||||
self.assertEqual("approved", approved["status"])
|
||||
self.assertFalse(period_close.is_month_locked(self.connection, self.MONTH))
|
||||
period_close.assert_date_writable(self.connection, "2026-07-15")
|
||||
second = period_close.execute_close(
|
||||
self.connection, self.MONTH, self.admin, confirm=True,
|
||||
)
|
||||
self.assertEqual("closed", second["status"])
|
||||
self.assertNotEqual(first["report_no"], second["report_no"])
|
||||
versions = self.connection.execute(
|
||||
"SELECT version, report_no FROM period_close_runs WHERE year_month = ? ORDER BY version",
|
||||
(self.MONTH,),
|
||||
).fetchall()
|
||||
self.assertGreaterEqual(len(versions), 2)
|
||||
self.assertEqual(1, versions[0]["version"])
|
||||
self.assertEqual(2, versions[-1]["version"])
|
||||
|
||||
def test_close_and_reopen_request_survive_connection_close(self) -> None:
|
||||
"""HEL-282: monthly close / reopen request must persist with audit."""
|
||||
from bank_importer.db import connect as db_connect
|
||||
|
||||
self._cover_month()
|
||||
closed = self._close()
|
||||
req = period_close.request_reopen(
|
||||
self.connection, self.MONTH, self.admin,
|
||||
reason="补录金牛煤业七月运输费并核对金额",
|
||||
)
|
||||
report_no = closed["report_no"]
|
||||
request_id = req["id"]
|
||||
self.connection.close()
|
||||
fresh = db_connect(self.db_path)
|
||||
try:
|
||||
run = fresh.execute(
|
||||
"SELECT status, report_no FROM period_close_runs WHERE year_month = ?",
|
||||
(self.MONTH,),
|
||||
).fetchone()
|
||||
reopen = fresh.execute(
|
||||
"SELECT status FROM period_reopen_requests WHERE id = ?",
|
||||
(request_id,),
|
||||
).fetchone()
|
||||
actions = {
|
||||
row["action"]
|
||||
for row in fresh.execute(
|
||||
"SELECT action FROM period_audit_events"
|
||||
).fetchall()
|
||||
}
|
||||
finally:
|
||||
fresh.close()
|
||||
self.assertEqual("closed", run["status"])
|
||||
self.assertEqual(report_no, run["report_no"])
|
||||
self.assertEqual("pending", reopen["status"])
|
||||
self.assertTrue({"close_execute", "reopen_request"} <= actions)
|
||||
|
||||
def test_wal_on_file_database(self) -> None:
|
||||
mode = self.connection.execute("PRAGMA journal_mode").fetchone()[0]
|
||||
self.assertEqual("wal", str(mode).lower())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -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):
|
||||
def test_migrate_creates_schema_and_is_idempotent(self) -> None:
|
||||
first = applied_versions(self.connection)
|
||||
self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8, 9], first)
|
||||
self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], first)
|
||||
self.assertEqual([], migrate(self.connection))
|
||||
self.assertEqual(first, applied_versions(self.connection))
|
||||
tables = {
|
||||
@@ -89,19 +89,23 @@ class MigrationTests(PersistenceTestCase):
|
||||
"coverage_gaps",
|
||||
"no_business_attestations",
|
||||
"reminders_legacy_manual",
|
||||
"period_close_runs",
|
||||
"period_reopen_requests",
|
||||
"period_late_arrivals",
|
||||
"period_audit_events",
|
||||
"schema_migrations",
|
||||
):
|
||||
self.assertIn(table, tables)
|
||||
|
||||
def test_rollback_removes_schema_and_forward_rebuilds_it(self) -> None:
|
||||
self.assertEqual([9, 8, 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))
|
||||
remaining = self.connection.execute(
|
||||
"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'source_rows'"
|
||||
).fetchone()
|
||||
self.assertIsNone(remaining)
|
||||
self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8, 9], migrate(self.connection))
|
||||
self.assertEqual([1, 2, 3, 4, 5, 6, 7, 8, 9], applied_versions(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, 8, 9, 10], applied_versions(self.connection))
|
||||
|
||||
def test_rollback_to_4_keeps_bank_evidence_and_drops_event_layer(self) -> None:
|
||||
self.import_sample()
|
||||
@@ -109,7 +113,7 @@ class MigrationTests(PersistenceTestCase):
|
||||
"SELECT COUNT(*) AS n FROM source_rows"
|
||||
).fetchone()["n"]
|
||||
self.assertGreater(row_count, 0)
|
||||
self.assertEqual([9, 8, 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.
|
||||
self.assertEqual(
|
||||
row_count,
|
||||
|
||||
@@ -477,8 +477,8 @@ class MigrationTests(unittest.TestCase):
|
||||
versions = connection.execute(
|
||||
"SELECT version FROM schema_migrations ORDER BY version"
|
||||
).fetchall()
|
||||
self.assertEqual(9, versions[-1]["version"])
|
||||
connection.execute("DELETE FROM schema_migrations WHERE version = 9")
|
||||
self.assertEqual(10, versions[-1]["version"])
|
||||
connection.execute("DELETE FROM schema_migrations WHERE version = 10")
|
||||
connection.executescript(
|
||||
"""
|
||||
DROP TRIGGER IF EXISTS reminders_no_delete;
|
||||
|
||||
@@ -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()
|
||||
+306
-109
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="description" content="金牛集团管理端" />
|
||||
<title>管理端 · 金牛集团</title>
|
||||
<link rel="stylesheet" href="design-system.css?v=8" />
|
||||
<link rel="stylesheet" href="design-system.css?v=10" />
|
||||
</head>
|
||||
<body data-portal="admin">
|
||||
<a class="skip-link" href="#main-content">跳到主要内容</a>
|
||||
@@ -25,6 +25,7 @@
|
||||
<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="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>
|
||||
</nav>
|
||||
<div class="side-foot">
|
||||
@@ -241,7 +242,7 @@
|
||||
<div class="notice warn" id="pairNotice" style="display: none; margin-bottom: 14px;">
|
||||
<div>
|
||||
<div class="n-title">该公司组合暂无归集数据</div>
|
||||
<div class="n-body">所选组合在正式环境中将按相同口径实时归集,当前仅内置演示数据组合。</div>
|
||||
<div class="n-body">所选组合暂无已确认往来,列表将显示「暂无数据」。</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="reopen" data-label="重开审批" aria-pressed="false">重开审批<span class="tab-count" id="reopenTabCount">0</span></button>
|
||||
</div>
|
||||
<div class="field" style="min-width: 180px;">
|
||||
<label for="auditCompany">公司</label>
|
||||
@@ -343,7 +345,7 @@
|
||||
</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">
|
||||
<thead>
|
||||
<tr>
|
||||
@@ -364,6 +366,19 @@
|
||||
<span>审核人:系统管理员 · 操作实时写入审核日志</span>
|
||||
</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 class="app-view" data-page="flows">
|
||||
@@ -426,9 +441,14 @@
|
||||
</thead>
|
||||
<tbody></tbody>
|
||||
</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">
|
||||
<span id="flowCount">共 0 笔</span>
|
||||
<span class="meta" id="flowsRangeMeta">数据范围:加载中…</span>
|
||||
<span class="num" id="flowSum"></span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -491,15 +511,8 @@
|
||||
<div class="card-head">
|
||||
<span class="card-title">账期时间轴<span class="sub" id="timelineSub">全局起算日 2026-01-01 起,每月 5 日结账</span></span>
|
||||
</div>
|
||||
<div class="timeline">
|
||||
<div class="tl-cell closed"><div class="tl-month">2026-01</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 class="timeline" id="periodTimeline">
|
||||
<div class="tl-cell open"><div class="tl-month">—</div><div class="tl-state">加载中</div></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -579,54 +592,146 @@
|
||||
|
||||
<div class="card" id="closingPanel">
|
||||
<div class="card-head">
|
||||
<span class="card-title">月度结账<span class="sub" id="closingDescription">2026 年 7 月 · 当前未达到结账条件</span></span>
|
||||
<span class="pill pill-danger" id="closingStatus">已阻断</span>
|
||||
<span class="card-title">月度结账<span class="sub" id="closingDescription">加载账期状态…</span></span>
|
||||
<span class="pill pill-muted" id="closingStatus">—</span>
|
||||
</div>
|
||||
<div id="closingBody">
|
||||
<div class="closing-check-list">
|
||||
<div class="list-row">
|
||||
<span class="pill pill-success" 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-side"><span class="pill pill-warn" data-closing-state>待处理</span></div>
|
||||
<div class="list-row" data-closing-key="submissions">
|
||||
<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>—</div></div>
|
||||
<div class="lr-side"><span class="pill pill-muted" data-closing-state>—</span></div>
|
||||
</div>
|
||||
<div class="list-row">
|
||||
<span class="pill pill-success" 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-side"><span class="pill pill-danger" data-closing-state>阻断</span></div>
|
||||
<div class="list-row" data-closing-key="coverage">
|
||||
<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>—</div></div>
|
||||
<div class="lr-side"><span class="pill pill-muted" data-closing-state>—</span></div>
|
||||
</div>
|
||||
<div class="list-row">
|
||||
<span class="pill pill-success" 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-side"><span class="pill pill-danger" data-closing-state>阻断</span></div>
|
||||
<div class="list-row" data-closing-key="reviews">
|
||||
<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>—</div></div>
|
||||
<div class="lr-side"><span class="pill pill-muted" data-closing-state>—</span></div>
|
||||
</div>
|
||||
<div class="list-row">
|
||||
<span class="pill pill-success" 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-side"><span class="pill pill-success" data-closing-state>已通过</span></div>
|
||||
<div class="list-row" data-closing-key="opening">
|
||||
<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>—</div></div>
|
||||
<div class="lr-side"><span class="pill pill-muted" data-closing-state>—</span></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>
|
||||
<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>
|
||||
</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>
|
||||
<div class="n-title">2026-07 已结账</div>
|
||||
<div class="n-body" id="closed-notice-body">结账后各公司 7 月往来数据已锁定,期初数将结转至 2026-08 账期。</div>
|
||||
<div class="n-title" id="closed-notice-title">账期已锁定</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 class="row" style="margin-top: 16px; justify-content: flex-end; flex-wrap: wrap;">
|
||||
<span class="meta" id="closingHistory" style="margin-right: auto;">最近结账:2026 年 6 月 · 系统管理员 · 2026.07.05 18:10</span>
|
||||
<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;">—</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 btn-primary" id="executeClosing" disabled title="请先处理全部阻断事项">执行 2026-07 月度结账</button>
|
||||
<button class="btn btn-primary" id="executeClosing" disabled title="请先处理全部阻断事项">执行月度结账</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</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">
|
||||
<div class="page-head">
|
||||
<div>
|
||||
@@ -638,7 +743,8 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card" id="pending-reminders-card" style="margin-bottom: 16px;">
|
||||
<div class="stack">
|
||||
<div class="card" id="pending-reminders-card">
|
||||
<div class="card-head">
|
||||
<span class="card-title">待提醒清单<span class="sub">系统按流水提交、断档、待确认自动发现,点发送即送达对应公司</span></span>
|
||||
<div class="row" style="gap: 10px; align-items: center;">
|
||||
@@ -651,72 +757,93 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-1-2">
|
||||
<div class="card">
|
||||
<div class="card-head">
|
||||
<span class="card-title">发送处理提醒<span class="sub">选择公司后系统自动列出待提醒事项,核对后一键发送</span></span>
|
||||
</div>
|
||||
<form id="reminderForm" novalidate>
|
||||
<div class="field" style="margin-bottom: 14px;">
|
||||
<label>接收公司(可多选)</label>
|
||||
<div class="row" id="reminderCompanyList" style="flex-wrap: wrap; gap: 8px 16px;"></div>
|
||||
<span class="hint error" id="company-error" style="display: none;">请至少选择一家接收公司</span>
|
||||
</div>
|
||||
<div class="field" style="margin-bottom: 14px;">
|
||||
<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" style="margin-bottom: 14px;">
|
||||
<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 class="field" style="margin-bottom: 18px;">
|
||||
<label for="reminder-deadline">截止日期</label>
|
||||
<input class="input" type="date" id="reminder-deadline" value="2026-08-29" min="2026-08-20" />
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary" id="send-btn" style="width: 100%;">发送提醒</button>
|
||||
<p class="hint" id="send-hint" style="margin-top: 10px; display: none;"></p>
|
||||
</form>
|
||||
<div class="card" id="reminder-history-card">
|
||||
<div class="card-head">
|
||||
<span class="card-title">提醒历史<span class="sub">含系统自动触发与人工发送的全部提醒记录</span></span>
|
||||
</div>
|
||||
<div class="tabs" id="reminder-tabs">
|
||||
<button type="button" class="active" data-filter="all">全部<span class="tab-count" id="count-all">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>
|
||||
</div>
|
||||
<div class="table-wrap history-table">
|
||||
<table class="ds-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>公司</th>
|
||||
<th>来源</th>
|
||||
<th>类型</th>
|
||||
<th class="wrap">内容摘要</th>
|
||||
<th>发送时间</th>
|
||||
<th>截止日期</th>
|
||||
<th>处理状态</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="reminder-tbody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="table-foot">
|
||||
<span id="table-foot-count">共 0 条提醒记录</span>
|
||||
<span id="table-foot-state">未读 0 · 处理中 0 · 已完成 0</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-head">
|
||||
<span class="card-title">提醒历史<span class="sub">含系统自动触发与人工发送的全部提醒记录</span></span>
|
||||
</div>
|
||||
<div class="tabs" id="reminder-tabs">
|
||||
<button type="button" class="active" data-filter="all">全部<span class="tab-count" id="count-all">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>
|
||||
</div>
|
||||
<div class="table-wrap" style="border: 0;">
|
||||
<table class="ds-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>公司</th>
|
||||
<th>来源</th>
|
||||
<th>类型</th>
|
||||
<th class="wrap">内容摘要</th>
|
||||
<th>发送时间</th>
|
||||
<th>截止日期</th>
|
||||
<th>处理状态</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="reminder-tbody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="table-foot">
|
||||
<span id="table-foot-count">共 0 条提醒记录</span>
|
||||
<span id="table-foot-state">未读 0 · 处理中 0 · 已完成 0</span>
|
||||
</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>
|
||||
</section>
|
||||
</main>
|
||||
@@ -891,29 +1018,99 @@
|
||||
<div class="modal-backdrop" id="closingDialog">
|
||||
<div class="modal">
|
||||
<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>
|
||||
</div>
|
||||
<p class="modal-sub">结账后成员公司的 7 月流水与往来确认将锁定,不可再修改。</p>
|
||||
<p class="modal-sub" id="closingDialogSub">结账后该月流水与往来确认将锁定,不可再直接修改。</p>
|
||||
<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">
|
||||
<dl class="kv">
|
||||
<dt>结账账期</dt><dd>2026-07</dd>
|
||||
<dt>检查通过</dt><dd>全部前置检查已通过</dd>
|
||||
<dt>期末归集</dt><dd>往来净额将结转至 2026-08 期初</dd>
|
||||
<dt>结账账期</dt><dd id="cdMonth">—</dd>
|
||||
<dt>检查通过</dt><dd id="cdChecks">—</dd>
|
||||
<dt>期末归集</dt><dd id="cdCarry">往来净额将结转至下一账期期初</dd>
|
||||
</dl>
|
||||
</div>
|
||||
<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>
|
||||
<div class="modal-actions">
|
||||
<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>
|
||||
</form>
|
||||
</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 wide">
|
||||
@@ -1011,6 +1208,6 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="toast-region" id="toastRegion" aria-live="polite"></div>
|
||||
<script src="app.js?v=13"></script>
|
||||
<script src="app.js?v=15"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+862
-395
File diff suppressed because it is too large
Load Diff
+3
-3
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="description" content="金牛集团公司业务端" />
|
||||
<title>公司业务端 · 金牛集团</title>
|
||||
<link rel="stylesheet" href="design-system.css?v=6" />
|
||||
<link rel="stylesheet" href="design-system.css?v=7" />
|
||||
</head>
|
||||
<body data-portal="company">
|
||||
<a class="skip-link" href="#main-content">跳到主要内容</a>
|
||||
@@ -301,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><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><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><select class="select" name="subject" required><option>应收</option><option>应付</option><option>其他应收</option><option>其他应付</option></select></div>
|
||||
</div>
|
||||
@@ -1009,6 +1009,6 @@
|
||||
</aside>
|
||||
|
||||
<div class="toast-region" id="toastRegion" aria-live="polite"></div>
|
||||
<script src="app.js?v=13"></script>
|
||||
<script src="app.js?v=15"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1083,3 +1083,211 @@ body[data-portal="company"] .side-nav a[data-view="transfers"].active svg {
|
||||
.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