feat(contract): 合同付款预警bug修复

This commit is contained in:
sophie committed 2026-10-28 09:09:53 +08:00
1 parent b02b776a97
commit f0334e5d22
16 files changed
+383 -104

No files matched your search

+3 -3
View File
@@ -5,7 +5,7 @@ backend/app/api/contract_payment/__init__.py
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、Agent 授权、contract_payment 服务和通用 Job 队列。
逻辑:页面查询合同、节点、本周待发送摘要、四张汇总卡和周汇总批次;失败批次返回可展示原因。同步和预警操作入队,避免请求线程执行外部系统和企微调用;发送后可按 Job 查询是否真正完成。
下载和单合同重解析走 read_contract_attachment_bytes:原文还在则直接读,被临时清理删掉则按附件 ID 从 OA/DMS 重新下载。
待确认合同的人工复核走 apply_manual_review:比例合计 100% 后改为已解析并进入台账。未付的预付款、出货款可手动标为已付。
待确认合同的人工复核走 apply_manual_review:比例合计 100% 后改为已解析并进入台账。四个付款阶段未付时都可手动标为已付。
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍;同时返回 OA 公司及对应 ERP 账套。
鉴权:查询接口要求平台管理员(is_platform_admin)或持有 `agent_code=contract_payment` 的 Agent 授权;
同步/扫描/周汇总发送仅平台管理员。权限组启用后,普通用户通过角色包获得该 Agent,不再按人授权。
@@ -641,9 +641,9 @@ def manual_review_contract(contract_id: int):
@contract_payment_bp.route("/contracts/<int:contract_id>/nodes/<int:node_id>/mark-paid", methods=["POST"])
def mark_contract_node_paid(contract_id: int, node_id: int):
"""
把未付的预付款或出货款手动标为已付。
把未付的付款阶段手动标为已付。
核心逻辑:与人工复核一样,持有合同付款 Agent 的用户即可提交。只改这一阶段,并关闭尚未发送的预警。
核心逻辑:与人工复核一样,持有合同付款 Agent 的用户即可提交。四个阶段都可以标记,只改这一阶段,并关闭尚未发送的预警。
Args:
contract_id: 合同台账主键。
@@ -3,7 +3,7 @@ services/contract_payment/alert_service.py
用途:按付款阶段生成待发送预警,在每周五按收件人汇总发送企业微信和 Excel 明细,并提供工作台待发送摘要。
依赖:合同付款模型、用户目录、openpyxl、企业微信通知服务、OA 上级矩阵、排程时区工具。
逻辑:每日任务只写入 pending 审计;周汇总任务锁定本周收件人批次,发送一条汇总卡片和一份逐笔 Excel;发送失败时把原因写入批次审计。摘要接口与周五发送使用同一 pending 口径。预付款、出货款可手动标为已付,并关闭该节点尚未发送的预警。
逻辑:每日任务只写入 pending 审计;周汇总任务锁定本周收件人批次,发送一条汇总卡片和一份逐笔 Excel;发送失败时把原因写入批次审计。摘要接口与周五发送使用同一 pending 口径。预付款、出货款、验收款、质保款都可手动标为已付,并关闭该节点尚未发送的预警。金额和比例都为 0 的阶段关闭未发送预警,不再新建。
第一轮按台账申请人 `real_name` 唯一匹配系统用户;第二、三轮查 OA HrmResource + Matrixtable_3,用 zz/jfl 作为企微 userid,不向第一轮兜底。
"""
@@ -40,6 +40,7 @@ from app.services.contract_payment.erp_payment_service import (
normalize_purchase_order_no,
resolve_paid_node_dates,
)
from app.services.contract_payment.ledger_focus import stage_has_nothing_to_pay
from app.services.contract_payment.supervisor_oa_service import SupervisorMatrixCache
from app.services.schedule.timezone_util import compute_next_run_at
@@ -52,6 +53,7 @@ class _AlertRecipient:
oa_wecom_userid: str | None = None
_ERP_PAID_STAGE_TYPES = {"prepayment", "shipment", "acceptance", "warranty"}
_ALERT_RULES: dict[str, tuple[tuple[int, str], ...]] = {
"prepayment": ((7, "owner"), (14, "department_head"), (21, "procurement_leader")),
"shipment": ((-7, "owner"), (0, "department_head"), (14, "procurement_leader")),
@@ -65,7 +67,7 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
AI 触发时机:每日排程或管理员手动执行扫描时调用。
核心逻辑:按阶段计算已到期的三轮提醒,按节点、轮次、收件人幂等;第二、三轮收件人来自 OA 部门矩阵;
ERP `apa_file` 的合格付款记录只停止尚未发送的后续轮次。
ERP `apa_file` 的合格付款记录按金额匹配四个阶段,并停止已付款阶段尚未发送的后续轮次。金额和比例都为 0 的阶段关闭未发送预警,不再新建。
Args:
today: 业务日期,未传时使用服务器日期。
send: 保留旧调用兼容参数;最新方案下始终不发送消息。
@@ -85,14 +87,20 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
payable_orders = [
(normalize_purchase_order_no(contract.purchase_order_no), contract.company_name)
for node, contract in rows
if node.node_type in {"prepayment", "shipment"} and normalize_purchase_order_no(contract.purchase_order_no)
if node.node_type in _ERP_PAID_STAGE_TYPES
and normalize_purchase_order_no(contract.purchase_order_no)
and not stage_has_nothing_to_pay(status=node.status, percentage=node.percentage, amount=node.amount)
]
paid_records = fetch_paid_records(payable_orders)
paid_node_dates: dict[int, str | None] = {}
nodes_by_ledger: dict[tuple[str, str], list[ContractPaymentNode]] = defaultdict(list)
for node, contract in rows:
purchase_order_no = normalize_purchase_order_no(contract.purchase_order_no)
if node.node_type in {"prepayment", "shipment"} and purchase_order_no:
if (
node.node_type in _ERP_PAID_STAGE_TYPES
and purchase_order_no
and not stage_has_nothing_to_pay(status=node.status, percentage=node.percentage, amount=node.amount)
):
nodes_by_ledger[(erp_schema_for_company(contract.company_name), purchase_order_no)].append(node)
for ledger_key, payment_nodes in nodes_by_ledger.items():
paid_node_dates.update(resolve_paid_node_dates(
@@ -100,6 +108,11 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
paid_records.get(ledger_key, []),
))
for node, contract in rows:
if stage_has_nothing_to_pay(status=node.status, percentage=node.percentage, amount=node.amount):
# 金额和比例都为 0 时没有应付金额,关掉尚未发送的预警,不再按日期升级。
resolved += _resolve_pending_alerts(node_id=node.id, reason="nothing_to_pay")
skipped += 1
continue
anchor = _anchor_date(contract=contract, node=node)
if anchor is None:
skipped += 1
@@ -113,7 +126,7 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
scheduled_date = anchor + timedelta(days=offset_days)
if today < scheduled_date:
continue
# ERP 合格付款先按金额匹配阶段;同金额时预付款优先于出货款。
# ERP 合格付款按金额匹配四个阶段;同金额时按预付款、出货款、验收款、质保款的顺序占用。
# 节点被匹配为已付款后,保留历史 sent,仅关闭尚未发送轮次。
if erp_paid:
resolved += _resolve_pending_alerts(node_id=node.id)
@@ -160,10 +173,10 @@ def _resolve_pending_alerts(*, node_id: int, reason: str = "erp_paid") -> int:
def mark_payment_node_paid(contract_id: int, node_id: int, payload: dict, *, operator_id: int | None = None) -> ContractPaymentContract:
"""
把一个未付的预付款或出货款手动标为已付。
把一个未付阶段手动标为已付。
核心逻辑:只改这一阶段。写入付款日期和手动来源,并关闭该节点尚未发送的预警;已发送记录保留。
验收款、质保款和已经付款的阶段不能标记。
核心逻辑:预付款、出货款、验收款、质保款都可以标记。只改这一阶段,写入付款日期和手动来源,并关闭该节点尚未发送的预警;已发送记录保留。
金额和比例都为 0、已经付款、或不是进行中的阶段不能标记。
Args:
contract_id: 合同台账主键。
@@ -186,8 +199,10 @@ def mark_payment_node_paid(contract_id: int, node_id: int, payload: dict, *, ope
node = db.session.get(ContractPaymentNode, node_id)
if node is None or node.contract_id != contract.id:
raise NotFoundError("付款节点不存在")
if node.node_type not in {"prepayment", "shipment"}:
raise ValidationError("只有预付款和出货款可以手动标为已付")
if node.node_type not in _ERP_PAID_STAGE_TYPES:
raise ValidationError("该阶段不能标为已付")
if stage_has_nothing_to_pay(status=node.status, percentage=node.percentage, amount=node.amount):
raise ValidationError("该阶段没有应付金额,不能标为已付")
if node.status == "paid":
raise ValidationError("该阶段已是已付")
if node.status != "active":
@@ -1,7 +1,7 @@
"""
backend/app/services/contract_payment/erp_payment_service.py
用途:从 ERP Oracle `apa_file` 读取采购单付款记录,作为预付款和出货款的付款完成事实来源。
用途:从 ERP Oracle `apa_file` 读取采购单付款记录,作为预付款、出货款、验收款和质保款的付款完成事实来源。
依赖:oracledb、Text2SQLService 的 Oracle 客户端初始化能力及 Flask 配置。
逻辑:按 OA「公司」选择账套后只读查询 `{账套}.apa_file`;只接受 `apa00='15'`(厂商预付款作业)且 `apa41='Y'`、`apa63=1` 的记录,并按采购单收集 `apa34f` 供明细和阶段匹配使用。
"""
@@ -17,7 +17,7 @@ from typing import Iterable
from flask import current_app
_PAYMENT_STAGE_ORDER = {"prepayment": 1, "shipment": 2}
_PAYMENT_STAGE_ORDER = {"prepayment": 1, "shipment": 2, "acceptance": 3, "warranty": 4}
# OA 合同申请单「公司」到 ERP 账套。未列出的公司默认 HXJM。标识符只允许来自这个白名单。
_SCHEMA_BY_COMPANY = {
"无锡和宏智散热科技有限公司": "WZHHZ",
@@ -100,7 +100,7 @@ def fetch_paid_records(orders: Iterable[tuple[str, str | None]]) -> dict[tuple[s
"""
按公司对应的 ERP 账套查询采购单已完成付款记录(含付款日期)。
AI 触发时机:合同付款预警每日扫描前,需要判断预付款/出货款是否已经完成付款。
AI 触发时机:合同付款预警每日扫描前,需要判断预付款、出货款、验收款、质保款是否已经完成付款。
核心逻辑:公司映射到 HXJM / WZHHZ / HTT 后,分别查询该账套的 `apa_file`;
先按 `apa00='15'` 限定为「厂商预付款作业」,再过滤 `apa41='Y'` 和 `apa63=1`,按 `apaud03` 收集 `apa34f` 与 `apa02`。
某一账套查询失败只影响该账套,其它账套继续。
@@ -234,14 +234,13 @@ def resolve_paid_node_dates(
paid_rows: Iterable[ErpPaidRow],
) -> dict[int, str | None]:
"""
将同一采购单的 ERP 付款记录匹配到预付款、出货款节点,并返回节点 ID 到付款日期的映射。
将同一采购单的 ERP 付款记录匹配到预付款、出货款、验收款、质保款节点,并返回节点 ID 到付款日期的映射。
核心逻辑:`apa00='15'`、`apa41='Y'` 且 `apa63=1` 的每笔 ERP 付款按金额与节点匹配;
金额相同则按预付款、出货款的业务顺序匹配最前面仍未付款的节点;若单节点无匹配但
「预付款+出货款」金额之和与该笔付款一致,说明预付款与出货款在同一笔请款中一并请款,
则把两者同时标记为已付款,并携带该笔付款日期。
金额相同则按预付款、出货款、验收款、质保款的业务顺序匹配最前面仍未付款的节点;若单节点无匹配但
若干阶段金额之和与该笔付款一致,则把这些阶段同时标记为已付款,并携带该笔付款日期。
Args:
nodes: 同一采购单的 `(node_id, node_type, amount)` 节点;只传预付款、出货款的 active 节点。
nodes: 同一采购单仍需付款的 `(node_id, node_type, amount)` 节点;金额为 0 的阶段不要传入。
paid_rows: 该采购单的合格 ERP 付款记录。
Returns:
已匹配节点的付款日期映射(节点 ID -> 付款日期,日期可能为空)。
@@ -268,14 +267,13 @@ def resolve_paid_node_ids(
paid_amounts: Iterable[Decimal],
) -> set[int]:
"""
将同一采购单的 ERP 付款金额匹配到预付款、出货款节点。
将同一采购单的 ERP 付款金额匹配到预付款、出货款、验收款、质保款节点。
核心逻辑:`apa00='15'`、`apa41='Y'` 且 `apa63=1` 的每笔 ERP 付款按 `apa34f` 与节点金额匹配;
金额不同则自然对应相应节点,金额相同时按预付款、出货款的业务顺序匹配最前面仍未付款的节点;
若单节点无匹配但「预付款+出货款」金额之和与该笔付款一致,则一并标记两者为已付款
(预付款、出货款在同一笔请款中一并请款的场景)。
金额不同则自然对应相应节点,金额相同时按预付款、出货款、验收款、质保款的业务顺序匹配最前面仍未付款的节点;
若单节点无匹配但若干阶段金额之和与该笔付款一致,则一并标记这些阶段为已付款。
Args:
nodes: 同一采购单的 `(node_id, node_type, amount)` 节点;只传预付款、出货款的 active 节点。
nodes: 同一采购单仍需付款的 `(node_id, node_type, amount)` 节点;金额为 0 的阶段不要传入。
paid_amounts: 该采购单的合格 ERP 每笔付款金额。
Returns:
已付款节点 ID 集合。
@@ -4,11 +4,13 @@ backend/app/services/contract_payment/ledger_focus.py
用途:合同台账汇总卡口径——即将到期、逾期未付、未到期(7日外)、本月应付,均按合同计数。
依赖:ContractPaymentContract、ContractPaymentNode、业务时区 Asia/Shanghai。
逻辑:由 list/summary API 调用;即将到期/逾期/未到期互斥,本月应付可与这三项重叠。行级「待补充」不进汇总卡。
金额和比例都为 0 的阶段不参与逾期、即将到期和本月应付。
"""
from __future__ import annotations
from collections import defaultdict
from decimal import Decimal, InvalidOperation
from datetime import date, datetime
from typing import Any, Iterable
from zoneinfo import ZoneInfo
@@ -58,6 +60,37 @@ def node_due_reference(due_date: date | None, anchor_date: date | None) -> date
return due_date or anchor_date
def stage_has_nothing_to_pay(*, status: str | None, percentage: object, amount: object) -> bool:
"""
判断付款阶段是否没有应付金额。
核心逻辑:无此阶段,或比例与金额都是 0(空值按 0)。已付阶段不按 0 处理。
与前台 isNothingToPay 一致,避免 0 元验收款、质保款把合同标成已逾期。
Args:
status: 节点状态。
percentage: 付款比例,可为 Decimal、数字或字符串。
amount: 应付金额,空值视为 0。
Returns:
无需付款时为 True。
"""
normalized = str(status or "").strip().lower()
if normalized == "not_applicable":
return True
if normalized == "paid":
return False
return _is_zero(percentage) and _is_zero(amount)
def _is_zero(value: object) -> bool:
"""空值和 0 都视为没有金额或比例;无法解析的值不当成 0。"""
if value is None or value == "":
return True
try:
return Decimal(str(value)) == 0
except (InvalidOperation, ValueError):
return False
def classify_ledger_status(
*,
contract_status: str | None,
@@ -69,11 +102,11 @@ def classify_ledger_status(
按合同聚合出台账状态,与列表「状态」列一致。
核心逻辑:非激活或待确认 → 待补充(仅行状态,不进汇总卡);无进行中节点则按是否已付分为已完成/待补充;
进行中节点若已过到期日 → 逾期,若在今天起 7 天内 → 即将到期,否则进行中。
金额和比例都为 0 的阶段不参与判断。其余进行中节点若已过到期日 → 逾期,若在今天起 7 天内 → 即将到期,否则进行中。
Args:
contract_status: 合同主状态。
parse_status: 解析状态。
nodes: 轻量节点 dict,含 status / due_date / anchor_date / paid_at。
nodes: 轻量节点 dict,含 status / due_date / anchor_date / paid_at / percentage / amount。
today: 业务日。
Returns:
overdue / due / active / completed / needs_completion。
@@ -83,7 +116,14 @@ def classify_ledger_status(
return "needs_completion"
if not node_list:
return "needs_completion"
active = [node for node in node_list if str(node.get("status") or "").strip().lower() == "active"]
active = [
node for node in node_list
if str(node.get("status") or "").strip().lower() == "active" and not stage_has_nothing_to_pay(
status=node.get("status"),
percentage=node.get("percentage"),
amount=node.get("amount"),
)
]
if not active:
has_paid = any(
str(node.get("status") or "").strip().lower() == "paid" or bool(node.get("paid_at"))
@@ -106,7 +146,7 @@ def has_unpaid_due_this_month(nodes: Iterable[dict[str, Any]], today: date) -> b
"""
合同是否有未付节点的到期日落在本自然月。
核心逻辑:只看 status=active 的节点;月份按 today 所在自然月(含 today 所在月的逾期节点)。
核心逻辑:只看 status=active 且仍有应付金额的节点;月份按 today 所在自然月(含 today 所在月的逾期节点)。
Args:
nodes: 轻量节点 dict。
today: 业务日,用于确定自然月。
@@ -118,6 +158,8 @@ def has_unpaid_due_this_month(nodes: Iterable[dict[str, Any]], today: date) -> b
for node in nodes:
if str(node.get("status") or "").strip().lower() != "active":
continue
if stage_has_nothing_to_pay(status=node.get("status"), percentage=node.get("percentage"), amount=node.get("amount")):
continue
ref = node_due_reference(node.get("due_date"), node.get("anchor_date"))
if ref and month_start <= ref < month_end:
return True
@@ -131,6 +173,8 @@ def _node_payload(node: ContractPaymentNode) -> dict[str, Any]:
"due_date": node.due_date,
"anchor_date": node.anchor_date,
"paid_at": (node.evidence_json or {}).get("paid_at"),
"percentage": node.percentage,
"amount": node.amount,
}