fix(contract-plan): 合同付款预警待确认合同增加人工复核功能
This commit is contained in:
1 parent
d13c881efb
commit
6867aeb90c
17 files changed
+1157
-43
No files matched your search
@@ -5,6 +5,7 @@ backend/app/api/contract_payment.py
|
||||
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、Agent 授权、contract_payment 服务和通用 Job 队列。
|
||||
逻辑:页面查询合同、节点、本周待发送摘要、四张汇总卡和周汇总批次;失败批次返回可展示原因。同步和预警操作入队,避免请求线程执行外部系统和企微调用;发送后可按 Job 查询是否真正完成。
|
||||
下载和单合同重解析走 read_contract_attachment_bytes:原文还在则直接读,被临时清理删掉则按附件 ID 从 OA/DMS 重新下载。
|
||||
待确认合同的人工复核走 apply_manual_review:比例合计 100% 后改为已解析并进入台账。
|
||||
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍。
|
||||
鉴权:查询接口要求平台 admin 或持有 `agent_code=contract_payment` 的 Agent 授权;
|
||||
同步/扫描/周汇总发送仅 `role=admin`。
|
||||
@@ -38,6 +39,7 @@ from app.services.contract_payment.ledger_focus import (
|
||||
ledger_focus_counts,
|
||||
)
|
||||
from app.services.contract_payment.parse_service import unique_parse_issues
|
||||
from app.services.contract_payment.review_service import apply_manual_review
|
||||
from app.services.contract_payment.sync_service import (
|
||||
build_payment_plan,
|
||||
build_payment_plan_from_bytes,
|
||||
@@ -606,3 +608,27 @@ def reparse_contract_attachment(contract_id: int):
|
||||
"parse_result": result,
|
||||
"attachment_name": attachment.file_name,
|
||||
}, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@contract_payment_bp.route("/contracts/<int:contract_id>/manual-review", methods=["POST"])
|
||||
def manual_review_contract(contract_id: int):
|
||||
"""
|
||||
保存待确认合同的人工复核,并在校验通过后放入合同台账。
|
||||
|
||||
核心逻辑:与单合同重解析一样,持有合同付款 Agent 的用户即可提交,不要求平台管理员。
|
||||
服务层负责比例合计、金额核对和必填日期;本接口只转交请求体并返回更新后的合同。
|
||||
|
||||
Args:
|
||||
contract_id: 合同付款台账主键。
|
||||
|
||||
Returns:
|
||||
标准成功 envelope,含复核后的合同详情。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 合同不存在。
|
||||
ValidationError: 采购单号、金额、比例或日期不满足进入台账的条件。
|
||||
"""
|
||||
user = _require_contract_payment_access()
|
||||
data = request.get_json() or {}
|
||||
row = apply_manual_review(contract_id, data, operator_id=getattr(user, "id", None))
|
||||
return ok({"contract": _serialize_contract(row)}, request_id=getattr(g, "request_id", None))
|
||||
@@ -0,0 +1,364 @@
|
||||
"""
|
||||
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
|
||||
|
||||
_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 = str(payload.get("purchase_order_no") or "").strip()
|
||||
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)
|
||||
@@ -0,0 +1,196 @@
|
||||
"""
|
||||
backend/tests/test_contract_payment_manual_review.py
|
||||
|
||||
用途:验收待确认合同人工复核进入台账的校验与落库。
|
||||
依赖:Flask test client、合同付款模型、Agent 授权。
|
||||
逻辑:构造 needs_review 合同,提交四阶段复核;合计不为 100% 或空比例时不得改解析状态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import Agent, ContractPaymentContract, ContractPaymentEvent, ContractPaymentNode, User
|
||||
from app.services.contract_payment.review_service import apply_manual_review
|
||||
|
||||
|
||||
def _create_user(*, username: str) -> User:
|
||||
"""创建已授予合同付款预警 Agent 的用户,供复核接口走 legacy header 认证。"""
|
||||
user = User(
|
||||
username=username,
|
||||
email=f"{username}@example.com",
|
||||
role="user",
|
||||
status="active",
|
||||
real_name=f"{username}-实名",
|
||||
employee_id=f"{username.upper()}-EMP",
|
||||
department="采购部",
|
||||
)
|
||||
user.set_password("password123")
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
agent = Agent.query.filter_by(agent_code="contract_payment", is_active=True).first()
|
||||
if not agent:
|
||||
agent = Agent(
|
||||
name="合同付款预警",
|
||||
agent_code="contract_payment",
|
||||
runtime_provider="builtin",
|
||||
conversation_mode="task_chat",
|
||||
type="api",
|
||||
is_active=True,
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.flush()
|
||||
user.agents.append(agent)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
db.session.expunge(user)
|
||||
return user
|
||||
|
||||
|
||||
def _auth_headers(user: User) -> dict[str, str]:
|
||||
"""生成测试鉴权头。"""
|
||||
return {
|
||||
"X-User-Id": str(user.id),
|
||||
"X-Username": user.username,
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
|
||||
def _review_payload(**overrides) -> dict:
|
||||
"""南通锻压样本:30/60/10,质保款无此阶段。"""
|
||||
payload = {
|
||||
"purchase_order_no": "5203-2609080001",
|
||||
"contract_no": "",
|
||||
"total_amount": "1550000",
|
||||
"archive_date": "2026-09-19",
|
||||
"stages": [
|
||||
{"node_type": "prepayment", "skipped": False, "percentage": "30", "amount": "465000", "basis_date": "2026-09-19"},
|
||||
{"node_type": "shipment", "skipped": False, "percentage": "60", "amount": "930000", "basis_date": "2027-01-31"},
|
||||
{"node_type": "acceptance", "skipped": False, "percentage": "10", "amount": "155000", "basis_date": ""},
|
||||
{"node_type": "warranty", "skipped": True, "percentage": "0", "amount": "0", "basis_date": ""},
|
||||
],
|
||||
}
|
||||
payload.update(overrides)
|
||||
return payload
|
||||
|
||||
|
||||
def _seed_review_contract() -> ContractPaymentContract:
|
||||
"""写入一份待确认合同,并带上已识别的出货款、验收款。"""
|
||||
contract = ContractPaymentContract(
|
||||
purchase_order_no="5203-2609080001",
|
||||
supplier_name="南通锻压设备如皋有限公司",
|
||||
total_amount=Decimal("1550000.00"),
|
||||
parse_status="needs_review",
|
||||
plan_status="needs_review",
|
||||
status="active",
|
||||
parse_result_json={"status": "needs_review", "issues": ["付款阶段比例无法识别:预付款、质保款"]},
|
||||
)
|
||||
db.session.add(contract)
|
||||
db.session.flush()
|
||||
db.session.add_all([
|
||||
ContractPaymentNode(
|
||||
contract_id=contract.id, node_code="shipment", node_type="shipment",
|
||||
amount=Decimal("930000.00"), percentage=Decimal("60"), status="needs_review",
|
||||
),
|
||||
ContractPaymentNode(
|
||||
contract_id=contract.id, node_code="acceptance", node_type="acceptance",
|
||||
amount=Decimal("155000.00"), percentage=Decimal("10"), status="needs_review",
|
||||
),
|
||||
])
|
||||
db.session.commit()
|
||||
return contract
|
||||
|
||||
|
||||
def test_manual_review_promotes_contract_into_ledger(client, app):
|
||||
"""比例合计 100% 且必填日期齐全时,合同离开待确认并写入四阶段。"""
|
||||
with app.app_context():
|
||||
user = _create_user(username="cp_review_ok")
|
||||
contract = _seed_review_contract()
|
||||
contract_id = contract.id
|
||||
|
||||
res = client.post(
|
||||
f"/api/contract-payment/contracts/{contract_id}/manual-review",
|
||||
json=_review_payload(),
|
||||
headers=_auth_headers(user),
|
||||
)
|
||||
assert res.status_code == 200
|
||||
body = res.get_json()["data"]["contract"]
|
||||
# 关键断言:复核通过后进入台账,质保款不参与预警,出货款日期写到交货期限。
|
||||
assert body["parse_status"] == "parsed"
|
||||
assert body["plan_status"] == "active"
|
||||
assert body["parse_issues"] == []
|
||||
assert body["delivery_due_date"] == "2027-01-31"
|
||||
by_type = {node["node_type"]: node for node in body["nodes"]}
|
||||
assert by_type["prepayment"]["status"] == "active"
|
||||
assert by_type["prepayment"]["due_date"] == "2026-09-19"
|
||||
assert by_type["warranty"]["status"] == "not_applicable"
|
||||
assert by_type["acceptance"]["due_date"] is None
|
||||
|
||||
|
||||
def test_manual_review_rejects_blank_percent_without_promoting(app):
|
||||
"""启用阶段留空比例时不得把空值当成 0,合同仍停留在待确认。"""
|
||||
with app.app_context():
|
||||
contract = _seed_review_contract()
|
||||
payload = _review_payload()
|
||||
payload["stages"][0]["percentage"] = ""
|
||||
payload["stages"][0]["amount"] = ""
|
||||
try:
|
||||
apply_manual_review(contract.id, payload, operator_id=1)
|
||||
raised = False
|
||||
except ValidationError:
|
||||
raised = True
|
||||
db.session.rollback()
|
||||
fresh = db.session.get(ContractPaymentContract, contract.id)
|
||||
# 关键断言:空比例被拒绝,解析状态不被改成 parsed。
|
||||
assert raised is True
|
||||
assert fresh.parse_status == "needs_review"
|
||||
|
||||
|
||||
def test_manual_review_rejects_duplicate_contract_no(app):
|
||||
"""合同编号与另一条台账冲突时拒绝复核。"""
|
||||
with app.app_context():
|
||||
contract = _seed_review_contract()
|
||||
db.session.add(ContractPaymentContract(contract_no="HT-EXISTING", parse_status="parsed", status="active"))
|
||||
db.session.commit()
|
||||
payload = _review_payload(contract_no="HT-EXISTING")
|
||||
try:
|
||||
apply_manual_review(contract.id, payload)
|
||||
raised = False
|
||||
except ValidationError as exc:
|
||||
raised = "冲突" in str(exc)
|
||||
# 关键断言:冲突编号不会写入当前合同。
|
||||
assert raised is True
|
||||
assert db.session.get(ContractPaymentContract, contract.id).contract_no is None
|
||||
|
||||
|
||||
def test_manual_review_keeps_paid_fact_and_acceptance_event(app):
|
||||
"""已付的预付款保持 paid;手填验收日且没有 OA 事件时补人工归档事件。"""
|
||||
with app.app_context():
|
||||
contract = _seed_review_contract()
|
||||
db.session.add(ContractPaymentNode(
|
||||
contract_id=contract.id,
|
||||
node_code="prepayment",
|
||||
node_type="prepayment",
|
||||
amount=Decimal("465000.00"),
|
||||
percentage=Decimal("30"),
|
||||
status="paid",
|
||||
evidence_json={"paid_at": "2026-09-20"},
|
||||
))
|
||||
db.session.commit()
|
||||
payload = _review_payload()
|
||||
payload["stages"][2]["basis_date"] = "2026-10-01"
|
||||
apply_manual_review(contract.id, payload, operator_id=7)
|
||||
nodes = {
|
||||
node.node_type: node
|
||||
for node in db.session.query(ContractPaymentNode).filter_by(contract_id=contract.id).all()
|
||||
}
|
||||
event = db.session.query(ContractPaymentEvent).filter_by(contract_id=contract.id, event_type="acceptance_archive").one()
|
||||
# 关键断言:ERP 已付事实保留;验收日成为预警锚点;跳过的质保款不是 active。
|
||||
assert nodes["prepayment"].status == "paid"
|
||||
assert nodes["prepayment"].evidence_json["paid_at"] == "2026-09-20"
|
||||
assert nodes["warranty"].status == "not_applicable"
|
||||
assert event.event_date == date(2026, 10, 1)
|
||||
assert event.source_event_id == f"manual-review:{contract.id}"
|
||||
Reference in new issue
Block a user