fix(contract): 合同付款预警bug修复
This commit is contained in:
1 parent
5330e08281
commit
161666c0e7
26 files changed
+1599
-117
No files matched your search
@@ -2,10 +2,12 @@
|
||||
backend/app/services/contract_payment/sync_service.py
|
||||
|
||||
用途:将 OA 合同、验收归档通知同步为合同付款预警事实,并由 ERP `apa_file` 提供付款完成事实。
|
||||
依赖:ContractOaClient、acceptance_oa_service、ContractPayment* 模型、parse_service。
|
||||
依赖:ContractOaClient、acceptance_oa_service、ContractPayment* 模型、parse_service、file_assets.service。
|
||||
逻辑:合同申请单走 HTTP 待办/已办;验收归档走 OA SQL(formtable_main_324.cgdh × workflow_requestbase.currentnodetype=3);
|
||||
通知按 source_event_id 幂等;合同编号与采购单号以 OA 为准;列表翻页截断时入库但不推进增量断点;
|
||||
付款状态不再读取 OA 请款作业;合同 owner_user_id 由申请人真实姓名匹配系统用户,附件存储所有者仍可回退默认账号。
|
||||
OA 合同金额为 0 或空时不当有效总额;正文抽出的正数在解析时回写台账,强制覆盖也不能把正数总额改成 0。
|
||||
OA/DMS 合同原文落库后标为已引用;临时清理删掉对象后,下载和重解析按附件 ID 重新下载。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,6 +20,7 @@ from typing import Any
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import (
|
||||
ContractPaymentAttachment,
|
||||
ContractPaymentContract,
|
||||
@@ -34,9 +37,14 @@ from app.services.contract_payment.acceptance_oa_service import (
|
||||
)
|
||||
from app.services.contract_payment.oa_client import ContractOaClient
|
||||
from app.services.contract_payment.dms_client import ContractDmsClient
|
||||
from app.services.contract_payment.parse_service import parse_contract_bytes, parse_contract_text
|
||||
from app.services.contract_payment.parse_service import parse_contract_bytes, parse_contract_text, positive_amount
|
||||
from app.services.contract_payment.alert_service import bind_contract_owner_from_applicant
|
||||
from app.services.file_assets.service import create_derived_file_asset_from_bytes, generate_asset_no
|
||||
from app.services.file_assets.service import (
|
||||
create_derived_file_asset_from_bytes,
|
||||
generate_asset_no,
|
||||
mark_asset_referenced,
|
||||
read_asset_bytes,
|
||||
)
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
|
||||
@@ -172,7 +180,7 @@ def sync_notifications(*, client: ContractOaClient | None = None, force: bool =
|
||||
purchase_order_no=str(item.get("purchase_order_no") or "").strip() or None,
|
||||
supplier_name=str(item.get("supplier_name") or "").strip() or None,
|
||||
applicant_name=str(item.get("applicant_name") or "").strip() or None,
|
||||
total_amount=item.get("total_amount"),
|
||||
total_amount=positive_amount(item.get("total_amount")),
|
||||
currency=str(item.get("currency") or "").strip() or None,
|
||||
effective_date=_as_date(item.get("effective_date")),
|
||||
delivery_due_date=_as_date(item.get("delivery_due_date")),
|
||||
@@ -192,9 +200,12 @@ def sync_notifications(*, client: ContractOaClient | None = None, force: bool =
|
||||
contract.purchase_order_no = contract.purchase_order_no or str(item.get("purchase_order_no") or "").strip() or None
|
||||
contract.applicant_name = contract.applicant_name or str(item.get("applicant_name") or "").strip() or None
|
||||
# [STEP 0] 普通同步只回填“仍为空”的 OA 标量字段,不用本次值覆盖已有值。
|
||||
# 合同金额/供应商/币别/生效/交货期限仅在创建时写入;早前创建时缺失的历史合同可由此自愈。
|
||||
# 合同金额的 0 与空相同,不能挡住正文正数,也不能用 OA 的 0 覆盖已有正数。
|
||||
contract.supplier_name = contract.supplier_name or str(item.get("supplier_name") or "").strip() or None
|
||||
contract.total_amount = contract.total_amount or item.get("total_amount")
|
||||
if positive_amount(contract.total_amount) is None:
|
||||
incoming_amount = positive_amount(item.get("total_amount"))
|
||||
if incoming_amount is not None:
|
||||
contract.total_amount = incoming_amount
|
||||
contract.currency = contract.currency or (str(item.get("currency") or "").strip() or None)
|
||||
contract.effective_date = contract.effective_date or _as_date(item.get("effective_date"))
|
||||
contract.delivery_due_date = contract.delivery_due_date or _as_date(item.get("delivery_due_date"))
|
||||
@@ -453,8 +464,8 @@ def _overwrite_oa_fields(contract: ContractPaymentContract, item: dict[str, Any]
|
||||
"""
|
||||
显式强制同步时,用 OA 本次返回的非空字段覆盖合同主表值。
|
||||
|
||||
核心逻辑:只接受 OA 明确返回的非空值,避免 OA 页面临时缺字段把本地正确值清空;同时把
|
||||
before/after 和操作人写入 source_payload_json,便于追溯“为什么金额发生变化”。
|
||||
核心逻辑:只接受 OA 明确返回的非空值,避免 OA 页面临时缺字段把本地正确值清空。
|
||||
合同金额为 0 视为未录入,不覆盖台账上已有的正数总额。变更写入 source_payload_json。
|
||||
Args:
|
||||
contract: 待更新的合同主记录。
|
||||
item: OA 合同归档事件。
|
||||
@@ -466,7 +477,7 @@ def _overwrite_oa_fields(contract: ContractPaymentContract, item: dict[str, Any]
|
||||
"purchase_order_no": lambda value: str(value).strip() or None,
|
||||
"supplier_name": lambda value: str(value).strip() or None,
|
||||
"applicant_name": lambda value: str(value).strip() or None,
|
||||
"total_amount": lambda value: value,
|
||||
"total_amount": lambda value: positive_amount(value),
|
||||
"currency": lambda value: str(value).strip() or None,
|
||||
"effective_date": lambda value: _as_date(value),
|
||||
"delivery_due_date": lambda value: _as_date(value),
|
||||
@@ -608,6 +619,155 @@ def sync_vendor_prepayment_requests(*, client: ContractOaClient) -> tuple[int, i
|
||||
return created, skipped
|
||||
|
||||
|
||||
def _stored_asset_is_readable(asset: FileAsset | None) -> bool:
|
||||
"""
|
||||
判断合同附件指向的 FileAsset 是否还能读出字节。
|
||||
|
||||
核心逻辑:软删除、上传未完成,或仍为 temporary 且已过期,都视为不可读。
|
||||
这类行不能再被普通同步当成“已保存”跳过,否则下载和重解析会一直报文件资产不存在。
|
||||
"""
|
||||
if asset is None or asset.deleted_at is not None:
|
||||
return False
|
||||
if str(asset.upload_status or "") != "ready":
|
||||
return False
|
||||
if asset.expires_at and asset.expires_at < datetime.utcnow() and str(asset.lifecycle_status or "") == "temporary":
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _retain_contract_file_asset(asset: FileAsset | None) -> None:
|
||||
"""
|
||||
把合同原文标成已引用,避免临时文件清理任务删掉 MinIO 对象。
|
||||
|
||||
核心逻辑:派生资产默认 lifecycle=temporary、reference_count=0,到期会被 cleanup 软删并删对象。
|
||||
已经是 referenced 且没有过期时间时不再 +1,避免每次下载都抬高引用计数。
|
||||
"""
|
||||
if asset is None or asset.id is None or asset.deleted_at is not None:
|
||||
return
|
||||
if (
|
||||
str(asset.lifecycle_status or "") == "referenced"
|
||||
and asset.expires_at is None
|
||||
and int(asset.reference_count or 0) > 0
|
||||
):
|
||||
return
|
||||
mark_asset_referenced(asset)
|
||||
|
||||
|
||||
def _attachment_external_id(attachment: ContractPaymentAttachment) -> str:
|
||||
"""从附件元数据或 source_key 取出 OA/DMS 侧的附件 ID。"""
|
||||
meta = attachment.metadata_json if isinstance(attachment.metadata_json, dict) else {}
|
||||
explicit = str(meta.get("attachment_id") or "").strip()
|
||||
if explicit:
|
||||
return explicit
|
||||
prefix = f"{attachment.source}:"
|
||||
key = str(attachment.source_key or "")
|
||||
if key.startswith(prefix):
|
||||
return key[len(prefix):].strip()
|
||||
return ""
|
||||
|
||||
|
||||
def _restore_contract_attachment_bytes(
|
||||
contract: ContractPaymentContract,
|
||||
attachment: ContractPaymentAttachment,
|
||||
) -> bytes:
|
||||
"""
|
||||
从 OA 或 DMS 重新下载已被清理的合同原文,并写回新的已引用 FileAsset。
|
||||
|
||||
核心逻辑:按 source 与附件 ID 拉取字节,挂到原合同父资产下,再标记 referenced。
|
||||
下载或落库失败时抛出 ATTACHMENT_UNAVAILABLE,避免前端只看到笼统的“文件资产不存在”。
|
||||
|
||||
Args:
|
||||
contract: 附件所属合同。OA 恢复使用 oa_record_id。
|
||||
attachment: 已落库但 FileAsset 不可读的附件行。
|
||||
|
||||
Returns:
|
||||
恢复后的原文字节。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 无法从原系统重新下载。code=CONTRACT_PAYMENT.ATTACHMENT_UNAVAILABLE。
|
||||
"""
|
||||
source = str(attachment.source or "").strip()
|
||||
external_id = _attachment_external_id(attachment)
|
||||
owner_id = contract.owner_user_id or _default_owner_user_id()
|
||||
try:
|
||||
if source == "oa":
|
||||
process_id = str(contract.oa_record_id or "").strip()
|
||||
if not process_id or not external_id or not owner_id:
|
||||
raise RuntimeError("缺少 OA 流程、附件 ID 或文件所有者")
|
||||
data, mime_type, response_name = ContractOaClient().download_attachment_by_id(
|
||||
process_id=process_id,
|
||||
attachment_id=external_id,
|
||||
)
|
||||
parent = _ensure_oa_parent_asset(owner_id=owner_id, contract=contract)
|
||||
asset_role = "contract_oa_attachment"
|
||||
elif source == "dms":
|
||||
if not external_id or not owner_id or not ContractDmsClient.is_configured():
|
||||
raise RuntimeError("缺少 DMS 附件 ID、文件所有者,或 DMS 未配置")
|
||||
data, mime_type, response_name = ContractDmsClient.download_attachment(external_id)
|
||||
parent = _ensure_dms_parent_asset(owner_id=owner_id, contract=contract)
|
||||
asset_role = "contract_dms_attachment"
|
||||
else:
|
||||
raise RuntimeError(f"不支持的附件来源 {source}")
|
||||
filename = (response_name or attachment.file_name or "contract").strip()[:255] or "contract"
|
||||
asset, _created = create_derived_file_asset_from_bytes(
|
||||
user_id=owner_id,
|
||||
parent=parent,
|
||||
data=data,
|
||||
filename=filename,
|
||||
mime_type=mime_type or mimetypes.guess_type(filename)[0],
|
||||
source_attachment_key=attachment.source_key,
|
||||
asset_role=asset_role,
|
||||
)
|
||||
# [STEP 1] 新落下的合同原文立刻改为已引用,避免再次进入 72 小时临时清理。
|
||||
_retain_contract_file_asset(asset)
|
||||
attachment.file_name = filename
|
||||
if mime_type:
|
||||
attachment.mime_type = mime_type[:128]
|
||||
attachment.file_asset_id = asset.id
|
||||
attachment.status = "stored"
|
||||
db.session.flush()
|
||||
return read_asset_bytes(asset)
|
||||
except NotFoundError:
|
||||
raise
|
||||
except Exception:
|
||||
current_app.logger.exception(
|
||||
"合同付款预警:合同原文已清理且重新下载失败 contract_id=%s attachment_id=%s",
|
||||
contract.id,
|
||||
attachment.id,
|
||||
)
|
||||
raise NotFoundError(
|
||||
"合同原文已被清理,且无法从原系统重新下载",
|
||||
code="CONTRACT_PAYMENT.ATTACHMENT_UNAVAILABLE",
|
||||
)
|
||||
|
||||
|
||||
def read_contract_attachment_bytes(
|
||||
contract: ContractPaymentContract,
|
||||
attachment: ContractPaymentAttachment,
|
||||
) -> bytes:
|
||||
"""
|
||||
读取合同原文。临时资产还在时顺手改为已引用;已被清理时从 OA 或 DMS 重新下载。
|
||||
|
||||
核心逻辑:先读本地 FileAsset;deleted_at 或过期 temporary 视为丢失,再按附件来源恢复。
|
||||
详情下载、单合同重解析和批量重解析都走这里,避免三处各自判断清理状态。
|
||||
|
||||
Args:
|
||||
contract: 附件所属合同,重新下载 OA 时要用 oa_record_id。
|
||||
attachment: 已落库的合同附件行。
|
||||
|
||||
Returns:
|
||||
原文字节。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 资产不存在且无法从原系统恢复。
|
||||
"""
|
||||
asset = db.session.get(FileAsset, attachment.file_asset_id) if attachment.file_asset_id else None
|
||||
if _stored_asset_is_readable(asset):
|
||||
_retain_contract_file_asset(asset)
|
||||
return read_asset_bytes(asset)
|
||||
return _restore_contract_attachment_bytes(contract, attachment)
|
||||
|
||||
|
||||
def save_oa_attachments(
|
||||
contract: ContractPaymentContract,
|
||||
*,
|
||||
@@ -651,10 +811,15 @@ def save_oa_attachments(
|
||||
contract_id=contract.id, source="oa", source_key=source_key
|
||||
).first()
|
||||
if existing and existing.file_asset_id and existing.status == "stored":
|
||||
# 已保存的附件不得随普通 OA 增量同步重复解析:该同步可能与详情页单合同重解析
|
||||
# 并发,旧解析结果会覆盖人工刚确认的状态。规则升级时只能由显式批量重解析执行。
|
||||
contract.status = "active"
|
||||
return {"found": len(attachments), "saved": saved}
|
||||
stored_asset = db.session.get(FileAsset, existing.file_asset_id)
|
||||
if _stored_asset_is_readable(stored_asset):
|
||||
# 已保存且仍可读的附件不得随普通 OA 增量同步重复解析:该同步可能与详情页单合同重解析
|
||||
# 并发,旧解析结果会覆盖人工刚确认的状态。规则升级时只能由显式批量重解析执行。
|
||||
# 顺手把仍是 temporary 的历史附件标为已引用,避免清理任务之后删掉原文。
|
||||
_retain_contract_file_asset(stored_asset)
|
||||
contract.status = "active"
|
||||
return {"found": len(attachments), "saved": saved}
|
||||
# 资产已被临时文件清理删掉时不要跳过,继续按当前 OA 下载地址重新落库。
|
||||
try:
|
||||
current_app.logger.info("合同付款预警:开始下载 OA 附件 attachment_id=%s label=%s", attachment_id, attachment.get("label"))
|
||||
data, mime_type, response_name = client.download_attachment(attachment)
|
||||
@@ -669,6 +834,7 @@ def save_oa_attachments(
|
||||
source_attachment_key=source_key,
|
||||
asset_role="contract_oa_attachment",
|
||||
)
|
||||
_retain_contract_file_asset(asset)
|
||||
if existing is None:
|
||||
existing = ContractPaymentAttachment(
|
||||
contract_id=contract.id, source="oa", source_key=source_key, file_name=filename
|
||||
@@ -686,7 +852,6 @@ def save_oa_attachments(
|
||||
contract.status = "active"
|
||||
db.session.flush()
|
||||
try:
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
build_payment_plan_from_bytes(contract, filename=filename, data=read_asset_bytes(asset))
|
||||
except Exception:
|
||||
current_app.logger.exception("合同付款预警:OA 附件已保存但付款条款解析失败,合同编号=%s", contract.contract_no)
|
||||
@@ -737,8 +902,9 @@ def reparse_existing_contracts(*, limit: int = 1000) -> dict[str, int]:
|
||||
使用已归档附件批量刷新存量合同解析结果。
|
||||
|
||||
AI 触发时机:解析规则升级后,管理员需要清理数据库中遗留的旧待确认原因时调用。
|
||||
核心逻辑:不依赖 OA 增量通知,直接按“盖章完成合同上传”优先选择已保存附件并重跑解析;
|
||||
没有可用附件的合同跳过,解析失败的合同保留 needs_review。
|
||||
核心逻辑:不走 OA 增量通知列表,按“盖章完成合同上传”优先选择已保存附件并重跑解析。
|
||||
原文若已被临时文件清理删除,则按附件 ID 从 OA 或 DMS 重新下载后再解析,不改 OA 表单字段。
|
||||
没有可用附件的合同跳过;解析失败的合同保留 needs_review;仅重新下载失败时不改解析状态。
|
||||
Args:
|
||||
limit: 本次最多重解析合同数,防止单个 Job 长时间占用 Worker。
|
||||
Returns:
|
||||
@@ -746,7 +912,6 @@ def reparse_existing_contracts(*, limit: int = 1000) -> dict[str, int]:
|
||||
"""
|
||||
rows = db.session.query(ContractPaymentContract).order_by(ContractPaymentContract.id.asc()).limit(max(int(limit or 0), 0)).all()
|
||||
scanned = reparsed = failed = skipped = 0
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
for contract in rows:
|
||||
scanned += 1
|
||||
attachments = (
|
||||
@@ -759,13 +924,12 @@ def reparse_existing_contracts(*, limit: int = 1000) -> dict[str, int]:
|
||||
skipped += 1
|
||||
continue
|
||||
attachment = min(attachments, key=lambda row: (0 if str((row.metadata_json or {}).get("label") or "").strip() == "盖章完成合同上传" else 1, row.id))
|
||||
asset = db.session.get(FileAsset, attachment.file_asset_id)
|
||||
if not asset:
|
||||
skipped += 1
|
||||
continue
|
||||
try:
|
||||
build_payment_plan_from_bytes(contract, filename=attachment.file_name, data=read_asset_bytes(asset))
|
||||
data = read_contract_attachment_bytes(contract, attachment)
|
||||
build_payment_plan_from_bytes(contract, filename=attachment.file_name, data=data)
|
||||
reparsed += 1
|
||||
except NotFoundError:
|
||||
failed += 1
|
||||
except Exception:
|
||||
failed += 1
|
||||
contract.parse_status = "needs_review"
|
||||
@@ -814,8 +978,11 @@ def supplement_from_dms(contract: ContractPaymentContract) -> dict[str, int]:
|
||||
source_key = f"dms:{attachment_id}"
|
||||
existing = db.session.query(ContractPaymentAttachment).filter_by(contract_id=contract.id, source="dms", source_key=source_key).first()
|
||||
if existing and existing.file_asset_id:
|
||||
contract.status = "active"
|
||||
return {"found": 1, "saved": 0}
|
||||
stored_asset = db.session.get(FileAsset, existing.file_asset_id)
|
||||
if _stored_asset_is_readable(stored_asset):
|
||||
_retain_contract_file_asset(stored_asset)
|
||||
contract.status = "active"
|
||||
return {"found": 1, "saved": 0}
|
||||
try:
|
||||
data, mime_type, response_name = ContractDmsClient.download_attachment(attachment_id)
|
||||
filename = response_name or str(row.get("LeafName") or "contract").strip() or "contract"
|
||||
@@ -838,6 +1005,7 @@ def supplement_from_dms(contract: ContractPaymentContract) -> dict[str, int]:
|
||||
source_attachment_key=source_key,
|
||||
asset_role="contract_dms_attachment",
|
||||
)
|
||||
_retain_contract_file_asset(asset)
|
||||
if existing is None:
|
||||
existing = ContractPaymentAttachment(contract_id=contract.id, source="dms", source_key=source_key, file_name=filename[:255])
|
||||
db.session.add(existing)
|
||||
@@ -852,7 +1020,6 @@ def supplement_from_dms(contract: ContractPaymentContract) -> dict[str, int]:
|
||||
db.session.flush()
|
||||
# 解析服务读取私有 FileAsset;失败时保留已保存附件并进入待复核。
|
||||
try:
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
build_payment_plan_from_bytes(contract, filename=filename, data=read_asset_bytes(asset))
|
||||
except Exception:
|
||||
contract.parse_status = "needs_review"
|
||||
@@ -962,9 +1129,10 @@ def build_payment_plan(contract: ContractPaymentContract, *, text: str = "") ->
|
||||
|
||||
def _persist_payment_plan(contract: ContractPaymentContract, *, result: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
持久化条款与节点,并只用附件正文回填真实合同编号。
|
||||
持久化条款与节点,并用正文正数金额回填台账总额。
|
||||
|
||||
核心逻辑:保持节点编码稳定以支持重解析覆盖;仅解析成功时启用提醒,防止不完整条款触发正式通知。
|
||||
台账总额为 0 或空、且本次解析得到正数金额时,用该正数覆盖 0。已有正数总额不被正文改写。
|
||||
若验收归档事件已先入库,节点生成后立即回放归档日到验收款/质保款。
|
||||
Args:
|
||||
contract: 当前合同台账记录。
|
||||
@@ -992,9 +1160,10 @@ def _persist_payment_plan(contract: ContractPaymentContract, *, result: dict[str
|
||||
contract.parse_status = "needs_review"
|
||||
else:
|
||||
contract.contract_no = parsed_contract_no
|
||||
if not contract.total_amount and fields.get("total_amount"):
|
||||
from decimal import Decimal
|
||||
contract.total_amount = Decimal(str(fields["total_amount"]))
|
||||
# [STEP 2] OA 手填 0 不是有效总额。解析结果里的正数(正文优先,否则为 OA 正数)只填补 0 或空值。
|
||||
parsed_amount = positive_amount(fields.get("total_amount"))
|
||||
if parsed_amount is not None and positive_amount(contract.total_amount) is None:
|
||||
contract.total_amount = parsed_amount
|
||||
contract.parse_result_json = result
|
||||
contract.parse_status = str(result.get("status") or "needs_review")
|
||||
contract.warranty_period_days = fields.get("warranty_period_days") or contract.warranty_period_days
|
||||
|
||||
Reference in new issue
Block a user