fix: fix merge conflicts

This commit is contained in:
sophie committed 2026-09-02 11:49:20 +08:00
commit 03b9b46ebd
114 files changed
+11408 -2996

No files matched your search

@@ -0,0 +1,11 @@
"""
backend/app/services/contract_payment/__init__.py
用途:采购合同付款预警 Agent 服务包入口。
依赖:sync_service、parse_service、alert_service。
逻辑:API 层从此包调用合同同步、解析、付款计划和预警编排能力。
"""
from app.services.contract_payment import alert_service, dms_client, oa_client, parse_service, sync_service
__all__ = ["alert_service", "dms_client", "oa_client", "parse_service", "sync_service"]
@@ -0,0 +1,300 @@
"""
backend/app/services/contract_payment/acceptance_oa_service.py
用途:从 OA ecology SQL Server 读取已归档资产验收单,供合同付款预警计算验收款/质保款锚点。
依赖:OASQLServerService(复用既有 OA_SQLSERVER_* 只读连接,不新增 OA 库凭据)、Flask current_app。
逻辑:formtable_main_324.cgdh 为采购单号,requestId 关联 workflow_requestbase;
currentnodetype='3' 表示验收单已归档(0 创建 / 1 批准 / 2 提交 / 3 归档)。
查询失败 fail-safe 返回空,不打断合同 HTTP 同步。
"""
from __future__ import annotations
import re
from datetime import date, datetime
from typing import Any
from flask import current_app
from app.services.oa_sqlserver import OASQLServerService
# [STEP] 仅允许字母数字下划线作为 SQL 标识符,表名/字段来自配置,禁止拼接任意字符串。
_SAFE_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
_DEFAULT_TABLE = "formtable_main_324"
_DEFAULT_PO_FIELD = "cgdh"
_DEFAULT_NODETYPE = "3"
_DEFAULT_REQUEST_ID_FIELD = "requestId"
_PO_IN_BATCH = 100
def source_event_id(request_id: str | int, contract_id: int) -> str:
"""
生成验收归档事件的幂等键。
核心逻辑:同一 OA requestId 在多份合同(相同采购单号)下各写一条事件,避免
`(event_type, source_event_id)` 全局唯一约束把第二份合同挤掉。
Args:
request_id: OA workflow_requestbase.requestid / 表单 requestId。
contract_id: 合同付款台账主键。
Returns:
形如 `oa-acceptance:{requestId}:c{contractId}` 的稳定 ID。
"""
return f"oa-acceptance:{str(request_id).strip()}:c{int(contract_id)}"
def fetch_archived_acceptances(
*,
since: datetime | None = None,
purchase_order_nos: list[str] | None = None,
) -> tuple[list[dict[str, Any]], bool]:
"""
查询已归档资产验收单及其采购单号。
AI 触发时机:合同付款 `sync_notifications` 在合同申请单 HTTP 同步之后调用,
用验收归档日驱动验收款/质保款节点日期。
核心逻辑:JOIN `formtable_main_324` 与 `workflow_requestbase`,过滤
currentnodetype=3(归档)且 cgdh 非空。增量按 lastoperatedate(归档后该字段即为归档日);
同时可用采购单号回补「验收先于合同入库」的漏扫。连接或查询失败返回 `([], False)`。
Args:
since: 增量下限;None 表示全量(管理员 force 或首次断点)。
purchase_order_nos: 台账中尚无验收事件的采购单号,用于回补窗口外历史归档。
Returns:
`(events, ok)`。ok=False 时调用方不得推进验收断点。每条 event 含
request_id、purchase_order_no、archive_at、currentnodetype。
"""
try:
table = _configured_ident("CONTRACT_PAYMENT_OA_ACCEPTANCE_TABLE", _DEFAULT_TABLE)
po_field = _configured_ident("CONTRACT_PAYMENT_OA_ACCEPTANCE_PO_FIELD", _DEFAULT_PO_FIELD)
request_id_field = _configured_ident(
"CONTRACT_PAYMENT_OA_ACCEPTANCE_REQUEST_ID_FIELD",
_DEFAULT_REQUEST_ID_FIELD,
)
node_type = str(
current_app.config.get("CONTRACT_PAYMENT_OA_ACCEPTANCE_NODETYPE") or _DEFAULT_NODETYPE
).strip() or _DEFAULT_NODETYPE
po_nos = _unique_po_list(purchase_order_nos)
sql, params = build_archived_acceptance_sql(
table=table,
po_field=po_field,
request_id_field=request_id_field,
node_type=node_type,
since=since,
purchase_order_nos=po_nos,
)
connection = OASQLServerService._connect()
try:
cursor = connection.cursor()
cursor.execute(sql, params)
rows = cursor.fetchall() or []
finally:
connection.close()
except Exception:
current_app.logger.exception("合同付款预警:读取 OA 验收归档失败")
return [], False
events: list[dict[str, Any]] = []
for row in rows:
event = _row_to_event(row)
if event is not None:
events.append(event)
current_app.logger.info(
"合同付款预警:OA 验收归档 SQL 命中 %d 条 since=%s backfill_po=%d",
len(events),
since.isoformat() if since else None,
len(po_nos),
)
return events, True
def build_archived_acceptance_sql(
*,
table: str,
po_field: str,
request_id_field: str,
node_type: str,
since: datetime | None,
purchase_order_nos: list[str],
) -> tuple[str, list[Any]]:
"""
组装已归档验收单查询 SQL(标识符已校验,业务值全部参数化)。
核心逻辑:固定 JOIN workflow_requestbase;增量日期与采购单号回补用 OR 合并,
避免验收早于合同入库且 lastoperatedate 落在窗口外时永久漏扫。
Args:
table: 资产验收单主表,默认 formtable_main_324。
po_field: 采购单号列,默认 cgdh。
request_id_field: 表单 requestId 列。
node_type: workflow_requestbase.currentnodetype 目标值,默认 '3'(归档)。
since: 增量下限;None 不加日期条件。
purchase_order_nos: 回补采购单号;空列表不加 IN 条件。
Returns:
`(sql, params)` 供 pyodbc execute。
Raises:
ValueError: 标识符未通过安全校验。
"""
table_sql = _bracket_ident(table)
po_sql = _bracket_ident(po_field)
request_sql = _bracket_ident(request_id_field)
# [STEP 1] 验收单主表无状态字段;归档以 currentnodetype 为准(char:0 创建 / 1 批准 / 2 提交 / 3 归档)。
# char 可能带尾随空格,比较前 LTRIM/RTRIM。归档日取 lastoperatedate/lastoperatetime:
# currentnodetype 变为 3 后该对字段即为最后一次操作(归档)时间。
sql = f"""
SELECT
f.{request_sql} AS request_id,
LTRIM(RTRIM(CAST(f.{po_sql} AS nvarchar(200)))) AS purchase_order_no,
LTRIM(RTRIM(CAST(w.[currentnodetype] AS nvarchar(10)))) AS currentnodetype,
w.lastoperatedate AS lastoperatedate,
w.lastoperatetime AS lastoperatetime,
w.createdate AS createdate,
w.createtime AS createtime
FROM {table_sql} f
INNER JOIN [workflow_requestbase] w ON w.[requestid] = f.{request_sql}
WHERE LTRIM(RTRIM(CAST(w.[currentnodetype] AS nvarchar(10)))) = ?
AND f.{po_sql} IS NOT NULL
AND LTRIM(RTRIM(CAST(f.{po_sql} AS nvarchar(200)))) <> N''
"""
params: list[Any] = [str(node_type).strip()]
extra_clauses: list[str] = []
if since is not None:
extra_clauses.append("LTRIM(RTRIM(CAST(w.[lastoperatedate] AS nvarchar(20)))) >= ?")
params.append(since.date().isoformat())
if purchase_order_nos:
placeholders = ", ".join("?" for _ in purchase_order_nos)
extra_clauses.append(
f"LTRIM(RTRIM(CAST(f.{po_sql} AS nvarchar(200)))) IN ({placeholders})"
)
params.extend(purchase_order_nos)
if extra_clauses:
sql += " AND (" + " OR ".join(extra_clauses) + ")"
return sql, params
def parse_oa_archive_at(date_value: Any, time_value: Any = None) -> datetime | None:
"""
将泛微 lastoperatedate + lastoperatetime 拼成 naive datetime。
核心逻辑:兼容 date/datetime、yyyy-MM-dd、yyyy/MM/dd、yyyyMMdd;时间可缺省为 00:00:00。
Args:
date_value: 日期列。
time_value: 可选时间列(HH:mm:ss 或 HHmmss)。
Returns:
解析成功的 datetime;无法解析则 None。
"""
day = _parse_oa_date(date_value)
if day is None:
return None
hour, minute, second = _parse_oa_time(time_value)
return datetime(day.year, day.month, day.day, hour, minute, second)
def _configured_ident(config_key: str, default: str) -> str:
"""读取 Flask 配置中的 SQL 标识符,非法时回退默认值并打日志。"""
raw = str(current_app.config.get(config_key) or default).strip() or default
if not _SAFE_IDENT.match(raw):
current_app.logger.error("合同付款预警:非法 SQL 标识符 %s=%r,回退 %s", config_key, raw, default)
return default
return raw
def _bracket_ident(name: str) -> str:
"""校验并返回 [ident] 形式的 SQL Server 标识符。"""
if not _SAFE_IDENT.match(name):
raise ValueError(f"非法 SQL 标识符: {name!r}")
return f"[{name}]"
def _unique_po_list(purchase_order_nos: list[str] | None) -> list[str]:
"""去空白、去重,并截断单批 IN 参数数量。"""
seen: set[str] = set()
result: list[str] = []
for raw in purchase_order_nos or []:
po = str(raw or "").strip()
if not po or po in seen:
continue
seen.add(po)
result.append(po)
if len(result) >= _PO_IN_BATCH:
break
return result
def _row_to_event(row: Any) -> dict[str, Any] | None:
"""将游标行转为验收事件字典;无 requestId 或采购单号则丢弃。"""
request_id = _row_value(row, 0)
purchase_order_no = str(_row_value(row, 1) or "").strip()
currentnodetype = str(_row_value(row, 2) or "").strip()
if request_id in (None, "") or not purchase_order_no:
return None
archive_at = parse_oa_archive_at(_row_value(row, 3), _row_value(row, 4))
if archive_at is None:
archive_at = parse_oa_archive_at(_row_value(row, 5), _row_value(row, 6))
return {
"event_type": "acceptance_archive",
"source": "oa_sqlserver",
"request_id": str(request_id).strip(),
"purchase_order_no": purchase_order_no,
"currentnodetype": currentnodetype,
"archive_at": archive_at.isoformat(sep=" ") if archive_at else None,
"lastoperatedate": _stringify(_row_value(row, 3)),
"lastoperatetime": _stringify(_row_value(row, 4)),
}
def _row_value(row: Any, index: int) -> Any:
"""按位置取值,兼容 tuple 与 pyodbc.Row。"""
try:
return row[index]
except (IndexError, TypeError, KeyError):
return None
def _stringify(value: Any) -> str | None:
text = str(value).strip() if value is not None else ""
return text or None
def _parse_oa_date(value: Any) -> date | None:
if isinstance(value, datetime):
return value.date()
if isinstance(value, date):
return value
raw = str(value or "").strip()
if not raw:
return None
digits = re.sub(r"[^0-9]", "", raw)
if len(digits) >= 8:
try:
return date(int(digits[0:4]), int(digits[4:6]), int(digits[6:8]))
except ValueError:
return None
return None
def _parse_oa_time(value: Any) -> tuple[int, int, int]:
if value is None or value == "":
return 0, 0, 0
if isinstance(value, datetime):
return value.hour, value.minute, value.second
raw = str(value).strip()
digits = re.sub(r"[^0-9]", "", raw)
if len(digits) >= 6:
try:
return int(digits[0:2]), int(digits[2:4]), int(digits[4:6])
except ValueError:
return 0, 0, 0
if len(digits) == 4:
try:
return int(digits[0:2]), int(digits[2:4]), 0
except ValueError:
return 0, 0, 0
return 0, 0, 0
@@ -0,0 +1,469 @@
"""
services/contract_payment/alert_service.py
用途:按付款阶段生成待发送预警,在每周五按收件人汇总发送企业微信和 Excel 明细,并提供工作台待发送摘要。
依赖:合同付款模型、用户目录、openpyxl、企业微信通知服务、OA 上级矩阵、排程时区工具。
逻辑:每日任务只写入 pending 审计;周汇总任务锁定本周收件人批次,发送一条汇总卡片和一份逐笔 Excel;摘要接口与周五发送使用同一 pending 口径。
第一轮按台账申请人 `real_name` 唯一匹配系统用户;第二、三轮查 OA HrmResource + Matrixtable_3,用 zz/jfl 作为企微 userid,不向第一轮兜底。
"""
from __future__ import annotations
from collections import Counter, defaultdict
from dataclasses import dataclass
from datetime import date, datetime, timedelta, timezone
from io import BytesIO
from uuid import uuid4
from flask import current_app
from openpyxl import Workbook
from openpyxl.styles import Font
from sqlalchemy import func
from app import db
from app.models import (
ContractPaymentAlert,
ContractPaymentAlertBatch,
ContractPaymentContract,
ContractPaymentEvent,
ContractPaymentNode,
User,
)
from app.services.wecom_notify import (
send_wecom_event_message,
send_wecom_file_message,
upload_wecom_temp_media,
)
from app.services.contract_payment.erp_payment_service import fetch_paid_records, resolve_paid_node_dates
from app.services.contract_payment.supervisor_oa_service import SupervisorMatrixCache
from app.services.schedule.timezone_util import compute_next_run_at
@dataclass(frozen=True)
class _AlertRecipient:
"""扫描时解析出的收件人:系统用户 + 可选 OA/企微 userid。"""
user: User
oa_wecom_userid: str | None = None
_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")),
"acceptance": ((30, "owner"), (40, "department_head"), (60, "procurement_leader")),
"warranty": ((-7, "owner"), (0, "department_head"), (14, "procurement_leader")),
}
def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[str, int]:
"""每日扫描付款节点并生成 pending 预警,不直接发送企微。
AI 触发时机:每日排程或管理员手动执行扫描时调用。
核心逻辑:按阶段计算已到期的三轮提醒,按节点、轮次、收件人幂等;第二、三轮收件人来自 OA 部门矩阵;
ERP `apa_file` 的合格付款记录只停止尚未发送的后续轮次。
Args:
today: 业务日期,未传时使用服务器日期。
send: 保留旧调用兼容参数;最新方案下始终不发送消息。
Returns:
created、pending、skipped、resolved 四项计数。
"""
_ = send
today = today or date.today()
created = skipped = resolved = 0
supervisors = SupervisorMatrixCache()
rows = (
db.session.query(ContractPaymentNode, ContractPaymentContract)
.join(ContractPaymentContract, ContractPaymentContract.id == ContractPaymentNode.contract_id)
.filter(ContractPaymentNode.status == "active", ContractPaymentContract.status == "active")
.all()
)
paid_records = fetch_paid_records(
contract.purchase_order_no
for _node, contract in rows
if _node.node_type in {"prepayment", "shipment"}
)
paid_node_dates: dict[int, str | None] = {}
nodes_by_purchase_order: dict[str, list[ContractPaymentNode]] = defaultdict(list)
for node, contract in rows:
purchase_order_no = str(contract.purchase_order_no or "").strip()
if node.node_type in {"prepayment", "shipment"} and purchase_order_no:
nodes_by_purchase_order[purchase_order_no].append(node)
for purchase_order_no, payment_nodes in nodes_by_purchase_order.items():
paid_node_dates.update(resolve_paid_node_dates(
[(node.id, node.node_type, node.amount) for node in payment_nodes],
paid_records.get(purchase_order_no, []),
))
for node, contract in rows:
anchor = _anchor_date(contract=contract, node=node)
if anchor is None:
skipped += 1
continue
erp_paid = node.id in paid_node_dates
if erp_paid:
node.status = "paid"
# [STEP 1] 记录 ERP 付款日期,供详情页付款计划展示“已付 + 日期”。
node.evidence_json = {**(node.evidence_json or {}), "paid_at": paid_node_dates.get(node.id)}
for alert_round, (offset_days, recipient_role) in enumerate(_ALERT_RULES.get(node.node_type, ()), start=1):
scheduled_date = anchor + timedelta(days=offset_days)
if today < scheduled_date:
continue
# ERP 合格付款先按金额匹配阶段;同金额时预付款优先于出货款。
# 节点被匹配为已付款后,保留历史 sent,仅关闭尚未发送轮次。
if erp_paid:
resolved += _resolve_pending_alerts(node_id=node.id)
break
recipients = _resolve_recipients(
contract=contract, recipient_role=recipient_role, supervisors=supervisors
)
if not recipients:
skipped += 1
continue
for recipient in recipients:
trigger_key = f"round:{alert_round}:date:{scheduled_date.isoformat()}"
exists = db.session.query(ContractPaymentAlert.id).filter_by(
node_id=node.id, trigger_key=trigger_key, recipient_user_id=recipient.user.id
).first()
if exists:
continue
message_json = {"scheduled_date": scheduled_date.isoformat()}
if recipient.oa_wecom_userid:
message_json["oa_wecom_userid"] = recipient.oa_wecom_userid
db.session.add(ContractPaymentAlert(
contract_id=contract.id,
node_id=node.id,
trigger_key=trigger_key,
alert_round=alert_round,
scheduled_at=datetime.combine(scheduled_date, datetime.min.time()),
recipient_user_id=recipient.user.id,
status="pending",
message_json=message_json,
))
created += 1
db.session.commit()
return {"created": created, "pending": created, "sent": 0, "skipped": skipped, "resolved": resolved}
def _resolve_pending_alerts(*, node_id: int) -> int:
"""将某节点未发送的提醒标记为已按 ERP 付款关闭,保留历史发送记录。"""
rows = db.session.query(ContractPaymentAlert).filter_by(node_id=node_id, status="pending").all()
for alert in rows:
alert.status = "resolved"
alert.message_json = {**(alert.message_json or {}), "resolved_reason": "erp_paid"}
return len(rows)
def send_weekly_alerts(*, today: date | None = None) -> dict[str, int]:
"""按收件人发送本周合同付款预警汇总及 Excel 明细。
AI 触发时机:每周五 18:00 的排程或管理员补发时调用。
核心逻辑:每位收件人每周只产生一个批次;企微正文仅发送总笔数和阶段数量,逐笔信息写入附件。
Args:
today: 用于确定 ISO 周标识,测试可显式传入。
Returns:
batches、sent、failed、alerts 四项计数。
"""
today = today or date.today()
week_key = today.strftime("%G-W%V")
rows = (
db.session.query(ContractPaymentAlert, ContractPaymentContract, ContractPaymentNode, User)
.join(ContractPaymentContract, ContractPaymentContract.id == ContractPaymentAlert.contract_id)
.join(ContractPaymentNode, ContractPaymentNode.id == ContractPaymentAlert.node_id)
.join(User, User.id == ContractPaymentAlert.recipient_user_id)
.filter(ContractPaymentAlert.status == "pending", ContractPaymentContract.status == "active")
.order_by(ContractPaymentAlert.recipient_user_id, ContractPaymentAlert.scheduled_at, ContractPaymentAlert.id)
.all()
)
grouped: dict[int, list[tuple[ContractPaymentAlert, ContractPaymentContract, ContractPaymentNode, User]]] = defaultdict(list)
for row in rows:
grouped[row[0].recipient_user_id].append(row)
batches = sent = failed = detail_count = 0
for recipient_id, items in grouped.items():
batch = db.session.query(ContractPaymentAlertBatch).filter_by(week_key=week_key, recipient_user_id=recipient_id).first()
if batch and batch.status == "sent":
continue
if batch is None:
batch = ContractPaymentAlertBatch(
batch_no=f"CPAW-{datetime.utcnow():%Y%m%d%H%M%S}-{uuid4().hex[:8].upper()}",
week_key=week_key,
recipient_user_id=recipient_id,
status="sending",
)
db.session.add(batch)
db.session.flush()
batches += 1
workbook_data, summary = _build_excel(items)
batch.summary_json = summary
batch.excel_file_name = f"合同付款预警明细-{week_key}-{recipient_id}.xlsx"
batch.excel_file_data = workbook_data
batch.excel_file_size = len(workbook_data)
user = items[0][3]
wecom_userid = _batch_wecom_userid(items, user)
result = send_wecom_event_message(
event_type="contract_payment_warning",
user=user,
title=f"合同付款预警汇总({summary['total']}笔)",
content=_build_summary_message(summary),
jump_path="/workspace/contract-payment",
jump_params={"batch_no": batch.batch_no},
wecom_userid=wecom_userid,
)
trace = {"textcard": result}
try:
media_id = upload_wecom_temp_media(workbook_data, batch.excel_file_name)
file_result = (
send_wecom_file_message(wecom_userid, media_id)
if wecom_userid
else {"errcode": -1, "errmsg": "user_unbound"}
)
trace["file"] = file_result
except Exception as exc:
trace["file_error"] = str(exc)
file_result = {"errcode": -1}
batch.wecom_trace_json = trace
if result.get("ok") and file_result.get("errcode") == 0:
batch.status = "sent"
batch.sent_at = datetime.utcnow()
for alert, *_ in items:
alert.status = "sent"
alert.sent_at = datetime.utcnow()
alert.message_json = {**(alert.message_json or {}), "batch_no": batch.batch_no}
detail_count += 1
sent += 1
else:
batch.status = "failed"
batch.error_message = str(trace)[:2000]
failed += 1
db.session.commit()
return {"batches": batches, "sent": sent, "failed": failed, "alerts": detail_count}
def build_weekly_alert_summary(*, now: datetime | None = None) -> dict[str, object]:
"""返回本周待发送笔数和下一次周五汇总发送时间。
核心逻辑:待发送口径与 `send_weekly_alerts` 一致(pending + 合同 active);
下次发送时刻复用排程 Cron `0 18 * * 5` 与上海时区,当前时刻已过本周五 18:00 则指向下周五。
Args:
now: 可选 UTC naive 基准时刻,测试可注入;未传时使用当前时间。
Returns:
pending_count、UTC ISO 的 next_send_at,以及业务时区名称。
"""
pending_count = (
db.session.query(ContractPaymentAlert)
.join(ContractPaymentContract, ContractPaymentContract.id == ContractPaymentAlert.contract_id)
.filter(ContractPaymentAlert.status == "pending", ContractPaymentContract.status == "active")
.count()
)
timezone_name = str(current_app.config.get("CONTRACT_PAYMENT_ALERT_TIMEZONE") or "Asia/Shanghai").strip() or "Asia/Shanghai"
cron = str(current_app.config.get("CONTRACT_PAYMENT_ALERT_WEEKLY_CRON") or "0 18 * * 5").strip() or "0 18 * * 5"
next_utc = compute_next_run_at(cron, base_utc_naive=now, timezone_name=timezone_name)
next_send_at = None
if next_utc is not None:
next_send_at = next_utc.replace(tzinfo=timezone.utc).isoformat().replace("+00:00", "Z")
return {
"pending_count": pending_count,
"next_send_at": next_send_at,
"timezone": timezone_name,
}
def _node_paid_date(node: ContractPaymentNode) -> str | None:
"""返回节点实际付款日期(ERP apa_file 的 paid_at);节点未付时返回 None。
用于 Excel 「付款日期」列:只有已付节点才展示付款日期,未付显示「—」,
避免把「到期日」(due_date)误标为付款日期。
"""
if str(node.status or "").strip().lower() != "paid":
return None
return (node.evidence_json or {}).get("paid_at")
def _build_excel(items) -> tuple[bytes, dict[str, object]]:
"""生成收件人专属逐笔付款预警明细 Excel。"""
wb = Workbook()
ws = wb.active
ws.title = "付款预警明细"
headers = ["合同编号", "采购编号", "供应商", "合同金额", "付款阶段", "付款金额", "比例", "付款日期", "到期日", "预警轮次", "收件岗位", "状态"]
ws.append(headers)
for cell in ws[1]:
cell.font = Font(bold=True)
counts = Counter()
for alert, contract, node, _user in items:
role = _ALERT_RULES[node.node_type][alert.alert_round - 1][1]
ws.append([
contract.contract_no or "待解析", contract.purchase_order_no or "—", contract.supplier_name or "—",
str(contract.total_amount or ""), _node_label(node.node_type), str(node.amount or ""),
str(node.percentage or ""), _node_paid_date(node) or "—", (node.due_date or node.anchor_date).isoformat() if (node.due_date or node.anchor_date) else "—",
f"第{alert.alert_round}次", _role_label(role), alert.status,
])
counts[node.node_type] += 1
ws.freeze_panes = "A2"
ws.auto_filter.ref = ws.dimensions
output = BytesIO()
wb.save(output)
return output.getvalue(), {"total": len(items), "stages": {_node_label(k): v for k, v in counts.items()}}
def _build_summary_message(summary: dict[str, object]) -> str:
stages = summary.get("stages") or {}
detail = "、".join(f"{key}{value}笔" for key, value in stages.items()) or "无"
return f"本周需关注付款 {summary.get('total', 0)} 笔\n阶段汇总:{detail}\n详细合同与付款信息请查看随附 Excel。"
def _anchor_date(*, contract: ContractPaymentContract, node: ContractPaymentNode) -> date | None:
"""返回付款节点的提醒规则锚点日期;缺少事实时返回 None。"""
if node.node_type == "prepayment":
return contract.oa_archive_at.date() if contract.oa_archive_at else None
if node.node_type == "shipment":
return node.due_date or contract.delivery_due_date
if node.node_type == "acceptance":
event = db.session.query(ContractPaymentEvent).filter_by(contract_id=contract.id, event_type="acceptance_archive").order_by(ContractPaymentEvent.event_date.asc()).first()
return event.event_date if event else None
if node.node_type == "warranty":
return node.due_date
return None
def bind_contract_owner_from_applicant(contract: ContractPaymentContract) -> User | None:
"""
将合同第一轮收件人绑定为台账申请人对应的系统用户。
核心逻辑:用 OA/台账上的申请人姓名对 `users.real_name` 做去空白后的精确匹配;
仅当且仅有一名 active 用户时写入 `owner_user_id`。匹配失败、姓名为空或重名时清空
`owner_user_id`,禁止继续使用默认管理员或其他兜底账号。
Args:
contract: 已带 applicant_name 的合同主记录。
Returns:
唯一匹配到的系统用户;无法唯一确定时返回 None。
"""
name = str(contract.applicant_name or "").strip()
if not name:
contract.owner_user_id = None
return None
matches = (
db.session.query(User)
.filter(User.status == "active", func.trim(User.real_name) == name)
.order_by(User.id.asc())
.all()
)
if len(matches) != 1:
current_app.logger.warning(
"contract_payment applicant mapping skipped contract_id=%s applicant=%s matches=%s",
getattr(contract, "id", None),
name,
len(matches),
)
contract.owner_user_id = None
return None
user = matches[0]
contract.owner_user_id = user.id
return user
def _batch_wecom_userid(
items: list[tuple[ContractPaymentAlert, ContractPaymentContract, ContractPaymentNode, User]],
user: User,
) -> str | None:
"""
解析本周批次实际发送的企业微信 userid。
核心逻辑:第二、三轮优先用 OA 矩阵写入的 `oa_wecom_userid`(即 HrmResource.id);
没有时回退系统用户已绑定的 wecom_userid。第一轮通常走后者。
"""
for alert, *_rest in items:
raw = (alert.message_json or {}).get("oa_wecom_userid")
text = str(raw or "").strip()
if text:
return text
bound = str(getattr(user, "wecom_userid", None) or "").strip()
return bound or None
def _resolve_recipients(
*,
contract: ContractPaymentContract,
recipient_role: str,
supervisors: SupervisorMatrixCache,
) -> list[_AlertRecipient]:
"""
根据轮次岗位解析有效收件人。
核心逻辑:第一轮按申请人真实姓名唯一匹配系统用户。第二轮用矩阵 zz、第三轮用 jfl,
该 OA id 同时作为企微 userid;再映射到系统用户以便写入 recipient_user_id。
查不到或无法唯一确定时跳过该轮,不向第一轮申请人或其他全局名单兜底。
"""
if recipient_role == "owner":
user = bind_contract_owner_from_applicant(contract)
return [_AlertRecipient(user=user)] if user else []
matrix = supervisors.get(contract.applicant_name)
if matrix is None or not matrix.ok:
return []
oa_id = matrix.round2_oa_id if recipient_role == "department_head" else matrix.round3_oa_id
lastname = matrix.round2_name if recipient_role == "department_head" else matrix.round3_name
user = _user_for_oa_wecom_id(oa_id, lastname)
if user is None:
current_app.logger.warning(
"contract_payment supervisor recipient missing role=%s contract_id=%s oa_id=%s",
recipient_role,
getattr(contract, "id", None),
oa_id,
)
return []
return [_AlertRecipient(user=user, oa_wecom_userid=str(oa_id))]
def _user_for_oa_wecom_id(oa_id: int | None, lastname: str | None) -> User | None:
"""
将 OA/企微 userid 映射为系统用户。
核心逻辑:优先 `users.wecom_userid` 精确等于 OA id;未绑定时再用主管 lastname
对 `users.real_name` 做唯一匹配,以便满足预警表的用户外键。重名或都未命中则放弃。
"""
if oa_id is None:
return None
wecom = str(oa_id)
by_wecom = (
db.session.query(User)
.filter(User.status == "active", User.wecom_userid == wecom)
.order_by(User.id.asc())
.all()
)
if len(by_wecom) == 1:
return by_wecom[0]
if len(by_wecom) > 1:
current_app.logger.warning(
"contract_payment supervisor wecom_userid not unique oa_id=%s matches=%s",
wecom,
len(by_wecom),
)
return None
name = str(lastname or "").strip()
if not name:
return None
by_name = (
db.session.query(User)
.filter(User.status == "active", func.trim(User.real_name) == name)
.order_by(User.id.asc())
.all()
)
if len(by_name) == 1:
return by_name[0]
current_app.logger.warning(
"contract_payment supervisor user mapping skipped oa_id=%s lastname=%s matches=%s",
wecom,
name,
len(by_name),
)
return None
def _node_label(node_type: str) -> str:
"""返回付款阶段中文名称。"""
return {"prepayment": "预付款", "shipment": "出货款", "acceptance": "验收款", "warranty": "质保款"}.get(node_type, node_type)
def _role_label(role: str) -> str:
"""返回提醒岗位中文名称。"""
return {"owner": "采购负责人", "department_head": "采购部负责人", "procurement_leader": "采购分管领导"}.get(role, role)
@@ -0,0 +1,205 @@
"""
backend/app/services/contract_payment/dms_client.py
用途:访问采购合同文档管理系统,作为 OA 附件缺失时的延迟补充来源。
依赖:requests、Flask 配置;接口模式复用固定资产图片服务的登录、目录查询和附件代理。
逻辑:使用配置的根 FolderID 逐级定位年份目录,按合同编号检索文件,再按创建日期窗口筛选并下载附件。
"""
from __future__ import annotations
import threading
import time
from datetime import date, datetime, timedelta
from typing import Any
from urllib.parse import urlencode
import requests
from flask import current_app
_LOCK = threading.Lock()
_CACHE: dict[str, Any] = {"session": None, "created_at": 0.0}
class ContractDmsClient:
"""采购合同文档库轻量客户端;不会把账号或密码返回给 API。"""
@classmethod
def _base(cls) -> str:
return str(current_app.config.get("CONTRACT_DMS_BASE_URL") or "").rstrip("/")
@classmethod
def is_configured(cls) -> bool:
"""判断 DMS 地址、账号、密码和文档库 ID 是否齐全。"""
return bool(
cls._base()
and current_app.config.get("CONTRACT_DMS_USERNAME")
and current_app.config.get("CONTRACT_DMS_PASSWORD")
and current_app.config.get("CONTRACT_DMS_LIBRARY_ID")
and current_app.config.get("CONTRACT_DMS_ROOT_FOLDER_ID")
)
@classmethod
def _session(cls, *, refresh: bool = False) -> requests.Session:
"""登录 DMS 并缓存会话;登录失败抛出异常,不暴露密码。"""
with _LOCK:
session = _CACHE.get("session")
if not refresh and isinstance(session, requests.Session) and time.time() - float(_CACHE.get("created_at") or 0) < 1200:
return session
session = requests.Session()
response = session.post(
f"{cls._base()}/Login/_api/Login",
json={"LoginName": current_app.config.get("CONTRACT_DMS_USERNAME"), "Pwd": current_app.config.get("CONTRACT_DMS_PASSWORD")},
timeout=20,
)
response.raise_for_status()
payload = response.json()
if int(payload.get("Code") or 0) != 0:
raise RuntimeError(payload.get("Msg") or "文档管理系统登录失败")
_CACHE.update({"session": session, "created_at": time.time()})
return session
@classmethod
def _page(cls, *, parent_folder_id: str, leaf_name: str = "", recursion: bool = False) -> list[dict[str, Any]]:
"""查询一个父目录下的条目;目录解析使用非递归,合同文件检索使用递归。"""
payload = {
"LibraryID": str(current_app.config.get("CONTRACT_DMS_LIBRARY_ID")),
"ParentFolderID": parent_folder_id,
"Keywords": "",
"Page": {"Size": 200, "Index": 1},
"Total": 0,
"Recursion": recursion,
"OrderBy": [],
"FieldQuery": [],
"LeafName": leaf_name,
}
session = cls._session()
response = session.post(f"{cls._base()}/Api/_api/APS/Public/Item/Page", json=payload, timeout=30)
if response.status_code in {401, 403}:
session = cls._session(refresh=True)
response = session.post(f"{cls._base()}/Api/_api/APS/Public/Item/Page", json=payload, timeout=30)
response.raise_for_status()
data = response.json()
if int(data.get("Code") or 0) != 0:
raise RuntimeError(data.get("Msg") or "文档管理系统查询失败")
section = data.get("Data") or {}
return section.get("Rows") or section.get("Items") or (section.get("Page") or {}).get("Items") or []
@classmethod
def resolve_folder(cls, *, archive_date: date | None = None, folder_id: str | None = None) -> str:
"""
根据归档年份解析合同目录 FolderID。
AI 触发时机:OA 附件缺失,需要在 DMS 补查合同时调用。
逻辑:传入 folder_id 时直接使用;否则从根目录查找“{year}年设备合同书”,查不到时回退根目录。
"""
explicit = str(folder_id or "").strip()
if explicit:
return explicit
root = str(current_app.config.get("CONTRACT_DMS_ROOT_FOLDER_ID") or "").strip()
if not root or not archive_date:
return root
if archive_date.year == 2026:
configured_2026 = str(current_app.config.get("CONTRACT_DMS_2026_FOLDER_ID") or "").strip()
if configured_2026:
return configured_2026
template = str(current_app.config.get("CONTRACT_DMS_YEAR_FOLDER_NAME_TEMPLATE") or "{year}年设备合同书")
wanted = template.format(year=archive_date.year)
rows = cls._page(parent_folder_id=root, recursion=False)
for row in rows:
if row.get("IsFolder") and str(row.get("LeafName") or "").strip() == wanted:
return str(row.get("ID") or root)
return root
@classmethod
def _created_at(cls, row: dict[str, Any]) -> datetime | None:
"""读取 DMS 条目的创建时间,无法解析时返回 None。"""
raw = row.get("CreatedDate") or row.get("CreatedAt") or row.get("CreateDate")
if isinstance(raw, datetime):
return raw.replace(tzinfo=None)
text = str(raw or "").strip()
if not text:
return None
try:
return datetime.fromisoformat(text.replace("Z", "+00:00")).replace(tzinfo=None)
except ValueError:
return None
@classmethod
def search(cls, *, contract_no: str, folder_id: str | None = None, archive_date: date | None = None) -> list[dict[str, Any]]:
"""
按合同编号查询 DMS 文件并按 OA 归档日期过滤。
AI 触发时机:OA 附件下载失败或延迟到达时调用。
约束:只返回文件元数据;不创建合同主记录、不生成采购单号。首选年份目录,最后查询暂存目录。
"""
if not cls.is_configured():
return []
normalized = str(contract_no or "").strip()
if not normalized:
return []
root = str(current_app.config.get("CONTRACT_DMS_ROOT_FOLDER_ID") or "").strip()
primary = cls.resolve_folder(archive_date=archive_date, folder_id=folder_id)
folder_ids = [primary]
temp_name = str(current_app.config.get("CONTRACT_DMS_TEMP_FOLDER_NAME") or "暂存").strip()
if primary == root and root:
rows = cls._page(parent_folder_id=root, recursion=False)
else:
rows = cls._page(parent_folder_id=root, recursion=False) if root else []
for row in rows:
if row.get("IsFolder") and str(row.get("LeafName") or "").strip() == temp_name:
temp_id = str(row.get("ID") or "")
if temp_id and temp_id not in folder_ids:
folder_ids.append(temp_id)
window = max(int(current_app.config.get("CONTRACT_DMS_LOOKUP_WINDOW_DAYS") or 30), 0)
start = datetime.combine(archive_date - timedelta(days=window), datetime.min.time()) if archive_date else None
end = datetime.combine(archive_date + timedelta(days=window), datetime.max.time()) if archive_date else None
matches: list[dict[str, Any]] = []
for current_folder in folder_ids:
for row in cls._page(parent_folder_id=current_folder, leaf_name=normalized, recursion=True):
if row.get("IsFolder"):
continue
if normalized.lower() not in str(row.get("LeafName") or "").lower():
continue
created = cls._created_at(row)
if start and end and created and not (start <= created <= end):
continue
row = dict(row)
row["DmsFolderID"] = current_folder
matches.append(row)
matches.sort(key=lambda row: cls._created_at(row) or datetime.min, reverse=True)
return matches
@classmethod
def download_attachment(cls, attachment_id: str, *, max_size: int | None = None) -> tuple[bytes, str, str | None]:
"""
下载 DMS 附件二进制,供 FileAsset 私有存储和合同解析使用。
参数约束:attachment_id 必须来自 DMS Item/Page 返回的 MainFileAttachment.ID。
返回:文件字节、MIME 类型、Content-Disposition 推断的文件名。
"""
attachment = str(attachment_id or "").strip()
if not attachment:
raise ValueError("DMS attachment ID is required")
session = cls._session()
response = session.get(cls.attachment_url(attachment), timeout=60, allow_redirects=True)
if response.status_code in {401, 403}:
session = cls._session(refresh=True)
response = session.get(cls.attachment_url(attachment), timeout=60, allow_redirects=True)
response.raise_for_status()
data = response.content
limit = max_size or 30 * 1024 * 1024
if len(data) > limit:
raise RuntimeError("DMS 附件超过文件大小限制")
content_type = (response.headers.get("content-type") or "application/octet-stream").split(";", 1)[0].strip().lower()
disposition = response.headers.get("content-disposition") or ""
filename = None
if "filename=" in disposition:
filename = disposition.split("filename=", 1)[1].strip().strip('"')
return data, content_type, filename
@classmethod
def attachment_url(cls, attachment_id: str) -> str:
"""生成同源附件 Embed URL;不把登录 Cookie 暴露给前端。"""
return f"{cls._base()}/Api/_api/DMS/Public/Attachment/Embed?{urlencode({'attachmentID': attachment_id})}"
@@ -0,0 +1,221 @@
"""
backend/app/services/contract_payment/erp_payment_service.py
用途:从 ERP Oracle `apa_file` 读取采购单付款记录,作为预付款和出货款的付款完成事实来源。
依赖:oracledb、Text2SQLService 的 Oracle 客户端初始化能力及 Flask 配置。
逻辑:仅执行只读查询;只接受 `apa00='15'`(厂商预付款作业)且 `apa41='Y'`、`apa63=1` 的记录,并按采购单收集 `apa34f` 供明细和阶段匹配使用。
"""
from __future__ import annotations
import itertools
from dataclasses import dataclass
from decimal import Decimal, InvalidOperation
from typing import Iterable
from flask import current_app
_PAYMENT_STAGE_ORDER = {"prepayment": 1, "shipment": 2}
@dataclass(frozen=True)
class ErpPaidRow:
"""ERP `apa_file` 中一条合格的付款记录。"""
amount: Decimal
# 付款日期(apa02)ISO 字符串;ERP 未提供或为空时保持 None。
paid_date: str | None
def fetch_paid_records(purchase_order_nos: Iterable[str]) -> dict[str, list[ErpPaidRow]]:
"""
查询采购单已完成付款记录(含付款日期)。
AI 触发时机:合同付款预警每日扫描前,需要判断预付款/出货款是否已经完成付款。
核心逻辑:查询 `apa_file`,先按 `apa00='15'` 限定为「厂商预付款作业」,再过滤 `apa41='Y'` 和 `apa63=1`,按 `apaud03` 收集 `apa34f`(金额)与 `apa02`(付款日期)。
Args:
purchase_order_nos: 待查询的采购单号集合;空集合不会连接 ERP。
Returns:
采购单号到合格付款记录列表的映射。ERP 未配置、驱动不可用或查询失败时返回空映射,
由调用方按未付款处理,避免错误停止预警。
"""
normalized = sorted({str(value or "").strip() for value in purchase_order_nos if str(value or "").strip()})
if not normalized:
return {}
dsn = str(current_app.config.get("CONTRACT_PAYMENT_ERP_DSN") or "").strip()
username = str(current_app.config.get("CONTRACT_PAYMENT_ERP_USERNAME") or "").strip()
password = str(current_app.config.get("CONTRACT_PAYMENT_ERP_PASSWORD") or "")
if not dsn or not username or not password:
# 打印缺失字段名,便于定位到底是 DSN / 用户名 / 密码哪一项在运行时为空(不输出密码本身)。
missing = [name for name, value in (("DSN", dsn), ("用户名", username), ("密码", password)) if not value]
current_app.logger.warning("合同付款预警:ERP 付款查询未配置,按未付款处理;缺失字段=%s", "、".join(missing) or "未知")
return {}
try:
import oracledb
from app.services.text2sql import Text2SQLService
except ImportError:
current_app.logger.warning("合同付款预警:Oracle 驱动不可用,按未付款处理")
return {}
connection = None
try:
# 合同付款仅需 apa_file 单表读取:优先尝试 thick(需本机 Oracle Client),
# 若本机未安装 Oracle Client(DPI-1047)则回退到 python-oracledb 默认的 thin 模式,
# 避免因缺少客户端库而把整笔已付事实误判为未付。
try:
Text2SQLService._init_oracle_client(oracledb)
except Exception:
current_app.logger.info("合同付款预警:Oracle Client 不可用,回退 thin 模式连接")
connection = oracledb.connect(user=username, password=password, dsn=dsn)
timeout = max(int(current_app.config.get("CONTRACT_PAYMENT_ERP_TIMEOUT_SECONDS") or 30), 5)
connection.call_timeout = timeout * 1000
cursor = connection.cursor()
placeholders = ", ".join(f":po_{index}" for index in range(len(normalized)))
# [STEP 1] 只取「厂商预付款作业」类型的付款记录:apa00='15' 为厂商预付款作业标志,
# 过滤掉其它作业类型(如对账/其它付款),避免把非预付款的付款误匹配到预付款/出货款节点;
# 后再叠加 apa41='Y'(有效)与 apa63=1(已完成付款)两层过滤,仅统计真正完成的预付款。
# apaud03 varchar2 40 采购单号
sql = f"""
SELECT TRIM(apaud03) AS purchase_order_no,
NVL(apa34f, 0) AS paid_amount,
TRUNC(apa02) AS paid_date
FROM apa_file
WHERE TRIM(apaud03) IN ({placeholders})
AND TRIM(TO_CHAR(apa00)) = '15'
AND UPPER(TRIM(apa41)) = 'Y'
AND TRIM(TO_CHAR(apa63)) = '1'
"""
cursor.execute(sql, {f"po_{index}": value for index, value in enumerate(normalized)})
result: dict[str, list[ErpPaidRow]] = {}
for raw_po, raw_amount, raw_paid_date in cursor:
po = str(raw_po or "").strip()
if not po:
continue
try:
amount = Decimal(str(raw_amount or "0"))
except (InvalidOperation, TypeError, ValueError):
continue
paid_date = getattr(raw_paid_date, "isoformat", lambda: None)().split("T")[0] if raw_paid_date else None
result.setdefault(po, []).append(ErpPaidRow(amount=amount, paid_date=paid_date))
return result
except Exception as exc:
# 记录具体 Oracle 错误码(如 ORA-01017/00942/12514)与消息,便于定位账号权限/服务名问题;不输出密码。
code = getattr(exc, "code", None) or getattr(exc, "full_code", None)
current_app.logger.warning(
"合同付款预警:ERP 付款查询失败,按未付款处理,error_type=%s code=%s message=%s",
type(exc).__name__,
code,
str(exc) or getattr(exc, "message", ""),
)
return {}
finally:
if connection is not None:
try:
connection.close()
except Exception:
pass
def fetch_paid_amounts(purchase_order_nos: Iterable[str]) -> dict[str, list[Decimal]]:
"""查询采购单已完成付款金额列表(兼容旧调用方)。"""
records = fetch_paid_records(purchase_order_nos)
return {po: [row.amount for row in rows] for po, rows in records.items()}
def _select_match(
unresolved: list[tuple[int, str, Decimal]],
amount: Decimal,
tolerance: Decimal,
) -> list[tuple[int, str, Decimal]]:
"""从待匹配节点列表中选出与某笔 ERP 付款金额匹配的节点。
核心逻辑:预付款与出货款可能「分开请款」也可能「同一笔请款一并请款」,
因此先按单节点金额匹配(分开请款场景);若单节点无命中,再按「多节点金额之和」
匹配(同一笔请款同时请预付款+出货款),命中后一次性返回全部相关节点,
由调用方把都标记为已付款,避免把组合金额漏判为未付款。
Args:
unresolved: 待匹配的 `(node_id, node_type, amount)` 列表,已按业务顺序排序。
amount: 本次 ERP 付款金额(apa34f)。
tolerance: 金额匹配容差(默认 0.01)。
Returns:
匹配到的节点列表;无匹配时返回空列表。单节点命中时只取顺序最前的一个。
"""
# [STEP 1] 分开请款:单节点金额与付款金额一致。
single = [item for item in unresolved if abs(item[2] - amount) <= tolerance]
if single:
return single[:1]
# [STEP 2] 同一笔请款:预付款+出货款等节点金额之和与付款金额一致,命中即全部视为已付。
# 节点数量极少(通常 2 个),组合搜索开销可忽略;优先从小组合(2 个)开始找。
for size in range(2, len(unresolved) + 1):
for combo in itertools.combinations(unresolved, size):
if abs(sum(item[2] for item in combo) - amount) <= tolerance:
return list(combo)
return []
def resolve_paid_node_dates(
nodes: Iterable[tuple[int, str, Decimal | None]],
paid_rows: Iterable[ErpPaidRow],
) -> dict[int, str | None]:
"""
将同一采购单的 ERP 付款记录匹配到预付款、出货款节点,并返回节点 ID 到付款日期的映射。
核心逻辑:`apa00='15'`、`apa41='Y'` 且 `apa63=1` 的每笔 ERP 付款按金额与节点匹配;
金额相同则按预付款、出货款的业务顺序匹配最前面仍未付款的节点;若单节点无匹配但
「预付款+出货款」金额之和与该笔付款一致,说明预付款与出货款在同一笔请款中一并请款,
则把两者同时标记为已付款,并携带该笔付款日期。
Args:
nodes: 同一采购单的 `(node_id, node_type, amount)` 节点;只传预付款、出货款的 active 节点。
paid_rows: 该采购单的合格 ERP 付款记录。
Returns:
已匹配节点的付款日期映射(节点 ID -> 付款日期,日期可能为空)。
"""
tolerance = Decimal("0.01")
unresolved = sorted(
((node_id, node_type, amount) for node_id, node_type, amount in nodes if amount is not None),
key=lambda item: (_PAYMENT_STAGE_ORDER.get(item[1], 99), item[0]),
)
matched: dict[int, str | None] = {}
for paid_row in paid_rows:
hits = _select_match(unresolved, paid_row.amount, tolerance)
if not hits:
continue
hit_ids = {item[0] for item in hits}
for item in hits:
matched[item[0]] = paid_row.paid_date
unresolved = [item for item in unresolved if item[0] not in hit_ids]
return matched
def resolve_paid_node_ids(
nodes: Iterable[tuple[int, str, Decimal | None]],
paid_amounts: Iterable[Decimal],
) -> set[int]:
"""
将同一采购单的 ERP 付款金额匹配到预付款、出货款节点。
核心逻辑:`apa00='15'`、`apa41='Y'` 且 `apa63=1` 的每笔 ERP 付款按 `apa34f` 与节点金额匹配;
金额不同则自然对应相应节点,金额相同时按预付款、出货款的业务顺序匹配最前面仍未付款的节点;
若单节点无匹配但「预付款+出货款」金额之和与该笔付款一致,则一并标记两者为已付款
(预付款、出货款在同一笔请款中一并请款的场景)。
Args:
nodes: 同一采购单的 `(node_id, node_type, amount)` 节点;只传预付款、出货款的 active 节点。
paid_amounts: 该采购单的合格 ERP 每笔付款金额。
Returns:
已付款节点 ID 集合。
"""
tolerance = Decimal("0.01")
unresolved = sorted(
((node_id, node_type, amount) for node_id, node_type, amount in nodes if amount is not None),
key=lambda item: (_PAYMENT_STAGE_ORDER.get(item[1], 99), item[0]),
)
matched: set[int] = set()
for paid_amount in paid_amounts:
hits = _select_match(unresolved, paid_amount, tolerance)
if not hits:
continue
hit_ids = {item[0] for item in hits}
matched.update(hit_ids)
unresolved = [item for item in unresolved if item[0] not in hit_ids]
return matched
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,414 @@
"""
backend/app/services/contract_payment/parse_service.py
用途:从 DOC/DOCX/PDF/TXT 抽取采购合同关键字段,并生成四个付款阶段的节点草稿。
依赖:标准库正则与日期处理;原文抽取由调用方传入,避免绑定某一种文件解析器。
逻辑:先识别固定字段和付款比例,再校验金额/比例/日期;无法确定的事实进入 needs_review,不猜测。
同一付款阶段的相同比例重复抽取不报重复;详情接口展示前对 issues 去重。
"""
from __future__ import annotations
from os import unlink
import re
import tempfile
from datetime import date, timedelta
from decimal import Decimal, InvalidOperation
from typing import Any
import requests
from flask import current_app
from app.services.procurement_contract.analyze import extract_text_from_bytes
_DATE_RE = re.compile(r"(20\d{2})[\s_]*[年./-][\s_]*(\d{1,2})[\s_]*[月./-][\s_]*(\d{1,2})[\s_]*日?")
_MONEY_RE = re.compile(r"(?:设备总价款\s*[((]?含税[))]?|人民币合同金额|合同金额|合同总价|含税总价)[::\s¥¥]*([\d,]+(?:\.\d+)?)", re.I)
_PERCENT_RE = re.compile(r"(预付款|定金|出货款|货款|验收款|质保款|保款|尾款)[^。;;\n]{0,140}?(\d+(?:\.\d+)?)\s*%", re.S)
_DELIVERY_RE = re.compile(r"(?:交货期限|约定到货日期|交付期限|交货期)[::\s]*[^。;;\n]{0,60}?(20\d{2}[^\n。;;]*)")
_WARRANTY_RE = re.compile(r"(?:质保期|保修期|保固期|质保款[^。;;\n]{0,100}?)(?:满后|为|:|:)?\s*(\d+)\s*(年|个月|月|天)")
_WARRANTY_PAYMENT_RE = re.compile(
r"(?:从验收(?:合格)?日起算\s*|质保款[^。;;\n]{0,100}?)(\d+)\s*(年|个月|月|天)\s*(?:质保期|保修期|保固期)?[^。;;\n]{0,24}?满后"
)
_CONTRACT_NO_RE = re.compile(r"(?:合同编号|合同号|Contract\s*No\.?)[::\s]*([A-Za-z0-9][A-Za-z0-9\-_/..]{3,63})", re.I)
_PAYMENT_NODE_LABELS = {
"prepayment": "预付款",
"shipment": "出货款",
"acceptance": "验收款",
"warranty": "质保款",
}
_PAYMENT_LABEL_TO_NODE_TYPE = {
"预付款": "prepayment", "定金": "prepayment",
"出货款": "shipment", "货款": "shipment",
"验收款": "acceptance",
"质保款": "warranty", "尾款": "warranty",
}
_PAYMENT_NODE_TYPES = tuple(_PAYMENT_NODE_LABELS)
def _parse_date(value: str | None) -> date | None:
"""
解析常见中文日期。
核心逻辑:只接受明确的年月日文本,避免将不完整期限猜测为业务日期。
Args:
value: 待解析的日期文本,可为空。
Returns:
合法日期;无法识别时返回 None。
"""
if not value:
return None
match = _DATE_RE.search(str(value))
if not match:
return None
try:
return date(int(match.group(1)), int(match.group(2)), int(match.group(3)))
except ValueError:
return None
def _parse_decimal(value: str | None) -> Decimal | None:
"""
解析金额或比例数字,忽略千分位逗号。
Args:
value: 金额或百分比中的数字文本。
Returns:
Decimal 数值;格式非法时返回 None。
"""
if value is None:
return None
try:
return Decimal(str(value).replace(",", "").strip())
except (InvalidOperation, ValueError):
return None
def _to_days(value: int, unit: str) -> int:
"""
将质保期限统一为自然日。
核心逻辑:按合同预警域现有约定,将年按 365 天、月按 30 天换算。
Args:
value: 期限数值,必须为非负整数。
unit: 年、月、个月或天。
Returns:
对应自然日数。
"""
if unit == "年":
return value * 365
if unit in {"月", "个月"}:
return value * 30
return value
def unique_parse_issues(issues: list[Any] | None) -> list[str]:
"""
按出现顺序去掉重复的解析问题文案。
核心逻辑:MinerU/OCR 常把付款表重复抽成多段,同一阶段会命中多次;页面只需要
每种原因一条,避免「出货款付款比例重复」连写六遍。空串和纯空白丢弃。
Args:
issues: 解析器或已落库 JSON 中的 issues 列表。
Returns:
去重后的问题文案;入参非法时返回空列表。
"""
if not isinstance(issues, list):
return []
seen: set[str] = set()
result: list[str] = []
for item in issues:
text = str(item or "").strip()
if not text or text in seen:
continue
seen.add(text)
result.append(text)
return result
def _extract_payment_percentages(body: str) -> tuple[dict[str, Decimal], list[str]]:
"""
提取四阶段付款比例,并校验阶段完整性及比例合计。
核心逻辑:同一语义阶段只允许一个比例。正文里同一比例被抽到多次(表格/页眉重复)
视为同一事实,不报重复;只有同一阶段出现不同比例才阻断。四阶段须完整且合计 100%。
Args:
body: 已抽取的合同正文。
Returns:
按付款节点归一化的比例,以及阻断自动预警的解析问题。
"""
found: dict[str, list[Decimal]] = {node_type: [] for node_type in _PAYMENT_NODE_TYPES}
issues: list[str] = []
for match in _PERCENT_RE.finditer(body):
label, raw = match.groups()
node_type = _PAYMENT_LABEL_TO_NODE_TYPE[label]
percentage = _parse_decimal(raw)
if percentage is None:
issues.append(f"{label}付款比例无法识别")
continue
found[node_type].append(percentage)
percentages: dict[str, Decimal] = {}
for node_type in _PAYMENT_NODE_TYPES:
values = found[node_type]
if not values:
continue
unique_values = list(dict.fromkeys(values))
if len(unique_values) > 1:
issues.append(f"{_PAYMENT_NODE_LABELS[node_type]}付款比例重复,需人工确认")
continue
percentages[node_type] = unique_values[0]
missing = [node_type for node_type in _PAYMENT_NODE_TYPES if node_type not in percentages]
if missing:
issues.append(f"付款阶段比例无法识别:{'、'.join(_PAYMENT_NODE_LABELS[item] for item in missing)}")
try:
matched = [(m.group(1), m.group(2)) for m in _PERCENT_RE.finditer(body)]
snippet = ""
for label in ("质保款", "验收款", "尾款"):
idx = body.find(label)
if idx >= 0:
snippet = body[max(0, idx - 40):idx + 80].replace("\n", "⏎")
break
current_app.logger.warning(
"合同付款预警:付款比例提取缺失 missing=%s matched=%s 片段=%r",
[_PAYMENT_NODE_LABELS[item] for item in missing], matched, snippet,
)
except Exception:
pass
elif sum(percentages.values(), Decimal("0")) != Decimal("100"):
issues.append("四阶段付款比例合计不等于100%")
return percentages, unique_parse_issues(issues)
def _log_delivery_extraction(body: str) -> None:
"""交货期限无法识别时输出正文片段与日期模式数,便于定位 MinerU/OCR 抽取差异。"""
from flask import current_app
snippet = ""
for token in ("交货期限", "约定到货", "交货期", "交付", "到货", "出货"):
idx = body.find(token)
if idx >= 0:
snippet = body[max(0, idx - 30):idx + 90].replace("\n", " ")
break
current_app.logger.warning(
"合同付款预警:交货期限未能识别;日期模式数=%s 正文片段=%r", len(_DATE_RE.findall(body)), snippet,
)
def _extract_mineru_text(filename: str, data: bytes) -> str:
"""
调用 MinerU 提取 PDF 的 Markdown 正文,作为合同付款条款的首选来源。
核心逻辑:将单份 PDF 上传至内网 MinerU `/file_parse`,只接受成功结果中非空的
`md_content`;Markdown 保留表格、标题与阅读顺序,便于后续规则识别付款比例。服务
未配置、超时或返回异常时返回空字符串,由调用方明确回退旧解析链路。
Args:
filename: 原始合同文件名,必须以 `.pdf` 结尾才会调用 MinerU。
data: 原始 PDF 字节,不允许为空。
Returns:
MinerU 返回的 Markdown 正文;未配置或解析失败时为空字符串。
"""
if not str(filename or "").lower().endswith(".pdf") or not data:
return ""
# 合同付款与采购合同审核解析同一类合同,固定复用审核域唯一的 MinerU 服务配置。
api_url = str(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_API_URL") or "").strip().rstrip("/")
if not api_url:
return ""
connect_timeout = max(int(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_CONNECT_TIMEOUT_SECONDS") or 5), 1)
read_timeout = max(int(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_READ_TIMEOUT_SECONDS") or 300), 30)
backend = str(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_BACKEND") or "pipeline").strip() or "pipeline"
parse_method = str(current_app.config.get("PROCUREMENT_CONTRACT_MINERU_PARSE_METHOD") or "auto").strip() or "auto"
try:
response = requests.post(
f"{api_url}/file_parse",
data={
"lang_list": "ch",
"backend": backend,
"parse_method": parse_method,
"formula_enable": "false",
},
files=[("files", (filename, data, "application/pdf"))],
timeout=(connect_timeout, read_timeout),
)
response.raise_for_status()
result = response.json()
except (ValueError, requests.RequestException):
return ""
if str(result.get("status") or "").lower() != "completed":
return ""
results = result.get("results")
if not isinstance(results, dict):
return ""
parsed = next((value for value in results.values() if isinstance(value, dict)), None)
return str((parsed or {}).get("md_content") or "").strip()
def _extract_ocr_text(filename: str, data: bytes) -> str:
"""
对扫描 PDF 执行 OCR 兜底。
核心逻辑:仅对 PDF 调用现有 OCR 能力;依赖不可用或解析失败时返回空文本,不伪造合同条款。
Args:
filename: 原始文件名,用于判断文件类型。
data: 原始文件字节。
Returns:
已识别的正文;无结果时为空字符串。
"""
if not str(filename or "").lower().endswith(".pdf"):
return ""
path = ""
try:
from edkb_system.contracts import Context
from edkb_system.skills import loader_pdf, ocr
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as handle:
handle.write(data)
path = handle.name
try:
context = Context(file_type="pdf")
blocks = loader_pdf.run({"file_path": path}, context)
if any(getattr(block, "type", "") == "image" for block in blocks):
blocks = ocr.run(blocks, context)
return "\n".join(
str(getattr(block, "text", "")).strip()
for block in blocks
if getattr(block, "type", "") in {"paragraph", "ocr_text"} and str(getattr(block, "text", "")).strip()
)
finally:
if path:
unlink(path)
except Exception:
return ""
def parse_contract_text(text: str, *, total_amount: Decimal | None = None, delivery_due_date: date | None = None) -> dict[str, Any]:
"""
解析合同正文并生成付款计划草稿。
AI 触发时机:合同附件保存后,需要自动获得付款节点时调用。
参数约束:text 为已抽取正文;不允许用模型猜测缺失日期或比例,结果必须可序列化为 JSON。
口径约定:合同正文是条款事实的权威来源;正文能抽取金额/交货期限时,即使与 OA 表单不同,
也以正文为准,不生成“与OA字段不一致”的待确认问题;仅当正文无法抽取时才回退 OA 表单值。
Returns:
包含 fields、nodes、status、issues、evidence 的结构化结果。
"""
body = str(text or "")
if body.startswith("[binary:"):
body = ""
issues: list[str] = []
# 合同正文是条款事实的权威来源;OA 字段只在正文未写明时作为补充。
# 正文能抽到金额/交货期限即以其为准,即使与 OA 表单不同也不再生成“不一致”待确认问题,
# 避免 OA 申请人录入错误把本可自动预警的合同永久卡在待复核。
amount_match = _MONEY_RE.search(body)
amount_from_contract = _parse_decimal(amount_match.group(1)) if amount_match else None
# OA 字段 total_amount 可能是字符串(如 _parse_amount 返回的 "221000.00"),统一归一为 Decimal,
# 否则下方 `amount * percentage` 会因字符串与 Decimal 相乘抛出 TypeError。
total_decimal = _parse_decimal(total_amount)
# 正文缺失时需回退 OA 交货期限;OA 字段可能以字符串到达(如 "2026-09-10"),
# 归一为 date 避免交付节点在 due_date.isoformat() 处因字符串抛错。
delivery_due_date = _parse_date(delivery_due_date)
amount = amount_from_contract if amount_from_contract is not None else total_decimal
delivery_match = _DELIVERY_RE.search(body)
delivery_from_contract = _parse_date(delivery_match.group(1)) if delivery_match else None
delivery = delivery_from_contract or delivery_due_date
if delivery is None:
# 合同常把日期写在“出货款/交货”句中,补充从付款条款附近抓取日期。
for match in _DATE_RE.finditer(body):
prefix = body[max(0, match.start() - 80):match.start()]
if any(token in prefix for token in ("交货", "交付", "到货", "出货")):
delivery = _parse_date(match.group(0))
break
warranty_days = None
# 付款条款中的期限优先于通用“保固”描述,确保质保款按应付款到期日预警。
warranty_match = _WARRANTY_PAYMENT_RE.search(body) or _WARRANTY_RE.search(body)
if warranty_match:
warranty_days = _to_days(int(warranty_match.group(1)), warranty_match.group(2))
contract_no_match = _CONTRACT_NO_RE.search(body)
contract_no = contract_no_match.group(1).strip(" 。;;,,") if contract_no_match else None
# [STEP 1] 一致性问题不再作为待确认阻断:正文为准,OA 仅在正文缺失时兜底。
# 资金与交货期限的取值已在上面以 amount / delivery 完成,此处只保留“无法识别”类问题。
if amount is None:
issues.append("合同金额无法识别")
if delivery is None:
issues.append("合同交货期限无法识别")
try:
_log_delivery_extraction(body)
except Exception:
pass
percentages, payment_issues = _extract_payment_percentages(body)
issues.extend(payment_issues)
issues = unique_parse_issues(issues)
nodes: list[dict[str, Any]] = []
for code, node_type in (("prepayment", "prepayment"), ("shipment", "shipment"), ("acceptance", "acceptance"), ("warranty", "warranty")):
percentage = percentages.get(node_type)
if percentage is None:
continue
node_amount = (amount * percentage / Decimal("100")).quantize(Decimal("0.01")) if amount is not None else None
# [STEP 1] 预付款和出货款是否已付款由 ERP apa_file 判定;合同只提供节点金额和出货款到期锚点。
anchor_type = (
"erp_payment"
if node_type in {"prepayment", "shipment"}
else "acceptance_archive"
)
due_date = delivery if node_type == "shipment" and delivery else None
nodes.append({
"node_code": code,
"node_type": node_type,
"amount": str(node_amount) if node_amount is not None else None,
"percentage": str(percentage),
"anchor_type": anchor_type,
"offset_days": 0,
"due_date": due_date.isoformat() if due_date else None,
"reminder_days": 0,
"evidence": {"matched_percent": str(percentage)},
})
if not nodes:
issues.append("未识别到预付款、出货款、验收款或质保款比例")
return {
"status": "needs_review" if issues else "parsed",
"fields": {
"contract_no": contract_no,
"total_amount": str(amount) if amount is not None else None,
"delivery_due_date": delivery.isoformat() if delivery else None,
"warranty_period_days": warranty_days,
},
"nodes": nodes,
"issues": issues,
"evidence": {
"parser": "contract-payment-four-stage-rules",
},
}
def parse_contract_bytes(filename: str, data: bytes, *, total_amount: Decimal | None = None, delivery_due_date: date | None = None) -> dict[str, Any]:
"""
从 DOC/DOCX/PDF 原文抽取文本后解析付款计划。
AI 触发时机:合同附件已资产化,需要直接从文件生成付款计划时调用。
核心逻辑:PDF 优先由 MinerU 提取 Markdown;服务不可用时再用统一附件解析器和旧 OCR
回退,最后委托文本解析器形成节点。
Args:
filename: 合同原始文件名,必须保留扩展名以供解析器选择路径。
data: 合同原始字节,不允许传入空字节伪造解析结果。
total_amount: OA 提供的合同总额,仅在正文未识别时作为补充。
delivery_due_date: OA 提供的约定到货日期,仅在正文未识别时作为补充。
Returns:
可 JSON 序列化的付款计划解析结果;不确定事实返回 needs_review。
"""
# [STEP 1] 扫描版 OA 合同没有可用文字层,MinerU 的版面 Markdown 优先于低精度 OCR。
mineru_text = _extract_mineru_text(filename, data)
extractor = "mineru" if mineru_text else "native_text"
text = mineru_text or extract_text_from_bytes(filename, data)
if text.startswith("[binary:"):
# [STEP 2] MinerU 不可用时保持旧 OCR 作为可用性兜底,不把附件同步整体判为失败。
ocr_text = _extract_ocr_text(filename, data)
if ocr_text.strip():
text = ocr_text
extractor = "legacy_ocr"
result = parse_contract_text(text, total_amount=total_amount, delivery_due_date=delivery_due_date)
result.setdefault("evidence", {})["document_extractor"] = extractor
current_app.logger.info(
"合同付款预警:合同正文抽取 extractor=%s mineru_len=%d text_len=%d",
extractor, len(mineru_text or ""), len(text or ""),
)
return result
@@ -0,0 +1,49 @@
"""合同付款预警默认排程种子:每日扫描与周五 18:00 汇总。"""
from __future__ import annotations
from datetime import datetime
from app import db
from app.models import ScheduleTask, User
from app.services.schedule.timezone_util import compute_next_run_at
_DEFAULTS = (
('SCH-CONTRACT-PAYMENT-SYNC', 'contract-payment-sync', '合同付款 OA 同步(日批)', '0 5 * * *'),
('SCH-CONTRACT-PAYMENT-ALERT-SCAN', 'contract-payment-alert-scan', '合同付款预警扫描(日批)', '0 6 * * *'),
('SCH-CONTRACT-PAYMENT-ALERT-WEEKLY', 'contract-payment-alert-weekly', '合同付款预警周汇总(周五 18:00)', '0 18 * * 5'),
)
def ensure_default_contract_payment_schedules(*, commit: bool = True):
"""幂等创建合同付款同步、每日扫描和周五汇总三个默认排程。
Args:
commit: 是否提交新建排程;测试或外层事务可传 False。
Returns:
新建的 ScheduleTask 列表;无用户时返回空列表。
"""
owner = db.session.query(User).filter(User.role == 'admin').order_by(User.id.asc()).first() or db.session.query(User).order_by(User.id.asc()).first()
if owner is None:
return []
created = []
for schedule_no, platform_path, name, cron in _DEFAULTS:
existing = db.session.query(ScheduleTask).filter((ScheduleTask.schedule_no == schedule_no) | (ScheduleTask.platform_api_path == platform_path)).first()
if existing:
continue
now = datetime.utcnow()
task = ScheduleTask(
schedule_no=schedule_no, name=name, schedule_type='platform_job', owner_user_id=owner.id,
cron_expr=cron, schedule_timezone='Asia/Shanghai', wait_seconds=0,
platform_api_path=platform_path, job_params={}, kb_sync_enabled=False,
notify_user_ids_json=[], notify_enabled=False, enabled=True,
next_run_at=compute_next_run_at(cron, timezone_name='Asia/Shanghai') or now,
created_by=owner.id, updated_by=owner.id, created_at=now, updated_at=now,
)
db.session.add(task); created.append(task)
if commit and created:
db.session.commit()
elif not commit:
db.session.flush()
return created
@@ -0,0 +1,316 @@
"""
backend/app/services/contract_payment/supervisor_oa_service.py
用途:从 OA ecology SQL Server 解析合同申请人的第二、三轮上级主管(企微收件人)。
依赖:OASQLServerService(复用 OA_SQLSERVER_* 只读连接)、Flask current_app。
逻辑:HrmResource.lastname = 申请人姓名 → departmentid;
Matrixtable_3.bm = departmentid,zz 为第二轮、jfl 为第三轮。
zz/jfl 即 HrmResource.id,也是企业微信 userid。查询失败 fail-safe 返回空,不向第一轮兜底。
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Any
from flask import current_app
from app.services.oa_sqlserver import OASQLServerService
# [STEP] 仅允许字母数字下划线作为 SQL 标识符,表名/字段来自配置,禁止拼接任意字符串。
_SAFE_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
_DEFAULT_HRM_TABLE = "HrmResource"
_DEFAULT_HRM_NAME_FIELD = "lastname"
_DEFAULT_HRM_DEPT_FIELD = "departmentid"
_DEFAULT_MATRIX_TABLE = "Matrixtable_3"
_DEFAULT_MATRIX_DEPT_FIELD = "bm"
_DEFAULT_MATRIX_ROUND2_FIELD = "zz"
_DEFAULT_MATRIX_ROUND3_FIELD = "jfl"
@dataclass(frozen=True)
class SupervisorMatrix:
"""一份合同申请人在 OA 矩阵中解析出的第二、三轮主管。"""
applicant_oa_id: int | None
department_id: int | None
round2_oa_id: int | None
round3_oa_id: int | None
round2_name: str | None
round3_name: str | None
ok: bool
class SupervisorMatrixCache:
"""同一扫描内按申请人姓名缓存 OA 矩阵,避免每个付款节点重复打 SQL。"""
def __init__(self) -> None:
self._store: dict[str, SupervisorMatrix | None] = {}
def get(self, applicant_name: str | None) -> SupervisorMatrix | None:
"""
返回该申请人的上级矩阵;姓名为空时不查 OA。
核心逻辑:去空白后的姓名作缓存键;首次调用才访问 ecology。
Args:
applicant_name: 台账申请人姓名,对应 HrmResource.lastname。
Returns:
解析结果;查询失败或无法唯一确定时为 None。
"""
key = str(applicant_name or "").strip()
if not key:
return None
if key not in self._store:
self._store[key] = fetch_supervisor_matrix(key)
return self._store[key]
def fetch_supervisor_matrix(applicant_name: str) -> SupervisorMatrix | None:
"""
按申请人姓名查询 OA 部门矩阵,得到第二、三轮主管的 OA/企微 ID。
AI 触发时机:合同付款每日扫描解析第二、三轮收件人时调用。
核心逻辑:lastname 必须唯一命中一名 HrmResource;再用 departmentid 唯一命中
Matrixtable_3.bm。重名、无部门、无矩阵行或查询失败时返回 None,禁止猜测。
Args:
applicant_name: 合同台账申请人,须与 OA lastname 一致。
Returns:
SupervisorMatrix;无法确定时 None。
"""
name = str(applicant_name or "").strip()
if not name:
return None
hrm_table = _configured_ident("CONTRACT_PAYMENT_OA_HRM_TABLE", _DEFAULT_HRM_TABLE)
name_field = _configured_ident("CONTRACT_PAYMENT_OA_HRM_NAME_FIELD", _DEFAULT_HRM_NAME_FIELD)
dept_field = _configured_ident("CONTRACT_PAYMENT_OA_HRM_DEPT_FIELD", _DEFAULT_HRM_DEPT_FIELD)
matrix_table = _configured_ident("CONTRACT_PAYMENT_OA_MATRIX_TABLE", _DEFAULT_MATRIX_TABLE)
matrix_dept_field = _configured_ident(
"CONTRACT_PAYMENT_OA_MATRIX_DEPT_FIELD", _DEFAULT_MATRIX_DEPT_FIELD
)
round2_field = _configured_ident(
"CONTRACT_PAYMENT_OA_MATRIX_ROUND2_FIELD", _DEFAULT_MATRIX_ROUND2_FIELD
)
round3_field = _configured_ident(
"CONTRACT_PAYMENT_OA_MATRIX_ROUND3_FIELD", _DEFAULT_MATRIX_ROUND3_FIELD
)
connection = None
try:
connection = OASQLServerService._connect()
cursor = connection.cursor()
# [STEP 1] 按姓名唯一确定申请人及其部门;精确匹配为空时再按包装串模糊匹配
hrm_sql, hrm_params = build_hrm_lookup_sql(
table=hrm_table, name_field=name_field, dept_field=dept_field, applicant_name=name
)
cursor.execute(hrm_sql, hrm_params)
hrm_rows = list(cursor.fetchall() or [])
people = _unique_hrm_rows(hrm_rows, name)
if people is None and not hrm_rows:
like_sql, like_params = build_hrm_lookup_sql(
table=hrm_table,
name_field=name_field,
dept_field=dept_field,
applicant_name=name,
fuzzy=True,
)
cursor.execute(like_sql, like_params)
people = _unique_hrm_rows(cursor.fetchall(), name)
if people is None:
current_app.logger.warning(
"contract_payment supervisor skipped: applicant lastname not unique or missing name=%s",
name,
)
return None
applicant_oa_id, department_id = people
# [STEP 2] 部门 ID 关联矩阵表,读取第二轮 zz、第三轮 jfl
matrix_sql, matrix_params = build_matrix_lookup_sql(
table=matrix_table,
dept_field=matrix_dept_field,
round2_field=round2_field,
round3_field=round3_field,
department_id=department_id,
)
cursor.execute(matrix_sql, matrix_params)
matrix_rows = cursor.fetchall() or []
if len(matrix_rows) != 1:
current_app.logger.warning(
"contract_payment supervisor skipped: matrix rows=%s department_id=%s applicant=%s",
len(matrix_rows),
department_id,
name,
)
return None
round2_oa_id = _as_positive_int(_row_value(matrix_rows[0], 1))
round3_oa_id = _as_positive_int(_row_value(matrix_rows[0], 2))
round2_name = _lookup_resource_name(cursor, hrm_table, name_field, round2_oa_id)
round3_name = _lookup_resource_name(cursor, hrm_table, name_field, round3_oa_id)
return SupervisorMatrix(
applicant_oa_id=applicant_oa_id,
department_id=department_id,
round2_oa_id=round2_oa_id,
round3_oa_id=round3_oa_id,
round2_name=round2_name,
round3_name=round3_name,
ok=True,
)
except Exception:
current_app.logger.exception(
"contract_payment supervisor OA lookup failed applicant=%s", name
)
return None
finally:
if connection is not None:
try:
connection.close()
except Exception:
pass
def build_hrm_lookup_sql(
*,
table: str,
name_field: str,
dept_field: str,
applicant_name: str,
fuzzy: bool = False,
) -> tuple[str, list[Any]]:
"""
构造按姓名查询 HrmResource 的 SQL。
核心逻辑:默认去空白后精确匹配 lastname;fuzzy=True 时用 LIKE 兼容 OA 多语言包装串。
Args:
table: 人员表名,默认 HrmResource。
name_field: 姓名列,默认 lastname。
dept_field: 部门列,默认 departmentid。
applicant_name: 绑定为查询参数。
fuzzy: 为 True 时改为包含匹配,结果仍须在 Python 侧按规范化姓名唯一命中。
Returns:
(sql, params)。
"""
column = f"r.{_bracket_ident(name_field)}"
predicate = f"{column} LIKE ?" if fuzzy else f"LTRIM(RTRIM({column})) = ?"
sql = (
f"SELECT r.{_bracket_ident('id')}, {column}, "
f"r.{_bracket_ident(dept_field)} "
f"FROM {_bracket_ident(table)} r "
f"WHERE {predicate}"
)
return sql, [f"%{applicant_name}%"] if fuzzy else [applicant_name]
def build_matrix_lookup_sql(
*,
table: str,
dept_field: str,
round2_field: str,
round3_field: str,
department_id: int,
) -> tuple[str, list[Any]]:
"""
构造按部门查询 Matrixtable_3 的 SQL。
核心逻辑:bm = HrmResource.departmentid;zz 第二轮、jfl 第三轮。
Args:
table: 矩阵表名。
dept_field: 部门列,默认 bm。
round2_field: 第二轮主管列,默认 zz。
round3_field: 第三轮主管列,默认 jfl。
department_id: 申请人部门 ID。
Returns:
(sql, params)。
"""
sql = (
f"SELECT m.{_bracket_ident(dept_field)}, m.{_bracket_ident(round2_field)}, "
f"m.{_bracket_ident(round3_field)} "
f"FROM {_bracket_ident(table)} m "
f"WHERE m.{_bracket_ident(dept_field)} = ?"
)
return sql, [department_id]
def _lookup_resource_name(cursor: Any, table: str, name_field: str, oa_id: int | None) -> str | None:
"""按 HrmResource.id 取 lastname,供系统用户真实姓名回退匹配。"""
if oa_id is None:
return None
sql = (
f"SELECT TOP 1 r.{_bracket_ident(name_field)} "
f"FROM {_bracket_ident(table)} r "
f"WHERE r.{_bracket_ident('id')} = ?"
)
cursor.execute(sql, [oa_id])
row = cursor.fetchone()
if not row:
return None
return OASQLServerService._normalize_oa_text(_row_value(row, 0)) or None
def _unique_hrm_rows(rows: list[Any], applicant_name: str) -> tuple[int, int] | None:
"""姓名命中且仅一人、且部门 ID 有效时返回 (oa_id, department_id)。"""
matched: list[tuple[int, int]] = []
seen_ids: set[int] = set()
for row in rows or []:
lastname = OASQLServerService._normalize_oa_text(_row_value(row, 1))
if lastname != applicant_name:
continue
oa_id = _as_positive_int(_row_value(row, 0))
department_id = _as_positive_int(_row_value(row, 2))
if oa_id is None or department_id is None or oa_id in seen_ids:
continue
seen_ids.add(oa_id)
matched.append((oa_id, department_id))
if len(matched) != 1:
return None
return matched[0]
def _as_positive_int(value: Any) -> int | None:
"""将 OA 数字字段转为正整数;多值逗号串无法唯一确定时返回 None。"""
if value is None or isinstance(value, bool):
return None
if isinstance(value, int):
return value if value > 0 else None
try:
number = int(value)
return number if number > 0 else None
except (TypeError, ValueError):
pass
text = str(value).strip()
if not text:
return None
if re.fullmatch(r"\d+", text):
number = int(text)
return number if number > 0 else None
if re.fullmatch(r"\d{1,3}(,\d{3})+", text):
number = int(text.replace(",", ""))
return number if number > 0 else None
return None
def _configured_ident(config_key: str, default: str) -> str:
"""读取 Flask 配置中的 SQL 标识符,非法时回退默认值。"""
raw = str(current_app.config.get(config_key) or default).strip() or default
if not _SAFE_IDENT.match(raw):
current_app.logger.error(
"合同付款预警:非法 SQL 标识符 %s=%r,回退 %s", config_key, raw, default
)
return default
return raw
def _bracket_ident(name: str) -> str:
"""校验并返回 [ident] 形式的 SQL Server 标识符。"""
if not _SAFE_IDENT.match(name):
raise ValueError(f"非法 SQL 标识符: {name!r}")
return f"[{name}]"
def _row_value(row: Any, index: int) -> Any:
"""按位置取值,兼容 tuple 与 pyodbc.Row。"""
try:
return row[index]
except (IndexError, TypeError, KeyError):
return None
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,66 @@
"""
backend/app/services/schedule/contract_payment_job.py
用途:将合同付款预警同步和扫描适配到现有 Schedule 平台任务。
依赖:contract_payment.sync_service、alert_service、ScheduleTask/Run。
逻辑:排程 worker 执行领域服务并把数量摘要返回给通用排程审计。
"""
from __future__ import annotations
from typing import Any
from app.models import ScheduleRun, ScheduleTask
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
def run_contract_payment_sync_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
执行 OA 合同、验收归档同步;付款完成状态由预警扫描查询 ERP。
Args:
task: 当前排程任务定义。
run: 当前排程执行记录。
Returns:
通用排程审计所需的七元组结果。
"""
from app.services.contract_payment.sync_service import sync_notifications
summary = sync_notifications()
count = int(summary.get("created_contracts") or 0) + int(summary.get("created_events") or 0)
return count, count, 0, int(summary.get("skipped") or 0), [summary], [], [{"step": "contract_payment_sync", "status": "success", "detail": summary}]
def run_contract_payment_alert_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
执行合同付款节点三轮预警扫描。
Args:
task: 当前排程任务定义。
run: 当前排程执行记录。
Returns:
通用排程审计所需的七元组结果。
"""
from app.services.contract_payment.alert_service import generate_alerts
summary = generate_alerts()
count = int(summary.get("created") or 0)
return count, 0, count, int(summary.get("skipped") or 0), [summary], [], [{"step": "contract_payment_alert_scan", "status": "success", "detail": summary}]
def run_contract_payment_weekly_alert_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""执行周五合同付款预警汇总发送。
Args:
task: 当前排程任务定义。
run: 当前排程执行记录。
Returns:
通用排程审计所需的七元组结果。
"""
from app.services.contract_payment.alert_service import send_weekly_alerts
summary = send_weekly_alerts()
failed = int(summary.get("failed") or 0)
sent = int(summary.get("sent") or 0)
return sent + failed, sent, failed, 0, [summary], [], [{"step": "contract_payment_alert_weekly", "status": "success" if not failed else "partial", "detail": summary}]
@@ -140,7 +140,44 @@ def _register_builtin_platform_jobs() -> None:
run_shipping_post_ot_auto_fulfill_compensation_schedule,
)
from app.services.schedule.voucher_check_job import run_voucher_check_schedule
from app.services.schedule.contract_payment_job import (
run_contract_payment_alert_schedule,
run_contract_payment_sync_schedule,
)
from app.services.voucher_check.config import DEFAULT_JOB_PARAMS, DEFAULT_REQUIRED_FILES
from app.services.schedule.contract_payment_job import (
run_contract_payment_alert_schedule,
run_contract_payment_sync_schedule,
run_contract_payment_weekly_alert_schedule,
)
register_platform_job(PlatformJobDefinition(
key="contract-payment-sync", label="合同付款 OA 同步", handler=run_contract_payment_sync_schedule,
description="同步 OA 合同归档、验收归档和厂商预付款请款作业。", category="contract_payment",
))
register_platform_job(PlatformJobDefinition(
key="contract-payment-alert-scan", label="合同付款预警扫描", handler=run_contract_payment_alert_schedule,
description="每日扫描四阶段付款节点,只生成待发送预警记录。", category="contract_payment",
))
register_platform_job(PlatformJobDefinition(
key="contract-payment-alert-weekly", label="合同付款预警周汇总", handler=run_contract_payment_weekly_alert_schedule,
description="每周五 18:00 按收件人发送一条付款预警汇总及 Excel 明细。", category="contract_payment",
))
register_platform_job(PlatformJobDefinition(
key="contract-payment-sync",
label="合同付款 OA 同步",
handler=run_contract_payment_sync_schedule,
description="同步合同申请单、验收归档和厂商预付款请款作业,为付款预警提供事实依据。",
category="procurement",
))
register_platform_job(PlatformJobDefinition(
key="contract-payment-alert",
label="合同付款三轮预警",
handler=run_contract_payment_alert_schedule,
description="按预付款、出货款、验收款、质保款的三轮升级规则发送企业微信提醒。",
category="procurement",
))
register_platform_job(PlatformJobDefinition(
key="shipping-order-extraction-progress-cleanup",
+20 -2
View File
@@ -186,12 +186,30 @@ def send_wecom_event_message(
jump_path: str = '/workspace',
jump_params: dict | None = None,
jump_url: str | None = None,
wecom_userid: str | None = None,
) -> dict:
"""
发送企微事件 textcard;可选 jump_url 覆盖默认跳转(如密码重置外链)。
核心逻辑:默认使用 `user.wecom_userid`;合同付款第二、三轮可传入 OA HrmResource.id
作为 wecom_userid,因为该 id 同时是企业微信 userid。
Args:
event_type: 通知事件开关名。
user: 审计关联的系统用户,可为收件人在 HXOPS 中的映射账号。
title: 卡片标题。
content: 卡片正文。
jump_path: 站内跳转路径。
jump_params: 跳转查询参数。
jump_url: 若传入则覆盖默认拼接的跳转地址。
wecom_userid: 可选,显式指定企微 touser;空则回退 user.wecom_userid。
Returns:
含 ok / trace_id 的发送结果字典。
"""
trace_id = uuid.uuid4().hex
audit = _create_audit(event_type, user, title, content, trace_id)
target_userid = str(wecom_userid or (user.wecom_userid if user else "") or "").strip()
if target_userid:
audit.wecom_userid = target_userid
if not current_app.config.get('WECOM_NOTIFY_ENABLED', True):
audit.error_code = 'NOTIFY_DISABLED'
@@ -203,7 +221,7 @@ def send_wecom_event_message(
audit.error_message = f'event {event_type} disabled'
return {'ok': False, 'trace_id': trace_id, 'reason': 'event_disabled'}
if not user or not user.wecom_userid:
if not target_userid:
audit.error_code = 'WECOM_USER_UNBOUND'
audit.error_message = 'user has no wecom_userid'
return {'ok': False, 'trace_id': trace_id, 'reason': 'user_unbound'}
@@ -214,7 +232,7 @@ def send_wecom_event_message(
else:
final_jump_url = _build_jump_url(jump_path, trace_id, jump_params)
audit.jump_url = final_jump_url
data = send_wecom_textcard_message(user.wecom_userid, title, content, final_jump_url)
data = send_wecom_textcard_message(target_userid, title, content, final_jump_url)
if data.get('errcode') == 0:
audit.status = 'sent'
return {'ok': True, 'trace_id': trace_id}