unis-oa/backend/scripts/check_quota_import.py

278 lines
15 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python3
"""守额度台账的批量导入(``service/quota.import_totals``):一次贴一批维度+总额,逐条结论必须说得住。
额度这一本账以前只有一格一格「导入总额」,年初预算几十上百笔就得点几十上百次,
所以补了表格导入。这一层最容易坏的三件事都不在"能不能写进去"上,而在**结论对不对**:
1. **维度就是这笔额度的身份证**。少填一个维度键、多填一个定义外的键,都会落成一笔
对不上账的新额度,而且界面上一眼看去毫无疑样——必须当场挡下来说是哪一列。
2. **重复导入不是多一笔**。同一组维度再导一次是把总额改成这个数(``overwrite``,
这本账一直的说法),``skip`` 才是"只补没有的";什么都没变的那行算跳过,
既不报成"改了它",也不为空跑记一条流水——流水是财务查账唯一能看的东西。
3. **总额往下改不等于改成功**。已经占用出去的钱不会跟着缩,可用额度会翻负;
导入要留下这一笔的痕迹(KIND_ISSUE 的负数流水),别让它像被谁偷偷抹了。
顺带钉住这几条容易漂的口径:归属人认账号/姓名/用户主键,重名不替人挑、查无此人说一句;
本批内重复维度只留第一条并指出跟第几行重复;总额是"1,234.00 元 / ¥1234 / (500)"这种写法
也认,但读不懂绝不当成 0;超长是挡下来说原因而不是截一半;行号认前端带来的那一格;
导入不是全量,没出现的额度行原样留着。
库里跑真行再自己删干净,只碰自己那个定义。跑在 backend 目录下::
PYTHONPATH=. python3 scripts/check_quota_import.py
"""
from __future__ import annotations
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
from sqlalchemy import select # noqa: E402
from app import models # noqa: E402
from app.db import SessionLocal # noqa: E402
from app.envelope import ApiError # noqa: E402
from app.service import quota # noqa: E402
FAILS: list[str] = []
PASSED = 0
CODE = "zz-check-quota-import"
DIM_LABEL = "预算科目"
YEAR_LABEL = "年度"
NICK = "导入体检重名师"
def check(label: str, ok: bool, detail: str = "") -> bool:
global PASSED
if ok:
PASSED += 1
print(f" \033[32m✓\033[0m {label}")
else:
FAILS.append(label)
print(f" \033[31m✗\033[0m {label}{(' << ' + detail) if detail else ''}")
return ok
def purge(db) -> None:
"""把这本体检台账的流水、额度行与定义都删干净(上一次跑挂了留下的也算)。"""
rows = db.execute(select(models.Quota).where(models.Quota.quota_def == CODE)).scalars().all()
ids = [row.id for row in rows]
if ids:
for entry in db.execute(
select(models.QuotaLedger).where(models.QuotaLedger.quota.in_(ids))
).scalars().all():
db.delete(entry)
for entry in db.execute(
select(models.QuotaLedger).where(models.QuotaLedger.quota_def == CODE)
).scalars().all():
db.delete(entry)
for row in rows:
db.delete(row)
def_row = db.execute(
select(models.QuotaDef).where(models.QuotaDef.code == CODE)
).scalar_one_or_none()
if def_row is not None:
db.delete(def_row)
for user in db.execute(
select(models.User).where(models.User.account.in_(("zz-import-a", "zz-import-b")))
).scalars().all():
db.delete(user)
db.commit()
def row_of(db, **dims) -> models.Quota:
digest = quota.dims_hash(dims)
return db.execute(
select(models.Quota).where(models.Quota.quota_def == CODE, models.Quota.dim_hash == digest)
).scalar_one()
def rows(db) -> list[models.Quota]:
return list(db.execute(
select(models.Quota).where(models.Quota.quota_def == CODE)
).scalars().all())
def ledger_of(db, **dims) -> list[models.QuotaLedger]:
return list(db.execute(
select(models.QuotaLedger).where(models.QuotaLedger.quota == row_of(db, **dims).id)
).scalars().all())
def dims(a: str, year: str = "2026") -> dict:
return {DIM_LABEL: a, YEAR_LABEL: year}
def main() -> int:
db = SessionLocal()
try:
purge(db)
db.add(models.QuotaDef(
code=CODE, name="导入体检", enabled=True, source=models.QuotaDef.SOURCE_EXTERNAL,
dims=[DIM_LABEL, YEAR_LABEL], scope="global", basis="local_all", over="hard",
))
# 两个同名的人:归属人只写姓名时不该替人挑一个
for account in ("zz-import-a", "zz-import-b"):
db.add(models.User(account=account, password_hash="x", display_name=NICK, status=1))
db.commit()
def_row = quota.get_def(db, CODE)
check("建了体检用的额度定义", def_row is not None)
print("\n[1] 第一次导入:一行一个结论")
result = quota.import_totals(db, def_row, reason="年初预算", items=[
{"row": 2, "dims": dims("差旅"), "total": 100000, "title": "市场部差旅"},
{"row": 3, "dims": dims("会议"), "total": "1,234.00 元"},
{"row": 4, "dims": {DIM_LABEL: "培训"}, "total": 5000},
{"row": 5, "dims": dims("招待"), "total": "待定"},
{"row": 6, "dims": dims("办公用品"), "total": ""},
{"row": 7, "dims": {**dims("差旅"), "币种": "CNY"}, "total": 1},
{"row": 8, "dims": dims("差旅"), "total": 200},
{"row": 9, "dims": dims("市场"), "total": 300, "title": "x" * 600},
])
check("两笔好的落了库,六行坏的各有原因",
(result["created"], result["updated"], result["skipped"], len(result["rejected"])) == (2, 0, 0, 6),
str(result))
check("ok=False:有行没收就要说出来", result["ok"] is False)
check("报文把几种下场分开数清", "新增 2 笔" in result["message"] and "6 行没收" in result["message"],
result["message"])
check("count 还是老含义:真的动了几笔", result["count"] == 2, str(result["count"]))
why = {item["row"]: item["reason"] for item in result["rejected"]}
check("维度少一个键的那行报是哪个键没填", 4 in why and "年度" in why[4] and "没填" in why[4], str(why))
check("总额不是数字的那行说它不是一个数字", 5 in why and "不是" in why[5], str(why))
check("总额空着也算不是数字,不悄悄当 0 落一笔", 6 in why and "不是" in why[6], str(why))
check("定义外的维度键挡下来说清楚,不顺手多落一笔账", 7 in why and "币种" in why[7], str(why))
check("本批里重复的维度指出跟第几行重复", 8 in why and "第 2 行" in why[8], str(why))
check("行号认前端带来的那一格(贴进去第几行就报第几行)", set(why) >= {4, 5, 8}, str(why))
check("库里就是落进去的那两笔", len(rows(db)) == 2, str(len(rows(db))))
check("1,234.00 元 这种写法认(Excel 里预算表就这么写)",
row_of(db, **dims("会议")).total_cents == 123400, str(row_of(db, **dims("会议")).total_cents))
check("写了名称就落名称", row_of(db, **dims("差旅")).title == "市场部差旅",
row_of(db, **dims("差旅")).title)
entries = ledger_of(db, **dims("差旅"))
check("落的每一笔都留了一条流水,动后余额等于总额",
len(entries) == 1 and entries[0].amount_cents == 10000000
and entries[0].balance_after_cents == 10000000
and entries[0].kind == models.QuotaLedger.KIND_ISSUE, str([(e.kind, e.amount_cents) for e in entries]))
check("流水上写的是导入给的原因", entries and entries[0].reason == "年初预算",
str(entries[0].reason if entries else ""))
print("\n[2] 同一组维度再导一次:改数,不多一笔")
before = len(rows(db))
result = quota.import_totals(db, def_row, items=[
{"dims": dims("差旅"), "total": 80000},
{"dims": dims("会议"), "total": 1234},
])
check("改到的算覆盖、一模一样那行算跳过",
(result["created"], result["updated"], result["skipped"], len(result["rejected"])) == (0, 1, 1, 0),
str(result))
check("总额真的改成新的那个数", row_of(db, **dims("差旅")).total_cents == 8000000,
str(row_of(db, **dims("差旅")).total_cents))
check("台账没有多出一笔", len(rows(db)) == before, f"{before} -> {len(rows(db))}")
entries = ledger_of(db, **dims("差旅"))
check("改动留了一条负数流水(总额被调下来的痕迹)",
len(entries) == 2 and any(e.amount_cents == -2000000 for e in entries),
str([e.amount_cents for e in entries]))
check("什么都没变的那行不再多记流水", len(ledger_of(db, **dims("会议"))) == 1,
str([e.amount_cents for e in ledger_of(db, **dims("会议"))]))
check("没写名称时不把手工写过的名称抹掉", row_of(db, **dims("差旅")).title == "市场部差旅",
row_of(db, **dims("差旅")).title)
print("\n[3] skip 模式:只补没有的")
result = quota.import_totals(db, def_row, mode="skip", items=[
{"dims": dims("差旅"), "total": 1},
{"dims": dims("新笔"), "total": 600},
])
check("已有那笔原样留着,新的一算新增",
(result["created"], result["updated"], result["skipped"]) == (1, 0, 1), str(result))
check("skip 真的没碰已有总额", row_of(db, **dims("差旅")).total_cents == 8000000,
str(row_of(db, **dims("差旅")).total_cents))
check("skip 模式下没出现的行原样留着(导入不是全量)", len(rows(db)) == 3, str(len(rows(db))))
print("\n[4] 归属人这一列")
only = db.execute(select(models.User).where(models.User.account == "zz-import-a")).scalar_one()
other_account = db.execute(
select(models.User).where(models.User.display_name != NICK).limit(1)
).scalar_one()
result = quota.import_totals(db, def_row, items=[
{"dims": dims("按账号"), "total": 100, "person": other_account.account},
{"dims": dims("按主键"), "total": 100, "person": str(only.id)},
{"dims": dims("查无此人"), "total": 100, "personName": "根本不叫这个"},
{"dims": dims("重名"), "total": 100, "personName": NICK},
])
check("账号、用户主键两种写法都认,查无人与重名各挡各的",
result["created"] == 2 and len(result["rejected"]) == 2, str(result))
reasons = " ".join(item["reason"] for item in result["rejected"])
check("查无此人说的是写登录账号最稳", "查不到这个人" in reasons and "登录账号" in reasons, reasons)
check("重名不替人挑一个,说清写账号区分", "有好几个人" in reasons, reasons)
check("认出人来之后 person 落的是主键、person_name 落的是姓名",
row_of(db, **dims("按账号")).person == str(other_account.id)
and row_of(db, **dims("按账号")).person_name == other_account.display_name,
f"{row_of(db, **dims('按账号')).person}/{row_of(db, **dims('按账号')).person_name}")
# 导入界面上的预检(GET /design/quotas/owners)与逐条落库必须说同一句话:
# 预览标成「没收」的行,导进去要带回一字不差的那句原因,否则「预览新增 3 笔、
# 导完变 2 笔」这种事永远没人查得动。
verdicts = quota.resolve_owners(
db, [other_account.account, str(only.id), "根本不叫这个", NICK, "", " "]
)
check("预检跳掉空写法,剩下的一个写法回一条", len(verdicts) == 4, str(len(verdicts)))
check("预检认得出的那两条回的是主键与姓名(跟落库同一个)",
[(item["person"], item["personName"]) for item in verdicts[:2]]
== [(str(other_account.id), other_account.display_name), (str(only.id), only.display_name)],
str(verdicts[:2]))
check("预检认不出的人与导入结果里的原因逐字一致",
sorted(item["reason"] for item in verdicts if not item["ok"])
== sorted(item["reason"] for item in result["rejected"]),
f"{[item['reason'] for item in verdicts if not item['ok']]} vs "
f"{[item['reason'] for item in result['rejected']]}")
check("认得出人时预检不给原因(别把没事的行标成有事)",
all(item["reason"] == "" for item in verdicts if item["ok"]), str(verdicts))
print("\n[5] 整批层面的挡法与口径")
for label, kwargs, expect in (
("空批不写库", {"items": []}, "没有要导入的额度"),
("超过上限报一句", {"items": [{"dims": dims(f"A{i}"), "total": 1} for i in range(quota.MAX_IMPORT_ROWS + 1)]},
"一次最多导入"),
):
try:
quota.import_totals(db, def_row, **kwargs)
check(label, False, "没报错")
except ApiError as exc:
check(label, exc.status_code == 400 and expect in str(exc.detail), f"{exc.status_code} {exc.detail}")
check("上限那一行也没落进去", all("A0" not in str(row.dims) for row in rows(db)), str(len(rows(db))))
check("金额读法:货币符号 / 千分位 / 会计红字 / 空",
(quota.parse_import_amount("¥1,200.50"), quota.parse_import_amount("(500)"),
quota.parse_import_amount(""), quota.parse_import_amount("12元"), quota.parse_import_amount(True))
== (120050, -50000, None, 1200, None),
str([quota.parse_import_amount("¥1,200.50"), quota.parse_import_amount("(500)")]))
check("列上限与模型一致(改了模型记得回来看这条)",
quota.IMPORT_TEXT_MAX == models.Quota.__table__.c.title.type.length
and quota.IMPORT_UNIT_MAX == models.Quota.__table__.c.unit.type.length,
f"{models.Quota.__table__.c.title.type.length}/{models.Quota.__table__.c.unit.type.length}")
result = quota.import_totals(db, def_row, items=[{"dims": dims("长名字"), "total": 1, "title": "x" * 600}])
check("名称超长是挡下来说原因,不是截一半存进去",
len(result["rejected"]) == 1 and "超过" in result["rejected"][0]["reason"]
and "长名字" not in [str(row.dims.get(DIM_LABEL)) for row in rows(db)], str(result["rejected"]))
print("\n[6] 导完读得到的就是刚导进去的那份")
view = [item for item in quota.list_quotas(db, CODE)]
check("台账列出来就是这几笔,总额对得上",
len(view) == len(rows(db)) and any(int(item.total_cents) == 8000000 for item in view),
str(len(view)))
check("定义上的维度键没被导入改坏", quota.get_def(db, CODE).dims == [DIM_LABEL, YEAR_LABEL],
str(quota.get_def(db, CODE).dims))
print(f"\n合计 {PASSED + len(FAILS)} 项:通过 {PASSED} / 失败 {len(FAILS)}")
return 1 if FAILS else 0
finally:
try:
purge(db)
finally:
db.close()
if __name__ == "__main__":
raise SystemExit(main())