fourcal-pms/backend/app/service/calc/validate.py

242 lines
9.6 KiB
Python
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.

"""结果校验:把只存在于浏览器里的约束搬到后端。
``RISK-BUD-VAL-001`` 写得很明白——差旅费/业务费 10% 限额、付款勾稽这些"关键校验"
全在前端,调接口或换个页面入口就能绕过。这里成为唯一实现,前端展示同样结论但不再是
把关者(``TO-BE-BACKEND-CALC-007``:输入校验与结果校验分开)。
每条规则都带稳定编号,前端提示、审计日志、测试用例引用同一个号。
"""
from __future__ import annotations
from dataclasses import dataclass
from dataclasses import field as dc_field
from decimal import Decimal
from .rules import RULES
from .money import ZERO, money_str, to_dec
SEVERITY_ERROR = "error"
SEVERITY_WARNING = "warning"
@dataclass
class Issue:
rule_id: str
severity: str
message: str
field: str = ""
detail: dict[str, object] = dc_field(default_factory=dict)
def to_dict(self) -> dict[str, object]:
return {
"ruleId": self.rule_id,
"severity": self.severity,
"message": self.message,
"field": self.field or None,
"detail": self.detail or None,
}
@dataclass
class ValidationReport:
issues: list[Issue] = dc_field(default_factory=list)
@property
def errors(self) -> list[Issue]:
return [item for item in self.issues if item.severity == SEVERITY_ERROR]
@property
def warnings(self) -> list[Issue]:
return [item for item in self.issues if item.severity == SEVERITY_WARNING]
@property
def passed(self) -> bool:
return not self.errors
def add(self, rule_id: str, severity: str, message: str, field: str = "", **detail: object) -> None:
self.issues.append(Issue(rule_id, severity, message, field, detail))
def error(self, rule_id: str, message: str, field: str = "", **detail: object) -> None:
self.add(rule_id, SEVERITY_ERROR, message, field, **detail)
def warning(self, rule_id: str, message: str, field: str = "", **detail: object) -> None:
self.add(rule_id, SEVERITY_WARNING, message, field, **detail)
def merge(self, other: "ValidationReport") -> None:
self.issues.extend(other.issues)
def to_dict(self) -> dict[str, object]:
return {
"passed": self.passed,
"errors": [i.to_dict() for i in self.errors],
"warnings": [i.to_dict() for i in self.warnings],
}
def check_required(report: ValidationReport, rows: list[dict], *, label: str, fields: list[str]) -> None:
"""输入校验:明细行必填项。``TAX-06`` 那类 NPE 从此变成明确的校验错误。"""
for index, row in enumerate(rows, start=1):
missing = [name for name in fields if str(row.get(name) or "").strip() == ""]
if missing:
report.error(
"INPUT-REQUIRED",
f"{label}第 {index} 行缺少必填项:{'、'.join(missing)}",
field=f"{label}#{index}",
rows_index=index,
missing=missing,
)
def check_travel_limit(
report: ValidationReport,
gross_a: Decimal,
manage_total: Decimal,
travel_and_business: Decimal,
) -> None:
"""``BUD-VAL-001``:差旅费 + 业务费 ≤ [毛利 A − (项目管理费用总额 − 差旅费 − 业务费)] × 比例。"""
rate = to_dec(RULES.travel_business_limit_rate)
travel = to_dec(travel_and_business)
allowed = (to_dec(gross_a) - (to_dec(manage_total) - travel)) * rate / Decimal("100")
if travel > allowed:
report.error(
"BUD-VAL-001",
"项目管理费用中差旅费与业务费合计 "
f"{money_str(travel)} 超出限额 {money_str(allowed)}"
f"(限额=[毛利A −(项目管理费用总额 − 差旅业务费)]×{rate}%)",
field="budget.manage_lines",
travel=money_str(travel),
allowed=money_str(allowed),
gross_a=money_str(gross_a),
manage_total=money_str(manage_total),
)
def check_contribution_rate(report: ValidationReport, contribution_rate: object) -> None:
"""``BUD-VAL-002``:贡献利润率阈值。老系统这个校验被注释掉了,实际不生效。
动作由系统参数 ``calc.contribution_rate_action`` 决定:``block`` 阻止送审,``warn`` 只告警
(默认,等业务确认后再收紧),``none`` 完全不检查。
"""
action = RULES.contribution_rate_action
if action == "none":
return
from .money import Ratio
value = contribution_rate
if isinstance(value, Ratio):
if not value.defined:
report.warning("BUD-VAL-002", "贡献利润率无法计算(不含税收入为 0),送审前请确认", "profit.contribution_rate")
return
value = value.value
threshold_key = "budget.contribution_rate_threshold"
threshold = to_dec(THRESHOLD_REGISTRY.get(threshold_key, "0"))
if threshold == ZERO:
return
if to_dec(value) < threshold:
message = f"项目贡献利润率 {money_str(value)}% 低于配置阈值 {money_str(threshold)}%"
if action == "block":
report.error("BUD-VAL-002", message, "profit.contribution_rate", value=money_str(value), threshold=money_str(threshold))
else:
report.warning("BUD-VAL-002", message, "profit.contribution_rate", value=money_str(value), threshold=money_str(threshold))
#: 阈值这类"业务随时要改"的数字放在系统配置里,由服务层在计算前灌进来。
THRESHOLD_REGISTRY: dict[str, str] = {}
def set_thresholds(values: dict[str, object]) -> None:
THRESHOLD_REGISTRY.clear()
THRESHOLD_REGISTRY.update({str(k): str(v) for k, v in (values or {}).items()})
def check_pay_plan_reconciles(
report: ValidationReport,
pay_by_type: dict[int, Decimal],
purchase_by_type: dict[int, Decimal],
) -> None:
"""``PLAN-VAL-001``:付款计划四类含税合计分别等于采购明细对应分类含税金额。"""
from .mapping import PURCHASE_TYPE_TO_KEY
labels = {1: "设备", 2: "施工", 3: "服务", 4: "其他"}
for code, label in labels.items():
paid = to_dec(pay_by_type.get(code))
purchased = to_dec(purchase_by_type.get(code))
if paid != purchased:
report.error(
"PLAN-VAL-001",
f"{label}类付款计划合计 {money_str(paid)} 与采购成本明细含税 {money_str(purchased)} 不一致",
field="budget.pay_plan",
purchase_type=code,
paid=money_str(paid),
purchased=money_str(purchased),
)
def check_fund_plan_totals(
report: ValidationReport,
*,
fund_cost_total: Decimal,
fund_income_total: Decimal,
purchase_include_total: Decimal,
earnest_cost_total: Decimal,
manage_total: Decimal,
income_include_total: Decimal,
earnest_income_total: Decimal,
) -> None:
"""``PLAN-VAL-002``:资金计划收付总额与明细勾稽。"""
expected_cost = to_dec(purchase_include_total) + to_dec(earnest_cost_total) + to_dec(manage_total)
if to_dec(fund_cost_total) != expected_cost:
report.error(
"PLAN-VAL-002",
f"资金计划支出合计 {money_str(fund_cost_total)} 应等于"
f"采购含税 {money_str(purchase_include_total)} + 保证金 {money_str(earnest_cost_total)}"
f" + 项目管理费用 {money_str(manage_total)} = {money_str(expected_cost)}",
field="budget.fund_months",
fund_total=money_str(fund_cost_total),
expected=money_str(expected_cost),
)
expected_income = to_dec(income_include_total) + to_dec(earnest_income_total)
if to_dec(fund_income_total) != expected_income:
report.error(
"PLAN-VAL-002",
f"资金计划收款合计 {money_str(fund_income_total)} 应等于"
f"收入含税 {money_str(income_include_total)} + 保证金收款 {money_str(earnest_income_total)}"
f" = {money_str(expected_income)}",
field="budget.fund_months",
fund_total=money_str(fund_income_total),
expected=money_str(expected_income),
)
def check_fund_months(report: ValidationReport, months: list[str], plan_start: str, plan_end: str) -> None:
"""``PLAN-VAL-003``:月份不得重复,起止月必须存在。"""
seen: set[str] = set()
for month in months:
if month in seen:
report.error("PLAN-VAL-003", f"资金计划月份 {month} 重复", "budget.fund_months", month=month)
seen.add(month)
for boundary, label in ((plan_start, "开始"), (plan_end, "结束")):
if boundary and boundary not in seen:
report.error(
"PLAN-VAL-003",
f"资金计划缺少项目{label}月 {boundary}",
"budget.fund_months",
missing=boundary,
)
def check_tax_inputs(report: ValidationReport, rows: list[dict], *, label: str) -> None:
"""``TAX-06``/``TAX-07``:税率范围与高精度税率提示。"""
for index, row in enumerate(rows, start=1):
raw = row.get("tax_rate")
if raw is None or str(raw).strip() == "":
continue
rate = to_dec(raw)
if rate < ZERO or rate > Decimal("100"):
report.error("INPUT-TAX-RANGE", f"{label}第 {index} 行税率 {raw} 不在 0~100 之间",
field=f"{label}#{index}", row_index=index)
elif rate != rate.quantize(Decimal("1")):
report.warning("TAX-07", f"{label}第 {index} 行税率 {raw} 含小数,请确认是否为录入误差",
field=f"{label}#{index}", row_index=index)