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

448 lines
17 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.

"""把明细行算成一份完整快照。
这是唯一的计算入口:概算、预算、审批、导出、预览都调这里,算完落成
``calc_snapshot`` 并把投影写回 ``project``(``TO-BE-ARCH-001`` / ``TO-BE-ARCH-003``)。
输出 JSON 的形状就是前端"预算信息"页签要显示的结构,因此前端不需要再算一遍。
"""
from __future__ import annotations
from dataclasses import dataclass
from decimal import Decimal
from functools import partial
from typing import Any, Iterable, Sequence
from . import fund_plan, profit, tax, validate
from .mapping import INCOME_TYPE_TO_KEY, PRODUCT_CATEGORY_TO_FIELD, PURCHASE_TYPE_TO_KEY
from .money import ZERO, money_str, round_money, to_dec
from .rules import RULES
def calc_version() -> str:
"""当前生效的计算口径版本。界面上能改,所以每次取都现读,不在导入时抄一份。"""
return RULES.version
@dataclass
class Line:
"""从 ORM 行折出来的通用输入,避免计算器依赖 SQLAlchemy 对象。"""
income_type: int = 0
purchase_type: int = 0
include_amount: Decimal = ZERO
qty: Decimal = ZERO
unit_price: Decimal = ZERO
tax_rate: Decimal = ZERO
exclude_amount: Decimal = ZERO
total: Decimal | None = None
item_code: str = ""
counts_to_travel_limit: bool = False
product_category: str = ""
bucket: str = ""
manual: bool = True
purchase_type_extra: int = 0
is_earnest: bool = False
raw: dict[str, Any] | None = None
def _as_line(row: Any) -> Line:
"""ORM 行或 dict 都能吃。"""
get = partial(_value_of, row)
return Line(
income_type=int(get("income_type") or 0),
purchase_type=int(get("purchase_type") or 0),
include_amount=get("include_amount"),
qty=to_dec(get("qty")),
unit_price=to_dec(get("unit_price")),
tax_rate=to_dec(get("tax_rate")),
exclude_amount=to_dec(get("exclude_amount")),
total=get("total"),
item_code=str(get("item_code") or ""),
counts_to_travel_limit=bool(get("counts_to_travel_limit") or False),
product_category=str(get("product_category") or ""),
bucket=str(get("bucket") or ""),
manual=bool(get("manual") if get("manual") is not None else True),
is_earnest=bool(get("is_earnest") or False),
raw=row if isinstance(row, dict) else None,
)
def _price_tax_total(lines: Sequence[Line], *, exclude_of_manual_line: bool = False) -> dict[str, Any]:
"""按"人工含税优先 → 数量×单价 → 价内税拆分"汇总一组明细。"""
results = [tax.line(item.include_amount, item.qty, item.unit_price, item.tax_rate) for item in lines]
include = sum((item.include for item in results), ZERO)
exclude = sum((item.exclude for item in results), ZERO)
tax_total = sum((item.tax for item in results), ZERO)
return {
"count": len(results),
"include": money_str(round_money(include)),
"exclude": money_str(round_money(exclude)),
"tax": money_str(round_money(tax_total)),
"_include": round_money(include),
"_exclude": round_money(exclude),
}
def group_income(lines: Iterable[Line]) -> dict[str, dict[str, Any]]:
"""收入按 设备/工程/服务 三类汇总(``BUD-INC-001``)。"""
buckets: dict[str, list[Line]] = {key: [] for key in INCOME_TYPE_TO_KEY.values()}
for row in lines:
key = INCOME_TYPE_TO_KEY.get(int(row.income_type or 0))
if key:
buckets[key].append(row)
return {key: _price_tax_total(items) for key, items in buckets.items()}
def group_purchase(lines: Iterable[Line]) -> dict[str, dict[str, Any]]:
"""采购按 设备/施工/服务/其他 四类汇总(``BUD-COST-001``)。"""
buckets: dict[str, list[Line]] = {key: [] for key in PURCHASE_TYPE_TO_KEY.values()}
for row in lines:
key = PURCHASE_TYPE_TO_KEY.get(int(row.purchase_type or 0))
if key:
buckets[key].append(row)
return {key: _price_tax_total(items) for key, items in buckets.items()}
def group_product_category(lines: Iterable[Line]) -> dict[str, str]:
"""按产品归属聚合到汇智/华智/华三/紫光其他(``BUD-COST-002``)。"""
totals: dict[str, Decimal] = {field: ZERO for field in PRODUCT_CATEGORY_TO_FIELD.values()}
for row in lines:
field = PRODUCT_CATEGORY_TO_FIELD.get(row.product_category)
if not field:
continue
totals[field] += to_dec(row.include_amount) or round_money(to_dec(row.qty) * to_dec(row.unit_price))
return {field: money_str(round_money(value)) for field, value in totals.items()}
def manage_total(lines: Sequence[Line]) -> tuple[Decimal, Decimal]:
"""项目管理费用总额,以及其中计入差旅/业务费限额的部分(``BUD-VAL-001`` 的左值)。
``BUD-PM-001``:人工总额优先,否则 数量×单价;项目管理成本视为不含税。
"""
total = ZERO
travel = ZERO
for row in lines:
if row.total is not None and str(row.total).strip() != "":
value = round_money(row.total)
else:
value = round_money(to_dec(row.qty) * to_dec(row.unit_price))
total += value
if row.counts_to_travel_limit:
travel += value
return round_money(total), round_money(travel)
def other_lines_total(lines: Sequence[Line], bucket: str) -> Decimal:
return round_money(sum((to_dec(row.exclude_amount) for row in lines if row.bucket == bucket), ZERO))
def company_manage_manual(lines: Sequence[Line]) -> Decimal | None:
"""概算里人工填的公司管理费用;没有人工行就返回 None 让利润层按费率派生。"""
for row in lines:
if row.bucket == "company_manage" and row.manual:
return to_dec(row.exclude_amount)
return None
def estimate_payload(
*,
income_lines: Sequence[Any],
cost_lines: Sequence[Any],
other_lines: Sequence[Any],
) -> dict[str, Any]:
"""概算快照。与预算共用同一个利润内核(``EST-003`` 说明老系统就是这么复用的)。"""
incomes = [_as_line(row) for row in income_lines]
purchases = [_as_line(row) for row in cost_lines]
others = [_as_line(row) for row in other_lines]
income_group = group_income(incomes)
purchase_group = group_purchase(purchases)
manage, travel = manage_total([row for row in others if row.bucket == "project_manage"])
other_cost = other_lines_total(others, "other_cost")
finance = other_lines_total(others, "capital_interest")
result = profit.calculate(
profit.ProfitInput(
income_device=_ex(income_group, "device"),
income_engineering=_ex(income_group, "engineering"),
income_service=_ex(income_group, "service"),
purchase_device=_ex(purchase_group, "device"),
purchase_construction=_ex(purchase_group, "construction"),
purchase_service=_ex(purchase_group, "service"),
purchase_other=_ex(purchase_group, "other"),
project_manage=manage,
other_cost=other_cost,
finance_cost=finance,
company_manage=company_manage_manual(others),
)
)
return {
"calc_version": calc_version(),
"groups": {
"income": {k: _public(v) for k, v in income_group.items()},
"purchase": {k: _public(v) for k, v in purchase_group.items()},
},
"product_amounts": group_product_category(purchases),
"manage": {"total": money_str(manage), "travel_business": money_str(travel)},
"other_cost": money_str(other_cost),
"finance_cost": money_str(finance),
"profit": result.to_dict(),
}
def budget_payload(
*,
income_lines: Sequence[Any],
purchase_lines: Sequence[Any],
manage_lines: Sequence[Any],
other_cost_lines: Sequence[Any] = (),
pay_plan_lines: Sequence[Any] = (),
income_plan_lines: Sequence[Any] = (),
fund_months: Sequence[Any] = (),
annual_rate: Decimal = ZERO,
plan_start: str = "",
plan_end: str = "",
income_tax: Decimal = ZERO,
) -> dict[str, Any]:
"""预算快照:八个页签要显示的东西一次算完。"""
incomes = [_as_line(row) for row in income_lines]
purchases = [_as_line(row) for row in purchase_lines]
manages = [_as_line(row) for row in manage_lines]
other_costs = [_as_line(row) for row in other_cost_lines]
income_group = group_income(incomes)
purchase_group = group_purchase(purchases)
manage_sum, travel_business = manage_total(manages)
other_cost = round_money(sum((to_dec(row.exclude_amount) for row in other_costs), ZERO))
# 资金计划:没录入月份时按收付款计划自动推导(TO-BE-PLAN-001 的"付款计划变了就整条重算")
months = [_as_fund_month(row, annual_rate) for row in fund_months]
if not months:
derived = fund_plan.derive_months(
[_plan_dict(row, "pay") for row in pay_plan_lines],
[_plan_dict(row, "receive") for row in income_plan_lines],
[_manage_dict(row) for row in manage_lines],
months=[],
annual_rate=to_dec(annual_rate),
)
months = derived
plan = fund_plan.calculate(months)
result = profit.calculate(
profit.ProfitInput(
income_device=_ex(income_group, "device"),
income_engineering=_ex(income_group, "engineering"),
income_service=_ex(income_group, "service"),
purchase_device=_ex(purchase_group, "device"),
purchase_construction=_ex(purchase_group, "construction"),
purchase_service=_ex(purchase_group, "service"),
purchase_other=_ex(purchase_group, "other"),
project_manage=manage_sum,
other_cost=other_cost,
finance_cost=plan.finance_cost,
company_manage=None,
income_tax=to_dec(income_tax),
)
)
report = validate.ValidationReport()
v = build_validations(
report,
result=result,
manage_total=manage_sum,
travel_business=travel_business,
purchase_group=purchase_group,
pay_plan_lines=pay_plan_lines,
plan=plan,
other_cost=other_cost,
income_group=income_group,
income_plan_lines=income_plan_lines,
months=[m.month for m in plan.months],
plan_start=plan_start,
plan_end=plan_end,
)
return {
"calc_version": calc_version(),
"groups": {
"income": {k: _public(x) for k, x in income_group.items()},
"purchase": {k: _public(x) for k, x in purchase_group.items()},
},
"product_amounts": group_product_category(purchases),
"manage": {"total": money_str(manage_sum), "travel_business": money_str(travel_business)},
"other_cost": money_str(other_cost),
"contract_amount": _include_all(income_group),
"fund_plan": plan.to_dict(),
"profit": result.to_dict(),
"validation": v.to_dict(),
}
def build_validations(
report: validate.ValidationReport,
*,
result: profit.ProfitResult,
manage_total: Decimal,
travel_business: Decimal,
purchase_group: dict[str, dict[str, Any]],
pay_plan_lines: Sequence[Any],
plan: fund_plan.FundPlanResult,
other_cost: Decimal,
income_group: dict[str, dict[str, Any]],
income_plan_lines: Sequence[Any] = (),
months: Sequence[str],
plan_start: str,
plan_end: str,
) -> validate.ValidationReport:
"""跑一遍所有结果校验。"""
validate.check_travel_limit(report, result.gross_a, manage_total, travel_business)
validate.check_contribution_rate(report, result.contribution_rate)
pay_by_type: dict[int, Decimal] = {}
for row in pay_plan_lines or []:
if _flag_of(row, "is_earnest"):
continue
code = int(_value_of(row, "purchase_type") or 0)
pay_by_type[code] = pay_by_type.get(code, ZERO) + _amount_of(row)
purchase_by_type = {
1: _inc(purchase_group, "device"),
2: _inc(purchase_group, "construction"),
3: _inc(purchase_group, "service"),
4: _inc(purchase_group, "other"),
}
# 只有真的录了付款计划才做勾稽,否则一进来就满屏报错,业务不会认这个体验
if pay_by_type:
validate.check_pay_plan_reconciles(report, pay_by_type, purchase_by_type)
purchase_include_total = round_money(sum(purchase_by_type.values()))
earnest_cost_total = round_money(sum(
_amount_of(row) for row in (pay_plan_lines or []) if _flag_of(row, "is_earnest")
))
earnest_income_total = round_money(sum(
_amount_of(row) for row in (income_plan_lines or []) if _flag_of(row, "is_earnest")
))
validate.check_fund_plan_totals(
report,
fund_cost_total=plan.total_cost,
fund_income_total=plan.total_income,
purchase_include_total=purchase_include_total,
earnest_cost_total=earnest_cost_total,
manage_total=manage_total,
income_include_total=_include_all_decimal(income_group),
earnest_income_total=earnest_income_total,
)
validate.check_fund_months(report, list(months), plan_start, plan_end)
return report
def _as_fund_month(row: Any, annual_rate: Decimal) -> fund_plan.FundMonthInput:
get = partial(_value_of, row)
return fund_plan.FundMonthInput(
month=str(get("month") or ""),
device_cost=to_dec(get("device_cost")),
construction_cost=to_dec(get("construction_cost")),
service_cost=to_dec(get("service_cost")),
other_cost=to_dec(get("other_cost")),
manage_cost=to_dec(get("manage_cost")),
earnest_cost=to_dec(get("earnest_cost")),
sale_income=to_dec(get("sale_income")),
earnest_income=to_dec(get("earnest_income")),
interest_rate=to_dec(get("interest_rate")) or to_dec(annual_rate),
opening_balance=to_dec(get("opening_balance")),
)
def _plan_dict(row: Any, kind: str) -> dict[str, Any]:
get = partial(_value_of, row)
# 收款计划用 receive_date、付款计划用 pay_date,老库里两张表字段名不同;
# 两边都接受任一种写法,迁移与前端两种 payload 都能喂进来。
pay_at = get("pay_date") or get("pay_time")
receive_at = get("receive_date") or get("receive_time") or pay_at
return {
"pay_date": pay_at,
"receive_date": receive_at,
"amount": get("amount"),
"purchase_type": get("purchase_type"),
"is_earnest": get("is_earnest"),
}
def _value_of(row: Any, key: str, default: Any = None) -> Any:
"""ORM 行与 dict 通吃的取值。"""
if isinstance(row, dict):
return row.get(key, default)
return getattr(row, key, default)
def _amount_of(row: Any) -> Decimal:
return to_dec(_value_of(row, "amount"))
def _flag_of(row: Any, key: str) -> bool:
return bool(_value_of(row, key) or False)
def _manage_dict(row: Any) -> dict[str, Any]:
"""项目管理费用行 -> 资金计划输入。没录支出时间时退回按总额计。"""
return {
"pay_date": _value_of(row, "pay_date") or _value_of(row, "pay_time"),
"pay_amount": _value_of(row, "pay_amount") or _value_of(row, "total"),
"total": _value_of(row, "total"),
}
def _public(block: dict[str, Any]) -> dict[str, Any]:
"""去掉内部键,只留对外字段。"""
return {k: v for k, v in block.items() if not k.startswith("_")}
def _ex(groups: dict[str, dict[str, Any]], key: str) -> Decimal:
return to_dec(groups.get(key, {}).get("_exclude"))
def _inc(groups: dict[str, dict[str, Any]], key: str) -> Decimal:
return to_dec(groups.get(key, {}).get("_include"))
def _include_all(groups: dict[str, dict[str, Any]]) -> str:
return money_str(_include_all_decimal(groups))
def _include_all_decimal(groups: dict[str, dict[str, Any]]) -> Decimal:
return round_money(sum((_inc(groups, key) for key in INCOME_TYPE_TO_KEY.values()), ZERO))
def project_projection(payload: dict[str, Any]) -> dict[str, Any]:
"""从快照抽出要写回 ``project`` 的投影列。"""
profit_block = payload.get("profit") or {}
fund = payload.get("fund_plan") or {}
products = payload.get("product_amounts") or {}
def dec(value: object) -> Decimal:
return to_dec(value)
rate = lambda key: _rate_of(profit_block, key) # noqa: E731
return {
"contract_amount": dec(payload.get("contract_amount") or profit_block.get("income_total")),
"gross_profit_a": dec(profit_block.get("gross_a")),
"gross_profit_a_rate": rate("gross_a_rate"),
"gross_profit": dec(profit_block.get("gross_b")),
"gross_profit_rate": rate("gross_b_rate"),
"contribution_profit": dec(profit_block.get("contribution")),
"contribution_profit_rate": rate("contribution_rate"),
"advance_plan_total": dec(fund.get("underwritten_total")),
"advance_interest_amount": dec(fund.get("interest_total")),
"advance_peak_month": str(fund.get("peak_month") or ""),
"advance_peak_value": dec(fund.get("peak_value")),
"calc_version": payload.get("calc_version") or calc_version(),
**{key: dec(value) for key, value in products.items()},
}
def _rate_of(profit_block: dict[str, Any], key: str) -> Decimal:
block = profit_block.get(key) or {}
value = block.get("value")
return to_dec(value) if value is not None else ZERO