421 lines
19 KiB
Python
421 lines
19 KiB
Python
"""计算口径的运行态:规则存在系统参数表里,界面上改,代码里读。
|
||
|
||
这些规则过去写在 ``config.toml`` 的 ``[calc]`` 段:想把公司管理费率调 0.2 个百分点,
|
||
得登机器改文件、重启后端,还得祈祷没人正在跑试算。现在它们落在 ``system_config``
|
||
(``group='calc'``),在「系统 → 计算口径」页面上改,保存即生效,配置文件里一个字都不留。
|
||
|
||
三条规矩:
|
||
|
||
* **默认值只写一次**::class:`CalcRules` 的字段默认值就是推荐口径。建库时按它把
|
||
``system_config`` 补齐,页面上的"恢复默认"也回到它,不存在第二份抄来的数字。
|
||
* **脏值进不来**:枚举取值、数字区间、位数是不是整数都在 :func:`normalize` 里挡,
|
||
保存不成功就回中文原因,绝不会把 ``HALF_UP`` 静默存成 ``halfup`` 再静默回落。
|
||
* **读取口只有一个**:``from .rules import RULES`` 之后写 ``RULES.money_scale``。
|
||
:func:`apply` 是原地改字段、不换新对象,所以各处 ``from .rules import RULES``
|
||
拿到的一直是同一个对象,界面上存完下一次试算就是新口径。
|
||
|
||
多进程部署(``uvicorn --workers 2``)时另一个 worker 看不见这次保存,所以每次试算前
|
||
:func:`app.service.biz.apply_sys_config` 都会按库里的值重新灌一遍——快照里的口径
|
||
永远跟这一次计算开始时库里的值一致。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
from contextlib import contextmanager
|
||
from dataclasses import dataclass, fields
|
||
from decimal import Decimal, InvalidOperation
|
||
from typing import Any, Iterable, Iterator, Mapping
|
||
|
||
logger = logging.getLogger("pms.calc.rules")
|
||
|
||
#: system_config.group 里属于计算口径的那一批
|
||
RULE_GROUP = "calc"
|
||
#: 参数编码的统一前缀(calc.money_scale 这种)
|
||
CODE_PREFIX = "calc."
|
||
#: 历史上界面上有、但内核没读过的重复参数:值搬进 calc.* 之后删掉,别再留两处
|
||
LEGACY_CODE_ALIASES = {
|
||
"finance.company_manage_fee_rate": "calc.company_manage_fee_rate",
|
||
"budget.travel_business_limit_rate": "calc.travel_business_limit_rate",
|
||
}
|
||
|
||
BOOL_TRUE = ("1", "true", "yes", "on")
|
||
BOOL_FALSE = ("0", "false", "no", "off")
|
||
|
||
|
||
@dataclass
|
||
class CalcRules:
|
||
"""一次计算用到的全部口径参数。默认值 = 推荐口径(docs/计算口径.md)。"""
|
||
|
||
version: str = "2026.10"
|
||
money_scale: int = 2
|
||
rate_scale: int = 4
|
||
percent_scale: int = 2
|
||
rounding: str = "HALF_UP"
|
||
zero_denominator: str = "undefined"
|
||
company_manage_fee_rate: float = 2.8
|
||
travel_business_limit_rate: float = 10.0
|
||
contribution_rate_action: str = "warn"
|
||
# 价内税:True(默认,TO-BE)先算不含税、税额=含税-不含税,保证 含税额=不含税+税额 分毫不差;
|
||
# False 回到老公式 税额=含税×r/(1+r)(TAX-002),双跑对账时用。
|
||
tax_from_complement: bool = True
|
||
# True 回到老口径:税率参与公式前先舍到 2 位(RISK-TAX-001),默认关闭。
|
||
tax_rate_pre_round: bool = False
|
||
# 利润各层的成本集合(DECISION-BUD-PROFIT-001)。默认按推荐口径:
|
||
# 项目毛利 = 采购毛利 - 项目管理费用 - 其他成本 - 财务费用
|
||
profit_manage_cost_in_gross: bool = True
|
||
profit_other_cost_in_gross: bool = True
|
||
profit_finance_cost_in_gross: bool = True
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class Choice:
|
||
value: str
|
||
label: str
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class RuleSpec:
|
||
"""一条规则在界面上的长相 + 校验它所需要的全部信息。
|
||
|
||
``attr`` 是 :class:`CalcRules` 上的字段名,参数编码由它拼出来(``calc.<attr>``),
|
||
所以 seed、页面、校验三处看到的是同一份定义,不会各写一份常量表。
|
||
"""
|
||
|
||
attr: str
|
||
name: str
|
||
section: str
|
||
kind: str # int / decimal / bool / enum / string
|
||
remark: str = ""
|
||
unit: str = ""
|
||
choices: tuple[Choice, ...] = ()
|
||
minimum: float | None = None
|
||
maximum: float | None = None
|
||
step: str = ""
|
||
|
||
@property
|
||
def code(self) -> str:
|
||
return f"{CODE_PREFIX}{self.attr}"
|
||
|
||
@property
|
||
def value_type(self) -> str:
|
||
return "number" if self.kind in ("int", "decimal") else ("bool" if self.kind == "bool" else "string")
|
||
|
||
@property
|
||
def default(self) -> Any:
|
||
return getattr(CalcRules(), self.attr)
|
||
|
||
@property
|
||
def default_text(self) -> str:
|
||
return format_value(self, self.default)
|
||
|
||
|
||
#: 页面按段落渲染,顺序就是这里排的顺序
|
||
RULE_SECTIONS: tuple[tuple[str, str, str], ...] = (
|
||
("scale", "舍入与位数", "金额、比率保留几位,遇到零分母怎么办"),
|
||
("tax", "价税分离", "TAX-001 / TAX-002 与双跑对账用的两个历史口径"),
|
||
("profit", "利润阶梯", "各层扣哪些成本,以及没人工填写时按什么费率派生"),
|
||
("validate", "校验阈值", "BUD-VAL-001 / BUD-VAL-002 用的比例与动作"),
|
||
)
|
||
|
||
RULE_SPECS: tuple[RuleSpec, ...] = (
|
||
RuleSpec(
|
||
"version", "计算口径版本", "scale", "string",
|
||
remark="写进每一次计算快照与项目的 calc_version。生产上改上面任何一条都必须同时升这一项,"
|
||
"否则同一项目会出现「数字变了但版本号没变」。",
|
||
),
|
||
RuleSpec("money_scale", "金额保留位数", "scale", "int", unit="位", minimum=0, maximum=12,
|
||
remark="所有金额舍入的小数位(round_money)。老系统 Java / 浏览器 / Excel 各舍一次,"
|
||
"这里只舍一处。", step="1"),
|
||
RuleSpec("rate_scale", "比率中间除法保留位数", "scale", "int", unit="位", minimum=1, maximum=12,
|
||
remark="中间除法保留的位数,对应老代码里散落的「除法保留 4 位」。", step="1"),
|
||
RuleSpec("percent_scale", "百分比结果保留位数", "scale", "int", unit="位", minimum=0, maximum=12,
|
||
remark="利润率这类百分比结果保留的位数(利润 / 收入 × 100)。", step="1"),
|
||
RuleSpec(
|
||
"rounding", "舍入方式", "scale", "enum",
|
||
choices=(Choice("HALF_UP", "四舍五入(HALF_UP)"), Choice("HALF_DOWN", "五舍六入(HALF_DOWN)"),
|
||
Choice("HALF_EVEN", "银行家舍入(HALF_EVEN)"), Choice("UP", "远离零进位(UP)"),
|
||
Choice("DOWN", "截断(DOWN)"), Choice("FLOOR", "向下取整(FLOOR)"),
|
||
Choice("CEILING", "向上取整(CEILING)")),
|
||
remark="所有舍入统一用它。老系统是 HALF_UP,换别的口径要在版本号上留痕。",
|
||
),
|
||
RuleSpec(
|
||
"zero_denominator", "零分母的利润率", "scale", "enum",
|
||
choices=(Choice("undefined", "返回未定义并带原因(推荐)"), Choice("zero", "返回 0(老系统口径)")),
|
||
remark="收入为 0 时利润率怎么算。老系统一会儿返回 0、一会儿返回「利润×100」、"
|
||
"一会儿把分母换成 1(BUD-PROFIT-002 / RISK-SET-RATE-001 / FINAL-RATE-001);"
|
||
"zero 只在逐月对账的过渡期用。",
|
||
),
|
||
RuleSpec(
|
||
"tax_from_complement", "税额取补数", "tax", "bool",
|
||
remark="开:税额 = 含税额 − 不含税额,保证三项相加正好等于含税额(推荐)。"
|
||
"关:回到老公式 税额 = 含税 × r/(1+r)(RISK-TAX-002),双跑对账期间用。",
|
||
),
|
||
RuleSpec(
|
||
"tax_rate_pre_round", "税率先舍到 2 位", "tax", "bool",
|
||
remark="开:税率进入公式前先舍到 2 位(RISK-TAX-001),高精度税率会先丢精度。默认关。",
|
||
),
|
||
RuleSpec(
|
||
"profit_manage_cost_in_gross", "项目毛利扣项目管理费用", "profit", "bool",
|
||
remark="DECISION-BUD-PROFIT-001:项目毛利 B = 采购毛利 A − 项目管理费用 M − 其他成本 O − 财务费用 F。"
|
||
"关掉就是从 B 里少扣一项,只用于复现老口径。",
|
||
),
|
||
RuleSpec(
|
||
"profit_other_cost_in_gross", "项目毛利扣其他成本", "profit", "bool",
|
||
remark="关掉它就精确复现老后端「没扣其他成本」的那一套(RISK-BUD-PROFIT-001),"
|
||
"双跑对账可以直接比。",
|
||
),
|
||
RuleSpec(
|
||
"profit_finance_cost_in_gross", "项目毛利扣财务费用", "profit", "bool",
|
||
remark="关掉就是从项目毛利里少扣财务费用,只用于复现老口径。",
|
||
),
|
||
RuleSpec(
|
||
"company_manage_fee_rate", "公司管理费用率", "profit", "decimal", unit="%",
|
||
minimum=0, maximum=100, step="0.1",
|
||
remark="没有人工填写公司管理费用时按这个费率派生(收入不含税 × 费率)。老系统把它写死在 "
|
||
"BudgetBean 的 getter 里返回 2.8%,页面上改了不生效(RISK-BUD-CM-001)。",
|
||
),
|
||
RuleSpec(
|
||
"travel_business_limit_rate", "差旅及业务费限额比例", "validate", "decimal", unit="%",
|
||
minimum=0, maximum=100, step="0.1",
|
||
remark="BUD-VAL-001:差旅费 + 业务费 ≤ [毛利A −(项目管理费用总额 − 差旅业务费)] × 该比例。",
|
||
),
|
||
RuleSpec(
|
||
"contribution_rate_action", "贡献利润率不达标时", "validate", "enum",
|
||
choices=(Choice("block", "拦截送审"), Choice("warn", "仅告警"), Choice("none", "不检查")),
|
||
remark="BUD-VAL-002 的动作。阈值在「业务参数」页的 budget.contribution_rate_threshold,"
|
||
"填 0 表示不检查;老系统这段校验是被注释掉的,实际从不生效。",
|
||
),
|
||
)
|
||
|
||
SPECS_BY_ATTR: dict[str, RuleSpec] = {spec.attr: spec for spec in RULE_SPECS}
|
||
SPECS_BY_CODE: dict[str, RuleSpec] = {spec.code: spec for spec in RULE_SPECS}
|
||
RULE_CODES: tuple[str, ...] = tuple(spec.code for spec in RULE_SPECS)
|
||
|
||
#: 当前生效的口径。整个进程只有这一个对象,apply() 原地改它。
|
||
RULES = CalcRules()
|
||
#: 每条规则当前的来源:config(库里的值)/ default(代码默认值)
|
||
SOURCES: dict[str, str] = {spec.attr: "default" for spec in RULE_SPECS}
|
||
|
||
|
||
def format_value(spec: RuleSpec, value: Any) -> str:
|
||
"""字段值 -> 存进 system_config / 给前端的字符串。
|
||
|
||
浮点走 :class:`~decimal.Decimal` 而不是 ``%g``:``%g`` 只留 6 位有效数字,
|
||
会把 12.345678 悄悄印成 12.3457,而这是要显示给财务看的"当前生效值"。
|
||
"""
|
||
if isinstance(value, bool):
|
||
return "true" if value else "false"
|
||
if isinstance(value, float):
|
||
return f"{Decimal(str(value)).normalize():f}"
|
||
return str(value)
|
||
|
||
|
||
def spec_for(code: str) -> RuleSpec | None:
|
||
return SPECS_BY_CODE.get((code or "").strip())
|
||
|
||
|
||
def normalize(spec: RuleSpec, raw: object) -> str:
|
||
"""把界面上填的东西折成规范字符串;不合法直接 ValueError(中文,能直接回给用户)。
|
||
|
||
这里严格,:func:`apply` 宽松:库里躺着一条脏值不该让整条计算链崩掉,
|
||
但人在界面上存一条脏值必须当场被怼回去。
|
||
"""
|
||
text = str(raw).strip() if raw is not None else ""
|
||
if spec.kind == "bool":
|
||
lowered = text.lower()
|
||
if lowered in BOOL_TRUE:
|
||
return "true"
|
||
if lowered in BOOL_FALSE:
|
||
return "false"
|
||
raise ValueError(f"{spec.name}只能是「是」或「否」")
|
||
if spec.kind == "int":
|
||
try:
|
||
number = int(text)
|
||
except (TypeError, ValueError):
|
||
raise ValueError(f"{spec.name}必须是整数") from None
|
||
_check_range(spec, number)
|
||
return str(number)
|
||
if spec.kind == "decimal":
|
||
try:
|
||
number = Decimal(text)
|
||
except (InvalidOperation, ValueError, TypeError):
|
||
raise ValueError(f"{spec.name}必须是数字") from None
|
||
if not number.is_finite():
|
||
raise ValueError(f"{spec.name}必须是有限数字")
|
||
_check_range(spec, number)
|
||
return f"{number.normalize():f}"
|
||
if spec.kind == "enum":
|
||
allowed = {choice.value.lower(): choice.value for choice in spec.choices}
|
||
if text.lower() not in allowed:
|
||
raise ValueError(f"{spec.name}只能是:{' / '.join(c.value for c in spec.choices)}")
|
||
return allowed[text.lower()]
|
||
if not text:
|
||
raise ValueError(f"{spec.name}不能为空")
|
||
if len(text) > 64:
|
||
raise ValueError(f"{spec.name}过长(最多 64 个字符)")
|
||
return text
|
||
|
||
|
||
def _check_range(spec: RuleSpec, number: Decimal | int) -> None:
|
||
if spec.minimum is not None and number < Decimal(str(spec.minimum)):
|
||
raise ValueError(f"{spec.name}不能小于 {spec.minimum:g}")
|
||
if spec.maximum is not None and number > Decimal(str(spec.maximum)):
|
||
raise ValueError(f"{spec.name}不能大于 {spec.maximum:g}")
|
||
|
||
|
||
def parse(spec: RuleSpec, text: str) -> Any:
|
||
"""规范字符串 -> 字段值。"""
|
||
if spec.kind == "bool":
|
||
return text.lower() in BOOL_TRUE
|
||
if spec.kind == "int":
|
||
return int(text)
|
||
if spec.kind == "decimal":
|
||
return float(Decimal(text))
|
||
return text
|
||
|
||
|
||
def apply(values: Mapping[str, object]) -> CalcRules:
|
||
"""把 system_config 里的原始值灌进 :data:`RULES`(原地改,不换新对象)。
|
||
|
||
认不出来或校验不过的键跳过并留一条 warning——库里躺着脏值时口径退回默认,
|
||
但绝不停掉试算。
|
||
"""
|
||
for spec in RULE_SPECS:
|
||
if spec.code not in values:
|
||
SOURCES[spec.attr] = "default"
|
||
continue
|
||
raw = values[spec.code]
|
||
try:
|
||
text = normalize(spec, raw)
|
||
except ValueError as exc:
|
||
SOURCES[spec.attr] = "default"
|
||
setattr(RULES, spec.attr, spec.default)
|
||
logger.warning("计算口径 %s 的取值 %r 不合法(%s),本条退回默认 %s",
|
||
spec.code, raw, exc, spec.default_text)
|
||
continue
|
||
setattr(RULES, spec.attr, parse(spec, text))
|
||
SOURCES[spec.attr] = "config"
|
||
return RULES
|
||
|
||
|
||
def reset_to_defaults() -> CalcRules:
|
||
"""退回代码默认口径(库连不上时的兜底,也是单用例之间的清场)。"""
|
||
defaults = CalcRules()
|
||
for f in fields(RULES):
|
||
setattr(RULES, f.name, getattr(defaults, f.name))
|
||
for spec in RULE_SPECS:
|
||
SOURCES[spec.attr] = "default"
|
||
return RULES
|
||
|
||
|
||
def reload(db: Any) -> CalcRules:
|
||
"""从库里把口径读回来。``db`` 是一个 SQLAlchemy Session。"""
|
||
return apply(read(db))
|
||
|
||
|
||
def read(db: Any) -> dict[str, str]:
|
||
"""读回 ``{参数编码: 原始字符串}``;一条都没有时返回空字典(口径退回默认)。"""
|
||
from sqlalchemy import select
|
||
|
||
from ...models import SystemConfig # 延迟导入:计算内核平时不碰 ORM
|
||
|
||
rows = db.execute(select(SystemConfig).where(SystemConfig.code.in_(RULE_CODES))).scalars().all()
|
||
return {row.code: str(row.value) for row in rows}
|
||
|
||
|
||
def seed_rows() -> list[tuple[str, str, str, str, str, str]]:
|
||
"""给 seed 用的参数行,形状跟 ``seed.CONFIGS`` 一致。"""
|
||
return [(spec.code, spec.name, spec.default_text, spec.value_type, RULE_GROUP, spec.remark)
|
||
for spec in RULE_SPECS]
|
||
|
||
|
||
def is_rule_code(code: str) -> bool:
|
||
return spec_for(code) is not None
|
||
|
||
|
||
def changed_count() -> int:
|
||
"""有多少条口径被改成跟推荐口径不一样。页面和启动日志都要这句实话。"""
|
||
return sum(1 for spec in RULE_SPECS
|
||
if SOURCES[spec.attr] == "config"
|
||
and format_value(spec, getattr(RULES, spec.attr)) != spec.default_text)
|
||
|
||
|
||
def view(db: Any) -> dict[str, Any]:
|
||
"""页面要的一切:段落、每条的当前值 / 默认值 / 库里存的原样。
|
||
|
||
进来先 reload 一次——另一个 worker 刚存过、或 DBA 直接改了库,页面都得说实话。
|
||
"""
|
||
stored = read(db)
|
||
apply(stored)
|
||
sections: list[dict[str, Any]] = []
|
||
for key, title, hint in RULE_SECTIONS:
|
||
items = []
|
||
for spec in RULE_SPECS:
|
||
if spec.section != key:
|
||
continue
|
||
effective = format_value(spec, getattr(RULES, spec.attr))
|
||
items.append({
|
||
"code": spec.code,
|
||
"key": spec.attr,
|
||
"name": spec.name,
|
||
"kind": spec.kind,
|
||
"valueType": spec.value_type,
|
||
"unit": spec.unit,
|
||
"step": spec.step or ("1" if spec.kind == "int" else "0.01"),
|
||
"min": spec.minimum,
|
||
"max": spec.maximum,
|
||
"choices": [{"value": choice.value, "label": choice.label} for choice in spec.choices],
|
||
"remark": spec.remark,
|
||
"value": effective,
|
||
"default": spec.default_text,
|
||
"stored": stored.get(spec.code, spec.default_text),
|
||
"configured": spec.code in stored,
|
||
# 库里存的原样跟生效值不一样 = 存进了非法值被退回默认,页面上得看得出来
|
||
"normalized": spec.code in stored and stored[spec.code] != effective,
|
||
})
|
||
sections.append({"key": key, "title": title, "hint": hint, "rules": items})
|
||
return {
|
||
"group": RULE_GROUP,
|
||
"version": RULES.version,
|
||
"sections": sections,
|
||
# 库里改过、而且跟推荐口径不一样的条数:页面据此提示"当前不是默认口径"
|
||
"changed": changed_count(),
|
||
"seeded": sum(1 for code in RULE_CODES if code in stored),
|
||
}
|
||
|
||
|
||
@contextmanager
|
||
def override(**values: object) -> Iterator[CalcRules]:
|
||
"""临时改口径,退出时还原。给用例和双跑对账脚本用,别在业务代码里调。
|
||
|
||
``with override(profit_other_cost_in_gross=False):`` 这种写法不用自己记 original。
|
||
"""
|
||
unknown = sorted(key for key in values if key not in SPECS_BY_ATTR)
|
||
if unknown:
|
||
raise KeyError(f"没有这条计算口径:{'、'.join(unknown)}")
|
||
spec_by_attr = SPECS_BY_ATTR
|
||
before = {attr: getattr(RULES, attr) for attr in values}
|
||
before_source = {attr: SOURCES.get(attr, "default") for attr in values}
|
||
try:
|
||
for attr, raw in values.items():
|
||
spec = spec_by_attr[attr]
|
||
setattr(RULES, attr, parse(spec, normalize(spec, raw)))
|
||
SOURCES[attr] = "override"
|
||
yield RULES
|
||
finally:
|
||
for attr, value in before.items():
|
||
setattr(RULES, attr, value)
|
||
SOURCES[attr] = before_source[attr]
|
||
|
||
|
||
def as_dict() -> dict[str, Any]:
|
||
"""当前生效口径的扁平字典(诊断与日志用)。"""
|
||
return {spec.attr: getattr(RULES, spec.attr) for spec in RULE_SPECS}
|
||
|
||
|
||
def describe(values: Iterable[str] | None = None) -> str:
|
||
"""一行话把口径说清楚,启动日志与快照留痕用。"""
|
||
wanted = list(values or ()) or [spec.attr for spec in RULE_SPECS]
|
||
return " ".join(f"{attr}={getattr(RULES, attr)}" for attr in wanted)
|