unis_manager/tests/test_custom_finance.py

277 lines
14 KiB
Python
Executable File
Raw Permalink 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.

"""定开财务口径:跨季度 / 跨年度统计、年度计收目标、验收时间与增量金额的联动。
这一组用例是「跨季度统计有问题」的回归防线:
金额一律「元」,年度目标一律「万元」,验收归属只认 accept_year + accept_date。
"""
from __future__ import annotations
from datetime import date
from app import constants, finance
def _ledger(h):
"""一套故意跨年份、带脏数据的定开台账。"""
rows = {}
rows["甲"] = h.custom("甲-2025下单2026验收", origin="华智下单", amount=100000,
sign_date="2025-11-20", accept_date="Q1", accept_year=2026)
rows["乙"] = h.custom("乙-2026下单2026验收", origin="华智下单", amount=200000,
sign_date="2026-01-10", accept_date="Q3", accept_year=2026)
rows["丙"] = h.custom("丙-非下单归属", origin="提前交付", amount=50000,
sign_date="2026-02-01", accept_date="Q3", accept_year=2026)
rows["丁"] = h.custom("丁-脏下单时间", origin="华智下单", amount=80000, sign_date="2024年3月前")
rows["戊"] = h.custom("戊-无下单时间", origin="华智下单", amount=60000)
rows["己"] = h.custom("己-缺验收年度", amount=70000)
return rows
def _finance(h, **params):
r = h.admin.get("/api/custom/finance", params=params)
assert r.status_code == 200, r.text
return r.json()
# ------------------------------------------------------------------ 跨季度 / 跨年度
def test_统计按选中年月的季度归集(h):
rows = _ledger(h)
# 只有季度没有年度的历史脏行:直接改库造出来,接口层是拦着的
from app.models import CustomProject
from app.db import SessionLocal
with SessionLocal() as s:
s.get(CustomProject, rows["己"]["id"]).accept_date = "Q2"
s.commit()
d = _finance(h, year=2026, month=1)
ctx = d["context"]
assert (ctx["year"], ctx["month"], ctx["quarter"]) == (2026, 1, 1)
assert ctx["quarter_label"] == "2026年Q1"
assert ctx["quarter_start"] == "2026-01-01" and ctx["quarter_end"] == "2026-03-31"
k = d["kpi"]
# 已下单只看项目归属:提前交付不算,四单共 44 万
assert k["placed"] == {"count": 4, "amount": 440000.0}
# 2026Q1 下单的只有乙;2026 年全年下单也只有乙
assert k["sign_quarter"] == {"count": 1, "amount": 200000.0}
assert k["sign_year"] == {"count": 1, "amount": 200000.0}
# 验收:甲是 2026Q1,乙丙是 2026Q3;本季度只算甲,全年算三笔
assert k["accept_quarter"] == {"count": 1, "amount": 100000.0}
assert k["accept_year"] == {"count": 3, "amount": 350000.0}
# 数据质量提示:认不出下单年份的 1 笔(戊),只有季度没有年度的 1 笔(己)
assert k["sign_unknown"] == 1 and k["accept_no_year"] == 1
def test_切到历史周期只看那一年(h):
_ledger(h)
y2025 = _finance(h, year=2025, month=12)
assert (y2025["context"]["year"], y2025["context"]["quarter"]) == (2025, 4)
# 甲 2025-11 下单 → 落在 2025Q4;它的验收在 2026,不能串回 2025
assert y2025["kpi"]["sign_quarter"] == {"count": 1, "amount": 100000.0}
assert y2025["kpi"]["sign_year"] == {"count": 1, "amount": 100000.0}
assert y2025["kpi"]["accept_quarter"] == {"count": 0, "amount": 0.0}
assert y2025["kpi"]["accept_year"] == {"count": 0, "amount": 0.0}
# 脏文本「2024年3月前」按 2024Q1 统计,不因为脏就整笔丢掉
y2024 = _finance(h, year=2024, month=2)
assert y2024["kpi"]["sign_quarter"] == {"count": 1, "amount": 80000.0}
assert y2024["kpi"]["sign_year"] == {"count": 1, "amount": 80000.0}
# 顶栏选周:周期换算出来的年月季度与月视图一致
week = h.period(2025, 12, 1)
byweek = _finance(h, period_id=week["id"])
assert byweek["context"]["label"] == week["full_label"]
assert byweek["context"]["quarter_label"] == y2025["context"]["quarter_label"]
assert byweek["kpi"] == y2025["kpi"]
def test_认不出季度的项目计入年度并单列未分季(h):
"""回归:有年份、认不出季度(「2024/」这种残缺值)的项目曾从季度表里静默消失,
导致同一屏上「年度任务合计」比 KPI 年度少一笔。"""
from app.db import SessionLocal
from app.models import CustomProject
h.custom("庚-下单只有年份", origin="华智下单", amount=320000, sign_date="2024/")
acc = h.custom("辛-验收只有年度", origin="华智下单", amount=150000, sign_date="2024-02-18")
with SessionLocal() as s: # 接口拦着「只填年度不填季度」,直接造脏行
s.get(CustomProject, acc["id"]).accept_year = 2024
s.commit()
d = _finance(h, year=2024, month=5)
k, a = d["kpi"], d["annual"]
q1, q2, q3, q4 = a["quarters"]
uns = a["unscheduled"]
# 都不在任何季度里,但都算进 2024 年度
assert (q1["sign_count"], q2["sign_count"], q3["sign_count"], q4["sign_count"]) == (1, 0, 0, 0)
assert (q1["acc_count"], q2["acc_count"], q3["acc_count"], q4["acc_count"]) == (0, 0, 0, 0)
assert uns["sign_count"] == 1 and uns["sign_amount"] == 320000.0
assert uns["acc_count"] == 1 and uns["acc_amount"] == 150000.0
assert k["sign_no_quarter"] == 1 and k["accept_no_quarter"] == 1
# 核心不变式:四季度 + 未分季 = 合计 = KPI 年度
t = a["total"]
assert t["sign_count"] == sum(x["sign_count"] for x in a["quarters"]) + uns["sign_count"]
assert t["sign_amount"] == k["sign_year"]["amount"] == 470000.0
assert t["acc_count"] == sum(x["acc_count"] for x in a["quarters"]) + uns["acc_count"] == 1
assert t["acc_amount"] == k["accept_year"]["amount"] == 150000.0
# 目标只按四个季度累加,未分季不占目标、也不折算完成率
assert t["target"] == sum(x["target"] for x in a["quarters"])
def test_未分季为空时不影响原有合计(h):
"""干净台账下未分季计数为 0,合计仍等于四个季度之和(不引入新的偏差)。"""
_ledger(h)
a = _finance(h, year=2026, month=8)["annual"]
uns, t = a["unscheduled"], a["total"]
assert uns == {"acc_count": 0, "acc_amount": 0.0, "sign_count": 0, "sign_amount": 0.0}
assert t["acc_count"] == sum(x["acc_count"] for x in a["quarters"])
assert t["sign_amount"] == round(sum(x["sign_amount"] for x in a["quarters"]), 2)
def test_顶栏周期换算成季度(db):
from app.db import SessionLocal
with SessionLocal() as s:
ctx = finance.period_context(s, year=2026, month=11)
assert (ctx["year"], ctx["quarter"]) == (2026, 4)
assert ctx["label"] == "2026年11月"
assert ctx["quarter_start"] == "2026-10-01" and ctx["quarter_end"] == "2026-12-31"
# 选中的周期不存在时按年月兜底,不会报错也不会算错年份
assert finance.period_context(s, period_id=424242, year=2025, month=2)["quarter"] == 1
assert finance.period_context(s)["year"] == date.today().year
assert constants.quarter_of_month(1) == 1 and constants.quarter_of_month(12) == 4
assert constants.quarter_end(2026, 1) == "2026-03-31"
assert constants.quarter_end(2024, 1) == "2024-03-31" # 闰年也认得
# ------------------------------------------------------------------ 年度计收目标
def test_年度目标保存后读回来一模一样(h):
_ledger(h)
r = h.admin.put("/api/custom/annual-targets",
json={"year": 2026, "targets": {"1": 10, "2": 0, "3": 20, "4": None}})
assert r.status_code == 200, r.text
saved = {"1": 10.0, "2": 0.0, "3": 20.0, "4": 0.0}
assert r.json()["targets"] == saved
assert h.admin.get("/api/custom/annual-targets", params={"year": 2026}).json()["targets"] == saved
annual = _finance(h, year=2026, month=1)["annual"]
assert annual["year"] == 2026 and annual["targets"] == saved
q1, q2, q3, q4 = annual["quarters"]
assert q1 == {**q1, "acc_count": 1, "acc_amount": 100000.0, "rate": 1.0, "current": True}
assert q2["target"] == 0.0 and q2["rate"] is None # 没设目标就不折算完成率
assert (q3["acc_count"], q3["acc_amount"], q3["rate"]) == (2, 250000.0, 1.25)
assert q4["current"] is False
assert annual["total"]["target"] == 30.0
assert annual["total"]["acc_count"] == 3 and annual["total"]["acc_amount"] == 350000.0
assert annual["total"]["sign_count"] == 1 and annual["total"]["sign_amount"] == 200000.0
def test_没配过的年份用默认目标(h):
defaults = {str(q): v for q, v in constants.CUSTOM_ANNUAL_TARGETS_DEFAULT.items()}
assert h.admin.get("/api/custom/annual-targets", params={"year": 2030}).json()["targets"] == defaults
assert h.admin.get("/api/custom/annual-targets").json()["year"] == __import__("datetime").date.today().year
def test_目标值不是数字要报错(h):
r = h.admin.put("/api/custom/annual-targets", json={"year": 2026, "targets": {"2": "十万"}})
assert r.status_code == 400 and "Q2" in r.json()["detail"]
# ------------------------------------------------------------------ 台账字段口径
def test_验收时间必须年度季度一起填(h):
cp = h.custom("验收时间校验", amount=1000)
assert cp["accept_label"] == ""
cid = cp["id"]
patch = lambda body: h.admin.patch(f"/api/custom/projects/{cid}", json=body)
assert "验收年度" in patch({"accept_date": "Q2"}).json()["detail"]
assert patch({"accept_date": "Q2"}).status_code == 400
assert "别留季度为空" in patch({"accept_year": 2027, "accept_date": ""}).json()["detail"]
ok = patch({"accept_date": "q2", "accept_year": 2027}).json() # 大小写不敏感,存成 Q2
assert (ok["accept_date"], ok["accept_year"], ok["accept_label"]) == ("Q2", 2027, "2027Q2")
cleared = patch({"accept_date": None, "accept_year": None}).json() # 要清就一起清
assert cleared["accept_date"] is None and cleared["accept_year"] is None
assert cleared["accept_label"] == ""
def test_项目状态是唯一状态字段(h):
cp = h.custom("阶段推导", project_status="退单", amount=100000)
assert cp["stage"] == "closed"
assert cp["confirmed_amount"] == 0.0 # 退单不确认收入
accepted = h.admin.patch(f"/api/custom/projects/{cp['id']}",
json={"project_status": "已验收"}).json()
assert accepted["stage"] == "accepted"
# 商务阶段不再是可写字段:传了也不生效,避免出现两套状态
ignored = h.admin.patch(f"/api/custom/projects/{cp['id']}", json={"stage": "lead"}).json()
assert ignored["stage"] == "accepted"
assert h.admin.patch(f"/api/custom/projects/{cp['id']}",
json={"project_status": "随便写"}).status_code == 400
assert h.admin.post("/api/custom/projects", json={"name": "阶段推导"}).status_code == 400
assert h.admin.post("/api/custom/projects", json={"name": " "}).status_code == 400
assert h.admin.patch("/api/custom/projects/424242", json={"name": "x"}).status_code == 404
def test_周期记录的新增量与台账同步(h):
pid = h.today_period_id
cp = h.custom("增量联动", amount=100000, revenue_amount=20000)
cur = lambda: h.admin.get(f"/api/custom/projects/{cp['id']}").json()["project"]
u = h.custom_update(cp["id"], pid, content="本月新增下单与计收",
amount_delta=50000, revenue_delta=30000)
assert (u["amount_delta"], u["revenue_delta"]) == (50000.0, 30000.0)
assert (cur()["amount"], cur()["revenue_amount"]) == (150000.0, 50000.0)
h.admin.patch(f"/api/custom/updates/{u['id']}", json={"revenue_delta": 10000})
assert (cur()["amount"], cur()["revenue_amount"]) == (150000.0, 30000.0) # 按差额回补
assert h.admin.patch(f"/api/custom/updates/{u['id']}", json={"period_id": None}).status_code == 400
assert h.admin.patch(f"/api/custom/updates/{u['id']}", json={"period_id": 424242}).status_code == 404
h.admin.delete(f"/api/custom/updates/{u['id']}")
assert (cur()["amount"], cur()["revenue_amount"]) == (100000.0, 20000.0) # 删记录一并扣回
assert h.admin.patch("/api/custom/updates/424242", json={"content": "x"}).status_code == 404
assert h.admin.delete("/api/custom/updates/424242").status_code == 404
assert h.admin.post("/api/custom/updates", json={"content": "没有项目"}).status_code == 404
assert h.admin.post("/api/custom/updates",
json={"custom_project_id": cp["id"], "content": "没有周期"}).status_code == 400
# ------------------------------------------------------------------ 老库回填
def test_回填补齐验收年份与商务阶段(h, db):
from app.models import CustomProject
cp = h.custom("待回填", accept_date=None)
other = h.custom("待改阶段", project_status="待开发")
db.expire_all()
row = db.get(CustomProject, cp["id"])
row.accept_date, row.accept_date_real, row.accept_year = "Q3", "2024-09-30", None
db.get(CustomProject, other["id"]).stage = "signed" # 状态与阶段对不上
db.commit()
notes = finance.backfill(db)
db.expire_all()
assert db.get(CustomProject, cp["id"]).accept_year == 2024
assert db.get(CustomProject, other["id"]).stage == "signed" # 待开发本来就是 signed
assert any("验收年份" in n for n in notes)
db.get(CustomProject, other["id"]).project_status = "已验收"
db.commit()
assert any("商务阶段" in n for n in finance.backfill(db))
db.expire_all()
assert db.get(CustomProject, other["id"]).stage == "accepted"
assert finance.backfill(db) == [] # 再跑一次不再改任何东西
def test_时间解析只认能进统计的写法():
assert constants.parse_quarter("Q3") == 3 and constants.parse_quarter("q3") == 3
assert constants.parse_quarter("三季度") is None and constants.parse_quarter("") is None
assert constants.parse_year_month("2026-03-31") == (2026, 3)
assert constants.parse_year_month("2026年3月") == (2026, 3)
assert constants.parse_year_month("2024年3月前") == (2024, 3)
assert constants.parse_year_month("2026") == (2026, 0)
assert constants.parse_year_month("待定") is None and constants.parse_year_month(None) is None
assert constants.derive_stage("已验收") == "accepted"
assert constants.derive_stage("", "developing") == "developing"
assert constants.merge_levels({"board": "ro"}, {"board": "rw", "rbac": "ro"}) == {
"board": "rw", "rbac": "ro"}