1038 lines
46 KiB
Python
1038 lines
46 KiB
Python
"""
|
||
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 用例只断言「收件人」列为真实姓名;失败原因用例只断言轨迹归类;OA 金额为 0 时断言正文正数回写台账;合同原文被清理后断言按附件 ID 重新下载;OA「公司」决定 ERP 账套,同一采购单号不能跨账套记成已付;增值税税率和「收到定金后 N 天」不计入付款比例。
|
||
"""
|
||
|
||
from datetime import date, datetime
|
||
from decimal import Decimal
|
||
|
||
from app import db
|
||
from app.models import (
|
||
ContractPaymentContract,
|
||
ContractPaymentAttachment,
|
||
ContractPaymentAlert,
|
||
ContractPaymentNode,
|
||
FileAsset,
|
||
User,
|
||
)
|
||
from io import BytesIO
|
||
|
||
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,
|
||
)
|
||
from app.services.contract_payment import parse_service
|
||
from app.services.contract_payment.parse_service import parse_contract_bytes, parse_contract_text
|
||
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,
|
||
_retain_contract_file_asset,
|
||
read_contract_attachment_bytes,
|
||
save_oa_attachments,
|
||
)
|
||
|
||
|
||
def test_force_oa_sync_overwrites_only_non_empty_values_and_keeps_audit():
|
||
"""关键断言:强制同步只覆盖 OA 明确返回字段,且最新原始载荷不会丢失金额变更审计。"""
|
||
contract = ContractPaymentContract(
|
||
purchase_order_no="PO-OLD",
|
||
supplier_name="旧供应商",
|
||
total_amount=Decimal("100.00"),
|
||
currency="人民币",
|
||
source_payload_json={"source_event_id": "old-event"},
|
||
)
|
||
|
||
changed = _overwrite_oa_fields(contract, {
|
||
"purchase_order_no": "PO-NEW",
|
||
"supplier_name": "",
|
||
"total_amount": Decimal("200.00"),
|
||
"currency": None,
|
||
}, operator_id=42)
|
||
payload = _with_force_sync_audit({"source_event_id": "new-event"}, contract.source_payload_json)
|
||
|
||
# 非空 OA 值覆盖,空值不清空原合同事实。
|
||
assert changed == 2
|
||
assert contract.purchase_order_no == "PO-NEW"
|
||
assert contract.supplier_name == "旧供应商"
|
||
assert contract.currency == "人民币"
|
||
assert payload["source_event_id"] == "new-event"
|
||
assert payload["force_sync_audit"][0]["operator_id"] == 42
|
||
assert payload["force_sync_audit"][0]["changed_fields"]["total_amount"] == {
|
||
"before": "100.00", "after": "200.00",
|
||
}
|
||
|
||
|
||
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():
|
||
contract = ContractPaymentContract(contract_no="HT-PO-MISSING")
|
||
db.session.add(contract)
|
||
db.session.flush()
|
||
|
||
result = _persist_payment_plan(contract, result={
|
||
"status": "parsed",
|
||
"fields": {},
|
||
"nodes": [],
|
||
"issues": [],
|
||
})
|
||
|
||
# persist 会 commit;断言须在 app_context 内读取 ORM 字段。
|
||
assert result["status"] == "needs_review"
|
||
assert "采购单号无法识别" in result["issues"]
|
||
assert contract.parse_status == "needs_review"
|
||
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 同步中不再重解析,避免覆盖单合同重解析结果。"""
|
||
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=owner.id,
|
||
parse_status="parsed",
|
||
plan_status="active",
|
||
)
|
||
db.session.add(contract)
|
||
db.session.flush()
|
||
db.session.add(ContractPaymentAttachment(
|
||
contract_id=contract.id,
|
||
source="oa",
|
||
source_key="oa:sealed-1",
|
||
file_name="盖章合同.pdf",
|
||
file_asset_id=asset.id,
|
||
status="stored",
|
||
))
|
||
db.session.flush()
|
||
monkeypatch.setattr(
|
||
"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=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(
|
||
"设备采购合同;合同编号:HT-2026-0001;设备总价款(含税):100,000元;"
|
||
"预付款10%;出货款在2026年8月20日前支付50%;验收款20%;质保款20%;质保期12个月。"
|
||
)
|
||
assert result["status"] == "parsed"
|
||
assert result["fields"]["delivery_due_date"] == "2026-08-20"
|
||
shipment = next(item for item in result["nodes"] if item["node_type"] == "shipment")
|
||
assert shipment["amount"] == "50000.00"
|
||
assert shipment["due_date"] == "2026-08-20"
|
||
assert shipment["anchor_type"] == "erp_payment"
|
||
|
||
|
||
def test_scanned_pdf_prefers_mineru_markdown_for_payment_plan(app, monkeypatch):
|
||
"""关键断言:扫描 PDF 配置 MinerU 后直接使用 Markdown,不再调用旧文字层或 OCR。"""
|
||
class MinerUResponse:
|
||
def raise_for_status(self):
|
||
return None
|
||
|
||
def json(self):
|
||
return {
|
||
"status": "completed",
|
||
"results": {"sealed-contract": {"md_content": (
|
||
"# 设备采购合同\n合同号:HT-2026-009;合同总价:100,000元;"
|
||
"预付款10%;出货款40%;验收款40%;质保款10%;交货期:2026年09月01日。"
|
||
)}},
|
||
}
|
||
|
||
with app.app_context():
|
||
app.config.update(PROCUREMENT_CONTRACT_MINERU_API_URL="http://mineru.example")
|
||
monkeypatch.setattr(parse_service, "extract_text_from_bytes", lambda *_: "[binary:pdf]")
|
||
monkeypatch.setattr(parse_service, "_extract_ocr_text", lambda *_: (_ for _ in ()).throw(AssertionError("不应调用旧 OCR")))
|
||
monkeypatch.setattr(parse_service.requests, "post", lambda *args, **kwargs: MinerUResponse())
|
||
result = parse_contract_bytes("盖章合同.pdf", b"scanned-pdf")
|
||
|
||
assert result["status"] == "parsed"
|
||
assert result["evidence"]["document_extractor"] == "mineru"
|
||
|
||
|
||
def test_parse_missing_delivery_is_review():
|
||
"""关键断言:无法确认交货期限时不能生成正式出货款提醒。"""
|
||
result = parse_contract_text("合同总价:100,000元;出货款50%;验收款20%。")
|
||
assert result["status"] == "needs_review"
|
||
assert "合同交货期限无法识别" in result["issues"]
|
||
|
||
|
||
def test_parse_pdf_contract_clause_extracts_contract_no_and_payment_terms():
|
||
"""关键断言:合同号来自正文,金额、四段付款比例与付款质保期均能识别。"""
|
||
result = parse_contract_text(
|
||
"设备采购合同\n合同号:20260729\n"
|
||
"设备总价款(含税):¥264,800 元整\n"
|
||
"预付款:¥79,440 元整(总价款的 30%)\n"
|
||
"出货款:¥79,440 元整(总价款的 30 %)\n"
|
||
"验收款(总价款的 30 %)¥79,440 元整\n"
|
||
"质保款(总价款的 10%)¥26,480 元整\n"
|
||
"交货期限:乙方应于 2026 年 09 月 11 日前将设备送达交货地点。\n"
|
||
"从验收合格日起算 12 个月质保期满后支付。\n"
|
||
"保固 贰 年"
|
||
)
|
||
assert result["status"] == "parsed"
|
||
assert result["fields"]["contract_no"] == "20260729"
|
||
assert result["fields"]["total_amount"] == "264800"
|
||
assert result["fields"]["warranty_period_days"] == 360
|
||
assert {node["node_type"]: node["percentage"] for node in result["nodes"]} == {
|
||
"prepayment": "30",
|
||
"shipment": "30",
|
||
"acceptance": "30",
|
||
"warranty": "10",
|
||
}
|
||
|
||
|
||
def test_payment_plan_requires_all_payment_ratios_to_total_one_hundred():
|
||
"""关键断言:无论合同措辞如何,四阶段比例仍必须完整且合计为 100%。"""
|
||
result = parse_contract_text(
|
||
"设备采购合同\n合同编号:HT-2026-001\n设备总价款(含税):100,000元\n"
|
||
"预付款30%;出货款35%;验收款35%;质保款5%;交货期限:2026年09月01日。"
|
||
)
|
||
|
||
assert result["status"] == "needs_review"
|
||
assert "四阶段付款比例合计不等于100%" in result["issues"]
|
||
|
||
|
||
def test_non_template_contract_can_be_parsed_when_required_facts_are_complete():
|
||
"""关键断言:不再以 V4 固定模板作为准入条件,完整四阶段条款可正常进入台账。"""
|
||
result = parse_contract_text(
|
||
"采购协议 合同号:HT-2026-002;合同总价:100,000元;"
|
||
"预付款10%;出货款40%;验收款40%;尾款10%;交货期:2026年09月01日。"
|
||
)
|
||
|
||
assert result["status"] == "parsed"
|
||
|
||
|
||
def test_missing_payment_stages_do_not_report_removed_template_match_rule():
|
||
"""关键断言:付款阶段缺失只报告真实条款问题,不再报告固定模板不匹配。"""
|
||
result = parse_contract_text("采购协议 合同号:HT-2026-003;合同总价:100,000元;预付款100%;交货期:2026年09月01日。")
|
||
|
||
assert result["status"] == "needs_review"
|
||
assert "付款阶段比例无法识别:出货款、验收款、质保款" in result["issues"]
|
||
assert not any("固定模板" in issue for issue in result["issues"])
|
||
|
||
|
||
def test_repeated_same_shipment_percentage_is_not_reported_six_times():
|
||
"""关键断言:MinerU 把出货款同一比例抽到多次时,只保留一条事实,不连写「比例重复」。"""
|
||
repeated = ";".join(["出货款30%"] * 7)
|
||
result = parse_contract_text(
|
||
f"采购协议 合同号:HT-2026-004;合同总价:100,000元;{repeated};交货期:2026年09月01日。"
|
||
)
|
||
|
||
duplicate_issues = [issue for issue in result["issues"] if "出货款付款比例重复" in issue]
|
||
assert duplicate_issues == []
|
||
shipment = next(item for item in result["nodes"] if item["node_type"] == "shipment")
|
||
assert shipment["percentage"] == "30"
|
||
|
||
|
||
def test_conflicting_shipment_percentages_report_duplicate_once():
|
||
"""关键断言:出货款出现 30% 与 40% 两种比例时,只报一条重复原因。"""
|
||
result = parse_contract_text(
|
||
"采购协议 合同号:HT-2026-005;合同总价:100,000元;"
|
||
"出货款30%;出货款40%;出货款30%;交货期:2026年09月01日。"
|
||
)
|
||
|
||
duplicate_issues = [issue for issue in result["issues"] if issue == "出货款付款比例重复,需人工确认"]
|
||
assert duplicate_issues == ["出货款付款比例重复,需人工确认"]
|
||
assert not any(node["node_type"] == "shipment" for node in result["nodes"])
|
||
|
||
|
||
def test_vat_rate_beside_deposit_schedule_is_not_prepayment_percentage():
|
||
"""关键断言:完成日期「收到定金后135天」后的含13%增值税不算预付款,结算条款的定金30%仍保留。"""
|
||
result = parse_contract_text(
|
||
"设备定作合同 收到定金后 135天 合计(人民币大写)壹佰伍拾伍万元整(含13%增值税) "
|
||
"四、结算方式及期限:甲方支付乙方定金:¥465,000.00元(总价款的30%),"
|
||
"甲方支付乙方发货款:¥930,000.00元(总价款的60%),"
|
||
"验收款(总价款的10%)¥155,000.00元。"
|
||
"设备总价款(含税):1550000.00元"
|
||
)
|
||
|
||
percentages = {node["node_type"]: node["percentage"] for node in result["nodes"]}
|
||
assert percentages["prepayment"] == "30"
|
||
assert percentages["shipment"] == "60"
|
||
assert percentages["acceptance"] == "10"
|
||
assert "warranty" not in percentages
|
||
assert "预付款付款比例重复,需人工确认" not in result["issues"]
|
||
assert "付款阶段比例无法识别:质保款" in result["issues"]
|
||
|
||
|
||
def test_tax_rate_in_same_clause_does_not_hide_payment_percentage():
|
||
"""关键断言:同一句里先写含13%增值税、再写总价款30%时,预付款取30%,不取税率。"""
|
||
result = parse_contract_text(
|
||
"采购协议 合同号:HT-2026-006;合同总价:100,000元;"
|
||
"定金(含13%增值税)为总价款的30%;出货款40%;验收款20%;质保款10%;交货期:2026年09月01日。"
|
||
)
|
||
|
||
assert result["status"] == "parsed"
|
||
prepayment = next(item for item in result["nodes"] if item["node_type"] == "prepayment")
|
||
assert prepayment["percentage"] == "30"
|
||
assert "预付款付款比例重复,需人工确认" not in result["issues"]
|
||
|
||
|
||
def test_dms_resolve_year_folder_uses_configured_root(app, monkeypatch):
|
||
"""关键断言:DMS 先用根 FolderID 查年份目录,并返回目录记录 ID。"""
|
||
app.config.update(
|
||
CONTRACT_DMS_BASE_URL="http://dms.example",
|
||
CONTRACT_DMS_USERNAME="contract-user",
|
||
CONTRACT_DMS_PASSWORD="secret",
|
||
CONTRACT_DMS_LIBRARY_ID="library-1",
|
||
CONTRACT_DMS_ROOT_FOLDER_ID="root-1",
|
||
CONTRACT_DMS_YEAR_FOLDER_NAME_TEMPLATE="{year}年设备合同书",
|
||
)
|
||
monkeypatch.setattr(
|
||
ContractDmsClient,
|
||
"_page",
|
||
classmethod(lambda cls, **kwargs: [{"IsFolder": True, "LeafName": "2026年设备合同书", "ID": "year-2026"}]),
|
||
)
|
||
from datetime import date
|
||
|
||
assert ContractDmsClient.resolve_folder(archive_date=date(2026, 8, 1)) == "year-2026"
|
||
|
||
|
||
def test_dms_search_filters_created_date_window(app, monkeypatch):
|
||
"""关键断言:同合同编号文件按 OA 归档日期窗口筛选,过期文件不返回。"""
|
||
app.config.update(
|
||
CONTRACT_DMS_BASE_URL="http://dms.example",
|
||
CONTRACT_DMS_USERNAME="contract-user",
|
||
CONTRACT_DMS_PASSWORD="secret",
|
||
CONTRACT_DMS_LIBRARY_ID="library-1",
|
||
CONTRACT_DMS_ROOT_FOLDER_ID="root-1",
|
||
CONTRACT_DMS_LOOKUP_WINDOW_DAYS=3,
|
||
)
|
||
monkeypatch.setattr(ContractDmsClient, "resolve_folder", classmethod(lambda cls, **kwargs: "year-1"))
|
||
monkeypatch.setattr(
|
||
ContractDmsClient,
|
||
"_page",
|
||
classmethod(
|
||
lambda cls, **kwargs: [
|
||
{"IsFolder": False, "LeafName": "合同-A.pdf", "CreatedDate": "2026-08-01T10:00:00", "ID": "new"},
|
||
{"IsFolder": False, "LeafName": "合同-A.pdf", "CreatedDate": "2025-01-01T10:00:00", "ID": "old"},
|
||
]
|
||
if kwargs.get("parent_folder_id") == "year-1"
|
||
else [{"IsFolder": True, "LeafName": "暂存", "ID": "temp-1"}],
|
||
),
|
||
)
|
||
from datetime import date
|
||
|
||
rows = ContractDmsClient.search(contract_no="合同-A", archive_date=date(2026, 8, 1))
|
||
assert [row["ID"] for row in rows] == ["new"]
|
||
|
||
|
||
def test_oa_contract_detail_parses_fields_and_prefers_sealed_attachment(app):
|
||
"""关键断言:盖章上传字段优先,即使普通附件文件名更像合同正文。"""
|
||
app.config.update(
|
||
CONTRACT_PAYMENT_OA_BASE_URL="http://oa.example",
|
||
CONTRACT_PAYMENT_OA_ATTACHMENT_URL_TEMPLATE="/workflow/download?attachmentid={attachment_id}",
|
||
)
|
||
page = """
|
||
<html><body>
|
||
<h1>流程处理 - 合同申请单 - 归档 HT-20260806-30062-0</h1>
|
||
<table>
|
||
<tr><td>合同单位</td><td>测试供应商有限公司</td><td>采购单号</td><td>PO-001</td><td>申请人</td><td>张三</td></tr>
|
||
<tr><td>合同金额</td><td>221,000.00</td><td>合同书币别</td><td>人民币</td></tr>
|
||
<tr><td>合同生效日期</td><td>2026-08-06</td><td>约定到货日期</td><td>2026-09-01</td></tr>
|
||
<tr><td>合同附件</td><td><a onclick=\"downloadFile('normal-1')\">采购合同正文.pdf</a></td></tr>
|
||
<tr><td>盖章完成合同上传</td><td><a onclick=\"downloadFile('sealed-1')\">双泵压缩机方案.pdf</a></td></tr>
|
||
</table>
|
||
</body></html>
|
||
"""
|
||
with app.app_context():
|
||
result = ContractOaClient()._parse_detail_html(page, base_url="http://oa.example/workflow/detail")
|
||
|
||
# 流程编号来自 OA 表单;真实合同编号只能由附件正文解析得到。
|
||
assert result["contract_no"] == ""
|
||
assert result["workflow_no"] == "HT-20260806-30062-0"
|
||
assert result["purchase_order_no"] == "PO-001"
|
||
assert result["applicant_name"] == "张三"
|
||
assert result["total_amount"] == "221000.00"
|
||
# 关键断言:生产 OA 的“合同书币别”标签应映射到合同台账币别。
|
||
assert result["currency"] == "人民币"
|
||
assert result["delivery_due_date"] == "2026-09-01"
|
||
# 字段语义高于文件名关键词:盖章上传文件必须是第一个下载候选。
|
||
assert [item["attachment_id"] for item in result["attachments"]] == ["sealed-1", "normal-1"]
|
||
|
||
|
||
def test_oa_contract_event_uses_process_id_as_idempotency_key():
|
||
"""关键断言:待办被查看并转入已办时,流程 ID 不变,因此生成相同的幂等事件键。"""
|
||
event = ContractOaClient._build_contract_event(
|
||
{"bucket": "todo", "process_id": "30062", "archive_at": "2026-08-06 10:00:00"},
|
||
{"workflow_name": "合同申请单", "status": "归档", "contract_no": None, "workflow_no": "HT-20260806-30062-0", "attachments": []},
|
||
)
|
||
assert event is not None
|
||
assert event["source_event_id"] == "oa-contract-archive:30062"
|
||
|
||
|
||
def test_oa_contract_detail_uses_workflow_download_control(app):
|
||
"""关键断言:泛微附件的 downloads(imageFileId) 必须生成可下载的 FileDownload URL。"""
|
||
app.config.update(
|
||
CONTRACT_PAYMENT_OA_BASE_URL="http://oa.example",
|
||
CONTRACT_PAYMENT_OA_BELONGTO_USER_ID="22238",
|
||
CONTRACT_PAYMENT_OA_ATTACHMENT_URL_TEMPLATE=(
|
||
"/weaver/weaver.file.FileDownload?fileid={attachment_id}&requestid={request_id}&download=1"
|
||
),
|
||
)
|
||
page = """
|
||
<table><tr><td>盖章完成合同上传</td><td>
|
||
<table class="annexblocktblclass"><tr><td>
|
||
<a onclick="openDocExt('document-1','version-1','image-1',1)" title="盖章合同.pdf">盖章合同.pdf</a>
|
||
<a onclick="downloads('image-1')" title="下载"></a>
|
||
</td></tr></table>
|
||
<a href="/hrm/company/HrmDepartmentDsp.jsp?id=513">供应链部</a>
|
||
</td></tr></table>
|
||
"""
|
||
with app.app_context():
|
||
result = ContractOaClient()._parse_detail_html(page, base_url="http://oa.example/workflow/detail", process_id="30062")
|
||
|
||
assert result["attachments"] == [{
|
||
"attachment_id": "image-1",
|
||
"file_name": "盖章合同.pdf",
|
||
"download_url": "http://oa.example/weaver/weaver.file.FileDownload?fileid=image-1&requestid=30062&download=1",
|
||
"label": "盖章完成合同上传",
|
||
"priority": 0,
|
||
}]
|
||
|
||
|
||
def test_three_round_prepayment_alerts_follow_recipient_escalation(app, monkeypatch):
|
||
"""关键断言:预付款在归档后第 7/14/21 天分别通知申请人、OA 矩阵第二轮 zz 与第三轮 jfl。"""
|
||
from app.services.contract_payment.supervisor_oa_service import SupervisorMatrix, SupervisorMatrixCache
|
||
|
||
with app.app_context():
|
||
owner = User(username="buyer", email="buyer@example.com", status="active", real_name="李采购")
|
||
head = User(
|
||
username="head", email="head@example.com", status="active",
|
||
real_name="王主管", wecom_userid="27100",
|
||
)
|
||
leader = User(
|
||
username="leader", email="leader@example.com", status="active",
|
||
real_name="赵分管", wecom_userid="63",
|
||
)
|
||
ignored = User(
|
||
username="ignored-global", email="ignored-global@example.com", status="active",
|
||
real_name="全局岗位",
|
||
)
|
||
db.session.add_all([owner, head, leader, ignored])
|
||
db.session.flush()
|
||
app.config.update(
|
||
CONTRACT_PAYMENT_DEPARTMENT_HEAD_USER_IDS=str(ignored.id),
|
||
CONTRACT_PAYMENT_PROCUREMENT_LEADER_USER_IDS=str(ignored.id),
|
||
)
|
||
monkeypatch.setattr(
|
||
SupervisorMatrixCache,
|
||
"get",
|
||
lambda self, name: SupervisorMatrix(
|
||
applicant_oa_id=18654,
|
||
department_id=513,
|
||
round2_oa_id=27100,
|
||
round3_oa_id=63,
|
||
round2_name="王主管",
|
||
round3_name="赵分管",
|
||
ok=True,
|
||
),
|
||
)
|
||
contract = ContractPaymentContract(
|
||
contract_no="HT-001",
|
||
applicant_name="李采购",
|
||
owner_user_id=None,
|
||
oa_archive_at=datetime(2026, 8, 1, 9, 0),
|
||
status="active",
|
||
)
|
||
db.session.add(contract)
|
||
db.session.flush()
|
||
db.session.add(ContractPaymentNode(
|
||
contract_id=contract.id,
|
||
node_code="prepayment",
|
||
node_type="prepayment",
|
||
anchor_type="erp_payment",
|
||
status="active",
|
||
))
|
||
db.session.commit()
|
||
|
||
result = generate_alerts(today=date(2026, 8, 22), send=False)
|
||
rows = db.session.query(ContractPaymentAlert).order_by(ContractPaymentAlert.alert_round).all()
|
||
owner_id, head_id, leader_id = owner.id, head.id, leader.id
|
||
bound_owner_id = db.session.get(ContractPaymentContract, contract.id).owner_user_id
|
||
|
||
assert result["created"] == 3
|
||
assert [(row.alert_round, row.recipient_user_id) for row in rows] == [
|
||
(1, owner_id), (2, head_id), (3, leader_id),
|
||
]
|
||
assert bound_owner_id == owner_id
|
||
|
||
|
||
def test_round_one_recipient_ignores_stale_default_owner(app):
|
||
"""关键断言:第一轮按申请人真实姓名匹配,忽略历史上写入的默认管理员 owner_user_id。"""
|
||
with app.app_context():
|
||
stale = User(username="cp-stale-admin", email="cp-stale-admin@example.com", status="active", real_name="系统管理员")
|
||
buyer = User(username="cp-real-buyer", email="cp-real-buyer@example.com", status="active", real_name="陈申请人")
|
||
db.session.add_all([stale, buyer])
|
||
db.session.flush()
|
||
contract = ContractPaymentContract(
|
||
contract_no="HT-OWNER-STALE",
|
||
applicant_name="陈申请人",
|
||
owner_user_id=stale.id,
|
||
oa_archive_at=datetime(2026, 8, 1, 9, 0),
|
||
status="active",
|
||
)
|
||
db.session.add(contract)
|
||
db.session.flush()
|
||
db.session.add(ContractPaymentNode(
|
||
contract_id=contract.id, node_code="prepayment", node_type="prepayment", status="active",
|
||
))
|
||
db.session.commit()
|
||
|
||
result = generate_alerts(today=date(2026, 8, 8), send=False)
|
||
rows = db.session.query(ContractPaymentAlert).filter_by(contract_id=contract.id).all()
|
||
buyer_id = buyer.id
|
||
bound_owner_id = db.session.get(ContractPaymentContract, contract.id).owner_user_id
|
||
|
||
assert result["created"] == 1
|
||
assert [row.recipient_user_id for row in rows] == [buyer_id]
|
||
assert bound_owner_id == buyer_id
|
||
|
||
|
||
def test_round_one_skips_when_applicant_name_is_ambiguous_or_missing(app):
|
||
"""关键断言:申请人为空、系统无对应用户或真实姓名重名时,第一轮不发送、不兜底。"""
|
||
with app.app_context():
|
||
first = User(username="cp-dup-a", email="cp-dup-a@example.com", status="active", real_name="同名采购")
|
||
second = User(username="cp-dup-b", email="cp-dup-b@example.com", status="active", real_name="同名采购")
|
||
db.session.add_all([first, second])
|
||
db.session.flush()
|
||
missing = ContractPaymentContract(
|
||
contract_no="HT-OWNER-MISS",
|
||
applicant_name="不存在的人",
|
||
oa_archive_at=datetime(2026, 8, 1, 9, 0),
|
||
status="active",
|
||
)
|
||
dup = ContractPaymentContract(
|
||
contract_no="HT-OWNER-DUP",
|
||
applicant_name="同名采购",
|
||
oa_archive_at=datetime(2026, 8, 1, 9, 0),
|
||
status="active",
|
||
)
|
||
empty = ContractPaymentContract(
|
||
contract_no="HT-OWNER-EMPTY",
|
||
applicant_name=None,
|
||
owner_user_id=first.id,
|
||
oa_archive_at=datetime(2026, 8, 1, 9, 0),
|
||
status="active",
|
||
)
|
||
db.session.add_all([missing, dup, empty])
|
||
db.session.flush()
|
||
for row in (missing, dup, empty):
|
||
db.session.add(ContractPaymentNode(
|
||
contract_id=row.id, node_code="prepayment", node_type="prepayment", status="active",
|
||
))
|
||
db.session.commit()
|
||
|
||
result = generate_alerts(today=date(2026, 8, 8), send=False)
|
||
alerts = db.session.query(ContractPaymentAlert).filter(
|
||
ContractPaymentAlert.contract_id.in_([missing.id, dup.id, empty.id])
|
||
).all()
|
||
empty_bound = bind_contract_owner_from_applicant(db.session.get(ContractPaymentContract, empty.id))
|
||
|
||
assert result["created"] == 0
|
||
assert alerts == []
|
||
assert empty_bound is None
|
||
|
||
|
||
def test_weekly_alert_summary_counts_pending_and_next_friday(app):
|
||
"""关键断言:待发送只计 active 合同的 pending;下次发送为上海时区下周五 18:00。"""
|
||
with app.app_context():
|
||
owner = User(username="summary-owner", email="summary-owner@example.com", status="active")
|
||
db.session.add(owner)
|
||
db.session.flush()
|
||
active = ContractPaymentContract(contract_no="HT-SUMMARY-1", owner_user_id=owner.id, status="active")
|
||
inactive = ContractPaymentContract(contract_no="HT-SUMMARY-2", owner_user_id=owner.id, status="archived")
|
||
db.session.add_all([active, inactive])
|
||
db.session.flush()
|
||
active_node = ContractPaymentNode(contract_id=active.id, node_code="prepayment", node_type="prepayment", status="active")
|
||
inactive_node = ContractPaymentNode(contract_id=inactive.id, node_code="prepayment", node_type="prepayment", status="active")
|
||
db.session.add_all([active_node, inactive_node])
|
||
db.session.flush()
|
||
db.session.add_all([
|
||
ContractPaymentAlert(
|
||
contract_id=active.id, node_id=active_node.id, trigger_key="round:1:date:2026-09-01",
|
||
recipient_user_id=owner.id, alert_round=1, status="pending",
|
||
),
|
||
ContractPaymentAlert(
|
||
contract_id=active.id, node_id=active_node.id, trigger_key="round:2:date:2026-09-01",
|
||
recipient_user_id=owner.id, alert_round=2, status="sent",
|
||
),
|
||
ContractPaymentAlert(
|
||
contract_id=inactive.id, node_id=inactive_node.id, trigger_key="round:1:date:2026-09-01",
|
||
recipient_user_id=owner.id, alert_round=1, status="pending",
|
||
),
|
||
])
|
||
db.session.commit()
|
||
|
||
before_friday = build_weekly_alert_summary(now=datetime(2026, 9, 3, 1, 0))
|
||
at_send_time = build_weekly_alert_summary(now=datetime(2026, 9, 4, 10, 0))
|
||
|
||
assert before_friday["pending_count"] == 1
|
||
assert before_friday["timezone"] == "Asia/Shanghai"
|
||
assert before_friday["next_send_at"] == "2026-09-04T10:00:00Z"
|
||
assert at_send_time["next_send_at"] == "2026-09-11T10:00:00Z"
|
||
|
||
|
||
def test_weekly_excel_writes_recipient_real_name_not_role(app):
|
||
"""关键断言:企微 Excel 列名为「收件人」,单元格写系统用户真实姓名,不再写岗位名称。"""
|
||
with app.app_context():
|
||
owner = User(
|
||
username="excel-owner",
|
||
email="excel-owner@example.com",
|
||
status="active",
|
||
real_name="张三",
|
||
)
|
||
db.session.add(owner)
|
||
db.session.flush()
|
||
contract = ContractPaymentContract(
|
||
contract_no="HT-EXCEL-1",
|
||
purchase_order_no="PO-1",
|
||
supplier_name="苏州供应商",
|
||
owner_user_id=owner.id,
|
||
status="active",
|
||
)
|
||
db.session.add(contract)
|
||
db.session.flush()
|
||
node = ContractPaymentNode(
|
||
contract_id=contract.id,
|
||
node_code="shipment",
|
||
node_type="shipment",
|
||
status="active",
|
||
due_date=date(2026, 9, 1),
|
||
)
|
||
db.session.add(node)
|
||
db.session.flush()
|
||
alert = ContractPaymentAlert(
|
||
contract_id=contract.id,
|
||
node_id=node.id,
|
||
trigger_key="round:1:date:2026-09-01",
|
||
recipient_user_id=owner.id,
|
||
alert_round=1,
|
||
status="pending",
|
||
)
|
||
db.session.add(alert)
|
||
db.session.commit()
|
||
|
||
data, summary = _build_excel([(alert, contract, node, owner)])
|
||
wb = load_workbook(BytesIO(data))
|
||
headers = [cell.value for cell in wb.active[1]]
|
||
row = [cell.value for cell in wb.active[2]]
|
||
|
||
assert "收件岗位" not in headers
|
||
assert headers[10] == "收件人"
|
||
assert row[10] == "张三"
|
||
assert row[11] == "待发送"
|
||
assert "pending" not in row
|
||
assert "采购负责人" not in row
|
||
assert summary["total"] == 1
|
||
|
||
|
||
def test_recipient_display_name_falls_back_to_username(app):
|
||
"""关键断言:真实姓名为空时 Excel 收件人回退用户名,而不是岗位标签。"""
|
||
with app.app_context():
|
||
named = User(username="buyer", email="named@example.com", status="active", real_name="李采购")
|
||
unnamed = User(username="buyer02", email="unnamed@example.com", status="active", real_name=" ")
|
||
|
||
assert _recipient_display_name(named) == "李采购"
|
||
assert _recipient_display_name(unnamed) == "buyer02"
|
||
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") == "待发送"
|
||
assert _alert_status_label("sent") == "已发送"
|
||
assert _alert_status_label("failed") == "发送失败"
|
||
assert _alert_status_label("resolved") == "已关闭"
|
||
assert _alert_status_label("unknown-code") == "unknown-code"
|
||
assert _alert_status_label(None) == "—"
|
||
|
||
|
||
def test_erp_payment_amount_matches_the_corresponding_stage():
|
||
"""关键断言:不同金额的 ERP 付款必须分别匹配同金额付款阶段。"""
|
||
paid_node_ids = resolve_paid_node_ids(
|
||
[(1, "prepayment", Decimal("20000")), (2, "shipment", Decimal("30000"))],
|
||
[Decimal("30000")],
|
||
)
|
||
|
||
assert paid_node_ids == {2}
|
||
|
||
|
||
def test_erp_equal_payment_amounts_follow_prepayment_then_shipment_order():
|
||
"""关键断言:预付款、出货款同金额时,付款记录按预付款优先的业务顺序占用节点。"""
|
||
nodes = [(1, "prepayment", Decimal("30000")), (2, "shipment", Decimal("30000"))]
|
||
|
||
assert resolve_paid_node_ids(nodes, [Decimal("30000")]) == {1}
|
||
assert resolve_paid_node_ids(nodes, [Decimal("30000"), Decimal("30000")]) == {1, 2}
|
||
|
||
|
||
def test_erp_combined_payment_marks_prepayment_and_shipment_paid():
|
||
"""关键断言:预付款、出货款在同一笔请款中一并请款时,单笔付款(金额=两者之和)应同时命中两个节点。"""
|
||
nodes = [(1, "prepayment", Decimal("21600")), (2, "shipment", Decimal("21600"))]
|
||
|
||
# 分开请款:各自一份仍按节点金额分别命中。
|
||
assert resolve_paid_node_ids(nodes, [Decimal("21600")]) == {1}
|
||
assert resolve_paid_node_ids(nodes, [Decimal("43200")]) == {1, 2}
|
||
# 一笔请款同时预付款+出货款:金额等于两者之和,一次性标记两者为已付。
|
||
assert resolve_paid_node_ids(nodes, [Decimal("43200")]) == {1, 2}
|
||
|
||
|
||
def test_erp_payment_matches_acceptance_amount_without_consuming_earlier_stages():
|
||
"""关键断言:验收款金额单独命中时只标验收款,不把预付款或出货款记成已付。"""
|
||
nodes = [
|
||
(1, "prepayment", Decimal("16740")),
|
||
(2, "shipment", Decimal("27900")),
|
||
(3, "acceptance", Decimal("11160")),
|
||
]
|
||
assert resolve_paid_node_ids(nodes, [Decimal("11160")]) == {3}
|
||
"""关键断言:公司下拉框只取 selected 项,不把全部候选项拼进公司名。"""
|
||
page = """
|
||
<table><tr>
|
||
<td>公司</td>
|
||
<td>
|
||
<select name="disfield8496">
|
||
<option value=""></option>
|
||
<option value="0">和泰电子(吴江)有限公司</option>
|
||
<option value="1">和泰科技(吴江)有限公司</option>
|
||
<option value="2" selected="selected">苏州和信精密科技有限公司</option>
|
||
<option value="4">无锡和宏智散热科技有限公司</option>
|
||
</select>
|
||
<input name="field8496" value="2" />
|
||
</td>
|
||
<td>合同单位</td><td>如兮环境科技(苏州)有限公司</td>
|
||
</tr></table>
|
||
"""
|
||
with app.app_context():
|
||
result = ContractOaClient()._parse_detail_html(page, base_url="http://oa.example/workflow/detail")
|
||
assert result["company_name"] == "苏州和信精密科技有限公司"
|
||
assert result["supplier_name"] == "如兮环境科技(苏州)有限公司"
|
||
|
||
|
||
def test_oa_contract_detail_reads_company_not_supplier(app):
|
||
"""关键断言:账套使用「公司」,合同单位仍是供应商。"""
|
||
page = """
|
||
<table>
|
||
<tr><td>公司</td><td>无锡和宏智散热科技有限公司</td><td>合同单位</td><td>无锡君鑫机械制造有限公司</td></tr>
|
||
<tr><td>采购单号</td><td>5202-2608270001</td></tr>
|
||
</table>
|
||
"""
|
||
with app.app_context():
|
||
result = ContractOaClient()._parse_detail_html(page, base_url="http://oa.example/workflow/detail")
|
||
assert result["company_name"] == "无锡和宏智散热科技有限公司"
|
||
assert result["supplier_name"] == "无锡君鑫机械制造有限公司"
|
||
assert result["purchase_order_no"] == "5202-2608270001"
|
||
|
||
|
||
def test_purchase_order_no_strips_edge_spaces_and_chinese():
|
||
"""关键断言:采购单号只去掉首尾空格和汉字,中间的数字与横杠保留。"""
|
||
from app.services.contract_payment.erp_payment_service import normalize_purchase_order_no
|
||
|
||
assert normalize_purchase_order_no("5203-2608270001 杰创") == "5203-2608270001"
|
||
assert normalize_purchase_order_no(" 杰创 5203-2608270001 ") == "5203-2608270001"
|
||
assert normalize_purchase_order_no("5203-2608270001") == "5203-2608270001"
|
||
assert normalize_purchase_order_no(" ") == ""
|
||
|
||
|
||
def test_company_name_selects_erp_schema():
|
||
"""关键断言:指定公司走对应账套,全角括号与其余公司(含空公司)走 HXJM。"""
|
||
from app.services.contract_payment.erp_payment_service import erp_schema_for_company, _paid_records_sql
|
||
|
||
assert erp_schema_for_company("无锡和宏智散热科技有限公司") == "WZHHZ"
|
||
assert erp_schema_for_company("和泰科技(吴江)有限公司") == "HTT"
|
||
assert erp_schema_for_company("苏州和信精密科技有限公司") == "HXJM"
|
||
assert erp_schema_for_company("其它公司") == "HXJM"
|
||
assert erp_schema_for_company(None) == "HXJM"
|
||
assert "WZHHZ.apa_file" in _paid_records_sql("WZHHZ", ":po_0")
|
||
try:
|
||
_paid_records_sql("无锡和宏智散热科技有限公司", ":po_0")
|
||
except ValueError:
|
||
rejected = True
|
||
else:
|
||
rejected = False
|
||
assert rejected
|
||
|
||
|
||
def test_paid_fact_stays_inside_the_company_schema(app, monkeypatch):
|
||
"""关键断言:同一采购单号在 WZHHZ 已付,不能把 HXJM 合同标成已付。"""
|
||
from app.services.contract_payment.erp_payment_service import ErpPaidRow
|
||
|
||
seen: dict[str, list] = {}
|
||
|
||
def fake_fetch(orders):
|
||
seen["orders"] = list(orders)
|
||
return {("WZHHZ", "5202-2608270001"): [ErpPaidRow(amount=Decimal("18000"), paid_date="2026-09-02")]}
|
||
|
||
monkeypatch.setattr("app.services.contract_payment.alert_service.fetch_paid_records", fake_fetch)
|
||
with app.app_context():
|
||
wuxi = ContractPaymentContract(
|
||
purchase_order_no="5202-2608270001",
|
||
company_name="无锡和宏智散热科技有限公司",
|
||
oa_archive_at=datetime(2026, 9, 1, 9, 0),
|
||
status="active",
|
||
)
|
||
suzhou = ContractPaymentContract(
|
||
purchase_order_no="5202-2608270001",
|
||
company_name="苏州和信精密科技有限公司",
|
||
oa_archive_at=datetime(2026, 9, 1, 9, 0),
|
||
status="active",
|
||
)
|
||
db.session.add_all([wuxi, suzhou])
|
||
db.session.flush()
|
||
db.session.add_all([
|
||
ContractPaymentNode(
|
||
contract_id=wuxi.id, node_code="prepayment", node_type="prepayment",
|
||
amount=Decimal("18000"), anchor_type="oa_archive", status="active",
|
||
),
|
||
ContractPaymentNode(
|
||
contract_id=suzhou.id, node_code="prepayment", node_type="prepayment",
|
||
amount=Decimal("18000"), anchor_type="oa_archive", status="active",
|
||
),
|
||
])
|
||
db.session.commit()
|
||
generate_alerts(today=date(2026, 9, 2), send=False)
|
||
wuxi_status = db.session.query(ContractPaymentNode).filter_by(contract_id=wuxi.id).one().status
|
||
suzhou_status = db.session.query(ContractPaymentNode).filter_by(contract_id=suzhou.id).one().status
|
||
|
||
assert ("5202-2608270001", "无锡和宏智散热科技有限公司") in seen["orders"]
|
||
assert ("5202-2608270001", "苏州和信精密科技有限公司") in seen["orders"]
|
||
assert wuxi_status == "paid"
|
||
assert suzhou_status == "active"
|