Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9193a3fce0 | ||
|
|
9e0e4a103a | ||
|
|
2d0ae4d7d1 | ||
|
|
9cfd515b8f |
@@ -28,3 +28,9 @@ package-lock.json
|
|||||||
# local vendor for agent test env (not shipped)
|
# local vendor for agent test env (not shipped)
|
||||||
.vendor/
|
.vendor/
|
||||||
vendor_wheels/
|
vendor_wheels/
|
||||||
|
|
||||||
|
# 正式环境部署产物(证书私钥、备份)
|
||||||
|
deploy/tls/certs/
|
||||||
|
backups/
|
||||||
|
ALERT.log
|
||||||
|
backup.log
|
||||||
|
|||||||
@@ -16,3 +16,16 @@ APP_BOOTSTRAP_ADMIN_PASSWORD=change-me-in-local-env
|
|||||||
|
|
||||||
# 内网测试可暂时关闭登录失败锁定;正式环境不得开启
|
# 内网测试可暂时关闭登录失败锁定;正式环境不得开启
|
||||||
# APP_LOGIN_RATE_LIMIT_DISABLED=1
|
# 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 生成证书
|
||||||
|
|||||||
@@ -46,6 +46,45 @@ docker exec caiwuzongzhang-app python -c "import sqlite3; s=sqlite3.connect('/ap
|
|||||||
docker cp caiwuzongzhang-app:/tmp/b.db ../backups/app.db.$STAMP
|
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 分钟内)
|
## 4. 回滚(应用层,5 分钟内)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -68,6 +107,16 @@ cd deploy && ./rollback.sh <上一个镜像tag>
|
|||||||
|
|
||||||
cron `*/5 * * * *` 运行 `deploy/monitor.sh`;连续失败或磁盘 ≥80% 时查看 `deploy/ALERT.log` 并按需扩容/清理。容器重启策略 `unless-stopped`。
|
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. 升级数据库
|
## 7. 升级数据库
|
||||||
|
|
||||||
应用启动时自动执行迁移(`MIGRATIONS`,当前版本 10)。迁移只前不改写历史;回退 schema 用对应 down 迁移,先备份后操作。
|
应用启动时自动执行迁移(`MIGRATIONS`,当前版本 10)。迁移只前不改写历史;回退 schema 用对应 down 迁移,先备份后操作。
|
||||||
|
|||||||
+55
-2
@@ -1,10 +1,16 @@
|
|||||||
# 测试/正式环境部署编排(正式口令不得写入本文件)。
|
# 测试/正式环境部署编排(正式口令不得写入本文件)。
|
||||||
# 使用:复制 .env.example 为 .env 填写;TAG 指定镜像标签(默认取当前提交 sha)。
|
# 使用:复制 .env.example 为 .env 填写;TAG 指定镜像标签(默认取当前提交 sha)。
|
||||||
# 例:TAG=v1.0.0-rc1 docker compose -f compose.yaml up -d --build
|
# 例: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:
|
services:
|
||||||
app:
|
app:
|
||||||
container_name: caiwuzongzhang-app
|
container_name: ${APP_CONTAINER_NAME:-caiwuzongzhang-app}
|
||||||
image: caiwuzongzhang:${TAG:-latest}
|
image: caiwuzongzhang:${TAG:-latest}
|
||||||
build:
|
build:
|
||||||
context: ..
|
context: ..
|
||||||
@@ -15,7 +21,7 @@ services:
|
|||||||
# APP_UID/APP_GID,正式与测试环境各自填写,默认镜像内 app=10001)
|
# APP_UID/APP_GID,正式与测试环境各自填写,默认镜像内 app=10001)
|
||||||
user: "${APP_UID:-10001}:${APP_GID:-10001}"
|
user: "${APP_UID:-10001}:${APP_GID:-10001}"
|
||||||
ports:
|
ports:
|
||||||
- "4173:4173"
|
- "${APP_PORT_MAP:-4173:4173}"
|
||||||
volumes:
|
volumes:
|
||||||
- ../data:/app/data
|
- ../data:/app/data
|
||||||
init: true
|
init: true
|
||||||
@@ -30,9 +36,56 @@ services:
|
|||||||
pids_limit: 128
|
pids_limit: 128
|
||||||
mem_limit: 512m
|
mem_limit: 512m
|
||||||
cpus: 1.0
|
cpus: 1.0
|
||||||
|
logging:
|
||||||
|
driver: json-file
|
||||||
|
options:
|
||||||
|
max-size: "10m"
|
||||||
|
max-file: "3"
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:4173/', timeout=2)"]
|
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:4173/', timeout=2)"]
|
||||||
interval: 15s
|
interval: 15s
|
||||||
timeout: 3s
|
timeout: 3s
|
||||||
retries: 5
|
retries: 5
|
||||||
start_period: 10s
|
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
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,7 +18,7 @@ from bank_importer import (
|
|||||||
manual_records, master_data, matching, multipart, period_close, personal_transit,
|
manual_records, master_data, matching, multipart, period_close, personal_transit,
|
||||||
positions, reminders, settings, subjects,
|
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
|
ROOT = Path(__file__).resolve().parent
|
||||||
@@ -2615,22 +2615,22 @@ class AppHandler(SimpleHTTPRequestHandler):
|
|||||||
)
|
)
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
|
with transaction(connection):
|
||||||
result = matching.reconcile_rows(connection, writable, actor=user)
|
result = matching.reconcile_rows(connection, writable, actor=user)
|
||||||
except Exception as exc:
|
|
||||||
self._send_json(500, {"status": "error", "message": f"重跑匹配失败:{exc}"})
|
|
||||||
return
|
|
||||||
try:
|
|
||||||
ledger_events.reconcile_bank_events(connection, actor=user)
|
ledger_events.reconcile_bank_events(connection, actor=user)
|
||||||
except Exception as exc:
|
|
||||||
self._send_json(500, {"status": "error", "message": f"同步往来事件失败:{exc}"})
|
|
||||||
return
|
|
||||||
result["late_arrivals"] = late
|
result["late_arrivals"] = late
|
||||||
auth.audit(
|
auth.audit(
|
||||||
connection, "transfer_reconcile", actor=user,
|
connection, "transfer_reconcile", actor=user,
|
||||||
target=f"rows:{len(writable)}",
|
target=f"rows:{len(writable)}",
|
||||||
detail=f"created:{result['created_events']};updated:{result['updated_events']};late:{late}",
|
detail=(
|
||||||
|
f"created:{result['created_events']};"
|
||||||
|
f"updated:{result['updated_events']};late:{late}"
|
||||||
|
),
|
||||||
ip=self._client_ip,
|
ip=self._client_ip,
|
||||||
)
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
self._send_json(500, {"status": "error", "message": f"重跑匹配失败:{exc}"})
|
||||||
|
return
|
||||||
self._send_json(200, {"status": "ok", "matching": result, "late_arrivals": late})
|
self._send_json(200, {"status": "ok", "matching": result, "late_arrivals": late})
|
||||||
finally:
|
finally:
|
||||||
connection.close()
|
connection.close()
|
||||||
@@ -2660,6 +2660,7 @@ class AppHandler(SimpleHTTPRequestHandler):
|
|||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
period_close.assert_event_writable(connection, event_id)
|
period_close.assert_event_writable(connection, event_id)
|
||||||
|
with transaction(connection):
|
||||||
payload = matching.apply_manual_decision(
|
payload = matching.apply_manual_decision(
|
||||||
connection,
|
connection,
|
||||||
event_id,
|
event_id,
|
||||||
@@ -2673,6 +2674,7 @@ class AppHandler(SimpleHTTPRequestHandler):
|
|||||||
else None,
|
else None,
|
||||||
participant=data.get("participant"),
|
participant=data.get("participant"),
|
||||||
)
|
)
|
||||||
|
ledger_events.reconcile_bank_events(connection, actor=user)
|
||||||
except period_close.PeriodLockedError as exc:
|
except period_close.PeriodLockedError as exc:
|
||||||
self._send_json(409, {"status": "error", "message": str(exc), "year_month": exc.year_month})
|
self._send_json(409, {"status": "error", "message": str(exc), "year_month": exc.year_month})
|
||||||
return
|
return
|
||||||
@@ -2682,8 +2684,6 @@ class AppHandler(SimpleHTTPRequestHandler):
|
|||||||
except matching.MatchInputError as exc:
|
except matching.MatchInputError as exc:
|
||||||
self._send_json(400, {"status": "error", "message": str(exc)})
|
self._send_json(400, {"status": "error", "message": str(exc)})
|
||||||
return
|
return
|
||||||
try:
|
|
||||||
ledger_events.reconcile_bank_events(connection, actor=user)
|
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
self._send_json(500, {"status": "error", "message": f"同步往来事件失败:{exc}"})
|
self._send_json(500, {"status": "error", "message": f"同步往来事件失败:{exc}"})
|
||||||
return
|
return
|
||||||
@@ -2976,6 +2976,7 @@ class AppHandler(SimpleHTTPRequestHandler):
|
|||||||
reason = str(data.get("reason") or "").strip() or "公司端确认单边流水"
|
reason = str(data.get("reason") or "").strip() or "公司端确认单边流水"
|
||||||
try:
|
try:
|
||||||
period_close.assert_event_writable(connection, event_id)
|
period_close.assert_event_writable(connection, event_id)
|
||||||
|
with transaction(connection):
|
||||||
payload = matching.apply_manual_decision(
|
payload = matching.apply_manual_decision(
|
||||||
connection,
|
connection,
|
||||||
event_id,
|
event_id,
|
||||||
@@ -2989,6 +2990,7 @@ class AppHandler(SimpleHTTPRequestHandler):
|
|||||||
"company_id": counterparty_company_id,
|
"company_id": counterparty_company_id,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
ledger_events.reconcile_bank_events(connection, actor=user)
|
||||||
except period_close.PeriodLockedError as exc:
|
except period_close.PeriodLockedError as exc:
|
||||||
self._send_json(409, {"status": "error", "message": str(exc), "year_month": exc.year_month})
|
self._send_json(409, {"status": "error", "message": str(exc), "year_month": exc.year_month})
|
||||||
return
|
return
|
||||||
@@ -2998,8 +3000,6 @@ class AppHandler(SimpleHTTPRequestHandler):
|
|||||||
except matching.MatchInputError as exc:
|
except matching.MatchInputError as exc:
|
||||||
self._send_json(400, {"status": "error", "message": str(exc)})
|
self._send_json(400, {"status": "error", "message": str(exc)})
|
||||||
return
|
return
|
||||||
try:
|
|
||||||
ledger_events.reconcile_bank_events(connection, actor=user)
|
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
self._send_json(500, {"status": "error", "message": f"同步往来事件失败:{exc}"})
|
self._send_json(500, {"status": "error", "message": f"同步往来事件失败:{exc}"})
|
||||||
return
|
return
|
||||||
@@ -3417,6 +3417,13 @@ class AppHandler(SimpleHTTPRequestHandler):
|
|||||||
period_close.assert_ledger_writable(connection, event_id)
|
period_close.assert_ledger_writable(connection, event_id)
|
||||||
if action in ("adjust", "reverse") and data.get("effective_at"):
|
if action in ("adjust", "reverse") and data.get("effective_at"):
|
||||||
period_close.assert_date_writable(connection, str(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":
|
if action == "reverse":
|
||||||
event_id, _revision_id = ledger_events.create_reversal(
|
event_id, _revision_id = ledger_events.create_reversal(
|
||||||
connection, event_id,
|
connection, event_id,
|
||||||
@@ -3425,7 +3432,7 @@ class AppHandler(SimpleHTTPRequestHandler):
|
|||||||
effective_at=data.get("effective_at") or None,
|
effective_at=data.get("effective_at") or None,
|
||||||
reason=reason, actor=user, idempotency_key=request_key,
|
reason=reason, actor=user, idempotency_key=request_key,
|
||||||
)
|
)
|
||||||
outcome: dict[str, object] = {
|
outcome = {
|
||||||
"action": "reverse", "ledger_event_id": event_id,
|
"action": "reverse", "ledger_event_id": event_id,
|
||||||
}
|
}
|
||||||
elif action == "adjust":
|
elif action == "adjust":
|
||||||
@@ -3450,18 +3457,16 @@ class AppHandler(SimpleHTTPRequestHandler):
|
|||||||
reason=reason, actor=user, idempotency_key=request_key,
|
reason=reason, actor=user, idempotency_key=request_key,
|
||||||
)
|
)
|
||||||
outcome = {"action": "adjust", "ledger_event_id": event_id}
|
outcome = {"action": "adjust", "ledger_event_id": event_id}
|
||||||
elif action == "reopen":
|
else:
|
||||||
event_id, _revision_id = ledger_events.reopen_subject(
|
event_id, _revision_id = ledger_events.reopen_subject(
|
||||||
connection, event_id, reason=reason, actor=user,
|
connection, event_id, reason=reason, actor=user,
|
||||||
idempotency_key=request_key,
|
idempotency_key=request_key,
|
||||||
)
|
)
|
||||||
outcome = {"action": "reopen", "ledger_event_id": event_id}
|
outcome = {"action": "reopen", "ledger_event_id": event_id}
|
||||||
else:
|
auth.audit(
|
||||||
self._send_json(
|
connection, f"ledger_{action}", actor=user,
|
||||||
400,
|
target=f"ledger_event:{event_id}", detail=reason, ip=self._client_ip,
|
||||||
{"status": "error", "message": "action 必须是 reverse、adjust 或 reopen。"},
|
|
||||||
)
|
)
|
||||||
return
|
|
||||||
except period_close.PeriodLockedError as exc:
|
except period_close.PeriodLockedError as exc:
|
||||||
self._send_json(409, {"status": "error", "message": str(exc), "year_month": exc.year_month})
|
self._send_json(409, {"status": "error", "message": str(exc), "year_month": exc.year_month})
|
||||||
return
|
return
|
||||||
@@ -3471,10 +3476,6 @@ class AppHandler(SimpleHTTPRequestHandler):
|
|||||||
except ledger_events.LedgerInputError as exc:
|
except ledger_events.LedgerInputError as exc:
|
||||||
self._send_json(400, {"status": "error", "message": str(exc)})
|
self._send_json(400, {"status": "error", "message": str(exc)})
|
||||||
return
|
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})
|
self._send_json(200, {"status": "ok", **outcome})
|
||||||
finally:
|
finally:
|
||||||
connection.close()
|
connection.close()
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import secrets
|
|||||||
import sqlite3
|
import sqlite3
|
||||||
import string
|
import string
|
||||||
|
|
||||||
from .db import utc_now
|
from .db import transaction, utc_now
|
||||||
|
|
||||||
|
|
||||||
MIN_PASSWORD_LENGTH = 8
|
MIN_PASSWORD_LENGTH = 8
|
||||||
@@ -308,7 +308,7 @@ def audit(
|
|||||||
ip: str | None = None,
|
ip: str | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Append an audit log entry. Never pass passwords in ``detail``."""
|
"""Append an audit log entry. Never pass passwords in ``detail``."""
|
||||||
with connection:
|
with transaction(connection):
|
||||||
connection.execute(
|
connection.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO audit_log (
|
INSERT INTO audit_log (
|
||||||
|
|||||||
@@ -7,8 +7,8 @@ from decimal import Decimal, InvalidOperation
|
|||||||
import json
|
import json
|
||||||
import sqlite3
|
import sqlite3
|
||||||
|
|
||||||
from .db import utc_now
|
from .db import transaction, utc_now
|
||||||
from . import master_data, matching
|
from . import auth, master_data, matching
|
||||||
|
|
||||||
|
|
||||||
SETTING_START_DATE = "calculation_start_date"
|
SETTING_START_DATE = "calculation_start_date"
|
||||||
@@ -81,7 +81,7 @@ def set_calculation_start_date(
|
|||||||
raise LockedError("已有结账月份,起算日已锁定。")
|
raise LockedError("已有结账月份,起算日已锁定。")
|
||||||
before = get_calculation_start_date(connection)
|
before = get_calculation_start_date(connection)
|
||||||
now = utc_now()
|
now = utc_now()
|
||||||
with connection:
|
with transaction(connection):
|
||||||
connection.execute(
|
connection.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO system_settings (key, value, updated_at, updated_by)
|
INSERT INTO system_settings (key, value, updated_at, updated_by)
|
||||||
@@ -185,7 +185,7 @@ def create_opening_balance(
|
|||||||
raise ConflictError("该对公司已有确认期初,请使用修订。")
|
raise ConflictError("该对公司已有确认期初,请使用修订。")
|
||||||
revision = _next_revision(connection, low_id, high_id)
|
revision = _next_revision(connection, low_id, high_id)
|
||||||
now = utc_now()
|
now = utc_now()
|
||||||
with connection:
|
with transaction(connection):
|
||||||
cursor = connection.execute(
|
cursor = connection.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO opening_balance_revisions (
|
INSERT INTO opening_balance_revisions (
|
||||||
@@ -235,7 +235,7 @@ def confirm_opening_balance(
|
|||||||
reason = str(reason or "").strip()
|
reason = str(reason or "").strip()
|
||||||
if len(reason) < 2:
|
if len(reason) < 2:
|
||||||
raise ValueError("确认期初必须填写原因。")
|
raise ValueError("确认期初必须填写原因。")
|
||||||
with connection:
|
with transaction(connection):
|
||||||
connection.execute(
|
connection.execute(
|
||||||
"""
|
"""
|
||||||
UPDATE opening_balance_revisions SET status = 'confirmed', reason = ?
|
UPDATE opening_balance_revisions SET status = 'confirmed', reason = ?
|
||||||
@@ -278,7 +278,7 @@ def revise_opening_balance(
|
|||||||
high_id = int(row["company_id_high"])
|
high_id = int(row["company_id_high"])
|
||||||
revision = _next_revision(connection, low_id, high_id)
|
revision = _next_revision(connection, low_id, high_id)
|
||||||
now = utc_now()
|
now = utc_now()
|
||||||
with connection:
|
with transaction(connection):
|
||||||
connection.execute(
|
connection.execute(
|
||||||
"UPDATE opening_balance_revisions SET status = 'superseded' WHERE id = ?",
|
"UPDATE opening_balance_revisions SET status = 'superseded' WHERE id = ?",
|
||||||
(revision_id,),
|
(revision_id,),
|
||||||
@@ -333,7 +333,7 @@ def void_opening_balance(
|
|||||||
reason = str(reason or "").strip()
|
reason = str(reason or "").strip()
|
||||||
if len(reason) < 2:
|
if len(reason) < 2:
|
||||||
raise ValueError("作废期初必须填写原因。")
|
raise ValueError("作废期初必须填写原因。")
|
||||||
with connection:
|
with transaction(connection):
|
||||||
connection.execute(
|
connection.execute(
|
||||||
"UPDATE opening_balance_revisions SET status = 'void', reason = ? WHERE id = ?",
|
"UPDATE opening_balance_revisions SET status = 'void', reason = ? WHERE id = ?",
|
||||||
(reason, revision_id),
|
(reason, revision_id),
|
||||||
@@ -551,7 +551,7 @@ def recalculate_coverage_gaps(connection: sqlite3.Connection) -> int:
|
|||||||
"SELECT * FROM bank_accounts WHERE status = 'active'"
|
"SELECT * FROM bank_accounts WHERE status = 'active'"
|
||||||
).fetchall()
|
).fetchall()
|
||||||
rebuilt = 0
|
rebuilt = 0
|
||||||
with connection:
|
with transaction(connection):
|
||||||
for account in accounts:
|
for account in accounts:
|
||||||
connection.execute(
|
connection.execute(
|
||||||
"""
|
"""
|
||||||
@@ -668,7 +668,7 @@ def submit_no_business_attestation(
|
|||||||
if account["company_id"] != company_id:
|
if account["company_id"] != company_id:
|
||||||
raise ValueError("只能为本公司账户提交说明。")
|
raise ValueError("只能为本公司账户提交说明。")
|
||||||
now = utc_now()
|
now = utc_now()
|
||||||
with connection:
|
with transaction(connection):
|
||||||
cursor = connection.execute(
|
cursor = connection.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO no_business_attestations (
|
INSERT INTO no_business_attestations (
|
||||||
@@ -688,6 +688,13 @@ def submit_no_business_attestation(
|
|||||||
),
|
),
|
||||||
)
|
)
|
||||||
attestation_id = int(cursor.lastrowid)
|
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)
|
return attestation_payload(connection, attestation_id)
|
||||||
|
|
||||||
|
|
||||||
@@ -712,7 +719,7 @@ def review_no_business_attestation(
|
|||||||
raise ValueError("审核必须填写理由。")
|
raise ValueError("审核必须填写理由。")
|
||||||
status = "approved" if decision == "approve" else "rejected"
|
status = "approved" if decision == "approve" else "rejected"
|
||||||
now = utc_now()
|
now = utc_now()
|
||||||
with connection:
|
with transaction(connection):
|
||||||
connection.execute(
|
connection.execute(
|
||||||
"""
|
"""
|
||||||
UPDATE no_business_attestations
|
UPDATE no_business_attestations
|
||||||
@@ -748,6 +755,13 @@ def review_no_business_attestation(
|
|||||||
""",
|
""",
|
||||||
(row["bank_account_id"], row["gap_end"], row["gap_start"]),
|
(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)
|
return attestation_payload(connection, attestation_id)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -10,10 +10,12 @@ version order; each records itself in ``schema_migrations`` so re-running
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
|
from contextlib import contextmanager
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import sqlite3
|
import sqlite3
|
||||||
|
from typing import Iterator
|
||||||
|
|
||||||
|
|
||||||
DEFAULT_DB_PATH = Path("data/app.db")
|
DEFAULT_DB_PATH = Path("data/app.db")
|
||||||
@@ -23,6 +25,31 @@ def utc_now() -> str:
|
|||||||
return datetime.now(timezone.utc).isoformat()
|
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)
|
@dataclass(frozen=True)
|
||||||
class Migration:
|
class Migration:
|
||||||
version: int
|
version: int
|
||||||
|
|||||||
@@ -650,13 +650,6 @@ def review_sheets(
|
|||||||
actor=actor,
|
actor=actor,
|
||||||
)
|
)
|
||||||
ledger_events.reconcile_bank_events(connection, actor=actor)
|
ledger_events.reconcile_bank_events(connection, actor=actor)
|
||||||
if began:
|
|
||||||
connection.commit()
|
|
||||||
except Exception:
|
|
||||||
if began:
|
|
||||||
connection.rollback()
|
|
||||||
raise
|
|
||||||
|
|
||||||
if updated:
|
if updated:
|
||||||
auth.audit(
|
auth.audit(
|
||||||
connection,
|
connection,
|
||||||
@@ -665,6 +658,13 @@ def review_sheets(
|
|||||||
target=f"batch:{batch_id}",
|
target=f"batch:{batch_id}",
|
||||||
detail=f"sheets:{','.join(updated)}" + (f";reason:{reason}" if reason else ""),
|
detail=f"sheets:{','.join(updated)}" + (f";reason:{reason}" if reason else ""),
|
||||||
)
|
)
|
||||||
|
if began:
|
||||||
|
connection.commit()
|
||||||
|
except Exception:
|
||||||
|
if began:
|
||||||
|
connection.rollback()
|
||||||
|
raise
|
||||||
|
|
||||||
payload: dict[str, object] = {"updated": updated, "already": already}
|
payload: dict[str, object] = {"updated": updated, "already": already}
|
||||||
if matching_result is not None:
|
if matching_result is not None:
|
||||||
payload["matching"] = matching_result
|
payload["matching"] = matching_result
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ from decimal import Decimal, InvalidOperation
|
|||||||
import json
|
import json
|
||||||
import sqlite3
|
import sqlite3
|
||||||
|
|
||||||
from .db import utc_now
|
from .db import transaction, utc_now
|
||||||
from .subjects import MIRROR, SUBJECTS, mirror_subject
|
from .subjects import MIRROR, SUBJECTS, mirror_subject
|
||||||
|
|
||||||
|
|
||||||
@@ -428,6 +428,16 @@ def reopen_subject(
|
|||||||
raise LedgerInputError(
|
raise LedgerInputError(
|
||||||
"该事件没有银行来源,无法重新进入科目审核;请改用调整或冲销。"
|
"该事件没有银行来源,无法重新进入科目审核;请改用调整或冲销。"
|
||||||
)
|
)
|
||||||
|
ev = connection.execute(
|
||||||
|
"SELECT * FROM eligible_intercompany_events WHERE event_id = ?",
|
||||||
|
(bank_claim["bank_event_id"],),
|
||||||
|
).fetchone()
|
||||||
|
if ev is None:
|
||||||
|
raise LedgerInputError("银行事件已不再纳入往来,无法重新入账。")
|
||||||
|
# One nestable transaction: reversal, replacement event, source re-claim
|
||||||
|
# and suggestions commit together. create_event used to commit on its own,
|
||||||
|
# leaving the bank-source UPDATE uncommitted for connection.close().
|
||||||
|
with transaction(connection):
|
||||||
if not _has_reversal(connection, ledger_event_id):
|
if not _has_reversal(connection, ledger_event_id):
|
||||||
create_reversal(
|
create_reversal(
|
||||||
connection, ledger_event_id,
|
connection, ledger_event_id,
|
||||||
@@ -438,12 +448,6 @@ def reopen_subject(
|
|||||||
idempotency_key=(idempotency_key + ":rev" if idempotency_key else None),
|
idempotency_key=(idempotency_key + ":rev" if idempotency_key else None),
|
||||||
rule_version=current["rule_version"],
|
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(
|
event_id, revision_id = _create_bank_event(
|
||||||
connection, ev, actor, reason="科目复核后重新入账,待确认科目",
|
connection, ev, actor, reason="科目复核后重新入账,待确认科目",
|
||||||
replacing_claim=bank_claim,
|
replacing_claim=bank_claim,
|
||||||
@@ -553,6 +557,7 @@ def _create_bank_event(
|
|||||||
reason: str,
|
reason: str,
|
||||||
replacing_claim: sqlite3.Row | None = None,
|
replacing_claim: sqlite3.Row | None = None,
|
||||||
) -> tuple[int, int]:
|
) -> tuple[int, int]:
|
||||||
|
with transaction(connection):
|
||||||
event_id, revision_id = create_event(
|
event_id, revision_id = create_event(
|
||||||
connection,
|
connection,
|
||||||
state="pending_subject",
|
state="pending_subject",
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import json
|
|||||||
import re
|
import re
|
||||||
import sqlite3
|
import sqlite3
|
||||||
|
|
||||||
from .db import utc_now
|
from .db import transaction, utc_now
|
||||||
|
|
||||||
|
|
||||||
ACCOUNT_TYPES = ("基本户", "一般户", "专用户")
|
ACCOUNT_TYPES = ("基本户", "一般户", "专用户")
|
||||||
@@ -143,7 +143,7 @@ def create_company(
|
|||||||
raise ValueError("公司名称不能为空。")
|
raise ValueError("公司名称不能为空。")
|
||||||
now = utc_now()
|
now = utc_now()
|
||||||
try:
|
try:
|
||||||
with connection:
|
with transaction(connection):
|
||||||
cursor = connection.execute(
|
cursor = connection.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO companies (
|
INSERT INTO companies (
|
||||||
@@ -153,16 +153,15 @@ def create_company(
|
|||||||
(name, (credit_code or "").strip() or None,
|
(name, (credit_code or "").strip() or None,
|
||||||
(cashier_name or "").strip() or None, now, now),
|
(cashier_name or "").strip() or None, now, now),
|
||||||
)
|
)
|
||||||
except sqlite3.IntegrityError as exc:
|
|
||||||
raise ConflictError("公司名称已存在。") from exc
|
|
||||||
company_id = int(cursor.lastrowid)
|
company_id = int(cursor.lastrowid)
|
||||||
with connection:
|
|
||||||
record_change(
|
record_change(
|
||||||
connection, "company", company_id, "create",
|
connection, "company", company_id, "create",
|
||||||
None, {"name": name, "credit_code": credit_code or None,
|
None, {"name": name, "credit_code": credit_code or None,
|
||||||
"cashier_name": cashier_name or None, "status": "active"},
|
"cashier_name": cashier_name or None, "status": "active"},
|
||||||
None, actor,
|
None, actor,
|
||||||
)
|
)
|
||||||
|
except sqlite3.IntegrityError as exc:
|
||||||
|
raise ConflictError("公司名称已存在。") from exc
|
||||||
return company_id
|
return company_id
|
||||||
|
|
||||||
|
|
||||||
@@ -210,7 +209,7 @@ def submit_bank_account(
|
|||||||
|
|
||||||
if existing is None:
|
if existing is None:
|
||||||
try:
|
try:
|
||||||
with connection:
|
with transaction(connection):
|
||||||
cursor = connection.execute(
|
cursor = connection.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO bank_accounts (
|
INSERT INTO bank_accounts (
|
||||||
@@ -222,11 +221,7 @@ def submit_bank_account(
|
|||||||
(company_id, number, holder, bank, kind,
|
(company_id, number, holder, bank, kind,
|
||||||
requested_from, actor["id"] if actor else None, now, now),
|
requested_from, actor["id"] if actor else None, now, now),
|
||||||
)
|
)
|
||||||
except sqlite3.IntegrityError as exc:
|
|
||||||
# Lost a concurrent-insert race on the UNIQUE constraint.
|
|
||||||
raise ConflictError("该银行账号已登记,请等待现有申请处理。") from exc
|
|
||||||
account_id = int(cursor.lastrowid)
|
account_id = int(cursor.lastrowid)
|
||||||
with connection:
|
|
||||||
record_change(
|
record_change(
|
||||||
connection, "bank_account", account_id, "submit", None,
|
connection, "bank_account", account_id, "submit", None,
|
||||||
{"company_id": company_id, "account_number": number,
|
{"company_id": company_id, "account_number": number,
|
||||||
@@ -234,11 +229,14 @@ def submit_bank_account(
|
|||||||
"effective_from": requested_from},
|
"effective_from": requested_from},
|
||||||
None, actor,
|
None, actor,
|
||||||
)
|
)
|
||||||
|
except sqlite3.IntegrityError as exc:
|
||||||
|
# Lost a concurrent-insert race on the UNIQUE constraint.
|
||||||
|
raise ConflictError("该银行账号已登记,请等待现有申请处理。") from exc
|
||||||
return get_account(connection, account_id)
|
return get_account(connection, account_id)
|
||||||
|
|
||||||
if existing["status"] == "returned" and existing["company_id"] == company_id:
|
if existing["status"] == "returned" and existing["company_id"] == company_id:
|
||||||
before = _snapshot(existing)
|
before = _snapshot(existing)
|
||||||
with connection:
|
with transaction(connection):
|
||||||
connection.execute(
|
connection.execute(
|
||||||
"""
|
"""
|
||||||
UPDATE bank_accounts
|
UPDATE bank_accounts
|
||||||
@@ -287,7 +285,7 @@ def review_bank_account(
|
|||||||
if account["status"] != "pending":
|
if account["status"] != "pending":
|
||||||
raise ConflictError("只有待复核的账户可以审核通过。")
|
raise ConflictError("只有待复核的账户可以审核通过。")
|
||||||
start = validate_date(effective_from, "启用日期") or account["effective_from"] or today
|
start = validate_date(effective_from, "启用日期") or account["effective_from"] or today
|
||||||
with connection:
|
with transaction(connection):
|
||||||
connection.execute(
|
connection.execute(
|
||||||
"""
|
"""
|
||||||
UPDATE bank_accounts
|
UPDATE bank_accounts
|
||||||
@@ -306,7 +304,7 @@ def review_bank_account(
|
|||||||
raise ConflictError("只有待复核的账户可以退回。")
|
raise ConflictError("只有待复核的账户可以退回。")
|
||||||
if reason is None:
|
if reason is None:
|
||||||
raise ValueError("退回必须填写原因。")
|
raise ValueError("退回必须填写原因。")
|
||||||
with connection:
|
with transaction(connection):
|
||||||
connection.execute(
|
connection.execute(
|
||||||
"""
|
"""
|
||||||
UPDATE bank_accounts
|
UPDATE bank_accounts
|
||||||
@@ -326,7 +324,7 @@ def review_bank_account(
|
|||||||
if reason is None:
|
if reason is None:
|
||||||
raise ValueError("停用必须填写原因。")
|
raise ValueError("停用必须填写原因。")
|
||||||
end = validate_date(effective_to, "停用日期") or today
|
end = validate_date(effective_to, "停用日期") or today
|
||||||
with connection:
|
with transaction(connection):
|
||||||
connection.execute(
|
connection.execute(
|
||||||
"""
|
"""
|
||||||
UPDATE bank_accounts
|
UPDATE bank_accounts
|
||||||
@@ -448,7 +446,7 @@ def add_alias(
|
|||||||
if start and end and end < start:
|
if start and end and end < start:
|
||||||
raise ValueError("别名失效日期不能早于生效日期。")
|
raise ValueError("别名失效日期不能早于生效日期。")
|
||||||
try:
|
try:
|
||||||
with connection:
|
with transaction(connection):
|
||||||
cursor = connection.execute(
|
cursor = connection.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO account_aliases (
|
INSERT INTO account_aliases (
|
||||||
@@ -459,10 +457,7 @@ def add_alias(
|
|||||||
(account_id, alias_kind, value, rank, start, end,
|
(account_id, alias_kind, value, rank, start, end,
|
||||||
actor["id"] if actor else None, utc_now()),
|
actor["id"] if actor else None, utc_now()),
|
||||||
)
|
)
|
||||||
except sqlite3.IntegrityError as exc:
|
|
||||||
raise ConflictError("该账户下相同别名已存在。") from exc
|
|
||||||
alias_id = int(cursor.lastrowid)
|
alias_id = int(cursor.lastrowid)
|
||||||
with connection:
|
|
||||||
record_change(
|
record_change(
|
||||||
connection, "account_alias", alias_id, "create", None,
|
connection, "account_alias", alias_id, "create", None,
|
||||||
{"bank_account_id": account_id, "alias_kind": alias_kind,
|
{"bank_account_id": account_id, "alias_kind": alias_kind,
|
||||||
@@ -470,6 +465,8 @@ def add_alias(
|
|||||||
"effective_from": start, "effective_to": end},
|
"effective_from": start, "effective_to": end},
|
||||||
None, actor,
|
None, actor,
|
||||||
)
|
)
|
||||||
|
except sqlite3.IntegrityError as exc:
|
||||||
|
raise ConflictError("该账户下相同别名已存在。") from exc
|
||||||
return alias_id
|
return alias_id
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ import re
|
|||||||
import sqlite3
|
import sqlite3
|
||||||
|
|
||||||
from .auth import audit
|
from .auth import audit
|
||||||
from .db import utc_now
|
from .db import transaction, utc_now
|
||||||
from .master_data import (
|
from .master_data import (
|
||||||
is_identifiable,
|
is_identifiable,
|
||||||
normalize_account_number,
|
normalize_account_number,
|
||||||
@@ -1457,6 +1457,8 @@ def rebuild_current_projection(connection: sqlite3.Connection) -> int:
|
|||||||
no current pointer and no claims. Returns the number of current decisions
|
no current pointer and no claims. Returns the number of current decisions
|
||||||
rebuilt. Intended as a recovery/consistency entry point.
|
rebuilt. Intended as a recovery/consistency entry point.
|
||||||
"""
|
"""
|
||||||
|
rebuilt = 0
|
||||||
|
with transaction(connection):
|
||||||
connection.execute("DELETE FROM transfer_observation_claims")
|
connection.execute("DELETE FROM transfer_observation_claims")
|
||||||
connection.execute("DELETE FROM current_transfer_decisions")
|
connection.execute("DELETE FROM current_transfer_decisions")
|
||||||
events = connection.execute(
|
events = connection.execute(
|
||||||
@@ -1467,9 +1469,8 @@ def rebuild_current_projection(connection: sqlite3.Connection) -> int:
|
|||||||
ORDER BY d2.revision DESC LIMIT 1) AS latest_id
|
ORDER BY d2.revision DESC LIMIT 1) AS latest_id
|
||||||
FROM canonical_transfer_events e
|
FROM canonical_transfer_events e
|
||||||
WHERE e.lifecycle = 'active'
|
WHERE e.lifecycle = 'active'
|
||||||
"""
|
""",
|
||||||
).fetchall()
|
).fetchall()
|
||||||
rebuilt = 0
|
|
||||||
for event in events:
|
for event in events:
|
||||||
if event["latest_id"] is None:
|
if event["latest_id"] is None:
|
||||||
continue
|
continue
|
||||||
@@ -1486,7 +1487,6 @@ def rebuild_current_projection(connection: sqlite3.Connection) -> int:
|
|||||||
""",
|
""",
|
||||||
(event["latest_id"],),
|
(event["latest_id"],),
|
||||||
).fetchall()
|
).fetchall()
|
||||||
with connection:
|
|
||||||
connection.execute(
|
connection.execute(
|
||||||
"""
|
"""
|
||||||
INSERT OR REPLACE INTO current_transfer_decisions (event_id, decision_id)
|
INSERT OR REPLACE INTO current_transfer_decisions (event_id, decision_id)
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import json
|
|||||||
import re
|
import re
|
||||||
import sqlite3
|
import sqlite3
|
||||||
|
|
||||||
from .db import utc_now
|
from .db import transaction, utc_now
|
||||||
from . import calculation, dashboard, settings as settings_mod
|
from . import calculation, dashboard, settings as settings_mod
|
||||||
|
|
||||||
|
|
||||||
@@ -237,10 +237,9 @@ def record_late_arrivals(
|
|||||||
return 0
|
return 0
|
||||||
now = utc_now()
|
now = utc_now()
|
||||||
inserted = 0
|
inserted = 0
|
||||||
# One transaction so the rows and their audit trail commit or roll back
|
# Nestable transaction: rows and their audit trail commit or roll back
|
||||||
# together; without it the caller's connection.close() silently rolled
|
# together. ``with connection:`` would commit an outer caller early.
|
||||||
# the late-arrival records back while the API still reported them.
|
with transaction(connection):
|
||||||
with connection:
|
|
||||||
for row_id, year_month in items:
|
for row_id, year_month in items:
|
||||||
existing = connection.execute(
|
existing = connection.execute(
|
||||||
"SELECT id FROM period_late_arrivals WHERE source_row_id = ?",
|
"SELECT id FROM period_late_arrivals WHERE source_row_id = ?",
|
||||||
@@ -530,7 +529,7 @@ def ensure_pending_tasks(
|
|||||||
first = earliest_month(connection) or last
|
first = earliest_month(connection) or last
|
||||||
created: list[str] = []
|
created: list[str] = []
|
||||||
month = first
|
month = first
|
||||||
with connection:
|
with transaction(connection):
|
||||||
while month <= last:
|
while month <= last:
|
||||||
existing = _current_run(connection, month)
|
existing = _current_run(connection, month)
|
||||||
if existing is None:
|
if existing is None:
|
||||||
@@ -598,7 +597,7 @@ def execute_close(
|
|||||||
snapshot = build_snapshot(connection, year_month)
|
snapshot = build_snapshot(connection, year_month)
|
||||||
digest = _hash_payload(snapshot)
|
digest = _hash_payload(snapshot)
|
||||||
now = utc_now()
|
now = utc_now()
|
||||||
with connection:
|
with transaction(connection):
|
||||||
if current is not None and current["status"] == "pending":
|
if current is not None and current["status"] == "pending":
|
||||||
version = int(current["version"])
|
version = int(current["version"])
|
||||||
report_no = _report_no(year_month, version)
|
report_no = _report_no(year_month, version)
|
||||||
@@ -665,7 +664,7 @@ def mark_close_failed(
|
|||||||
reason = str(reason or "").strip() or "结账失败"
|
reason = str(reason or "").strip() or "结账失败"
|
||||||
current = _current_run(connection, year_month)
|
current = _current_run(connection, year_month)
|
||||||
now = utc_now()
|
now = utc_now()
|
||||||
with connection:
|
with transaction(connection):
|
||||||
if current is None:
|
if current is None:
|
||||||
version = 1
|
version = 1
|
||||||
connection.execute(
|
connection.execute(
|
||||||
@@ -727,7 +726,7 @@ def request_reopen(
|
|||||||
if pending is not None:
|
if pending is not None:
|
||||||
raise PeriodConflictError("该账期已有待审批的重开申请。")
|
raise PeriodConflictError("该账期已有待审批的重开申请。")
|
||||||
now = utc_now()
|
now = utc_now()
|
||||||
with connection:
|
with transaction(connection):
|
||||||
cursor = connection.execute(
|
cursor = connection.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO period_reopen_requests (
|
INSERT INTO period_reopen_requests (
|
||||||
@@ -786,7 +785,7 @@ def decide_reopen(
|
|||||||
close_run = connection.execute(
|
close_run = connection.execute(
|
||||||
"SELECT * FROM period_close_runs WHERE id = ?", (row["period_close_id"],)
|
"SELECT * FROM period_close_runs WHERE id = ?", (row["period_close_id"],)
|
||||||
).fetchone()
|
).fetchone()
|
||||||
with connection:
|
with transaction(connection):
|
||||||
if approve:
|
if approve:
|
||||||
window_end = (
|
window_end = (
|
||||||
datetime.now(timezone.utc) + timedelta(days=int(row["window_days"]))
|
datetime.now(timezone.utc) + timedelta(days=int(row["window_days"]))
|
||||||
@@ -873,7 +872,7 @@ def expire_reopen_windows(
|
|||||||
for row in rows:
|
for row in rows:
|
||||||
year_month = row["year_month"]
|
year_month = row["year_month"]
|
||||||
now = utc_now()
|
now = utc_now()
|
||||||
with connection:
|
with transaction(connection):
|
||||||
connection.execute(
|
connection.execute(
|
||||||
"""
|
"""
|
||||||
UPDATE period_close_runs
|
UPDATE period_close_runs
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import sqlite3
|
import sqlite3
|
||||||
|
|
||||||
from .db import utc_now
|
from .db import transaction, utc_now
|
||||||
from .master_data import (
|
from .master_data import (
|
||||||
ConflictError,
|
ConflictError,
|
||||||
mask_account_number,
|
mask_account_number,
|
||||||
@@ -67,7 +67,7 @@ def submit_mapping(
|
|||||||
).fetchone()
|
).fetchone()
|
||||||
if existing is None:
|
if existing is None:
|
||||||
try:
|
try:
|
||||||
with connection:
|
with transaction(connection):
|
||||||
cursor = connection.execute(
|
cursor = connection.execute(
|
||||||
"""
|
"""
|
||||||
INSERT INTO personal_transit_mappings (
|
INSERT INTO personal_transit_mappings (
|
||||||
@@ -81,10 +81,7 @@ def submit_mapping(
|
|||||||
start, actor["id"] if actor else None, now, now,
|
start, actor["id"] if actor else None, now, now,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
except sqlite3.IntegrityError as exc:
|
|
||||||
raise ConflictError("该个人过账账号已登记,请等待现有申请处理。") from exc
|
|
||||||
mapping_id = int(cursor.lastrowid)
|
mapping_id = int(cursor.lastrowid)
|
||||||
with connection:
|
|
||||||
record_change(
|
record_change(
|
||||||
connection, "personal_transit_mapping", mapping_id, "submit", None,
|
connection, "personal_transit_mapping", mapping_id, "submit", None,
|
||||||
{"account_number": number, "account_name": holder,
|
{"account_number": number, "account_name": holder,
|
||||||
@@ -93,10 +90,12 @@ def submit_mapping(
|
|||||||
"effective_from": start},
|
"effective_from": start},
|
||||||
None, actor,
|
None, actor,
|
||||||
)
|
)
|
||||||
|
except sqlite3.IntegrityError as exc:
|
||||||
|
raise ConflictError("该个人过账账号已登记,请等待现有申请处理。") from exc
|
||||||
return get_mapping(connection, mapping_id)
|
return get_mapping(connection, mapping_id)
|
||||||
|
|
||||||
if existing["status"] == "returned":
|
if existing["status"] == "returned":
|
||||||
with connection:
|
with transaction(connection):
|
||||||
connection.execute(
|
connection.execute(
|
||||||
"""
|
"""
|
||||||
UPDATE personal_transit_mappings
|
UPDATE personal_transit_mappings
|
||||||
@@ -143,7 +142,7 @@ def review_mapping(
|
|||||||
if mapping["status"] != "pending":
|
if mapping["status"] != "pending":
|
||||||
raise ConflictError("只有待复核的映射可以审核通过。")
|
raise ConflictError("只有待复核的映射可以审核通过。")
|
||||||
start = validate_date(effective_from, "生效日期") or mapping["effective_from"] or today
|
start = validate_date(effective_from, "生效日期") or mapping["effective_from"] or today
|
||||||
with connection:
|
with transaction(connection):
|
||||||
connection.execute(
|
connection.execute(
|
||||||
"""
|
"""
|
||||||
UPDATE personal_transit_mappings
|
UPDATE personal_transit_mappings
|
||||||
@@ -162,7 +161,7 @@ def review_mapping(
|
|||||||
raise ConflictError("只有待复核的映射可以退回。")
|
raise ConflictError("只有待复核的映射可以退回。")
|
||||||
if reason is None:
|
if reason is None:
|
||||||
raise ValueError("退回必须填写原因。")
|
raise ValueError("退回必须填写原因。")
|
||||||
with connection:
|
with transaction(connection):
|
||||||
connection.execute(
|
connection.execute(
|
||||||
"""
|
"""
|
||||||
UPDATE personal_transit_mappings
|
UPDATE personal_transit_mappings
|
||||||
@@ -182,7 +181,7 @@ def review_mapping(
|
|||||||
if reason is None:
|
if reason is None:
|
||||||
raise ValueError("停用必须填写原因。")
|
raise ValueError("停用必须填写原因。")
|
||||||
end = validate_date(effective_to, "停用日期") or today
|
end = validate_date(effective_to, "停用日期") or today
|
||||||
with connection:
|
with transaction(connection):
|
||||||
connection.execute(
|
connection.execute(
|
||||||
"""
|
"""
|
||||||
UPDATE personal_transit_mappings
|
UPDATE personal_transit_mappings
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import re
|
|||||||
import sqlite3
|
import sqlite3
|
||||||
from datetime import datetime
|
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.
|
# Defaults are applied when a key is absent; the value type is always string.
|
||||||
@@ -93,7 +93,7 @@ def update_settings(
|
|||||||
if not cleaned:
|
if not cleaned:
|
||||||
raise ValueError("没有需要保存的设置项。")
|
raise ValueError("没有需要保存的设置项。")
|
||||||
current = get_settings(connection)
|
current = get_settings(connection)
|
||||||
with connection:
|
with transaction(connection):
|
||||||
for key, new_value in cleaned.items():
|
for key, new_value in cleaned.items():
|
||||||
old_value = current.get(key)
|
old_value = current.get(key)
|
||||||
if old_value == new_value:
|
if old_value == new_value:
|
||||||
|
|||||||
@@ -349,6 +349,66 @@ class CoverageGapTests(CalculationBase):
|
|||||||
).fetchone()
|
).fetchone()
|
||||||
self.assertEqual("closed_attested", closed["status"])
|
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):
|
class BalanceBasisTests(CalculationBase):
|
||||||
def setUp(self) -> None:
|
def setUp(self) -> None:
|
||||||
|
|||||||
@@ -257,6 +257,56 @@ class ProjectionTests(LedgerBase):
|
|||||||
self.assertEqual("confirmed", revision["state"])
|
self.assertEqual("confirmed", revision["state"])
|
||||||
self.assertEqual("receivable", revision["subject_code"])
|
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):
|
class SubjectSuggestionTests(LedgerBase):
|
||||||
def test_mirror_mapping_is_symmetric(self) -> None:
|
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):
|
class MasterDataApiTests(unittest.TestCase):
|
||||||
"""Live-server workflow tests for account registration and review."""
|
"""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(before), sorted(after))
|
||||||
self.assertEqual(sorted(claims_before), sorted(claims_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):
|
class ConcurrentReconcileTests(MatchingBase):
|
||||||
def test_concurrent_reconcile_creates_one_event(self) -> None:
|
def test_concurrent_reconcile_creates_one_event(self) -> None:
|
||||||
|
|||||||
@@ -189,6 +189,42 @@ class PeriodCloseTests(LedgerBase):
|
|||||||
self.assertEqual(1, versions[0]["version"])
|
self.assertEqual(1, versions[0]["version"])
|
||||||
self.assertEqual(2, versions[-1]["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:
|
def test_wal_on_file_database(self) -> None:
|
||||||
mode = self.connection.execute("PRAGMA journal_mode").fetchone()[0]
|
mode = self.connection.execute("PRAGMA journal_mode").fetchone()[0]
|
||||||
self.assertEqual("wal", str(mode).lower())
|
self.assertEqual("wal", str(mode).lower())
|
||||||
|
|||||||
Reference in New Issue
Block a user