366 lines
15 KiB
Python
366 lines
15 KiB
Python
"""
|
|
services/contract_payment/review_service.py
|
|
|
|
用途:把待确认合同的人工复核结果写入台账,使其可以进入付款预警。
|
|
依赖:ContractPaymentContract、ContractPaymentNode、ContractPaymentEvent、ValidationError。
|
|
逻辑:由 api/contract_payment 的 manual-review 路由调用。校验通过后覆盖四阶段节点,
|
|
合同改为 parsed / active;勾选无此阶段的节点状态为 not_applicable,扫描预警时会被跳过。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import date, datetime, time
|
|
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
|
|
from typing import Any
|
|
|
|
from app import db
|
|
from app.core.errors import NotFoundError, ValidationError
|
|
from app.models import ContractPaymentContract, ContractPaymentEvent, ContractPaymentNode
|
|
from app.services.contract_payment.erp_payment_service import normalize_purchase_order_no
|
|
|
|
_STAGE_TYPES = ("prepayment", "shipment", "acceptance", "warranty")
|
|
_DATE_REQUIRED = {"prepayment", "shipment"}
|
|
_PERCENT_SUM = Decimal("100")
|
|
_SUM_TOLERANCE = Decimal("0.001")
|
|
_AMOUNT_TOLERANCE = Decimal("0.02")
|
|
_MANUAL_ACCEPTANCE_PREFIX = "manual-review:"
|
|
|
|
|
|
def apply_manual_review(
|
|
contract_id: int,
|
|
payload: dict[str, Any],
|
|
*,
|
|
operator_id: int | None = None,
|
|
) -> ContractPaymentContract:
|
|
"""
|
|
用人工填写的金额、比例和日期依据确认一份合同,并放入合同台账。
|
|
|
|
核心逻辑:先完整校验再落库。启用阶段的比例不能留空,合计须为 100%,金额须等于合同金额乘比例。
|
|
预付款、出货款必须有日期依据;验收款、质保款日期可空。无此阶段写成 0 且不参与预警。
|
|
预付款日期写入节点,合同归档日写入 oa_archive_at,供首轮预警按归档日加 7 天计算。
|
|
|
|
Args:
|
|
contract_id: 合同台账主键。
|
|
payload: 采购单号、合同金额、可选合同编号、归档日,以及四个阶段。
|
|
operator_id: 当前操作人用户主键,写入复核审计;缺失时只记录复核事实。
|
|
|
|
Returns:
|
|
已提交并刷新后的合同记录。
|
|
|
|
Raises:
|
|
NotFoundError: 合同不存在。
|
|
ValidationError: 采购单号、金额、比例合计、金额核对或必填日期不满足进入台账的条件。
|
|
"""
|
|
contract = db.session.get(ContractPaymentContract, contract_id)
|
|
if contract is None:
|
|
raise NotFoundError("合同不存在")
|
|
# [STEP 1] 先把请求整理成可比较的数字和日期,失败时不改台账。
|
|
review = _normalize_review(contract, payload)
|
|
# [STEP 2] 主表进入台账。人工确认的金额允许覆盖原来的 0 或错误正数,这是复核本身的目的。
|
|
contract.purchase_order_no = review["purchase_order_no"]
|
|
contract.contract_no = review["contract_no"]
|
|
contract.total_amount = review["total_amount"]
|
|
if review["archive_date"] is not None:
|
|
contract.oa_archive_at = datetime.combine(review["archive_date"], time.min)
|
|
elif review["prepayment_date"] is not None:
|
|
contract.oa_archive_at = datetime.combine(review["prepayment_date"], time.min)
|
|
previous = dict(contract.parse_result_json or {})
|
|
contract.parse_result_json = {
|
|
**previous,
|
|
"status": "parsed",
|
|
"issues": [],
|
|
"manual_review": {
|
|
"operator_id": operator_id,
|
|
"reviewed_at": datetime.utcnow().replace(microsecond=0).isoformat() + "Z",
|
|
"previous_issues": list(previous.get("issues") or []),
|
|
},
|
|
}
|
|
contract.parse_status = "parsed"
|
|
contract.plan_status = "active"
|
|
kept_ids: set[int] = set()
|
|
for stage in review["stages"]:
|
|
node = _upsert_stage_node(contract, stage)
|
|
kept_ids.add(node.id)
|
|
if stage["node_type"] == "shipment" and not stage["skipped"] and stage["basis_date"] is not None:
|
|
contract.delivery_due_date = stage["basis_date"]
|
|
for stale in db.session.query(ContractPaymentNode).filter_by(contract_id=contract.id).all():
|
|
if stale.id in kept_ids:
|
|
continue
|
|
# 同类型重复节点或历史淘汰节点不再参与预警,避免复核后仍扫到旧阶段。
|
|
stale.amount = None
|
|
stale.percentage = None
|
|
stale.anchor_date = None
|
|
stale.due_date = None
|
|
stale.status = "not_applicable"
|
|
stale.evidence_json = {**(stale.evidence_json or {}), "manual_review": "未纳入本次复核"}
|
|
_sync_manual_acceptance_event(contract, review["acceptance_date"], operator_id=operator_id)
|
|
db.session.commit()
|
|
db.session.refresh(contract)
|
|
return contract
|
|
|
|
|
|
def _normalize_review(contract: ContractPaymentContract, payload: dict[str, Any]) -> dict[str, Any]:
|
|
"""
|
|
把复核请求整理成四个阶段的金额、比例和日期。
|
|
|
|
核心逻辑:启用阶段空比例不算 0;合计须为 100%;金额与合同金额乘比例的差额不超过 0.02。
|
|
合同编号留空时不覆盖成空字符串,以免撞上唯一约束。
|
|
|
|
Args:
|
|
contract: 当前合同,用于合同编号冲突检查。
|
|
payload: 原始 JSON。
|
|
|
|
Returns:
|
|
可直接落库的采购单号、金额、归档日和阶段列表。
|
|
|
|
Raises:
|
|
ValidationError: 任一进入台账的条件不满足。
|
|
"""
|
|
purchase_order_no = normalize_purchase_order_no(payload.get("purchase_order_no"))
|
|
if not purchase_order_no:
|
|
raise ValidationError("请填写采购单号")
|
|
if len(purchase_order_no) > 128:
|
|
raise ValidationError("采购单号过长")
|
|
total_amount = _parse_decimal(payload.get("total_amount"), "合同金额")
|
|
if total_amount is None or total_amount <= 0:
|
|
raise ValidationError("请填写大于 0 的合同金额")
|
|
total_amount = total_amount.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
|
|
|
contract_no = str(payload.get("contract_no") or "").strip() or None
|
|
if contract_no and len(contract_no) > 128:
|
|
raise ValidationError("合同编号过长")
|
|
if contract_no and contract_no != contract.contract_no:
|
|
conflict = db.session.query(ContractPaymentContract).filter(
|
|
ContractPaymentContract.contract_no == contract_no,
|
|
ContractPaymentContract.id != contract.id,
|
|
).first()
|
|
if conflict:
|
|
raise ValidationError("合同编号与另一条合同台账冲突")
|
|
|
|
raw_stages = payload.get("stages")
|
|
if not isinstance(raw_stages, list):
|
|
raise ValidationError("请提交四个付款阶段")
|
|
by_type: dict[str, dict[str, Any]] = {}
|
|
for item in raw_stages:
|
|
if not isinstance(item, dict):
|
|
raise ValidationError("付款阶段格式不正确")
|
|
node_type = str(item.get("node_type") or "").strip()
|
|
if node_type not in _STAGE_TYPES or node_type in by_type:
|
|
raise ValidationError("请提交预付款、出货款、验收款、质保款各一次")
|
|
by_type[node_type] = item
|
|
if set(by_type) != set(_STAGE_TYPES):
|
|
raise ValidationError("请提交预付款、出货款、验收款、质保款各一次")
|
|
|
|
stages: list[dict[str, Any]] = []
|
|
enabled_percent = Decimal("0")
|
|
enabled_count = 0
|
|
for node_type in _STAGE_TYPES:
|
|
item = by_type[node_type]
|
|
skipped = bool(item.get("skipped"))
|
|
if skipped:
|
|
stages.append({
|
|
"node_type": node_type,
|
|
"skipped": True,
|
|
"percentage": Decimal("0"),
|
|
"amount": Decimal("0.00"),
|
|
"basis_date": None,
|
|
})
|
|
continue
|
|
percentage = _parse_decimal(item.get("percentage"), f"{_stage_label(node_type)}比例")
|
|
amount = _parse_decimal(item.get("amount"), f"{_stage_label(node_type)}金额")
|
|
if percentage is None:
|
|
raise ValidationError("启用阶段的付款比例不能为空")
|
|
if percentage < 0 or percentage > _PERCENT_SUM:
|
|
raise ValidationError("启用阶段的付款比例须在 0 到 100 之间")
|
|
if amount is None:
|
|
raise ValidationError("启用阶段的金额不能为空")
|
|
percentage = percentage.quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP)
|
|
amount = amount.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
|
expected = (total_amount * percentage / _PERCENT_SUM).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
|
if abs(amount - expected) > _AMOUNT_TOLERANCE:
|
|
raise ValidationError("阶段金额须等于合同金额乘以比例")
|
|
basis_date = _parse_date(item.get("basis_date"), f"{_stage_label(node_type)}日期依据")
|
|
if node_type in _DATE_REQUIRED and basis_date is None:
|
|
raise ValidationError("预付款、出货款须填写日期依据")
|
|
enabled_percent += percentage
|
|
enabled_count += 1
|
|
stages.append({
|
|
"node_type": node_type,
|
|
"skipped": False,
|
|
"percentage": percentage,
|
|
"amount": amount,
|
|
"basis_date": basis_date,
|
|
})
|
|
if enabled_count == 0 or abs(enabled_percent - _PERCENT_SUM) > _SUM_TOLERANCE:
|
|
raise ValidationError("启用阶段的付款比例合计须为 100%")
|
|
|
|
prepayment = next(stage for stage in stages if stage["node_type"] == "prepayment")
|
|
acceptance = next(stage for stage in stages if stage["node_type"] == "acceptance")
|
|
return {
|
|
"purchase_order_no": purchase_order_no,
|
|
"contract_no": contract_no,
|
|
"total_amount": total_amount,
|
|
"archive_date": _parse_date(payload.get("archive_date"), "合同归档日"),
|
|
"prepayment_date": None if prepayment["skipped"] else prepayment["basis_date"],
|
|
"acceptance_date": None if acceptance["skipped"] else acceptance["basis_date"],
|
|
"stages": stages,
|
|
}
|
|
|
|
|
|
def _upsert_stage_node(contract: ContractPaymentContract, stage: dict[str, Any]) -> ContractPaymentNode:
|
|
"""
|
|
按阶段类型覆盖或新建付款节点。
|
|
|
|
核心逻辑:已有 ERP 已付事实且本次仍启用该阶段时保留 paid 和付款日。无此阶段改为 not_applicable。
|
|
预付款的到期判断用复核填入的日期依据;出货款同时作为交货期限。
|
|
|
|
Args:
|
|
contract: 当前合同。
|
|
stage: 已规范化的单个阶段。
|
|
|
|
Returns:
|
|
已挂到会话上的节点。节点主键在 flush 后可用于排除陈旧行。
|
|
"""
|
|
node = (
|
|
db.session.query(ContractPaymentNode)
|
|
.filter_by(contract_id=contract.id, node_type=stage["node_type"])
|
|
.order_by(ContractPaymentNode.id.asc())
|
|
.first()
|
|
)
|
|
if node is None:
|
|
node = ContractPaymentNode(
|
|
contract_id=contract.id,
|
|
node_code=stage["node_type"],
|
|
node_type=stage["node_type"],
|
|
reminder_days=0,
|
|
offset_days=0,
|
|
)
|
|
db.session.add(node)
|
|
db.session.flush()
|
|
was_paid = str(node.status or "").strip().lower() == "paid"
|
|
evidence = dict(node.evidence_json or {})
|
|
evidence["manual_review"] = True
|
|
node.amount = stage["amount"]
|
|
node.percentage = stage["percentage"]
|
|
node.reminder_days = 0
|
|
node.offset_days = 0
|
|
if stage["skipped"]:
|
|
node.anchor_type = None
|
|
node.anchor_date = None
|
|
node.due_date = None
|
|
node.status = "not_applicable"
|
|
else:
|
|
node.anchor_type = "acceptance_archive" if stage["node_type"] == "acceptance" else (
|
|
"warranty_expiry" if stage["node_type"] == "warranty" else "erp_payment"
|
|
)
|
|
node.anchor_date = stage["basis_date"]
|
|
node.due_date = stage["basis_date"]
|
|
node.status = "paid" if was_paid else "active"
|
|
node.evidence_json = evidence
|
|
return node
|
|
|
|
|
|
def _sync_manual_acceptance_event(
|
|
contract: ContractPaymentContract,
|
|
basis_date: date | None,
|
|
*,
|
|
operator_id: int | None,
|
|
) -> None:
|
|
"""
|
|
在还没有 OA 验收归档时,用复核填入的日期补一条验收事件。
|
|
|
|
核心逻辑:验收款预警读取最早的 acceptance_archive,不读节点上的日期。
|
|
仅维护 source_event_id 为人工复核的那一条;已有 OA 事件时不另造,避免改写归档日。
|
|
日期清空或阶段被跳过时删掉人工事件。
|
|
|
|
Args:
|
|
contract: 当前合同。
|
|
basis_date: 复核填入的验收单归档日;空表示不补事件。
|
|
operator_id: 写入事件载荷的操作人。
|
|
|
|
Returns:
|
|
None。
|
|
"""
|
|
source_event_id = f"{_MANUAL_ACCEPTANCE_PREFIX}{contract.id}"
|
|
manual = db.session.query(ContractPaymentEvent).filter_by(
|
|
contract_id=contract.id,
|
|
event_type="acceptance_archive",
|
|
source_event_id=source_event_id,
|
|
).first()
|
|
if basis_date is None:
|
|
if manual is not None:
|
|
db.session.delete(manual)
|
|
return
|
|
official = db.session.query(ContractPaymentEvent).filter(
|
|
ContractPaymentEvent.contract_id == contract.id,
|
|
ContractPaymentEvent.event_type == "acceptance_archive",
|
|
ContractPaymentEvent.source_event_id != source_event_id,
|
|
).first()
|
|
if official is not None:
|
|
return
|
|
if manual is None:
|
|
manual = ContractPaymentEvent(
|
|
contract_id=contract.id,
|
|
event_type="acceptance_archive",
|
|
event_date=basis_date,
|
|
source_event_id=source_event_id,
|
|
)
|
|
db.session.add(manual)
|
|
manual.event_date = basis_date
|
|
manual.payload_json = {"source": "manual_review", "operator_id": operator_id}
|
|
|
|
|
|
def _parse_decimal(value: Any, label: str) -> Decimal | None:
|
|
"""
|
|
把请求中的金额或比例转成 Decimal。
|
|
|
|
Args:
|
|
value: 原始字段,允许空。
|
|
label: 出错时展示的字段名。
|
|
|
|
Returns:
|
|
空值返回 None,否则返回 Decimal。
|
|
|
|
Raises:
|
|
ValidationError: 字段不是数字。
|
|
"""
|
|
if value is None:
|
|
return None
|
|
raw = str(value).strip()
|
|
if not raw:
|
|
return None
|
|
try:
|
|
return Decimal(raw)
|
|
except InvalidOperation as exc:
|
|
raise ValidationError(f"{label}不是有效数字") from exc
|
|
|
|
|
|
def _parse_date(value: Any, label: str) -> date | None:
|
|
"""
|
|
把 YYYY-MM-DD 转成日期。
|
|
|
|
Args:
|
|
value: 原始字段,允许空。
|
|
label: 出错时展示的字段名。
|
|
|
|
Returns:
|
|
空值返回 None。
|
|
|
|
Raises:
|
|
ValidationError: 日期格式不正确。
|
|
"""
|
|
if value is None:
|
|
return None
|
|
raw = str(value).strip()
|
|
if not raw:
|
|
return None
|
|
try:
|
|
return date.fromisoformat(raw[:10])
|
|
except ValueError as exc:
|
|
raise ValidationError(f"{label}格式应为 YYYY-MM-DD") from exc
|
|
|
|
|
|
def _stage_label(node_type: str) -> str:
|
|
"""返回校验文案里的阶段名称。"""
|
|
return {"prepayment": "预付款", "shipment": "出货款", "acceptance": "验收款", "warranty": "质保款"}.get(node_type, node_type)
|