""" backend/app/services/contract_payment/sync_service.py 用途:将 OA 合同、验收归档通知同步为合同付款预警事实,并由 ERP `apa_file` 提供付款完成事实。 依赖:ContractOaClient、acceptance_oa_service、ContractPayment* 模型、parse_service。 逻辑:合同申请单走 HTTP 待办/已办;验收归档走 OA SQL(formtable_main_324.cgdh × workflow_requestbase.currentnodetype=3); 通知按 source_event_id 幂等;合同编号与采购单号以 OA 为准;列表翻页截断时入库但不推进增量断点; 付款状态不再读取 OA 请款作业;合同 owner_user_id 由申请人真实姓名匹配系统用户,附件存储所有者仍可回退默认账号。 """ from __future__ import annotations from datetime import date, datetime, timedelta import hashlib import mimetypes from typing import Any from flask import current_app from app import db from app.models import ( ContractPaymentAttachment, ContractPaymentContract, ContractPaymentEvent, ContractPaymentNode, ContractPaymentSyncState, ContractPaymentVendorRequest, FileAsset, User, ) from app.services.contract_payment.acceptance_oa_service import ( fetch_archived_acceptances, source_event_id as acceptance_source_event_id, ) 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.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.storage import file_asset_storage # OA 合同归档通知增量同步断点键:同一键只存一行,记录上次成功同步位置。 _OA_ARCHIVE_SYNC_STATE_KEY = "oa-contract-archive" # 验收归档走独立 SQL 断点,避免合同 HTTP 列表截断绑死验收扫描。 _OA_ACCEPTANCE_SYNC_STATE_KEY = "oa-acceptance-archive" def compute_oa_sync_since( *, now: datetime | None = None, state_key: str = _OA_ARCHIVE_SYNC_STATE_KEY, ) -> tuple[datetime | None, ContractPaymentSyncState | None]: """ 计算本次 OA 同步的时间下限,并返回对应断点行。 AI 触发时机:`sync_notifications` 每次运行开始时调用。 核心逻辑: - 没有断点(首次)返回 `(None, None)`,即全量扫描,保证历史归档完整入库; - 已有断点则用 `last_successful_sync_at - overlap` 作为 since,overlap 兜住上轮结束前后的迟到/越序记录, 重复项由 `(event_type, source_event_id)` 幂等键去重,实现「只拉新增、重复运行不重复入库」。 Args: now: 当前时间;测试可注入。缺省使用系统 UTC 时间。 state_key: 断点键;合同 HTTP 列表与验收 SQL 分键存储。 Returns: `(since, state)`;`since` 为 None 表示全量。 """ now = now or datetime.utcnow() row = db.session.query(ContractPaymentSyncState).filter_by(state_key=state_key).first() if row is None or row.last_successful_sync_at is None: return None, row overlap = max(int(current_app.config.get("CONTRACT_PAYMENT_OA_SYNC_OVERLAP_SECONDS", 3600) or 3600), 0) since = row.last_successful_sync_at - timedelta(seconds=overlap) return since, row def _advance_oa_sync_state( state: ContractPaymentSyncState | None, *, max_archive_at: datetime | None = None, processed: int = 0, now: datetime | None = None, state_key: str = _OA_ARCHIVE_SYNC_STATE_KEY, ) -> ContractPaymentSyncState: """ 推进 OA 增量同步断点:记录本次成功同步时间、迄今见到的最大归档时间与已处理数。 核心逻辑:仅在整批合同同步提交前调用;失败不调用,事务回滚时断点不前进,下次仍按旧窗口重扫。 `last_archive_seen_at` 单调递增(取历史最大值),供运维查看用了多久翻到最新归档。 Args: state: 已存在的断点行;为 None 时新建。 max_archive_at: 本次处理到的最大归档时间,可为 None。 processed: 本次新建合同与事件总数。 now: 当前时间;测试可注入。 state_key: 新建断点时使用的键;已有行不改键。 Returns: 更新后的断点行(已加入当前 session,尚未提交)。 """ now = now or datetime.utcnow() if state is None: state = ContractPaymentSyncState(state_key=state_key) db.session.add(state) state.last_successful_sync_at = now state.last_run_at = now state.synced_contract_count = int(state.synced_contract_count or 0) + processed if max_archive_at is not None: previous = state.last_archive_seen_at if previous is None or max_archive_at > previous: state.last_archive_seen_at = max_archive_at return state def sync_notifications(*, client: ContractOaClient | None = None, force: bool = False, operator_id: int | None = None) -> dict[str, int]: """ 同步 OA 合同申请单与资产验收单归档事实。 AI 触发时机:定时任务或管理接口要求增量读取 OA 通知时调用。 约束:没有稳定事件 ID/合同编号的通知只记录跳过计数,不创建不完整合同。force 仅由显式管理员 操作传入,用本次 OA 明确返回的非空字段覆盖已有 OA 字段,并保留字段变更审计;同时全量重扫验收 SQL。 """ client = client or ContractOaClient() oa_config = client.configuration_status() sync_since, sync_state = compute_oa_sync_since() acceptance_since, acceptance_state = compute_oa_sync_since(state_key=_OA_ACCEPTANCE_SYNC_STATE_KEY) if force: # 强制同步由管理员显式触发,用于修正窗口外存量字段:绕过时间窗口,全量重扫 OA。 # 对应 POST /sync 的 { force: true },覆盖 采购单号/金额 等字段,并保留 before/after 审计。 sync_since = None acceptance_since = None max_archive_at: datetime | None = None created_contracts = created_events = oa_found = oa_saved = dms_found = dms_saved = skipped = overwritten = 0 acceptance_found = acceptance_saved = acceptance_skipped = 0 acceptance_error = False notifications, worklist_truncated = client.fetch_notifications(since=sync_since) current_app.logger.info( "合同付款预警:开始同步 OA 合同通知,通知数=%d truncated=%s since=%s force=%s", len(notifications), worklist_truncated, sync_since.isoformat(sep=" ", timespec="seconds") if sync_since else "全量", force, ) for item in notifications: source_id = str(item.get("source_event_id") or item.get("id") or "").strip() event_type = str(item.get("event_type") or "").strip() contract_no = str(item.get("contract_no") or "").strip() or None oa_record_id = str(item.get("oa_record_id") or "").strip() or None workflow_no = str(item.get("workflow_no") or "").strip() or None if not source_id or not event_type: skipped += 1 continue archive_at = _as_datetime(item.get("archive_at")) if archive_at and (max_archive_at is None or archive_at > max_archive_at): max_archive_at = archive_at contract = ( db.session.query(ContractPaymentContract).filter_by(oa_record_id=oa_record_id).first() if oa_record_id else None ) if contract is None and contract_no: contract = db.session.query(ContractPaymentContract).filter_by(contract_no=contract_no).first() if contract is None and event_type == "acceptance_archive": purchase_order_no = str(item.get("purchase_order_no") or "").strip() if purchase_order_no: contract = ( db.session.query(ContractPaymentContract) .filter_by(purchase_order_no=purchase_order_no) .first() ) if event_type == "contract_archive": if contract is None: contract = ContractPaymentContract( contract_no=contract_no, 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"), 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")), owner_user_id=None, oa_record_id=oa_record_id, workflow_no=workflow_no, oa_archive_at=_as_datetime(item.get("archive_at")) or datetime.utcnow(), source_payload_json=item, ) db.session.add(contract) db.session.flush() bind_contract_owner_from_applicant(contract) created_contracts += 1 else: if force: overwritten += _overwrite_oa_fields(contract, item, operator_id=operator_id) 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 标量字段,不用本次值覆盖已有值。 # 合同金额/供应商/币别/生效/交货期限仅在创建时写入;早前创建时缺失的历史合同可由此自愈。 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") 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")) contract.workflow_no = contract.workflow_no or workflow_no contract.oa_record_id = contract.oa_record_id or oa_record_id # 保留强制覆盖审计;原始 OA 载荷仍以本次同步结果为准。 contract.source_payload_json = _with_force_sync_audit(item, contract.source_payload_json) bind_contract_owner_from_applicant(contract) existing_event = db.session.query(ContractPaymentEvent).filter_by(event_type=event_type, source_event_id=source_id).first() if existing_event is None: db.session.add(ContractPaymentEvent( contract_id=contract.id, event_type=event_type, event_date=_as_date(item.get("archive_at")) or date.today(), source_event_id=source_id, payload_json=item, )) created_events += 1 # [STEP 1] OA 是主来源。即使归档事件已处理,也允许对曾经下载失败的附件安全重试。 current_app.logger.info( "合同付款预警:处理合同 event=%s contract_no=%s,开始保存 OA 附件", event_type, contract_no, ) oa_result = save_oa_attachments(contract, item=item, client=client) current_app.logger.info( "合同付款预警:合同 contract_no=%s 保存 OA 附件完成 found=%d saved=%d", contract_no, oa_result["found"], oa_result["saved"], ) # 兼容历史版本写入的“固定模板”错误:当前解析规则已取消模板准入,普通同步时 # 仅清理这类陈旧原因,不重新解析、不改动其他真实待确认问题。 _clear_legacy_template_review(contract) oa_found += oa_result["found"] oa_saved += oa_result["saved"] # [STEP 2] 仅当 OA 没有取得合同文件时,才以 DMS 作为延迟补充来源。 if not oa_result["saved"] and not db.session.query(ContractPaymentAttachment).filter_by(contract_id=contract.id, source="oa", status="stored").first(): current_app.logger.info("合同付款预警:OA 无附件,尝试 DMS 补充 contract_no=%s", contract_no) dms_result = supplement_from_dms(contract) dms_found += dms_result["found"] dms_saved += dms_result["saved"] elif event_type == "acceptance_archive": if contract is None: skipped += 1 continue if db.session.query(ContractPaymentEvent).filter_by(event_type=event_type, source_event_id=source_id).first(): apply_acceptance_archive_to_nodes( contract, _as_date(item.get("archive_at") or item.get("acceptance_date")), ) continue archive_date = _as_date(item.get("archive_at") or item.get("acceptance_date")) or date.today() db.session.add(ContractPaymentEvent( contract_id=contract.id, event_type=event_type, event_date=archive_date, source_event_id=source_id, payload_json=item, )) created_events += 1 apply_acceptance_archive_to_nodes(contract, archive_date) # [STEP 2.5] 验收归档主来源改为 OA SQL:资产验收单 formtable_main_324.cgdh 对采购单号, # workflow_requestbase.currentnodetype='3'(归档)。HTTP 列表几乎收不到验收事件,此处独立扫描并幂等落库。 # SQL 失败不打断已处理的合同 HTTP 结果,且不推进验收断点。 backfill_pos = _purchase_orders_awaiting_acceptance() if acceptance_since is not None else [] acceptance_items, acceptance_ok = fetch_archived_acceptances( since=acceptance_since, purchase_order_nos=backfill_pos, ) if not acceptance_ok: acceptance_error = True else: acceptance_found = len(acceptance_items) acceptance_saved, acceptance_skipped = ingest_acceptance_archives(acceptance_items) created_events += acceptance_saved skipped += acceptance_skipped max_acceptance_at: datetime | None = None for acc_item in acceptance_items: acc_at = _as_datetime(acc_item.get("archive_at")) if acc_at and (max_acceptance_at is None or acc_at > max_acceptance_at): max_acceptance_at = acc_at _advance_oa_sync_state( acceptance_state, max_archive_at=max_acceptance_at, processed=acceptance_saved, state_key=_OA_ACCEPTANCE_SYNC_STATE_KEY, ) # [STEP 3] 兼容清理所有历史解析结果中的固定模板残留,避免 OA 事件因幂等或时间窗口未返回 # 时旧提示继续留在页面;只删除已废弃的模板问题,不重跑附件、不改 OA 字段。 for stale_contract in db.session.query(ContractPaymentContract).filter(ContractPaymentContract.parse_result_json.is_not(None)).all(): _clear_legacy_template_review(stale_contract) # [STEP 4] 付款完成状态改由预警扫描查询 ERP `apa_file`,同步阶段不再访问 OA 厂商预付款请款作业。 current_app.logger.info("合同付款预警:开始扫描待补/ERP 付款状态") pending = supplement_pending_contracts() dms_found += pending["found"] dms_saved += pending["saved"] # [STEP 5] 仅当 OA 已配置且列表完整翻完时推进增量断点。 # 列表被页上限截断时保留已入库数据,但不前进 last_successful_sync_at,下次仍按原窗口补扫漏页。 if oa_config["configured"] and oa_config["list_configured"] and not worklist_truncated: _advance_oa_sync_state( sync_state, max_archive_at=max_archive_at, processed=created_contracts + created_events - acceptance_saved, ) elif worklist_truncated: current_app.logger.warning("合同付款预警:OA 列表翻页截断,已同步记录保留,增量断点不前进") db.session.commit() return { "created_contracts": created_contracts, "created_events": created_events, "created_vendor_requests": 0, "oa_configured": oa_config["configured"], "oa_list_configured": oa_config["list_configured"], "oa_missing_config": oa_config["missing"], "oa_attachment_template_configured": oa_config.get("attachment_template_configured", False), "oa_candidates": oa_found, "oa_found": oa_found, "oa_saved": oa_saved, "dms_found": dms_found, "dms_saved": dms_saved, "skipped": skipped, "force": force, "overwritten_fields": overwritten, "oa_worklist_truncated": worklist_truncated, "acceptance_found": acceptance_found, "acceptance_saved": acceptance_saved, "acceptance_skipped": acceptance_skipped, "acceptance_error": acceptance_error, } def apply_acceptance_archive_to_nodes( contract: ContractPaymentContract, archive_date: date | None, ) -> None: """ 把验收归档日写到验收款、质保款节点。 核心逻辑:同一采购单多张验收单取更早日期,避免后到的归档把已起算的锚点推后。 已清空金额/比例的陈旧节点不再回写,以免重解析淘汰的阶段被验收事件复活。 Args: contract: 合同台账。 archive_date: 验收单归档日;空则忽略。 Returns: None。 """ if archive_date is None: return for node in db.session.query(ContractPaymentNode).filter( ContractPaymentNode.contract_id == contract.id, ContractPaymentNode.node_type.in_(("acceptance", "warranty")), ): if node.percentage is None and node.amount is None: continue if node.anchor_date is None or archive_date < node.anchor_date: node.anchor_date = archive_date if node.node_type == "acceptance": node.due_date = node.anchor_date elif contract.warranty_period_days and node.anchor_date: node.due_date = node.anchor_date + timedelta(days=int(contract.warranty_period_days)) def refresh_acceptance_nodes_from_events(contract: ContractPaymentContract) -> None: """ 用该合同已保存的最早验收归档事件回放节点日期。 AI 触发时机:付款计划刚持久化(验收事件可能先于节点生成)或验收 SQL 入库后调用。 核心逻辑:按 event_date 升序取第一条 acceptance_archive,再套用 apply_acceptance_archive_to_nodes。 Args: contract: 合同台账。 Returns: None。 """ event = ( db.session.query(ContractPaymentEvent) .filter_by(contract_id=contract.id, event_type="acceptance_archive") .order_by(ContractPaymentEvent.event_date.asc()) .first() ) if event is None: return apply_acceptance_archive_to_nodes(contract, event.event_date) def ingest_acceptance_archives(items: list[dict[str, Any]]) -> tuple[int, int]: """ 按采购单号把 OA SQL 验收归档写入事件表并刷新节点。 核心逻辑:cgdh 精确匹配 purchase_order_no;无合同则跳过(下次增量用采购单号回补); source_event_id 含 requestId 与合同 ID,重复运行不重复入库。 Args: items: fetch_archived_acceptances 返回的事件字典列表。 Returns: `(created, skipped)`。 """ created = skipped = 0 touched_ids: set[int] = set() for item in items: purchase_order_no = str(item.get("purchase_order_no") or "").strip() request_id = str(item.get("request_id") or "").strip() if not purchase_order_no or not request_id: skipped += 1 continue contracts = ( db.session.query(ContractPaymentContract) .filter_by(purchase_order_no=purchase_order_no) .all() ) if not contracts: skipped += 1 continue archive_date = _as_date(item.get("archive_at")) or date.today() for contract in contracts: source_id = acceptance_source_event_id(request_id, contract.id) existing = ( db.session.query(ContractPaymentEvent) .filter_by(event_type="acceptance_archive", source_event_id=source_id) .first() ) if existing is None: db.session.add(ContractPaymentEvent( contract_id=contract.id, event_type="acceptance_archive", event_date=archive_date, source_event_id=source_id, payload_json=item, )) created += 1 touched_ids.add(contract.id) for contract_id in touched_ids: contract = db.session.get(ContractPaymentContract, contract_id) if contract is not None: refresh_acceptance_nodes_from_events(contract) return created, skipped def _purchase_orders_awaiting_acceptance() -> list[str]: """ 列出已有采购单号、尚无验收归档事件的合同,供 SQL 窗口外回补。 Returns: 去重后的采购单号列表。 """ accepted_ids = ( db.session.query(ContractPaymentEvent.contract_id) .filter(ContractPaymentEvent.event_type == "acceptance_archive") ) rows = ( db.session.query(ContractPaymentContract.purchase_order_no) .filter(ContractPaymentContract.purchase_order_no.isnot(None)) .filter(ContractPaymentContract.purchase_order_no != "") .filter(~ContractPaymentContract.id.in_(accepted_ids)) .distinct() .all() ) return [str(po).strip() for (po,) in rows if str(po or "").strip()] def _overwrite_oa_fields(contract: ContractPaymentContract, item: dict[str, Any], *, operator_id: int | None = None) -> int: """ 显式强制同步时,用 OA 本次返回的非空字段覆盖合同主表值。 核心逻辑:只接受 OA 明确返回的非空值,避免 OA 页面临时缺字段把本地正确值清空;同时把 before/after 和操作人写入 source_payload_json,便于追溯“为什么金额发生变化”。 Args: contract: 待更新的合同主记录。 item: OA 合同归档事件。 operator_id: 发起强制同步的用户 ID,可为空(定时任务不应默认强制覆盖)。 Returns: 实际发生覆盖的字段数量。 """ field_parsers = { "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, "currency": lambda value: str(value).strip() or None, "effective_date": lambda value: _as_date(value), "delivery_due_date": lambda value: _as_date(value), "workflow_no": lambda value: str(value).strip() or None, "oa_archive_at": lambda value: _as_datetime(value), } changed: dict[str, dict[str, Any]] = {} for field, parser in field_parsers.items(): if field not in item or item.get(field) in (None, "", "—"): continue before = getattr(contract, field) after = parser(item.get(field)) if after is None: continue before_text = before.isoformat() if hasattr(before, "isoformat") else str(before) if before is not None else None after_text = after.isoformat() if hasattr(after, "isoformat") else str(after) if after is not None else None if before_text == after_text: continue setattr(contract, field, after) changed[field] = {"before": before_text, "after": after_text} if changed: payload = dict(contract.source_payload_json or {}) audit = list(payload.get("force_sync_audit") or []) audit.append({"operator_id": operator_id, "at": datetime.utcnow().isoformat(), "changed_fields": changed}) payload["force_sync_audit"] = audit[-20:] contract.source_payload_json = payload bind_contract_owner_from_applicant(contract) return len(changed) def _with_force_sync_audit(item: dict[str, Any], previous_payload: dict[str, Any] | None) -> dict[str, Any]: """ 使用本次 OA 原始载荷更新来源信息,并保留历史强制同步审计。 Args: item: 本次 OA 返回的合同归档事件。 previous_payload: 当前合同已保存的来源载荷,可能包含强制同步审计。 Returns: 最新 OA 载荷及保留的强制同步审计。 """ payload = dict(item) audit = (previous_payload or {}).get("force_sync_audit") if audit: payload["force_sync_audit"] = audit return payload def _clear_legacy_template_review(contract: ContractPaymentContract) -> bool: """ 清理历史版本残留的固定模板待确认原因。 核心逻辑:当前解析器不再执行模板匹配;仅删除旧 JSON 中的模板错误,保留其他真实问题。 若问题已全部清除,则同步恢复合同、计划和节点状态,否则继续保持待确认。 Args: contract: 待兼容处理的合同主记录。 Returns: 是否删除了至少一条历史模板问题。 """ result = contract.parse_result_json if not isinstance(result, dict) or not isinstance(result.get("issues"), list): return False issues = result["issues"] cleaned = [issue for issue in issues if "未匹配设备采购合同" not in str(issue)] if len(cleaned) == len(issues): return False updated = dict(result) updated["issues"] = cleaned evidence = dict(updated.get("evidence") or {}) evidence["parser"] = "contract-payment-four-stage-rules" updated["evidence"] = evidence updated["status"] = "parsed" if not cleaned else "needs_review" contract.parse_result_json = updated contract.parse_status = updated["status"] contract.plan_status = "active" if updated["status"] == "parsed" else "needs_review" for node in db.session.query(ContractPaymentNode).filter_by(contract_id=contract.id).all(): node.status = "active" if updated["status"] == "parsed" else "needs_review" return True def sync_vendor_prepayment_requests(*, client: ContractOaClient) -> tuple[int, int]: """ 兼容保留的 OA 厂商预付款请款同步函数(当前付款完成判断不再调用)。 付款完成状态已改由 ERP `apa_file` 查询;此函数仅为历史调用方保留,新的同步流程不会调用。 AI 触发时机:`sync_notifications` 完成合同事件同步后调用。 核心逻辑:按合同号优先、采购单号兜底匹配;同一 OA 请求 ID 幂等更新; 无法唯一关联或阶段不明确的记录只计入 skipped,避免误停止其它合同的提醒。 Args: client: 已创建的 OA 客户端,用于复用登录会话。 Returns: `(created, skipped)`,分别代表新增请款事实数量和安全跳过数量。 """ created = skipped = 0 for item in client.fetch_vendor_prepayment_requests(): source_request_id = str(item.get("source_request_id") or "").strip() stage = str(item.get("payment_stage") or "").strip() if not source_request_id or stage not in {"prepayment", "shipment"}: skipped += 1 continue contract_no = str(item.get("contract_no") or "").strip() purchase_order_no = str(item.get("purchase_order_no") or "").strip() if not contract_no and not purchase_order_no: skipped += 1 continue # [STEP 1] 合同号是首选匹配键;历史 OA 作业可能尚未回填合同号, # 此时才回退采购单号。两个键均无法唯一关联时 fail-safe 跳过。 matches = ( db.session.query(ContractPaymentContract) .filter(ContractPaymentContract.contract_no == contract_no) .limit(2) .all() if contract_no else [] ) if len(matches) != 1 and purchase_order_no: matches = ( db.session.query(ContractPaymentContract) .filter(ContractPaymentContract.purchase_order_no == purchase_order_no) .limit(2) .all() ) if len(matches) != 1: skipped += 1 continue row = db.session.query(ContractPaymentVendorRequest).filter_by(source_request_id=source_request_id).first() if row is None: row = ContractPaymentVendorRequest( contract_id=matches[0].id, source_request_id=source_request_id, payment_stage=stage, ) db.session.add(row) created += 1 row.request_no = str(item.get("request_no") or "").strip() or None row.request_status = str(item.get("request_status") or "").strip() or None row.requested_at = _as_datetime(item.get("requested_at")) row.payload_json = item.get("payload") if isinstance(item.get("payload"), dict) else item return created, skipped def save_oa_attachments( contract: ContractPaymentContract, *, item: dict[str, Any], client: ContractOaClient, ) -> dict[str, int]: """ 下载 OA 合同申请单中的合同附件,落私有 FileAsset 并触发付款条款解析。 核心逻辑:附件按详情页优先级(盖章完成合同上传优先于合同附件)依次下载; `(contract_id, source, source_key)` 保证重试不会重复保存。下载失败只将合同标记为待补文件,下一轮仍可重试。 Args: contract: 已创建或已存在的合同台账记录。 item: OA 客户端返回的合同归档事件,必须包含 attachments。 client: 本轮已登录的 OA 客户端,复用其 Cookie 下载附件。 Returns: `found` 为页面发现附件数,`saved` 为实际成功保存数。 """ attachments = [value for value in (item.get("attachments") or []) if isinstance(value, dict)] if not attachments: contract.status = "pending_artifact" db.session.flush() return {"found": 0, "saved": 0} owner_id = contract.owner_user_id or _default_owner_user_id() if not owner_id: contract.status = "pending_artifact" db.session.flush() return {"found": len(attachments), "saved": 0} parent = _ensure_oa_parent_asset(owner_id=owner_id, contract=contract) saved = 0 # OA 一个字段可能返回同一文件的多个历史 imageFileId;先按“盖章完成合同上传”字段,再按字段内文件优先级下载。 attachments = sorted(attachments, key=lambda value: (int(value.get("priority") or 99), str(value.get("file_name") or ""))) for attachment in attachments: attachment_id = str(attachment.get("attachment_id") or attachment.get("file_name") or "").strip() if not attachment_id: continue source_key = f"oa:{attachment_id}" existing = db.session.query(ContractPaymentAttachment).filter_by( 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} 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) filename = (response_name or str(attachment.get("file_name") or "contract")).strip()[:255] current_app.logger.info("合同付款预警:OA 附件下载完成 filename=%s size=%d", filename, len(data or b"")) 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=source_key, asset_role="contract_oa_attachment", ) if existing is None: existing = ContractPaymentAttachment( contract_id=contract.id, source="oa", source_key=source_key, file_name=filename ) db.session.add(existing) existing.file_name = filename existing.mime_type = mime_type[:128] if mime_type else None existing.file_asset_id = asset.id existing.metadata_json = { "attachment_id": attachment_id, "label": attachment.get("label"), "source_event_id": item.get("source_event_id"), } existing.status = "stored" 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) contract.parse_status = "needs_review" saved += 1 # 第一版仅需要一份可解析的、优先级最高的合同正文,避免同流程辅助附件反复覆盖付款计划。 # 盖章附件按优先级排在最前;下载成功后即可结束本轮,避免辅助附件覆盖解析结果。 return {"found": len(attachments), "saved": saved} except Exception: current_app.logger.warning("合同付款预警:OA 合同附件下载失败,合同编号=%s", contract.contract_no) contract.status = "pending_artifact" db.session.flush() return {"found": len(attachments), "saved": saved} def supplement_pending_contracts(*, limit: int = 200) -> dict[str, int]: """ 为明确标记为“待补文件”的合同执行延迟 DMS 补查。 [STEP 1] 只扫描 `pending_artifact` 合同;`active` 合同即使没有 DMS 附件也不轮询,避免 OA 主附件已可用时重复访问 DMS。 [STEP 2] 委托 supplement_from_dms 完成 FolderID、日期窗口和附件落库。 Args: limit: 单次最多处理的合同数,防止排程长期占用 worker。 Returns: found/saved 计数摘要。 """ rows = ( db.session.query(ContractPaymentContract) .filter(ContractPaymentContract.status == "pending_artifact") .order_by(ContractPaymentContract.oa_archive_at.asc(), ContractPaymentContract.id.asc()) .limit(max(int(limit or 0), 0)) .all() ) found = saved = 0 for contract in rows: if db.session.query(ContractPaymentAttachment).filter_by(contract_id=contract.id, source="dms", status="stored").first(): continue result = supplement_from_dms(contract) found += result["found"] saved += result["saved"] return {"found": found, "saved": saved} def reparse_existing_contracts(*, limit: int = 1000) -> dict[str, int]: """ 使用已归档附件批量刷新存量合同解析结果。 AI 触发时机:解析规则升级后,管理员需要清理数据库中遗留的旧待确认原因时调用。 核心逻辑:不依赖 OA 增量通知,直接按“盖章完成合同上传”优先选择已保存附件并重跑解析; 没有可用附件的合同跳过,解析失败的合同保留 needs_review。 Args: limit: 本次最多重解析合同数,防止单个 Job 长时间占用 Worker。 Returns: scanned/reparsed/failed/skipped 计数。 """ 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 = ( db.session.query(ContractPaymentAttachment) .filter_by(contract_id=contract.id, status="stored") .filter(ContractPaymentAttachment.file_asset_id.is_not(None)) .all() ) if not attachments: 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)) reparsed += 1 except Exception: failed += 1 contract.parse_status = "needs_review" db.session.commit() return {"scanned": scanned, "reparsed": reparsed, "failed": failed, "skipped": skipped} def supplement_from_dms(contract: ContractPaymentContract) -> dict[str, int]: """ 从文档管理系统补充 OA 缺失的采购合同附件并解析付款计划。 [STEP 1] 按 OA 归档日期选择年份目录,暂存目录由 DMS 客户端作为兜底。 [STEP 2] 按合同编号和创建日期窗口筛选文件,避免同号旧文件误匹配。 [STEP 3] 下载首个可解析附件,落入私有 FileAsset 并记录来源;失败只保留待补文件状态。 Args: contract: 已落库且包含合同编号的 OA 合同。 Returns: found/saved 计数摘要;不会创建新的合同主记录。 """ # OA 附件是主来源;存在已保存的 OA 附件时,DMS 只作为延迟补充,不重复拉取。 if db.session.query(ContractPaymentAttachment).filter_by(contract_id=contract.id, source="oa", status="stored").first(): return {"found": 0, "saved": 0} if not ContractDmsClient.is_configured(): return {"found": 0, "saved": 0} if not contract.contract_no: # 合同号只能由正文解析得到,未解析前 DMS 没有采购单号可用于安全检索。 return {"found": 0, "saved": 0} archive_date = contract.oa_archive_at.date() if contract.oa_archive_at else None try: rows = ContractDmsClient.search(contract_no=contract.contract_no, archive_date=archive_date) except Exception: contract.status = "pending_artifact" db.session.flush() return {"found": 0, "saved": 0} if not rows: contract.status = "pending_artifact" db.session.flush() return {"found": 0, "saved": 0} for row in rows: attachment = row.get("MainFileAttachment") or {} attachment_id = str(attachment.get("ID") or row.get("AttachmentID") or "").strip() if not attachment_id: continue 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} try: data, mime_type, response_name = ContractDmsClient.download_attachment(attachment_id) filename = response_name or str(row.get("LeafName") or "contract").strip() or "contract" if "." not in filename: extension = str(attachment.get("Extension") or "").strip().lstrip(".") if extension: filename = f"{filename}.{extension}" # [STEP 3] DMS 文件没有用户上下文,使用合同负责人/默认负责人作为私有资产所有者。 owner_id = contract.owner_user_id or _default_owner_user_id() if not owner_id: contract.status = "pending_artifact" return {"found": 1, "saved": 0} parent = _ensure_dms_parent_asset(owner_id=owner_id, contract=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=source_key, asset_role="contract_dms_attachment", ) if existing is None: existing = ContractPaymentAttachment(contract_id=contract.id, source="dms", source_key=source_key, file_name=filename[:255]) db.session.add(existing) existing.file_name = filename[:255] existing.mime_type = mime_type[:128] if mime_type else None existing.file_asset_id = asset.id existing.dms_path = str(row.get("Path") or "")[:1024] or None existing.created_at = ContractDmsClient._created_at(row) existing.metadata_json = {"item_id": row.get("ID"), "version_id": row.get("VersionID"), "folder_id": row.get("DmsFolderID")} existing.status = "stored" contract.status = "active" 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" db.session.commit() return {"found": 1, "saved": 1} except Exception: contract.status = "pending_artifact" db.session.flush() db.session.commit() return {"found": 1, "saved": 0} def _default_owner_user_id() -> int | None: """读取附件存储用的默认文件所有者;不得作为预警第一轮收件人。""" raw = str(current_app.config.get("CONTRACT_PAYMENT_DEFAULT_OWNER_USER_ID") or "").strip() try: if raw: return int(raw) except ValueError: pass fallback = db.session.query(User).filter(User.username == "admin").first() return fallback.id if fallback else None def _ensure_dms_parent_asset(*, owner_id: int, contract: ContractPaymentContract) -> FileAsset: """创建用于挂载 DMS 派生附件的轻量父资产;同一合同重复同步时复用。""" source_key = f"contract-dms:{contract.id}" parent = db.session.query(FileAsset).filter_by(owner_user_id=owner_id, source_attachment_key=source_key).first() if parent: return parent parent = FileAsset( asset_no=generate_asset_no(), owner_user_id=owner_id, asset_role="contract_dms_root", source_attachment_key=source_key, original_filename=f"{_contract_identity(contract)}.dms", storage_provider="minio", storage_bucket=file_asset_storage.bucket_name, storage_key=f"contract-dms/{owner_id}/{contract.id}", content_hash=hashlib.sha256(source_key.encode("utf-8")).hexdigest(), file_size=0, mime_type="application/octet-stream", extension="dms", upload_status="ready", lifecycle_status="referenced", reference_count=1, ) db.session.add(parent) db.session.flush() return parent def _ensure_oa_parent_asset(*, owner_id: int, contract: ContractPaymentContract) -> FileAsset: """ 创建 OA 附件的轻量父资产并按合同复用。 Args: owner_id: 采购负责人或系统配置的默认负责人,用于文件权限归属。 contract: 当前合同台账记录。 Returns: 可供 `create_derived_file_asset_from_bytes` 挂载的父 FileAsset。 """ source_key = f"contract-oa:{contract.id}" parent = db.session.query(FileAsset).filter_by(owner_user_id=owner_id, source_attachment_key=source_key).first() if parent: return parent parent = FileAsset( asset_no=generate_asset_no(), owner_user_id=owner_id, asset_role="contract_oa_root", source_attachment_key=source_key, original_filename=f"{_contract_identity(contract)}.oa", storage_provider="minio", storage_bucket=file_asset_storage.bucket_name, storage_key=f"contract-oa/{owner_id}/{contract.id}", content_hash=hashlib.sha256(source_key.encode("utf-8")).hexdigest(), file_size=0, mime_type="application/octet-stream", extension="oa", upload_status="ready", lifecycle_status="referenced", reference_count=1, ) db.session.add(parent) db.session.flush() return parent def _contract_identity(contract: ContractPaymentContract) -> str: """返回派生文件名使用的稳定标识,正文未解析合同号时回退流程编号。""" return str(contract.contract_no or contract.workflow_no or contract.oa_record_id or contract.id) def build_payment_plan_from_bytes(contract: ContractPaymentContract, *, filename: str, data: bytes) -> dict[str, Any]: """ 从合同附件生成付款计划。 核心逻辑:调用文件解析/OCR 产生四阶段节点,随后通过统一持久化逻辑更新合同台账。 Args: contract: 已落库的合同台账记录。 filename: 合同原始文件名。 data: 合同原始字节。 Returns: 结构化解析结果。 """ result = parse_contract_bytes( filename, data, total_amount=contract.total_amount, delivery_due_date=contract.delivery_due_date, ) return _persist_payment_plan(contract, result=result) def build_payment_plan(contract: ContractPaymentContract, *, text: str = "") -> dict[str, Any]: """ 从已抽取的正文生成付款计划,供人工复核接口调用。 Args: contract: 已落库的合同台账记录。 text: 已提取的合同正文;为空时解析器将返回待复核结果。 Returns: 结构化解析结果。 """ result = parse_contract_text(text, total_amount=contract.total_amount, delivery_due_date=contract.delivery_due_date) return _persist_payment_plan(contract, result=result) def _persist_payment_plan(contract: ContractPaymentContract, *, result: dict[str, Any]) -> dict[str, Any]: """ 持久化条款与节点,并只用附件正文回填真实合同编号。 核心逻辑:保持节点编码稳定以支持重解析覆盖;仅解析成功时启用提醒,防止不完整条款触发正式通知。 若验收归档事件已先入库,节点生成后立即回放归档日到验收款/质保款。 Args: contract: 当前合同台账记录。 result: 解析器返回的可序列化结果。 Returns: 原始解析结果。 """ fields = result.get("fields") or {} # [STEP 1] 采购单号是 ERP 回查预付款、出货款完成事实的唯一业务键;缺失时即使 # 合同正文条款完整,也不能进入自动预警台账,以免将已付款节点误判为未付款。 if not str(contract.purchase_order_no or "").strip(): issues = result.setdefault("issues", []) if "采购单号无法识别" not in issues: issues.append("采购单号无法识别") result["status"] = "needs_review" parsed_contract_no = str(fields.get("contract_no") or "").strip() or None if parsed_contract_no and parsed_contract_no != contract.contract_no: conflict = db.session.query(ContractPaymentContract).filter( ContractPaymentContract.contract_no == parsed_contract_no, ContractPaymentContract.id != contract.id, ).first() if conflict: result.setdefault("issues", []).append("合同编号与另一条合同台账冲突") result["status"] = "needs_review" 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"])) 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 if not contract.delivery_due_date: contract.delivery_due_date = _as_date(fields.get("delivery_due_date")) parsed_node_codes: set[str] = set() for item in result.get("nodes") or []: parsed_node_codes.add(str(item["node_code"])) node = db.session.query(ContractPaymentNode).filter_by(contract_id=contract.id, node_code=item["node_code"]).first() if node is None: node = ContractPaymentNode(contract_id=contract.id, node_code=item["node_code"], node_type=item["node_type"]) db.session.add(node) node.amount = item.get("amount") node.percentage = item.get("percentage") node.anchor_type = item.get("anchor_type") node.anchor_date = _as_date(item.get("anchor_date")) node.due_date = _as_date(item.get("due_date")) if node.node_type == "prepayment" and contract.oa_archive_at: # [STEP 1] 预付款的到期/逾期判断以「合同归档日期」为 due_date(与锚点同源); # 预警日期仍按 anchor+7/14/21 首轮展示,二者解耦(见前端 displayAlertDate)。 node.anchor_date = contract.oa_archive_at.date() node.due_date = contract.oa_archive_at.date() elif node.node_type == "shipment" and node.due_date: node.anchor_date = node.due_date node.reminder_days = 0 node.evidence_json = item.get("evidence") node.status = "active" if result.get("status") == "parsed" else "needs_review" if node.node_type == "acceptance" and node.anchor_date and not node.due_date: node.due_date = node.anchor_date # [STEP 2] 重解析可能比历史结果少识别节点;清空旧事实,避免页面继续展示已被新结果淘汰的阶段。 for stale_node in db.session.query(ContractPaymentNode).filter_by(contract_id=contract.id).all(): if stale_node.node_code in parsed_node_codes: continue stale_node.amount = None stale_node.percentage = None stale_node.anchor_date = None stale_node.due_date = None stale_node.evidence_json = {"reparse": "当前附件未识别"} stale_node.status = "needs_review" # [STEP 3] 验收事件可能先于节点生成:节点落库后再回放已有 acceptance_archive。 refresh_acceptance_nodes_from_events(contract) contract.plan_status = "active" if result.get("status") == "parsed" else "needs_review" db.session.commit() return result def _as_date(value: Any) -> date | None: if isinstance(value, date) and not isinstance(value, datetime): return value raw = str(value or "").strip()[:10] try: return date.fromisoformat(raw) except ValueError: return None def _as_datetime(value: Any) -> datetime | None: if isinstance(value, datetime): return value raw = str(value or "").strip() if not raw: return None try: return datetime.fromisoformat(raw.replace("Z", "+00:00")).replace(tzinfo=None) except ValueError: return None