feat(calc): 二次分摊拆行与 #12 单笔侧开关——按方案比例拆给参与人、余额归负责人
- _personal_rate 的 TPL_MANAGER_SHARE 分支读 manager.personal.included:1=按业务员递减公式计提,0=单笔落 0(现状) - _load_allocations 装载生效方案并防御拦截(合计超 100%、参与人含负责人) - _persist_ledger 拆行落库:参与人=份额×比例(q2)、负责人=q2 全额−已分累计(行合计守恒防分漂);快照带 alloc_plan/alloc_role/alloc_ratio - _prepare_mode 重算改 list_active_by_receipt 作废全部拆分行;uk 三列版支持同回款按人多行 - business_service 保存侧同口径校验(超 100% 400、负责人自分 400、hint 文案定稿) - 集成用例 +5(拆行守恒/叠加进度登记/重算全作废/双拦截)+保存侧 3 条 Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
1 parent
48c0a86279
commit
ccfd20651b
5 files changed
+479
-58
No files matched your search
@@ -6,9 +6,13 @@
|
||||
按行汇总,对照表 #14)。两者的任何口径修改必须同步——预览给业务对数、
|
||||
核算才是算钱的法定固化点。
|
||||
|
||||
策略点(待业务答复,全部集中为单函数,答复后只改函数 + 按回款批量重算):
|
||||
- ``_personal_rate``:#12 经理个人户单笔落台账 rate=0/绩效 0(12.5%+5%
|
||||
聚合口径在月结时由 manager_team_share 计算);#20 在 ``_row_profit``
|
||||
策略点(业务答复 2026-10-19 已回填,后续调整仍集中在对应函数 + 按回款批量重算):
|
||||
- ``_personal_rate``:#12 经理个人户单笔由参数 manager.personal.included
|
||||
分流——0=单笔落 0(聚合口径在月结时由 manager_team_share 计算)、
|
||||
1=按业务员递减公式计提;#20 在 ``_row_profit``(暂按不含税原样相减)
|
||||
- 二次分摊(澄清 #1 答复「分配绩效」,算后分):``_load_allocations``
|
||||
读生效方案,``_persist_ledger`` 按比例拆行(参与人份额 + 负责人余额,
|
||||
行合计守恒);#2 余额归负责人、#3 二次分配即协助场景的核算载体
|
||||
- 核算粒度 #25:业务级一次性计提——首个触发核算的回款计算全额应发,
|
||||
后续回款仅置 settlement_status=1(repeated=True),不重复计提
|
||||
"""
|
||||
@@ -29,6 +33,7 @@ from app.models import (
|
||||
BusinessItem,
|
||||
Customer,
|
||||
PerformanceLedger,
|
||||
Personnel,
|
||||
Receipt,
|
||||
Shipment,
|
||||
User,
|
||||
@@ -54,8 +59,8 @@ from app.services.param_service import parse_fraction, resolve_snapshot
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# snapshot_json 里的策略点注记(答复回填时的检索锚点)
|
||||
_NOTE_MANAGER_PENDING = "经理个人户单笔不计提(#12 待答复):聚合口径在月结时由团队聚合计算"
|
||||
# snapshot_json 里的策略点注记(口径检索锚点;#12 已参数化,开关 0 时留此注记)
|
||||
_NOTE_MANAGER_PENDING = "经理个人户单笔不计提(基数开关=0):聚合口径在月结时由团队聚合计算"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -115,31 +120,34 @@ def calc_receipt(
|
||||
person = _load_person(session, business)
|
||||
snapshot = resolve_snapshot(session, receipt.receipt_date)
|
||||
items = _load_items(session, business)
|
||||
allocations = _load_allocations(session, business, person.id)
|
||||
|
||||
conversion = _convert_items(snapshot, person, items)
|
||||
amounts = _compose_amounts(
|
||||
session, snapshot, person, business, receipt, shipment, conversion
|
||||
)
|
||||
row = _persist_ledger(
|
||||
rows = _persist_ledger(
|
||||
session,
|
||||
receipt=receipt,
|
||||
business=business,
|
||||
person=person,
|
||||
shipment=shipment,
|
||||
items=items,
|
||||
allocations=allocations,
|
||||
conversion=conversion,
|
||||
amounts=amounts,
|
||||
recalc_reason=recalc_reason,
|
||||
is_recalc=is_recalc,
|
||||
)
|
||||
session.flush()
|
||||
out = CalcReceiptOut(ledger=_to_out(row), repeated=False)
|
||||
out = CalcReceiptOut(ledger=_to_out(rows.owner_row), repeated=False)
|
||||
session.commit()
|
||||
logger.info(
|
||||
"核算完成 | receipt=%s | ledger=%s | payable=%s",
|
||||
"核算完成 | receipt=%s | ledger=%s | payable=%s | 分摊行=%s",
|
||||
receipt_id,
|
||||
row.id,
|
||||
rows.owner_row.id,
|
||||
amounts.payable,
|
||||
len(rows.share_rows),
|
||||
)
|
||||
return out
|
||||
|
||||
@@ -184,10 +192,12 @@ def _prepare_mode(
|
||||
# 以后)——本无独立计提,继续重算会凭空落一行生效行,同业务出现
|
||||
# 两行生效行导致双重计提 → 一律 400
|
||||
if is_recalc:
|
||||
old = performance_ledger_repository.get_active_by_receipt(session, receipt.id)
|
||||
if old is None:
|
||||
# 分摊拆行后旧版本可能多行(负责人+参与人)——全部作废再落新版本
|
||||
olds = performance_ledger_repository.list_active_by_receipt(session, receipt.id)
|
||||
if not olds:
|
||||
raise BadRequestError("该回款为进度登记(业务已按一次性计提核算),无独立台账行可重算")
|
||||
performance_ledger_repository.mark_inactive(session, old)
|
||||
for old in olds:
|
||||
performance_ledger_repository.mark_inactive(session, old)
|
||||
return None
|
||||
|
||||
# 核算粒度 #25(一期口径,仅首算模式):业务级一次性计提——已有生效
|
||||
@@ -231,6 +241,27 @@ def _load_items(session: Session, business: Business) -> list[BusinessItem]:
|
||||
return items
|
||||
|
||||
|
||||
def _load_allocations(session: Session, business: Business, owner_id: int) -> list:
|
||||
"""业务生效的二次分配方案(澄清 #1 答复 2026-10-19:分配绩效——算后分)。
|
||||
|
||||
校验双保险之一(保存侧在 business_service):比例合计 >100% 会把负责人
|
||||
份额算成负数(多算参与人绩效);合同负责人不可出现在参与人列表(自分
|
||||
份额会双重计入)。无方案返回空列表 = 全额归负责人。
|
||||
"""
|
||||
allocations = business_repository.list_allocations(session, business.id)
|
||||
if not allocations:
|
||||
return []
|
||||
total = sum((a.ratio for a in allocations), Decimal("0"))
|
||||
if total > Decimal("100"):
|
||||
raise BadRequestError(
|
||||
f"二次分配比例合计 {total.quantize(Decimal('0.01'))}% 超过 100%,"
|
||||
"无法核算(先调整方案比例)"
|
||||
)
|
||||
if any(a.personnel_id == owner_id for a in allocations):
|
||||
raise BadRequestError("二次分配参与人含合同负责营销人员,无法核算(先调整方案)")
|
||||
return list(allocations)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _Conversion:
|
||||
"""逐行折算结果(行级明细入台账快照,汇总值驱动计提与起付判定)。"""
|
||||
@@ -347,6 +378,14 @@ def _compose_amounts(
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _LedgerRows:
|
||||
"""拆行落库结果:负责人行恒存在(出参与 CAS 锚点),参与人份额行可空。"""
|
||||
|
||||
owner_row: PerformanceLedger
|
||||
share_rows: list[PerformanceLedger]
|
||||
|
||||
|
||||
def _persist_ledger(
|
||||
session: Session,
|
||||
*,
|
||||
@@ -355,14 +394,23 @@ def _persist_ledger(
|
||||
person,
|
||||
shipment: Shipment,
|
||||
items: list[BusinessItem],
|
||||
allocations: list,
|
||||
conversion: _Conversion,
|
||||
amounts: _Amounts,
|
||||
recalc_reason: str | None,
|
||||
is_recalc: bool,
|
||||
) -> PerformanceLedger:
|
||||
"""落台账行(版本号自增;金额两位 HALF_UP)+ 首算 CAS 置已核算。"""
|
||||
) -> _LedgerRows:
|
||||
"""落台账行(分摊拆行;版本号自增;金额两位 HALF_UP)+ 首算 CAS 置已核算。
|
||||
|
||||
分摊(澄清 #1 答复 2026-10-19「分配绩效」,算后分):业务级全额(含
|
||||
递减比例、抵顶、支付权重全环节)算完后按方案比例拆给参与人,余额归
|
||||
合同负责人。行合计与业务级全额**守恒**(负责人行取 q2 全额减参与人
|
||||
q2 份额的差额,防分漂);每行快照带完整方案快照,行级可独立回溯。
|
||||
参与人离职照分(历史方案事实,方案调整是业务侧责任——入职校验只在
|
||||
保存侧,核算侧只要求人员存在,FK RESTRICT 已保证)。
|
||||
"""
|
||||
receipt_date = receipt.receipt_date
|
||||
snapshot_json: dict[str, Any] = {
|
||||
base_snapshot: dict[str, Any] = {
|
||||
"params_as_of": str(receipt_date),
|
||||
"line_details": conversion.line_details,
|
||||
"start_payment_ok": amounts.start_ok,
|
||||
@@ -371,43 +419,100 @@ def _persist_ledger(
|
||||
"profit_total": str(conversion.total_profit),
|
||||
}
|
||||
if amounts.decision.manager_pending:
|
||||
snapshot_json["strategy_note"] = _NOTE_MANAGER_PENDING
|
||||
base_snapshot["strategy_note"] = _NOTE_MANAGER_PENDING
|
||||
if allocations:
|
||||
base_snapshot["alloc_plan"] = [
|
||||
{
|
||||
"personnel_id": a.personnel_id,
|
||||
"personnel_name": a.personnel_name,
|
||||
"ratio": str(a.ratio),
|
||||
}
|
||||
for a in allocations
|
||||
]
|
||||
|
||||
version = performance_ledger_repository.next_version(session, receipt.id)
|
||||
customer_type = _customer_type(session, business)
|
||||
category = _category_label(items)
|
||||
|
||||
# 份额清单:(person, ratio, tag)——ratio 为 None 时走余额公式(q2 全额
|
||||
# 减已分累计,守恒);负责人余额的百分数(100−∑参与人)仅作快照展示,
|
||||
# 不参与计算——按它乘全额会丢 q2 尾差(39.1111×30% ≠ 39.11−27.37)
|
||||
shares: list[tuple[Any, Decimal | None, str]] = []
|
||||
owner_ratio_text: str | None = None
|
||||
if not allocations:
|
||||
shares.append((person, None, "owner"))
|
||||
owner_ratio_text = "100"
|
||||
else:
|
||||
total_ratio = Decimal("0")
|
||||
for a in allocations:
|
||||
shares.append((session.get(Personnel, a.personnel_id), a.ratio, "participant"))
|
||||
total_ratio += a.ratio
|
||||
owner_ratio_text = str((Decimal("100") - total_ratio).quantize(Decimal("0.01")))
|
||||
shares.append((person, None, "owner"))
|
||||
|
||||
def _share(full: Decimal, ratio: Decimal | None, *, added: Decimal = Decimal("0")) -> Decimal:
|
||||
"""单份额金额:参与人 = 全额×比例(q2);负责人 = q2 全额 − 已分累计。"""
|
||||
if ratio is None:
|
||||
return _q2(full - added) or Decimal("0")
|
||||
# Fraction 乘积先 to_decimal 再 q2(Fraction 无 quantize,直接喂 _q2 会炸)
|
||||
return _q2(param_service.to_decimal(Fraction(full) * Fraction(ratio) / 100)) or Decimal("0")
|
||||
|
||||
added_perf = Decimal("0")
|
||||
added_conv = Decimal("0")
|
||||
added_pay = Decimal("0")
|
||||
owner_row: PerformanceLedger | None = None
|
||||
share_rows: list[PerformanceLedger] = []
|
||||
for target, ratio, tag in shares:
|
||||
perf = _share(amounts.performance, ratio, added=added_perf)
|
||||
conv = _share(amounts.converted, ratio, added=added_conv)
|
||||
pay = _share(amounts.payable, ratio, added=added_pay)
|
||||
added_perf += perf
|
||||
added_conv += conv
|
||||
added_pay += pay
|
||||
row = performance_ledger_repository.add(
|
||||
session,
|
||||
PerformanceLedger(
|
||||
receipt_id=receipt.id,
|
||||
calc_version=version,
|
||||
calc_type=CALC_TYPE_RECEIPT,
|
||||
business_id=business.id,
|
||||
business_no=business.business_no,
|
||||
personnel_id=target.id,
|
||||
personnel_name=target.personnel_name,
|
||||
role_code=role_code_of(target),
|
||||
customer_type=customer_type,
|
||||
product_category=category,
|
||||
ship_date=shipment.ship_date,
|
||||
receipt_date=receipt_date,
|
||||
payment_days=amounts.days,
|
||||
rate_text=str(amounts.decision.rate),
|
||||
converted_profit=conv,
|
||||
performance_amount=perf,
|
||||
barter_applied=1 if amounts.barter_applied else 0,
|
||||
weight_r=amounts.weight_r,
|
||||
payment_weight=param_service.to_decimal(amounts.weight),
|
||||
payable_amount=pay,
|
||||
settlement_month=receipt_date.strftime("%Y-%m"),
|
||||
is_probation=1 if target.is_probation == 1 else 0,
|
||||
missing_cost=1 if conversion.missing_cost else 0,
|
||||
snapshot_json={
|
||||
**base_snapshot,
|
||||
"alloc_role": tag,
|
||||
"alloc_ratio": owner_ratio_text if tag == "owner" else str(ratio),
|
||||
},
|
||||
calc_reason=recalc_reason,
|
||||
),
|
||||
)
|
||||
if tag == "owner":
|
||||
owner_row = row
|
||||
else:
|
||||
share_rows.append(row)
|
||||
|
||||
row = performance_ledger_repository.add(
|
||||
session,
|
||||
PerformanceLedger(
|
||||
receipt_id=receipt.id,
|
||||
calc_version=performance_ledger_repository.next_version(session, receipt.id),
|
||||
calc_type=CALC_TYPE_RECEIPT,
|
||||
business_id=business.id,
|
||||
business_no=business.business_no,
|
||||
personnel_id=person.id,
|
||||
personnel_name=person.personnel_name,
|
||||
role_code=role_code_of(person),
|
||||
customer_type=_customer_type(session, business),
|
||||
product_category=_category_label(items),
|
||||
ship_date=shipment.ship_date,
|
||||
receipt_date=receipt_date,
|
||||
payment_days=amounts.days,
|
||||
rate_text=str(amounts.decision.rate),
|
||||
converted_profit=_q2(amounts.converted),
|
||||
performance_amount=_q2(amounts.performance),
|
||||
barter_applied=1 if amounts.barter_applied else 0,
|
||||
weight_r=amounts.weight_r,
|
||||
payment_weight=param_service.to_decimal(amounts.weight),
|
||||
payable_amount=_q2(amounts.payable),
|
||||
settlement_month=receipt_date.strftime("%Y-%m"),
|
||||
is_probation=1 if person.is_probation == 1 else 0,
|
||||
missing_cost=1 if conversion.missing_cost else 0,
|
||||
snapshot_json=snapshot_json,
|
||||
calc_reason=recalc_reason,
|
||||
),
|
||||
)
|
||||
# CAS 仅首算执行:重算模式状态本就是已核算(UPDATE ... WHERE status=0
|
||||
# 会 rowcount=0 误报并发撞车)
|
||||
if not is_recalc:
|
||||
_mark_settled(session, receipt)
|
||||
return row
|
||||
return _LedgerRows(owner_row=owner_row, share_rows=share_rows)
|
||||
|
||||
|
||||
def _q2(value: Decimal | None) -> Decimal | None:
|
||||
@@ -443,12 +548,23 @@ def _personal_rate(
|
||||
|
||||
template = role.calc_template if role else "TPL_SALESPERSON_DECAY"
|
||||
if template == "TPL_MANAGER_SHARE":
|
||||
return _RateDecision(
|
||||
Decimal("0"),
|
||||
"经理个人户:12.5%+5% 聚合计提(月结时计算),单笔落 0",
|
||||
None,
|
||||
True,
|
||||
)
|
||||
# #12 答复(2026-10-19)参数化:manager.personal.included=1 时个人户
|
||||
# 单按业务员递减公式单笔计提(个人户单本质是正常业务,有发货/回款/
|
||||
# 毛利;聚合基数开关在 settlement_service 同参数消费)——0 时单笔落 0
|
||||
if snapshot.get("manager.personal.included") != "1":
|
||||
return _RateDecision(
|
||||
Decimal("0"),
|
||||
"经理个人户:12.5%+5% 聚合计提(月结时计算),单笔落 0",
|
||||
None,
|
||||
True,
|
||||
)
|
||||
start = parse_fraction(snapshot.get("salesperson.rate.start"))
|
||||
slope = parse_fraction(snapshot.get("salesperson.rate.slope"))
|
||||
floor = parse_fraction(snapshot.get("salesperson.rate.floor"))
|
||||
boundary = int(parse_fraction(snapshot.get("salesperson.days.boundary")))
|
||||
rate = salesperson_rate(days, start=start, slope=slope, floor=floor, boundary_days=boundary)
|
||||
note = f"经理个人户(基数开关=1):按业务员递减 {start}‰ 起,{days} 天"
|
||||
return _RateDecision(rate, note, None, False)
|
||||
if template == "TPL_INFO_SALES_FIXED":
|
||||
# 信息员基数=本人销售额(覆盖折算与阈值),‰ 换算同防线
|
||||
rate = parse_fraction(snapshot.get("info.rate")) / 1000
|
||||
|
||||
Reference in new issue
Block a user