fix(contract): 合同付款预警bug修复
This commit is contained in:
1 parent
5330e08281
commit
161666c0e7
26 files changed
+1599
-117
No files matched your search
@@ -3,7 +3,7 @@ backend/tests/test_contract_payment_parse.py
|
||||
|
||||
用途:验证合同付款预警解析器、三轮预警升级、ERP 金额匹配、周汇总摘要及企微 Excel 收件人列。
|
||||
依赖:contract_payment.parse_service、alert_service、erp_payment_service、supervisor_oa_service(三轮测试 mock)、openpyxl。
|
||||
逻辑:覆盖确定性解析边界、pending 计数与下一次周五 18:00;三轮升级 mock OA 矩阵,不调用外部 OA、文档库或企业微信;Excel 用例只断言「收件人」列为真实姓名。
|
||||
逻辑:覆盖确定性解析边界、pending 计数与下一次周五 18:00;三轮升级 mock OA 矩阵,不调用外部 OA、文档库或企业微信;Excel 用例只断言「收件人」列为真实姓名;失败原因用例只断言轨迹归类;OA 金额为 0 时断言正文正数回写台账;合同原文被清理后断言按附件 ID 重新下载。
|
||||
"""
|
||||
|
||||
from datetime import date, datetime
|
||||
@@ -15,6 +15,7 @@ from app.models import (
|
||||
ContractPaymentAttachment,
|
||||
ContractPaymentAlert,
|
||||
ContractPaymentNode,
|
||||
FileAsset,
|
||||
User,
|
||||
)
|
||||
from io import BytesIO
|
||||
@@ -24,7 +25,9 @@ from openpyxl import load_workbook
|
||||
from app.services.contract_payment.alert_service import (
|
||||
bind_contract_owner_from_applicant,
|
||||
build_weekly_alert_summary,
|
||||
describe_batch_failure,
|
||||
generate_alerts,
|
||||
render_batch_failure_message,
|
||||
_alert_status_label,
|
||||
_build_excel,
|
||||
_recipient_display_name,
|
||||
@@ -35,7 +38,12 @@ from app.services.contract_payment.dms_client import ContractDmsClient
|
||||
from app.services.contract_payment.oa_client import ContractOaClient
|
||||
from app.services.contract_payment.erp_payment_service import resolve_paid_node_ids
|
||||
from app.services.contract_payment.sync_service import _overwrite_oa_fields, _with_force_sync_audit
|
||||
from app.services.contract_payment.sync_service import _persist_payment_plan, save_oa_attachments
|
||||
from app.services.contract_payment.sync_service import (
|
||||
_persist_payment_plan,
|
||||
_retain_contract_file_asset,
|
||||
read_contract_attachment_bytes,
|
||||
save_oa_attachments,
|
||||
)
|
||||
|
||||
|
||||
def test_force_oa_sync_overwrites_only_non_empty_values_and_keeps_audit():
|
||||
@@ -68,6 +76,53 @@ def test_force_oa_sync_overwrites_only_non_empty_values_and_keeps_audit():
|
||||
}
|
||||
|
||||
|
||||
def test_force_oa_sync_does_not_replace_positive_amount_with_zero():
|
||||
"""OA 手填 0 不能在强制覆盖时清掉台账上已有的正数总额。"""
|
||||
contract = ContractPaymentContract(
|
||||
purchase_order_no="PO-KEEP",
|
||||
total_amount=Decimal("150.00"),
|
||||
)
|
||||
changed = _overwrite_oa_fields(contract, {"total_amount": "0.00"}, operator_id=7)
|
||||
# 0 与空值相同,不是一次有效的 OA 金额覆盖。
|
||||
assert changed == 0
|
||||
assert contract.total_amount == Decimal("150.00")
|
||||
|
||||
|
||||
def test_parse_uses_contract_text_when_oa_amount_is_zero():
|
||||
"""正文有正数金额时,不用 OA 的 0 去乘付款比例。"""
|
||||
result = parse_contract_text(
|
||||
"合同金额:150元;预付款30%;出货款30%;验收款35%;质保款5%;交货期限:2026年10月12日。",
|
||||
total_amount="0.00",
|
||||
)
|
||||
# 阶段金额按正文 150 计算,30% 为 45。
|
||||
assert result["status"] == "parsed"
|
||||
assert result["fields"]["total_amount"] == "150"
|
||||
prepayment = next(item for item in result["nodes"] if item["node_type"] == "prepayment")
|
||||
assert prepayment["amount"] == "45.00"
|
||||
|
||||
|
||||
def test_zero_oa_amount_is_replaced_when_plan_is_persisted(app):
|
||||
"""台账总额已是 0 时,解析落库应回写正文中的正数金额。"""
|
||||
with app.app_context():
|
||||
contract = ContractPaymentContract(
|
||||
contract_no="HT-ZERO-AMOUNT",
|
||||
purchase_order_no="PO-ZERO-AMOUNT",
|
||||
total_amount=Decimal("0.00"),
|
||||
)
|
||||
db.session.add(contract)
|
||||
db.session.flush()
|
||||
result = parse_contract_text(
|
||||
"合同编号:HT-ZERO-AMOUNT;合同金额:150元;预付款30%;出货款30%;验收款35%;质保款5%;交货期限:2026年10月12日。",
|
||||
total_amount=contract.total_amount,
|
||||
)
|
||||
_persist_payment_plan(contract, result=result)
|
||||
# 0 被正文 150 替换,节点金额与比例同时落库。
|
||||
assert contract.total_amount == Decimal("150")
|
||||
node = db.session.query(ContractPaymentNode).filter_by(contract_id=contract.id, node_code="prepayment").one()
|
||||
assert Decimal(str(node.amount)) == Decimal("45.00")
|
||||
assert Decimal(str(node.percentage)) == Decimal("30")
|
||||
|
||||
|
||||
def test_payment_plan_requires_purchase_order_for_automatic_alerts(app):
|
||||
"""关键断言:采购单号缺失时,解析结果不能进入自动付款预警台账。"""
|
||||
with app.app_context():
|
||||
@@ -89,12 +144,39 @@ def test_payment_plan_requires_purchase_order_for_automatic_alerts(app):
|
||||
assert contract.plan_status == "needs_review"
|
||||
|
||||
|
||||
def _contract_file_asset(user_id: int, *, asset_no: str, **overrides) -> FileAsset:
|
||||
"""构造测试用合同原文资产;调用方负责 add/flush。"""
|
||||
values = dict(
|
||||
asset_no=asset_no,
|
||||
owner_user_id=user_id,
|
||||
original_filename="盖章合同.pdf",
|
||||
storage_provider="minio",
|
||||
storage_bucket="test",
|
||||
storage_key=f"contract-oa/{asset_no}",
|
||||
content_hash=asset_no.ljust(64, "0")[:64],
|
||||
file_size=4,
|
||||
mime_type="application/pdf",
|
||||
upload_status="ready",
|
||||
lifecycle_status="referenced",
|
||||
reference_count=1,
|
||||
expires_at=None,
|
||||
deleted_at=None,
|
||||
)
|
||||
values.update(overrides)
|
||||
return FileAsset(**values)
|
||||
|
||||
|
||||
def test_normal_oa_sync_does_not_overwrite_a_single_contract_reparse(app, monkeypatch):
|
||||
"""关键断言:已归档附件在普通 OA 同步中不再重解析,避免覆盖单合同重解析结果。"""
|
||||
"""关键断言:仍可读的已归档附件在普通 OA 同步中不再重解析,避免覆盖单合同重解析结果。"""
|
||||
with app.app_context():
|
||||
owner = User(username="cp-live-asset", email="cp-live-asset@example.com", status="active")
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
asset = _contract_file_asset(owner.id, asset_no="FA-CP-LIVE")
|
||||
db.session.add(asset)
|
||||
contract = ContractPaymentContract(
|
||||
contract_no="HT-SINGLE-REPARSE",
|
||||
owner_user_id=1,
|
||||
owner_user_id=owner.id,
|
||||
parse_status="parsed",
|
||||
plan_status="active",
|
||||
)
|
||||
@@ -105,25 +187,135 @@ def test_normal_oa_sync_does_not_overwrite_a_single_contract_reparse(app, monkey
|
||||
source="oa",
|
||||
source_key="oa:sealed-1",
|
||||
file_name="盖章合同.pdf",
|
||||
file_asset_id=1,
|
||||
file_asset_id=asset.id,
|
||||
status="stored",
|
||||
))
|
||||
db.session.flush()
|
||||
monkeypatch.setattr(
|
||||
'app.services.contract_payment.sync_service.build_payment_plan_from_bytes',
|
||||
"app.services.contract_payment.sync_service.build_payment_plan_from_bytes",
|
||||
lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("普通 OA 同步不应重新解析已归档附件")),
|
||||
)
|
||||
|
||||
class Client:
|
||||
def download_attachment(self, _attachment):
|
||||
raise AssertionError("仍可读的附件不应重新下载")
|
||||
|
||||
result = save_oa_attachments(
|
||||
contract,
|
||||
item={"attachments": [{"attachment_id": "sealed-1", "file_name": "盖章合同.pdf", "priority": 0}]},
|
||||
client=object(),
|
||||
client=Client(),
|
||||
)
|
||||
|
||||
assert result == {"found": 1, "saved": 0}
|
||||
assert contract.parse_status == "parsed"
|
||||
|
||||
|
||||
def test_retain_marks_temporary_contract_asset_referenced(app):
|
||||
"""关键断言:仍存活的临时合同原文会被标为已引用,且重复调用不继续加引用计数。"""
|
||||
with app.app_context():
|
||||
owner = User(username="cp-retain-asset", email="cp-retain-asset@example.com", status="active")
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
asset = _contract_file_asset(
|
||||
owner.id,
|
||||
asset_no="FA-CP-TEMP",
|
||||
lifecycle_status="temporary",
|
||||
reference_count=0,
|
||||
expires_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
|
||||
_retain_contract_file_asset(asset)
|
||||
db.session.refresh(asset)
|
||||
assert asset.lifecycle_status == "referenced"
|
||||
assert asset.expires_at is None
|
||||
assert asset.reference_count == 1
|
||||
|
||||
_retain_contract_file_asset(asset)
|
||||
db.session.refresh(asset)
|
||||
assert asset.reference_count == 1
|
||||
|
||||
|
||||
def test_deleted_contract_attachment_is_redownloaded(app, monkeypatch):
|
||||
"""关键断言:软删除的合同原文按 OA 流程和附件 ID 重新下载,并写回已引用资产。"""
|
||||
with app.app_context():
|
||||
owner = User(username="cp-deleted-asset", email="cp-deleted-asset@example.com", status="active")
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
dead = _contract_file_asset(
|
||||
owner.id,
|
||||
asset_no="FA-CP-DEAD",
|
||||
upload_status="deleted",
|
||||
lifecycle_status="expired",
|
||||
deleted_at=datetime.utcnow(),
|
||||
)
|
||||
parent = _contract_file_asset(owner.id, asset_no="FA-CP-PARENT", asset_role="contract_oa_root")
|
||||
db.session.add_all([dead, parent])
|
||||
contract = ContractPaymentContract(
|
||||
contract_no="HT-REDOWNLOAD",
|
||||
oa_record_id="5203",
|
||||
owner_user_id=owner.id,
|
||||
)
|
||||
db.session.add(contract)
|
||||
db.session.flush()
|
||||
attachment = ContractPaymentAttachment(
|
||||
contract_id=contract.id,
|
||||
source="oa",
|
||||
source_key="oa:att-9",
|
||||
file_name="盖章合同.pdf",
|
||||
file_asset_id=dead.id,
|
||||
status="stored",
|
||||
metadata_json={"attachment_id": "att-9"},
|
||||
)
|
||||
db.session.add(attachment)
|
||||
db.session.flush()
|
||||
calls: dict[str, tuple[str, str]] = {}
|
||||
|
||||
def fake_download(self, *, process_id, attachment_id):
|
||||
calls["ids"] = (process_id, attachment_id)
|
||||
return b"pdf-bytes", "application/pdf", "restored.pdf"
|
||||
|
||||
def fake_create(**kwargs):
|
||||
live = _contract_file_asset(
|
||||
owner.id,
|
||||
asset_no="FA-CP-RESTORED",
|
||||
lifecycle_status="temporary",
|
||||
reference_count=0,
|
||||
expires_at=datetime.utcnow(),
|
||||
parent_asset_id=parent.id,
|
||||
)
|
||||
db.session.add(live)
|
||||
db.session.flush()
|
||||
return live, True
|
||||
|
||||
monkeypatch.setattr(ContractOaClient, "download_attachment_by_id", fake_download)
|
||||
monkeypatch.setattr(
|
||||
"app.services.contract_payment.sync_service._ensure_oa_parent_asset",
|
||||
lambda **_kwargs: parent,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.contract_payment.sync_service.create_derived_file_asset_from_bytes",
|
||||
fake_create,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"app.services.contract_payment.sync_service.read_asset_bytes",
|
||||
lambda _asset: b"pdf-bytes",
|
||||
)
|
||||
|
||||
data = read_contract_attachment_bytes(contract, attachment)
|
||||
db.session.refresh(attachment)
|
||||
restored = db.session.get(FileAsset, attachment.file_asset_id)
|
||||
# 断言留在同一会话内,避免上下文结束后 ORM 实例过期。
|
||||
assert data == b"pdf-bytes"
|
||||
assert calls["ids"] == ("5203", "att-9")
|
||||
assert attachment.file_name == "restored.pdf"
|
||||
assert restored is not None
|
||||
assert restored.asset_no == "FA-CP-RESTORED"
|
||||
assert restored.lifecycle_status == "referenced"
|
||||
assert restored.deleted_at is None
|
||||
|
||||
|
||||
def test_parse_standard_payment_plan():
|
||||
"""关键断言:预付款纳入节点,出货款到期锚点为交货期限,金额按比例计算。"""
|
||||
result = parse_contract_text(
|
||||
@@ -621,6 +813,37 @@ def test_recipient_display_name_falls_back_to_username(app):
|
||||
assert _recipient_display_name(None) == "—"
|
||||
|
||||
|
||||
def test_describe_batch_failure_collapses_unbound_recipient():
|
||||
"""收件人未绑定企微时,卡片和附件的同一原因只保留一条。"""
|
||||
reasons = describe_batch_failure({
|
||||
"textcard": {"ok": False, "reason": "user_unbound"},
|
||||
"file": {"errcode": -1, "errmsg": "user_unbound"},
|
||||
})
|
||||
# 未绑定账号是配置问题,不把附件失败再报一遍。
|
||||
assert reasons == [{"code": "user_unbound", "detail": ""}]
|
||||
assert render_batch_failure_message(reasons) == "收件人未绑定企业微信账号"
|
||||
|
||||
|
||||
def test_describe_batch_failure_keeps_card_and_file_errors():
|
||||
"""卡片与附件分别失败时,两条原因和企微 errmsg 都要保留。"""
|
||||
reasons = describe_batch_failure({
|
||||
"textcard": {"ok": False, "reason": "send_failed", "raw": {"errcode": 81013, "errmsg": "user ticket invalid"}},
|
||||
"file_error": "upload timeout",
|
||||
})
|
||||
# 卡片失败看 errmsg,附件上传异常单独成条,不混成一条未知错误。
|
||||
assert reasons == [
|
||||
{"code": "textcard_failed", "detail": "user ticket invalid"},
|
||||
{"code": "file_upload_failed", "detail": "upload timeout"},
|
||||
]
|
||||
|
||||
|
||||
def test_describe_batch_failure_falls_back_to_stored_message():
|
||||
"""没有发送轨迹时,回退展示已保存的错误文本。"""
|
||||
reasons = describe_batch_failure(None, fallback="gateway timeout")
|
||||
# 历史批次可能只有 error_message,页面仍要能点开原因。
|
||||
assert reasons == [{"code": "unknown", "detail": "gateway timeout"}]
|
||||
|
||||
|
||||
def test_alert_status_label_uses_chinese():
|
||||
"""关键断言:Excel 状态列把 pending/sent/failed 写成中文,未知码保留原文。"""
|
||||
assert _alert_status_label("pending") == "待发送"
|
||||
|
||||
Reference in new issue
Block a user